// `archilyzer reports import-local-runs [--apply] [--runs ] [--only ] // [--move-projects]` (release 27 S10; plans/release-27.md D9) — the stopgap's // kept runs (`~/reports/local-reports/runs//`, and its video projects in // `videos//`) become ITERATIONS, 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. // // A run becomes its article's `i1`, kind `sweep`: // - the article is `ui.json`'s `id`, else the run's name; // - iteration.json from run.json: the model, the question, the channels, the // spend per model, the minutes, the checks; `imported` names the run; // - report.json (its `id` set to the article's), sweep.md, and turns.jsonl — // the stopgap's transcript.jsonl in S1's transcript shape where an entry // maps (`start` → a note, `turn` → a response, `tool` → a tool entry), // else kept as it is; // - the video project, when the stopgap has one, copied (or moved, with // `--move-projects`) to `projectOf(projectsRoot, id, 1)` and recorded as // the iteration's `projectDir`. // An ARTICLE THE REGISTRY HAS: i1 is made current (makeCurrent) only when the // run's report.json is the article's (`audience` and `video` aside), and // current for the video when the article has a video attached. A RUN WITH NO // ARTICLE becomes an article in the making: i1, never made current, so nothing // reaches the published list or the drafts until the operator chooses. // // The stopgap's routing policy, `~/.config/archilyzer/generation.json`, when // there is one, becomes `settings.generation.{routes, models}` through the // editor's settings writer (`POST /api/ops/settings`), or settings.json's // (`writeSettings`) when nothing listens at the editor's URL. // // The dry run also lists the stopgap's TEST runs, projects and registry // drafts (D9: `ui-test-*`, `shondo-*`, `local-test-*`) with their sizes, to be // deleted after the operator's OK. This command deletes nothing. // // Exit 0 when every run is importable (dry run) or imported (apply), or was // imported before; 1 when any is refused or fails; 2 for a usage error. import { isLocalOnly } from "../lib/llm/localOnly"; import { projectsRootFrom } from "../lib/projectsRoot.mjs"; import { cp, lstat, mkdir, readdir, readFile, rename, rm, stat } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { pathToFileURL } from "node:url"; import type { GenerationRoute, GenerationSettings } from "../lib/generationSettings"; import { GENERATION_ROUTES, GENERATION_TASKS } from "../lib/generationSettings"; import type { Paths } from "../lib/paths"; import { createIteration, iterationLabel, makeCurrent, projectOf, readIterations, setCurrentVideo, updateIteration, writeIterationFile, type IterationCheck, type IterationUsage, } from "../lib/report/iterations"; import { articleDir, isReportAudience, listArticleDirs, listPendingArticles, readArticleState, RESERVED_ARTICLE_IDS } from "../lib/report/registry"; import { isReportId } from "../lib/report/schema"; import { parseReport } from "../lib/report/validate"; type Out = { log: (s: string) => void; error: (s: string) => void }; type StorePaths = Pick; // D9: the runs imported when --only names none. export const DEFAULT_IMPORT_RUNS = ["piratesoftware-ai-friends", "api-shondo-recent"] as const; // D9: the stopgap's test runs, projects and registry drafts — listed for // deletion after the operator's OK, never deleted here. export const TEST_RUN_PREFIXES = ["ui-test-", "shondo-", "local-test-"] as const; export const DEFAULT_STOPGAP_DIR = path.join(os.homedir(), "reports", "local-reports"); export const DEFAULT_GENERATION_FILE = path.join(os.homedir(), ".config", "archilyzer", "generation.json"); const isTestName = (name: string) => TEST_RUN_PREFIXES.some((p) => name.startsWith(p)); // ─── The stopgap's files ─── type StopgapRunJson = { question?: unknown; channels?: unknown; model?: unknown; extractor?: unknown; minutes?: unknown; converted?: unknown; verified?: unknown; problems?: unknown; by_model?: unknown; }; async function readJson(file: string): Promise<{ ok: true; value: unknown } | { ok: false; why: string }> { let text: string; try { text = await readFile(file, "utf8"); } catch (err) { return { ok: false, why: (err as NodeJS.ErrnoException).code === "ENOENT" ? "absent" : (err as Error).message }; } try { return { ok: true, value: JSON.parse(text) }; } catch { return { ok: false, why: "not JSON" }; } } const obj = (v: unknown): Record => (v && typeof v === "object" && !Array.isArray(v) ? (v as Record) : {}); const num = (v: unknown): number | undefined => (typeof v === "number" && Number.isFinite(v) ? v : undefined); const str = (v: unknown): string | undefined => (typeof v === "string" && v.trim() ? v.trim() : undefined); const nonNeg = (v: unknown) => Math.max(0, Math.round(num(v) ?? 0)); // run.json's `by_model` as the iteration's `usage`. export function usageFromRun(byModel: unknown): Record { const out: Record = {}; for (const [model, raw] of Object.entries(obj(byModel))) { const m = obj(raw); out[model] = { usd: Math.max(0, num(m.usd) ?? 0), inputTokens: nonNeg(m.input), outputTokens: nonNeg(m.output), cacheReadTokens: nonNeg(m.cache_read), cacheWriteTokens: nonNeg(m.cache_write), calls: nonNeg(m.calls), }; } return out; } // run.json's convert and verify results as the iteration's checks. export function checksFromRun(run: StopgapRunJson): IterationCheck[] { const problems = Array.isArray(run.problems) ? run.problems.map(String) : []; const checks: IterationCheck[] = []; if (typeof run.converted === "boolean") checks.push({ name: "convert", ok: run.converted }); if (typeof run.verified === "boolean" || problems.length) { checks.push({ name: "verify-quotes", ok: run.verified !== false && problems.length === 0, ...(problems.length ? { detail: problems.slice(0, 3).join("; ") } : {}), }); } return checks; } // THE STOPGAP'S TRANSCRIPT IN S1'S SHAPE (lib/llm/agent.ts TranscriptEntry) // where an entry maps: `start` → a note (its settings kept under `stopgap`), // `turn` → a response (the text, the tool names it called, usage, USD), `tool` // → a tool entry (the stopgap kept no result: `result` is empty, `chars` its // length). Anything else is kept as it is. A line that is not JSON is kept as // a note naming it. export function mapStopgapTurns(text: string, run: string): { entries: unknown[]; mapped: number; kept: number } { const entries: unknown[] = []; let mapped = 0; let kept = 0; let turn = 0; let model = ""; let prevT: number | undefined; const at = (t: unknown) => (num(t) !== undefined ? new Date((t as number) * 1000).toISOString() : undefined); const lines = text.split("\n").filter((l) => l.trim()); entries.push({ kind: "note", turn: 0, at: at(firstT(lines)) ?? new Date(0).toISOString(), text: `imported from the stopgap run ${run} (transcript.jsonl)` }); for (const [i, line] of lines.entries()) { let e: Record; try { e = obj(JSON.parse(line)); } catch { entries.push({ kind: "note", turn, at: new Date(0).toISOString(), text: `line ${i + 1} of transcript.jsonl is not JSON` }); kept++; continue; } const t = num(e.t); const when = at(t) ?? new Date(0).toISOString(); if (e.kind === "start") { model = str(e.model) ?? model; turn = 0; const { kind: _k, t: _t, ...rest } = e; const parts = [str(e.model) && `model ${String(e.model)}`, str(e.extractor) && `extractor ${String(e.extractor)}`, num(e.max_usd) !== undefined && `cap $${String(e.max_usd)}`].filter(Boolean); entries.push({ kind: "note", turn: 0, at: when, text: `stopgap run started${parts.length ? `: ${parts.join(", ")}` : ""}`, stopgap: rest }); mapped++; } else if (e.kind === "turn") { turn = num(e.n) ?? turn; const content: unknown[] = []; if (typeof e.text === "string" && e.text) content.push({ type: "text", text: e.text }); for (const name of Array.isArray(e.calls) ? e.calls : []) content.push({ type: "tool_use", name: String(name) }); entries.push({ kind: "response", turn, provider: model.startsWith("claude") ? "api" : "local", at: when, stopReason: typeof e.stop === "string" ? e.stop : null, content, usage: obj(e.usage), usd: num(e.usd) ?? 0, }); mapped++; } else if (e.kind === "tool") { entries.push({ kind: "tool", turn, name: String(e.name ?? ""), input: e.input ?? null, result: "", chars: nonNeg(e.chars), error: e.error === true, ms: t !== undefined && prevT !== undefined ? Math.max(0, Math.round((t - prevT) * 1000)) : 0, }); mapped++; } else { entries.push(e); kept++; } if (t !== undefined) prevT = t; } return { entries, mapped, kept }; } function firstT(lines: string[]): number | undefined { for (const l of lines) { try { const t = num(obj(JSON.parse(l)).t); if (t !== undefined) return t; } catch { /* the next */ } } return undefined; } // ─── Sizes ─── // A directory's size, each file once however many links it has (the // stopgap's dedupe hard-links identical segments and voices). `seen` carries // the files already counted across several calls. export async function dirSize(dir: string, seen: Set = new Set()): Promise<{ bytes: number; files: number }> { let bytes = 0; let files = 0; const walk = async (d: string) => { let names: import("node:fs").Dirent[]; try { names = await readdir(d, { withFileTypes: true }); } catch { return; } for (const e of names) { const p = path.join(d, e.name); if (e.isDirectory()) await walk(p); else { const s = await lstat(p).catch(() => null); if (!s) continue; files++; const key = `${s.dev}:${s.ino}`; if (seen.has(key)) continue; seen.add(key); bytes += s.size; } } }; await walk(dir); return { bytes, files }; } export function humanBytes(n: number): string { if (n < 1024) return `${n} B`; const units = ["kB", "MB", "GB"]; let v = n / 1024; let i = 0; while (v >= 1024 && i < units.length - 1) { v /= 1024; i++; } return `${v >= 10 ? v.toFixed(0) : v.toFixed(1)} ${units[i]}`; } const exists = (p: string) => stat(p).then(() => true, () => false); // ─── The plan ─── export type RunPlan = { run: string; dir: string; article: string; // `article`: the registry has it; `pending`: it will be an article in the making. mode: "article" | "pending"; // Why it is not imported; nothing is written for it. refused?: string; // It was imported before: the iteration it is. imported?: number; articleState?: { published: boolean; audience: string; title: string | null; hasVideo: boolean }; model: string; extractor?: string; question: string; channels: string[]; usage: Record; usd: number; minutes?: number; checks: IterationCheck[]; createdAt: Date; endedAt: Date; // report.json's own id, when it is not the article's (it is set to it). reportIdWas?: string; report: Record; reportProblems: string[]; sweepMd: string; turns: { entries: unknown[]; mapped: number; kept: number } | null; // An article's run: whether its report.json is the article's. current?: { match: boolean; differs: string[] }; project?: { from: string; to: string; bytes: number; files: number }; notes: string[]; }; export type GenerationPlan = | { file: string; state: "absent" } | { file: string; state: "unreadable"; why: string } | { file: string; state: "ready"; patch: { routes: Record; models: GenerationSettings["models"] }; changes: string[]; ignored: string[] }; export type CleanupItem = { what: "run" | "project" | "draft"; name: string; path: string; bytes: number; note?: string }; export type ImportPlan = { stopgapDir: string; // What deleting every cleanup item frees, each file once. cleanupBytes: number; projectsRoot: string; runs: RunPlan[]; generation: GenerationPlan; cleanup: CleanupItem[]; // Runs and projects neither imported nor named for deletion. untouched: CleanupItem[]; }; export type ImportOptions = { stopgapDir: string; only?: string[]; projectsRoot: string; generationFile: string; moveProjects?: boolean; paths: StorePaths; currentGeneration: () => GenerationSettings; }; // Two report documents compared as an article: `audience` (the registry's) // and `video` (attached by the stopgap's chain after the run) aside. The // top-level keys that differ. export function reportDifferences(run: Record, article: Record): string[] { const skip = new Set(["audience", "video"]); const keys = new Set([...Object.keys(run), ...Object.keys(article)].filter((k) => !skip.has(k))); return [...keys].filter((k) => JSON.stringify(run[k]) !== JSON.stringify(article[k])).sort(); } async function planRun(run: string, o: ImportOptions): Promise { const dir = path.join(o.stopgapDir, "runs", run); const base: RunPlan = { run, dir, article: run, mode: "pending", model: "", question: "", channels: [], usage: {}, usd: 0, checks: [], createdAt: new Date(0), endedAt: new Date(0), report: {}, reportProblems: [], sweepMd: "", turns: null, notes: [], }; const refuse = (why: string): RunPlan => ({ ...base, refused: why }); if (!(await exists(dir))) return refuse(`no run directory ${dir}`); const ui = await readJson(path.join(dir, "ui.json")); const article = (ui.ok ? str(obj(ui.value).id) : undefined) ?? run; base.article = article; if (!isReportId(article) || RESERVED_ARTICLE_IDS.includes(article)) return refuse(`"${article}" is not an article id`); const runJson = await readJson(path.join(dir, "run.json")); if (!runJson.ok) return refuse(`run.json is ${runJson.why}`); const r = obj(runJson.value) as StopgapRunJson; const model = str(r.model); if (!model) return refuse("run.json names no model"); const question = str(r.question); if (!question) return refuse("run.json has no question"); base.model = model; base.question = question; const extractor = str(r.extractor); if (extractor) base.extractor = extractor; base.channels = (Array.isArray(r.channels) ? r.channels : []).map(String).filter((c) => /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(c)); base.usage = usageFromRun(r.by_model); base.usd = Object.values(base.usage).reduce((s, u) => s + u.usd, 0); const minutes = num(r.minutes); if (minutes !== undefined && minutes >= 0) base.minutes = minutes; base.checks = checksFromRun(r); let sweepMd: string; try { sweepMd = await readFile(path.join(dir, "sweep.md"), "utf8"); } catch { return refuse("there is no sweep.md"); } base.sweepMd = sweepMd; const reportRead = await readJson(path.join(dir, "report.json")); if (!reportRead.ok) return refuse(`report.json is ${reportRead.why}`); const report = { ...obj(reportRead.value) }; const wasId = str(report.id); if (wasId !== article) { base.reportIdWas = wasId ?? "(none)"; report.id = article; } // The 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(`report.json does not parse as a report: ${parsed.problems.slice(0, 3).map((p) => `${p.path || "(root)"}: ${p.message}`).join("; ")}`); base.report = report; base.reportProblems = parsed.problems.map((p) => `${p.path || "(root)"}: ${p.message}`); try { base.turns = mapStopgapTurns(await readFile(path.join(dir, "transcript.jsonl"), "utf8"), run); } catch { base.notes.push("no transcript.jsonl: turns.jsonl is not written"); } // When: the transcript's first stamp (else ui.json's createdAt, else // run.json's time) to run.json's time. const runStat = await stat(path.join(dir, "run.json")); base.endedAt = runStat.mtime; const firstStamp = base.turns ? (base.turns.entries[1] as { at?: string } | undefined)?.at : undefined; const uiCreated = ui.ok ? str(obj(ui.value).createdAt) : undefined; const created = [firstStamp, uiCreated].map((s) => (s ? new Date(s) : null)).find((d) => d && Number.isFinite(d.getTime()) && d.getTime() > 0); base.createdAt = created && created <= base.endedAt ? created : base.endedAt; // The registry: an article, an article in the making, or nothing yet. const state = await readArticleState(article, o.paths); const its = await readIterations(article, o.paths).catch(() => null); const already = its?.iterations.find((it) => obj((it as Record).imported).run === run); if (already) return { ...base, mode: state?.exists ? "article" : "pending", imported: already.n }; if (its && (its.iterations.length || its.problems.length)) { return refuse(`"${article}" has iterations already (${[...its.iterations.map((i) => i.n), ...its.problems.map((p) => p.n)].sort((a, b) => a - b).map(iterationLabel).join(", ")}); the import makes i1`); } if (state?.exists) { base.mode = "article"; const articleRead = await readJson(path.join(articleDir(o.paths, article), "report.json")); const articleDoc = articleRead.ok ? obj(articleRead.value) : {}; base.articleState = { published: state.published, audience: isReportAudience(articleDoc.audience) ? String(articleDoc.audience) : state.audience, title: state.title, hasVideo: articleDoc.video !== undefined, }; const differs = reportDifferences(report, articleDoc); base.current = { match: differs.length === 0, differs }; } else if (state) { // The index names it but its report.json is gone. return refuse(`the registry names "${article}" but it has no report.json`); } const projectFrom = path.join(o.stopgapDir, "videos", run); if (await exists(projectFrom)) { const to = projectOf(o.projectsRoot, article, 1); if (await exists(to)) { const there = await readdir(to).catch(() => []); if (there.length) return refuse(`the project's place ${to} is taken (${there.length} entries)`); } base.project = { from: projectFrom, to, ...(await dirSize(projectFrom)) }; } return base; } async function planGeneration(file: string, current: () => GenerationSettings): Promise { const read = await readJson(file); if (!read.ok) return read.why === "absent" ? { file, state: "absent" } : { file, state: "unreadable", why: read.why }; const g = obj(read.value); const cur = current(); const routes: Record = { ...cur.routes }; const ignored: string[] = []; for (const [task, route] of Object.entries(obj(g.routes))) { if (!(GENERATION_TASKS as readonly string[]).includes(task)) ignored.push(`routes.${task} (no such task)`); else if (!(GENERATION_ROUTES as readonly string[]).includes(String(route))) ignored.push(`routes.${task} = ${JSON.stringify(route)} (not code, api or local)`); else routes[task] = route as GenerationRoute; } const m = obj(g.models); const models = { ...cur.models }; for (const k of ["api", "local", "extractor"] as const) { if (m[k] === undefined) continue; const v = str(m[k]); if (v) models[k] = v; else ignored.push(`models.${k} (not a model name)`); } for (const k of Object.keys(g)) if (!["preset", "routes", "models"].includes(k)) ignored.push(`${k} (not carried)`); const changes: string[] = []; for (const t of GENERATION_TASKS) if (routes[t] !== cur.routes[t]) changes.push(`routes.${t}: ${cur.routes[t]} → ${routes[t]}`); for (const k of ["api", "local", "extractor"] as const) if (models[k] !== cur.models[k]) changes.push(`models.${k}: ${cur.models[k]} → ${models[k]}`); return { file, state: "ready", patch: { routes, models }, changes, ignored }; } async function planCleanup(o: ImportOptions, importing: Set): Promise<{ cleanup: CleanupItem[]; untouched: CleanupItem[]; cleanupBytes: number }> { const cleanup: CleanupItem[] = []; const untouched: CleanupItem[] = []; for (const [what, sub] of [["run", "runs"], ["project", "videos"]] as const) { const root = path.join(o.stopgapDir, sub); const names = (await readdir(root, { withFileTypes: true }).catch(() => [])).filter((e) => e.isDirectory()).map((e) => e.name).sort(); for (const name of names) { const p = path.join(root, name); const item: CleanupItem = { what, name, path: p, bytes: (await dirSize(p)).bytes }; if (isTestName(name)) cleanup.push(item); else if (!importing.has(name)) untouched.push(item); } } for (const id of [...(await listArticleDirs(o.paths)), ...(await listPendingArticles(o.paths))]) { if (!isTestName(id)) continue; const state = await readArticleState(id, o.paths); const p = articleDir(o.paths, id); cleanup.push({ what: "draft", name: id, path: p, bytes: (await dirSize(p)).bytes, ...(state?.published ? { note: "PUBLISHED — unpublish first" } : {}), }); } return { cleanup, untouched, cleanupBytes: await sumSeen(cleanup.map((c) => c.path)) }; } async function sumSeen(dirs: string[]): Promise { const seen = new Set(); let bytes = 0; for (const d of dirs) bytes += (await dirSize(d, seen)).bytes; return bytes; } export async function planImport(o: ImportOptions): Promise { const names = o.only?.length ? o.only : [...DEFAULT_IMPORT_RUNS]; const runs: RunPlan[] = []; for (const run of names) runs.push(await planRun(run, o)); const { cleanup, untouched, cleanupBytes } = await planCleanup(o, new Set(names)); return { stopgapDir: o.stopgapDir, projectsRoot: o.projectsRoot, runs, generation: await planGeneration(o.generationFile, o.currentGeneration), cleanup, cleanupBytes, untouched, }; } // ─── Printing ─── const usd = (n: number) => `$${n.toFixed(2)}`; const utc = (d: Date) => `${d.toISOString().slice(0, 16).replace("T", " ")} UTC`; const one = (s: string, max = 100) => { const t = s.replace(/\s+/g, " ").trim(); return t.length > max ? `${t.slice(0, max - 1)}…` : t; }; export function formatPlan(plan: ImportPlan, o: { apply: boolean; moveProjects: boolean }): string[] { const L: string[] = []; L.push(o.apply ? "reports import-local-runs: APPLY" : "reports import-local-runs: DRY RUN — nothing is written (--apply writes)"); L.push(`stopgap: ${plan.stopgapDir}`); L.push(`projects root: ${plan.projectsRoot}`); for (const r of plan.runs) { L.push(""); if (r.refused) { L.push(`${r.run}: REFUSED — ${r.refused}`); continue; } if (r.imported !== undefined) { L.push(`${r.run}: already imported as "${r.article}" ${iterationLabel(r.imported)} — nothing to do`); continue; } const a = r.articleState; L.push( r.mode === "article" ? `${r.run} → i1 of the article "${r.article}" (${a?.published ? "published" : "a draft"}, ${a?.audience ?? "private"})` : `${r.run} → i1 of "${r.article}", a NEW article in the making (not made current: not listed, not a draft, until the operator chooses)`, ); const by = Object.entries(r.usage).map(([m, u]) => `${m} ${usd(u.usd)}`).join(", "); L.push(` sweep on ${r.model}${r.extractor ? ` (extractor ${r.extractor})` : ""} · ${usd(r.usd)}${by ? ` (${by})` : ""}${r.minutes !== undefined ? ` · ${r.minutes} min` : ""} · ${utc(r.createdAt)} → ${utc(r.endedAt)}`); L.push(` question: “${one(r.question)}”`); if (r.channels.length) L.push(` channels: ${r.channels.join(", ")}`); if (r.checks.length) L.push(` checks: ${r.checks.map((c) => `${c.name} ${c.ok ? "ok" : "FAILED"}${c.detail ? ` (${one(c.detail, 60)})` : ""}`).join(", ")}`); const files = [ `report.json${r.reportIdWas ? ` (its id "${r.reportIdWas}" becomes "${r.article}")` : ""}`, `sweep.md (${humanBytes(Buffer.byteLength(r.sweepMd))})`, ...(r.turns ? [`turns.jsonl (${r.turns.entries.length} lines: ${r.turns.mapped} in S1's shape, ${r.turns.kept} kept as they were, 1 import note)`] : []), ]; L.push(` files: ${files.join(", ")}`); if (r.reportProblems.length) L.push(` report.json has ${r.reportProblems.length} problem(s), so it cannot be made current: ${r.reportProblems.slice(0, 3).join("; ")}`); if (r.mode === "article" && r.current) { if (r.current.match && !r.reportProblems.length) { L.push(` report.json IS the article's (audience and video aside) → i1 made current for the article (the same document is written)`); } else if (!r.current.match) { L.push(` report.json is NOT the article's — differs in: ${r.current.differs.join(", ")} → i1 is NOT made current; the article is unchanged`); } } if (r.project) { L.push(` video project: ${r.project.from} (${humanBytes(r.project.bytes)}, ${r.project.files} files) → ${o.moveProjects ? "moved" : "copied"} to ${r.project.to}`); if (r.mode === "article") { L.push(a?.hasVideo ? " the article has a video attached → i1 made current for the video" : " the article has no video attached → the video is not marked current"); } } for (const n of r.notes) L.push(` note: ${n}`); } L.push(""); const g = plan.generation; if (g.state === "absent") L.push(`generation.json: none at ${g.file} — nothing to carry into settings.generation`); else if (g.state === "unreadable") L.push(`generation.json: ${g.file} is ${g.why} — not carried`); else { L.push(`generation.json: ${g.file} → settings.generation (the editor's settings writer, else settings.json's)`); L.push(g.changes.length ? ` patch: ${g.changes.join("; ")}` : " patch: none (settings.generation already says the same)"); if (g.ignored.length) L.push(` not carried: ${g.ignored.join("; ")}`); } L.push(""); L.push(`To delete after the operator's OK (D9; not touched here) — ${plan.cleanup.length} item(s), ${humanBytes(plan.cleanupBytes)} freed (a file hard-linked into several counted once):`); for (const what of ["run", "project", "draft"] as const) { const items = plan.cleanup.filter((c) => c.what === what); if (!items.length) continue; L.push(` ${what === "run" ? "runs" : what === "project" ? "video projects" : "registry drafts"}:`); for (const c of items) L.push(` ${c.path} ${humanBytes(c.bytes)}${c.note ? ` ${c.note}` : ""}`); } if (plan.untouched.length) { L.push("Neither imported nor named for deletion (kept):"); for (const c of plan.untouched) L.push(` ${c.path} ${humanBytes(c.bytes)}`); } return L; } // ─── Applying ─── export type GenerationWriter = (patch: { routes: Record; models: GenerationSettings["models"] }) => Promise; async function copyProject(from: string, to: string, move: boolean): Promise { await mkdir(path.dirname(to), { recursive: true }); if (move) { try { await rename(from, to); return; } catch (err) { if ((err as NodeJS.ErrnoException).code !== "EXDEV") throw err; } } await cp(from, to, { recursive: true, errorOnExist: true, force: false, preserveTimestamps: true, verbatimSymlinks: true }); if (move) await rm(from, { recursive: true, force: true }); } async function applyRun(r: RunPlan, o: { paths: StorePaths; moveProjects: boolean; now: Date }, log: (s: string) => void): Promise { const created = await createIteration( r.article, { kind: "sweep", model: r.model, question: r.question, ...(r.channels.length ? { scope: { channels: r.channels } } : {}), status: "running" }, o.paths, r.createdAt, ); if (created.n !== 1) throw new Error(`"${r.article}" got ${iterationLabel(created.n)}, not i1 (another writer?) — stopped there`); const n = created.n; await writeIterationFile(r.article, n, "report.json", r.report, o.paths); await writeIterationFile(r.article, n, "sweep.md", r.sweepMd, o.paths); if (r.turns) await writeIterationFile(r.article, n, "turns.jsonl", r.turns.entries.map((e) => JSON.stringify(e)).join("\n") + "\n", o.paths); if (r.project) { await copyProject(r.project.from, r.project.to, o.moveProjects); log(` ${o.moveProjects ? "moved" : "copied"} the video project to ${r.project.to}`); } await updateIteration( r.article, n, { status: "done", usage: r.usage, ...(r.minutes !== undefined ? { minutes: r.minutes } : {}), checks: r.checks, ...(r.project ? { projectDir: r.project.to } : {}), endedAt: r.endedAt.toISOString(), imported: { from: "local-reports", run: r.run, at: o.now.toISOString(), ...(r.extractor ? { extractor: r.extractor } : {}) }, } as Parameters[2], o.paths, o.now, ); log(` wrote "${r.article}" i1 (done)`); if (r.mode === "article" && r.current?.match && !r.reportProblems.length) { await makeCurrent(r.article, n, o.paths, o.now); log(" i1 made current for the article"); if (r.project && r.articleState?.hasVideo) { await setCurrentVideo(r.article, n, o.paths, o.now); log(" i1 made current for the video"); } } } export async function importMain( o: ImportOptions & { apply: boolean; generationWriter?: GenerationWriter; now?: () => Date }, out: Out = console, ): Promise { const plan = await planImport(o); for (const l of formatPlan(plan, { apply: o.apply, moveProjects: o.moveProjects === true })) out.log(l); let bad = plan.runs.some((r) => r.refused); if (!o.apply) { out.log(""); out.log(bad ? "dry run: a run is refused (above); --apply would import the rest" : "dry run: nothing written"); return bad ? 1 : 0; } out.log(""); const now = (o.now ?? (() => new Date()))(); for (const r of plan.runs) { if (r.refused || r.imported !== undefined) continue; out.log(`${r.run}:`); try { await applyRun(r, { paths: o.paths, moveProjects: o.moveProjects === true, now }, (s) => out.log(s)); } catch (err) { bad = true; out.error(` FAILED: ${(err as Error).message}`); } } if (plan.generation.state === "ready" && plan.generation.changes.length) { try { const where = await (o.generationWriter ?? defaultGenerationWriter())(plan.generation.patch); out.log(`settings.generation written through ${where}`); } catch (err) { bad = true; out.error(`settings.generation: FAILED — ${(err as Error).message}`); } } out.log(bad ? "import: done with failures (above)" : "import: done"); return bad ? 1 : 0; } // The editor's settings writer (`POST /api/ops/settings`, with `pnpm ops`'s // env) when it answers; settings.json's writer when nothing listens there. An // editor that is there and refuses, or does not answer, is an error, and // settings.json is never written beside it (as `archilyzer gen`). export function defaultGenerationWriter(env: NodeJS.ProcessEnv = process.env, fetchImpl: typeof fetch = fetch): GenerationWriter { return async (patch) => { const { REPO_ROOT } = await import("./_spawnBin"); const ops = (await import(pathToFileURL(path.join(REPO_ROOT, "scripts", "archilyzer-ops.mjs")).href)) as { loadEditorEnv: (env: NodeJS.ProcessEnv) => Record; tokenHint: (status: number, sources: Record, url: string) => string; }; const sources = ops.loadEditorEnv(env); const base = (env.ARCHILYZER_EDITOR_URL || "http://localhost:3001").replace(/\/+$/, ""); const token = env.WORKER_TOKEN ?? ""; let res: Response; try { res = await fetchImpl(`${base}/api/ops/settings`, { method: "POST", headers: { "content-type": "application/json", ...(token ? { authorization: `Bearer ${token}` } : {}) }, body: JSON.stringify({ patch: { generation: patch } }), signal: AbortSignal.timeout(15_000), }); } catch (e) { const code = (e as Error & { cause?: { code?: string } }).cause?.code ?? ""; if (!/ECONNREFUSED|ENOTFOUND|EHOSTUNREACH|EAI_AGAIN/.test(code)) { throw new Error(`the editor at ${base} did not answer (${(e as Error).name === "TimeoutError" ? "no answer within 15 s" : (e as Error).message}) — not writing settings.json beside a running editor`); } const { getSettings, writeSettings } = await import("../lib/settings"); const { getPaths } = await import("../lib/paths"); const s = getSettings(); await writeSettings({ ...s, generation: { ...s.generation, routes: { ...s.generation.routes, ...patch.routes }, models: { ...s.generation.models, ...patch.models } } }); return `settings.json (${getPaths().settingsFile}; no editor answering)`; } const j = (await res.json().catch(() => null)) as Record | null; if (!res.ok || !j || j.ok === false) { const error = typeof j?.error === "string" ? j.error : `HTTP ${res.status}`; throw new Error(`the editor refused (HTTP ${res.status}): ${error}${res.status === 401 || res.status === 503 ? ` (${ops.tokenHint(res.status, sources, base)})` : ""}`); } return `the editor at ${base}`; }; } const expandHome = (p: string) => (p === "~" ? os.homedir() : p.startsWith("~/") ? path.join(os.homedir(), p.slice(2)) : p); // settings.generation.projectsRoot, `~` expanded; blank = ~/reports/articles // (controller/reportDraft.ts projectsRootOf, which a bin does not import). const projectsRootOf = (gen: GenerationSettings) => (projectsRootFrom(gen.projectsRoot)); // The CLI row's options, from the flags and the settings. export async function importRow(flags: { apply?: boolean; runs?: string; only?: string; "move-projects"?: boolean; generation?: string }): 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-local-runs: refused — this instance is local only (ARCHILYZER_LOCAL_ONLY=1), and a report made elsewhere is not imported into it"); return 1; } const only = typeof flags.only === "string" ? flags.only.split(",").map((s) => s.trim()).filter(Boolean) : undefined; if (flags.only !== undefined && !only?.length) { console.error("reports import-local-runs: --only names runs, comma-separated"); return 2; } const { getPaths } = await import("../lib/paths"); const { getSettings } = await import("../lib/settings"); const gen = getSettings().generation; return importMain({ apply: flags.apply === true, stopgapDir: typeof flags.runs === "string" ? path.resolve(expandHome(flags.runs)) : DEFAULT_STOPGAP_DIR, ...(only ? { only } : {}), projectsRoot: projectsRootOf(gen), generationFile: typeof flags.generation === "string" ? path.resolve(expandHome(flags.generation)) : DEFAULT_GENERATION_FILE, moveProjects: flags["move-projects"] === true, paths: getPaths(), currentGeneration: () => getSettings().generation, }); }