commit bd36860bc3586e3dea66c6c11b759bc5c8688fc6
parent a749e6ec3cd628096d49a49b9c7e303a3c329341
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 13 Oct 2026 13:52:43 -0400
common: `archilyzer reports import-local-runs` — the stopgap's kept runs as iterations (release 27 S10, D9)
A dry run unless --apply. Each run becomes i1 of its article through the
iterations store: iteration.json from run.json (model, question, channels,
spend per model, minutes, checks, `imported`), report.json, sweep.md, and
turns.jsonl (the stopgap's transcript in S1's shape where it maps). An
article the registry has gets i1 made current only when the run's report is
the article's, and current for the video when one is attached; a run with no
article becomes an article in the making. Video projects are copied (or
moved) to projectOf(projectsRoot, id, 1). 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, never deleted.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
4 files changed, 1121 insertions(+), 0 deletions(-)
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/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/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,
+ });
+}