Archilyzer · Source

archilyzer

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

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

docker/demo.sh: one command to a local-only instance -- up (dry run, prerequisites in one sentence, GPU found, host ollama warned, .env.demo kept, images once, model pulled once, every task local), down (volumes kept unless --volumes), status, check, voice (demo epic D5)

- docker/demo.sh, POSIX sh (checked under bash, dash and busybox): only docker
  and compose v2.24+ on the host. Project archilyzer-demo, images
  archilyzer:demo{,-umtool}; settings written through the product's own
  commands (gen preset local, gen model local|extractor).
- docker-compose.demo.yml: ARCHILYZER_LOCAL_ONLY=1, TRANSCRIPT_SITE_URL and
  WORKER_TOKEN for the editor and umtool; ollama with OLLAMA_NO_CLOUD, one
  request and one model at a time, LLAMA_ARG_CACHE_RAM 1024 MiB, mem_limit =
  memswap_limit, and a start wrapper (docker/ollama-start.sh) that prints one
  line on the GPU it can see.
- docker-compose.ollama-vulkan.yml / -nvidia.yml: the GPU for ollama alone.
- entrypoint: an `ollama:` line (answers or NOT ANSWERING) and `models: LOCAL
  ONLY` on every editor boot.
- RUNNING_IN_DOCKER.md: the demo section; the OLLAMA_HOST=0.0.0.0 advice
  replaced by the compose service or a gateway-only socat bridge.
- scripts/demo.test.mjs: a stub docker that fails any changing call; the
  plan, every refusal, idempotency, the token never printed, down's volumes,
  check, voice, the wrapper.

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

