// `archilyzer reports import-sweep --article --question // [--sweep ] [--channels ] [--model ] [--minutes ] [--apply]` // — a report made OUTSIDE the editor's report-draft jobs (a Claude Code // session's /sweep, a hand-run research pass) becomes the next ITERATION of its // article, through the iterations store (lib/report/iterations.ts), never by // hand. A DRY RUN unless `--apply`: it prints what it would do and writes // nothing. // // Why: a task routed to `code` (settings.generation) runs in Claude Code, which // writes its report to a file; only the editor's API and local jobs made // iterations. Without this the only path into the registry was the release-27 // one-off `import-local-runs`, which labels the result as the retired // stopgap's. This is the general door, and it says where the iteration came // from: `imported: { from: "claude-code" | <--from>, at, report }`. // // The iteration is kind `sweep`, status `done`, `$0` (a Claude Code session is // not billed through the generation ledger), with the question, the channels // and the minutes given. Its report.json is the file given, its `id` set to the // article's and its `audience` dropped (the registry's alone); it must parse as // a report. It is NEVER made current: the operator chooses it in umtool // ("Use this iteration") or `umtool chain ` makes it current as its // first step. A new article id makes an article in the making. // // Exit 0 when the plan is sound (dry run) or the iteration is written (apply); // 1 when it is refused; 2 for a usage error. import { isLocalOnly } from "../lib/llm/localOnly"; import { readFile } from "node:fs/promises"; import path from "node:path"; import type { Paths } from "../lib/paths"; import { createIteration, iterationLabel, readIterations, updateIteration, writeIterationFile } from "../lib/report/iterations"; import { RESERVED_ARTICLE_IDS, readArticleState } from "../lib/report/registry"; import { isReportId } from "../lib/report/schema"; import { parseReport } from "../lib/report/validate"; type StorePaths = Pick; type Out = { log: (s: string) => void; error: (s: string) => void }; export type ImportSweepOptions = { reportFile: string; article: string; question: string; sweepFile?: string; channels?: string[]; model?: string; from?: string; minutes?: number; apply: boolean; paths: StorePaths; now?: () => Date; }; export type ImportSweepPlan = | { ok: false; refused: string } | { ok: true; article: string; articleExists: boolean; nextLabel: string; report: Record; reportIdWas?: string; problems: string[]; sweepMd?: string; model: string; from: string; channels: string[]; }; export const DEFAULT_IMPORT_MODEL = "claude-code"; const CHANNEL_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/; const obj = (v: unknown): Record => (v && typeof v === "object" && !Array.isArray(v) ? (v as Record) : {}); export async function planImportSweep(o: ImportSweepOptions): Promise { const refuse = (refused: string): ImportSweepPlan => ({ ok: false, refused }); const article = o.article.trim(); if (!isReportId(article) || RESERVED_ARTICLE_IDS.includes(article)) return refuse(`"${article}" is not an article id`); if (!o.question.trim()) return refuse("an imported sweep names its question (--question)"); const channels = (o.channels ?? []).map((c) => c.trim()).filter(Boolean); const badChannel = channels.find((c) => !CHANNEL_RE.test(c)); if (badChannel) return refuse(`"${badChannel}" is not a channel slug`); let raw: unknown; try { raw = JSON.parse(await readFile(o.reportFile, "utf8")); } catch (err) { return refuse(`${o.reportFile}: ${(err as NodeJS.ErrnoException).code === "ENOENT" ? "no such file" : "not JSON"}`); } const report = { ...obj(raw) }; const wasId = typeof report.id === "string" ? report.id : undefined; report.id = article; // An iteration's report never carries an audience: the registry's alone. delete report.audience; const parsed = parseReport(report, { id: article }); if (!parsed.ok) { return refuse(`the report does not parse: ${parsed.problems.slice(0, 3).map((p) => `${p.path || "(root)"}: ${p.message}`).join("; ")}`); } let sweepMd: string | undefined; if (o.sweepFile) { try { sweepMd = await readFile(o.sweepFile, "utf8"); } catch { return refuse(`${o.sweepFile}: no such file`); } } const its = await readIterations(article, o.paths).catch(() => null); if (its?.problems.length) return refuse(`"${article}" has unsound iterations (${its.problems.map((p) => iterationLabel(p.n)).join(", ")}); fix them first`); const highest = Math.max(0, ...(its?.iterations ?? []).map((i) => i.n), its?.current?.highest ?? 0); const state = await readArticleState(article, o.paths); return { ok: true, article, articleExists: state?.exists === true, nextLabel: iterationLabel(highest + 1), report, ...(wasId !== article ? { reportIdWas: wasId ?? "(none)" } : {}), problems: parsed.problems.map((p) => `${p.path || "(root)"}: ${p.message}`), ...(sweepMd !== undefined ? { sweepMd } : {}), model: o.model?.trim() || DEFAULT_IMPORT_MODEL, from: o.from?.trim() || "claude-code", channels, }; } export function formatImportSweep(plan: ImportSweepPlan, o: { apply: boolean; reportFile: string }): string[] { if (!plan.ok) return [`reports import-sweep: REFUSED — ${plan.refused}`]; const L = [o.apply ? "reports import-sweep: APPLY" : "reports import-sweep: DRY RUN — nothing is written (--apply writes)"]; L.push( `${o.reportFile} → ${plan.nextLabel} of "${plan.article}", ${plan.articleExists ? "an article the registry has (it is NOT made current)" : "a NEW article in the making (not listed, not a draft, until it is made current)"}`, ); L.push(` sweep on ${plan.model} · from ${plan.from} · $0.00${plan.channels.length ? ` · channels ${plan.channels.join(", ")}` : ""}`); L.push(` files: report.json${plan.reportIdWas ? ` (its id "${plan.reportIdWas}" becomes "${plan.article}")` : ""}${plan.sweepMd !== undefined ? ", sweep.md" : ""}`); if (plan.problems.length) L.push(` the report has ${plan.problems.length} problem(s), so it cannot be made current until they are fixed: ${plan.problems.slice(0, 3).join("; ")}`); L.push(` make it current: umtool's Iterations tab ("Use this iteration"), or \`umtool chain ${plan.article} \` (its first step)`); return L; } export async function importSweepMain(o: ImportSweepOptions, out: Out = console): Promise { const plan = await planImportSweep(o); for (const l of formatImportSweep(plan, { apply: o.apply, reportFile: o.reportFile })) out.log(l); if (!plan.ok) return 1; if (!o.apply) return 0; const now = (o.now ?? (() => new Date()))(); const created = await createIteration( plan.article, { kind: "sweep", model: plan.model, question: o.question.trim(), ...(plan.channels.length ? { scope: { channels: plan.channels } } : {}), status: "running" }, o.paths, now, ); const n = created.n; await writeIterationFile(plan.article, n, "report.json", plan.report, o.paths); if (plan.sweepMd !== undefined) await writeIterationFile(plan.article, n, "sweep.md", plan.sweepMd, o.paths); await updateIteration( plan.article, n, { status: "done", ...(o.minutes !== undefined && Number.isFinite(o.minutes) && o.minutes >= 0 ? { minutes: o.minutes } : {}), endedAt: now.toISOString(), imported: { from: plan.from, at: now.toISOString(), report: path.basename(o.reportFile) }, } as Parameters[2], o.paths, now, ); out.log(`wrote "${plan.article}" ${iterationLabel(n)} (done)`); return 0; } // The CLI row. export async function importSweepRow( reportFile: string | undefined, flags: { article?: string; question?: string; sweep?: string; channels?: string; model?: string; from?: string; minutes?: string; apply?: boolean }, ): Promise { // LOCAL ONLY (lib/llm/localOnly.ts): a report made elsewhere is not // imported into a local-only instance — its words came from a model this // instance cannot vouch for (and `gen local-check` fails on one already in). if (isLocalOnly()) { console.error("reports import-sweep: refused — this instance is local only (ARCHILYZER_LOCAL_ONLY=1), and a report made elsewhere is not imported into it"); return 1; } if (!reportFile || typeof flags.article !== "string" || typeof flags.question !== "string") { console.error("reports import-sweep: give --article --question "); return 2; } const minutes = typeof flags.minutes === "string" ? Number(flags.minutes) : undefined; if (minutes !== undefined && !(Number.isFinite(minutes) && minutes >= 0)) { console.error("reports import-sweep: --minutes is a number of minutes"); return 2; } const { getPaths } = await import("../lib/paths"); return importSweepMain({ reportFile: path.resolve(reportFile), article: flags.article, question: flags.question, ...(typeof flags.sweep === "string" ? { sweepFile: path.resolve(flags.sweep) } : {}), ...(typeof flags.channels === "string" ? { channels: flags.channels.split(",") } : {}), ...(typeof flags.model === "string" ? { model: flags.model } : {}), ...(typeof flags.from === "string" ? { from: flags.from } : {}), ...(minutes !== undefined ? { minutes } : {}), apply: flags.apply === true, paths: getPaths(), }); }