From 43ece0cfd64d36f7da4cba26b69eb1aa7c6d9351 Mon Sep 17 00:00:00 2001 From: Gabby Morgan Date: Fri, 2 Oct 2026 19:47:56 +0000 Subject: [PATCH] bootstrap: seed config.json once; move refs to committed pins.json config.json is now per-machine USER config that no code writes: bootstrap seeds it from config.example.json only when absent, then reads every per-machine value from it. Flags override those values for the run only and are never written back. External refs (engine commit, GGUF url+sha256, HF tokenizer revision, simplex-chat version/url+sha256) move out of config into a committed, code-owned pins.json, so a git pull bump propagates on the next bootstrap run instead of being frozen per machine. The agent reads engine source/revision from pins.json and derives the GGUF path from engine.gguf_url under .runtime/models/ (an explicit engine.gguf in config.json overrides it). - config.example.json: drop all refs; ship the provisioned defaults (codegen.timeout 3600, gateway/bridge enabled, dashboard 127.0.0.1) - scripts/bootstrap.sh: seed config.json if absent, read pins from pins.json and per-machine values from config.json, never write config.json; drop the flags that only existed to populate config.json; US-delimit read fields so empty values do not shift later fields - semif_agent/cli.py: add load_pins / build_engine_config; load_config hard-errors when config.json is missing - tests/integration + README/AGENTS updated --- AGENTS.md | 79 ++++---- README.md | 49 +++-- config.example.json | 27 +-- pins.json | 16 ++ scripts/bootstrap.sh | 296 +++++++++++++---------------- semif_agent/cli.py | 63 ++++-- tests/integration/test_pipeline.py | 21 +- 7 files changed, 294 insertions(+), 257 deletions(-) create mode 100644 pins.json diff --git a/AGENTS.md b/AGENTS.md index a033131..59b9559 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -220,10 +220,16 @@ values are yours to choose. ## Git / sync - Push/pull from your git remote — never rsync/tar the code. -- **`config.json` is gitignored and per-machine** (hosts use different - engine/LLM paths and models). Copy `config.example.json` to `config.json` and - edit. `data/decisions.jsonl`, `data/runs.jsonl`, and `data/drafts/` are - runtime artifacts and gitignored too. +- **`config.json` is gitignored, per-machine, and required** (hosts use + different LLM/codegen endpoints and models). `scripts/bootstrap.sh` seeds it + from `config.example.json` once (only when absent) and **nothing writes it + afterwards — only a human edits `config.json`**. `data/decisions.jsonl`, + `data/runs.jsonl`, and `data/drafts/` are runtime artifacts and gitignored too. +- **`pins.json` is committed and code-owned** — the single home for every + external ref (SemIf commit, GGUF url+sha256, HF tokenizer revision, + simplex-chat version/url+sha256). These are bumped by a git change and picked + up on the next bootstrap run; they are deliberately NOT in `config.json` (a + ref replaced on every update is not per-machine user config). - Decision rows logged before the `run_id` threading landed show up under run_id `"?"` in the dashboard — that's expected, not a bug. @@ -453,16 +459,19 @@ CLI, unit tests (24) + integration tests (2). ### Provisioning (`scripts/bootstrap.sh`) - Provision a fresh Ubuntu machine into a running host: clone `semif-agent` to - a checkout (register its SSH key on your git host first), then - `scripts/bootstrap.sh --llm-url --codegen-url - --llm-model --codegen-model `. - The script must be run from a checkout — it reads pins from that checkout's - `config.example.json` and never re-clones the agent repo (only the SemIf - engine and the simplex-chat binary). Idempotent and rerunnable; every stage - no-ops on existing state, so it also boots an unknown-state machine. It - installs **no ollama**: `llm` is the local ollama (bootstrap pulls - `llm.model`), `codegen` may point at a peer host. It WARNs (never auto-pulls) - if the remote codegen host is missing its model. + a checkout (register its SSH key on your git host first), then run + `scripts/bootstrap.sh`. With no `config.json` yet it seeds one from + `config.example.json`; edit that to set `llm.model`/`codegen.model` and the + endpoints. Flags (`--llm-url`, `--codegen-url`, `--llm-model`, + `--codegen-model`) override the values read from `config.json` **for that run + only** and are never written back. The script must be run from a checkout — + it reads pins from that checkout's `pins.json` and never re-clones the agent + repo (only the SemIf engine and the simplex-chat binary). Idempotent and + rerunnable; every stage no-ops on existing state, so it also boots an + unknown-state machine. It installs **no ollama**: `llm` is the local ollama + (bootstrap pulls `llm.model` if configured), `codegen` may point at a peer + host. It WARNs (never auto-pulls) if the remote codegen host is missing its + model, and WARNs if `llm.model`/`codegen.model` are unset. - **All installation artifacts live inside the checkout under a gitignored `.runtime/`** (`venv/`, `engine/`, `models/`, `hf/`, `bin/simplex-chat`, `simplex/`, `systemd/`), so an end user can find and debug the whole stack in @@ -470,39 +479,41 @@ CLI, unit tests (24) + integration tests (2). (`~/.ssh`) and the real systemd user dir + linger (the rendered units are stored in `.runtime/systemd/` and symlinked into `~/.config/systemd/user/`). See the "Code principles" containment rule. -- All pins are read from `config.example.json`: the `engine` block +- All pins are read from the committed `pins.json`: the `engine` block (`semif_repo` public GitHub `TheoLeeCJ/SemIf`, `semif_ref` pinned commit, `gguf_url`/`gguf_sha256`, HF tokenizer `source`/`revision`) and the - `simplex_chat` block (`version`, `bin_url`, `sha256`, `port`, - `display_name`). The python dep pins live in `requirements/staging.txt` - (committed, one versioned artifact — every host provisions from it). - **Maintenance**: bump the pins in `config.example.json` / - `requirements/staging.txt`, rerun the script, re-run the integration tests. - The script never guesses. + `simplex_chat` block (`version`, `bin_url`, `sha256`). Per-machine + `simplex_chat` ports/display names stay in `config.json`. The python dep pins + live in `requirements/staging.txt` (committed, one versioned artifact — every + host provisions from it). The agent reads `engine.source`/`revision` from + `pins.json` and derives the GGUF path from `engine.gguf_url` under + `.runtime/models/` (an explicit `engine.gguf` in `config.json` overrides it). + **Maintenance**: bump the pins in `pins.json` / `requirements/staging.txt`, + rerun the script, re-run the integration tests. The script never guesses. - pip prints **expected** "dependency conflict" warnings at install time (semif-phase1 declares torch/accelerate/protobuf/sentencepiece/numpy 2.2.6 that we intentionally do not install — the llama.cpp CPU path doesn't need them; numpy 2.3.5 is deliberate, 2.2.6 has no cp314 wheel). Do not "fix" them by installing torch. -- Generates `config.json` with `llm.base_url` = `--llm-url`, `codegen.base_url` - = `--codegen-url` (`codegen.timeout: 3600` for a LAN), the model names from - `--llm-model`/`--codegen-model`, a repo-relative `.runtime/models` GGUF path, - and a backup of any prior file. `--threads N` overrides engine threads; - `--copy-data SRC` rsyncs a prior host's `data/` for continuity; - `--public-dashboard` binds the dashboard to `0.0.0.0`. - It also enables the SimpleX gateway (`gateway.simplex.enabled = true`, - `ws_url` from `simplex_chat.port`) and the standalone forwarding bridge - (`bridges.simplex.enabled = true`, `ws_url` from `simplex_chat.forward_port`, - top-level `simplex_bridge_url`), rendering/enabling four user services: +- Seeds `config.json` from `config.example.json` (only when absent) and **never + writes it again** — only a human edits `config.json`. `config.example.json` + ships the provisioned defaults, so a seeded `config.json` already has + `codegen.timeout: 3600`, the SimpleX gateway enabled + (`gateway.simplex.enabled = true`, `ws_url` from `simplex_chat.port`) and the + standalone forwarding bridge enabled (`bridges.simplex.enabled = true`, + `ws_url` from `simplex_chat.forward_port`, top-level `simplex_bridge_url`); + the operator sets `llm.model`/`llm.base_url` and `codegen.model`/ + `codegen.base_url`. Bootstrap renders/enables four user services: `semif-simplex.service` (the command `simplex-chat` bot daemon, `--create-bot-display-name` on `simplex_chat.port`), `semif-gateway.service` (`.runtime/venv/bin/python -m semif_agent.cli gateway`), `semif-simplex-forward.service` (the bridge's **own** daemon/profile on `simplex_chat.forward_port`) and `semif-bridge.service` - (`.runtime/venv/bin/python -m semif_agent.cli bridge`). `--simplex-allowed-users - CSV` / `--simplex-home-channel ID` / `--simplex-display-name NAME` populate - the gateway allowlist/fallback/identity; with an empty allowlist the gateway + (`.runtime/venv/bin/python -m semif_agent.cli bridge`). The gateway allowlist + (`gateway.simplex.allowed_users`) and fallback (`home_channel`) are + `config.json` fields the operator edits; with an empty allowlist the gateway denies everyone (the safe default until the human adds their contact id). + `--copy-data SRC` rsyncs a prior host's `data/` for continuity. Bootstrap then runs `scripts/simplex-address.py` to create/print the command bot's contact address (and the forwarding bot's, via `--ws-url`). - First run downloads the 2.8G GGUF and builds `llama-cpp-python` from source diff --git a/README.md b/README.md index e3bb6c9..e760103 100644 --- a/README.md +++ b/README.md @@ -384,7 +384,8 @@ tests/ stdlib unit tests + tests/integration (real engine + LLM) SKILL.md the contract fed to the skill-body codegen model TESTGEN.md the contract fed to the test/contract codegen model AGENTS.md the operational guide (read this before touching code) -config.example.json per-machine config template +config.example.json per-machine config template (seeded to config.json once) +pins.json committed pins: engine/GGUF/tokenizer/simplex-chat refs local/ gitignored: this deployment's notes (hosts, addresses, models) ``` @@ -418,13 +419,14 @@ build enables it), not ollama. On a fresh Ubuntu machine, from a checkout of this repo: ```sh -scripts/bootstrap.sh \ - --llm-url http://127.0.0.1:11434 \ - --codegen-url http://:11434 \ - --llm-model \ - --codegen-model +scripts/bootstrap.sh ``` +With no `config.json` yet, the script seeds one from `config.example.json`; edit +it to set `llm.model`/`codegen.model` (and the endpoints). Flags override those +values for the run only — `--llm-url`, `--codegen-url`, `--llm-model`, +`--codegen-model` — and are never written back to `config.json`. + The script is idempotent (every stage no-ops on existing state) and: 1. installs system prereqs + enables linger; @@ -435,18 +437,22 @@ The script is idempotent (every stage no-ops on existing state) and: 4. downloads and sha256-verifies the pinned GGUF into `.runtime/models/`; 5. pre-fetches the HF tokenizer into `.runtime/hf/`; 6. downloads and sha256-verifies the pinned `simplex-chat` binary; -7. writes `config.json` (paths, LLM/codegen URLs, dashboard, SimpleX); +7. seeds `config.json` from `config.example.json` **only if it does not already + exist** — it never rewrites `config.json` (only a human edits that file); 8. renders and enables systemd **user** units: `semif-simplex` (bot daemon), `semif-gateway` (agent gateway), `semif-simplex-forward` (the bridge's own daemon), `semif-bridge`; 9. prints the bot's SimpleX contact address. -Useful flags: `--threads N`, `--public-dashboard`, `--copy-data SRC`, -`--simplex-allowed-users CSV`, `--simplex-home-channel ID`, -`--simplex-display-name NAME`. Run `scripts/bootstrap.sh -h` for the full list. +Flags (`--llm-url`, `--codegen-url`, `--llm-model`, `--codegen-model`, +`--copy-data SRC`) override the values read from `config.json` for that run only. +Run `scripts/bootstrap.sh -h` for the full list. It installs **no ollama**; it expects one for `llm` and pulls `llm.model`, warning (never auto-pulling) if the remote codegen host is missing its model. +Pinned external refs (engine commit, GGUF url+sha256, HF tokenizer revision, +simplex-chat version/url+sha256) live in the committed `pins.json`, not in +`config.json`. ### Option B: core only (stdlib) @@ -458,22 +464,29 @@ python3 -m pytest tests/ -q --ignore=tests/integration For a full install on a machine you manage, follow the same steps bootstrap performs (venv, `semif-phase1 --no-deps`, `requirements/staging.txt`, GGUF, -tokenizer cache), then copy `config.example.json` to `config.json` and adjust -paths. - -### Configuration - -`config.json` is **gitignored and per-machine**. Copy the template and edit: +tokenizer cache), then create `config.json` from the template and adjust paths: ```sh cp config.example.json config.json ``` +### Configuration + +`config.json` is **gitignored, per-machine, and required** — the agent refuses +to start without it. `scripts/bootstrap.sh` seeds it from `config.example.json` +once; afterwards only a human edits it (nothing writes `config.json`). Pinned +external refs live in the committed `pins.json`, so `config.json` holds only +per-machine settings: + +```sh +cp config.example.json config.json # if not already created by bootstrap +``` + Key blocks: | Block | What it controls | | --- | --- | -| `engine` | SemIf source/revision, GGUF path, context, threads | +| `engine` | per-machine engine settings: backend, context, threads, optional GGUF path override (refs come from `pins.json`) | | `llm` | small model endpoint that authors new category/skill title + description | | `codegen` | skill-body model endpoint, timeouts, sampler, elicitation, fidelity, repair, test, degeneration watchdog, token budget | | `navigation` | two-stage guards: leaf `intent_tau`, category `category_tau` | @@ -483,7 +496,7 @@ Key blocks: | `gateway.simplex` | command gateway: ws_url, allowlist, batching | | `bridges.simplex` | forwarding bridge: host/port/token/ws_url | | `simplex_bridge_url` / `simplex_bridge_token` | what skill bodies call | -| `simplex_chat` | pinned simplex-chat binary + gateway/forward ports | +| `simplex_chat` | gateway/forward ports and bot display names (binary refs come from `pins.json`) | | `dashboard` | bind host/port | `llm.model` and `codegen.model` are **required** (no default): set each to a diff --git a/config.example.json b/config.example.json index 81141ed..4f5baae 100644 --- a/config.example.json +++ b/config.example.json @@ -1,5 +1,5 @@ { - "_comment": "Per-machine config. config.json is gitignored; copy this file to config.json and adjust paths. Every machine keeps its own config.json.", + "_comment": "Per-machine config. config.json is gitignored. bootstrap.sh seeds config.json from this file only when config.json does not exist, and NOTHING writes config.json afterwards — only a human edits it. Pinned engine/tokenizer/GGUF/simplex-chat refs live in the committed pins.json, not here. Every machine keeps its own config.json.", "tau": 0.6, "max_reentries": 3, "creation_approval": false, @@ -10,19 +10,13 @@ }, "queue": {"max_size": 100, "age_rate": 0.01}, "engine": { + "_comment": "Per-machine engine settings only. The pinned engine/tokenizer/GGUF refs (semif_repo, semif_ref, gguf_url, gguf_sha256, source, revision) live in the committed pins.json — bumped on update, never per-machine config. The GGUF path is derived from pins.json's engine.gguf_url under .runtime/models/; set `gguf` here only to override it with a custom path.", "backend": "llamacpp", - "source": "Qwen/Qwen3.5-4B", - "revision": "851bf6e806efd8d0a36b00ddf55e13ccb7b8cd0a", - "gguf": ".runtime/models/Qwen3.5-4B-Q4_K_M.gguf", - "gguf_url": "https://huggingface.co/bartowski/Qwen_Qwen3.5-4B-GGUF/resolve/main/Qwen_Qwen3.5-4B-Q4_K_M.gguf", - "gguf_sha256": "13c16f426047e2de38cd075bdade4a7bcbc8c774384876f677740cda65f8a983", - "semif_repo": "https://github.com/TheoLeeCJ/SemIf.git", - "semif_ref": "1f2dea3e25379f9dfc98cb83c324f00ab5deda37", "context_tokens": 4096, "threads": 8 }, "llm": { - "_comment": "Small OpenAI-compatible model that authors a new category/skill title + description (never the runnable body — that is `codegen` below). Deliberately its own endpoint/model, so it can be local and fast even when codegen is remote. Runs on THIS machine's local ollama; bootstrap sets base_url from --llm-url (default http://127.0.0.1:11434) and pulls `model` if it is missing. `model` is required (no default): set it to a model the endpoint serves. Uses the same provider machinery as codegen (real SSE stream, token budget, idle watchdog); short JSON replies. Sampler params (temperature/top_p/presence_penalty/frequency_penalty) are opt-in: an unset value is omitted from the request so the server's model default applies — set them here only when you know the right values for the model. The draft is authored asynchronously by a single-slot worker and the request re-runs when it lands; an unreachable endpoint is graceful (traced, user notified), not fatal. disable_thinking sends reasoning_effort:none so a reasoning model answers the short JSON directly instead of spending the reply budget on hidden chain-of-thought (set false only for an endpoint that rejects the parameter). provider selects the transport: \"ollama\" (default; a local OpenAI-compatible server, context auto-detected via /api/show) or \"opencode\" (the hosted OpenCode Console inference API at https://opencode.ai/inference/openai/v1 — set model to a Chat Completions family id such as kimi-k2.7-code or glm-5.3, and provide api_key or api_key_env; the ollama probe is skipped).", + "_comment": "Small OpenAI-compatible model that authors a new category/skill title + description (never the runnable body — that is `codegen` below). Deliberately its own endpoint/model, so it can be local and fast even when codegen is remote. Runs on THIS machine's local ollama; bootstrap reads base_url/model from here (a --llm-url/--llm-model flag overrides for that run only) and pulls `model` if it is missing. `model` is required (no default): set it to a model the endpoint serves. Uses the same provider machinery as codegen (real SSE stream, token budget, idle watchdog); short JSON replies. Sampler params (temperature/top_p/presence_penalty/frequency_penalty) are opt-in: an unset value is omitted from the request so the server's model default applies — set them here only when you know the right values for the model. The draft is authored asynchronously by a single-slot worker and the request re-runs when it lands; an unreachable endpoint is graceful (traced, user notified), not fatal. disable_thinking sends reasoning_effort:none so a reasoning model answers the short JSON directly instead of spending the reply budget on hidden chain-of-thought (set false only for an endpoint that rejects the parameter). provider selects the transport: \"ollama\" (default; a local OpenAI-compatible server, context auto-detected via /api/show) or \"opencode\" (the hosted OpenCode Console inference API at https://opencode.ai/inference/openai/v1 — set model to a Chat Completions family id such as kimi-k2.7-code or glm-5.3, and provide api_key or api_key_env; the ollama probe is skipped).", "provider": "ollama", "base_url": "http://localhost:11434/v1", "model": "", @@ -41,14 +35,14 @@ "disable_thinking": true }, "codegen": { - "_comment": "OpenAI-compatible model that writes runnable skill bodies. Runs on a REMOTE ollama host (bootstrap sets base_url from --codegen-url); the local small model is `llm` above. `model` is required (no default): set it to a code-capable model the endpoint serves. Bodies perform real actions against the user's configured services via stdlib transports, read every operational value from ctx.config, and declare their integration (INTEGRATION: service/transport/config_vars). Larger/slower than the decision or title/description model. The transport always streams so the client-side token budget (output cap / peak total fill) can abort a runaway in real time; stream only toggles console echo of tokens. timeout is total seconds; idle_warn/idle_timeout surface a silent (wedged) stream. The context window is auto-detected via ollama /api/show; context_window is the manual fallback (0 = auto/default 100000). smart_limit/warn_limit and max_fill_ratio/warn_fill_ratio bound total fill; max_output caps streamed output (>=1 absolute tokens, 0=1 absolute tokens, 0&2; usage 1 ;; esac @@ -81,6 +69,8 @@ done REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" EXAMPLE="$REPO_ROOT/config.example.json" +CONFIG="$REPO_ROOT/config.json" +PINS="$REPO_ROOT/pins.json" RUNTIME="$REPO_ROOT/.runtime" VENV="$RUNTIME/venv" @@ -98,70 +88,85 @@ if [[ ! -f "$EXAMPLE" ]]; then echo "config.example.json not found at $EXAMPLE — run from a semif-agent checkout" >&2 exit 1 fi +if [[ ! -f "$PINS" ]]; then + echo "pins.json not found at $PINS — run from a semif-agent checkout" >&2 + exit 1 +fi -# --- read pins from config.example.json ------------------------------------ -read -r SEMIF_REPO SEMIF_REF GGUF_URL GGUF_SHA256 HF_SOURCE HF_REV \ - SIMPLEX_BIN_URL SIMPLEX_SHA256 SIMPLEX_PORT SIMPLEX_DISPLAY \ - SIMPLEX_FORWARD_PORT SIMPLEX_FORWARD_DISPLAY EXAMPLE_LLM_MODEL \ - EXAMPLE_CODEGEN_MODEL < <( - python3 - "$EXAMPLE" <<'PY' +# config.json is per-machine USER config. Seed it once from the template, then +# never write it again — only a human edits config.json. +if [[ ! -f "$CONFIG" ]]; then + echo "== seeding config.json from config.example.json (edit it to configure this machine)" + cp "$EXAMPLE" "$CONFIG" +fi + +# --- read pins from the committed pins.json --------------------------------- +# The ASCII unit separator (\x1f) delimits fields so an empty value never +# shifts the fields after it (space-splitting collapses runs of whitespace). +IFS=$'\x1f' read -r SEMIF_REPO SEMIF_REF GGUF_URL GGUF_SHA256 HF_SOURCE HF_REV \ + SIMPLEX_BIN_URL SIMPLEX_SHA256 < <( + python3 - "$PINS" <<'PY' import json, sys -cfg = json.load(open(sys.argv[1])) -e = cfg["engine"] -s = cfg.get("simplex_chat", {}) -print( - " ".join( - [ - str(e.get("semif_repo", "")), - str(e.get("semif_ref", "")), - str(e.get("gguf_url", "")), - str(e.get("gguf_sha256", "")), - str(e.get("source", "")), - str(e.get("revision", "")), - str(s.get("bin_url", "")), - str(s.get("sha256", "")), - str(s.get("port", "")), - str(s.get("display_name", "")), - str(s.get("forward_port", "")), - str(s.get("forward_display_name", "")), - str(cfg.get("llm", {}).get("model", "")), - str(cfg.get("codegen", {}).get("model", "")), - ] - ) -) +pins = json.load(open(sys.argv[1])) +e = pins["engine"] +s = pins.get("simplex_chat", {}) +print("\x1f".join([ + str(e.get("semif_repo", "")), + str(e.get("semif_ref", "")), + str(e.get("gguf_url", "")), + str(e.get("gguf_sha256", "")), + str(e.get("source", "")), + str(e.get("revision", "")), + str(s.get("bin_url", "")), + str(s.get("sha256", "")), +])) PY ) if [[ -z "$SEMIF_REPO" || -z "$SEMIF_REF" || -z "$GGUF_URL" || -z "$GGUF_SHA256" ]]; then - echo "engine pins missing in $EXAMPLE (semif_repo/semif_ref/gguf_url/gguf_sha256)" >&2 + echo "engine pins missing in $PINS (semif_repo/semif_ref/gguf_url/gguf_sha256)" >&2 exit 1 fi -if [[ -z "$SIMPLEX_BIN_URL" || -z "$SIMPLEX_SHA256" || -z "$SIMPLEX_PORT" ]]; then - echo "simplex_chat pins missing in $EXAMPLE (bin_url/sha256/port)" >&2 +if [[ -z "$SIMPLEX_BIN_URL" || -z "$SIMPLEX_SHA256" ]]; then + echo "simplex_chat pins missing in $PINS (bin_url/sha256)" >&2 exit 1 fi -# Model names are deployment-specific and user-supplied: prefer the CLI flag, -# else fall back to config.example.json. There is deliberately no default. -LLM_MODEL="${LLM_MODEL:-$EXAMPLE_LLM_MODEL}" -CODEGEN_MODEL="${CODEGEN_MODEL:-$EXAMPLE_CODEGEN_MODEL}" -if [[ -z "$CODEGEN_URL" ]]; then - echo "--codegen-url is required (the ollama API for codegen skill bodies)" >&2 - exit 1 -fi -if [[ -z "$LLM_MODEL" ]]; then - echo "--llm-model is required (or set llm.model in config.example.json)" >&2 - exit 1 -fi -if [[ -z "$CODEGEN_MODEL" ]]; then - echo "--codegen-model is required (or set codegen.model in config.example.json)" >&2 - exit 1 -fi +# --- read per-machine values from config.json (flags override for this run) -- +IFS=$'\x1f' read -r CFG_LLM_URL CFG_LLM_MODEL CFG_CODEGEN_URL CFG_CODEGEN_MODEL \ + SIMPLEX_PORT SIMPLEX_DISPLAY SIMPLEX_FORWARD_PORT SIMPLEX_FORWARD_DISPLAY < <( + python3 - "$CONFIG" <<'PY' +import json, sys +cfg = json.load(open(sys.argv[1])) +s = cfg.get("simplex_chat", {}) +def strip_v1(u): + u = str(u or "").rstrip("/") + return u[:-3] if u.endswith("/v1") else u +print("\x1f".join([ + strip_v1(cfg.get("llm", {}).get("base_url")), + str(cfg.get("llm", {}).get("model", "") or ""), + strip_v1(cfg.get("codegen", {}).get("base_url")), + str(cfg.get("codegen", {}).get("model", "") or ""), + str(s.get("port", "")), + str(s.get("display_name", "") or ""), + str(s.get("forward_port", "")), + str(s.get("forward_display_name", "") or ""), +])) +PY +) -if [[ -n "$SIMPLEX_DISPLAY_NAME" ]]; then - SIMPLEX_DISPLAY="$SIMPLEX_DISPLAY_NAME" +# A flag overrides config.json for this run only; config.json is never touched. +LLM_URL="${LLM_URL:-${CFG_LLM_URL:-http://127.0.0.1:11434}}" +CODEGEN_URL="${CODEGEN_URL:-$CFG_CODEGEN_URL}" +LLM_MODEL="${LLM_MODEL:-$CFG_LLM_MODEL}" +CODEGEN_MODEL="${CODEGEN_MODEL:-$CFG_CODEGEN_MODEL}" + +if [[ -z "$SIMPLEX_PORT" || -z "$SIMPLEX_FORWARD_PORT" ]]; then + echo "config.json: simplex_chat.port and simplex_chat.forward_port are required" >&2 + exit 1 fi SIMPLEX_DISPLAY="${SIMPLEX_DISPLAY:-semif}" +SIMPLEX_FORWARD_DISPLAY="${SIMPLEX_FORWARD_DISPLAY:-semif-forward}" # Native ollama API bases (no /v1) for tags/pull; the clients use /v1. LLM_API="${LLM_URL%/v1}"; LLM_API="${LLM_API%/}" @@ -274,57 +279,9 @@ fi simplex_ok || { echo "simplex-chat sha256 mismatch: expected $SIMPLEX_SHA256" >&2; exit 1; } echo "== simplex-chat verified ($SIMPLEX_BIN)" -# --- stage 7: config.json ----------------------------------------------------------- -if [[ -f "$REPO_ROOT/config.json" ]]; then - cp "$REPO_ROOT/config.json" "$REPO_ROOT/config.json.bak.$(date +%s)" -fi -echo "== writing config.json (llm -> $LLM_URL, codegen -> $CODEGEN_URL, runtime -> $RUNTIME)" -python3 - "$REPO_ROOT/config.example.json" "$REPO_ROOT/config.json" "$THREADS" "$LLM_URL" "$CODEGEN_URL" \ - "$([ "$PUBLIC_DASHBOARD" = 1 ] && echo 0.0.0.0 || echo 127.0.0.1)" \ - "$REPO_ROOT" "$SIMPLEX_ALLOWED_USERS" "$SIMPLEX_HOME_CHANNEL" "$SIMPLEX_DISPLAY" \ - "$LLM_MODEL" "$CODEGEN_MODEL" <<'PY' -import json, os, sys -(example, out, threads, llm_url, codegen_url, dash_host, repo, - allowed_csv, home_channel, display, llm_model, codegen_model) = sys.argv[1:] -cfg = json.load(open(example)) -eng = cfg["engine"] -runtime = os.path.join(repo, ".runtime") -eng["gguf"] = os.path.join(runtime, "models", os.path.basename(eng["gguf_url"])) -if threads and threads != "__example__": - eng["threads"] = int(threads) -# The clients hit {base_url}/chat/completions on ollama's OpenAI-compat path, -# which lives under /v1. The native API (/api/tags, /api/show) has no /v1. -def v1(url): - url = url.rstrip("/") - return url if url.endswith("/v1") else url + "/v1" -cfg["llm"]["base_url"] = v1(llm_url) -cfg["llm"]["model"] = llm_model -cfg["codegen"]["base_url"] = v1(codegen_url) -cfg["codegen"]["model"] = codegen_model -cfg["codegen"]["timeout"] = 3600 -cfg.setdefault("simplex_chat", {})["display_name"] = display -cfg.setdefault("dashboard", {})["port"] = 8765 -cfg["dashboard"]["host"] = dash_host -allowed = [u.strip() for u in allowed_csv.split(",") if u.strip()] -simplex = cfg.setdefault("gateway", {}).setdefault("simplex", {}) -simplex["enabled"] = True -simplex["ws_url"] = f"ws://127.0.0.1:{cfg['simplex_chat'].get('port', 5226)}" -simplex["allowed_users"] = allowed -simplex["home_channel"] = home_channel -# The standalone SimpleX forwarding bridge owns its own daemon/profile -# (simplex_chat.forward_port), separate from the command gateway, and serves the -# invite-link / read / send HTTP API skills use. Expose its URL as the top-level -# `simplex_bridge_url` so the data-contract config search auto-populates it, and -# mirror its optional shared secret as `simplex_bridge_token` for the auth header. -bridge = cfg.setdefault("bridges", {}).setdefault("simplex", {}) -bridge_port = int(bridge.get("port", 5227)) -bridge["enabled"] = True -bridge["ws_url"] = f"ws://127.0.0.1:{cfg['simplex_chat'].get('forward_port', 5228)}" -cfg["simplex_bridge_url"] = f"http://127.0.0.1:{bridge_port}" -cfg["simplex_bridge_token"] = bridge.get("token", "") or "" -simplex.pop("bridge", None) # legacy key; forwarding is a separate service now -json.dump(cfg, open(out, "w"), indent=2) -PY +# config.json is USER config: seeded above if absent, read for per-machine values, +# and never written by this script. Edit config.json to change endpoints, models, +# ports, the dashboard bind, or the gateway allowlist. # --- stage 8: systemd user units ----------------------------------------------------- render_unit() { @@ -433,43 +390,51 @@ echo "== verifying imports" # The small self-assessment model runs on this machine's local ollama; ensure it # is pulled so assess/elicitation/fidelity work without a remote dependency. -echo "== llm ollama ($LLM_API), model $LLM_MODEL" -if ! curl -sf --max-time 5 "$LLM_API/api/tags" >/dev/null 2>&1; then - echo "WARN: no local ollama at $LLM_API — install/run ollama and pull $LLM_MODEL" >&2 - echo " (bootstrap installs no ollama; only codegen is remote)" >&2 +if [[ -z "$LLM_MODEL" ]]; then + echo "WARN: llm.model is not set in config.json — set it (and codegen.model) before starting the agent" >&2 else - LLM_TAGS="$(curl -sf --max-time 5 "$LLM_API/api/tags" || true)" - if grep -qF "\"$LLM_MODEL\"" <<<"$LLM_TAGS"; then - echo "llm model $LLM_MODEL: present" + echo "== llm ollama ($LLM_API), model $LLM_MODEL" + if ! curl -sf --max-time 5 "$LLM_API/api/tags" >/dev/null 2>&1; then + echo "WARN: no local ollama at $LLM_API — install/run ollama and pull $LLM_MODEL" >&2 + echo " (bootstrap installs no ollama; only codegen is remote)" >&2 else - echo "== pulling llm model $LLM_MODEL from $LLM_API" - if ! curl -sf --max-time 3600 "$LLM_API/api/pull" -H 'Content-Type: application/json' \ - -d "{\"model\":\"$LLM_MODEL\",\"stream\":false}" >/dev/null; then - echo "WARN: /api/pull failed; trying the ollama CLI" >&2 - if command -v ollama >/dev/null 2>&1; then - ollama pull "$LLM_MODEL" || echo "WARN: could not pull $LLM_MODEL" >&2 - else - echo "WARN: could not pull $LLM_MODEL (no ollama CLI)" >&2 + LLM_TAGS="$(curl -sf --max-time 5 "$LLM_API/api/tags" || true)" + if grep -qF "\"$LLM_MODEL\"" <<<"$LLM_TAGS"; then + echo "llm model $LLM_MODEL: present" + else + echo "== pulling llm model $LLM_MODEL from $LLM_API" + if ! curl -sf --max-time 3600 "$LLM_API/api/pull" -H 'Content-Type: application/json' \ + -d "{\"model\":\"$LLM_MODEL\",\"stream\":false}" >/dev/null; then + echo "WARN: /api/pull failed; trying the ollama CLI" >&2 + if command -v ollama >/dev/null 2>&1; then + ollama pull "$LLM_MODEL" || echo "WARN: could not pull $LLM_MODEL" >&2 + else + echo "WARN: could not pull $LLM_MODEL (no ollama CLI)" >&2 + fi fi fi - fi - # The OpenAI-compat chat path is what llm actually hits; probe it explicitly. - LLM_V1_OK="$(curl -sf --max-time 60 "$LLM_V1/chat/completions" -H 'Content-Type: application/json' \ - -d "{\"model\":\"$LLM_MODEL\",\"messages\":[{\"role\":\"user\",\"content\":\"hi\"}],\"stream\":false,\"options\":{\"num_predict\":1}}" || true)" - if grep -qE 'chatcmpl|"choices"' <<<"$LLM_V1_OK"; then - echo "llm /v1/chat/completions ($LLM_MODEL): OK" - else - echo "WARN: local llm /v1/chat/completions returned no completion" >&2 + # The OpenAI-compat chat path is what llm actually hits; probe it explicitly. + LLM_V1_OK="$(curl -sf --max-time 60 "$LLM_V1/chat/completions" -H 'Content-Type: application/json' \ + -d "{\"model\":\"$LLM_MODEL\",\"messages\":[{\"role\":\"user\",\"content\":\"hi\"}],\"stream\":false,\"options\":{\"num_predict\":1}}" || true)" + if grep -qE 'chatcmpl|"choices"' <<<"$LLM_V1_OK"; then + echo "llm /v1/chat/completions ($LLM_MODEL): OK" + else + echo "WARN: local llm /v1/chat/completions returned no completion" >&2 + fi fi fi # Codegen is the larger model, possibly on a remote host. Warn only — never auto-pull. -echo "== codegen ollama ($CODEGEN_API)" -CODEGEN_TAGS="$(curl -sf --max-time 5 "$CODEGEN_API/api/tags" || true)" -if grep -qF "$CODEGEN_MODEL" <<<"$CODEGEN_TAGS"; then - echo "codegen serves $CODEGEN_MODEL: OK" +if [[ -n "$CODEGEN_URL" && -n "$CODEGEN_MODEL" ]]; then + echo "== codegen ollama ($CODEGEN_API)" + CODEGEN_TAGS="$(curl -sf --max-time 5 "$CODEGEN_API/api/tags" || true)" + if grep -qF "$CODEGEN_MODEL" <<<"$CODEGEN_TAGS"; then + echo "codegen serves $CODEGEN_MODEL: OK" + else + echo "WARN: codegen host $CODEGEN_API serves no $CODEGEN_MODEL (offline? new-skill authoring will fail)" >&2 + fi else - echo "WARN: codegen host $CODEGEN_API serves no $CODEGEN_MODEL (offline? new-skill authoring will fail)" >&2 + echo "WARN: codegen.base_url/model is not set in config.json — set it before starting the agent" >&2 fi if command -v systemctl >/dev/null 2>&1; then @@ -483,6 +448,9 @@ fi cat < dict: def load_config(path: str = "config.json") -> dict: """Load config.json and anchor its runtime paths to the checkout root. + config.json is the per-machine user config and is required: bootstrap.sh + seeds it from config.example.json once, and only a human edits it. There is + no in-code fallback — a missing config.json is a hard error. + Path-valued keys (`skill_seeds`, `skill_bodies`, `category_registry`, `log`, `trace`) resolve against REPO_ROOT, not the process cwd, so a fresh clone loads its committed seeds and writes runtime artifacts into the checkout no matter where the CLI is invoked from. Absolute values pass through untouched. """ - config = json.loads(Path(path).read_text()) + config_path = Path(path) + if not config_path.is_file(): + raise SystemExit( + f"config.json not found at {config_path} — run scripts/bootstrap.sh " + f"to seed it from config.example.json, then configure it" + ) + config = json.loads(config_path.read_text()) for key in _PATH_KEYS: config[key] = _anchor_path(config.get(key) or _PATH_DEFAULTS[key]) return config -def build_scheduler(config: dict) -> tuple[Scheduler, dict]: - engine = SemIfEngine( - EngineConfig( - backend=config.get("engine", {}).get("backend", "llamacpp"), - source=config.get("engine", {}).get("source", ""), - revision=config.get("engine", {}).get("revision", ""), - gguf=config.get("engine", {}).get("gguf", ""), - context_tokens=int(config.get("engine", {}).get("context_tokens", 4096)), - threads=config.get("engine", {}).get("threads"), - ) +def load_pins(path: str | None = None) -> dict: + """Load the committed pin manifest (pins.json) that owns every external ref. + + Pins are code, not per-machine config: the SemIf engine commit, GGUF + url+sha256, HF tokenizer revision, and simplex-chat version/url+sha256 live + in pins.json so a `git pull` bump propagates on the next bootstrap run + instead of being frozen in each machine's config.json. + """ + pins_path = Path(path) if path else REPO_ROOT / "pins.json" + if not pins_path.is_file(): + raise SystemExit(f"pins.json not found at {pins_path}") + return json.loads(pins_path.read_text()) + + +def build_engine_config(config: dict, pins: dict | None = None) -> EngineConfig: + """Engine settings for a run: per-machine tuning from config.json, pinned + refs from pins.json. + + `engine.backend`/`context_tokens`/`threads` are per-machine config. The + tokenizer source/revision and the GGUF are pins; the GGUF path is derived + from the pin's filename under `.runtime/models/`, unless config.json sets an + explicit `engine.gguf` override. + """ + pins = load_pins() if pins is None else pins + eng = config.get("engine", {}) or {} + pin_eng = pins.get("engine", {}) or {} + override = eng.get("gguf") + gguf = _anchor_path(override) if override else str( + REPO_ROOT / ".runtime" / "models" / os.path.basename(pin_eng.get("gguf_url", "")) ) + return EngineConfig( + backend=eng.get("backend", "llamacpp"), + source=pin_eng.get("source", ""), + revision=pin_eng.get("revision", ""), + gguf=gguf, + context_tokens=int(eng.get("context_tokens", 4096)), + threads=eng.get("threads"), + ) + + +def build_scheduler(config: dict) -> tuple[Scheduler, dict]: + engine = SemIfEngine(build_engine_config(config)) llm_cfg = config.get("llm", {}) or {} llm_provider = str(llm_cfg.get("provider", "ollama") or "ollama").lower() llm_cls = ConsoleLLMClient if llm_provider == "opencode" else LLMClient diff --git a/tests/integration/test_pipeline.py b/tests/integration/test_pipeline.py index f24337d..08a3ea4 100644 --- a/tests/integration/test_pipeline.py +++ b/tests/integration/test_pipeline.py @@ -12,7 +12,13 @@ import time import pytest -from semif_agent.cli import _opt_float, _required_model, build_scheduler, load_config +from semif_agent.cli import ( + _opt_float, + _required_model, + build_engine_config, + build_scheduler, + load_config, +) from semif_agent.codegen import ( CodegenClient, generate_skill_body, @@ -40,18 +46,9 @@ from semif_agent.skills import ( def require_real(config: dict): - from semif_agent.engine import SemIfEngine, EngineConfig + from semif_agent.engine import SemIfEngine - engine = SemIfEngine( - EngineConfig( - backend=config.get("engine", {}).get("backend", "llamacpp"), - source=config.get("engine", {}).get("source", ""), - revision=config.get("engine", {}).get("revision", ""), - gguf=config.get("engine", {}).get("gguf", ""), - context_tokens=int(config.get("engine", {}).get("context_tokens", 4096)), - threads=config.get("engine", {}).get("threads"), - ) - ) + engine = SemIfEngine(build_engine_config(config)) try: engine._ensure_loaded() except EngineUnavailable as exc: