commit a749e6ec3cd628096d49a49b9c7e303a3c329341
parent b829b189a46480f42a31073937cafb7950d30e99
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 13 Oct 2026 13:39:32 -0400
Merge r27/gen-balance: release 27 S9 — the Claude Code balance (MCP generation_policy/generate, /gen, archilyzer gen)
# Conflicts:
# editor/CHANGELOG.md
# plans/release-27.md
Diffstat:
24 files changed, 2293 insertions(+), 19 deletions(-)
diff --git a/.claude/commands/gen.md b/.claude/commands/gen.md
@@ -0,0 +1,48 @@
+---
+description: Media generation (reports, revisions, video cuts, narration) routed by the operator's balance policy — Claude Code, the Claude API, or the local model
+---
+
+The operator balances media-generation work between this Claude Code session, the Claude API (billed apart from
+the Code plan) and the local model (free). The policy — `settings.generation`, in the editor — decides who does
+each task. Use the archilyzer MCP tools only; run no script for it.
+
+1. Call `mcp__archilyzer__generation_policy` with no arguments and read the routes, the models and the day's spend.
+2. Map the request below to tasks: `sweep` (a new cited report), `revise-report` (a new iteration of an article's
+ report from feedback), `revise-video` (a new iteration of its video cut: cards, narration, title), `narrate`
+ (card narration drafts for a done iteration's cut), `research` (find what the corpus lacks and propose
+ acquisitions — archive.org imports, channels, posts — under an autonomy: propose, limits or auto; a sweep with
+ the research run's iteration continues it over the widened scope). The clip fetches, voices, render and podcast are the
+ pipeline's code, not generation: the operator runs that chain from umtool (the article's Iterations tab).
+3. For each task routed to `api` or `local`, call `mcp__archilyzer__generate` with the task, the article, its
+ inputs (question and channels for a sweep or research run; iteration and concrete feedback for a revision;
+ iteration for a narration) and `wait: true`, and do not redo its work yourself. If it answers still running, call it again with
+ the job, article and iteration it names — never start the same task twice. Then REVIEW what it made, as its
+ answer says: read the iteration's files, spot-check its quotes with `mcp__archilyzer__get_transcript`, read the
+ ops it refused and its checks, and tell the operator what is good and what is not. Recommend making it current
+ (the operator does that in umtool) or a revision; for a revision, call `generate` again with that feedback.
+ A research run's proposals are the operator's to approve (umtool's research queue); say which you would approve
+ and why. Edit an iteration's files by hand only if the operator asks.
+4. For each task routed to `code`, do it yourself as usual: `/sweep` for a report (its plan reads the same
+ policy).
+5. `via: "api"` or `"local"` on `generate` (or `via=` in a `/sweep` request) overrides one run when the operator asks
+ for it. To move the balance itself, `generation_policy` with `preset` (code, balanced, api, local) or with
+ `task` and `route` — only when the operator asks.
+
+The request:
+
+$ARGUMENTS
+
+<!--
+The repo's /gen (release 27 S9, D8). It replaces the stopgap's user-level
+command of the same name, which drove the stopgap's own scripts; that one is
+retired with the stopgap (release 27 S10).
+
+Same editing caveats as `.claude/commands/sweep.md`: no `$1` placeholders in
+this body (they tokenize), and the `mcp__archilyzer__` prefix is the MCP
+server's name as registered on this machine (AGENTS.md: register it as
+`archilyzer`). The tools need an editor: the MCP registered with
+ARCHILYZER_EDITOR_URL and WORKER_TOKEN.
+
+The routing and review discipline lives in the server (`mcp/src/generation.ts`
+and `mcp/src/instructions.ts`), not here.
+-->
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -35,6 +35,10 @@ Run from the repo root (in the container: `docker compose exec editor pnpm archi
| `archilyzer reports verify-quotes` | `<report.json> \| --article <articleId>` | \[--json\] every video, audio and post quote of one report against its record with compose's own check: the best score and track, and the en-orig track's score where the record has one — a quote that matches a served `en` rewrite and not en-orig is reported (exit 1 when any quote drifted) |
| `archilyzer reports attach-video` | `<report.json> <video> \| --article <articleId> <video>` | \[--poster <image>\] \[--caption <line>\] the report's video: remuxed (an H.264 mp4 under the limit) or encoded to fit the 24 MiB publish limit, written beside report.json as video.mp4 with a poster (given, kept, or a frame of the video), and `video` set in report.json (an article's through the article registry) |
| `archilyzer reports iterations` | `<articleId> [--json]` | an article's iterations (transcripts/reports/<id>/iterations/): each one's kind, model, status, cost, lineage and what it revised or copied, the current article and current video marked (exit 1 when an iteration.json is unsound; 2 for no such article) |
+| `archilyzer gen policy` | `[--json]` | the generation policy: where each task runs (code = Claude Code, api = the Claude API, local = the local model), the models, the caps and the day's Claude API spend — from the editor, or settings.json when none answers |
+| `archilyzer gen preset` | `<code\|balanced\|api\|local>` | route every generation task by a preset (its routes are written; settings.generation.routes) |
+| `archilyzer gen set` | `<task> <code\|api\|local>` | route one generation task (sweep, revise-report, revise-video, narrate, research) |
+| `archilyzer gen run` | `<task> [<question\|feedback>] --article <id> [--via api\|local\|code] [--model <m>] [--iteration <n>] [--channels a,b] [--from YYYY-MM-DD] [--to YYYY-MM-DD] [--copy-of <n>] [--max-usd <usd>] [--cards a,b] [--force] [--autonomy propose\|limits\|auto] [--source <handle>\|--build <id>] [--wait]` | enqueue a report-draft job as `pnpm ops report-draft` does (--wait follows it; `sweep --iteration <n>` continues research run n); EXITS 3 and runs nothing when the task is routed to code (Claude Code does it; --via overrides once) |
| `archilyzer reports move-to-articles` | `[--keep <site>/<id>,…] [--drafts] [--apply]` | ONE-OFF (release 26): every report a site lists, but the pages named by --keep, moved to transcripts/reports/ as an article — audience private, published in reports/index.json in the sites' order (a report with problems as a draft), dropped from its site; --drafts moves unlisted ones too. A dry run printing the plan unless --apply *(passthrough)* |
| `archilyzer reports convert` | `<sweep\|ask\|manifest> <in> --out <report.json> [--channels-dir <dir>] [--id <id>] [--title <title>]` | a /sweep report (markdown), an /ask answer or a report-to-video manifest as a report.json, written only when it validates (--channels-dir: widen spans from the cues, find posts' channels) |
| `archilyzer reports to-manifest` | `<report.json> --out <manifest.json> [--channels-dir <dir>] [--site-origin <url>]` | a starter report-to-video manifest from a report (a chapter card per section, a claim's still and clips stamped with its verdict, its posts) |
@@ -159,6 +163,7 @@ Usage: pnpm ops <action> [--json '<body>' | --file <path>] [--wait]
pnpm ops get remote-listing <slug> [--wait-timeout <seconds>]
pnpm ops get transcript <videoId> [--slug <slug>]
pnpm ops get coverage <slug>
+ pnpm ops get generation-usage [<YYYY-MM-DD>] | iterations <article>
pnpm ops list
--wait follows the job's log and survives a poll that fails (a busy
@@ -202,6 +207,12 @@ get coverage <slug> is what a channel holds by date: held, dated (by
over 30 days with nothing held. Off disk; nothing written. (The MCP's
channel_coverage takes gap days, a date window and a video list.)
+get generation-usage [<day>] is the day's Claude API spend on generation
+ (the usage ledger's total for the UTC day, default today) and the daily
+ cap it is checked against: {day, usd, jobs, daily}.
+get iterations <article> is an article's iterations (iteration.json each)
+ and which is current. (The MCP's generate reads one, with its files.)
+
get transcript <videoId> [--slug <slug>] reads one video's cues off disk
with no index: a fresh cues.json, else what build-cues would write, else
the English VTT alone — {source, cuesJson, title?, ..., cues}. Nothing is
diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md
@@ -57,7 +57,7 @@ Tokens, credentials and knobs a running process reads. Most configuration is not
| Variable | Default | What it does | Read by |
|---|---|---|---|
-| `WORKER_TOKEN` | unset (both surfaces off) | Bearer token for the remote-worker API and for `/api/ops/*` (`pnpm ops`; the MCP's `fetch_clip`, `enqueue`, `get_job`, `channel_coverage` and `get_transcript`'s editor fallback), and for an agent's write to umtool's notes (the MCP's `notes` reply, stamped "agent"; umtool reads it from its environment, else the editor's `editor/.env`). Set the same value on every end. | common/lib/workerToken.ts, scripts/archilyzer-ops.mjs, mcp/src/fetchClip.ts, mcp/src/editorOps.ts, mcp/src/archivalTools.ts, umtool/lib/annotations/agentAuth.mjs |
+| `WORKER_TOKEN` | unset (both surfaces off) | Bearer token for the remote-worker API and for `/api/ops/*` (`pnpm ops` and `archilyzer gen`; the MCP's `fetch_clip`, `enqueue`, `get_job`, `channel_coverage`, `generation_policy`, `generate` and `get_transcript`'s editor fallback), and for an agent's write to umtool's notes (the MCP's `notes` reply, stamped "agent"; umtool reads it from its environment, else the editor's `editor/.env`). Set the same value on every end. | common/lib/workerToken.ts, scripts/archilyzer-ops.mjs, common/bin/gen.ts, mcp/src/fetchClip.ts, mcp/src/editorOps.ts, mcp/src/archivalTools.ts, umtool/lib/annotations/agentAuth.mjs |
| `ANTHROPIC_API_KEY` | unset (the API key file is read instead) | The Claude API key for report and video generation on the API (release 27): read first, before the mode-600 key file the generation settings name. Sent only to the Messages API in `x-api-key`; never logged, and never in an error, a job record or a transcript. | common/lib/llm/anthropic.ts |
| `SYNC_HEARTBEAT_SECONDS` | `settings.syncScheduler.heartbeatSeconds` | Overrides the editor's in-process sync heartbeat. `0` = no internal timer (tick from cron instead). | editor/app/scheduler/heartbeat.ts |
| `SYNC_TICK_URL` | `http://127.0.0.1:3001/api/scheduler/tick` | Where `archilyzer sync tick` (cron's heartbeat) posts. | common/bin/sync-tick.ts |
@@ -98,7 +98,7 @@ Tokens, credentials and knobs a running process reads. Most configuration is not
| `ARCHILYZER_INDEX_ALLOW_HELD` | off | `1` lets a FULL index rebuild (a schema change, or no index yet) proceed while a channel's media cannot be read; that channel stays out of the index until its media is back and the index is built again. Unset, such a build refuses and names each channel. | common/controller/buildIndex.ts |
| `UV_THREADPOOL_SIZE` | `16` for the editor (`4` is Node's own) | Threads in Node's pool for filesystem calls. A call on a stalled drive holds one until the drive answers, so the editor starts with 16. It buys time for calls already in flight and isolates nothing: the storage health probe and its gate keep new calls off a stalled drive. | Node's libuv (set by editor/package.json `start` and docker/entrypoint.sh) |
| `MCP_IO_STATS` | off | `1` turns on per-call I/O accounting, for `mcp/bench`. | common/lib/archive/io-stats.ts |
-| `ARCHILYZER_EDITOR_URL` | `http://localhost:3001` | Which editor `pnpm ops` and the MCP's editor-backed tools (`fetch_clip`, `enqueue`, `get_job`, `channel_coverage`, `get_transcript`'s fallback) talk to, and whose `/api/pulse` `archilyzer storage migrate-tier` asks before it refuses to run beside it. | scripts/archilyzer-ops.mjs, mcp/src/fetchClip.ts, mcp/src/editorOps.ts, umtool, common/bin/migrate-media-tier.ts |
+| `ARCHILYZER_EDITOR_URL` | `http://localhost:3001` | Which editor `pnpm ops`, `archilyzer gen` and the MCP's editor-backed tools (`fetch_clip`, `enqueue`, `get_job`, `channel_coverage`, `generation_policy`, `generate`, `get_transcript`'s fallback) talk to, and whose `/api/pulse` `archilyzer storage migrate-tier` asks before it refuses to run beside it. | scripts/archilyzer-ops.mjs, common/bin/gen.ts, mcp/src/fetchClip.ts, mcp/src/editorOps.ts, umtool, common/bin/migrate-media-tier.ts |
| `ARCHILYZER_AGENT` | `cli` | Who is asking, recorded as the provenance of a curated-tag write through `pnpm ops`. | scripts/archilyzer-ops.mjs |
| `DIARIZE_ENGINE_KIND` | `sherpa-onnx` | The diarization engine: `sherpa-onnx` or `sortformer`. | scripts/diarize.mjs |
| `DIARIZE_ENGINE_CMD` | the bundled sherpa script | The engine command the wrapper runs. | scripts/diarize.mjs |
diff --git a/common/bin/archilyzer.ts b/common/bin/archilyzer.ts
@@ -398,6 +398,53 @@ export const COMMANDS: Command[] = [
return (await import("./reports-iterations")).iterationsMain({ article, json: flags.json === true });
},
},
+ // The generation balance (release 27 S9; bin/gen.ts): settings.generation
+ // through the editor's ops API, or settings.json when no editor answers.
+ {
+ path: ["gen", "policy"],
+ usage:
+ "[--json] the generation policy: where each task runs (code = Claude Code, api = the Claude API, local = the local model), the models, the caps and the day's Claude API spend — from the editor, or settings.json when none answers",
+ flags: { json: "boolean" },
+ run: async (ctx) => (await import("./gen")).genPolicyRow(ctx),
+ },
+ {
+ path: ["gen", "preset"],
+ usage: "<code|balanced|api|local> route every generation task by a preset (its routes are written; settings.generation.routes)",
+ maxPositionals: 1,
+ run: async (ctx) => (await import("./gen")).genPresetRow(ctx),
+ },
+ {
+ path: ["gen", "set"],
+ usage: "<task> <code|api|local> route one generation task (sweep, revise-report, revise-video, narrate, research)",
+ maxPositionals: 2,
+ run: async (ctx) => (await import("./gen")).genSetRow(ctx),
+ },
+ {
+ path: ["gen", "run"],
+ usage:
+ "<task> [<question|feedback>] --article <id> [--via api|local|code] [--model <m>] [--iteration <n>] [--channels a,b] [--from YYYY-MM-DD] [--to YYYY-MM-DD] [--copy-of <n>] [--max-usd <usd>] [--cards a,b] [--force] [--autonomy propose|limits|auto] [--source <handle>|--build <id>] [--wait] enqueue a report-draft job as `pnpm ops report-draft` does (--wait follows it; `sweep --iteration <n>` continues research run n); EXITS 3 and runs nothing when the task is routed to code (Claude Code does it; --via overrides once)",
+ flags: {
+ via: "string",
+ article: "string",
+ iteration: "string",
+ question: "string",
+ feedback: "string",
+ channels: "string",
+ from: "string",
+ to: "string",
+ "copy-of": "string",
+ model: "string",
+ "max-usd": "string",
+ cards: "string",
+ force: "boolean",
+ autonomy: "string",
+ source: "string",
+ build: "string",
+ wait: "boolean",
+ },
+ maxPositionals: 2,
+ run: async (ctx) => (await import("./gen")).genRunRow(ctx),
+ },
script(["reports", "move-to-articles"], "move-reports-to-articles.ts",
"[--keep <site>/<id>,…] [--drafts] [--apply] ONE-OFF (release 26): every report a site lists, but the pages named by --keep, moved to transcripts/reports/ as an article — audience private, published in reports/index.json in the sites' order (a report with problems as a draft), dropped from its site; --drafts moves unlisted ones too. A dry run printing the plan unless --apply"),
{
diff --git a/common/bin/gen.test.ts b/common/bin/gen.test.ts
@@ -0,0 +1,212 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+// `archilyzer gen` (release 27 S9). settings.json and the ledger are pinned to
+// a temp dir BEFORE anything reads getPaths() (it caches), so the offline
+// store writes there and nowhere else.
+const ROOT = mkdtempSync(path.join(os.tmpdir(), "gen-cli-"));
+Object.assign(process.env, {
+ TRANSCRIPTS_DIR: path.join(ROOT, "transcripts"),
+ SETTINGS_FILE: path.join(ROOT, "settings.json"),
+ GENERATION_USAGE_FILE: path.join(ROOT, "usage.jsonl"),
+});
+writeFileSync(path.join(ROOT, "settings.json"), JSON.stringify({ minFreeDiskGB: 0 }));
+test.after(() => rmSync(ROOT, { recursive: true, force: true }));
+
+const gen = await import("./gen");
+type GenStore = import("./gen").GenStore;
+type GenPolicy = import("./gen").GenPolicy;
+
+function capture() {
+ const lines: string[] = [];
+ const errors: string[] = [];
+ return { lines, errors, out: { log: (s: string) => lines.push(s), error: (s: string) => errors.push(s) } };
+}
+
+const BALANCED: GenPolicy = {
+ 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 },
+};
+
+// A store in memory, recording what it was asked to write.
+function memoryStore(policy: GenPolicy = BALANCED, offline = false) {
+ const written: Record<string, string>[] = [];
+ let p = structuredClone(policy);
+ const store: GenStore = {
+ where: offline ? "settings.json (test)" : "the editor at http://editor.test",
+ offline,
+ read: async () => p,
+ usage: async () => ({ day: "2026-10-13", usd: 1.5, jobs: 2, daily: 20 }),
+ writeRoutes: async (routes) => {
+ written.push(routes);
+ p = { ...p, routes, preset: "custom" };
+ return p;
+ },
+ };
+ return { store, written };
+}
+
+test("gen policy prints the routes, models, caps and today's spend", async () => {
+ const c = capture();
+ const { store } = memoryStore();
+ assert.equal(await gen.policyMain({ json: false }, { store: async () => store, runOps: async () => 0, out: c.out }), 0);
+ assert.equal(c.lines[0], "preset balanced · api model claude-sonnet-5-5 · local model qwen3:8b · extractor claude-haiku-4-5");
+ assert.ok(c.lines.includes(" sweep → code"));
+ assert.ok(c.lines.includes(" revise-report → api"));
+ assert.ok(c.lines.includes("caps: sweep $5.00 · revision $2.00 · narration $1.00 · max $10.00 · daily $20.00"));
+ assert.ok(c.lines.includes("today 2026-10-13 (UTC): $1.50 on the Claude API in 2 job(s)"));
+ const j = capture();
+ await gen.policyMain({ json: true }, { store: async () => store, runOps: async () => 0, out: j.out });
+ assert.equal(JSON.parse(j.lines[0]).routes.narrate, "local");
+ const refused = capture();
+ assert.equal(await gen.policyMain({ json: false }, { store: async () => ({ error: "the editor refused" }), runOps: async () => 0, out: refused.out }), 1);
+ assert.match(refused.errors[0], /^gen policy: the editor refused/);
+});
+
+test("gen preset writes the preset's routes; gen set writes one; nonsense is a usage error", async () => {
+ const c = capture();
+ const m = memoryStore();
+ const deps = { store: async () => m.store, runOps: async () => 0, out: c.out };
+ assert.equal(await gen.setMain({ preset: "local" }, deps), 0);
+ assert.deepEqual(m.written[0], { sweep: "local", "revise-report": "local", "revise-video": "local", narrate: "local", research: "local" });
+ assert.equal(await gen.setMain({ task: "sweep", route: "api" }, deps), 0);
+ assert.deepEqual(m.written[1], { sweep: "api", "revise-report": "local", "revise-video": "local", narrate: "local", research: "local" });
+ assert.ok(c.lines.includes("(written to the editor at http://editor.test)"));
+ for (const o of [{ preset: "cheap" }, { task: "sweep", route: "cloud" }, { task: "sweep" }, { task: "teaser", route: "api" }]) {
+ assert.equal(await gen.setMain(o, deps), 2, JSON.stringify(o));
+ }
+ assert.equal(m.written.length, 2);
+});
+
+test("gen run exits 3 and runs nothing when the task is routed to code", async () => {
+ const c = capture();
+ const ran: string[][] = [];
+ const deps = { store: async () => memoryStore().store, runOps: async (a: string[]) => (ran.push(a), 0), out: c.out };
+ const code = await gen.runMain({ task: "sweep", text: "What about the shop?", flags: { article: "synth-a", channels: "synth-kitchen" } }, deps);
+ assert.equal(code, 3);
+ assert.equal(ran.length, 0);
+ assert.match(c.lines[0], /sweep is routed to Claude Code \(preset balanced\)/);
+ assert.equal(await gen.runMain({ task: "revise-report", text: "Shorter.", flags: { article: "synth-a", iteration: "2", via: "code" } }, deps), 3);
+ assert.equal(ran.length, 0);
+});
+
+test("gen run enqueues through pnpm ops report-draft on the route's model; --via overrides; --wait follows", async () => {
+ const c = capture();
+ const ran: string[][] = [];
+ const deps = { store: async () => memoryStore().store, runOps: async (a: string[]) => (ran.push(a), 0), out: c.out };
+ assert.equal(
+ await gen.runMain(
+ { task: "sweep", text: "What about the shop?", flags: { article: "synth-a", channels: "synth-kitchen, synth-other", via: "api", "max-usd": "3", from: "2026-01-01", wait: true } },
+ deps,
+ ),
+ 0,
+ );
+ assert.equal(ran[0][0], "report-draft");
+ assert.deepEqual(JSON.parse(ran[0][2]), {
+ task: "sweep",
+ article: "synth-a",
+ question: "What about the shop?",
+ channels: ["synth-kitchen", "synth-other"],
+ from: "2026-01-01",
+ maxUsd: 3,
+ model: "claude-sonnet-5-5",
+ });
+ assert.equal(ran[0][3], "--wait");
+ assert.equal(await gen.runMain({ task: "revise-video", text: "Shorter.", flags: { article: "synth-a", iteration: "2" } }, deps), 0);
+ assert.deepEqual(JSON.parse(ran[1][2]), { task: "revise-video", article: "synth-a", iteration: 2, feedback: "Shorter.", model: "qwen3:8b" });
+ assert.equal(ran[1].length, 3);
+ // --model names it outright: the policy is not asked.
+ let asked = 0;
+ const named = { ...deps, store: async () => (asked++, memoryStore().store) };
+ assert.equal(await gen.runMain({ task: "sweep", text: "q", flags: { article: "synth-a", channels: "x", model: "qwen3:8b" } }, named), 0);
+ assert.equal(asked, 0);
+ // Usage errors before anything is asked.
+ for (const flags of <Record<string, string>[]>[{}, { article: "a", iteration: "zero" }, { article: "a", "max-usd": "-1" }, { article: "a", via: "cloud" }, { article: "a", via: "api", model: "m" }]) {
+ assert.equal(await gen.runMain({ task: "sweep", text: "q", flags }, named), 2, JSON.stringify(flags));
+ }
+ assert.equal(asked, 0);
+ // Offline: the route is known, but no editor runs the job.
+ const offline = { ...deps, store: async () => memoryStore(BALANCED, true).store };
+ assert.equal(await gen.runMain({ task: "narrate", flags: { article: "a", iteration: "1" } }, offline), 1);
+ assert.match(c.errors.at(-1)!, /no editor answers — generation runs in the editor/);
+});
+
+test("the editor store: through the ops API with the token; refused → error; nothing listening → offline", async () => {
+ const env = { WORKER_TOKEN: "tok", ARCHILYZER_EDITOR_URL: "http://editor.test/" };
+ const sent: { url: string; method: string; auth?: string; body?: unknown }[] = [];
+ let policy: Record<string, unknown> = { ...BALANCED };
+ const fetchImpl = (async (url: string, init: RequestInit) => {
+ const headers = init.headers as Record<string, string>;
+ sent.push({ url, method: init.method ?? "GET", auth: headers.authorization, body: init.body ? JSON.parse(String(init.body)) : undefined });
+ const u = new URL(url);
+ const json = (status: number, body: unknown) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
+ if (u.pathname === "/api/ops/settings" && init.method === "POST") {
+ policy = { ...policy, routes: (sent.at(-1)!.body as { patch: { generation: { routes: unknown } } }).patch.generation.routes, preset: "api" };
+ return json(200, { ok: true, changed: ["generation"], value: { generation: policy } });
+ }
+ if (u.pathname === "/api/ops/settings") return json(200, { ok: true, key: "generation", value: policy });
+ if (u.pathname === "/api/ops/generation-usage") return json(200, { ok: true, day: "2026-10-13", usd: 0.5, jobs: 1, daily: 20 });
+ return json(404, { ok: false, error: "no" });
+ }) as unknown as typeof fetch;
+ const store = (await gen.editorStore({ ...env }, fetchImpl)) as GenStore;
+ assert.equal(store.offline, false);
+ assert.equal((await store.read()).preset, "balanced");
+ assert.deepEqual(await store.usage(), { day: "2026-10-13", usd: 0.5, jobs: 1, daily: 20 });
+ const saved = await store.writeRoutes({ sweep: "api", "revise-report": "api", "revise-video": "api", narrate: "api", research: "api" });
+ assert.equal(saved.preset, "api");
+ assert.ok(sent.every((s) => s.auth === "Bearer tok" && s.url.startsWith("http://editor.test/api/ops/")));
+ assert.deepEqual(sent.find((s) => s.method === "POST")!.body, {
+ patch: { generation: { routes: { sweep: "api", "revise-report": "api", "revise-video": "api", narrate: "api", research: "api" } } },
+ });
+
+ const refusing = (async () => new Response(JSON.stringify({ ok: false, error: "unauthorized" }), { status: 401 })) as unknown as typeof fetch;
+ const r = (await gen.editorStore({ ...env }, refusing)) as { error: string };
+ assert.match(r.error, /refused \(HTTP 401\): unauthorized \(hint: /);
+
+ const refused = (async () => {
+ throw Object.assign(new TypeError("fetch failed"), { cause: { code: "ECONNREFUSED" } });
+ }) as unknown as typeof fetch;
+ assert.equal(await gen.editorStore({ ...env }, refused), null);
+
+ const silent = (async () => {
+ throw Object.assign(new Error("The operation was aborted due to timeout"), { name: "TimeoutError" });
+ }) as unknown as typeof fetch;
+ const s = (await gen.editorStore({ ...env }, silent)) as { error: string };
+ assert.match(s.error, /did not answer \(no answer within 15 s\) — not writing settings\.json beside a running editor/);
+});
+
+test("the offline store reads and writes settings.json through the settings writer", async () => {
+ const store = await gen.offlineStore();
+ assert.equal(store.offline, true);
+ const before = await store.read();
+ assert.equal(before.preset, "balanced");
+ const after = await store.writeRoutes({ ...before.routes, sweep: "local" });
+ assert.equal(after.routes.sweep, "local");
+ assert.equal(after.preset, "custom");
+ const file = JSON.parse(readFileSync(path.join(ROOT, "settings.json"), "utf8"));
+ assert.equal(file.generation.routes.sweep, "local");
+ assert.equal(file.minFreeDiskGB, 0);
+ assert.deepEqual(await store.usage(), { day: new Date().toISOString().slice(0, 10), usd: 0, jobs: 0, daily: 20 });
+ // A preset chosen offline is its routes, and reads back as the preset.
+ const c = capture();
+ assert.equal(await gen.setMain({ preset: "api" }, { store: async () => store, runOps: async () => 0, out: c.out }), 0);
+ assert.equal((await store.read()).preset, "api");
+});
+
+test("gen run research takes --autonomy; nothing else does", async () => {
+ assert.deepEqual(gen.runBody("research", "what is missing?", { article: "synth-a", channels: "synth-kitchen", autonomy: "limits" }), {
+ task: "research",
+ article: "synth-a",
+ question: "what is missing?",
+ channels: ["synth-kitchen"],
+ autonomy: "limits",
+ });
+ assert.deepEqual(gen.runBody("sweep", undefined, { article: "synth-a", autonomy: "auto" }), { error: "gen run: --autonomy is a research run's" });
+ // A continuation: a sweep naming the research run.
+ assert.deepEqual(gen.runBody("sweep", undefined, { article: "synth-a", iteration: "4", force: true }), { task: "sweep", article: "synth-a", iteration: 4, force: true });
+});
diff --git a/common/bin/gen.ts b/common/bin/gen.ts
@@ -0,0 +1,355 @@
+// `archilyzer gen policy|preset|set|run` — the generation balance from a
+// terminal (release 27 S9; D8): the stopgap's `gen` over settings.generation.
+//
+// archilyzer gen policy [--json] the routes, models, caps and the day's API spend
+// archilyzer gen preset code|balanced|api|local route every task at once
+// archilyzer gen set <task> code|api|local route one task
+// archilyzer gen run <task> [<question|feedback>] --article <id> [--via api|local|code] […] [--wait]
+// enqueue a report-draft job (`pnpm ops report-draft`)
+//
+// THROUGH THE EDITOR when it answers: `GET/POST /api/ops/settings` (its one
+// settings writer) and `GET /api/ops/generation-usage`, with the token
+// `pnpm ops` reads (WORKER_TOKEN / ARCHILYZER_EDITOR_URL, else editor/.env).
+// OFFLINE when nothing listens at the editor's URL (the connection is
+// refused): settings.json through the settings writer (`writeSettings`) and
+// the ledger off disk — the way `archilyzer release cut` works with no editor.
+// An editor that is there but does not answer, or refuses the token, is an
+// error: settings.json is never written beside a running editor.
+//
+// `run` asks the policy first and EXITS 3, running nothing, when the task is
+// routed to code (Claude Code does it in its session — the stopgap's
+// contract); `--via` overrides the route once, `--model` names the model
+// outright. The job itself is `pnpm ops report-draft` (a child), so `--wait`
+// follows it exactly as `pnpm ops … --wait` does and prints its result.
+//
+// The API key is never read, printed or written here: it is not a setting.
+
+import path from "node:path";
+import { pathToFileURL } from "node:url";
+import type { CommandContext } from "./_cli";
+import type { FlagValue } from "./_parseFlags";
+import { REPO_ROOT, runChild } from "./_spawnBin";
+import {
+ GENERATION_PRESETS,
+ GENERATION_PRESET_NAMES,
+ GENERATION_ROUTES,
+ type GenerationPreset,
+ type GenerationRoute,
+} from "../lib/generationSettings";
+
+type Out = { log: (s: string) => void; error: (s: string) => void };
+
+// The part of settings.generation this command shows and changes.
+export type GenPolicy = {
+ preset: string;
+ routes: Record<string, GenerationRoute>;
+ models: { api: string; local: string; extractor?: string };
+ caps?: Record<string, number>;
+};
+export type GenUsage = { day: string; usd: number; jobs: number; daily: number };
+
+// Where the policy is read and written: the editor, or settings.json offline.
+export type GenStore = {
+ where: string;
+ // settings.json with no editor answering: generation jobs cannot run.
+ offline: boolean;
+ read(): Promise<GenPolicy>;
+ usage(): Promise<GenUsage | null>;
+ writeRoutes(routes: Record<string, GenerationRoute>): Promise<GenPolicy>;
+};
+
+export type GenDeps = {
+ // The store, or why there is none (an editor that is there and refuses).
+ store: () => Promise<GenStore | { error: string }>;
+ // `pnpm ops <argv>` as a child; its exit code.
+ runOps: (argv: string[]) => Promise<number>;
+ out?: Out;
+};
+
+const TASKS_HELP = "sweep, revise-report, revise-video, narrate, research";
+const isRoute = (v: unknown): v is GenerationRoute => typeof v === "string" && (GENERATION_ROUTES as readonly string[]).includes(v);
+
+export function policyFrom(value: unknown): GenPolicy | null {
+ if (!value || typeof value !== "object") return null;
+ const v = value as Record<string, unknown>;
+ const routes: Record<string, GenerationRoute> = {};
+ for (const [t, r] of Object.entries((v.routes as Record<string, unknown>) ?? {})) if (isRoute(r)) routes[t] = r;
+ const m = (v.models as Record<string, unknown>) ?? {};
+ if (typeof m.api !== "string" || typeof m.local !== "string") return null;
+ return {
+ preset: typeof v.preset === "string" ? v.preset : "custom",
+ routes,
+ models: { api: m.api, local: m.local, ...(typeof m.extractor === "string" ? { extractor: m.extractor } : {}) },
+ ...(v.caps && typeof v.caps === "object" ? { caps: v.caps as Record<string, number> } : {}),
+ };
+}
+
+const usd = (n: number) => `$${n.toFixed(2)}`;
+
+export function formatPolicy(p: GenPolicy, usage: GenUsage | null): string[] {
+ const lines = [
+ `preset ${p.preset} · api model ${p.models.api} · local model ${p.models.local}${p.models.extractor ? ` · extractor ${p.models.extractor}` : ""}`,
+ ...Object.entries(p.routes).map(([t, r]) => ` ${t.padEnd(14)} → ${r}`),
+ ];
+ const c = p.caps;
+ if (c) {
+ lines.push(
+ `caps: ${["sweep", "revision", "narration", "max"].filter((k) => typeof c[k] === "number").map((k) => `${k} ${usd(c[k])}`).join(" · ")}` +
+ (typeof c.daily === "number" ? ` · ${c.daily > 0 ? `daily ${usd(c.daily)}` : "no daily cap"}` : ""),
+ );
+ }
+ if (usage) lines.push(`today ${usage.day} (UTC): ${usd(usage.usd)} on the Claude API in ${usage.jobs} job(s)`);
+ return lines;
+}
+
+// ─── The two stores ───
+
+type Answer = { kind: "ok"; body: Record<string, unknown> } | { kind: "refused"; status: number; error: string } | { kind: "absent"; message: string } | { kind: "silent"; message: string };
+
+// The editor's ops API with `pnpm ops`'s env (the same files, never printed).
+export async function editorStore(env: NodeJS.ProcessEnv = process.env, fetchImpl: typeof fetch = fetch): Promise<GenStore | { error: string } | null> {
+ const ops = (await import(pathToFileURL(path.join(REPO_ROOT, "scripts", "archilyzer-ops.mjs")).href)) as {
+ loadEditorEnv: (env: NodeJS.ProcessEnv) => Record<string, string>;
+ tokenHint: (status: number, sources: Record<string, string>, url: string) => string;
+ };
+ const sources = ops.loadEditorEnv(env);
+ const base = (env.ARCHILYZER_EDITOR_URL || "http://localhost:3001").replace(/\/+$/, "");
+ const token = env.WORKER_TOKEN ?? "";
+ const call = async (method: "GET" | "POST", route: string, body?: unknown): Promise<Answer> => {
+ let res: Response;
+ try {
+ res = await fetchImpl(`${base}${route}`, {
+ method,
+ headers: { ...(token ? { authorization: `Bearer ${token}` } : {}), ...(body ? { "content-type": "application/json" } : {}) },
+ ...(body ? { body: JSON.stringify(body) } : {}),
+ signal: AbortSignal.timeout(15_000),
+ });
+ } catch (e) {
+ const err = e as Error & { cause?: { code?: string } };
+ const code = err.cause?.code ?? "";
+ // Nothing listening: offline. Anything else (a timeout above all) may be
+ // an editor too busy to answer — never write the file beside it.
+ if (/ECONNREFUSED|ENOTFOUND|EHOSTUNREACH|EAI_AGAIN/.test(code)) return { kind: "absent", message: `${code} at ${base}` };
+ return { kind: "silent", message: err.name === "TimeoutError" ? "no answer within 15 s" : err.message };
+ }
+ const j = (await res.json().catch(() => null)) as Record<string, unknown> | null;
+ if (res.ok && j && j.ok !== false) return { kind: "ok", body: j };
+ const error = typeof j?.error === "string" ? j.error : `HTTP ${res.status}`;
+ return { kind: "refused", status: res.status, error: res.status === 401 || res.status === 503 ? `${error} (${ops.tokenHint(res.status, sources, base)})` : error };
+ };
+ const first = await call("GET", "/api/ops/settings?key=generation");
+ if (first.kind === "absent") return null;
+ if (first.kind === "silent") return { error: `the editor at ${base} did not answer (${first.message}) — not writing settings.json beside a running editor` };
+ if (first.kind === "refused") return { error: `the editor at ${base} refused (HTTP ${first.status}): ${first.error}` };
+ let readOnce = false;
+ const fail = (a: Answer) => new Error(a.kind === "refused" ? `the editor refused (HTTP ${a.status}): ${a.error}` : `the editor at ${base}: ${"message" in a ? a.message : "no answer"}`);
+ const read = async () => {
+ const a = first.kind === "ok" && !readOnce ? first : await call("GET", "/api/ops/settings?key=generation");
+ readOnce = true;
+ if (a.kind !== "ok") throw fail(a);
+ const p = policyFrom(a.body.value);
+ if (!p) throw new Error("the editor's answer carried no generation block");
+ return p;
+ };
+ return {
+ where: `the editor at ${base}`,
+ offline: false,
+ read,
+ async usage() {
+ const a = await call("GET", "/api/ops/generation-usage");
+ if (a.kind !== "ok" || typeof a.body.usd !== "number") return null;
+ return { day: String(a.body.day), usd: a.body.usd, jobs: Number(a.body.jobs) || 0, daily: Number(a.body.daily) || 0 };
+ },
+ async writeRoutes(routes) {
+ const a = await call("POST", "/api/ops/settings", { patch: { generation: { routes } } });
+ if (a.kind !== "ok") throw fail(a);
+ const p = policyFrom((a.body.value as Record<string, unknown> | undefined)?.generation);
+ if (!p) throw new Error("the editor's answer carried no generation block");
+ return p;
+ },
+ };
+}
+
+// settings.json and the ledger, with no editor running.
+export async function offlineStore(): Promise<GenStore> {
+ const { getSettings, writeSettings } = await import("../lib/settings");
+ const { getPaths } = await import("../lib/paths");
+ const { dayUsage } = await import("../controller/generationUsage");
+ const read = async () => policyFrom(getSettings().generation)!;
+ return {
+ where: `settings.json (${getPaths().settingsFile}; no editor answering)`,
+ offline: true,
+ read,
+ async usage() {
+ const s = getSettings();
+ return { ...(await dayUsage(getPaths().generationUsageFile)), daily: s.generation.caps.daily };
+ },
+ async writeRoutes(routes) {
+ const s = getSettings();
+ // The one settings writer; the schema derives the preset from the routes.
+ await writeSettings({ ...s, generation: { ...s.generation, routes: { ...s.generation.routes, ...routes } as typeof s.generation.routes } });
+ return read();
+ },
+ };
+}
+
+export async function defaultStore(env: NodeJS.ProcessEnv = process.env): Promise<GenStore | { error: string }> {
+ return (await editorStore(env)) ?? (await offlineStore());
+}
+
+// ─── The four verbs ───
+
+export async function policyMain(o: { json: boolean }, deps: GenDeps): Promise<number> {
+ const out = deps.out ?? console;
+ const store = await deps.store();
+ if ("error" in store) {
+ out.error(`gen policy: ${store.error}`);
+ return 1;
+ }
+ const p = await store.read();
+ const usage = await store.usage();
+ if (o.json) out.log(JSON.stringify({ ...p, usage, from: store.where }, null, 2));
+ else for (const l of [...formatPolicy(p, usage), `(from ${store.where})`]) out.log(l);
+ return 0;
+}
+
+export async function setMain(o: { preset?: string; task?: string; route?: string }, deps: GenDeps): Promise<number> {
+ const out = deps.out ?? console;
+ const name = o.preset !== undefined ? "gen preset" : "gen set";
+ if (o.preset !== undefined && !(GENERATION_PRESET_NAMES as string[]).includes(o.preset)) {
+ out.error(`gen preset: one of ${GENERATION_PRESET_NAMES.join(", ")}`);
+ return 2;
+ }
+ if (o.preset === undefined && (!o.task || !isRoute(o.route))) {
+ out.error(`gen set: <task> ${GENERATION_ROUTES.join("|")}`);
+ return 2;
+ }
+ const store = await deps.store();
+ if ("error" in store) {
+ out.error(`${name}: ${store.error}`);
+ return 1;
+ }
+ const p = await store.read();
+ if (o.task && !Object.hasOwn(p.routes, o.task)) {
+ out.error(`gen set: no task "${o.task}" — the policy routes ${Object.keys(p.routes).join(", ")}`);
+ return 2;
+ }
+ // Choosing a preset is writing its routes; the preset is read back from them.
+ const routes = o.preset
+ ? { ...p.routes, ...GENERATION_PRESETS[o.preset as GenerationPreset] }
+ : { ...p.routes, [o.task!]: o.route as GenerationRoute };
+ const saved = await store.writeRoutes(routes);
+ for (const l of [...formatPolicy(saved, await store.usage()), `(written to ${store.where})`]) out.log(l);
+ return 0;
+}
+
+// The report-draft body from `gen run`'s words, or why not. The editor judges
+// the rest (controller/reportDraft.ts parseReportDraftBody).
+export function runBody(task: string, text: string | undefined, flags: Record<string, FlagValue>): Record<string, unknown> | { error: string } {
+ const str = (k: string) => (typeof flags[k] === "string" ? (flags[k] as string).trim() : undefined);
+ const article = str("article");
+ if (!article) return { error: "gen run: --article <id> names the article (a sweep may name a new one)" };
+ const body: Record<string, unknown> = { task, article };
+ const int = (k: string, key: string) => {
+ const v = str(k);
+ if (v === undefined) return null;
+ const n = Number(v);
+ if (!Number.isInteger(n) || n < 1) return `gen run: --${k} is an iteration number`;
+ body[key] = n;
+ return null;
+ };
+ for (const [k, key] of [["iteration", "iteration"], ["copy-of", "copyOf"]] as const) {
+ const e = int(k, key);
+ if (e) return { error: e };
+ }
+ const words = text?.trim();
+ if (words) body[task === "sweep" || task === "research" ? "question" : "feedback"] = words;
+ for (const k of ["question", "feedback", "from", "to", "model", "source", "build"] as const) {
+ const v = str(k);
+ if (v) body[k] = v;
+ }
+ for (const k of ["channels", "cards"] as const) {
+ const v = str(k);
+ if (v) body[k] = v.split(",").map((x) => x.trim()).filter(Boolean);
+ }
+ const max = str("max-usd");
+ if (max !== undefined) {
+ const n = Number(max);
+ if (!(n > 0)) return { error: "gen run: --max-usd is a positive number of dollars" };
+ body.maxUsd = n;
+ }
+ if (flags.force === true) body.force = true;
+ const autonomy = str("autonomy");
+ if (autonomy !== undefined) {
+ if (task !== "research") return { error: "gen run: --autonomy is a research run's" };
+ body.autonomy = autonomy;
+ }
+ return body;
+}
+
+export async function runMain(o: { task?: string; text?: string; flags: Record<string, FlagValue> }, deps: GenDeps): Promise<number> {
+ const out = deps.out ?? console;
+ if (!o.task) {
+ out.error(`gen run: which task? ${TASKS_HELP}`);
+ return 2;
+ }
+ const body = runBody(o.task, o.text, o.flags);
+ if ("error" in body) {
+ out.error(String(body.error));
+ return 2;
+ }
+ const via = typeof o.flags.via === "string" ? o.flags.via : undefined;
+ if (via !== undefined && !isRoute(via)) {
+ out.error(`gen run: --via is ${GENERATION_ROUTES.join(", ")}`);
+ return 2;
+ }
+ if (via && body.model) {
+ out.error("gen run: give --model or --via, not both");
+ return 2;
+ }
+ if (!body.model) {
+ const store = await deps.store();
+ if ("error" in store) {
+ out.error(`gen run: ${store.error}`);
+ return 1;
+ }
+ const p = await store.read();
+ const route = via ?? p.routes[o.task];
+ if (route === "code") {
+ out.log(
+ `gen: ${o.task} is routed to Claude Code (${via ? "--via code" : `preset ${p.preset}`}) — do it in the session; ` +
+ "`gen run … --via api|local` overrides once.",
+ );
+ return 3;
+ }
+ if (store.offline) {
+ out.error(`gen run: ${o.task} is routed to ${route ?? "?"}, and no editor answers — generation runs in the editor; start it`);
+ return 1;
+ }
+ if (route) body.model = p.models[route];
+ out.error(`gen: ${o.task} → ${route ?? "the editor's choice"}${body.model ? ` (${String(body.model)})` : ""}`);
+ }
+ return deps.runOps(["report-draft", "--json", JSON.stringify(body), ...(o.flags.wait === true ? ["--wait"] : [])]);
+}
+
+// `pnpm ops <argv>` as a child of this process (stdio inherited).
+export function runOpsChild(argv: string[]): Promise<number> {
+ return runChild({ command: process.execPath, args: [path.join(REPO_ROOT, "scripts", "archilyzer-ops.mjs"), ...argv], cwd: REPO_ROOT });
+}
+
+const defaultDeps = (ctx: CommandContext): GenDeps => ({ store: () => defaultStore(ctx.env), runOps: runOpsChild });
+
+export async function genPolicyRow(ctx: CommandContext): Promise<number> {
+ return policyMain({ json: ctx.flags.json === true }, defaultDeps(ctx));
+}
+export async function genPresetRow(ctx: CommandContext): Promise<number> {
+ return setMain({ preset: ctx.positionals[0] ?? "" }, defaultDeps(ctx));
+}
+export async function genSetRow(ctx: CommandContext): Promise<number> {
+ const [task, route] = ctx.positionals;
+ return setMain({ ...(task ? { task } : {}), ...(route ? { route } : {}) }, defaultDeps(ctx));
+}
+export async function genRunRow(ctx: CommandContext): Promise<number> {
+ const [task, text] = ctx.positionals;
+ return runMain({ ...(task ? { task } : {}), ...(text ? { text } : {}), flags: ctx.flags }, defaultDeps(ctx));
+}
diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts
@@ -93,7 +93,7 @@ const DECLARED: EnvVarDecl[] = [
paths("STAGIT_BIN", "`stagit` on PATH, then `~/.local/bin/stagit`", "stagit, which renders the source's history pages (`/source/git/`: the log and a page per commit with its diff). Optional: without it the source is published without them. See [PUBLISH.md](PUBLISH.md)."),
// ── runtime ────────────────────────────────────────────────────────────
- { name: "WORKER_TOKEN", audience: "runtime", default: "unset (both surfaces off)", readBy: "common/lib/workerToken.ts, scripts/archilyzer-ops.mjs, mcp/src/fetchClip.ts, mcp/src/editorOps.ts, mcp/src/archivalTools.ts, umtool/lib/annotations/agentAuth.mjs", doc: "Bearer token for the remote-worker API and for `/api/ops/*` (`pnpm ops`; the MCP's `fetch_clip`, `enqueue`, `get_job`, `channel_coverage` and `get_transcript`'s editor fallback), and for an agent's write to umtool's notes (the MCP's `notes` reply, stamped \"agent\"; umtool reads it from its environment, else the editor's `editor/.env`). Set the same value on every end." },
+ { name: "WORKER_TOKEN", audience: "runtime", default: "unset (both surfaces off)", readBy: "common/lib/workerToken.ts, scripts/archilyzer-ops.mjs, common/bin/gen.ts, mcp/src/fetchClip.ts, mcp/src/editorOps.ts, mcp/src/archivalTools.ts, umtool/lib/annotations/agentAuth.mjs", doc: "Bearer token for the remote-worker API and for `/api/ops/*` (`pnpm ops` and `archilyzer gen`; the MCP's `fetch_clip`, `enqueue`, `get_job`, `channel_coverage`, `generation_policy`, `generate` and `get_transcript`'s editor fallback), and for an agent's write to umtool's notes (the MCP's `notes` reply, stamped \"agent\"; umtool reads it from its environment, else the editor's `editor/.env`). Set the same value on every end." },
{ name: "ANTHROPIC_API_KEY", audience: "runtime", default: "unset (the API key file is read instead)", readBy: "common/lib/llm/anthropic.ts", doc: "The Claude API key for report and video generation on the API (release 27): read first, before the mode-600 key file the generation settings name. Sent only to the Messages API in `x-api-key`; never logged, and never in an error, a job record or a transcript." },
{ name: "SYNC_HEARTBEAT_SECONDS", audience: "runtime", default: "`settings.syncScheduler.heartbeatSeconds`", readBy: "editor/app/scheduler/heartbeat.ts", doc: "Overrides the editor's in-process sync heartbeat. `0` = no internal timer (tick from cron instead)." },
{ name: "SYNC_TICK_URL", audience: "runtime", default: "`http://127.0.0.1:3001/api/scheduler/tick`", readBy: "common/bin/sync-tick.ts", doc: "Where `archilyzer sync tick` (cron's heartbeat) posts." },
@@ -134,7 +134,7 @@ const DECLARED: EnvVarDecl[] = [
{ name: "ARCHILYZER_INDEX_ALLOW_HELD", audience: "runtime", default: "off", readBy: "common/controller/buildIndex.ts", doc: "`1` lets a FULL index rebuild (a schema change, or no index yet) proceed while a channel's media cannot be read; that channel stays out of the index until its media is back and the index is built again. Unset, such a build refuses and names each channel." },
{ name: "UV_THREADPOOL_SIZE", audience: "runtime", default: "`16` for the editor (`4` is Node's own)", readBy: "Node's libuv (set by editor/package.json `start` and docker/entrypoint.sh)", doc: "Threads in Node's pool for filesystem calls. A call on a stalled drive holds one until the drive answers, so the editor starts with 16. It buys time for calls already in flight and isolates nothing: the storage health probe and its gate keep new calls off a stalled drive." },
{ name: "MCP_IO_STATS", audience: "runtime", default: "off", readBy: "common/lib/archive/io-stats.ts", doc: "`1` turns on per-call I/O accounting, for `mcp/bench`." },
- { name: "ARCHILYZER_EDITOR_URL", audience: "runtime", default: "`http://localhost:3001`", readBy: "scripts/archilyzer-ops.mjs, mcp/src/fetchClip.ts, mcp/src/editorOps.ts, umtool, common/bin/migrate-media-tier.ts", doc: "Which editor `pnpm ops` and the MCP's editor-backed tools (`fetch_clip`, `enqueue`, `get_job`, `channel_coverage`, `get_transcript`'s fallback) talk to, and whose `/api/pulse` `archilyzer storage migrate-tier` asks before it refuses to run beside it." },
+ { name: "ARCHILYZER_EDITOR_URL", audience: "runtime", default: "`http://localhost:3001`", readBy: "scripts/archilyzer-ops.mjs, common/bin/gen.ts, mcp/src/fetchClip.ts, mcp/src/editorOps.ts, umtool, common/bin/migrate-media-tier.ts", doc: "Which editor `pnpm ops`, `archilyzer gen` and the MCP's editor-backed tools (`fetch_clip`, `enqueue`, `get_job`, `channel_coverage`, `generation_policy`, `generate`, `get_transcript`'s fallback) talk to, and whose `/api/pulse` `archilyzer storage migrate-tier` asks before it refuses to run beside it." },
{ name: "ARCHILYZER_AGENT", audience: "runtime", default: "`cli`", readBy: "scripts/archilyzer-ops.mjs", doc: "Who is asking, recorded as the provenance of a curated-tag write through `pnpm ops`." },
{ name: "DIARIZE_ENGINE_KIND", audience: "runtime", default: "`sherpa-onnx`", readBy: "scripts/diarize.mjs", doc: "The diarization engine: `sherpa-onnx` or `sortformer`." },
{ name: "DIARIZE_ENGINE_CMD", audience: "runtime", default: "the bundled sherpa script", readBy: "scripts/diarize.mjs", doc: "The engine command the wrapper runs." },
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -5,6 +5,10 @@
- **Two iterations side by side: `/articles/<id>/compare?a=&b=`.** Each side's report, section by section, with what the other side lacks marked; the ops its revision applied and refused (and why); its failed checks; and, when both have one, the two video cuts with their narration. Tick **compare** on two iterations to open it.
- **The generation policy is on `/articles/new`.** The presets (`code`, `balanced`, `api`, `local`), where each task runs, the models and the caps, saved into the editor's `settings.generation`; the editor refuses a cap it would not keep, in its words. The API key is never shown or taken: the panel shows the key file's path and whether the file is there. The day's API spend is shown against the daily cap.
- **umtool's `/drafts` page is gone; it opens `/articles/new`.**
+- **Claude Code follows the generation balance: `/gen`, and the MCP's `generation_policy` and `generate`.** `generation_policy` shows where each generation task runs (`code` = this Claude Code session, `api` = the Claude API, `local` = the local model), on which model, the caps and the day's Claude API spend against the daily cap; with a preset or a task and route it moves the balance, only when you ask. `generate` runs a task as a `report-draft` job on the editor (a sweep, a revision of a report or its video, a narration, a research run with its autonomy, or a sweep continuing a research run), refuses one routed to Claude Code, and with `wait: true` follows the job and answers the iteration it made: its cost, the ops it applied and refused, its checks and where its files are, with what to review before it is made current. `/gen` (`.claude/commands/gen.md`, in the repo) wraps both: tasks routed away are run through `generate` and reviewed, tasks routed to Claude Code are done in the session. It replaces the stopgap's user-level `/gen`. Claude Code picks the tools up on its next start; they need the MCP registered with `ARCHILYZER_EDITOR_URL` and `WORKER_TOKEN`.
+- **`/sweep` follows the policy too.** When sweeps are routed to the API or the local model, the `/sweep` plan's first step is `generate`, then a review of what it made — read the iteration's report, spot-check its quotes with `get_transcript`, then recommend making it current or a revision — instead of running the sweep in the session. `via=code` (or `api`, `local`) in the request overrides the policy for that plan, and `article=` names the article. With no editor configured the plan is unchanged. `/ask` still answers in the conversation, and names the tasks the policy routes away.
+- **`archilyzer gen policy | preset | set | run`** is the same balance from a terminal: through the editor when it answers, else `settings.json` through the settings writer when no editor is listening (never beside one that is there but silent). `gen run <task> [<question or feedback>] --article <id> …` enqueues the job as `pnpm ops report-draft` does (`--wait` follows it) and exits 3, running nothing, when the task is routed to Claude Code; `--via` overrides once.
+- **Two new reads: `pnpm ops get generation-usage [<day>]`** (the day's Claude API spend and the daily cap) **and `pnpm ops get iterations <article>`** (an article's iterations and which is current). Needs a restart of the editor.
- **Research runs: the editor finds what an article's archive lacks and asks for it.** `pnpm ops report-draft --json '{"task": "research", "article", "question", "channels"?, "autonomy"?}'` runs a research iteration: a model searches the corpus, the web and archive.org (an item's file list included), then proposes each acquisition it needs (an archive.org import, a video, a new channel, a post, a transcription, a persist) with its reason, evidence links and estimated size. Under `propose` every one waits for your yes or no; under `limits` imports into existing channels under the caps run at once; under `auto` everything runs, through the editor's own queues and holds, until a cap. A new channel is always created on no site, an X channel is never put on one, and a Twitch VOD is never fetched, in every mode. The proposals are kept in the iteration's `proposals.json`.
- **`pnpm ops research-approve` settles a research run.** `{"article", "iteration", "ids": ["p01", …], "approve": true | false, "note"?}` runs the approved proposals through the editor (past the run's autonomy and caps, never past a standing rule) or rejects them; with no ids it answers the run's state. Every call first checks the jobs of what was enqueued, so the run moves from waiting to ready as they finish. `report-draft {"task": "sweep", "article", "iteration": <the research run>}` then continues it: a sweep over the run's channels and every channel it acquired into, its question by default (refused while the run still waits, unless `"force": true`).
- **New settings: `generation.research`** (SETTINGS.md): a research run's default autonomy (`propose`), and its limits — 20 items, 5 GB and 6 hours of transcription a run, new channels and post walks waiting for approval under `limits`. `generation.routes.research` says where a research run runs (`api` in the balanced preset); a settings file from before keeps its preset.
diff --git a/editor/app/api/ops/_generation.test.ts b/editor/app/api/ops/_generation.test.ts
@@ -0,0 +1,93 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { callGet, setupOpsCorpus } from "./_testCorpus";
+
+// Run with:
+// pnpm -C editor exec tsx --test "app/api/ops/_generation.test.ts"
+//
+// The two generation reads (release 27 S9): the day's API spend
+// (`generation-usage`) and an article's iterations (`iterations`), behind the
+// token, read only — what the MCP's generation_policy and generate ask.
+
+const corpus = await setupOpsCorpus(null);
+const usageFile = path.join(corpus.root, ".generation", "usage.jsonl");
+process.env.GENERATION_USAGE_FILE = usageFile;
+await corpus.writeSettings({ minFreeDiskGB: 0, generation: { caps: { daily: 7 } } });
+
+type Get = Parameters<typeof callGet>[0];
+const route = async (name: string) => (await import(`./${name}/route`)).GET as Get;
+test.after(() => corpus.cleanup());
+
+const row = (day: string, jobId: string, usd: number) =>
+ JSON.stringify({
+ at: `${day}T10:00:00.000Z`,
+ day,
+ jobId,
+ article: "synth-a",
+ iteration: 1,
+ task: "sweep",
+ model: "claude-sonnet-5-5",
+ inputTokens: 1,
+ outputTokens: 1,
+ cacheReadTokens: 0,
+ cacheWriteTokens: 0,
+ usd,
+ });
+
+test("both reads are behind the token", async () => {
+ for (const name of ["generation-usage", "iterations"]) {
+ const res = await callGet(await route(name), "http://localhost/api/ops/x?article=a", {}, {});
+ assert.equal(res.status, 401, name);
+ }
+});
+
+test("generation-usage answers the day's ledger total and the daily cap", async () => {
+ const get = await route("generation-usage");
+ const none = await callGet(get, "http://localhost/api/ops/generation-usage?day=2026-10-01");
+ assert.deepEqual(none.body, { ok: true, day: "2026-10-01", usd: 0, jobs: 0, daily: 7 });
+ await mkdir(path.dirname(usageFile), { recursive: true });
+ await writeFile(usageFile, [row("2026-10-01", "j1", 1.25), row("2026-10-01", "j2", 0.5), row("2026-10-02", "j3", 9)].join("\n") + "\n");
+ const some = await callGet(get, "http://localhost/api/ops/generation-usage?day=2026-10-01");
+ assert.deepEqual(some.body, { ok: true, day: "2026-10-01", usd: 1.75, jobs: 2, daily: 7 });
+ const today = await callGet(get, "http://localhost/api/ops/generation-usage");
+ assert.equal(today.body.day, new Date().toISOString().slice(0, 10));
+ const bad = await callGet(get, "http://localhost/api/ops/generation-usage?day=yesterday");
+ assert.equal(bad.status, 400);
+ const stray = await callGet(get, "http://localhost/api/ops/generation-usage?date=2026-10-01");
+ assert.equal(stray.status, 400);
+});
+
+test("iterations lists an article's iterations, and one with where its files are", async () => {
+ const { createIteration, updateIteration, writeIterationFile } = await import(
+ "yt-dlp-transcript-common/lib/report/iterations"
+ );
+ await createIteration("synth-a", { kind: "sweep", model: "claude-sonnet-5-5", question: "q?", scope: { channels: ["synth-kitchen"] } });
+ await writeIterationFile("synth-a", 1, "sweep.md", "# A sweep\n");
+ await updateIteration("synth-a", 1, { status: "done", ops: { applied: [{ op: "drop" }], refused: [] } });
+ const get = await route("iterations");
+
+ const all = await callGet(get, "http://localhost/api/ops/iterations?article=synth-a");
+ assert.equal(all.status, 200);
+ const its = all.body.iterations as { n: number; status: string }[];
+ assert.deepEqual(its.map((i) => [i.n, i.status]), [[1, "done"]]);
+ assert.deepEqual(all.body.current, { report: null, reportFrom: null, video: null });
+
+ const one = await callGet(get, "http://localhost/api/ops/iterations?article=synth-a&n=1");
+ assert.equal(one.status, 200);
+ assert.equal((one.body.iteration as { kind: string }).kind, "sweep");
+ const files = one.body.files as Record<string, string | null>;
+ assert.equal(files["sweep.md"], path.join(String(one.body.dir), "sweep.md"));
+ assert.equal(files["report.json"], null);
+ assert.ok(String(one.body.dir).startsWith(corpus.transcripts));
+
+ const missing = await callGet(get, "http://localhost/api/ops/iterations?article=synth-a&n=4");
+ assert.equal(missing.status, 404);
+ const nobody = await callGet(get, "http://localhost/api/ops/iterations?article=synth-none");
+ assert.equal(nobody.status, 404);
+ const badId = await callGet(get, "http://localhost/api/ops/iterations?article=../x");
+ assert.equal(badId.status, 400);
+ const badN = await callGet(get, "http://localhost/api/ops/iterations?article=synth-a&n=0");
+ assert.equal(badN.status, 400);
+});
diff --git a/editor/app/api/ops/generation-usage/route.ts b/editor/app/api/ops/generation-usage/route.ts
@@ -0,0 +1,26 @@
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { getSettings } from "yt-dlp-transcript-common/lib/settings";
+import { dayUsage, utcDay } from "yt-dlp-transcript-common/controller/generationUsage";
+import { readRoute } from "../_read";
+import { opsFail } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// GET [?day=YYYY-MM-DD]
+// -> { ok, day, usd, jobs, daily }
+//
+// The day's Claude API spend on generation (release 27 S9): the usage
+// ledger's total for the UTC day (default today) — what the daily cap is
+// checked against (controller/generationUsage.ts) — and the cap itself
+// (`settings.generation.caps.daily`, 0 = none). The MCP's generation_policy
+// and `archilyzer gen policy` show it beside the routes. Read only.
+const DAY = /^\d{4}-\d{2}-\d{2}$/;
+
+export async function GET(request: Request) {
+ return readRoute(request, ["day"], async (q) => {
+ const day = q.get("day")?.trim() || utcDay();
+ if (!DAY.test(day)) return opsFail('"day" must be a date YYYY-MM-DD (UTC)');
+ const used = await dayUsage(getPaths().generationUsageFile, day);
+ return { ...used, daily: getSettings().generation.caps.daily };
+ });
+}
diff --git a/editor/app/api/ops/iterations/route.ts b/editor/app/api/ops/iterations/route.ts
@@ -0,0 +1,56 @@
+import { access } from "node:fs/promises";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import {
+ ITERATION_FILES,
+ iterationDir,
+ iterationFile,
+ readIteration,
+ readIterations,
+} from "yt-dlp-transcript-common/lib/report/iterations";
+import { isReportId } from "yt-dlp-transcript-common/lib/report/schema";
+import { readRoute } from "../_read";
+import { opsFail } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// GET ?article=<id>[&n=<n>]
+// -> { ok, article, current, iterations: [iteration.json…], problems }
+// -> with n: { ok, article, current, iteration, dir, files: {<name>: <path> | null} }
+//
+// An article's iterations (release 27 S9; lib/report/iterations.ts), read
+// only: every one with which is current, or one with where it lives on the
+// editor's disk — its directory and the path of each file it has (report.json,
+// sweep.md, turns.jsonl, proposals.json; null when absent). The MCP's
+// `generate` summarises a finished job's iteration from it, and names the
+// files Claude Code reviews. Nothing here writes; making one current is
+// umtool's Iterations tab (or the chain's `current` step).
+export async function GET(request: Request) {
+ return readRoute(request, ["article", "n"], async (q) => {
+ const article = q.get("article")?.trim() ?? "";
+ if (!article) return opsFail('"article" is required (an article id)');
+ if (!isReportId(article)) return opsFail(`"${article}" is not an article id`);
+ const paths = getPaths();
+ const rawN = q.get("n");
+ const read = await readIterations(article, paths);
+ if (rawN === null) {
+ if (read.iterations.length === 0 && read.problems.length === 0) {
+ return opsFail(`"${article}" has no iterations`, 404);
+ }
+ return { article, current: read.current, iterations: read.iterations, problems: read.problems };
+ }
+ const n = Number(rawN);
+ if (!Number.isInteger(n) || n < 1) return opsFail('"n" is an iteration number (1, 2, …)');
+ const it = await readIteration(article, n, paths).catch((e: Error) => e);
+ if (it instanceof Error) return opsFail(`"${article}" i${n}: ${it.message}`, 500);
+ if (!it) return opsFail(`"${article}" has no iteration i${n}`, 404);
+ const files: Record<string, string | null> = {};
+ for (const name of ITERATION_FILES) {
+ const file = iterationFile(paths, article, n, name);
+ files[name] = await access(file).then(
+ () => file,
+ () => null,
+ );
+ }
+ return { article, current: read.current, iteration: it, dir: iterationDir(paths, article, n), files };
+ });
+}
diff --git a/mcp/README.md b/mcp/README.md
@@ -12,8 +12,11 @@ The exceptions all ask a local Archilyzer editor (`ARCHILYZER_EDITOR_URL` +
window, `enqueue` queues archival work, `get_job` / `channel_coverage` read the
editor's jobs and disk, and `get_transcript` falls back to the editor's disk for a
video not yet published; `notes` reads umtool (`UMTOOL_URL`) and writes a reply
-there as the agent's. The MCP itself still writes nothing. Settings, storage and
-deletes are not reachable from it (`pnpm ops` only).
+there as the agent's; `generate` runs a report or video generation as an editor
+job and `generation_policy` reads (and, when the operator asks, sets) where each
+generation task runs. The MCP itself still writes nothing. Settings — but for the
+generation routes — storage and deletes are not reachable from it (`pnpm ops`
+only).
## Tools
@@ -33,10 +36,12 @@ deletes are not reachable from it (`pnpm ops` only).
| `enqueue` | Queue archival work on a channel the editor archives, as its page's buttons do (`POST /api/ops/<kind>`): `sync` (`full`), `download-missing`, `retry-bucket` (`bucket`, `ids` — the way to download chosen videos), `transcribe-bucket` (`ids`), `fetch-posts` (`full` / `older`), `import-video` (`url`). Answers the job id; the editor runs it on its own queues at each platform's pace. Only when the operator asks. Needs the editor. |
| `channel_coverage` | What a channel **holds** on the editor's disk by date (`GET /api/ops/coverage`): count, first and last day, per year, and every gap longer than `gap_days` (30); `date_from` / `date_to` narrow it, `list` lists the videos. Each video is dated by its **recorded date** when the channel has a title rule (a VOD mirror, release 20), else its upload date. Needs the editor. |
| `notes` | The operator's notes in umtool on articles and report-video projects: `list` (every open note, by target), `read` (`target` as `list` names it — the digest with anchors resolved and the source file to edit). `reply` (`note_id`, `text`, `resolve`) writes the reply in umtool (`POST /api/notes` with `Authorization: Bearer <WORKER_TOKEN>`), which stamps it "agent" — never the operator's; its `target` is found from the open notes when omitted. Edit the note's source file and regenerate first. Needs `UMTOOL_URL`; a reply needs `WORKER_TOKEN` (the editor's own, which umtool reads too — a 401 means umtool holds another). |
+| `generation_policy` | The operator's generation balance (`settings.generation`, `GET /api/ops/settings?key=generation`): for each task — `sweep`, `revise-report`, `revise-video`, `narrate`, `research` — whether this Claude Code session (`code`), the Claude API (`api`) or the local model (`local`) does it, on which model; the caps; and the day's Claude API spend against the daily cap (`GET /api/ops/generation-usage`). `preset` (`code`, `balanced`, `api`, `local`) or `task` + `route` rewrites the routes (`POST /api/ops/settings`) — only when the operator asks. Never shows the API key. Needs the editor. |
+| `generate` | Run a generation task as a `report-draft` job on the editor (`POST /api/ops/report-draft`): `sweep` (`question`, `channels`, `from`/`to`), `revise-report` / `revise-video` (`iteration`, `feedback`), `narrate` (`iteration`, `cards`, `force`), `research` (`question`, `channels`, `autonomy`: `propose`, `limits` or `auto`; a `sweep` with the run's `iteration` continues it over the widened scope); `copyOf` runs an iteration again on another model. The model is `model`, else `via`'s route, else the policy's route — a task routed to `code` is refused (do it in the session). `wait: true` follows the job (one poll every 5 s, a progress notification each, up to `wait_seconds`, default 90, max 300; resume with `job`) and answers the iteration: status, cost per model, ops applied and refused, checks, and where its files are on the editor's disk (`GET /api/ops/iterations`), with the review to do before anything is made current. Needs the editor. |
| `open_link` | Paste an archilyzer viewer **share link** to re-run that exact search here (query tree + every filter, at full fidelity) — plan, results and corpus handle in **one** call. `dry_run:true` for the plan alone. |
| `list_sources` | Show the **default** corpus and, with a hub, its member sites as ready-to-paste handles. A site with reports says how many; a cited-only site says it is one. |
| `resolve_source` | Turn a URL or site name into the canonical `source` handle and check it can be read. Changes nothing. |
-| `sweep_plan` / `ask_plan` | Turn a plain-English request (plus an optional pasted link) into a resolved, step-by-step plan. What `/sweep` and `/ask` call. |
+| `sweep_plan` / `ask_plan` | Turn a plain-English request (plus an optional pasted link) into a resolved, step-by-step plan. What `/sweep` and `/ask` call. With an editor configured they read the generation policy: a sweep routed to `api` or `local` becomes "call `generate`, wait, review it" (`via=code` in the request runs it here instead); an ask names the routed tasks. |
**Clickable moment links.** Every timestamp the read tools emit is a Markdown link
to the exact second — an **archilyzer viewer** deep link (`…/?v=<slug>&t=<sec>`,
@@ -298,6 +303,14 @@ tools and the prompt — rather than duplicated into the markdown command files,
so it cannot drift out of sync with the tools it names. A test asserts every
tool the instructions mention actually exists.
+### `/gen`
+
+`.claude/commands/gen.md` is the generation balance's entry point (release 27):
+it reads `generation_policy`, maps the request to tasks, runs each task routed to
+`api` or `local` through `generate` and **reviews** what it made, and does a task
+routed to `code` in the session (`/sweep` for a report). `archilyzer gen
+policy|preset|set|run` is the same balance from a terminal.
+
## Counts are of recordings, not uploads
Some videos exist in the archive more than once — the same recording mirrored to
@@ -505,8 +518,8 @@ nothing to reset).
**Still read-only.** A `source` handle only changes *which* already-published
static shards are read — the same capability the startup flags already grant
-this locally-run tool. This server never writes to any corpus; `fetch_clip` and
-`enqueue` ask the editor, and the editor writes.
+this locally-run tool. This server never writes to any corpus; `fetch_clip`,
+`enqueue` and `generate` ask the editor, and the editor writes.
## Protocol
diff --git a/mcp/src/editorOps.ts b/mcp/src/editorOps.ts
@@ -18,7 +18,9 @@ import {
// said in words, never as a stack.
//
// Settings, storage and deletes are NOT reachable from here (operator ruling,
-// release 19): those stay `pnpm ops` / `archilyzer` only.
+// release 19): those stay `pnpm ops` / `archilyzer` only. The one exception is
+// the generation routes, which generation_policy writes when the operator asks
+// (release 27 D8; generation.ts).
export type EditorDeps = Pick<FetchClipDeps, "env" | "fetch" | "requestTimeoutMs">;
diff --git a/mcp/src/generation.test.ts b/mcp/src/generation.test.ts
@@ -0,0 +1,367 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { connectWith, fakeEditor, isError, textOf } from "./editorOps.testkit";
+import {
+ GENERATE_POLL_MS,
+ GENERATE_TASKS,
+ generateTool,
+ generationPolicyTool,
+ planGeneration,
+ 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: "<redacted>",
+ 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<string, unknown>; runPolls?: number; end?: string; iteration?: Record<string, unknown>; marker?: boolean } = {}) {
+ 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({ article: "synth-a", iteration: 3, 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<string, string> } } }).patch.generation.routes;
+ const presets: Record<string, string> = {
+ "code,code,code,code,code": "code",
+ "api,api,api,api,api": "api",
+ "local,local,local,local,local": "local",
+ "code,api,local,local,api": "balanced",
+ };
+ policy = { ...policy, routes: routes as typeof policy.routes, preset: presets[Object.values(routes).join(",")] ?? "custom" };
+ 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") 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" } } },
+ });
+ 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: { sweep: "local", "revise-report": "api", "revise-video": "api", narrate: "api", research: "api" } } },
+ });
+ 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<string, unknown>, 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: "teaser", route: "api" }, e.deps as never);
+ assert.match(unknown.text, /no task "teaser" — 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);
+ for (const [args, re] of [
+ [{ task: "teaser", article: "a" }, /task is one of sweep, revise-report, revise-video, narrate, research/],
+ [{ 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/],
+ ] as const) {
+ const v = validateGenerateArgs(args as Record<string, unknown>);
+ assert.equal(v.ok, false, JSON.stringify(args));
+ assert.match((v as { error: string }).error, re);
+ }
+});
+
+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/);
+});
diff --git a/mcp/src/generation.ts b/mcp/src/generation.ts
@@ -0,0 +1,648 @@
+import {
+ GENERATION_PRESETS,
+ GENERATION_PRESET_NAMES,
+ GENERATION_ROUTES,
+ GENERATION_TASKS,
+ type GenerationPreset,
+} from "yt-dlp-transcript-common/lib/generationSettings";
+import { AUTONOMIES } from "yt-dlp-transcript-common/lib/report/draft/research/decide";
+import { describeEditorFailure, editorGet, editorPost, type EditorAnswer } from "./editorOps";
+import type { FetchClipDeps, PollProgress } from "./fetchClip";
+import { reviewGuidance, type GenerationRoute, type PlanGeneration } from "./instructions";
+import type { ToolAnswer } from "./archivalTools";
+
+// ─── The Claude Code balance (release 27 S9; D8) ───
+//
+// Report and video generation runs in the editor, as `report-draft` jobs on
+// the Claude API or the local model, routed per task by settings.generation.
+// These two tools are Claude Code's side of that balance:
+//
+// generation_policy GET /api/ops/settings?key=generation (the routes)
+// GET /api/ops/generation-usage (the day's spend)
+// POST /api/ops/settings {patch: {generation: {routes}}}
+// — a preset or one route, ONLY when the operator asks
+// generate POST /api/ops/report-draft (enqueue)
+// GET /api/ops/job/<id>?tail=N (follow)
+// GET /api/ops/iterations?article=&n= (the result)
+//
+// The release 19 ruling keeps settings out of the MCP; D8 (ratified
+// 2026-10-13) makes the generation ROUTES the one exception, so the operator
+// can move the balance from a Claude Code session. Nothing else in settings is
+// reachable, and the API key never is: it is not a setting (only its file's
+// path is, and the editor redacts that), and this module renders neither.
+//
+// Pure apart from the injected deps (env, fetch, sleep, now); server.ts adapts.
+
+export type GenerationDeps = FetchClipDeps;
+
+// The policy as the editor answers it (sanitizeGeneration's output).
+export type GenerationPolicy = PlanGeneration & {
+ models: { api: string; local: string; extractor?: string };
+ caps?: { sweep?: number; revision?: number; narration?: number; daily?: number; max?: number };
+};
+export type GenerationUsageDay = { day: string; usd: number; jobs: number; daily: number };
+
+// The tasks `generate` takes: the policy's (research included, S11).
+export const GENERATE_TASKS = [...new Set<string>([...GENERATION_TASKS, "research"])];
+
+const ARTICLE_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;
+const JOB_RE = /^[A-Za-z0-9_-]+$/;
+const trimmed = (v: unknown) => (typeof v === "string" ? v.trim() : "");
+
+const isRoute = (v: unknown): v is GenerationRoute =>
+ typeof v === "string" && (GENERATION_ROUTES as readonly string[]).includes(v);
+
+// The editor's `generation` block, or why not.
+function policyOf(value: unknown): GenerationPolicy | null {
+ if (!value || typeof value !== "object") return null;
+ const v = value as Record<string, unknown>;
+ const routes = v.routes && typeof v.routes === "object" ? (v.routes as Record<string, unknown>) : null;
+ const models = v.models && typeof v.models === "object" ? (v.models as Record<string, unknown>) : null;
+ if (!routes || !models || typeof models.api !== "string" || typeof models.local !== "string") return null;
+ const r: Record<string, GenerationRoute> = {};
+ for (const [task, route] of Object.entries(routes)) if (isRoute(route)) r[task] = route;
+ return {
+ preset: typeof v.preset === "string" ? v.preset : "custom",
+ routes: r,
+ models: {
+ api: models.api,
+ local: models.local,
+ ...(typeof models.extractor === "string" ? { extractor: models.extractor } : {}),
+ },
+ ...(v.caps && typeof v.caps === "object" ? { caps: v.caps as GenerationPolicy["caps"] } : {}),
+ };
+}
+
+export async function readPolicy(
+ deps: GenerationDeps,
+): Promise<{ ok: true; policy: GenerationPolicy } | { ok: false; answer: Exclude<EditorAnswer, { kind: "ok" }> | null }> {
+ const a = await editorGet(deps, "/api/ops/settings?key=generation");
+ if (a.kind !== "ok") return { ok: false, answer: a };
+ const policy = policyOf(a.body.value);
+ return policy ? { ok: true, policy } : { ok: false, answer: null };
+}
+
+async function readUsage(deps: GenerationDeps): Promise<GenerationUsageDay | string> {
+ const a = await editorGet(deps, "/api/ops/generation-usage");
+ if (a.kind !== "ok") return describeEditorFailure("the day's spend", a);
+ const b = a.body;
+ if (typeof b.usd !== "number" || typeof b.day !== "string") return "the day's spend: the editor's answer carried none";
+ return { day: b.day, usd: b.usd, jobs: Number(b.jobs) || 0, daily: Number(b.daily) || 0 };
+}
+
+// What a plan needs: the policy when the editor answers, else nothing (with a
+// note when an editor was configured and did not answer).
+export async function planGeneration(deps: GenerationDeps): Promise<{ generation?: PlanGeneration; note?: string }> {
+ const r = await readPolicy(deps);
+ if (r.ok) return { generation: { preset: r.policy.preset, routes: r.policy.routes, models: { api: r.policy.models.api, local: r.policy.models.local } } };
+ if (r.answer?.kind === "no_editor") return {};
+ return {
+ note:
+ `the generation policy could not be read (${r.answer ? describeEditorFailure("generation_policy", r.answer) : "the editor's answer carried no generation block"}) — ` +
+ `this plan is for this session`,
+ };
+}
+
+const usd = (n: number) => `$${n.toFixed(2)}`;
+
+export function renderPolicy(p: GenerationPolicy, usage: GenerationUsageDay | string | null, changed?: string): string {
+ const lines: string[] = [];
+ if (changed) lines.push(changed, "");
+ lines.push(`Generation policy (settings.generation): preset **${p.preset}**`);
+ for (const [task, route] of Object.entries(p.routes)) {
+ lines.push(
+ `- ${task} → ${route}` +
+ (route === "code" ? " (this Claude Code session)" : ` (${route === "api" ? "the Claude API" : "the local model"}, ${p.models[route]})`),
+ );
+ }
+ lines.push(
+ `Models: api ${p.models.api} · local ${p.models.local}${p.models.extractor ? ` · extractor ${p.models.extractor}` : ""}`,
+ );
+ const c = p.caps;
+ if (c) {
+ const parts = [
+ c.sweep !== undefined ? `sweep ${usd(c.sweep)}` : "",
+ c.revision !== undefined ? `revision ${usd(c.revision)}` : "",
+ c.narration !== undefined ? `narration ${usd(c.narration)}` : "",
+ c.max !== undefined ? `any job at most ${usd(c.max)}` : "",
+ c.daily !== undefined ? (c.daily > 0 ? `daily ${usd(c.daily)}` : "no daily cap") : "",
+ ].filter(Boolean);
+ if (parts.length) lines.push(`Caps (Claude API, per job unless said): ${parts.join(" · ")}`);
+ }
+ if (typeof usage === "string") lines.push(`Today's spend: unknown (${usage})`);
+ else if (usage) {
+ lines.push(
+ `Today (${usage.day}, UTC): ${usd(usage.usd)} spent on the Claude API in ${usage.jobs} job(s)` +
+ (usage.daily > 0 ? ` of the ${usd(usage.daily)} daily cap` : ""),
+ );
+ }
+ lines.push(
+ "",
+ "A task routed to api or local: call generate (wait: true) and REVIEW what it makes. " +
+ "A task routed to code: do it in this session (/sweep for a report). " +
+ "Change the routes only when the operator asks (generation_policy with preset, or task and route).",
+ );
+ return lines.join("\n");
+}
+
+// ─── generation_policy ───
+
+export async function generationPolicyTool(args: Record<string, unknown>, deps: GenerationDeps): Promise<ToolAnswer> {
+ const preset = trimmed(args.preset);
+ const task = trimmed(args.task);
+ const route = trimmed(args.route);
+ if (preset && (task || route)) {
+ return { text: "generation_policy: give a preset, or a task and its route — not both", isError: true };
+ }
+ if ((task && !route) || (route && !task)) {
+ return { text: "generation_policy: a route change names both task and route (code, api or local)", isError: true };
+ }
+ if (preset && !(GENERATION_PRESET_NAMES as string[]).includes(preset)) {
+ return { text: `generation_policy: preset is one of ${GENERATION_PRESET_NAMES.join(", ")}`, isError: true };
+ }
+ if (route && !isRoute(route)) {
+ return { text: `generation_policy: route is one of ${GENERATION_ROUTES.join(", ")}`, isError: true };
+ }
+ const read = await readPolicy(deps);
+ if (!read.ok) {
+ return {
+ text: read.answer ? describeEditorFailure("generation_policy", read.answer) : "generation_policy: the editor's answer carried no generation block",
+ isError: true,
+ };
+ }
+ const policy = read.policy;
+ if (!preset && !task) return { text: renderPolicy(policy, await readUsage(deps)) };
+
+ if (task && !Object.hasOwn(policy.routes, task)) {
+ return { text: `generation_policy: no task "${task}" — the policy routes ${Object.keys(policy.routes).join(", ")}`, isError: true };
+ }
+ // The ROUTES are the truth (S6): a preset is written as its routes, and the
+ // preset is read back from them. The patch names the whole routes object —
+ // the settings writer merges one level, so a nested object replaces.
+ const routes: Record<string, GenerationRoute> = preset
+ ? { ...policy.routes, ...GENERATION_PRESETS[preset as GenerationPreset] }
+ : { ...policy.routes, [task]: route as GenerationRoute };
+ const a = await editorPost(deps, "/api/ops/settings", { patch: { generation: { routes } } });
+ if (a.kind !== "ok") return { text: describeEditorFailure("generation_policy", a), isError: true };
+ const saved = policyOf((a.body.value as Record<string, unknown> | undefined)?.generation) ?? { ...policy, routes };
+ const what = preset ? `Set preset ${preset}.` : `Routed ${task} to ${route}.`;
+ return { text: renderPolicy(saved, await readUsage(deps), what) };
+}
+
+// ─── generate ───
+
+export const GENERATE_POLL_MS = 5000;
+export const DEFAULT_GENERATE_WAIT_SECONDS = 90;
+export const MAX_GENERATE_WAIT_SECONDS = 300;
+const RESULT_MARKER = "@@report-draft ";
+const SUMMARY_TAIL = 60;
+
+type Body = Record<string, unknown>;
+
+export type GenerateRequest =
+ | { kind: "start"; body: Body; via?: "api" | "local"; wait: boolean; waitSeconds: number }
+ | { kind: "resume"; job: string; article?: string; iteration?: number; waitSeconds: number };
+
+function waitSecondsOf(v: unknown): number | null {
+ if (v === undefined) return DEFAULT_GENERATE_WAIT_SECONDS;
+ if (typeof v !== "number" || !Number.isFinite(v) || v < 0) return null;
+ return Math.min(MAX_GENERATE_WAIT_SECONDS, Math.round(v));
+}
+
+// The arguments, checked as far as the tool can say without asking; the
+// editor judges the rest (controller/reportDraft.ts parseReportDraftBody).
+export function validateGenerateArgs(args: Record<string, unknown>): { ok: true; request: GenerateRequest } | { ok: false; error: string } {
+ const bad = (error: string) => ({ ok: false as const, error: `generate: ${error}` });
+ const waitSeconds = waitSecondsOf(args.wait_seconds);
+ if (waitSeconds === null) return bad("wait_seconds is a number of seconds, 0 or more");
+ const intOf = (k: string): number | undefined | null => {
+ const v = args[k];
+ if (v === undefined) return undefined;
+ return typeof v === "number" && Number.isInteger(v) && v >= 1 ? v : null;
+ };
+ const job = trimmed(args.job);
+ if (job) {
+ if (!JOB_RE.test(job)) return bad(`"${job}" is not a job id`);
+ const article = trimmed(args.article);
+ if (article && !ARTICLE_RE.test(article)) return bad(`"${article}" is not an article id`);
+ const iteration = intOf("iteration");
+ if (iteration === null) return bad("iteration is an iteration number (1, 2, …)");
+ return {
+ ok: true,
+ request: { kind: "resume", job, ...(article ? { article } : {}), ...(iteration ? { iteration } : {}), waitSeconds },
+ };
+ }
+ const task = trimmed(args.task);
+ if (!GENERATE_TASKS.includes(task)) return bad(`task is one of ${GENERATE_TASKS.join(", ")}`);
+ const article = trimmed(args.article);
+ if (!ARTICLE_RE.test(article)) return bad("article is an article id (a lowercase slug: a-z, 0-9, -)");
+ const body: Body = { task, article };
+ for (const k of ["iteration", "copyOf"] as const) {
+ const n = intOf(k);
+ if (n === null) return bad(`${k} is an iteration number (1, 2, …)`);
+ if (n !== undefined) body[k] = n;
+ }
+ for (const k of ["model", "feedback", "question", "from", "to"] as const) {
+ if (args[k] === undefined) continue;
+ const v = trimmed(args[k]);
+ if (!v) return bad(`${k} is text`);
+ body[k] = v;
+ }
+ for (const k of ["channels", "cards"] as const) {
+ if (args[k] === undefined) continue;
+ const v = args[k];
+ if (!Array.isArray(v) || v.length === 0 || v.some((x) => typeof x !== "string" || !x.trim())) {
+ return bad(`${k} is a non-empty list of names`);
+ }
+ body[k] = v.map((x: string) => x.trim());
+ }
+ if (args.maxUsd !== undefined) {
+ if (typeof args.maxUsd !== "number" || !(args.maxUsd > 0)) return bad("maxUsd is a positive number of dollars");
+ body.maxUsd = args.maxUsd;
+ }
+ if (args.force !== undefined) {
+ if (typeof args.force !== "boolean") return bad("force is true or false");
+ body.force = args.force;
+ }
+ if (args.autonomy !== undefined) {
+ const a = trimmed(args.autonomy);
+ if (!(AUTONOMIES as readonly string[]).includes(a)) return bad(`autonomy is one of ${AUTONOMIES.join(", ")}`);
+ if (task !== "research") return bad("autonomy is a research run's");
+ body.autonomy = a;
+ }
+ let via: "api" | "local" | undefined;
+ if (args.via !== undefined) {
+ const v = trimmed(args.via);
+ if (v !== "api" && v !== "local") return bad('via is "api" or "local" (a task routed to code is this session\'s)');
+ if (body.model) return bad("give model or via, not both");
+ via = v;
+ }
+ if (args.wait !== undefined && typeof args.wait !== "boolean") return bad("wait is true or false");
+ return { ok: true, request: { kind: "start", body, ...(via ? { via } : {}), wait: args.wait === true, waitSeconds } };
+}
+
+type JobView = { id: string; status: string; kind?: string; detail?: string; queue?: { key: string; position: number; queued: number } };
+type Followed =
+ | { kind: "ended"; job: JobView; tail: string[] }
+ | { kind: "waiting"; job: JobView; waited: number; last?: string }
+ | { kind: "error"; text: string };
+
+const ENDED = new Set(["done", "failed", "cancelled"]);
+
+async function jobOnce(deps: GenerationDeps, id: string, tail: number): Promise<{ job: JobView; tail: string[] } | { error: string }> {
+ const a = await editorGet(deps, `/api/ops/job/${encodeURIComponent(id)}?tail=${tail}`);
+ if (a.kind === "refused" && a.status === 404) return { error: `generate: the editor knows no job ${id}` };
+ if (a.kind !== "ok") return { error: `${describeEditorFailure("generate", a)} (job ${id} keeps running on the editor; resume with job: "${id}")` };
+ const job = a.body.job as JobView | undefined;
+ if (!job || typeof job.status !== "string") return { error: "generate: the editor's answer carried no job" };
+ return { job, tail: Array.isArray(a.body.tail) ? (a.body.tail as unknown[]).map(String) : [] };
+}
+
+// Poll the job politely (every GENERATE_POLL_MS) until it ends or the wait
+// runs out. A wait that runs out is not a failure: the job keeps running.
+export async function followGeneration(
+ deps: GenerationDeps,
+ id: string,
+ waitSeconds: number,
+ onPoll?: (p: PollProgress) => void | Promise<void>,
+): Promise<Followed> {
+ const started = deps.now();
+ const deadline = started + waitSeconds * 1000;
+ const waited = () => Math.round((deps.now() - started) / 1000);
+ let polls = 0;
+ for (;;) {
+ const r = await jobOnce(deps, id, 1);
+ if ("error" in r) return { kind: "error", text: r.error };
+ if (ENDED.has(r.job.status)) {
+ const full = await jobOnce(deps, id, SUMMARY_TAIL);
+ return "error" in full ? { kind: "ended", job: r.job, tail: r.tail } : { kind: "ended", job: full.job, tail: full.tail };
+ }
+ const last = r.tail[r.tail.length - 1];
+ if (deps.now() >= deadline) return { kind: "waiting", job: r.job, waited: waited(), ...(last ? { last } : {}) };
+ polls++;
+ if (onPoll) {
+ try {
+ await onPoll({ jobId: id, status: last ? `${r.job.status}: ${last.slice(0, 120)}` : r.job.status, polls, waited: waited() });
+ } catch {
+ /* a progress report is a courtesy */
+ }
+ }
+ await deps.sleep(GENERATE_POLL_MS);
+ }
+}
+
+type Marker = { article?: string; iteration?: number; task?: string; status?: string; summary?: string; usd?: number; minutes?: number };
+
+export function resultMarkerOf(tail: readonly string[]): Marker | null {
+ for (let i = tail.length - 1; i >= 0; i--) {
+ const at = tail[i].indexOf(RESULT_MARKER);
+ if (at < 0) continue;
+ try {
+ return JSON.parse(tail[i].slice(at + RESULT_MARKER.length)) as Marker;
+ } catch {
+ return null;
+ }
+ }
+ return null;
+}
+
+type IterationView = {
+ n: number;
+ kind: string;
+ model: string;
+ status: string;
+ error?: string;
+ parent: number | null;
+ copyOf: number | null;
+ usage: Record<string, { usd: number }>;
+ ops?: { applied: unknown[]; refused: unknown[] };
+ minutes?: number;
+ checks?: { name: string; ok: boolean; detail?: string }[];
+ steps?: { task: string; model?: string; status: string; cost?: number; jobId?: string; detail?: string }[];
+ projectDir?: string;
+ // A research run's (S11): its autonomy, phase and notes.
+ research?: { autonomy?: string; phase?: string; notes?: string[]; continuedBy?: number };
+};
+
+const MAX_LISTED = 12;
+
+// A refused op as the tasks store it: the op's own fields plus `why`.
+function opLine(o: unknown): string {
+ const r = (o ?? {}) as { op?: { op?: string } | string; why?: string };
+ const name = typeof r.op === "string" ? r.op : (r.op?.op ?? "op");
+ return `${name}${r.why ? `: ${r.why}` : ""}`;
+}
+
+export function renderIterationSummary(
+ o: { task: string; article: string; jobId: string; marker: Marker | null; iteration: IterationView; dir?: string; files?: Record<string, string | null> },
+): string {
+ const it = o.iteration;
+ const step = o.task === "narrate" ? [...(it.steps ?? [])].reverse().find((s) => s.task === "narrate" && s.jobId === o.jobId) : undefined;
+ const status = step?.status ?? o.marker?.status ?? it.status;
+ const lines: string[] = [];
+ lines.push(`generate: ${o.task} of ${o.article} i${it.n} — **${status}** on ${step?.model ?? it.model} (job ${o.jobId})`);
+ if (o.marker?.summary) lines.push(o.marker.summary);
+ if (it.error && status !== "done") lines.push(`error: ${it.error}`);
+ if (step?.detail) lines.push(`narration: ${step.detail}`);
+ const per = Object.entries(it.usage ?? {}).filter(([, u]) => u.usd > 0);
+ const total = step ? (step.cost ?? 0) : per.reduce((s, [, u]) => s + u.usd, 0);
+ const minutes = o.marker?.minutes ?? it.minutes;
+ lines.push(
+ `Cost: ${usd(total)}` +
+ (!step && per.length > 1 ? ` (${per.map(([m, u]) => `${m} ${usd(u.usd)}`).join(", ")})` : "") +
+ (typeof minutes === "number" ? ` · ${minutes.toFixed(1)} min` : ""),
+ );
+ if (it.ops) {
+ const refused = it.ops.refused ?? [];
+ lines.push(`Ops: ${it.ops.applied?.length ?? 0} applied, ${refused.length} refused`);
+ for (const r of refused.slice(0, MAX_LISTED)) lines.push(` - refused ${opLine(r)}`);
+ if (refused.length > MAX_LISTED) lines.push(` - … (+${refused.length - MAX_LISTED} more)`);
+ }
+ const checks = it.checks ?? [];
+ if (checks.length) {
+ const failing = checks.filter((c) => !c.ok);
+ lines.push(`Checks: ${checks.length - failing.length} passed, ${failing.length} not`);
+ for (const c of failing.slice(0, MAX_LISTED)) lines.push(` - ${c.name}${c.detail ? `: ${c.detail}` : ""}`);
+ if (failing.length > MAX_LISTED) lines.push(` - … (+${failing.length - MAX_LISTED} more)`);
+ }
+ if (o.dir) {
+ const present = Object.entries(o.files ?? {}).filter(([, p]) => p) as [string, string][];
+ lines.push(`Where (the editor's disk): ${o.dir}`);
+ for (const [name, p] of present) if (name !== "turns.jsonl") lines.push(` - ${name}: ${p}`);
+ }
+ if (it.projectDir) lines.push(`Video project: ${it.projectDir}`);
+ if (it.kind === "research") {
+ const r = it.research ?? {};
+ lines.push(`Research: phase ${r.phase ?? "?"}, autonomy ${r.autonomy ?? "?"}${r.continuedBy ? `, continued by i${r.continuedBy}` : ""}`);
+ for (const note of (r.notes ?? []).slice(0, MAX_LISTED)) lines.push(` - ${note}`);
+ if (status === "done") lines.push("", researchGuidance(o.article, it.n));
+ } else if (status === "done") lines.push("", reviewGuidance());
+ else if (status === "failed") lines.push("", "It failed: say why to the operator. Running it again, or here instead, is their call.");
+ return lines.join("\n");
+}
+
+// What to do with a finished research run: its proposals are the operator's to
+// approve, and a sweep over the widened scope continues it.
+function researchGuidance(article: string, n: number): string {
+ return (
+ `**Review its proposals** (\`proposals.json\` above): each acquisition's action, reason and evidence, ` +
+ `and which were enqueued, wait or were refused. Tell the operator which you would approve and why; the ` +
+ `yes or no is theirs (umtool's research queue, or \`pnpm ops research-approve\`) — not yours unless they ask. ` +
+ `When nothing waits (phase ready), continue it into a sweep over the widened scope: generate with task "sweep", ` +
+ `article "${article}", iteration: ${n}, wait: true — then review that iteration as any sweep.`
+ );
+}
+
+async function summarise(
+ deps: GenerationDeps,
+ f: Extract<Followed, { kind: "ended" }>,
+ hint: { task?: string; article?: string; iteration?: number },
+): Promise<ToolAnswer> {
+ const marker = resultMarkerOf(f.tail);
+ const article = marker?.article ?? hint.article;
+ const n = marker?.iteration ?? hint.iteration;
+ const task = marker?.task ?? hint.task ?? "report-draft";
+ const logTail = f.tail.filter((l) => !l.includes(RESULT_MARKER)).slice(-8);
+ if (!article || !n) {
+ return {
+ text:
+ `generate: job ${f.job.id} ended **${f.job.status}**${f.job.detail ? ` (${f.job.detail})` : ""}; its log names no iteration ` +
+ `(pass article and iteration to read it).` +
+ (logTail.length ? `\n\nlast log lines:\n\`\`\`\n${logTail.join("\n")}\n\`\`\`` : ""),
+ isError: f.job.status !== "done",
+ };
+ }
+ const a = await editorGet(deps, `/api/ops/iterations?article=${encodeURIComponent(article)}&n=${n}`);
+ if (a.kind !== "ok") {
+ return {
+ text: `generate: job ${f.job.id} ended ${f.job.status}; ${article} i${n} could not be read: ${describeEditorFailure("generate", a)}`,
+ isError: true,
+ };
+ }
+ const iteration = a.body.iteration as IterationView;
+ const text = renderIterationSummary({
+ task,
+ article,
+ jobId: f.job.id,
+ marker,
+ iteration,
+ ...(typeof a.body.dir === "string" ? { dir: a.body.dir } : {}),
+ ...(a.body.files && typeof a.body.files === "object" ? { files: a.body.files as Record<string, string | null> } : {}),
+ });
+ const failed = f.job.status !== "done";
+ return {
+ text: failed && logTail.length ? `${text}\n\nlast log lines:\n\`\`\`\n${logTail.join("\n")}\n\`\`\`` : text,
+ isError: failed,
+ };
+}
+
+function waitingText(f: Extract<Followed, { kind: "waiting" }>, hint: { article?: string; iteration?: number }): string {
+ const q = f.job.queue;
+ const where =
+ f.job.status === "queued" && q && q.position > 0 ? ` (position ${q.position} of ${q.queued} on ${q.key})` : "";
+ const resume = [`job: "${f.job.id}"`, hint.article ? `article: "${hint.article}"` : "", hint.iteration ? `iteration: ${hint.iteration}` : ""]
+ .filter(Boolean)
+ .join(", ");
+ return (
+ `Still ${f.job.status}${where} after ${f.waited}s.` +
+ (f.last ? ` Last log line: ${f.last}` : "") +
+ `\nCall generate again with ${resume} to keep waiting — never start the same task again. ` +
+ `A sweep takes minutes; nothing is lost while you wait.`
+ );
+}
+
+export async function generateTool(
+ args: Record<string, unknown>,
+ deps: GenerationDeps,
+ onPoll?: (p: PollProgress) => void | Promise<void>,
+): Promise<ToolAnswer> {
+ const v = validateGenerateArgs(args);
+ if (!v.ok) return { text: v.error, isError: true };
+ const req = v.request;
+
+ if (req.kind === "resume") {
+ const f = await followGeneration(deps, req.job, req.waitSeconds, onPoll);
+ if (f.kind === "error") return { text: f.text, isError: true };
+ if (f.kind === "waiting") return { text: `generate: job ${req.job}. ${waitingText(f, req)}` };
+ return summarise(deps, f, req);
+ }
+
+ const body = { ...req.body };
+ const task = String(body.task);
+ // Who runs it: the asked model, the asked route's model, else the policy's
+ // route — and a task routed to code is this session's, not the editor's.
+ if (!body.model) {
+ const read = await readPolicy(deps);
+ if (!read.ok) {
+ return {
+ text: read.answer ? describeEditorFailure("generate", read.answer) : "generate: the editor's answer carried no generation block",
+ isError: true,
+ };
+ }
+ const p = read.policy;
+ if (req.via) body.model = p.models[req.via];
+ else if (p.routes[task] === "code") {
+ const continuing = task === "sweep" && typeof body.iteration === "number";
+ return {
+ text: continuing
+ ? `generate: a sweep continuing research run i${String(body.iteration)} is routed to Claude Code (preset ${p.preset}) — ` +
+ `sweep its widened channels here (sweep_plan), or, when the operator asks, pass via: "api" or "local" to run it on the editor.`
+ : `generate: ${task} is routed to Claude Code (preset ${p.preset}) — do it in this session ` +
+ `(sweep_plan for a sweep). Pass via: "api" or "local" only when the operator asks to run it elsewhere.`,
+ isError: true,
+ };
+ }
+ }
+ const a = await editorPost(deps, "/api/ops/report-draft", body);
+ if (a.kind !== "ok") return { text: describeEditorFailure("generate", a), isError: true };
+ const jobId = typeof a.body.jobId === "string" ? a.body.jobId : "";
+ const n = typeof a.body.iteration === "number" ? a.body.iteration : undefined;
+ if (!jobId) return { text: `generate: the editor accepted it and started no job (${JSON.stringify(a.body)})`, isError: true };
+ const article = String(body.article);
+ const warnings = Array.isArray(a.body.warnings) ? (a.body.warnings as unknown[]).map(String) : [];
+ const head =
+ `generate ${task}: queued as job ${jobId}` +
+ (n ? `, ${task === "narrate" ? "narrating" : "making"} ${article} i${n}` : ` for ${article}`) +
+ (body.model ? ` on ${String(body.model)}` : " on the policy's model") +
+ "." +
+ warnings.map((w) => `\n⚠ ${w}`).join("");
+ if (!req.wait) {
+ return {
+ text:
+ `${head} It runs on the editor's draft queue. Follow it with generate (job: "${jobId}", article: "${article}"` +
+ `${n ? `, iteration: ${n}` : ""}, wait: true), or get_job.`,
+ };
+ }
+ const f = await followGeneration(deps, jobId, req.waitSeconds, onPoll);
+ if (f.kind === "error") return { text: `${head}\n${f.text}`, isError: true };
+ if (f.kind === "waiting") return { text: `${head}\n${waitingText(f, { article, ...(n ? { iteration: n } : {}) })}` };
+ return summarise(deps, f, { task, article, ...(n ? { iteration: n } : {}) });
+}
+
+// ─── The tool definitions (server.ts's TOOLS takes them in order) ───
+
+export const GENERATION_TOOLS = [
+ {
+ name: "generation_policy",
+ description:
+ "The operator's generation balance (settings.generation, read from the local editor): for each " +
+ "generation task — sweep (a new cited report), revise-report, revise-video, narrate, research — whether this " +
+ "Claude Code session does it (code), the Claude API does it (api) or the local model does it " +
+ "(local), on which model; the spend caps; and the day's Claude API spend against the daily cap. " +
+ "With preset (code, balanced, api, local) it routes every task at once; with task and route it " +
+ "routes one — ONLY when the operator asks to move the balance. Never shows the API key. Needs " +
+ "ARCHILYZER_EDITOR_URL and WORKER_TOKEN.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ preset: {
+ type: "string",
+ enum: [...GENERATION_PRESET_NAMES],
+ description: "Route every task by this preset: code (all here), balanced, api, local.",
+ },
+ task: { type: "string", description: "Route one task (with route): sweep, revise-report, revise-video, narrate, research." },
+ route: { type: "string", enum: [...GENERATION_ROUTES], description: "Where that task runs." },
+ },
+ additionalProperties: false,
+ },
+ },
+ {
+ name: "generate",
+ description:
+ "Run a generation task on the local editor as a report-draft job — on the Claude API or the " +
+ "local model, by the policy's route (generation_policy) unless model or via says otherwise — and, " +
+ "with wait: true, follow it and return the iteration it made: status, cost, the ops applied and " +
+ "refused, the checks, and where its files are on the editor's disk. task sweep makes a new " +
+ "iteration of article from question over channels; revise-report and revise-video make one from " +
+ "iteration and feedback; narrate voices a done iteration's cut; research finds what the corpus lacks " +
+ "and proposes acquisitions under its autonomy (propose, limits, auto), and task sweep with a research " +
+ "run's iteration continues it over the widened scope. copyOf runs an iteration again on another model. " +
+ "A task routed to code is refused: do it in this session. The wait is bounded (wait_seconds, " +
+ "default 90, at most 300) and polite (one poll every 5 s, a progress notification each); if the " +
+ "job is still running it answers its id — call again with job (and article, iteration) to keep " +
+ "waiting; the job keeps running either way. Then REVIEW what it made before anything is made " +
+ "current. Needs ARCHILYZER_EDITOR_URL and WORKER_TOKEN.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ task: { type: "string", enum: GENERATE_TASKS, description: "What to generate." },
+ article: { type: "string", description: "The article id (a lowercase slug). A sweep may name a new one." },
+ iteration: {
+ type: "integer",
+ minimum: 1,
+ description:
+ "revise-report / revise-video: the iteration revised; narrate: the iteration voiced; sweep: the research run it continues; with job: the iteration to summarise.",
+ },
+ question: { type: "string", description: "sweep / research: the question, in words." },
+ channels: { type: "array", items: { type: "string" }, description: "sweep / research: the channel slugs to read." },
+ from: { type: "string", description: "sweep: only videos on or after this date (YYYY-MM-DD)." },
+ to: { type: "string", description: "sweep: only videos on or before this date (YYYY-MM-DD)." },
+ feedback: { type: "string", description: "A revision's feedback: what to change, concretely." },
+ copyOf: { type: "integer", minimum: 1, description: "Run this iteration again (same kind and inputs) on model or via." },
+ model: { type: "string", description: "The model to run on (else the route's)." },
+ via: { type: "string", enum: ["api", "local"], description: "Run on this route's model instead of the policy's route — only when the operator asks." },
+ maxUsd: { type: "number", description: "An API job's cap in USD (else the task's default; never above the settings' max)." },
+ cards: { type: "array", items: { type: "string" }, description: "narrate: only these card ids." },
+ force: {
+ type: "boolean",
+ description: "narrate: redraft cards that already have narration; a sweep continuing a research run: continue while proposals still wait.",
+ },
+ autonomy: {
+ type: "string",
+ enum: [...AUTONOMIES],
+ description: "research: propose (every acquisition waits for the operator), limits (within the caps), auto (all through the editor) — default the settings'.",
+ },
+ wait: { type: "boolean", description: "Follow the job and return its iteration's summary (default false)." },
+ wait_seconds: {
+ type: "number",
+ description: `How long to follow it before answering with its job id (default ${DEFAULT_GENERATE_WAIT_SECONDS}, max ${MAX_GENERATE_WAIT_SECONDS}).`,
+ },
+ job: {
+ type: "string",
+ description: "Resume: the job id an earlier call returned. Every argument but article, iteration and wait_seconds is then ignored.",
+ },
+ },
+ additionalProperties: false,
+ },
+ },
+] as const;
diff --git a/mcp/src/instructions.test.ts b/mcp/src/instructions.test.ts
@@ -230,3 +230,91 @@ test("a sweep carries the narration hard rule: delivery, never the claims", () =
assert.match(text, /own sentence after a colon lead-in/);
assert.match(text, /serves Kokoro too/);
});
+
+// ─── Routing by the generation policy (release 27 S9) ───
+
+const POLICY = (sweep: "code" | "api" | "local", rest: "code" | "api" | "local" = "code") => ({
+ generation: {
+ preset: "custom",
+ routes: { sweep, "revise-report": rest, "revise-video": rest, narrate: rest },
+ models: { api: "claude-sonnet-5-5", local: "qwen3:8b" },
+ },
+});
+
+test("a sweep routed to code (or with no policy) is the plan it always was", () => {
+ const plain = sweep("coffee channels=chan-a");
+ assert.equal(sweep("coffee channels=chan-a", POLICY("code")), plain);
+ // via=code overrides a policy that routes it away.
+ assert.equal(
+ sweep("coffee channels=chan-a via=code", POLICY("api")),
+ sweep("coffee channels=chan-a via=code"),
+ );
+ assert.match(plain, /`enumerate_matches`/);
+});
+
+test("a sweep routed to api or local: the first step is generate, then the review", () => {
+ const text = sweep("coffee channels=chan-a article=coffee-claims", POLICY("api"));
+ assert.match(text, /— \*\*routed to the Claude API\*\* \(the generation policy, preset custom\)/);
+ const steps = text.split(/\n\n(?=\d+\. )/).slice(1);
+ assert.match(steps[0], /^1\. \*\*Generate — do not sweep it yourself\.\*\*/);
+ assert.match(
+ steps[0],
+ /Call `generate` with task: "sweep", article: "coffee-claims", question: "coffee", channels: \["chan-a"\], model: "claude-sonnet-5-5", wait: true/,
+ );
+ assert.match(steps[0], /never enqueue the same sweep twice/);
+ assert.match(steps[1], /^2\. \*\*Review it — you are the reviewer, not the author\.\*\*/);
+ assert.match(steps[1], /`get_transcript` \(source: "remote:https:\/\/site\.example", /);
+ assert.match(steps[1], /\*\*make it current\*\*.*Use this iteration.*\*\*revise\*\*/);
+ assert.match(steps[2], /^3\. \*\*Report back\.\*\*/);
+ // The sweep engine's steps are not in it.
+ assert.doesNotMatch(text, /enumerate_matches|DUMB EXTRACTOR/);
+
+ const local = sweep("coffee channels=chan-a", POLICY("local"));
+ assert.match(local, /routed to the local model/);
+ assert.match(local, /model: "qwen3:8b"/);
+ assert.match(local, /article: "<a new article id/);
+ // via=local with no policy at all still routes, by route name.
+ const via = sweep("coffee channels=chan-a via=local");
+ assert.match(via, /routed to the local model\*\* \(via=local\)/);
+ assert.match(via, /channels: \["chan-a"\], via: "local", wait: true/);
+});
+
+test("a routed sweep still stops on an unknown scope, and asks for one not given", () => {
+ const halted = sweep("coffee channels=ghost", { ...POLICY("api"), unknownChannels: ["ghost"] });
+ assert.match(halted, /1\. \*\*Fix the scope first\.\*\*/);
+ assert.doesNotMatch(halted, /`generate`/);
+ const open = sweep("coffee", POLICY("api"));
+ assert.match(open, /1\. \*\*Generate/);
+ assert.match(open, /channels: \[<the slugs I choose>\]/);
+ assert.match(open, /2\. \*\*Choose the scope first/);
+ const report = sweep("coffee channels=a report=./out.md", POLICY("api"));
+ assert.match(report, /The report lands in the iteration, not at `\.\/out\.md`/);
+});
+
+test("ask: answered here whatever the policy; the routed tasks are named", () => {
+ const plain = ask("what did they say about coffee");
+ assert.equal(ask("what did they say about coffee", POLICY("code")), plain);
+ const routed = ask("what did they say about coffee", POLICY("code", "local"));
+ assert.match(routed, /\*\*Generation goes by the policy\.\*\* This answer is yours to give here\./);
+ assert.match(routed, /revise-report → local \(qwen3:8b\), revise-video → local \(qwen3:8b\), narrate → local \(qwen3:8b\) \(preset custom\)/);
+ assert.doesNotMatch(routed, /sweep → /);
+ assert.match(routed, /call `generate` \(wait: true\) and review/);
+});
+
+test("every tool a routed plan names exists", () => {
+ const known = new Set(TOOLS.map((t) => t.name));
+ const texts = [
+ sweep("coffee channels=chan-a", POLICY("api")),
+ sweep("https://site.example/?q=a follow this", POLICY("local")),
+ ask("what about coffee", POLICY("api", "api")),
+ ];
+ const NOT_TOOLS = new Set(["dry_run", "moment_base", "date_from", "date_to", "media_type", "link_style", "content_types", "max_pages"]);
+ for (const text of texts) {
+ for (const m of text.matchAll(/`([a-z][a-z0-9]*(?:_[a-z0-9]+)*)`/g)) {
+ const name = m[1];
+ if (!name.includes("_") && name !== "generate") continue;
+ if (NOT_TOOLS.has(name)) continue;
+ assert.ok(known.has(name), `a routed plan names a nonexistent tool: ${name}`);
+ }
+ }
+});
diff --git a/mcp/src/instructions.ts b/mcp/src/instructions.ts
@@ -34,6 +34,19 @@ export type PlanContext = {
availableGroups?: { id: string; name: string; channels: number }[];
// Extra notes to surface (e.g. a decoded link's plan).
notes?: string[];
+ // The generation policy (settings.generation), read from the editor at plan
+ // time (release 27 S9). Absent when there is no editor to ask: the plan is
+ // then this session's, as it always was.
+ generation?: PlanGeneration;
+};
+
+export type GenerationRoute = "code" | "api" | "local";
+
+// What a plan needs of the policy: who does each task, and on what model.
+export type PlanGeneration = {
+ preset: string;
+ routes: Record<string, GenerationRoute>;
+ models: { api: string; local: string };
};
function quoted(xs: string[]): string {
@@ -205,16 +218,173 @@ function archiveStep(): string {
`by the day they were recorded). The operator's notes on articles and ` +
`video projects: \`notes\` (list, read; reply — after editing the note's ` +
`source and regenerating — writes the reply in umtool as the agent's). ` +
- `Settings, storage and deletes are not reachable from here — name the ` +
+ `Settings (but for the generation routes \`generation_policy\` sets when ` +
+ `I ask), storage and deletes are not reachable from here — name the ` +
`\`pnpm ops\` command instead.`
);
}
+// ─── Routing by the generation policy (release 27 S9; D8) ───
+//
+// settings.generation routes each generation task to `code` (this session),
+// `api` (the Claude API) or `local` (the local model). A sweep routed to api or
+// local is NOT run here: the plan's first step calls `generate` (the editor's
+// report-draft job), waits, and the rest is a REVIEW of what it made. Routed to
+// code — or with no policy to read — the plan is the one it always was. A
+// request's `via=` overrides the policy for that one plan.
+
+export const ROUTE_WORDS: Record<Exclude<GenerationRoute, "code">, string> = {
+ api: "the Claude API",
+ local: "the local model",
+};
+
+// Where a task goes for this plan, and why.
+export function routeFor(
+ task: string,
+ req: Pick<PromptRequest, "via">,
+ ctx: Pick<PlanContext, "generation">,
+): { route: GenerationRoute; model?: string; by: string } {
+ if (req.via) {
+ const model = req.via === "code" ? undefined : ctx.generation?.models[req.via];
+ return { route: req.via, ...(model ? { model } : {}), by: `via=${req.via}` };
+ }
+ const g = ctx.generation;
+ const route = g?.routes[task];
+ if (!g || !route || route === "code") return { route: "code", by: g ? `preset ${g.preset}` : "no policy" };
+ return { route, model: g.models[route], by: `the generation policy, preset ${g.preset}` };
+}
+
+// The review of a generated iteration — the step Claude Code owns when the
+// work itself was routed away. Shared by the routed plan and `generate`'s
+// answer, so the two say the same thing.
+export function reviewGuidance(corpus?: string): string {
+ const src = corpus ? `source: "${corpus}", ` : "";
+ return (
+ `**Review it — you are the reviewer, not the author.** When \`generate\` ` +
+ `reports the iteration done: (1) read the iteration's \`sweep.md\` end to ` +
+ `end (the path \`generate\` names; \`report.json\` is its converted form; ` +
+ `a video revision names its project instead). (2) Spot-check the quotes: ` +
+ `for at least five findings — every one when there are fewer, and always ` +
+ `the ones the conclusions rest on — call \`get_transcript\` (${src}the ` +
+ `cited video, timestamps on) around the cited second, and check the quote ` +
+ `is verbatim, the speaker is the one the claim names, and the claim says ` +
+ `no more than the words do. The strict check proved each generated quote is in the ` +
+ `transcript within ±90 s; nothing has checked attribution or reading. (3) ` +
+ `Read its checks and the ops it refused (\`generate\` lists them). (4) Tell ` +
+ `me in a few lines what is good and what is not, and recommend ONE of: ` +
+ `**make it current** — I do that in umtool (the article's Iterations tab, ` +
+ `"Use this iteration"), you do not unless I ask; or **revise** — call ` +
+ `\`generate\` with task "revise-report" (or "revise-video"), the article, ` +
+ `iteration: <n>, concrete feedback (which finding, what to change) and ` +
+ `wait: true, then review that iteration the same way. Never edit an ` +
+ `iteration's files by hand.`
+ );
+}
+
+// The generate call a routed sweep makes, with its scope settled.
+function generateSweepStep(req: PromptRequest, r: { route: GenerationRoute; model?: string; by: string }): string {
+ const article = req.article
+ ? `article: "${req.article}"`
+ : `article: "<a new article id: a short lowercase slug you choose from the subject — a-z, 0-9, ->"`;
+ const question = req.query
+ ? `question: "${req.query}${req.directive ? ` — extract ${req.directive}` : ""}"`
+ : `question: "<the subject in words — decode the share link with \`open_link\` (dry_run: true) first>"`;
+ const channels =
+ req.channels.length > 0
+ ? `channels: [${quoted(req.channels)}]`
+ : req.groups.length > 0
+ ? `channels: [<the channel slugs of group(s) ${quoted(req.groups)}, from \`list_channels\`>]`
+ : `channels: [<the slugs I choose>]`;
+ const model = r.model ? `, model: "${r.model}"` : req.via && req.via !== "code" ? `, via: "${req.via}"` : "";
+ return (
+ `**Generate — do not sweep it yourself.** This sweep is routed to ` +
+ `${r.route === "code" ? "Claude Code" : ROUTE_WORDS[r.route]}${r.model ? ` (${r.model})` : ""} by ${r.by}. ` +
+ `Call \`generate\` with task: "sweep", ${article}, ${question}, ${channels}${model}, ` +
+ `wait: true (add from/to, YYYY-MM-DD, when I named a period). The editor runs ` +
+ `it as a report-draft job on its own corpus build and caps; the article's ` +
+ `iteration is what it makes, never its published report. If the answer ` +
+ `says it is still running, call \`generate\` again with the job, article ` +
+ `and iteration it names and wait: true — never enqueue the same sweep ` +
+ `twice. If it is refused (the daily cap, no editor, no build holding the ` +
+ `channels), tell me why and stop: running it here instead is my call ` +
+ `(\`/sweep … via=code\`).` +
+ (req.reportPath
+ ? ` The report lands in the iteration, not at \`${req.reportPath}\`; copy it there only if I ask.`
+ : "")
+ );
+}
+
+function buildRoutedSweepInstructions(
+ req: PromptRequest,
+ ctx: PlanContext,
+ r: { route: GenerationRoute; model?: string; by: string },
+): string {
+ const subject = req.query ? `"${req.query}"` : req.link ? "the share link's search" : "the subject below";
+ const scope = scopeSteps(req, ctx);
+ // A scope that did not resolve still stops everything; a scope not yet
+ // chosen is asked for inside the generate step's own words.
+ const steps: string[] = scope.halt
+ ? [...scope.steps]
+ : [
+ generateSweepStep(req, r),
+ ...scope.steps,
+ reviewGuidance(ctx.corpus),
+ `**Report back.** Say which iteration it made, what it cost, how many ` +
+ `findings you checked and what you found, and your recommendation. ` +
+ `Keep every citation you quote clickable — \`[title @ mm:ss](url)\`.`,
+ ];
+ const numbered = steps.map((s, i) => `${i + 1}. ${s}`).join("\n\n");
+ const scopeNote = scopeProse(req);
+ const head =
+ `A **corpus sweep** for ${subject}` +
+ (scopeNote ? `, scoped to ${scopeNote}` : "") +
+ ` — **routed to ${r.route === "code" ? "Claude Code" : ROUTE_WORDS[r.route]}** (${r.by}). ` +
+ `You do not run this sweep: the editor does, as a report-draft job, and ` +
+ `your work is to start it, wait for it, and REVIEW what it made.\n\n` +
+ `**Corpus: \`${ctx.corpus}\`.** Pass \`source: "${ctx.corpus}"\` on every ` +
+ `read you make while reviewing.`;
+ const notes =
+ ctx.notes && ctx.notes.length > 0
+ ? `\n\nContext already resolved for you:\n${ctx.notes.map((n) => `- ${n}`).join("\n")}`
+ : "";
+ return renderWarnings(req.warnings) + `${head}${notes}\n\nFollow these steps:\n\n${numbered}`;
+}
+
+// The ask variant's one addition: a question is answered here whatever the
+// policy says (the policy routes generation tasks, and an answer in the
+// conversation is not one), but the tasks it does route are named, so a
+// follow-up ("make that a report") goes the right way.
+function routedTasksStep(req: PromptRequest, ctx: PlanContext): string | null {
+ const g = ctx.generation;
+ const away = g
+ ? Object.entries(g.routes).filter(([t]) => routeFor(t, req, ctx).route !== "code")
+ : req.via && req.via !== "code"
+ ? [["sweep", req.via] as const]
+ : [];
+ if (away.length === 0) return null;
+ const list = away
+ .map(([t]) => {
+ const r = routeFor(t, req, ctx);
+ return `${t} → ${r.route}${r.model ? ` (${r.model})` : ""}`;
+ })
+ .join(", ");
+ return (
+ `**Generation goes by the policy.** This answer is yours to give here. ` +
+ `If I then ask for a report on it, a revision of an article or its video, ` +
+ `or narration, those are routed: ${list}${g ? ` (preset ${g.preset})` : ""}. ` +
+ `For a routed task call \`generate\` (wait: true) and review what it makes ` +
+ `— read its files, spot-check its quotes with \`get_transcript\` — instead ` +
+ `of doing the work yourself; a task routed to code is yours (\`/sweep\` for a report).`
+ );
+}
+
// The full sweep instructions.
export function buildSweepInstructions(
req: PromptRequest,
ctx: PlanContext,
): string {
+ const routed = routeFor("sweep", req, ctx);
+ if (routed.route !== "code") return buildRoutedSweepInstructions(req, ctx, routed);
const reportPath = req.reportPath ?? DEFAULT_REPORT_PATH;
const directive = req.directive ?? DEFAULT_DIRECTIVE;
const subject = req.query
@@ -420,6 +590,9 @@ export function buildAskInstructions(
steps.push(clipStep(ctx));
steps.push(archiveStep());
+
+ const routedTasks = routedTasksStep(req, ctx);
+ if (routedTasks) steps.push(routedTasks);
}
const numbered = steps.map((s, i) => `${i + 1}. ${s}`).join("\n\n");
diff --git a/mcp/src/promptRequest.test.ts b/mcp/src/promptRequest.test.ts
@@ -325,3 +325,18 @@ test("a genuinely bad value is refused even from a form client", () => {
["report_path"],
);
});
+
+test("via= and article= (release 27 S9): routed plans", () => {
+ const r = parsePromptRequest("coffee channels=a via=API article=coffee-claims");
+ assert.equal(r.via, "api");
+ assert.equal(r.article, "coffee-claims");
+ assert.equal(r.query, "coffee");
+ assert.deepEqual(r.warnings, []);
+ assert.equal(parsePromptRequest("coffee route=local").via, "local");
+ const bad = parsePromptRequest("coffee via=cloud article=Not_An_Id");
+ assert.equal(bad.via, undefined);
+ assert.equal(bad.article, undefined);
+ assert.equal(bad.warnings.length, 2);
+ assert.match(bad.warnings[0], /via "cloud" is not code, api or local/);
+ assert.match(bad.warnings[1], /article "Not_An_Id" is not an article id/);
+});
diff --git a/mcp/src/promptRequest.ts b/mcp/src/promptRequest.ts
@@ -37,6 +37,12 @@ export type PromptRequest = {
source?: string;
contentTypes?: ("video" | "post")[];
regex: boolean;
+ // Who does the work, overriding the generation policy for this one plan
+ // (release 27 S9): `code` (this session), `api` or `local` (the editor's
+ // report-draft job, through the MCP's generate).
+ via?: "code" | "api" | "local";
+ // The article a routed sweep becomes an iteration of.
+ article?: string;
warnings: string[];
};
@@ -57,6 +63,8 @@ const KEYS: Record<string, string[]> = {
source: ["corpus"],
content_types: ["content_type", "types", "type"],
regex: ["re"],
+ via: ["route"],
+ article: ["article_id"],
};
const CANONICAL = new Map<string, string>();
@@ -341,6 +349,17 @@ export function parsePromptRequest(input: string): PromptRequest {
if (t) req.contentTypes = t;
}
+ if (seen.has("via")) {
+ const v = seen.get("via")!.trim().toLowerCase();
+ if (v === "code" || v === "api" || v === "local") req.via = v;
+ else warnings.push(`via "${seen.get("via")}" is not code, api or local — the generation policy decides.`);
+ }
+ if (seen.has("article")) {
+ const a = seen.get("article")!.trim();
+ if (/^[a-z0-9][a-z0-9-]{0,63}$/.test(a)) req.article = a;
+ else warnings.push(`article "${a}" is not an article id (a lowercase slug: a-z, 0-9, -) — ignored.`);
+ }
+
if (!req.link && req.query === "") {
warnings.push(
"no query and no link — say what to sweep for, or paste a share link.",
diff --git a/mcp/src/protocol.test.ts b/mcp/src/protocol.test.ts
@@ -49,6 +49,8 @@ const EXPECTED_TOOLS = [
"enqueue",
"channel_coverage",
"notes",
+ "generation_policy",
+ "generate",
"list_sources",
"resolve_source",
"open_link",
diff --git a/mcp/src/server.ts b/mcp/src/server.ts
@@ -97,6 +97,12 @@ import {
notesTool,
type ToolAnswer,
} from "./archivalTools";
+import {
+ GENERATION_TOOLS,
+ generateTool,
+ generationPolicyTool,
+ planGeneration,
+} from "./generation";
import { extractVideoId } from "yt-dlp-transcript-common/lib/videoId";
import {
decodeShareLink,
@@ -895,6 +901,8 @@ export const TOOLS: Tool[] = [
},
// Archival writes through the editor (release 19 A9): archivalTools.ts.
...(ARCHIVAL_TOOLS as unknown as Tool[]),
+ // The Claude Code balance (release 27 S9): generation.ts.
+ ...(GENERATION_TOOLS as unknown as Tool[]),
{
name: "list_sources",
description:
@@ -1042,10 +1050,14 @@ export const TOOLS: Tool[] = [
"share link — into the step-by-step plan for a corpus sweep, with the " +
"scope, corpus handle and batch count already resolved. Call this when " +
"the user asks to sweep, survey, or systematically go through the " +
- "archive. It only RETURNS instructions: it reads nothing, writes " +
- "nothing, and starts nothing. Following the plan it returns is a long " +
- "job that writes a report file with your own Write/Edit tools, so run " +
- "it when that is what was asked for, and show the plan's ⚠ warnings.",
+ "archive. It only RETURNS instructions: it writes nothing and starts " +
+ "nothing (it reads the corpus's channel list and, when an editor is " +
+ "configured, the generation policy). Following the plan it returns is " +
+ "a long job that writes a report file with your own Write/Edit tools, " +
+ "so run it when that is what was asked for, and show the plan's ⚠ " +
+ "warnings. When the policy routes sweeps to the Claude API or the " +
+ "local model, the plan says instead to start it with generate and " +
+ "review what it makes.",
inputSchema: {
type: "object",
properties: {
@@ -1057,7 +1069,10 @@ export const TOOLS: Tool[] = [
"what to sweep for, in the user's own words, punctuation intact. " +
"Recognised settings may be appended as key=value — channels=, " +
"groups=, batch_size=, parse_model=, report=, directive=, " +
- "source=, content_types=, regex= (quote a multi-word value). " +
+ "source=, content_types=, regex=, via= (code, api or local: " +
+ "overrides the generation policy for this plan), article= (the " +
+ "article a routed sweep becomes an iteration of) — quote a " +
+ "multi-word value. " +
"Anything else stays part of the question.",
},
},
@@ -1073,7 +1088,8 @@ export const TOOLS: Tool[] = [
"to run, against which corpus handle, and how to cite the answer. Use " +
"it for a question to be answered in conversation (sweep_plan is for a " +
"systematic pass that writes a report). It only RETURNS instructions: " +
- "it reads nothing and writes nothing.",
+ "it writes nothing (when an editor is configured it reads the " +
+ "generation policy, and names the tasks it routes away).",
inputSchema: {
type: "object",
properties: {
@@ -1301,6 +1317,16 @@ export function createServer(
return fromAnswer(await channelCoverageTool(args, fetchClipDeps));
case "notes":
return fromAnswer(await notesTool(args, fetchClipDeps));
+ case "generation_policy":
+ return fromAnswer(await generationPolicyTool(args, fetchClipDeps));
+ case "generate":
+ return fromAnswer(
+ await generateTool(
+ args,
+ fetchClipDeps,
+ progressNotifier(ctx.mcpReq._meta?.progressToken, ctx.mcpReq.notify),
+ ),
+ );
case "list_sources":
return handleListSources(registry, resolved);
case "resolve_source":
@@ -1312,9 +1338,9 @@ export function createServer(
case "open_link":
return handleOpenLink(registry, resolved, args);
case "sweep_plan":
- return handlePlan("sweep", registry, resolved, args);
+ return handlePlan("sweep", registry, resolved, args, fetchClipDeps);
case "ask_plan":
- return handlePlan("ask", registry, resolved, args);
+ return handlePlan("ask", registry, resolved, args, fetchClipDeps);
default:
return errorText(`unknown tool: ${name}`);
}
@@ -3234,6 +3260,7 @@ async function handlePlan(
registry: SourceRegistry,
callerCorpus: ResolvedSource,
args: Record<string, unknown>,
+ deps: FetchClipDeps,
): Promise<ToolResult> {
const raw = typeof args.request === "string" ? args.request : "";
if (raw.trim() === "") {
@@ -3259,6 +3286,11 @@ async function handlePlan(
}
const ctx = await buildPlanContext(corpus, req);
+ // Who does the work (release 27 S9): the generation policy, asked of the
+ // editor at plan time. No editor: the plan is this session's, as before.
+ const routing = await planGeneration(deps);
+ if (routing.generation) ctx.generation = routing.generation;
+ if (routing.note) ctx.notes = [...(ctx.notes ?? []), routing.note];
return text(
kind === "sweep"
? buildSweepInstructions(req, ctx)
diff --git a/plans/release-27.md b/plans/release-27.md
@@ -549,6 +549,46 @@ Gates:
- After the merge, at `afbd921e`: `article-new` + `article-iterations` 7 passed, 40.2 s; `article-compare` + `articles` 5 passed, 11.4 s. At `dc5a1c5d`: `article-new` 3 passed, 30.0 s.
Found: none outside the lane.
+### S9, as shipped (2026-10-13, lane F, `r27/gen-balance`)
+
+The Claude Code balance (D8), on `r27/gen-balance` from `r27/integration` `5962c543`, `b3f14445` (S11's backend) merged in.
+
+| Commit | What |
+| --- | --- |
+| `39a0b852` | editor reads `GET /api/ops/generation-usage[?day=]` and `GET /api/ops/iterations?article=[&n=]`; `pnpm ops get generation-usage` / `get iterations`; COMMANDS.md; `_generation.test.ts` |
+| `55fdbd11` | `mcp/src/generation.ts` (`generation_policy`, `generate`, `planGeneration`); `instructions.ts` routing (`routeFor`, `reviewGuidance`, the routed sweep plan, the ask's routed-tasks step); `via=` / `article=` in a plan request; the pinned tool list |
+| `945312e6` | `common/bin/gen.ts` and its four `archilyzer gen` rows; COMMANDS.md |
+| `7eb937b0` | `.claude/commands/gen.md`; mcp/README.md; WORKER_TOKEN / ARCHILYZER_EDITOR_URL docs (ENVIRONMENT.md) |
+| `6268f4d0` | after S11: `generate`'s `autonomy`, the continuation's refusal, a research iteration's summary; `gen run --autonomy` |
+| (this commit) | this record; the CHANGELOG bullets |
+
+- **`generation_policy`** reads `GET /api/ops/settings?key=generation` and `GET /api/ops/generation-usage`: each task's route and model, the caps, the day's API spend against the daily cap. With `preset`, or `task` + `route`, it writes `POST /api/ops/settings {patch: {generation: {routes}}}` — the whole routes object, since the writer merges one level. It renders no other field: no key-file path, no projects root.
+ - **Ruled here:** the release 19 rule keeps settings out of the MCP; the generation routes are its one exception (D8), only when the operator asks.
+- **`generate`** posts `report-draft` with the tool's own checks first (task, article, numbers, lists, `autonomy` only for research, `via` or `model`).
+ - The model is `model`, else `via`'s route's, else the editor's choice by the route.
+ - A task routed to `code` is refused before anything is enqueued. A sweep with an `iteration` (continuing a research run) says so in its own words.
+ - `wait: true` polls `GET /api/ops/job/<id>` every 5 s (a progress notification each, carrying the last log line) up to `wait_seconds` (90, at most 300). It then reads the `@@report-draft` line and `GET /api/ops/iterations?article=&n=`.
+ - The answer: status, cost per model, minutes, ops applied and refused (each refusal's why), the failing checks, the files on the editor's disk, and the review to do. A research iteration gets its phase, notes and proposals, the operator's approval and the continuation instead.
+ - A wait that runs out answers the job, article and iteration to resume with. Nothing is re-enqueued.
+- **The plans.** `sweep_plan` / `ask_plan` read the policy at plan time (`planGeneration`). With no editor configured there is no policy, and the plan is unchanged. An editor that fails adds a note, and the plan is this session's.
+ - A sweep routed to `api` or `local`: step 1 is `generate`, step 2 the review (read `sweep.md`, spot-check at least five quotes with `get_transcript`, read checks and refused ops, recommend making it current or a revision), step 3 report back. An unknown scope still halts first. A scope not given is asked for after the generate step, which names the channels as `<the slugs I choose>`.
+ - Routed to `code`, the plan is byte-identical to the unrouted one (tested), and `via=code` makes it so whatever the policy.
+ - **Ruled here:** an ask is answered in the conversation whatever the policy (the policy routes generation tasks, and an answer is not one). Its plan gains one last step naming the routed tasks, so a follow-up goes the right way. With every task routed to code, it is unchanged.
+ - **Ruled here:** making an iteration current stays the operator's (umtool's Iterations tab). The review recommends; it does not make current.
+- **`archilyzer gen policy|preset|set|run`.**
+ - Through the editor's ops API when it answers, with `pnpm ops`'s env.
+ - When nothing listens (connection refused), settings.json through `writeSettings` and the ledger off disk. An editor that is there but silent, or refuses the token, is an error, and the file is never written beside it.
+ - `run` asks the policy and exits 3 with nothing run when the task is routed to code. Otherwise it runs `pnpm ops report-draft` as a child (`--wait` follows it the same way).
+- **`.claude/commands/gen.md`** is over MCP tools only. The operator's user-level `/gen` is untouched; S10's docs retire it.
+
+Gates:
+- tsc clean (all packages).
+- mcp 342/342 (19 new: `generation.test.ts` 13; instructions 5, promptRequest 1; the pinned list gains `generation_policy`, `generate` after `notes`).
+- common 3991/3991 (7 new, `bin/gen.test.ts`); editor unit 285/285 (3 new, `_generation.test.ts`); `test:scripts` 852 pass + 3 skipped (1 new).
+- `docs env|files|cli --check`, `settings example --check`: clean.
+- Editor build (heavy slot, 5 GB cap): clean in 49 s; `/api/ops/generation-usage` and `/api/ops/iterations` built. No e2e: the two routes are read-only and covered by `_generation.test.ts` (their door, refusals and answers).
+
+Not done here: AGENTS.md's section on `.claude/commands/{ask,sweep}.md` does not name `gen.md` yet (S10's docs).
## Rollout
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -195,6 +195,11 @@ const GETTERS = {
if (jobs.slug) q.set("slug", jobs.slug);
return `/api/ops/transcript?${q.toString()}`;
},
+ // Generation (release 27 S9): the day's Claude API spend against the daily
+ // cap (default today, UTC), and an article's iterations with which is current.
+ "generation-usage": (day) =>
+ day ? `/api/ops/generation-usage?day=${encodeURIComponent(day)}` : "/api/ops/generation-usage",
+ iterations: (article) => `/api/ops/iterations?article=${encodeURIComponent(article)}`,
};
// READS THAT ARE JOBS: the answer needs a request upstream, so the editor
@@ -224,6 +229,7 @@ const GET_ARG_OPTIONAL = new Set([
"workers",
"auto-queue",
"scheduler",
+ "generation-usage",
]);
// The flags each noun takes beyond the shared ones; any other is refused.
@@ -713,6 +719,7 @@ export function usage() {
" pnpm ops get remote-listing <slug> [--wait-timeout <seconds>]",
" pnpm ops get transcript <videoId> [--slug <slug>]",
" pnpm ops get coverage <slug>",
+ " pnpm ops get generation-usage [<YYYY-MM-DD>] | iterations <article>",
" pnpm ops list",
"",
`Actions: ${ACTIONS.join(", ")}`,
@@ -770,6 +777,12 @@ export function usage() {
" over 30 days with nothing held. Off disk; nothing written. (The MCP's",
" channel_coverage takes gap days, a date window and a video list.)",
"",
+ "get generation-usage [<day>] is the day's Claude API spend on generation",
+ " (the usage ledger's total for the UTC day, default today) and the daily",
+ " cap it is checked against: {day, usd, jobs, daily}.",
+ "get iterations <article> is an article's iterations (iteration.json each)",
+ " and which is current. (The MCP's generate reads one, with its files.)",
+ "",
"get transcript <videoId> [--slug <slug>] reads one video's cues off disk",
" with no index: a fresh cues.json, else what build-cues would write, else",
" the English VTT alone — {source, cuesJson, title?, ..., cues}. Nothing is",
diff --git a/scripts/archilyzer-ops.test.mjs b/scripts/archilyzer-ops.test.mjs
@@ -856,3 +856,13 @@ test("get coverage reads one channel's coverage", () => {
assert.match(usage(), /get coverage <slug> is what a channel holds by date/);
assert.match(usage(), /recordedDateTitlePattern/);
});
+
+test("get generation-usage and get iterations read the generation state (release 27 S9)", () => {
+ assert.equal(parseArgs(["get", "generation-usage"]).path, "/api/ops/generation-usage");
+ assert.equal(parseArgs(["get", "generation-usage", "2026-10-01"]).path, "/api/ops/generation-usage?day=2026-10-01");
+ const r = parseArgs(["get", "iterations", "demo-article"]);
+ assert.equal(r.method, "GET");
+ assert.equal(r.path, "/api/ops/iterations?article=demo-article");
+ assert.match(parseArgs(["get", "iterations"]).error, /needs an argument/);
+ assert.match(usage(), /get generation-usage \[<day>\] is the day's Claude API spend/);
+});