From 38cba33bbf2576a101a591f638d24f8e4be7f590 Mon Sep 17 00:00:00 2001 From: Gabby Morgan Date: Fri, 2 Oct 2026 18:07:39 +0000 Subject: [PATCH] remove dev environment references from codebase --- .gitignore | 5 +- AGENTS.md | 273 +++++++++++------------------ README.md | 51 +++--- config.example.json | 12 +- requirements/staging.txt | 2 +- scripts/bootstrap.sh | 66 +++++-- scripts/tune_navigation.py | 4 +- semif_agent/cli.py | 23 ++- semif_agent/codegen.py | 4 +- semif_agent/dashboard.py | 6 +- semif_agent/llm.py | 2 +- tests/conftest.py | 2 +- tests/integration/test_pipeline.py | 12 +- tests/test_dashboard_api.py | 6 +- tests/test_gateway.py | 4 +- tests/test_no_env_leaks.py | 100 +++++++++++ tests/test_simplex_ws.py | 2 +- tests/test_skills.py | 2 +- 18 files changed, 327 insertions(+), 249 deletions(-) create mode 100644 tests/test_no_env_leaks.py diff --git a/.gitignore b/.gitignore index 78989ad..936d65f 100644 --- a/.gitignore +++ b/.gitignore @@ -12,8 +12,9 @@ data/drafts/ .pytest_cache/ config.json *.log -# Machine-specific experiments/recipes (GPU offload probe, benchmark harness). -# Deliberately not part of the shipped agent. +# Machine-specific material: deployment notes (hostnames, addresses, SSH, +# model choices), GPU offload probe, benchmark harness. Deliberately not part +# of the shipped agent. local/ *.egg-info/ *.bak.* \ No newline at end of file diff --git a/AGENTS.md b/AGENTS.md index 1268911..a033131 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -204,90 +204,35 @@ simplex_ws.py neutral SimpleX daemon protocol shared by the command gateway ## Run / verify -Dev machine is a thin client (no GPU, ~1.4G disk): only pure stdlib unit tests -run here (`python3 -m pytest tests/ -q --ignore=tests/integration`). -Integration tests run on the staging machine `jarvis` (see "### jarvis (staging)"). +Pure stdlib unit tests run anywhere: +`python3 -m pytest tests/ -q --ignore=tests/integration`. Integration tests need +a real SemIf engine + a real LLM endpoint; run them on a provisioned host (see +"### Provisioning (`scripts/bootstrap.sh`)"). + +## Local deployment notes + +This repo is generic: it names no particular host, address, path, or model. +**Every deployment-specific value lives in the gitignored `local/` folder** — +see `local/ENVIRONMENT.md` for this deployment's hostnames, addresses, SSH keys, +paths, and model choices. If that file is absent, this is a fresh clone and the +values are yours to choose. ## Git / sync -- Canonical repo lives on Gitea: `git.manyworlds.fit`, **SSH on port 222** - (`ssh://git@git.manyworlds.fit:222/gabby/semif-agent.git`). Key - `~/.ssh/id_ed25519` is registered there. The staging machine `jarvis` runs - from a manual clone at `~/repos/semif-agent` (`scripts/bootstrap.sh` provisions - everything else and never re-clones the agent repo); the old box working copy - is also at `~/repos/semif-agent` (its editable install still points at the moved - `~/semif-agent`, so `import semif_agent` is broken there — moot, guppy runs - ollama only now); the dev machine at `~/Repos/semif-agent`. Push/pull from - Gitea — never rsync/tar the code. -- **`config.json` is gitignored and per-machine** (dev and the box use different - engine/LLM paths). Copy `config.example.json` to `config.json` and edit. - `data/decisions.jsonl`, `data/runs.jsonl`, and `data/drafts/` are runtime - artifacts and gitignored too. -- The Gitea instance was rebuilt fresh (Sep 2026) after its git pack transfer - broke (`sh: bad option '--oneshot'` — a stray system `uploadpack.packObjectsHook` - killed pack generation; the old AGENTS.md note blaming `authorized_keys` was - a misdiagnosis). Both the dev key (`shitass@nunya`) and the box key - (`guppy@semif-agent`) are re-registered; clone/fetch/push all work now. If a - fresh machine can't pull, the durable fix is on the Gitea host: - `git config --system --unset-all uploadpack.packObjectsHook`. +- 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. - Decision rows logged before the `run_id` threading landed show up under run_id `"?"` in the dashboard — that's expected, not a bug. -Machine split (Sep 2026): **guppy** hosts the remote **codegen** model (the -12G `qwen38-iq3s`) only; **jarvis** is the staging/test target (semif-agent + -SemIf engine + deps) and runs its **own local ollama** serving the small -title/description model (`qwen3.5:4b`). Only codegen traffic travels to guppy. -Provision jarvis with `scripts/bootstrap.sh` (see "### jarvis (staging)"). - -**Connecting to jarvis (`ssh jarvis@192.168.8.130`)**: this is a plain `ssh` -call. The key `~/.ssh/id_ed25519` is passphrase-protected and Linux Mint pops an -askpass dialog for it; the flatpak overlay -(`SSH_AUTH_SOCK=/run/flatpak/ssh-auth`) blocks the user's password locker, so -they cannot paste from it and must type the passphrase by hand. **Warn the user -right before running the command** ("about to ssh to jarvis — be ready to type -your passphrase") so they can enter it, then just run `ssh`. Do **not** burn -tokens on ssh-agent/askpass/fixed-socket workarounds — once the user types the -passphrase at the prompt, plain `ssh` works for the session. The `agent refused -operation` error from the flatpak socket is exactly this prompt, not a broken -key. - -Guppy key facts: - -- ssh key `~/.ssh/id_ed25519` is passphrase-protected. Load it into an agent at - a fixed socket before connecting (the default flatpak `SSH_AUTH_SOCK` refuses): - ```sh - SOCK=/tmp/opencode/ssh-agent.sock; rm -f "$SOCK"; eval $(ssh-agent -a "$SOCK") - printf '#!/bin/sh\necho ""\n' > /tmp/opencode/askpass.sh; chmod 700 /tmp/opencode/askpass.sh - SSH_ASKPASS=/tmp/opencode/askpass.sh SSH_ASKPASS_REQUIRE=force setsid -w ssh-add ~/.ssh/id_ed25519 - ``` - The agent dies if this machine restarts; redo it each session. -- The agent on guppy is **deprecated** (guppy is ollama-only now). The box - venv's editable install (`__editable__.semif_agent_0_1_0_finder.py`) still - maps to `/home/abby/semif-agent`, which was moved to `~/repos/semif-agent`, - so `import semif_agent` fails there — expected, not a bug. Run the agent on - **jarvis** instead (below). -- Dashboard: runs as a systemd **user** service on the box - (`semif-dashboard.service`, linger enabled, binds `0.0.0.0:8765`), so it's up - after reboots with no manual launch — browser UI at http://192.168.8.181:8765/. - Manage it with `systemctl --user status/restart semif-dashboard.service`. - Note the submit/relabel POST endpoints are therefore open to the whole LAN. - It works in live mode on the box (submit runs the real engine + LLM) and in - replay mode anywhere (`--replay`; reads decisions.jsonl + runs.jsonl; submit - degrades to a JSON error without the engine). Relabeling in the UI writes a - human override (3x weight in dream) via `POST /api/relabel`. On the dev - machine, replay mode: `cd ~/Repos/semif-agent && python3 -m semif_agent.cli - dashboard --replay` (binds 127.0.0.1:8765). -- Integration tests (real engine + real LLM) only run on the box: - `~/semif-venv/bin/python -m pytest tests/integration -q -s` - They take ~100s (model load ~34s). Run them in the background and poll — - long-lived ssh sessions get SIGHUP'd and kill the run. - ## Roadmap ### v1 (done) Core loop, urgency queue, skill tree, skill loop with real SemIf assessment (decision, not generation), decision logging, `dream` cost pass, REPL + JSONL -CLI, unit tests (24) + box integration tests (2). +CLI, unit tests (24) + integration tests (2). ### v2 - Real fine-tuning from `decisions.jsonl` at a regular interval ("dreaming"): @@ -302,7 +247,7 @@ CLI, unit tests (24) + box integration tests (2). persisted to `data/categories.json` (under that category's `skills` list) and merged into the running tree as a leaf. Since Sep 2026 the leaf also gets a real runnable body via the async authoring pipeline: a larger - OpenAI-compatible model (`codegen`, default `qwen38-iq3s`) writes an `act`-only + OpenAI-compatible model (`codegen`, your configured code-capable model) writes an `act`-only body plus its own flat `CONTRACT` against `SKILL.md`, then a test (against `TESTGEN.md`) is generated and auto-run before the leaf is declared ready — all persisted to a folder in `data/skills/` and @@ -446,35 +391,33 @@ CLI, unit tests (24) + box integration tests (2). ## Constraints & gotchas (learned the hard way) ### Environment -- **Dev box**: Python 3.13, GTX 780M (Kepler, useless), ~1.4G disk free. Never - pip-install heavy deps here. -- **guppy box**: Python 3.14, AMD RX 6950 XT (gfx1030), 32 cores, 30G RAM, - passwordless sudo. Now serves **codegen only** (`qwen38-iq3s`). SemIf runs via - llama.cpp **CPU** backend (its llamacpp backend forces `n_gpu_layers=0`), so - the GPU is NOT used by the decision engine — it IS used by ollama. -- **jarvis box**: runs the agent and its **own local ollama** serving the small - title/description model (`qwen3.5:4b`). `config.json` `llm.base_url` points at - `http://127.0.0.1:11434/v1`; only `codegen.base_url` points at guppy. +- The core is pure stdlib and runs anywhere Python does. Never pip-install heavy + deps on a thin client; a full install belongs on a provisioned host. +- The SemIf engine runs via llama.cpp **CPU** backend (its llamacpp backend + forces `n_gpu_layers=0`), so the decision engine does not use a GPU; ollama + does. - The SemIf tokenizer is fetched from HF (`Qwen/Qwen3.5-4B` at the pinned revision), cached under each checkout's `.runtime/hf` (`HF_HOME`). +- Per-host specs and model choices for this deployment: `local/ENVIRONMENT.md`. -### SemIf install (box) -- **Legacy layout** (predates the `.runtime/` containment rule; kept for the - deprecated guppy agent venv). New machines use `scripts/bootstrap.sh`, which - installs the venv/engine/GGUF/cache under the checkout's `.runtime/` — see - "### jarvis (staging)" and "Code principles". +### SemIf install +- New machines use `scripts/bootstrap.sh`, which installs the venv/engine/GGUF/ + cache under the checkout's `.runtime/` — see "### Provisioning + (`scripts/bootstrap.sh`)" and "Code principles". (A legacy layout that + installed the engine outside the checkout predates the `.runtime/` + containment rule; prefer bootstrap.) - SemIf hard-pins `torch==2.10.0`, `numpy==2.2.6`, etc. The llamacpp path does **not** need torch (torch is imported lazily inside `direct.score`). Install with `--no-deps` and bring only what's needed — the committed manifest `requirements/staging.txt` is the single source of truth: - `pip install -e ~/semif --no-deps`, then + `pip install -e --no-deps`, then `CMAKE_BUILD_PARALLEL_LEVEL=6 MAKEFLAGS=-j6 pip install -r requirements/staging.txt` (numpy 2.3.5, transformers 5.17.0, tokenizers 0.23.2, huggingface-hub 1.31.0, llama-cpp-python 0.3.35, pytest). - **Expected pip warnings:** pip reports "dependency conflicts" against semif-phase1's declared requirements (torch/accelerate/protobuf/sentencepiece - not installed, numpy 2.2.6 vs 2.3.5). These are informational — the box runs - exactly this set — not a bug; do not "fix" them by installing torch. + not installed, numpy 2.2.6 vs 2.3.5). These are informational — the staging + host runs exactly this set — not a bug; do not "fix" them by installing torch. - `numpy==2.2.6` has **no cp314 wheel** → pip tries a source build that fails without `pkg-config` + `python3-dev`. Use numpy 2.3.5 (has cp314 wheels). - `llama-cpp-python==0.3.35` builds from source. With all 32 cores it OOM-kills @@ -482,57 +425,44 @@ CLI, unit tests (24) + box integration tests (2). `CMAKE_BUILD_PARALLEL_LEVEL=6 MAKEFLAGS=-j6 pip install llama-cpp-python==0.3.35`. Do NOT bump the llama-cpp-python version — SemIf calls specific llama.cpp C APIs that change between versions. -- The pinned GGUF: `Qwen3.5-4B-Q4_K_M.gguf` from bartowski (2.8G) at - `~/models/`. Load ~34s; score ~0.9s/decision on CPU at 8 threads. +- The pinned GGUF: `Qwen3.5-4B-Q4_K_M.gguf` from bartowski (2.8G), downloaded + into `.runtime/models/` by bootstrap. Load ~34s; score ~0.9s/decision on CPU + at 8 threads. ### ollama -- **guppy = codegen host.** Installed at `/home/abby/ollama/bin/ollama` (not on - PATH), systemd service `ollama.service`, ROCm backend with - `HSA_OVERRIDE_GFX_VERSION=10.3.0` and KV cache q4_0 + flash attention. Serves - `qwen38-iq3s` (12G 27B, the codegen model). Binds `OLLAMA_HOST=0.0.0.0`, so - jarvis reaches it as a plain remote API at `http://192.168.8.181:11434` (no - auth — LAN-visible, same exposure as the old dashboard POST endpoints). -- `semif-hermes` / `semif-hermes-v3` are for ANOTHER project (hermes agent) — - ignore them; they spew "token repeat limit" errors. -- If generation hangs with no log output, restart the service - (`sudo systemctl restart ollama`) — the ROCm runner can wedge. -- **jarvis = local small model.** Runs its own ollama (`/usr/local/bin/ollama`, - systemd `ollama.service`, `127.0.0.1:11434`) serving `qwen3.5:4b` for - new-skill title/description authoring (~3s). `bootstrap.sh` ensures - that model is pulled; `config.json` `llm.base_url` points here. -- `bootstrap.sh` installs **no ollama**: it expects the target box to already - run one for `llm` (and pulls `llm.model` into it), while codegen is remote. -- **The local `llm` model is a reasoning model — thinking must be off.** The - default `qwen3.5:4b` has ollama's `thinking` capability: it emits hidden - chain-of-thought and puts the answer in `content`. Through the `/v1` compat - endpoint the CoT consumes the entire reply budget, so +- `bootstrap.sh` installs **no ollama**: it expects the target host to already + run one for `llm` (and pulls `llm.model` into it), while `codegen` may be + remote. Point `--llm-url`/`--codegen-url` at the right daemons. +- If generation hangs with no log output, restart the ollama service — the GPU + runner can wedge. +- **A local reasoning model needs thinking off for `llm`.** A reasoning model + emits hidden chain-of-thought and puts the answer in `content`. Through the + `/v1` compat endpoint the CoT consumes the entire reply budget, so `generate_category`/`generate_skill`'s `max_tokens=128` returns `finish_reason: length` with `content: ""` → `JSONDecodeError` and a traced `draft_failed` (no category/skill is ever authored — the whole create branch - is silently dead). `LLMClient` now sends `reasoning_effort: "none"` + is silently dead). `LLMClient` sends `reasoning_effort: "none"` (`llm.disable_thinking`, **default on**) so the model answers the ~30-token - JSON directly (~2.5s). Ollama's native `think:false` is **not** plumbed + JSON directly. Ollama's native `think:false` is **not** plumbed through `/v1` (silently ignored), and `/no_think` in the prompt is ignored too; only `reasoning_effort` works there. Codegen *wants* the reasoning, so the knob is `llm`-only — `CodegenClient` never sets it. Unbounded (no - `max_tokens`) does not help: the model loops on this prompt (2048 tokens of - reasoning, still empty `content`, 3+ min). + `max_tokens`) does not help: a reasoning model can loop on this prompt + (thousands of reasoning tokens, still empty `content`). -### jarvis (staging) +### Provisioning (`scripts/bootstrap.sh`) -- Provision a fresh Ubuntu machine into a running staging box: clone - `semif-agent` to a checkout (jarvis keeps it at `~/repos/semif-agent`; the - script derives all paths from wherever it is run, so any path works — just - register its SSH key on Gitea first), then - `scripts/bootstrap.sh --llm-url http://127.0.0.1:11434 --codegen-url http://192.168.8.181:11434`. +- 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 this box's local ollama (bootstrap pulls - `llm.model`), only `codegen` points at the peer guppy. It pulls the pinned - small model into the local ollama and WARNs (never auto-pulls) if the remote - codegen host is missing. + 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. - **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 @@ -545,21 +475,21 @@ CLI, unit tests (24) + box integration tests (2). `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 — jarvis, guppy, and any future box all - provision from it). **Maintenance**: bump the pins in `config.example.json` / + (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. - 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). Same as the box; - do not "fix" them by installing torch. -- Generates `config.json` with `llm.base_url` = `--llm-url` (this box, local) and - `codegen.base_url` = `--codegen-url` (the remote codegen host; `codegen.timeout: - 3600` since it travels the LAN), a repo-relative `.runtime/models` GGUF path, + 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 guppy's `data/` for continuity; `--public-dashboard` - binds the dashboard to `0.0.0.0`. + `--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`, @@ -575,22 +505,14 @@ CLI, unit tests (24) + box integration tests (2). denies everyone (the safe default until the human adds their contact id). Bootstrap then runs `scripts/simplex-address.py` to create/print the command bot's contact address (and the forwarding bot's, via `--ws-url`). -- Run / verify on jarvis: - ```sh - REPO=~/repos/semif-agent && cd "$REPO" && export HF_HOME="$REPO/.runtime/hf" - "$REPO/.runtime/venv/bin/python" -m semif_agent.cli run # REPL - "$REPO/.runtime/venv/bin/python" -m semif_agent.cli dream # cost report - "$REPO/.runtime/venv/bin/python" -m pytest tests/integration -q -s # ~100s, background+poll - "$REPO/.runtime/venv/bin/python" -m semif_agent.cli dashboard --port 8765 - systemctl --user status semif-simplex semif-gateway semif-simplex-forward semif-bridge # gateway + bridge stack - ``` - First run downloads the 2.8G GGUF and builds `llama-cpp-python` from source (~10 min on 6 cores); reruns are fast no-ops. +- Per-host run/verify commands and addresses: `local/ENVIRONMENT.md`. -### codegen (skill bodies, box) +### codegen (skill bodies) - Skill **bodies** are written by a separate OpenAI-compatible model, configured - under `codegen` in config.json (default model `qwen38-iq3s`, the 12G 27B - IQ3_S GGUF — huge/slow). Title + description for new skills come from the + under `codegen` in config.json (your configured code-capable model — + larger/slower than `llm`). Title + description for new skills come from the separate small `llm` provider (its own endpoint/model, shared transport in `provider.py`); only the runnable code body uses codegen. - **Alternate hosted provider: OpenCode Console** (`console.py`). Either @@ -618,15 +540,14 @@ CLI, unit tests (24) + box integration tests (2). their own adapters. The Console's **Jev** (`/zen/v1/systemone`) is a probability/decision evaluator — do NOT wire it into routing/assessment; SemIf alone decides. -- **Do NOT cap `max_tokens`** on the codegen call. qwen38-iq3s reasons first - and a cap truncates the hidden reasoning, leaving `content` empty - (`finish_reason: length`) and the body write fails with "skill body is - empty". Unbounded, it runs to completion in ~25–45 min with the card - sampler (~28–70k tokens of reasoning then the code, ~25–40 tok/s); the - client reads only `content`, so reasoning is filtered automatically. The - client default timeout is 1200s and qwen38-iq3s routinely exceeds it — - the box `config.json` sets `codegen.timeout: 3600`. Raise `codegen.timeout` - in config if a harder prompt needs more. +- **Do NOT cap `max_tokens`** on the codegen call. A reasoning codegen model + reasons first and a cap truncates the hidden reasoning, leaving `content` + empty (`finish_reason: length`) and the body write fails with "skill body is + empty". Unbounded, it runs to completion (tens of thousands of reasoning + tokens then the code); the client reads only `content`, so reasoning is + filtered automatically. The client default timeout is 1200s and a slow codegen + model can exceed it — the per-machine `config.json` sets `codegen.timeout: + 3600`. Raise `codegen.timeout` in config if a harder prompt needs more. - Bodies are persisted as one **folder per skill**: `data/skills///` holding `skill.py`, `skill.test.py`, `contract.json`, and `config.json` (all gitignored), loaded back at startup via `importlib`, so @@ -663,8 +584,8 @@ CLI, unit tests (24) + box integration tests (2). catalog revision on the trace is future work. - **Trust boundary**: generated skill code is executed locally (it is imported as a module and its `act` runs in-process; `skill.test.py` runs as a - subprocess in the skill folder). The box is the intended target; treat the - endpoint as trusted. + subprocess in the skill folder). The provisioned host is the intended target; + treat the endpoint as trusted. - Flow in `scheduler._dispatch_skill`: the request is queued to the **single-slot `llm` draft worker** (small model authors title+description) → stub registered + hot-merged into the tree → the body write is queued to a **separate @@ -716,8 +637,8 @@ CLI, unit tests (24) + box integration tests (2). the skill row / `skill_write_failed` flow node. Codegen failure — including a request timeout — is raised as `CodegenError` by the client, never a raw `TimeoutError`. The default codegen timeout is 1200s - (`cli.build_scheduler`); the box `config.json` sets `codegen.timeout: 3600` - because qwen38-iq3s's card sampler writes routinely run 25–45 min. Raise + (`cli.build_scheduler`); a slow codegen model's writes can run 25–45 min, so + the per-machine `config.json` sets `codegen.timeout: 3600`. Raise `codegen.timeout` in config for harder prompts. - **Config tiering + first-fire collection.** After the contract lands, a SemIf `choice` per variable auto-populates the skill `config.json` from the whole @@ -777,7 +698,7 @@ CLI, unit tests (24) + box integration tests (2). `reasoning` (ollama) or `reasoning_content` (other OpenAI-compatible backends) — do not drop one for the other. Echoing is console-only; the returned content is identical either way. Integration tests already force - streaming; see it with `-s` on the box. + streaming; see it with `-s`. - `codegen.idle_warn` (default 60s) / `codegen.idle_timeout` (default 180s) surface a silent stream: a wedged generation prints a warning at `idle_warn` seconds with no tokens, then raises `CodegenError` (→ graceful stub) at @@ -799,7 +720,7 @@ CLI, unit tests (24) + box integration tests (2). handles both shapes and falls back to `model_info..context_length`. The total wall-clock `timeout` is enforced while the stream is live (a continuously-streaming runaway is cut off), not only during idle gaps. The - budget is a safety net, not the loop cure: qwen38-iq3s's reasoning routinely + budget is a safety net, not the loop cure: a reasoning codegen model routinely exceeds even the relaxed cap before it settles on a body. - **Sampler params (opt-in).** `temperature`/`top_p`/`presence_penalty`/ `frequency_penalty` are **not sent by default**: a `None`/absent value is @@ -807,8 +728,8 @@ CLI, unit tests (24) + box integration tests (2). provider never guesses a value for the user — set one in the `llm`/`codegen` config block (or per `chat` call) only when you know the right value for the model. `config.example.json` ships explicit values as a starting point, so a - provisioned box still sends them. When configured, a high `presence_penalty` - (not greedy temperature) is the anti-repetition loop cure for qwen38-iq3s, and + provisioned host still sends them. When configured, a high `presence_penalty` + (not greedy temperature) is the anti-repetition loop cure for a looping codegen model, and those four are the only sampler knobs reachable via ollama's OpenAI-compat API (`repeat_penalty`/`min_p`/`top_k` are Modelfile-only). There is **no escalated preset**: a rejected body retries with a fresh short prompt that @@ -825,7 +746,7 @@ CLI, unit tests (24) + box integration tests (2). Recorded as **trace-only** events (kind `codegen`, with probs and `stop_prob`) — never in the decision log. Disabled when no engine is available (`enabled` defaults true; the runtime engine check is what gates - it off the box). + it off when no engine is loaded). ### gateway (messenger intake) @@ -834,7 +755,7 @@ CLI, unit tests (24) + box integration tests (2). configured `gateway.simplex` adapter in the foreground. `--dashboard` co-serves the browser UI from a daemon thread. Config lives under `gateway.simplex` in `config.json`; `enabled` defaults false. On a - bootstrap-provisioned box `scripts/bootstrap.sh` renders and enables the + bootstrap-provisioned host `scripts/bootstrap.sh` renders and enables the `semif-simplex.service` bot daemon (pinned `simplex-chat` in **bot mode**, profile under `.runtime/simplex/`, port from `simplex_chat.port`) and the `semif-gateway.service` agent process, so the gateway runs across @@ -909,7 +830,7 @@ CLI, unit tests (24) + box integration tests (2). `/_show_address` / `/_address` (`SimplexDaemon.request_address`, thread-safe via `run_coroutine_threadsafe`). It carries no policy: no allowlist, no scheduler, no HTTP. -- **Tests.** `tests/test_gateway.py` (stdlib, dev box): adapter allowlist/auth, +- **Tests.** `tests/test_gateway.py` (stdlib): adapter allowlist/auth, structured send command, batching (real `asyncio`), and `GatewayService` routing against a real `Scheduler` (lazy engine, unreachable LLM). `tests/test_simplex_ws.py` covers the neutral protocol layer (parse shapes, @@ -920,9 +841,9 @@ CLI, unit tests (24) + box integration tests (2). `tests/test_seed_skills.py` hermetically tests every `seeds///` package, including `simplex.next_message` and `simplex.connect_link`. The live `websockets` transport against a real daemon - is a jarvis integration concern. + is a live-daemon integration concern. - **Deps.** `websockets` is pinned in `requirements/staging.txt` (staging - only); the dev box core stays stdlib-only. + only); the core stays stdlib-only. ### bridges (third-party API services) @@ -944,7 +865,7 @@ CLI, unit tests (24) + box integration tests (2). bridges until interrupted. Each bridge owns its service daemon: `SimplexBridge` connects to a **second** simplex-chat daemon/profile (`bridges.simplex.ws_url`, default port 5228, pinning `simplex_chat.forward_port`), separate from the - command gateway's. On a bootstrap-provisioned box, `scripts/bootstrap.sh` + command gateway's. On a bootstrap-provisioned host, `scripts/bootstrap.sh` renders and enables `semif-simplex-forward.service` (the second daemon) and `semif-bridge.service` (`cli bridge`) alongside the gateway units. - **HTTP surface** (`bridges/base.py` + `bridges/simplex.py`): JSON in/out, @@ -1022,7 +943,7 @@ The bridge read path (`simplex.next_message`) and contact-link lookup touch data-structure math only (queue ordering, dream cost, contract serialization) or drive scheduling mechanics through the `ScriptedEngine` double in `tests/conftest.py`; decisions themselves are verified by - integration tests on the box. + integration tests on a provisioned host. - Engine import is **lazy** (`engine.py`) so the rest of the package stays pure stdlib and testable without SemIf installed. Keep it that way. - `DecisionLog.append` labels a row with the *selected* option by default @@ -1050,8 +971,12 @@ The bridge read path (`simplex.next_message`) and contact-link lookup the `_parse_json` helper and the LLMClient provider. `tests/conftest.py``s `ScriptedEngine` drives scheduling mechanics (assessment is now a SemIf decision) without a GGUF. -- `tests/integration/` — jarvis only (staging); requires real SemIf + real - ollama (guppy serves the models over the LAN). +- `tests/test_no_env_leaks.py` guards the generic-repo rule: it fails if a + deployment hostname, address, username, absolute home path, or local model + name reappears in a tracked file. Deployment specifics belong in the + gitignored `local/` folder (see "Local deployment notes"). +- `tests/integration/` — run only where real SemIf + a real LLM endpoint are + available (the endpoint may be remote). - After touching scheduler/skills/codegen/engine, re-run both; the integration tests are the only end-to-end verification. - **Fixtures are not the runtime.** Generated skill tests (and unit tests of the diff --git a/README.md b/README.md index e433406..e3bb6c9 100644 --- a/README.md +++ b/README.md @@ -28,8 +28,8 @@ A successful release of this could be defined by a single question: "Can I use t - [Features](#features) - [Repository layout](#repository-layout) - [Installation](#installation) - - [Option A: one-command staging box (`bootstrap.sh`)](#option-a-one-command-staging-box-bootstrapsh) - - [Option B: dev machine (stdlib only)](#option-b-dev-machine-stdlib-only) + - [Option A: one-command provisioning (`bootstrap.sh`)](#option-a-one-command-provisioning-bootstrapsh) + - [Option B: core only (stdlib)](#option-b-core-only-stdlib) - [Prerequisites: ollama models](#prerequisites-ollama-models) - [Configuration](#configuration) - [Running the agent](#running-the-agent) @@ -176,7 +176,7 @@ worker. It is **asynchronous**, so the gate stays free while either model thinks gateway) defers to a question queue and the worker waits (`codegen.elicitation.wait_timeout`). 3. **Codegen body** (`generate_skill_body`): a larger OpenAI-compatible model - (`codegen`, default `qwen38-iq3s`) writes a single `act` against `SKILL.md`, + (`codegen`, your configured code-capable model) writes a single `act` against `SKILL.md`, reading every operational value from `ctx.config` and declaring `INTEGRATION` (service / transport / config_vars) plus its own flat `CONTRACT` (variable → description; every key must be read from `ctx.config`). @@ -380,11 +380,12 @@ semif_agent/ seeds/ committed starter skills (calendar, simplex) scripts/ bootstrap.sh, simplex-address.py, systemd/*.in requirements/ staging.txt — the pinned engine deps -tests/ stdlib unit tests + tests/integration (staging only) +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 +local/ gitignored: this deployment's notes (hosts, addresses, models) ``` --- @@ -401,25 +402,27 @@ in the checkout. Two OpenAI-compatible endpoints (usually ollama), which may be on different machines: -- **`codegen`** — the large model that writes skill bodies (e.g. - `qwen38-iq3s`, a 27B IQ3_S GGUF). This is slow and ideally on a beefier host. -- **`llm`** — a small, fast model (e.g. `qwen3.5:4b`) that authors the title + - description of a newly created category/skill. Deliberately its own - endpoint/model, so it can stay local even when `codegen` is remote; it uses - the same provider transport (`provider.py`) and an unreachable endpoint is - graceful (the request is not re-dispatched), never fatal. +- **`codegen`** — a large, code-capable model that writes skill bodies. This is + slow and ideally on a beefier host. +- **`llm`** — a small, fast model that authors the title + description of a + newly created category/skill. Deliberately its own endpoint/model, so it can + stay local even when `codegen` is remote; it uses the same provider transport + (`provider.py`) and an unreachable endpoint is graceful (the request is not + re-dispatched), never fatal. The **decision engine is separate** and runs via llama.cpp CPU (or Vulkan if your build enables it), not ollama. -### Option A: one-command staging box (`bootstrap.sh`) +### Option A: one-command provisioning (`bootstrap.sh`) 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://192.168.8.181:11434 + --codegen-url http://:11434 \ + --llm-model \ + --codegen-model ``` The script is idempotent (every stage no-ops on existing state) and: @@ -445,7 +448,7 @@ Useful flags: `--threads N`, `--public-dashboard`, `--copy-data SRC`, 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. -### Option B: dev machine (stdlib only) +### Option B: core only (stdlib) The core is dependency-free, so unit tests run anywhere: @@ -483,12 +486,16 @@ Key blocks: | `simplex_chat` | pinned simplex-chat binary + gateway/forward ports | | `dashboard` | bind host/port | +`llm.model` and `codegen.model` are **required** (no default): set each to a +model its endpoint serves. A missing model fails fast at startup with a clear +config error rather than sending a request to a model that isn't there. + Runtime artifacts (`data/decisions.jsonl`, `data/runs.jsonl`, `data/categories.json`, `data/skills/`, `data/drafts/`) are gitignored too. -> **Codegen timeout:** do not cap codegen `max_tokens`. The reasoning model -> writes for 25–45 min; `codegen.timeout` defaults to 1200 s and the staging -> config raises it to 3600 s. +> **Codegen timeout:** do not cap codegen `max_tokens`. A reasoning codegen +> model can write for 25–45 min; `codegen.timeout` defaults to 1200 s and a +> per-machine config may raise it to 3600 s. --- @@ -508,10 +515,10 @@ python -m semif_agent.cli gateway [--platform simplex] [--dashboard] python -m semif_agent.cli bridge [--name simplex] ``` -On a bootstrap box, use the venv and set `HF_HOME` to the checkout's cache: +On a provisioned host, use the venv and set `HF_HOME` to the checkout's cache: ```sh -REPO=~/repos/semif-agent +REPO= HF_HOME="$REPO/.runtime/hf" "$REPO/.runtime/venv/bin/python" -m semif_agent.cli run ``` @@ -652,14 +659,14 @@ committed seed never holds secrets. # anywhere, fast, stdlib only python3 -m pytest tests/ -q --ignore=tests/integration -# staging box only: real SemIf + real ollama -~/repos/semif-agent/.runtime/venv/bin/python -m pytest tests/integration -q -s +# where real SemIf + a real ollama are available (run from the checkout root) +./.runtime/venv/bin/python -m pytest tests/integration -q -s ``` Unit tests use the `ScriptedEngine` double (`tests/conftest.py`) to drive scheduling mechanics without a GGUF; data-structure tests cover queue ordering, dream cost and contract serialization. Integration tests exercise the real -engine + LLM end to end and take ~100 s on the staging box. +engine + LLM end to end. **Fixtures are not the runtime.** Skill tests use real local endpoints (a loopback server, never a mock); a real run is the only proof an integration diff --git a/config.example.json b/config.example.json index 9d4dee7..81141ed 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. The box (guppy) keeps its own config.json with local paths.", + "_comment": "Per-machine config. config.json is gitignored; copy this file to config.json and adjust paths. Every machine keeps its own config.json.", "tau": 0.6, "max_reentries": 3, "creation_approval": false, @@ -13,7 +13,7 @@ "backend": "llamacpp", "source": "Qwen/Qwen3.5-4B", "revision": "851bf6e806efd8d0a36b00ddf55e13ccb7b8cd0a", - "gguf": "/home/abby/models/Qwen3.5-4B-Q4_K_M.gguf", + "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", @@ -22,10 +22,10 @@ "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. 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 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).", "provider": "ollama", "base_url": "http://localhost:11434/v1", - "model": "qwen3.5:4b", + "model": "", "api_key": "", "api_key_env": "", "user_agent": "", @@ -41,10 +41,10 @@ "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, default guppy http://192.168.8.181:11434); the local small model is `llm` above. 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 + 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 + if [[ -n "$SIMPLEX_DISPLAY_NAME" ]]; then SIMPLEX_DISPLAY="$SIMPLEX_DISPLAY_NAME" fi @@ -256,10 +281,11 @@ 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" <<'PY' + "$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) = sys.argv[1:] + 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") @@ -272,7 +298,9 @@ 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 @@ -435,13 +463,13 @@ else fi fi -# Codegen is the remote larger model (e.g. guppy). Warn only — never auto-pull. +# 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 -qE "qwen38-iq3s" <<<"$CODEGEN_TAGS"; then - echo "codegen serves qwen38-iq3s: OK" +if grep -qF "$CODEGEN_MODEL" <<<"$CODEGEN_TAGS"; then + echo "codegen serves $CODEGEN_MODEL: OK" else - echo "WARN: codegen host $CODEGEN_API serves no qwen38-iq3s (offline? new-skill authoring will fail)" >&2 + echo "WARN: codegen host $CODEGEN_API serves no $CODEGEN_MODEL (offline? new-skill authoring will fail)" >&2 fi if command -v systemctl >/dev/null 2>&1; then diff --git a/scripts/tune_navigation.py b/scripts/tune_navigation.py index c545e3c..df04863 100644 --- a/scripts/tune_navigation.py +++ b/scripts/tune_navigation.py @@ -13,12 +13,12 @@ Navigation is two-stage at both levels, and the guards are the create doors: This replays a hand-labeled eval set through the **real** decision engine and the **real** skill tree, measuring each guard's probability per request so the floors can be placed between the true matches and the true mismatches. Run it on -a box with the pinned engine (jarvis): +a host with the pinned engine: .runtime/venv/bin/python scripts/tune_navigation.py .runtime/venv/bin/python scripts/tune_navigation.py --level leaf --tau 0.6 -The tree is whatever the box currently has loaded (committed seeds + the runtime +The tree is whatever the host currently has loaded (committed seeds + the runtime `data/skills/`), so an expectation naming a skill that is not present is reported as N/A rather than counted wrong. Labels are hand-written ground truth; self-labeled decision rows are not evidence. Nothing is written to the runtime diff --git a/semif_agent/cli.py b/semif_agent/cli.py index d67ce89..8447f38 100644 --- a/semif_agent/cli.py +++ b/semif_agent/cli.py @@ -1,6 +1,6 @@ """CLI entrypoint: interactive REPL, scripted JSONL mode, and subcommands. -Run on the box with SemIf + a GGUF + a local OpenAI-compatible server: +Run on a host with SemIf + a GGUF + a local OpenAI-compatible server: python -m semif_agent.cli run # REPL python -m semif_agent.cli run --script inputs.jsonl @@ -76,6 +76,23 @@ def _opt_float(value) -> float | None: return None if value is None else float(value) +def _required_model(cfg: dict, provider: str) -> str: + """The configured model name, or a clear fatal error. + + There is no default: which model an endpoint serves is deployment-specific, + so the per-machine config must name it rather than the code guessing a model + the endpoint may not have. Failing fast turns a missing model into an + actionable config error instead of a request to a model that isn't there. + """ + model = str(cfg.get("model") or "").strip() + if not model: + raise SystemExit( + f"config.json: {provider}.model is required " + f"(set it to a model your {provider} endpoint serves)" + ) + return model + + def _provider_endpoint(cfg: dict, default_base: str) -> dict: """Endpoint kwargs shared by the llm/codegen clients. @@ -127,7 +144,7 @@ def build_scheduler(config: dict) -> tuple[Scheduler, dict]: llm_endpoint = _provider_endpoint(llm_cfg, "http://localhost:11434/v1") llm = llm_cls( base_url=llm_endpoint["base_url"], - model=llm_cfg.get("model", "qwen2.5:3b"), + model=_required_model(llm_cfg, "llm"), timeout=float(llm_cfg.get("timeout", 600.0)), stream=bool(llm_cfg.get("stream", False)), idle_warn=float(llm_cfg.get("idle_warn", 30.0)), @@ -156,7 +173,7 @@ def build_scheduler(config: dict) -> tuple[Scheduler, dict]: ) codegen = codegen_cls( base_url=codegen_endpoint["base_url"], - model=codegen_cfg.get("model", "qwen38-iq3s"), + model=_required_model(codegen_cfg, "codegen"), timeout=float(codegen_cfg.get("timeout", 1200.0)), stream=bool(codegen_cfg.get("stream", False)), idle_warn=float(codegen_cfg.get("idle_warn", 60.0)), diff --git a/semif_agent/codegen.py b/semif_agent/codegen.py index 8d7950c..198cbf1 100644 --- a/semif_agent/codegen.py +++ b/semif_agent/codegen.py @@ -1,8 +1,8 @@ """Skill code-body generation through an OpenAI-compatible API. The small `llm` provider authors a skill's title + description; writing the -runnable body is a separate step: a larger OpenAI-compatible model (e.g. -qwen38-iq3s on ollama) is prompted with the SKILL.md contract plus the request +runnable body is a separate step: a larger OpenAI-compatible model (a +code-capable model on your configured codegen endpoint) is prompted with the SKILL.md contract plus the request and the existing tree, and must reply with valid Python implementing `act` plus the `INTEGRATION` and `CONTRACT` module constants. The shared provider transport lives in `provider.py`. diff --git a/semif_agent/dashboard.py b/semif_agent/dashboard.py index c44c29d..a64eb6c 100644 --- a/semif_agent/dashboard.py +++ b/semif_agent/dashboard.py @@ -8,9 +8,9 @@ request, answer a run paused for input, answer a deferred authoring question, resolve a repair offer, restart a skill write, and relabel a decision (human override). -The scheduler's engine and LLM are built lazily, so the dashboard runs on the -thin dev box in replay mode (reads logs; submit degrades to a JSON error) and -in live mode on the box with SemIf + a local LLM. +The scheduler's engine and LLM are built lazily, so the dashboard runs in +replay mode on a machine without the engine (reads logs; submit degrades to a +JSON error) and in live mode on a host with SemIf + a local LLM. python -m semif_agent.cli dashboard [--port 8765] """ diff --git a/semif_agent/llm.py b/semif_agent/llm.py index 905c168..3a793db 100644 --- a/semif_agent/llm.py +++ b/semif_agent/llm.py @@ -30,7 +30,7 @@ class LLMClient(OpenAICompatClient): from config. `disable_thinking` defaults **on**: the small local model is often a - reasoning model (e.g. `qwen3.5:4b`) whose hidden chain-of-thought consumes + reasoning model whose hidden chain-of-thought consumes the short reply budget and leaves `content` empty — the same cap problem codegen documents, but here the reply is a ~30-token JSON object, so the thinking is pure overhead. Set `llm.disable_thinking: false` for a diff --git a/tests/conftest.py b/tests/conftest.py index 3fdc573..eeb86a0 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -4,7 +4,7 @@ engine used ONLY by pure-stdlib unit tests of scheduling mechanics (pausing, resuming, routing, authoring). The real engine is the decision-maker in production and in the integration tests; this double exists so a mechanics test -can drive the loop without loading a GGUF on the dev machine, exactly as a +can drive the loop without loading a GGUF locally, exactly as a loopback HTTP server stands in for a live service elsewhere. It is not a mock of SemIf scoring: it answers each `DecisionRequest` with a diff --git a/tests/integration/test_pipeline.py b/tests/integration/test_pipeline.py index 7604583..f24337d 100644 --- a/tests/integration/test_pipeline.py +++ b/tests/integration/test_pipeline.py @@ -1,4 +1,4 @@ -"""End-to-end pipeline test. Run ONLY on the box with real SemIf + real LLM. +"""End-to-end pipeline test. Run ONLY where real SemIf + a real LLM are available. python -m pytest tests/integration -q @@ -12,7 +12,7 @@ import time import pytest -from semif_agent.cli import _opt_float, build_scheduler, load_config +from semif_agent.cli import _opt_float, _required_model, build_scheduler, load_config from semif_agent.codegen import ( CodegenClient, generate_skill_body, @@ -61,7 +61,7 @@ def require_real(config: dict): def _isolate_runtime(config: dict, tmp_path) -> None: """Point every runtime artifact at tmp_path. - Without this, persisted authoring output in the box's `data/categories.json` + Without this, persisted authoring output in the runtime `data/categories.json` and `data/skills/` leaks into the tree and navigation routes to a stale stub instead of the injected fixture — an environment-dependent failure. """ @@ -294,8 +294,8 @@ def test_generate_skill_body_codegen(tmp_path): The body must perform the action via a stdlib transport and declare INTEGRATION; the test is a hermetic mechanics check (loopback for HTTP), not - proof of the live integration. Slow: uses the big codegen model - (qwen38-iq3s by default). Run this one in the background and poll — + proof of the live integration. Slow: uses the configured codegen model. + Run this one in the background and poll — long-lived ssh sessions get SIGHUP'd. """ config = load_config() @@ -303,7 +303,7 @@ def test_generate_skill_body_codegen(tmp_path): codegen_cfg = config.get("codegen", {}) client = CodegenClient( base_url=codegen_cfg.get("base_url", "http://localhost:11434/v1"), - model=codegen_cfg.get("model", "qwen38-iq3s"), + model=_required_model(codegen_cfg, "codegen"), timeout=float(codegen_cfg.get("timeout", 1200.0)), stream=True, temperature=_opt_float(codegen_cfg.get("temperature")), diff --git a/tests/test_dashboard_api.py b/tests/test_dashboard_api.py index c81510d..1ca62f4 100644 --- a/tests/test_dashboard_api.py +++ b/tests/test_dashboard_api.py @@ -2,7 +2,7 @@ The scheduler is constructed with the lazy SemIfEngine (never loaded), so this runs anywhere without SemIf. Submit degrades to a JSON error, which is the -expected behaviour on the thin dev box; relabel works against a seeded log. +expected behaviour without an engine; relabel works against a seeded log. """ import json @@ -223,7 +223,7 @@ def test_skill_writing_and_created_events_in_payload(tmp_path): category="tracking", skill="track_live", description="Follow a package in real time.", - model="qwen38-iq3s", + model="test-codegen", contract_ref="a1b2c3d", contract_dirty=True, ) @@ -246,7 +246,7 @@ def test_skill_writing_and_created_events_in_payload(tmp_path): writing = next(e for e in run["events"] if e["kind"] == "skill_writing") assert writing["skill"] == "track_live" assert "real time" in writing["description"] - assert writing["model"] == "qwen38-iq3s" + assert writing["model"] == "test-codegen" assert writing["contract_ref"] == "a1b2c3d" assert writing["contract_dirty"] is True created = next(e for e in run["events"] if e["kind"] == "skill_created") diff --git a/tests/test_gateway.py b/tests/test_gateway.py index 6e9cf7e..3b97d58 100644 --- a/tests/test_gateway.py +++ b/tests/test_gateway.py @@ -4,8 +4,8 @@ The gateway is the agent's command surface only. These tests exercise its own routing, authorization, and batching; parsing/accept/address live in `tests/test_simplex_ws.py`. The decision engine is never loaded and the LLM endpoint is unreachable, so scheduler calls degrade to errors — which is fine. -The real `websockets` transport against a live `simplex-chat` daemon is a jarvis -integration concern, not a dev-box unit test. +The real `websockets` transport against a live `simplex-chat` daemon is a +live-daemon integration concern, not a unit test. """ import asyncio diff --git a/tests/test_no_env_leaks.py b/tests/test_no_env_leaks.py new file mode 100644 index 0000000..c0a7f42 --- /dev/null +++ b/tests/test_no_env_leaks.py @@ -0,0 +1,100 @@ +"""Guard: no deployment-specific artifacts in tracked files. + +The repo is generic. Hostnames, addresses, usernames, absolute home paths, and +the local model choices of any one deployment must not leak into tracked files — +they belong in the gitignored ``local/`` folder (see ``local/ENVIRONMENT.md``). +This test fails if a denylisted term reappears anywhere in the tree. +""" + +from __future__ import annotations + +import os +import re +import subprocess +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parent.parent + +# Generated/ignored trees and binary assets. ``local/`` is the intended home +# for deployment specifics and is gitignored, so it is exempt. +SKIP_DIRS = {".git", ".runtime", "local", "data", ".pytest_cache", "__pycache__"} +SKIP_SUFFIXES = { + ".pyc", ".svg", ".png", ".jpg", ".jpeg", ".gif", ".ico", + ".woff", ".woff2", ".ttf", ".pdf", ".zip", ".gz", +} +SKIP_NAMES = {Path(__file__).name} +# Fallback (non-git) walk: skip gitignored per-machine artifacts by name/pattern. +SKIP_GLOBS = ("config.json", "*.bak.*", "*.log") + +# label -> regex. Kept specific so a legitimate generic term is not flagged. +DENYLIST = { + "deployment hostname": r"jarvis|guppy", + "operator username": r"\babby\b", + "ssh key comment": r"shitass", + "git owner": r"gabby", + "git host": r"manyworlds", + "lan address": r"192\.168\.8\.", + "local codegen model": r"qwen38", + "local llm model": r"qwen3\.5:4b", + "stale llm default": r"qwen2\.5:3b", + "absolute home path": r"/home/abby", + "old venv path": r"semif-venv", + "machine descriptor": r"\b(?:the box|dev box|dev machine|staging box)\b", +} + + +def _git_tracked_files() -> list[Path] | None: + """Tracked files from git (so gitignored per-machine files are exempt). + + Returns ``None`` when git is unavailable or this is not a checkout, so the + guard still works on an extracted tarball via the walk fallback. + """ + try: + out = subprocess.run( + ["git", "-C", str(REPO_ROOT), "ls-files", "-z"], + capture_output=True, + check=True, + ).stdout + except (OSError, subprocess.CalledProcessError): + return None + names = [n for n in out.decode("utf-8", "surrogateescape").split("\0") if n] + return [REPO_ROOT / n for n in names] + + +def _iter_tracked_text_files(): + """Yield candidate files, pruning ignored trees and binary assets.""" + tracked = _git_tracked_files() + if tracked is not None: + candidates = tracked + else: + candidates = [] + for dirpath, dirnames, filenames in os.walk(REPO_ROOT): + dirnames[:] = [d for d in dirnames if d not in SKIP_DIRS] + for name in filenames: + path = Path(dirpath) / name + if any(path.match(g) for g in SKIP_GLOBS): + continue + candidates.append(path) + for path in candidates: + if path.name in SKIP_NAMES or path.suffix in SKIP_SUFFIXES: + continue + yield path + + +def test_no_deployment_specific_artifacts(): + hits: list[str] = [] + for path in _iter_tracked_text_files(): + try: + text = path.read_text(encoding="utf-8") + except (UnicodeDecodeError, OSError): + continue + for label, pattern in DENYLIST.items(): + for match in re.finditer(pattern, text, re.IGNORECASE): + line = text.count("\n", 0, match.start()) + 1 + hits.append( + f"{path.relative_to(REPO_ROOT)}:{line}: {label} " + f"-> {match.group(0)!r}" + ) + assert not hits, "deployment-specific artifacts in tracked files:\n" + "\n".join( + hits + ) diff --git a/tests/test_simplex_ws.py b/tests/test_simplex_ws.py index 75f3085..21c9300 100644 --- a/tests/test_simplex_ws.py +++ b/tests/test_simplex_ws.py @@ -3,7 +3,7 @@ `semif_agent.simplex_ws` is shared by the command gateway and the forwarding bridge, so its parsing/accept/address behavior is tested here, independent of either front end. The real `websockets` transport against a live daemon is a -jarvis integration concern. +live-daemon integration concern. """ import asyncio diff --git a/tests/test_skills.py b/tests/test_skills.py index fa02358..70deabe 100644 --- a/tests/test_skills.py +++ b/tests/test_skills.py @@ -4,7 +4,7 @@ path when the engine is unavailable. No mocking: the async write test uses a real CodegenClient against a throwaway stdlib HTTP server (real endpoint, per the repo rule); engine-dependent success -paths are exercised only by the box integration tests against the real decision +paths are exercised only by the integration tests against the real decision model. """