commit d612a6752e4ccf3963c970e675d955a875d40638
parent c265febaa465fd40e898db2e6d0a8a7926b4edc0
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 13 Oct 2026 14:16:05 -0400
Merge r27/migrate-docs: release 27 S10 — import-local-runs (dry run) and the docs
Diffstat:
15 files changed, 1495 insertions(+), 24 deletions(-)
diff --git a/AGENTS.md b/AGENTS.md
@@ -102,11 +102,11 @@ pnpm 11 may install first after a pull, and that output goes to stdout either wa
build off disk. The server never writes to an archive — `fetch_clip` asks the editor,
and the editor writes.
-**Register it as `archilyzer`.** `.claude/commands/{ask,sweep}.md` are tracked in git
-and call `mcp__archilyzer__ask_plan` / `mcp__archilyzer__sweep_plan`. That tool name
-embeds the server name as registered on this machine, so any other name silently breaks
-both commands. Either use `archilyzer` or edit the `mcp__<name>__` prefix in those two
-files.
+**Register it as `archilyzer`.** `.claude/commands/{ask,sweep,gen}.md` are tracked in
+git and call `mcp__archilyzer__ask_plan` / `mcp__archilyzer__sweep_plan` /
+`mcp__archilyzer__generate`. That tool name embeds the server name as registered on this
+machine, so any other name silently breaks all three commands. Either use `archilyzer` or
+edit the `mcp__<name>__` prefix in those three files.
**The corpus discipline lives in `mcp/src/instructions.ts`, not in prose.** Citation
format, extractor budget, base-link expansion and the coverage rule are returned *by
@@ -114,7 +114,9 @@ the `*_plan` tools as a plan an agent then follows*. Fix guidance there, not by
another markdown file that will drift from it.
Use `/ask` for a question answered in the conversation and `/sweep` for a cited report
-written to a file.
+written to a file. `/gen` runs a generation task where `settings.generation` routes it (the
+editor's Claude API or local model, or this session) and reviews what it made;
+[OPERATING.md](OPERATING.md), "Generate and iterate".
**Running an archive — adding channels, syncing, importing, transcribing, tagging,
reports, publishing — is [OPERATING.md](OPERATING.md)**: recipes over `pnpm ops` (the
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -35,6 +35,7 @@ Run from the repo root (in the container: `docker compose exec editor pnpm archi
| `archilyzer reports verify-quotes` | `<report.json> \| --article <articleId>` | \[--json\] every video, audio and post quote of one report against its record with compose's own check: the best score and track, and the en-orig track's score where the record has one — a quote that matches a served `en` rewrite and not en-orig is reported (exit 1 when any quote drifted) |
| `archilyzer reports attach-video` | `<report.json> <video> \| --article <articleId> <video>` | \[--poster <image>\] \[--caption <line>\] the report's video: remuxed (an H.264 mp4 under the limit) or encoded to fit the 24 MiB publish limit, written beside report.json as video.mp4 with a poster (given, kept, or a frame of the video), and `video` set in report.json (an article's through the article registry) |
| `archilyzer reports iterations` | `<articleId> [--json]` | an article's iterations (transcripts/reports/<id>/iterations/): each one's kind, model, status, cost, lineage and what it revised or copied, the current article and current video marked (exit 1 when an iteration.json is unsound; 2 for no such article) |
+| `archilyzer reports import-local-runs` | `[--apply] [--runs <dir>] [--only <run,…>] [--move-projects] [--generation <file>]` | ONE-OFF (release 27): the stopgap's kept runs (--runs: its directory, default ~/reports/local-reports; --only: those runs, default piratesoftware-ai-friends and api-shondo-recent) become i1 of their article through the iterations store — made current only when the run's report.json is the article's; a run with no article becomes an article in the making — and each video project is copied (--move-projects: moved) to the generation projects root; ~/.config/archilyzer/generation.json, when there is one, becomes settings.generation's routes and models. Lists the stopgap's test runs, projects and drafts to delete after the operator's OK (deletes nothing). A dry run printing the plan unless --apply (exit 1 when a run is refused) |
| `archilyzer gen policy` | `[--json]` | the generation policy: where each task runs (code = Claude Code, api = the Claude API, local = the local model), the models, the caps and the day's Claude API spend — from the editor, or settings.json when none answers |
| `archilyzer gen preset` | `<code\|balanced\|api\|local>` | route every generation task by a preset (its routes are written; settings.generation.routes) |
| `archilyzer gen set` | `<task> <code\|api\|local>` | route one generation task (sweep, revise-report, revise-video, narrate, research) |
diff --git a/OPERATING.md b/OPERATING.md
@@ -148,6 +148,110 @@ pnpm ops reports-export --json '{"siteId":"example-site","formats":["html","md"
`pnpm archilyzer reports export <siteId>`.
- One cited moment's media, from an agent: the MCP's `fetch_clip`.
+## Generate and iterate
+
+```sh
+pnpm ops report-draft --json '{"task":"sweep","article":"example-article","question":"What does she say about the shop?","channels":["example"]}' --wait
+pnpm ops report-draft --json '{"task":"revise-report","article":"example-article","iteration":1,"feedback":"Drop the second finding."}' --wait
+pnpm ops report-draft --json '{"task":"revise-video","article":"example-article","iteration":2,"feedback":"Trim the opening clip."}' --wait
+pnpm ops report-draft --json '{"task":"narrate","article":"example-article","iteration":3}' --wait
+pnpm ops report-draft --json '{"task":"sweep","article":"example-article","copyOf":1,"model":"qwen3:8b"}'
+pnpm ops job cancel <jobId>
+pnpm archilyzer reports iterations example-article
+umtool chain example-article 3
+```
+
+- In umtool: `/articles/new` starts an article with a sweep or with research (question, channels, dates, model,
+ cap; research takes an autonomy, defaulted from the settings, and needs no channel); the article's **Iterations**
+ tab (`/articles/<id>?tab=iterations`) lists its iterations and runs the rest (**New iteration**, **Copy with
+ model**, **Narrate**, **Cancel**, **Make the video**, **Use this iteration**); `/articles/<id>/compare?a=&b=`
+ puts two side by side. The pages: [umtool/docs/sites.md](umtool/docs/sites.md).
+- Each generation is an **iteration** of the article, `i1`, `i2`, … in `transcripts/reports/<id>/iterations/<n>/`,
+ never published ([REPORT.md](REPORT.md), "Iterations"). The article's `report.json` changes only when you choose
+ **Use this iteration**. An article with iterations and no `report.json` is in the making: not listed, not a
+ draft.
+- `report-draft` is a job on `draft:api` (a Claude model) or `draft:local` (the local model). Its log ends with
+ `@@report-draft {article, iteration, task, status, summary, usd, minutes}`. A sweep makes a new iteration; a
+ revision makes one from the iteration it names and your feedback; `copyOf` runs an iteration again on another
+ `model`; a narration is a step on a done iteration. The model is the one named, else the task's route. The
+ corpus is `source`, else `build`, else the newest build that holds the channels.
+- Every quote a model writes must be the record's words within 90 s of its link, or the finding is dropped. Links
+ cite the archive, never the platform.
+- **Make the video** (or `umtool chain <id> <n>`) runs ten steps over an iteration, each recorded in it: make it
+ current, fetch the cited windows, prepare `--only`, capture its posts, the manifest, the voices, the video, the
+ podcast, attach, dedupe. A re-run resumes at the first step not done. The project is
+ `<projectsRoot>/<id>/i<n>/` (default `~/reports/articles`), off the corpus disk.
+
+**The policy** is `settings.generation`: where each task runs (`code` = Claude Code, `api` = the Claude API,
+`local` = the local model), the models, the caps.
+
+```sh
+pnpm archilyzer gen policy
+pnpm archilyzer gen preset balanced
+pnpm archilyzer gen set narrate local
+pnpm archilyzer gen run sweep "What does she say about the shop?" --article example-article --channels example --wait
+pnpm ops get generation-usage
+```
+
+- The presets: `code` (everything in Claude Code), `balanced` (sweeps in Claude Code, report revisions and research
+ on the API, video revisions and narration local), `api`, `local`. Choosing one writes its routes; the panel on
+ `/articles/new` writes the same settings.
+- `gen run` exits 3 and runs nothing for a task routed to `code`. In Claude Code, `/gen` and the MCP's `generate`
+ run a routed task through the editor and review what it made; `generation_policy` reads the policy and moves it
+ when you ask. `/sweep` follows the policy too.
+- **Caps (USD, Claude API only):** a job's `maxUsd`, else $5 a sweep or research run, $2 a revision, $1 a narration;
+ never above `caps.max` ($10). The editor refuses a job once the day's API spend (UTC) reaches `caps.daily` ($20),
+ naming the day's total; a job already running stops at its own cap. The ledger is `.generation/usage.jsonl` in
+ the checkout. A local job has no dollar cap.
+- **The API key** is a file, never a setting: `settings.generation.apiKeyFile` (default
+ `~/.config/archilyzer/anthropic.env`), mode 600 (refused when group or others have any bit). `ANTHROPIC_API_KEY`
+ in the editor's environment wins. A key typed where the path goes is refused and never stored. Nothing prints it.
+- **The local model** (`qwen3:8b`) shares the 8 GB GPU with transcription and TTS. A prompt is at most 8k tokens and
+ `num_ctx` at most 12k (a prompt over is refused before it is sent); a larger model does not fit. Each call waits
+ while a transcription or a synthesis runs, and the model is unloaded when its job ends. A local sweep is the
+ code-driven pipeline (the model proposes terms, judges, extracts and groups; code reads, cites and checks). It
+ reads the web through the editor's paced `web-search` / `web-fetch`; a Claude model uses its own web search.
+- The stopgap's kept runs (`~/reports/local-reports`) are imported once by
+ `pnpm archilyzer reports import-local-runs` (a dry run; `--apply` writes).
+
+## Research runs
+
+```sh
+pnpm ops report-draft --json '{"task":"research","article":"example-article","question":"Where did the shop story start?","autonomy":"propose"}' --wait
+pnpm ops research-approve --json '{"article":"example-article","iteration":1}'
+pnpm ops research-approve --json '{"article":"example-article","iteration":1,"ids":["p01","p03"],"approve":true}'
+pnpm ops research-approve --json '{"article":"example-article","iteration":1,"ids":["p02"],"approve":false,"note":"wrong channel"}'
+pnpm ops report-draft --json '{"task":"sweep","article":"example-article","iteration":1}' --wait
+```
+
+- A research run searches the corpus, the web and archive.org (an item's file list included), then proposes the
+ acquisitions it needs, each with its reason, evidence links and estimated size: an archive.org import, a video, a
+ new channel, posts (a walk, a capture, one post by URL), a transcription, a priority bump, persisting a video. They
+ are kept in the iteration's `proposals.json`.
+- **Autonomy**, per run (default `settings.generation.research.autonomy`, `propose`):
+ - `propose`: every acquisition waits for your yes or no.
+ - `limits`: an acquisition into an existing channel under the caps runs at once; a new channel or a post walk
+ waits when its setting says so; a priority bump always waits.
+ - `auto`: everything runs, until a cap.
+- **Limits** (`settings.generation.research`): `maxItemsPerRun` 20, `maxGbPerRun` 5, `maxTranscribeHours` 6,
+ `newChannelsNeedApproval`, `postWalksNeedApproval`. A proposal past a cap, or of unknown size, waits in every
+ mode.
+- **Approve or reject** in umtool: the run's queue in the Iterations tab shows each acquisition (what it fetches,
+ why, its evidence links, its estimate, why it waits) with **Yes** and **No** (an optional reason) on each that
+ waits, and an approved one's editor job as it runs. Or with `research-approve`. A yes runs it through the
+ editor's own action, past the run's autonomy and caps. With no ids it answers the run's state. It is refused
+ while the run's job is still going.
+- **Phases:** `discover` (the job runs), `wait` (a proposal waits for you, or an acquisition's job has not ended),
+ `ready` (nothing pending), `continued`. Each read refreshes the acquisitions from their jobs.
+- **Continue** (umtool's **Continue into a sweep**, shown once the run is done and nothing is pending) is a sweep
+ with `"iteration"` naming the research run: its question, over its channels and every
+ channel an acquisition wrote into. It is refused while the run waits, unless `"force": true`. A channel on no site
+ is in no build: put it on a site and build before continuing. Nothing continues on its own.
+- **The standing rules hold in every mode**, and a proposal that breaks one is refused: a new channel is created on
+ no site; an X channel never goes on a site; a Twitch VOD URL is refused (look for the stream on archive.org); every fetch goes through the
+ editor's queues, holds and cooldowns (one stream, real gaps, backing off on a 429), never yt-dlp or gallery-dl by
+ hand. Keep a local-only subject on no site.
+
## Publish
```sh
@@ -181,4 +285,6 @@ pnpm archilyzer publish build example-site --out /srv/example-private
transcribe-bucket, fetch-posts, import-video), follows it (`get_job`), reports what a channel holds by date and
where the gaps are (`channel_coverage`), and reads a video not yet published (`get_transcript`). The operator's
notes: `notes` (with `UMTOOL_URL`). Settings, storage and deletes stay `pnpm ops`.
+- `generation_policy` and `generate` route a generation task by the policy ("Generate and iterate" above); `/gen`
+ wraps them.
- Tools and their arguments: [mcp/README.md](mcp/README.md).
diff --git a/REPORT.md b/REPORT.md
@@ -6,7 +6,7 @@ One cited report, format `"archilyzer-report"`, version 1, persisted as `report.
A report lives in one of two stores:
-- **An article** — `transcripts/reports/<reportId>/report.json`, published by the project homepage. `transcripts/reports/index.json` — `{"published": [ids]}` — is the published, ordered list; an article directory it does not name is a draft. An article's `audience` (below) says which homepage build carries it: the public one only `"public"` articles, the private one every published article. An article may cite any channel of the corpus.
+- **An article** — `transcripts/reports/<reportId>/report.json`, published by the project homepage. `transcripts/reports/index.json` — `{"published": [ids]}` — is the published, ordered list; an article directory it does not name is a draft. An article's `audience` (below) says which homepage build carries it: the public one only `"public"` articles, the private one every published article. An article may cite any channel of the corpus. An article may not be called `new` (umtool's `/articles/new` is a page).
- **A site's page** — `transcripts/sites/<siteId>/reports/<reportId>/report.json`, published by its site at `/pages/<reportId>/`: the site's `pages` list in `site.json` is the published, ordered list — see [SITE.md](SITE.md). A page cites the site's `channels` and `citedChannels`.
`index.json` and an article's `audience` are written ONLY through `common/lib/report/registry.ts` (`configureArticle`, `setPublished`, `setArticlesOrder`, `patchArticle`, `writeArticle`: locked, validated, atomic) and `pnpm ops articles-config` (`{"id", "audience"?, "published"?, "position"?}`), never by hand. Only a sound article (no problem below) is published; a patch may not add a problem to an article.
@@ -116,6 +116,30 @@ The shared vocabulary (`common/lib/report/verdicts.mjs` — the one copy; report
| `NOT_FOUND` | Not found | `#8b93a7` |
| `UNTESTABLE` | Untestable | `#7d8fd6` |
+## Iterations
+
+An article made or revised by a model keeps each generation as an **iteration**, `i1`, `i2`, … (`common/lib/report/iterations.ts`), in `transcripts/reports/<id>/iterations/<n>/`:
+
+| File | What |
+|---|---|
+| `iteration.json` | its kind (`sweep`, `revise-report`, `revise-video`, `research`), model, `parent` (the iteration it revises), `copyOf` (the iteration it repeats on another model), question or feedback, scope, status (`queued`, `running`, `done`, `failed`, `cancelled`), spend and tokens per model, ops applied and refused, minutes, checks, steps (narration, the video chain) and `projectDir` |
+| `report.json` | the report it made (a `revise-video` iteration has none: its report is its nearest ancestor's) |
+| `sweep.md` | the sweep's markdown |
+| `turns.jsonl` | the model's turns |
+| `proposals.json` | a research run's acquisitions |
+
+`iterations/current.json` names the iteration the article is, and the one its video is.
+
+- **Use this iteration** (umtool's Iterations tab) writes the article's `report.json` from a done iteration through the registry's writer: locked, validated, the article's `audience` and attached `video` kept. Nothing a generation runs writes the article's `report.json`; the next export records the change as the next Revision.
+- Iterations are never published: compose, the homepage and the site history read only the article's own files.
+- A directory with iterations and no `report.json` is an article **in the making**: the registry lists it neither as published nor as a draft until an iteration is made current.
+- An iteration's video project is off the corpus disk, in `<settings.generation.projectsRoot>/<id>/i<n>/` (blank: `~/reports/articles`).
+- `archilyzer reports iterations <id>` lists an article's iterations; `pnpm ops get iterations <id>` reads them from the editor.
+
+## Checking quotes
+
+`archilyzer reports verify-quotes <report.json> | --article <id>` checks every quote against its record as compose does (token recall, on every track) and names a quote that matches a served `en` rewrite but not `en-orig` (`en-orig-drift`). A quote that passes recall but is not verbatim (case, punctuation and curly quotes aside) within ±90 s of its cited second is **`inexact`**: a warning, printed and counted, that does not change the exit code; compose and publish do not use it. A GENERATED quote must pass that strict check: a finding whose quote fails it is dropped. The statuses: `ok`, `drift`, `en-orig-drift`, `inexact`, `missing-record`, `no-cues`, `missing-post`, `unreadable`.
+
## Making a report from what exists
`archilyzer reports convert <sweep|ask|manifest> <in> --out <report.json>` makes a report of a /sweep report (markdown: its `#` heading the title, each `##` section a section, each list item or paragraph that cites a claim), an /ask answer (its `[n @ mm:ss]` markers resolved against its sources) or a report-to-video manifest (chapter cards the sections, `claim` entries the claims, clips, stills and posts the citations), and writes it only when it validates. A /sweep or /ask citation carries one second: `--channels-dir <transcripts/channels>` widens it through the record's cues to whole sentences (else it is the second plus 10 s) and finds the channel that keeps a post cited by its platform link. `archilyzer reports to-manifest <report.json> --out <manifest.json>` goes the other way: a starter manifest — a title card, a chapter card per section, each claim's still and clips stamped with its verdict, its posts. The converters are `common/lib/report/convert*.ts`; the warnings say what a conversion left out.
diff --git a/common/bin/archilyzer.ts b/common/bin/archilyzer.ts
@@ -398,6 +398,13 @@ export const COMMANDS: Command[] = [
return (await import("./reports-iterations")).iterationsMain({ article, json: flags.json === true });
},
},
+ {
+ path: ["reports", "import-local-runs"],
+ usage:
+ "[--apply] [--runs <dir>] [--only <run,…>] [--move-projects] [--generation <file>] ONE-OFF (release 27): the stopgap's kept runs (--runs: its directory, default ~/reports/local-reports; --only: those runs, default piratesoftware-ai-friends and api-shondo-recent) become i1 of their article through the iterations store — made current only when the run's report.json is the article's; a run with no article becomes an article in the making — and each video project is copied (--move-projects: moved) to the generation projects root; ~/.config/archilyzer/generation.json, when there is one, becomes settings.generation's routes and models. Lists the stopgap's test runs, projects and drafts to delete after the operator's OK (deletes nothing). A dry run printing the plan unless --apply (exit 1 when a run is refused)",
+ flags: { apply: "boolean", runs: "string", only: "string", "move-projects": "boolean", generation: "string" },
+ run: async ({ flags }) => (await import("./reports-import-local-runs")).importRow(flags as Parameters<typeof import("./reports-import-local-runs").importRow>[0]),
+ },
// The generation balance (release 27 S9; bin/gen.ts): settings.generation
// through the editor's ops API, or settings.json when no editor answers.
{
diff --git a/common/bin/cli-docs.test.ts b/common/bin/cli-docs.test.ts
@@ -116,13 +116,15 @@ test("unknownCommandsIn names what no action, getter or command answers to", ()
"pnpm ops list",
"pnpm ops get channel x and pnpm ops get bogus",
"pnpm ops frobnicate --wait",
+ "pnpm ops job cancel <id> and pnpm ops job explode <id>",
"`pnpm archilyzer publish build <id>`, `pnpm archilyzer doctor`.",
"pnpm archilyzer publish destroy x",
].join("\n");
- const usage = OPS_USAGE.replace("pnpm ops list", "pnpm ops list\n pnpm ops get channel <slug>");
+ const usage = OPS_USAGE.replace("pnpm ops list", "pnpm ops list\n pnpm ops get channel <slug>\n pnpm ops job cancel|retry <id>...");
assert.deepEqual(unknownCommandsIn(md, cli, usage), [
"pnpm ops get bogus",
"pnpm ops frobnicate",
+ "pnpm ops job explode",
"pnpm archilyzer publish destroy x",
]);
});
diff --git a/common/bin/cli-docs.ts b/common/bin/cli-docs.ts
@@ -200,10 +200,16 @@ export function unknownCommandsIn(
): string[] {
const actions = new Set(opsActions(opsUsage));
const nouns = new Set([...opsUsage.matchAll(/pnpm ops get ([a-z][a-z-]*)/g)].map((m) => m[1]));
+ // `pnpm ops job <verb> <id>` (a /jobs row's button): the verbs its usage line lists.
+ const jobVerbs = new Set((/pnpm ops job ([a-z|-]+)/.exec(opsUsage)?.[1] ?? "").split("|").filter(Boolean));
const bad = new Set<string>();
for (const m of markdown.matchAll(/pnpm ops ([^\s`'"]+)(?:[ \t]+([^\s`'"]+))?/g)) {
const [, word, next] = m;
if (word.startsWith("<") || word === "list") continue;
+ if (word === "job") {
+ if (!next || !jobVerbs.has(next)) bad.add(`pnpm ops job ${next ?? ""}`.trim());
+ continue;
+ }
if (word === "get") {
if (!next || !nouns.has(next)) bad.add(`pnpm ops get ${next ?? ""}`.trim());
continue;
diff --git a/common/bin/reports-import-local-runs.test.ts b/common/bin/reports-import-local-runs.test.ts
@@ -0,0 +1,327 @@
+// `archilyzer reports import-local-runs` (release 27 S10; D9): the stopgap's
+// kept runs as iterations through the store, a dry run by default. A
+// synthetic stopgap tree and a temp corpus only — never the real runs.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test bin/reports-import-local-runs.test.ts
+
+import { after, test } from "node:test";
+import assert from "node:assert/strict";
+import { existsSync, linkSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+const ROOT = mkdtempSync(path.join(tmpdir(), "import-local-runs-"));
+Object.assign(process.env, {
+ TRANSCRIPTS_DIR: path.join(ROOT, "transcripts"),
+ SITES_DIR: path.join(ROOT, "transcripts", "sites"),
+ SETTINGS_FILE: path.join(ROOT, "settings.json"),
+ EXPORT_INDEX_DIR: path.join(ROOT, ".export-index"),
+});
+after(() => rmSync(ROOT, { recursive: true, force: true }));
+
+const { getPaths } = await import("../lib/paths");
+const { DEFAULT_GENERATION_SETTINGS } = await import("../lib/generationSettings");
+const { configureArticle, writeArticle } = await import("../lib/report/registry");
+const { currentIteration, readIteration, readIterationFile, readIterations } = await import("../lib/report/iterations");
+const imp = await import("./reports-import-local-runs");
+
+const paths = getPaths();
+const KIT = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "testing", "draft");
+const BASIC = JSON.parse(readFileSync(path.join(KIT, "reports", "basic.report.json"), "utf8")) as Record<string, unknown>;
+const SWEEP = readFileSync(path.join(KIT, "sweeps", "basic.md"), "utf8");
+
+const writeJson = (file: string, value: unknown) => {
+ mkdirSync(path.dirname(file), { recursive: true });
+ writeFileSync(file, JSON.stringify(value, null, 2));
+};
+const T0 = 1_790_000_000; // 2026-09-21
+
+// A stopgap run as the stopgap wrote it: run.json, sweep.md, report.json,
+// transcript.jsonl (+ ui.json when the UI started it).
+function stopgapRun(dir: string, name: string, o: { reportId: string; ui?: Record<string, unknown>; model?: string; transcript?: boolean }) {
+ const run = path.join(dir, "runs", name);
+ writeJson(path.join(run, "run.json"), {
+ question: "What does the baker say about the bakery?",
+ channels: ["synth-kitchen"],
+ source: "local:/somewhere/out",
+ model: o.model ?? "claude-sonnet-5-5",
+ extractor: "claude-haiku-4-5",
+ minutes: 1.5,
+ converted: true,
+ verified: true,
+ problems: [],
+ usd_estimate: 0.3,
+ by_model: {
+ "claude-sonnet-5-5": { calls: 4, input: 10, cache_write: 1000, cache_read: 4000, output: 500, usd: 0.25 },
+ "claude-haiku-4-5": { calls: 1, input: 20, cache_write: 0, cache_read: 0, output: 5, usd: 0.05 },
+ },
+ });
+ writeFileSync(path.join(run, "sweep.md"), SWEEP);
+ writeJson(path.join(run, "report.json"), { ...BASIC, id: o.reportId });
+ if (o.ui) writeJson(path.join(run, "ui.json"), o.ui);
+ if (o.transcript !== false) {
+ writeFileSync(
+ path.join(run, "transcript.jsonl"),
+ [
+ { kind: "start", question: "q", channels: ["synth-kitchen"], model: "claude-sonnet-5-5", extractor: "claude-haiku-4-5", max_usd: 5, t: T0 },
+ { kind: "turn", n: 0, stop: "tool_use", usage: { input_tokens: 2, output_tokens: 30 }, usd: 0.01, text: "", calls: ["enumerate_matches"], t: T0 + 5 },
+ { kind: "tool", name: "enumerate_matches", input: { query: "bakery" }, chars: 1234, error: false, t: T0 + 7 },
+ { kind: "turn", n: 1, stop: "end_turn", usage: { input_tokens: 3, output_tokens: 40 }, usd: 0.02, text: "Done.", calls: [], t: T0 + 20 },
+ { kind: "odd", what: "kept as is", t: T0 + 21 },
+ ]
+ .map((e) => JSON.stringify(e))
+ .join("\n") + "\n",
+ );
+ }
+ const end = new Date((T0 + 90) * 1000);
+ utimesSync(path.join(run, "run.json"), end, end);
+}
+
+function stopgapProject(dir: string, name: string) {
+ const p = path.join(dir, "videos", name);
+ mkdirSync(path.join(p, "out", "narration"), { recursive: true });
+ writeJson(path.join(p, "video.manifest.json"), { timeline: [] });
+ writeFileSync(path.join(p, "out", "narration", "a.wav"), Buffer.alloc(2000));
+ linkSync(path.join(p, "out", "narration", "a.wav"), path.join(p, "out", "narration", "b.wav"));
+ return p;
+}
+
+function options(stopgapDir: string, over: Partial<Parameters<typeof imp.importMain>[0]> = {}) {
+ return {
+ apply: false,
+ stopgapDir,
+ projectsRoot: path.join(ROOT, "projects"),
+ generationFile: path.join(stopgapDir, "generation.json"),
+ paths,
+ currentGeneration: () => structuredClone(DEFAULT_GENERATION_SETTINGS),
+ now: () => new Date("2026-10-13T12:00:00Z"),
+ ...over,
+ };
+}
+
+function capture() {
+ const lines: string[] = [];
+ return { text: () => lines.join("\n"), out: { log: (s: string) => lines.push(s), error: (s: string) => lines.push(s) } };
+}
+
+// Every file under a directory with its size and mtime: what "wrote nothing" compares.
+function snapshot(dir: string): string[] {
+ const out: string[] = [];
+ const walk = (d: string) => {
+ if (!existsSync(d)) return;
+ for (const e of readdirSync(d, { withFileTypes: true })) {
+ const p = path.join(d, e.name);
+ if (e.isDirectory()) walk(p);
+ else {
+ const s = statSync(p);
+ out.push(`${path.relative(dir, p)} ${s.size} ${s.mtimeMs}`);
+ }
+ }
+ };
+ walk(dir);
+ return out.sort();
+}
+
+// The world: an article the registry has (its report the run's, a video
+// attached), a run with no article, the test runs and drafts.
+const SG = path.join(ROOT, "stopgap");
+stopgapRun(SG, "synth-friends", { reportId: "synth-friends", ui: { id: "synth-friends", createdAt: new Date(T0 * 1000).toISOString() } });
+stopgapProject(SG, "synth-friends");
+stopgapRun(SG, "api-synth-recent", { reportId: "api-test-synth-recent", model: "claude-opus-5-5" });
+stopgapRun(SG, "ui-test-synth-cats", { reportId: "ui-test-synth-cats" });
+stopgapRun(SG, "api-synth-other", { reportId: "api-synth-other" });
+stopgapProject(SG, "local-test-synth-baking");
+await writeArticle({ ...BASIC, id: "synth-friends", video: { src: "video.mp4", poster: "poster.jpg" } });
+await configureArticle("synth-friends", { audience: "public" });
+await writeArticle({ ...BASIC, id: "local-test-synth-baking" });
+
+test("the transcript in S1's shape: start a note, turn a response, tool a tool entry, the rest kept", () => {
+ const text = readFileSync(path.join(SG, "runs", "synth-friends", "transcript.jsonl"), "utf8");
+ const t = imp.mapStopgapTurns(text + "not json\n", "synth-friends");
+ assert.equal(t.mapped, 4);
+ assert.equal(t.kept, 2);
+ const [note, start, r0, tool, r1, odd, bad] = t.entries as Record<string, unknown>[];
+ assert.match(String(note.text), /imported from the stopgap run synth-friends/);
+ assert.equal(start.kind, "note");
+ assert.match(String(start.text), /model claude-sonnet-5-5, extractor claude-haiku-4-5, cap \$5/);
+ assert.equal(r0.kind, "response");
+ assert.equal(r0.provider, "api");
+ assert.equal(r0.stopReason, "tool_use");
+ assert.deepEqual(r0.content, [{ type: "tool_use", name: "enumerate_matches" }]);
+ assert.equal(r0.at, new Date((T0 + 5) * 1000).toISOString());
+ assert.deepEqual(
+ { kind: tool.kind, turn: tool.turn, name: tool.name, chars: tool.chars, result: tool.result, ms: tool.ms },
+ { kind: "tool", turn: 0, name: "enumerate_matches", chars: 1234, result: "", ms: 2000 },
+ );
+ assert.deepEqual(r1.content, [{ type: "text", text: "Done." }]);
+ assert.equal(odd.kind, "odd");
+ assert.match(String(bad.text), /not JSON/);
+});
+
+test("usage and checks from run.json", () => {
+ assert.deepEqual(imp.usageFromRun({ m: { calls: 2, input: 1, output: 3, cache_read: 4, cache_write: 5, usd: 0.5 } }), {
+ m: { usd: 0.5, inputTokens: 1, outputTokens: 3, cacheReadTokens: 4, cacheWriteTokens: 5, calls: 2 },
+ });
+ assert.deepEqual(imp.checksFromRun({ converted: true, verified: true, problems: ["c03: drift"] }), [
+ { name: "convert", ok: true },
+ { name: "verify-quotes", ok: false, detail: "c03: drift" },
+ ]);
+});
+
+test("the dry run prints the plan and writes nothing — not the corpus, not the stopgap, not the projects root", async () => {
+ const before = [snapshot(ROOT)];
+ const c = capture();
+ const code = await imp.importMain(options(SG, { only: ["synth-friends", "api-synth-recent"] }), c.out);
+ assert.equal(code, 0, c.text());
+ assert.deepEqual([snapshot(ROOT)], before);
+ const text = c.text();
+ assert.match(text, /DRY RUN — nothing is written/);
+ assert.match(text, /synth-friends → i1 of the article "synth-friends" \(a draft, public\)/);
+ assert.match(text, /report\.json IS the article's .* i1 made current for the article/);
+ assert.match(text, /video project: .*synth-friends \(.*, 3 files\) → copied to .*projects\/synth-friends\/i1/);
+ assert.match(text, /i1 made current for the video/);
+ assert.match(text, /api-synth-recent → i1 of "api-synth-recent", a NEW article in the making/);
+ assert.match(text, /its id "api-test-synth-recent" becomes "api-synth-recent"/);
+ assert.match(text, /turns\.jsonl \(6 lines: 4 in S1's shape, 1 kept as they were, 1 import note\)/);
+ assert.match(text, /generation\.json: none at/);
+ // The test runs, projects and drafts are listed, never touched.
+ assert.match(text, /To delete after the operator's OK .* 3 item\(s\)/);
+ assert.match(text, /runs\/ui-test-synth-cats/);
+ assert.match(text, /videos\/local-test-synth-baking/);
+ assert.match(text, /reports\/local-test-synth-baking/);
+ assert.match(text, /Neither imported nor named for deletion \(kept\):\n.*runs\/api-synth-other/);
+ assert.match(text, /dry run: nothing written/);
+});
+
+test("a hard-linked file is counted once", async () => {
+ const p = path.join(SG, "videos", "synth-friends");
+ const size = await imp.dirSize(p);
+ assert.equal(size.files, 3);
+ assert.equal(size.bytes, 2000 + statSync(path.join(p, "video.manifest.json")).size);
+});
+
+test("generation.json: the dry run prints the patch; apply writes routes and models through the writer", async () => {
+ const sg = path.join(ROOT, "stopgap-gen");
+ writeJson(path.join(sg, "generation.json"), {
+ preset: "custom",
+ routes: { sweep: "api", "revise-report": "api", "revise-video": "local", narrate: "local", bogus: "api" },
+ models: { api: "claude-opus-5-5", local: "qwen3:8b" },
+ });
+ mkdirSync(path.join(sg, "runs"), { recursive: true });
+ const c = capture();
+ assert.equal(await imp.importMain(options(sg, { only: ["nothing-here"] }), c.out), 1);
+ assert.match(c.text(), /nothing-here: REFUSED — no run directory/);
+ assert.match(c.text(), /patch: routes\.sweep: code → api; models\.api: claude-sonnet-5-5 → claude-opus-5-5/);
+ assert.match(c.text(), /not carried: routes\.bogus \(no such task\)/);
+
+ const written: unknown[] = [];
+ const c2 = capture();
+ await imp.importMain(
+ options(sg, {
+ only: ["nothing-here"],
+ apply: true,
+ generationWriter: async (patch) => {
+ written.push(patch);
+ return "a fake writer";
+ },
+ }),
+ c2.out,
+ );
+ assert.equal(written.length, 1);
+ const patch = written[0] as { routes: Record<string, string>; models: Record<string, string> };
+ assert.equal(patch.routes.sweep, "api");
+ assert.equal(patch.routes.research, DEFAULT_GENERATION_SETTINGS.routes.research);
+ assert.deepEqual(patch.models, { ...DEFAULT_GENERATION_SETTINGS.models, api: "claude-opus-5-5" });
+ assert.match(c2.text(), /settings\.generation written through a fake writer/);
+});
+
+test("apply: the article's i1 made current for the article and the video; the run with no article an article in the making", async () => {
+ const c = capture();
+ const code = await imp.importMain(options(SG, { only: ["synth-friends", "api-synth-recent"], apply: true }), c.out);
+ assert.equal(code, 0, c.text());
+
+ const it = await readIteration("synth-friends", 1);
+ assert.ok(it);
+ assert.equal(it.kind, "sweep");
+ assert.equal(it.status, "done");
+ assert.equal(it.model, "claude-sonnet-5-5");
+ assert.equal(it.question, "What does the baker say about the bakery?");
+ assert.deepEqual(it.scope, { channels: ["synth-kitchen"] });
+ assert.equal(it.usage["claude-sonnet-5-5"].usd, 0.25);
+ assert.equal(it.usage["claude-haiku-4-5"].calls, 1);
+ assert.equal(it.minutes, 1.5);
+ assert.equal(it.createdAt, new Date(T0 * 1000).toISOString());
+ assert.equal(it.endedAt, new Date((T0 + 90) * 1000).toISOString());
+ assert.equal((it.imported as { run: string }).run, "synth-friends");
+ const project = path.join(ROOT, "projects", "synth-friends", "i1");
+ assert.equal(it.projectDir, project);
+ assert.ok(existsSync(path.join(project, "video.manifest.json")));
+ assert.ok(existsSync(path.join(SG, "videos", "synth-friends")), "copied, not moved");
+ assert.equal(await readIterationFile("synth-friends", 1, "sweep.md"), SWEEP);
+ assert.equal(JSON.parse((await readIterationFile("synth-friends", 1, "report.json"))!).id, "synth-friends");
+ const turns = (await readIterationFile("synth-friends", 1, "turns.jsonl"))!.trim().split("\n");
+ assert.equal(turns.length, 6);
+ const cur = await currentIteration("synth-friends");
+ assert.equal(cur.report, 1);
+ assert.equal(cur.video, 1);
+ // The article keeps its audience and its video.
+ const art = JSON.parse(readFileSync(path.join(paths.articlesDir, "synth-friends", "report.json"), "utf8"));
+ assert.equal(art.audience, "public");
+ assert.deepEqual(art.video, { src: "video.mp4", poster: "poster.jpg" });
+
+ const pend = await readIteration("api-synth-recent", 1);
+ assert.ok(pend);
+ assert.equal(pend.model, "claude-opus-5-5");
+ assert.equal(JSON.parse((await readIterationFile("api-synth-recent", 1, "report.json"))!).id, "api-synth-recent");
+ assert.equal(existsSync(path.join(paths.articlesDir, "api-synth-recent", "report.json")), false, "an article in the making has no report.json");
+ assert.equal((await currentIteration("api-synth-recent")).report, null);
+
+ // Run again: nothing to do.
+ const c2 = capture();
+ assert.equal(await imp.importMain(options(SG, { only: ["synth-friends", "api-synth-recent"], apply: true }), c2.out), 0);
+ assert.match(c2.text(), /synth-friends: already imported as "synth-friends" i1 — nothing to do/);
+ assert.equal((await readIterations("synth-friends")).iterations.length, 1);
+});
+
+test("a run whose report.json is not the article's: imported, NOT made current; the article unchanged", async () => {
+ const sg = path.join(ROOT, "stopgap-differs");
+ stopgapRun(sg, "synth-differs", { reportId: "synth-differs" });
+ await writeArticle({ ...BASIC, id: "synth-differs", title: "Another title" });
+ const before = readFileSync(path.join(paths.articlesDir, "synth-differs", "report.json"), "utf8");
+ const c = capture();
+ assert.equal(await imp.importMain(options(sg, { only: ["synth-differs"], apply: true }), c.out), 0, c.text());
+ assert.match(c.text(), /report\.json is NOT the article's — differs in: title → i1 is NOT made current/);
+ assert.equal((await readIteration("synth-differs", 1))?.status, "done");
+ assert.equal((await currentIteration("synth-differs")).report, null);
+ assert.equal(readFileSync(path.join(paths.articlesDir, "synth-differs", "report.json"), "utf8"), before);
+});
+
+test("refusals: an article with iterations already, a taken project place, a run with no run.json", async () => {
+ const sg = path.join(ROOT, "stopgap-refuse");
+ stopgapRun(sg, "synth-friends", { reportId: "synth-friends", transcript: false });
+ writeJson(path.join(sg, "runs", "synth-taken", "ui.json"), {});
+ stopgapRun(sg, "synth-taken", { reportId: "synth-taken" });
+ stopgapProject(sg, "synth-taken");
+ mkdirSync(path.join(ROOT, "projects", "synth-taken", "i1"), { recursive: true });
+ writeFileSync(path.join(ROOT, "projects", "synth-taken", "i1", "x"), "x");
+ mkdirSync(path.join(sg, "runs", "synth-bare"), { recursive: true });
+ const c = capture();
+ assert.equal(await imp.importMain(options(sg, { only: ["synth-friends", "synth-taken", "synth-bare"], apply: true }), c.out), 1);
+ const text = c.text();
+ // synth-friends was imported from another stopgap dir (same run name): already imported.
+ assert.match(text, /synth-friends: already imported/);
+ assert.match(text, /synth-taken: REFUSED — the project's place .* is taken/);
+ assert.match(text, /synth-bare: REFUSED — run\.json is absent/);
+ assert.equal((await readIterations("synth-taken")).iterations.length, 0);
+});
+
+test("--move-projects moves the project", async () => {
+ const sg = path.join(ROOT, "stopgap-move");
+ stopgapRun(sg, "synth-moved", { reportId: "synth-moved" });
+ stopgapProject(sg, "synth-moved");
+ const c = capture();
+ assert.equal(await imp.importMain(options(sg, { only: ["synth-moved"], apply: true, moveProjects: true }), c.out), 0, c.text());
+ assert.equal(existsSync(path.join(sg, "videos", "synth-moved")), false);
+ assert.ok(existsSync(path.join(ROOT, "projects", "synth-moved", "i1", "out", "narration", "b.wav")));
+});
diff --git a/common/bin/reports-import-local-runs.ts b/common/bin/reports-import-local-runs.ts
@@ -0,0 +1,786 @@
+// `archilyzer reports import-local-runs [--apply] [--runs <dir>] [--only <run,…>]
+// [--move-projects]` (release 27 S10; plans/release-27.md D9) — the stopgap's
+// kept runs (`~/reports/local-reports/runs/<name>/`, and its video projects in
+// `videos/<name>/`) become ITERATIONS, through the iterations store
+// (lib/report/iterations.ts), never by hand. A DRY RUN unless `--apply`: it
+// prints what it would do and writes nothing.
+//
+// A run becomes its article's `i1`, kind `sweep`:
+// - the article is `ui.json`'s `id`, else the run's name;
+// - iteration.json from run.json: the model, the question, the channels, the
+// spend per model, the minutes, the checks; `imported` names the run;
+// - report.json (its `id` set to the article's), sweep.md, and turns.jsonl —
+// the stopgap's transcript.jsonl in S1's transcript shape where an entry
+// maps (`start` → a note, `turn` → a response, `tool` → a tool entry),
+// else kept as it is;
+// - the video project, when the stopgap has one, copied (or moved, with
+// `--move-projects`) to `projectOf(projectsRoot, id, 1)` and recorded as
+// the iteration's `projectDir`.
+// An ARTICLE THE REGISTRY HAS: i1 is made current (makeCurrent) only when the
+// run's report.json is the article's (`audience` and `video` aside), and
+// current for the video when the article has a video attached. A RUN WITH NO
+// ARTICLE becomes an article in the making: i1, never made current, so nothing
+// reaches the published list or the drafts until the operator chooses.
+//
+// The stopgap's routing policy, `~/.config/archilyzer/generation.json`, when
+// there is one, becomes `settings.generation.{routes, models}` through the
+// editor's settings writer (`POST /api/ops/settings`), or settings.json's
+// (`writeSettings`) when nothing listens at the editor's URL.
+//
+// The dry run also lists the stopgap's TEST runs, projects and registry
+// drafts (D9: `ui-test-*`, `shondo-*`, `local-test-*`) with their sizes, to be
+// deleted after the operator's OK. This command deletes nothing.
+//
+// Exit 0 when every run is importable (dry run) or imported (apply), or was
+// imported before; 1 when any is refused or fails; 2 for a usage error.
+
+import { cp, lstat, mkdir, readdir, readFile, rename, rm, stat } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { pathToFileURL } from "node:url";
+import type { GenerationRoute, GenerationSettings } from "../lib/generationSettings";
+import { GENERATION_ROUTES, GENERATION_TASKS } from "../lib/generationSettings";
+import type { Paths } from "../lib/paths";
+import {
+ createIteration,
+ iterationLabel,
+ makeCurrent,
+ projectOf,
+ readIterations,
+ setCurrentVideo,
+ updateIteration,
+ writeIterationFile,
+ type IterationCheck,
+ type IterationUsage,
+} from "../lib/report/iterations";
+import { articleDir, isReportAudience, listArticleDirs, listPendingArticles, readArticleState, RESERVED_ARTICLE_IDS } from "../lib/report/registry";
+import { isReportId } from "../lib/report/schema";
+import { parseReport } from "../lib/report/validate";
+
+type Out = { log: (s: string) => void; error: (s: string) => void };
+type StorePaths = Pick<Paths, "articlesDir" | "exportIndexDir">;
+
+// D9: the runs imported when --only names none.
+export const DEFAULT_IMPORT_RUNS = ["piratesoftware-ai-friends", "api-shondo-recent"] as const;
+// D9: the stopgap's test runs, projects and registry drafts — listed for
+// deletion after the operator's OK, never deleted here.
+export const TEST_RUN_PREFIXES = ["ui-test-", "shondo-", "local-test-"] as const;
+export const DEFAULT_STOPGAP_DIR = path.join(os.homedir(), "reports", "local-reports");
+export const DEFAULT_GENERATION_FILE = path.join(os.homedir(), ".config", "archilyzer", "generation.json");
+
+const isTestName = (name: string) => TEST_RUN_PREFIXES.some((p) => name.startsWith(p));
+
+// ─── The stopgap's files ───
+
+type StopgapRunJson = {
+ question?: unknown;
+ channels?: unknown;
+ model?: unknown;
+ extractor?: unknown;
+ minutes?: unknown;
+ converted?: unknown;
+ verified?: unknown;
+ problems?: unknown;
+ by_model?: unknown;
+};
+
+async function readJson(file: string): Promise<{ ok: true; value: unknown } | { ok: false; why: string }> {
+ let text: string;
+ try {
+ text = await readFile(file, "utf8");
+ } catch (err) {
+ return { ok: false, why: (err as NodeJS.ErrnoException).code === "ENOENT" ? "absent" : (err as Error).message };
+ }
+ try {
+ return { ok: true, value: JSON.parse(text) };
+ } catch {
+ return { ok: false, why: "not JSON" };
+ }
+}
+
+const obj = (v: unknown): Record<string, unknown> => (v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : {});
+const num = (v: unknown): number | undefined => (typeof v === "number" && Number.isFinite(v) ? v : undefined);
+const str = (v: unknown): string | undefined => (typeof v === "string" && v.trim() ? v.trim() : undefined);
+const nonNeg = (v: unknown) => Math.max(0, Math.round(num(v) ?? 0));
+
+// run.json's `by_model` as the iteration's `usage`.
+export function usageFromRun(byModel: unknown): Record<string, IterationUsage> {
+ const out: Record<string, IterationUsage> = {};
+ for (const [model, raw] of Object.entries(obj(byModel))) {
+ const m = obj(raw);
+ out[model] = {
+ usd: Math.max(0, num(m.usd) ?? 0),
+ inputTokens: nonNeg(m.input),
+ outputTokens: nonNeg(m.output),
+ cacheReadTokens: nonNeg(m.cache_read),
+ cacheWriteTokens: nonNeg(m.cache_write),
+ calls: nonNeg(m.calls),
+ };
+ }
+ return out;
+}
+
+// run.json's convert and verify results as the iteration's checks.
+export function checksFromRun(run: StopgapRunJson): IterationCheck[] {
+ const problems = Array.isArray(run.problems) ? run.problems.map(String) : [];
+ const checks: IterationCheck[] = [];
+ if (typeof run.converted === "boolean") checks.push({ name: "convert", ok: run.converted });
+ if (typeof run.verified === "boolean" || problems.length) {
+ checks.push({
+ name: "verify-quotes",
+ ok: run.verified !== false && problems.length === 0,
+ ...(problems.length ? { detail: problems.slice(0, 3).join("; ") } : {}),
+ });
+ }
+ return checks;
+}
+
+// THE STOPGAP'S TRANSCRIPT IN S1'S SHAPE (lib/llm/agent.ts TranscriptEntry)
+// where an entry maps: `start` → a note (its settings kept under `stopgap`),
+// `turn` → a response (the text, the tool names it called, usage, USD), `tool`
+// → a tool entry (the stopgap kept no result: `result` is empty, `chars` its
+// length). Anything else is kept as it is. A line that is not JSON is kept as
+// a note naming it.
+export function mapStopgapTurns(text: string, run: string): { entries: unknown[]; mapped: number; kept: number } {
+ const entries: unknown[] = [];
+ let mapped = 0;
+ let kept = 0;
+ let turn = 0;
+ let model = "";
+ let prevT: number | undefined;
+ const at = (t: unknown) => (num(t) !== undefined ? new Date((t as number) * 1000).toISOString() : undefined);
+ const lines = text.split("\n").filter((l) => l.trim());
+ entries.push({ kind: "note", turn: 0, at: at(firstT(lines)) ?? new Date(0).toISOString(), text: `imported from the stopgap run ${run} (transcript.jsonl)` });
+ for (const [i, line] of lines.entries()) {
+ let e: Record<string, unknown>;
+ try {
+ e = obj(JSON.parse(line));
+ } catch {
+ entries.push({ kind: "note", turn, at: new Date(0).toISOString(), text: `line ${i + 1} of transcript.jsonl is not JSON` });
+ kept++;
+ continue;
+ }
+ const t = num(e.t);
+ const when = at(t) ?? new Date(0).toISOString();
+ if (e.kind === "start") {
+ model = str(e.model) ?? model;
+ turn = 0;
+ const { kind: _k, t: _t, ...rest } = e;
+ const parts = [str(e.model) && `model ${String(e.model)}`, str(e.extractor) && `extractor ${String(e.extractor)}`, num(e.max_usd) !== undefined && `cap $${String(e.max_usd)}`].filter(Boolean);
+ entries.push({ kind: "note", turn: 0, at: when, text: `stopgap run started${parts.length ? `: ${parts.join(", ")}` : ""}`, stopgap: rest });
+ mapped++;
+ } else if (e.kind === "turn") {
+ turn = num(e.n) ?? turn;
+ const content: unknown[] = [];
+ if (typeof e.text === "string" && e.text) content.push({ type: "text", text: e.text });
+ for (const name of Array.isArray(e.calls) ? e.calls : []) content.push({ type: "tool_use", name: String(name) });
+ entries.push({
+ kind: "response",
+ turn,
+ provider: model.startsWith("claude") ? "api" : "local",
+ at: when,
+ stopReason: typeof e.stop === "string" ? e.stop : null,
+ content,
+ usage: obj(e.usage),
+ usd: num(e.usd) ?? 0,
+ });
+ mapped++;
+ } else if (e.kind === "tool") {
+ entries.push({
+ kind: "tool",
+ turn,
+ name: String(e.name ?? ""),
+ input: e.input ?? null,
+ result: "",
+ chars: nonNeg(e.chars),
+ error: e.error === true,
+ ms: t !== undefined && prevT !== undefined ? Math.max(0, Math.round((t - prevT) * 1000)) : 0,
+ });
+ mapped++;
+ } else {
+ entries.push(e);
+ kept++;
+ }
+ if (t !== undefined) prevT = t;
+ }
+ return { entries, mapped, kept };
+}
+
+function firstT(lines: string[]): number | undefined {
+ for (const l of lines) {
+ try {
+ const t = num(obj(JSON.parse(l)).t);
+ if (t !== undefined) return t;
+ } catch {
+ /* the next */
+ }
+ }
+ return undefined;
+}
+
+// ─── Sizes ───
+
+// A directory's size, each file once however many links it has (the
+// stopgap's dedupe hard-links identical segments and voices). `seen` carries
+// the files already counted across several calls.
+export async function dirSize(dir: string, seen: Set<string> = new Set()): Promise<{ bytes: number; files: number }> {
+ let bytes = 0;
+ let files = 0;
+ const walk = async (d: string) => {
+ let names: import("node:fs").Dirent[];
+ try {
+ names = await readdir(d, { withFileTypes: true });
+ } catch {
+ return;
+ }
+ for (const e of names) {
+ const p = path.join(d, e.name);
+ if (e.isDirectory()) await walk(p);
+ else {
+ const s = await lstat(p).catch(() => null);
+ if (!s) continue;
+ files++;
+ const key = `${s.dev}:${s.ino}`;
+ if (seen.has(key)) continue;
+ seen.add(key);
+ bytes += s.size;
+ }
+ }
+ };
+ await walk(dir);
+ return { bytes, files };
+}
+
+export function humanBytes(n: number): string {
+ if (n < 1024) return `${n} B`;
+ const units = ["kB", "MB", "GB"];
+ let v = n / 1024;
+ let i = 0;
+ while (v >= 1024 && i < units.length - 1) {
+ v /= 1024;
+ i++;
+ }
+ return `${v >= 10 ? v.toFixed(0) : v.toFixed(1)} ${units[i]}`;
+}
+
+const exists = (p: string) => stat(p).then(() => true, () => false);
+
+// ─── The plan ───
+
+export type RunPlan = {
+ run: string;
+ dir: string;
+ article: string;
+ // `article`: the registry has it; `pending`: it will be an article in the making.
+ mode: "article" | "pending";
+ // Why it is not imported; nothing is written for it.
+ refused?: string;
+ // It was imported before: the iteration it is.
+ imported?: number;
+ articleState?: { published: boolean; audience: string; title: string | null; hasVideo: boolean };
+ model: string;
+ extractor?: string;
+ question: string;
+ channels: string[];
+ usage: Record<string, IterationUsage>;
+ usd: number;
+ minutes?: number;
+ checks: IterationCheck[];
+ createdAt: Date;
+ endedAt: Date;
+ // report.json's own id, when it is not the article's (it is set to it).
+ reportIdWas?: string;
+ report: Record<string, unknown>;
+ reportProblems: string[];
+ sweepMd: string;
+ turns: { entries: unknown[]; mapped: number; kept: number } | null;
+ // An article's run: whether its report.json is the article's.
+ current?: { match: boolean; differs: string[] };
+ project?: { from: string; to: string; bytes: number; files: number };
+ notes: string[];
+};
+
+export type GenerationPlan =
+ | { file: string; state: "absent" }
+ | { file: string; state: "unreadable"; why: string }
+ | { file: string; state: "ready"; patch: { routes: Record<string, GenerationRoute>; models: GenerationSettings["models"] }; changes: string[]; ignored: string[] };
+
+export type CleanupItem = { what: "run" | "project" | "draft"; name: string; path: string; bytes: number; note?: string };
+
+export type ImportPlan = {
+ stopgapDir: string;
+ // What deleting every cleanup item frees, each file once.
+ cleanupBytes: number;
+ projectsRoot: string;
+ runs: RunPlan[];
+ generation: GenerationPlan;
+ cleanup: CleanupItem[];
+ // Runs and projects neither imported nor named for deletion.
+ untouched: CleanupItem[];
+};
+
+export type ImportOptions = {
+ stopgapDir: string;
+ only?: string[];
+ projectsRoot: string;
+ generationFile: string;
+ moveProjects?: boolean;
+ paths: StorePaths;
+ currentGeneration: () => GenerationSettings;
+};
+
+// Two report documents compared as an article: `audience` (the registry's)
+// and `video` (attached by the stopgap's chain after the run) aside. The
+// top-level keys that differ.
+export function reportDifferences(run: Record<string, unknown>, article: Record<string, unknown>): string[] {
+ const skip = new Set(["audience", "video"]);
+ const keys = new Set([...Object.keys(run), ...Object.keys(article)].filter((k) => !skip.has(k)));
+ return [...keys].filter((k) => JSON.stringify(run[k]) !== JSON.stringify(article[k])).sort();
+}
+
+async function planRun(run: string, o: ImportOptions): Promise<RunPlan> {
+ const dir = path.join(o.stopgapDir, "runs", run);
+ const base: RunPlan = {
+ run,
+ dir,
+ article: run,
+ mode: "pending",
+ model: "",
+ question: "",
+ channels: [],
+ usage: {},
+ usd: 0,
+ checks: [],
+ createdAt: new Date(0),
+ endedAt: new Date(0),
+ report: {},
+ reportProblems: [],
+ sweepMd: "",
+ turns: null,
+ notes: [],
+ };
+ const refuse = (why: string): RunPlan => ({ ...base, refused: why });
+ if (!(await exists(dir))) return refuse(`no run directory ${dir}`);
+
+ const ui = await readJson(path.join(dir, "ui.json"));
+ const article = (ui.ok ? str(obj(ui.value).id) : undefined) ?? run;
+ base.article = article;
+ if (!isReportId(article) || RESERVED_ARTICLE_IDS.includes(article)) return refuse(`"${article}" is not an article id`);
+
+ const runJson = await readJson(path.join(dir, "run.json"));
+ if (!runJson.ok) return refuse(`run.json is ${runJson.why}`);
+ const r = obj(runJson.value) as StopgapRunJson;
+ const model = str(r.model);
+ if (!model) return refuse("run.json names no model");
+ const question = str(r.question);
+ if (!question) return refuse("run.json has no question");
+ base.model = model;
+ base.question = question;
+ const extractor = str(r.extractor);
+ if (extractor) base.extractor = extractor;
+ base.channels = (Array.isArray(r.channels) ? r.channels : []).map(String).filter((c) => /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(c));
+ base.usage = usageFromRun(r.by_model);
+ base.usd = Object.values(base.usage).reduce((s, u) => s + u.usd, 0);
+ const minutes = num(r.minutes);
+ if (minutes !== undefined && minutes >= 0) base.minutes = minutes;
+ base.checks = checksFromRun(r);
+
+ let sweepMd: string;
+ try {
+ sweepMd = await readFile(path.join(dir, "sweep.md"), "utf8");
+ } catch {
+ return refuse("there is no sweep.md");
+ }
+ base.sweepMd = sweepMd;
+
+ const reportRead = await readJson(path.join(dir, "report.json"));
+ if (!reportRead.ok) return refuse(`report.json is ${reportRead.why}`);
+ const report = { ...obj(reportRead.value) };
+ const wasId = str(report.id);
+ if (wasId !== article) {
+ base.reportIdWas = wasId ?? "(none)";
+ report.id = article;
+ }
+ // The iteration's report never carries an audience (the registry's alone).
+ delete report.audience;
+ const parsed = parseReport(report, { id: article });
+ if (!parsed.ok) return refuse(`report.json does not parse as a report: ${parsed.problems.slice(0, 3).map((p) => `${p.path || "(root)"}: ${p.message}`).join("; ")}`);
+ base.report = report;
+ base.reportProblems = parsed.problems.map((p) => `${p.path || "(root)"}: ${p.message}`);
+
+ try {
+ base.turns = mapStopgapTurns(await readFile(path.join(dir, "transcript.jsonl"), "utf8"), run);
+ } catch {
+ base.notes.push("no transcript.jsonl: turns.jsonl is not written");
+ }
+
+ // When: the transcript's first stamp (else ui.json's createdAt, else
+ // run.json's time) to run.json's time.
+ const runStat = await stat(path.join(dir, "run.json"));
+ base.endedAt = runStat.mtime;
+ const firstStamp = base.turns ? (base.turns.entries[1] as { at?: string } | undefined)?.at : undefined;
+ const uiCreated = ui.ok ? str(obj(ui.value).createdAt) : undefined;
+ const created = [firstStamp, uiCreated].map((s) => (s ? new Date(s) : null)).find((d) => d && Number.isFinite(d.getTime()) && d.getTime() > 0);
+ base.createdAt = created && created <= base.endedAt ? created : base.endedAt;
+
+ // The registry: an article, an article in the making, or nothing yet.
+ const state = await readArticleState(article, o.paths);
+ const its = await readIterations(article, o.paths).catch(() => null);
+ const already = its?.iterations.find((it) => obj((it as Record<string, unknown>).imported).run === run);
+ if (already) return { ...base, mode: state?.exists ? "article" : "pending", imported: already.n };
+ if (its && (its.iterations.length || its.problems.length)) {
+ return refuse(`"${article}" has iterations already (${[...its.iterations.map((i) => i.n), ...its.problems.map((p) => p.n)].sort((a, b) => a - b).map(iterationLabel).join(", ")}); the import makes i1`);
+ }
+ if (state?.exists) {
+ base.mode = "article";
+ const articleRead = await readJson(path.join(articleDir(o.paths, article), "report.json"));
+ const articleDoc = articleRead.ok ? obj(articleRead.value) : {};
+ base.articleState = {
+ published: state.published,
+ audience: isReportAudience(articleDoc.audience) ? String(articleDoc.audience) : state.audience,
+ title: state.title,
+ hasVideo: articleDoc.video !== undefined,
+ };
+ const differs = reportDifferences(report, articleDoc);
+ base.current = { match: differs.length === 0, differs };
+ } else if (state) {
+ // The index names it but its report.json is gone.
+ return refuse(`the registry names "${article}" but it has no report.json`);
+ }
+
+ const projectFrom = path.join(o.stopgapDir, "videos", run);
+ if (await exists(projectFrom)) {
+ const to = projectOf(o.projectsRoot, article, 1);
+ if (await exists(to)) {
+ const there = await readdir(to).catch(() => []);
+ if (there.length) return refuse(`the project's place ${to} is taken (${there.length} entries)`);
+ }
+ base.project = { from: projectFrom, to, ...(await dirSize(projectFrom)) };
+ }
+ return base;
+}
+
+async function planGeneration(file: string, current: () => GenerationSettings): Promise<GenerationPlan> {
+ const read = await readJson(file);
+ if (!read.ok) return read.why === "absent" ? { file, state: "absent" } : { file, state: "unreadable", why: read.why };
+ const g = obj(read.value);
+ const cur = current();
+ const routes: Record<string, GenerationRoute> = { ...cur.routes };
+ const ignored: string[] = [];
+ for (const [task, route] of Object.entries(obj(g.routes))) {
+ if (!(GENERATION_TASKS as readonly string[]).includes(task)) ignored.push(`routes.${task} (no such task)`);
+ else if (!(GENERATION_ROUTES as readonly string[]).includes(String(route))) ignored.push(`routes.${task} = ${JSON.stringify(route)} (not code, api or local)`);
+ else routes[task] = route as GenerationRoute;
+ }
+ const m = obj(g.models);
+ const models = { ...cur.models };
+ for (const k of ["api", "local", "extractor"] as const) {
+ if (m[k] === undefined) continue;
+ const v = str(m[k]);
+ if (v) models[k] = v;
+ else ignored.push(`models.${k} (not a model name)`);
+ }
+ for (const k of Object.keys(g)) if (!["preset", "routes", "models"].includes(k)) ignored.push(`${k} (not carried)`);
+ const changes: string[] = [];
+ for (const t of GENERATION_TASKS) if (routes[t] !== cur.routes[t]) changes.push(`routes.${t}: ${cur.routes[t]} → ${routes[t]}`);
+ for (const k of ["api", "local", "extractor"] as const) if (models[k] !== cur.models[k]) changes.push(`models.${k}: ${cur.models[k]} → ${models[k]}`);
+ return { file, state: "ready", patch: { routes, models }, changes, ignored };
+}
+
+async function planCleanup(o: ImportOptions, importing: Set<string>): Promise<{ cleanup: CleanupItem[]; untouched: CleanupItem[]; cleanupBytes: number }> {
+ const cleanup: CleanupItem[] = [];
+ const untouched: CleanupItem[] = [];
+ for (const [what, sub] of [["run", "runs"], ["project", "videos"]] as const) {
+ const root = path.join(o.stopgapDir, sub);
+ const names = (await readdir(root, { withFileTypes: true }).catch(() => [])).filter((e) => e.isDirectory()).map((e) => e.name).sort();
+ for (const name of names) {
+ const p = path.join(root, name);
+ const item: CleanupItem = { what, name, path: p, bytes: (await dirSize(p)).bytes };
+ if (isTestName(name)) cleanup.push(item);
+ else if (!importing.has(name)) untouched.push(item);
+ }
+ }
+ for (const id of [...(await listArticleDirs(o.paths)), ...(await listPendingArticles(o.paths))]) {
+ if (!isTestName(id)) continue;
+ const state = await readArticleState(id, o.paths);
+ const p = articleDir(o.paths, id);
+ cleanup.push({
+ what: "draft",
+ name: id,
+ path: p,
+ bytes: (await dirSize(p)).bytes,
+ ...(state?.published ? { note: "PUBLISHED — unpublish first" } : {}),
+ });
+ }
+ return { cleanup, untouched, cleanupBytes: await sumSeen(cleanup.map((c) => c.path)) };
+}
+
+async function sumSeen(dirs: string[]): Promise<number> {
+ const seen = new Set<string>();
+ let bytes = 0;
+ for (const d of dirs) bytes += (await dirSize(d, seen)).bytes;
+ return bytes;
+}
+
+export async function planImport(o: ImportOptions): Promise<ImportPlan> {
+ const names = o.only?.length ? o.only : [...DEFAULT_IMPORT_RUNS];
+ const runs: RunPlan[] = [];
+ for (const run of names) runs.push(await planRun(run, o));
+ const { cleanup, untouched, cleanupBytes } = await planCleanup(o, new Set(names));
+ return {
+ stopgapDir: o.stopgapDir,
+ projectsRoot: o.projectsRoot,
+ runs,
+ generation: await planGeneration(o.generationFile, o.currentGeneration),
+ cleanup,
+ cleanupBytes,
+ untouched,
+ };
+}
+
+// ─── Printing ───
+
+const usd = (n: number) => `$${n.toFixed(2)}`;
+const utc = (d: Date) => `${d.toISOString().slice(0, 16).replace("T", " ")} UTC`;
+const one = (s: string, max = 100) => {
+ const t = s.replace(/\s+/g, " ").trim();
+ return t.length > max ? `${t.slice(0, max - 1)}…` : t;
+};
+
+export function formatPlan(plan: ImportPlan, o: { apply: boolean; moveProjects: boolean }): string[] {
+ const L: string[] = [];
+ L.push(o.apply ? "reports import-local-runs: APPLY" : "reports import-local-runs: DRY RUN — nothing is written (--apply writes)");
+ L.push(`stopgap: ${plan.stopgapDir}`);
+ L.push(`projects root: ${plan.projectsRoot}`);
+ for (const r of plan.runs) {
+ L.push("");
+ if (r.refused) {
+ L.push(`${r.run}: REFUSED — ${r.refused}`);
+ continue;
+ }
+ if (r.imported !== undefined) {
+ L.push(`${r.run}: already imported as "${r.article}" ${iterationLabel(r.imported)} — nothing to do`);
+ continue;
+ }
+ const a = r.articleState;
+ L.push(
+ r.mode === "article"
+ ? `${r.run} → i1 of the article "${r.article}" (${a?.published ? "published" : "a draft"}, ${a?.audience ?? "private"})`
+ : `${r.run} → i1 of "${r.article}", a NEW article in the making (not made current: not listed, not a draft, until the operator chooses)`,
+ );
+ const by = Object.entries(r.usage).map(([m, u]) => `${m} ${usd(u.usd)}`).join(", ");
+ L.push(` sweep on ${r.model}${r.extractor ? ` (extractor ${r.extractor})` : ""} · ${usd(r.usd)}${by ? ` (${by})` : ""}${r.minutes !== undefined ? ` · ${r.minutes} min` : ""} · ${utc(r.createdAt)} → ${utc(r.endedAt)}`);
+ L.push(` question: “${one(r.question)}”`);
+ if (r.channels.length) L.push(` channels: ${r.channels.join(", ")}`);
+ if (r.checks.length) L.push(` checks: ${r.checks.map((c) => `${c.name} ${c.ok ? "ok" : "FAILED"}${c.detail ? ` (${one(c.detail, 60)})` : ""}`).join(", ")}`);
+ const files = [
+ `report.json${r.reportIdWas ? ` (its id "${r.reportIdWas}" becomes "${r.article}")` : ""}`,
+ `sweep.md (${humanBytes(Buffer.byteLength(r.sweepMd))})`,
+ ...(r.turns ? [`turns.jsonl (${r.turns.entries.length} lines: ${r.turns.mapped} in S1's shape, ${r.turns.kept} kept as they were, 1 import note)`] : []),
+ ];
+ L.push(` files: ${files.join(", ")}`);
+ if (r.reportProblems.length) L.push(` report.json has ${r.reportProblems.length} problem(s), so it cannot be made current: ${r.reportProblems.slice(0, 3).join("; ")}`);
+ if (r.mode === "article" && r.current) {
+ if (r.current.match && !r.reportProblems.length) {
+ L.push(` report.json IS the article's (audience and video aside) → i1 made current for the article (the same document is written)`);
+ } else if (!r.current.match) {
+ L.push(` report.json is NOT the article's — differs in: ${r.current.differs.join(", ")} → i1 is NOT made current; the article is unchanged`);
+ }
+ }
+ if (r.project) {
+ L.push(` video project: ${r.project.from} (${humanBytes(r.project.bytes)}, ${r.project.files} files) → ${o.moveProjects ? "moved" : "copied"} to ${r.project.to}`);
+ if (r.mode === "article") {
+ L.push(a?.hasVideo ? " the article has a video attached → i1 made current for the video" : " the article has no video attached → the video is not marked current");
+ }
+ }
+ for (const n of r.notes) L.push(` note: ${n}`);
+ }
+ L.push("");
+ const g = plan.generation;
+ if (g.state === "absent") L.push(`generation.json: none at ${g.file} — nothing to carry into settings.generation`);
+ else if (g.state === "unreadable") L.push(`generation.json: ${g.file} is ${g.why} — not carried`);
+ else {
+ L.push(`generation.json: ${g.file} → settings.generation (the editor's settings writer, else settings.json's)`);
+ L.push(g.changes.length ? ` patch: ${g.changes.join("; ")}` : " patch: none (settings.generation already says the same)");
+ if (g.ignored.length) L.push(` not carried: ${g.ignored.join("; ")}`);
+ }
+ L.push("");
+ L.push(`To delete after the operator's OK (D9; not touched here) — ${plan.cleanup.length} item(s), ${humanBytes(plan.cleanupBytes)} freed (a file hard-linked into several counted once):`);
+ for (const what of ["run", "project", "draft"] as const) {
+ const items = plan.cleanup.filter((c) => c.what === what);
+ if (!items.length) continue;
+ L.push(` ${what === "run" ? "runs" : what === "project" ? "video projects" : "registry drafts"}:`);
+ for (const c of items) L.push(` ${c.path} ${humanBytes(c.bytes)}${c.note ? ` ${c.note}` : ""}`);
+ }
+ if (plan.untouched.length) {
+ L.push("Neither imported nor named for deletion (kept):");
+ for (const c of plan.untouched) L.push(` ${c.path} ${humanBytes(c.bytes)}`);
+ }
+ return L;
+}
+
+// ─── Applying ───
+
+export type GenerationWriter = (patch: { routes: Record<string, GenerationRoute>; models: GenerationSettings["models"] }) => Promise<string>;
+
+async function copyProject(from: string, to: string, move: boolean): Promise<void> {
+ await mkdir(path.dirname(to), { recursive: true });
+ if (move) {
+ try {
+ await rename(from, to);
+ return;
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code !== "EXDEV") throw err;
+ }
+ }
+ await cp(from, to, { recursive: true, errorOnExist: true, force: false, preserveTimestamps: true, verbatimSymlinks: true });
+ if (move) await rm(from, { recursive: true, force: true });
+}
+
+async function applyRun(r: RunPlan, o: { paths: StorePaths; moveProjects: boolean; now: Date }, log: (s: string) => void): Promise<void> {
+ const created = await createIteration(
+ r.article,
+ { kind: "sweep", model: r.model, question: r.question, ...(r.channels.length ? { scope: { channels: r.channels } } : {}), status: "running" },
+ o.paths,
+ r.createdAt,
+ );
+ if (created.n !== 1) throw new Error(`"${r.article}" got ${iterationLabel(created.n)}, not i1 (another writer?) — stopped there`);
+ const n = created.n;
+ await writeIterationFile(r.article, n, "report.json", r.report, o.paths);
+ await writeIterationFile(r.article, n, "sweep.md", r.sweepMd, o.paths);
+ if (r.turns) await writeIterationFile(r.article, n, "turns.jsonl", r.turns.entries.map((e) => JSON.stringify(e)).join("\n") + "\n", o.paths);
+ if (r.project) {
+ await copyProject(r.project.from, r.project.to, o.moveProjects);
+ log(` ${o.moveProjects ? "moved" : "copied"} the video project to ${r.project.to}`);
+ }
+ await updateIteration(
+ r.article,
+ n,
+ {
+ status: "done",
+ usage: r.usage,
+ ...(r.minutes !== undefined ? { minutes: r.minutes } : {}),
+ checks: r.checks,
+ ...(r.project ? { projectDir: r.project.to } : {}),
+ endedAt: r.endedAt.toISOString(),
+ imported: { from: "local-reports", run: r.run, at: o.now.toISOString(), ...(r.extractor ? { extractor: r.extractor } : {}) },
+ } as Parameters<typeof updateIteration>[2],
+ o.paths,
+ o.now,
+ );
+ log(` wrote "${r.article}" i1 (done)`);
+ if (r.mode === "article" && r.current?.match && !r.reportProblems.length) {
+ await makeCurrent(r.article, n, o.paths, o.now);
+ log(" i1 made current for the article");
+ if (r.project && r.articleState?.hasVideo) {
+ await setCurrentVideo(r.article, n, o.paths, o.now);
+ log(" i1 made current for the video");
+ }
+ }
+}
+
+export async function importMain(
+ o: ImportOptions & { apply: boolean; generationWriter?: GenerationWriter; now?: () => Date },
+ out: Out = console,
+): Promise<number> {
+ const plan = await planImport(o);
+ for (const l of formatPlan(plan, { apply: o.apply, moveProjects: o.moveProjects === true })) out.log(l);
+ let bad = plan.runs.some((r) => r.refused);
+ if (!o.apply) {
+ out.log("");
+ out.log(bad ? "dry run: a run is refused (above); --apply would import the rest" : "dry run: nothing written");
+ return bad ? 1 : 0;
+ }
+ out.log("");
+ const now = (o.now ?? (() => new Date()))();
+ for (const r of plan.runs) {
+ if (r.refused || r.imported !== undefined) continue;
+ out.log(`${r.run}:`);
+ try {
+ await applyRun(r, { paths: o.paths, moveProjects: o.moveProjects === true, now }, (s) => out.log(s));
+ } catch (err) {
+ bad = true;
+ out.error(` FAILED: ${(err as Error).message}`);
+ }
+ }
+ if (plan.generation.state === "ready" && plan.generation.changes.length) {
+ try {
+ const where = await (o.generationWriter ?? defaultGenerationWriter())(plan.generation.patch);
+ out.log(`settings.generation written through ${where}`);
+ } catch (err) {
+ bad = true;
+ out.error(`settings.generation: FAILED — ${(err as Error).message}`);
+ }
+ }
+ out.log(bad ? "import: done with failures (above)" : "import: done");
+ return bad ? 1 : 0;
+}
+
+// The editor's settings writer (`POST /api/ops/settings`, with `pnpm ops`'s
+// env) when it answers; settings.json's writer when nothing listens there. An
+// editor that is there and refuses, or does not answer, is an error, and
+// settings.json is never written beside it (as `archilyzer gen`).
+export function defaultGenerationWriter(env: NodeJS.ProcessEnv = process.env, fetchImpl: typeof fetch = fetch): GenerationWriter {
+ return async (patch) => {
+ const { REPO_ROOT } = await import("./_spawnBin");
+ const ops = (await import(pathToFileURL(path.join(REPO_ROOT, "scripts", "archilyzer-ops.mjs")).href)) as {
+ loadEditorEnv: (env: NodeJS.ProcessEnv) => Record<string, string>;
+ tokenHint: (status: number, sources: Record<string, string>, url: string) => string;
+ };
+ const sources = ops.loadEditorEnv(env);
+ const base = (env.ARCHILYZER_EDITOR_URL || "http://localhost:3001").replace(/\/+$/, "");
+ const token = env.WORKER_TOKEN ?? "";
+ let res: Response;
+ try {
+ res = await fetchImpl(`${base}/api/ops/settings`, {
+ method: "POST",
+ headers: { "content-type": "application/json", ...(token ? { authorization: `Bearer ${token}` } : {}) },
+ body: JSON.stringify({ patch: { generation: patch } }),
+ signal: AbortSignal.timeout(15_000),
+ });
+ } catch (e) {
+ const code = (e as Error & { cause?: { code?: string } }).cause?.code ?? "";
+ if (!/ECONNREFUSED|ENOTFOUND|EHOSTUNREACH|EAI_AGAIN/.test(code)) {
+ throw new Error(`the editor at ${base} did not answer (${(e as Error).name === "TimeoutError" ? "no answer within 15 s" : (e as Error).message}) — not writing settings.json beside a running editor`);
+ }
+ const { getSettings, writeSettings } = await import("../lib/settings");
+ const { getPaths } = await import("../lib/paths");
+ const s = getSettings();
+ await writeSettings({ ...s, generation: { ...s.generation, routes: { ...s.generation.routes, ...patch.routes }, models: { ...s.generation.models, ...patch.models } } });
+ return `settings.json (${getPaths().settingsFile}; no editor answering)`;
+ }
+ const j = (await res.json().catch(() => null)) as Record<string, unknown> | null;
+ if (!res.ok || !j || j.ok === false) {
+ const error = typeof j?.error === "string" ? j.error : `HTTP ${res.status}`;
+ throw new Error(`the editor refused (HTTP ${res.status}): ${error}${res.status === 401 || res.status === 503 ? ` (${ops.tokenHint(res.status, sources, base)})` : ""}`);
+ }
+ return `the editor at ${base}`;
+ };
+}
+
+const expandHome = (p: string) => (p === "~" ? os.homedir() : p.startsWith("~/") ? path.join(os.homedir(), p.slice(2)) : p);
+// settings.generation.projectsRoot, `~` expanded; blank = ~/reports/articles
+// (controller/reportDraft.ts projectsRootOf, which a bin does not import).
+const projectsRootOf = (gen: GenerationSettings) => (gen.projectsRoot ? expandHome(gen.projectsRoot) : path.join(os.homedir(), "reports", "articles"));
+
+// The CLI row's options, from the flags and the settings.
+export async function importRow(flags: { apply?: boolean; runs?: string; only?: string; "move-projects"?: boolean; generation?: string }): Promise<number> {
+ const only = typeof flags.only === "string" ? flags.only.split(",").map((s) => s.trim()).filter(Boolean) : undefined;
+ if (flags.only !== undefined && !only?.length) {
+ console.error("reports import-local-runs: --only names runs, comma-separated");
+ return 2;
+ }
+ const { getPaths } = await import("../lib/paths");
+ const { getSettings } = await import("../lib/settings");
+ const gen = getSettings().generation;
+ return importMain({
+ apply: flags.apply === true,
+ stopgapDir: typeof flags.runs === "string" ? path.resolve(expandHome(flags.runs)) : DEFAULT_STOPGAP_DIR,
+ ...(only ? { only } : {}),
+ projectsRoot: projectsRootOf(gen),
+ generationFile: typeof flags.generation === "string" ? path.resolve(expandHome(flags.generation)) : DEFAULT_GENERATION_FILE,
+ moveProjects: flags["move-projects"] === true,
+ paths: getPaths(),
+ currentGeneration: () => getSettings().generation,
+ });
+}
diff --git a/common/lib/report/docs.ts b/common/lib/report/docs.ts
@@ -49,7 +49,8 @@ export function renderReportMarkdown(): string {
"the published, ordered list; an article directory it does not name is a draft. " +
"An article's `audience` (below) says which homepage build carries it: the public " +
"one only `\"public\"` articles, the private one every published article. An " +
- "article may cite any channel of the corpus.",
+ "article may cite any channel of the corpus. An article may not be called `new` " +
+ "(umtool's `/articles/new` is a page).",
);
out.push(
"- **A site's page** — `transcripts/sites/<siteId>/reports/<reportId>/report.json`, " +
@@ -150,6 +151,65 @@ export function renderReportMarkdown(): string {
out.push(`| \`${v}\` | ${cell(d.label)} | \`${d.color}\` |`);
}
out.push("");
+ out.push("## Iterations");
+ out.push("");
+ out.push(
+ "An article made or revised by a model keeps each generation as an **iteration**, `i1`, " +
+ "`i2`, … (`common/lib/report/iterations.ts`), in `transcripts/reports/<id>/iterations/<n>/`:",
+ );
+ out.push("");
+ out.push("| File | What |");
+ out.push("|---|---|");
+ out.push(
+ "| `iteration.json` | its kind (`sweep`, `revise-report`, `revise-video`, `research`), model, " +
+ "`parent` (the iteration it revises), `copyOf` (the iteration it repeats on another model), " +
+ "question or feedback, scope, status (`queued`, `running`, `done`, `failed`, `cancelled`), " +
+ "spend and tokens per model, ops applied and refused, minutes, checks, steps (narration, " +
+ "the video chain) and `projectDir` |",
+ );
+ out.push("| `report.json` | the report it made (a `revise-video` iteration has none: its report is its nearest ancestor's) |");
+ out.push("| `sweep.md` | the sweep's markdown |");
+ out.push("| `turns.jsonl` | the model's turns |");
+ out.push("| `proposals.json` | a research run's acquisitions |");
+ out.push("");
+ out.push("`iterations/current.json` names the iteration the article is, and the one its video is.");
+ out.push("");
+ out.push(
+ "- **Use this iteration** (umtool's Iterations tab) writes the article's `report.json` from a " +
+ "done iteration through the registry's writer: locked, validated, the article's `audience` " +
+ "and attached `video` kept. Nothing a generation runs writes the article's `report.json`; " +
+ "the next export records the change as the next Revision.",
+ );
+ out.push(
+ "- Iterations are never published: compose, the homepage and the site history read only " +
+ "the article's own files.",
+ );
+ out.push(
+ "- A directory with iterations and no `report.json` is an article **in the making**: the " +
+ "registry lists it neither as published nor as a draft until an iteration is made current.",
+ );
+ out.push(
+ "- An iteration's video project is off the corpus disk, in " +
+ "`<settings.generation.projectsRoot>/<id>/i<n>/` (blank: `~/reports/articles`).",
+ );
+ out.push(
+ "- `archilyzer reports iterations <id>` lists an article's iterations; `pnpm ops get " +
+ "iterations <id>` reads them from the editor.",
+ );
+ out.push("");
+ out.push("## Checking quotes");
+ out.push("");
+ out.push(
+ "`archilyzer reports verify-quotes <report.json> | --article <id>` checks every quote " +
+ "against its record as compose does (token recall, on every track) and names a quote that " +
+ "matches a served `en` rewrite but not `en-orig` (`en-orig-drift`). A quote that passes " +
+ "recall but is not verbatim (case, punctuation and curly quotes aside) within ±90 s of its " +
+ "cited second is **`inexact`**: a warning, printed and counted, that does not change the " +
+ "exit code; compose and publish do not use it. A GENERATED quote must pass that strict " +
+ "check: a finding whose quote fails it is dropped. The statuses: `ok`, `drift`, " +
+ "`en-orig-drift`, `inexact`, `missing-record`, `no-cues`, `missing-post`, `unreadable`.",
+ );
+ out.push("");
out.push("## Making a report from what exists");
out.push("");
out.push(
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,32 +1,31 @@
# Changelog
## [Unreleased]
+- **Reports and their revisions can be generated by the editor: `pnpm ops report-draft`.** `{"task": "sweep", "article", "question", "channels"}` drafts a new report of an article as its next iteration; `{"task": "revise-report" | "revise-video", "article", "iteration", "feedback"}` revises one; `{"task": "narrate", "article", "iteration"}` drafts the narration of an iteration's video cut; `"copyOf": N` runs iteration N again on another `"model"`. Each is a **Report draft** job on /jobs, on the Claude API (`draft:api`) or the local model (`draft:local`) by the model, and `pnpm ops job cancel` stops one. Every quote a model writes must be the transcript's words within 90 seconds of its link, or the finding is dropped; links cite the archive, never the platform. The answer names the job and the iteration; the job's log ends with the outcome. Needs a restart of the editor.
+- **umtool makes and iterates articles: `/articles/new` and an article's Iterations tab.** `/articles/new` takes a question, channels picked from the editor's list, dates, the sweep (the agent on a Claude model or the pipeline on the local model), the model and a cap (the policy's default, which can only go down); **Start** has the editor run it as a report draft and opens the article's iterations. Each iteration shows its kind, model, parent, copy, status, cost per model, minutes, ops applied and refused, and checks, and which one is the article and which the video. On an iteration: **Use this iteration** (the article's report becomes its report), **New iteration** (a revision of the report or the video from your feedback, on a model), **Copy with model**, **Narrate**, **Cancel** (with the running job's log), and **Make the video** (the pipeline chain as a umtool job, step by step, resumable). An article whose only content is iterations is listed on `/articles` as in the making. umtool's `/drafts` page is gone; it opens `/articles/new`. Needs a restart of umtool.
- **umtool shows a research run's queue, and /articles/new can start with research.** On an article's Iterations tab, a research iteration lists each acquisition it proposed: what it fetches, why, its evidence links, its estimate, and why it waits or was refused. Each one that waits has Yes and No (with an optional reason). An approved one shows its editor job's state as it runs. Once nothing is pending, **Continue into a sweep** starts the sweep over the run's channels and every channel it acquired into. On /articles/new, "start with research" takes an autonomy (propose, limits or auto; default the settings') and needs no channel.
-- **umtool makes and iterates articles: `/articles/new` and an article's Iterations tab.** `/articles/new` takes a question, channels picked from the editor's list, dates, the sweep (the agent on a Claude model or the pipeline on the local model), the model and a cap (the policy's default, which can only go down); **Start** has the editor run it as a report draft and opens the article's iterations. Each iteration shows its kind, model, parent, copy, status, cost per model, minutes, ops applied and refused, and checks, and which one is the article and which the video. On an iteration: **Use this iteration** (the article's report becomes its report), **New iteration** (a revision of the report or the video from your feedback, on a model), **Copy with model**, **Narrate**, **Cancel** (with the running job's log), and **Make the video** (the pipeline chain as a umtool job, step by step, resumable). An article whose only content is iterations is listed on `/articles` as in the making. Needs a restart of umtool.
- **Two iterations side by side: `/articles/<id>/compare?a=&b=`.** Each side's report, section by section, with what the other side lacks marked; the ops its revision applied and refused (and why); its failed checks; and, when both have one, the two video cuts with their narration. Tick **compare** on two iterations to open it.
- **The generation policy is on `/articles/new`.** The presets (`code`, `balanced`, `api`, `local`), where each task runs, the models and the caps, saved into the editor's `settings.generation`; the editor refuses a cap it would not keep, in its words. The API key is never shown or taken: the panel shows the key file's path and whether the file is there. The day's API spend is shown against the daily cap.
-- **umtool's `/drafts` page is gone; it opens `/articles/new`.**
+- **Spending on the Claude API is capped.** A job is capped by its task ($5 a sweep, $2 a revision, $1 a narration, or the `maxUsd` it asks for, never above `settings.generation.caps.max`), and the editor refuses a job once the day's API spend (UTC) has reached `caps.daily` ($20), naming the day's total. Each finished API job adds its spend to a ledger beside the checkout (`.generation/usage.jsonl`), which is where the day's total comes from.
+- **Research runs: the editor finds what an article's archive lacks and asks for it.** `pnpm ops report-draft --json '{"task": "research", "article", "question", "channels"?, "autonomy"?}'` runs a research iteration: a model searches the corpus, the web and archive.org (an item's file list included), then proposes each acquisition it needs (an archive.org import, a video, a new channel, a post, a transcription, a persist) with its reason, evidence links and estimated size. Under `propose` every one waits for your yes or no; under `limits` imports into existing channels under the caps run at once; under `auto` everything runs, through the editor's own queues and holds, until a cap. A new channel is always created on no site, an X channel is never put on one, and a Twitch VOD is never fetched, in every mode. The proposals are kept in the iteration's `proposals.json`.
+- **`pnpm ops research-approve` settles a research run.** `{"article", "iteration", "ids": ["p01", …], "approve": true | false, "note"?}` runs the approved proposals through the editor (past the run's autonomy and caps, never past a standing rule) or rejects them; with no ids it answers the run's state. Every call first checks the jobs of what was enqueued, so the run moves from waiting to ready as they finish. `report-draft {"task": "sweep", "article", "iteration": <the research run>}` then continues it: a sweep over the run's channels and every channel it acquired into, its question by default (refused while the run still waits, unless `"force": true`).
- **Claude Code follows the generation balance: `/gen`, and the MCP's `generation_policy` and `generate`.** `generation_policy` shows where each generation task runs (`code` = this Claude Code session, `api` = the Claude API, `local` = the local model), on which model, the caps and the day's Claude API spend against the daily cap; with a preset or a task and route it moves the balance, only when you ask. `generate` runs a task as a `report-draft` job on the editor (a sweep, a revision of a report or its video, a narration, a research run with its autonomy, or a sweep continuing a research run), refuses one routed to Claude Code, and with `wait: true` follows the job and answers the iteration it made: its cost, the ops it applied and refused, its checks and where its files are, with what to review before it is made current. `/gen` (`.claude/commands/gen.md`, in the repo) wraps both: tasks routed away are run through `generate` and reviewed, tasks routed to Claude Code are done in the session. It replaces the stopgap's user-level `/gen`. Claude Code picks the tools up on its next start; they need the MCP registered with `ARCHILYZER_EDITOR_URL` and `WORKER_TOKEN`.
- **`/sweep` follows the policy too.** When sweeps are routed to the API or the local model, the `/sweep` plan's first step is `generate`, then a review of what it made — read the iteration's report, spot-check its quotes with `get_transcript`, then recommend making it current or a revision — instead of running the sweep in the session. `via=code` (or `api`, `local`) in the request overrides the policy for that plan, and `article=` names the article. With no editor configured the plan is unchanged. `/ask` still answers in the conversation, and names the tasks the policy routes away.
- **`archilyzer gen policy | preset | set | run`** is the same balance from a terminal: through the editor when it answers, else `settings.json` through the settings writer when no editor is listening (never beside one that is there but silent). `gen run <task> [<question or feedback>] --article <id> …` enqueues the job as `pnpm ops report-draft` does (`--wait` follows it) and exits 3, running nothing, when the task is routed to Claude Code; `--via` overrides once.
- **Two new reads: `pnpm ops get generation-usage [<day>]`** (the day's Claude API spend and the daily cap) **and `pnpm ops get iterations <article>`** (an article's iterations and which is current). Needs a restart of the editor.
-- **Research runs: the editor finds what an article's archive lacks and asks for it.** `pnpm ops report-draft --json '{"task": "research", "article", "question", "channels"?, "autonomy"?}'` runs a research iteration: a model searches the corpus, the web and archive.org (an item's file list included), then proposes each acquisition it needs (an archive.org import, a video, a new channel, a post, a transcription, a persist) with its reason, evidence links and estimated size. Under `propose` every one waits for your yes or no; under `limits` imports into existing channels under the caps run at once; under `auto` everything runs, through the editor's own queues and holds, until a cap. A new channel is always created on no site, an X channel is never put on one, and a Twitch VOD is never fetched, in every mode. The proposals are kept in the iteration's `proposals.json`.
-- **`pnpm ops research-approve` settles a research run.** `{"article", "iteration", "ids": ["p01", …], "approve": true | false, "note"?}` runs the approved proposals through the editor (past the run's autonomy and caps, never past a standing rule) or rejects them; with no ids it answers the run's state. Every call first checks the jobs of what was enqueued, so the run moves from waiting to ready as they finish. `report-draft {"task": "sweep", "article", "iteration": <the research run>}` then continues it: a sweep over the run's channels and every channel it acquired into, its question by default (refused while the run still waits, unless `"force": true`).
-- **New settings: `generation.research`** (SETTINGS.md): a research run's default autonomy (`propose`), and its limits — 20 items, 5 GB and 6 hours of transcription a run, new channels and post walks waiting for approval under `limits`. `generation.routes.research` says where a research run runs (`api` in the balanced preset); a settings file from before keeps its preset.
-- **Reports and their revisions can be generated by the editor: `pnpm ops report-draft`.** `{"task": "sweep", "article", "question", "channels"}` drafts a new report of an article as its next iteration; `{"task": "revise-report" | "revise-video", "article", "iteration", "feedback"}` revises one; `{"task": "narrate", "article", "iteration"}` drafts the narration of an iteration's video cut; `"copyOf": N` runs iteration N again on another `"model"`. Each is a **Report draft** job on /jobs, on the Claude API (`draft:api`) or the local model (`draft:local`) by the model, and `pnpm ops job cancel` stops one. Every quote a model writes must be the transcript's words within 90 seconds of its link, or the finding is dropped; links cite the archive, never the platform. The answer names the job and the iteration; the job's log ends with the outcome. Needs a restart of the editor.
-- **Spending on the Claude API is capped.** A job is capped by its task ($5 a sweep, $2 a revision, $1 a narration, or the `maxUsd` it asks for, never above `settings.generation.caps.max`), and the editor refuses a job once the day's API spend (UTC) has reached `caps.daily` ($20), naming the day's total. Each finished API job adds its spend to a ledger beside the checkout (`.generation/usage.jsonl`), which is where the day's total comes from.
-- **New settings block `generation`** (SETTINGS.md): where each task runs (`code` = Claude Code, `api`, `local`, with the presets `code`, `balanced`, `api`, `local`), the models, the caps, the API key FILE (mode 600; the key itself is refused as a setting and never stored), and where video projects live (`projectsRoot`, which `umtool chain` now reads too).
-- **Text to speech and local drafting take turns on the GPU.** An Orpheus synthesis waits while a local model is drafting, and a local-model draft call waits while a transcription or a synthesis is running; digests still yield to transcription as before. The local model is unloaded when its draft job ends, so its memory is free for the next transcription.
-- **The `/sweep` plan says a claim carries no quoted words, and quotes are verbatim.** The MCP's `sweep_plan` now tells Claude Code, at the merge step, that every quoted span before a link becomes that link's quote (so a claim that quotes words breaks its own citation), and that a quote is the transcript's words, copied, within 90 seconds of its link. The same rules, from one place in the code, are what release 27's generation jobs are held to. Claude Code picks it up on its next start.
-- **`umtool chain <article> <n>` takes an article's iteration to a video and a podcast.** One step a process, each recorded in the iteration: make it current, have the editor fetch every cited clip window (padded to the cut's 3 s, so the article's clips and the video share one fetch), `reports prepare --article <id> --only`, have the editor capture this article's missing post screenshots, make the video manifest in `~/reports/articles/<id>/i<n>/` (its narration and voices carried over from the parent iteration's project), voice the narration through the editor, build the video and the podcast, attach the video to the article and check it, and hard-link the segments and voices the article's projects share. Run again, it resumes at the first step not done; `--from <step>` runs from one, `--dry` prints the steps, `--final` crossfades. Nothing is fetched, captured or voiced but by the editor.
-- **`reports prepare --article <id> --only` answers for that article.** Its problems fail the run, another article's are printed as warnings, and only it is exported, so a draft being readied is no longer held up by a gap in a published article. The media of every published article is still prepared (their cache is shared).
-- **A report video made by `reports to-manifest` no longer shows "undefined" under its title or ends on a silent card.** The title card now has an empty third line (and a manifest made before this renders one too), and a section with nothing to show — a trailing Coverage note, a section of posts only — gets no chapter card; the article keeps the section.
-- **`umtool build <project> --dry` names the real pipeline directory wherever it is run from** (it printed `<cwd>/report-to-video`).
- **`archilyzer reports iterations <id> [--json]` lists an article's iterations.** Release 27 keeps each generation of an article (a sweep, a revision of its report or its video, a research run) as an ITERATION under `transcripts/reports/<id>/iterations/<n>/`, with its kind, model, status, cost, parent and the iteration it copies; the command lists them with their lineage (`i1 › i3 › i4`), and marks the current article and the current video. Iterations are never published: compose, an article's history and the homepage ignore them, and an article whose only content is iterations (no report.json yet) is not listed anywhere until one of them is made current.
+- **`umtool chain <article> <n>` takes an article's iteration to a video and a podcast.** One step a process, each recorded in the iteration: make it current, have the editor fetch every cited clip window (padded to the cut's 3 s, so the article's clips and the video share one fetch), `reports prepare --article <id> --only`, have the editor capture this article's missing post screenshots, make the video manifest in `~/reports/articles/<id>/i<n>/` (its narration and voices carried over from the parent iteration's project), voice the narration through the editor, build the video and the podcast, attach the video to the article and check it, and hard-link the segments and voices the article's projects share. Run again, it resumes at the first step not done; `--from <step>` runs from one, `--dry` prints the steps, `--final` crossfades. Nothing is fetched, captured or voiced but by the editor.
+- **The stopgap's kept runs come into the app: `archilyzer reports import-local-runs`.** A dry run unless `--apply`: it prints what it would do and writes nothing. Each run named (by default the two kept ones) becomes `i1` of its article through the iterations store, with its model, question, channels, spend, checks and turns; an article the registry already has gets `i1` made current only when the run's report is the article's (and current for the video when one is attached), and its video project is copied (`--move-projects`: moved) to the projects root. A run with no article becomes an article in the making, not made current. The stopgap's `generation.json`, when there is one, becomes `settings.generation`'s routes and models. The stopgap's test runs, projects and drafts are listed with their sizes, to delete after your OK; the command deletes nothing.
- **Import one post by its URL.** `pnpm ops import-post --json '{"slug", "url"}'` imports one X status or one Bluesky post into a posts channel of that platform that archives that account, as an `import-post` job on the platform's queue, through the channel's own fetcher (gallery-dl with the channel's X login; the public Bluesky API). It is refused before any job when the URL is not a post, when the channel is not a posts channel of that platform (or its fetcher cannot read one post), when the post is another account's, or while the platform is held or cooling down after a rate limit. A post already archived is not read again. Needs a restart of the editor.
- **archive.org from the command line, read only.** `pnpm ops archive-search --json '{"query", "limit"?}'` answers the items an archive.org search finds, and `pnpm ops archive-item --json '{"item"}'` one item's files with their sizes, formats and lengths, which are the media an import would take, and what archive.org restricts. Both go through the editor's archive.org client, paced like an import, and download nothing. Needs a restart of the editor.
- **`pnpm ops web-search` and `pnpm ops web-fetch` read the web, politely.** `web-search` (`{"query", "n"?}`) answers DuckDuckGo's results as titles, links and snippets; `web-fetch` (`{"url", "maxChars"?}`) answers one page as plain text. Both are read only and go through one queue in the editor: one request at a time, three seconds apart, backing off when a site answers 429 or 503. A page on a private or local address (`localhost`, `192.168.…`, a name that resolves to one) is refused before anything is sent, and so is a file that is not a page (a PDF, an image). Needs a restart of the editor.
- **`archilyzer reports verify-quotes` flags an inexact quote.** A quote that passes the usual check but whose words are not, word for word, in the transcript within 90 seconds of its cited second — a word dropped that reverses its meaning, a quote from another moment — is now reported as `INEXACT (warning)`, with the first fragment that was not found. It is a warning: it is counted in the summary line and does not change the exit code; compose and publish are unchanged. Quotes a model writes in release 27's generation are held to it.
+- **The `/sweep` plan says a claim carries no quoted words, and quotes are verbatim.** The MCP's `sweep_plan` now tells Claude Code, at the merge step, that every quoted span before a link becomes that link's quote (so a claim that quotes words breaks its own citation), and that a quote is the transcript's words, copied, within 90 seconds of its link. The same rules, from one place in the code, are what release 27's generation jobs are held to. Claude Code picks it up on its next start.
+- **Text to speech and local drafting take turns on the GPU.** An Orpheus synthesis waits while a local model is drafting, and a local-model draft call waits while a transcription or a synthesis is running; digests still yield to transcription as before. The local model is unloaded when its draft job ends, so its memory is free for the next transcription.
+- **`reports prepare --article <id> --only` answers for that article.** Its problems fail the run, another article's are printed as warnings, and only it is exported, so a draft being readied is no longer held up by a gap in a published article. The media of every published article is still prepared (their cache is shared).
+- **A report video made by `reports to-manifest` no longer shows "undefined" under its title or ends on a silent card.** The title card now has an empty third line (and a manifest made before this renders one too), and a section with nothing to show — a trailing Coverage note, a section of posts only — gets no chapter card; the article keeps the section.
+- **`umtool build <project> --dry` names the real pipeline directory wherever it is run from** (it printed `<cwd>/report-to-video`).
+- **New settings block `generation`** (SETTINGS.md): where each task runs (`code` = Claude Code, `api`, `local`, with the presets `code`, `balanced`, `api`, `local`), the models, the caps, the API key FILE (mode 600; the key itself is refused as a setting and never stored), and where video projects live (`projectsRoot`, which `umtool chain` now reads too). Its `research` block: a research run's default autonomy (`propose`), and its limits — 20 items, 5 GB and 6 hours of transcription a run, new channels and post walks waiting for approval under `limits`. `generation.routes.research` says where a research run runs (`api` in the balanced preset); a settings file from before keeps its preset.
- **Orpheus speaks as the operator picked by ear: zac, calmer, quicker, in longer runs.** The default Orpheus voice is now `zac` (leah stays available); the sampler is cooler (temperature 0.55, top_p 0.85) and its repeat penalty higher (1.2), which reads less acted and less over-enunciated; a chunk holds up to 5 sentences and 420 characters, with shorter joins (0.2 s after a sentence, 0.1 s after a clause, 0.4 s after a paragraph), so the voice restarts its phrasing less often; and a very short line gets at least four seconds of budget, so it can no longer fail every take. Orpheus narration made before this is made again the next time it is asked for. Needs a restart of the editor.
- **A site's reports are its pages.** site.json `reports` is now `pages` (a file that still says `reports` reads as `pages` for this release; saving writes `pages`). Each page is served at `/pages/<id>/` and linked from the site's header by its title, after Ask AI; there is no Reports index any more. A site with search off shows its first page as its home, and saving a site with search off and no pages is refused. The site form lists them as **Pages**. Rebuild each site that has pages.
- **Site ids `articles` and `new` are refused.** The editor's `/sites/articles` and `/sites/new` (and umtool's `articles/`) would hide a site of either name, so a save under one is refused, naming why.
diff --git a/plans/FACTS.md b/plans/FACTS.md
@@ -9146,3 +9146,33 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri
record (`buildIndex.ts`, the `mtimes.put` after processing writes the same `metaMs`/`transcriptMs`/…). So a
record the pass took from no text to text keeps `hasTranscript: false` and its old `cueCount` in the stats until
something else moves its record.
+
+## Release 27: generation in the application (verified 2026-10-13, against `r27/integration` `1575479b`)
+
+- **An iteration's files** are `transcripts/reports/<id>/iterations/<n>/{iteration.json, report.json, sweep.md,
+ turns.jsonl, proposals.json}`; `iterations/current.json` is `{report, reportFrom, video}`. Every write is
+ `common/lib/report/iterations.ts` under the registry's lock (`withArticleStoreLock`); `writeIterationFile` takes only
+ `ITERATION_FILES`. The article's `report.json` is written from an iteration only by `makeCurrent`
+ (`writeArticleHoldingLock`, audience and video kept).
+- **An article in the making** is a directory with `iterations/` and no `report.json` (`isPendingArticleDir`,
+ `registry.ts`). `listArticleDirs` and `readArticleState` leave it out; `listPendingArticles` lists it. The
+ registry has no delete: an article directory is removed by hand only after the operator's OK.
+- **An article may not be called `new`** (`RESERVED_ARTICLE_IDS`, `assertArticleId`): umtool's `/articles/new` is a
+ page.
+- **Generation jobs** are job kind `report-draft` on the queues `draft:api` and `draft:local` (`DRAFT_API_QUEUE`,
+ `DRAFT_LOCAL_QUEUE`, `common/lib/queueKeys.ts`), enqueued by `enqueueReportDraft` (`common/controller/reportDraft.ts`).
+ A `sweep` body with `iteration` CONTINUES a research run; a copy is `copyOf` with no `iteration`.
+- **The spend ledger** is `<repo>/.generation/usage.jsonl` (`paths.generationUsageFile`, `GENERATION_USAGE_FILE`),
+ gitignored; one line per model per finished API job. The daily cap is a scan of the day's lines (UTC).
+- **`settings.generation.apiKeyFile` is redacted by the editor's settings read** (`redactSecrets`,
+ `editor/app/api/ops/_read.ts`: its name matches the secret pattern), so umtool and `archilyzer gen` read the PATH
+ from `settings.json` and never through the API. The settings write refuses a key-looking value without echoing it
+ (`looksLikeApiKey`).
+- **`projectsRoot` blank = `~/reports/articles`**, resolved in three places that must agree:
+ `projectsRootOf` in `common/controller/reportDraft.ts` and `umtool/lib/articles/generation.ts`, and
+ `DEFAULT_PROJECTS_ROOT` in `umtool/lib/report/chain.mjs`.
+- **A fetch window's `from`/`to` are the padded window; `pad` is provenance** (S7): every caller pads before it asks.
+- **verify-quotes `inexact`** is a warning only (`QUOTE_WARNING_STATUSES`, `common/bin/reports-check.ts`); `drift` and
+ `en-orig-drift` take precedence over it.
+- **The stopgap's `~/.config/archilyzer/generation.json` is retired** (absent on this machine at 2026-10-13); its runs
+ come in once through `archilyzer reports import-local-runs` (`common/bin/reports-import-local-runs.ts`).
diff --git a/plans/STATE.md b/plans/STATE.md
@@ -3,7 +3,36 @@
The working memory for the local-AI derived-corpus work. Rewritten at the end of every
session, before context is cleared. See [`README.md`](README.md) for the protocol.
-**Now (2026-10-09): release 18 is complete on `r18/integration`, and `main` is merged into it (`4cffda3f`, 94
+**Now (2026-10-13): release 27 — report and video generation inside the application — is built on
+`r27/integration`, not on `main` and not live** (plan and record: [`release-27.md`](release-27.md); D1–D9 ratified as
+recommended). `main` is `9f05d557`.
+- **Merged into `r27/integration`:** S0 (test kit), S1 (providers and the agent loop), S2 (strict quote check and op
+ engines), S3 (corpus tools in process, `web-search` / `web-fetch`), S3b (`archive-search`, `archive-item`,
+ `import-post`, the acquisition tools), S4 (iterations store), S5 (tasks), S6 (`report-draft` jobs, GPU arbiter, caps,
+ `settings.generation`), S7 (the umtool chain and the four owed bugs), S8 (umtool `/articles/new`, Iterations,
+ compare, policy panel), S9 (`generation_policy` / `generate`, `/gen`, `archilyzer gen`), S11 (research runs,
+ `research-approve`, umtool's research queue). S10 (`archilyzer reports import-local-runs` and the docs) is on
+ `r27/migrate-docs`.
+- **Owed, in order:** merge S10; the gate round on the integration tip (typecheck, unit suites, docs
+ checks, the four capped builds, `pnpm e2e:all` with `article-new`, `article-iterations`, `article-compare`,
+ `article-research` and `report-draft`), including the two runs no lane could make under the memory floor (a
+ standalone editor `next build`; umtool's `build.spec.ts` and its capped build); the privacy greps; fast-forward
+ `main`; the rollout (editor rebuild and restart, umtool build and restart, Claude Code restart for the MCP tools,
+ the homepage source-mirror publish; no public site changes); the live smoke on the operator's key (≤ $3, the list in
+ the plan's Gates).
+- **Then the stopgap:** the operator reads the import's dry run (`pnpm archilyzer reports import-local-runs`), then
+ `--apply`; then the test runs, projects and drafts it lists are deleted on the operator's OK (15 items, 307 MB, three
+ of them registry drafts with no registry delete verb); the user-level `~/.claude/commands/gen.md` is retired; the
+ stopgap stays read-only until the operator deletes it. `runs/api-shondo-fishing` is neither imported nor deleted
+ (ruled 2026-10-13): it is on the operator's list.
+- **Found during release 27, not fixed:** transcription leaves `/tmp/parakeet-stitch-*` directories behind (21 since
+ 2026-10-02, ~210 MB of the RAM tmpfs). `controller/relocateChannelMedia.test.ts` ("reconcile: an extra and a
+ changed file") failed once in a full common run on `r27/migrate-docs` and passes alone.
+- **Later candidates:** a research run under `auto` continuing into its sweep by itself (r27 keeps continuing
+ explicit); a per-job extractor model (r27: policy-level only); a turns meter on the `report-draft` job; release 28's
+ media tasks on the same machinery (D5).
+
+**Previously (2026-10-09): release 18 is complete on `r18/integration`, and `main` is merged into it (`4cffda3f`, 94
commits ahead of `main` `e921f82f`, 0 behind: a fast-forward).** The merge brought main's ~70 commits since 2026-10-06
(umtool articles + notes, `ops transcribe` with word timings, fetch-windows, metadata refresh, channel
create/rename/delete over ops; record: [`landed-2026-10.md`](landed-2026-10.md)); the changelogs keep both sides, r18
diff --git a/plans/release-27.md b/plans/release-27.md
@@ -616,6 +616,63 @@ Gates:
- umtool build (heavy slot, 5 GB cap, the corpus linked for the build only and removed): clean, `/api/articles/research` built. It waited 22 min for the heavy slot behind the orchestrator's e2e.
- e2e, foreground, two specs a run: `article-research` + `article-new` 4 passed, 1 failed (Continue's request was asserted before the stub recorded it; now polled); then `article-research` + `article-iterations` 6/6 (50.6 s).
+### S10, as shipped (2026-10-13, lane H, `r27/migrate-docs`)
+
+Migration and docs, on `r27/migrate-docs` from `r27/integration` `1575479b`.
+
+| Commit | What |
+| --- | --- |
+| `bc8d7f08` | `common/bin/reports-import-local-runs.ts` (+ tests), its `archilyzer` row, COMMANDS.md |
+| `ed3ae443` | OPERATING.md "Generate and iterate" and "Research runs"; `umtool/docs/authoring.md` "Generating with a model"; REPORT.md "Iterations" and "Checking quotes" (from `lib/report/docs.ts`); the CHANGELOG pass; AGENTS.md (`gen.md` in the prefix rule); STATE "Now"; FACTS; `docs cli --check` knows `pnpm ops job <verb>` |
+| `8e3329fa` | this record |
+| `fa22afd1` | merge `r27/integration` (S11's umtool queue) |
+| (this commit) | OPERATING.md and authoring.md checked against S11's queue and `/articles/new` (start with a sweep or research, Yes / No, Continue into a sweep); this record |
+
+- **`archilyzer reports import-local-runs [--apply] [--runs <dir>] [--only <run,…>] [--move-projects] [--generation <file>]`**
+ is a dry run unless `--apply`. Each run named (default: D9's two) becomes `i1` of its article through the
+ iterations store, never by hand:
+ - The article is `ui.json`'s `id`, else the run's name; the run's `report.json` gets that id (a different one is
+ printed).
+ - `iteration.json`: kind `sweep`, `run.json`'s model, question and channels; usage from `by_model`; minutes; checks
+ `convert` and `verify-quotes`; `createdAt` the transcript's first stamp, `endedAt` run.json's time; `imported
+ {from, run, at, extractor}`.
+ - `turns.jsonl`: an import note, then `start` → a note (its settings under `stopgap`), `turn` → a response (text and
+ the tool names as content, usage, USD), `tool` → a tool entry (`result` empty, the stopgap kept none; `chars`; `ms`
+ from the stamps); anything else kept as it was.
+ - An article the registry has: `makeCurrent` only when the run's report equals the article's with `audience` and
+ `video` aside (otherwise the differing keys are printed and the article is unchanged); `setCurrentVideo` when the
+ article has a video attached and the run has a project.
+ - A run with no article: an article in the making, not made current.
+ - The video project is copied (`--move-projects`: renamed, else copied and removed) to `projectOf(projectsRoot, id,
+ 1)`, recorded as `projectDir`.
+ - Refused, writing nothing for that run: no run directory, run.json or sweep.md; a report that does not parse; an
+ article with iterations already; a project place that is taken. A run imported before is "already imported".
+ - `generation.json`, when there is one: its routes (known tasks and routes only) and models over the current
+ `settings.generation`, printed as a patch; applied through the editor's `POST /api/ops/settings`, else
+ `writeSettings` when nothing listens (never beside an editor that is there and silent).
+ - The dry run lists the `ui-test-*`, `shondo-*` and `local-test-*` runs, projects and registry drafts with their sizes
+ (a hard-linked file counted once), and the runs neither imported nor named for deletion. Nothing is deleted.
+- **The dry run against the real stopgap and corpus** (read only; nothing written, checked with `find -newer`): both
+ runs importable. `piratesoftware-ai-friends` → the article's `i1`, its report equal to the article's, made current
+ for the article and the video, its project (72 MB, 90 files) copied to `~/reports/articles/piratesoftware-ai-friends/i1`.
+ `api-shondo-recent` → `i1` of a new article in the making (report id `api-test-shondo-recent` becomes the article's).
+ No `generation.json` on this machine. To delete after the OK: 15 items, 307 MB (8 runs, 4 projects, 3 registry
+ drafts). Kept, named by neither list: `runs/api-shondo-fishing`. Output: the job's `r27h-import-dry.txt`.
+- **Ruled (orchestrator, 2026-10-13):** `runs/api-shondo-fishing` is neither imported nor deleted; it goes on the
+ operator's list. The `api-shondo-recent` article id is the run name.
+- **Decided here:** the imported iteration's `createdAt` is the run's first transcript stamp, so it spans the run's
+ earlier attempts in the same transcript (the piratesoftware run has three starts). The registry has no delete verb:
+ the three test drafts are removed by hand after the OK.
+
+Gates:
+- tsc clean (all packages) before each commit.
+- common 4000/4001 at `bc8d7f08` (9 new, `reports-import-local-runs.test.ts`); the one red is
+ `controller/relocateChannelMedia.test.ts` "reconcile: an extra and a changed file …", 44/44 when run alone.
+ `cli-docs.test.ts` 9/9 after the checker change.
+- After the merge of `r27/integration` (S11's queue): tsc clean (all packages); common 4001/4001.
+- `docs cli|env|files --check`, `settings example --check`: clean.
+- No builds (no app code).
+
## Rollout
- Fast-forward `main`.
diff --git a/umtool/docs/authoring.md b/umtool/docs/authoring.md
@@ -106,6 +106,41 @@ umtool build <slug> --preset final
Watch the fast pass end to end. It is the only way to find a clip that is
technically correct and editorially wrong.
+## Generating with a model
+
+A model can make the report and the cut in place of steps 0–2: in umtool,
+`/articles/new` and then the article's Iterations tab ([sites.md](sites.md)),
+or from a shell. When the archive may lack the material, start with research
+instead of a sweep: its queue proposes what to fetch, and **Continue into a
+sweep** makes the report once it is in (OPERATING.md, "Research runs").
+
+```sh
+pnpm ops report-draft --json '{"task":"sweep","article":"<id>","question":"…","channels":["<slug>"]}' --wait
+umtool chain <id> <n> # the iteration to a video and a podcast
+pnpm ops report-draft --json '{"task":"revise-video","article":"<id>","iteration":<n>,"feedback":"…"}' --wait
+pnpm ops report-draft --json '{"task":"narrate","article":"<id>","iteration":<n>}' --wait
+```
+
+- **The chain** writes the project in `<projectsRoot>/<id>/i<n>/` (default
+ `~/reports/articles`). The editor fetches each cited window, padded by the
+ cut's 3 s. `siteOrigin` comes from the sweep's links, else `--site-origin`;
+ a manifest without one says so. The manifest is seeded from the parent
+ iteration's project: narration by card id, else by heading, and the voices
+ hard-linked.
+- **A video revision** applies checked ops to its parent's cut: drop, move,
+ heading, narration, trim (inside the clip's citation span), add a clip (from
+ the report's citations), title. Quotes never change. A refused op is listed
+ with its reason on the compare page.
+- **Narration** is drafted per title and chapter card from the card's
+ evidence. Numbers and names must be in the report, no quote is read aloud,
+ and a card gets 35 words (a title) or 45 (a chapter). A sentence that fails
+ is removed. The manifest before it is kept in
+ `revisions/<stamp>-auto-before-narration.manifest.json`, the draft in
+ `narration-draft.json`.
+- **Then review it as a hand-made cut:** `umtool check`, steps 4–6, and a fast
+ pass watched end to end. A generated window is the cue span plus its pad, so
+ widen or lock it as in step 4.
+
## The checklist
- [ ] `siteOrigin` is the archive's real origin