commit 576ef87799c1d2ac1603f7bf1231733db9423574
parent 0c7e0504d10f5d1a723dec15b4526d13836e2b45
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 13 Oct 2026 13:25:51 -0400
common: release 27 S9 — `archilyzer gen policy|preset|set|run`
The stopgap's gen over settings.generation: through the editor's ops API
(its one settings writer, the token pnpm ops reads) when it answers, else
settings.json through writeSettings with no editor listening; an editor that
is there and silent or refusing is an error, never a write beside it. `run`
enqueues `pnpm ops report-draft` (a child, so --wait follows it the same way)
on the route's model, and exits 3 with nothing run when the task is routed to
code; --via overrides once, --model names the model. COMMANDS.md regenerated.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
4 files changed, 599 insertions(+), 0 deletions(-)
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) |
+| `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] [--source <handle>\|--build <id>] [--wait]` | enqueue a report-draft job as `pnpm ops report-draft` does (--wait follows it); 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) |
diff --git a/common/bin/archilyzer.ts b/common/bin/archilyzer.ts
@@ -398,6 +398,52 @@ 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)",
+ 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] [--source <handle>|--build <id>] [--wait] enqueue a report-draft job as `pnpm ops report-draft` does (--wait follows it); 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",
+ 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,199 @@
+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" },
+ 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" });
+ 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" });
+ 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" });
+ 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" } } },
+ });
+
+ 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");
+});
diff --git a/common/bin/gen.ts b/common/bin/gen.ts
@@ -0,0 +1,350 @@
+// `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 (and research once the editor runs it)";
+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;
+ 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));
+}