Archilyzer · Source

archilyzer

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

commit 200646d65b3437a6e672d95c4a3e7333fb18798c
parent 5a3c2576230edcb57848fdf2b155c8a5e178f4b4
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri, 13 Nov 2026 01:01:57 -0500

Merge lane/demo-setup: one command stands up a local-models-only instance -- ./docker/demo.sh up|down|status|check|voice runs the editor, umtool and ollama in Docker as their own project, connected to a published archive, bound to 127.0.0.1 only, with ollama's memory bounded and its GPU or CPU said honestly; ARCHILYZER_LOCAL_ONLY refuses every Claude API call, Claude Code answer, cloud ollama model and model server that is not on this machine before anything is sent, and archilyzer gen local-check says whether that held; the exposure guard now sees the bind that is actually published; a local draft under the memory floor waits instead of starting; without the flag nothing changes

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

Diffstat:
M.env.example | 4+++-
MCOMMANDS.md | 2++
MENVIRONMENT.md | 3+++
MRUNNING_IN_DOCKER.md | 133+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
MSETTINGS.md | 2+-
Mcommon/bin/archilyzer.ts | 15+++++++++++++++
Mcommon/bin/gen.test.ts | 178+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/bin/gen.ts | 349++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
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/frameScan.ts | 6+++++-
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 | 6+++---
Mcommon/controller/reportDraft.ts | 80++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Acommon/controller/reportDraftLocalOnly.test.ts | 48++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/digestApps.ts | 12++++++++++++
Mcommon/lib/envVars.ts | 3+++
Mcommon/lib/generationSettings.ts | 2+-
Mcommon/lib/llm/anthropic.ts | 8++++++++
Mcommon/lib/llm/index.ts | 1+
Acommon/lib/llm/localOnly.test.ts | 263+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/llm/localOnly.ts | 215+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/llm/ollama.ts | 51+++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/workers.test.ts | 15+++++++++++++++
Mcommon/lib/workers.ts | 5+++++
Mcommon/testing/llm/fakeOllama.d.mts | 4++++
Mcommon/testing/llm/fakeOllama.mjs | 17+++++++++++++++++
Adocker-compose.demo.yml | 73+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Adocker-compose.ollama-nvidia.yml | 15+++++++++++++++
Adocker-compose.ollama-vulkan.yml | 16++++++++++++++++
Mdocker-compose.yml | 9+++++++++
Adocker/demo.sh | 705+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mdocker/entrypoint.sh | 37+++++++++++++++++++++++++++++++++++++
Adocker/ollama-start.sh | 39+++++++++++++++++++++++++++++++++++++++
Meditor/CHANGELOG.md | 5+++++
Meditor/app/api/ops/_generation.test.ts | 12+++++++++++-
Meditor/app/api/ops/_reportDraft.test.ts | 121++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Meditor/app/api/ops/_writes.test.ts | 25+++++++++++++++++++++++++
Meditor/app/api/ops/generation-usage/route.ts | 9++++++---
Meditor/app/api/ops/settings/patch.ts | 7+++++++
Meditor/app/settings/saveSettings.test.ts | 21+++++++++++++++++++++
Meditor/app/settings/saveSettings.ts | 9++++++++-
Ascripts/demo.test.mjs | 464+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/piece/PolicyChip.tsx | 28++++++++++++++++++++++++++--
Aumtool/lib/articles/policyChip.test.ts | 15+++++++++++++++
Aumtool/lib/articles/policyChip.ts | 26++++++++++++++++++++++++++
50 files changed, 3137 insertions(+), 19 deletions(-)