Diffstat:
M.env.example | 4+++-
MRUNNING_IN_DOCKER.md | 101+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Adocker-compose.demo.yml | 62++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Adocker-compose.ollama-nvidia.yml | 15+++++++++++++++
Adocker-compose.ollama-vulkan.yml | 16++++++++++++++++
Adocker/demo.sh | 573+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mdocker/entrypoint.sh | 22++++++++++++++++++++++
Adocker/ollama-start.sh | 39+++++++++++++++++++++++++++++++++++++++
Meditor/CHANGELOG.md | 5+++++
Ascripts/demo.test.mjs | 309+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
10 files changed, 1143 insertions(+), 3 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/RUNNING_IN_DOCKER.md b/RUNNING_IN_DOCKER.md @@ -124,6 +124,72 @@ 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. + +**Local only.** `docker-compose.demo.yml` sets `ARCHILYZER_LOCAL_ONLY=1` on the +editor and umtool (common/lib/llm/localOnly.ts): the Claude API client refuses +before any request, a task routed to Claude Code or a session's `answers` is +refused, the digest's `claude` lane is never started, an ollama cloud model (a +`…-cloud` tag) is refused, and a settings write that routes a task anywhere but +`local` is refused. ollama runs with `OLLAMA_NO_CLOUD=1`, and the Claude API +overlay is never part of this stack. The editor's boot log says `models: LOCAL +ONLY`; umtool's policy chip says "local only" with the local model's name. +`./docker/demo.sh check` (and `archilyzer gen local-check` in the editor) proves +it afterwards, by counts: the flag on, every route local, no API key at hand, +and the usage ledger holding no Claude API row. + +**Bounds on ollama** (the demo overlay): one request and one model at a time, +`OLLAMA_KEEP_ALIVE=2m`, llama.cpp's prompt cache capped at 1024 MiB +(`LLAMA_ARG_CACHE_RAM`; its default is 8192 MiB, which grew to 8–11 GB in the +baseline and was OOM-killed twice), and `mem_limit` equal to `memswap_limit` — +40% of RAM, 4 to 8 GB — so a runaway dies in its own container. A report-draft +job on the local model refuses to start under 3072 MB MemAvailable +(`LOCAL_MODEL_MIN_FREE_MB`). + +**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 +564,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/docker-compose.demo.yml b/docker-compose.demo.yml @@ -0,0 +1,62 @@ +# 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 and umtool run LOCAL ONLY (ARCHILYZER_LOCAL_ONLY=1, +# common/lib/llm/localOnly.ts): the Claude API, a Claude Code session's +# answers, the digest's `claude` lane and an ollama cloud model are refused +# before any request. The anthropic overlay is never part of this stack, so +# there is no API key in it either. `archilyzer gen local-check` proves it. +# * The 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, and the exposure guard is unchanged. + +services: + editor: + environment: + ARCHILYZER_LOCAL_ONLY: "1" + 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" + 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/demo.sh b/docker/demo.sh @@ -0,0 +1,573 @@ +#!/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 + +cd "$(dirname "$0")/.." + +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 + +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 +} + +prev_token="$(env_get WORKER_TOKEN)" +[ -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 + +case "${ARCHIVE}" in +http://* | https://*) ;; +*) refuse "--archive is an http(s) URL (got \"${ARCHIVE}\")." ;; +esac +ARCHIVE="${ARCHIVE%/}" +ARCHIVE="${ARCHIVE%/corpus.json}" +case "${MODEL}" in +*-cloud | *:cloud) refuse "--model ${MODEL} is an ollama CLOUD model — the demo runs local models only." ;; +claude*) refuse "--model ${MODEL} is a Claude model — the demo runs local models only." ;; +esac +printf '%s' "${MODEL}" | grep -Eq '^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$' || refuse "--model \"${MODEL}\" is not a model name." +case "${GPU}" in +auto | vulkan | nvidia | none) ;; +*) refuse "--gpu is auto, vulkan, nvidia or none (got \"${GPU}\")." ;; +esac +for p in "${EDITOR_PORT}" "${UMTOOL_PORT}" "${SITE_PORT}" "${HOMEPAGE_PORT}"; do + case "$p" in + '' | *[!0-9]*) refuse "a port is a number (got \"$p\")." ;; + esac + [ "$p" -ge 1 ] && [ "$p" -le 65535 ] || refuse "a port is 1 to 65535 (got $p)." +done + +# ─── prerequisites (read-only probes) ─── + +check_docker() { + command -v docker >/dev/null 2>&1 || refuse "docker is not installed — install Docker Engine (or Docker Desktop) and run this again." + docker info >/dev/null 2>&1 || refuse "the docker daemon is not answering — start it (sudo systemctl start docker) and run this again." + 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}")" + [ -n "${kb}" ] && echo $((kb / 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 / 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)" ] +} + +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); a JSON argument goes +# through `run_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) "$@" +} + +# `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 48 ]; do + # shellcheck disable=SC2046 + if docker compose $(compose_args) exec -T editor curl -fsS -o /dev/null http://127.0.0.1:3001/api/pulse 2>/dev/null; then + return 0 + fi + i=$((i + 1)) + sleep 5 + done + refuse "the editor did not answer within 4 minutes — see: docker compose -p ${PROJECT} logs editor" +} + +# 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() { + 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 + case "${GPU_USED}" in + vulkan) say "GPU: ${GPU_NODE:-${DRI_DIR}} -> ollama on Vulkan" ;; + nvidia) say "GPU: NVIDIA -> ollama on CUDA" ;; + none) say "GPU: none -> ollama on the CPU (about 10x slower)" ;; + 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 + else + say "images: archilyzer:demo and archilyzer:demo-umtool present (--rebuild builds them again)" + fi + say "starting editor, umtool and ollama" + compose up -d + wait_editor + ollama_device_line + # shellcheck disable=SC2046 + if [ "${DRY}" = 0 ] && docker compose $(compose_args) exec -T ollama ollama list 2>/dev/null | awk 'NR>1 {print $1}' | grep -qxF "${MODEL}"; then + say "model ${MODEL}: present" + else + if [ "${DRY}" = 1 ]; then say "model ${MODEL}: pulled unless ollama already has it (once; a 7B model is about 4.7 GB)"; else say "pulling ${MODEL} (once; a 7B model is about 4.7 GB)"; fi + compose exec -T ollama ollama pull "${MODEL}" + fi + say "generation: preset local, model ${MODEL} (every task on the local model)" + compose exec -T editor pnpm --silent archilyzer gen preset local + compose exec -T editor pnpm --silent archilyzer gen model local "${MODEL}" + compose exec -T editor pnpm --silent archilyzer gen model extractor "${MODEL}" + 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 + if [ ! -f "${ENV_FILE}" ] && [ -z "${DEMO_TEST_STACK_RUNNING:-}" ]; then + say "nothing to stop: no ${ENV_FILE} here (the demo was never started from this checkout)" + 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,22 @@ 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 +} + # --------------------------------------------------------------------------- # 5. The exposure rail. Shared with the caddy container — one implementation. # --------------------------------------------------------------------------- @@ -295,6 +311,12 @@ editor) if [ "${ARCHILYZER_IDLE_BOOT:-}" = "1" ]; then log "idle boot: schedulers, auto-queue runners and sweeps stay STOPPED" fi + ollama_line + case "${ARCHILYZER_LOCAL_ONLY:-}" in + 1 | true | yes | on) + log "models: LOCAL ONLY — the Claude API, Claude Code answers and ollama cloud models are refused (ARCHILYZER_LOCAL_ONLY)" + ;; + esac 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. `down` keeps the volumes unless `--volumes`; `status` shows the stack; `voice` says what Orpheus needs. Nothing is opened off this machine. RUNNING_IN_DOCKER.md, "A local-only demo". +- **Local only, provably: `ARCHILYZER_LOCAL_ONLY=1`.** With it set (the demo sets it), the editor and umtool refuse every model call that would leave the machine before anything is sent: the Claude API, a task routed to Claude Code or a session's answers, the digest's `claude` lane, and an ollama cloud model (a `-cloud` tag). A settings change that routes a task anywhere but the local model is refused. A refused job says so in one sentence. `archilyzer gen local-check` (and `./docker/demo.sh check`) proves it afterwards by counts: the flag on, every route local, no API key present, and no Claude API row in the usage ledger since a date; it exits 1 when any of these fails, and never prints a key. The editor's boot log says `models: LOCAL ONLY`, and gives one line on whether ollama answers. Unset, nothing changes. Needs a restart of the editor and umtool. +- **`archilyzer gen model api|local|extractor <model>` sets the model a route runs** (settings.generation.models), from a terminal or a container; bare, it shows the three. +- **A report draft on the local model needs 3072 MB of free memory to start.** Under that it is refused at its turn ("1000 MB available is under the 3072 MB a local model's run starts with"), like a lookout run, instead of starting a model on a machine already short of memory. `LOCAL_MODEL_MIN_FREE_MB` changes the floor (0 turns it off). Needs a restart of the editor. +- **umtool: the policy chip names the model that runs.** With no task routed to the Claude API it shows the local model and no API spend, and on a local-only instance it says "local only". Needs a restart of umtool. - **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: - The set is built from the whole project manifest (and a take's), and the build, the chrome composer, the podcast, Play, Present and the previews all take it from one function. diff --git a/scripts/demo.test.mjs b/scripts/demo.test.mjs @@ -0,0 +1,309 @@ +// 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"); +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_NO_DAEMON:-}" ] && exit 1; 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 + *" 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("/bin/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("/bin/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.match(lines[0], /^demo: docker 27\.3\.1, compose v2\.29\.1 · 16 GB RAM · 80 GB free · ok$/); + assert.match(r.out, /demo: GPU: .*renderD128 -> ollama on Vulkan/); + assert.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 on the CPU/); + 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 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; with no .env.demo there is nothing to stop", () => { + const none = fixture(); + const empty = demo(["down"], none); + assert.equal(empty.code, 0); + assert.match(empty.out, /nothing to stop/); + assert.deepEqual(forbidden(empty.calls), []); + + const f = fixture(); + writeFileSync(f.env, "WORKER_TOKEN=x\n"); + const keep = demo(["down"], f, { STUB_PERMISSIVE: "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" }); + 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); + assert.deepEqual(forbidden(dry.calls), []); + assert.match(dry.out, /would run: docker compose .* down -v/); +}); + +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/); +});