// `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; 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; 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[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[]; 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; models: Record }; 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"))); });