Archilyzer · Source

archilyzer

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

commit 084c824729303d630e6ad63bbabebe6babcc6cd5
parent ba2de05d35c1a7d5a3df6c93f7636767802f1918
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri, 13 Nov 2026 00:28:20 -0500

demo-setup review round 1: "local" is this machine, the demo cannot be bound off loopback, the memory floor waits, and local-check proves only what it read (M1, M2, S1-S9)

M1. docker/demo.sh checks every value it writes to .env.demo by character
class with shell builtins (--archive: a single-line http(s) URL; no space,
quote, $, backtick, # or control character), refuses a .env.demo line it did
not write or a *_BIND other than 127.0.0.1 there or in the shell, and exports
127.0.0.1 for every bind before compose runs. docker-compose.yml hands the
caddy container the interpolated *_BIND values, so guard-exposure.sh judges
what `ports:` publishes (for every stack, not only the demo).

M2. Under ARCHILYZER_LOCAL_ONLY a model server must be loopback or a host in
ARCHILYZER_LOCAL_MODEL_HOSTS (the demo overlay: `ollama`): ollamaChat,
unloadOllama, the digest's ollama-direct (run and probe; an LLM worker's
baseUrl arrives there), acquireLlmSlot and validateWorkers refuse anything
else before any request; the ops settings patch and the editor's
saveSettings refuse generation.ollamaUrl / digest.apps.*.baseUrl elsewhere.
gen local-check prints each effective endpoint by host and fails on one
elsewhere. LOCAL_ONLY_CLAIM is the one sentence every doc quotes.

S1 one sentence for each failed step of up. S2 the report-draft floor waits
(15 s polls, 10 min, cancel ends it). S3 umtool's chip asks the editor and is
main's chip without the flag. S4 the editor's own writer guarded. S5 /api/show
once per server and model; a remote_host refuses, an unreadable show refuses.
S6 local-check: no calls = NOTHING TO PROVE YET (exit 0, never PASS), --since a
real date not after today, the per-call logs counted, imports refused under
the flag and failed on, paths tildified. S7 entrypoint and localOnlyFlag read
the flag alike; a value not understood is an ERROR line. S8 down without
.env.demo, socket permission sentence, dry-run header names the host ollama
GET, GPU as intent, sizes only for known models, name:latest. S9 the claude
lane says "refused: local only".

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

