// 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//iterations//iteration.json what it is (below) // transcripts/reports//iterations//report.json the report it made // transcripts/reports//iterations//sweep.md the sweep's text // transcripts/reports//iterations//turns.jsonl the model turns // transcripts/reports//iterations//trace.jsonl a sweep's steps as // they happen (umtool // R3, tasks/trace.ts) // transcripts/reports//iterations//proposals.json a research run's // acquisitions (S11) // transcripts/reports//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)` = `//i/`, recorded // in the iteration as `projectDir`. // // SERVER-ONLY (node:fs). import { appendFile, mkdir, readdir, readFile, rename } 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, assertArticleId, 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"; // `refresh` (umtool R4, draft/refresh): fetch what is new, say what changed // against its parent, and fold it in — a revision of its parent that names no // feedback of its own. // `hand` (release 32): written by a person in umtool, no model — a blank start // (no parent), or a claim added by hand to the report of its parent // (controller/handEdits.ts). Its model is "hand"; it costs nothing. export const ITERATION_KINDS = ["sweep", "revise-report", "revise-video", "research", "refresh", "hand"] 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. // `seed.md`: a seeded sweep's starting report (a research board, umtool R2). // `trace.jsonl`: a sweep's structured trace, appended as it runs (umtool R3, // draft/tasks/trace.ts) — one JSON object a line, like turns.jsonl. // `refresh.json`: a refresh's fetches, build and delta (umtool R4, // draft/refresh/types.ts RefreshFile). // `items.jsonl`: a local sweep's checked items, one a line — each quote with // the transcript around it, its gate, the meaning check's prompt, answer, // decision and seconds (demo epic D2; what the model log shows). // `calls.jsonl` / `calls-text.jsonl`: the model log, every model call of the // iteration's runs and its steps (demo epic D3, lib/llm/callLog.ts) — // appended by its writer only, never through writeIterationFile. export const ITERATION_FILES = ["report.json", "sweep.md", "turns.jsonl", "proposals.json", "seed.md", "trace.jsonl", "refresh.json", "items.jsonl", "calls.jsonl", "calls-text.jsonl"] as const; export type IterationFile = (typeof ITERATION_FILES)[number]; // The files only their own writer appends to (lib/llm/callLog-server.ts): a // name of the iteration, never one writeIterationFile replaces. export const APPEND_ONLY_ITERATION_FILES: readonly IterationFile[] = ["calls.jsonl", "calls-text.jsonl"]; // A revision needs something to revise (and feedback saying how); a refresh // needs the iteration it refreshes (its feedback is what it finds). const NEEDS_PARENT: readonly IterationKind[] = ["revise-report", "revise-video"]; const NEEDS_PARENT_ONLY: readonly IterationKind[] = ["refresh"]; // ─── 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; // 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; export const iterationCheckSchema = z.looseObject({ name: z.string().min(1), ok: z.boolean(), detail: z.string().optional(), }); export type IterationCheck = z.infer; export const iterationScopeSchema = z.looseObject({ channels: z.array(channelSlug).optional(), from: ymd.optional(), to: ymd.optional(), // A sweep restricted to these recordings (umtool R4: a refresh's new ones). ids: z.array(z.string().min(1)).optional(), // The triage run this sweep escalates (umtool R6): reports/.triage///. triage: z.looseObject({ owner: z.string().min(1), k: z.number().int().positive() }).optional(), // The corpus the sweep read when it was not the editor's own build (demo epic // D1): a handle, `remote:` or `hub:`. Its revisions, // media drafts and video chain read and cite the same one (lineageSource). source: z.string().regex(/^(local|remote|hub):\S+/).optional(), }); export type IterationScope = z.infer; // What a sweep enumerated and read (umtool R3): the coverage rule // (mcp/src/instructions.ts, "State the plan") as data. `matched`: the distinct // recordings and posts the enumerations returned; `read`: the distinct ones // whose text was read; `partial`: an enumeration hit its cap (COVERAGE // PARTIAL); `unreached`: the channels a capped scan never reached. Optional: // an iteration written before R3 has none, and a reader ignores it if absent. export const iterationCoverageSchema = z.looseObject({ matched: z.number().int().nonnegative(), read: z.number().int().nonnegative(), partial: z.boolean(), unreached: z.array(z.string()), }); export type IterationCoverage = z.infer; // 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(), coverage: iterationCoverageSchema.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; // 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; // The highest iteration number ever allocated, kept once an iteration is // deleted (./delete.ts) so a number is never handed out twice: the usage // ledger and job logs name iterations by number. Absent = the highest // directory on disk. highest?: number; }; 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`); if (NEEDS_PARENT_ONLY.includes(it.kind) && it.parent === null) problems.push(`parent: a ${it.kind} names the iteration it refreshes`); return problems.length ? { ok: false, problems } : { ok: true, value: it }; } // ─── Where ─── type StorePaths = Pick; 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: `//i/` (D1). export function projectOf(projectsRoot: string, id: string, n: number): string { assertId(id); assertN(n); return path.join(projectsRoot, id, iterationLabel(n)); } const assertId: (id: unknown) => asserts id is string = assertArticleId; 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 { 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 { 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 { 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; 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 } : {}), ...(num(v.highest) !== null ? { highest: num(v.highest) as number } : {}), }; } async function writeCurrent(paths: StorePaths, id: string, current: IterationsCurrent): Promise { 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 { 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 { 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 { 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 { 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; } // The corpus handle an iteration's lineage read (demo epic D1): the newest // `scope.source` from n back to its root, or null — the editor's own build. export async function lineageSource(id: string, n: number, paths: StorePaths = getPaths()): Promise { let at: number | null = n; while (at !== null) { const it: Iteration | null = await readIteration(id, at, paths); if (!it) return null; if (it.scope?.source) return it.scope.source; at = it.parent; } return null; } // 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 { 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 { 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): 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; 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 { 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 (NEEDS_PARENT_ONLY.includes(input.kind) && parent === null) { throw new ArticleRegistryError(`a ${input.kind} iteration needs the iteration it refreshes (parent)`); } 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 = Math.max(taken[taken.length - 1] ?? 0, (await readCurrent(paths, id)).highest ?? 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 { 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 { 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>; // 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 { 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 { 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 = { ...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 { 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 { 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" || name === "refresh.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(`${name} 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" || name === "trace.jsonl") assertJsonLines(text, name); return text; } function assertJsonLines(text: string, name: string): void { for (const [i, line] of text.split("\n").entries()) { if (!line.trim()) continue; try { JSON.parse(line); } catch { throw new ArticleRegistryError(`${name} 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 and trace.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 { assertId(id); assertN(n); if (!(ITERATION_FILES as readonly string[]).includes(name)) { throw new ArticleRegistryError(`"${name}" is not an iteration file (${ITERATION_FILES.join(", ")})`); } if (APPEND_ONLY_ITERATION_FILES.includes(name)) { throw new ArticleRegistryError(`"${name}" is the model log: its writer appends to it, and nothing replaces it`); } 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 { 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; 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 { 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); } // The numbers of an article's iteration directories, ascending (a sound // iteration.json or not) — what a delete plans over. export async function iterationDirNumbers(id: string, paths: StorePaths = getPaths()): Promise { assertId(id); return iterationNumbers(paths, id); } // RETIRE ITERATION `n`'s NUMBER and take its directory out of the store, for // a caller HOLDING withArticleStoreLock (./delete.ts deleteIteration, which // has already refused a current, busy or parent iteration). The directory is // RENAMED to `iterations/.deleting--` — not an iteration name, so no // reader sees it from here on — and the caller removes it after the lock is // let go. `current.json` keeps `highest`, so `n` is never allocated again. // Answers the parked directory. export async function retireIterationHoldingLock(id: string, n: number, paths: StorePaths, stamp: string): Promise { assertId(id); assertN(n); const taken = await iterationNumbers(paths, id); if (!taken.includes(n)) throw new ArticleRegistryError(`"${id}" has no iteration ${iterationLabel(n)}`); const was = await readCurrent(paths, id); const highest = Math.max(was.highest ?? 0, ...taken); await writeCurrent(paths, id, { ...was, highest }); const parked = path.join(iterationsDir(paths, id), `${DELETING_PREFIX}${n}-${stamp}`); await rename(iterationDir(paths, id, n), parked); return parked; } // What a delete parks a directory as, until it is removed (./delete.ts). export const DELETING_PREFIX = ".deleting-"; // Whether the article has a report.json (an article in the making has not). export async function hasArticleReport(id: string, paths: StorePaths = getPaths()): Promise { return (await readJsonFile(articleFile(paths, id))).ok; }