Archilyzer · Source

archilyzer

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

commit 1a3b91b1636425dc247553e942345250114d2fe6
parent daa62081e9044b283bd1b2e8a626572391638e30
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu, 12 Nov 2026 22:27:48 -0500

local only: ARCHILYZER_LOCAL_ONLY refuses every model call that would leave the machine before its I/O; gen model and gen local-check; a local model's run has a memory floor (demo epic D5)

- common/lib/llm/localOnly.ts: the flag, LocalOnlyError, the ollama cloud
  tag rule and the refusals. The Claude API client refuses at construction
  and at messages() (process.env, never the key's env), the ollama clients
  refuse a "-cloud" tag, the digest's claude CLI lane is never started and
  probes false. report-draft and frame-scan refuse at the ask with a
  sentence (a code route, a Claude Code session's answers, a Claude or cloud
  model, an extractor); the settings patch refuses a route other than local.
  Unset, every function is a no-op.
- archilyzer gen model [api|local|extractor <m>] (settings.generation.models'
  CLI twin) and gen local-check [--since] [--json]: guard, routes, API key
  presence (never read out), the ledger's API rows; exit 1 on any failure.
  generation-usage answers localOnly (the editor's own flag).
- a report-draft job on the local model refuses to start under 3072 MB
  MemAvailable (LOCAL_MODEL_MIN_FREE_MB; 0 off); the lookout run's floor is
  the same constant.
- umtool's policy chip names the local model and shows no spend when no task
  is routed to the API, and says "local only".
- the projectsRoot docstring says the REPORTS_DIR rule. COMMANDS.md,
  ENVIRONMENT.md, SETTINGS.md regenerated.

Co-Authored-By: Claude <noreply@anthropic.com>

Diffstat:
MCOMMANDS.md | 2++
MENVIRONMENT.md | 2++
MSETTINGS.md | 2+-
Mcommon/bin/archilyzer.ts | 15+++++++++++++++
Mcommon/bin/gen.test.ts | 120+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/bin/gen.ts | 206++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mcommon/controller/frameScan.ts | 6+++++-
Mcommon/controller/lookoutRun.ts | 6+++---
Mcommon/controller/reportDraft.ts | 49++++++++++++++++++++++++++++++++++++++++++++++++-
Acommon/controller/reportDraftLocalOnly.test.ts | 48++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/digestApps.ts | 7+++++++
Mcommon/lib/envVars.ts | 2++
Mcommon/lib/generationSettings.ts | 2+-
Mcommon/lib/llm/anthropic.ts | 8++++++++
Mcommon/lib/llm/index.ts | 1+
Acommon/lib/llm/localOnly.test.ts | 157+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/llm/localOnly.ts | 91+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/llm/ollama.ts | 5+++++
Meditor/app/api/ops/_reportDraft.test.ts | 77++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Meditor/app/api/ops/_writes.test.ts | 20++++++++++++++++++++
Meditor/app/api/ops/generation-usage/route.ts | 9++++++---
Meditor/app/api/ops/settings/patch.ts | 10++++++++++
Mumtool/components/piece/PolicyChip.tsx | 23+++++++++++++++++------
Aumtool/lib/articles/policyChip.test.ts | 36++++++++++++++++++++++++++++++++++++
Aumtool/lib/articles/policyChip.ts | 31+++++++++++++++++++++++++++++++
25 files changed, 917 insertions(+), 18 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -45,6 +45,8 @@ Run from the repo root (in the container: `docker compose exec editor pnpm archi | `archilyzer gen preset` | `<code\|balanced\|api\|local>` | route every generation task by a preset (its routes are written; settings.generation.routes) | | `archilyzer gen set` | `<task> <code\|api\|local>` | route one generation task (sweep, revise-report, revise-video, research; the media drafts cut, onscreen, teaser, flips, threads, narrate, youtube, social) | | `archilyzer gen local-sweep` | `[--form neutral\|sentence] [--read-aloud flag\|drop\|off]` | the local route's sweep (settings.generation.localSweep): who writes a finding's line — neutral: code (In &lt;title&gt; (&lt;date&gt;), on &lt;topic&gt;: "&lt;quote&gt;"; the model only picks the quote and labels its topic), sentence: the model, judged by a meaning check — and what happens to a quote whose transcript has a sign of reading aloud around it (a tweet, a headline, "it says"): flag keeps it marked to check by ear, drop leaves it out, off does not look; bare, what they are | +| `archilyzer gen model` | `[api\|local\|extractor <model>]` | the model a route runs (settings.generation.models): api = the Claude API's, local = the ollama model the local route runs, extractor = an API sweep's batch reader; bare, the three. On a local-only instance (ARCHILYZER\_LOCAL\_ONLY=1) a Claude or ollama cloud model is refused for local and extractor | +| `archilyzer gen local-check` | `[--since YYYY-MM-DD] [--json]` | read-only: whether this instance stayed local (demo epic D5) — ARCHILYZER\_LOCAL\_ONLY on (the editor's own answer when one answers), every generation route local, no Claude API key at hand (its presence only: never read out), and the usage ledger since the date holding no Claude API row (local rows counted by model, calls and jobs); exit 1 when any check fails | | `archilyzer gen run` | `<task> [<question\|feedback>] --article <id> [--via api\|local\|code] [--model <m>] [--iteration <n>] [--channels a,b] [--from YYYY-MM-DD] [--to YYYY-MM-DD] [--copy-of <n>] [--max-usd <usd>] [--cards a,b] [--entries a,b] [--force] [--autonomy propose\|limits\|auto] [--source <handle>\|--build <id>] [--wait]` | enqueue a report-draft job as `pnpm ops report-draft` does (--wait follows it; `sweep --iteration <n>` continues research run n); a media draft (cut, onscreen, teaser, flips, threads, narrate, youtube, social) is a step on --iteration &lt;n&gt;, takes no words, --entries limits it, --force re-drafts only fields a model drafted; EXITS 3 and runs nothing when the task is routed to code (Claude Code does it; --via overrides once) | | `archilyzer reports move-to-articles` | `[--keep <site>/<id>,…] [--drafts] [--apply]` | ONE-OFF (release 26): every report a site lists, but the pages named by --keep, moved to transcripts/reports/ as an article — audience private, published in reports/index.json in the sites' order (a report with problems as a draft), dropped from its site; --drafts moves unlisted ones too. A dry run printing the plan unless --apply *(passthrough)* | | `archilyzer reports convert` | `<sweep\|ask\|manifest> <in> --out <report.json> [--channels-dir <dir>] [--id <id>] [--title <title>]` | a /sweep report (markdown), an /ask answer or a report-to-video manifest as a report.json, written only when it validates (--channels-dir: widen spans from the cues, find posts' channels) | diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md @@ -100,6 +100,8 @@ Tokens, credentials and knobs a running process reads. Most configuration is not | `UMTOOL_URL` | unset (no link; the MCP's `notes` off) | umtool's front door; when set, the video page links to it, its Find clips hands the recording to umtool's clip finder (the `find-clips` job posts to `/api/report/clips` with WORKER_TOKEN), and the MCP's `notes` tool reads the operator's notes there and writes a reply as the agent's (e.g. `http://localhost:3050`). Unset: Find clips is disabled. | editor/app/channels/[slug]/videos/[id]/page.tsx, common/lib/umtoolUrl.ts, mcp/src/archivalTools.ts | | `TRANSCRIPT_SITE_URL` | — | MCP server: one published archive to read over HTTP. Also the default connected archive (common/lib/remoteArchives.ts): the editor, umtool and the MCP offer it as a source when settings.remoteArchives does not list it, without writing it. | mcp/src/sources.ts | | `ARCHILYZER_ALLOW_PRIVATE_ARCHIVES` | off | `1` lets the editor connect an archive whose host is this machine or its network (loopback, private, link-local, a `.local` name, or a name resolving to such an address), which is refused otherwise: umtool, which can connect one, is open on the LAN. TRANSCRIPT_SITE_URL's archive, and one already written in settings.json, are connected without it. The check is made once, when the archive is connected: a name re-pointed at a private address afterwards is not rechecked (the archive is still read on its own origin only). | common/controller/remoteArchives.ts | +| `ARCHILYZER_LOCAL_ONLY` | off | `1` makes the instance LOCAL ONLY (demo epic D5): every model call that would leave the machine is refused before any request or process — the Claude API, a Claude Code session's `answers` and a task routed to `code`, the digest's `claude` CLI lane, an ollama cloud model (a `…-cloud` tag) — and a settings write that routes a task anywhere but `local` is refused. `archilyzer gen local-check` proves it afterwards. The demo overlay (docker-compose.demo.yml) sets it; unset, nothing changes. | common/lib/llm/localOnly.ts (the Claude API client, the ollama clients, the digest's metered lane, the report-draft and frame-scan dispatch, the settings writer, `archilyzer gen`), umtool/components/piece/PolicyChip.tsx | +| `LOCAL_MODEL_MIN_FREE_MB` | `3072` | The MemAvailable floor (MiB) a report-draft job on the local model starts with, at its turn: under it the job is refused with a sentence (demo epic D5; a lookout run has the same floor). `0` turns it off. | common/controller/reportDraft.ts | | `ARCHIVE_CACHE_DIR` | `.archive-cache` beside EXPORT_BUILDS_DIR | Where a remote archive's documents (corpus.json, manifests, shard pages) are kept on disk, by the archive's build: a sweep over a published archive downloads a shard once per build, not once per sweep. In a container it is on the builds volume. | common/lib/archiveCache-server.ts | | `ARCHIVE_CACHE_MAX_MB` | 512 | The disk cache of remote archive documents' size cap, MB: past it the least recently used are dropped. | common/lib/archiveCache-server.ts | | `ARCHIVE_CACHE` | on (off under node's test runner) | `0` reads remote archives without the disk cache (every read over the network, still one at a time); `1` turns it on under node's test runner, where it is off. | common/lib/archiveCache-server.ts | diff --git a/SETTINGS.md b/SETTINGS.md @@ -1139,7 +1139,7 @@ Report and video generation (release 27): where each task runs (`code` = Claude | `apiKeyFile` | `"~/.config/archilyzer/anthropic.env"` | The file holding the Claude API key (`ANTHROPIC_API_KEY=…`), mode 600 — refused when the group or others can read it. `~` is the editor's home. The KEY itself is never a setting: a value that looks like one is refused, never stored. `ANTHROPIC_API_KEY` in the editor's environment wins over the file. | | `anthropicBaseUrl` | `""` | Advanced: the Messages API's base URL. Blank = Anthropic's. Tests point it at a fake. | | `ollamaUrl` | `""` | The local model's server (ollama). Blank = the editor's `OLLAMA_URL` (the digest lane's server, default http://127.0.0.1:11434). | -| `projectsRoot` | `""` | Where an iteration's video project and renders live: `<projectsRoot>/<article>/i<n>/`, off the corpus disk (D1). Blank = `~/reports/articles`. | +| `projectsRoot` | `""` | Where an iteration's video project and renders live: `<projectsRoot>/<article>/i<n>/`, off the corpus disk (D1). Blank = `<REPORTS_DIR>/articles` when REPORTS_DIR is set (a container's reports volume: `/data/reports/articles`), else `~/reports/articles` (common/lib/projectsRoot.mjs). | | `web` | object — see below | The web an agent may read for context (below). Read-only and paced: one request at a time, 3 s apart. | | `citationOrigin` | `""` | The origin a generated report's moment links cite when its corpus build's site has no public URL (a private build). Blank = the project site. | | `research` | object — see below | A research run's default autonomy and its limits (below). A run may name its own autonomy; the limits are the settings'. | diff --git a/common/bin/archilyzer.ts b/common/bin/archilyzer.ts @@ -491,6 +491,21 @@ export const COMMANDS: Command[] = [ run: async (ctx) => (await import("./gen")).genLocalSweepRow(ctx), }, { + path: ["gen", "model"], + usage: + "[api|local|extractor <model>] the model a route runs (settings.generation.models): api = the Claude API's, local = the ollama model the local route runs, extractor = an API sweep's batch reader; bare, the three. On a local-only instance (ARCHILYZER_LOCAL_ONLY=1) a Claude or ollama cloud model is refused for local and extractor", + maxPositionals: 2, + run: async (ctx) => (await import("./gen")).genModelRow(ctx), + }, + { + path: ["gen", "local-check"], + usage: + "[--since YYYY-MM-DD] [--json] read-only: whether this instance stayed local (demo epic D5) — ARCHILYZER_LOCAL_ONLY on (the editor's own answer when one answers), every generation route local, no Claude API key at hand (its presence only: never read out), and the usage ledger since the date holding no Claude API row (local rows counted by model, calls and jobs); exit 1 when any check fails", + flags: { since: "string", json: "boolean" }, + maxPositionals: 0, + run: async (ctx) => (await import("./gen")).genLocalCheckRow(ctx), + }, + { path: ["gen", "run"], usage: "<task> [<question|feedback>] --article <id> [--via api|local|code] [--model <m>] [--iteration <n>] [--channels a,b] [--from YYYY-MM-DD] [--to YYYY-MM-DD] [--copy-of <n>] [--max-usd <usd>] [--cards a,b] [--entries a,b] [--force] [--autonomy propose|limits|auto] [--source <handle>|--build <id>] [--wait] enqueue a report-draft job as `pnpm ops report-draft` does (--wait follows it; `sweep --iteration <n>` continues research run n); a media draft (cut, onscreen, teaser, flips, threads, narrate, youtube, social) is a step on --iteration <n>, takes no words, --entries limits it, --force re-drafts only fields a model drafted; EXITS 3 and runs nothing when the task is routed to code (Claude Code does it; --via overrides once)", diff --git a/common/bin/gen.test.ts b/common/bin/gen.test.ts @@ -262,3 +262,123 @@ test("gen run a media draft: a step on --iteration, no words, --entries and --fo assert.deepEqual(gen.runBody("sweep", "q", { article: "synth-a", entries: "c01" }), { error: "gen run: --entries is a media draft's" }); }); + +// ─── demo epic D5: gen model, gen local-check, the local-only refusal ─── + +const ALL_LOCAL: GenPolicy = { + preset: "local", + routes: { sweep: "local", "revise-report": "local", "revise-video": "local", narrate: "local", research: "local" }, + models: { api: "claude-sonnet-5-5", local: "qwen2.5:7b", extractor: "qwen2.5:7b" }, +}; + +function modelStore(policy: GenPolicy) { + const { store } = memoryStore(policy); + const writes: GenPolicy["models"][] = []; + let p = structuredClone(policy); + store.read = async () => p; + store.writeModels = async (models) => { + writes.push(models); + p = { ...p, models }; + return p; + }; + return { store, writes }; +} + +test("gen model: shows the three; writes one slot keeping the others; an unchanged one is not written", async () => { + const { store, writes } = modelStore(BALANCED); + const c = capture(); + assert.equal(await gen.modelMain({}, { store: async () => store, runOps: async () => 0, out: c.out }), 0); + assert.match(c.lines[0]!, /^api claude-sonnet-5-5 · local qwen3:8b · extractor claude-haiku-4-5 {2}\(from the editor/); + assert.equal(await gen.modelMain({ slot: "local", name: "qwen2.5:7b" }, { store: async () => store, runOps: async () => 0, out: c.out }), 0); + assert.deepEqual(writes, [{ api: "claude-sonnet-5-5", local: "qwen2.5:7b", extractor: "claude-haiku-4-5" }]); + assert.equal(await gen.modelMain({ slot: "local", name: "qwen2.5:7b" }, { store: async () => store, runOps: async () => 0, out: c.out }), 0); + assert.equal(writes.length, 1, "already so: nothing written"); + const e = capture(); + assert.equal(await gen.modelMain({ slot: "vision", name: "x" }, { store: async () => store, runOps: async () => 0, out: e.out }), 2); + assert.equal(await gen.modelMain({ slot: "local", name: "bad name!" }, { store: async () => store, runOps: async () => 0, out: e.out }), 2); + assert.equal(await gen.modelMain({ slot: "local" }, { store: async () => store, runOps: async () => 0, out: e.out }), 2); +}); + +test("gen model on a local-only instance: a Claude or cloud model refused for local and extractor", async () => { + const { store, writes } = modelStore(ALL_LOCAL); + const env = { ARCHILYZER_LOCAL_ONLY: "1" }; + const c = capture(); + assert.equal(await gen.modelMain({ slot: "extractor", name: "claude-haiku-4-5" }, { store: async () => store, runOps: async () => 0, out: c.out, env }), 1); + assert.equal(await gen.modelMain({ slot: "local", name: "gpt-oss:120b-cloud" }, { store: async () => store, runOps: async () => 0, out: c.out, env }), 1); + assert.match(c.errors.join("\n"), /local only \(ARCHILYZER_LOCAL_ONLY=1\): "claude-haiku-4-5" is not a local model/); + assert.equal(writes.length, 0); +}); + +test("gen preset/set on a local-only instance: a route other than local refused before any write", async () => { + const { store, written } = memoryStore(ALL_LOCAL, true); + const c = capture(); + const deps = { store: async () => store, runOps: async () => 0, out: c.out, env: { ARCHILYZER_LOCAL_ONLY: "1" } }; + assert.equal(await gen.setMain({ preset: "balanced" }, deps), 1); + assert.equal(await gen.setMain({ task: "sweep", route: "code" }, deps), 1); + assert.match(c.errors.join("\n"), /every generation route stays local — not saved: sweep → code/); + assert.equal(written.length, 0); + assert.equal(await gen.setMain({ preset: "local" }, deps), 0); + assert.equal(written.length, 1); +}); + +const row = (r: Partial<import("../controller/generationUsage").GenerationUsageRow>) => ({ + at: "2026-11-13T10:00:00Z", + day: "2026-11-13", + jobId: "j1", + article: "a", + iteration: 1, + task: "sweep", + model: "qwen2.5:7b", + inputTokens: 10, + outputTokens: 5, + cacheReadTokens: 0, + cacheWriteTokens: 0, + usd: 0, + route: "local" as const, + calls: 12, + ...r, +}); + +test("gen local-check: PASS by counts and route names; each failing check named; --since narrows the ledger", async () => { + const pass = gen.localChecks({ policy: ALL_LOCAL, guardHere: true, guardEditor: true, apiKey: null, rows: [row({}), row({ jobId: "j2", calls: 3 })], since: null }); + assert.equal(pass.ok, true); + assert.deepEqual(pass.local, [{ model: "qwen2.5:7b", calls: 15, jobs: 2 }]); + assert.deepEqual(pass.checks.map((c) => [c.name, c.ok]), [["guard", true], ["routes", true], ["api key", true], ["ledger", true]]); + assert.match(pass.checks[3]!.line, /all of it: 0 Claude API rows; local: qwen2.5:7b 15 call\(s\) in 2 job\(s\)/); + + const apiRow = row({ day: "2026-11-01", model: "claude-sonnet-5-5", route: "api", usd: 0.4, jobId: "old" }); + const fail = gen.localChecks({ policy: BALANCED, guardHere: false, guardEditor: false, apiKey: "file", rows: [apiRow, row({})], since: null }); + assert.equal(fail.ok, false); + assert.deepEqual(fail.checks.map((c) => c.ok), [false, false, false, false]); + assert.match(fail.checks[1]!.line, /3 of 5 not local: sweep → code, revise-report → api, research → api/); + assert.match(fail.checks[2]!.line, /the key file exists/); + assert.match(fail.checks[3]!.line, /1 Claude API row\(s\) \(claude-sonnet-5-5\)/); + // The API row is before --since: the ledger check passes from that day. + const since = gen.localChecks({ policy: ALL_LOCAL, guardHere: true, guardEditor: null, apiKey: null, rows: [apiRow, row({})], since: "2026-11-13" }); + assert.equal(since.ok, true); + assert.match(since.checks[0]!.line, /this process; no editor answered/); +}); + +test("gen local-check: the command's lines and exit; never a key or a key path", async () => { + const { store } = memoryStore(ALL_LOCAL); + store.editorLocalOnly = async () => true; + const c = capture(); + const code = await gen.localCheckMain( + { json: false }, + { store: async () => store, runOps: async () => 0, out: c.out, env: {}, ledger: async () => [row({})], apiKeyAtHand: async () => null }, + ); + assert.equal(code, 0, c.errors.join("\n")); + assert.equal(c.lines[0], "local-check: PASS"); + assert.ok(c.lines.some((l) => /guard {4}ARCHILYZER_LOCAL_ONLY is on \(the editor says so\)/.test(l)), c.lines.join("\n")); + const j = capture(); + assert.equal( + await gen.localCheckMain({ json: true, since: "2026-11-01" }, { store: async () => store, runOps: async () => 0, out: j.out, env: {}, ledger: async () => [], apiKeyAtHand: async () => "env" }), + 1, + ); + const body = JSON.parse(j.lines[0]!); + assert.equal(body.ok, false); + assert.equal(body.since, "2026-11-01"); + assert.ok(!/anthropic\.env|sk-|ANTHROPIC_API_KEY=/.test(j.lines[0]!), "no key file path or key"); + const bad = capture(); + assert.equal(await gen.localCheckMain({ json: false, since: "13 Nov" }, { store: async () => store, runOps: async () => 0, out: bad.out }), 2); +}); diff --git a/common/bin/gen.ts b/common/bin/gen.ts @@ -7,6 +7,8 @@ // 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 <model>] 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 <task> [<question|feedback>] --article <id> [--via api|local|code] […] [--wait] // enqueue a report-draft job (`pnpm ops report-draft`); // a media draft (cut, onscreen, teaser, flips, threads, @@ -48,8 +50,10 @@ import { type GenerationPreset, type GenerationRoute, } from "../lib/generationSettings"; +import { isCloudOllamaModel, isLocalOnly, localOnlyRoutesRefusal } from "../lib/llm/localOnly"; +import type { GenerationUsageRow } from "../controller/generationUsage"; -type Out = { log: (s: string) => void; error: (s: string) => void }; +type Out ={ log: (s: string) => void; error: (s: string) => void }; // The part of settings.generation this command shows and changes. export type GenPolicy = { @@ -70,6 +74,10 @@ export type GenStore = { usage(): Promise<GenUsage | null>; writeRoutes(routes: Record<string, GenerationRoute>): Promise<GenPolicy>; writeLocalSweep(localSweep: GenerationLocalSweep): Promise<GenPolicy>; + writeModels?(models: GenPolicy["models"]): Promise<GenPolicy>; + // Whether the editor itself runs local only (ARCHILYZER_LOCAL_ONLY in ITS + // environment), or null when no editor answers. + editorLocalOnly?(): Promise<boolean | null>; }; export type GenDeps = { @@ -78,6 +86,13 @@ export type GenDeps = { // `pnpm ops <argv>` as a child; its exit code. runOps: (argv: string[]) => Promise<number>; out?: Out; + // This process's environment (ARCHILYZER_LOCAL_ONLY, ANTHROPIC_API_KEY's + // presence); default process.env. + env?: Record<string, string | undefined>; + // `gen local-check`: the usage ledger's rows and whether an API key is at + // hand (default: the ledger file and the key's env/file, never read out). + ledger?: () => Promise<GenerationUsageRow[]>; + apiKeyAtHand?: () => Promise<"env" | "file" | null>; }; const TASKS_HELP = `sweep, revise-report, revise-video, research, or a media draft: ${MEDIA_STEP_TASKS.join(", ")}`; @@ -209,6 +224,17 @@ export async function editorStore(env: NodeJS.ProcessEnv = process.env, fetchImp 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; + }, }; } @@ -237,6 +263,14 @@ export async function offlineStore(): Promise<GenStore> { 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; + }, }; } @@ -285,6 +319,12 @@ export async function setMain(o: { preset?: string; task?: string; route?: strin 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; @@ -325,6 +365,162 @@ export async function localSweepMain(o: { form?: string; readAloud?: string }, d 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 and route names — the guard on, +// every route local, no Claude API key at hand, and the usage ledger since +// the date holding no Claude API row. Exit 0 when every check passes, 1 +// otherwise. It never prints a key, a key file's path or its contents. +export type LocalCheck = { name: string; ok: boolean; line: string }; + +export function localChecks(o: { + policy: GenPolicy; + guardHere: boolean; + guardEditor: boolean | null; + apiKey: "env" | "file" | null; + rows: readonly GenerationUsageRow[]; + since: string | null; +}): { ok: boolean; checks: LocalCheck[]; local: { model: string; calls: number; jobs: number }[]; apiRows: number } { + const checks: LocalCheck[] = []; + const guardOn = o.guardEditor ?? o.guardHere; + checks.push({ + name: "guard", + ok: guardOn, + line: 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", + }); + const routes = Object.entries(o.policy.routes); + const off = routes.filter(([, r]) => r !== "local"); + checks.push({ + name: "routes", + ok: off.length === 0, + line: 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(", ")}`, + }); + checks.push({ + name: "api key", + ok: o.apiKey === null, + line: 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 rows = o.since ? o.rows.filter((r) => r.day >= o.since!) : o.rows; + 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 apiModels = [...new Set(api.map((r) => r.model))].sort(); + checks.push({ + name: "ledger", + ok: api.length === 0, + line: + `${o.since ? `since ${o.since}` : "all of it"}: ${api.length === 0 ? "0 Claude API rows" : `${api.length} Claude API row(s) (${apiModels.join(", ")})`}; ` + + (local.length ? `local: ${local.map((m) => `${m.model} ${m.calls} call(s) in ${m.jobs} job(s)`).join(", ")}` : "no local runs yet"), + }); + return { ok: checks.every((c) => c.ok), checks, local, apiRows: api.length }; +} + +export async function localCheckMain(o: { since?: string; json: boolean }, deps: GenDeps): Promise<number> { + const out = deps.out ?? console; + if (o.since !== undefined && !/^\d{4}-\d{2}-\d{2}$/.test(o.since)) { + out.error("gen local-check: --since is a date YYYY-MM-DD (UTC)"); + return 2; + } + const store = await deps.store(); + if ("error" in store) { + out.error(`gen local-check: ${store.error}`); + return 1; + } + const policy = await store.read(); + const r = localChecks({ + policy, + guardHere: isLocalOnly(deps.env), + guardEditor: store.editorLocalOnly ? await store.editorLocalOnly() : null, + apiKey: await (deps.apiKeyAtHand ?? defaultApiKeyAtHand)(), + rows: await (deps.ledger ?? defaultLedger)(), + since: o.since ?? null, + }); + if (o.json) { + out.log(JSON.stringify({ ok: r.ok, since: o.since ?? null, checks: r.checks, local: r.local, apiRows: r.apiRows, from: store.where }, null, 2)); + } else { + out.log(`local-check: ${r.ok ? "PASS" : "FAIL"}`); + for (const c of r.checks) out.log(` ${(c.ok ? "ok " : "FAIL").padEnd(4)} ${c.name.padEnd(8)} ${c.line}`); + out.log(`(from ${store.where})`); + } + return r.ok ? 0 : 1; +} + +async function defaultLedger(): Promise<GenerationUsageRow[]> { + const { getPaths } = await import("../lib/paths"); + const { readGenerationUsage } = await import("../controller/generationUsage"); + return readGenerationUsage(getPaths().generationUsageFile); +} + +// 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 os = await import("node:os"); + 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 } { @@ -444,6 +640,14 @@ export async function genLocalSweepRow(ctx: CommandContext): Promise<number> { 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)); diff --git a/common/controller/frameScan.ts b/common/controller/frameScan.ts @@ -40,7 +40,7 @@ import type { Paths } from "../lib/paths"; import type { GenerationSettings } from "../lib/generationSettings"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import { DRAFT_LOCAL_QUEUE, FRAME_SCAN_QUEUE } from "../lib/queueKeys"; -import { providerOf, unloadOllama } from "../lib/llm"; +import { localOnlyJobRefusal, providerOf, unloadOllama } from "../lib/llm"; import { isSafeChannelSegment, isSafeIdSegment } from "../lib/citations/moments"; import { resolveSavedVideo } from "../lib/savedVideo-server"; import { frameCacheDirOf, frameScanSidecar } from "../lib/frameScan-server"; @@ -259,6 +259,10 @@ export async function enqueueFrameScan(raw: Record<string, unknown>, deps: Frame return refuse((e as Error).message); } const route = providerOf(model); + // LOCAL ONLY (lib/llm/localOnly.ts): refused at the ask with a sentence; + // the API client refuses again before any request. + const localOnly = localOnlyJobRefusal({ models: [model] }, (m) => providerOf(m) === "local"); + if (localOnly) return refuse(localOnly); const capRefusal = async () => (route === "api" ? dailyCapRefusal(await dayUsage(paths.generationUsageFile, utcDay(deps.now?.())), gen.caps.daily) : null); const early = await capRefusal(); if (early) return refuse(early); diff --git a/common/controller/lookoutRun.ts b/common/controller/lookoutRun.ts @@ -98,15 +98,15 @@ import { CUES_JSON_FILENAME } from "../lib/videoStatus"; import { cueLines, cuesOfDoc, planLookout, type LookoutPlanOptions } from "./lookoutPlan"; import { modelLogged } from "./jobModelLog"; import { readMemAvailableMb } from "./persistVideos"; -import { llmConfigOf } from "./reportDraft"; +import { LOCAL_DRAFT_MIN_FREE_MB, llmConfigOf } from "./reportDraft"; export const LOOKOUT_RUN_JOB_KIND = "lookout-run"; export const LOOKOUT_RUN_RESULT_MARKER = "@@lookout-run "; export const LOOKOUT_TASK = "lookout" as const; /** Reading calls one run may make; past it the run ends `partial` with what it has. */ export const LOOKOUT_MAX_CALLS = 400; -/** The job does not start with less MemAvailable than this (MiB). */ -export const LOOKOUT_MIN_FREE_MB = 3072; +/** The job does not start with less MemAvailable than this (MiB): every local model's run's floor (reportDraft.ts). */ +export const LOOKOUT_MIN_FREE_MB = LOCAL_DRAFT_MIN_FREE_MB; /** This many failed calls in a row end the run `failed`. */ export const LOOKOUT_MAX_FAILED_IN_A_ROW = 3; /** Render mode is looked at again this often while it holds. */ diff --git a/common/controller/reportDraft.ts b/common/controller/reportDraft.ts @@ -73,7 +73,8 @@ import { getPaths, type Paths } from "../lib/paths"; import { getSettings } from "../lib/settings"; import { GENERATION_TASKS, capFor, isStepTask, type GenerationSettings, type GenerationTask } from "../lib/generationSettings"; import { PROJECT_URL } from "../lib/project"; -import { PRICES, providerOf, unloadOllama, type LlmConfig } from "../lib/llm"; +import { PRICES, isLocalOnly, localOnlyJobRefusal, providerOf, unloadOllama, type LlmConfig } from "../lib/llm"; +import { readMemAvailableMb } from "./persistVideos"; import { webTools } from "../lib/web/tools"; import { copyIteration, @@ -539,6 +540,36 @@ export function projectsRootOf(gen: GenerationSettings): string { return projectsRootFrom(gen.projectsRoot); } +// LOCAL ONLY (lib/llm/localOnly.ts): the refusal for a report-draft job on a +// local-only instance, or null — at the ask, so the job is refused with a +// sentence. It is not the guarantee: the Claude API client, the ollama client +// and the digest's CLI lane refuse at their own last point before any I/O. +export function localOnlyRefusalOf(body: ReportDraftBody, gen: GenerationSettings, env?: Record<string, string | undefined>): string | null { + if (!isLocalOnly(env)) return null; + const task = body.task; + const route = task === REFRESH_TASK ? gen.routes.sweep : task === TRIAGE_DRAFT_TASK ? null : (gen.routes[task as GenerationTask] ?? null); + const models: string[] = []; + if (body.model) models.push(body.model); + else if (task === TRIAGE_DRAFT_TASK) models.push(gen.triage.model === "local" ? gen.models.local : gen.models.extractor); + else if (route === "api") models.push(gen.models.api); + else if (route === "local" && task !== "verdicts") models.push(gen.models.local); + if (body.extractorModel) models.push(body.extractorModel); + return localOnlyJobRefusal( + { models, answers: body.answers !== undefined && body.answers !== null, route: body.model ? null : route }, + (m) => providerOf(m) === "local", + env, + ); +} + +/** A `draft:local` job does not start with less MemAvailable than this (MiB); the lookout run's floor is this one. */ +export const LOCAL_DRAFT_MIN_FREE_MB = 3072; + +/** The floor a report-draft job on a local model starts with: LOCAL_MODEL_MIN_FREE_MB (MiB; 0 = none), else LOCAL_DRAFT_MIN_FREE_MB. */ +export function localDraftFloorMb(env: Record<string, string | undefined> = process.env): number { + const v = (env.LOCAL_MODEL_MIN_FREE_MB ?? "").trim(); + return /^\d+$/.test(v) ? Number(v) : LOCAL_DRAFT_MIN_FREE_MB; +} + // The model a task runs on: the asked one, else the route's. export function modelFor(gen: GenerationSettings, task: GenerationTask, asked?: string): string { if (asked) return asked; @@ -582,6 +613,9 @@ export type ReportDraftDeps = { researchEditor?: ResearchEditor; // An editor job's state (default: the registry and the .jobs sidecars). jobOf?: JobOf; + // MemAvailable in MiB, or null when unknown (default: /proc/meminfo) — the + // local-model floor (LOCAL_DRAFT_MIN_FREE_MB). + memAvailableMb?: () => Promise<number | null>; // R4.1: why transcription would not run now, or null (default: the worker // pool — paused, or no worker enabled). A refresh's fetch skips // transcribe-bucket under a hold rather than wait on it. @@ -649,6 +683,8 @@ export async function enqueueReportDraft(raw: Record<string, unknown>, deps: Rep return { result: { ok: false, error: (e as Error).message } }; } const refuse = (error: string) => ({ result: { ok: false as const, error } }); + const localOnly = localOnlyRefusalOf(body, gen); + if (localOnly) return refuse(localOnly); if (body.task === TRIAGE_DRAFT_TASK) { try { const { enqueueTriage } = await import("./reportTriage"); @@ -844,6 +880,17 @@ async function runReportDraft( const gen = (deps.settings ?? getSettings)().generation; const provider = providerOf(model); onLog(`${body.task} of ${body.article} i${n} on ${model} (${provider === "api" ? `the Claude API, cap $${o.maxUsd}` : "the local model"})`); + if (provider === "local") { + // The memory floor (demo epic D5), at the job's turn: a local model's run + // beside a machine already short of memory is what OOM-killed ollama in D0. + const floor = localDraftFloorMb(); + const mb = floor > 0 ? await (deps.memAvailableMb ?? readMemAvailableMb)() : null; + if (mb !== null && mb < floor) { + const refusal = `refused: ${mb} MB available is under the ${floor} MB a local model's run starts with — run it when the machine is quieter`; + if (!isStepTask(body.task)) await updateIteration(body.article, n, { status: "failed", error: refusal }, paths).catch(() => {}); + throw new Error(refusal); + } + } if (provider === "api") { // Again at the job's turn: jobs ahead in the queue may have spent the day. const refusal = dailyCapRefusal(await dayUsage(paths.generationUsageFile, utcDay(deps.now?.())), gen.caps.daily); diff --git a/common/controller/reportDraftLocalOnly.test.ts b/common/controller/reportDraftLocalOnly.test.ts @@ -0,0 +1,48 @@ +// The report-draft dispatch's local-only refusal (demo epic D5) and the local +// model's memory floor knob. The end-to-end refusals (no request reaching a +// fake) are editor/app/api/ops/_reportDraft.test.ts's. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { LOCAL_DRAFT_MIN_FREE_MB, localDraftFloorMb, localOnlyRefusalOf, parseReportDraftBody } from "./reportDraft"; +import { GENERATION_PRESETS, sanitizeGeneration } from "../lib/generationSettings"; +import { LOOKOUT_MIN_FREE_MB } from "./lookoutRun"; + +const ON = { ARCHILYZER_LOCAL_ONLY: "1" }; +const local = sanitizeGeneration({ routes: { ...GENERATION_PRESETS.local }, models: { local: "qwen2.5:7b", extractor: "qwen2.5:7b" } }); +const balanced = sanitizeGeneration({}); + +test("off: nothing is refused, whatever the route or model", () => { + const body = parseReportDraftBody({ task: "sweep", article: "a", model: "claude-sonnet-5-5", question: "q", channels: ["c"] }); + assert.equal(localOnlyRefusalOf(body, balanced, {}), null); +}); + +test("on: every task on the local preset passes; a route to code or api is refused by name", () => { + const sweep = parseReportDraftBody({ task: "sweep", article: "a", question: "q", channels: ["c"] }); + assert.equal(localOnlyRefusalOf(sweep, local, ON), null); + assert.match(localOnlyRefusalOf(sweep, balanced, ON)!, /routed to Claude Code/); + const revise = parseReportDraftBody({ task: "revise-report", article: "a", iteration: 1, feedback: "f" }); + assert.match(localOnlyRefusalOf(revise, balanced, ON)!, /"claude-sonnet-5-5" is not a local model/); + const refresh = parseReportDraftBody({ task: "refresh", article: "a" }); + assert.match(localOnlyRefusalOf(refresh, balanced, ON)!, /routed to Claude Code/, "a refresh takes the sweep's route"); + assert.equal(localOnlyRefusalOf(refresh, local, ON), null); +}); + +test("on: a triage on the extractor follows models.extractor", () => { + const triage = parseReportDraftBody({ task: "triage", article: "a", terms: "x", question: "q", channels: ["c"] }); + assert.match(localOnlyRefusalOf(triage, sanitizeGeneration({ triage: { model: "extractor" } }), ON)!, /"claude-haiku-4-5" is not a local model/); + assert.equal(localOnlyRefusalOf(triage, local, ON), null); +}); + +test("on: a Claude Code session's answers are refused even on a local route", () => { + const body = parseReportDraftBody({ task: "propose-groups", project: "/tmp/p", answers: { groups: [] } }); + assert.match(localOnlyRefusalOf(body, local, ON)!, /a Claude Code session's answers are refused/); +}); + +test("the memory floor: 3072 MB by default, LOCAL_MODEL_MIN_FREE_MB overrides it, 0 turns it off; the lookout's is the same", () => { + assert.equal(LOCAL_DRAFT_MIN_FREE_MB, 3072); + assert.equal(LOOKOUT_MIN_FREE_MB, LOCAL_DRAFT_MIN_FREE_MB); + assert.equal(localDraftFloorMb({}), 3072); + assert.equal(localDraftFloorMb({ LOCAL_MODEL_MIN_FREE_MB: "4096" }), 4096); + assert.equal(localDraftFloorMb({ LOCAL_MODEL_MIN_FREE_MB: "0" }), 0); + assert.equal(localDraftFloorMb({ LOCAL_MODEL_MIN_FREE_MB: "lots" }), 3072); +}); diff --git a/common/lib/digestApps.ts b/common/lib/digestApps.ts @@ -28,6 +28,7 @@ import { type DigestLane, } from "./digest"; import "./childKillGuard"; +import { assertLocalOnlyAllowsClaudeCli, assertLocalOnlyAllowsOllamaModel, isLocalOnly } from "./llm/localOnly"; // The lane type, the app ids and DigestAppConfig are defined in the client-safe // digest.ts and re-exported here, so settings.ts can consume them without @@ -170,6 +171,8 @@ const ollamaDirect: DigestApp = { const base = ollamaBase(config); if (!base) throw new Error("ollama URL is not configured (set OLLAMA_URL)"); const model = config.model?.trim() || ollamaDirect.defaultModel(); + // LOCAL ONLY: an ollama cloud model is refused before the request. + assertLocalOnlyAllowsOllamaModel(model); const numCtx = resolveNumCtx(config); const startedAt = Date.now(); @@ -300,6 +303,8 @@ const claudeCode: DigestApp = { fields: { bin: true, model: true }, defaultModel: () => process.env.CLAUDE_DIGEST_MODEL ?? "", async probe(config) { + // LOCAL ONLY: the metered lane is not available, and its CLI is not run. + if (isLocalOnly()) return false; const bin = config.bin?.trim() || getPaths().claudeBin; try { const res = await execa(bin, ["--version"], { @@ -313,6 +318,8 @@ const claudeCode: DigestApp = { } }, async run({ system, prompt, schema, config, signal, onLog }) { + // LOCAL ONLY: refused before the `claude` CLI is started. + assertLocalOnlyAllowsClaudeCli(); const bin = config.bin?.trim() || getPaths().claudeBin; const model = config.model?.trim() || claudeCode.defaultModel(); const startedAt = Date.now(); diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts @@ -136,6 +136,8 @@ const DECLARED: EnvVarDecl[] = [ { name: "UMTOOL_URL", audience: "runtime", default: "unset (no link; the MCP's `notes` off)", readBy: "editor/app/channels/[slug]/videos/[id]/page.tsx, common/lib/umtoolUrl.ts, mcp/src/archivalTools.ts", doc: "umtool's front door; when set, the video page links to it, its Find clips hands the recording to umtool's clip finder (the `find-clips` job posts to `/api/report/clips` with WORKER_TOKEN), and the MCP's `notes` tool reads the operator's notes there and writes a reply as the agent's (e.g. `http://localhost:3050`). Unset: Find clips is disabled." }, { name: "TRANSCRIPT_SITE_URL", audience: "runtime", default: "—", readBy: "mcp/src/sources.ts", doc: "MCP server: one published archive to read over HTTP. Also the default connected archive (common/lib/remoteArchives.ts): the editor, umtool and the MCP offer it as a source when settings.remoteArchives does not list it, without writing it." }, { name: "ARCHILYZER_ALLOW_PRIVATE_ARCHIVES", audience: "runtime", default: "off", readBy: "common/controller/remoteArchives.ts", doc: "`1` lets the editor connect an archive whose host is this machine or its network (loopback, private, link-local, a `.local` name, or a name resolving to such an address), which is refused otherwise: umtool, which can connect one, is open on the LAN. TRANSCRIPT_SITE_URL's archive, and one already written in settings.json, are connected without it. The check is made once, when the archive is connected: a name re-pointed at a private address afterwards is not rechecked (the archive is still read on its own origin only)." }, + { name: "ARCHILYZER_LOCAL_ONLY", audience: "runtime", default: "off", readBy: "common/lib/llm/localOnly.ts (the Claude API client, the ollama clients, the digest's metered lane, the report-draft and frame-scan dispatch, the settings writer, `archilyzer gen`), umtool/components/piece/PolicyChip.tsx", doc: "`1` makes the instance LOCAL ONLY (demo epic D5): every model call that would leave the machine is refused before any request or process — the Claude API, a Claude Code session's `answers` and a task routed to `code`, the digest's `claude` CLI lane, an ollama cloud model (a `…-cloud` tag) — and a settings write that routes a task anywhere but `local` is refused. `archilyzer gen local-check` proves it afterwards. The demo overlay (docker-compose.demo.yml) sets it; unset, nothing changes." }, + { name: "LOCAL_MODEL_MIN_FREE_MB", audience: "runtime", default: "`3072`", readBy: "common/controller/reportDraft.ts", doc: "The MemAvailable floor (MiB) a report-draft job on the local model starts with, at its turn: under it the job is refused with a sentence (demo epic D5; a lookout run has the same floor). `0` turns it off." }, { name: "ARCHIVE_CACHE_DIR", audience: "runtime", default: "`.archive-cache` beside EXPORT_BUILDS_DIR", readBy: "common/lib/archiveCache-server.ts", doc: "Where a remote archive's documents (corpus.json, manifests, shard pages) are kept on disk, by the archive's build: a sweep over a published archive downloads a shard once per build, not once per sweep. In a container it is on the builds volume." }, { name: "ARCHIVE_CACHE_MAX_MB", audience: "runtime", default: "512", readBy: "common/lib/archiveCache-server.ts", doc: "The disk cache of remote archive documents' size cap, MB: past it the least recently used are dropped." }, { name: "ARCHIVE_CACHE", audience: "runtime", default: "on (off under node's test runner)", readBy: "common/lib/archiveCache-server.ts", doc: "`0` reads remote archives without the disk cache (every read over the network, still one at a time); `1` turns it on under node's test runner, where it is off." }, diff --git a/common/lib/generationSettings.ts b/common/lib/generationSettings.ts @@ -193,7 +193,7 @@ export const GENERATION_SETTINGS_FIELD_DOCS: FieldDocs<GenerationSettings> = { anthropicBaseUrl: "Advanced: the Messages API's base URL. Blank = Anthropic's. Tests point it at a fake.", ollamaUrl: "The local model's server (ollama). Blank = the editor's `OLLAMA_URL` (the digest lane's server, default http://127.0.0.1:11434).", projectsRoot: - "Where an iteration's video project and renders live: `<projectsRoot>/<article>/i<n>/`, off the corpus disk (D1). Blank = `~/reports/articles`.", + "Where an iteration's video project and renders live: `<projectsRoot>/<article>/i<n>/`, off the corpus disk (D1). Blank = `<REPORTS_DIR>/articles` when REPORTS_DIR is set (a container's reports volume: `/data/reports/articles`), else `~/reports/articles` (common/lib/projectsRoot.mjs).", web: "The web an agent may read for context (below). Read-only and paced: one request at a time, 3 s apart.", citationOrigin: "The origin a generated report's moment links cite when its corpus build's site has no public URL (a private build). Blank = the project site.", diff --git a/common/lib/llm/anthropic.ts b/common/lib/llm/anthropic.ts @@ -21,6 +21,7 @@ import { readFileSync, statSync } from "node:fs"; import os from "node:os"; import type { CacheTtl } from "./prices"; import type { Meter, Usage } from "./meter"; +import { assertLocalOnlyAllowsApi } from "./localOnly"; export type AnthropicConfig = { apiKeyFile?: string; @@ -248,6 +249,10 @@ export class AnthropicClient { #key: string | undefined; constructor(cfg: AnthropicConfig) { + // LOCAL ONLY (./localOnly.ts): refused before anything — no key read, no + // request. Read from process.env, never cfg.env (that one is the KEY's + // environment, and is {} for a non-Anthropic base URL). + assertLocalOnlyAllowsApi(); this.#cfg = cfg; this.cacheTtl = cfg.cacheTtl ?? "5m"; this.maxRetries = cfg.maxRetries ?? DEFAULT_MAX_RETRIES; @@ -285,6 +290,9 @@ export class AnthropicClient { body: Record<string, unknown>, o: { meter?: Meter; signal?: AbortSignal } = {}, ): Promise<MessagesResponse> { + // Again here, the last point before the network (a client made before the + // flag was set is refused too). + assertLocalOnlyAllowsApi(); const key = this.key(); let sent = prepareBody(body, this.cacheTtl); const doFetch = this.#cfg.fetch ?? fetch; diff --git a/common/lib/llm/index.ts b/common/lib/llm/index.ts @@ -13,3 +13,4 @@ export * from "./agent"; export * from "./callLog"; export * from "./callLog-server"; export * from "./callLogView"; +export * from "./localOnly"; diff --git a/common/lib/llm/localOnly.test.ts b/common/lib/llm/localOnly.test.ts @@ -0,0 +1,157 @@ +// ARCHILYZER_LOCAL_ONLY (demo epic D5): every path a model call leaves the +// machine by is refused BEFORE its I/O — a fake fetch, or a fake `claude` +// binary that leaves a marker file, must never be reached. And with the flag +// unset each path does exactly what it did before (the fake IS reached). +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { existsSync } from "node:fs"; +import { chmod, mkdtemp, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { + AnthropicClient, + LocalOnlyError, + Meter, + isCloudOllamaModel, + isLocalOnly, + localOnlyJobRefusal, + localOnlyRoutesRefusal, + ollamaChat, + providerOf, + runAgent, + structuredAnswer, +} from "./index"; +import { plainAnswer } from "../report/draft/tasks/llmText"; +import { getDigestApp } from "../digestApps"; +import { CLAUDE_DIGEST_APP_ID, OLLAMA_DIGEST_APP_ID } from "../digest"; + +const ON = { ARCHILYZER_LOCAL_ONLY: "1" }; + +async function withFlag<T>(value: string | undefined, body: () => Promise<T>): Promise<T> { + const was = process.env.ARCHILYZER_LOCAL_ONLY; + if (value === undefined) delete process.env.ARCHILYZER_LOCAL_ONLY; + else process.env.ARCHILYZER_LOCAL_ONLY = value; + try { + return await body(); + } finally { + if (was === undefined) delete process.env.ARCHILYZER_LOCAL_ONLY; + else process.env.ARCHILYZER_LOCAL_ONLY = was; + } +} + +// A fetch that counts its calls and answers like a server that refuses (the +// unset case only needs to show the request was SENT). +function countingFetch() { + const calls: string[] = []; + const f = (async (url: string | URL | Request) => { + calls.push(String(url)); + return new Response(JSON.stringify({ error: "fake" }), { status: 500, headers: { "content-type": "application/json" } }); + }) as typeof fetch; + return { f, calls }; +} + +const anthropic = (f: typeof fetch) => ({ baseUrl: "http://fake.invalid", env: { ANTHROPIC_API_KEY: "fake-key-0000-never-real" }, fetch: f, maxRetries: 0, sleep: async () => {} }); + +test("the flag: 1/true/yes/on, anything else off; an ollama cloud tag", () => { + for (const v of ["1", "true", "YES", " on "]) assert.equal(isLocalOnly({ ARCHILYZER_LOCAL_ONLY: v }), true, v); + for (const v of [undefined, "", "0", "false", "off", "local"]) assert.equal(isLocalOnly({ ARCHILYZER_LOCAL_ONLY: v }), false, String(v)); + for (const m of ["gpt-oss:120b-cloud", "qwen3-coder:480b-cloud", "kimi-k2:1t-cloud", "x:cloud"]) assert.equal(isCloudOllamaModel(m), true, m); + for (const m of ["qwen2.5:7b", "qwen3:8b", "cloud", "cloudy:7b", "gemma2:9b-cloudless"]) assert.equal(isCloudOllamaModel(m), false, m); +}); + +test("the Claude API client: refused at construction and at messages(), before any request", async () => { + const { f, calls } = countingFetch(); + const early = new AnthropicClient(anthropic(f)); // made before the flag + await withFlag("1", async () => { + assert.throws(() => new AnthropicClient(anthropic(f)), LocalOnlyError); + await assert.rejects(early.messages({ model: "claude-sonnet-5-5", max_tokens: 8, messages: [] }), /local only \(ARCHILYZER_LOCAL_ONLY=1\): a call to the Claude API is refused/); + }); + assert.equal(calls.length, 0, "no request was sent"); + // Unset: the same client sends (the fake answers 500). + await withFlag(undefined, async () => { + await assert.rejects(early.messages({ model: "claude-sonnet-5-5", max_tokens: 8, messages: [] })); + }); + assert.equal(calls.length, 1, "unset, the request is sent as before"); +}); + +test("structuredAnswer, plainAnswer and runAgent on a Claude model: refused, the fake never called", async () => { + const { f, calls } = countingFetch(); + const llm = { anthropic: anthropic(f) }; + const ask = { llm, model: "claude-sonnet-5-5", system: "s", user: "u" }; + await withFlag("1", async () => { + await assert.rejects(structuredAnswer({ ...ask, schema: { type: "object" } }), LocalOnlyError); + await assert.rejects(plainAnswer({ ...ask, meter: new Meter() }), LocalOnlyError); + await assert.rejects(runAgent({ ...ask, tools: [], meter: new Meter() }), LocalOnlyError); + }); + assert.equal(calls.length, 0); +}); + +test("the ollama client: a cloud model refused before the request; a local model is asked", async () => { + const { f, calls } = countingFetch(); + const cfg = { baseUrl: "http://ollama.invalid", fetch: f }; + await withFlag("1", async () => { + await assert.rejects(ollamaChat(cfg, { model: "gpt-oss:120b-cloud", messages: [{ role: "user", content: "hi" }] }), /the ollama cloud model "gpt-oss:120b-cloud" is refused/); + assert.equal(calls.length, 0); + await assert.rejects(ollamaChat(cfg, { model: "qwen2.5:7b", messages: [{ role: "user", content: "hi" }] }), /ollama returned 500/); + }); + assert.equal(calls.length, 1, "the local model's request went out"); + await withFlag(undefined, async () => { + await assert.rejects(ollamaChat(cfg, { model: "gpt-oss:120b-cloud", messages: [{ role: "user", content: "hi" }] }), /ollama returned 500/); + }); + assert.equal(calls.length, 2, "unset, a cloud tag is sent as before"); +}); + +test("the digest's lanes: the claude CLI is never started; an ollama cloud model never asked", async () => { + const dir = await mkdtemp(path.join(os.tmpdir(), "local-only-")); + try { + const marker = path.join(dir, "ran"); + const bin = path.join(dir, "fake-claude.sh"); + await writeFile(bin, `#!/bin/sh\ntouch '${marker}'\necho '{"result":"{}"}'\n`); + await chmod(bin, 0o755); + const claude = getDigestApp(CLAUDE_DIGEST_APP_ID); + assert.equal(claude.id, CLAUDE_DIGEST_APP_ID); + const input = { system: "s", prompt: "p", schema: { type: "object" }, config: { bin } }; + await withFlag("1", async () => { + await assert.rejects(claude.run(input as never), /the Claude Code CLI \(the digest's metered lane\) is refused/); + assert.equal(await claude.probe!({ bin } as never), false); + }); + assert.equal(existsSync(marker), false, "the CLI was never started"); + // Unset: the same lane runs the binary. + await withFlag(undefined, async () => { + await claude.run(input as never).catch(() => {}); + }); + assert.equal(existsSync(marker), true, "unset, the CLI runs as before"); + + const ollama = getDigestApp(OLLAMA_DIGEST_APP_ID); + const realFetch = globalThis.fetch; + const { f, calls } = countingFetch(); + globalThis.fetch = f; + try { + await withFlag("1", async () => { + await assert.rejects(ollama.run({ system: "s", prompt: "p", schema: {}, config: { baseUrl: "http://ollama.invalid", model: "deepseek-v3.1:671b-cloud" } } as never), LocalOnlyError); + }); + } finally { + globalThis.fetch = realFetch; + } + assert.equal(calls.length, 0); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("a job's refusal: answers, the code route, a Claude or cloud model; local passes; off is always null", () => { + const isLocal = (m: string) => providerOf(m) === "local"; + assert.match(localOnlyJobRefusal({ models: [], answers: true }, isLocal, ON)!, /a Claude Code session's answers are refused/); + assert.match(localOnlyJobRefusal({ models: [], route: "code" }, isLocal, ON)!, /routed to Claude Code/); + assert.match(localOnlyJobRefusal({ models: ["qwen3:8b", "claude-haiku-4-5"] }, isLocal, ON)!, /"claude-haiku-4-5" is not a local model/); + assert.match(localOnlyJobRefusal({ models: ["gpt-oss:120b-cloud"] }, isLocal, ON)!, /ollama cloud model/); + assert.equal(localOnlyJobRefusal({ models: ["qwen2.5:7b", null, undefined] }, isLocal, ON), null); + assert.equal(localOnlyJobRefusal({ models: ["claude-sonnet-5-5"], answers: true, route: "code" }, isLocal, {}), null); +}); + +test("a settings write: any route but local refused under the flag, nothing refused without it", () => { + assert.equal(localOnlyRoutesRefusal({ sweep: "local", narrate: "local" }, ON), null); + assert.match(localOnlyRoutesRefusal({ sweep: "code", narrate: "local", frames: "api" }, ON)!, /not saved: sweep → code, frames → api/); + assert.equal(localOnlyRoutesRefusal({ sweep: "api" }, {}), null); + assert.equal(localOnlyRoutesRefusal(null, ON), null); +}); diff --git a/common/lib/llm/localOnly.ts b/common/lib/llm/localOnly.ts @@ -0,0 +1,91 @@ +// LOCAL ONLY (demo epic D5): `ARCHILYZER_LOCAL_ONLY=1` makes this instance +// refuse every model call that would leave the machine — the Claude API, a +// Claude Code session's answer (the `code` route), the digest's metered lane +// (the `claude` CLI) and an ollama CLOUD model (a `…-cloud` tag, which ollama +// forwards to its hosted service) — BEFORE any network request or process is +// started. It FAILS CLOSED: each path asks `assertLocalOnly…` at the last point +// before its I/O, so a route, a preset or a model named by hand cannot get past +// it; the dispatchers ask too, earlier, only so that a job is refused with a +// sentence instead of failing at its first call. +// +// Unset (or anything but 1/true/yes/on), every function here is a no-op and +// every caller behaves exactly as before the flag existed. +// +// Pure, browser-safe: no node:* import (it reads the environment it is given, +// process.env by default). + +type Env = Record<string, string | undefined>; + +const envOf = (env?: Env): Env => env ?? (typeof process !== "undefined" ? process.env : {}); + +/** Whether ARCHILYZER_LOCAL_ONLY is on. */ +export function isLocalOnly(env?: Env): boolean { + const v = (envOf(env).ARCHILYZER_LOCAL_ONLY ?? "").trim().toLowerCase(); + return v === "1" || v === "true" || v === "yes" || v === "on"; +} + +export const LOCAL_ONLY_WHY = "this instance is local only (ARCHILYZER_LOCAL_ONLY=1)"; + +export class LocalOnlyError extends Error { + constructor(what: string) { + super(`${LOCAL_ONLY_WHY}: ${what} is refused`); + this.name = "LocalOnlyError"; + } +} + +/** + * An ollama model name that runs on ollama's hosted service rather than on + * this machine: its tag is `cloud` or ends in `-cloud` (`gpt-oss:120b-cloud`, + * `qwen3-coder:480b-cloud`, `kimi-k2:1t-cloud`). + */ +export function isCloudOllamaModel(model: string): boolean { + const tag = model.trim().toLowerCase().split(":").slice(1).join(":"); + return tag === "cloud" || tag.endsWith("-cloud"); +} + +/** Throws before the Claude API is asked anything. */ +export function assertLocalOnlyAllowsApi(env?: Env): void { + if (isLocalOnly(env)) throw new LocalOnlyError("a call to the Claude API"); +} + +/** Throws before the `claude` CLI (the digest's metered lane) is started. */ +export function assertLocalOnlyAllowsClaudeCli(env?: Env): void { + if (isLocalOnly(env)) throw new LocalOnlyError("the Claude Code CLI (the digest's metered lane)"); +} + +/** Throws before an ollama model that is not on this machine is asked. */ +export function assertLocalOnlyAllowsOllamaModel(model: string, env?: Env): void { + if (isLocalOnly(env) && isCloudOllamaModel(model)) throw new LocalOnlyError(`the ollama cloud model "${model}"`); +} + +/** + * The refusal for a generation job, or null: on a local-only instance a job + * runs on a local model only and takes no Claude Code session's answers. + * `models` are every model the job would run on (its model, an extractor); + * `isLocal` says whether one is local (providerOf). + */ +export function localOnlyJobRefusal( + o: { models: readonly (string | null | undefined)[]; answers?: boolean; route?: string | null }, + isLocal: (model: string) => boolean, + env?: Env, +): string | null { + if (!isLocalOnly(env)) return null; + if (o.answers) return `${LOCAL_ONLY_WHY}: a Claude Code session's answers are refused`; + if (o.route === "code") return `${LOCAL_ONLY_WHY}: the task is routed to Claude Code — route it to local (\`archilyzer gen preset local\`)`; + for (const m of o.models) { + if (!m) continue; + if (!isLocal(m)) return `${LOCAL_ONLY_WHY}: "${m}" is not a local model — run it on the local model`; + if (isCloudOllamaModel(m)) return `${LOCAL_ONLY_WHY}: "${m}" is an ollama cloud model`; + } + return null; +} + +/** + * The refusal for a settings write on a local-only instance, or null: a + * generation route other than `local`. + */ +export function localOnlyRoutesRefusal(routes: Record<string, unknown> | null | undefined, env?: Env): string | null { + if (!isLocalOnly(env) || !routes) return null; + const off = Object.entries(routes).filter(([, r]) => r !== "local").map(([t, r]) => `${t} → ${String(r)}`); + return off.length ? `${LOCAL_ONLY_WHY}: every generation route stays local — not saved: ${off.join(", ")}` : null; +} diff --git a/common/lib/llm/ollama.ts b/common/lib/llm/ollama.ts @@ -9,6 +9,8 @@ // unless the caller asks for thinking. // `digestApps.ts`'s `ollamaDirect` is the digest's own call and is left as it is. +import { assertLocalOnlyAllowsOllamaModel } from "./localOnly"; + export type OllamaConfig = { baseUrl: string; numCtx?: number; @@ -142,6 +144,9 @@ export async function ollamaChat( signal?: AbortSignal; }, ): Promise<{ message: OllamaMessage; promptTokens: number; evalTokens: number }> { + // LOCAL ONLY (./localOnly.ts): an ollama cloud model is ollama's hosted + // service, not this machine — refused before the request. + assertLocalOnlyAllowsOllamaModel(req.model); const cap = promptCapOf(cfg); const estimate = promptEstimate(req); if (estimate > cap) throw new PromptTooLargeError(estimate, cap); diff --git a/editor/app/api/ops/_reportDraft.test.ts b/editor/app/api/ops/_reportDraft.test.ts @@ -65,12 +65,26 @@ after(async () => { await rm(tmp, { recursive: true, force: true }); }); -const deps = (g: Partial<GenerationSettings> = {}) => ({ +const deps = (g: Partial<GenerationSettings> = {}, memAvailableMb: number | null = 8000) => ({ paths, corpusTools: (s: string) => createCorpusTools({ source: s }), settings: () => ({ generation: { ...gen, ...g } }), + // The local model's memory floor reads this, not the machine's. + memAvailableMb: async () => memAvailableMb, }); +// ARCHILYZER_LOCAL_ONLY for one test's body (demo epic D5), restored after. +async function localOnly<T>(body: () => Promise<T>): Promise<T> { + const was = process.env.ARCHILYZER_LOCAL_ONLY; + process.env.ARCHILYZER_LOCAL_ONLY = "1"; + try { + return await body(); + } finally { + if (was === undefined) delete process.env.ARCHILYZER_LOCAL_ONLY; + else process.env.ARCHILYZER_LOCAL_ONLY = was; + } +} + const run = async (name: string) => JSON.parse(await readFile(path.join(DRAFT, "runs", `${name}.json`), "utf8")); test("the body: each task's needs, and the refusals in words", () => { @@ -313,3 +327,64 @@ test("a local sweep (demo epic D3): its calls in the iteration's model log; the assert.ok(!models.some((m) => m.route === "api" || m.model.startsWith("claude")), "a local-only run lists no cloud model"); assert.deepEqual(await dayUsage(paths.generationUsageFile), spentBefore, "the cap's total and jobs count are the API's alone"); }); + +test("the local model's memory floor (demo epic D5): under it the job fails at its turn with the sentence, and ollama is never asked", async () => { + const r = await run("sweep-pipeline"); + const asked = ol.requests.length; + const out = await enqueueReportDraft({ task: "sweep", article: "synth-floor", model: r.model, question: r.question, channels: r.channels, source }, deps({}, 1000)); + assert.ok(out.result.ok && "iteration" in out, (out.result as { error?: string }).error); + void out.result.stream.cancel(); + const done = await out.result.done; + assert.equal(done.status, "failed"); + const it = (await readIteration("synth-floor", out.iteration, paths))!; + assert.equal(it.status, "failed"); + assert.match(it.error ?? "", /1000 MB available is under the 3072 MB a local model's run starts with/); + assert.equal(ol.requests.length, asked, "no call to the local model"); +}); + +test("local only (demo epic D5): an API model, the API route, a Claude Code session's answers and an ollama cloud model are refused at the ask — no request reaches either fake", async () => { + const apiBefore = api.requests.length; + const olBefore = ol.requests.length; + await localOnly(async () => { + const byModel = await enqueueReportDraft({ task: "sweep", article: "synth-lo-1", model: "claude-sonnet-5-5", question: "q", channels: ["synth-kitchen"], source }, deps()); + assert.equal(byModel.result.ok, false); + assert.match((byModel.result as { error: string }).error, /local only \(ARCHILYZER_LOCAL_ONLY=1\): "claude-sonnet-5-5" is not a local model/); + const byRoute = await enqueueReportDraft( + { task: "sweep", article: "synth-lo-2", question: "q", channels: ["synth-kitchen"], source }, + deps({ routes: { ...gen.routes, sweep: "api" } }), + ); + assert.match((byRoute.result as { error: string }).error, /"claude-sonnet-5-5" is not a local model/); + const code = await enqueueReportDraft({ task: "sweep", article: "synth-lo-3", question: "q", channels: ["synth-kitchen"], source }, deps({ routes: { ...gen.routes, sweep: "code" } })); + assert.match((code.result as { error: string }).error, /routed to Claude Code/); + const extractor = await enqueueReportDraft( + { task: "sweep", article: "synth-lo-4", model: "qwen3:8b", extractorModel: "claude-haiku-4-5", question: "q", channels: ["synth-kitchen"], source }, + deps(), + ); + assert.match((extractor.result as { error: string }).error, /"claude-haiku-4-5" is not a local model/); + const cloud = await enqueueReportDraft({ task: "sweep", article: "synth-lo-5", model: "gpt-oss:120b-cloud", question: "q", channels: ["synth-kitchen"], source }, deps()); + assert.match((cloud.result as { error: string }).error, /"gpt-oss:120b-cloud" is an ollama cloud model/); + for (const a of ["synth-lo-1", "synth-lo-2", "synth-lo-3", "synth-lo-4", "synth-lo-5"]) assert.equal(await readIteration(a, 1, paths), null, `${a}: no iteration made`); + }); + assert.equal(api.requests.length, apiBefore, "the fake Claude API was never asked"); + assert.equal(ol.requests.length, olBefore, "the fake ollama was never asked"); +}); + +test("local only: a local sweep still runs, on the local model alone", async () => { + const r = await run("sweep-pipeline"); + // Its own fake ollama: the shared one's script may hold an earlier test's turns. + const own = await startFakeOllama({ turns: r.turns }); + const apiBefore = api.requests.length; + try { + await localOnly(async () => { + const out = await enqueueReportDraft({ task: "sweep", article: "synth-lo-local", model: r.model, question: r.question, channels: r.channels, source }, deps({ ollamaUrl: own.url })); + assert.ok(out.result.ok && "iteration" in out, (out.result as { error?: string }).error); + void out.result.stream.cancel(); + const done = await out.result.done; + assert.equal(done.status, "done", await readFile(getRegistry().get(out.result.jobId)!.logPath, "utf8")); + }); + assert.ok(own.requests.length > 0, "the local model was asked"); + } finally { + await own.close(); + } + assert.equal(api.requests.length, apiBefore, "the Claude API was not"); +}); diff --git a/editor/app/api/ops/_writes.test.ts b/editor/app/api/ops/_writes.test.ts @@ -79,6 +79,26 @@ test("the patch rule: leaves compared, arrays element by element, absent keys no assert.equal(settingsPatchProblem({ a: 1 }, ["a"], { a: 1 }), null); }); +test("local only (demo epic D5): a patch that routes a task anywhere but local is refused; other generation writes pass", () => { + const was = process.env.ARCHILYZER_LOCAL_ONLY; + const parsed = (routes: Record<string, string>) => ({ generation: { routes, models: { local: "qwen2.5:7b" } } }); + try { + process.env.ARCHILYZER_LOCAL_ONLY = "1"; + assert.match( + settingsPatchProblem({ generation: { routes: { sweep: "api" } } }, ["generation"], parsed({ sweep: "api", narrate: "local" }))!, + /local only \(ARCHILYZER_LOCAL_ONLY=1\): every generation route stays local — not saved: sweep → api/, + ); + assert.equal(settingsPatchProblem({ generation: { routes: { sweep: "local" } } }, ["generation"], parsed({ sweep: "local", narrate: "local" })), null); + // A write that does not touch the routes is not held by routes already on disk. + assert.equal(settingsPatchProblem({ generation: { models: { local: "qwen2.5:7b" } } }, ["generation"], parsed({ sweep: "code" })), null); + delete process.env.ARCHILYZER_LOCAL_ONLY; + assert.equal(settingsPatchProblem({ generation: { routes: { sweep: "api" } } }, ["generation"], parsed({ sweep: "api" })), null, "unset: as before"); + } finally { + if (was === undefined) delete process.env.ARCHILYZER_LOCAL_ONLY; + else process.env.ARCHILYZER_LOCAL_ONLY = was; + } +}); + test("lane: the publish lane is a lane; an unknown one is refused by the full list", async () => { const lane = await route("lane"); const bogus = await callPost(lane, { lane: "transcode", held: true }); diff --git a/editor/app/api/ops/generation-usage/route.ts b/editor/app/api/ops/generation-usage/route.ts @@ -1,13 +1,14 @@ import { getPaths } from "yt-dlp-transcript-common/lib/paths"; import { getSettings } from "yt-dlp-transcript-common/lib/settings"; import { dayModels, dayUsage, utcDay } from "yt-dlp-transcript-common/controller/generationUsage"; +import { isLocalOnly } from "yt-dlp-transcript-common/lib/llm/localOnly"; import { readRoute } from "../_read"; import { opsFail } from "../_lib"; export const dynamic = "force-dynamic"; // GET [?day=YYYY-MM-DD] -// -> { ok, day, usd, jobs, daily, models: [{model, route, calls, jobs, inputTokens, outputTokens}] } +// -> { ok, day, usd, jobs, daily, models: [{model, route, calls, jobs, inputTokens, outputTokens}], localOnly } // // The day's Claude API spend on generation (release 27 S9): the usage // ledger's total for the UTC day (default today) — what the daily cap is @@ -15,7 +16,9 @@ export const dynamic = "force-dynamic"; // (`settings.generation.caps.daily`, 0 = none). The MCP's generation_policy // and `archilyzer gen policy` show it beside the routes. `models`: every model // the day's generation called and on which route ("api", or "local" with no -// cost, demo epic D3) — a local-only day lists no Claude model. Read only. +// cost, demo epic D3) — a local-only day lists no Claude model. `localOnly`: +// whether THIS editor runs with ARCHILYZER_LOCAL_ONLY on (demo epic D5; +// `archilyzer gen local-check`, umtool's policy chip). Read only. const DAY = /^\d{4}-\d{2}-\d{2}$/; export async function GET(request: Request) { @@ -24,6 +27,6 @@ export async function GET(request: Request) { if (!DAY.test(day)) return opsFail('"day" must be a date YYYY-MM-DD (UTC)'); const file = getPaths().generationUsageFile; const [used, models] = await Promise.all([dayUsage(file, day), dayModels(file, day)]); - return { ...used, daily: getSettings().generation.caps.daily, models }; + return { ...used, daily: getSettings().generation.caps.daily, models, localOnly: isLocalOnly() }; }); } diff --git a/editor/app/api/ops/settings/patch.ts b/editor/app/api/ops/settings/patch.ts @@ -1,6 +1,8 @@ // WHAT `POST /api/ops/settings` REFUSES, as one pure function — testable // without a settings file, a schema or a server. +import { localOnlyRoutesRefusal } from "yt-dlp-transcript-common/lib/llm/localOnly"; + // Keys another writer owns. Writing one raw would skip what that writer keeps // true, so the refusal names the writer: // - channelPriority: the priority write compiles the four lanes' trees in the @@ -60,6 +62,14 @@ export function settingsPatchProblem( if (owned.length) { return owned.map((k) => `"${k}" is not patched here: ${OWNED_KEYS[k]}`).join("; "); } + // LOCAL ONLY (common/lib/llm/localOnly.ts): a patch that routes a task + // anywhere but `local` is refused while ARCHILYZER_LOCAL_ONLY is on. + const gen = patch.generation; + if (isObject(gen) && Object.hasOwn(gen, "routes")) { + const routes = isObject(parsed.generation) && isObject(parsed.generation.routes) ? parsed.generation.routes : null; + const refusal = localOnlyRoutesRefusal(routes); + if (refusal) return refusal; + } const coerced = keys.flatMap((k) => coercedLeaves(patch[k], parsed[k], k)); if (coerced.length) { return `not saved — the schema would not keep ${coerced.length === 1 ? "this value" : "these values"} as sent: ${coerced.join("; ")}`; diff --git a/umtool/components/piece/PolicyChip.tsx b/umtool/components/piece/PolicyChip.tsx @@ -1,14 +1,18 @@ import Link from "next/link"; import { cache } from "react"; import { badgeVariants } from "@/components/ui/badge"; +import { isLocalOnly } from "yt-dlp-transcript-common/lib/llm/localOnly"; import { readPolicy, readToday } from "@/lib/articles/generation"; +import { policyChipLabel } from "@/lib/articles/policyChip"; import { generationPolicyHref } from "@/lib/hrefs"; import { cn } from "@/lib/utils"; // THE GENERATION POLICY, as a chip (P4a-2; canvas "Create": "Policy shown as a -// chip"): the policy's one line -- its preset, the API model, the day's spend -// against the daily cap -- with a Meter dot, linking to where it is set -// (/settings/generation, P5's page, which holds the PolicyPanel). +// chip"): the policy's one line -- its preset, the model that runs (the API's +// when a task is routed to the API, else the local model's), the day's spend +// against the daily cap when the API is in use, "local only" on a local-only +// instance (lib/articles/policyChip.ts) -- with a Meter dot, linking to where +// it is set (/settings/generation, P5's page, which holds the PolicyPanel). // // Async: the policy is the editor's (askEditor), so the frame streams this in // under a <Suspense>; an editor that does not answer is said, not hidden. @@ -19,7 +23,6 @@ const policyOnce = cache(() => readPolicy()); const todayOnce = cache((daily: number) => readToday(daily)); const usd = (v: number) => `$${v.toFixed(2)}`; -const shortModel = (m: string) => m.replace(/^claude-/, ""); export function PolicyChipShell({ children, preset }: { children: React.ReactNode; preset?: string }) { return ( @@ -47,11 +50,19 @@ export default async function PolicyChip() { ); } const g = policy.generation; - const today = await todayOnce(g.caps.daily).catch(() => null); + const label = policyChipLabel(g, isLocalOnly()); + const today = label.spend ? await todayOnce(g.caps.daily).catch(() => null) : null; return ( <PolicyChipShell preset={g.preset}> <span>{g.preset}</span> - <span className="font-mono text-[11px] text-muted">{shortModel(g.models.api)}</span> + <span className="font-mono text-[11px] text-muted" data-policy-model={label.model}> + {label.model} + </span> + {label.localOnly && ( + <span className="text-[11px] text-muted" data-policy-local-only=""> + local only + </span> + )} {today && ( <span className="font-mono text-[11px] text-meter" data-policy-today={today.usd.toFixed(2)}> today {usd(today.usd)} diff --git a/umtool/lib/articles/policyChip.test.ts b/umtool/lib/articles/policyChip.test.ts @@ -0,0 +1,36 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { policyChipLabel } from "./policyChip"; + +const models = { api: "claude-sonnet-5-5", local: "qwen2.5:7b" }; + +test("a policy that routes a task to the API shows the API model and the day's spend", () => { + assert.deepEqual(policyChipLabel({ preset: "balanced", routes: { sweep: "code", "revise-report": "api", narrate: "local" }, models }, false), { + preset: "balanced", + model: "sonnet-5-5", + spend: true, + localOnly: false, + }); +}); + +test("an all-local policy shows the local model and no spend", () => { + assert.deepEqual(policyChipLabel({ preset: "local", routes: { sweep: "local", narrate: "local" }, models }, false), { + preset: "local", + model: "qwen2.5:7b", + spend: false, + localOnly: false, + }); +}); + +test("a code route alone is not the API: the local model is shown", () => { + assert.equal(policyChipLabel({ preset: "code", routes: { sweep: "code", narrate: "local" }, models }, false).model, "qwen2.5:7b"); +}); + +test("local only: the local model, no spend, and the flag, whatever the routes say", () => { + assert.deepEqual(policyChipLabel({ preset: "custom", routes: { sweep: "api" }, models }, true), { + preset: "custom", + model: "qwen2.5:7b", + spend: false, + localOnly: true, + }); +}); diff --git a/umtool/lib/articles/policyChip.ts b/umtool/lib/articles/policyChip.ts @@ -0,0 +1,31 @@ +// What the generation policy's chip says (components/piece/PolicyChip.tsx): +// the preset, then the model that runs — the Claude API's when any task is +// routed to the API, else the local model's — and the day's API spend only +// when the API is in use. On a local-only instance (ARCHILYZER_LOCAL_ONLY, +// demo epic D5) it says "local only" and shows no spend at all. Pure. + +export type PolicyChipInput = { + preset: string; + routes: Record<string, string>; + models: { api: string; local: string }; +}; + +export type PolicyChipLabel = { + preset: string; + model: string; + // Show the day's Claude API spend beside it. + spend: boolean; + localOnly: boolean; +}; + +const shortModel = (m: string) => m.replace(/^claude-/, ""); + +export function policyChipLabel(g: PolicyChipInput, localOnly: boolean): PolicyChipLabel { + const usesApi = !localOnly && Object.values(g.routes).some((r) => r === "api"); + return { + preset: g.preset, + model: usesApi ? shortModel(g.models.api) : g.models.local, + spend: usesApi, + localOnly, + }; +}