Diffstat:
MCOMMANDS.md | 2+-
MENVIRONMENT.md | 5+++--
MRUNNING_IN_DOCKER.md | 62+++++++++++++++++++++++++++++++++++++++++++++++---------------
Mcommon/bin/archilyzer.ts | 2+-
Mcommon/bin/gen.test.ts | 104+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------
Mcommon/bin/gen.ts | 245++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------------
Mcommon/bin/reports-import-local-runs.ts | 8++++++++
Mcommon/bin/reports-import-sweep.test.ts | 22++++++++++++++++++++++
Mcommon/bin/reports-import-sweep.ts | 8++++++++
Mcommon/controller/laneGuards.test.ts | 22++++++++++++++++++++++
Mcommon/controller/laneGuards.ts | 6++++++
Mcommon/controller/llmWorkers.test.ts | 22++++++++++++++++++++++
Mcommon/controller/llmWorkers.ts | 10++++++++++
Mcommon/controller/lookoutRun.ts | 2+-
Mcommon/controller/reportDraft.ts | 45+++++++++++++++++++++++++++++++++++++++------
Mcommon/lib/digestApps.ts | 11++++++++---
Mcommon/lib/envVars.ts | 5+++--
Mcommon/lib/llm/localOnly.test.ts | 122+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------
Mcommon/lib/llm/localOnly.ts | 152+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
Mcommon/lib/llm/ollama.ts | 54++++++++++++++++++++++++++++++++++++++++++++++++++----
Mcommon/lib/workers.test.ts | 15+++++++++++++++
Mcommon/lib/workers.ts | 5+++++
Mcommon/testing/llm/fakeOllama.d.mts | 4++++
Mcommon/testing/llm/fakeOllama.mjs | 17+++++++++++++++++
Mdocker-compose.demo.yml | 23+++++++++++++++++------
Mdocker-compose.yml | 9+++++++++
Mdocker/demo.sh | 185+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------
Mdocker/entrypoint.sh | 25++++++++++++++++++++-----
Meditor/CHANGELOG.md | 8++++----
Meditor/app/api/ops/_reportDraft.test.ts | 54+++++++++++++++++++++++++++++++++++++++++++++++++-----
Meditor/app/api/ops/_writes.test.ts | 5+++++
Meditor/app/api/ops/settings/patch.ts | 13+++++--------
Meditor/app/settings/saveSettings.test.ts | 21+++++++++++++++++++++
Meditor/app/settings/saveSettings.ts | 9++++++++-
Mscripts/demo.test.mjs | 179+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------
Mumtool/components/piece/PolicyChip.tsx | 47++++++++++++++++++++++++++++++-----------------
Mumtool/lib/articles/policyChip.test.ts | 33++++++---------------------------
Mumtool/lib/articles/policyChip.ts | 23+++++++++--------------
38 files changed, 1327 insertions(+), 257 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -46,7 +46,7 @@ Run from the repo root (in the container: `docker compose exec editor pnpm archi | `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 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; a value it does not understand is named), every generation route local, every model server a local route asks (generation.ollamaUrl or OLLAMA\_URL, the digest's, each enabled LLM worker; printed by host) on this machine (loopback, or ARCHILYZER\_LOCAL\_MODEL\_HOSTS), no Claude API key at hand (its presence only: never read out), the usage ledger and the per-call logs since the date holding no call off the local route, and no iteration imported from a run made elsewhere; --since is a calendar date (UTC), not after today. Exit 1 when any check fails; with none failing but no call recorded yet the verdict is NOTHING TO PROVE YET (exit 0), never PASS. Paths are printed with the home directory as ~ | | `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,8 +100,9 @@ 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 | +| `ARCHILYZER_LOCAL_ONLY` | off | LOCAL ONLY (demo epic D5). With ARCHILYZER_LOCAL_ONLY=1, this instance refuses — before any request is sent or any process started — every call to the Claude API, every Claude Code answer (a task routed to `code`, or `answers` posted by a session), the digest's `claude` CLI lane, and every call to an ollama model that is a cloud model (a `-cloud` tag, or one whose /api/show names a remote host) or that is served from anywhere but this machine (a loopback address) or a host named in ARCHILYZER_LOCAL_MODEL_HOSTS. It does not cover the web pages a local model may read (its web_search and fetch tools), the published site's in-browser Ask, or remote transcription workers, which are not language models. Settings writes that would route a task off `local` or name a model server elsewhere are refused too, and `reports import-sweep` / `import-local-runs` are. `1`, `true`, `yes`, `on` (trimmed, any case) turn it on; `0`, `false`, `no`, `off` or unset leave it off; anything else is not understood — off, and the editor's boot log says so as an ERROR. `archilyzer gen local-check` checks it afterwards. umtool makes no model call itself (it asks the editor). 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 lanes, LLM workers, the report-draft and frame-scan dispatch, the settings writers, the report imports, `archilyzer gen`), docker/entrypoint.sh | +| `ARCHILYZER_LOCAL_MODEL_HOSTS` | none | Under ARCHILYZER_LOCAL_ONLY: the host names besides loopback (127.0.0.0/8, ::1, localhost) a local model may be served from — comma-separated, exact, case-insensitive. docker-compose.demo.yml sets `ollama`, the compose service on the stack's own network. Without the flag it means nothing. | common/lib/llm/localOnly.ts | +| `LOCAL_MODEL_MIN_FREE_MB` | `3072` | The MemAvailable floor (MiB) a report-draft job on the local model WAITS for at its turn (demo epic D5): under it the job logs `waiting for memory — N MB available, the floor is F MB`, reads MemAvailable again every 15 s, and fails with a sentence only after 10 minutes; a cancel ends the wait. `0` turns it off. A lookout run refuses (it does not wait) below its own fixed 3072 MB, which this variable does not move. | 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/RUNNING_IN_DOCKER.md b/RUNNING_IN_DOCKER.md @@ -164,26 +164,58 @@ its device (`ollama: GPU Vulkan, AMD Radeon …` or `ollama: CPU ONLY`); pulls the model unless ollama has it; and sets every task local through the product's own commands (`archilyzer gen preset local`, `gen model local|extractor <model>`). It is idempotent: a second `up` changes nothing that is already so. - -**Local only.** `docker-compose.demo.yml` sets `ARCHILYZER_LOCAL_ONLY=1` on the -editor and umtool (common/lib/llm/localOnly.ts): the Claude API client refuses -before any request, a task routed to Claude Code or a session's `answers` is -refused, the digest's `claude` lane is never started, an ollama cloud model (a -`…-cloud` tag) is refused, and a settings write that routes a task anywhere but -`local` is refused. ollama runs with `OLLAMA_NO_CLOUD=1`, and the Claude API -overlay is never part of this stack. The editor's boot log says `models: LOCAL -ONLY`; umtool's policy chip says "local only" with the local model's name. -`./docker/demo.sh check` (and `archilyzer gen local-check` in the editor) proves -it afterwards, by counts: the flag on, every route local, no API key at hand, -and the usage ledger holding no Claude API row. +A step that fails after the stack has started (the start itself, the editor's +first answer, the pull, the settings) ends `up` with one sentence naming it, +saying the demo is partly up and that `./docker/demo.sh down` stops it. `down` +stops project `archilyzer-demo` whether or not `.env.demo` is still there. + +**Local only.** `docker-compose.demo.yml` sets `ARCHILYZER_LOCAL_ONLY=1` and +`ARCHILYZER_LOCAL_MODEL_HOSTS=ollama` on the editor +(common/lib/llm/localOnly.ts). What that enforces, word for word: + +> With ARCHILYZER_LOCAL_ONLY=1, this instance refuses — before any request is +> sent or any process started — every call to the Claude API, every Claude Code +> answer (a task routed to `code`, or `answers` posted by a session), the +> digest's `claude` CLI lane, and every call to an ollama model that is a cloud +> model (a `-cloud` tag, or one whose /api/show names a remote host) or that is +> served from anywhere but this machine (a loopback address) or a host named in +> ARCHILYZER_LOCAL_MODEL_HOSTS. It does not cover the web pages a local model +> may read (its web_search and fetch tools), the published site's in-browser +> Ask, or remote transcription workers, which are not language models. + +Settings writes (the ops route and the editor's own pages) that would route a +task off `local` or name a model server elsewhere are refused too, and so are +`reports import-sweep` and `reports import-local-runs`. umtool makes no model +call itself — it asks the editor. The Claude API overlay is never part of this +stack, and ollama runs with `OLLAMA_NO_CLOUD=1` (its effect on ollama 0.40.5 is +not yet verified; the `-cloud` tag and /api/show checks do not depend on it). +The editor's boot log says `models: LOCAL ONLY` (a value of the flag it does +not understand is an ERROR line there); umtool's policy chip, asking the +editor, names the local model and says "local only". + +`./docker/demo.sh check` (and `archilyzer gen local-check` in the editor) checks +it afterwards, by counts and host names: the flag on, every route local, every +model server a local route asks on this machine, no API key at hand, no call +off the local route in the usage ledger or the per-call logs since `--since`, +and no imported iteration. With nothing recorded yet it says NOTHING TO PROVE +YET rather than PASS. **Bounds on ollama** (the demo overlay): one request and one model at a time, `OLLAMA_KEEP_ALIVE=2m`, llama.cpp's prompt cache capped at 1024 MiB (`LLAMA_ARG_CACHE_RAM`; its default is 8192 MiB, which grew to 8–11 GB in the baseline and was OOM-killed twice), and `mem_limit` equal to `memswap_limit` — -40% of RAM, 4 to 8 GB — so a runaway dies in its own container. A report-draft -job on the local model refuses to start under 3072 MB MemAvailable -(`LOCAL_MODEL_MIN_FREE_MB`). +40% of RAM, 4 to 8 GB — so a runaway dies in its own container. These names +are the ones the bundled llama-server and ollama 0.40.16's `serve --help` +list; whether ollama 0.40.5 hands `LLAMA_ARG_CACHE_RAM` to its runner is +checked only at a real `up`. A report-draft job on the local model WAITS (up to +10 minutes, saying so in its log) while MemAvailable is under 3072 MB +(`LOCAL_MODEL_MIN_FREE_MB`), then fails with a sentence. + +**Binds.** demo.sh refuses a `*_BIND` other than 127.0.0.1 in `.env.demo` or in +the shell, refuses any `.env.demo` line it did not write (or a value outside +its character class), and exports 127.0.0.1 for every bind before compose runs; +docker-compose.yml hands the caddy container the binds compose publishes on, so +the exposure guard judges what is really published. **The voice.** Orpheus runs on a `llama-server` the editor starts per batch, and this image carries none (see [Text to speech](#text-to-speech)): `up` says diff --git a/common/bin/archilyzer.ts b/common/bin/archilyzer.ts @@ -500,7 +500,7 @@ export const COMMANDS: Command[] = [ { 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", + "[--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; a value it does not understand is named), every generation route local, every model server a local route asks (generation.ollamaUrl or OLLAMA_URL, the digest's, each enabled LLM worker; printed by host) on this machine (loopback, or ARCHILYZER_LOCAL_MODEL_HOSTS), no Claude API key at hand (its presence only: never read out), the usage ledger and the per-call logs since the date holding no call off the local route, and no iteration imported from a run made elsewhere; --since is a calendar date (UTC), not after today. Exit 1 when any check fails; with none failing but no call recorded yet the verdict is NOTHING TO PROVE YET (exit 0), never PASS. Paths are printed with the home directory as ~", flags: { since: "string", json: "boolean" }, maxPositionals: 0, run: async (ctx) => (await import("./gen")).genLocalCheckRow(ctx), diff --git a/common/bin/gen.test.ts b/common/bin/gen.test.ts @@ -339,46 +339,104 @@ const row = (r: Partial<import("../controller/generationUsage").GenerationUsageR ...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); +const ON = { on: true, raw: "1", understood: true }; +const base = (o: Partial<Parameters<typeof gen.localChecks>[0]> = {}) => + gen.localChecks({ + policy: ALL_LOCAL, + flagHere: ON, + guardEditor: true, + apiKey: null, + endpoints: [{ what: "the local route (OLLAMA_URL)", url: "http://127.0.0.1:11434" }], + rows: [], + calls: [], + imported: [], + since: null, + env: {}, + ...o, + }); +const call = (route: string, at = "2026-11-13T10:00:00Z", model = "qwen2.5:7b") => ({ route, at, model }); + +test("gen local-check: PASS only with recorded calls, all local; each failing check named; --since narrows", () => { + const pass = base({ rows: [row({}), row({ jobId: "j2", calls: 3 })], calls: [call("local"), call("local")] }); + assert.equal(pass.verdict, "pass"); 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\)/); + assert.deepEqual(pass.checks.map((c) => [c.name, c.status]), [["guard", "ok"], ["routes", "ok"], ["endpoints", "ok"], ["api key", "ok"], ["ledger", "ok"], ["model log", "ok"], ["imports", "ok"]]); + assert.match(pass.checks[4]!.line, /all of it: 0 Claude API rows; local: qwen2\.5:7b 15 call\(s\) in 2 job\(s\)/); + assert.match(pass.checks[5]!.line, /2 call\(s\), every one on the local route/); + assert.match(pass.checks[2]!.line, /^the local route \(OLLAMA_URL\) → 127\.0\.0\.1$/); 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 }); + const fail = base({ + policy: BALANCED, + flagHere: { on: false, raw: "", understood: true }, + guardEditor: false, + apiKey: "file", + endpoints: [{ what: "the local route (generation.ollamaUrl)", url: "https://ollama-proxy.cloud.example" }, { what: "LLM worker w1", url: "http://gpu-box.lan:11434" }], + rows: [apiRow, row({})], + calls: [call("api", "2026-11-01T00:00:00Z", "claude-sonnet-5-5"), call("local")], + imported: [{ article: "a", n: 2, at: "2026-11-02T00:00:00Z", from: "claude-code" }], + }); + assert.equal(fail.verdict, "fail"); assert.equal(fail.ok, false); - assert.deepEqual(fail.checks.map((c) => c.ok), [false, false, false, false]); + assert.deepEqual(fail.checks.map((c) => c.status), ["fail", "fail", "fail", "fail", "fail", "fail", "fail"]); 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(fail.checks[2]!.line, /ollama-proxy\.cloud\.example \(NOT this machine\); LLM worker w1 → gpu-box\.lan \(NOT this machine\)/); + assert.match(fail.checks[3]!.line, /the key file exists/); + assert.match(fail.checks[4]!.line, /1 Claude API row\(s\) \(claude-sonnet-5-5\)/); + assert.match(fail.checks[5]!.line, /2 call\(s\), 1 NOT local \(api claude-sonnet-5-5\)/); + assert.match(fail.checks[6]!.line, /1 iteration\(s\) made elsewhere and imported: a i2 \(from claude-code\)/); + // Before --since, the API rows, the call and the import do not count. + const since = base({ guardEditor: null, rows: [apiRow, row({})], calls: [call("api", "2026-11-01T00:00:00Z"), call("local")], imported: [{ article: "a", n: 2, at: "2026-11-02T00:00:00Z", from: "x" }], since: "2026-11-13" }); + assert.equal(since.verdict, "pass"); assert.match(since.checks[0]!.line, /this process; no editor answered/); + // ARCHILYZER_LOCAL_MODEL_HOSTS names the compose service. + const compose = base({ endpoints: [{ what: "w", url: "http://ollama:11434" }], env: { ARCHILYZER_LOCAL_MODEL_HOSTS: "ollama" } }); + assert.equal(compose.checks[2]!.status, "ok"); + assert.equal(base({ endpoints: [{ what: "w", url: "http://ollama:11434" }] }).checks[2]!.status, "fail"); +}); + +test("gen local-check: an empty ledger and log is 'nothing to prove yet' (exit 0), never a pass; a flag not understood is named (S6, S7)", () => { + const empty = base(); + assert.equal(empty.verdict, "nothing-yet"); + assert.equal(empty.ok, true); + assert.deepEqual(empty.checks.filter((c) => c.status === "none").map((c) => [c.name, c.line]), [["ledger", "all of it: no calls recorded"], ["model log", "all of it: no calls recorded"]]); + const typo = base({ flagHere: { on: false, raw: "enabled", understood: false }, guardEditor: null }); + assert.equal(typo.checks[0]!.status, "fail"); + assert.match(typo.checks[0]!.line, /ARCHILYZER_LOCAL_ONLY="enabled" is not understood here, so the guard is OFF/); +}); + +test("gen local-check --since: a real calendar date, not in the future", () => { + assert.equal(gen.sinceProblem("2026-11-13", "2026-11-13"), null); + assert.match(gen.sinceProblem("2026-02-30", "2026-11-13")!, /not a calendar date/); + assert.match(gen.sinceProblem("2099-01-01", "2026-11-13")!, /is after today \(2026-11-13, UTC\)/); + assert.match(gen.sinceProblem("13 Nov", "2026-11-13")!, /YYYY-MM-DD/); }); -test("gen local-check: the command's lines and exit; never a key or a key path", async () => { +test("gen local-check: the command's lines and exit; never a key, a key path or a home path", async () => { const { store } = memoryStore(ALL_LOCAL); store.editorLocalOnly = async () => true; + store.where = `settings.json (${os.homedir()}/x/settings.json; no editor answering)`; + const evidence = async () => ({ endpoints: [{ what: "the local route (OLLAMA_URL)", url: "http://ollama:11434" }], rows: [row({})], calls: [call("local")], imported: [] }); 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 code = await gen.localCheckMain({ json: false }, { store: async () => store, runOps: async () => 0, out: c.out, env: { ARCHILYZER_LOCAL_MODEL_HOSTS: "ollama" }, evidence, apiKeyAtHand: async () => null }); + assert.equal(code, 0, c.lines.join("\n")); + assert.equal(c.lines[0], "local-check: PASS — the setup is local only, and every recorded call was local"); + assert.ok(c.lines.some((l) => /^ {2}ok {3}guard {5}ARCHILYZER_LOCAL_ONLY is on \(the editor says so\)$/.test(l)), c.lines.join("\n")); + assert.ok(c.lines.some((l) => /endpoints .*→ ollama$/.test(l)), c.lines.join("\n")); + assert.equal(c.lines.at(-1), "(from settings.json (~/x/settings.json; no editor answering))"); + assert.ok(!c.lines.join("\n").includes(os.homedir() + "/"), "no absolute home path"); + const n = capture(); + assert.equal(await gen.localCheckMain({ json: false }, { store: async () => store, runOps: async () => 0, out: n.out, env: {}, evidence: async () => ({ endpoints: [], rows: [], calls: [], imported: [] }), apiKeyAtHand: async () => null }), 0); + assert.match(n.lines[0]!, /^local-check: NOTHING TO PROVE YET/); 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" }), + await gen.localCheckMain({ json: true, since: "2026-11-01" }, { store: async () => store, runOps: async () => 0, out: j.out, env: {}, evidence: async () => ({ endpoints: [], rows: [], calls: [], imported: [] }), apiKeyAtHand: async () => "env" }), 1, ); const body = JSON.parse(j.lines[0]!); assert.equal(body.ok, false); - assert.equal(body.since, "2026-11-01"); + assert.equal(body.verdict, "fail"); 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); + assert.equal(await gen.localCheckMain({ json: false, since: "2099-01-01" }, { store: async () => store, runOps: async () => 0, out: bad.out }), 2); }); diff --git a/common/bin/gen.ts b/common/bin/gen.ts @@ -31,6 +31,7 @@ // // The API key is never read, printed or written here: it is not a setting. +import os from "node:os"; import path from "node:path"; import { pathToFileURL } from "node:url"; import type { CommandContext } from "./_cli"; @@ -50,7 +51,7 @@ import { type GenerationPreset, type GenerationRoute, } from "../lib/generationSettings"; -import { isCloudOllamaModel, isLocalOnly, localOnlyRoutesRefusal } from "../lib/llm/localOnly"; +import { isCloudOllamaModel, isLocalModelUrl, isLocalOnly, localOnlyFlag, localOnlyRoutesRefusal, modelHostOf } from "../lib/llm/localOnly"; import type { GenerationUsageRow } from "../controller/generationUsage"; type Out ={ log: (s: string) => void; error: (s: string) => void }; @@ -78,6 +79,8 @@ export type GenStore = { // Whether the editor itself runs local only (ARCHILYZER_LOCAL_ONLY in ITS // environment), or null when no editor answers. editorLocalOnly?(): Promise<boolean | null>; + // One top-level settings key as the store holds it (secrets redacted), or null. + readKey?(key: string): Promise<unknown>; }; export type GenDeps = { @@ -89,9 +92,10 @@ export type GenDeps = { // 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[]>; + // `gen local-check`: what it judges (default: the editor's settings, the + // ledger, the per-call logs and the iterations, off disk) and whether an API + // key is at hand (its env var or file's presence, never read out). + evidence?: (store: GenStore) => Promise<LocalEvidence>; apiKeyAtHand?: () => Promise<"env" | "file" | null>; }; @@ -235,6 +239,10 @@ export async function editorStore(env: NodeJS.ProcessEnv = process.env, fetchImp const a = await call("GET", "/api/ops/generation-usage"); return a.kind === "ok" && typeof a.body.localOnly === "boolean" ? a.body.localOnly : null; }, + async readKey(key) { + const a = await call("GET", `/api/ops/settings?key=${encodeURIComponent(key)}`); + return a.kind === "ok" ? (a.body.value ?? null) : null; + }, }; } @@ -416,42 +424,74 @@ export async function modelMain(o: { slot?: string; name?: string }, deps: GenDe } // `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 }; +// this instance has stayed local, by counts, hosts and route names — never a +// key, a key file's path or its contents, never an absolute home path. +// +// guard ARCHILYZER_LOCAL_ONLY on (the editor's own answer when one +// answers); a value the flag does not understand is named +// routes every generation route local +// endpoints every model server a local route asks (generation.ollamaUrl, +// else OLLAMA_URL; the digest's ollama; each enabled LLM worker) +// on this machine — loopback, or ARCHILYZER_LOCAL_MODEL_HOSTS +// api key none at hand (presence only) +// ledger the usage ledger since the date: no Claude API row +// model log the per-call logs (calls/<jobId>, and the iterations they +// point at): no call on a route but local +// imports no iteration imported from a run made elsewhere +// (`reports import-sweep`, `reports import-local-runs`, which +// local only refuses) +// +// Exit 1 when any check FAILS. When none fails but neither the ledger nor the +// model log holds a call yet, the verdict is "nothing to prove yet" (exit 0): +// the setup is local only, and no model call has been recorded to prove it by. +export type CheckStatus = "ok" | "fail" | "none"; +export type LocalCheck = { name: string; ok: boolean; status: CheckStatus; line: string }; +export type LocalEndpoint = { what: string; url: string }; +export type LoggedCall = { route: string; at: string; model: string }; +export type ImportedIteration = { article: string; n: number; at: string; from: string }; +export type LocalVerdict = "pass" | "fail" | "nothing-yet"; + +const check = (name: string, status: CheckStatus, line: string): LocalCheck => ({ name, ok: status !== "fail", status, line }); export function localChecks(o: { policy: GenPolicy; - guardHere: boolean; + flagHere: { on: boolean; raw: string; understood: boolean }; guardEditor: boolean | null; apiKey: "env" | "file" | null; + endpoints: readonly LocalEndpoint[]; rows: readonly GenerationUsageRow[]; + calls: readonly LoggedCall[]; + imported: readonly ImportedIteration[]; since: string | null; -}): { ok: boolean; checks: LocalCheck[]; local: { model: string; calls: number; jobs: number }[]; apiRows: number } { + env?: Record<string, string | undefined>; +}): { ok: boolean; verdict: LocalVerdict; checks: LocalCheck[]; local: { model: string; calls: number; jobs: number }[]; apiRows: number } { const checks: LocalCheck[] = []; - const guardOn = o.guardEditor ?? o.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 guardOn = o.guardEditor ?? o.flagHere.on; + const notUnderstood = !o.flagHere.understood ? ` — ARCHILYZER_LOCAL_ONLY=${JSON.stringify(o.flagHere.raw)} is not understood here, so the guard is OFF in this process` : ""; + checks.push( + check( + "guard", + guardOn ? "ok" : "fail", + (guardOn + ? `ARCHILYZER_LOCAL_ONLY is on (${o.guardEditor === null ? "this process; no editor answered" : "the editor says so"})` + : "ARCHILYZER_LOCAL_ONLY is OFF — a Claude route would be called") + notUnderstood, + ), + ); const routes = Object.entries(o.policy.routes); const off = routes.filter(([, r]) => r !== "local"); - checks.push({ - 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; + checks.push(check("routes", off.length === 0 ? "ok" : "fail", off.length === 0 ? `${routes.length} of ${routes.length} local (preset ${o.policy.preset})` : `${off.length} of ${routes.length} not local: ${off.map(([t, r]) => `${t} → ${r}`).join(", ")}`)); + const hostOf = (url: string) => modelHostOf(url) ?? (url ? "an unreadable URL" : "not set"); + const far = o.endpoints.filter((e) => !isLocalModelUrl(e.url, o.env)); + checks.push( + check( + "endpoints", + far.length === 0 ? "ok" : "fail", + o.endpoints.map((e) => `${e.what} → ${hostOf(e.url)}${isLocalModelUrl(e.url, o.env) ? "" : " (NOT this machine)"}`).join("; ") || "none configured", + ), + ); + checks.push(check("api key", o.apiKey === null ? "ok" : "fail", o.apiKey === null ? "none at hand (no ANTHROPIC_API_KEY, no key file)" : `one is at hand (${o.apiKey === "env" ? "ANTHROPIC_API_KEY is set" : "the key file exists"})`)); + const inRange = (day: string) => !o.since || day >= o.since; + const rows = o.rows.filter((r) => inRange(r.day)); const api = rows.filter((r) => r.route !== "local"); const byModel = new Map<string, { model: string; calls: number; jobs: Set<string> }>(); for (const r of rows) { @@ -462,51 +502,155 @@ export function localChecks(o: { 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 }; + const range = o.since ? `since ${o.since}` : "all of it"; + if (rows.length === 0) checks.push(check("ledger", "none", `${range}: no calls recorded`)); + else + checks.push( + check( + "ledger", + api.length === 0 ? "ok" : "fail", + `${range}: ${api.length === 0 ? "0 Claude API rows" : `${api.length} Claude API row(s) (${[...new Set(api.map((r) => r.model))].sort().join(", ")})`}; ` + + (local.length ? `local: ${local.map((m) => `${m.model} ${m.calls} call(s) in ${m.jobs} job(s)`).join(", ")}` : "no local calls"), + ), + ); + const calls = o.calls.filter((c) => inRange(c.at.slice(0, 10))); + const farCalls = calls.filter((c) => c.route !== "local"); + if (calls.length === 0) checks.push(check("model log", "none", `${range}: no calls recorded`)); + else { + const routesSeen = [...new Set(farCalls.map((c) => `${c.route} ${c.model}`))].sort(); + checks.push(check("model log", farCalls.length === 0 ? "ok" : "fail", `${range}: ${calls.length} call(s), ${farCalls.length === 0 ? "every one on the local route" : `${farCalls.length} NOT local (${routesSeen.join(", ")})`}`)); + } + const imports = o.imported.filter((i) => inRange(i.at.slice(0, 10))); + checks.push(check("imports", imports.length === 0 ? "ok" : "fail", imports.length === 0 ? `${range}: no iteration imported from elsewhere` : `${imports.length} iteration(s) made elsewhere and imported: ${imports.map((i) => `${i.article} i${i.n} (from ${i.from})`).join(", ")}`)); + const failed = checks.some((c) => c.status === "fail"); + const nothing = !failed && checks.find((c) => c.name === "ledger")!.status === "none" && checks.find((c) => c.name === "model log")!.status === "none"; + return { ok: !failed, verdict: failed ? "fail" : nothing ? "nothing-yet" : "pass", checks, local, apiRows: api.length }; +} + +/** `--since`'s refusal, or null: a real calendar date (UTC), not after today. */ +export function sinceProblem(since: string, today: string = new Date().toISOString().slice(0, 10)): string | null { + if (!/^\d{4}-\d{2}-\d{2}$/.test(since)) return "--since is a date YYYY-MM-DD (UTC)"; + const t = Date.parse(`${since}T00:00:00Z`); + if (Number.isNaN(t) || new Date(t).toISOString().slice(0, 10) !== since) return `--since ${since} is not a calendar date`; + if (since > today) return `--since ${since} is after today (${today}, UTC)`; + return null; +} + +// A path as it may be printed: the home directory as `~` (a container's +// /data paths are printed as they are). +export function tildify(text: string, home: string = os.homedir()): string { + return home && home !== "/" ? text.split(home).join("~") : text; } export async function localCheckMain(o: { since?: string; json: boolean }, deps: GenDeps): Promise<number> { const out = deps.out ?? console; - 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)"); + const bad = o.since !== undefined ? sinceProblem(o.since) : null; + if (bad) { + out.error(`gen local-check: ${bad}`); return 2; } const store = await deps.store(); if ("error" in store) { - out.error(`gen local-check: ${store.error}`); + out.error(tildify(`gen local-check: ${store.error}`)); return 1; } const policy = await store.read(); + const env = deps.env ?? process.env; + const ev = await (deps.evidence ?? defaultEvidence)(store); const r = localChecks({ policy, - guardHere: isLocalOnly(deps.env), + flagHere: localOnlyFlag(env), guardEditor: store.editorLocalOnly ? await store.editorLocalOnly() : null, apiKey: await (deps.apiKeyAtHand ?? defaultApiKeyAtHand)(), - rows: await (deps.ledger ?? defaultLedger)(), + endpoints: ev.endpoints, + rows: ev.rows, + calls: ev.calls, + imported: ev.imported, since: o.since ?? null, + env, }); + const where = tildify(store.where); if (o.json) { - out.log(JSON.stringify({ ok: r.ok, since: o.since ?? null, checks: r.checks, local: r.local, apiRows: r.apiRows, from: store.where }, null, 2)); + out.log(JSON.stringify({ ok: r.ok, verdict: r.verdict, since: o.since ?? null, checks: r.checks, local: r.local, apiRows: r.apiRows, from: where }, null, 2)); } else { - out.log(`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})`); + out.log( + r.verdict === "fail" + ? "local-check: FAIL" + : r.verdict === "nothing-yet" + ? "local-check: NOTHING TO PROVE YET — the setup is local only, and no model call is recorded yet to prove it by" + : "local-check: PASS — the setup is local only, and every recorded call was local", + ); + for (const c of r.checks) out.log(` ${(c.status === "ok" ? "ok" : c.status === "none" ? "--" : "FAIL").padEnd(4)} ${c.name.padEnd(9)} ${c.line}`); + out.log(`(from ${where})`); } return r.ok ? 0 : 1; } -async function defaultLedger(): Promise<GenerationUsageRow[]> { +export type LocalEvidence = { endpoints: LocalEndpoint[]; rows: GenerationUsageRow[]; calls: LoggedCall[]; imported: ImportedIteration[] }; + +// What local-check reads, off disk (it runs where the editor's files are: +// the editor's container, or the host of a host install) and from the store. +async function defaultEvidence(store: GenStore): Promise<LocalEvidence> { const { getPaths } = await import("../lib/paths"); + const { getSettings } = await import("../lib/settings"); const { readGenerationUsage } = await import("../controller/generationUsage"); - return readGenerationUsage(getPaths().generationUsageFile); + const paths = getPaths(); + const s = getSettings(); + const gen = (store.readKey ? ((await store.readKey("generation")) as Record<string, unknown> | null) : null) ?? (s.generation as unknown as Record<string, unknown>); + const digest = (store.readKey ? ((await store.readKey("digest")) as Record<string, unknown> | null) : null) ?? (s.digest as unknown as Record<string, unknown>); + const workers = (store.readKey ? ((await store.readKey("workers")) as unknown[] | null) : null) ?? (s.workers as unknown[]); + const endpoints: LocalEndpoint[] = []; + const genUrl = typeof gen?.ollamaUrl === "string" && gen.ollamaUrl.trim() ? gen.ollamaUrl.trim() : paths.ollamaUrl; + endpoints.push({ what: typeof gen?.ollamaUrl === "string" && gen.ollamaUrl.trim() ? "the local route (generation.ollamaUrl)" : "the local route (OLLAMA_URL)", url: genUrl }); + const apps = digest && typeof digest.apps === "object" && digest.apps ? (digest.apps as Record<string, { baseUrl?: string }>) : {}; + const digestUrl = apps["ollama-direct"]?.baseUrl?.trim(); + endpoints.push({ what: digestUrl ? "the digest (digest.apps.ollama-direct)" : "the digest (OLLAMA_URL)", url: digestUrl || paths.ollamaUrl }); + for (const w of Array.isArray(workers) ? workers : []) { + const x = w as { kind?: string; enabled?: boolean; id?: string; llm?: { baseUrl?: string } }; + if (x.kind === "llm" && x.enabled) endpoints.push({ what: `LLM worker ${x.id ?? "?"}`, url: x.llm?.baseUrl ?? "" }); + } + return { + endpoints, + rows: await readGenerationUsage(paths.generationUsageFile), + calls: await loggedCalls(paths), + imported: await importedIterations(paths), + }; +} + +// Every call the per-call logs hold: each job's own (calls/<jobId>/) and the +// iteration logs the jobs point at, each file read once. +async function loggedCalls(paths: import("../lib/paths").Paths): Promise<LoggedCall[]> { + const { readdir } = await import("node:fs/promises"); + const { locateJobModelLog } = await import("../controller/jobModelLog"); + const { readModelLog } = await import("../lib/llm/callLog-server"); + const dir = path.join(path.dirname(paths.generationUsageFile), "calls"); + const ids = await readdir(dir).catch(() => [] as string[]); + const seen = new Set<string>(); + const out: LoggedCall[] = []; + for (const id of ids) { + if (!/^[A-Za-z0-9._-]+$/.test(id) || /^\.+$/.test(id)) continue; + const at = await locateJobModelLog(paths, id).catch(() => null); + if (!at || seen.has(at.files.calls)) continue; + seen.add(at.files.calls); + const log = await readModelLog(at.files).catch(() => null); + for (const c of log?.calls ?? []) out.push({ route: c.route, at: c.at, model: c.model }); + } + return out; +} + +// Every iteration that carries `imported` (a run made elsewhere). +async function importedIterations(paths: import("../lib/paths").Paths): Promise<ImportedIteration[]> { + const { listArticles } = await import("../lib/report/registry"); + const { listIterations } = await import("../lib/report/iterations"); + const out: ImportedIteration[] = []; + for (const a of await listArticles(paths).catch(() => [])) { + for (const it of await listIterations(a.id, paths).catch(() => [])) { + const imp = (it as unknown as { imported?: { from?: unknown; run?: unknown } }).imported; + if (!imp) continue; + out.push({ article: a.id, n: it.n, at: it.createdAt, from: typeof imp.from === "string" ? imp.from : typeof imp.run === "string" ? `the stopgap run ${imp.run}` : "elsewhere" }); + } + } + return out; } // Whether a Claude API key is at hand — its presence only: the variable is @@ -515,7 +659,6 @@ 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; diff --git a/common/bin/reports-import-local-runs.ts b/common/bin/reports-import-local-runs.ts @@ -34,6 +34,7 @@ // Exit 0 when every run is importable (dry run) or imported (apply), or was // imported before; 1 when any is refused or fails; 2 for a usage error. +import { isLocalOnly } from "../lib/llm/localOnly"; import { projectsRootFrom } from "../lib/projectsRoot.mjs"; import { cp, lstat, mkdir, readdir, readFile, rename, rm, stat } from "node:fs/promises"; import os from "node:os"; @@ -766,6 +767,13 @@ const projectsRootOf = (gen: GenerationSettings) => (projectsRootFrom(gen.projec // The CLI row's options, from the flags and the settings. export async function importRow(flags: { apply?: boolean; runs?: string; only?: string; "move-projects"?: boolean; generation?: string }): Promise<number> { + // LOCAL ONLY (lib/llm/localOnly.ts): a report made elsewhere is not + // imported into a local-only instance — its words came from a model this + // instance cannot vouch for (and `gen local-check` fails on one already in). + if (isLocalOnly()) { + console.error("reports import-local-runs: refused — this instance is local only (ARCHILYZER_LOCAL_ONLY=1), and a report made elsewhere is not imported into it"); + return 1; + } const only = typeof flags.only === "string" ? flags.only.split(",").map((s) => s.trim()).filter(Boolean) : undefined; if (flags.only !== undefined && !only?.length) { console.error("reports import-local-runs: --only names runs, comma-separated"); diff --git a/common/bin/reports-import-sweep.test.ts b/common/bin/reports-import-sweep.test.ts @@ -128,3 +128,25 @@ test("the CLI row: usage errors exit 2", async () => { console.error = err; } }); + +test("local only (demo epic D5): import-sweep and import-local-runs are refused before they read or write anything", async () => { + const { importSweepRow } = await import("./reports-import-sweep"); + const { importRow } = await import("./reports-import-local-runs"); + const was = process.env.ARCHILYZER_LOCAL_ONLY; + const errors: string[] = []; + const err = console.error; + console.error = (m: string) => errors.push(m); + process.env.ARCHILYZER_LOCAL_ONLY = "1"; + try { + assert.equal(await importSweepRow("/nonexistent/report.json", { article: "lo-import", question: "q", apply: true }), 1); + assert.equal(await importRow({ apply: true }), 1); + } finally { + console.error = err; + if (was === undefined) delete process.env.ARCHILYZER_LOCAL_ONLY; + else process.env.ARCHILYZER_LOCAL_ONLY = was; + } + assert.deepEqual(errors, [ + "reports import-sweep: refused — this instance is local only (ARCHILYZER_LOCAL_ONLY=1), and a report made elsewhere is not imported into it", + "reports import-local-runs: refused — this instance is local only (ARCHILYZER_LOCAL_ONLY=1), and a report made elsewhere is not imported into it", + ]); +}); diff --git a/common/bin/reports-import-sweep.ts b/common/bin/reports-import-sweep.ts @@ -24,6 +24,7 @@ // Exit 0 when the plan is sound (dry run) or the iteration is written (apply); // 1 when it is refused; 2 for a usage error. +import { isLocalOnly } from "../lib/llm/localOnly"; import { readFile } from "node:fs/promises"; import path from "node:path"; import type { Paths } from "../lib/paths"; @@ -173,6 +174,13 @@ export async function importSweepRow( reportFile: string | undefined, flags: { article?: string; question?: string; sweep?: string; channels?: string; model?: string; from?: string; minutes?: string; apply?: boolean }, ): Promise<number> { + // LOCAL ONLY (lib/llm/localOnly.ts): a report made elsewhere is not + // imported into a local-only instance — its words came from a model this + // instance cannot vouch for (and `gen local-check` fails on one already in). + if (isLocalOnly()) { + console.error("reports import-sweep: refused — this instance is local only (ARCHILYZER_LOCAL_ONLY=1), and a report made elsewhere is not imported into it"); + return 1; + } if (!reportFile || typeof flags.article !== "string" || typeof flags.question !== "string") { console.error("reports import-sweep: give <report.json> --article <id> --question <question>"); return 2; diff --git a/common/controller/laneGuards.test.ts b/common/controller/laneGuards.test.ts @@ -161,3 +161,25 @@ test("only the digest lanes share a duplicate's output", () => { false, ); }); + +test("local only (demo epic D5): the metered lane is refused as such, without probing — never 'is the claude CLI installed'", async () => { + const was = process.env.ARCHILYZER_LOCAL_ONLY; + process.env.ARCHILYZER_LOCAL_ONLY = "1"; + try { + let probed = false; + const verdict = await digestPreflight({ + settings: settingsWith({ remoteEnabled: true }), + lane: "remote", + app: { id: "claude-code", lane: "remote-api", probe: async () => ((probed = true), true) }, + }); + assert.equal(verdict.ok, false); + assert.match(verdict.ok ? "" : verdict.error, /^refused: local only \(ARCHILYZER_LOCAL_ONLY=1\) — the digest's claude-code lane runs the claude CLI, which this instance never starts$/); + assert.equal(probed, false); + // The local lane is not touched by the flag. + const local = await digestPreflight({ settings: settingsWith({}), lane: "local", app: { id: "ollama", lane: "local-gpu", probe: async () => true } }); + assert.equal(local.ok, true); + } finally { + if (was === undefined) delete process.env.ARCHILYZER_LOCAL_ONLY; + else process.env.ARCHILYZER_LOCAL_ONLY = was; + } +}); diff --git a/common/controller/laneGuards.ts b/common/controller/laneGuards.ts @@ -7,6 +7,7 @@ import { import type { DigestLane } from "../lib/digest"; import { isGateHeld } from "../lib/pauseGates"; import { transcriptionActivity } from "./digestYield"; +import { isLocalOnly } from "../lib/llm/localOnly"; // THE LANE'S RULES, declared once, in the two shapes a dispatcher can act on. // @@ -90,6 +91,11 @@ export async function digestPreflight( "The metered digest lane is disabled (settings.digest.remoteEnabled). Enable it in Settings before running it.", }; } + // LOCAL ONLY (lib/llm/localOnly.ts): the metered lane is refused, and its + // probe answers false for that reason — say so, not "is it installed". + if (input.app.lane === "remote-api" && isLocalOnly()) { + return { ok: false, error: `refused: local only (ARCHILYZER_LOCAL_ONLY=1) — the digest's ${input.app.id} lane runs the claude CLI, which this instance never starts` }; + } if (!(await input.app.probe())) { return { ok: false, diff --git a/common/controller/llmWorkers.test.ts b/common/controller/llmWorkers.test.ts @@ -120,3 +120,25 @@ test("a dead endpoint is degraded rather than looped on", async () => { assert.equal(slot, null); assert.equal(pool.summary().find((w) => w.id === "dead")?.degraded, true); }); + +test("local only (demo epic D5): an LLM worker not on this machine is degraded without a request; a loopback one is leased", async () => { + clearLlmVerificationCache(); + const was = process.env.ARCHILYZER_LOCAL_ONLY; + process.env.ARCHILYZER_LOCAL_ONLY = "1"; + try { + await withOllamaStub(["qwen2.5:7b"], async (localUrl) => { + const pool = new WorkerPool(); + // The far one first: it must be skipped, and asked nothing (no server + // listens at that name — a request would fail the other way). + pool.reconfigure([llmWorker("far", "http://gpu-box.lan:11434", 0), llmWorker("here", localUrl, 1)], { applyEnabled: true }); + const logs: string[] = []; + const slot = await acquireLlmSlot("digest", "qwen2.5:7b", (m) => logs.push(m), pool); + assert.equal(slot?.workerId, "here"); + slot!.lease.release(); + assert.match(logs.join("\n"), /LLM worker far at gpu-box\.lan is not on this machine .* — degraded for this run/); + }); + } finally { + if (was === undefined) delete process.env.ARCHILYZER_LOCAL_ONLY; + else process.env.ARCHILYZER_LOCAL_ONLY = was; + } +}); diff --git a/common/controller/llmWorkers.ts b/common/controller/llmWorkers.ts @@ -17,6 +17,7 @@ // dispatcher's limit() is the pool's freeSlots. import { getWorkerPool, type Lease, type WorkerPool } from "../jobs/workerPool"; +import { localOnlyEndpointRefusal } from "../lib/llm/localOnly"; export type LlmSlot = { lease: Lease; @@ -89,6 +90,15 @@ export async function acquireLlmSlot( lease.release(); continue; } + // LOCAL ONLY (lib/llm/localOnly.ts): an endpoint not on this machine is + // never asked anything — not even /api/tags. + const notLocal = localOnlyEndpointRefusal(baseUrl, `LLM worker ${workerId}`); + if (notLocal) { + log(`${notLocal} — degraded for this run`); + pool.markDegraded(workerId); + lease.release(); + continue; + } const hit = verified.get(workerId); const fresh = hit && hit.model === model && Date.now() - hit.at < VERIFY_TTL_MS; diff --git a/common/controller/lookoutRun.ts b/common/controller/lookoutRun.ts @@ -105,7 +105,7 @@ 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): every local model's run's floor (reportDraft.ts). */ +/** The job does not start with less MemAvailable than this (MiB) — it refuses; the report-draft floor (reportDraft.ts) is the same number but waits. LOCAL_MODEL_MIN_FREE_MB moves only that one. */ 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; diff --git a/common/controller/reportDraft.ts b/common/controller/reportDraft.ts @@ -561,8 +561,11 @@ export function localOnlyRefusalOf(body: ReportDraftBody, gen: GenerationSetting ); } -/** A `draft:local` job does not start with less MemAvailable than this (MiB); the lookout run's floor is this one. */ +/** A `draft:local` report-draft job waits for this much MemAvailable (MiB) before it starts; a lookout run refuses below the same number. */ export const LOCAL_DRAFT_MIN_FREE_MB = 3072; +/** How often a job under the floor reads MemAvailable again, and how long it waits in all before it fails. */ +export const LOCAL_DRAFT_MEMORY_POLL_MS = 15_000; +export const LOCAL_DRAFT_MEMORY_WAIT_MS = 10 * 60_000; /** 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 { @@ -616,6 +619,8 @@ export type ReportDraftDeps = { // MemAvailable in MiB, or null when unknown (default: /proc/meminfo) — the // local-model floor (LOCAL_DRAFT_MIN_FREE_MB). memAvailableMb?: () => Promise<number | null>; + // The floor's wait (default LOCAL_DRAFT_MEMORY_POLL_MS / _WAIT_MS; tests shorten them). + memoryWait?: { pollMs?: number; maxWaitMs?: number }; // 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. @@ -882,13 +887,41 @@ async function runReportDraft( 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. + // beside a machine already short of memory is what OOM-killed ollama in + // D0. Under it the job WAITS — MemAvailable read again every pollMs, one + // log line when it starts waiting and one when it goes on — and fails with + // the sentence only after maxWaitMs. A cancel ends the wait at once. const floor = localDraftFloorMb(); - const mb = floor > 0 ? await (deps.memAvailableMb ?? readMemAvailableMb)() : null; + const readMb = deps.memAvailableMb ?? readMemAvailableMb; + const { pollMs = LOCAL_DRAFT_MEMORY_POLL_MS, maxWaitMs = LOCAL_DRAFT_MEMORY_WAIT_MS } = deps.memoryWait ?? {}; + let mb = floor > 0 ? await readMb() : 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); + const started = Date.now(); + const minutes = maxWaitMs >= 60_000 ? `${Math.round(maxWaitMs / 60_000)} min` : `${Math.round(maxWaitMs / 1000)} s`; + onLog(`waiting for memory — ${mb} MB available, the floor is ${floor} MB (LOCAL_MODEL_MIN_FREE_MB); waits up to ${minutes}`); + o.setProgress?.({ metric: "MB free", initial: 0, target: floor, current: mb }); + while (mb !== null && mb < floor) { + if (Date.now() - started >= maxWaitMs) { + const refusal = `refused: ${mb} MB available is under the ${floor} MB a local model's run starts with, after waiting ${minutes} — 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); + } + await new Promise<void>((resolve, reject) => { + if (signal.aborted) return reject(new Error("cancelled while waiting for memory")); + const onAbort = () => { + clearTimeout(t); + reject(new Error("cancelled while waiting for memory")); + }; + const t = setTimeout(() => { + signal.removeEventListener("abort", onAbort); + resolve(); + }, pollMs); + signal.addEventListener("abort", onAbort, { once: true }); + }); + mb = await readMb(); + if (mb !== null) o.setProgress?.({ metric: "MB free", initial: 0, target: floor, current: Math.min(mb, floor) }); + } + onLog(`memory: ${mb ?? "unknown"} MB available — going on`); } } if (provider === "api") { diff --git a/common/lib/digestApps.ts b/common/lib/digestApps.ts @@ -28,7 +28,8 @@ import { type DigestLane, } from "./digest"; import "./childKillGuard"; -import { assertLocalOnlyAllowsClaudeCli, assertLocalOnlyAllowsOllamaModel, isLocalOnly } from "./llm/localOnly"; +import { assertLocalOnlyAllowsClaudeCli, isLocalOnly, localOnlyEndpointRefusal } from "./llm/localOnly"; +import { assertLocalOllama } from "./llm/ollama"; // 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 @@ -158,6 +159,8 @@ const ollamaDirect: DigestApp = { async probe(config) { const base = ollamaBase(config); if (!base) return false; + // LOCAL ONLY: a server not on this machine is not asked anything. + if (localOnlyEndpointRefusal(base, "the digest's ollama")) return false; try { const res = await fetch(`${base}/api/tags`, { signal: AbortSignal.timeout(3000), @@ -171,8 +174,10 @@ 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); + // LOCAL ONLY: a server not on this machine (an LLM worker's included: its + // baseUrl arrives here) or an ollama cloud model is refused before the + // request (llm/ollama.ts assertLocalOllama). + await assertLocalOllama(base, model); const numCtx = resolveNumCtx(config); const startedAt = Date.now(); diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts @@ -136,8 +136,9 @@ 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: "ARCHILYZER_LOCAL_ONLY", audience: "runtime", default: "off", readBy: "common/lib/llm/localOnly.ts (the Claude API client, the ollama clients, the digest's lanes, LLM workers, the report-draft and frame-scan dispatch, the settings writers, the report imports, `archilyzer gen`), docker/entrypoint.sh", doc: "LOCAL ONLY (demo epic D5). With ARCHILYZER_LOCAL_ONLY=1, this instance refuses — before any request is sent or any process started — every call to the Claude API, every Claude Code answer (a task routed to `code`, or `answers` posted by a session), the digest's `claude` CLI lane, and every call to an ollama model that is a cloud model (a `-cloud` tag, or one whose /api/show names a remote host) or that is served from anywhere but this machine (a loopback address) or a host named in ARCHILYZER_LOCAL_MODEL_HOSTS. It does not cover the web pages a local model may read (its web_search and fetch tools), the published site's in-browser Ask, or remote transcription workers, which are not language models. Settings writes that would route a task off `local` or name a model server elsewhere are refused too, and `reports import-sweep` / `import-local-runs` are. `1`, `true`, `yes`, `on` (trimmed, any case) turn it on; `0`, `false`, `no`, `off` or unset leave it off; anything else is not understood — off, and the editor's boot log says so as an ERROR. `archilyzer gen local-check` checks it afterwards. umtool makes no model call itself (it asks the editor). The demo overlay (docker-compose.demo.yml) sets it; unset, nothing changes." }, + { name: "ARCHILYZER_LOCAL_MODEL_HOSTS", audience: "runtime", default: "none", readBy: "common/lib/llm/localOnly.ts", doc: "Under ARCHILYZER_LOCAL_ONLY: the host names besides loopback (127.0.0.0/8, ::1, localhost) a local model may be served from — comma-separated, exact, case-insensitive. docker-compose.demo.yml sets `ollama`, the compose service on the stack's own network. Without the flag it means nothing." }, + { 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 WAITS for at its turn (demo epic D5): under it the job logs `waiting for memory — N MB available, the floor is F MB`, reads MemAvailable again every 15 s, and fails with a sentence only after 10 minutes; a cancel ends the wait. `0` turns it off. A lookout run refuses (it does not wait) below its own fixed 3072 MB, which this variable does not move." }, { 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/llm/localOnly.test.ts b/common/lib/llm/localOnly.test.ts @@ -13,10 +13,16 @@ import { LocalOnlyError, Meter, isCloudOllamaModel, + isLocalModelUrl, isLocalOnly, + localOnlyFlag, localOnlyJobRefusal, localOnlyRoutesRefusal, + localOnlySettingsRefusal, + LOCAL_ONLY_CLAIM, ollamaChat, + resetLocalOllamaChecks, + unloadOllama, providerOf, runAgent, structuredAnswer, @@ -41,13 +47,38 @@ async function withFlag<T>(value: string | undefined, body: () => Promise<T>): P // 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() { +// `/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<string, unknown> | number = { details: { family: "qwen2" } }) { const calls: string[] = []; + const shows: string[] = []; const f = (async (url: string | URL | Request) => { - calls.push(String(url)); + 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 }; + return { f, calls, shows }; +} + +async function withEnv<T>(vars: Record<string, string | undefined>, body: () => Promise<T>): Promise<T> { + const was: Record<string, string | undefined> = {}; + 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 () => {} }); @@ -86,21 +117,87 @@ test("structuredAnswer, plainAnswer and runAgent on a Claude model: refused, the 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://ollama.invalid", fetch: f }; + const cfg = { baseUrl: "http://127.0.0.1:11434", 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/); + 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, { model: "qwen2.5:7b", messages: [{ role: "user", content: "hi" }] }), /ollama returned 500/); + 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, { model: "gpt-oss:120b-cloud", messages: [{ role: "user", content: "hi" }] }), /ollama returned 500/); + 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<string, unknown>, digest: Record<string, unknown> = {}) => ({ 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 { @@ -128,7 +225,10 @@ test("the digest's lanes: the claude CLI is never started; an ollama cloud model 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); + 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; @@ -155,3 +255,9 @@ test("a settings write: any route but local refused under the flag, nothing refu 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 as { name: string; doc: string }[]).find((v) => v.name === "ARCHILYZER_LOCAL_ONLY"); + assert.ok(row?.doc.includes(LOCAL_ONLY_CLAIM), "ENVIRONMENT.md states the claim word for word"); +}); diff --git a/common/lib/llm/localOnly.ts b/common/lib/llm/localOnly.ts @@ -1,15 +1,32 @@ -// 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. +// LOCAL ONLY (demo epic D5). THE CLAIM, exactly as enforced (the docs quote +// LOCAL_ONLY_CLAIM): // -// 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. +// With ARCHILYZER_LOCAL_ONLY=1, this instance refuses — before any request +// is sent or any process started — every call to the Claude API, every +// Claude Code answer (a task routed to `code`, or `answers` posted by a +// session), the digest's `claude` CLI lane, and every call to an ollama +// model that is a cloud model (a `-cloud` tag, or one whose /api/show names +// a remote host) or that is served from anywhere but this machine (a +// loopback address) or a host named in ARCHILYZER_LOCAL_MODEL_HOSTS. It does +// not cover the web pages a local model may read (its web_search and fetch +// tools), the published site's in-browser Ask, or remote transcription +// workers, which are not language models. +// +// It FAILS CLOSED: each path asks `assertLocalOnly…` at the last point before +// its I/O, so a route, a preset, a URL or a model named by hand cannot get +// past it; the dispatchers and the settings writers ask too, earlier, only so +// that a job or a write is refused with a sentence. +// +// "Local" is a HOST: 127.0.0.0/8, ::1, `localhost`, or a name in +// ARCHILYZER_LOCAL_MODEL_HOSTS (comma-separated, exact, case-insensitive) — +// set by docker-compose.demo.yml to `ollama`, the compose service on the +// stack's own network. Nothing else. +// +// Unset, every function here is a no-op and every caller behaves exactly as +// before the flag existed. The flag's values are parsed by `localOnlyFlag` +// alone (docker/entrypoint.sh mirrors it): 1/true/yes/on (trimmed, any case) +// is on, 0/false/no/off or unset is off, anything else is NOT UNDERSTOOD — +// off, and said so at boot and by `gen local-check`. // // Pure, browser-safe: no node:* import (it reads the environment it is given, // process.env by default). @@ -18,17 +35,87 @@ type Env = Record<string, string | undefined>; const envOf = (env?: Env): Env => env ?? (typeof process !== "undefined" ? process.env : {}); +export const LOCAL_ONLY_CLAIM = + "With ARCHILYZER_LOCAL_ONLY=1, this instance refuses — before any request is sent or any process started — every call to the Claude API, every Claude Code answer (a task routed to `code`, or `answers` posted by a session), the digest's `claude` CLI lane, and every call to an ollama model that is a cloud model (a `-cloud` tag, or one whose /api/show names a remote host) or that is served from anywhere but this machine (a loopback address) or a host named in ARCHILYZER_LOCAL_MODEL_HOSTS. It does not cover the web pages a local model may read (its web_search and fetch tools), the published site's in-browser Ask, or remote transcription workers, which are not language models."; + +/** How ARCHILYZER_LOCAL_ONLY reads: on, off, or a value that is not understood (off). */ +export function localOnlyFlag(env?: Env): { on: boolean; raw: string; understood: boolean } { + const raw = envOf(env).ARCHILYZER_LOCAL_ONLY ?? ""; + const v = raw.trim().toLowerCase(); + if (v === "1" || v === "true" || v === "yes" || v === "on") return { on: true, raw, understood: true }; + if (v === "" || v === "0" || v === "false" || v === "no" || v === "off") return { on: false, raw, understood: true }; + return { on: false, raw, understood: false }; +} + /** 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"; + return localOnlyFlag(env).on; } export const LOCAL_ONLY_WHY = "this instance is local only (ARCHILYZER_LOCAL_ONLY=1)"; +const LOOPBACK_NAMES = new Set(["localhost", "::1", "[::1]"]); + +/** The hosts besides loopback a local model may be served from (ARCHILYZER_LOCAL_MODEL_HOSTS). */ +export function localModelHosts(env?: Env): string[] { + return (envOf(env).ARCHILYZER_LOCAL_MODEL_HOSTS ?? "") + .split(",") + .map((h) => h.trim().toLowerCase()) + .filter(Boolean); +} + +/** The host of a model server's URL, lowercased, or null when it does not parse as http(s). */ +export function modelHostOf(url: string): string | null { + try { + const u = new URL(url.trim()); + if (u.protocol !== "http:" && u.protocol !== "https:") return null; + return u.hostname.toLowerCase(); + } catch { + return null; + } +} + +/** Whether a model server's URL is on this machine: loopback, or a host in ARCHILYZER_LOCAL_MODEL_HOSTS. */ +export function isLocalModelUrl(url: string, env?: Env): boolean { + const host = modelHostOf(url); + if (!host) return false; + if (LOOPBACK_NAMES.has(host) || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(host)) return true; + return localModelHosts(env).includes(host); +} + +/** + * The refusal for a model server URL on a local-only instance, or null. `what` + * names it ("the local route's ollama", "LLM worker w1"). + */ +export function localOnlyEndpointRefusal(url: string, what: string, env?: Env): string | null { + if (!isLocalOnly(env)) return null; + if (isLocalModelUrl(url, env)) return null; + const host = modelHostOf(url) ?? "an unreadable URL"; + return `${LOCAL_ONLY_WHY}: ${what} at ${host} is not on this machine (a loopback address, or a host in ARCHILYZER_LOCAL_MODEL_HOSTS)`; +} + +/** Throws before a model server that is not on this machine is asked anything. */ +export function assertLocalOnlyAllowsEndpoint(url: string, what: string, env?: Env): void { + const r = localOnlyEndpointRefusal(url, what, env); + if (r) throw new LocalOnlyError(r); +} + +/** + * Whether an ollama /api/show answer says the model runs elsewhere: a + * `remote_host` or `remote_model` (ollama's cloud models), at the top level or + * under `details`. (Field names as ollama documents its cloud models; checked + * against 0.40.5 only at the real up.) + */ +export function showNamesRemote(show: unknown): boolean { + const o = show && typeof show === "object" ? (show as Record<string, unknown>) : {}; + const d = o.details && typeof o.details === "object" ? (o.details as Record<string, unknown>) : {}; + const set = (v: unknown) => typeof v === "string" && v.trim() !== ""; + return set(o.remote_host) || set(o.remote_model) || set(d.remote_host) || set(d.remote_model); +} + export class LocalOnlyError extends Error { constructor(what: string) { - super(`${LOCAL_ONLY_WHY}: ${what} is refused`); + super(what.startsWith(LOCAL_ONLY_WHY) ? what : `${LOCAL_ONLY_WHY}: ${what} is refused`); this.name = "LocalOnlyError"; } } @@ -89,3 +176,40 @@ export function localOnlyRoutesRefusal(routes: Record<string, unknown> | 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; } + +const isObj = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null && !Array.isArray(v); + +/** + * The refusal for a settings write on a local-only instance, or null — what + * the ops route and the editor's settings writer both ask: a patch that + * routes a generation task anywhere but `local`, or names a model server not + * on this machine (settings.generation.ollamaUrl, a digest engine's + * baseUrl). Only what the patch TOUCHES is judged, against `merged` (the + * settings as they would be saved); a blank URL means OLLAMA_URL, judged at + * call time. + */ +export function localOnlySettingsRefusal(patch: Record<string, unknown>, merged: Record<string, unknown>, env?: Env): string | null { + if (!isLocalOnly(env)) return null; + const gen = isObj(merged.generation) ? merged.generation : {}; + const pg = patch.generation; + if (isObj(pg)) { + if (Object.hasOwn(pg, "routes")) { + const r = localOnlyRoutesRefusal(isObj(gen.routes) ? gen.routes : null, env); + if (r) return r; + } + if (Object.hasOwn(pg, "ollamaUrl") && typeof gen.ollamaUrl === "string" && gen.ollamaUrl.trim()) { + const r = localOnlyEndpointRefusal(gen.ollamaUrl, "the local route's model server (generation.ollamaUrl)", env); + if (r) return `${r} — not saved`; + } + } + if (isObj(patch.digest)) { + const apps = isObj(merged.digest) && isObj(merged.digest.apps) ? merged.digest.apps : {}; + for (const [id, cfg] of Object.entries(apps)) { + const url = isObj(cfg) && typeof cfg.baseUrl === "string" ? cfg.baseUrl.trim() : ""; + if (!url) continue; + const r = localOnlyEndpointRefusal(url, `the digest engine ${id} (digest.apps.${id}.baseUrl)`, env); + if (r) return `${r} — not saved`; + } + } + return null; +} diff --git a/common/lib/llm/ollama.ts b/common/lib/llm/ollama.ts @@ -9,7 +9,7 @@ // 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"; +import { LOCAL_ONLY_WHY, LocalOnlyError, assertLocalOnlyAllowsEndpoint, assertLocalOnlyAllowsOllamaModel, isLocalOnly, showNamesRemote } from "./localOnly"; export type OllamaConfig = { baseUrl: string; @@ -109,6 +109,49 @@ export class PromptTooLargeError extends OllamaError { const base = (cfg: OllamaConfig) => cfg.baseUrl.replace(/\/+$/, ""); +// LOCAL ONLY's ollama check (./localOnly.ts), the one every ollama caller +// asks before it sends anything (this module's chat and unload, the digest's +// ollama-direct): a no-op without the flag. With it: the server's host must +// be on this machine, the name must not be a cloud tag, and — once per server +// and model per process, before the first prompt — the server's own +// /api/show must not name a remote host (a cloud model behind a local +// alias). A show that cannot be read refuses: the check fails closed. +const SHOWN_KEY = Symbol.for("archilyzer.localOnly.shown"); +function shownCache(): Map<string, true> { + const g = globalThis as unknown as Record<symbol, Map<string, true> | undefined>; + return (g[SHOWN_KEY] ??= new Map()); +} + +export async function assertLocalOllama(baseUrl: string, model: string, fetchImpl: typeof fetch = fetch, o: { show?: boolean } = {}): Promise<void> { + if (!isLocalOnly()) return; + const b = baseUrl.replace(/\/+$/, ""); + assertLocalOnlyAllowsEndpoint(b, "the ollama server"); + assertLocalOnlyAllowsOllamaModel(model); + if (o.show === false) return; + const key = `${b} ${model}`; + if (shownCache().has(key)) return; + let show: unknown; + try { + const res = await fetchImpl(`${b}/api/show`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ model }), + signal: AbortSignal.timeout(15_000), + }); + if (!res.ok) throw new Error(`/api/show answered ${res.status}`); + show = await res.json(); + } catch (e) { + throw new LocalOnlyError(`${LOCAL_ONLY_WHY}: could not confirm that "${model}" runs on this machine (${(e as Error).message}) — refused`); + } + if (showNamesRemote(show)) throw new LocalOnlyError(`${LOCAL_ONLY_WHY}: "${model}" is served from a remote host (its /api/show says so) — refused`); + shownCache().set(key, true); +} + +/** Forget what /api/show said (tests). */ +export function resetLocalOllamaChecks(): void { + shownCache().clear(); +} + // ollama returns tool-call arguments as an object; some models send a string. function normalizeMessage(m: Partial<OllamaMessage> | undefined): OllamaMessage { const out: OllamaMessage = { ...(m ?? {}), role: m?.role ?? "assistant", content: m?.content ?? "" }; @@ -144,9 +187,10 @@ 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); + // LOCAL ONLY (./localOnly.ts): a model server not on this machine, or an + // ollama cloud model (by name, then by what /api/show says), is refused + // before the request. + await assertLocalOllama(base(cfg), req.model, cfg.fetch ?? fetch); const cap = promptCapOf(cfg); const estimate = promptEstimate(req); if (estimate > cap) throw new PromptTooLargeError(estimate, cap); @@ -203,6 +247,8 @@ export async function ollamaChat( // Frees the card: `keep_alive: 0` with nothing to answer. export async function unloadOllama(cfg: OllamaConfig, model: string): Promise<void> { + // LOCAL ONLY: nothing is sent to a server that is not on this machine. + await assertLocalOllama(base(cfg), model, cfg.fetch ?? fetch, { show: false }); const res = await (cfg.fetch ?? fetch)(`${base(cfg)}/api/generate`, { method: "POST", headers: { "content-type": "application/json" }, diff --git a/common/lib/workers.test.ts b/common/lib/workers.test.ts @@ -126,3 +126,18 @@ test("unknownWorkerTags names only tags outside the vocabulary", () => { assert.deepEqual(unknownWorkerTags(workers, known), ["diarizatoin"]); assert.deepEqual(unknownWorkerTags(workers, [...known, "diarizatoin"]), []); }); + +test("local only (demo epic D5): an enabled LLM worker not on this machine is not saved; loopback and a disabled one are", () => { + const was = process.env.ARCHILYZER_LOCAL_ONLY; + process.env.ARCHILYZER_LOCAL_ONLY = "1"; + try { + const t = { id: "t", name: "t", kind: "local" as const, enabled: true, priority: 0, appId: "whisper-cpp", config: {} }; + const llm = (baseUrl: string, enabled = true) => ({ id: "l", name: "box", kind: "llm" as const, enabled, priority: 1, llm: { baseUrl } }); + assert.match(validateWorkers([t, llm("http://gpu-box.lan:11434")] as never)!, /LLM worker "box" at gpu-box\.lan is not on this machine .* — not saved/); + assert.equal(validateWorkers([t, llm("http://127.0.0.1:11434")] as never), null); + assert.equal(validateWorkers([t, llm("http://gpu-box.lan:11434", false)] as never), null); + } finally { + if (was === undefined) delete process.env.ARCHILYZER_LOCAL_ONLY; + else process.env.ARCHILYZER_LOCAL_ONLY = was; + } +}); diff --git a/common/lib/workers.ts b/common/lib/workers.ts @@ -20,6 +20,7 @@ import { validateTranscribeArgs, } from "./transcriptionApps"; import type { FieldDocs } from "./fieldDocs"; +import { localOnlyEndpointRefusal } from "./llm/localOnly"; export type WorkerKind = "local" | "remote" | "llm"; @@ -342,6 +343,10 @@ export function validateWorkers(workers: Worker[]): string | null { } catch { return `LLM worker "${label}" has an invalid base URL`; } + // LOCAL ONLY (lib/llm/localOnly.ts): an enabled endpoint must be on + // this machine (a disabled one is never asked). + const notLocal = w.enabled ? localOnlyEndpointRefusal(url, `LLM worker "${label}"`) : null; + if (notLocal) return `${notLocal} — not saved`; continue; } if (w.kind === "local") { diff --git a/common/testing/llm/fakeOllama.d.mts b/common/testing/llm/fakeOllama.d.mts @@ -21,6 +21,8 @@ export type FakeOllama = { url: string; requests: any[]; unloads: string[]; + // Every model /api/show was asked about (local only's check), in order. + shows: string[]; loaded(): string[]; push(...turns: OllamaScripted[]): void; remaining(): number; @@ -31,6 +33,8 @@ export function startFakeOllama(opts?: { promptCapTokens?: number; numCtxCap?: number; turns?: OllamaScripted[]; + // Models /api/show answers as ollama's cloud models (a remote_host). + remote?: string[]; }): Promise<FakeOllama>; export const IMAGE_TOKENS: number; export function imagesOf(body: any): { bytes: Buffer; width: number; height: number }[]; diff --git a/common/testing/llm/fakeOllama.mjs b/common/testing/llm/fakeOllama.mjs @@ -92,6 +92,7 @@ export async function startFakeOllama(opts = {}) { const script = [...(opts.turns ?? [])]; const requests = []; const unloads = []; + const shows = []; const loaded = new Set(); const send = (res, status, payload) => { @@ -107,6 +108,21 @@ export async function startFakeOllama(opts = {}) { return send(res, 200, { models: models.map((name) => ({ name, model: name })) }); if (req.method === "GET" && req.url === "/api/ps") return send(res, 200, { models: [...loaded].map((name) => ({ name, model: name })) }); + // /api/show (what local only asks before a model's first prompt): a + // model in `opts.remote` answers as ollama's cloud models do, with a + // remote_host. Asked, never counted in `requests`. + if (req.method === "POST" && req.url === "/api/show") { + let name = ""; + try { + name = JSON.parse(raw).model ?? ""; + } catch { + // falls through to not found + } + shows.push(name); + if (!models.includes(name)) return send(res, 404, { error: `model "${name}" not found` }); + const remote = (opts.remote ?? []).includes(name); + return send(res, 200, { details: { format: "gguf", family: "qwen2" }, ...(remote ? { remote_host: "https://ollama.com:443", remote_model: name } : {}) }); + } if (req.method !== "POST" || (req.url !== "/api/chat" && req.url !== "/api/generate")) return send(res, 404, { error: `fake: no route ${req.method} ${req.url}` }); let body; @@ -159,6 +175,7 @@ export async function startFakeOllama(opts = {}) { url: `http://127.0.0.1:${port}`, requests, unloads, + shows, loaded: () => [...loaded], push: (...turns) => script.push(...turns), remaining: () => script.length, diff --git a/docker-compose.demo.yml b/docker-compose.demo.yml @@ -7,11 +7,16 @@ # # What it changes, and nothing else: # -# * The editor and umtool run LOCAL ONLY (ARCHILYZER_LOCAL_ONLY=1, -# common/lib/llm/localOnly.ts): the Claude API, a Claude Code session's -# answers, the digest's `claude` lane and an ollama cloud model are refused -# before any request. The anthropic overlay is never part of this stack, so -# there is no API key in it either. `archilyzer gen local-check` proves it. +# * The editor runs LOCAL ONLY (ARCHILYZER_LOCAL_ONLY=1, +# common/lib/llm/localOnly.ts LOCAL_ONLY_CLAIM): it refuses, before any +# request or process, the Claude API, Claude Code answers, the digest's +# `claude` lane, ollama cloud models, and every model server that is not +# loopback or `ollama` — the compose service, the one name +# ARCHILYZER_LOCAL_MODEL_HOSTS allows. umtool makes no model call itself +# (it asks the editor); it carries the same variables only so nothing it +# starts could differ. The anthropic overlay is never part of this stack, +# so there is no API key in it either. `archilyzer gen local-check` checks +# it afterwards. # * The published archive DEMO_ARCHIVE is the connected source # (TRANSCRIPT_SITE_URL: offered by umtool's Source chip and the editor with # nothing written; a sweep over it cites it). @@ -20,12 +25,17 @@ # prompt cache and a memory limit with no swap beyond it. # # Nothing here publishes a port or changes a bind: Caddy stays the only front -# door, on 127.0.0.1, and the exposure guard is unchanged. +# door, on 127.0.0.1 (demo.sh exports 127.0.0.1 for every *_BIND and refuses +# any other), and the exposure guard judges the binds compose publishes on +# (docker-compose.yml hands caddy the same interpolated values). services: editor: environment: ARCHILYZER_LOCAL_ONLY: "1" + # "Local" is loopback, or this — the compose ollama service's name on the + # stack's own network. Nothing else a model is asked from is allowed. + ARCHILYZER_LOCAL_MODEL_HOSTS: ollama TRANSCRIPT_SITE_URL: ${DEMO_ARCHIVE:-https://jeralyzer.pages.dev} WORKER_TOKEN: ${WORKER_TOKEN:-} OLLAMA_URL: http://ollama:11434 @@ -36,6 +46,7 @@ services: umtool: environment: ARCHILYZER_LOCAL_ONLY: "1" + ARCHILYZER_LOCAL_MODEL_HOSTS: ollama TRANSCRIPT_SITE_URL: ${DEMO_ARCHIVE:-https://jeralyzer.pages.dev} WORKER_TOKEN: ${WORKER_TOKEN:-} OLLAMA_URL: http://ollama:11434 diff --git a/docker-compose.yml b/docker-compose.yml @@ -110,6 +110,15 @@ services: # Runs the same exposure rail the app entrypoint does — this is the process # that actually opens the ports, so it refuses first. entrypoint: ["/bin/sh", "/etc/archilyzer/caddy-start.sh"] + # The binds the rail judges are the binds `ports:` below publishes on: the + # same interpolation, not the .env file's line (compose prefers a shell + # variable, or --env-file's, over .env, so the two could differ — and a + # port published on 0.0.0.0 would go unseen by the rail). + environment: + SITE_BIND: ${SITE_BIND:-127.0.0.1} + EDITOR_BIND: ${EDITOR_BIND:-127.0.0.1} + HOMEPAGE_BIND: ${HOMEPAGE_BIND:-127.0.0.1} + UMTOOL_BIND: ${UMTOOL_BIND:-127.0.0.1} ports: # published-bind : published-port : caddy-port - "${SITE_BIND:-127.0.0.1}:${SITE_HTTP_PORT:-8080}:8080" diff --git a/docker/demo.sh b/docker/demo.sh @@ -29,7 +29,12 @@ # POSIX sh: no bashisms (dash, busybox). set -eu -cd "$(dirname "$0")/.." +# The checkout's root, with no external tool (a PATH with no coreutils must +# still reach the "docker is not installed" sentence). +case "$0" in +*/*) cd "${0%/*}/.." ;; +*) cd .. ;; +esac PROJECT="archilyzer-demo" ENV_FILE="${DEMO_ENV_FILE:-.env.demo}" @@ -71,6 +76,8 @@ up | down | status | check | voice) ;; ;; *) refuse "unknown command \"${VERB}\" — one of: up, down, status, check, voice." ;; esac +# Every verb needs docker; say so before anything else is looked at. +command -v docker >/dev/null 2>&1 || refuse "docker is not installed — install Docker Engine (or Docker Desktop) and run this again." ARCHIVE="" MODEL="" @@ -118,7 +125,70 @@ env_get() { sed -n "s/^$1=//p" "${ENV_FILE}" | tail -n 1 } +# The binds the base compose publishes Caddy's ports on. The demo publishes on +# 127.0.0.1 only: a different one in .env.demo or in this shell is refused (no +# flag turns that off), and demo.sh exports 127.0.0.1 for each before compose +# runs — so the value compose interpolates is the one the exposure guard (in +# the caddy container, docker-compose.yml passes it the same value) judges. +BIND_VARS="SITE_BIND EDITOR_BIND HOMEPAGE_BIND UMTOOL_BIND" + +# Every line of .env.demo is checked BEFORE compose reads it (compose fills +# ${…} in the compose files from it): a comment, or KEY=value for a key +# demo.sh writes, its value from the same strict class as when it is written. +# Anything else — another key, a bind off loopback, a value with a space, a +# quote, a `$` or a control character — is refused in one sentence. +ENV_KEYS="WORKER_TOKEN DEMO_ARCHIVE DEMO_MODEL DEMO_GPU_ASKED DEMO_OLLAMA_MEM ARCHILYZER_TAG EDITOR_HTTP_PORT UMTOOL_HTTP_PORT SITE_HTTP_PORT HOMEPAGE_HTTP_PORT" + +# Whether $1 holds only the characters of class $2 (and is not empty). +only_chars() { + [ -n "$1" ] || return 1 + case "$1" in + *[!$2]*) return 1 ;; + esac + return 0 +} + +URL_CHARS='A-Za-z0-9._~:/?=&%+@,-' + +check_env_file() { + [ -f "${ENV_FILE}" ] || return 0 + n=0 + while IFS= read -r line || [ -n "${line}" ]; do + n=$((n + 1)) + case "${line}" in + '' | '#'*) continue ;; + esac + key="${line%%=*}" + [ "${key}" != "${line}" ] || refuse "line ${n} of ${ENV_FILE} is not KEY=value — remove it, or delete ${ENV_FILE} to start again." + value="${line#*=}" + case " ${BIND_VARS} " in + *" ${key} "*) + [ "${value}" = "127.0.0.1" ] || refuse "${ENV_FILE} sets ${key} to something other than 127.0.0.1, which would publish a port beyond this machine — the demo binds 127.0.0.1 only; remove that line." + continue + ;; + esac + case " ${ENV_KEYS} " in + *" ${key} "*) ;; + *) refuse "line ${n} of ${ENV_FILE} sets a key demo.sh does not write — remove it, or delete ${ENV_FILE} to start again." ;; + esac + only_chars "${value}" "${URL_CHARS}" || refuse "line ${n} of ${ENV_FILE} (${key}) holds a character no demo value has (a space, a quote, \$, # or a control character) — fix it, or delete ${ENV_FILE} to start again." + done <"${ENV_FILE}" +} + +check_shell_binds() { + for b in ${BIND_VARS}; do + eval "v=\${${b}:-}" + [ -z "${v}" ] || [ "${v}" = "127.0.0.1" ] || refuse "${b} is set in this shell to something other than 127.0.0.1, which would publish a port beyond this machine — unset it; the demo binds 127.0.0.1 only." + done +} + +check_env_file +check_shell_binds + prev_token="$(env_get WORKER_TOKEN)" +if [ -n "${prev_token}" ]; then + only_chars "${prev_token}" 'A-Za-z0-9_-' || refuse "WORKER_TOKEN in ${ENV_FILE} is not a token (letters, digits, - and _) — delete that line and a new one is made." +fi [ -n "${ARCHIVE}" ] || ARCHIVE="$(env_get DEMO_ARCHIVE)" [ -n "${ARCHIVE}" ] || ARCHIVE="${DEFAULT_ARCHIVE}" [ -n "${MODEL}" ] || MODEL="$(env_get DEMO_MODEL)" @@ -134,33 +204,54 @@ prev_token="$(env_get WORKER_TOKEN)" [ -n "${HOMEPAGE_PORT}" ] || HOMEPAGE_PORT="$(env_get HOMEPAGE_HTTP_PORT)" [ -n "${HOMEPAGE_PORT}" ] || HOMEPAGE_PORT=8082 +# Every value that is written to .env.demo is checked here, by character +# class, with nothing but the shell: a value that fails is refused WITHOUT +# echoing it (it may hold a newline). A newline, a space, a quote, `$`, a +# backtick or `#` is in no class, so a value can never carry a second line. case "${ARCHIVE}" in http://* | https://*) ;; -*) refuse "--archive is an http(s) URL (got \"${ARCHIVE}\")." ;; +*) refuse "--archive is not an http(s) URL." ;; esac +only_chars "${ARCHIVE}" "${URL_CHARS}" || refuse "--archive is not a single-line http(s) URL of URL characters (letters, digits and - . _ ~ : / ? = & % + @ ,)." +[ "${#ARCHIVE}" -le 300 ] || refuse "--archive is longer than 300 characters." ARCHIVE="${ARCHIVE%/}" ARCHIVE="${ARCHIVE%/corpus.json}" case "${MODEL}" in -*-cloud | *:cloud) refuse "--model ${MODEL} is an ollama CLOUD model — the demo runs local models only." ;; -claude*) refuse "--model ${MODEL} is a Claude model — the demo runs local models only." ;; +*-cloud | *:cloud) refuse "--model is an ollama CLOUD model — the demo runs local models only." ;; +claude*) refuse "--model is a Claude model — the demo runs local models only." ;; +[!A-Za-z0-9]*) refuse "--model is not a model name (letters, digits and . _ : / -, starting with a letter or digit)." ;; esac -printf '%s' "${MODEL}" | grep -Eq '^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$' || refuse "--model \"${MODEL}\" is not a model name." +only_chars "${MODEL}" 'A-Za-z0-9._:/-' && [ "${#MODEL}" -le 128 ] || refuse "--model is not a model name (letters, digits and . _ : / -, starting with a letter or digit)." case "${GPU}" in auto | vulkan | nvidia | none) ;; -*) refuse "--gpu is auto, vulkan, nvidia or none (got \"${GPU}\")." ;; +*) refuse "--gpu is auto, vulkan, nvidia or none." ;; esac for p in "${EDITOR_PORT}" "${UMTOOL_PORT}" "${SITE_PORT}" "${HOMEPAGE_PORT}"; do - case "$p" in - '' | *[!0-9]*) refuse "a port is a number (got \"$p\")." ;; - esac - [ "$p" -ge 1 ] && [ "$p" -le 65535 ] || refuse "a port is 1 to 65535 (got $p)." + only_chars "$p" '0-9' && [ "${#p}" -le 5 ] || refuse "a port is a number from 1 to 65535." + [ "$p" -ge 1 ] && [ "$p" -le 65535 ] || refuse "a port is a number from 1 to 65535." +done +for v in $(env_get DEMO_OLLAMA_MEM) $(env_get ARCHILYZER_TAG); do + only_chars "${v}" 'A-Za-z0-9' || refuse "${ENV_FILE} holds a DEMO_OLLAMA_MEM or ARCHILYZER_TAG that is not one demo.sh writes — delete ${ENV_FILE} to start again." done +# What compose interpolates is what was checked: the shell's own values (which +# compose prefers to --env-file's) are these. +# (WORKER_TOKEN, DEMO_OLLAMA_MEM and ARCHILYZER_TAG come from .env.demo alone.) +unset WORKER_TOKEN DEMO_OLLAMA_MEM ARCHILYZER_TAG +export DEMO_ARCHIVE="${ARCHIVE}" DEMO_MODEL="${MODEL}" +for b in ${BIND_VARS}; do export "${b}=127.0.0.1"; done +export EDITOR_HTTP_PORT="${EDITOR_PORT}" UMTOOL_HTTP_PORT="${UMTOOL_PORT}" SITE_HTTP_PORT="${SITE_PORT}" HOMEPAGE_HTTP_PORT="${HOMEPAGE_PORT}" + # ─── prerequisites (read-only probes) ─── check_docker() { command -v docker >/dev/null 2>&1 || refuse "docker is not installed — install Docker Engine (or Docker Desktop) and run this again." - docker info >/dev/null 2>&1 || refuse "the docker daemon is not answering — start it (sudo systemctl start docker) and run this again." + if ! info_err="$(docker info 2>&1 >/dev/null)"; then + case "${info_err}" in + *"ermission denied"*) refuse "docker is installed, but this user may not use its socket (permission denied) — add yourself to the docker group (sudo usermod -aG docker \$USER, then log in again) and run this again." ;; + esac + refuse "the docker daemon is not answering — start it (sudo systemctl start docker) and run this again." + fi cv="$(docker compose version --short 2>/dev/null || true)" [ -n "${cv}" ] || refuse "docker compose v2 is missing — install the compose plugin (docker-compose v1 is not enough) and run this again." cv="${cv#v}" @@ -224,6 +315,30 @@ stack_running() { [ -n "$(docker compose -p "${PROJECT}" ps -q caddy 2>/dev/null || true)" ] } +# Any container of the project, running or stopped (what `down` stops). +project_exists() { + [ -n "${DEMO_TEST_STACK_RUNNING:-}" ] && return 0 + [ -n "$(docker compose -p "${PROJECT}" ps -aq 2>/dev/null || true)" ] +} + +# The name ollama lists a model under: a tagless name is `<name>:latest`. +listed_name() { + case "$1" in + *:*) printf '%s' "$1" ;; + *) printf '%s:latest' "$1" ;; + esac +} + +# A pull's size, for the models whose size is known (ollama's library +# listing); nothing for any other. +model_size() { + case "$(listed_name "$1")" in + qwen2.5:7b) printf '4.7 GB' ;; + qwen3:8b) printf '5.2 GB' ;; + llama3.2:3b) printf '2.0 GB' ;; + esac +} + detect_gpu() { case "${GPU}" in vulkan | nvidia | none) @@ -304,6 +419,15 @@ compose() { run compose $(compose_args) "$@" } +# A step of `up` after which the stack may be partly up: on a failure, ONE +# sentence that says what failed and how to stop what started, and exit 1. +must() { + what="$1" + shift + if "$@"; then return 0; fi + refuse "${what} failed — the demo is partly up; ./docker/demo.sh down stops it." +} + # `docker compose exec -T editor pnpm --silent ops <action> --json <json>`: # the JSON is one argument, never split. ops_json() { @@ -371,15 +495,15 @@ wait_editor() { return 0 fi i=0 - while [ "${i}" -lt 48 ]; do + while [ "${i}" -lt "${DEMO_TEST_WAIT_TRIES:-48}" ]; do # shellcheck disable=SC2046 if docker compose $(compose_args) exec -T editor curl -fsS -o /dev/null http://127.0.0.1:3001/api/pulse 2>/dev/null; then return 0 fi i=$((i + 1)) - sleep 5 + sleep "${DEMO_TEST_WAIT_SLEEP:-5}" done - refuse "the editor did not answer within 4 minutes — see: docker compose -p ${PROJECT} logs editor" + refuse "the editor did not answer within 4 minutes (docker compose -p ${PROJECT} logs editor says why) — the demo is partly up; ./docker/demo.sh down stops it." } # ollama's own word on its device: the first `inference compute` line. @@ -412,6 +536,9 @@ ollama_device_line() { # ─── the verbs ─── do_up() { + if [ "${DRY}" = 1 ]; then + say "dry run: only read-only probes — docker version and info, df, /proc/meminfo, /dev/dri, the listening ports, and GET ${HOST_OLLAMA_URL}/api/ps (a host ollama, if one answers); nothing is written, built, pulled or started" + fi check_docker RAM_GB="$(ram_gb)" [ -n "${RAM_GB}" ] || RAM_GB=0 @@ -430,35 +557,37 @@ do_up() { done fi detect_gpu + # Intent, not result: ollama's own line after the start says what it uses. case "${GPU_USED}" in - vulkan) say "GPU: ${GPU_NODE:-${DRI_DIR}} -> ollama on Vulkan" ;; - nvidia) say "GPU: NVIDIA -> ollama on CUDA" ;; - none) say "GPU: none -> ollama on the CPU (about 10x slower)" ;; + vulkan) say "GPU: ${GPU_NODE:-${DRI_DIR}} found -> will ask ollama for Vulkan" ;; + nvidia) say "GPU: NVIDIA found -> will ask ollama for CUDA" ;; + none) say "GPU: none -> ollama will run on the CPU (about 10x slower)" ;; esac check_host_ollama say "archive ${ARCHIVE} · model ${MODEL} · LOCAL ONLY (the Claude API is refused)" write_env if [ "${REBUILD}" = 1 ] || image_missing archilyzer:demo || image_missing archilyzer:demo-umtool; then say "building images (the first run takes about 10 minutes)" - compose build editor umtool + compose build editor umtool || refuse "building the images failed (the build's output is above) — nothing was started; fix it and run ./docker/demo.sh up again." else say "images: archilyzer:demo and archilyzer:demo-umtool present (--rebuild builds them again)" fi say "starting editor, umtool and ollama" - compose up -d + must "starting the stack (docker compose up)" compose up -d wait_editor ollama_device_line + size="$(model_size "${MODEL}")" # shellcheck disable=SC2046 - if [ "${DRY}" = 0 ] && docker compose $(compose_args) exec -T ollama ollama list 2>/dev/null | awk 'NR>1 {print $1}' | grep -qxF "${MODEL}"; then + if [ "${DRY}" = 0 ] && docker compose $(compose_args) exec -T ollama ollama list 2>/dev/null | awk 'NR>1 {print $1}' | grep -qxF "$(listed_name "${MODEL}")"; then say "model ${MODEL}: present" else - if [ "${DRY}" = 1 ]; then say "model ${MODEL}: pulled unless ollama already has it (once; a 7B model is about 4.7 GB)"; else say "pulling ${MODEL} (once; a 7B model is about 4.7 GB)"; fi - compose exec -T ollama ollama pull "${MODEL}" + if [ "${DRY}" = 1 ]; then say "model ${MODEL}: pulled unless ollama already has it (once${size:+, ${size}})"; else say "pulling ${MODEL} (once${size:+, ${size}})"; fi + must "pulling ${MODEL}" compose exec -T ollama ollama pull "${MODEL}" fi say "generation: preset local, model ${MODEL} (every task on the local model)" - compose exec -T editor pnpm --silent archilyzer gen preset local - compose exec -T editor pnpm --silent archilyzer gen model local "${MODEL}" - compose exec -T editor pnpm --silent archilyzer gen model extractor "${MODEL}" + must "setting the local preset (archilyzer gen preset local)" compose exec -T editor pnpm --silent archilyzer gen preset local + must "setting the local model (archilyzer gen model local)" compose exec -T editor pnpm --silent archilyzer gen model local "${MODEL}" + must "setting the extractor model (archilyzer gen model extractor)" compose exec -T editor pnpm --silent archilyzer gen model extractor "${MODEL}" voice_line if [ "${DRY}" = 1 ]; then say "dry run: nothing was written, built, pulled or started" @@ -516,8 +645,10 @@ do_voice() { do_down() { check_docker - if [ ! -f "${ENV_FILE}" ] && [ -z "${DEMO_TEST_STACK_RUNNING:-}" ]; then - say "nothing to stop: no ${ENV_FILE} here (the demo was never started from this checkout)" + # The project is stopped whether or not .env.demo is still here (compose + # needs no env file to take down what it started). + if ! project_exists; then + say "nothing to stop: no ${PROJECT} containers on this machine" return 0 fi GPU_USED=none diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh @@ -268,6 +268,25 @@ ollama_line() { fi } +# ARCHILYZER_LOCAL_ONLY, read exactly as common/lib/llm/localOnly.ts +# `localOnlyFlag` reads it: trimmed, any case; 1/true/yes/on is on, +# empty/0/false/no/off is off, anything else is NOT UNDERSTOOD — the app +# treats it as off, so this says so as an ERROR line rather than nothing. +local_only_line() { + local raw v + raw="${ARCHILYZER_LOCAL_ONLY:-}" + v="$(printf '%s' "${raw}" | sed 's/^[[:space:]]*//; s/[[:space:]]*$//' | tr '[:upper:]' '[:lower:]')" + case "${v}" in + 1 | true | yes | on) + log "models: LOCAL ONLY — the Claude API, Claude Code answers, the claude CLI lane, ollama cloud models and model servers off this machine are refused (ARCHILYZER_LOCAL_ONLY)" + ;; + "" | 0 | false | no | off) ;; + *) + printf '[entrypoint] ERROR: ARCHILYZER_LOCAL_ONLY=%s is not understood — the guard is OFF (1, true, yes or on turns it on)\n' "${raw}" >&2 + ;; + esac +} + # --------------------------------------------------------------------------- # 5. The exposure rail. Shared with the caddy container — one implementation. # --------------------------------------------------------------------------- @@ -312,11 +331,7 @@ editor) log "idle boot: schedulers, auto-queue runners and sweeps stay STOPPED" fi ollama_line - case "${ARCHILYZER_LOCAL_ONLY:-}" in - 1 | true | yes | on) - log "models: LOCAL ONLY — the Claude API, Claude Code answers and ollama cloud models are refused (ARCHILYZER_LOCAL_ONLY)" - ;; - esac + local_only_line cd /repo/editor # Sixteen threads for Node's filesystem pool instead of four. A call on a # drive that has stalled holds its thread until the drive answers; with four, diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,11 +1,11 @@ # Changelog ## [Unreleased] -- **A local-only Archilyzer in one command: `./docker/demo.sh up`.** On a machine with only docker (compose v2.24 or newer), it starts the editor, umtool and a local model server (ollama) in Docker, connects a published archive as a source (https://jeralyzer.pages.dev unless `--archive`), pulls the model (`--model`, default qwen2.5:7b) and routes every AI task to it. Every step is one printed line; `--dry-run` prints every command and changes nothing; a missing prerequisite (docker, compose, the daemon, 12 GB of RAM, 25 GB free, a port) is one sentence and exit 1. The GPU is found by itself (a render node: ollama on Vulkan; NVIDIA; else the CPU, said so), and ollama's own line about the device it uses is printed. A host ollama already holding a model on the GPU is warned about. The choices are kept in `.env.demo` (mode 600) and reused, so a second `up` changes nothing. `down` keeps the volumes unless `--volumes`; `status` shows the stack; `voice` says what Orpheus needs. Nothing is opened off this machine. RUNNING_IN_DOCKER.md, "A local-only demo". -- **Local only, provably: `ARCHILYZER_LOCAL_ONLY=1`.** With it set (the demo sets it), the editor and umtool refuse every model call that would leave the machine before anything is sent: the Claude API, a task routed to Claude Code or a session's answers, the digest's `claude` lane, and an ollama cloud model (a `-cloud` tag). A settings change that routes a task anywhere but the local model is refused. A refused job says so in one sentence. `archilyzer gen local-check` (and `./docker/demo.sh check`) proves it afterwards by counts: the flag on, every route local, no API key present, and no Claude API row in the usage ledger since a date; it exits 1 when any of these fails, and never prints a key. The editor's boot log says `models: LOCAL ONLY`, and gives one line on whether ollama answers. Unset, nothing changes. Needs a restart of the editor and umtool. +- **A local-only Archilyzer in one command: `./docker/demo.sh up`.** On a machine with only docker (compose v2.24 or newer), it starts the editor, umtool and a local model server (ollama) in Docker, connects a published archive as a source (https://jeralyzer.pages.dev unless `--archive`), pulls the model (`--model`, default qwen2.5:7b) and routes every AI task to it. Every step is one printed line; `--dry-run` prints every command and changes nothing; a missing prerequisite (docker, compose, the daemon, 12 GB of RAM, 25 GB free, a port) is one sentence and exit 1. The GPU is found by itself (a render node: ollama on Vulkan; NVIDIA; else the CPU, said so), and ollama's own line about the device it uses is printed. A host ollama already holding a model on the GPU is warned about. The choices are kept in `.env.demo` (mode 600) and reused, so a second `up` changes nothing. A step that fails after the start (the start itself, the editor's first answer, the pull, the settings) ends with one sentence saying the demo is partly up and that `./docker/demo.sh down` stops it. `down` keeps the volumes unless `--volumes`, and stops the stack even when `.env.demo` is gone; `status` shows the stack; `voice` says what Orpheus needs. Nothing is opened off this machine: every value written to `.env.demo` is checked character by character (a newline cannot be smuggled in through `--archive`), a `.env.demo` line it did not write or a bind other than 127.0.0.1 (in the file or the shell) is refused, and the exposure guard is handed the binds compose really publishes on (docker-compose.yml, for every stack). RUNNING_IN_DOCKER.md, "A local-only demo". +- **Local only: `ARCHILYZER_LOCAL_ONLY=1` (the demo sets it).** With ARCHILYZER_LOCAL_ONLY=1, this instance refuses — before any request is sent or any process started — every call to the Claude API, every Claude Code answer (a task routed to `code`, or `answers` posted by a session), the digest's `claude` CLI lane, and every call to an ollama model that is a cloud model (a `-cloud` tag, or one whose /api/show names a remote host) or that is served from anywhere but this machine (a loopback address) or a host named in ARCHILYZER_LOCAL_MODEL_HOSTS. It does not cover the web pages a local model may read (its web_search and fetch tools), the published site's in-browser Ask, or remote transcription workers, which are not language models. A settings change (on the ops route or the editor's own pages) that would route a task off the local model or name a model server elsewhere is refused, an LLM worker elsewhere is not saved and is skipped, and `reports import-sweep` and `import-local-runs` are refused. A refused job or write says so in one sentence; the digest's metered lane says "refused: local only", not "is the claude CLI installed". `archilyzer gen local-check` (and `./docker/demo.sh check`) checks it afterwards by counts and host names: the flag on, every route local, every model server a local route asks on this machine, no API key present, no call off the local route in the usage ledger or the per-call logs since a date, and no imported iteration; it exits 1 when any fails, says NOTHING TO PROVE YET (not PASS) while no call is recorded, and never prints a key or a home path. The editor's boot log says `models: LOCAL ONLY`, says as an ERROR when the flag holds a value it does not understand, and gives one line on whether ollama answers. umtool makes no model call itself. Unset, nothing changes. Needs a restart of the editor. - **`archilyzer gen model api|local|extractor <model>` sets the model a route runs** (settings.generation.models), from a terminal or a container; bare, it shows the three. -- **A report draft on the local model needs 3072 MB of free memory to start.** Under that it is refused at its turn ("1000 MB available is under the 3072 MB a local model's run starts with"), like a lookout run, instead of starting a model on a machine already short of memory. `LOCAL_MODEL_MIN_FREE_MB` changes the floor (0 turns it off). Needs a restart of the editor. -- **umtool: the policy chip names the model that runs.** With no task routed to the Claude API it shows the local model and no API spend, and on a local-only instance it says "local only". Needs a restart of umtool. +- **A report draft on the local model waits for 3072 MB of free memory before it starts.** Under that it waits at its turn, saying "waiting for memory — 1000 MB available, the floor is 3072 MB" in its log, looks again every 15 seconds, and goes on as soon as memory is back; only after 10 minutes does it fail with a sentence. Cancel stops the wait at once. It no longer starts a model on a machine already short of memory. `LOCAL_MODEL_MIN_FREE_MB` changes the floor (0 turns it off); a lookout run keeps its own refusal below 3072 MB. Needs a restart of the editor. +- **umtool: on a local-only editor the policy chip names the local model and says "local only".** It asks the editor; without the flag the chip is as it was. Needs a restart of umtool. - **umtool: a report video can end on an analysis item, built from the ledger.** A new timeline entry, `{type: "analysis"}`, draws a full-frame ending on the deck's fonts and colours. It has a chart of a named run of his weights with a shaded band and marks, a pace table, status rows and one reading line. The line draws in and the rows land; there is no slam, hit or camera move. Every figure comes from a ledger row. A loss ("down 31.5") is placed against the run's start, the same weight a loss goal's base uses. A pace row's pounds and days are computed, never typed. A bound ("under 300") is drawn as a hollow point, and a pace row ending on one says it in words that stay true, "MORE THAN 10.5 lb lost" or "AT MOST 8.5 lb lost". A number typed into the words is a lint warning. The page is measured before it is encoded, and an item that overflows the frame is refused. With `audio`, a clip's sound plays under the item and its citation and QR code are shown, but not its picture. Without audio the item is silent for at most 8 seconds. `umtool lint` names the row behind every refusal. `umtool timeline <p> [--take <t>] add-analysis | set-analysis` writes one into the draft or a take, with an undo point, and `--dry-run` prints every figure with its row. Play the cut draws the item as the build does, but silently. A cut without an analysis item builds exactly as before. - **umtool: a build and a take refuse a picked read that says an anonymous author's handle or name.** `umtool lint` reported it, but the lint a build enforces (and so every take's render) did not, so a recorded "@realguy is lying" rendered with the card anonymised and the audio saying the handle. The enforced lint now carries the same error in the same words; `--no-lint` is still the only override, and a video with no anonymous character lints exactly as before. Also: a video with anonymous characters whose `video.manifest.json` is missing or unreadable is refused rather than read with an empty set; a read collapses a status link to an anonymous author's post; a `--post-take` part takes its words from what the source take said; and the words sent to a model lose an anonymous author's display name, bare handle, `/i/web/status/` links and percent-encoded handles too. - **umtool: anonymity covers the whole project, every link, the podcast and the previews; old reads keep their speed.** Re-checking the anonymous characters found several gaps. An item that named one in another variant, or one dropped by a ruling, `--only`, a window or a take, left the author in clear. The deck's corner QR on an anonymous author's post item still led to the real post. Links were rewritten with the status id kept. The podcast's show notes and the chrome preview, still and onscreen routes had no pass at all. Now: diff --git a/editor/app/api/ops/_reportDraft.test.ts b/editor/app/api/ops/_reportDraft.test.ts @@ -65,12 +65,14 @@ after(async () => { await rm(tmp, { recursive: true, force: true }); }); -const deps = (g: Partial<GenerationSettings> = {}, memAvailableMb: number | null = 8000) => ({ +const deps = (g: Partial<GenerationSettings> = {}, memAvailableMb: number | null | (() => 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, + // The local model's memory floor reads this, not the machine's, and waits + // milliseconds, not minutes. + memAvailableMb: async () => (typeof memAvailableMb === "function" ? memAvailableMb() : memAvailableMb), + memoryWait: { pollMs: 10, maxWaitMs: 300 }, }); // ARCHILYZER_LOCAL_ONLY for one test's body (demo epic D5), restored after. @@ -328,7 +330,7 @@ test("a local sweep (demo epic D3): its calls in the iteration's model log; the 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 () => { +test("the local model's memory floor (demo epic D5): under it the job WAITS, saying so, then fails with the sentence; 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)); @@ -336,12 +338,53 @@ test("the local model's memory floor (demo epic D5): under it the job fails at i void out.result.stream.cancel(); const done = await out.result.done; assert.equal(done.status, "failed"); + const log = await readFile(getRegistry().get(out.result.jobId)!.logPath, "utf8"); + assert.match(log, /waiting for memory — 1000 MB available, the floor is 3072 MB \(LOCAL_MODEL_MIN_FREE_MB\); waits up to 0 s/); 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.match(it.error ?? "", /1000 MB available is under the 3072 MB a local model's run starts with, after waiting 0 s/); assert.equal(ol.requests.length, asked, "no call to the local model"); }); +test("the memory floor: a job that waited goes on once memory is back (an existing job is delayed, never failed)", async () => { + const r = await run("sweep-pipeline"); + const own = await startFakeOllama({ turns: r.turns }); + const reads = [1000, 2000, 8000]; + try { + const out = await enqueueReportDraft( + { task: "sweep", article: "synth-floor-back", model: r.model, question: r.question, channels: r.channels, source }, + { ...deps({ ollamaUrl: own.url }, () => reads.shift() ?? 8000), memoryWait: { pollMs: 10, maxWaitMs: 60_000 } }, + ); + 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; + const log = await readFile(getRegistry().get(out.result.jobId)!.logPath, "utf8"); + assert.equal(done.status, "done", log); + assert.match(log, /waiting for memory — 1000 MB available/); + assert.match(log, /memory: 8000 MB available — going on/); + } finally { + await own.close(); + } +}); + +test("the memory floor: a cancel ends the wait at once", async () => { + const r = await run("sweep-pipeline"); + const asked = ol.requests.length; + const out = await enqueueReportDraft( + { task: "sweep", article: "synth-floor-cancel", model: r.model, question: r.question, channels: r.channels, source }, + { ...deps({}, 1000), memoryWait: { pollMs: 50, maxWaitMs: 600_000 } }, + ); + assert.ok(out.result.ok && "iteration" in out, (out.result as { error?: string }).error); + void out.result.stream.cancel(); + for (let i = 0; i < 100 && !/waiting for memory/.test(await readFile(getRegistry().get(out.result.jobId)!.logPath, "utf8").catch(() => "")); i++) await new Promise((ok) => setTimeout(ok, 20)); + const t0 = Date.now(); + getRegistry().cancel(out.result.jobId); + const done = await out.result.done; + assert.equal(done.status, "cancelled"); + assert.ok(Date.now() - t0 < 5000, "not the ten minutes"); + assert.equal(ol.requests.length, asked); +}); + 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; @@ -383,6 +426,7 @@ test("local only: a local sweep still runs, on the local model alone", async () 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"); + assert.deepEqual([...new Set(own.shows)], [r.model], "after its /api/show said it is local"); } finally { await own.close(); } diff --git a/editor/app/api/ops/_writes.test.ts b/editor/app/api/ops/_writes.test.ts @@ -91,6 +91,11 @@ test("local only (demo epic D5): a patch that routes a task anywhere but local i 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); + // A model server not on this machine (M2): the probe's patch. + assert.match( + settingsPatchProblem({ generation: { ollamaUrl: "https://ollama-proxy.cloud.example" } }, ["generation"], { generation: { ollamaUrl: "https://ollama-proxy.cloud.example", routes: { sweep: "local" } } })!, + /generation\.ollamaUrl\) at ollama-proxy\.cloud\.example is not on this machine .* — not saved/, + ); delete process.env.ARCHILYZER_LOCAL_ONLY; assert.equal(settingsPatchProblem({ generation: { routes: { sweep: "api" } } }, ["generation"], parsed({ sweep: "api" })), null, "unset: as before"); } finally { diff --git a/editor/app/api/ops/settings/patch.ts b/editor/app/api/ops/settings/patch.ts @@ -1,7 +1,7 @@ // 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"; +import { localOnlySettingsRefusal } 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: @@ -63,13 +63,10 @@ export function settingsPatchProblem( 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; - } + // anywhere but `local`, or names a model server not on this machine, is + // refused while ARCHILYZER_LOCAL_ONLY is on. + const localOnly = localOnlySettingsRefusal(patch, parsed); + if (localOnly) return localOnly; 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/editor/app/settings/saveSettings.test.ts b/editor/app/settings/saveSettings.test.ts @@ -157,3 +157,24 @@ test("a save waits for a held read-modify-write and keeps its change", async () assert.equal(after.syncScheduler.maxConcurrentSyncs, 5); assert.equal(after.minFreeDiskGB, 42, "the later save read the held writer's result"); }); + +test("local only (demo epic D5): the editor's own writer refuses what the ops route refuses — a route off local, a model server elsewhere — and writes nothing", async () => { + const was = process.env.ARCHILYZER_LOCAL_ONLY; + process.env.ARCHILYZER_LOCAL_ONLY = "1"; + try { + writeFileSync(process.env.SETTINGS_FILE!, JSON.stringify({ minFreeDiskGB: 0 })); + const before = readFileSync(process.env.SETTINGS_FILE!, "utf8"); + const gen = getSettings().generation; + await assert.rejects( + saveSettings({ generation: { ...gen, routes: { ...gen.routes, sweep: "api" } } }), + /every generation route stays local — not saved: sweep → api/, + ); + await assert.rejects(saveSettings({ generation: { ollamaUrl: "https://ollama-proxy.cloud.example" } } as never), /ollama-proxy\.cloud\.example is not on this machine/); + assert.equal(readFileSync(process.env.SETTINGS_FILE!, "utf8"), before, "nothing written"); + await saveSettings({ minFreeDiskGB: 1 }); + assert.equal(getSettings().minFreeDiskGB, 1, "other writes go through"); + } finally { + if (was === undefined) delete process.env.ARCHILYZER_LOCAL_ONLY; + else process.env.ARCHILYZER_LOCAL_ONLY = was; + } +}); diff --git a/editor/app/settings/saveSettings.ts b/editor/app/settings/saveSettings.ts @@ -5,6 +5,7 @@ import { } from "yt-dlp-transcript-common/lib/settings"; import { getPaths } from "yt-dlp-transcript-common/lib/paths"; import { withJsonFileLock } from "yt-dlp-transcript-common/lib/jsonFile-server"; +import { localOnlySettingsRefusal } from "yt-dlp-transcript-common/lib/llm/localOnly"; // THE EDITOR'S ONE SETTINGS WRITER (one-core phase 3 slice 4a). // @@ -70,7 +71,13 @@ export function withSettingsLock<T>(fn: () => Promise<T>): Promise<T> { // A save for a caller already holding the lock. export async function saveSettingsHeld(patch: Patch): Promise<void> { - await writeSettings(mergeSettingsPatch(getSettings(), patch)); + const merged = mergeSettingsPatch(getSettings(), patch); + // LOCAL ONLY (common/lib/llm/localOnly.ts): the same refusal the ops route + // answers, here for every other writer (the settings pages' server + // actions): a route off `local`, or a model server not on this machine. + const localOnly = localOnlySettingsRefusal(patch as Record<string, unknown>, merged as unknown as Record<string, unknown>); + if (localOnly) throw new Error(localOnly); + await writeSettings(merged); } export async function saveSettings(patch: Patch): Promise<void> { diff --git a/scripts/demo.test.mjs b/scripts/demo.test.mjs @@ -13,6 +13,8 @@ import os from "node:os"; import path from "node:path"; const SCRIPT = path.join(import.meta.dirname, "..", "docker", "demo.sh"); +// The shell demo.sh runs under (DEMO_TEST_SHELL: dash, busybox — the review runs it under each). +const SH = process.env.DEMO_TEST_SHELL || "/bin/sh"; const START = path.join(import.meta.dirname, "..", "docker", "ollama-start.sh"); const ROOT = mkdtempSync(path.join(os.tmpdir(), "demo-sh-")); test.after(() => rmSync(ROOT, { recursive: true, force: true })); @@ -27,7 +29,8 @@ writeFileSync( `#!/bin/sh printf '%s\\n' "$*" >> "$STUB_LOG" case "$*" in -info) [ -n "\${STUB_NO_DAEMON:-}" ] && exit 1; exit 0 ;; +info) [ -n "\${STUB_DENIED:-}" ] && { echo "permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock" >&2; exit 1; }; [ -n "\${STUB_NO_DAEMON:-}" ] && exit 1; exit 0 ;; +*" ps -aq") { [ -n "\${STUB_RUNNING:-}" ] || [ -n "\${STUB_EXISTS:-}" ]; } && echo c0ffee; exit 0 ;; "info --format {{.DockerRootDir}}") echo /var/lib/docker; exit 0 ;; "compose version --short") [ -n "\${STUB_NO_COMPOSE:-}" ] && exit 1; echo "\${STUB_COMPOSE:-2.29.1}"; exit 0 ;; "version --format {{.Server.Version}}") echo 27.3.1; exit 0 ;; @@ -35,6 +38,10 @@ info) [ -n "\${STUB_NO_DAEMON:-}" ] && exit 1; exit 0 ;; "image inspect "*) [ -n "\${STUB_IMAGES:-}" ] && exit 0; exit 1 ;; esac if [ -n "\${STUB_PERMISSIVE:-}" ]; then + case "$*" in *" up -d") [ -n "\${STUB_ENV_DUMP:-}" ] && printf '%s %s %s %s\\n' "\${SITE_BIND-unset}" "\${EDITOR_BIND-unset}" "\${HOMEPAGE_BIND-unset}" "\${UMTOOL_BIND-unset}" > "\${STUB_ENV_DUMP}" ;; esac + if [ -n "\${STUB_FAIL:-}" ]; then + case "$*" in *"\${STUB_FAIL}"*) echo "Error: stub says no" >&2; exit 1 ;; esac + fi case "$*" in *" logs "*) echo 'time=x level=INFO source=types.go:60 msg="inference compute" id=0 library=Vulkan name=Vulkan0 description="AMD Radeon RX 6600 XT (RADV NAVI23)" type=discrete total="8.0 GiB" available="7.0 GiB"' ;; *"exec -T ollama ollama list"*) printf 'NAME ID SIZE MODIFIED\\n%s abc 4.7GB now\\n' "\${STUB_HAS_MODEL:-none}" ;; @@ -89,7 +96,7 @@ function callsOf(f) { function demo(args, f, extra = {}) { rmSync(f.log, { force: true }); - const res = spawnSync("/bin/sh", [SCRIPT, ...args], { encoding: "utf8", env: envOf(f, extra) }); + const res = spawnSync(SH, [SCRIPT, ...args], { encoding: "utf8", env: envOf(f, extra) }); return { code: res.status, out: res.stdout, err: res.stderr, calls: callsOf(f) }; } @@ -97,7 +104,7 @@ function demo(args, f, extra = {}) { function demoAsync(args, f, extra = {}) { rmSync(f.log, { force: true }); return new Promise((resolve) => { - const child = spawn("/bin/sh", [SCRIPT, ...args], { env: envOf(f, extra) }); + const child = spawn(SH, [SCRIPT, ...args], { env: envOf(f, extra) }); let out = ""; let err = ""; child.stdout.on("data", (d) => (out += d)); @@ -115,8 +122,10 @@ test("up --dry-run: the plan, in plain lines; nothing written, nothing changed", assert.deepEqual(forbidden(r.calls), []); assert.equal(existsSync(f.env), false, "no .env.demo"); const lines = r.out.split("\n"); - assert.match(lines[0], /^demo: docker 27\.3\.1, compose v2\.29\.1 · 16 GB RAM · 80 GB free · ok$/); - assert.match(r.out, /demo: GPU: .*renderD128 -> ollama on Vulkan/); + assert.equal(lines[0], "demo: dry run: only read-only probes — docker version and info, df, /proc/meminfo, /dev/dri, the listening ports, and GET http://127.0.0.1:9/api/ps (a host ollama, if one answers); nothing is written, built, pulled or started"); + assert.match(lines[1], /^demo: docker 27\.3\.1, compose v2\.29\.1 · 16 GB RAM · 80 GB free · ok$/); + assert.match(r.out, /demo: GPU: .*renderD128 found -> will ask ollama for Vulkan/); + assert.match(r.out, /demo: model qwen2\.5:7b: pulled unless ollama already has it \(once, 4\.7 GB\)/); assert.match(r.out, /demo: archive https:\/\/jeralyzer\.pages\.dev · model qwen2\.5:7b · LOCAL ONLY \(the Claude API is refused\)/); assert.match(r.out, /would write .*\.env\.demo \(mode 600, a new WORKER_TOKEN\)/); const compose = "docker compose -p archilyzer-demo --env-file " + f.env + " -f docker-compose.yml -f docker-compose.demo.yml -f docker-compose.ollama-vulkan.yml --profile umtool --profile ollama"; @@ -133,7 +142,8 @@ test("up --dry-run with the flags: another archive and model, no GPU, images pre assert.equal(r.code, 0, r.err); assert.deepEqual(forbidden(r.calls), []); assert.match(r.out, /archive https:\/\/example\.org · model qwen3:8b/); - assert.match(r.out, /GPU: none -> ollama on the CPU/); + assert.match(r.out, /GPU: none -> ollama will run on the CPU/); + assert.match(r.out, /model qwen3:8b: pulled unless ollama already has it \(once, 5\.2 GB\)/); assert.match(r.out, /images: archilyzer:demo and archilyzer:demo-umtool present/); assert.doesNotMatch(r.out, /build editor umtool/); assert.doesNotMatch(r.out, /ollama-vulkan|ollama-nvidia/); @@ -169,7 +179,7 @@ test("each missing prerequisite: one sentence, exit 1, nothing changed", () => { [["up", "--model", "claude-sonnet-5-5"], /a Claude model — the demo runs local models only/], [["up", "--gpu", "rocm"], /--gpu is auto, vulkan, nvidia or none/], [["up", "--editor-port", "80x"], /a port is a number/], - [["up", "--archive", "ftp://x"], /--archive is an http\(s\) URL/], + [["up", "--archive", "ftp://x"], /--archive is not an http\(s\) URL/], [["down", "--model", "x"], /only up takes/], [["up", "--volumes"], /only down takes --volumes/], [["launch"], /unknown command "launch"/], @@ -243,27 +253,35 @@ test("up for real (the stub plays along): .env.demo written once, mode 600; a re assert.match(readFileSync(f.env, "utf8"), new RegExp(`^WORKER_TOKEN=${token}$`, "m")); }); -test("down keeps the volumes unless --volumes; with no .env.demo there is nothing to stop", () => { +test("down keeps the volumes unless --volumes; it stops the project with or without .env.demo; nothing there is nothing to stop", () => { const none = fixture(); const empty = demo(["down"], none); assert.equal(empty.code, 0); - assert.match(empty.out, /nothing to stop/); + assert.match(empty.out, /nothing to stop: no archilyzer-demo containers on this machine/); assert.deepEqual(forbidden(empty.calls), []); const f = fixture(); writeFileSync(f.env, "WORKER_TOKEN=x\n"); - const keep = demo(["down"], f, { STUB_PERMISSIVE: "1" }); + const keep = demo(["down"], f, { STUB_PERMISSIVE: "1", STUB_EXISTS: "1" }); assert.equal(keep.code, 0, keep.err); assert.match(keep.out, /volumes kept; --volumes deletes them/); const downs = keep.calls.filter((c) => / down/.test(c)); assert.equal(downs.length, 1); assert.match(downs[0], / down$/); - const wipe = demo(["down", "--volumes"], f, { STUB_PERMISSIVE: "1" }); + const wipe = demo(["down", "--volumes"], f, { STUB_PERMISSIVE: "1", STUB_EXISTS: "1" }); assert.match(wipe.out, /AND deleting its volumes/); assert.ok(wipe.calls.some((c) => / down -v$/.test(c))); - const dry = demo(["down", "--volumes", "--dry-run"], f); + const dry = demo(["down", "--volumes", "--dry-run"], f, { STUB_EXISTS: "1" }); assert.deepEqual(forbidden(dry.calls), []); assert.match(dry.out, /would run: docker compose .* down -v/); + + // .env.demo deleted while the stack runs (S8): it is still stopped, no --env-file. + const lost = fixture(); + const gone = demo(["down"], lost, { STUB_PERMISSIVE: "1", STUB_EXISTS: "1" }); + assert.equal(gone.code, 0, gone.err); + const d = gone.calls.filter((c) => / down$/.test(c)); + assert.equal(d.length, 1); + assert.ok(d[0].startsWith("compose -p archilyzer-demo -f docker-compose.yml"), d[0]); }); test("check: exit 1 when ollama runs without OLLAMA_NO_CLOUD; refused when the demo is not running", () => { @@ -307,3 +325,140 @@ test("ollama-start.sh: one honest gpu line, then ollama serve", () => { assert.match(on.stdout, /cloud: {6}OLLAMA_NO_CLOUD=1/); assert.match(on.stdout, /prompt cache 1024 MiB/); }); + +test("entrypoint: ARCHILYZER_LOCAL_ONLY read as localOnlyFlag reads it; a value it does not understand is an ERROR line, never silent (S7)", (t) => { + // The entrypoint is bash (the app image's); an image without bash skips this. + if (!spawnSync("sh", ["-c", "command -v bash"], { encoding: "utf8" }).stdout.trim()) return t.skip("no bash here"); + const ENTRY = path.join(import.meta.dirname, "..", "docker", "entrypoint.sh"); + const fn = readFileSync(ENTRY, "utf8").match(/^local_only_line\(\) \{[\s\S]*?^\}$/m)?.[0]; + assert.ok(fn, "local_only_line is in the entrypoint"); + const run = (v) => + spawnSync("bash", ["-c", `log() { printf '[entrypoint] %s\\n' "$*"; }\n${fn}\nlocal_only_line`], { encoding: "utf8", env: { PATH: process.env.PATH, ARCHILYZER_LOCAL_ONLY: v } }); + // The same table as common/lib/llm/localOnly.test.ts (localOnlyFlag). + for (const v of ["1", " TRUE ", "yes", "On"]) { + const r = run(v); + assert.match(r.stdout, /models: {3}LOCAL ONLY/, v); + assert.equal(r.stderr, "", v); + } + for (const v of ["", "0", "false", "NO", "off"]) { + const r = run(v); + assert.equal(r.stdout + r.stderr, "", JSON.stringify(v)); + } + for (const v of ["2", "y", "enabled", "local"]) { + const r = run(v); + assert.equal(r.stdout, ""); + assert.equal(r.stderr, `[entrypoint] ERROR: ARCHILYZER_LOCAL_ONLY=${v} is not understood — the guard is OFF (1, true, yes or on turns it on)\n`, v); + } +}); + +// ─── review round 1 ─── + +test("M1: --archive cannot inject a line: a newline, a space, a quote, $, a backtick or # is refused in one line, nothing written", () => { + for (const bad of ["https://x.example\nEDITOR_BIND=0.0.0.0", "https://x.example EDITOR_BIND=0.0.0.0", 'https://x.example"', "https://x.example/$HOME", "https://x.example/`id`", "https://x.example/#frag", "https://x.example/\r"]) { + const f = fixture(); + const r = demo(["up", "--archive", bad], f, { STUB_PERMISSIVE: "1" }); + assert.equal(r.code, 1, JSON.stringify(bad)); + assert.equal(r.err, "demo: --archive is not a single-line http(s) URL of URL characters (letters, digits and - . _ ~ : / ? = & % + @ ,).\n", JSON.stringify(bad)); + assert.equal(existsSync(f.env), false); + assert.deepEqual(r.calls.filter((c) => / up -d| build /.test(c)), []); + } + const ok = demo(["up", "--dry-run", "--archive", "https://archive.example/sub/path?x=1&y=2"], fixture()); + assert.equal(ok.code, 0, ok.err); +}); + +test("M1: a hand-edited .env.demo — a bind off loopback, a key demo.sh does not write, a bad value — is refused before compose reads it", () => { + const cases = [ + ["WORKER_TOKEN=tok\nEDITOR_BIND=0.0.0.0\n", /^demo: \S+\.env\.demo sets EDITOR_BIND to something other than 127\.0\.0\.1, which would publish a port beyond this machine — the demo binds 127\.0\.0\.1 only; remove that line\.\n$/], + ["WORKER_TOKEN=tok\nUMTOOL_BIND=192.168.1.9\n", /sets UMTOOL_BIND to something other than 127\.0\.0\.1/], + ["WORKER_TOKEN=tok\nUMTOOL_ALLOWED_HOSTS=evil.example\n", /^demo: line 2 of \S+ sets a key demo\.sh does not write — remove it, or delete \S+ to start again\.\n$/], + ["WORKER_TOKEN=tok\nDEMO_ARCHIVE=https://x.example/$(id)\n", /line 2 of \S+ \(DEMO_ARCHIVE\) holds a character no demo value has/], + ["garbage\n", /line 1 of \S+ is not KEY=value/], + ]; + for (const [text, msg] of cases) { + for (const verb of ["up", "down", "status", "check"]) { + const f = fixture(); + writeFileSync(f.env, text); + const r = demo([verb], f, { STUB_PERMISSIVE: "1", STUB_RUNNING: "1" }); + assert.equal(r.code, 1, `${verb} ${JSON.stringify(text)}: ${r.out}`); + assert.match(r.err, msg, verb); + assert.deepEqual(r.calls.filter((c) => c.startsWith("compose")), [], `${verb}: compose never ran`); + } + } + // A bind of 127.0.0.1 is allowed. + const f = fixture(); + writeFileSync(f.env, "WORKER_TOKEN=tok\nEDITOR_BIND=127.0.0.1\n"); + assert.equal(demo(["up", "--dry-run"], f).code, 0); +}); + +test("M1: a bind off loopback in this shell is refused; compose is always handed 127.0.0.1 for every bind", () => { + const f = fixture(); + const r = demo(["up"], f, { STUB_PERMISSIVE: "1", EDITOR_BIND: "0.0.0.0" }); + assert.equal(r.code, 1); + assert.equal(r.err, "demo: EDITOR_BIND is set in this shell to something other than 127.0.0.1, which would publish a port beyond this machine — unset it; the demo binds 127.0.0.1 only.\n"); + // The stub sees the environment compose would: 127.0.0.1 for each bind, + // even with none set (compose would otherwise read .env.demo, or nothing). + const g = fixture(); + const binds = path.join(g.dir, "binds"); + const r2 = demo(["up"], g, { STUB_PERMISSIVE: "1", STUB_IMAGES: "1", STUB_ENV_DUMP: binds }); + assert.equal(r2.code, 0, r2.err); + assert.equal(readFileSync(binds, "utf8"), "127.0.0.1 127.0.0.1 127.0.0.1 127.0.0.1\n"); +}); + +test("M1: the exposure guard in the caddy container sees the bind compose publishes on (docker compose config, when docker is here)", (t) => { + const real = spawnSync("sh", ["-c", "command -v docker"], { encoding: "utf8" }).stdout.trim(); + if (!real) return t.skip("no docker on this machine"); + const dir = mkdtempSync(path.join(ROOT, "cfg-")); + const env = path.join(dir, "bind.env"); + writeFileSync(env, "WORKER_TOKEN=tok\nEDITOR_BIND=0.0.0.0\n"); + const repo = path.join(import.meta.dirname, ".."); + const r = spawnSync(real, ["compose", "-p", "archilyzer-demo-cfgtest", "--env-file", env, "-f", "docker-compose.yml", "-f", "docker-compose.demo.yml", "--profile", "umtool", "--profile", "ollama", "config", "--format", "json"], { cwd: repo, encoding: "utf8", env: { PATH: process.env.PATH, HOME: process.env.HOME } }); + if (r.status !== 0) return t.skip(`docker compose config did not run: ${r.stderr.slice(0, 200)}`); + const caddy = JSON.parse(r.stdout).services.caddy; + assert.equal(caddy.environment.EDITOR_BIND, "0.0.0.0", "the guard is told what is published"); + assert.equal(caddy.environment.UMTOOL_BIND, "127.0.0.1"); + assert.ok(caddy.ports.some((p) => p.host_ip === "0.0.0.0")); +}); + +test("S1: a failed step of up ends with ONE sentence — what failed, partly up, down stops it — and exit 1", () => { + const steps = [ + [" up -d", "demo: starting the stack (docker compose up) failed — the demo is partly up; ./docker/demo.sh down stops it.\n"], + ["ollama pull", "demo: pulling llama3.2:3b failed — the demo is partly up; ./docker/demo.sh down stops it.\n"], + ["gen preset local", "demo: setting the local preset (archilyzer gen preset local) failed — the demo is partly up; ./docker/demo.sh down stops it.\n"], + ["gen model local", "demo: setting the local model (archilyzer gen model local) failed — the demo is partly up; ./docker/demo.sh down stops it.\n"], + ["curl -fsS -o /dev/null", "demo: the editor did not answer within 4 minutes (docker compose -p archilyzer-demo logs editor says why) — the demo is partly up; ./docker/demo.sh down stops it.\n"], + ]; + for (const [fail, sentence] of steps) { + const f = fixture(); + const r = demo(["up", "--model", "llama3.2:3b"], f, { STUB_PERMISSIVE: "1", STUB_IMAGES: "1", STUB_FAIL: fail, DEMO_TEST_WAIT_TRIES: "2", DEMO_TEST_WAIT_SLEEP: "0" }); + assert.equal(r.code, 1, fail); + assert.ok(r.err.endsWith(sentence), `${fail}\n${r.err}`); + assert.doesNotMatch(r.out, /demo: ready/); + } + const b = fixture(); + const build = demo(["up"], b, { STUB_PERMISSIVE: "1", STUB_FAIL: " build editor umtool" }); + assert.equal(build.code, 1); + assert.ok(build.err.endsWith("demo: building the images failed (the build's output is above) — nothing was started; fix it and run ./docker/demo.sh up again.\n")); + assert.ok(!build.calls.some((c) => / up -d/.test(c)), "nothing was started"); +}); + +test("S8: permission denied on the socket has its own sentence; no coreutils on PATH still reaches 'docker is not installed'", () => { + const f = fixture(); + const r = demo(["up"], f, { STUB_DENIED: "1" }); + assert.equal(r.code, 1); + assert.equal(r.err, "demo: docker is installed, but this user may not use its socket (permission denied) — add yourself to the docker group (sudo usermod -aG docker $USER, then log in again) and run this again.\n"); + const empty = mkdtempSync(path.join(ROOT, "nopath-")); + const res = spawnSync(SH, [SCRIPT, "up"], { encoding: "utf8", env: { PATH: empty } }); + assert.equal(res.status, 1); + assert.equal(res.stderr, "demo: docker is not installed — install Docker Engine (or Docker Desktop) and run this again.\n"); +}); + +test("S8: a tagless model is found as name:latest; a model of unknown size prints no size", () => { + const f = fixture(); + const have = demo(["up", "--model", "mistral"], f, { STUB_PERMISSIVE: "1", STUB_IMAGES: "1", STUB_HAS_MODEL: "mistral:latest" }); + assert.equal(have.code, 0, have.err); + assert.match(have.out, /model mistral: present/); + assert.ok(!have.calls.some((c) => / pull /.test(c))); + const g = fixture(); + const pull = demo(["up", "--model", "gemma3:27b"], g, { STUB_PERMISSIVE: "1", STUB_IMAGES: "1" }); + assert.match(pull.out, /demo: pulling gemma3:27b \(once\)\n/); +}); diff --git a/umtool/components/piece/PolicyChip.tsx b/umtool/components/piece/PolicyChip.tsx @@ -1,18 +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 { askEditor, 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 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). +// 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). On a +// local-only EDITOR (its generation-usage answer's `localOnly`, demo epic D5) +// it names the local model and says "local only", with no spend +// (lib/articles/policyChip.ts); otherwise it is exactly as it always was. // // 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. @@ -21,8 +21,15 @@ import { cn } from "@/lib/utils"; // the ⋯ sheet's -- PieceFrame), and the editor need not be asked twice. const policyOnce = cache(() => readPolicy()); const todayOnce = cache((daily: number) => readToday(daily)); +// The editor's own word on local only; an editor that does not say is not. +const localOnlyOnce = cache(async () => + askEditor<{ localOnly?: unknown }>("/api/ops/generation-usage") + .then((a) => a.localOnly === true) + .catch(() => false), +); 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 ( @@ -50,19 +57,25 @@ export default async function PolicyChip() { ); } const g = policy.generation; - 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" data-policy-model={label.model}> - {label.model} - </span> - {label.localOnly && ( + const label = policyChipLabel(g, await localOnlyOnce()); + if (label.localOnly) { + return ( + <PolicyChipShell preset={g.preset}> + <span>{g.preset}</span> + <span className="font-mono text-[11px] text-muted" data-policy-model={label.model}> + {label.model} + </span> <span className="text-[11px] text-muted" data-policy-local-only=""> local only </span> - )} + </PolicyChipShell> + ); + } + const today = await todayOnce(g.caps.daily).catch(() => null); + return ( + <PolicyChipShell preset={g.preset}> + <span>{g.preset}</span> + <span className="font-mono text-[11px] text-muted">{shortModel(g.models.api)}</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 @@ -4,33 +4,12 @@ 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("without local only the chip is what it always was: the API model and the day's spend, whatever the preset", () => { + for (const preset of ["balanced", "local", "code", "api"]) { + assert.deepEqual(policyChipLabel({ preset, models }, false), { preset, 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, - }); +test("on a local-only editor: the local model, no spend, and the flag", () => { + assert.deepEqual(policyChipLabel({ preset: "local", models }, true), { preset: "local", model: "qwen2.5:7b", spend: false, localOnly: true }); }); diff --git a/umtool/lib/articles/policyChip.ts b/umtool/lib/articles/policyChip.ts @@ -1,12 +1,12 @@ -// 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. +// What the generation policy's chip says (components/piece/PolicyChip.tsx). +// Without local only it is exactly what it always was: the preset, the Claude +// API's model and the day's API spend. On a local-only EDITOR -- its own +// answer (generation-usage's `localOnly`, the flag in the editor's +// environment, demo epic D5), never umtool's environment -- it says the local +// model, "local only", and no spend. Pure. export type PolicyChipInput = { preset: string; - routes: Record<string, string>; models: { api: string; local: string }; }; @@ -20,12 +20,7 @@ export type PolicyChipLabel = { 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, - }; +export function policyChipLabel(g: PolicyChipInput, editorLocalOnly: boolean): PolicyChipLabel { + if (!editorLocalOnly) return { preset: g.preset, model: shortModel(g.models.api), spend: true, localOnly: false }; + return { preset: g.preset, model: g.models.local, spend: false, localOnly: true }; }