// `archilyzer gen policy|preset|set|run` — the generation balance from a // terminal (release 27 S9; D8): the stopgap's `gen` over settings.generation. // // archilyzer gen policy [--json] the routes, models, caps and the day's API spend // archilyzer gen preset code|balanced|api|local route every task at once // archilyzer gen set code|api|local route one task // archilyzer gen local-sweep [--form neutral|sentence] [--read-aloud flag|drop|off] // the local sweep's claim form and read-aloud rule // (settings.generation.localSweep); bare: what they are // archilyzer gen model [api|local|extractor ] the model a route runs (settings.generation.models) // archilyzer gen local-check [--since D] [--json] whether the instance stayed local (D5): exit 1 if not // archilyzer gen run [] --article [--via api|local|code] […] [--wait] // enqueue a report-draft job (`pnpm ops report-draft`); // a media draft (cut, onscreen, teaser, flips, threads, // narrate, youtube, social) takes --iteration, --entries, --force // // THROUGH THE EDITOR when it answers: `GET/POST /api/ops/settings` (its one // settings writer) and `GET /api/ops/generation-usage`, with the token // `pnpm ops` reads (WORKER_TOKEN / ARCHILYZER_EDITOR_URL, else editor/.env). // OFFLINE when nothing listens at the editor's URL (the connection is // refused): settings.json through the settings writer (`writeSettings`) and // the ledger off disk — the way `archilyzer release cut` works with no editor. // An editor that is there but does not answer, or refuses the token, is an // error: settings.json is never written beside a running editor. // // `run` asks the policy first and EXITS 3, running nothing, when the task is // routed to code (Claude Code does it in its session — the stopgap's // contract); `--via` overrides the route once, `--model` names the model // outright. The job itself is `pnpm ops report-draft` (a child), so `--wait` // follows it exactly as `pnpm ops … --wait` does and prints its result. // // The API key is never read, printed or written here: it is not a setting. import os from "node:os"; import path from "node:path"; import { pathToFileURL } from "node:url"; import type { CommandContext } from "./_cli"; import type { FlagValue } from "./_parseFlags"; import { REPO_ROOT, runChild } from "./_spawnBin"; import { CLAIM_FORMS, READ_ALOUD_MODES, type ClaimForm, type GenerationLocalSweep, type ReadAloudMode, GENERATION_PRESETS, GENERATION_PRESET_NAMES, GENERATION_ROUTES, MEDIA_STEP_TASKS, isStepTask, type GenerationPreset, type GenerationRoute, } from "../lib/generationSettings"; import { isCloudOllamaModel, isLocalModelUrl, isLocalOnly, localOnlyFlag, localOnlyRoutesRefusal, modelHostOf } from "../lib/llm/localOnly"; import type { GenerationUsageRow } from "../controller/generationUsage"; type Out ={ log: (s: string) => void; error: (s: string) => void }; // The part of settings.generation this command shows and changes. export type GenPolicy = { preset: string; routes: Record; models: { api: string; local: string; extractor?: string }; caps?: Record; localSweep?: GenerationLocalSweep; }; export type GenUsage = { day: string; usd: number; jobs: number; daily: number }; // Where the policy is read and written: the editor, or settings.json offline. export type GenStore = { where: string; // settings.json with no editor answering: generation jobs cannot run. offline: boolean; read(): Promise; usage(): Promise; writeRoutes(routes: Record): Promise; writeLocalSweep(localSweep: GenerationLocalSweep): Promise; writeModels?(models: GenPolicy["models"]): Promise; // Whether the editor itself runs local only (ARCHILYZER_LOCAL_ONLY in ITS // environment), or null when no editor answers. editorLocalOnly?(): Promise; // One top-level settings key as the store holds it (secrets redacted), or null. readKey?(key: string): Promise; }; export type GenDeps = { // The store, or why there is none (an editor that is there and refuses). store: () => Promise; // `pnpm ops ` as a child; its exit code. runOps: (argv: string[]) => Promise; out?: Out; // This process's environment (ARCHILYZER_LOCAL_ONLY, ANTHROPIC_API_KEY's // presence); default process.env. env?: Record; // `gen local-check`: what it judges (default: the editor's settings, the // ledger, the per-call logs and the iterations, off disk) and whether an API // key is at hand (its env var or file's presence, never read out). evidence?: (store: GenStore) => Promise; apiKeyAtHand?: () => Promise<"env" | "file" | null>; }; const TASKS_HELP = `sweep, revise-report, revise-video, research, or a media draft: ${MEDIA_STEP_TASKS.join(", ")}`; const isRoute = (v: unknown): v is GenerationRoute => typeof v === "string" && (GENERATION_ROUTES as readonly string[]).includes(v); export function policyFrom(value: unknown): GenPolicy | null { if (!value || typeof value !== "object") return null; const v = value as Record; const routes: Record = {}; for (const [t, r] of Object.entries((v.routes as Record) ?? {})) if (isRoute(r)) routes[t] = r; const m = (v.models as Record) ?? {}; if (typeof m.api !== "string" || typeof m.local !== "string") return null; return { preset: typeof v.preset === "string" ? v.preset : "custom", routes, models: { api: m.api, local: m.local, ...(typeof m.extractor === "string" ? { extractor: m.extractor } : {}) }, ...(v.caps && typeof v.caps === "object" ? { caps: v.caps as Record } : {}), ...(localSweepFrom(v.localSweep) ? { localSweep: localSweepFrom(v.localSweep)! } : {}), }; } function localSweepFrom(value: unknown): GenerationLocalSweep | null { const v = value && typeof value === "object" ? (value as Record) : null; if (!v || !(CLAIM_FORMS as readonly unknown[]).includes(v.claimForm) || !(READ_ALOUD_MODES as readonly unknown[]).includes(v.readAloud)) return null; return { claimForm: v.claimForm as ClaimForm, readAloud: v.readAloud as ReadAloudMode }; } const FORM_WORDS: Record = { neutral: "neutral (code writes each line: In (<date>), on <topic>: \"<quote>\")", sentence: "sentence (the model drafts each claim; a meaning check judges it)", }; const READ_ALOUD_WORDS: Record<ReadAloudMode, string> = { flag: "flag (kept, marked to check by ear)", drop: "drop (left out)", off: "off (not looked for)", }; export function formatLocalSweep(ls: GenerationLocalSweep): string[] { return [`local sweep: claim form ${FORM_WORDS[ls.claimForm]}`, ` a quote that may be read aloud: ${READ_ALOUD_WORDS[ls.readAloud]}`]; } const usd = (n: number) => `$${n.toFixed(2)}`; export function formatPolicy(p: GenPolicy, usage: GenUsage | null): string[] { const lines = [ `preset ${p.preset} · api model ${p.models.api} · local model ${p.models.local}${p.models.extractor ? ` · extractor ${p.models.extractor}` : ""}`, ...Object.entries(p.routes).map(([t, r]) => ` ${t.padEnd(14)} → ${r}`), ]; const c = p.caps; if (c) { lines.push( `caps: ${["sweep", "revision", "narration", "max"].filter((k) => typeof c[k] === "number").map((k) => `${k} ${usd(c[k])}`).join(" · ")}` + (typeof c.daily === "number" ? ` · ${c.daily > 0 ? `daily ${usd(c.daily)}` : "no daily cap"}` : ""), ); } if (p.localSweep) lines.push(...formatLocalSweep(p.localSweep)); if (usage) lines.push(`today ${usage.day} (UTC): ${usd(usage.usd)} on the Claude API in ${usage.jobs} job(s)`); return lines; } // ─── The two stores ─── type Answer = { kind: "ok"; body: Record<string, unknown> } | { kind: "refused"; status: number; error: string } | { kind: "absent"; message: string } | { kind: "silent"; message: string }; // The editor's ops API with `pnpm ops`'s env (the same files, never printed). export async function editorStore(env: NodeJS.ProcessEnv = process.env, fetchImpl: typeof fetch = fetch): Promise<GenStore | { error: string } | null> { const ops = (await import(pathToFileURL(path.join(REPO_ROOT, "scripts", "archilyzer-ops.mjs")).href)) as { loadEditorEnv: (env: NodeJS.ProcessEnv) => Record<string, string>; tokenHint: (status: number, sources: Record<string, string>, url: string) => string; }; const sources = ops.loadEditorEnv(env); const base = (env.ARCHILYZER_EDITOR_URL || "http://localhost:3001").replace(/\/+$/, ""); const token = env.WORKER_TOKEN ?? ""; const call = async (method: "GET" | "POST", route: string, body?: unknown): Promise<Answer> => { let res: Response; try { res = await fetchImpl(`${base}${route}`, { method, headers: { ...(token ? { authorization: `Bearer ${token}` } : {}), ...(body ? { "content-type": "application/json" } : {}) }, ...(body ? { body: JSON.stringify(body) } : {}), signal: AbortSignal.timeout(15_000), }); } catch (e) { const err = e as Error & { cause?: { code?: string } }; const code = err.cause?.code ?? ""; // Nothing listening: offline. Anything else (a timeout above all) may be // an editor too busy to answer — never write the file beside it. if (/ECONNREFUSED|ENOTFOUND|EHOSTUNREACH|EAI_AGAIN/.test(code)) return { kind: "absent", message: `${code} at ${base}` }; return { kind: "silent", message: err.name === "TimeoutError" ? "no answer within 15 s" : err.message }; } const j = (await res.json().catch(() => null)) as Record<string, unknown> | null; if (res.ok && j && j.ok !== false) return { kind: "ok", body: j }; const error = typeof j?.error === "string" ? j.error : `HTTP ${res.status}`; return { kind: "refused", status: res.status, error: res.status === 401 || res.status === 503 ? `${error} (${ops.tokenHint(res.status, sources, base)})` : error }; }; const first = await call("GET", "/api/ops/settings?key=generation"); if (first.kind === "absent") return null; if (first.kind === "silent") return { error: `the editor at ${base} did not answer (${first.message}) — not writing settings.json beside a running editor` }; if (first.kind === "refused") return { error: `the editor at ${base} refused (HTTP ${first.status}): ${first.error}` }; let readOnce = false; const fail = (a: Answer) => new Error(a.kind === "refused" ? `the editor refused (HTTP ${a.status}): ${a.error}` : `the editor at ${base}: ${"message" in a ? a.message : "no answer"}`); const read = async () => { const a = first.kind === "ok" && !readOnce ? first : await call("GET", "/api/ops/settings?key=generation"); readOnce = true; if (a.kind !== "ok") throw fail(a); const p = policyFrom(a.body.value); if (!p) throw new Error("the editor's answer carried no generation block"); return p; }; return { where: `the editor at ${base}`, offline: false, read, async usage() { const a = await call("GET", "/api/ops/generation-usage"); if (a.kind !== "ok" || typeof a.body.usd !== "number") return null; return { day: String(a.body.day), usd: a.body.usd, jobs: Number(a.body.jobs) || 0, daily: Number(a.body.daily) || 0 }; }, async writeRoutes(routes) { const a = await call("POST", "/api/ops/settings", { patch: { generation: { routes } } }); if (a.kind !== "ok") throw fail(a); const p = policyFrom((a.body.value as Record<string, unknown> | undefined)?.generation); if (!p) throw new Error("the editor's answer carried no generation block"); return p; }, async writeLocalSweep(localSweep) { const a = await call("POST", "/api/ops/settings", { patch: { generation: { localSweep } } }); if (a.kind !== "ok") throw fail(a); const p = policyFrom((a.body.value as Record<string, unknown> | undefined)?.generation); if (!p) throw new Error("the editor's answer carried no generation block"); return p; }, async writeModels(models) { const a = await call("POST", "/api/ops/settings", { patch: { generation: { models } } }); if (a.kind !== "ok") throw fail(a); const p = policyFrom((a.body.value as Record<string, unknown> | undefined)?.generation); if (!p) throw new Error("the editor's answer carried no generation block"); return p; }, async editorLocalOnly() { const a = await call("GET", "/api/ops/generation-usage"); return a.kind === "ok" && typeof a.body.localOnly === "boolean" ? a.body.localOnly : null; }, async readKey(key) { const a = await call("GET", `/api/ops/settings?key=${encodeURIComponent(key)}`); return a.kind === "ok" ? (a.body.value ?? null) : null; }, }; } // settings.json and the ledger, with no editor running. export async function offlineStore(): Promise<GenStore> { const { getSettings, writeSettings } = await import("../lib/settings"); const { getPaths } = await import("../lib/paths"); const { dayUsage } = await import("../controller/generationUsage"); const read = async () => policyFrom(getSettings().generation)!; return { where: `settings.json (${getPaths().settingsFile}; no editor answering)`, offline: true, read, async usage() { const s = getSettings(); return { ...(await dayUsage(getPaths().generationUsageFile)), daily: s.generation.caps.daily }; }, async writeRoutes(routes) { const s = getSettings(); // The one settings writer; the schema derives the preset from the routes. await writeSettings({ ...s, generation: { ...s.generation, routes: { ...s.generation.routes, ...routes } as typeof s.generation.routes } }); return read(); }, async writeLocalSweep(localSweep) { const s = getSettings(); await writeSettings({ ...s, generation: { ...s.generation, localSweep } }); return read(); }, async writeModels(models) { const s = getSettings(); await writeSettings({ ...s, generation: { ...s.generation, models: { ...s.generation.models, ...models } } }); return read(); }, async editorLocalOnly() { return null; }, }; } export async function defaultStore(env: NodeJS.ProcessEnv = process.env): Promise<GenStore | { error: string }> { return (await editorStore(env)) ?? (await offlineStore()); } // ─── The verbs ─── export async function policyMain(o: { json: boolean }, deps: GenDeps): Promise<number> { const out = deps.out ?? console; const store = await deps.store(); if ("error" in store) { out.error(`gen policy: ${store.error}`); return 1; } const p = await store.read(); const usage = await store.usage(); if (o.json) out.log(JSON.stringify({ ...p, usage, from: store.where }, null, 2)); else for (const l of [...formatPolicy(p, usage), `(from ${store.where})`]) out.log(l); return 0; } export async function setMain(o: { preset?: string; task?: string; route?: string }, deps: GenDeps): Promise<number> { const out = deps.out ?? console; const name = o.preset !== undefined ? "gen preset" : "gen set"; if (o.preset !== undefined && !(GENERATION_PRESET_NAMES as string[]).includes(o.preset)) { out.error(`gen preset: one of ${GENERATION_PRESET_NAMES.join(", ")}`); return 2; } if (o.preset === undefined && (!o.task || !isRoute(o.route))) { out.error(`gen set: <task> ${GENERATION_ROUTES.join("|")}`); return 2; } const store = await deps.store(); if ("error" in store) { out.error(`${name}: ${store.error}`); return 1; } const p = await store.read(); if (o.task && !Object.hasOwn(p.routes, o.task)) { out.error(`gen set: no task "${o.task}" — the policy routes ${Object.keys(p.routes).join(", ")}`); return 2; } // Choosing a preset is writing its routes; the preset is read back from them. const routes = o.preset ? { ...p.routes, ...GENERATION_PRESETS[o.preset as GenerationPreset] } : { ...p.routes, [o.task!]: o.route as GenerationRoute }; // LOCAL ONLY: here too, for the offline store (the editor refuses its own). const refusal = localOnlyRoutesRefusal(routes, deps.env); if (refusal) { out.error(`${name}: ${refusal}`); return 1; } const saved = await store.writeRoutes(routes); for (const l of [...formatPolicy(saved, await store.usage()), `(written to ${store.where})`]) out.log(l); return 0; } // `gen local-sweep`: the local sweep's claim form and what it does with a // quote that may be read aloud (settings.generation.localSweep). Bare: what // they are. export async function localSweepMain(o: { form?: string; readAloud?: string }, deps: GenDeps): Promise<number> { const out = deps.out ?? console; if (o.form !== undefined && !(CLAIM_FORMS as readonly string[]).includes(o.form)) { out.error(`gen local-sweep: --form is one of ${CLAIM_FORMS.join(", ")}`); return 2; } if (o.readAloud !== undefined && !(READ_ALOUD_MODES as readonly string[]).includes(o.readAloud)) { out.error(`gen local-sweep: --read-aloud is one of ${READ_ALOUD_MODES.join(", ")}`); return 2; } const store = await deps.store(); if ("error" in store) { out.error(`gen local-sweep: ${store.error}`); return 1; } const p = await store.read(); if (!p.localSweep) { out.error(`gen local-sweep: ${store.where} carries no generation.localSweep (an editor older than this checkout?)`); return 1; } if (o.form === undefined && o.readAloud === undefined) { for (const l of [...formatLocalSweep(p.localSweep), `(from ${store.where})`]) out.log(l); return 0; } const saved = await store.writeLocalSweep({ claimForm: (o.form as ClaimForm | undefined) ?? p.localSweep.claimForm, readAloud: (o.readAloud as ReadAloudMode | undefined) ?? p.localSweep.readAloud, }); for (const l of [...formatLocalSweep(saved.localSweep ?? p.localSweep), `(written to ${store.where})`]) out.log(l); return 0; } // `gen model <api|local|extractor> <name>`: the model a route runs // (settings.generation.models). Bare `gen model`: the three. const MODEL_SLOTS = ["api", "local", "extractor"] as const; type ModelSlot = (typeof MODEL_SLOTS)[number]; const MODEL_NAME = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/; export async function modelMain(o: { slot?: string; name?: string }, deps: GenDeps): Promise<number> { const out = deps.out ?? console; if (o.slot !== undefined && !(MODEL_SLOTS as readonly string[]).includes(o.slot)) { out.error(`gen model: ${MODEL_SLOTS.join("|")} <model>`); return 2; } if (o.name !== undefined && !MODEL_NAME.test(o.name)) { out.error(`gen model: "${o.name}" is not a model name (letters, digits and . _ : / -)`); return 2; } if (o.slot !== undefined && o.name === undefined) { out.error(`gen model: ${o.slot} <model> — name the model`); return 2; } const store = await deps.store(); if ("error" in store) { out.error(`gen model: ${store.error}`); return 1; } const p = await store.read(); const show = (q: GenPolicy, verb: string) => out.log(`api ${q.models.api} · local ${q.models.local}${q.models.extractor ? ` · extractor ${q.models.extractor}` : ""} (${verb} ${store.where})`); if (o.slot === undefined) { show(p, "from"); return 0; } const slot = o.slot as ModelSlot; const name = o.name!; if (isLocalOnly(deps.env) && (slot === "api" ? false : name.startsWith("claude") || isCloudOllamaModel(name))) { out.error(`gen model: this instance is local only (ARCHILYZER_LOCAL_ONLY=1): "${name}" is not a local model`); return 1; } if (!store.writeModels) { out.error(`gen model: ${store.where} cannot write models`); return 1; } if (p.models[slot] === name) { show(p, "already, in"); return 0; } show(await store.writeModels({ ...p.models, [slot]: name }), "written to"); return 0; } // `gen local-check [--since YYYY-MM-DD] [--json]` (demo epic D5): whether // this instance has stayed local, by counts, hosts and route names — never a // key, a key file's path or its contents, never an absolute home path. // // guard ARCHILYZER_LOCAL_ONLY on (the editor's own answer when one // answers); a value the flag does not understand is named // routes every generation route local // endpoints every model server a local route asks (generation.ollamaUrl, // else OLLAMA_URL; the digest's ollama; each enabled LLM worker) // on this machine — loopback, or ARCHILYZER_LOCAL_MODEL_HOSTS // api key none at hand (presence only) // ledger the usage ledger since the date: no Claude API row // model log the per-call logs (calls/<jobId>, and the iterations they // point at): no call on a route but local // imports no iteration imported from a run made elsewhere // (`reports import-sweep`, `reports import-local-runs`, which // local only refuses) // // Exit 1 when any check FAILS. When none fails but neither the ledger nor the // model log holds a call yet, the verdict is "nothing to prove yet" (exit 0): // the setup is local only, and no model call has been recorded to prove it by. export type CheckStatus = "ok" | "fail" | "none"; export type LocalCheck = { name: string; ok: boolean; status: CheckStatus; line: string }; export type LocalEndpoint = { what: string; url: string }; export type LoggedCall = { route: string; at: string; model: string }; export type ImportedIteration = { article: string; n: number; at: string; from: string }; export type LocalVerdict = "pass" | "fail" | "nothing-yet"; const check = (name: string, status: CheckStatus, line: string): LocalCheck => ({ name, ok: status !== "fail", status, line }); export function localChecks(o: { policy: GenPolicy; flagHere: { on: boolean; raw: string; understood: boolean }; guardEditor: boolean | null; apiKey: "env" | "file" | null; endpoints: readonly LocalEndpoint[]; rows: readonly GenerationUsageRow[]; calls: readonly LoggedCall[]; imported: readonly ImportedIteration[]; since: string | null; env?: Record<string, string | undefined>; }): { ok: boolean; verdict: LocalVerdict; checks: LocalCheck[]; local: { model: string; calls: number; jobs: number }[]; apiRows: number } { const checks: LocalCheck[] = []; const guardOn = o.guardEditor ?? o.flagHere.on; const notUnderstood = !o.flagHere.understood ? ` — ARCHILYZER_LOCAL_ONLY=${JSON.stringify(o.flagHere.raw)} is not understood here, so the guard is OFF in this process` : ""; checks.push( check( "guard", guardOn ? "ok" : "fail", (guardOn ? `ARCHILYZER_LOCAL_ONLY is on (${o.guardEditor === null ? "this process; no editor answered" : "the editor says so"})` : "ARCHILYZER_LOCAL_ONLY is OFF — a Claude route would be called") + notUnderstood, ), ); const routes = Object.entries(o.policy.routes); const off = routes.filter(([, r]) => r !== "local"); checks.push(check("routes", off.length === 0 ? "ok" : "fail", off.length === 0 ? `${routes.length} of ${routes.length} local (preset ${o.policy.preset})` : `${off.length} of ${routes.length} not local: ${off.map(([t, r]) => `${t} → ${r}`).join(", ")}`)); const hostOf = (url: string) => modelHostOf(url) ?? (url ? "an unreadable URL" : "not set"); const far = o.endpoints.filter((e) => !isLocalModelUrl(e.url, o.env)); checks.push( check( "endpoints", far.length === 0 ? "ok" : "fail", o.endpoints.map((e) => `${e.what} → ${hostOf(e.url)}${isLocalModelUrl(e.url, o.env) ? "" : " (NOT this machine)"}`).join("; ") || "none configured", ), ); checks.push(check("api key", o.apiKey === null ? "ok" : "fail", o.apiKey === null ? "none at hand (no ANTHROPIC_API_KEY, no key file)" : `one is at hand (${o.apiKey === "env" ? "ANTHROPIC_API_KEY is set" : "the key file exists"})`)); const inRange = (day: string) => !o.since || day >= o.since; const rows = o.rows.filter((r) => inRange(r.day)); const api = rows.filter((r) => r.route !== "local"); const byModel = new Map<string, { model: string; calls: number; jobs: Set<string> }>(); for (const r of rows) { if (r.route !== "local") continue; const m = byModel.get(r.model) ?? { model: r.model, calls: 0, jobs: new Set<string>() }; m.calls += typeof r.calls === "number" ? r.calls : 0; m.jobs.add(r.jobId); byModel.set(r.model, m); } const local = [...byModel.values()].map((m) => ({ model: m.model, calls: m.calls, jobs: m.jobs.size })).sort((a, b) => b.calls - a.calls || a.model.localeCompare(b.model)); const range = o.since ? `since ${o.since}` : "all of it"; if (rows.length === 0) checks.push(check("ledger", "none", `${range}: no calls recorded`)); else checks.push( check( "ledger", api.length === 0 ? "ok" : "fail", `${range}: ${api.length === 0 ? "0 Claude API rows" : `${api.length} Claude API row(s) (${[...new Set(api.map((r) => r.model))].sort().join(", ")})`}; ` + (local.length ? `local: ${local.map((m) => `${m.model} ${m.calls} call(s) in ${m.jobs} job(s)`).join(", ")}` : "no local calls"), ), ); const calls = o.calls.filter((c) => inRange(c.at.slice(0, 10))); const farCalls = calls.filter((c) => c.route !== "local"); if (calls.length === 0) checks.push(check("model log", "none", `${range}: no calls recorded`)); else { const routesSeen = [...new Set(farCalls.map((c) => `${c.route} ${c.model}`))].sort(); checks.push(check("model log", farCalls.length === 0 ? "ok" : "fail", `${range}: ${calls.length} call(s), ${farCalls.length === 0 ? "every one on the local route" : `${farCalls.length} NOT local (${routesSeen.join(", ")})`}`)); } const imports = o.imported.filter((i) => inRange(i.at.slice(0, 10))); checks.push(check("imports", imports.length === 0 ? "ok" : "fail", imports.length === 0 ? `${range}: no iteration imported from elsewhere` : `${imports.length} iteration(s) made elsewhere and imported: ${imports.map((i) => `${i.article} i${i.n} (from ${i.from})`).join(", ")}`)); const failed = checks.some((c) => c.status === "fail"); const nothing = !failed && checks.find((c) => c.name === "ledger")!.status === "none" && checks.find((c) => c.name === "model log")!.status === "none"; return { ok: !failed, verdict: failed ? "fail" : nothing ? "nothing-yet" : "pass", checks, local, apiRows: api.length }; } /** `--since`'s refusal, or null: a real calendar date (UTC), not after today. */ export function sinceProblem(since: string, today: string = new Date().toISOString().slice(0, 10)): string | null { if (!/^\d{4}-\d{2}-\d{2}$/.test(since)) return "--since is a date YYYY-MM-DD (UTC)"; const t = Date.parse(`${since}T00:00:00Z`); if (Number.isNaN(t) || new Date(t).toISOString().slice(0, 10) !== since) return `--since ${since} is not a calendar date`; if (since > today) return `--since ${since} is after today (${today}, UTC)`; return null; } // A path as it may be printed: the home directory as `~` (a container's // /data paths are printed as they are). export function tildify(text: string, home: string = os.homedir()): string { return home && home !== "/" ? text.split(home).join("~") : text; } export async function localCheckMain(o: { since?: string; json: boolean }, deps: GenDeps): Promise<number> { const out = deps.out ?? console; const bad = o.since !== undefined ? sinceProblem(o.since) : null; if (bad) { out.error(`gen local-check: ${bad}`); return 2; } const store = await deps.store(); if ("error" in store) { out.error(tildify(`gen local-check: ${store.error}`)); return 1; } const policy = await store.read(); const env = deps.env ?? process.env; const ev = await (deps.evidence ?? defaultEvidence)(store); const r = localChecks({ policy, flagHere: localOnlyFlag(env), guardEditor: store.editorLocalOnly ? await store.editorLocalOnly() : null, apiKey: await (deps.apiKeyAtHand ?? defaultApiKeyAtHand)(), endpoints: ev.endpoints, rows: ev.rows, calls: ev.calls, imported: ev.imported, since: o.since ?? null, env, }); const where = tildify(store.where); if (o.json) { out.log(JSON.stringify({ ok: r.ok, verdict: r.verdict, since: o.since ?? null, checks: r.checks, local: r.local, apiRows: r.apiRows, from: where }, null, 2)); } else { out.log( r.verdict === "fail" ? "local-check: FAIL" : r.verdict === "nothing-yet" ? "local-check: NOTHING TO PROVE YET — the setup is local only, and no model call is recorded yet to prove it by" : "local-check: PASS — the setup is local only, and every recorded call was local", ); for (const c of r.checks) out.log(` ${(c.status === "ok" ? "ok" : c.status === "none" ? "--" : "FAIL").padEnd(4)} ${c.name.padEnd(9)} ${c.line}`); out.log(`(from ${where})`); } return r.ok ? 0 : 1; } export type LocalEvidence = { endpoints: LocalEndpoint[]; rows: GenerationUsageRow[]; calls: LoggedCall[]; imported: ImportedIteration[] }; // What local-check reads, off disk (it runs where the editor's files are: // the editor's container, or the host of a host install) and from the store. async function defaultEvidence(store: GenStore): Promise<LocalEvidence> { const { getPaths } = await import("../lib/paths"); const { getSettings } = await import("../lib/settings"); const { readGenerationUsage } = await import("../controller/generationUsage"); const paths = getPaths(); const s = getSettings(); const gen = (store.readKey ? ((await store.readKey("generation")) as Record<string, unknown> | null) : null) ?? (s.generation as unknown as Record<string, unknown>); const digest = (store.readKey ? ((await store.readKey("digest")) as Record<string, unknown> | null) : null) ?? (s.digest as unknown as Record<string, unknown>); const workers = (store.readKey ? ((await store.readKey("workers")) as unknown[] | null) : null) ?? (s.workers as unknown[]); const endpoints: LocalEndpoint[] = []; const genUrl = typeof gen?.ollamaUrl === "string" && gen.ollamaUrl.trim() ? gen.ollamaUrl.trim() : paths.ollamaUrl; endpoints.push({ what: typeof gen?.ollamaUrl === "string" && gen.ollamaUrl.trim() ? "the local route (generation.ollamaUrl)" : "the local route (OLLAMA_URL)", url: genUrl }); const apps = digest && typeof digest.apps === "object" && digest.apps ? (digest.apps as Record<string, { baseUrl?: string }>) : {}; const digestUrl = apps["ollama-direct"]?.baseUrl?.trim(); endpoints.push({ what: digestUrl ? "the digest (digest.apps.ollama-direct)" : "the digest (OLLAMA_URL)", url: digestUrl || paths.ollamaUrl }); for (const w of Array.isArray(workers) ? workers : []) { const x = w as { kind?: string; enabled?: boolean; id?: string; llm?: { baseUrl?: string } }; if (x.kind === "llm" && x.enabled) endpoints.push({ what: `LLM worker ${x.id ?? "?"}`, url: x.llm?.baseUrl ?? "" }); } return { endpoints, rows: await readGenerationUsage(paths.generationUsageFile), calls: await loggedCalls(paths), imported: await importedIterations(paths), }; } // Every call the per-call logs hold: each job's own (calls/<jobId>/) and the // iteration logs the jobs point at, each file read once. async function loggedCalls(paths: import("../lib/paths").Paths): Promise<LoggedCall[]> { const { readdir } = await import("node:fs/promises"); const { locateJobModelLog } = await import("../controller/jobModelLog"); const { readModelLog } = await import("../lib/llm/callLog-server"); const dir = path.join(path.dirname(paths.generationUsageFile), "calls"); const ids = await readdir(dir).catch(() => [] as string[]); const seen = new Set<string>(); const out: LoggedCall[] = []; for (const id of ids) { if (!/^[A-Za-z0-9._-]+$/.test(id) || /^\.+$/.test(id)) continue; const at = await locateJobModelLog(paths, id).catch(() => null); if (!at || seen.has(at.files.calls)) continue; seen.add(at.files.calls); const log = await readModelLog(at.files).catch(() => null); for (const c of log?.calls ?? []) out.push({ route: c.route, at: c.at, model: c.model }); } return out; } // Every iteration that carries `imported` (a run made elsewhere). async function importedIterations(paths: import("../lib/paths").Paths): Promise<ImportedIteration[]> { const { listArticles } = await import("../lib/report/registry"); const { listIterations } = await import("../lib/report/iterations"); const out: ImportedIteration[] = []; for (const a of await listArticles(paths).catch(() => [])) { for (const it of await listIterations(a.id, paths).catch(() => [])) { const imp = (it as unknown as { imported?: { from?: unknown; run?: unknown } }).imported; if (!imp) continue; out.push({ article: a.id, n: it.n, at: it.createdAt, from: typeof imp.from === "string" ? imp.from : typeof imp.run === "string" ? `the stopgap run ${imp.run}` : "elsewhere" }); } } return out; } // Whether a Claude API key is at hand — its presence only: the variable is // checked for a value, the file for existence; neither is read out. async function defaultApiKeyAtHand(): Promise<"env" | "file" | null> { if ((process.env.ANTHROPIC_API_KEY ?? "").trim()) return "env"; const { getSettings } = await import("../lib/settings"); const { existsSync } = await import("node:fs"); const f = getSettings().generation.apiKeyFile; const file = f === "~" || f.startsWith("~/") ? os.homedir() + f.slice(1) : f; return file && existsSync(file) ? "file" : null; } // The report-draft body from `gen run`'s words, or why not. The editor judges // the rest (controller/reportDraft.ts parseReportDraftBody). export function runBody(task: string, text: string | undefined, flags: Record<string, FlagValue>): Record<string, unknown> | { error: string } { const str = (k: string) => (typeof flags[k] === "string" ? (flags[k] as string).trim() : undefined); const article = str("article"); if (!article) return { error: "gen run: --article <id> names the article (a sweep may name a new one)" }; const body: Record<string, unknown> = { task, article }; const int = (k: string, key: string) => { const v = str(k); if (v === undefined) return null; const n = Number(v); if (!Number.isInteger(n) || n < 1) return `gen run: --${k} is an iteration number`; body[key] = n; return null; }; for (const [k, key] of [["iteration", "iteration"], ["copy-of", "copyOf"]] as const) { const e = int(k, key); if (e) return { error: e }; } const words = text?.trim(); // A media draft (release 28) is a step on the iteration it names; it takes // no words — it drafts from the iteration's report and cut. if (isStepTask(task)) { if (body.iteration === undefined) return { error: `gen run: a ${task} draft names its iteration (--iteration <n>)` }; if (body.copyOf !== undefined) return { error: `gen run: a ${task} draft is a step on its iteration: no --copy-of` }; if (words || str("question") || str("feedback")) return { error: `gen run: a ${task} draft takes no question or feedback: it drafts from the iteration's report and cut` }; } else if (str("entries")) return { error: "gen run: --entries is a media draft's" }; if (words) body[task === "sweep" || task === "research" ? "question" : "feedback"] = words; for (const k of ["question", "feedback", "from", "to", "model", "source", "build"] as const) { const v = str(k); if (v) body[k] = v; } for (const k of ["channels", "cards", "entries"] as const) { const v = str(k); if (v) body[k] = v.split(",").map((x) => x.trim()).filter(Boolean); } const max = str("max-usd"); if (max !== undefined) { const n = Number(max); if (!(n > 0)) return { error: "gen run: --max-usd is a positive number of dollars" }; body.maxUsd = n; } if (flags.force === true) body.force = true; const autonomy = str("autonomy"); if (autonomy !== undefined) { if (task !== "research") return { error: "gen run: --autonomy is a research run's" }; body.autonomy = autonomy; } return body; } export async function runMain(o: { task?: string; text?: string; flags: Record<string, FlagValue> }, deps: GenDeps): Promise<number> { const out = deps.out ?? console; if (!o.task) { out.error(`gen run: which task? ${TASKS_HELP}`); return 2; } const body = runBody(o.task, o.text, o.flags); if ("error" in body) { out.error(String(body.error)); return 2; } const via = typeof o.flags.via === "string" ? o.flags.via : undefined; if (via !== undefined && !isRoute(via)) { out.error(`gen run: --via is ${GENERATION_ROUTES.join(", ")}`); return 2; } if (via && body.model) { out.error("gen run: give --model or --via, not both"); return 2; } if (!body.model) { const store = await deps.store(); if ("error" in store) { out.error(`gen run: ${store.error}`); return 1; } const p = await store.read(); const route = via ?? p.routes[o.task]; if (route === "code") { out.log( `gen: ${o.task} is routed to Claude Code (${via ? "--via code" : `preset ${p.preset}`}) — do it in the session; ` + "`gen run … --via api|local` overrides once.", ); return 3; } if (store.offline) { out.error(`gen run: ${o.task} is routed to ${route ?? "?"}, and no editor answers — generation runs in the editor; start it`); return 1; } if (route) body.model = p.models[route]; out.error(`gen: ${o.task} → ${route ?? "the editor's choice"}${body.model ? ` (${String(body.model)})` : ""}`); } return deps.runOps(["report-draft", "--json", JSON.stringify(body), ...(o.flags.wait === true ? ["--wait"] : [])]); } // `pnpm ops <argv>` as a child of this process (stdio inherited). export function runOpsChild(argv: string[]): Promise<number> { return runChild({ command: process.execPath, args: [path.join(REPO_ROOT, "scripts", "archilyzer-ops.mjs"), ...argv], cwd: REPO_ROOT }); } const defaultDeps = (ctx: CommandContext): GenDeps => ({ store: () => defaultStore(ctx.env), runOps: runOpsChild }); export async function genPolicyRow(ctx: CommandContext): Promise<number> { return policyMain({ json: ctx.flags.json === true }, defaultDeps(ctx)); } export async function genPresetRow(ctx: CommandContext): Promise<number> { return setMain({ preset: ctx.positionals[0] ?? "" }, defaultDeps(ctx)); } export async function genSetRow(ctx: CommandContext): Promise<number> { const [task, route] = ctx.positionals; return setMain({ ...(task ? { task } : {}), ...(route ? { route } : {}) }, defaultDeps(ctx)); } export async function genLocalSweepRow(ctx: CommandContext): Promise<number> { const str = (k: string) => (typeof ctx.flags[k] === "string" ? (ctx.flags[k] as string).trim() : undefined); const form = str("form"); const readAloud = str("read-aloud"); return localSweepMain({ ...(form !== undefined ? { form } : {}), ...(readAloud !== undefined ? { readAloud } : {}) }, defaultDeps(ctx)); } export async function genModelRow(ctx: CommandContext): Promise<number> { const [slot, name] = ctx.positionals; return modelMain({ ...(slot ? { slot } : {}), ...(name ? { name } : {}) }, { ...defaultDeps(ctx), env: ctx.env }); } export async function genLocalCheckRow(ctx: CommandContext): Promise<number> { const since = typeof ctx.flags.since === "string" ? ctx.flags.since.trim() : undefined; return localCheckMain({ ...(since !== undefined ? { since } : {}), json: ctx.flags.json === true }, { ...defaultDeps(ctx), env: ctx.env }); } export async function genRunRow(ctx: CommandContext): Promise<number> { const [task, text] = ctx.positionals; return runMain({ ...(task ? { task } : {}), ...(text ? { text } : {}), flags: ctx.flags }, defaultDeps(ctx)); }