diff --git a/.env.example b/.env.example @@ -175,7 +175,9 @@ # Local models, the Claude API, browser cookies # --------------------------------------------------------------------------- # The digest lanes and generation routed to "local" ask an ollama. Default: the -# `ollama` service (`--profile ollama`), pinned by ARCHILYZER_OLLAMA_TAG. A host's own: +# `ollama` service (`--profile ollama`), pinned by ARCHILYZER_OLLAMA_TAG. A host's own +# (it listens on 127.0.0.1, which a container cannot reach — never OLLAMA_HOST=0.0.0.0; +# RUNNING_IN_DOCKER.md, "Local models", bridges it onto the docker gateway alone): #OLLAMA_URL=http://host.docker.internal:11434 #ARCHILYZER_OLLAMA_TAG=0.40.5 # diff --git a/COMMANDS.md b/COMMANDS.md @@ -45,6 +45,8 @@ Run from the repo root (in the container: `docker compose exec editor pnpm archi | `archilyzer gen preset` | `<code\|balanced\|api\|local>` | route every generation task by a preset (its routes are written; settings.generation.routes) | | `archilyzer gen set` | `<task> <code\|api\|local>` | route one generation task (sweep, revise-report, revise-video, research; the media drafts cut, onscreen, teaser, flips, threads, narrate, youtube, social) | | `archilyzer gen local-sweep` | `[--form neutral\|sentence] [--read-aloud flag\|drop\|off]` | the local route's sweep (settings.generation.localSweep): who writes a finding's line — neutral: code (In &lt;title&gt; (&lt;date&gt;), on &lt;topic&gt;: "&lt;quote&gt;"; the model only picks the quote and labels its topic), sentence: the model, judged by a meaning check — and what happens to a quote whose transcript has a sign of reading aloud around it (a tweet, a headline, "it says"): flag keeps it marked to check by ear, drop leaves it out, off does not look; bare, what they are | +| `archilyzer gen model` | `[api\|local\|extractor <model>]` | the model a route runs (settings.generation.models): api = the Claude API's, local = the ollama model the local route runs, extractor = an API sweep's batch reader; bare, the three. On a local-only instance (ARCHILYZER\_LOCAL\_ONLY=1) a Claude or ollama cloud model is refused for local and extractor | +| `archilyzer gen local-check` | `[--since YYYY-MM-DD] [--json]` | read-only: whether this instance stayed local (demo epic D5) — ARCHILYZER\_LOCAL\_ONLY on (the editor's own answer when one answers; 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,6 +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 | 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 @@ -124,6 +124,104 @@ replaced while it runs keeps running until `service restart`. `--dry-run` prints every unit and every command and writes nothing. Every flag is in [COMMANDS.md](COMMANDS.md). +### A local-only demo, in one command + +```sh +git clone <your-remote> archilyzer && cd archilyzer +./docker/demo.sh up +``` + +The editor and umtool in Docker, connected to a published archive +(https://jeralyzer.pages.dev unless `--archive <url>`) as a source, with every +AI task on a local model (`--model`, default `qwen2.5:7b`) served by the +compose `ollama` service — and the Claude API refused, provably. It needs only +docker with compose v2.24 or newer; no Node, no pnpm, no `.env` to write, no +secret to type. Every step is one printed line; a missing prerequisite (docker, +compose v2, the daemon, 12 GB of RAM, 25 GB free, a port) ends it with one +sentence and exit 1. + +```sh +./docker/demo.sh up --dry-run # the plan: every command it would run; writes and starts nothing +./docker/demo.sh up [--archive <url>] [--model <name>] [--gpu auto|vulkan|nvidia|none] + [--editor-port 8081] [--umtool-port 8083] [--site-port 8080] [--homepage-port 8082] [--rebuild] +./docker/demo.sh status # containers, ollama's device, the policy, the voice +./docker/demo.sh check # the local-only proof: exit 1 when it fails +./docker/demo.sh voice # the Orpheus narration voice (about 4 GB, once) +./docker/demo.sh down [--volumes] # stops it; volumes are kept unless --volumes +``` + +What `up` does, in order: checks the prerequisites; picks the GPU (`--gpu +auto`: a render node at /dev/dri → ollama on Vulkan through +`docker-compose.ollama-vulkan.yml`; NVIDIA → `docker-compose.ollama-nvidia.yml`; +else the CPU, and says so); warns — never refuses — when a host ollama answers +on 127.0.0.1:11434 with a model loaded (asked with `GET /api/ps`, which loads +nothing); writes `.env.demo` (mode 600, gitignored: a random `WORKER_TOKEN`, +the archive, the model, the ports — reused by every later run, a flag changes +its line); builds the images once (`archilyzer:demo`, `archilyzer:demo-umtool`; +`--rebuild` again); starts project `archilyzer-demo` with +`docker-compose.demo.yml`; waits for the editor; prints ollama's own word on +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. +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. 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 +so in its `voice:` line, and `./docker/demo.sh voice` names what is missing +rather than install half of it. + --- ## The exposure model @@ -498,8 +596,39 @@ OLLAMA_URL=http://host.docker.internal:11434 ``` (`host.docker.internal` resolves on Linux too — compose maps it for the editor -and umtool. The host's ollama must listen beyond loopback for a container to -reach it: `OLLAMA_HOST=0.0.0.0`.) +and umtool.) But a host's ollama listens on 127.0.0.1 by default, and that +address is not reachable from a container: `host.docker.internal` is the +docker bridge's gateway, so the request is refused. **Do not "fix" it with +`OLLAMA_HOST=0.0.0.0`** — that puts the model server on every interface, the +LAN included, with no auth. Either run the compose `ollama` service (above, +and `docker-compose.ollama-vulkan.yml` gives it the GPU alone), or bridge +loopback onto the gateway address only, with the network's subnet pinned so +that address is known: + +```yaml +# docker-compose.ollama-host.yml (yours; not shipped) +networks: + archilyzer: + ipam: + config: + - subnet: 172.31.250.0/24 + gateway: 172.31.250.1 +services: + ollama-bridge: + image: alpine/socat:1.8.0.3 + network_mode: host + restart: unless-stopped + command: ["TCP-LISTEN:11434,bind=172.31.250.1,fork,reuseaddr", "TCP:127.0.0.1:11434"] +``` + +with `OLLAMA_URL=http://172.31.250.1:11434` in `.env`: it listens on the +gateway address alone, which nothing off this machine reaches (pick a subnet no +other network uses). The demo epic's baseline ran this way. + +**One server per card.** A host ollama and the compose one each keep their own +model in VRAM; on an 8 GB card the second spills to the CPU or fails. Run one +at a time — `./docker/demo.sh up` warns when a host ollama answers with a model +loaded. ### The Claude API diff --git a/SETTINGS.md b/SETTINGS.md @@ -1139,7 +1139,7 @@ Report and video generation (release 27): where each task runs (`code` = Claude | `apiKeyFile` | `"~/.config/archilyzer/anthropic.env"` | The file holding the Claude API key (`ANTHROPIC_API_KEY=…`), mode 600 — refused when the group or others can read it. `~` is the editor's home. The KEY itself is never a setting: a value that looks like one is refused, never stored. `ANTHROPIC_API_KEY` in the editor's environment wins over the file. | | `anthropicBaseUrl` | `""` | Advanced: the Messages API's base URL. Blank = Anthropic's. Tests point it at a fake. | | `ollamaUrl` | `""` | The local model's server (ollama). Blank = the editor's `OLLAMA_URL` (the digest lane's server, default http://127.0.0.1:11434). | -| `projectsRoot` | `""` | Where an iteration's video project and renders live: `<projectsRoot>/<article>/i<n>/`, off the corpus disk (D1). Blank = `~/reports/articles`. | +| `projectsRoot` | `""` | Where an iteration's video project and renders live: `<projectsRoot>/<article>/i<n>/`, off the corpus disk (D1). Blank = `<REPORTS_DIR>/articles` when REPORTS_DIR is set (a container's reports volume: `/data/reports/articles`), else `~/reports/articles` (common/lib/projectsRoot.mjs). | | `web` | object — see below | The web an agent may read for context (below). Read-only and paced: one request at a time, 3 s apart. | | `citationOrigin` | `""` | The origin a generated report's moment links cite when its corpus build's site has no public URL (a private build). Blank = the project site. | | `research` | object — see below | A research run's default autonomy and its limits (below). A run may name its own autonomy; the limits are the settings'. | diff --git a/common/bin/archilyzer.ts b/common/bin/archilyzer.ts @@ -491,6 +491,21 @@ export const COMMANDS: Command[] = [ run: async (ctx) => (await import("./gen")).genLocalSweepRow(ctx), }, { + path: ["gen", "model"], + usage: + "[api|local|extractor <model>] the model a route runs (settings.generation.models): api = the Claude API's, local = the ollama model the local route runs, extractor = an API sweep's batch reader; bare, the three. On a local-only instance (ARCHILYZER_LOCAL_ONLY=1) a Claude or ollama cloud model is refused for local and extractor", + maxPositionals: 2, + run: async (ctx) => (await import("./gen")).genModelRow(ctx), + }, + { + path: ["gen", "local-check"], + usage: + "[--since YYYY-MM-DD] [--json] read-only: whether this instance stayed local (demo epic D5) — ARCHILYZER_LOCAL_ONLY on (the editor's own answer when one answers; 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), + }, + { path: ["gen", "run"], usage: "<task> [<question|feedback>] --article <id> [--via api|local|code] [--model <m>] [--iteration <n>] [--channels a,b] [--from YYYY-MM-DD] [--to YYYY-MM-DD] [--copy-of <n>] [--max-usd <usd>] [--cards a,b] [--entries a,b] [--force] [--autonomy propose|limits|auto] [--source <handle>|--build <id>] [--wait] enqueue a report-draft job as `pnpm ops report-draft` does (--wait follows it; `sweep --iteration <n>` continues research run n); a media draft (cut, onscreen, teaser, flips, threads, narrate, youtube, social) is a step on --iteration <n>, takes no words, --entries limits it, --force re-drafts only fields a model drafted; EXITS 3 and runs nothing when the task is routed to code (Claude Code does it; --via overrides once)", diff --git a/common/bin/gen.test.ts b/common/bin/gen.test.ts @@ -262,3 +262,181 @@ test("gen run a media draft: a step on --iteration, no words, --entries and --fo assert.deepEqual(gen.runBody("sweep", "q", { article: "synth-a", entries: "c01" }), { error: "gen run: --entries is a media draft's" }); }); + +// ─── demo epic D5: gen model, gen local-check, the local-only refusal ─── + +const ALL_LOCAL: GenPolicy = { + preset: "local", + routes: { sweep: "local", "revise-report": "local", "revise-video": "local", narrate: "local", research: "local" }, + models: { api: "claude-sonnet-5-5", local: "qwen2.5:7b", extractor: "qwen2.5:7b" }, +}; + +function modelStore(policy: GenPolicy) { + const { store } = memoryStore(policy); + const writes: GenPolicy["models"][] = []; + let p = structuredClone(policy); + store.read = async () => p; + store.writeModels = async (models) => { + writes.push(models); + p = { ...p, models }; + return p; + }; + return { store, writes }; +} + +test("gen model: shows the three; writes one slot keeping the others; an unchanged one is not written", async () => { + const { store, writes } = modelStore(BALANCED); + const c = capture(); + assert.equal(await gen.modelMain({}, { store: async () => store, runOps: async () => 0, out: c.out }), 0); + assert.match(c.lines[0]!, /^api claude-sonnet-5-5 · local qwen3:8b · extractor claude-haiku-4-5 {2}\(from the editor/); + assert.equal(await gen.modelMain({ slot: "local", name: "qwen2.5:7b" }, { store: async () => store, runOps: async () => 0, out: c.out }), 0); + assert.deepEqual(writes, [{ api: "claude-sonnet-5-5", local: "qwen2.5:7b", extractor: "claude-haiku-4-5" }]); + assert.equal(await gen.modelMain({ slot: "local", name: "qwen2.5:7b" }, { store: async () => store, runOps: async () => 0, out: c.out }), 0); + assert.equal(writes.length, 1, "already so: nothing written"); + const e = capture(); + assert.equal(await gen.modelMain({ slot: "vision", name: "x" }, { store: async () => store, runOps: async () => 0, out: e.out }), 2); + assert.equal(await gen.modelMain({ slot: "local", name: "bad name!" }, { store: async () => store, runOps: async () => 0, out: e.out }), 2); + assert.equal(await gen.modelMain({ slot: "local" }, { store: async () => store, runOps: async () => 0, out: e.out }), 2); +}); + +test("gen model on a local-only instance: a Claude or cloud model refused for local and extractor", async () => { + const { store, writes } = modelStore(ALL_LOCAL); + const env = { ARCHILYZER_LOCAL_ONLY: "1" }; + const c = capture(); + assert.equal(await gen.modelMain({ slot: "extractor", name: "claude-haiku-4-5" }, { store: async () => store, runOps: async () => 0, out: c.out, env }), 1); + assert.equal(await gen.modelMain({ slot: "local", name: "gpt-oss:120b-cloud" }, { store: async () => store, runOps: async () => 0, out: c.out, env }), 1); + assert.match(c.errors.join("\n"), /local only \(ARCHILYZER_LOCAL_ONLY=1\): "claude-haiku-4-5" is not a local model/); + assert.equal(writes.length, 0); +}); + +test("gen preset/set on a local-only instance: a route other than local refused before any write", async () => { + const { store, written } = memoryStore(ALL_LOCAL, true); + const c = capture(); + const deps = { store: async () => store, runOps: async () => 0, out: c.out, env: { ARCHILYZER_LOCAL_ONLY: "1" } }; + assert.equal(await gen.setMain({ preset: "balanced" }, deps), 1); + assert.equal(await gen.setMain({ task: "sweep", route: "code" }, deps), 1); + assert.match(c.errors.join("\n"), /every generation route stays local — not saved: sweep → code/); + assert.equal(written.length, 0); + assert.equal(await gen.setMain({ preset: "local" }, deps), 0); + assert.equal(written.length, 1); +}); + +const row = (r: Partial<import("../controller/generationUsage").GenerationUsageRow>) => ({ + at: "2026-11-13T10:00:00Z", + day: "2026-11-13", + jobId: "j1", + article: "a", + iteration: 1, + task: "sweep", + model: "qwen2.5:7b", + inputTokens: 10, + outputTokens: 5, + cacheReadTokens: 0, + cacheWriteTokens: 0, + usd: 0, + route: "local" as const, + calls: 12, + ...r, +}); + +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.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 = 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.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, /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, 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: { 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: {}, 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.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: "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 @@ -7,6 +7,8 @@ // archilyzer gen local-sweep [--form neutral|sentence] [--read-aloud flag|drop|off] // the local sweep's claim form and read-aloud rule // (settings.generation.localSweep); bare: what they are +// archilyzer gen model [api|local|extractor <model>] the model a route runs (settings.generation.models) +// archilyzer gen local-check [--since D] [--json] whether the instance stayed local (D5): exit 1 if not // archilyzer gen run <task> [<question|feedback>] --article <id> [--via api|local|code] […] [--wait] // enqueue a report-draft job (`pnpm ops report-draft`); // a media draft (cut, onscreen, teaser, flips, threads, @@ -29,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"; @@ -48,8 +51,10 @@ import { type GenerationPreset, type GenerationRoute, } from "../lib/generationSettings"; +import { isCloudOllamaModel, isLocalModelUrl, isLocalOnly, localOnlyFlag, localOnlyRoutesRefusal, modelHostOf } from "../lib/llm/localOnly"; +import type { GenerationUsageRow } from "../controller/generationUsage"; -type Out = { log: (s: string) => void; error: (s: string) => void }; +type Out ={ log: (s: string) => void; error: (s: string) => void }; // The part of settings.generation this command shows and changes. export type GenPolicy = { @@ -70,6 +75,12 @@ export type GenStore = { usage(): Promise<GenUsage | null>; writeRoutes(routes: Record<string, GenerationRoute>): Promise<GenPolicy>; writeLocalSweep(localSweep: GenerationLocalSweep): Promise<GenPolicy>; + writeModels?(models: GenPolicy["models"]): Promise<GenPolicy>; + // Whether the editor itself runs local only (ARCHILYZER_LOCAL_ONLY in ITS + // environment), or null when no editor answers. + editorLocalOnly?(): Promise<boolean | null>; + // One top-level settings key as the store holds it (secrets redacted), or null. + readKey?(key: string): Promise<unknown>; }; export type GenDeps = { @@ -78,6 +89,14 @@ export type GenDeps = { // `pnpm ops <argv>` as a child; its exit code. runOps: (argv: string[]) => Promise<number>; out?: Out; + // This process's environment (ARCHILYZER_LOCAL_ONLY, ANTHROPIC_API_KEY's + // presence); default process.env. + env?: Record<string, string | undefined>; + // `gen local-check`: 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>; }; const TASKS_HELP = `sweep, revise-report, revise-video, research, or a media draft: ${MEDIA_STEP_TASKS.join(", ")}`; @@ -209,6 +228,21 @@ export async function editorStore(env: NodeJS.ProcessEnv = process.env, fetchImp if (!p) throw new Error("the editor's answer carried no generation block"); return p; }, + async writeModels(models) { + const a = await call("POST", "/api/ops/settings", { patch: { generation: { models } } }); + if (a.kind !== "ok") throw fail(a); + const p = policyFrom((a.body.value as Record<string, unknown> | undefined)?.generation); + if (!p) throw new Error("the editor's answer carried no generation block"); + return p; + }, + async editorLocalOnly() { + const a = await call("GET", "/api/ops/generation-usage"); + return a.kind === "ok" && typeof a.body.localOnly === "boolean" ? a.body.localOnly : null; + }, + async readKey(key) { + const a = await call("GET", `/api/ops/settings?key=${encodeURIComponent(key)}`); + return a.kind === "ok" ? (a.body.value ?? null) : null; + }, }; } @@ -237,6 +271,14 @@ export async function offlineStore(): Promise<GenStore> { await writeSettings({ ...s, generation: { ...s.generation, localSweep } }); return read(); }, + async writeModels(models) { + const s = getSettings(); + await writeSettings({ ...s, generation: { ...s.generation, models: { ...s.generation.models, ...models } } }); + return read(); + }, + async editorLocalOnly() { + return null; + }, }; } @@ -285,6 +327,12 @@ export async function setMain(o: { preset?: string; task?: string; route?: strin const routes = o.preset ? { ...p.routes, ...GENERATION_PRESETS[o.preset as GenerationPreset] } : { ...p.routes, [o.task!]: o.route as GenerationRoute }; + // LOCAL ONLY: here too, for the offline store (the editor refuses its own). + const refusal = localOnlyRoutesRefusal(routes, deps.env); + if (refusal) { + out.error(`${name}: ${refusal}`); + return 1; + } const saved = await store.writeRoutes(routes); for (const l of [...formatPolicy(saved, await store.usage()), `(written to ${store.where})`]) out.log(l); return 0; @@ -325,6 +373,297 @@ export async function localSweepMain(o: { form?: string; readAloud?: string }, d return 0; } +// `gen model <api|local|extractor> <name>`: the model a route runs +// (settings.generation.models). Bare `gen model`: the three. +const MODEL_SLOTS = ["api", "local", "extractor"] as const; +type ModelSlot = (typeof MODEL_SLOTS)[number]; +const MODEL_NAME = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/; + +export async function modelMain(o: { slot?: string; name?: string }, deps: GenDeps): Promise<number> { + const out = deps.out ?? console; + if (o.slot !== undefined && !(MODEL_SLOTS as readonly string[]).includes(o.slot)) { + out.error(`gen model: ${MODEL_SLOTS.join("|")} <model>`); + return 2; + } + if (o.name !== undefined && !MODEL_NAME.test(o.name)) { + out.error(`gen model: "${o.name}" is not a model name (letters, digits and . _ : / -)`); + return 2; + } + if (o.slot !== undefined && o.name === undefined) { + out.error(`gen model: ${o.slot} <model> — name the model`); + return 2; + } + const store = await deps.store(); + if ("error" in store) { + out.error(`gen model: ${store.error}`); + return 1; + } + const p = await store.read(); + const show = (q: GenPolicy, verb: string) => + out.log(`api ${q.models.api} · local ${q.models.local}${q.models.extractor ? ` · extractor ${q.models.extractor}` : ""} (${verb} ${store.where})`); + if (o.slot === undefined) { + show(p, "from"); + return 0; + } + const slot = o.slot as ModelSlot; + const name = o.name!; + if (isLocalOnly(deps.env) && (slot === "api" ? false : name.startsWith("claude") || isCloudOllamaModel(name))) { + out.error(`gen model: this instance is local only (ARCHILYZER_LOCAL_ONLY=1): "${name}" is not a local model`); + return 1; + } + if (!store.writeModels) { + out.error(`gen model: ${store.where} cannot write models`); + return 1; + } + if (p.models[slot] === name) { + show(p, "already, in"); + return 0; + } + show(await store.writeModels({ ...p.models, [slot]: name }), "written to"); + return 0; +} + +// `gen local-check [--since YYYY-MM-DD] [--json]` (demo epic D5): whether +// this instance has stayed local, by counts, hosts and route names — never a +// key, a key file's path or its contents, never an absolute home path. +// +// guard ARCHILYZER_LOCAL_ONLY on (the editor's own answer when one +// answers); a value the flag does not understand is named +// routes every generation route local +// endpoints every model server a local route asks (generation.ollamaUrl, +// else OLLAMA_URL; the digest's ollama; each enabled LLM worker) +// on this machine — loopback, or ARCHILYZER_LOCAL_MODEL_HOSTS +// api key none at hand (presence only) +// ledger the usage ledger since the date: no Claude API row +// model log the per-call logs (calls/<jobId>, and the iterations they +// point at): no call on a route but local +// imports no iteration imported from a run made elsewhere +// (`reports import-sweep`, `reports import-local-runs`, which +// local only refuses) +// +// Exit 1 when any check FAILS. When none fails but neither the ledger nor the +// model log holds a call yet, the verdict is "nothing to prove yet" (exit 0): +// the setup is local only, and no model call has been recorded to prove it by. +export type CheckStatus = "ok" | "fail" | "none"; +export type LocalCheck = { name: string; ok: boolean; status: CheckStatus; line: string }; +export type LocalEndpoint = { what: string; url: string }; +export type LoggedCall = { route: string; at: string; model: string }; +export type ImportedIteration = { article: string; n: number; at: string; from: string }; +export type LocalVerdict = "pass" | "fail" | "nothing-yet"; + +const check = (name: string, status: CheckStatus, line: string): LocalCheck => ({ name, ok: status !== "fail", status, line }); + +export function localChecks(o: { + policy: GenPolicy; + flagHere: { on: boolean; raw: string; understood: boolean }; + guardEditor: boolean | null; + apiKey: "env" | "file" | null; + endpoints: readonly LocalEndpoint[]; + rows: readonly GenerationUsageRow[]; + calls: readonly LoggedCall[]; + imported: readonly ImportedIteration[]; + since: string | null; + env?: Record<string, string | undefined>; +}): { ok: boolean; verdict: LocalVerdict; checks: LocalCheck[]; local: { model: string; calls: number; jobs: number }[]; apiRows: number } { + const checks: LocalCheck[] = []; + const guardOn = o.guardEditor ?? o.flagHere.on; + const notUnderstood = !o.flagHere.understood ? ` — ARCHILYZER_LOCAL_ONLY=${JSON.stringify(o.flagHere.raw)} is not understood here, so the guard is OFF in this process` : ""; + checks.push( + check( + "guard", + guardOn ? "ok" : "fail", + (guardOn + ? `ARCHILYZER_LOCAL_ONLY is on (${o.guardEditor === null ? "this process; no editor answered" : "the editor says so"})` + : "ARCHILYZER_LOCAL_ONLY is OFF — a Claude route would be called") + notUnderstood, + ), + ); + const routes = Object.entries(o.policy.routes); + const off = routes.filter(([, r]) => r !== "local"); + checks.push(check("routes", off.length === 0 ? "ok" : "fail", off.length === 0 ? `${routes.length} of ${routes.length} local (preset ${o.policy.preset})` : `${off.length} of ${routes.length} not local: ${off.map(([t, r]) => `${t} → ${r}`).join(", ")}`)); + const hostOf = (url: string) => modelHostOf(url) ?? (url ? "an unreadable URL" : "not set"); + const far = o.endpoints.filter((e) => !isLocalModelUrl(e.url, o.env)); + checks.push( + check( + "endpoints", + far.length === 0 ? "ok" : "fail", + o.endpoints.map((e) => `${e.what} → ${hostOf(e.url)}${isLocalModelUrl(e.url, o.env) ? "" : " (NOT this machine)"}`).join("; ") || "none configured", + ), + ); + checks.push(check("api key", o.apiKey === null ? "ok" : "fail", o.apiKey === null ? "none at hand (no ANTHROPIC_API_KEY, no key file)" : `one is at hand (${o.apiKey === "env" ? "ANTHROPIC_API_KEY is set" : "the key file exists"})`)); + const inRange = (day: string) => !o.since || day >= o.since; + const rows = o.rows.filter((r) => inRange(r.day)); + const api = rows.filter((r) => r.route !== "local"); + const byModel = new Map<string, { model: string; calls: number; jobs: Set<string> }>(); + for (const r of rows) { + if (r.route !== "local") continue; + const m = byModel.get(r.model) ?? { model: r.model, calls: 0, jobs: new Set<string>() }; + m.calls += typeof r.calls === "number" ? r.calls : 0; + m.jobs.add(r.jobId); + byModel.set(r.model, m); + } + const local = [...byModel.values()].map((m) => ({ model: m.model, calls: m.calls, jobs: m.jobs.size })).sort((a, b) => b.calls - a.calls || a.model.localeCompare(b.model)); + const range = o.since ? `since ${o.since}` : "all of it"; + if (rows.length === 0) checks.push(check("ledger", "none", `${range}: no calls recorded`)); + else + checks.push( + check( + "ledger", + api.length === 0 ? "ok" : "fail", + `${range}: ${api.length === 0 ? "0 Claude API rows" : `${api.length} Claude API row(s) (${[...new Set(api.map((r) => r.model))].sort().join(", ")})`}; ` + + (local.length ? `local: ${local.map((m) => `${m.model} ${m.calls} call(s) in ${m.jobs} job(s)`).join(", ")}` : "no local calls"), + ), + ); + const calls = o.calls.filter((c) => inRange(c.at.slice(0, 10))); + const farCalls = calls.filter((c) => c.route !== "local"); + if (calls.length === 0) checks.push(check("model log", "none", `${range}: no calls recorded`)); + else { + const routesSeen = [...new Set(farCalls.map((c) => `${c.route} ${c.model}`))].sort(); + checks.push(check("model log", farCalls.length === 0 ? "ok" : "fail", `${range}: ${calls.length} call(s), ${farCalls.length === 0 ? "every one on the local route" : `${farCalls.length} NOT local (${routesSeen.join(", ")})`}`)); + } + const imports = o.imported.filter((i) => inRange(i.at.slice(0, 10))); + checks.push(check("imports", imports.length === 0 ? "ok" : "fail", imports.length === 0 ? `${range}: no iteration imported from elsewhere` : `${imports.length} iteration(s) made elsewhere and imported: ${imports.map((i) => `${i.article} i${i.n} (from ${i.from})`).join(", ")}`)); + const failed = checks.some((c) => c.status === "fail"); + const nothing = !failed && checks.find((c) => c.name === "ledger")!.status === "none" && checks.find((c) => c.name === "model log")!.status === "none"; + return { ok: !failed, verdict: failed ? "fail" : nothing ? "nothing-yet" : "pass", checks, local, apiRows: api.length }; +} + +/** `--since`'s refusal, or null: a real calendar date (UTC), not after today. */ +export function sinceProblem(since: string, today: string = new Date().toISOString().slice(0, 10)): string | null { + if (!/^\d{4}-\d{2}-\d{2}$/.test(since)) return "--since is a date YYYY-MM-DD (UTC)"; + const t = Date.parse(`${since}T00:00:00Z`); + if (Number.isNaN(t) || new Date(t).toISOString().slice(0, 10) !== since) return `--since ${since} is not a calendar date`; + if (since > today) return `--since ${since} is after today (${today}, UTC)`; + return null; +} + +// A path as it may be printed: the home directory as `~` (a container's +// /data paths are printed as they are). +export function tildify(text: string, home: string = os.homedir()): string { + return home && home !== "/" ? text.split(home).join("~") : text; +} + +export async function localCheckMain(o: { since?: string; json: boolean }, deps: GenDeps): Promise<number> { + const out = deps.out ?? console; + const bad = o.since !== undefined ? sinceProblem(o.since) : null; + if (bad) { + out.error(`gen local-check: ${bad}`); + return 2; + } + const store = await deps.store(); + if ("error" in store) { + out.error(tildify(`gen local-check: ${store.error}`)); + return 1; + } + const policy = await store.read(); + const env = deps.env ?? process.env; + const ev = await (deps.evidence ?? defaultEvidence)(store); + const r = localChecks({ + policy, + flagHere: localOnlyFlag(env), + guardEditor: store.editorLocalOnly ? await store.editorLocalOnly() : null, + apiKey: await (deps.apiKeyAtHand ?? defaultApiKeyAtHand)(), + endpoints: ev.endpoints, + rows: ev.rows, + calls: ev.calls, + imported: ev.imported, + since: o.since ?? null, + env, + }); + const where = tildify(store.where); + if (o.json) { + out.log(JSON.stringify({ ok: r.ok, verdict: r.verdict, since: o.since ?? null, checks: r.checks, local: r.local, apiRows: r.apiRows, from: where }, null, 2)); + } else { + out.log( + r.verdict === "fail" + ? "local-check: FAIL" + : r.verdict === "nothing-yet" + ? "local-check: NOTHING TO PROVE YET — the setup is local only, and no model call is recorded yet to prove it by" + : "local-check: PASS — the setup is local only, and every recorded call was local", + ); + for (const c of r.checks) out.log(` ${(c.status === "ok" ? "ok" : c.status === "none" ? "--" : "FAIL").padEnd(4)} ${c.name.padEnd(9)} ${c.line}`); + out.log(`(from ${where})`); + } + return r.ok ? 0 : 1; +} + +export type LocalEvidence = { endpoints: LocalEndpoint[]; rows: GenerationUsageRow[]; calls: LoggedCall[]; imported: ImportedIteration[] }; + +// What local-check reads, off disk (it runs where the editor's files are: +// the editor's container, or the host of a host install) and from the store. +async function defaultEvidence(store: GenStore): Promise<LocalEvidence> { + const { getPaths } = await import("../lib/paths"); + const { getSettings } = await import("../lib/settings"); + const { readGenerationUsage } = await import("../controller/generationUsage"); + const paths = getPaths(); + const s = getSettings(); + const gen = (store.readKey ? ((await store.readKey("generation")) as Record<string, unknown> | null) : null) ?? (s.generation as unknown as Record<string, unknown>); + const digest = (store.readKey ? ((await store.readKey("digest")) as Record<string, unknown> | null) : null) ?? (s.digest as unknown as Record<string, unknown>); + const workers = (store.readKey ? ((await store.readKey("workers")) as unknown[] | null) : null) ?? (s.workers as unknown[]); + const endpoints: LocalEndpoint[] = []; + const genUrl = typeof gen?.ollamaUrl === "string" && gen.ollamaUrl.trim() ? gen.ollamaUrl.trim() : paths.ollamaUrl; + endpoints.push({ what: typeof gen?.ollamaUrl === "string" && gen.ollamaUrl.trim() ? "the local route (generation.ollamaUrl)" : "the local route (OLLAMA_URL)", url: genUrl }); + const apps = digest && typeof digest.apps === "object" && digest.apps ? (digest.apps as Record<string, { baseUrl?: string }>) : {}; + const digestUrl = apps["ollama-direct"]?.baseUrl?.trim(); + endpoints.push({ what: digestUrl ? "the digest (digest.apps.ollama-direct)" : "the digest (OLLAMA_URL)", url: digestUrl || paths.ollamaUrl }); + for (const w of Array.isArray(workers) ? workers : []) { + const x = w as { kind?: string; enabled?: boolean; id?: string; llm?: { baseUrl?: string } }; + if (x.kind === "llm" && x.enabled) endpoints.push({ what: `LLM worker ${x.id ?? "?"}`, url: x.llm?.baseUrl ?? "" }); + } + return { + endpoints, + rows: await readGenerationUsage(paths.generationUsageFile), + calls: await loggedCalls(paths), + imported: await importedIterations(paths), + }; +} + +// Every call the per-call logs hold: each job's own (calls/<jobId>/) and the +// iteration logs the jobs point at, each file read once. +async function loggedCalls(paths: import("../lib/paths").Paths): Promise<LoggedCall[]> { + const { readdir } = await import("node:fs/promises"); + const { locateJobModelLog } = await import("../controller/jobModelLog"); + const { readModelLog } = await import("../lib/llm/callLog-server"); + const dir = path.join(path.dirname(paths.generationUsageFile), "calls"); + const ids = await readdir(dir).catch(() => [] as string[]); + const seen = new Set<string>(); + const out: LoggedCall[] = []; + for (const id of ids) { + if (!/^[A-Za-z0-9._-]+$/.test(id) || /^\.+$/.test(id)) continue; + const at = await locateJobModelLog(paths, id).catch(() => null); + if (!at || seen.has(at.files.calls)) continue; + seen.add(at.files.calls); + const log = await readModelLog(at.files).catch(() => null); + for (const c of log?.calls ?? []) out.push({ route: c.route, at: c.at, model: c.model }); + } + return out; +} + +// Every iteration that carries `imported` (a run made elsewhere). +async function importedIterations(paths: import("../lib/paths").Paths): Promise<ImportedIteration[]> { + const { listArticles } = await import("../lib/report/registry"); + const { listIterations } = await import("../lib/report/iterations"); + const out: ImportedIteration[] = []; + for (const a of await listArticles(paths).catch(() => [])) { + for (const it of await listIterations(a.id, paths).catch(() => [])) { + const imp = (it as unknown as { imported?: { from?: unknown; run?: unknown } }).imported; + if (!imp) continue; + out.push({ article: a.id, n: it.n, at: it.createdAt, from: typeof imp.from === "string" ? imp.from : typeof imp.run === "string" ? `the stopgap run ${imp.run}` : "elsewhere" }); + } + } + return out; +} + +// Whether a Claude API key is at hand — its presence only: the variable is +// checked for a value, the file for existence; neither is read out. +async function defaultApiKeyAtHand(): Promise<"env" | "file" | null> { + if ((process.env.ANTHROPIC_API_KEY ?? "").trim()) return "env"; + const { getSettings } = await import("../lib/settings"); + const { existsSync } = await import("node:fs"); + const f = getSettings().generation.apiKeyFile; + const file = f === "~" || f.startsWith("~/") ? os.homedir() + f.slice(1) : f; + return file && existsSync(file) ? "file" : null; +} + // The report-draft body from `gen run`'s words, or why not. The editor judges // the rest (controller/reportDraft.ts parseReportDraftBody). export function runBody(task: string, text: string | undefined, flags: Record<string, FlagValue>): Record<string, unknown> | { error: string } { @@ -444,6 +783,14 @@ export async function genLocalSweepRow(ctx: CommandContext): Promise<number> { const readAloud = str("read-aloud"); return localSweepMain({ ...(form !== undefined ? { form } : {}), ...(readAloud !== undefined ? { readAloud } : {}) }, defaultDeps(ctx)); } +export async function genModelRow(ctx: CommandContext): Promise<number> { + const [slot, name] = ctx.positionals; + return modelMain({ ...(slot ? { slot } : {}), ...(name ? { name } : {}) }, { ...defaultDeps(ctx), env: ctx.env }); +} +export async function genLocalCheckRow(ctx: CommandContext): Promise<number> { + const since = typeof ctx.flags.since === "string" ? ctx.flags.since.trim() : undefined; + return localCheckMain({ ...(since !== undefined ? { since } : {}), json: ctx.flags.json === true }, { ...defaultDeps(ctx), env: ctx.env }); +} export async function genRunRow(ctx: CommandContext): Promise<number> { const [task, text] = ctx.positionals; return runMain({ ...(task ? { task } : {}), ...(text ? { text } : {}), flags: ctx.flags }, defaultDeps(ctx)); diff --git a/common/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/frameScan.ts b/common/controller/frameScan.ts @@ -40,7 +40,7 @@ import type { Paths } from "../lib/paths"; import type { GenerationSettings } from "../lib/generationSettings"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import { DRAFT_LOCAL_QUEUE, FRAME_SCAN_QUEUE } from "../lib/queueKeys"; -import { providerOf, unloadOllama } from "../lib/llm"; +import { localOnlyJobRefusal, providerOf, unloadOllama } from "../lib/llm"; import { isSafeChannelSegment, isSafeIdSegment } from "../lib/citations/moments"; import { resolveSavedVideo } from "../lib/savedVideo-server"; import { frameCacheDirOf, frameScanSidecar } from "../lib/frameScan-server"; @@ -259,6 +259,10 @@ export async function enqueueFrameScan(raw: Record<string, unknown>, deps: Frame return refuse((e as Error).message); } const route = providerOf(model); + // LOCAL ONLY (lib/llm/localOnly.ts): refused at the ask with a sentence; + // the API client refuses again before any request. + const localOnly = localOnlyJobRefusal({ models: [model] }, (m) => providerOf(m) === "local"); + if (localOnly) return refuse(localOnly); const capRefusal = async () => (route === "api" ? dailyCapRefusal(await dayUsage(paths.generationUsageFile, utcDay(deps.now?.())), gen.caps.daily) : null); const early = await capRefusal(); if (early) return refuse(early); diff --git a/common/controller/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 @@ -98,15 +98,15 @@ import { CUES_JSON_FILENAME } from "../lib/videoStatus"; import { cueLines, cuesOfDoc, planLookout, type LookoutPlanOptions } from "./lookoutPlan"; import { modelLogged } from "./jobModelLog"; import { readMemAvailableMb } from "./persistVideos"; -import { llmConfigOf } from "./reportDraft"; +import { LOCAL_DRAFT_MIN_FREE_MB, llmConfigOf } from "./reportDraft"; export const LOOKOUT_RUN_JOB_KIND = "lookout-run"; export const LOOKOUT_RUN_RESULT_MARKER = "@@lookout-run "; export const LOOKOUT_TASK = "lookout" as const; /** Reading calls one run may make; past it the run ends `partial` with what it has. */ export const LOOKOUT_MAX_CALLS = 400; -/** The job does not start with less MemAvailable than this (MiB). */ -export const LOOKOUT_MIN_FREE_MB = 3072; +/** The job does not start with less MemAvailable than this (MiB) — 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; /** Render mode is looked at again this often while it holds. */ diff --git a/common/controller/reportDraft.ts b/common/controller/reportDraft.ts @@ -73,7 +73,8 @@ import { getPaths, type Paths } from "../lib/paths"; import { getSettings } from "../lib/settings"; import { GENERATION_TASKS, capFor, isStepTask, type GenerationSettings, type GenerationTask } from "../lib/generationSettings"; import { PROJECT_URL } from "../lib/project"; -import { PRICES, providerOf, unloadOllama, type LlmConfig } from "../lib/llm"; +import { PRICES, isLocalOnly, localOnlyJobRefusal, providerOf, unloadOllama, type LlmConfig } from "../lib/llm"; +import { readMemAvailableMb } from "./persistVideos"; import { webTools } from "../lib/web/tools"; import { copyIteration, @@ -539,6 +540,39 @@ export function projectsRootOf(gen: GenerationSettings): string { return projectsRootFrom(gen.projectsRoot); } +// LOCAL ONLY (lib/llm/localOnly.ts): the refusal for a report-draft job on a +// local-only instance, or null — at the ask, so the job is refused with a +// sentence. It is not the guarantee: the Claude API client, the ollama client +// and the digest's CLI lane refuse at their own last point before any I/O. +export function localOnlyRefusalOf(body: ReportDraftBody, gen: GenerationSettings, env?: Record<string, string | undefined>): string | null { + if (!isLocalOnly(env)) return null; + const task = body.task; + const route = task === REFRESH_TASK ? gen.routes.sweep : task === TRIAGE_DRAFT_TASK ? null : (gen.routes[task as GenerationTask] ?? null); + const models: string[] = []; + if (body.model) models.push(body.model); + else if (task === TRIAGE_DRAFT_TASK) models.push(gen.triage.model === "local" ? gen.models.local : gen.models.extractor); + else if (route === "api") models.push(gen.models.api); + else if (route === "local" && task !== "verdicts") models.push(gen.models.local); + if (body.extractorModel) models.push(body.extractorModel); + return localOnlyJobRefusal( + { models, answers: body.answers !== undefined && body.answers !== null, route: body.model ? null : route }, + (m) => providerOf(m) === "local", + env, + ); +} + +/** A `draft:local` 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 { + const v = (env.LOCAL_MODEL_MIN_FREE_MB ?? "").trim(); + return /^\d+$/.test(v) ? Number(v) : LOCAL_DRAFT_MIN_FREE_MB; +} + // The model a task runs on: the asked one, else the route's. export function modelFor(gen: GenerationSettings, task: GenerationTask, asked?: string): string { if (asked) return asked; @@ -582,6 +616,11 @@ export type ReportDraftDeps = { researchEditor?: ResearchEditor; // An editor job's state (default: the registry and the .jobs sidecars). jobOf?: JobOf; + // MemAvailable in MiB, or null when unknown (default: /proc/meminfo) — the + // local-model floor (LOCAL_DRAFT_MIN_FREE_MB). + memAvailableMb?: () => Promise<number | null>; + // 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. @@ -649,6 +688,8 @@ export async function enqueueReportDraft(raw: Record<string, unknown>, deps: Rep return { result: { ok: false, error: (e as Error).message } }; } const refuse = (error: string) => ({ result: { ok: false as const, error } }); + const localOnly = localOnlyRefusalOf(body, gen); + if (localOnly) return refuse(localOnly); if (body.task === TRIAGE_DRAFT_TASK) { try { const { enqueueTriage } = await import("./reportTriage"); @@ -844,6 +885,43 @@ async function runReportDraft( const gen = (deps.settings ?? getSettings)().generation; const provider = providerOf(model); onLog(`${body.task} of ${body.article} i${n} on ${model} (${provider === "api" ? `the Claude API, cap $${o.maxUsd}` : "the local model"})`); + if (provider === "local") { + // The memory floor (demo epic D5), at the job's turn: a local model's run + // beside a machine already short of memory is what OOM-killed ollama in + // D0. 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 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 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}`); + 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(); + } + onLog(`memory: ${mb ?? "unknown"} MB available — going on`); + } + } if (provider === "api") { // Again at the job's turn: jobs ahead in the queue may have spent the day. const refusal = dailyCapRefusal(await dayUsage(paths.generationUsageFile, utcDay(deps.now?.())), gen.caps.daily); diff --git a/common/controller/reportDraftLocalOnly.test.ts b/common/controller/reportDraftLocalOnly.test.ts @@ -0,0 +1,48 @@ +// The report-draft dispatch's local-only refusal (demo epic D5) and the local +// model's memory floor knob. The end-to-end refusals (no request reaching a +// fake) are editor/app/api/ops/_reportDraft.test.ts's. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { LOCAL_DRAFT_MIN_FREE_MB, localDraftFloorMb, localOnlyRefusalOf, parseReportDraftBody } from "./reportDraft"; +import { GENERATION_PRESETS, sanitizeGeneration } from "../lib/generationSettings"; +import { LOOKOUT_MIN_FREE_MB } from "./lookoutRun"; + +const ON = { ARCHILYZER_LOCAL_ONLY: "1" }; +const local = sanitizeGeneration({ routes: { ...GENERATION_PRESETS.local }, models: { local: "qwen2.5:7b", extractor: "qwen2.5:7b" } }); +const balanced = sanitizeGeneration({}); + +test("off: nothing is refused, whatever the route or model", () => { + const body = parseReportDraftBody({ task: "sweep", article: "a", model: "claude-sonnet-5-5", question: "q", channels: ["c"] }); + assert.equal(localOnlyRefusalOf(body, balanced, {}), null); +}); + +test("on: every task on the local preset passes; a route to code or api is refused by name", () => { + const sweep = parseReportDraftBody({ task: "sweep", article: "a", question: "q", channels: ["c"] }); + assert.equal(localOnlyRefusalOf(sweep, local, ON), null); + assert.match(localOnlyRefusalOf(sweep, balanced, ON)!, /routed to Claude Code/); + const revise = parseReportDraftBody({ task: "revise-report", article: "a", iteration: 1, feedback: "f" }); + assert.match(localOnlyRefusalOf(revise, balanced, ON)!, /"claude-sonnet-5-5" is not a local model/); + const refresh = parseReportDraftBody({ task: "refresh", article: "a" }); + assert.match(localOnlyRefusalOf(refresh, balanced, ON)!, /routed to Claude Code/, "a refresh takes the sweep's route"); + assert.equal(localOnlyRefusalOf(refresh, local, ON), null); +}); + +test("on: a triage on the extractor follows models.extractor", () => { + const triage = parseReportDraftBody({ task: "triage", article: "a", terms: "x", question: "q", channels: ["c"] }); + assert.match(localOnlyRefusalOf(triage, sanitizeGeneration({ triage: { model: "extractor" } }), ON)!, /"claude-haiku-4-5" is not a local model/); + assert.equal(localOnlyRefusalOf(triage, local, ON), null); +}); + +test("on: a Claude Code session's answers are refused even on a local route", () => { + const body = parseReportDraftBody({ task: "propose-groups", project: "/tmp/p", answers: { groups: [] } }); + assert.match(localOnlyRefusalOf(body, local, ON)!, /a Claude Code session's answers are refused/); +}); + +test("the memory floor: 3072 MB by default, LOCAL_MODEL_MIN_FREE_MB overrides it, 0 turns it off; the lookout's is the same", () => { + assert.equal(LOCAL_DRAFT_MIN_FREE_MB, 3072); + assert.equal(LOOKOUT_MIN_FREE_MB, LOCAL_DRAFT_MIN_FREE_MB); + assert.equal(localDraftFloorMb({}), 3072); + assert.equal(localDraftFloorMb({ LOCAL_MODEL_MIN_FREE_MB: "4096" }), 4096); + assert.equal(localDraftFloorMb({ LOCAL_MODEL_MIN_FREE_MB: "0" }), 0); + assert.equal(localDraftFloorMb({ LOCAL_MODEL_MIN_FREE_MB: "lots" }), 3072); +}); diff --git a/common/lib/digestApps.ts b/common/lib/digestApps.ts @@ -28,6 +28,8 @@ import { type DigestLane, } from "./digest"; import "./childKillGuard"; +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 @@ -157,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), @@ -170,6 +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: 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(); @@ -300,6 +308,8 @@ const claudeCode: DigestApp = { fields: { bin: true, model: true }, defaultModel: () => process.env.CLAUDE_DIGEST_MODEL ?? "", async probe(config) { + // LOCAL ONLY: the metered lane is not available, and its CLI is not run. + if (isLocalOnly()) return false; const bin = config.bin?.trim() || getPaths().claudeBin; try { const res = await execa(bin, ["--version"], { @@ -313,6 +323,8 @@ const claudeCode: DigestApp = { } }, async run({ system, prompt, schema, config, signal, onLog }) { + // LOCAL ONLY: refused before the `claude` CLI is started. + assertLocalOnlyAllowsClaudeCli(); const bin = config.bin?.trim() || getPaths().claudeBin; const model = config.model?.trim() || claudeCode.defaultModel(); const startedAt = Date.now(); diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts @@ -136,6 +136,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 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/generationSettings.ts b/common/lib/generationSettings.ts @@ -193,7 +193,7 @@ export const GENERATION_SETTINGS_FIELD_DOCS: FieldDocs<GenerationSettings> = { anthropicBaseUrl: "Advanced: the Messages API's base URL. Blank = Anthropic's. Tests point it at a fake.", ollamaUrl: "The local model's server (ollama). Blank = the editor's `OLLAMA_URL` (the digest lane's server, default http://127.0.0.1:11434).", projectsRoot: - "Where an iteration's video project and renders live: `<projectsRoot>/<article>/i<n>/`, off the corpus disk (D1). Blank = `~/reports/articles`.", + "Where an iteration's video project and renders live: `<projectsRoot>/<article>/i<n>/`, off the corpus disk (D1). Blank = `<REPORTS_DIR>/articles` when REPORTS_DIR is set (a container's reports volume: `/data/reports/articles`), else `~/reports/articles` (common/lib/projectsRoot.mjs).", web: "The web an agent may read for context (below). Read-only and paced: one request at a time, 3 s apart.", citationOrigin: "The origin a generated report's moment links cite when its corpus build's site has no public URL (a private build). Blank = the project site.", diff --git a/common/lib/llm/anthropic.ts b/common/lib/llm/anthropic.ts @@ -21,6 +21,7 @@ import { readFileSync, statSync } from "node:fs"; import os from "node:os"; import type { CacheTtl } from "./prices"; import type { Meter, Usage } from "./meter"; +import { assertLocalOnlyAllowsApi } from "./localOnly"; export type AnthropicConfig = { apiKeyFile?: string; @@ -248,6 +249,10 @@ export class AnthropicClient { #key: string | undefined; constructor(cfg: AnthropicConfig) { + // LOCAL ONLY (./localOnly.ts): refused before anything — no key read, no + // request. Read from process.env, never cfg.env (that one is the KEY's + // environment, and is {} for a non-Anthropic base URL). + assertLocalOnlyAllowsApi(); this.#cfg = cfg; this.cacheTtl = cfg.cacheTtl ?? "5m"; this.maxRetries = cfg.maxRetries ?? DEFAULT_MAX_RETRIES; @@ -285,6 +290,9 @@ export class AnthropicClient { body: Record<string, unknown>, o: { meter?: Meter; signal?: AbortSignal } = {}, ): Promise<MessagesResponse> { + // Again here, the last point before the network (a client made before the + // flag was set is refused too). + assertLocalOnlyAllowsApi(); const key = this.key(); let sent = prepareBody(body, this.cacheTtl); const doFetch = this.#cfg.fetch ?? fetch; diff --git a/common/lib/llm/index.ts b/common/lib/llm/index.ts @@ -13,3 +13,4 @@ export * from "./agent"; export * from "./callLog"; export * from "./callLog-server"; export * from "./callLogView"; +export * from "./localOnly"; diff --git a/common/lib/llm/localOnly.test.ts b/common/lib/llm/localOnly.test.ts @@ -0,0 +1,263 @@ +// ARCHILYZER_LOCAL_ONLY (demo epic D5): every path a model call leaves the +// machine by is refused BEFORE its I/O — a fake fetch, or a fake `claude` +// binary that leaves a marker file, must never be reached. And with the flag +// unset each path does exactly what it did before (the fake IS reached). +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { existsSync } from "node:fs"; +import { chmod, mkdtemp, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { + AnthropicClient, + LocalOnlyError, + Meter, + isCloudOllamaModel, + isLocalModelUrl, + isLocalOnly, + localOnlyFlag, + localOnlyJobRefusal, + localOnlyRoutesRefusal, + localOnlySettingsRefusal, + LOCAL_ONLY_CLAIM, + ollamaChat, + resetLocalOllamaChecks, + unloadOllama, + providerOf, + runAgent, + structuredAnswer, +} from "./index"; +import { plainAnswer } from "../report/draft/tasks/llmText"; +import { getDigestApp } from "../digestApps"; +import { CLAUDE_DIGEST_APP_ID, OLLAMA_DIGEST_APP_ID } from "../digest"; + +const ON = { ARCHILYZER_LOCAL_ONLY: "1" }; + +async function withFlag<T>(value: string | undefined, body: () => Promise<T>): Promise<T> { + const was = process.env.ARCHILYZER_LOCAL_ONLY; + if (value === undefined) delete process.env.ARCHILYZER_LOCAL_ONLY; + else process.env.ARCHILYZER_LOCAL_ONLY = value; + try { + return await body(); + } finally { + if (was === undefined) delete process.env.ARCHILYZER_LOCAL_ONLY; + else process.env.ARCHILYZER_LOCAL_ONLY = was; + } +} + +// A fetch that counts its calls and answers like a server that refuses (the +// unset case only needs to show the request was SENT). +// `/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) => { + const u = String(url); + if (u.endsWith("/api/show")) { + shows.push(u); + return typeof show === "number" ? new Response("{}", { status: show }) : new Response(JSON.stringify(show), { status: 200 }); + } + calls.push(u); + return new Response(JSON.stringify({ error: "fake" }), { status: 500, headers: { "content-type": "application/json" } }); + }) as typeof fetch; + return { f, calls, shows }; +} + +async function withEnv<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 () => {} }); + +test("the flag: 1/true/yes/on, anything else off; an ollama cloud tag", () => { + for (const v of ["1", "true", "YES", " on "]) assert.equal(isLocalOnly({ ARCHILYZER_LOCAL_ONLY: v }), true, v); + for (const v of [undefined, "", "0", "false", "off", "local"]) assert.equal(isLocalOnly({ ARCHILYZER_LOCAL_ONLY: v }), false, String(v)); + for (const m of ["gpt-oss:120b-cloud", "qwen3-coder:480b-cloud", "kimi-k2:1t-cloud", "x:cloud"]) assert.equal(isCloudOllamaModel(m), true, m); + for (const m of ["qwen2.5:7b", "qwen3:8b", "cloud", "cloudy:7b", "gemma2:9b-cloudless"]) assert.equal(isCloudOllamaModel(m), false, m); +}); + +test("the Claude API client: refused at construction and at messages(), before any request", async () => { + const { f, calls } = countingFetch(); + const early = new AnthropicClient(anthropic(f)); // made before the flag + await withFlag("1", async () => { + assert.throws(() => new AnthropicClient(anthropic(f)), LocalOnlyError); + await assert.rejects(early.messages({ model: "claude-sonnet-5-5", max_tokens: 8, messages: [] }), /local only \(ARCHILYZER_LOCAL_ONLY=1\): a call to the Claude API is refused/); + }); + assert.equal(calls.length, 0, "no request was sent"); + // Unset: the same client sends (the fake answers 500). + await withFlag(undefined, async () => { + await assert.rejects(early.messages({ model: "claude-sonnet-5-5", max_tokens: 8, messages: [] })); + }); + assert.equal(calls.length, 1, "unset, the request is sent as before"); +}); + +test("structuredAnswer, plainAnswer and runAgent on a Claude model: refused, the fake never called", async () => { + const { f, calls } = countingFetch(); + const llm = { anthropic: anthropic(f) }; + const ask = { llm, model: "claude-sonnet-5-5", system: "s", user: "u" }; + await withFlag("1", async () => { + await assert.rejects(structuredAnswer({ ...ask, schema: { type: "object" } }), LocalOnlyError); + await assert.rejects(plainAnswer({ ...ask, meter: new Meter() }), LocalOnlyError); + await assert.rejects(runAgent({ ...ask, tools: [], meter: new Meter() }), LocalOnlyError); + }); + assert.equal(calls.length, 0); +}); + +const hi = (model: string) => ({ model, messages: [{ role: "user", content: "hi" }] }); + +test("the ollama client: a cloud model refused before the request; a local model is asked", async () => { + resetLocalOllamaChecks(); + const { f, calls } = countingFetch(); + const cfg = { baseUrl: "http://127.0.0.1:11434", fetch: f }; + await withFlag("1", async () => { + await assert.rejects(ollamaChat(cfg, hi("gpt-oss:120b-cloud")), /the ollama cloud model "gpt-oss:120b-cloud" is refused/); + assert.equal(calls.length, 0); + await assert.rejects(ollamaChat(cfg, hi("qwen2.5:7b")), /ollama returned 500/); + }); + assert.equal(calls.length, 1, "the local model's request went out"); + await withFlag(undefined, async () => { + await assert.rejects(ollamaChat(cfg, hi("gpt-oss:120b-cloud")), /ollama returned 500/); + }); + assert.equal(calls.length, 2, "unset, a cloud tag is sent as before"); +}); + +test("'local' is a host: loopback or ARCHILYZER_LOCAL_MODEL_HOSTS; anything else is refused before any request (M2)", async () => { + resetLocalOllamaChecks(); + const { f, calls, shows } = countingFetch(); + await withEnv({ ARCHILYZER_LOCAL_ONLY: "1", ARCHILYZER_LOCAL_MODEL_HOSTS: undefined }, async () => { + for (const far of ["https://ollama-proxy.cloud.example", "http://ollama:11434", "http://192.168.1.20:11434", "http://10.0.0.5:11434"]) { + await assert.rejects(ollamaChat({ baseUrl: far, fetch: f }, hi("qwen2.5:7b")), /the ollama server at .* is not on this machine/, far); + await assert.rejects(unloadOllama({ baseUrl: far, fetch: f }, "qwen2.5:7b"), /is not on this machine/, far); + } + assert.equal(calls.length + shows.length, 0, "nothing was sent anywhere"); + for (const here of ["http://127.0.0.1:11434", "http://127.3.4.5:1", "http://localhost:11434", "http://[::1]:11434"]) { + assert.equal(isLocalModelUrl(here), true, here); + } + }); + await withEnv({ ARCHILYZER_LOCAL_ONLY: "1", ARCHILYZER_LOCAL_MODEL_HOSTS: "ollama" }, async () => { + await assert.rejects(ollamaChat({ baseUrl: "http://ollama:11434", fetch: f }, hi("qwen2.5:7b")), /ollama returned 500/); + assert.equal(calls.length, 1, "the compose service host the demo names is asked"); + assert.equal(isLocalModelUrl("http://ollama.evil.example:11434"), false, "an exact name, not a prefix"); + }); +}); + +test("a cloud model behind a local alias: /api/show naming a remote host refuses; an unreadable show refuses; a good one is asked once per process (S5)", async () => { + await withFlag("1", async () => { + resetLocalOllamaChecks(); + const remote = countingFetch({ remote_host: "https://ollama.com:443", remote_model: "gpt-oss:120b", details: {} }); + await assert.rejects(ollamaChat({ baseUrl: "http://127.0.0.1:11434", fetch: remote.f }, hi("my-alias:latest")), /"my-alias:latest" is served from a remote host \(its \/api\/show says so\)/); + assert.equal(remote.calls.length, 0); + resetLocalOllamaChecks(); + const down = countingFetch(503); + await assert.rejects(ollamaChat({ baseUrl: "http://127.0.0.1:11434", fetch: down.f }, hi("qwen2.5:7b")), /could not confirm that "qwen2.5:7b" runs on this machine \(\/api\/show answered 503\)/); + assert.equal(down.calls.length, 0); + resetLocalOllamaChecks(); + const ok = countingFetch(); + for (let i = 0; i < 3; i++) await assert.rejects(ollamaChat({ baseUrl: "http://127.0.0.1:11434", fetch: ok.f }, hi("qwen2.5:7b")), /ollama returned 500/); + assert.equal(ok.shows.length, 1, "asked once per server and model"); + assert.equal(ok.calls.length, 3); + }); + // Unset: no show is asked at all. + resetLocalOllamaChecks(); + const off = countingFetch(); + await withFlag(undefined, async () => { + await assert.rejects(ollamaChat({ baseUrl: "http://ollama.lan:11434", fetch: off.f }, hi("qwen2.5:7b")), /ollama returned 500/); + }); + assert.equal(off.shows.length, 0); +}); + +test("the flag's values: one parser; a value it does not understand is off AND said so (S7)", () => { + for (const v of ["1", " TRUE ", "yes", "On"]) assert.deepEqual([localOnlyFlag({ ARCHILYZER_LOCAL_ONLY: v }).on, localOnlyFlag({ ARCHILYZER_LOCAL_ONLY: v }).understood], [true, true], v); + for (const v of [undefined, "", "0", "false", "NO", "off"]) assert.deepEqual([localOnlyFlag({ ARCHILYZER_LOCAL_ONLY: v }).on, localOnlyFlag({ ARCHILYZER_LOCAL_ONLY: v }).understood], [false, true], String(v)); + for (const v of ["2", "y", "enabled", "local"]) assert.deepEqual([localOnlyFlag({ ARCHILYZER_LOCAL_ONLY: v }).on, localOnlyFlag({ ARCHILYZER_LOCAL_ONLY: v }).understood], [false, false], v); +}); + +test("a settings write: a route off local, a non-local generation.ollamaUrl or digest baseUrl refused; untouched keys are not judged (M2)", () => { + const ON2 = { ARCHILYZER_LOCAL_ONLY: "1" }; + const merged = (gen: Record<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 { + const marker = path.join(dir, "ran"); + const bin = path.join(dir, "fake-claude.sh"); + await writeFile(bin, `#!/bin/sh\ntouch '${marker}'\necho '{"result":"{}"}'\n`); + await chmod(bin, 0o755); + const claude = getDigestApp(CLAUDE_DIGEST_APP_ID); + assert.equal(claude.id, CLAUDE_DIGEST_APP_ID); + const input = { system: "s", prompt: "p", schema: { type: "object" }, config: { bin } }; + await withFlag("1", async () => { + await assert.rejects(claude.run(input as never), /the Claude Code CLI \(the digest's metered lane\) is refused/); + assert.equal(await claude.probe!({ bin } as never), false); + }); + assert.equal(existsSync(marker), false, "the CLI was never started"); + // Unset: the same lane runs the binary. + await withFlag(undefined, async () => { + await claude.run(input as never).catch(() => {}); + }); + assert.equal(existsSync(marker), true, "unset, the CLI runs as before"); + + const ollama = getDigestApp(OLLAMA_DIGEST_APP_ID); + const realFetch = globalThis.fetch; + const { f, calls } = countingFetch(); + globalThis.fetch = f; + try { + await withFlag("1", async () => { + await assert.rejects(ollama.run({ system: "s", prompt: "p", schema: {}, config: { baseUrl: "http://127.0.0.1:11434", model: "deepseek-v3.1:671b-cloud" } } as never), LocalOnlyError); + // An LLM worker's (or digest.apps') baseUrl elsewhere: neither run nor probe asks it. + await assert.rejects(ollama.run({ system: "s", prompt: "p", schema: {}, config: { baseUrl: "http://gpu-box.lan:11434", model: "qwen2.5:7b" } } as never), /the ollama server at gpu-box\.lan is not on this machine/); + assert.equal(await ollama.probe!({ baseUrl: "http://gpu-box.lan:11434" } as never), false); + }); + } finally { + globalThis.fetch = realFetch; + } + assert.equal(calls.length, 0); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("a job's refusal: answers, the code route, a Claude or cloud model; local passes; off is always null", () => { + const isLocal = (m: string) => providerOf(m) === "local"; + assert.match(localOnlyJobRefusal({ models: [], answers: true }, isLocal, ON)!, /a Claude Code session's answers are refused/); + assert.match(localOnlyJobRefusal({ models: [], route: "code" }, isLocal, ON)!, /routed to Claude Code/); + assert.match(localOnlyJobRefusal({ models: ["qwen3:8b", "claude-haiku-4-5"] }, isLocal, ON)!, /"claude-haiku-4-5" is not a local model/); + assert.match(localOnlyJobRefusal({ models: ["gpt-oss:120b-cloud"] }, isLocal, ON)!, /ollama cloud model/); + assert.equal(localOnlyJobRefusal({ models: ["qwen2.5:7b", null, undefined] }, isLocal, ON), null); + assert.equal(localOnlyJobRefusal({ models: ["claude-sonnet-5-5"], answers: true, route: "code" }, isLocal, {}), null); +}); + +test("a settings write: any route but local refused under the flag, nothing refused without it", () => { + assert.equal(localOnlyRoutesRefusal({ sweep: "local", narrate: "local" }, ON), null); + assert.match(localOnlyRoutesRefusal({ sweep: "code", narrate: "local", frames: "api" }, ON)!, /not saved: sweep → code, frames → api/); + assert.equal(localOnlyRoutesRefusal({ sweep: "api" }, {}), null); + assert.equal(localOnlyRoutesRefusal(null, ON), null); +}); + +test("the claim the docs make is the one this module states (ENVIRONMENT.md's row quotes LOCAL_ONLY_CLAIM)", async () => { + const { ENV_VARS } = await import("../envVars"); + const row = ENV_VARS.find((v) => v.name === "ARCHILYZER_LOCAL_ONLY"); + assert.ok(row?.doc.includes(LOCAL_ONLY_CLAIM), "ENVIRONMENT.md states the claim word for word"); +}); diff --git a/common/lib/llm/localOnly.ts b/common/lib/llm/localOnly.ts @@ -0,0 +1,215 @@ +// LOCAL ONLY (demo epic D5). THE CLAIM, exactly as enforced (the docs quote +// 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. +// +// 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). + +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 { + 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(what.startsWith(LOCAL_ONLY_WHY) ? what : `${LOCAL_ONLY_WHY}: ${what} is refused`); + this.name = "LocalOnlyError"; + } +} + +/** + * An ollama model name that runs on ollama's hosted service rather than on + * this machine: its tag is `cloud` or ends in `-cloud` (`gpt-oss:120b-cloud`, + * `qwen3-coder:480b-cloud`, `kimi-k2:1t-cloud`). + */ +export function isCloudOllamaModel(model: string): boolean { + const tag = model.trim().toLowerCase().split(":").slice(1).join(":"); + return tag === "cloud" || tag.endsWith("-cloud"); +} + +/** Throws before the Claude API is asked anything. */ +export function assertLocalOnlyAllowsApi(env?: Env): void { + if (isLocalOnly(env)) throw new LocalOnlyError("a call to the Claude API"); +} + +/** Throws before the `claude` CLI (the digest's metered lane) is started. */ +export function assertLocalOnlyAllowsClaudeCli(env?: Env): void { + if (isLocalOnly(env)) throw new LocalOnlyError("the Claude Code CLI (the digest's metered lane)"); +} + +/** Throws before an ollama model that is not on this machine is asked. */ +export function assertLocalOnlyAllowsOllamaModel(model: string, env?: Env): void { + if (isLocalOnly(env) && isCloudOllamaModel(model)) throw new LocalOnlyError(`the ollama cloud model "${model}"`); +} + +/** + * The refusal for a generation job, or null: on a local-only instance a job + * runs on a local model only and takes no Claude Code session's answers. + * `models` are every model the job would run on (its model, an extractor); + * `isLocal` says whether one is local (providerOf). + */ +export function localOnlyJobRefusal( + o: { models: readonly (string | null | undefined)[]; answers?: boolean; route?: string | null }, + isLocal: (model: string) => boolean, + env?: Env, +): string | null { + if (!isLocalOnly(env)) return null; + if (o.answers) return `${LOCAL_ONLY_WHY}: a Claude Code session's answers are refused`; + if (o.route === "code") return `${LOCAL_ONLY_WHY}: the task is routed to Claude Code — route it to local (\`archilyzer gen preset local\`)`; + for (const m of o.models) { + if (!m) continue; + if (!isLocal(m)) return `${LOCAL_ONLY_WHY}: "${m}" is not a local model — run it on the local model`; + if (isCloudOllamaModel(m)) return `${LOCAL_ONLY_WHY}: "${m}" is an ollama cloud model`; + } + return null; +} + +/** + * The refusal for a settings write on a local-only instance, or null: a + * generation route other than `local`. + */ +export function localOnlyRoutesRefusal(routes: Record<string, unknown> | null | undefined, env?: Env): string | null { + if (!isLocalOnly(env) || !routes) return null; + const off = Object.entries(routes).filter(([, r]) => r !== "local").map(([t, r]) => `${t} → ${String(r)}`); + return off.length ? `${LOCAL_ONLY_WHY}: every generation route stays local — not saved: ${off.join(", ")}` : null; +} + +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,6 +9,8 @@ // unless the caller asks for thinking. // `digestApps.ts`'s `ollamaDirect` is the digest's own call and is left as it is. +import { LOCAL_ONLY_WHY, LocalOnlyError, assertLocalOnlyAllowsEndpoint, assertLocalOnlyAllowsOllamaModel, isLocalOnly, showNamesRemote } from "./localOnly"; + export type OllamaConfig = { baseUrl: string; numCtx?: number; @@ -107,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 ?? "" }; @@ -142,6 +187,10 @@ export async function ollamaChat( signal?: AbortSignal; }, ): Promise<{ message: OllamaMessage; promptTokens: number; evalTokens: number }> { + // 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); @@ -198,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 @@ -0,0 +1,73 @@ +# The LOCAL-ONLY demo overlay (demo epic D5). `./docker/demo.sh up` applies it; +# by hand: +# +# docker compose -p archilyzer-demo --env-file .env.demo \ +# -f docker-compose.yml -f docker-compose.demo.yml [-f docker-compose.ollama-vulkan.yml] \ +# --profile umtool --profile ollama up -d +# +# What it changes, and nothing else: +# +# * 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). +# * The apps reach the `ollama` service (profile `ollama`), which runs with +# bounds: one request and one model at a time, no cloud models, a capped +# 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 (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 + depends_on: + ollama: + condition: service_started + + 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 + + ollama: + # A wrapper that prints one honest line about the GPU, then execs + # `ollama serve` (docker/ollama-start.sh). + entrypoint: ["/bin/sh", "/etc/archilyzer/ollama-start.sh"] + volumes: + - ./docker:/etc/archilyzer:ro + environment: + # Ollama's hosted models are not this machine's: off. + OLLAMA_NO_CLOUD: "1" + # One request and one loaded model at a time (an 8 GB card holds one 7B). + OLLAMA_NUM_PARALLEL: "1" + OLLAMA_MAX_LOADED_MODELS: "1" + OLLAMA_KEEP_ALIVE: ${DEMO_OLLAMA_KEEP_ALIVE:-2m} + # llama.cpp's prompt cache (llama-server --cache-ram, default 8192 MiB): + # it grew to 8-11 GB of host RAM in D0 and was OOM-killed twice. + LLAMA_ARG_CACHE_RAM: ${DEMO_OLLAMA_CACHE_RAM_MIB:-1024} + # The backstop: ollama dies in its own cgroup, not the desktop session. + # memswap_limit equal to mem_limit = no swap on top. + mem_limit: ${DEMO_OLLAMA_MEM:-6g} + memswap_limit: ${DEMO_OLLAMA_MEM:-6g} diff --git a/docker-compose.ollama-nvidia.yml b/docker-compose.ollama-nvidia.yml @@ -0,0 +1,15 @@ +# ollama ALONE on an NVIDIA GPU (the NVIDIA container toolkit on the host): +# the editor's image is not retargeted (docker-compose.gpu.yml does that, and +# gives ollama the same block). `./docker/demo.sh up --gpu nvidia` adds this. +# +# docker compose -f docker-compose.yml -f docker-compose.ollama-nvidia.yml --profile ollama up -d + +services: + ollama: + deploy: + resources: + reservations: + devices: + - driver: nvidia + count: all + capabilities: [gpu] diff --git a/docker-compose.ollama-vulkan.yml b/docker-compose.ollama-vulkan.yml @@ -0,0 +1,16 @@ +# ollama ALONE on the GPU through Vulkan (AMD, Intel, NVIDIA): the render node +# and ollama's opt-in Vulkan backend, and nothing else — the editor's image is +# not retargeted (docker-compose.vulkan.yml does that, and gives ollama the +# same block). `./docker/demo.sh up` adds this when /dev/dri has a render node. +# +# docker compose -f docker-compose.yml -f docker-compose.ollama-vulkan.yml --profile ollama up -d +# +# Check what it found: `docker compose logs ollama | grep "inference compute"` +# names the device (library=Vulkan), or says library=cpu. + +services: + ollama: + devices: + - /dev/dri:/dev/dri + environment: + OLLAMA_VULKAN: "1" 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 @@ -0,0 +1,705 @@ +#!/bin/sh +# ONE COMMAND to a LOCAL-ONLY Archilyzer (demo epic D5): the editor and umtool in +# Docker, connected to a published archive as a source, every AI task on a local +# model (ollama), and the Claude API refused — provably (`check`). +# +# ./docker/demo.sh up [--archive <url>] [--model <name>] [--gpu auto|vulkan|nvidia|none] +# [--editor-port N] [--umtool-port N] [--site-port N] [--homepage-port N] +# [--rebuild] [--dry-run] +# ./docker/demo.sh down [--volumes] [--dry-run] +# ./docker/demo.sh status +# ./docker/demo.sh check the local-only proof (exit 1 when it fails) +# ./docker/demo.sh voice install the Orpheus voice (about 4 GB, once) +# +# It needs docker and compose v2 on the host — no Node, no pnpm. Everything it +# does is printed, one line per step; `--dry-run` prints the plan and writes and +# starts nothing (it only asks docker for its version, df, /proc/meminfo and +# /dev/dri). A missing prerequisite ends it with one sentence and exit 1. +# +# Idempotent: .env.demo (mode 600, gitignored) is written on the first `up` with +# a random WORKER_TOKEN and the choices; a later `up` reuses it and changes only +# what a flag names. Images are built only when missing (or with --rebuild); a +# model already pulled is not pulled again; settings already local are left. +# `down` never deletes a volume without --volumes. +# +# Nothing is bound off loopback: Caddy is the only front door, on 127.0.0.1 +# (docker-compose.yml), and docker/guard-exposure.sh is unchanged. No secret is +# asked for; the Claude API overlay is never part of this stack. +# +# POSIX sh: no bashisms (dash, busybox). +set -eu + +# 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}" +DEFAULT_ARCHIVE="https://jeralyzer.pages.dev" +DEFAULT_MODEL="qwen2.5:7b" +MIN_RAM_GB=12 +MIN_FREE_GB=25 +HOST_OLLAMA_URL="${DEMO_HOST_OLLAMA_URL:-http://127.0.0.1:11434}" +DRI_DIR="${DEMO_TEST_DRI_DIR:-/dev/dri}" +MEMINFO="${DEMO_TEST_MEMINFO:-/proc/meminfo}" + +say() { printf 'demo: %s\n' "$*"; } +refuse() { + printf 'demo: %s\n' "$*" >&2 + exit 1 +} + +usage() { + cat <<'EOF' +./docker/demo.sh up [--archive <url>] [--model <name>] [--gpu auto|vulkan|nvidia|none] + [--editor-port N] [--umtool-port N] [--site-port N] [--homepage-port N] + [--rebuild] [--dry-run] +./docker/demo.sh down [--volumes] [--dry-run] +./docker/demo.sh status +./docker/demo.sh check the local-only proof (exit 1 when it fails) +./docker/demo.sh voice install the Orpheus voice (about 4 GB, once) +EOF +} + +# ─── arguments ─── + +VERB="${1:-}" +[ $# -gt 0 ] && shift +case "${VERB}" in +up | down | status | check | voice) ;; +-h | --help | help | "") + usage + exit 0 + ;; +*) 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="" +GPU="" +EDITOR_PORT="" +UMTOOL_PORT="" +SITE_PORT="" +HOMEPAGE_PORT="" +REBUILD=0 +DRY=0 +VOLUMES=0 + +need_value() { + [ $# -ge 2 ] && [ -n "$2" ] || refuse "$1 needs a value." +} + +while [ $# -gt 0 ]; do + case "$1" in + --archive) need_value "$@"; ARCHIVE="$2"; shift 2 ;; + --model) need_value "$@"; MODEL="$2"; shift 2 ;; + --gpu) need_value "$@"; GPU="$2"; shift 2 ;; + --editor-port) need_value "$@"; EDITOR_PORT="$2"; shift 2 ;; + --umtool-port) need_value "$@"; UMTOOL_PORT="$2"; shift 2 ;; + --site-port) need_value "$@"; SITE_PORT="$2"; shift 2 ;; + --homepage-port) need_value "$@"; HOMEPAGE_PORT="$2"; shift 2 ;; + --rebuild) REBUILD=1; shift ;; + --dry-run) DRY=1; shift ;; + --volumes) VOLUMES=1; shift ;; + *) refuse "unknown flag \"$1\" for ${VERB} — see ./docker/demo.sh --help." ;; + esac +done + +if [ "${VERB}" != "up" ]; then + for v in "${ARCHIVE}" "${MODEL}" "${GPU}" "${EDITOR_PORT}" "${UMTOOL_PORT}" "${SITE_PORT}" "${HOMEPAGE_PORT}"; do + [ -z "$v" ] || refuse "only up takes --archive, --model, --gpu and the port flags." + done + [ "${REBUILD}" = 0 ] || refuse "only up takes --rebuild." +fi +[ "${VOLUMES}" = 0 ] || [ "${VERB}" = "down" ] || refuse "only down takes --volumes." + +# ─── .env.demo: the choices, kept between runs ─── + +env_get() { + [ -f "${ENV_FILE}" ] || return 0 + 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)" +[ -n "${MODEL}" ] || MODEL="${DEFAULT_MODEL}" +[ -n "${GPU}" ] || GPU="$(env_get DEMO_GPU_ASKED)" +[ -n "${GPU}" ] || GPU="auto" +[ -n "${EDITOR_PORT}" ] || EDITOR_PORT="$(env_get EDITOR_HTTP_PORT)" +[ -n "${EDITOR_PORT}" ] || EDITOR_PORT=8081 +[ -n "${UMTOOL_PORT}" ] || UMTOOL_PORT="$(env_get UMTOOL_HTTP_PORT)" +[ -n "${UMTOOL_PORT}" ] || UMTOOL_PORT=8083 +[ -n "${SITE_PORT}" ] || SITE_PORT="$(env_get SITE_HTTP_PORT)" +[ -n "${SITE_PORT}" ] || SITE_PORT=8080 +[ -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 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 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 +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." ;; +esac +for p in "${EDITOR_PORT}" "${UMTOOL_PORT}" "${SITE_PORT}" "${HOMEPAGE_PORT}"; do + 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." + 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}" + major="${cv%%.*}" + rest="${cv#*.}" + minor="${rest%%.*}" + case "${major}${minor}" in + '' | *[!0-9]*) refuse "docker compose answered an unreadable version (\"${cv}\") — compose v2.24 or newer is needed." ;; + esac + if [ "${major}" -lt 2 ] || { [ "${major}" -eq 2 ] && [ "${minor}" -lt 24 ]; }; then + refuse "docker compose ${cv} is too old — the demo needs compose v2.24 or newer." + fi + COMPOSE_VERSION="${cv}" + DOCKER_VERSION="$(docker version --format '{{.Server.Version}}' 2>/dev/null || echo '?')" +} + +ram_gb() { + if [ -r "${MEMINFO}" ]; then + kb="$(sed -n 's/^MemTotal:[[:space:]]*\([0-9]*\) kB/\1/p' "${MEMINFO}")" + # Rounded, not floored: a "16 GB" machine's MemTotal is about 15.6 GiB. + [ -n "${kb}" ] && echo $(((kb + 524288) / 1048576)) && return 0 + fi + if command -v sysctl >/dev/null 2>&1; then + b="$(sysctl -n hw.memsize 2>/dev/null || true)" + [ -n "${b}" ] && echo $(((b + 536870912) / 1073741824)) && return 0 + fi + echo "" +} + +free_gb() { + if [ -n "${DEMO_TEST_FREE_KB:-}" ]; then + echo $((DEMO_TEST_FREE_KB / 1048576)) + return 0 + fi + root="$(docker info --format '{{.DockerRootDir}}' 2>/dev/null || true)" + kb="$(df -Pk "${root:-.}" 2>/dev/null | awk 'NR==2 {print $4}' || true)" + [ -n "${kb}" ] || kb="$(df -Pk . 2>/dev/null | awk 'NR==2 {print $4}' || true)" + [ -n "${kb}" ] && echo $((kb / 1048576)) || echo "" +} + +# A port something already listens on (ss, else netstat; DEMO_TEST_BUSY_PORTS +# in tests). Our own stack's ports are not "taken": a re-run finds them bound. +port_busy() { + if [ -n "${DEMO_TEST_BUSY_PORTS+x}" ]; then + case " ${DEMO_TEST_BUSY_PORTS} " in *" $1 "*) return 0 ;; esac + return 1 + fi + if command -v ss >/dev/null 2>&1; then + ss -Hltn 2>/dev/null | awk '{print $4}' | grep -Eq "[:.]$1\$" + return $? + fi + if command -v netstat >/dev/null 2>&1; then + netstat -ltn 2>/dev/null | awk '{print $4}' | grep -Eq "[:.]$1\$" + return $? + fi + return 1 +} + +stack_running() { + [ -n "${DEMO_TEST_STACK_RUNNING:-}" ] && return 0 + [ -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) + GPU_USED="${GPU}" + return 0 + ;; + esac + for n in "${DRI_DIR}"/renderD*; do + if [ -e "$n" ]; then + GPU_USED=vulkan + GPU_NODE="${n}" + return 0 + fi + done + if command -v nvidia-smi >/dev/null 2>&1 && docker info 2>/dev/null | grep -qi nvidia; then + GPU_USED=nvidia + return 0 + fi + GPU_USED=none +} + +# A host ollama answering with a model loaded: two servers would share the +# card. Asked with GET /api/ps, which loads nothing. A warning, never a refusal. +check_host_ollama() { + ps_json="" + if command -v curl >/dev/null 2>&1; then + ps_json="$(curl -fsS -m 2 "${HOST_OLLAMA_URL}/api/ps" 2>/dev/null || true)" + elif command -v wget >/dev/null 2>&1; then + ps_json="$(wget -q -T 2 -O - "${HOST_OLLAMA_URL}/api/ps" 2>/dev/null || true)" + else + say "host ollama: not checked (no curl or wget on this machine)" + return 0 + fi + [ -n "${ps_json}" ] || return 0 + loaded="$(printf '%s' "${ps_json}" | tr ',' '\n' | sed -n 's/.*"name":"\([^"]*\)".*/\1/p' | head -n 3 | tr '\n' ' ')" + if [ -n "${loaded}" ]; then + say "WARNING: a host ollama at ${HOST_OLLAMA_URL} has ${loaded}loaded — two servers would share the GPU; unload it first (ollama stop <model>)" + else + say "host ollama: answering at ${HOST_OLLAMA_URL} with no model loaded (stop it while the demo runs, so two servers never share the GPU)" + fi +} + +# ─── compose ─── + +overlays() { + o="-f docker-compose.yml -f docker-compose.demo.yml" + case "${GPU_USED:-none}" in + vulkan) o="${o} -f docker-compose.ollama-vulkan.yml" ;; + nvidia) o="${o} -f docker-compose.ollama-nvidia.yml" ;; + esac + printf '%s' "${o}" +} + +compose_args() { + # The env file once there is one (`up` writes it before its first compose + # call; a dry run prints the commands as they will be). + if [ -f "${ENV_FILE}" ] || [ "${VERB}" = "up" ]; then + printf '%s' "-p ${PROJECT} --env-file ${ENV_FILE} $(overlays) --profile umtool --profile ollama" + else + printf '%s' "-p ${PROJECT} $(overlays) --profile umtool --profile ollama" + fi +} + +# Run a docker command, or print it under --dry-run. The words are split on +# spaces on purpose (every argument here is space-free: the model name and the +# ports are checked above); a JSON argument goes through `ops_json`. +run() { + if [ "${DRY}" = 1 ]; then + printf ' would run: docker %s\n' "$*" + return 0 + fi + # shellcheck disable=SC2086 + docker $* +} + +compose() { + # shellcheck disable=SC2046 + 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() { + if [ "${DRY}" = 1 ]; then + printf " would run: docker compose %s exec -T editor pnpm --silent ops %s --json '%s'\n" "$(compose_args)" "$1" "$2" + return 0 + fi + # shellcheck disable=SC2046 + docker compose $(compose_args) exec -T editor pnpm --silent ops "$1" --json "$2" +} + +new_token() { + if [ -r /dev/urandom ]; then + od -An -tx1 -N24 /dev/urandom | tr -d ' \n' + else + date +%s%N | sha256sum | cut -c1-48 + fi +} + +write_env() { + token="${prev_token:-$(new_token)}" + old="$(cat "${ENV_FILE}" 2>/dev/null || true)" + # DEMO_OLLAMA_MEM: 40% of RAM, at most 8 GB, at least 4. + mem=$((RAM_GB * 4 / 10)) + [ "${mem}" -gt 8 ] && mem=8 + [ "${mem}" -lt 4 ] && mem=4 + next="# Written by ./docker/demo.sh (demo epic D5). Kept between runs; a flag changes its line. +WORKER_TOKEN=${token} +DEMO_ARCHIVE=${ARCHIVE} +DEMO_MODEL=${MODEL} +DEMO_GPU_ASKED=${GPU} +DEMO_OLLAMA_MEM=${mem}g +ARCHILYZER_TAG=demo +EDITOR_HTTP_PORT=${EDITOR_PORT} +UMTOOL_HTTP_PORT=${UMTOOL_PORT} +SITE_HTTP_PORT=${SITE_PORT} +HOMEPAGE_HTTP_PORT=${HOMEPAGE_PORT}" + if [ "${old}" = "${next}" ]; then + say "choices: ${ENV_FILE} unchanged" + return 0 + fi + # Never the token itself: only whether it is the same one. + if [ -n "${prev_token}" ]; then which="the same WORKER_TOKEN"; else which="a new WORKER_TOKEN"; fi + if [ "${DRY}" = 1 ]; then + say "choices: would write ${ENV_FILE} (mode 600, ${which})" + return 0 + fi + ( + umask 077 + printf '%s\n' "${next}" >"${ENV_FILE}.tmp" + ) + chmod 600 "${ENV_FILE}.tmp" + mv "${ENV_FILE}.tmp" "${ENV_FILE}" + say "choices: wrote ${ENV_FILE} (mode 600, ${which})" +} + +image_missing() { + [ "${DRY}" = 1 ] && [ -n "${DEMO_TEST_IMAGES_PRESENT:-}" ] && return 1 + ! docker image inspect "$1" >/dev/null 2>&1 +} + +wait_editor() { + if [ "${DRY}" = 1 ]; then + printf ' would wait: the editor answering /api/pulse (up to 4 minutes)\n' + return 0 + fi + i=0 + 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 "${DEMO_TEST_WAIT_SLEEP:-5}" + done + 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. +ollama_device_line() { + if [ "${DRY}" = 1 ]; then + printf ' would read: ollama'"'"'s "inference compute" log line (GPU or CPU)\n' + return 0 + fi + line="" + i=0 + while [ "${i}" -lt 12 ] && [ -z "${line}" ]; do + # shellcheck disable=SC2046 + line="$(docker compose $(compose_args) logs --no-log-prefix ollama 2>/dev/null | grep -m 1 'inference compute' || true)" + [ -n "${line}" ] || sleep 2 + i=$((i + 1)) + done + if [ -z "${line}" ]; then + say "ollama: no \"inference compute\" line yet — docker compose -p ${PROJECT} logs ollama says which device it found" + return 0 + fi + lib="$(printf '%s' "${line}" | sed -n 's/.*library=\([^ ]*\).*/\1/p')" + desc="$(printf '%s' "${line}" | sed -n 's/.*description="\([^"]*\)".*/\1/p')" + total="$(printf '%s' "${line}" | sed -n 's/.*total="\([^"]*\)".*/\1/p')" + case "${lib}" in + cpu | CPU | "") say "ollama: CPU ONLY — no GPU is in use; models run about 10x slower" ;; + *) say "ollama: GPU ${lib}${desc:+, ${desc}}${total:+ ${total}}" ;; + esac +} + +# ─── 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 + FREE_GB="$(free_gb)" + [ -n "${FREE_GB}" ] || FREE_GB=0 + [ "${RAM_GB}" -ge "${MIN_RAM_GB}" ] || refuse "this machine has ${RAM_GB} GB of RAM; the demo needs at least ${MIN_RAM_GB} GB (a 7B model, the editor and a render)." + [ "${FREE_GB}" -ge "${MIN_FREE_GB}" ] || refuse "${FREE_GB} GB is free where docker keeps its images; the demo needs ${MIN_FREE_GB} GB (images about 8, ollama about 6, a model about 5, the voice about 4)." + say "docker ${DOCKER_VERSION}, compose v${COMPOSE_VERSION} · ${RAM_GB} GB RAM · ${FREE_GB} GB free · ok" + if ! stack_running; then + for pair in "editor-port ${EDITOR_PORT}" "umtool-port ${UMTOOL_PORT}" "site-port ${SITE_PORT}" "homepage-port ${HOMEPAGE_PORT}"; do + flag="${pair%% *}" + p="${pair#* }" + if port_busy "${p}"; then + refuse "port ${p} is already taken on this machine — pick another with --${flag} <port>." + fi + 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}} 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 || 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" + 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 "$(listed_name "${MODEL}")"; then + say "model ${MODEL}: present" + else + 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)" + 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" + return 0 + fi + say "ready. umtool http://localhost:${UMTOOL_PORT}/research · editor http://localhost:${EDITOR_PORT}" + say "prove it stayed local any time: ./docker/demo.sh check" +} + +# Is the Orpheus voice usable here? The image must carry a llama-server, and the +# voice must be installed. +voice_state() { + if [ "${DRY}" = 1 ]; then + VOICE_STATE="${DEMO_TEST_VOICE_STATE:-unknown}" + return 0 + fi + # shellcheck disable=SC2046 + if ! docker compose $(compose_args) exec -T editor test -x /usr/lib/ollama/llama-server 2>/dev/null; then + VOICE_STATE=no-server + return 0 + fi + # shellcheck disable=SC2046 + if docker compose $(compose_args) exec -T editor pnpm --silent archilyzer tts setup --engine orpheus --check >/dev/null 2>&1; then + VOICE_STATE=installed + else + VOICE_STATE=not-installed + fi +} + +voice_line() { + voice_state + case "${VOICE_STATE}" in + installed) say "voice: Orpheus installed" ;; + not-installed) say "voice: Orpheus not installed -> run ./docker/demo.sh voice (about 4 GB, once)" ;; + no-server) say "voice: Orpheus is not available in this image (it carries no llama-server) -> ./docker/demo.sh voice says what is missing" ;; + *) say "voice: would check whether Orpheus is installed (./docker/demo.sh voice installs it)" ;; + esac +} + +do_voice() { + check_docker + stack_running || refuse "the demo is not running — start it with ./docker/demo.sh up first." + voice_state + case "${VOICE_STATE}" in + no-server) refuse "Orpheus needs a llama-server inside the editor image, and this image has none (/usr/lib/ollama/llama-server is missing) — the Orpheus voice is not available in this image yet; Kokoro is: docker compose -p ${PROJECT} exec editor pnpm archilyzer tts setup --engine kokoro" ;; + installed) say "voice: Orpheus already installed" ;; + *) + say "installing the Orpheus voice (the Q8_0 GGUF and its decoder, about 4 GB, once)" + compose exec -T editor pnpm --silent archilyzer tts setup --engine orpheus + ;; + esac + ops_json settings '{"patch":{"tts":{"engine":"orpheus"}}}' + say "voice: Orpheus is the narration voice (settings.tts.engine)" +} + +do_down() { + check_docker + # 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 + if [ "${VOLUMES}" = 1 ]; then + say "stopping the demo AND deleting its volumes (corpus, config, models, builds, reports, ollama's models)" + compose down -v + else + say "stopping the demo (volumes kept; --volumes deletes them)" + compose down + fi +} + +do_status() { + check_docker + GPU_USED=none + compose ps + stack_running || return 0 + ollama_device_line + compose exec -T editor pnpm --silent archilyzer gen policy + voice_line +} + +do_check() { + check_docker + stack_running || refuse "the demo is not running — start it with ./docker/demo.sh up first." + GPU_USED=none + failed=0 + # shellcheck disable=SC2046 + if docker compose $(compose_args) exec -T editor pnpm --silent archilyzer gen local-check; then :; else failed=1; fi + # shellcheck disable=SC2046 + cloud="$(docker compose $(compose_args) exec -T ollama printenv OLLAMA_NO_CLOUD 2>/dev/null | tr -d '\r' || true)" + if [ "${cloud}" = "1" ]; then + say "check: ok ollama runs with OLLAMA_NO_CLOUD=1" + else + say "check: FAIL ollama runs without OLLAMA_NO_CLOUD=1" + failed=1 + fi + # shellcheck disable=SC2046 + if docker compose $(compose_args) exec -T editor test -e /root/.config/archilyzer/anthropic.env 2>/dev/null; then + say "check: FAIL a Claude API key file is mounted in the editor" + failed=1 + else + say "check: ok no Claude API key file in the editor" + fi + [ "${failed}" = 0 ] && say "LOCAL ONLY: yes" || refuse "LOCAL ONLY: NOT proven — see the FAIL lines above." +} + +case "${VERB}" in +up) do_up ;; +down) do_down ;; +status) do_status ;; +check) do_check ;; +voice) do_voice ;; +esac diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh @@ -252,6 +252,41 @@ ytdlp_line() { fi } +# One line on every boot: does the local model server answer? Asked with GET +# /api/version (loads nothing), three seconds at most; the ollama service may +# still be starting, so a miss is a WARNING, never a refusal. +ollama_line() { + local url version + url="${OLLAMA_URL:-http://127.0.0.1:11434}" + url="${url%/}" + if version="$(curl -fsS -m 3 "${url}/api/version" 2>/dev/null)" && [ -n "${version}" ]; then + version="$(printf '%s' "${version}" | sed -n 's/.*"version":"\([^"]*\)".*/\1/p')" + log "ollama: ${url} answers (version ${version:-unknown})" + else + log "ollama: NOT ANSWERING at ${url} — local generation fails until it does" + log " (still starting? docker compose logs ollama; a host's ollama: RUNNING_IN_DOCKER.md, \"Local models\")" + 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. # --------------------------------------------------------------------------- @@ -295,6 +330,8 @@ editor) if [ "${ARCHILYZER_IDLE_BOOT:-}" = "1" ]; then log "idle boot: schedulers, auto-queue runners and sweeps stay STOPPED" fi + ollama_line + 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/docker/ollama-start.sh b/docker/ollama-start.sh @@ -0,0 +1,39 @@ +#!/bin/sh +# Entrypoint for the ollama service under docker-compose.demo.yml: one line +# that says whether this container can see a GPU, then `ollama serve`. +# +# Honest about what it can know: whether a device is passed through and the +# backend switched on. Whether ollama USES it is ollama's own +# `inference compute ... library=…` line, which follows — `./docker/demo.sh up` +# reads that one back. +# +# POSIX sh (the ollama image's /bin/sh). +set -eu + +DRI_DIR="${OLLAMA_START_DRI_DIR:-/dev/dri}" + +log() { printf '[ollama] %s\n' "$*"; } + +render_nodes() { + for n in "${DRI_DIR}"/renderD*; do + [ -e "$n" ] && printf '%s ' "${n##*/}" + done + return 0 +} + +nodes="$(render_nodes)" +if [ -n "${nodes}" ]; then + if [ "${OLLAMA_VULKAN:-}" = "1" ]; then + log "gpu: ${nodes}passed through, OLLAMA_VULKAN=1 — the \"inference compute\" line below names the device" + else + log "gpu: ${nodes}passed through, but OLLAMA_VULKAN is not 1 — ollama will not use it (docker-compose.ollama-vulkan.yml sets it)" + fi +elif command -v nvidia-smi >/dev/null 2>&1 && nvidia-smi -L >/dev/null 2>&1; then + log "gpu: NVIDIA $(nvidia-smi -L 2>/dev/null | head -n 1)" +else + log "gpu: NONE in this container — models run on the CPU, about 10x slower (docker-compose.ollama-vulkan.yml passes a GPU through)" +fi +log "cloud: OLLAMA_NO_CLOUD=${OLLAMA_NO_CLOUD:-unset}" +log "bounds: parallel ${OLLAMA_NUM_PARALLEL:-default}, loaded models ${OLLAMA_MAX_LOADED_MODELS:-default}, keep-alive ${OLLAMA_KEEP_ALIVE:-default}, prompt cache ${LLAMA_ARG_CACHE_RAM:-default} MiB" + +exec "${OLLAMA_START_BIN:-/bin/ollama}" serve diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +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. 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 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/_generation.test.ts b/editor/app/api/ops/_generation.test.ts @@ -46,7 +46,7 @@ test("both reads are behind the token", async () => { test("generation-usage answers the day's ledger total and the daily cap", async () => { const get = await route("generation-usage"); const none = await callGet(get, "http://localhost/api/ops/generation-usage?day=2026-10-01"); - assert.deepEqual(none.body, { ok: true, day: "2026-10-01", usd: 0, jobs: 0, daily: 7, models: [] }); + assert.deepEqual(none.body, { ok: true, day: "2026-10-01", usd: 0, jobs: 0, daily: 7, models: [], localOnly: false }); await mkdir(path.dirname(usageFile), { recursive: true }); // A local job's row (demo epic D3): a model called at no cost — never in the // spend or its jobs count, always in `models`. @@ -63,9 +63,19 @@ test("generation-usage answers the day's ledger total and the daily cap", async { model: "claude-sonnet-5-5", route: "api", calls: 0, jobs: 2, inputTokens: 2, outputTokens: 2 }, { model: "qwen3:8b", route: "local", calls: 5, jobs: 1, inputTokens: 900, outputTokens: 80 }, ], + localOnly: false, }); const today = await callGet(get, "http://localhost/api/ops/generation-usage"); assert.equal(today.body.day, new Date().toISOString().slice(0, 10)); + // The editor's own flag (demo epic D5), read per request. + const was = process.env.ARCHILYZER_LOCAL_ONLY; + process.env.ARCHILYZER_LOCAL_ONLY = "1"; + try { + assert.equal((await callGet(get, "http://localhost/api/ops/generation-usage")).body.localOnly, true); + } finally { + if (was === undefined) delete process.env.ARCHILYZER_LOCAL_ONLY; + else process.env.ARCHILYZER_LOCAL_ONLY = was; + } const bad = await callGet(get, "http://localhost/api/ops/generation-usage?day=yesterday"); assert.equal(bad.status, 400); const stray = await callGet(get, "http://localhost/api/ops/generation-usage?date=2026-10-01"); diff --git a/editor/app/api/ops/_reportDraft.test.ts b/editor/app/api/ops/_reportDraft.test.ts @@ -65,12 +65,28 @@ after(async () => { await rm(tmp, { recursive: true, force: true }); }); -const deps = (g: Partial<GenerationSettings> = {}) => ({ +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, 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. +async function localOnly<T>(body: () => Promise<T>): Promise<T> { + const was = process.env.ARCHILYZER_LOCAL_ONLY; + process.env.ARCHILYZER_LOCAL_ONLY = "1"; + try { + return await body(); + } finally { + if (was === undefined) delete process.env.ARCHILYZER_LOCAL_ONLY; + else process.env.ARCHILYZER_LOCAL_ONLY = was; + } +} + const run = async (name: string) => JSON.parse(await readFile(path.join(DRAFT, "runs", `${name}.json`), "utf8")); test("the body: each task's needs, and the refusals in words", () => { @@ -313,3 +329,106 @@ test("a local sweep (demo epic D3): its calls in the iteration's model log; the assert.ok(!models.some((m) => m.route === "api" || m.model.startsWith("claude")), "a local-only run lists no cloud model"); assert.deepEqual(await dayUsage(paths.generationUsageFile), spentBefore, "the cap's total and jobs count are the API's alone"); }); + +test("the local model's memory floor (demo epic D5): under it the job 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)); + assert.ok(out.result.ok && "iteration" in out, (out.result as { error?: string }).error); + void out.result.stream.cancel(); + const done = await out.result.done; + assert.equal(done.status, "failed"); + const 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, 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; + await localOnly(async () => { + const byModel = await enqueueReportDraft({ task: "sweep", article: "synth-lo-1", model: "claude-sonnet-5-5", question: "q", channels: ["synth-kitchen"], source }, deps()); + assert.equal(byModel.result.ok, false); + assert.match((byModel.result as { error: string }).error, /local only \(ARCHILYZER_LOCAL_ONLY=1\): "claude-sonnet-5-5" is not a local model/); + const byRoute = await enqueueReportDraft( + { task: "sweep", article: "synth-lo-2", question: "q", channels: ["synth-kitchen"], source }, + deps({ routes: { ...gen.routes, sweep: "api" } }), + ); + assert.match((byRoute.result as { error: string }).error, /"claude-sonnet-5-5" is not a local model/); + const code = await enqueueReportDraft({ task: "sweep", article: "synth-lo-3", question: "q", channels: ["synth-kitchen"], source }, deps({ routes: { ...gen.routes, sweep: "code" } })); + assert.match((code.result as { error: string }).error, /routed to Claude Code/); + const extractor = await enqueueReportDraft( + { task: "sweep", article: "synth-lo-4", model: "qwen3:8b", extractorModel: "claude-haiku-4-5", question: "q", channels: ["synth-kitchen"], source }, + deps(), + ); + assert.match((extractor.result as { error: string }).error, /"claude-haiku-4-5" is not a local model/); + const cloud = await enqueueReportDraft({ task: "sweep", article: "synth-lo-5", model: "gpt-oss:120b-cloud", question: "q", channels: ["synth-kitchen"], source }, deps()); + assert.match((cloud.result as { error: string }).error, /"gpt-oss:120b-cloud" is an ollama cloud model/); + for (const a of ["synth-lo-1", "synth-lo-2", "synth-lo-3", "synth-lo-4", "synth-lo-5"]) assert.equal(await readIteration(a, 1, paths), null, `${a}: no iteration made`); + }); + assert.equal(api.requests.length, apiBefore, "the fake Claude API was never asked"); + assert.equal(ol.requests.length, olBefore, "the fake ollama was never asked"); +}); + +test("local only: a local sweep still runs, on the local model alone", async () => { + const r = await run("sweep-pipeline"); + // Its own fake ollama: the shared one's script may hold an earlier test's turns. + const own = await startFakeOllama({ turns: r.turns }); + const apiBefore = api.requests.length; + try { + await localOnly(async () => { + const out = await enqueueReportDraft({ task: "sweep", article: "synth-lo-local", model: r.model, question: r.question, channels: r.channels, source }, deps({ ollamaUrl: own.url })); + assert.ok(out.result.ok && "iteration" in out, (out.result as { error?: string }).error); + void out.result.stream.cancel(); + const done = await out.result.done; + assert.equal(done.status, "done", await readFile(getRegistry().get(out.result.jobId)!.logPath, "utf8")); + }); + assert.ok(own.requests.length > 0, "the local model was asked"); + assert.deepEqual([...new Set(own.shows)], [r.model], "after its /api/show said it is local"); + } finally { + await own.close(); + } + assert.equal(api.requests.length, apiBefore, "the Claude API was not"); +}); diff --git a/editor/app/api/ops/_writes.test.ts b/editor/app/api/ops/_writes.test.ts @@ -79,6 +79,31 @@ test("the patch rule: leaves compared, arrays element by element, absent keys no assert.equal(settingsPatchProblem({ a: 1 }, ["a"], { a: 1 }), null); }); +test("local only (demo epic D5): a patch that routes a task anywhere but local is refused; other generation writes pass", () => { + const was = process.env.ARCHILYZER_LOCAL_ONLY; + const parsed = (routes: Record<string, string>) => ({ generation: { routes, models: { local: "qwen2.5:7b" } } }); + try { + process.env.ARCHILYZER_LOCAL_ONLY = "1"; + assert.match( + settingsPatchProblem({ generation: { routes: { sweep: "api" } } }, ["generation"], parsed({ sweep: "api", narrate: "local" }))!, + /local only \(ARCHILYZER_LOCAL_ONLY=1\): every generation route stays local — not saved: sweep → api/, + ); + assert.equal(settingsPatchProblem({ generation: { routes: { sweep: "local" } } }, ["generation"], parsed({ sweep: "local", narrate: "local" })), null); + // A write that does not touch the routes is not held by routes already on disk. + assert.equal(settingsPatchProblem({ generation: { models: { local: "qwen2.5:7b" } } }, ["generation"], parsed({ sweep: "code" })), null); + // 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 { + if (was === undefined) delete process.env.ARCHILYZER_LOCAL_ONLY; + else process.env.ARCHILYZER_LOCAL_ONLY = was; + } +}); + test("lane: the publish lane is a lane; an unknown one is refused by the full list", async () => { const lane = await route("lane"); const bogus = await callPost(lane, { lane: "transcode", held: true }); diff --git a/editor/app/api/ops/generation-usage/route.ts b/editor/app/api/ops/generation-usage/route.ts @@ -1,13 +1,14 @@ import { getPaths } from "yt-dlp-transcript-common/lib/paths"; import { getSettings } from "yt-dlp-transcript-common/lib/settings"; import { dayModels, dayUsage, utcDay } from "yt-dlp-transcript-common/controller/generationUsage"; +import { isLocalOnly } from "yt-dlp-transcript-common/lib/llm/localOnly"; import { readRoute } from "../_read"; import { opsFail } from "../_lib"; export const dynamic = "force-dynamic"; // GET [?day=YYYY-MM-DD] -// -> { ok, day, usd, jobs, daily, models: [{model, route, calls, jobs, inputTokens, outputTokens}] } +// -> { ok, day, usd, jobs, daily, models: [{model, route, calls, jobs, inputTokens, outputTokens}], localOnly } // // The day's Claude API spend on generation (release 27 S9): the usage // ledger's total for the UTC day (default today) — what the daily cap is @@ -15,7 +16,9 @@ export const dynamic = "force-dynamic"; // (`settings.generation.caps.daily`, 0 = none). The MCP's generation_policy // and `archilyzer gen policy` show it beside the routes. `models`: every model // the day's generation called and on which route ("api", or "local" with no -// cost, demo epic D3) — a local-only day lists no Claude model. Read only. +// cost, demo epic D3) — a local-only day lists no Claude model. `localOnly`: +// whether THIS editor runs with ARCHILYZER_LOCAL_ONLY on (demo epic D5; +// `archilyzer gen local-check`, umtool's policy chip). Read only. const DAY = /^\d{4}-\d{2}-\d{2}$/; export async function GET(request: Request) { @@ -24,6 +27,6 @@ export async function GET(request: Request) { if (!DAY.test(day)) return opsFail('"day" must be a date YYYY-MM-DD (UTC)'); const file = getPaths().generationUsageFile; const [used, models] = await Promise.all([dayUsage(file, day), dayModels(file, day)]); - return { ...used, daily: getSettings().generation.caps.daily, models }; + return { ...used, daily: getSettings().generation.caps.daily, models, localOnly: isLocalOnly() }; }); } diff --git a/editor/app/api/ops/settings/patch.ts b/editor/app/api/ops/settings/patch.ts @@ -1,6 +1,8 @@ // WHAT `POST /api/ops/settings` REFUSES, as one pure function — testable // without a settings file, a schema or a server. +import { 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: // - channelPriority: the priority write compiles the four lanes' trees in the @@ -60,6 +62,11 @@ export function settingsPatchProblem( if (owned.length) { return owned.map((k) => `"${k}" is not patched here: ${OWNED_KEYS[k]}`).join("; "); } + // LOCAL ONLY (common/lib/llm/localOnly.ts): a patch that routes a task + // anywhere but `local`, 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 @@ -0,0 +1,464 @@ +// docker/demo.sh (demo epic D5), against a STUB `docker` on PATH that records +// every call and, unless told to play along, fails any call that would change +// something (up, build, pull, exec, down). No real docker, no network but a +// loopback fake of the host's ollama, nothing outside a temp dir. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import test from "node:test"; +import { spawn, spawnSync } from "node:child_process"; +import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs"; +import http from "node:http"; +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 })); + +// The stub. Read-only probes answer; anything else is FORBIDDEN (exit 99) +// unless STUB_PERMISSIVE, when it is recorded and succeeds — `logs` and +// `ollama list` answer as a running stack would. +const BIN = path.join(ROOT, "bin"); +mkdirSync(BIN); +writeFileSync( + path.join(BIN, "docker"), + `#!/bin/sh +printf '%s\\n' "$*" >> "$STUB_LOG" +case "$*" in +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 ;; +*" ps -q caddy") [ -n "\${STUB_RUNNING:-}" ] && echo c0ffee; 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}" ;; + *"exec -T editor test -x /usr/lib/ollama/llama-server"*) exit 1 ;; + *"exec -T editor test -e"*) exit 1 ;; + *"exec -T ollama printenv OLLAMA_NO_CLOUD"*) echo "\${STUB_NO_CLOUD:-1}" ;; + esac + exit 0 +fi +echo "FORBIDDEN $*" >> "$STUB_LOG" +exit 99 +`, +); +chmodSync(path.join(BIN, "docker"), 0o755); + +let n = 0; +function fixture({ ramGb = 16, freeGb = 80, dri = true } = {}) { + const dir = path.join(ROOT, `case-${++n}`); + mkdirSync(path.join(dir, "dri"), { recursive: true }); + if (dri) writeFileSync(path.join(dir, "dri", "renderD128"), ""); + writeFileSync(path.join(dir, "meminfo"), `MemTotal: ${ramGb * 1048576} kB\nMemFree: 1 kB\n`); + return { dir, log: path.join(dir, "docker.log"), env: path.join(dir, ".env.demo"), freeKb: String(freeGb * 1048576) }; +} + +// The tools the script needs, and NOT docker: a PATH for "docker is not installed". +const TOOLS = path.join(ROOT, "tools"); +mkdirSync(TOOLS); +for (const t of ["sh", "dirname", "sed", "tail", "head", "grep", "awk", "cat", "tr", "od", "cut", "chmod", "mv", "curl"]) { + const where = spawnSync("sh", ["-c", `command -v ${t}`], { encoding: "utf8" }).stdout.trim(); + if (where) symlinkSync(where, path.join(TOOLS, t)); +} + +function envOf(f, extra) { + return { + PATH: `${BIN}:${process.env.PATH}`, + HOME: f.dir, + STUB_LOG: f.log, + DEMO_ENV_FILE: f.env, + DEMO_TEST_DRI_DIR: path.join(f.dir, "dri"), + DEMO_TEST_MEMINFO: path.join(f.dir, "meminfo"), + DEMO_TEST_FREE_KB: f.freeKb, + DEMO_TEST_BUSY_PORTS: "", + // A closed port: no host ollama answers unless a test starts one. + DEMO_HOST_OLLAMA_URL: "http://127.0.0.1:9", + ...extra, + }; +} + +function callsOf(f) { + return existsSync(f.log) ? readFileSync(f.log, "utf8").trim().split("\n").filter(Boolean) : []; +} + +function demo(args, f, extra = {}) { + rmSync(f.log, { force: true }); + 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) }; +} + +// The same, without blocking the event loop (a test's own server must answer). +function demoAsync(args, f, extra = {}) { + rmSync(f.log, { force: true }); + return new Promise((resolve) => { + const child = spawn(SH, [SCRIPT, ...args], { env: envOf(f, extra) }); + let out = ""; + let err = ""; + child.stdout.on("data", (d) => (out += d)); + child.stderr.on("data", (d) => (err += d)); + child.on("close", (code) => resolve({ code, out, err, calls: callsOf(f) })); + }); +} + +const forbidden = (calls) => calls.filter((c) => c.startsWith("FORBIDDEN")); + +test("up --dry-run: the plan, in plain lines; nothing written, nothing changed", () => { + const f = fixture(); + const r = demo(["up", "--dry-run"], f); + assert.equal(r.code, 0, r.err); + assert.deepEqual(forbidden(r.calls), []); + assert.equal(existsSync(f.env), false, "no .env.demo"); + const lines = r.out.split("\n"); + 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"; + for (const tail of ["build editor umtool", "up -d", "exec -T ollama ollama pull qwen2.5:7b", "exec -T editor pnpm --silent archilyzer gen preset local", "exec -T editor pnpm --silent archilyzer gen model local qwen2.5:7b", "exec -T editor pnpm --silent archilyzer gen model extractor qwen2.5:7b"]) { + assert.ok(r.out.includes(` would run: ${compose} ${tail}\n`), `${tail}\n${r.out}`); + } + assert.doesNotMatch(r.out, /anthropic/, "the Claude API overlay is never part of it"); + assert.match(r.out, /demo: dry run: nothing was written, built, pulled or started\n$/); +}); + +test("up --dry-run with the flags: another archive and model, no GPU, images present, other ports", () => { + const f = fixture({ dri: false }); + const r = demo(["up", "--dry-run", "--archive", "https://example.org/corpus.json", "--model", "qwen3:8b", "--gpu", "none", "--editor-port", "18081", "--umtool-port", "18083"], f, { STUB_IMAGES: "1", DEMO_TEST_IMAGES_PRESENT: "1" }); + 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 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/); + assert.match(r.out, /gen model local qwen3:8b/); +}); + +test("each missing prerequisite: one sentence, exit 1, nothing changed", () => { + const cases = [ + [{ PATH: TOOLS }, /^demo: docker is not installed — install Docker Engine \(or Docker Desktop\) and run this again\.\n$/], + [{ STUB_NO_DAEMON: "1" }, /^demo: the docker daemon is not answering — start it \(sudo systemctl start docker\) and run this again\.\n$/], + [{ STUB_NO_COMPOSE: "1" }, /^demo: docker compose v2 is missing — install the compose plugin \(docker-compose v1 is not enough\) and run this again\.\n$/], + [{ STUB_COMPOSE: "2.20.3" }, /^demo: docker compose 2\.20\.3 is too old — the demo needs compose v2\.24 or newer\.\n$/], + [{ DEMO_TEST_BUSY_PORTS: "8083" }, /^demo: port 8083 is already taken on this machine — pick another with --umtool-port <port>\.\n$/], + ]; + for (const [env, msg] of cases) { + const f = fixture(); + const r = demo(["up"], f, env); + assert.equal(r.code, 1, `${JSON.stringify(env)}: ${r.out}${r.err}`); + assert.match(r.err, msg); + assert.deepEqual(forbidden(r.calls), []); + assert.equal(existsSync(f.env), false); + } + const small = fixture({ ramGb: 8 }); + const ram = demo(["up"], small); + assert.equal(ram.code, 1); + assert.match(ram.err, /^demo: this machine has 8 GB of RAM; the demo needs at least 12 GB \(a 7B model, the editor and a render\)\.\n$/); + const full = fixture({ freeGb: 10 }); + const disk = demo(["up"], full); + assert.equal(disk.code, 1); + assert.match(disk.err, /^demo: 10 GB is free where docker keeps its images; the demo needs 25 GB/); + for (const [args, msg] of [ + [["up", "--model", "gpt-oss:120b-cloud"], /an ollama CLOUD model — the demo runs local models only/], + [["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 not an http\(s\) URL/], + [["down", "--model", "x"], /only up takes/], + [["up", "--volumes"], /only down takes --volumes/], + [["launch"], /unknown command "launch"/], + [["up", "--fast"], /unknown flag "--fast"/], + ]) { + const f = fixture(); + const r = demo(args, f); + assert.equal(r.code, 1, args.join(" ")); + assert.match(r.err, msg); + assert.equal(r.err.trim().split("\n").length, 1, "one sentence"); + } +}); + +test("a host ollama with a model loaded is a WARNING, never a refusal (asked with GET /api/ps)", async () => { + const asked = []; + const server = http.createServer((req, res) => { + asked.push(`${req.method} ${req.url}`); + res.setHeader("content-type", "application/json"); + res.end(JSON.stringify({ models: [{ name: "qwen3:8b", model: "qwen3:8b", size: 1 }] })); + }); + await new Promise((ok) => server.listen(0, "127.0.0.1", ok)); + const url = `http://127.0.0.1:${server.address().port}`; + try { + const f = fixture(); + const r = await demoAsync(["up", "--dry-run"], f, { DEMO_HOST_OLLAMA_URL: url }); + assert.equal(r.code, 0, r.err); + assert.match(r.out, new RegExp(`demo: WARNING: a host ollama at ${url} has qwen3:8b loaded — two servers would share the GPU`)); + } finally { + server.close(); + } + assert.deepEqual(asked, ["GET /api/ps"]); +}); + +test("up for real (the stub plays along): .env.demo written once, mode 600; a re-run reuses the token and changes nothing", () => { + const f = fixture(); + const play = { STUB_PERMISSIVE: "1" }; + const first = demo(["up"], f, play); + assert.equal(first.code, 0, first.err + first.out); + const env = readFileSync(f.env, "utf8"); + assert.equal(statSync(f.env).mode & 0o777, 0o600); + const token = /^WORKER_TOKEN=([0-9a-f]{48})$/m.exec(env)?.[1]; + assert.ok(token, env); + assert.ok(!first.out.includes(token) && !first.err.includes(token), "the token is never printed"); + assert.match(env, /^DEMO_ARCHIVE=https:\/\/jeralyzer\.pages\.dev$/m); + assert.match(env, /^ARCHILYZER_TAG=demo$/m); + assert.match(env, /^DEMO_OLLAMA_MEM=6g$/m, "40% of 16 GB"); + assert.match(first.out, /demo: ollama: GPU Vulkan, AMD Radeon RX 6600 XT \(RADV NAVI23\) 8\.0 GiB/); + assert.match(first.out, /demo: voice: Orpheus is not available in this image \(it carries no llama-server\)/); + assert.match(first.out, /demo: ready\. umtool http:\/\/localhost:8083\/research · editor http:\/\/localhost:8081/); + const order = first.calls.map((c) => c.replace(/^compose -p archilyzer-demo --env-file \S+ -f docker-compose\.yml -f docker-compose\.demo\.yml -f docker-compose\.ollama-vulkan\.yml --profile umtool --profile ollama /, "C ")); + const want = ["C build editor umtool", "C up -d", "C exec -T ollama ollama pull qwen2.5:7b", "C exec -T editor pnpm --silent archilyzer gen preset local", "C exec -T editor pnpm --silent archilyzer gen model local qwen2.5:7b"]; + let at = 0; + for (const w of want) { + const i = order.indexOf(w, at); + assert.ok(i >= at, `${w} after ${want[want.indexOf(w) - 1]}\n${order.join("\n")}`); + at = i; + } + assert.ok(!first.calls.some((c) => / down/.test(c) || /-v\b/.test(c))); + + const again = demo(["up"], f, { ...play, STUB_RUNNING: "1", STUB_IMAGES: "1", STUB_HAS_MODEL: "qwen2.5:7b", DEMO_TEST_BUSY_PORTS: "8080 8081 8082 8083" }); + assert.equal(again.code, 0, again.err); + assert.match(again.out, /choices: .*\.env\.demo unchanged/); + assert.match(again.out, /images: archilyzer:demo and archilyzer:demo-umtool present/); + assert.match(again.out, /model qwen2\.5:7b: present/); + assert.ok(!again.calls.some((c) => / build | pull /.test(c)), again.calls.join("\n")); + assert.equal(readFileSync(f.env, "utf8"), env, "the same file, the same token"); + // A flag changes its line, and only that. + const model = demo(["up", "--model", "qwen3:8b"], f, { ...play, STUB_RUNNING: "1", STUB_IMAGES: "1" }); + assert.equal(model.code, 0, model.err); + assert.match(readFileSync(f.env, "utf8"), /^DEMO_MODEL=qwen3:8b$/m); + assert.match(readFileSync(f.env, "utf8"), new RegExp(`^WORKER_TOKEN=${token}$`, "m")); +}); + +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: 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", 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", 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, { 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", () => { + const f = fixture(); + writeFileSync(f.env, "WORKER_TOKEN=x\n"); + const ok = demo(["check"], f, { STUB_PERMISSIVE: "1", STUB_RUNNING: "1" }); + assert.equal(ok.code, 0, ok.err + ok.out); + assert.match(ok.out, /LOCAL ONLY: yes/); + assert.ok(ok.calls.some((c) => /exec -T editor pnpm --silent archilyzer gen local-check$/.test(c))); + const bad = demo(["check"], f, { STUB_PERMISSIVE: "1", STUB_RUNNING: "1", STUB_NO_CLOUD: "0" }); + assert.equal(bad.code, 1); + assert.match(bad.out, /check: FAIL ollama runs without OLLAMA_NO_CLOUD=1/); + assert.match(bad.err, /LOCAL ONLY: NOT proven/); + const down = demo(["check"], f); + assert.equal(down.code, 1); + assert.match(down.err, /^demo: the demo is not running — start it with \.\/docker\/demo\.sh up first\.\n$/); +}); + +test("voice: says plainly what is missing when the image has no llama-server", () => { + const f = fixture(); + writeFileSync(f.env, "WORKER_TOKEN=x\n"); + const r = demo(["voice"], f, { STUB_PERMISSIVE: "1", STUB_RUNNING: "1" }); + assert.equal(r.code, 1); + assert.match(r.err, /^demo: Orpheus needs a llama-server inside the editor image, and this image has none \(\/usr\/lib\/ollama\/llama-server is missing\)/); + assert.ok(!r.calls.some((c) => /tts setup --engine orpheus$/.test(c)), "nothing installed"); +}); + +test("ollama-start.sh: one honest gpu line, then ollama serve", () => { + const dri = path.join(ROOT, "start-dri"); + mkdirSync(dri, { recursive: true }); + const run = (env) => + spawnSync("sh", [START], { encoding: "utf8", env: { PATH: process.env.PATH, OLLAMA_START_DRI_DIR: dri, OLLAMA_START_BIN: "echo", ...env } }); + const none = run({}); + assert.match(none.stdout, /\[ollama\] gpu: {8}NONE in this container — models run on the CPU/); + assert.match(none.stdout, /\nserve\n$/, "execs `<bin> serve`"); + writeFileSync(path.join(dri, "renderD128"), ""); + const off = run({}); + assert.match(off.stdout, /renderD128 passed through, but OLLAMA_VULKAN is not 1/); + const on = run({ OLLAMA_VULKAN: "1", OLLAMA_NO_CLOUD: "1", LLAMA_ARG_CACHE_RAM: "1024" }); + assert.match(on.stdout, /renderD128 passed through, OLLAMA_VULKAN=1/); + 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,14 +1,18 @@ import Link from "next/link"; import { cache } from "react"; import { badgeVariants } from "@/components/ui/badge"; -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 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). +// (/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. @@ -17,6 +21,12 @@ 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-/, ""); @@ -47,6 +57,20 @@ export default async function PolicyChip() { ); } const g = policy.generation; + 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}> diff --git a/umtool/lib/articles/policyChip.test.ts b/umtool/lib/articles/policyChip.test.ts @@ -0,0 +1,15 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { policyChipLabel } from "./policyChip"; + +const models = { api: "claude-sonnet-5-5", local: "qwen2.5:7b" }; + +test("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("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 @@ -0,0 +1,26 @@ +// 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; + models: { api: string; local: string }; +}; + +export type PolicyChipLabel = { + preset: string; + model: string; + // Show the day's Claude API spend beside it. + spend: boolean; + localOnly: boolean; +}; + +const shortModel = (m: string) => m.replace(/^claude-/, ""); + +export function policyChipLabel(g: PolicyChipInput, 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 }; +}