// 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, isLocalModelUrl, isLocalOnly, localOnlyFlag, localOnlyJobRefusal, localOnlyRoutesRefusal, localOnlySettingsRefusal, LOCAL_ONLY_CLAIM, ollamaChat, resetLocalOllamaChecks, unloadOllama, 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(value: string | undefined, body: () => Promise): Promise { 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). // `/api/show` answers `show` (a local model by default: no remote_host), so // only the model calls are counted in `calls`; `shows` counts the shows. function countingFetch(show: Record | number = { details: { family: "qwen2" } }) { const calls: string[] = []; const shows: string[] = []; const f = (async (url: string | URL | Request) => { const u = String(url); if (u.endsWith("/api/show")) { shows.push(u); return typeof show === "number" ? new Response("{}", { status: show }) : new Response(JSON.stringify(show), { status: 200 }); } calls.push(u); return new Response(JSON.stringify({ error: "fake" }), { status: 500, headers: { "content-type": "application/json" } }); }) as typeof fetch; return { f, calls, shows }; } async function withEnv(vars: Record, body: () => Promise): Promise { const was: Record = {}; for (const [k, v] of Object.entries(vars)) { was[k] = process.env[k]; if (v === undefined) delete process.env[k]; else process.env[k] = v; } try { return await body(); } finally { for (const [k, v] of Object.entries(was)) { if (v === undefined) delete process.env[k]; else process.env[k] = v; } } } 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); }); const hi = (model: string) => ({ model, messages: [{ role: "user", content: "hi" }] }); test("the ollama client: a cloud model refused before the request; a local model is asked", async () => { resetLocalOllamaChecks(); const { f, calls } = countingFetch(); const cfg = { baseUrl: "http://127.0.0.1:11434", fetch: f }; await withFlag("1", async () => { await assert.rejects(ollamaChat(cfg, hi("gpt-oss:120b-cloud")), /the ollama cloud model "gpt-oss:120b-cloud" is refused/); assert.equal(calls.length, 0); await assert.rejects(ollamaChat(cfg, hi("qwen2.5:7b")), /ollama returned 500/); }); assert.equal(calls.length, 1, "the local model's request went out"); await withFlag(undefined, async () => { await assert.rejects(ollamaChat(cfg, hi("gpt-oss:120b-cloud")), /ollama returned 500/); }); assert.equal(calls.length, 2, "unset, a cloud tag is sent as before"); }); test("'local' is a host: loopback or ARCHILYZER_LOCAL_MODEL_HOSTS; anything else is refused before any request (M2)", async () => { resetLocalOllamaChecks(); const { f, calls, shows } = countingFetch(); await withEnv({ ARCHILYZER_LOCAL_ONLY: "1", ARCHILYZER_LOCAL_MODEL_HOSTS: undefined }, async () => { for (const far of ["https://ollama-proxy.cloud.example", "http://ollama:11434", "http://192.168.1.20:11434", "http://10.0.0.5:11434"]) { await assert.rejects(ollamaChat({ baseUrl: far, fetch: f }, hi("qwen2.5:7b")), /the ollama server at .* is not on this machine/, far); await assert.rejects(unloadOllama({ baseUrl: far, fetch: f }, "qwen2.5:7b"), /is not on this machine/, far); } assert.equal(calls.length + shows.length, 0, "nothing was sent anywhere"); for (const here of ["http://127.0.0.1:11434", "http://127.3.4.5:1", "http://localhost:11434", "http://[::1]:11434"]) { assert.equal(isLocalModelUrl(here), true, here); } }); await withEnv({ ARCHILYZER_LOCAL_ONLY: "1", ARCHILYZER_LOCAL_MODEL_HOSTS: "ollama" }, async () => { await assert.rejects(ollamaChat({ baseUrl: "http://ollama:11434", fetch: f }, hi("qwen2.5:7b")), /ollama returned 500/); assert.equal(calls.length, 1, "the compose service host the demo names is asked"); assert.equal(isLocalModelUrl("http://ollama.evil.example:11434"), false, "an exact name, not a prefix"); }); }); test("a cloud model behind a local alias: /api/show naming a remote host refuses; an unreadable show refuses; a good one is asked once per process (S5)", async () => { await withFlag("1", async () => { resetLocalOllamaChecks(); const remote = countingFetch({ remote_host: "https://ollama.com:443", remote_model: "gpt-oss:120b", details: {} }); await assert.rejects(ollamaChat({ baseUrl: "http://127.0.0.1:11434", fetch: remote.f }, hi("my-alias:latest")), /"my-alias:latest" is served from a remote host \(its \/api\/show says so\)/); assert.equal(remote.calls.length, 0); resetLocalOllamaChecks(); const down = countingFetch(503); await assert.rejects(ollamaChat({ baseUrl: "http://127.0.0.1:11434", fetch: down.f }, hi("qwen2.5:7b")), /could not confirm that "qwen2.5:7b" runs on this machine \(\/api\/show answered 503\)/); assert.equal(down.calls.length, 0); resetLocalOllamaChecks(); const ok = countingFetch(); for (let i = 0; i < 3; i++) await assert.rejects(ollamaChat({ baseUrl: "http://127.0.0.1:11434", fetch: ok.f }, hi("qwen2.5:7b")), /ollama returned 500/); assert.equal(ok.shows.length, 1, "asked once per server and model"); assert.equal(ok.calls.length, 3); }); // Unset: no show is asked at all. resetLocalOllamaChecks(); const off = countingFetch(); await withFlag(undefined, async () => { await assert.rejects(ollamaChat({ baseUrl: "http://ollama.lan:11434", fetch: off.f }, hi("qwen2.5:7b")), /ollama returned 500/); }); assert.equal(off.shows.length, 0); }); test("the flag's values: one parser; a value it does not understand is off AND said so (S7)", () => { for (const v of ["1", " TRUE ", "yes", "On"]) assert.deepEqual([localOnlyFlag({ ARCHILYZER_LOCAL_ONLY: v }).on, localOnlyFlag({ ARCHILYZER_LOCAL_ONLY: v }).understood], [true, true], v); for (const v of [undefined, "", "0", "false", "NO", "off"]) assert.deepEqual([localOnlyFlag({ ARCHILYZER_LOCAL_ONLY: v }).on, localOnlyFlag({ ARCHILYZER_LOCAL_ONLY: v }).understood], [false, true], String(v)); for (const v of ["2", "y", "enabled", "local"]) assert.deepEqual([localOnlyFlag({ ARCHILYZER_LOCAL_ONLY: v }).on, localOnlyFlag({ ARCHILYZER_LOCAL_ONLY: v }).understood], [false, false], v); }); test("a settings write: a route off local, a non-local generation.ollamaUrl or digest baseUrl refused; untouched keys are not judged (M2)", () => { const ON2 = { ARCHILYZER_LOCAL_ONLY: "1" }; const merged = (gen: Record, digest: Record = {}) => ({ generation: { routes: { sweep: "local" }, ...gen }, digest }); assert.match(localOnlySettingsRefusal({ generation: { ollamaUrl: "https://ollama-proxy.cloud.example" } }, merged({ ollamaUrl: "https://ollama-proxy.cloud.example" }), ON2)!, /the local route's model server \(generation\.ollamaUrl\) at ollama-proxy\.cloud\.example is not on this machine .* — not saved/); assert.equal(localOnlySettingsRefusal({ generation: { ollamaUrl: "" } }, merged({ ollamaUrl: "" }), ON2), null, "blank = OLLAMA_URL, judged at call time"); assert.equal(localOnlySettingsRefusal({ generation: { ollamaUrl: "http://127.0.0.1:11434" } }, merged({ ollamaUrl: "http://127.0.0.1:11434" }), ON2), null); assert.match(localOnlySettingsRefusal({ digest: { apps: {} } }, merged({}, { apps: { "ollama-direct": { baseUrl: "http://gpu-box:11434" } } }), ON2)!, /the digest engine ollama-direct \(digest\.apps\.ollama-direct\.baseUrl\) at gpu-box/); assert.match(localOnlySettingsRefusal({ generation: { routes: { sweep: "api" } } }, merged({ routes: { sweep: "api" } }), ON2)!, /not saved: sweep → api/); assert.equal(localOnlySettingsRefusal({ minFreeDiskGB: 1 }, merged({ ollamaUrl: "https://far.example", routes: { sweep: "code" } }), ON2), null, "a write that touches neither is not held"); assert.equal(localOnlySettingsRefusal({ generation: { ollamaUrl: "https://far.example" } }, merged({ ollamaUrl: "https://far.example" }), {}), null, "unset: 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://127.0.0.1:11434", model: "deepseek-v3.1:671b-cloud" } } as never), LocalOnlyError); // An LLM worker's (or digest.apps') baseUrl elsewhere: neither run nor probe asks it. await assert.rejects(ollama.run({ system: "s", prompt: "p", schema: {}, config: { baseUrl: "http://gpu-box.lan:11434", model: "qwen2.5:7b" } } as never), /the ollama server at gpu-box\.lan is not on this machine/); assert.equal(await ollama.probe!({ baseUrl: "http://gpu-box.lan:11434" } as never), false); }); } 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); }); test("the claim the docs make is the one this module states (ENVIRONMENT.md's row quotes LOCAL_ONLY_CLAIM)", async () => { const { ENV_VARS } = await import("../envVars"); const row = ENV_VARS.find((v) => v.name === "ARCHILYZER_LOCAL_ONLY"); assert.ok(row?.doc.includes(LOCAL_ONLY_CLAIM), "ENVIRONMENT.md states the claim word for word"); });