Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 1a4f2091bd7f33440a7f246aa3c17f8192346624
parent c721c02f1041b22a26054b6698bca74a61f7a624
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 13 Oct 2026 10:39:47 -0400

common: the iterations store — an article's generations under the registry's lock (release 27 S4)

lib/report/iterations.ts: transcripts/reports/<id>/iterations/<n>/ holds
iteration.json (a zod schema: kind, model, parent, copyOf, feedback or
question, scope, status, usage per model, ops, checks, steps, projectDir,
jobId, times), report.json, sweep.md, turns.jsonl and proposals.json;
iterations/current.json says which iteration the article and its video are.
createIteration allocates n under withArticleStoreLock; updateIteration,
recordIterationStep, addIterationUsage, writeIterationFile (an allowlist),
appendIterationTurns, readIteration(s), listIterations, currentIteration,
lineage, reportSourceOf, copyIteration, setCurrentVideo, projectOf.
makeCurrent writes the article's report.json through the registry's writer
(writeArticleHoldingLock, keeping the audience and the attached video).

registry.ts: a directory with iterations and no report.json is an article in
the making — listArticleDirs and readArticleState leave it out, so compose,
the homepage, the editor's Articles tab, umtool /articles and reports check
never see it; listPendingArticles lists them.

`archilyzer reports iterations <id> [--json]` lists them with lineage and the
current marked. Tests: the store (lineage, current, copy, contention,
refusals), the homepage compose and an article's history never carry them.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
MCOMMANDS.md | 1+
Mcommon/bin/archilyzer.ts | 15+++++++++++++++
Mcommon/bin/compose-homepage.test.ts | 38+++++++++++++++++++++++++++++++++++++-
Mcommon/bin/reports-article.test.ts | 60+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Acommon/bin/reports-iterations.ts | 116+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/iterations.test.ts | 276+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/iterations.ts | 751+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/report/registry.ts | 103++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------
Meditor/CHANGELOG.md | 1+
9 files changed, 1340 insertions(+), 21 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -34,6 +34,7 @@ Run from the repo root (in the container: `docker compose exec editor pnpm archi | `archilyzer reports check` | `<id> [--reports <a,b>] \| --article <articleId>` | \[--allow-missing-media\] what compose would say about the site's reports, with no build: each report validated, every cited quote checked against its record, every cited moment's prepared media present and current, the report video under the publish limit (exit 1 with the list; --reports checks those, drafts included; default id: SITE\_ID); --article: one article (transcripts/reports/), published or a draft, as the homepage's compose would | | `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 &lt;image&gt;\] \[--caption &lt;line&gt;\] 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/&lt;id&gt;/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 move-to-articles` | `[--keep <site>/<id>,…] [--drafts] [--apply]` | ONE-OFF (release 26): every report a site lists, but the pages named by --keep, moved to transcripts/reports/ as an article — audience private, published in reports/index.json in the sites' order (a report with problems as a draft), dropped from its site; --drafts moves unlisted ones too. A dry run printing the plan unless --apply *(passthrough)* | | `archilyzer reports convert` | `<sweep\|ask\|manifest> <in> --out <report.json> [--channels-dir <dir>] [--id <id>] [--title <title>]` | a /sweep report (markdown), an /ask answer or a report-to-video manifest as a report.json, written only when it validates (--channels-dir: widen spans from the cues, find posts' channels) | | `archilyzer reports to-manifest` | `<report.json> --out <manifest.json> [--channels-dir <dir>] [--site-origin <url>]` | a starter report-to-video manifest from a report (a chapter card per section, a claim's still and clips stamped with its verdict, its posts) | diff --git a/common/bin/archilyzer.ts b/common/bin/archilyzer.ts @@ -377,6 +377,21 @@ export const COMMANDS: Command[] = [ }); }, }, + { + path: ["reports", "iterations"], + usage: + "<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)", + flags: { json: "boolean" }, + maxPositionals: 1, + run: async ({ positionals, flags }) => { + const [article] = positionals; + if (!article) { + console.error("reports iterations: give <articleId>"); + return 2; + } + return (await import("./reports-iterations")).iterationsMain({ article, json: flags.json === true }); + }, + }, script(["reports", "move-to-articles"], "move-reports-to-articles.ts", "[--keep <site>/<id>,…] [--drafts] [--apply] ONE-OFF (release 26): every report a site lists, but the pages named by --keep, moved to transcripts/reports/ as an article — audience private, published in reports/index.json in the sites' order (a report with problems as a draft), dropped from its site; --drafts moves unlisted ones too. A dry run printing the plan unless --apply"), { diff --git a/common/bin/compose-homepage.test.ts b/common/bin/compose-homepage.test.ts @@ -7,7 +7,7 @@ import { after, test } from "node:test"; import assert from "node:assert/strict"; -import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; @@ -30,6 +30,7 @@ const { getPaths } = await import("../lib/paths"); const { buildIndex } = await import("../controller/buildIndex"); const { articleDir, configureArticle } = await import("../lib/report/registry"); const { main, channelSiteUrlOf } = await import("./compose-homepage"); +const { createIteration, updateIteration, writeIterationFile } = await import("../lib/report/iterations"); const { REPORT_MEDIA_FORMAT, REPORT_MEDIA_VERSION } = await import("../publish/reportMedia"); const paths = getPaths(); @@ -137,3 +138,38 @@ test("channelSiteUrlOf: the first listed site with a public URL; none for a chan assert.equal(of("y"), undefined); assert.equal(of("z"), undefined); }); + +// Every file under `dir`, relative. +function filesUnder(dir: string): string[] { + const out: string[] = []; + const walk = (d: string, rel: string) => { + for (const e of readdirSync(d, { withFileTypes: true })) { + const r = rel ? `${rel}/${e.name}` : e.name; + if (e.isDirectory()) walk(path.join(d, e.name), r); + else out.push(r); + } + }; + if (existsSync(dir)) walk(dir, ""); + return out; +} + +test("iterations are never published: a public article's iterations and an article in the making stay off the homepage (release 27 S4)", async () => { + const MARK = "ITERATION-ONLY-WORDS-7f3a"; + await createIteration("open", { kind: "sweep", model: "qwen3:8b", question: `${MARK}?` }, paths); + await writeIterationFile("open", 1, "report.json", article("open", { title: `${MARK} title` }), paths); + await writeIterationFile("open", 1, "sweep.md", `# ${MARK}\n`, paths); + await writeIterationFile("open", 1, "turns.jsonl", `${JSON.stringify({ role: "user", content: MARK })}\n`, paths); + await updateIteration("open", 1, { status: "done" }, paths); + await createIteration("in-the-making", { kind: "sweep", model: "qwen3:8b", question: `${MARK}?` }, paths); + await writeIterationFile("in-the-making", 1, "report.json", article("in-the-making", { title: MARK }), paths); + for (const audience of ["public", "private"] as const) { + await quietly(() => main({ paths, audience })); + const files = filesUnder(PUBLIC); + assert.ok(files.length > 0); + assert.deepEqual(files.filter((f) => /iteration|in-the-making|turns\.jsonl|sweep\.md/.test(f)), [], `${audience}: no iteration file`); + const leaked = files.filter((f) => /\.(json|html|md|txt|xml)$/.test(f) && readFileSync(path.join(PUBLIC, f), "utf8").includes(MARK)); + assert.deepEqual(leaked, [], `${audience}: no iteration's words`); + const index = readJson<{ reports: { id: string }[] }>(path.join(PUBLIC, "articles", "index.json")); + assert.ok(!index.reports.some((r) => r.id === "in-the-making")); + } +}); diff --git a/common/bin/reports-article.test.ts b/common/bin/reports-article.test.ts @@ -8,7 +8,7 @@ import { after, test } from "node:test"; import assert from "node:assert/strict"; import { execFileSync } from "node:child_process"; -import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; @@ -30,6 +30,7 @@ const { main: prepareMain } = await import("./reports-prepare"); const { main: exportMain } = await import("./reports-export"); const { attachVideoMain } = await import("./reports-attach-video"); const { readRevisionHead } = await import("../publish/reportHistory"); +const { createIteration, makeCurrent, updateIteration, writeIterationFile } = await import("../lib/report/iterations"); const paths = getPaths(); const CHAN = "lone"; @@ -133,6 +134,38 @@ test("export --article: one article's files under .export-index/articles/, its h assert.equal(await exportMain({ article: "nope", paths }, none.out), 2); }); +test("an article's iterations stay out of its history; making one current is the next revision (release 27 S4)", async () => { + const gitDir = path.join(path.dirname(articleFile(paths, "pub")), "history-git"); + await createIteration("pub", { kind: "sweep", model: "qwen3:8b", question: "What was said?" }, paths); + await writeIterationFile("pub", 1, "report.json", { ...article("pub"), title: "Article pub, iterated" }, paths); + await writeIterationFile("pub", 1, "sweep.md", "# iterated\n", paths); + await updateIteration("pub", 1, { status: "done" }, paths); + const tree = () => + execFileSync("git", ["--git-dir", gitDir, "ls-tree", "-r", "--name-only", "main"], { encoding: "utf8" }).trim().split("\n"); + // An export with iterations on disk and the article unchanged: nothing new. + const same = capture(); + assert.equal(await exportMain({ article: "pub", paths, formats: ["md"], allowMissingMedia: true }, same.out), 0, same.text()); + assert.equal((await readRevisionHead(gitDir))?.revision, 1); + await makeCurrent("pub", 1, paths); + const c = capture(); + assert.equal(await exportMain({ article: "pub", paths, formats: ["md"], allowMissingMedia: true }, c.out), 0, c.text()); + const head = await readRevisionHead(gitDir); + assert.equal(head?.revision, 2); + assert.deepEqual(head?.summary, ["Title changed: “Article pub” → “Article pub, iterated”"]); + assert.deepEqual(tree(), ["exports.json", "report.json", "report.md"]); + assert.ok(!readdirSync(path.join(STAGING, "report-exports", "pub")).some((f) => /iteration|sweep|turns/.test(f))); +}); + +test("an article in the making is no article to check, prepare or export (release 27 S4)", async () => { + await createIteration("making", { kind: "sweep", model: "qwen3:8b", question: "What was said?" }, paths); + await writeIterationFile("making", 1, "report.json", article("making"), paths); + const check = capture(); + assert.equal(await checkMain({ article: "making", paths, allowMissingMedia: true }, check.out), 2); + assert.match(check.text(), /no article "making"/); + const ex = capture(); + assert.equal(await exportMain({ article: "making", paths }, ex.out), 2); +}); + test("verify-quotes takes an article's file", async () => { const c = capture(); assert.equal(await verifyQuotesMain({ file: articleFile(paths, "pub"), paths }, c.out), 0, c.text()); @@ -166,3 +199,28 @@ test("attach-video --article: `video` written through the registry, the audience const none = capture(); assert.equal(await attachVideoMain({ article: "nope", video: src }, none.out), 1); }); + +test("reports iterations: the list with lineage, the current marked; JSON; an article in the making; refusals (release 27 S4)", async () => { + const { iterationsMain } = await import("./reports-iterations"); + await createIteration("pub", { kind: "revise-report", model: "claude-sonnet-5-5", parent: 1, feedback: "Name the bridge." }, paths); + const c = capture(); + assert.equal(await iterationsMain({ article: "pub", paths }, c.out), 0, c.text()); + const lines = c.text().split("\n"); + assert.match(lines[0], /reports iterations pub: 2 iteration\(s\)$/); + assert.match(lines[1], /^\* i1 +sweep +qwen3:8b +done .* i1 “What was said\?” ← current article$/); + assert.match(lines[2], /^ {2}i2 +revise-report +claude-sonnet-5-5 +queued .* i1 › i2 \(revises i1\) “Name the bridge\.”$/); + const j = capture(); + assert.equal(await iterationsMain({ article: "pub", json: true, paths }, j.out), 0); + const parsed = JSON.parse(j.text()) as { inTheMaking: boolean; current: { report: number }; iterations: { n: number; lineage: number[]; currentReport: boolean }[] }; + assert.equal(parsed.inTheMaking, false); + assert.equal(parsed.current.report, 1); + assert.deepEqual(parsed.iterations.map((i) => [i.n, i.lineage, i.currentReport]), [[1, [1], true], [2, [1, 2], false]]); + const making = capture(); + assert.equal(await iterationsMain({ article: "making", paths }, making.out), 0); + assert.match(making.text(), /an article in the making/); + const none = capture(); + assert.equal(await iterationsMain({ article: "nope", paths }, none.out), 2); + assert.match(none.text(), /no article "nope"/); + const bad = capture(); + assert.equal(await iterationsMain({ article: "Bad", paths }, bad.out), 2); +}); diff --git a/common/bin/reports-iterations.ts b/common/bin/reports-iterations.ts @@ -0,0 +1,116 @@ +// `archilyzer reports iterations <id> [--json]` (release 27 S4) — an +// article's iterations (lib/report/iterations.ts): each with its kind, model, +// status, cost, lineage and what it revised or copied, the current article +// and current video marked. Reads only. +// +// Exit 0 with the list (an article with none says so); 1 when an +// iteration.json is unsound (it is named); 2 for a bad id, or an id that is +// neither an article nor an article in the making. + +import { getPaths, type Paths } from "../lib/paths"; +import { readArticleState } from "../lib/report/registry"; +import { + iterationLabel, + iterationUsd, + readIterations, + type Iteration, + type IterationsCurrent, +} from "../lib/report/iterations"; +import { isReportId } from "../lib/report/schema"; + +type Out = { log: (s: string) => void; error: (s: string) => void }; + +export type IterationRow = Iteration & { + lineage: number[]; + usd: number; + currentReport: boolean; + currentVideo: boolean; +}; + +// The lineage of each iteration from the list itself (no further reads): its +// ancestors by parent, first to it. An unsound ancestor ends the walk. +export function iterationRows(iterations: readonly Iteration[], current: IterationsCurrent): IterationRow[] { + const byN = new Map(iterations.map((i) => [i.n, i])); + return iterations.map((it) => { + const line: number[] = []; + let at: Iteration | undefined = it; + while (at) { + line.unshift(at.n); + at = at.parent === null ? undefined : byN.get(at.parent); + } + return { + ...it, + lineage: line, + usd: iterationUsd(it), + currentReport: current.report === it.n, + currentVideo: current.video === it.n, + }; + }); +} + +const one = (s: string, max = 60) => { + const t = s.replace(/\s+/g, " ").trim(); + return t.length > max ? `${t.slice(0, max - 1)}…` : t; +}; + +export function formatIterationRow(r: IterationRow): string { + const marks = [r.currentReport ? "current article" : "", r.currentVideo ? "current video" : ""].filter(Boolean); + const from = [ + r.parent !== null ? `revises ${iterationLabel(r.parent)}` : "", + r.copyOf !== null ? `copy of ${iterationLabel(r.copyOf)}` : "", + ].filter(Boolean); + const words = r.feedback ?? r.question; + return [ + `${r.currentReport || r.currentVideo ? "*" : " "} ${iterationLabel(r.n).padEnd(4)}`, + r.kind.padEnd(13), + r.model.padEnd(20), + r.status.padEnd(9), + (r.usd > 0 ? `$${r.usd.toFixed(2)}` : "—").padEnd(7), + r.createdAt.slice(0, 16).replace("T", " "), + ` ${r.lineage.map(iterationLabel).join(" › ")}`, + ...(from.length ? [`(${from.join(", ")})`] : []), + ...(words ? [`“${one(words)}”`] : []), + ...(marks.length ? [`← ${marks.join(", ")}`] : []), + ].join(" "); +} + +export async function iterationsMain( + opts: { article: string; json?: boolean; paths?: Pick<Paths, "articlesDir" | "exportIndexDir"> }, + out: Out = console, +): Promise<number> { + const paths = opts.paths ?? getPaths(); + const id = opts.article; + if (!isReportId(id)) { + out.error(`reports iterations: "${id}" is not an article id`); + return 2; + } + let read; + try { + read = await readIterations(id, paths); + } catch (err) { + out.error(`reports iterations: ${(err as Error).message}`); + return 2; + } + const exists = (await readArticleState(id, paths)) !== null; + if (!exists && read.iterations.length === 0 && read.problems.length === 0) { + out.error(`reports iterations: no article "${id}" (no reports/${id}/)`); + return 2; + } + const rows = iterationRows(read.iterations, read.current); + if (opts.json) { + out.log( + JSON.stringify( + { article: id, inTheMaking: !exists, current: read.current, iterations: rows, problems: read.problems }, + null, + 2, + ), + ); + } else { + out.log( + `reports iterations ${id}: ${rows.length} iteration(s)${exists ? "" : " — an article in the making (no report.json yet)"}`, + ); + for (const r of rows) out.log(formatIterationRow(r)); + for (const p of read.problems) out.error(` ${iterationLabel(p.n)}: ${p.problems.join("; ")}`); + } + return read.problems.length > 0 ? 1 : 0; +} diff --git a/common/lib/report/iterations.test.ts b/common/lib/report/iterations.test.ts @@ -0,0 +1,276 @@ +// 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, + 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<string, unknown> = {}) => ({ + 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<string, unknown>; + +async function done(paths: ReturnType<typeof store>, 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/); + 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<string, unknown>).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<string, unknown>, 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: <root>/<id>/i<n>/", () => { + assert.equal(projectOf("/projects", "my-article", 3), path.join("/projects", "my-article", "i3")); +}); diff --git a/common/lib/report/iterations.ts b/common/lib/report/iterations.ts @@ -0,0 +1,751 @@ +// AN ARTICLE'S ITERATIONS — one generation's result and its provenance +// (release 27, S4; plans/release-27.md "Shape" and D1). "Iteration" because +// "version" (Report.version, the format), "revision" (the site history's +// "Revision N"), "draft" (an unpublished article) and "take" (umtool's +// alternative renders) are taken (plans/FACTS.md). +// +// transcripts/reports/<id>/iterations/<n>/iteration.json what it is (below) +// transcripts/reports/<id>/iterations/<n>/report.json the report it made +// transcripts/reports/<id>/iterations/<n>/sweep.md the sweep's text +// transcripts/reports/<id>/iterations/<n>/turns.jsonl the model turns +// transcripts/reports/<id>/iterations/<n>/proposals.json a research run's +// acquisitions (S11) +// transcripts/reports/<id>/iterations/current.json which iteration +// the article and +// its video are +// +// Every write goes through the article registry's lock (registry.ts +// withArticleStoreLock), is validated, and replaces its file whole. The +// article's own report.json is the CURRENT iteration's: `makeCurrent` writes +// it, through the registry's writer, and nothing a generation runs ever does. +// Its site history (publish/reportHistory.ts) commits report.json alone, so a +// makeCurrent is a Revision like any other write the next export sees. +// +// Iterations are NEVER published: compose copies named files of an article, +// never its directory; the history commits report.json, report.md and +// exports.json; the homepage reads the registry. A directory with iterations +// and no report.json is an article in the making — the registry does not list +// it (registry.ts listPendingArticles) until its first makeCurrent. +// +// A video project lives OFF the corpus disk, under the generation settings' +// projects root (D1): `projectOf(root, id, n)` = `<root>/<id>/i<n>/`, recorded +// in the iteration as `projectDir`. +// +// SERVER-ONLY (node:fs). + +import { appendFile, mkdir, readdir, readFile } from "node:fs/promises"; +import path from "node:path"; +import { z } from "zod"; +import { getPaths, type Paths } from "../paths"; +import { readJsonFile, writeFileAtomic, writeJsonAtomic } from "../jsonFile-server"; +import { isReportId, REPORT_ID_RE, type Report } from "./schema"; +import { parseReport } from "./validate"; +import { + ARTICLE_ITERATIONS_DIRNAME, + ArticleRegistryError, + articleDir, + articleFile, + withArticleStoreLock, + writeArticleHoldingLock, +} from "./registry"; + +export const ITERATION_FORMAT = "archilyzer-iteration"; +export const ITERATION_VERSION = 1; +export const ITERATION_FILENAME = "iteration.json"; +export const ITERATIONS_CURRENT_FILENAME = "current.json"; +export const ITERATIONS_CURRENT_FORMAT = "archilyzer-iterations-current"; + +export const ITERATION_KINDS = ["sweep", "revise-report", "revise-video", "research"] as const; +export type IterationKind = (typeof ITERATION_KINDS)[number]; +// `queued`: created for a job that has not started; the rest as a job ends. +export const ITERATION_STATUSES = ["queued", "running", "done", "failed", "cancelled"] as const; +export type IterationStatus = (typeof ITERATION_STATUSES)[number]; +export const ITERATION_STEP_STATUSES = ["pending", "running", "done", "failed", "cancelled", "skipped"] as const; +export type IterationStepStatus = (typeof ITERATION_STEP_STATUSES)[number]; + +// The files writeIterationFile may write (iteration.json is written by +// create/update only). A later slice adds a name here, never a path. +export const ITERATION_FILES = ["report.json", "sweep.md", "turns.jsonl", "proposals.json"] as const; +export type IterationFile = (typeof ITERATION_FILES)[number]; + +// A revision needs something to revise. +const NEEDS_PARENT: readonly IterationKind[] = ["revise-report", "revise-video"]; + +// ─── The schema ─── + +const isoTime = z.string().refine((s) => Number.isFinite(Date.parse(s)), "is not an ISO 8601 time"); +const ymd = z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "is not a YYYY-MM-DD date"); +const iterationNumber = z.number().int().positive(); +const channelSlug = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/, "is not a channel slug"); + +// One model's spend in an iteration, summed over its calls. +export const iterationUsageSchema = z.looseObject({ + usd: z.number().nonnegative(), + inputTokens: z.number().int().nonnegative(), + outputTokens: z.number().int().nonnegative(), + cacheReadTokens: z.number().int().nonnegative().optional(), + cacheWriteTokens: z.number().int().nonnegative().optional(), + calls: z.number().int().nonnegative().optional(), +}); +export type IterationUsage = z.infer<typeof iterationUsageSchema>; + +// One step a job or the chain ran over the iteration (narration, the +// pipeline's steps): what, on which model, how it went, what it cost. +export const iterationStepSchema = z.looseObject({ + task: z.string().min(1), + model: z.string().min(1).optional(), + status: z.enum(ITERATION_STEP_STATUSES), + // USD. + cost: z.number().nonnegative().optional(), + minutes: z.number().nonnegative().optional(), + startedAt: isoTime.optional(), + endedAt: isoTime.optional(), + jobId: z.string().min(1).optional(), + // One line: what it did, or why it failed. + detail: z.string().optional(), +}); +export type IterationStep = z.infer<typeof iterationStepSchema>; + +export const iterationCheckSchema = z.looseObject({ + name: z.string().min(1), + ok: z.boolean(), + detail: z.string().optional(), +}); +export type IterationCheck = z.infer<typeof iterationCheckSchema>; + +export const iterationScopeSchema = z.looseObject({ + channels: z.array(channelSlug).optional(), + from: ymd.optional(), + to: ymd.optional(), +}); +export type IterationScope = z.infer<typeof iterationScopeSchema>; + +// Loose: a key a later slice adds survives an update by code that predates it. +export const iterationSchema = z.looseObject({ + format: z.literal(ITERATION_FORMAT), + version: z.literal(ITERATION_VERSION), + article: z.string().regex(REPORT_ID_RE), + n: iterationNumber, + kind: z.enum(ITERATION_KINDS), + model: z.string().min(1), + // The iteration it revises (a revision's), else null. + parent: iterationNumber.nullable(), + // The iteration it is a copy of on another model (same parent, feedback, + // question and scope), else null. + copyOf: iterationNumber.nullable(), + feedback: z.string().optional(), + question: z.string().optional(), + scope: iterationScopeSchema.optional(), + status: z.enum(ITERATION_STATUSES), + error: z.string().optional(), + // By model id. + usage: z.record(z.string(), iterationUsageSchema), + ops: z.looseObject({ applied: z.array(z.unknown()), refused: z.array(z.unknown()) }).optional(), + minutes: z.number().nonnegative().optional(), + checks: z.array(iterationCheckSchema).optional(), + steps: z.array(iterationStepSchema), + // The video project (projectOf), once one is made. + projectDir: z.string().min(1).optional(), + // The editor job that generates it. + jobId: z.string().min(1).optional(), + createdAt: isoTime, + updatedAt: isoTime, + endedAt: isoTime.optional(), +}); +export type Iteration = z.infer<typeof iterationSchema>; + +// Which iteration the article is, and which its video is. `reportFrom` is the +// iteration whose report.json the article holds: the iteration itself, or — +// for a video revision, which has no report of its own — its nearest +// ancestor's. +export type IterationsCurrent = { + report: number | null; + reportFrom: number | null; + video: number | null; + reportAt?: string; + videoAt?: string; +}; + +const NO_CURRENT: IterationsCurrent = { report: null, reportFrom: null, video: null }; + +function problemsOf(error: z.ZodError): string[] { + return error.issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`); +} + +// An iteration.json, checked: the schema, and what the schema cannot say — +// that it is the article's and the number's it is filed under, and that its +// parent and original are earlier iterations. +export function parseIteration( + raw: unknown, + where: { article: string; n: number }, +): { ok: true; value: Iteration } | { ok: false; problems: string[] } { + const r = iterationSchema.safeParse(raw); + if (!r.success) return { ok: false, problems: problemsOf(r.error) }; + const it = r.data; + const problems: string[] = []; + if (it.article !== where.article) problems.push(`article: "${it.article}" is filed under "${where.article}"`); + if (it.n !== where.n) problems.push(`n: ${it.n} is filed under iterations/${where.n}`); + if (it.parent !== null && it.parent >= it.n) problems.push(`parent: i${it.parent} is not an earlier iteration`); + if (it.copyOf !== null && it.copyOf >= it.n) problems.push(`copyOf: i${it.copyOf} is not an earlier iteration`); + if (NEEDS_PARENT.includes(it.kind) && it.parent === null) problems.push(`parent: a ${it.kind} revises an iteration`); + return problems.length ? { ok: false, problems } : { ok: true, value: it }; +} + +// ─── Where ─── + +type StorePaths = Pick<Paths, "articlesDir" | "exportIndexDir">; + +export function iterationsDir(paths: StorePaths, id: string): string { + return path.join(articleDir(paths, id), ARTICLE_ITERATIONS_DIRNAME); +} + +export function iterationDir(paths: StorePaths, id: string, n: number): string { + return path.join(iterationsDir(paths, id), String(n)); +} + +export function iterationFile(paths: StorePaths, id: string, n: number, name: IterationFile | typeof ITERATION_FILENAME): string { + return path.join(iterationDir(paths, id, n), name); +} + +// How an iteration is named to a person: `i3`. +export function iterationLabel(n: number): string { + return `i${n}`; +} + +// An iteration's video project: `<projectsRoot>/<id>/i<n>/` (D1). +export function projectOf(projectsRoot: string, id: string, n: number): string { + assertId(id); + assertN(n); + return path.join(projectsRoot, id, iterationLabel(n)); +} + +function assertId(id: unknown): asserts id is string { + if (!isReportId(id)) { + throw new ArticleRegistryError(`"${String(id)}" is not an article id (a lowercase slug: [a-z0-9][a-z0-9-]*, at most 64)`); + } +} + +function assertN(n: unknown): asserts n is number { + if (typeof n !== "number" || !Number.isInteger(n) || n < 1) { + throw new ArticleRegistryError(`${String(n)} is not an iteration number (1, 2, …)`); + } +} + +// ─── Reading ─── + +// The iteration numbers on disk, ascending: directories named 1, 2, …. +async function iterationNumbers(paths: StorePaths, id: string): Promise<number[]> { + let names: string[]; + try { + names = (await readdir(iterationsDir(paths, id), { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name); + } catch { + return []; + } + return names + .filter((n) => /^[1-9]\d{0,8}$/.test(n)) + .map(Number) + .sort((a, b) => a - b); +} + +// One iteration, or null when there is none. Throws when its iteration.json +// is unreadable or unsound. +export async function readIteration(id: string, n: number, paths: StorePaths = getPaths()): Promise<Iteration | null> { + assertId(id); + assertN(n); + const read = await readJsonFile(iterationFile(paths, id, n, ITERATION_FILENAME)); + if (!read.ok) { + if (read.reason === "absent") return null; + throw new ArticleRegistryError(`reports/${id}/iterations/${n}/${ITERATION_FILENAME} is ${read.reason}`); + } + const parsed = parseIteration(read.value, { article: id, n }); + if (!parsed.ok) throw new ArticleRegistryError(`reports/${id}/iterations/${n}/${ITERATION_FILENAME} is not sound`, parsed.problems); + return parsed.value; +} + +async function readCurrent(paths: StorePaths, id: string): Promise<IterationsCurrent> { + const read = await readJsonFile(path.join(iterationsDir(paths, id), ITERATIONS_CURRENT_FILENAME)); + if (!read.ok || !read.value || typeof read.value !== "object") return { ...NO_CURRENT }; + const v = read.value as Record<string, unknown>; + const num = (x: unknown) => (typeof x === "number" && Number.isInteger(x) && x > 0 ? x : null); + return { + report: num(v.report), + reportFrom: num(v.reportFrom) ?? num(v.report), + video: num(v.video), + ...(typeof v.reportAt === "string" ? { reportAt: v.reportAt } : {}), + ...(typeof v.videoAt === "string" ? { videoAt: v.videoAt } : {}), + }; +} + +async function writeCurrent(paths: StorePaths, id: string, current: IterationsCurrent): Promise<void> { + await writeJsonAtomic( + path.join(iterationsDir(paths, id), ITERATIONS_CURRENT_FILENAME), + { format: ITERATIONS_CURRENT_FORMAT, version: 1, ...current }, + { mkdir: true }, + ); +} + +export type IterationsRead = { + // The sound ones, by n. + iterations: Iteration[]; + // One per iteration directory whose iteration.json is absent or unsound. + problems: { n: number; problems: string[] }[]; + current: IterationsCurrent; +}; + +// Every iteration of an article, its unsound ones named, and which is current. +export async function readIterations(id: string, paths: StorePaths = getPaths()): Promise<IterationsRead> { + assertId(id); + const out: IterationsRead = { iterations: [], problems: [], current: await readCurrent(paths, id) }; + for (const n of await iterationNumbers(paths, id)) { + try { + const it = await readIteration(id, n, paths); + if (it) out.iterations.push(it); + else out.problems.push({ n, problems: [`there is no ${ITERATION_FILENAME}`] }); + } catch (err) { + const e = err as ArticleRegistryError; + out.problems.push({ n, problems: e.problems?.length ? e.problems : [e.message] }); + } + } + return out; +} + +export async function listIterations(id: string, paths: StorePaths = getPaths()): Promise<Iteration[]> { + return (await readIterations(id, paths)).iterations; +} + +// Which iteration the article is and which its video is (nulls: none made +// current yet, or an article older than iterations). +export async function currentIteration(id: string, paths: StorePaths = getPaths()): Promise<IterationsCurrent> { + assertId(id); + return readCurrent(paths, id); +} + +// The iterations from the first to `n` by parent: [1, 3, 5] for i5 revising +// i3 revising i1. A parent is always earlier (create refuses otherwise), so +// the walk ends. +export async function lineage(id: string, n: number, paths: StorePaths = getPaths()): Promise<number[]> { + const out: number[] = []; + let at: number | null = n; + while (at !== null) { + const it = await readIteration(id, at, paths); + if (!it) throw new ArticleRegistryError(`"${id}" has no iteration ${iterationLabel(at)}`); + out.unshift(at); + at = it.parent; + } + return out; +} + +// A file of an iteration as text, or null when it has none. +export async function readIterationFile( + id: string, + n: number, + name: IterationFile, + paths: StorePaths = getPaths(), +): Promise<string | null> { + assertId(id); + assertN(n); + if (!(ITERATION_FILES as readonly string[]).includes(name)) throw new ArticleRegistryError(`"${name}" is not an iteration file`); + try { + return await readFile(iterationFile(paths, id, n, name), "utf8"); + } catch (err) { + if ((err as NodeJS.ErrnoException).code === "ENOENT") return null; + throw err; + } +} + +// The iteration whose report.json `n`'s report is: n itself when it made one, +// else the nearest ancestor that did (a video revision keeps its parent's +// report). Null when none in its lineage has one. +export async function reportSourceOf(id: string, n: number, paths: StorePaths = getPaths()): Promise<number | null> { + const line = await lineage(id, n, paths); + for (let i = line.length - 1; i >= 0; i--) { + if ((await readIterationFile(id, line[i], "report.json", paths)) !== null) return line[i]; + } + return null; +} + +// What an iteration cost in USD, over every model. +export function iterationUsd(it: Pick<Iteration, "usage">): number { + return Object.values(it.usage).reduce((s, u) => s + u.usd, 0); +} + +// ─── Writing ─── + +export type NewIteration = { + kind: IterationKind; + model: string; + parent?: number | null; + copyOf?: number | null; + feedback?: string; + question?: string; + scope?: IterationScope; + status?: Extract<IterationStatus, "queued" | "running">; + projectDir?: string; + jobId?: string; +}; + +// Write a new iteration.json for `id` at the next number, under the lock the +// caller holds. +async function createLocked(id: string, input: NewIteration, paths: StorePaths, now: Date): Promise<Iteration> { + const parent = input.parent ?? null; + const copyOf = input.copyOf ?? null; + if (parent !== null) { + assertN(parent); + const p = await readIteration(id, parent, paths); + if (!p) throw new ArticleRegistryError(`"${id}" has no iteration ${iterationLabel(parent)} to revise`); + if (p.status !== "done") throw new ArticleRegistryError(`"${id}" ${iterationLabel(parent)} is ${p.status}: only a done iteration is revised`); + } + if (copyOf !== null) { + assertN(copyOf); + if (!(await readIteration(id, copyOf, paths))) throw new ArticleRegistryError(`"${id}" has no iteration ${iterationLabel(copyOf)} to copy`); + } + if (NEEDS_PARENT.includes(input.kind)) { + if (parent === null) throw new ArticleRegistryError(`a ${input.kind} iteration needs the iteration it revises (parent)`); + if (!input.feedback?.trim()) throw new ArticleRegistryError(`a ${input.kind} iteration needs feedback: say what to change`); + } + if ((input.kind === "sweep" || input.kind === "research") && parent === null && !input.question?.trim() && copyOf === null) { + throw new ArticleRegistryError(`a ${input.kind} iteration needs its question`); + } + const taken = await iterationNumbers(paths, id); + const n = (taken[taken.length - 1] ?? 0) + 1; + const at = now.toISOString(); + const raw: Iteration = { + format: ITERATION_FORMAT, + version: ITERATION_VERSION, + article: id, + n, + kind: input.kind, + model: input.model, + parent, + copyOf, + ...(input.feedback?.trim() ? { feedback: input.feedback.trim() } : {}), + ...(input.question?.trim() ? { question: input.question.trim() } : {}), + ...(input.scope ? { scope: input.scope } : {}), + status: input.status ?? "queued", + usage: {}, + steps: [], + ...(input.projectDir ? { projectDir: input.projectDir } : {}), + ...(input.jobId ? { jobId: input.jobId } : {}), + createdAt: at, + updatedAt: at, + }; + const parsed = parseIteration(raw, { article: id, n }); + if (!parsed.ok) throw new ArticleRegistryError(`"${id}": the new iteration is not sound`, parsed.problems); + await mkdir(iterationsDir(paths, id), { recursive: true }); + // Not recursive: a directory that is already there (a writer that did not + // take the lock) is refused, never shared. + await mkdir(iterationDir(paths, id, n)); + await writeJsonAtomic(iterationFile(paths, id, n, ITERATION_FILENAME), parsed.value); + return parsed.value; +} + +// A NEW ITERATION of `id` — of an article, or of an article in the making +// (S8's /articles/new: no report.json yet). Its number is the next one, +// allocated under the lock, so two creates never share one. +export async function createIteration( + id: string, + input: NewIteration, + paths: StorePaths = getPaths(), + now: Date = new Date(), +): Promise<Iteration> { + assertId(id); + if (!(ITERATION_KINDS as readonly string[]).includes(input.kind)) { + throw new ArticleRegistryError(`kind must be one of ${ITERATION_KINDS.join(", ")}`); + } + if (!input.model?.trim()) throw new ArticleRegistryError("an iteration names its model"); + return withArticleStoreLock(() => createLocked(id, { ...input, model: input.model.trim() }, paths, now), paths); +} + +// A COPY of iteration `n` on another model: the same kind, parent, feedback, +// question and scope, `copyOf` n — to compare two models on the same work. +export async function copyIteration( + id: string, + n: number, + opts: { model: string; jobId?: string; status?: NewIteration["status"] }, + paths: StorePaths = getPaths(), + now: Date = new Date(), +): Promise<Iteration> { + assertId(id); + assertN(n); + if (!opts.model?.trim()) throw new ArticleRegistryError("a copy names its model"); + return withArticleStoreLock(async () => { + const src = await readIteration(id, n, paths); + if (!src) throw new ArticleRegistryError(`"${id}" has no iteration ${iterationLabel(n)} to copy`); + return createLocked( + id, + { + kind: src.kind, + model: opts.model.trim(), + parent: src.parent, + copyOf: n, + ...(src.feedback ? { feedback: src.feedback } : {}), + ...(src.question ? { question: src.question } : {}), + ...(src.scope ? { scope: src.scope } : {}), + ...(opts.jobId ? { jobId: opts.jobId } : {}), + ...(opts.status ? { status: opts.status } : {}), + }, + paths, + now, + ); + }, paths); +} + +// What names an iteration and where it came from: an update never changes it. +const FIXED_KEYS = ["format", "version", "article", "n", "kind", "parent", "copyOf", "createdAt"] as const; + +export type IterationPatch = Partial<Omit<Iteration, (typeof FIXED_KEYS)[number] | "updatedAt">>; + +// PATCH AN ITERATION — read inside the lock and patched as it is now (a +// function patch is given it). A key given as `undefined` is removed. Written +// only when the result is sound. `updatedAt` is stamped; `endedAt` too when +// the status becomes done, failed or cancelled and the patch gives none. +export async function updateIteration( + id: string, + n: number, + patch: IterationPatch | ((current: Iteration) => IterationPatch), + paths: StorePaths = getPaths(), + now: Date = new Date(), +): Promise<Iteration> { + assertId(id); + assertN(n); + return withArticleStoreLock(() => updateLocked(id, n, patch, paths, now), paths); +} + +async function updateLocked( + id: string, + n: number, + patch: IterationPatch | ((current: Iteration) => IterationPatch), + paths: StorePaths, + now: Date, +): Promise<Iteration> { + const cur = await readIteration(id, n, paths); + if (!cur) throw new ArticleRegistryError(`"${id}" has no iteration ${iterationLabel(n)}`); + const changes = typeof patch === "function" ? patch(cur) : patch; + for (const k of [...FIXED_KEYS, "updatedAt"]) { + if (k in (changes as object)) throw new ArticleRegistryError(`"${id}" ${iterationLabel(n)}: an update may not change "${k}"`); + } + const next: Record<string, unknown> = { ...cur }; + for (const [k, v] of Object.entries(changes)) { + if (v === undefined) delete next[k]; + else next[k] = v; + } + next.updatedAt = now.toISOString(); + const ended = ["done", "failed", "cancelled"].includes(String(next.status)); + if (ended && cur.status !== next.status && !("endedAt" in changes)) next.endedAt = now.toISOString(); + const parsed = parseIteration(next, { article: id, n }); + if (!parsed.ok) throw new ArticleRegistryError(`"${id}" ${iterationLabel(n)}: the update would make it unsound`, parsed.problems); + await writeJsonAtomic(iterationFile(paths, id, n, ITERATION_FILENAME), parsed.value); + return parsed.value; +} + +// Record one step (narration, a pipeline step): it replaces the newest record +// of the same task, else is appended — so a step re-run or resumed is one +// record, as it last ran. +export async function recordIterationStep( + id: string, + n: number, + step: IterationStep, + paths: StorePaths = getPaths(), + now: Date = new Date(), +): Promise<Iteration> { + return updateIteration( + id, + n, + (cur) => { + const steps = [...cur.steps]; + let at = -1; + for (let i = steps.length - 1; i >= 0; i--) { + if (steps[i].task === step.task) { + at = i; + break; + } + } + if (at >= 0) steps[at] = step; + else steps.push(step); + return { steps }; + }, + paths, + now, + ); +} + +// Add one call's spend to a model's usage. +export async function addIterationUsage( + id: string, + n: number, + model: string, + add: IterationUsage, + paths: StorePaths = getPaths(), + now: Date = new Date(), +): Promise<Iteration> { + return updateIteration( + id, + n, + (cur) => { + const was = cur.usage[model]; + const sum = (a?: number, b?: number) => (a === undefined && b === undefined ? undefined : (a ?? 0) + (b ?? 0)); + const next: IterationUsage = { + usd: (was?.usd ?? 0) + add.usd, + inputTokens: (was?.inputTokens ?? 0) + add.inputTokens, + outputTokens: (was?.outputTokens ?? 0) + add.outputTokens, + }; + for (const k of ["cacheReadTokens", "cacheWriteTokens", "calls"] as const) { + const v = sum(was?.[k], add[k]); + if (v !== undefined) next[k] = v; + } + return { usage: { ...cur.usage, [model]: next } }; + }, + paths, + now, + ); +} + +function fileText(name: IterationFile, data: string | Uint8Array | object, id: string): string | Buffer { + if (name === "report.json" || name === "proposals.json") { + let value: unknown; + if (typeof data === "string" || data instanceof Uint8Array) { + try { + value = JSON.parse(typeof data === "string" ? data : Buffer.from(data).toString("utf8")); + } catch { + throw new ArticleRegistryError(`${name} is not JSON`); + } + } else { + value = data; + } + if (name === "report.json") { + const parsed = parseReport(value, { id }); + if (!parsed.ok) { + throw new ArticleRegistryError(`the iteration's report.json does not parse`, parsed.problems.map((p) => `${p.path || "(root)"}: ${p.message}`)); + } + if ((value as { id?: unknown }).id !== id) { + throw new ArticleRegistryError(`the iteration's report.json is "${String((value as { id?: unknown }).id)}", not "${id}"`); + } + } else if (!value || typeof value !== "object") { + throw new ArticleRegistryError("proposals.json is a JSON object or list"); + } + return `${JSON.stringify(value, null, 2)}\n`; + } + if (typeof data !== "string" && !(data instanceof Uint8Array)) throw new ArticleRegistryError(`${name} is text`); + const text = typeof data === "string" ? data : Buffer.from(data).toString("utf8"); + if (name === "turns.jsonl") assertJsonLines(text); + return text; +} + +function assertJsonLines(text: string): void { + for (const [i, line] of text.split("\n").entries()) { + if (!line.trim()) continue; + try { + JSON.parse(line); + } catch { + throw new ArticleRegistryError(`turns.jsonl line ${i + 1} is not JSON`); + } + } +} + +// WRITE ONE FILE OF AN ITERATION — a name from ITERATION_FILES, replaced +// whole. report.json must parse as a report of this article (its problems +// are the checks' to name; makeCurrent refuses a report with any); proposals.json +// must be JSON; turns.jsonl one JSON value a line. Answers the file's path. +export async function writeIterationFile( + id: string, + n: number, + name: IterationFile, + data: string | Uint8Array | object, + paths: StorePaths = getPaths(), +): Promise<string> { + assertId(id); + assertN(n); + if (!(ITERATION_FILES as readonly string[]).includes(name)) { + throw new ArticleRegistryError(`"${name}" is not an iteration file (${ITERATION_FILES.join(", ")})`); + } + const text = fileText(name, data, id); + return withArticleStoreLock(async () => { + if (!(await readIteration(id, n, paths))) throw new ArticleRegistryError(`"${id}" has no iteration ${iterationLabel(n)}`); + const file = iterationFile(paths, id, n, name); + await writeFileAtomic(file, text); + return file; + }, paths); +} + +// Append turns to turns.jsonl, one JSON line each (a run's transcript grows +// as it goes; a whole rewrite per turn would be quadratic). +export async function appendIterationTurns( + id: string, + n: number, + turns: readonly unknown[], + paths: StorePaths = getPaths(), +): Promise<void> { + assertId(id); + assertN(n); + const text = turns.map((t) => `${JSON.stringify(t)}\n`).join(""); + if (!text) return; + await withArticleStoreLock(async () => { + if (!(await readIteration(id, n, paths))) throw new ArticleRegistryError(`"${id}" has no iteration ${iterationLabel(n)}`); + await appendFile(iterationFile(paths, id, n, "turns.jsonl"), text); + }, paths); +} + +// USE THIS ITERATION: the article's report.json becomes the iteration's +// report (a video revision's: its nearest ancestor's), written through the +// registry's writer — the only path that writes it from an iteration, so it is +// validated (a report with any problem is refused) and keeps the article's +// audience and its attached video. Only a done iteration is made current. +// The first makeCurrent of an article in the making creates its report.json: +// from then on it is a draft like any other. +export async function makeCurrent( + id: string, + n: number, + paths: StorePaths = getPaths(), + now: Date = new Date(), +): Promise<{ report: Report; current: IterationsCurrent }> { + assertId(id); + assertN(n); + return withArticleStoreLock(async () => { + const it = await readIteration(id, n, paths); + if (!it) throw new ArticleRegistryError(`"${id}" has no iteration ${iterationLabel(n)}`); + if (it.status !== "done") throw new ArticleRegistryError(`"${id}" ${iterationLabel(n)} is ${it.status}: only a done iteration is made current`); + const from = await reportSourceOf(id, n, paths); + if (from === null) throw new ArticleRegistryError(`"${id}" ${iterationLabel(n)} has no report.json, nor has any iteration it revises`); + const text = await readIterationFile(id, from, "report.json", paths); + let doc: unknown; + try { + doc = JSON.parse(text ?? ""); + } catch { + throw new ArticleRegistryError(`reports/${id}/iterations/${from}/report.json is not JSON`); + } + // Who may read the article is the registry's (configureArticle), never a + // generation's: the article's audience on disk is kept. + if (doc && typeof doc === "object" && !Array.isArray(doc)) { + const { audience: _audience, ...rest } = doc as Record<string, unknown>; + doc = rest; + } + const report = await writeArticleHoldingLock(doc, { paths, keepAudience: true, keepVideo: true }); + const was = await readCurrent(paths, id); + const current: IterationsCurrent = { ...was, report: n, reportFrom: from, reportAt: now.toISOString() }; + await writeCurrent(paths, id, current); + return { report, current }; + }, paths); +} + +// Record that the article's video is iteration `n`'s (the chain's attach +// step, after `reports attach-video` wrote it). +export async function setCurrentVideo( + id: string, + n: number, + paths: StorePaths = getPaths(), + now: Date = new Date(), +): Promise<IterationsCurrent> { + assertId(id); + assertN(n); + return withArticleStoreLock(async () => { + if (!(await readIteration(id, n, paths))) throw new ArticleRegistryError(`"${id}" has no iteration ${iterationLabel(n)}`); + const current: IterationsCurrent = { ...(await readCurrent(paths, id)), video: n, videoAt: now.toISOString() }; + await writeCurrent(paths, id, current); + return current; + }, paths); +} + +// Whether the article has a report.json (an article in the making has not). +export async function hasArticleReport(id: string, paths: StorePaths = getPaths()): Promise<boolean> { + return (await readJsonFile(articleFile(paths, id))).ok; +} diff --git a/common/lib/report/registry.ts b/common/lib/report/registry.ts @@ -11,6 +11,13 @@ // transcripts/reports/<id>/report.json the article (REPORT.md), with // `audience` "public" | "private" // (absent = private, D2) +// transcripts/reports/<id>/iterations/ the article's generations +// (release 27, ./iterations.ts), +// written under the same lock and +// never published; a directory with +// iterations and no report.json is +// an article in the making, not +// listed (listPendingArticles) // transcripts/reports/.registry.lock held while a write runs // // THE LOCK is two locks: withJsonFileLock (in-process: the editor's routes and @@ -123,12 +130,14 @@ export async function readArticlesIndex(paths: Pick<Paths, "articlesDir"> = getP return parsed.index; } -// Every article directory, published or draft: a directory under -// `transcripts/reports/` whose name is an article id. Sorted. -export async function listArticleDirs(paths: Pick<Paths, "articlesDir"> = getPaths()): Promise<string[]> { +// The directory of an article's iterations (release 27, ./iterations.ts). +// Named here because the registry must know one when it lists articles. +export const ARTICLE_ITERATIONS_DIRNAME = "iterations"; + +async function idDirs(dir: string): Promise<string[]> { let entries: Dirent[]; try { - entries = await readdir(paths.articlesDir, { withFileTypes: true }); + entries = await readdir(dir, { withFileTypes: true }); } catch { return []; } @@ -138,6 +147,37 @@ export async function listArticleDirs(paths: Pick<Paths, "articlesDir"> = getPat .sort((a, b) => a.localeCompare(b)); } +// An article IN THE MAKING (release 27, S4): a directory with `iterations/` +// and no report.json — a generation started it, and no iteration has been made +// current yet. The registry does not list it as an article (not even a draft): +// nothing that reads the registry — compose, the homepage, the editor's +// Articles tab, umtool's /articles, `reports check` — sees it until the first +// makeCurrent writes its report.json. `listPendingArticles` lists them. +async function isPendingArticleDir(dir: string): Promise<boolean> { + if (await stat(path.join(dir, "report.json")).then(() => true, () => false)) return false; + return (await stat(path.join(dir, ARTICLE_ITERATIONS_DIRNAME)).catch(() => null))?.isDirectory() ?? false; +} + +// Every article directory, published or draft: a directory under +// `transcripts/reports/` whose name is an article id — an article in the +// making (iterations and no report.json) excepted. Sorted. +export async function listArticleDirs(paths: Pick<Paths, "articlesDir"> = getPaths()): Promise<string[]> { + const out: string[] = []; + for (const id of await idDirs(paths.articlesDir)) { + if (!(await isPendingArticleDir(path.join(paths.articlesDir, id)))) out.push(id); + } + return out; +} + +// Every article in the making: iterations and no report.json yet. Sorted. +export async function listPendingArticles(paths: Pick<Paths, "articlesDir"> = getPaths()): Promise<string[]> { + const out: string[] = []; + for (const id of await idDirs(paths.articlesDir)) { + if (await isPendingArticleDir(path.join(paths.articlesDir, id))) out.push(id); + } + return out; +} + // One article as the registry knows it. export type ArticleState = { id: string; @@ -195,6 +235,8 @@ export async function readArticleState( if (!read.ok && read.reason === "absent" && !index.published.includes(id)) { const dir = await stat(articleDir(paths, id)).catch(() => null); if (!dir?.isDirectory()) return null; + // An article in the making is not an article yet. + if (await isPendingArticleDir(articleDir(paths, id))) return null; } return stateOf(id, read, index); } @@ -483,25 +525,48 @@ export async function patchArticle( // problem. A document with no `audience` keeps the one on disk (regenerating a // public article does not make it private); `keepAudience: false` writes it as // given. Its place in the index is untouched: publish with setPublished. -export async function writeArticle( - doc: unknown, - opts: { paths?: Pick<Paths, "articlesDir" | "exportIndexDir">; keepAudience?: boolean } = {}, -): Promise<Report> { +export type WriteArticleOptions = { + paths?: Pick<Paths, "articlesDir" | "exportIndexDir">; + keepAudience?: boolean; + // Keep the attached `video` on disk when the document has none (release 27: + // making a report iteration current does not take the article's video away; + // the chain's attach step replaces it). Default false. + keepVideo?: boolean; +}; + +export async function writeArticle(doc: unknown, opts: WriteArticleOptions = {}): Promise<Report> { const paths = opts.paths ?? getPaths(); + articleIdOf(doc); // refused before the lock is taken + return withArticleStoreLock(() => writeArticleHoldingLock(doc, { ...opts, paths }), paths); +} + +function articleIdOf(doc: unknown): string { if (!doc || typeof doc !== "object" || Array.isArray(doc)) throw new ArticleRegistryError("an article is a JSON object"); const id = (doc as { id?: unknown }).id; assertId(id); - return withArticleStoreLock(async () => { - let next = doc as Record<string, unknown>; - if (opts.keepAudience !== false && next.audience === undefined) { - const read = await readArticle(paths, id); - if (read.ok && read.raw.audience !== undefined) next = { ...next, audience: read.raw.audience }; + return id; +} + +// writeArticle's body, for a caller that already holds withArticleStoreLock +// and writes more than the article as one (lib/report/iterations.ts +// makeCurrent). The lock is not re-entrant: never call writeArticle there. +export async function writeArticleHoldingLock(doc: unknown, opts: WriteArticleOptions = {}): Promise<Report> { + const paths = opts.paths ?? getPaths(); + const id = articleIdOf(doc); + let next = doc as Record<string, unknown>; + if ((opts.keepAudience !== false && next.audience === undefined) || (opts.keepVideo === true && next.video === undefined)) { + const read = await readArticle(paths, id); + if (read.ok && opts.keepAudience !== false && next.audience === undefined && read.raw.audience !== undefined) { + next = { ...next, audience: read.raw.audience }; } - const parsed = parseReport(next, { id }); - if (!parsed.ok || parsed.problems.length > 0) { - throw new ArticleRegistryError(`"${id}" is not a sound report`, problemLines(parsed.problems)); + if (read.ok && opts.keepVideo === true && next.video === undefined && read.raw.video !== undefined) { + next = { ...next, video: read.raw.video }; } - await writeJsonAtomic(articleFile(paths, id), next, { mkdir: true }); - return parsed.value; - }, paths); + } + const parsed = parseReport(next, { id }); + if (!parsed.ok || parsed.problems.length > 0) { + throw new ArticleRegistryError(`"${id}" is not a sound report`, problemLines(parsed.problems)); + } + await writeJsonAtomic(articleFile(paths, id), next, { mkdir: true }); + return parsed.value; } diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,7 @@ # Changelog ## [Unreleased] +- **`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. - **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.