// An article's iterations (release 27 S4): created under the registry's lock, // validated, never the article until made current. Temp stores only. // // Run with: node_modules/.bin/tsx --test lib/report/iterations.test.ts import { after, test } from "node:test"; import assert from "node:assert/strict"; import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import os from "node:os"; import path from "node:path"; import { ARTICLES_LOCK_FILENAME, ArticleRegistryError, articleFile, configureArticle, listArticleDirs, listArticles, listPendingArticles, readArticleState, writeArticle, } from "./registry"; import { addIterationUsage, appendIterationTurns, copyIteration, createIteration, currentIteration, iterationDir, iterationUsd, lineage, lineageSource, listIterations, makeCurrent, parseIteration, projectOf, readIteration, readIterationFile, readIterations, recordIterationStep, reportSourceOf, setCurrentVideo, updateIteration, writeIterationFile, } from "./iterations"; const ROOTS: string[] = []; after(() => { for (const r of ROOTS) rmSync(r, { recursive: true, force: true }); }); function store() { const root = mkdtempSync(path.join(tmpdir(), "article-iterations-")); ROOTS.push(root); return { articlesDir: path.join(root, "transcripts", "reports"), exportIndexDir: path.join(root, ".export-index") }; } const doc = (id: string, over: Record = {}) => ({ format: "archilyzer-report", version: 1, id, kind: "sweep", title: `Article ${id}`, sections: [{ id: "s1", title: "One", body: "Plain words." }], ...over, }); const NOW = new Date("2026-10-13T12:00:00.000Z"); const json = (file: string) => JSON.parse(readFileSync(file, "utf8")) as Record; async function done(paths: ReturnType, id: string, n: number, report?: unknown) { if (report) await writeIterationFile(id, n, "report.json", report, paths); return updateIteration(id, n, { status: "done" }, paths, NOW); } test("a new article: its first iteration is not an article until it is made current", async () => { const paths = store(); const it = await createIteration("fresh", { kind: "sweep", model: "qwen3:8b", question: "What was said?", scope: { channels: ["synth-kitchen"] } }, paths, NOW); assert.equal(it.n, 1); assert.equal(it.status, "queued"); assert.equal(it.parent, null); assert.ok(existsSync(path.join(iterationDir(paths, "fresh", 1), "iteration.json"))); // Not listed, not a draft, not readable as an article. assert.deepEqual(await listArticleDirs(paths), []); assert.deepEqual(await listArticles(paths), []); assert.equal(await readArticleState("fresh", paths), null); assert.deepEqual(await listPendingArticles(paths), ["fresh"]); await assert.rejects(configureArticle("fresh", { published: true }, paths), /no article "fresh"/); // Made current, it is a draft like any other. await done(paths, "fresh", 1, doc("fresh")); const { report, current } = await makeCurrent("fresh", 1, paths, NOW); assert.equal(report.title, "Article fresh"); assert.deepEqual(current, { report: 1, reportFrom: 1, video: null, reportAt: NOW.toISOString() }); assert.deepEqual(await listArticleDirs(paths), ["fresh"]); assert.deepEqual(await listPendingArticles(paths), []); const state = await readArticleState("fresh", paths); assert.equal(state?.published, false); assert.equal(state?.exists, true); }); test("lineage, current and copy: revisions chain by parent; a copy shares the base and names its original", async () => { const paths = store(); await writeArticle(doc("art"), { paths }); await configureArticle("art", { audience: "public" }, paths); await createIteration("art", { kind: "sweep", model: "claude-sonnet-5-5", question: "Q?" }, paths, NOW); await done(paths, "art", 1, doc("art", { title: "First" })); const i2 = await createIteration("art", { kind: "revise-report", model: "qwen3:8b", parent: 1, feedback: " tighter " }, paths, NOW); assert.equal(i2.feedback, "tighter"); await done(paths, "art", 2, doc("art", { title: "Second" })); const i3 = await createIteration("art", { kind: "revise-video", model: "qwen3:8b", parent: 2, feedback: "shorter" }, paths, NOW); await done(paths, "art", 3); const i4 = await copyIteration("art", 2, { model: "claude-sonnet-5-5" }, paths, NOW); assert.deepEqual([i4.n, i4.kind, i4.parent, i4.copyOf, i4.feedback, i4.model], [4, "revise-report", 1, 2, "tighter", "claude-sonnet-5-5"]); assert.deepEqual(await lineage("art", 3, paths), [1, 2, 3]); assert.deepEqual(await lineage("art", 4, paths), [1, 4]); assert.equal(i3.n, 3); // A video revision's report is its parent's. assert.equal(await reportSourceOf("art", 3, paths), 2); const made = await makeCurrent("art", 3, paths, NOW); assert.equal(made.report.title, "Second"); assert.deepEqual([made.current.report, made.current.reportFrom], [3, 2]); // The audience on disk is the registry's; the iteration's report never sets it. assert.equal(json(articleFile(paths, "art")).audience, "public"); // The video: recorded by the chain's attach step, kept by a later makeCurrent. await setCurrentVideo("art", 3, paths, NOW); const again = await makeCurrent("art", 1, paths, NOW); assert.deepEqual([again.current.report, again.current.reportFrom, again.current.video], [1, 1, 3]); assert.equal(json(articleFile(paths, "art")).title, "First"); assert.deepEqual((await currentIteration("art", paths)).video, 3); assert.deepEqual((await listIterations("art", paths)).map((i) => i.n), [1, 2, 3, 4]); }); test("makeCurrent keeps the article's attached video when the report has none", async () => { const paths = store(); await writeArticle(doc("vid", { video: { src: "video.mp4", poster: "poster.jpg" } }), { paths }); await createIteration("vid", { kind: "sweep", model: "m", question: "Q?" }, paths, NOW); await done(paths, "vid", 1, doc("vid", { title: "New words" })); await makeCurrent("vid", 1, paths, NOW); const onDisk = json(articleFile(paths, "vid")); assert.equal(onDisk.title, "New words"); assert.deepEqual(onDisk.video, { src: "video.mp4", poster: "poster.jpg" }); }); test("locking under contention: concurrent creates get distinct numbers; a held lock is waited for", async () => { const paths = store(); const made = await Promise.all( Array.from({ length: 8 }, (_, i) => createIteration("busy", { kind: "sweep", model: `m${i}`, question: "Q?" }, paths, NOW)), ); assert.deepEqual(made.map((m) => m.n).sort((a, b) => a - b), [1, 2, 3, 4, 5, 6, 7, 8]); // Another process holds the store's lock (a live pid on this host): a create waits for it. const lock = path.join(paths.articlesDir, ARTICLES_LOCK_FILENAME); writeFileSync(lock, JSON.stringify({ pid: process.pid, host: os.hostname(), since: Date.now() })); let settled = false; const pending = createIteration("busy", { kind: "sweep", model: "late", question: "Q?" }, paths, NOW).then((it) => { settled = true; return it; }); await new Promise((r) => setTimeout(r, 150)); assert.equal(settled, false, "waits while the lock is held"); rmSync(lock); assert.equal((await pending).n, 9); // Concurrent updates of one iteration: each patch reads it as it is now. await Promise.all( Array.from({ length: 6 }, (_, i) => recordIterationStep("busy", 1, { task: `step-${i}`, status: "done" }, paths, NOW), ), ); assert.equal((await readIteration("busy", 1, paths))?.steps.length, 6); }); test("refusals: a revision needs a done parent and feedback; fixed keys; files by allowlist; only done is made current", async () => { const paths = store(); await assert.rejects(createIteration("Bad Id", { kind: "sweep", model: "m", question: "Q?" }, paths), /not an article id/); await assert.rejects(createIteration("r", { kind: "sweep", model: "m" }, paths), /needs its question/); await assert.rejects(createIteration("r", { kind: "sweep", model: " ", question: "Q?" }, paths), /names its model/); await assert.rejects(createIteration("r", { kind: "nope" as "sweep", model: "m", question: "Q?" }, paths), /kind must be one of/); await assert.rejects(createIteration("r", { kind: "revise-report", model: "m", feedback: "x" }, paths), /needs the iteration it revises/); await createIteration("r", { kind: "sweep", model: "m", question: "Q?" }, paths, NOW); await assert.rejects(createIteration("r", { kind: "revise-report", model: "m", parent: 1, feedback: "x" }, paths), /i1 is queued: only a done iteration is revised/); await assert.rejects(createIteration("r", { kind: "revise-report", model: "m", parent: 7, feedback: "x" }, paths), /no iteration i7/); await updateIteration("r", 1, { status: "done" }, paths, NOW); await assert.rejects(createIteration("r", { kind: "revise-report", model: "m", parent: 1, feedback: " " }, paths), /needs feedback/); await assert.rejects(updateIteration("r", 1, { kind: "research" } as never, paths), /may not change "kind"/); await assert.rejects(updateIteration("r", 1, { status: "exploded" } as never, paths), /would make it unsound/); await assert.rejects(updateIteration("r", 2, { status: "done" }, paths), /no iteration i2/); await assert.rejects(writeIterationFile("r", 1, "../evil.json" as "sweep.md", "x", paths), /not an iteration file/); await assert.rejects(writeIterationFile("r", 1, "report.json", doc("other"), paths), /is "other", not "r"|does not parse/); await assert.rejects(writeIterationFile("r", 1, "report.json", "{nope", paths), /not JSON/); // The model log is its writer's: a name of the iteration, never one this replaces. await assert.rejects(writeIterationFile("r", 1, "calls.jsonl", "{}\n", paths), /is the model log/); await assert.rejects(writeIterationFile("r", 1, "calls-text.jsonl", "{}\n", paths), /is the model log/); await assert.rejects(writeIterationFile("r", 1, "turns.jsonl", '{"a":1}\nnope\n', paths), /line 2 is not JSON/); await assert.rejects(writeIterationFile("r", 9, "sweep.md", "# x", paths), /no iteration i9/); // Made current: needs a report in its lineage, and a sound one. await assert.rejects(makeCurrent("r", 1, paths), /has no report.json/); await createIteration("r", { kind: "sweep", model: "m", question: "Q?" }, paths, NOW); await writeIterationFile("r", 2, "report.json", doc("r"), paths); await assert.rejects(makeCurrent("r", 2, paths), /i2 is queued: only a done iteration is made current/); await updateIteration("r", 2, { status: "done" }, paths, NOW); // A report that parses but has a problem (an unknown citation id) is kept in // the iteration and refused as the article. await writeIterationFile("r", 2, "report.json", doc("r", { sections: [{ id: "s1", title: "One", body: "See [x](cite:missing)." }] }), paths); await assert.rejects(makeCurrent("r", 2, paths), (e: unknown) => e instanceof ArticleRegistryError && /not a sound report/.test(e.message)); assert.equal(existsSync(articleFile(paths, "r")), false, "nothing written"); assert.throws(() => projectOf("/p", "Bad", 1), /not an article id/); assert.throws(() => projectOf("/p", "ok", 0), /not an iteration number/); }); test("updates: endedAt stamped when a run ends; usage summed per model; turns appended; steps replaced by task", async () => { const paths = store(); await createIteration("u", { kind: "sweep", model: "claude-sonnet-5-5", question: "Q?", status: "running" }, paths, NOW); const later = new Date("2026-10-13T12:05:00.000Z"); await addIterationUsage("u", 1, "claude-sonnet-5-5", { usd: 0.25, inputTokens: 1000, outputTokens: 200, cacheReadTokens: 50 }, paths, later); await addIterationUsage("u", 1, "claude-sonnet-5-5", { usd: 0.5, inputTokens: 10, outputTokens: 20, calls: 1 }, paths, later); await addIterationUsage("u", 1, "claude-haiku-4-5", { usd: 0.01, inputTokens: 5, outputTokens: 5 }, paths, later); await recordIterationStep("u", 1, { task: "narrate", model: "qwen3:8b", status: "running" }, paths, later); await recordIterationStep("u", 1, { task: "narrate", model: "qwen3:8b", status: "done", minutes: 2 }, paths, later); await appendIterationTurns("u", 1, [{ role: "user", content: "hi" }], paths); await appendIterationTurns("u", 1, [{ role: "assistant", content: "hello" }, { role: "user", content: "more" }], paths); const it = await updateIteration("u", 1, { status: "done", minutes: 5 }, paths, later); assert.equal(it.endedAt, later.toISOString()); assert.equal(it.updatedAt, later.toISOString()); assert.equal(it.createdAt, NOW.toISOString()); assert.deepEqual(it.usage["claude-sonnet-5-5"], { usd: 0.75, inputTokens: 1010, outputTokens: 220, cacheReadTokens: 50, calls: 1 }); assert.equal(iterationUsd(it), 0.76); assert.deepEqual(it.steps, [{ task: "narrate", model: "qwen3:8b", status: "done", minutes: 2 }]); const turns = (await readIterationFile("u", 1, "turns.jsonl", paths))!.trim().split("\n").map((l) => JSON.parse(l)); assert.deepEqual(turns.map((t) => t.content), ["hi", "hello", "more"]); // A key a later slice adds survives an update. await updateIteration("u", 1, { proposalsPending: 2 } as never, paths, later); await updateIteration("u", 1, { minutes: 6 }, paths, later); assert.equal((await readIteration("u", 1, paths) as Record).proposalsPending, 2); }); test("an unsound iteration.json is named, the rest still listed", async () => { const paths = store(); await createIteration("p", { kind: "sweep", model: "m", question: "Q?" }, paths, NOW); await createIteration("p", { kind: "sweep", model: "m", question: "Q?" }, paths, NOW); writeFileSync(path.join(iterationDir(paths, "p", 2), "iteration.json"), "{torn"); mkdirSync(iterationDir(paths, "p", 3)); const read = await readIterations("p", paths); assert.deepEqual(read.iterations.map((i) => i.n), [1]); assert.deepEqual(read.problems.map((p) => p.n), [2, 3]); assert.match(read.problems[0].problems[0], /unparseable/); // The next number is past every directory, sound or not. assert.equal((await createIteration("p", { kind: "sweep", model: "m", question: "Q?" }, paths, NOW)).n, 4); }); test("parseIteration: filed under its own article and number; parent and original are earlier", () => { const base = { format: "archilyzer-iteration", version: 1, article: "a", n: 2, kind: "sweep", model: "m", parent: null, copyOf: null, status: "done", usage: {}, steps: [], createdAt: NOW.toISOString(), updatedAt: NOW.toISOString(), }; assert.equal(parseIteration(base, { article: "a", n: 2 }).ok, true); const bad = (over: Record, where = { article: "a", n: 2 }) => { const r = parseIteration({ ...base, ...over }, where); return r.ok ? [] : r.problems; }; assert.match(bad({}, { article: "b", n: 2 })[0], /filed under "b"/); assert.match(bad({}, { article: "a", n: 3 })[0], /filed under iterations\/3/); assert.match(bad({ parent: 2 })[0], /not an earlier iteration/); assert.match(bad({ copyOf: 5 })[0], /not an earlier iteration/); assert.match(bad({ kind: "revise-video" })[0], /revises an iteration/); assert.match(bad({ scope: { channels: ["../x"] } })[0], /channel slug/); }); test("projectOf: //i/", () => { assert.equal(projectOf("/projects", "my-article", 3), path.join("/projects", "my-article", "i3")); }); test("an article may not be called `new` (umtool's /articles/new is a page)", async () => { const paths = store(); await assert.rejects( createIteration("new", { kind: "sweep", model: "claude-sonnet-5-5" }, paths), /reserved/, ); }); // demo epic D1: a sweep over a published archive records it; its revisions read it. test("a sweep's source is kept in its scope and inherited down its lineage", async () => { const paths = store(); await createIteration("arc", { kind: "sweep", model: "m", question: "q", scope: { channels: ["alpha"], source: "remote:https://stub.test" } }, paths, NOW); await done(paths, "arc", 1, doc("arc")); await createIteration("arc", { kind: "revise-report", model: "m", parent: 1, feedback: "tighter" }, paths, NOW); assert.equal(await lineageSource("arc", 2, paths), "remote:https://stub.test"); assert.equal((await readIteration("arc", 1, paths))?.scope?.source, "remote:https://stub.test"); // A sweep of the editor's own build has none. await createIteration("own", { kind: "sweep", model: "m", question: "q", scope: { channels: ["alpha"] } }, paths, NOW); assert.equal(await lineageSource("own", 1, paths), null); assert.equal(await lineageSource("nope", 1, paths), null); // Not a handle: refused at the schema. await assert.rejects(createIteration("bad", { kind: "sweep", model: "m", question: "q", scope: { channels: ["alpha"], source: "https://stub.test" } }, paths, NOW)); });