commit bc858274c39d7aa6f0a7c25bb5ebe2d3b078d748
parent 7b13fcde91b6622fdf3ca9067e884c988e40d0c4
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 13 Oct 2026 12:20:33 -0400
common, editor, umtool: release 27 S6 — report-draft jobs, the GPU arbiter, settings.generation, caps and the usage ledger
- Job kind `report-draft` on `draft:api` / `draft:local` (by the model's
provider): `pnpm ops report-draft {task, article, iteration?, model?, …}`
creates the iteration queued, runs the S5 task in process with the job's
AbortSignal, and answers {ok, jobId, iteration}; `job cancel` ends it
cancelled. The corpus is the MCP's tools in process (the editor transpiles
the mcp package now) over a composed build — the newest holding the
channels, or `build` / `source`; links cite the build's site, else
`generation.citationOrigin`.
- controller/gpuArbiter.ts: one place for the 8 GB card. Digests keep yielding
to transcription; TTS waits for transcription and a running draft call; a
draft call waits for transcription and a running synthesis (each ollama
request of a draft:local job is gated and held). ttsFile's checks are the
arbiter's. ollama is unloaded when a draft:local job ends.
- settings.generation (routes and presets, models, caps, cacheTtl, the API key
FILE — a key-looking value refused, never stored — anthropicBaseUrl,
ollamaUrl, projectsRoot, web, citationOrigin); SETTINGS.md regenerated.
- Caps: per job by task, never above caps.max; a daily API cap read from the
usage ledger (GENERATION_USAGE_FILE, <repo>/.generation/usage.jsonl), a
row per model per finished API job; a job past it is refused at the ask and
at its turn, naming the day's total. A non-Anthropic base URL never gets the
environment's key.
- umtool's chain reads settings.generation.projectsRoot.
- e2e report-draft.spec.ts; editor unit _reportDraft.test.ts.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
32 files changed, 1699 insertions(+), 38 deletions(-)
diff --git a/.gitignore b/.gitignore
@@ -178,6 +178,10 @@ yarn-error.log*
# <sha256>.wav + .json per distinct synthesis. Rebuildable; never committed.
/.tts/
+# Generation usage ledger (release 27): a line per finished API generation job,
+# read for the daily spend cap. Editor state; never committed.
+/.generation/
+
# Diarization runtime: the uv-managed python 3.13 venv + the sherpa-onnx models.
# Machine-specific (~148 MB) and rebuildable from .diarize/README.md, which IS
# tracked. sherpa-onnx ships wheels only to cp313 and this box's system python is
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -135,6 +135,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `archive-search` | archive-search searches archive.org (its advanced-search syntax) and answers the items: {"query", "limit"?: 50 (at most 500)} -> {found, items: \[{identifier, title?}\]}, in identifier order. One request through the editor's archive.org client, paced and backed off as an import is. Read only; import-archive-org with "query" imports what a search finds. | `pnpm ops archive-search --json '{"query":"title:(kitchen) AND mediatype:movies","limit":20}'` |
| `archive-item` | archive-item answers one archive.org item's files from its metadata: {"item"} -> {item: {identifier, url, title?, date?, mediatype?, creator?, collections, restricted, mediaFiles, mediaBytes, files: \[{name, format?, source?, size?, seconds?, media, restricted, original?}\]}}. media marks the originals an import takes (one record each); restricted, what archive.org will not hand out. Read only; nothing is downloaded. | `pnpm ops archive-item --json '{"item":"example-item"}'` |
| `import-post` | import-post imports ONE post by its URL into a posts channel of its platform: {"slug", "url"} — an X status (x.com/<handle>/status/<id>) or a Bluesky post (bsky.app/profile/<handle>/post/<id>, or its at:// URI). Read through the channel's own fetcher (gallery-dl for X, with the channel's login; the public AppView for Bluesky) as an import-post job on the platform's queue. Refused, before any job: a URL that is not a post, a channel that is not a posts channel of that platform or whose fetcher cannot read one post, a post the URL names as another account's, the platform held or cooling down. A post already archived is not read again; one the platform says is another account's is not written. The log ends with @@import-post {ok, slug, url, id, written, already?, post?, error?}. | `pnpm ops import-post --json '{"slug":"demo-x","url":"https://x.com/example/status/1700000000000000001"}' --wait` |
+| `report-draft` | report-draft runs a generation over an article's iteration as a report-draft job: {"task": "sweep" \| "revise-report" \| "revise-video" \| "narrate", "article", ...} -> {jobId, iteration}. A sweep takes "question" and "channels" (and "from"/"to"): a new iteration; a revision takes "iteration" (the one it revises) and "feedback": a new iteration; a narration takes "iteration" (a done one; "cards"?, "force"?) and is a step on it. "copyOf" N runs iteration N again on "model". "model" defaults to settings.generation's route for the task (one routed to code needs a model named). A Claude model runs on draft:api, capped at "maxUsd" (default by task, never above caps.max), and is refused when the day's API total has reached caps.daily; a local model runs on draft:local, through the GPU arbiter, and is unloaded when it ends. The corpus is "source" (a handle), "build" (a composed build), or the newest build holding the channels. `job cancel <id>` stops it. The log ends with @@report-draft {article, iteration, task, status, summary, usd, minutes}; --wait prints it. | `pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","question":"What does she say about the shop?","channels":["demo-channel"]}' --wait`<br>`pnpm ops report-draft --json '{"task":"revise-report","article":"demo-article","iteration":1,"feedback":"Drop the second finding."}'` |
### Usage, flags and environment
diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md
@@ -34,6 +34,7 @@ The one override surface for where things live and which binary runs. Every one
| `PARAKEET_CLI` | `parakeet-cli` on PATH | The parakeet.cpp binary the wrapper drives (the wrapper reads it too). | common/lib/paths.ts (getPaths) |
| `PARAKEET_MODEL` | none | parakeet.cpp's `.gguf`, when a worker names none (the wrapper reads it too). | common/lib/paths.ts (getPaths) |
| `DIARIZE_BIN` | `<repo>/scripts/diarize.mjs` | The speaker-diarization wrapper. The e2e suite swaps in a fake here. | common/lib/paths.ts (getPaths) |
+| `GENERATION_USAGE_FILE` | `<repo>/.generation/usage.jsonl` | The generation usage ledger: a line per finished Claude API generation job, read for the day's spend cap (`settings.generation.caps.daily`). The e2e server points it at a scratch file. | common/lib/paths.ts (getPaths) |
| `TTS_BIN` | `<repo>/scripts/tts.mjs` | The text-to-speech wrapper (text in, 48 kHz WAV out) every engine runs behind. A test swaps in a fake here. | common/lib/paths.ts (getPaths) |
| `ESPEAK_NG_BIN` | `espeak-ng` on PATH | eSpeak NG, the zero-install text-to-speech engine (the wrapper reads it too). | common/lib/paths.ts (getPaths) |
| `RSYNC_BIN` | `rsync` on PATH | Mirrors the saved-video store to a backup destination. | common/lib/paths.ts (getPaths) |
diff --git a/SETTINGS.md b/SETTINGS.md
@@ -50,6 +50,7 @@ A copied example PINS every default it spells — including each lane's `autoQue
| [`publish`](#publish) | object — see below |
| [`seeder`](#seeder) | object — see below |
| [`tts`](#tts) | object — see below |
+| [`generation`](#generation) | object — see below |
## `adminTitle`
@@ -944,3 +945,93 @@ Default:
}
}
```
+
+## `generation`
+
+Report and video generation (release 27): where each task runs (`code` = Claude Code, `api` = the Claude API with a key, `local` = the local model), the models, the spend caps (a job's default, its max, the day's), the API key FILE (never the key), and where video projects live. A generation runs as a `report-draft` editor job (`pnpm ops report-draft`) on `draft:api` or `draft:local`. See GenerationSettings and common/lib/generationSettings.ts.
+
+#### `generation`
+
+| Key | Default | Description |
+|---|---|---|
+| `preset` | `"balanced"` | The balance knob: `code` (Claude Code does every task), `balanced` (sweeps in Claude Code, report revisions on the API, video revisions and narration on the local model), `api`, `local`. Named by `routes`: the preset whose routes they are, else `custom` — choosing a preset is writing its routes. |
+| `routes` | object — see below | Where each task runs: `code`, `api` or `local` (below). |
+| `models` | object — see below | The model each route runs (below). |
+| `caps` | object — see below | The spend caps in USD (below). |
+| `cacheTtl` | `"5m"` | The prompt cache's lifetime on the Claude API: `5m` (writes bill 1.25× input) or `1h` (2×, for long runs with pauses). |
+| `apiKeyFile` | `"~/.config/archilyzer/anthropic.env"` | The file holding the Claude API key (`ANTHROPIC_API_KEY=…`), mode 600 — refused when the group or others can read it. `~` is the editor's home. The KEY itself is never a setting: a value that looks like one is refused, never stored. `ANTHROPIC_API_KEY` in the editor's environment wins over the file. |
+| `anthropicBaseUrl` | `""` | Advanced: the Messages API's base URL. Blank = Anthropic's. Tests point it at a fake. |
+| `ollamaUrl` | `""` | The local model's server (ollama). Blank = the editor's `OLLAMA_URL` (the digest lane's server, default http://127.0.0.1:11434). |
+| `projectsRoot` | `""` | Where an iteration's video project and renders live: `<projectsRoot>/<article>/i<n>/`, off the corpus disk (D1). Blank = `~/reports/articles`. |
+| `web` | object — see below | The web an agent may read for context (below). Read-only and paced: one request at a time, 3 s apart. |
+| `citationOrigin` | `""` | The origin a generated report's moment links cite when its corpus build's site has no public URL (a private build). Blank = the project site. |
+
+#### `generation.routes`
+
+| Key | Default | Description |
+|---|---|---|
+| `sweep` | `"code"` | A new report from a question: `code` (/sweep in Claude Code), `api` (the agent on `models.api`) or `local` (the code-driven pipeline on `models.local`). |
+| `revise-report` | `"api"` | A report iteration from feedback, through checked ops. |
+| `revise-video` | `"local"` | A video-cut iteration from feedback, through checked ops. |
+| `narrate` | `"local"` | Card narration for an iteration's cut, under the narration rules and the grounding checks. |
+
+#### `generation.models`
+
+| Key | Default | Description |
+|---|---|---|
+| `api` | `"claude-sonnet-5-5"` | The Claude model the `api` route runs (Sonnet 5.5: no temperature, no forced tool choice, thinking between tools). |
+| `local` | `"qwen3:8b"` | The ollama model the `local` route runs. Prompts stay under 8k tokens and `num_ctx` under 12k on the 8 GB card. |
+| `extractor` | `"claude-haiku-4-5"` | The cheap model an API sweep's `extract_batch` runs — the plan's dumb extractor (Claude or a local model). |
+
+#### `generation.caps`
+
+| Key | Default | Description |
+|---|---|---|
+| `sweep` | `5` | A sweep job's cap when it names none. The agent wraps up at 85% and stops at the cap. |
+| `revision` | `2` | A report or video revision job's cap when it names none. |
+| `narration` | `1` | A narration job's cap when it names none. |
+| `daily` | `20` | The API spend a day (UTC) may reach: a job that would start past it is refused, naming the day's total. 0 = no daily cap. |
+| `max` | `10` | The most a job may ask for: a larger `maxUsd` is refused. |
+
+#### `generation.web`
+
+| Key | Default | Description |
+|---|---|---|
+| `provider` | `"duckduckgo"` | The search a local model's `web_search` reads: `duckduckgo` (its HTML page). Claude uses the API's own search. |
+| `searchUrl` | `""` | Advanced: the search endpoint. Blank = the provider's. Tests point it at a fake. |
+
+Default:
+
+```json
+{
+ "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
+ },
+ "cacheTtl": "5m",
+ "apiKeyFile": "~/.config/archilyzer/anthropic.env",
+ "anthropicBaseUrl": "",
+ "ollamaUrl": "",
+ "projectsRoot": "",
+ "web": {
+ "provider": "duckduckgo",
+ "searchUrl": ""
+ },
+ "citationOrigin": ""
+}
+```
diff --git a/common/controller/generationUsage.test.ts b/common/controller/generationUsage.test.ts
@@ -0,0 +1,28 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, rm } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { appendGenerationUsage, dailyCapRefusal, dayUsage, readGenerationUsage, utcDay } from "./generationUsage";
+
+test("the usage ledger: rows appended, the day's total read back, a torn line skipped; the daily refusal names the total", async () => {
+ const dir = await mkdtemp(path.join(os.tmpdir(), "gen-usage-"));
+ try {
+ const file = path.join(dir, "sub", "usage.jsonl");
+ assert.deepEqual(await dayUsage(file, "2026-10-13"), { day: "2026-10-13", usd: 0, jobs: 0 });
+ const row = { at: "2026-10-13T10:00:00Z", day: "2026-10-13", jobId: "j1", article: "a", iteration: 1, task: "sweep", model: "claude-sonnet-5-5", inputTokens: 1, outputTokens: 1, cacheReadTokens: 0, cacheWriteTokens: 0, usd: 3.25 };
+ await appendGenerationUsage(file, [row, { ...row, model: "claude-haiku-4-5", usd: 0.5 }]);
+ await appendGenerationUsage(file, [{ ...row, jobId: "j2", day: "2026-10-12", usd: 9 }]);
+ const { appendFile } = await import("node:fs/promises");
+ await appendFile(file, "{torn\n");
+ assert.equal((await readGenerationUsage(file)).length, 3);
+ const today = await dayUsage(file, "2026-10-13");
+ assert.deepEqual(today, { day: "2026-10-13", usd: 3.75, jobs: 1 });
+ assert.equal(dailyCapRefusal(today, 20), null);
+ assert.equal(dailyCapRefusal(today, 0), null, "0 = no daily cap");
+ assert.match(dailyCapRefusal(today, 3.75)!, /the day's Claude API spend is \$3\.75 \(2026-10-13, UTC\), at or past the \$3\.75 daily cap/);
+ assert.equal(utcDay(new Date("2026-10-13T23:59:59Z")), "2026-10-13");
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
diff --git a/common/controller/generationUsage.ts b/common/controller/generationUsage.ts
@@ -0,0 +1,69 @@
+// THE GENERATION USAGE LEDGER (release 27, S6; D6) — one JSON line per model
+// per finished Claude API generation job, appended to `paths.generationUsageFile`
+// (editor state, never inside the corpus). The daily cap reads the day's total
+// from it; a job shows its own rows' sum. The digest's metered lane, which
+// kept costs only in log lines, is the precedent this replaces with a file.
+//
+// The day is UTC. A line that does not parse is skipped, never fatal.
+
+import { appendFile, mkdir, readFile } from "node:fs/promises";
+import path from "node:path";
+
+export type GenerationUsageRow = {
+ at: string;
+ day: string;
+ jobId: string;
+ article: string;
+ iteration: number;
+ task: string;
+ model: string;
+ inputTokens: number;
+ outputTokens: number;
+ cacheReadTokens: number;
+ cacheWriteTokens: number;
+ usd: number;
+};
+
+export const utcDay = (d: Date = new Date()) => d.toISOString().slice(0, 10);
+
+export async function appendGenerationUsage(file: string, rows: readonly GenerationUsageRow[]): Promise<void> {
+ if (!rows.length) return;
+ await mkdir(path.dirname(file), { recursive: true });
+ await appendFile(file, rows.map((r) => `${JSON.stringify(r)}\n`).join(""));
+}
+
+export async function readGenerationUsage(file: string): Promise<GenerationUsageRow[]> {
+ let text: string;
+ try {
+ text = await readFile(file, "utf8");
+ } catch {
+ return [];
+ }
+ const out: GenerationUsageRow[] = [];
+ for (const line of text.split("\n")) {
+ if (!line.trim()) continue;
+ try {
+ const r = JSON.parse(line) as GenerationUsageRow;
+ if (r && typeof r.usd === "number" && typeof r.day === "string") out.push(r);
+ } catch {
+ // a torn line is skipped
+ }
+ }
+ return out;
+}
+
+// The day's API spend: its total and how many jobs it took.
+export async function dayUsage(file: string, day: string = utcDay()): Promise<{ day: string; usd: number; jobs: number }> {
+ const rows = (await readGenerationUsage(file)).filter((r) => r.day === day);
+ const usd = Math.round(rows.reduce((s, r) => s + r.usd, 0) * 10_000) / 10_000;
+ return { day, usd, jobs: new Set(rows.map((r) => r.jobId)).size };
+}
+
+// The refusal for a job that would start past the daily cap, or null.
+export function dailyCapRefusal(day: { day: string; usd: number }, daily: number): string | null {
+ if (!(daily > 0) || day.usd < daily) return null;
+ return (
+ `the day's Claude API spend is $${day.usd.toFixed(2)} (${day.day}, UTC), at or past the $${daily.toFixed(2)} ` +
+ "daily cap (settings.generation.caps.daily) — refused; it resets at midnight UTC"
+ );
+}
diff --git a/common/controller/gpuArbiter.test.ts b/common/controller/gpuArbiter.test.ts
@@ -0,0 +1,69 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { gpuBusyFor, gpuGatedFetch, gpuHolds, holdGpu, waitForGpu, withGpu } from "./gpuArbiter";
+
+const none = { tts: 0, "draft-local": 0 } as const;
+
+test("the rules: TTS waits for transcription and a draft call; a draft waits for transcription and a synthesis", () => {
+ const off = () => false;
+ const on = () => true;
+ assert.deepEqual(gpuBusyFor("tts", { transcriptionOnGpu: off, holds: none }), { busy: false, reason: null });
+ assert.equal(gpuBusyFor("tts", { transcriptionOnGpu: on, holds: none }).reason, "a transcription is running");
+ assert.equal(gpuBusyFor("tts", { transcriptionOnGpu: off, holds: { ...none, "draft-local": 1 } }).reason, "a local model is drafting");
+ assert.deepEqual(gpuBusyFor("draft-local", { transcriptionLane: off, holds: none }), { busy: false, reason: null });
+ assert.equal(gpuBusyFor("draft-local", { transcriptionLane: on, holds: none }).reason, "a transcription is running");
+ assert.equal(gpuBusyFor("draft-local", { transcriptionLane: off, holds: { ...none, tts: 1 } }).reason, "a synthesis is running");
+ // Neither waits for itself.
+ assert.equal(gpuBusyFor("tts", { transcriptionOnGpu: off, holds: { ...none, tts: 2 } }).busy, false);
+ assert.equal(gpuBusyFor("draft-local", { transcriptionLane: off, holds: { ...none, "draft-local": 1 } }).busy, false);
+});
+
+test("holds count, and a release is idempotent", () => {
+ const a = holdGpu("tts");
+ const b = holdGpu("tts");
+ assert.equal(gpuHolds().tts, 2);
+ a();
+ a();
+ assert.equal(gpuHolds().tts, 1);
+ b();
+ assert.equal(gpuHolds().tts, 0);
+});
+
+test("waitForGpu waits to start, logs why, and stops on a cancel", async () => {
+ let n = 0;
+ const lines: string[] = [];
+ const waited = await waitForGpu({ busy: () => ({ busy: n++ < 2, reason: "a synthesis is running" }), onLog: (l) => lines.push(l), pollMs: 1 });
+ assert.ok(waited >= 0);
+ assert.match(lines[0]!, /Waiting for the GPU: a synthesis is running/);
+ assert.match(lines[1]!, /The GPU is free/);
+ const ctrl = new AbortController();
+ ctrl.abort();
+ await assert.rejects(waitForGpu({ busy: () => true, onLog: () => {}, signal: ctrl.signal, pollMs: 1 }), /cancelled while waiting/);
+});
+
+test("a draft call holds the GPU while in flight — a synthesis sees it — and the unload is never held", async () => {
+ let seenDuring = -1;
+ const base = (async (url: string) => {
+ seenDuring = gpuHolds()["draft-local"];
+ assert.equal(gpuBusyFor("tts", { transcriptionOnGpu: () => false }).busy, url.endsWith("/api/chat"));
+ return new Response(JSON.stringify({ ok: true }), { status: 200, headers: { "content-type": "application/json" } });
+ }) as unknown as typeof fetch;
+ const f = gpuGatedFetch(base, { onLog: () => {}, busy: () => false });
+ const res = await f("http://127.0.0.1:1/api/chat", { method: "POST" });
+ assert.deepEqual(await res.json(), { ok: true });
+ assert.equal(seenDuring, 1);
+ assert.equal(gpuHolds()["draft-local"], 0, "released once the answer is in hand");
+ await f("http://127.0.0.1:1/api/generate", { method: "POST" });
+ assert.equal(seenDuring, 0, "the unload is not held");
+ // A draft call waits out a synthesis.
+ const release = holdGpu("tts");
+ let started = false;
+ const p = withGpu("draft-local", async () => {
+ started = true;
+ }, { onLog: () => {}, pollMs: 2, busy: () => gpuBusyFor("draft-local", { transcriptionLane: () => false }) });
+ await new Promise((r) => setTimeout(r, 15));
+ assert.equal(started, false);
+ release();
+ await p;
+ assert.equal(started, true);
+});
diff --git a/common/controller/gpuArbiter.ts b/common/controller/gpuArbiter.ts
@@ -0,0 +1,146 @@
+// THE GPU ARBITER — one place that says who may use the 8 GB card now
+// (release 27, S6). Four users share it: transcription (the worker pool's
+// local engines), text-to-speech with a GPU engine (Orpheus), local-model
+// drafting (`report-draft` on `draft:local`, ollama) and the local digest lane
+// (ollama too).
+//
+// The rules:
+// - a DIGEST yields to transcription — digestYield.ts's
+// transcriptionActivity(), unchanged (its CPU carve-out and gap signal);
+// - TTS waits for transcription on a GPU worker AND for a running draft call;
+// - a DRAFT call waits for transcription (the digest's signal) AND for a
+// running GPU synthesis.
+// Each is a YIELD at the start of one unit of work (a synthesis, one ollama
+// call), never an interruption: a call in flight finishes.
+//
+// "Running" is the in-process hold a user takes around its unit of work
+// (`holdGpu`), so the check is exact and needs no registry scan; the editor is
+// one process and every one of these runs in it. A draft's hold wraps each
+// ollama request (gpuGatedFetch), so a synthesis can slip in between two calls
+// of a long draft, and a draft waits out a synthesis between its calls.
+
+import { getWorkerPool } from "../jobs/workerPool";
+import { transcriptionActivity } from "./digestYield";
+
+export type GpuUser = "tts" | "draft-local";
+
+const holds: Record<GpuUser, number> = { tts: 0, "draft-local": 0 };
+
+// Take the GPU for one unit of work; the release is idempotent.
+export function holdGpu(user: GpuUser): () => void {
+ holds[user]++;
+ let released = false;
+ return () => {
+ if (released) return;
+ released = true;
+ holds[user] = Math.max(0, holds[user] - 1);
+ };
+}
+
+export function gpuHolds(): Readonly<Record<GpuUser, number>> {
+ return { ...holds };
+}
+
+// A transcription running on a local worker that is not explicitly on the CPU
+// (an unknown device may be the GPU: parakeet-cli's default can be).
+export function transcriptionOnGpu(): boolean {
+ try {
+ return getWorkerPool()
+ .summary()
+ .some((w) => w.busy && w.kind === "local" && (w.device ?? "").toLowerCase() !== "cpu");
+ } catch {
+ return false; // fail open: an unreadable pool must not wedge a lane
+ }
+}
+
+export type GpuVerdict = { busy: boolean; reason: string | null };
+
+// Whether `user` must wait now, and for whom. The signals are injectable for
+// the tests (and default to the live ones).
+export function gpuBusyFor(
+ user: GpuUser,
+ signals: { transcriptionOnGpu?: () => boolean; transcriptionLane?: () => boolean; holds?: Readonly<Record<GpuUser, number>> } = {},
+): GpuVerdict {
+ const h = signals.holds ?? holds;
+ if (user === "tts") {
+ if ((signals.transcriptionOnGpu ?? transcriptionOnGpu)()) return { busy: true, reason: "a transcription is running" };
+ if (h["draft-local"] > 0) return { busy: true, reason: "a local model is drafting" };
+ return { busy: false, reason: null };
+ }
+ const lane = signals.transcriptionLane ?? (() => {
+ try {
+ return transcriptionActivity().busy;
+ } catch {
+ return false;
+ }
+ });
+ if (lane()) return { busy: true, reason: "a transcription is running" };
+ if (h.tts > 0) return { busy: true, reason: "a synthesis is running" };
+ return { busy: false, reason: null };
+}
+
+// Wait until `busy()` is false — to START; a unit of work running is never
+// interrupted. Answers the milliseconds waited. Abortable.
+export async function waitForGpu(opts: {
+ busy: () => boolean | GpuVerdict;
+ onLog: (line: string) => void;
+ signal?: AbortSignal;
+ pollMs?: number;
+ what?: string;
+}): Promise<number> {
+ const t0 = Date.now();
+ const check = (): GpuVerdict => {
+ const v = opts.busy();
+ return typeof v === "boolean" ? { busy: v, reason: v ? "a transcription is running" : null } : v;
+ };
+ let v = check();
+ if (!v.busy) return 0;
+ opts.onLog(`Waiting for the GPU: ${v.reason ?? "it is in use"}…`);
+ while (v.busy) {
+ if (opts.signal?.aborted) throw new Error("cancelled while waiting for the GPU");
+ await new Promise((r) => setTimeout(r, opts.pollMs ?? 5000));
+ v = check();
+ }
+ const waited = Date.now() - t0;
+ opts.onLog(`The GPU is free (waited ${(waited / 1000).toFixed(1)}s)`);
+ return waited;
+}
+
+// Wait for the GPU and hold it as `user` around `work`.
+export async function withGpu<T>(
+ user: GpuUser,
+ work: () => Promise<T>,
+ opts: { onLog: (line: string) => void; signal?: AbortSignal; pollMs?: number; busy?: () => boolean | GpuVerdict },
+): Promise<T> {
+ await waitForGpu({ busy: opts.busy ?? (() => gpuBusyFor(user)), onLog: opts.onLog, signal: opts.signal, pollMs: opts.pollMs });
+ const release = holdGpu(user);
+ try {
+ return await work();
+ } finally {
+ release();
+ }
+}
+
+// A fetch for the ollama config of a `draft:local` job: every chat request
+// waits for the GPU and holds it as a draft while in flight. The unload call
+// (`/api/generate` with keep_alive 0) frees memory and is never held back.
+export function gpuGatedFetch(
+ base: typeof fetch,
+ opts: { onLog: (line: string) => void; signal?: AbortSignal; pollMs?: number; busy?: () => boolean | GpuVerdict },
+): typeof fetch {
+ return (async (input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => {
+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
+ if (!/\/api\/chat$/.test(url)) return base(input, init);
+ // The body is read inside the hold: ollama answers once it has generated,
+ // and the hold ends when the answer is in hand.
+ return withGpu(
+ "draft-local",
+ async () => {
+ const res = await base(input, init);
+ const body = await res.arrayBuffer();
+ return new Response(body, { status: res.status, statusText: res.statusText, headers: res.headers });
+ },
+ opts,
+ );
+ }) as typeof fetch;
+}
diff --git a/common/controller/reportDraft.ts b/common/controller/reportDraft.ts
@@ -0,0 +1,452 @@
+// `report-draft` — a generation over an article's iteration, as an editor job
+// (release 27, S6; D6). `pnpm ops report-draft` → POST /api/ops/report-draft →
+// here.
+//
+// task sweep | revise-report | revise-video | narrate
+// article the article id (an article in the making is fine for a sweep)
+// iteration a revision's parent; the iteration a narration voices; else none
+// model default: settings.generation.models[route] for the task's route
+// question / channels / from / to a sweep's
+// feedback a revision's
+// copyOf run iteration N again on another model (same kind and inputs)
+// maxUsd the job's cap (default by task; never above caps.max)
+// source / build the corpus (default: the newest build holding the channels)
+// cards / force a narration's
+//
+// The iteration is created `queued` before the job, and the job's id set on it;
+// the job runs the S5 task in process. Its queue is the model's provider's:
+// `draft:api` (network, never the GPU lane or the heavy slot) or `draft:local`
+// (every ollama call through the GPU arbiter; ollama unloaded when the job
+// ends). An API job is held to its cap and to the DAILY cap: a job that would
+// start past the day's total is refused, at the ask and again at its turn.
+// Every finished API job appends its usage rows to the ledger.
+//
+// The corpus tools come in from the caller (`deps.corpusTools`): they are the
+// MCP's, and common cannot import the mcp package.
+
+import os from "node:os";
+import path from "node:path";
+import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand";
+import { DRAFT_API_QUEUE, DRAFT_LOCAL_QUEUE } from "../lib/queueKeys";
+import type { Paths } from "../lib/paths";
+import { getSettings } from "../lib/settings";
+import { capFor, type GenerationSettings, type GenerationTask } from "../lib/generationSettings";
+import { PROJECT_URL } from "../lib/project";
+import { providerOf, unloadOllama, type LlmConfig } from "../lib/llm";
+import { webTools } from "../lib/web/tools";
+import {
+ copyIteration,
+ createIteration,
+ readIteration,
+ readIterationFile,
+ reportSourceOf,
+ updateIteration,
+ type Iteration,
+} from "../lib/report/iterations";
+import { diskPostChannelOf } from "../lib/report/convert-server";
+import { readAllPosts } from "../lib/posts-server";
+import { runTask, type TaskDeps, type TaskInput, type TaskResult, pickCorpusBuild, siteOriginOf } from "../lib/report/draft/tasks/index";
+import { corpusCuesOf } from "../lib/report/draft/tasks/corpusCues";
+import type { CorpusToolsLike } from "../lib/report/draft/tasks/types";
+import { verifyReportQuotes } from "../bin/reports-check";
+import { appendGenerationUsage, dailyCapRefusal, dayUsage, utcDay, type GenerationUsageRow } from "./generationUsage";
+import { gpuGatedFetch } from "./gpuArbiter";
+
+export const REPORT_DRAFT_JOB_KIND = "report-draft";
+export const REPORT_DRAFT_RESULT_MARKER = "@@report-draft ";
+
+export const REPORT_DRAFT_BODY_KEYS = [
+ "task",
+ "article",
+ "iteration",
+ "model",
+ "feedback",
+ "question",
+ "channels",
+ "from",
+ "to",
+ "copyOf",
+ "maxUsd",
+ "source",
+ "build",
+ "cards",
+ "force",
+] as const;
+
+export class ReportDraftInputError extends Error {}
+
+export type ReportDraftBody = {
+ task: GenerationTask;
+ article: string;
+ iteration?: number;
+ model?: string;
+ feedback?: string;
+ question?: string;
+ channels?: string[];
+ from?: string;
+ to?: string;
+ copyOf?: number;
+ maxUsd?: number;
+ source?: string;
+ build?: string;
+ cards?: string[];
+ force?: boolean;
+};
+
+const TASKS: readonly GenerationTask[] = ["sweep", "revise-report", "revise-video", "narrate"];
+const ymd = /^\d{4}-\d{2}-\d{2}$/;
+
+function fail(msg: string): never {
+ throw new ReportDraftInputError(msg);
+}
+
+// The body, judged without touching the disk.
+export function parseReportDraftBody(b: Record<string, unknown>): ReportDraftBody {
+ const task = b.task;
+ if (typeof task !== "string" || !TASKS.includes(task as GenerationTask)) fail(`"task" is one of ${TASKS.join(", ")}`);
+ const article = b.article;
+ if (typeof article !== "string" || !/^[a-z0-9][a-z0-9-]{0,63}$/.test(article)) fail('"article" is an article id (a lowercase slug)');
+ const int = (k: string) => {
+ const v = b[k];
+ if (v === undefined || v === null) return undefined;
+ if (typeof v !== "number" || !Number.isInteger(v) || v < 1) fail(`"${k}" is an iteration number (1, 2, …)`);
+ return v as number;
+ };
+ const text = (k: string) => {
+ const v = b[k];
+ if (v === undefined || v === null) return undefined;
+ if (typeof v !== "string" || !v.trim()) fail(`"${k}" is text`);
+ return (v as string).trim();
+ };
+ const list = (k: string) => {
+ const v = b[k];
+ if (v === undefined || v === null) return undefined;
+ const arr = typeof v === "string" ? v.split(",") : v;
+ if (!Array.isArray(arr) || !arr.every((x) => typeof x === "string" && x.trim())) fail(`"${k}" is a list of names`);
+ return (arr as string[]).map((x) => x.trim());
+ };
+ const out: ReportDraftBody = { task: task as GenerationTask, article: article as string };
+ const set = <K extends keyof ReportDraftBody>(k: K, v: ReportDraftBody[K] | undefined) => {
+ if (v !== undefined) out[k] = v;
+ };
+ set("iteration", int("iteration"));
+ set("copyOf", int("copyOf"));
+ set("model", text("model"));
+ set("feedback", text("feedback"));
+ set("question", text("question"));
+ set("channels", list("channels"));
+ set("cards", list("cards"));
+ set("source", text("source"));
+ set("build", text("build"));
+ for (const k of ["from", "to"] as const) {
+ const v = text(k);
+ if (v !== undefined && !ymd.test(v)) fail(`"${k}" is a YYYY-MM-DD date`);
+ set(k, v);
+ }
+ if (b.maxUsd !== undefined && b.maxUsd !== null) {
+ if (typeof b.maxUsd !== "number" || !(b.maxUsd > 0)) fail('"maxUsd" is a positive number of dollars');
+ out.maxUsd = b.maxUsd;
+ }
+ if (b.force !== undefined) {
+ if (typeof b.force !== "boolean") fail('"force" is true or false');
+ out.force = b.force;
+ }
+ if (out.source && !/^(local|remote|hub):\S+/.test(out.source)) fail('"source" is a corpus handle: local:<dir>, remote:<url> or hub:<url>');
+ if (out.source && out.build) fail('give "source" or "build", not both');
+ // What each task needs.
+ if (out.task === "sweep" && out.copyOf === undefined) {
+ if (!out.question) fail("a sweep needs its question");
+ if (!out.channels?.length) fail("a sweep needs its channels");
+ }
+ if ((out.task === "revise-report" || out.task === "revise-video") && out.copyOf === undefined) {
+ if (out.iteration === undefined) fail(`a ${out.task} names the iteration it revises ("iteration")`);
+ if (!out.feedback) fail(`a ${out.task} needs feedback: say what to change`);
+ }
+ if (out.task === "narrate" && out.iteration === undefined) fail('a narration names the iteration it voices ("iteration")');
+ if (out.task === "narrate" && out.copyOf !== undefined) fail("a narration is a step, not an iteration: it has no copy");
+ return out;
+}
+
+const KIND_OF: Record<GenerationTask, Iteration["kind"]> = {
+ sweep: "sweep",
+ "revise-report": "revise-report",
+ "revise-video": "revise-video",
+ narrate: "sweep", // (a step: no iteration of its own)
+};
+
+const CAP_OF: Record<GenerationTask, "sweep" | "revision" | "narration"> = {
+ sweep: "sweep",
+ "revise-report": "revision",
+ "revise-video": "revision",
+ narrate: "narration",
+};
+
+export function expandHome(p: string): string {
+ return p === "~" ? os.homedir() : p.startsWith("~/") ? path.join(os.homedir(), p.slice(2)) : p;
+}
+
+export function projectsRootOf(gen: GenerationSettings): string {
+ return gen.projectsRoot ? expandHome(gen.projectsRoot) : path.join(os.homedir(), "reports", "articles");
+}
+
+// The model a task runs on: the asked one, else the route's.
+export function modelFor(gen: GenerationSettings, task: GenerationTask, asked?: string): string {
+ if (asked) return asked;
+ const route = gen.routes[task];
+ if (route === "code") {
+ fail(`${task} is routed to Claude Code (settings.generation.routes) — name a model to run it here, or route it to api or local`);
+ }
+ return route === "api" ? gen.models.api : gen.models.local;
+}
+
+// The LLM config a job runs on. A base URL that is not Anthropic's is never
+// sent the environment's key: only the configured file's.
+export function llmConfigOf(gen: GenerationSettings, paths: Pick<Paths, "ollamaUrl">, local?: { onLog: (l: string) => void; signal?: AbortSignal }): LlmConfig {
+ return {
+ anthropic: {
+ apiKeyFile: gen.apiKeyFile,
+ cacheTtl: gen.cacheTtl,
+ ...(gen.anthropicBaseUrl ? { baseUrl: gen.anthropicBaseUrl, env: {} } : {}),
+ },
+ ollama: {
+ baseUrl: gen.ollamaUrl || paths.ollamaUrl,
+ ...(local ? { fetch: gpuGatedFetch(fetch, local) } : {}),
+ },
+ };
+}
+
+export type ReportDraftDeps = {
+ paths: Paths;
+ // The MCP's corpus tools over a source handle (mcp/src/callTool.ts).
+ corpusTools: (source: string) => Promise<CorpusToolsLike & { close(): Promise<void> }>;
+ settings?: () => { generation: GenerationSettings };
+ now?: () => Date;
+};
+
+// The channels a revision or narration reads: its report's citations'.
+async function channelsOfReport(article: string, n: number, paths: Paths): Promise<string[]> {
+ const from = await reportSourceOf(article, n, paths).catch(() => null);
+ const text = from === null ? null : await readIterationFile(article, from, "report.json", paths);
+ if (!text) return [];
+ const cites = (JSON.parse(text) as { citations?: Record<string, { channel?: string }> }).citations ?? {};
+ return [...new Set(Object.values(cites).map((c) => c.channel).filter((c): c is string => !!c))];
+}
+
+// The corpus and the origin the run cites on.
+export async function resolveCorpus(
+ body: Pick<ReportDraftBody, "source" | "build">,
+ channels: string[],
+ paths: Pick<Paths, "exportBuildsDir" | "sitesDir">,
+ gen: GenerationSettings,
+): Promise<{ source: string; origin: string; build?: string }> {
+ const fallback = gen.citationOrigin || PROJECT_URL;
+ if (body.source) return { source: body.source, origin: fallback };
+ const b = await pickCorpusBuild(channels, { exportBuildsDir: paths.exportBuildsDir, ...(body.build ? { want: body.build } : {}) });
+ return { source: `local:${b.dir}`, origin: (await siteOriginOf(b.build, paths.sitesDir)) ?? fallback, build: b.build };
+}
+
+export type ReportDraftEnqueued = { result: StreamActionResult; iteration: number };
+
+export async function enqueueReportDraft(raw: Record<string, unknown>, deps: ReportDraftDeps): Promise<ReportDraftEnqueued | { result: StreamActionResult & { ok: false } }> {
+ const paths = deps.paths;
+ const gen = (deps.settings ?? getSettings)().generation;
+ let body: ReportDraftBody;
+ try {
+ body = parseReportDraftBody(raw);
+ } catch (e) {
+ return { result: { ok: false, error: (e as Error).message } };
+ }
+ const refuse = (error: string) => ({ result: { ok: false as const, error } });
+ try {
+ // The model, and from it the lane; the copy's source tells a copy's kind.
+ const src = body.copyOf !== undefined ? await readIteration(body.article, body.copyOf, paths) : null;
+ if (body.copyOf !== undefined) {
+ if (!src) return refuse(`"${body.article}" has no iteration i${body.copyOf} to copy`);
+ if (src.kind !== KIND_OF[body.task]) return refuse(`i${body.copyOf} is a ${src.kind} iteration, not a ${body.task}`);
+ }
+ const model = modelFor(gen, body.task, body.model);
+ const provider = providerOf(model);
+ let maxUsd: number | undefined;
+ if (provider === "api") {
+ maxUsd = capFor(gen.caps, CAP_OF[body.task], body.maxUsd);
+ const refusal = dailyCapRefusal(await dayUsage(paths.generationUsageFile, utcDay(deps.now?.())), gen.caps.daily);
+ if (refusal) return refuse(refusal);
+ }
+ // The iteration: a new one (or a copy), queued; a narration's is the one named.
+ let n: number;
+ if (body.task === "narrate") {
+ const it = await readIteration(body.article, body.iteration!, paths);
+ if (!it) return refuse(`"${body.article}" has no iteration i${body.iteration}`);
+ if (it.status !== "done") return refuse(`"${body.article}" i${it.n} is ${it.status}: a narration runs over a done iteration`);
+ n = it.n;
+ } else if (src) {
+ n = (await copyIteration(body.article, src.n, { model }, paths)).n;
+ } else {
+ n = (
+ await createIteration(
+ body.article,
+ {
+ kind: KIND_OF[body.task],
+ model,
+ ...(body.task === "sweep"
+ ? { question: body.question, scope: { channels: body.channels!, ...(body.from ? { from: body.from } : {}), ...(body.to ? { to: body.to } : {}) } }
+ : { parent: body.iteration!, feedback: body.feedback }),
+ },
+ paths,
+ )
+ ).n;
+ }
+ const result = await runManagedFunction({
+ kind: REPORT_DRAFT_JOB_KIND,
+ queueKey: provider === "api" ? DRAFT_API_QUEUE : DRAFT_LOCAL_QUEUE,
+ paths,
+ fn: (onLog, signal, _progress, ctx) => runReportDraft({ body, model, maxUsd, n, jobId: ctx.jobId, onLog, signal }, deps),
+ });
+ if (!result.ok) {
+ if (body.task !== "narrate") await updateIteration(body.article, n, { status: "failed", error: result.error }, paths).catch(() => {});
+ return { result };
+ }
+ if (body.task !== "narrate") await updateIteration(body.article, n, { jobId: result.jobId }, paths).catch(() => {});
+ // A job cancelled (or refused) before it ran leaves its iteration queued: end it.
+ void result.done.then(async (d) => {
+ if (body.task === "narrate") return;
+ const it = await readIteration(body.article, n, paths).catch(() => null);
+ if (it?.status === "queued") {
+ await updateIteration(body.article, n, { status: d.status === "cancelled" ? "cancelled" : "failed", error: `the job ended ${d.status} before it ran` }, paths).catch(() => {});
+ }
+ });
+ return { result, iteration: n };
+ } catch (e) {
+ return refuse((e as Error).message);
+ }
+}
+
+async function runReportDraft(
+ o: { body: ReportDraftBody; model: string; maxUsd?: number; n: number; jobId: string; onLog: (l: string) => void; signal: AbortSignal },
+ deps: ReportDraftDeps,
+): Promise<void> {
+ const { body, model, n, onLog, signal } = o;
+ const paths = deps.paths;
+ const gen = (deps.settings ?? getSettings)().generation;
+ const provider = providerOf(model);
+ onLog(`${body.task} of ${body.article} i${n} on ${model} (${provider === "api" ? `the Claude API, cap $${o.maxUsd}` : "the local model"})`);
+ if (provider === "api") {
+ // Again at the job's turn: jobs ahead in the queue may have spent the day.
+ const refusal = dailyCapRefusal(await dayUsage(paths.generationUsageFile, utcDay(deps.now?.())), gen.caps.daily);
+ if (refusal) {
+ if (body.task !== "narrate") await updateIteration(body.article, n, { status: "failed", error: refusal }, paths).catch(() => {});
+ throw new Error(refusal);
+ }
+ }
+ const it = (await readIteration(body.article, n, paths))!;
+ const channels = body.task === "sweep" ? (it.scope?.channels ?? []) : await channelsOfReport(body.article, body.task === "narrate" ? n : (it.parent ?? n), paths);
+ let corpus: (CorpusToolsLike & { close(): Promise<void> }) | null = null;
+ let result: TaskResult | null = null;
+ try {
+ const where = await resolveCorpus(body, channels, paths, gen);
+ onLog(`corpus ${where.source}${where.build ? ` (build ${where.build})` : ""}; links on ${where.origin}`);
+ corpus = await deps.corpusTools(where.source);
+ const disk = paths.channelsDir;
+ const posts = new Map<string, Promise<Map<string, string>>>();
+ const postText = (ch: string, id: string) => {
+ let p = posts.get(ch);
+ if (!p) {
+ p = readAllPosts(path.join(disk, ch)).then((all) => new Map(all.map((x) => [x.id, x.text])), () => new Map());
+ posts.set(ch, p);
+ }
+ return p.then((m) => m.get(id) ?? null);
+ };
+ const taskDeps: TaskDeps = {
+ llm: llmConfigOf(gen, paths, provider === "local" ? { onLog, signal } : undefined),
+ corpus,
+ web: webTools({ ...(gen.web.searchUrl ? { searchUrl: gen.web.searchUrl } : {}) }),
+ cuesOf: corpusCuesOf(corpus),
+ postTextOf: postText,
+ postChannelOf: diskPostChannelOf(disk),
+ // The corpus on disk adds what the build cannot say: an en-orig track
+ // whose words differ. Only a drift counts; a record the disk does not
+ // hold is the build's to answer.
+ verifyReport: async (report) =>
+ (await verifyReportQuotes(report, { paths }).catch(() => []))
+ .filter((r) => r.status === "drift" || r.status === "en-orig-drift")
+ .map((r) => ({ citation: r.citation, status: r.status, ...(r.message ? { message: r.message } : {}) })),
+ paths,
+ log: onLog,
+ signal,
+ ...(deps.now ? { now: deps.now } : {}),
+ };
+ const projectsRoot = projectsRootOf(gen);
+ // A local run costs nothing: it has no dollar cap.
+ const cap = provider === "api" ? o.maxUsd! : Number.POSITIVE_INFINITY;
+ const extractor = gen.models.extractor;
+ let input: TaskInput;
+ switch (body.task) {
+ case "sweep":
+ input =
+ provider === "api"
+ ? { task: "sweep-agent", article: body.article, n, extractorModel: extractor, origin: where.origin, maxUsd: cap }
+ : { task: "sweep-pipeline", article: body.article, n, origin: where.origin };
+ break;
+ case "revise-report":
+ input = { task: "revise-report", article: body.article, n, origin: where.origin, maxUsd: cap };
+ break;
+ case "revise-video":
+ input = { task: "revise-video", article: body.article, n, origin: where.origin, maxUsd: cap, projectsRoot };
+ break;
+ case "narrate":
+ input = { task: "narrate", article: body.article, n, model, projectsRoot, ...(o.maxUsd ? { maxUsd: o.maxUsd } : {}), jobId: o.jobId, ...(body.cards ? { cards: body.cards } : {}), ...(body.force ? { force: true } : {}) };
+ break;
+ }
+ result = await runTask(input, taskDeps);
+ } catch (e) {
+ if (body.task !== "narrate") {
+ const cur = await readIteration(body.article, n, paths).catch(() => null);
+ if (cur && (cur.status === "queued" || cur.status === "running")) {
+ await updateIteration(body.article, n, { status: signal.aborted ? "cancelled" : "failed", error: (e as Error).message }, paths).catch(() => {});
+ }
+ }
+ throw e;
+ } finally {
+ await corpus?.close().catch(() => {});
+ if (provider === "local") {
+ // Free the card for transcription and TTS, however the job ended.
+ await unloadOllama({ baseUrl: gen.ollamaUrl || paths.ollamaUrl }, model).then(
+ () => onLog(`unloaded ${model} from ollama`),
+ (e) => onLog(`ollama unload failed: ${(e as Error).message}`),
+ );
+ }
+ if (provider === "api" && result) {
+ await recordUsage(body, n, model, o.jobId, paths, deps.now?.() ?? new Date()).catch((e) => onLog(`usage not recorded: ${(e as Error).message}`));
+ }
+ }
+ onLog(`${REPORT_DRAFT_RESULT_MARKER}${JSON.stringify({ article: body.article, iteration: n, task: body.task, status: result.status, summary: result.summary, usd: result.usd, minutes: result.minutes })}`);
+ if (result.status === "cancelled" || signal.aborted) throw new Error("cancelled");
+ if (result.status === "failed") throw new Error(result.summary);
+}
+
+// The job's spend, per model, from the iteration's usage (a narration: the
+// step's cost, on its model).
+async function recordUsage(body: ReportDraftBody, n: number, model: string, jobId: string, paths: Paths, now: Date) {
+ const it = await readIteration(body.article, n, paths);
+ if (!it) return;
+ const day = utcDay(now);
+ const base = { at: now.toISOString(), day, jobId, article: body.article, iteration: n, task: body.task };
+ let rows: GenerationUsageRow[];
+ if (body.task === "narrate") {
+ const step = [...it.steps].reverse().find((s) => s.task === "narrate" && s.jobId === jobId);
+ rows = step?.cost ? [{ ...base, model, inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, usd: step.cost }] : [];
+ } else {
+ rows = Object.entries(it.usage)
+ .filter(([m, u]) => providerOf(m) === "api" && (u.usd > 0 || (u.calls ?? 0) > 0))
+ .map(([m, u]) => ({
+ ...base,
+ model: m,
+ inputTokens: u.inputTokens,
+ outputTokens: u.outputTokens,
+ cacheReadTokens: u.cacheReadTokens ?? 0,
+ cacheWriteTokens: u.cacheWriteTokens ?? 0,
+ usd: Math.round(u.usd * 10_000) / 10_000,
+ }));
+ }
+ await appendGenerationUsage(paths.generationUsageFile, rows);
+}
diff --git a/common/controller/ttsFile.ts b/common/controller/ttsFile.ts
@@ -54,7 +54,7 @@ import {
resolveTtsHome,
type TtsSettings,
} from "../lib/ttsSettings";
-import { getWorkerPool } from "../jobs/workerPool";
+import { gpuBusyFor, holdGpu, transcriptionOnGpu, waitForGpu } from "./gpuArbiter";
import { getTtsServerHolder, type TtsServerHolder } from "./ttsServer";
import { TTS_QUEUE } from "../lib/queueKeys";
import { copyFileAtomic, writeJsonAtomic } from "../lib/jsonFile-server";
@@ -394,34 +394,9 @@ export type RunTtsOpts = {
gpuPollMs?: number;
};
-// A transcription running on a local worker that is not explicitly on the CPU
-// (an unknown device may be the GPU: parakeet-cli's default can be).
-export function transcriptionOnGpu(): boolean {
- return getWorkerPool()
- .summary()
- .some((w) => w.busy && w.kind === "local" && (w.device ?? "").toLowerCase() !== "cpu");
-}
-
-// A GPU engine waits while a transcription holds the GPU — the `tts` queue
-// yields to transcription. It only waits to START; a synthesis running is
-// never interrupted.
-export async function waitForGpu(opts: {
- busy: () => boolean;
- onLog: (line: string) => void;
- signal?: AbortSignal;
- pollMs?: number;
-}): Promise<number> {
- const t0 = Date.now();
- if (!opts.busy()) return 0;
- opts.onLog("Waiting for the GPU: a transcription is running…");
- while (opts.busy()) {
- if (opts.signal?.aborted) throw new Error("cancelled while waiting for the GPU");
- await new Promise((r) => setTimeout(r, opts.pollMs ?? 5000));
- }
- const waited = Date.now() - t0;
- opts.onLog(`The GPU is free (waited ${(waited / 1000).toFixed(1)}s)`);
- return waited;
-}
+// The GPU checks are the arbiter's (gpuArbiter.ts, release 27): TTS waits for
+// a transcription on a GPU worker AND for a running local-model draft call.
+export { transcriptionOnGpu, waitForGpu };
// Run the engine through the wrapper into the cache; write the sidecar after
// the WAV is in place, so a sidecar always means a complete file.
@@ -439,13 +414,16 @@ export async function runTtsSynthesis(opts: RunTtsOpts): Promise<TtsSidecar> {
);
let started = Date.now();
let server: { url: string; release: () => void } | null = null;
+ let releaseGpu: (() => void) | null = null;
try {
// A GPU engine waits while a transcription holds the GPU; a server engine
// takes its server (started for the batch behind the heavy slot, stopped
// once the `tts` queue has been idle) and hands its URL to the wrapper.
// The engine's time starts once both are in hand.
if (req.engine.device === "gpu") {
- await waitForGpu({ busy: opts.gpuBusy ?? transcriptionOnGpu, onLog, signal: opts.signal, pollMs: opts.gpuPollMs });
+ await waitForGpu({ busy: opts.gpuBusy ?? (() => gpuBusyFor("tts")), onLog, signal: opts.signal, pollMs: opts.gpuPollMs });
+ // Held while the engine runs: a draft call waits for it.
+ releaseGpu = holdGpu("tts");
}
if (req.engine.runtime === "server" && req.engine.serverCommand) {
const holder = opts.servers ?? getTtsServerHolder(paths.monorepoRoot);
@@ -530,6 +508,7 @@ export async function runTtsSynthesis(opts: RunTtsOpts): Promise<TtsSidecar> {
await writeJsonAtomic(target.json, sidecar, { indent: 2 });
return sidecar;
} finally {
+ releaseGpu?.();
server?.release();
await rm(textFile, { force: true }).catch(() => {});
}
diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts
@@ -929,6 +929,19 @@ const JOB_KINDS: Record<string, JobKindMeta> = {
// engine. Not an ingest kind: nothing the index reads changes. One engine
// run — cancelled, not drained; not replayable (the caller asks again, and
// the cache answers).
+ // A generation over an article's iteration (release 27 S6): a sweep, a
+ // report or video revision, or a narration step — `pnpm ops report-draft`,
+ // on `draft:api` or `draft:local` by the model's provider. It reads the
+ // corpus through the MCP's tools from a composed build, never a channel's
+ // data, so it declares neither guard. Not replayable: a new ask is a new
+ // iteration.
+ "report-draft": {
+ kind: "report-draft",
+ label: "Report draft",
+ drainable: false,
+ replayable: false,
+ queueKeyStrategy: "custom",
+ },
"tts-file": {
kind: "tts-file",
label: "Text to speech",
diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts
@@ -75,6 +75,7 @@ const DECLARED: EnvVarDecl[] = [
paths("PARAKEET_CLI", "`parakeet-cli` on PATH", "The parakeet.cpp binary the wrapper drives (the wrapper reads it too)."),
paths("PARAKEET_MODEL", "none", "parakeet.cpp's `.gguf`, when a worker names none (the wrapper reads it too)."),
paths("DIARIZE_BIN", "`<repo>/scripts/diarize.mjs`", "The speaker-diarization wrapper. The e2e suite swaps in a fake here."),
+ paths("GENERATION_USAGE_FILE", "`<repo>/.generation/usage.jsonl`", "The generation usage ledger: a line per finished Claude API generation job, read for the day's spend cap (`settings.generation.caps.daily`). The e2e server points it at a scratch file."),
paths("TTS_BIN", "`<repo>/scripts/tts.mjs`", "The text-to-speech wrapper (text in, 48 kHz WAV out) every engine runs behind. A test swaps in a fake here."),
paths("ESPEAK_NG_BIN", "`espeak-ng` on PATH", "eSpeak NG, the zero-install text-to-speech engine (the wrapper reads it too)."),
paths("RSYNC_BIN", "`rsync` on PATH", "Mirrors the saved-video store to a backup destination."),
diff --git a/common/lib/generationSettings.test.ts b/common/lib/generationSettings.test.ts
@@ -0,0 +1,52 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import {
+ DEFAULT_GENERATION_SETTINGS,
+ GENERATION_PRESETS,
+ capFor,
+ looksLikeApiKey,
+ presetOf,
+ sanitizeGeneration,
+} from "./generationSettings";
+
+test("generation settings: the defaults are the stopgap's balanced policy, Sonnet 5.5, qwen3:8b, Haiku, D6's caps", () => {
+ const d = sanitizeGeneration(undefined);
+ assert.deepEqual(d, DEFAULT_GENERATION_SETTINGS);
+ assert.equal(d.preset, "balanced");
+ assert.deepEqual(d.routes, GENERATION_PRESETS.balanced);
+ assert.deepEqual(d.caps, { sweep: 5, revision: 2, narration: 1, daily: 20, max: 10 });
+ assert.equal(sanitizeGeneration(d).preset, "balanced", "idempotent");
+});
+
+test("the routes are the truth: the preset is the one they match, else custom", () => {
+ assert.equal(sanitizeGeneration({ routes: GENERATION_PRESETS.api }).preset, "api");
+ assert.equal(sanitizeGeneration({ preset: "api" }).preset, "balanced", "a preset alone does not move the routes");
+ const custom = sanitizeGeneration({ routes: { ...GENERATION_PRESETS.balanced, narrate: "api" } });
+ assert.equal(custom.preset, "custom");
+ assert.equal(presetOf(custom.routes), "custom");
+ assert.equal(sanitizeGeneration({ routes: { sweep: "nope" } }).routes.sweep, "code");
+});
+
+test("the API key is never a setting: a value that looks like one is dropped for the default path", () => {
+ assert.equal(looksLikeApiKey("sk-ant-api03-abcdef"), true);
+ assert.equal(looksLikeApiKey("A".repeat(40)), true);
+ assert.equal(looksLikeApiKey("~/.config/archilyzer/anthropic.env"), false);
+ assert.equal(looksLikeApiKey("/etc/keys/anthropic.env"), false);
+ assert.equal(sanitizeGeneration({ apiKeyFile: "sk-ant-api03-xyz" }).apiKeyFile, DEFAULT_GENERATION_SETTINGS.apiKeyFile);
+ assert.equal(sanitizeGeneration({ apiKeyFile: "/srv/key.env" }).apiKeyFile, "/srv/key.env");
+});
+
+test("caps: a task's default, an asked one within max, a larger one refused; URLs and models checked", () => {
+ const g = sanitizeGeneration({ caps: { sweep: 50, max: 8, daily: -1 } });
+ assert.equal(g.caps.sweep, 8, "no default above max");
+ assert.equal(g.caps.daily, 20, "a negative daily is the default");
+ assert.equal(capFor(g.caps, "revision"), 2);
+ assert.equal(capFor(g.caps, "sweep", 3), 3);
+ assert.throws(() => capFor(g.caps, "sweep", 9), /over the settings' max of \$8/);
+ assert.throws(() => capFor(g.caps, "sweep", 0), /positive/);
+ const u = sanitizeGeneration({ anthropicBaseUrl: "http://127.0.0.1:9/", ollamaUrl: "not a url", models: { api: "bad model id!" } });
+ assert.equal(u.anthropicBaseUrl, "http://127.0.0.1:9");
+ assert.equal(u.ollamaUrl, "");
+ assert.equal(u.models.api, "claude-sonnet-5-5");
+ assert.equal(sanitizeGeneration({ cacheTtl: "1h" }).cacheTtl, "1h");
+});
diff --git a/common/lib/generationSettings.ts b/common/lib/generationSettings.ts
@@ -0,0 +1,177 @@
+// settings.generation — report and video generation (release 27, S6; D6).
+//
+// Pure: the type, its defaults, the sanitizer settingsSchema.ts runs it
+// through, the per-field docs SETTINGS.md renders, the routing presets (the
+// stopgap's gen.py), and the caps a `report-draft` job is held to. It replaces
+// the stopgap's ~/.config/archilyzer/generation.json; the API KEY itself is
+// never a setting — only the path of the mode-600 file that holds it (a value
+// that looks like a key is refused, and never stored).
+
+import type { FieldDocs } from "./fieldDocs";
+
+export const GENERATION_TASKS = ["sweep", "revise-report", "revise-video", "narrate"] as const;
+export type GenerationTask = (typeof GENERATION_TASKS)[number];
+
+export const GENERATION_ROUTES = ["code", "api", "local"] as const;
+export type GenerationRoute = (typeof GENERATION_ROUTES)[number];
+
+export const GENERATION_PRESETS = {
+ code: { sweep: "code", "revise-report": "code", "revise-video": "code", narrate: "code" },
+ balanced: { sweep: "code", "revise-report": "api", "revise-video": "local", narrate: "local" },
+ api: { sweep: "api", "revise-report": "api", "revise-video": "api", narrate: "api" },
+ local: { sweep: "local", "revise-report": "local", "revise-video": "local", narrate: "local" },
+} as const satisfies Record<string, Record<GenerationTask, GenerationRoute>>;
+export type GenerationPreset = keyof typeof GENERATION_PRESETS;
+export const GENERATION_PRESET_NAMES = Object.keys(GENERATION_PRESETS) as GenerationPreset[];
+
+export type GenerationRoutes = Record<GenerationTask, GenerationRoute>;
+export type GenerationModels = { api: string; local: string; extractor: string };
+// USD. A job's cap defaults by its task; `max` bounds any cap a job asks for;
+// `daily` refuses a job that would start past it.
+export type GenerationCaps = { sweep: number; revision: number; narration: number; daily: number; max: number };
+export type GenerationWeb = { provider: "duckduckgo"; searchUrl: string };
+
+export type GenerationSettings = {
+ preset: GenerationPreset | "custom";
+ routes: GenerationRoutes;
+ models: GenerationModels;
+ caps: GenerationCaps;
+ cacheTtl: "5m" | "1h";
+ apiKeyFile: string;
+ anthropicBaseUrl: string;
+ ollamaUrl: string;
+ projectsRoot: string;
+ web: GenerationWeb;
+ citationOrigin: string;
+};
+
+export const DEFAULT_API_KEY_FILE = "~/.config/archilyzer/anthropic.env";
+
+export const DEFAULT_GENERATION_SETTINGS: GenerationSettings = {
+ preset: "balanced",
+ routes: { ...GENERATION_PRESETS.balanced },
+ 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",
+ apiKeyFile: DEFAULT_API_KEY_FILE,
+ anthropicBaseUrl: "",
+ ollamaUrl: "",
+ projectsRoot: "",
+ web: { provider: "duckduckgo", searchUrl: "" },
+ citationOrigin: "",
+};
+
+export const GENERATION_SETTINGS_FIELD_DOCS: FieldDocs<GenerationSettings> = {
+ preset:
+ "The balance knob: `code` (Claude Code does every task), `balanced` (sweeps in Claude Code, report revisions on the API, video revisions and narration on the local model), `api`, `local`. Named by `routes`: the preset whose routes they are, else `custom` — choosing a preset is writing its routes.",
+ routes: "Where each task runs: `code`, `api` or `local` (below).",
+ models: "The model each route runs (below).",
+ caps: "The spend caps in USD (below).",
+ cacheTtl: "The prompt cache's lifetime on the Claude API: `5m` (writes bill 1.25× input) or `1h` (2×, for long runs with pauses).",
+ apiKeyFile:
+ "The file holding the Claude API key (`ANTHROPIC_API_KEY=…`), mode 600 — refused when the group or others can read it. `~` is the editor's home. The KEY itself is never a setting: a value that looks like one is refused, never stored. `ANTHROPIC_API_KEY` in the editor's environment wins over the file.",
+ anthropicBaseUrl: "Advanced: the Messages API's base URL. Blank = Anthropic's. Tests point it at a fake.",
+ ollamaUrl: "The local model's server (ollama). Blank = the editor's `OLLAMA_URL` (the digest lane's server, default http://127.0.0.1:11434).",
+ projectsRoot:
+ "Where an iteration's video project and renders live: `<projectsRoot>/<article>/i<n>/`, off the corpus disk (D1). Blank = `~/reports/articles`.",
+ web: "The web an agent may read for context (below). Read-only and paced: one request at a time, 3 s apart.",
+ citationOrigin:
+ "The origin a generated report's moment links cite when its corpus build's site has no public URL (a private build). Blank = the project site.",
+};
+
+export const GENERATION_ROUTES_FIELD_DOCS: FieldDocs<GenerationRoutes> = {
+ sweep: "A new report from a question: `code` (/sweep in Claude Code), `api` (the agent on `models.api`) or `local` (the code-driven pipeline on `models.local`).",
+ "revise-report": "A report iteration from feedback, through checked ops.",
+ "revise-video": "A video-cut iteration from feedback, through checked ops.",
+ narrate: "Card narration for an iteration's cut, under the narration rules and the grounding checks.",
+};
+
+export const GENERATION_MODELS_FIELD_DOCS: FieldDocs<GenerationModels> = {
+ api: "The Claude model the `api` route runs (Sonnet 5.5: no temperature, no forced tool choice, thinking between tools).",
+ local: "The ollama model the `local` route runs. Prompts stay under 8k tokens and `num_ctx` under 12k on the 8 GB card.",
+ extractor: "The cheap model an API sweep's `extract_batch` runs — the plan's dumb extractor (Claude or a local model).",
+};
+
+export const GENERATION_CAPS_FIELD_DOCS: FieldDocs<GenerationCaps> = {
+ sweep: "A sweep job's cap when it names none. The agent wraps up at 85% and stops at the cap.",
+ revision: "A report or video revision job's cap when it names none.",
+ narration: "A narration job's cap when it names none.",
+ daily: "The API spend a day (UTC) may reach: a job that would start past it is refused, naming the day's total. 0 = no daily cap.",
+ max: "The most a job may ask for: a larger `maxUsd` is refused.",
+};
+
+export const GENERATION_WEB_FIELD_DOCS: FieldDocs<GenerationWeb> = {
+ provider: "The search a local model's `web_search` reads: `duckduckgo` (its HTML page). Claude uses the API's own search.",
+ searchUrl: "Advanced: the search endpoint. Blank = the provider's. Tests point it at a fake.",
+};
+
+// What a key looks like: the API's own prefix, or one long unbroken token with
+// no path in it.
+export function looksLikeApiKey(v: string): boolean {
+ const s = v.trim();
+ return /sk-ant-/i.test(s) || (!s.includes("/") && !s.startsWith("~") && /^[A-Za-z0-9_-]{32,}$/.test(s));
+}
+
+const str = (v: unknown, d: string) => (typeof v === "string" ? v.trim() : d);
+const url = (v: unknown, d: string) => {
+ const s = typeof v === "string" ? v.trim().replace(/\/+$/, "") : null;
+ if (s === null) return d;
+ if (s === "") return "";
+ return /^https?:\/\/[^\s]+$/.test(s) ? s : d;
+};
+const usd = (v: unknown, d: number, max = 1000) =>
+ typeof v === "number" && Number.isFinite(v) && v >= 0 ? Math.min(max, Math.round(v * 100) / 100) : d;
+
+export function sanitizeGeneration(value: unknown): GenerationSettings {
+ const d = DEFAULT_GENERATION_SETTINGS;
+ const r = value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : {};
+ const rr = r.routes && typeof r.routes === "object" ? (r.routes as Record<string, unknown>) : {};
+ const routes = {} as GenerationRoutes;
+ for (const t of GENERATION_TASKS) {
+ const v = rr[t];
+ routes[t] = typeof v === "string" && (GENERATION_ROUTES as readonly string[]).includes(v) ? (v as GenerationRoute) : d.routes[t];
+ }
+ // The ROUTES are the truth; the preset names them (the preset whose routes
+ // they are, else `custom`). Choosing a preset is writing its routes.
+ const preset: GenerationSettings["preset"] = presetOf(routes);
+ const m = r.models && typeof r.models === "object" ? (r.models as Record<string, unknown>) : {};
+ const model = (v: unknown, fallback: string) =>
+ typeof v === "string" && /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/.test(v.trim()) ? v.trim() : fallback;
+ const c = r.caps && typeof r.caps === "object" ? (r.caps as Record<string, unknown>) : {};
+ const max = usd(c.max, d.caps.max);
+ const w = r.web && typeof r.web === "object" ? (r.web as Record<string, unknown>) : {};
+ const keyFile = str(r.apiKeyFile, d.apiKeyFile);
+ return {
+ preset,
+ routes,
+ models: { api: model(m.api, d.models.api), local: model(m.local, d.models.local), extractor: model(m.extractor, d.models.extractor) },
+ caps: {
+ sweep: Math.min(max, usd(c.sweep, d.caps.sweep)),
+ revision: Math.min(max, usd(c.revision, d.caps.revision)),
+ narration: Math.min(max, usd(c.narration, d.caps.narration)),
+ daily: usd(c.daily, d.caps.daily, 100_000),
+ max,
+ },
+ cacheTtl: r.cacheTtl === "1h" ? "1h" : "5m",
+ // Never a key: a value that looks like one is the default path.
+ apiKeyFile: keyFile && !looksLikeApiKey(keyFile) ? keyFile : d.apiKeyFile,
+ anthropicBaseUrl: url(r.anthropicBaseUrl, d.anthropicBaseUrl),
+ ollamaUrl: url(r.ollamaUrl, d.ollamaUrl),
+ projectsRoot: str(r.projectsRoot, d.projectsRoot),
+ web: { provider: "duckduckgo", searchUrl: url(w.searchUrl, d.web.searchUrl) },
+ citationOrigin: url(r.citationOrigin, d.citationOrigin),
+ };
+}
+
+export function presetOf(routes: GenerationRoutes): GenerationPreset | "custom" {
+ return GENERATION_PRESET_NAMES.find((p) => GENERATION_TASKS.every((t) => routes[t] === GENERATION_PRESETS[p][t])) ?? "custom";
+}
+
+// The cap a job runs under: the task's default, or the asked one when it is
+// within `max` (else an error naming both).
+export function capFor(caps: GenerationCaps, task: "sweep" | "revision" | "narration", asked?: number): number {
+ if (asked === undefined || asked === null) return caps[task];
+ if (!Number.isFinite(asked) || asked <= 0) throw new Error(`maxUsd must be a positive number of dollars`);
+ if (asked > caps.max) throw new Error(`maxUsd $${asked} is over the settings' max of $${caps.max} (settings.generation.caps.max)`);
+ return asked;
+}
diff --git a/common/lib/paths.ts b/common/lib/paths.ts
@@ -168,6 +168,10 @@ export type Paths = {
espeakNgBin: string;
ttsHome: string;
ttsCacheDir: string;
+ // The generation usage ledger (release 27 S6): one JSON line per finished
+ // API generation job — what the day's spend cap is read from. Editor state,
+ // never inside the corpus (`<repo>/.generation/usage.jsonl`, gitignored).
+ generationUsageFile: string;
// Base URL of the local ollama server, the local-GPU digest lane
// (common/lib/digestApps.ts posts to `${ollamaUrl}/api/chat`). The FIRST
// URL-valued entry in Paths, so it is normalized here the way
@@ -320,6 +324,7 @@ export function getPaths(): Paths {
espeakNgBin: process.env.ESPEAK_NG_BIN ?? "espeak-ng",
ttsHome: path.join(os.homedir(), ".local", "share", "archilyzer", "tts"),
ttsCacheDir: under(monorepoRoot, ".tts", "cache"),
+ generationUsageFile: process.env.GENERATION_USAGE_FILE ?? under(monorepoRoot, ".generation", "usage.jsonl"),
ollamaUrl: (process.env.OLLAMA_URL ?? "http://127.0.0.1:11434").replace(
/\/+$/,
"",
diff --git a/common/lib/queueKeys.ts b/common/lib/queueKeys.ts
@@ -18,6 +18,13 @@ export { TRANSCRIPTION_QUEUE };
export const DIGEST_LOCAL_QUEUE = "digest:local";
export const DIGEST_REMOTE_QUEUE = "digest:remote";
+// The two generation lanes (release 27 S6), split for the digests' reason: a
+// `report-draft` on the local model holds the GPU (and yields through the GPU
+// arbiter, controller/gpuArbiter.ts), one on the Claude API is network work
+// that must not wait behind it. Each runs one job at a time.
+export const DRAFT_LOCAL_QUEUE = "draft:local";
+export const DRAFT_API_QUEUE = "draft:api";
+
// The backfill lane (controller/operationBatch.ts). Its own key for exactly the
// reason the two digest keys have theirs: registry.ts submits every non-empty
// queueKey at concurrency 1, so a distinct key is the ONLY way to get a lane
diff --git a/common/lib/report/draft/tasks/corpusCues.ts b/common/lib/report/draft/tasks/corpusCues.ts
@@ -0,0 +1,39 @@
+// A recording's cues as the run's corpus has them (release 27, S6): read
+// through the corpus tools' `get_transcript` with timestamps — the same build
+// the agent quoted from, so convert widens and the strict check reads the
+// words it saw. A cue ends where the next begins (the transcript shows starts).
+
+import type { CuesOf } from "../../convertShared";
+import type { CorpusToolsLike } from "./types";
+
+const LINE = /^\[\[((?:\d+:)?\d+:\d+)\]\([^)]*\)\]\s?(.*)$/;
+
+const seconds = (stamp: string) => stamp.split(":").reduce((s, p) => s * 60 + Number(p), 0);
+
+export function parseTimestampedTranscript(text: string): { start: number; end: number; text: string }[] {
+ const starts: { start: number; text: string }[] = [];
+ for (const raw of text.split("\n")) {
+ const m = LINE.exec(raw.trim());
+ if (m) starts.push({ start: seconds(m[1]!), text: m[2]!.trim() });
+ }
+ return starts.map((c, i) => ({ start: c.start, end: Math.max(c.start + 0.5, (starts[i + 1]?.start ?? c.start + 5) - 0.01), text: c.text }));
+}
+
+export function corpusCuesOf(corpus: Pick<CorpusToolsLike, "call">): CuesOf {
+ const cache = new Map<string, Promise<{ start: number; end: number; text: string }[] | null>>();
+ return (channel, id) => {
+ const key = `${channel}/${id}`;
+ let p = cache.get(key);
+ if (!p) {
+ p = corpus
+ .call("get_transcript", { video_id: id, channel, timestamps: true })
+ .then((t) => {
+ const cues = parseTimestampedTranscript(t);
+ return cues.length ? cues : null;
+ })
+ .catch(() => null);
+ cache.set(key, p);
+ }
+ return p;
+ };
+}
diff --git a/common/lib/report/draft/tasks/tasks.test.ts b/common/lib/report/draft/tasks/tasks.test.ts
@@ -198,3 +198,17 @@ test("narrate: a card's evidence; the better draft kept, failing sentences remov
assert.equal(best.text.includes("I did not enter the contest this year"), false);
assert.ok(best.soft.some((s) => s.startsWith("trimmed")));
});
+
+test("corpus cues: get_transcript's timestamped lines as cues, each ending where the next begins", async () => {
+ const { parseTimestampedTranscript, corpusCuesOf } = await import("./corpusCues");
+ const text = "# Pie\n\n## Transcript\n\n[[0:00](https://v.example/watch?v=p)] good evening\n[[0:05](https://v.example/watch?v=p&t=5s)] a lot of you asked\n[[1:02:03](https://v.example/watch?v=p&t=3723s)] late line\n\n(corpus: x)";
+ const cues = parseTimestampedTranscript(text);
+ assert.deepEqual(cues.map((c) => [c.start, c.text]), [[0, "good evening"], [5, "a lot of you asked"], [3723, "late line"]]);
+ assert.equal(cues[0]!.end, 4.99);
+ let calls = 0;
+ const of = corpusCuesOf({ call: async () => (calls++, text) });
+ assert.equal((await of("c", "p"))!.length, 3);
+ await of("c", "p");
+ assert.equal(calls, 1, "read once per recording");
+ assert.equal(await corpusCuesOf({ call: async () => { throw new Error("no"); } })("c", "x"), null);
+});
diff --git a/common/lib/settingsDocs.ts b/common/lib/settingsDocs.ts
@@ -24,6 +24,11 @@ import {
SEEDER_SETTINGS_FIELD_DOCS,
TTS_SETTINGS_FIELD_DOCS,
ORPHEUS_TTS_SETTINGS_FIELD_DOCS,
+ GENERATION_CAPS_FIELD_DOCS,
+ GENERATION_MODELS_FIELD_DOCS,
+ GENERATION_ROUTES_FIELD_DOCS,
+ GENERATION_SETTINGS_FIELD_DOCS,
+ GENERATION_WEB_FIELD_DOCS,
SOCIAL_LINK_FIELD_DOCS,
SOCIAL_SETTINGS_FIELD_DOCS,
X_SOCIAL_SETTINGS_FIELD_DOCS,
@@ -274,6 +279,13 @@ export function blockTables(d: SiteSettings): Partial<Record<keyof SiteSettings,
defaults: fromObject(d.tts.orpheus),
},
],
+ generation: [
+ { path: "generation", docs: GENERATION_SETTINGS_FIELD_DOCS, defaults: fromObject(d.generation) },
+ { path: "generation.routes", docs: GENERATION_ROUTES_FIELD_DOCS, defaults: fromObject(d.generation.routes) },
+ { path: "generation.models", docs: GENERATION_MODELS_FIELD_DOCS, defaults: fromObject(d.generation.models) },
+ { path: "generation.caps", docs: GENERATION_CAPS_FIELD_DOCS, defaults: fromObject(d.generation.caps) },
+ { path: "generation.web", docs: GENERATION_WEB_FIELD_DOCS, defaults: fromObject(d.generation.web) },
+ ],
};
}
diff --git a/common/lib/settingsSchema.test.ts b/common/lib/settingsSchema.test.ts
@@ -32,6 +32,7 @@ import type { StorageSettings } from "./storageLocations";
import type { ArchiveOrgFetchSettings } from "./archiveOrgTorrent";
import type { SeederSettings } from "./seederSettings";
import type { TtsSettings } from "./ttsSettings";
+import type { GenerationSettings } from "./generationSettings";
import type {
AttributionSettings,
BackfillSettings,
@@ -109,13 +110,15 @@ type PreSchemaSiteSettings = {
seeder: SeederSettings;
// Local text-to-speech (release 25 T1).
tts: TtsSettings;
+ // Report and video generation (release 27 S6).
+ generation: GenerationSettings;
};
// Bracketed so the conditional does not distribute (see commit 8c43231).
type Same<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false;
const shapeUnchanged: Same<SiteSettings, PreSchemaSiteSettings> = true;
-test("SiteSettings keeps its 38 fields, in file order", () => {
+test("SiteSettings keeps its 39 fields, in file order", () => {
assert.equal(shapeUnchanged, true);
assert.deepEqual(Object.keys(siteSettingsSchema.shape), [
"adminTitle",
@@ -156,6 +159,7 @@ test("SiteSettings keeps its 38 fields, in file order", () => {
"publish",
"seeder",
"tts",
+ "generation",
]);
// A parsed object carries every key, in that order — writeSettings writes
// exactly this, so the order is the on-disk order.
diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts
@@ -79,6 +79,15 @@ import {
import { sanitizeSeeder, type SeederSettings } from "./seederSettings";
export { SEEDER_SETTINGS_FIELD_DOCS, type SeederSettings } from "./seederSettings";
import { sanitizeTts, type TtsSettings } from "./ttsSettings";
+import { sanitizeGeneration, type GenerationSettings } from "./generationSettings";
+export {
+ GENERATION_CAPS_FIELD_DOCS,
+ GENERATION_MODELS_FIELD_DOCS,
+ GENERATION_ROUTES_FIELD_DOCS,
+ GENERATION_SETTINGS_FIELD_DOCS,
+ GENERATION_WEB_FIELD_DOCS,
+ type GenerationSettings,
+} from "./generationSettings";
export { ORPHEUS_TTS_SETTINGS_FIELD_DOCS, TTS_SETTINGS_FIELD_DOCS, type TtsSettings } from "./ttsSettings";
import {
DEFAULT_COOKIE_MODE,
@@ -1832,6 +1841,9 @@ export const siteSettingsSchema = z.object({
tts: settingsField((v): TtsSettings => sanitizeTts(v)).describe(
"Local text-to-speech (release 25): narration for report videos and podcasts, synthesized as an editor job (`pnpm ops tts`, the `tts` queue, one at a time) with a STOCK voice — never a cloned one — and cached by content. The default engine is Kokoro-82M with the voice `af_heart`, installed by `archilyzer tts setup`; espeak-ng needs no install. Every synthesis is disclosed as a synthetic voice (its sidecar and the result's `disclosure`). See TtsSettings and common/controller/ttsFile.ts.",
),
+ generation: settingsField((v): GenerationSettings => sanitizeGeneration(v)).describe(
+ "Report and video generation (release 27): where each task runs (`code` = Claude Code, `api` = the Claude API with a key, `local` = the local model), the models, the spend caps (a job's default, its max, the day's), the API key FILE (never the key), and where video projects live. A generation runs as a `report-draft` editor job (`pnpm ops report-draft`) on `draft:api` or `draft:local`. See GenerationSettings and common/lib/generationSettings.ts.",
+ ),
});
export type SiteSettings = z.infer<typeof siteSettingsSchema>;
diff --git a/editor/app/api/ops/_reportDraft.test.ts b/editor/app/api/ops/_reportDraft.test.ts
@@ -0,0 +1,188 @@
+import { after, before, test } from "node:test";
+import assert from "node:assert/strict";
+import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { createCorpusTools } from "yt-dlp-transcript-mcp/callTool";
+import { ORIGIN, writeDraftCorpus } from "yt-dlp-transcript-common/testing/draft/corpus.mjs";
+import { FAKE_KEY, startFakeAnthropic, textTurn, type FakeAnthropic } from "yt-dlp-transcript-common/testing/llm/fakeAnthropic.mjs";
+import { startFakeOllama, type FakeOllama } from "yt-dlp-transcript-common/testing/llm/fakeOllama.mjs";
+import { enqueueReportDraft, parseReportDraftBody } from "yt-dlp-transcript-common/controller/reportDraft";
+import { sanitizeGeneration, type GenerationSettings } from "yt-dlp-transcript-common/lib/generationSettings";
+import { getRegistry } from "yt-dlp-transcript-common/jobs/registry";
+import { readGenerationUsage } from "yt-dlp-transcript-common/controller/generationUsage";
+import { createIteration, projectOf, readIteration, updateIteration, writeIterationFile } from "yt-dlp-transcript-common/lib/report/iterations";
+import type { Paths } from "yt-dlp-transcript-common/lib/paths";
+
+// Run with:
+// pnpm -C editor exec tsx --test "app/api/ops/_reportDraft.test.ts"
+//
+// The `report-draft` job (release 27 S6) end to end in this process: the
+// controller the route adapts, the MCP's corpus tools over the synthetic
+// corpus, the fake Anthropic and ollama servers, a temp store, jobs dir and
+// usage ledger. The key is a mode-600 file holding the fake's key.
+
+const DRAFT = path.join(path.dirname(new URL(import.meta.url).pathname), "../../../../common/testing/draft");
+let tmp: string;
+let api: FakeAnthropic;
+let ol: FakeOllama;
+let source: string;
+let paths: Paths;
+let gen: GenerationSettings;
+
+before(async () => {
+ tmp = await mkdtemp(path.join(os.tmpdir(), "report-draft-"));
+ source = `local:${await writeDraftCorpus(path.join(tmp, "corpus"))}`;
+ api = await startFakeAnthropic();
+ ol = await startFakeOllama();
+ const keyFile = path.join(tmp, "anthropic.env");
+ await writeFile(keyFile, `ANTHROPIC_API_KEY=${FAKE_KEY}\n`);
+ await chmod(keyFile, 0o600);
+ await mkdir(path.join(tmp, "channels"), { recursive: true });
+ paths = {
+ jobsDir: path.join(tmp, ".jobs"),
+ articlesDir: path.join(tmp, "reports"),
+ exportIndexDir: path.join(tmp, ".export-index"),
+ exportBuildsDir: path.join(tmp, ".export-builds"),
+ sitesDir: path.join(tmp, "sites"),
+ channelsDir: path.join(tmp, "channels"),
+ generationUsageFile: path.join(tmp, ".generation", "usage.jsonl"),
+ ollamaUrl: ol.url,
+ } as Paths;
+ gen = sanitizeGeneration({
+ apiKeyFile: keyFile,
+ anthropicBaseUrl: api.url,
+ citationOrigin: ORIGIN,
+ projectsRoot: path.join(tmp, "projects"),
+ caps: { sweep: 2, daily: 20, max: 5 },
+ });
+});
+
+after(async () => {
+ await api.close();
+ await ol.close();
+ await rm(tmp, { recursive: true, force: true });
+});
+
+const deps = (g: Partial<GenerationSettings> = {}) => ({
+ paths,
+ corpusTools: (s: string) => createCorpusTools({ source: s }),
+ settings: () => ({ generation: { ...gen, ...g } }),
+});
+
+const run = async (name: string) => JSON.parse(await readFile(path.join(DRAFT, "runs", `${name}.json`), "utf8"));
+
+test("the body: each task's needs, and the refusals in words", () => {
+ assert.throws(() => parseReportDraftBody({ task: "nope", article: "a" }), /"task" is one of sweep, revise-report, revise-video, narrate/);
+ assert.throws(() => parseReportDraftBody({ task: "sweep", article: "a", channels: ["x"] }), /needs its question/);
+ assert.throws(() => parseReportDraftBody({ task: "revise-report", article: "a", iteration: 1 }), /needs feedback/);
+ assert.throws(() => parseReportDraftBody({ task: "narrate", article: "a" }), /names the iteration it voices/);
+ assert.throws(() => parseReportDraftBody({ task: "sweep", article: "a", question: "q", channels: "x", source: "ftp:x" }), /corpus handle/);
+ assert.deepEqual(parseReportDraftBody({ task: "sweep", article: "a", question: " q ", channels: "x, y" }), { task: "sweep", article: "a", question: "q", channels: ["x", "y"] });
+});
+
+test("refused before any iteration: a task routed to Claude Code with no model, a cap over max", async () => {
+ const code = await enqueueReportDraft({ task: "sweep", article: "synth-refused", question: "q", channels: ["synth-kitchen"], source }, deps());
+ assert.equal(code.result.ok, false);
+ assert.match((code.result as { error: string }).error, /routed to Claude Code/);
+ const big = await enqueueReportDraft({ task: "sweep", article: "synth-refused", model: "claude-sonnet-5-5", question: "q", channels: ["synth-kitchen"], maxUsd: 9, source }, deps());
+ assert.match((big.result as { error: string }).error, /over the settings' max of \$5/);
+ assert.equal(await readIteration("synth-refused", 1, paths), null);
+});
+
+test("an API sweep: a report-draft job on draft:api, the iteration done with its job, the usage in the ledger", async () => {
+ const r = await run("sweep-agent");
+ api.push(...r.turns);
+ const out = await enqueueReportDraft(
+ { task: "sweep", article: "synth-api", model: r.model, question: r.question, channels: r.channels, source },
+ deps(),
+ );
+ assert.ok(out.result.ok && "iteration" in out, (out.result as { error?: string }).error);
+ const job = getRegistry().get(out.result.jobId)!;
+ assert.equal(job.kind, "report-draft");
+ assert.equal(job.queueKey, "draft:api");
+ void out.result.stream.cancel();
+ const done = await out.result.done;
+ const log = await readFile(job.logPath, "utf8");
+ assert.equal(done.status, "done", log);
+ assert.match(log, /@@report-draft \{"article":"synth-api","iteration":1,"task":"sweep","status":"done"/);
+ assert.ok(!log.includes(FAKE_KEY), "the key is never in the log");
+ const it = (await readIteration("synth-api", out.iteration, paths))!;
+ assert.equal(it.status, "done");
+ assert.equal(it.jobId, out.result.jobId);
+ const rows = await readGenerationUsage(paths.generationUsageFile);
+ assert.deepEqual(rows.map((x) => x.model).sort(), ["claude-haiku-4-5", "claude-sonnet-5-5"]);
+ const jobId = out.result.jobId;
+ assert.ok(rows.every((x) => x.jobId === jobId && x.article === "synth-api" && x.iteration === 1));
+ assert.equal(api.requestHeaders.at(-1)!["x-api-key"], FAKE_KEY, "the key file's key");
+});
+
+test("the daily cap: a job that would start past the day's total is refused, naming it", async () => {
+ const before = await readGenerationUsage(paths.generationUsageFile);
+ const total = before.reduce((s, x) => s + x.usd, 0);
+ assert.ok(total > 0);
+ const out = await enqueueReportDraft(
+ { task: "sweep", article: "synth-daily", model: "claude-sonnet-5-5", question: "q", channels: ["synth-kitchen"], source },
+ deps({ caps: { ...gen.caps, daily: total / 2 } }),
+ );
+ assert.equal(out.result.ok, false);
+ assert.match((out.result as { error: string }).error, /the day's Claude API spend is \$\d+\.\d\d .* daily cap \(settings\.generation\.caps\.daily\) — refused/);
+ assert.equal(await readIteration("synth-daily", 1, paths), null, "no iteration made");
+});
+
+test("job cancel stops a running draft: the request in flight aborted, the iteration cancelled", async () => {
+ let release!: () => void;
+ const held = new Promise<void>((r) => (release = r));
+ let arrived!: () => void;
+ const inFlight = new Promise<void>((r) => (arrived = r));
+ api.push(async () => {
+ arrived();
+ await held;
+ return textTurn("too late");
+ });
+ const out = await enqueueReportDraft(
+ { task: "sweep", article: "synth-cancel", model: "claude-sonnet-5-5", question: "q", channels: ["synth-kitchen"], source },
+ deps(),
+ );
+ assert.ok(out.result.ok && "iteration" in out);
+ void out.result.stream.cancel();
+ await inFlight;
+ assert.equal(getRegistry().cancel(out.result.jobId), true);
+ const done = await out.result.done;
+ release();
+ assert.equal(done.status, "cancelled");
+ let it = await readIteration("synth-cancel", out.iteration, paths);
+ for (let i = 0; i < 50 && it?.status !== "cancelled"; i++) {
+ await new Promise((r) => setTimeout(r, 20));
+ it = await readIteration("synth-cancel", out.iteration, paths);
+ }
+ assert.equal(it!.status, "cancelled");
+});
+
+test("a local narration: draft:local, a step on the iteration, ollama unloaded when the job ends", async () => {
+ const r = await run("narrate");
+ ol.push(...r.turns);
+ const article = "synth-basic";
+ await createIteration(article, { kind: "sweep", model: "claude-sonnet-5-5", question: "q", scope: { channels: ["synth-kitchen"] } }, paths);
+ const report = JSON.parse(await readFile(path.join(DRAFT, "reports", "basic.report.json"), "utf8"));
+ await writeIterationFile(article, 1, "report.json", report, paths);
+ const dir = projectOf(gen.projectsRoot, article, 1);
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, "video.manifest.json"), await readFile(path.join(DRAFT, "manifests", "basic.video.manifest.json"), "utf8"));
+ await writeFile(path.join(dir, "report.json"), JSON.stringify(report));
+ await updateIteration(article, 1, { status: "done", projectDir: dir }, paths);
+ const out = await enqueueReportDraft({ task: "narrate", article, iteration: 1, model: r.model, source }, deps());
+ assert.ok(out.result.ok && "iteration" in out, (out.result as { error?: string }).error);
+ assert.equal(getRegistry().get(out.result.jobId)!.queueKey, "draft:local");
+ void out.result.stream.cancel();
+ const done = await out.result.done;
+ assert.equal(done.status, "done", await readFile(getRegistry().get(out.result.jobId)!.logPath, "utf8"));
+ assert.deepEqual(ol.unloads, ["qwen3:8b"]);
+ const it = (await readIteration(article, 1, paths))!;
+ assert.equal(it.status, "done");
+ const step = it.steps.find((s) => s.task === "narrate")!;
+ assert.equal(step.status, "done");
+ assert.equal(step.jobId, out.result.jobId);
+ const m = JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8"));
+ assert.ok(m.timeline.find((e: { id: string }) => e.id === "the-bakery").narration.text);
+});
diff --git a/editor/app/api/ops/report-draft/route.ts b/editor/app/api/ops/report-draft/route.ts
@@ -0,0 +1,38 @@
+import { NextResponse } from "next/server";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { REPORT_DRAFT_BODY_KEYS, enqueueReportDraft } from "yt-dlp-transcript-common/controller/reportDraft";
+import { createCorpusTools } from "yt-dlp-transcript-mcp/callTool";
+import { jobResponse, ops } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { task, article, iteration?, model?, feedback?, question?, channels?,
+// from?, to?, copyOf?, maxUsd?, source?, build?, cards?, force? }
+// -> { ok: true, jobId, iteration }
+//
+// A generation over an article's iteration (release 27 S6), as a
+// `report-draft` job on `draft:api` or `draft:local` by the model's provider:
+// - task "sweep": a new iteration from `question` over `channels` (and
+// `from`/`to`); the API model runs the agent, a local model the pipeline;
+// - "revise-report" / "revise-video": a new iteration revising `iteration`
+// from `feedback`;
+// - "narrate": a step on the done iteration `iteration` (`cards`, `force`);
+// - `copyOf` N: iteration N again on `model` (same kind and inputs).
+// `model` defaults to settings.generation's route for the task (a task routed
+// to `code` needs one named). An API job's cap is `maxUsd`, else the task's
+// default (settings.generation.caps), never above `caps.max`; a job that would
+// start past the day's API total (`caps.daily`) is refused, naming it. The
+// corpus is `source` (a handle), `build` (a composed build's id), or the newest
+// build holding the channels. `job cancel` stops it (the iteration ends
+// `cancelled`). The job's log ends `@@report-draft {json}` with the result.
+//
+// AN ADAPTER: the refusals are the controller's (controller/reportDraft.ts);
+// the corpus tools are the MCP's own, in process (mcp/src/callTool.ts).
+export async function POST(request: Request) {
+ return ops(request, REPORT_DRAFT_BODY_KEYS, async (body) => {
+ const out = await enqueueReportDraft(body, { paths: getPaths(), corpusTools: (source) => createCorpusTools({ source }) });
+ if (!out.result.ok || !("iteration" in out)) return jobResponse(out.result);
+ void out.result.stream.cancel();
+ return NextResponse.json({ ok: true, jobId: out.result.jobId, iteration: out.iteration });
+ });
+}
diff --git a/editor/app/api/ops/settings/route.ts b/editor/app/api/ops/settings/route.ts
@@ -4,6 +4,7 @@ import { mergeSettingsPatch, saveSettings } from "../../../settings/saveSettings
import { OpsInputError, ops, opsFail } from "../_lib";
import { readRoute, redactSecrets } from "../_read";
import { settingsPatchProblem } from "./patch";
+import { looksLikeApiKey } from "yt-dlp-transcript-common/lib/generationSettings";
export const dynamic = "force-dynamic";
@@ -55,6 +56,15 @@ export async function POST(request: Request) {
}
const keys = Object.keys(patch);
if (keys.length === 0) throw new OpsInputError('"patch" is empty — nothing to change');
+ // The Claude API key is never a setting (release 27 S6): a key file path
+ // that looks like a key is refused WITHOUT echoing it, before the generic
+ // check below would print what was sent.
+ const keyFile = (patch as { generation?: { apiKeyFile?: unknown } }).generation?.apiKeyFile;
+ if (typeof keyFile === "string" && looksLikeApiKey(keyFile)) {
+ throw new OpsInputError(
+ "generation.apiKeyFile is the PATH of the mode-600 file that holds the key, and the value sent looks like a key itself — refused, not stored",
+ );
+ }
const current = getSettings();
const problem = settingsPatchProblem(
patch as Record<string, unknown>,
diff --git a/editor/e2e/report-draft.spec.ts b/editor/e2e/report-draft.spec.ts
@@ -0,0 +1,157 @@
+import { test, expect, type APIRequestContext } from "@playwright/test";
+import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+// By relative path, as digest.spec.ts imports common: the test kit's fakes and
+// the synthetic corpus are plain .mjs.
+import { FAKE_KEY, startFakeAnthropic, textTurn, type FakeAnthropic } from "../../common/testing/llm/fakeAnthropic.mjs";
+import { ORIGIN, writeDraftCorpus } from "../../common/testing/draft/corpus.mjs";
+import { baseUrl } from "./baseUrl";
+import { resetData, testPaths, writeSettings } from "./helpers";
+
+// `pnpm ops report-draft` end to end (release 27 S6): the editor against the
+// fake Anthropic (started here, on loopback; settings point at it with a
+// mode-600 key file holding the fake's key), over the synthetic draft corpus
+// written as a composed build into the test server's .export-builds/ (the
+// newest build holding the channels is the one a job picks). The usage ledger
+// is the test server's GENERATION_USAGE_FILE, inside test-transcripts/, so a
+// reset clears it.
+
+const AUTH = { authorization: "Bearer test-worker-token" };
+const RUNS = join(dirname(fileURLToPath(import.meta.url)), "..", "..", "common", "testing", "draft", "runs");
+
+let api: FakeAnthropic;
+let keyDir: string;
+
+test.beforeAll(async () => {
+ api = await startFakeAnthropic();
+ keyDir = await mkdtemp(join(os.tmpdir(), "e2e-report-draft-"));
+});
+
+test.afterAll(async () => {
+ await api?.close();
+ await rm(keyDir, { recursive: true, force: true });
+});
+
+async function setup(caps: Record<string, number> = {}) {
+ await resetData(null);
+ const keyFile = join(keyDir, "anthropic.env");
+ await writeFile(keyFile, `ANTHROPIC_API_KEY=${FAKE_KEY}\n`);
+ await chmod(keyFile, 0o600);
+ await writeSettings({
+ minFreeDiskGB: 0,
+ generation: {
+ apiKeyFile: keyFile,
+ anthropicBaseUrl: api.url,
+ citationOrigin: ORIGIN,
+ projectsRoot: join(keyDir, "projects"),
+ caps: { sweep: 3, revision: 2, narration: 1, daily: 20, max: 5, ...caps },
+ },
+ });
+ const t = testPaths().transcriptsDir;
+ await writeDraftCorpus(join(t, ".export-builds", "draft-e2e", "out"));
+}
+
+async function draft(request: APIRequestContext, data: Record<string, unknown>) {
+ const res = await request.post(`${baseUrl}/api/ops/report-draft`, { headers: AUTH, data });
+ return { status: res.status(), body: (await res.json()) as { ok?: boolean; error?: string; jobId?: string; iteration?: number } };
+}
+
+async function jobUntil(request: APIRequestContext, id: string, done: (s: string) => boolean, ms = 60_000) {
+ const t0 = Date.now();
+ let last = "";
+ while (Date.now() - t0 < ms) {
+ const res = await request.get(`${baseUrl}/api/ops/job/${id}?tail=40`, { headers: AUTH });
+ const body = (await res.json()) as { job?: { status?: string }; status?: string; tail?: string[] };
+ last = body.job?.status ?? body.status ?? "";
+ if (done(last)) return body;
+ await new Promise((r) => setTimeout(r, 300));
+ }
+ throw new Error(`job ${id} is still ${last}`);
+}
+
+const iterationJson = async (article: string, n: number) =>
+ JSON.parse(await readFile(join(testPaths().transcriptsDir, "reports", article, "iterations", String(n), "iteration.json"), "utf8"));
+
+const run = async (name: string) => JSON.parse(await readFile(join(RUNS, `${name}.json`), "utf8"));
+
+test.describe.configure({ mode: "serial" });
+
+test("a sweep draft: enqueued over ops, followed to done, its iteration read back", async ({ request }) => {
+ test.setTimeout(120_000);
+ await setup();
+ const r = await run("sweep-agent");
+ api.push(...r.turns);
+ const { status, body } = await draft(request, {
+ task: "sweep",
+ article: "synth-e2e",
+ model: r.model,
+ question: r.question,
+ channels: r.channels,
+ });
+ expect(status, body.error).toBe(200);
+ expect(body.ok).toBe(true);
+ expect(body.iteration).toBe(1);
+ const job = await jobUntil(request, body.jobId!, (s) => ["done", "failed", "cancelled"].includes(s));
+ expect(job.job?.status ?? job.status, JSON.stringify(job.tail)).toBe("done");
+ const it = await iterationJson("synth-e2e", 1);
+ expect(it.status).toBe("done");
+ expect(it.jobId).toBe(body.jobId);
+ expect(it.usage["claude-sonnet-5-5"].usd).toBeGreaterThan(0);
+ const report = JSON.parse(
+ await readFile(join(testPaths().transcriptsDir, "reports", "synth-e2e", "iterations", "1", "report.json"), "utf8"),
+ );
+ expect(Object.keys(report.citations)).toHaveLength(3);
+ const ledger = await readFile(join(testPaths().transcriptsDir, ".generation-usage.jsonl"), "utf8");
+ expect(ledger).toContain(body.jobId!);
+ expect(ledger).not.toContain(FAKE_KEY);
+ expect(api.remaining()).toBe(0);
+});
+
+test("a cancel mid-run: job cancel stops the draft and its iteration ends cancelled", async ({ request }) => {
+ test.setTimeout(120_000);
+ await setup();
+ let release!: () => void;
+ const held = new Promise<void>((r) => (release = r));
+ const before = api.requests.length;
+ api.push(async () => {
+ await held;
+ return textTurn("too late");
+ });
+ const { body } = await draft(request, {
+ task: "sweep",
+ article: "synth-cancel",
+ model: "claude-sonnet-5-5",
+ question: "What does she say about the contest?",
+ channels: ["synth-kitchen"],
+ });
+ expect(body.ok, body.error).toBe(true);
+ await expect.poll(() => api.requests.length, { timeout: 30_000 }).toBeGreaterThan(before);
+ const cancel = await request.post(`${baseUrl}/api/ops/job`, { headers: AUTH, data: { verb: "cancel", ids: [body.jobId] } });
+ expect(cancel.status()).toBe(200);
+ const job = await jobUntil(request, body.jobId!, (s) => ["done", "failed", "cancelled"].includes(s));
+ release();
+ expect(job.job?.status ?? job.status).toBe("cancelled");
+ await expect.poll(async () => (await iterationJson("synth-cancel", 1)).status, { timeout: 10_000 }).toBe("cancelled");
+});
+
+test("the daily cap: a job that would start past the day's API total is refused, naming it", async ({ request }) => {
+ await setup({ daily: 4 });
+ const day = new Date().toISOString().slice(0, 10);
+ await writeFile(
+ join(testPaths().transcriptsDir, ".generation-usage.jsonl"),
+ `${JSON.stringify({ at: new Date().toISOString(), day, jobId: "earlier", article: "x", iteration: 1, task: "sweep", model: "claude-sonnet-5-5", inputTokens: 1, outputTokens: 1, cacheReadTokens: 0, cacheWriteTokens: 0, usd: 4.5 })}\n`,
+ );
+ const { status, body } = await draft(request, {
+ task: "sweep",
+ article: "synth-daily",
+ model: "claude-sonnet-5-5",
+ question: "q",
+ channels: ["synth-kitchen"],
+ });
+ expect(status).toBe(400);
+ expect(body.error).toContain("the day's Claude API spend is $4.50");
+ expect(body.error).toContain("$4.00 daily cap");
+ await expect(readFile(join(testPaths().transcriptsDir, "reports", "synth-daily", "iterations", "1", "iteration.json"))).rejects.toThrow(/ENOENT/);
+});
diff --git a/editor/next.config.ts b/editor/next.config.ts
@@ -38,7 +38,7 @@ const nextConfig: NextConfig = {
},
],
},
- transpilePackages: ["yt-dlp-transcript-common"],
+ transpilePackages: ["yt-dlp-transcript-common", "yt-dlp-transcript-mcp"],
serverExternalPackages: ["lmdb", "msgpackr", "msgpackr-extract"],
experimental: {
serverActions: {
diff --git a/editor/package.json b/editor/package.json
@@ -5,8 +5,8 @@
"type": "module",
"scripts": {
"dev": "next dev --port ${EDITOR_PORT:-3001}",
- "dev:test": "WORKER_TOKEN=test-worker-token TRANSCRIPTS_DIR=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts EXPORT_PUBLIC_DIR=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts/.export-public SETTINGS_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-settings.json EDITOR_CHANGELOG_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-changelog.md EXPORT_CHANGELOG_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-export-changelog.md YTDLP_BIN=$(pwd)/e2e/fixtures/bin/fake-ytdlp.mjs GALLERY_DL_BIN=$(pwd)/e2e/fixtures/bin/fake-gallery-dl.mjs WHISPER_BIN=$(pwd)/e2e/fixtures/bin/fake-whisper.mjs WHISPER_MODEL=/dev/null CHOUGH_BIN=$(pwd)/e2e/fixtures/bin/fake-chough.mjs CHOUGH_MODEL=/dev/null PARAKEET_STITCH_BIN=$(pwd)/e2e/fixtures/bin/fake-parakeet-stitch.mjs PARAKEET_CLI=/dev/null PARAKEET_MODEL=/dev/null DIARIZE_BIN=$(pwd)/e2e/fixtures/bin/fake-diarize.mjs FFMPEG_BIN=$(pwd)/e2e/fixtures/bin/fake-ffmpeg.mjs FFPROBE_BIN=$(pwd)/e2e/fixtures/bin/fake-ffprobe.mjs OLLAMA_URL=http://127.0.0.1:${OLLAMA_STUB_PORT:-11435} CLAUDE_BIN=$(pwd)/e2e/fixtures/bin/fake-claude.mjs FINDMNT_BIN=$(pwd)/e2e/fixtures/bin/fake-findmnt.mjs UDISKSCTL_BIN=$(pwd)/e2e/fixtures/bin/fake-udisksctl.mjs next dev --port ${PORT:-3011}",
- "start:test": "WORKER_TOKEN=test-worker-token TRANSCRIPTS_DIR=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts EXPORT_PUBLIC_DIR=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts/.export-public SETTINGS_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-settings.json EDITOR_CHANGELOG_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-changelog.md EXPORT_CHANGELOG_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-export-changelog.md YTDLP_BIN=$(pwd)/e2e/fixtures/bin/fake-ytdlp.mjs GALLERY_DL_BIN=$(pwd)/e2e/fixtures/bin/fake-gallery-dl.mjs WHISPER_BIN=$(pwd)/e2e/fixtures/bin/fake-whisper.mjs WHISPER_MODEL=/dev/null CHOUGH_BIN=$(pwd)/e2e/fixtures/bin/fake-chough.mjs CHOUGH_MODEL=/dev/null PARAKEET_STITCH_BIN=$(pwd)/e2e/fixtures/bin/fake-parakeet-stitch.mjs PARAKEET_CLI=/dev/null PARAKEET_MODEL=/dev/null DIARIZE_BIN=$(pwd)/e2e/fixtures/bin/fake-diarize.mjs FFMPEG_BIN=$(pwd)/e2e/fixtures/bin/fake-ffmpeg.mjs FFPROBE_BIN=$(pwd)/e2e/fixtures/bin/fake-ffprobe.mjs OLLAMA_URL=http://127.0.0.1:${OLLAMA_STUB_PORT:-11435} CLAUDE_BIN=$(pwd)/e2e/fixtures/bin/fake-claude.mjs FINDMNT_BIN=$(pwd)/e2e/fixtures/bin/fake-findmnt.mjs UDISKSCTL_BIN=$(pwd)/e2e/fixtures/bin/fake-udisksctl.mjs next start --port ${PORT:-3011}",
+ "dev:test": "WORKER_TOKEN=test-worker-token TRANSCRIPTS_DIR=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts EXPORT_PUBLIC_DIR=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts/.export-public SETTINGS_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-settings.json EDITOR_CHANGELOG_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-changelog.md EXPORT_CHANGELOG_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-export-changelog.md GENERATION_USAGE_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts/.generation-usage.jsonl YTDLP_BIN=$(pwd)/e2e/fixtures/bin/fake-ytdlp.mjs GALLERY_DL_BIN=$(pwd)/e2e/fixtures/bin/fake-gallery-dl.mjs WHISPER_BIN=$(pwd)/e2e/fixtures/bin/fake-whisper.mjs WHISPER_MODEL=/dev/null CHOUGH_BIN=$(pwd)/e2e/fixtures/bin/fake-chough.mjs CHOUGH_MODEL=/dev/null PARAKEET_STITCH_BIN=$(pwd)/e2e/fixtures/bin/fake-parakeet-stitch.mjs PARAKEET_CLI=/dev/null PARAKEET_MODEL=/dev/null DIARIZE_BIN=$(pwd)/e2e/fixtures/bin/fake-diarize.mjs FFMPEG_BIN=$(pwd)/e2e/fixtures/bin/fake-ffmpeg.mjs FFPROBE_BIN=$(pwd)/e2e/fixtures/bin/fake-ffprobe.mjs OLLAMA_URL=http://127.0.0.1:${OLLAMA_STUB_PORT:-11435} CLAUDE_BIN=$(pwd)/e2e/fixtures/bin/fake-claude.mjs FINDMNT_BIN=$(pwd)/e2e/fixtures/bin/fake-findmnt.mjs UDISKSCTL_BIN=$(pwd)/e2e/fixtures/bin/fake-udisksctl.mjs next dev --port ${PORT:-3011}",
+ "start:test": "WORKER_TOKEN=test-worker-token TRANSCRIPTS_DIR=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts EXPORT_PUBLIC_DIR=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts/.export-public SETTINGS_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-settings.json EDITOR_CHANGELOG_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-changelog.md EXPORT_CHANGELOG_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-export-changelog.md GENERATION_USAGE_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts/.generation-usage.jsonl YTDLP_BIN=$(pwd)/e2e/fixtures/bin/fake-ytdlp.mjs GALLERY_DL_BIN=$(pwd)/e2e/fixtures/bin/fake-gallery-dl.mjs WHISPER_BIN=$(pwd)/e2e/fixtures/bin/fake-whisper.mjs WHISPER_MODEL=/dev/null CHOUGH_BIN=$(pwd)/e2e/fixtures/bin/fake-chough.mjs CHOUGH_MODEL=/dev/null PARAKEET_STITCH_BIN=$(pwd)/e2e/fixtures/bin/fake-parakeet-stitch.mjs PARAKEET_CLI=/dev/null PARAKEET_MODEL=/dev/null DIARIZE_BIN=$(pwd)/e2e/fixtures/bin/fake-diarize.mjs FFMPEG_BIN=$(pwd)/e2e/fixtures/bin/fake-ffmpeg.mjs FFPROBE_BIN=$(pwd)/e2e/fixtures/bin/fake-ffprobe.mjs OLLAMA_URL=http://127.0.0.1:${OLLAMA_STUB_PORT:-11435} CLAUDE_BIN=$(pwd)/e2e/fixtures/bin/fake-claude.mjs FINDMNT_BIN=$(pwd)/e2e/fixtures/bin/fake-findmnt.mjs UDISKSCTL_BIN=$(pwd)/e2e/fixtures/bin/fake-udisksctl.mjs next start --port ${PORT:-3011}",
"build": "next build",
"start": "UV_THREADPOOL_SIZE=${UV_THREADPOOL_SIZE:-16} next start --port ${EDITOR_PORT:-3001}",
"test": "tsx --test \"app/**/*.test.ts\" \"e2e/*.unit.ts\"",
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -100,6 +100,8 @@
// pnpm ops archive-search --json '{"query":"title:(kitchen) AND mediatype:movies","limit":20}'
// pnpm ops archive-item --json '{"item":"example-item"}'
// pnpm ops import-post --json '{"slug":"demo-x","url":"https://x.com/example/status/1700000000000000001"}' --wait
+// pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","question":"What does she say about the shop?","channels":["demo-channel"]}' --wait
+// pnpm ops report-draft --json '{"task":"revise-report","article":"demo-article","iteration":1,"feedback":"Drop the second finding."}'
//
// --file reads the BODY from a JSON file, which is how a big one gets sent: a
// four-thousand-id tag-videos body is written by a script, not typed by a model
@@ -375,6 +377,11 @@ const ACTIONS = [
"archive-search",
"archive-item",
"import-post",
+ // GENERATION (release 27 S6): a sweep, a report or video revision, or a
+ // narration step over an article's iteration ({task, article, iteration?,
+ // model?, feedback?, question?, channels?, copyOf?, maxUsd?, …}), as a
+ // report-draft job on draft:api or draft:local. `job cancel` stops it.
+ "report-draft",
];
// The log line a transcribe job ends with: this marker, then the result as
@@ -384,6 +391,9 @@ export const TRANSCRIBE_RESULT_MARKER = "@@transcribe-result ";
// The same for a text-to-speech job (TTS_RESULT_MARKER in
// common/controller/ttsFile.ts).
export const TTS_RESULT_MARKER = "@@tts-result ";
+// The same for a generation (REPORT_DRAFT_RESULT_MARKER in
+// common/controller/reportDraft.ts).
+export const REPORT_DRAFT_RESULT_MARKER = "@@report-draft ";
// The same for a remote listing (REMOTE_LISTING_RESULT_MARKER in
// common/controller/remoteListing.ts).
export const REMOTE_LISTING_RESULT_MARKER = "@@remote-listing ";
@@ -610,6 +620,7 @@ export function parseArgs(argv) {
...(action === "transcribe" ? { resultMarker: TRANSCRIBE_RESULT_MARKER } : {}),
...(action === "tts" ? { resultMarker: TTS_RESULT_MARKER } : {}),
...(action === "remote-listing" ? { resultMarker: REMOTE_LISTING_RESULT_MARKER } : {}),
+ ...(action === "report-draft" ? { resultMarker: REPORT_DRAFT_RESULT_MARKER } : {}),
wait,
quiet,
waitTimeout,
@@ -1133,6 +1144,22 @@ export function usage() {
" one the platform says is another account's is not written. The log ends",
" with @@import-post {ok, slug, url, id, written, already?, post?, error?}.",
"",
+ 'report-draft runs a generation over an article\'s iteration as a',
+ ' report-draft job: {"task": "sweep" | "revise-report" | "revise-video" |',
+ ' "narrate", "article", ...} -> {jobId, iteration}. A sweep takes "question"',
+ ' and "channels" (and "from"/"to"): a new iteration; a revision takes',
+ ' "iteration" (the one it revises) and "feedback": a new iteration; a',
+ ' narration takes "iteration" (a done one; "cards"?, "force"?) and is a step',
+ ' on it. "copyOf" N runs iteration N again on "model". "model" defaults to',
+ " settings.generation's route for the task (one routed to code needs a model",
+ ' named). A Claude model runs on draft:api, capped at "maxUsd" (default by',
+ " task, never above caps.max), and is refused when the day's API total has",
+ " reached caps.daily; a local model runs on draft:local, through the GPU",
+ ' arbiter, and is unloaded when it ends. The corpus is "source" (a handle),',
+ ' "build" (a composed build), or the newest build holding the channels.',
+ " `job cancel <id>` stops it. The log ends with @@report-draft {article,",
+ " iteration, task, status, summary, usd, minutes}; --wait prints it.",
+ "",
"Env: ARCHILYZER_EDITOR_URL (default http://localhost:3001), WORKER_TOKEN,",
" ARCHILYZER_AGENT (provenance of a tag write; default \"cli\").",
" WORKER_TOKEN and ARCHILYZER_EDITOR_URL, when unset, are read from",
diff --git a/settings.json.example b/settings.json.example
@@ -236,5 +236,36 @@
"takes": 3,
"tagCheck": false
}
+ },
+ "generation": {
+ "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
+ },
+ "cacheTtl": "5m",
+ "apiKeyFile": "~/.config/archilyzer/anthropic.env",
+ "anthropicBaseUrl": "",
+ "ollamaUrl": "",
+ "projectsRoot": "",
+ "web": {
+ "provider": "duckduckgo",
+ "searchUrl": ""
+ },
+ "citationOrigin": ""
}
}
diff --git a/umtool/lib/report/chain-run.mjs b/umtool/lib/report/chain-run.mjs
@@ -38,7 +38,7 @@ import { main as prepareMain } from "yt-dlp-transcript-common/bin/reports-prepar
import { toManifestMain } from "yt-dlp-transcript-common/bin/reports-convert";
import { attachVideoMain } from "yt-dlp-transcript-common/bin/reports-attach-video";
import { checkMain } from "yt-dlp-transcript-common/bin/reports-check";
-import { CHAIN_STEP_NAMES, CHAIN_WINDOW_PAD, DEFAULT_PROJECTS_ROOT, REPO_ROOT, chainTask, chainWindows, originFromSweep } from "./chain.mjs";
+import { CHAIN_STEP_NAMES, CHAIN_WINDOW_PAD, REPO_ROOT, configuredProjectsRoot, chainTask, chainWindows, originFromSweep } from "./chain.mjs";
import { PIPELINE_DIR } from "./driver.mjs";
import { dedupeMedia, seedFromParent } from "./iterations.mjs";
@@ -284,7 +284,7 @@ export async function runChainStep(article, n, name, opts = {}) {
console.error(`chain: "${article}" i${n} is ${iteration.status} — the chain runs over a done iteration`);
return 2;
}
- const projectsRoot = opts.projectsRoot ?? DEFAULT_PROJECTS_ROOT;
+ const projectsRoot = opts.projectsRoot ?? configuredProjectsRoot();
const ctx = {
article,
n,
diff --git a/umtool/lib/report/chain.mjs b/umtool/lib/report/chain.mjs
@@ -57,7 +57,7 @@ export const chainTask = (name) => `chain:${name}`;
// STARTER_RENDER): the windows are fetched this wide so the cut finds them.
export const CHAIN_WINDOW_PAD = 3;
-// Until S6's `settings.generation.projectsRoot`: off the corpus disk (D1).
+// Off the corpus disk (D1): `settings.generation.projectsRoot`, blank = this.
export const DEFAULT_PROJECTS_ROOT = path.join(/* turbopackIgnore: true */ os.homedir(), "reports", "articles");
// From driver.mjs's package root, which is found from the module (or, under
@@ -67,6 +67,22 @@ export const REPO_ROOT = path.dirname(/* turbopackIgnore: true */ UMTOOL_DIR);
/** The executor every step runs. */
export const CHAIN_RUN = path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "lib", "report", "chain-run.mjs");
+/**
+ * The projects root the settings name (`settings.generation.projectsRoot`,
+ * release 27 S6), read from the checkout's settings.json (`SETTINGS_FILE`
+ * overrides) — `~` expanded; blank, absent or unreadable = DEFAULT_PROJECTS_ROOT.
+ */
+export function configuredProjectsRoot(settingsFile = process.env.SETTINGS_FILE ?? path.join(/* turbopackIgnore: true */ REPO_ROOT, "settings.json")) {
+ try {
+ const v = JSON.parse(readFileSync(/* turbopackIgnore: true */ settingsFile, "utf8"))?.generation?.projectsRoot;
+ if (typeof v !== "string" || !v.trim()) return DEFAULT_PROJECTS_ROOT;
+ const s = v.trim();
+ return s === "~" ? os.homedir() : s.startsWith("~/") ? path.join(/* turbopackIgnore: true */ os.homedir(), s.slice(2)) : s;
+ } catch {
+ return DEFAULT_PROJECTS_ROOT;
+ }
+}
+
const ID_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;
/** `<projectsRoot>/<id>/i<n>/` (common/lib/report/iterations.ts projectOf). */
@@ -121,7 +137,7 @@ export function readIterationRecord(articlesDir, article, n) {
* @returns {import("../trim").Step[]}
*/
export function chainSteps(o) {
- const projectsRoot = o.projectsRoot ?? DEFAULT_PROJECTS_ROOT;
+ const projectsRoot = o.projectsRoot ?? configuredProjectsRoot();
chainProject(projectsRoot, o.article, o.n);
const start = o.start === undefined ? CHAIN_STEP_NAMES[0] : o.start;
if (start === null) return [];
diff --git a/umtool/lib/report/chain.test.mjs b/umtool/lib/report/chain.test.mjs
@@ -14,8 +14,10 @@ import { fileURLToPath } from "node:url";
import {
CHAIN_RUN,
CHAIN_STEP_NAMES,
+ DEFAULT_PROJECTS_ROOT,
REPO_ROOT,
chainProject,
+ configuredProjectsRoot,
chainStart,
chainSteps,
chainWindows,
@@ -136,3 +138,19 @@ test("planChain: the record, the resume point and the steps; a queued iteration
assert.throws(() => planChain({ articlesDir: articles, article: "art", n: 2 }), /i2 is queued/);
assert.throws(() => planChain({ articlesDir: articles, article: "art", n: 7 }), /has no iteration i7/);
});
+
+test("the projects root comes from settings.generation.projectsRoot (release 27 S6), else the default", () => {
+ const dir = mkdtempSync(path.join(os.tmpdir(), "chain-settings-"));
+ try {
+ const file = path.join(dir, "settings.json");
+ assert.equal(configuredProjectsRoot(path.join(dir, "absent.json")), DEFAULT_PROJECTS_ROOT);
+ writeFileSync(file, JSON.stringify({ generation: { projectsRoot: "" } }));
+ assert.equal(configuredProjectsRoot(file), DEFAULT_PROJECTS_ROOT);
+ writeFileSync(file, JSON.stringify({ generation: { projectsRoot: "/srv/projects" } }));
+ assert.equal(configuredProjectsRoot(file), "/srv/projects");
+ writeFileSync(file, JSON.stringify({ generation: { projectsRoot: "~/elsewhere" } }));
+ assert.equal(configuredProjectsRoot(file), path.join(os.homedir(), "elsewhere"));
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});