A third decision-engine provider alongside the local SemIf GGUF and the remote Winnow server: `engine.provider == "ollama"` talks to ollama's native `/v1/systemone` route via `semif_agent/ollama_systemone.py`. It reuses the Winnow DecisionRequest -> choice mapping and the same strict distribution validation over exactly the requested option ids, and adds the edges only ollama has: - no `/health`: `warm()` probes `GET /api/version` + `POST /api/show`, which also proves the model is pulled and advertises the `decision` capability; - `engine.ollama.context_tokens: 0` follows the model's real `num_ctx` from `/api/show`; - `keep_alive` rides on the request, criteria descriptions use the ollama subset `string | null`, and a choice question needs >= 2 options; - decision models do not generate text, so `generate()` raises `EngineUnavailable` (use `llm.provider == "ollama"` for chat). Every failure is an `EngineUnavailable` (fatal, like the local engine) and the engine lock still serializes on the single-slot server. `cli.build_engine` selects it, the setup interview and `--answers` accept it, and the install plan skips the engine clone/GGUF/tokenizer for it. Docs, config.example.json, and tests updated.
147 KiB
AGENTS.md
Guidance for working on the semif agent. Read this before touching code.
Product premise (read first)
Semif-agent is an end-user application. An everyday person asks it to do a basic task in plain language, and it does it:
- The user asks for a task ("check my email", "message Sam on SimpleX", "put lunch with Dana on my Nextcloud calendar").
- If the skill tree already knows how, the agent does it.
- If it does not, the agent says it cannot help — unless the host has opted in
to live skill authoring (the default is deny; see "New-skill creation
mode" below), in which case it asks a few questions and generates a new skill.
The primary way to extend the agent is the committed skill packs
(
packs/), not runtime authoring. - It performs the task for real, against the user's actual service. If the real attempt fails, it says so and offers to fix/learn. It never pretends a task succeeded.
Skills are therefore real integrations, not simulations: mail protocols,
SimpleX, CalDAV/WebDAV, configured local CLIs, APIs — using the user's own
accounts. A skill that returns a canned result, fabricates working values, or
silently downgrades to "draft you can review" is broken, regardless of what its
test says. Connection details, accounts, and credentials are asked once and
recorded in tiered config; bodies read them from ctx.config.
Two boundaries must never blur:
- SemIf routes, gates, scores, assesses, and automates; an LLM only generates. Skills are not chat responses. Assessment and fidelity are SemIf decisions, never model prose.
- "No mocking" means the decision engine is always real. Skill tests are hermetic mechanics checks with fixtures; passing one is not proof the real integration works. Only a real run against the user's service is.
When requirements or connection details are unclear, the agent asks the user. Guessing, inventing data, or shipping a toy is always the wrong answer.
What this is
A local desktop CLI agent whose entire control flow is a single decision model
(SemIf). Inputs are queued FIFO and dispatched through a
skill tree. Nothing is gated out up front: every input is dispatched and inputs
that are not requests fall through navigation into the closed response tree of
canned replies (a request no skill covers authors a skill instead — the
actionability guard). Every SemIf decision is logged as a labeled training row; the
dream pass computes the prediction-vs-observation cost (cross-entropy / NLL +
ECE) that later drives fine-tuning. See "Product premise" above for what the
agent is for; this section is the machinery.
The design spec is IDEA.md. The key point: semantic ifs, not text
generation, do the routing. SemIf returns probabilities conditional on the
supplied options; an LLM is used only for generation.
Gateway isolation is non-negotiable. The command gateway (gateway/) exists
only to take commands and send replies. Everything that is messaging UX —
invite links, reading a contact's messages, composing/sending on the user's
behalf — belongs to the standalone bridge services (semif_agent.bridges),
which run as their own processes against their own service daemons/profiles.
Never widen the gateway's surface for convenience: a new read/send/address
capability is a new bridge, not a gateway feature.
Architecture map
cli.py argparse: run (REPL / --script), dream, skills, status, relabel,
dashboard, gateway (command intake), bridge (standalone
third-party API bridges), check-config (validate config/
against the core + pack schemas), setup (first-run interview ->
split config/ + secrets.json + install plan), config-init (seed
the schema-default split config/ + secrets.json)
config.py layered per-machine config: config.json is a thin index
(`{"include": [...]}`) over config/core.json + config/gateway.json
+ config/bridges.json + config/packs/<name>.json, deep-merged in
order; `"!secret <key>"` resolves from the gitignored
secrets.json; the core schema owns defaults and, with each
pack's `config` schema, GENERATES config.example.json
(check-config --write-example) and validates a live config
packs.py SkillPack + PackRegistry: discovers packs/ (a `pack.json`
manifest + skills/<category>/<leaf>/; each pack is cloned from its own repo — the list is the semif-packs index repo), binds a concern to its
categories, bridge(s), requirements, and config schema;
merge_packs loads every enabled pack into the tree
scheduler.py no up-front gate: every input is dispatched
-> FIFO queue when busy; a skill run paused for input
(needs_input) keeps `current` busy; `answer` routes straight to
the pending run, bypassing the queue/navigation; draft authoring
(title+description by the
small `llm` provider) AND skill-body authoring (codegen) are ASYNC
single-slot workers: a create_category/create_skill request is
queued, the gate stays free, the category job chains into its
skill job, and the original request is re-queued and re-runs the
new leaf when the body lands; an optional human approval gate
(new-skill mode `ask`; see below) blocks the draft worker
after the proposal is authored and before anything is
registered — one prompt per request, denial/timeout aborts
creation, surfaced via the approval queue; the body worker runs the full
pipeline: codegen body from a **de-identified spec** (goal +
service/transport; codegen never sees the request, question
answers, or run output) that declares its own flat
`CONTRACT` -> fidelity
gate -> test -> auto-run test (SemIf regen ladder on failure,
code/test); config
search auto-populates the skill config from the full config
cascade; a
`failed` step triggers a logged SemIf repair choice
(retry/repair_skill/ask_user/no_repair) surfaced to the user,
while a `continue` step is re-dispatched into next-step routing
with a bounded run ledger (the chained multi-step path);
a completed real-skill run's ledger is also held in memory per
origin source for `query_recall_window` seconds (0 disables), so a
follow-up request in the same chat arrives with it as
`prior_ledger` (a `previous request` context block) and can refer
to the prior result — kept separate from `run_ledger` so a
recall never skips the actionability guard or feeds the
monotonic-progress guard;
housekeeping meta skills (delete/clear-config/regen/cancel-build)
operate on the tree via `ctx.admin` (mutation); every other body
sees the tree only through the read-only `ctx.catalog`
(`ActionContext.catalog`, an `SkillCatalog`); new-skill creation is gated by
a tri-state mode (`new_skill_creation`: deny/allow/ask, **deny by
default**) with a
per-category override in the category config, with
`housekeeping`/`response` always denied in code; front ends get a
structured `SchedulerReply` (status, text, run_id, skill_ref,
result) from `submit_request`/`answer`/`run_queue` so they never
parse the run id or skill ref back out of the summary
queue.py bounded FIFO request queue (arrival order, max depth)
skills.py tree + registry (hardcoded built-ins: the closed `response` canned
tree plus the `housekeeping` meta skills), navigation = SemIf
choices per level (logged; the question is "which category/skill
is the logical next step toward satisfying this request?" for the
first step AND each continuation, and the run ledger is rendered
into the state, so a chained step sees what was already done;
the actionability guard runs first, at the top of navigation, to
arbitrate the response/create boundary — but ONLY on the first
step, since a continuation is actionable by construction),
create_category
and create_skill author + register stubs via the small `llm`
provider (separate from codegen); SkillStore persists one folder per skill
(skill.py, skill.test.py, contract.json, config.json) and
materialize_skill / merge_skill_store
hot-load runnable skills from data/skills/;
merge_packs (semif_agent/packs.py) loads each pack's skills
from packs/<name>/skills/ (each cloned from its own repo) with their recorded config read from
data/skills/ (each pack bundles its concern, category scope,
bridge, and config schema);
ActionResult.needs_input pauses a run for human input;
Skill.integration / integration_source read the body's
INTEGRATION declaration (or infer it); Skill.contract is read
from the body's `CONTRACT` constant (contract.json is a derived
mirror);
resolve_skill_config / unresolved_variables drive the tiered
config merge (global -> category -> skill) + pre-act
contract collection; Skill.origin records builtin/seed/generated;
DeletedSkills (data/deleted_skills.json) tombstones a deleted
skill so a seed does not reappear on restart; resolve_skill_ref
parses a free-form request for a category.skill or bare name;
parse_meta_command recognizes explicit housekeeping commands and
the meta skills resolve or ask for their target as an input
variable; compose_state / render_ledger / render_recall render
the steps already taken (and, for a follow-up within
`query_recall_window`, the recalled `prior_ledger` as a `previous
request` block) into the routing/assessment state, and
last_result returns the last run-ledger (or recalled) outcome a
chained body can reuse instead of recomputing
skill.py loop: observe -> act -> observe -> assess; the body is a single
act(ctx, request) phase that returns ActionResult (its own
SemIf sub-decisions ride on ActionResult.decisions and are
logged with the run outcome, phase `act`);
assess is a SemIf decision (`assess:outcome`: is there any
additional work to satisfy the request? -> done / continue /
failed, at threshold precedence failed > done > continue) and the
run summary is deterministic (no generation), built from
category.skill + ok/failed + action_log — the body writes only the
result, the runner adds the `category.name:` ref; the assess state
carries the skill's declared action, the goal, the resolved inputs
(secrets redacted), the bounded action log, and the steps already
taken (the run ledger); `continue` re-dispatches the request into
next-step routing with a bounded run-ledger entry (capped by
`max_reentries` + the monotonic-progress guard), `failed` offers a
repair; a `DETERMINISTIC_CATEGORIES`
run (housekeeping) skips assessment/repair — it is an internal
mechanical action with a known result, not an external run;
every skill's output is truncated to the one shared speakable
budget (`chain.result_chars`);
a run paused for input is resumed by re-invoking act with the
answer on request.user_input; a
contract variable the runner cannot satisfy pauses BEFORE
act (pre_act), collects it, and re-runs the full path;
the run context supplies the read-only `catalog` to every body
and the mutating `admin` only to the housekeeping category
timers.py in-process timer/alarm service (TimerService) owned by the
scheduler and exposed on ActionContext.timers: a single
background thread fires scheduled timers on the host clock,
records a `timer_fired` trace event, and queues the
notification for the front end that set it (the REPL prints it,
the gateway routes it to the originating chat, the dashboard
shows pending/fired). Real local compute (`compute` transport),
per-process, and deliberately NOT persisted across restarts.
reading.py neutral long-form reading helpers (stdlib): the
`bookmarks.json` beside the saved books (load/save/read a book
key -> last read offset, atomic write) and a deterministic
speakable chunker (`chunk_text` -> `(offset, chunk)` at
paragraph/sentence boundaries). Knows nothing about the
scheduler, a gateway, or audio.
speech.py the scheduler's speech channel (SpeechService on
ActionContext.speech, the sibling of timers): a skill that
resolves a long text to be read aloud registers a `ReadAloud`
(path + bookmark key + start offset) and returns immediately;
the gateway owning the chat drains it and hands it to the
platform adapter, which streams it with text-to-speech until
the user stops it. Neutral and stdlib-only; the skill never
reaches into a front end.
engine.py DecisionEngine (the pluggable contract: call/warm/loaded/
generate) + SemIfEngine, the default local provider ->
semif_phase1.llamacpp_backend (lazy import); call() scores a
decision, generate() autoregressively samples text from the
same loaded model (shares the engine lock, clears the KV cache)
— backs the `semif` llm provider. Selected per machine by
`engine.provider` (mirrors llm.provider/codegen.provider).
winnow.py WinnowEngine -> a remote Winnow `/v1/systemone` typed-decision
HTTP API (`engine.provider == "winnow"`): maps DecisionRequest
to a `choice` question (options -> criteria), validates and
normalizes the returned distribution over exactly those option
ids, and generate() via /v1/chat/completions. stdlib urllib; an
internal lock serializes on the single-slot server; every
failure raises EngineUnavailable (fatal, like the local engine)
ollama_systemone.py
OllamaSystemOneEngine -> ollama's native System One
`/v1/systemone` route (`engine.provider == "ollama"`): same
DecisionRequest -> choice mapping and strict distribution
validation, plus ollama's own edges — reachability/warmth via
/api/version + /api/show (model exists, `decision` capability,
real `num_ctx`), request `keep_alive`, `string | null` criteria
descriptions, and no text generation (decision models don't
generate). stdlib urllib; internal lock; every failure raises
EngineUnavailable.
codegen.py CodegenClient (OpenAI-compatible) writes real-integration skill
bodies against CODEGEN.md (real actions via stdlib transports,
data from the runner via ctx.config, never embedded; bodies
declare INTEGRATION service/transport/config_vars, and declare
their own flat `CONTRACT` {var: description});
parse/validate (compile + act + CONTRACT keys all read from
ctx.config + every referenced name imported/bound, via symtable)
+ parse_contract / parse_integration /
infer_integration / integration_findings; the bridge catalog
(describe_bridges()) is injected into the body, retry, regen,
and testgen prompts — it is the single source of
bridge specifics (service, base-URL var, auth header/token var,
config-var docs, endpoints with error shapes), while CODEGEN.md/
TESTGEN.md carry only the generic pattern; the advisory
service/transport integration hint rides on every body/retry/regen
prompt; TESTGEN.md drives the shared-context test
call producing skill.test.py (hermetic mechanics test: inline
fixtures, loopback http.server for HTTP bodies, no external
network, no mock_data.json); run_skill_test executes
the test as a subprocess
llm.py small OpenAI-compatible provider (LLMClient) that authors a
new category/skill title + description — its own endpoint/model,
deliberate separate from codegen; provider logic (SSE/budget/idle)
is shared from provider.py; `_parse_json` is also borrowed by the
authoring parsers; SemIfLLMClient serves the same `llm` task from
the loaded SemIf engine model (llm.provider == "semif")
provider.py shared OpenAI-compatible chat transport (OpenAICompatClient:
SSE stream, token budget, idle watchdog, degeneration hook,
optional `api_key` bearer auth + `extra_headers`/`user_agent`,
and `query_context` to skip the ollama /api/show probe)
subclassed by llm.LLMClient and codegen.CodegenClient;
SemIfEngineClient is the non-HTTP sibling that generates text
from the in-process SemIf engine behind the same `chat(...)`
surface (llm.provider == "semif")
console.py OpenCode Console provider: OpenCodeConsoleClient + the
ConsoleLLMClient / ConsoleCodegenClient endpoint subclasses.
Hosted, authenticated OpenAI-compatible Chat Completions API
(https://opencode.ai/inference/openai/v1); bearer key, skips the
ollama probe, always sends a User-Agent (the gateway 403s
urllib's default Python-urllib/<ver>), and forces
disable_thinking off (the gateway 400s reasoning_effort).
Selected via the llm/codegen `provider` key
("opencode" vs "ollama"; `llm` also accepts "semif", the
in-process engine model).
log.py decisions.jsonl rows {state, question, options, predicted_probs,
selected, observed_outcome, label_source}
trace.py runs.jsonl lifecycle events keyed by run_id (submit/queued/
dequeued/assessed/...); decisions reference run_id in extra
dream.py NLL of observed outcome per row; weighted CE, accuracy, ECE
decisions.py contract dataclasses (Option, DecisionRequest, DecisionResult,
Request)
dashboard.py stdlib http.server + JSON API (tree/trace/dream/status/
questions/repairs + POST submit/answer/questions/repair/restart/
relabel); static/ frontend served at /; submit/answer drain the
queue after replying (like the CLI and gateway) so a multi-step
`continue` chain completes instead of stranding its child
gateway/ messenger COMMAND intake/reply — and nothing else. base.py:
GatewayAdapter contract + Inbound/OutboundMessage. service.py:
GatewayService maps chats onto the single-slot scheduler
(submit_request, owner maps, pending-run ownership, queue
drain, authoring questions/repairs routed back to the origin
chat); it is platform-aware and fronts one or more adapters at
once, keyed by platform name (source `<platform>:<chat>`, the
single pending-run guard shared across platforms). simplex.py:
SimplexAdapter — command simplex-chat daemon over its JSON
WebSocket API (lazy `websockets`, allowlist, batching,
structured `/_send`). lxmf.py: LxmfAdapter — LXMF/Reticulum
(lazy `lxmf`), in-process, allowlist + batching, plus Sideband
push-to-talk voice commands (transcribe `FIELD_AUDIO` locally
when `gateway.lxmf.voice.enabled`) and voice replies (Piper ->
Opus/OGG back in `FIELD_AUDIO` when `voice.reply_with_voice`).
voice.py:
VoiceAdapter — the local microphone front end (wake word +
speech-to-text + text-to-speech) over the neutral
`semif_agent/voice_transport.py`; no remote peer and no
allowlist (physical mic access is the authorization), a single
configured `chat_id`, replies spoken back. humanize.py:
Humanizer — optional LLM cleanup of a result line (generation,
never a decision; grounded prompt + always falls back to the
raw text), gated by `gateway.humanize` / a per-platform
`humanize` override, reusing the scheduler's `llm` client with
a short per-call timeout. Run with
`python -m semif_agent.cli gateway [--platform
simplex,lxmf,voice|all] [--dashboard]`; config under
`gateway.simplex` / `gateway.lxmf` / `gateway.voice`. The
gateway MUST NOT read history, show/create invite links, or
compose messages — see "gateway isolation" below.
bridges/ standalone third-party API bridges. The core keeps only the
shared contract + discovery: base.py: BridgeInfo +
BridgeService (shared localhost JSON HTTP layer,
`X-Semif-Token` guard, `from_config` build hook,
`checkout_root()` for `.runtime/` anchoring). inbox.py:
MessagingInbox (bounded FIFO + contacts learned from inbound DMs
and the daemon contact list, bridge-owned read cursor).
llm.py: LLMBridge — the one shared, pack-less bridge (a generic
`POST /chat` in front of the scheduler's configured `llm`
client, reused not re-configured). registry.py: discovers each
bridge from its pack's `bridge/` by convention (no hardcoded
CATALOG), describe_bridges() (catalog injected into the codegen
prompts), derived_config_vars(), run_bridges() (threads the
scheduler's `llm` client through each bridge's `from_config`).
The concrete bridges ship with their packs:
packs/simplex/bridge/simplex.py (SimplexBridge — owns its OWN
simplex-chat daemon/profile, separate from the gateway's,
buffers every inbound DM, refreshes the daemon contact list on
(re)connect + on demand, serves invite-link/read/send plus
daemon-backed unread + per-chat history);
packs/nextcloud/bridge/nextcloud.py + nextcloud_client.py
(files/WebDAV, calendar events + tasks/CalDAV, contacts/CardDAV,
Notes/OCS behind one JSON surface; no daemon, stdlib-only;
`from_config` falls back to the top-level `nextcloud_*` values);
packs/outlook/bridge/outlook.py + outlook_client.py (Microsoft
Graph: mail, calendar, To Do, contacts, OneDrive, plus the
OAuth2 device-code + refresh flow; tokens under
`.runtime/outlook/token.json`, seeded once with
`packs/outlook/scripts/outlook-auth.py`);
packs/browser/bridge/browser.py + browser_client.py (Playwright
open/read/click/fill/screenshot, owning a persistent browser
profile; optional heavy dep, lazy so a missing browser is a
per-call 503 and never blocks the other bridges; runs the async
API on one dedicated event-loop thread).
Run with `python -m semif_agent.cli bridge [--name NAME]`;
config under `bridges`.
simplex_ws.py neutral SimpleX daemon protocol shared by the command gateway
adapter and the bridge (parse direct text across v7 shapes,
structured `/_send`, corrId→Future round-trips, contact-address
`/_show_address`/`/_address`, contact-request accept, contact
list + chat previews/history). Knows nothing about the
scheduler or either front end.
lxmf_transport.py
neutral LXMF (Reticulum) transport: one in-process Reticulum
instance + LXMF router, persisted delivery identity, announce
loop, inbound normalization (text + the `FIELD_AUDIO`/`AM_*`
Sideband PTT voice payload, via `parse_audio_field`), outbound
send queue. Lazy `RNS`/`LXMF` imports keep the module
stdlib-only. Knows nothing about the scheduler or the gateway.
voice_transport.py
neutral voice transport: a 16 kHz mono capture loop with an
always-on wake word (openWakeWord), VAD endpointing
(webrtcvad, energy fallback), speech-to-text (faster-whisper)
and text-to-speech (Piper) over `sounddevice`; half-duplex by
default with optional wake-word barge-in (abort a spoken reply
and listen for an interrupt command). Every heavy dep is
lazy-imported, keeping the module stdlib-only; the engine
interfaces are plain classes so tests inject fakes. Knows
nothing about the scheduler or the gateway.
voice_train.py
neutral recording helpers for training a custom Piper voice
(optional, off-bootstrap): LJSpeech dataset writer
(`metadata.csv` + `wavs/NNNN.wav`), prompt loading, WAV I/O,
level math for the mic check, and the silence-endpointing
capture loop. Stdlib-only (numpy lazy in `resample_pcm16`);
`scripts/voice-record.py` is the CLI front end and
`scripts/voice-train.sh` the GPU fine-tune/export pipeline. See
docs/VOICE-TRAIN.md. Knows nothing about the scheduler.
Run / verify
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
- Push/pull from your git remote — never rsync/tar the code.
config.json(a thin index), theconfig/fragments, andsecrets.jsonare gitignored, per-machine, and required (hosts use different LLM/codegen endpoints and models).config.jsonis an index ({"include": [...]});config/core.json+config/gateway.json+config/bridges.json+config/packs/<name>.jsonhold the values, andsecrets.jsonholds credentials referenced as"!secret <key>".scripts/bootstrap.shgenerates the split config once from the setup interview (viasetup, only whenconfig.jsonis absent, or--reconfigure) and nothing writes it afterwards — only a human edits it. The committedconfig.example.jsonis GENERATED from the core schema (semif_agent/config.py) and each pack'sconfigschema — regenerate it withpython -m semif_agent.cli check-config --write-example config.example.jsonafter changing a schema; validate a live config withcheck-config.data/decisions.jsonl,data/runs.jsonl, anddata/drafts/are runtime artifacts and gitignored too.pins.jsonis 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 inconfig.json(a ref replaced on every update is not per-machine user config).- Decision rows logged before the
run_idthreading landed show up under run_id"?"in the dashboard — that's expected, not a bug.
Roadmap
v1 (done)
Core loop, FIFO queue, skill tree, skill loop with real SemIf assessment
(decision, not generation), decision logging, dream cost pass, REPL + JSONL
CLI, unit tests (24) + integration tests (2).
v2
- Real fine-tuning from
decisions.jsonlat a regular interval ("dreaming"): accumulate labeled rows, compute cost, fine-tune the decision model, CI/CD validate (accuracy/ECE on a held-out slice, prompt-hash regression), swap the pinned model revision. GPU offload: train on a beefier GPU; the running agent keeps a frozen inference revision until a swap validates. create_skillbranch: live, mirroringcreate_category. The smallllmprovider (a dedicated endpoint/model, separate fromcodegen; production may point both at the same host) proposes a specific skill title + description for the chosen category; the stub is persisted todata/categories.json(under that category'sskillslist) 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, your configured code-capable model) writes anact-only body plus its own flatCONTRACTagainstCODEGEN.md, then a test (againstTESTGEN.md) is generated and auto-run before the leaf is declared ready — all persisted to a folder indata/skills/and hot-loaded. Authoring is asynchronous: the draft is authored by a single-slotllmworker, the stub is created and the gate freed immediately, the body write runs on a separate single-slot codegen worker, and once the body lands the request that prompted creation is re-queued and re-runs navigation onto the new leaf (an empty/in-progress leaf can be restarted viarestart <category> <skill>or the dashboard). A request that prompted a whole new category runs the same chain deterministically:create_category→create_skill→ async body → re-dispatch. An unreachablellmendpoint is graceful (traceddraft_failed, user notified, request not re-dispatched); only SemIf availability is fatal. Authoring is still a single pass — validating/reusing written bodies across runs is future work. Navigation is two-stage at both levels; the guards are the create doors (Oct 2026). Category level: the softmax offers every existing category with its description pluscreate_category, and the winner is confirmed byconfirm_category_fit(phasenavigate:category_scope, P(covers) >=navigation.category_tau); a rejected winner or acreate_categorywin authors a new category. Descriptions are load-bearing — with bare names the model sent "book a flight to japan" tosimplex(0.49 vs create_category 0.12); with descriptions it pickscreate_category0.87.Skillcarriescategory_description, seeded byCATEGORY_DESCRIPTIONSfor the built-ins (response/nextcloud/simplex/time/calculator/browser) and read from the registry for authored categories;category_descriptions(tree)collapses it per category so an empty bucket is never offered bare. The old category threshold gate (create_tau/create_margin) is retired. Leaf level: the softmax contains only existing skills —create_skillwas removed because sharing a softmax with the real skills diluted its probability and let a crowded tree drift into create on a weak plurality (real runs scoredcreate_skill0.585–0.803 on requests a seed skill clearly matched). The reuse-vs-create decision is the intent guard (confirm_skill_fit, phasenavigate:intent) atnavigation.intent_tau: it decides what the softmax winner does for the request —same(performs the next action the request needs),part(the request needs more than one action and this skill performs one required part), ordifferent(author a new leaf). The run ledger is part of the guard's state so a later step judges against the remaining work, not the whole request; the guard only decides whether the skill contributes — whether more work remains isassess:outcome's call, so a compound request is broken into known skills while the final step still stops cleanly (a forced continue onpartwas tried and rejected: the guard labeled the final send steppart0.85 while assessment correctly saiddone0.99, and the forced continue authored a spurious category). The actionability guard (confirm_non_action, phasenavigate:actionability) atnavigation.action_tau(default 0.5) runs at the top of navigation, before category selection: it decides whether the input is an actionable request at all, so the closedresponsetree is reached only for non-action input (chit-chat, a statement, or a fragment too vague/incomplete to act on, e.g. "what") and a request can never be canned. Non-action goes straight to theresponsetree and never reaches the category softmax — a vague fragment lands on the catchallresponse.clarify; a request proceeds to the category softmax, which now offers only the real categories (the cannedresponsetree is never an option) pluscreate_category. Deciding this first — rather than only when the softmax happens to proposeresponse/create_category— is what keeps a non-request out of a real category: a single category description cannot draw that line ("1+1=2" a statement and "what is 255 * 12?" a request both read as math to the softmax), and the scope guard is deliberately permissive. A request no skill covers (e.g. "what is 255 * 12?") authors instead of getting a canned reply, while a stray statement (e.g. "1+1=2") or a vague fragment (e.g. "what") still gets one — unless new-skill creation is denied (see the tri-state mode below), in which case an unservable request gets a plain refusal (skills.UNABLE_MESSAGE, "I'm sorry, I'm not able to help with that.") and is never told that authoring exists. All three taus are separate from the top-leveltau, so tuning reuse-vs-create or actionability does not move assessment/fidelity. The guards are deliberately permissive (in-scope scores 0.9–1.0): a borderline over-cover routes into a plausible category and the leaf guard catches it. Empty and single-skill categories skip their softmax.- No handle/ignore gate; the
responsetree is the non-request catchall (Sep 2026; actionability guard Oct 2026): the top-level_contains_requesthandle/ignore gate is gone. Every input is dispatched; input that is not a request falls through navigation into the closedresponsecategory, a hardcoded tree of canned replies (response.greeting,response.thanks,response.acknowledge,response.farewell,response.affirm, and the catchallresponse.clarify— "Could you try being more specific?"). A request is never answered from here, even one no skill covers: the actionability guard (confirm_non_action, phasenavigate:actionability) runs at the top of navigation and sends a request to authoring (this is what keeps "what is 255 * 12?" out of the tree; the oldresponse.unablecanned refusal is gone — an unsupported request authors a skill, it is not refused, except undernew_skill_creation: deny, where it gets the plainUNABLE_MESSAGErefusal). A fragment too vague/incomplete to act on (e.g. "what") is non-action, so it lands on the catchallresponse.clarifyrather than authoring a redundant clarify skill.responseis aCANNED_CATEGORIESmember:navigatenever offerscreate_skillthere (the intent guard is skipped too),Scheduler._dispatch_skill/restart_skillrefuse to author it, and the runner skipsassess:outcome/repair for it — a canned line has no side effect to assess. The leaf choice logs phasenavigate:responseand tracesresponse_selected.response.reject(a stub that never ran) is gone. - New-skill creation mode: deny / allow / ask (Oct 2026; tri-state Oct 2026;
deny-by-default Oct 2026): one setting governs whether the agent may author new
skills/categories, as a three-way mode. Global default is the top-level
new_skill_creation—"deny"by default (the agent leans on the shipped packs, the primary way to extend functionality), with"allow"an explicit opt-in for a host with the resources, or"ask"; a category overrides it with its ownnew_skill_creationindata/skills/<category>/config.json(absent = inherit the global).allowauthors immediately;denyblocks authoring outright (Scheduler._blocked_create, tracedskill_create_blocked/category_create_blocked) and answers the request with a plain refusal (skills.UNABLE_MESSAGE) that never names a category, skill, or config — a denied deployment gives no hint that authoring exists;askauthors only after the human approves the proposal. Theaskpath is the old approval gate: the single-slotllmdraft worker blocks after it authors a proposal and before anything is registered; the human approves/denies via the REPL prompt, the dashboard approvals panel (GET/POST /api/approvals), or a gateway chat reply (yes/no). One prompt per creation request — a new category's chained skill is covered by the category approval (DraftAuthor.approved). Denial or timeout aborts creation: nothing is registered, no body is written, and the request is not re-dispatched; the wait reusescodegen.approval.wait_timeout. With no deferring front endaskdenies immediately rather than stalling the worker. The mode is resolved byScheduler._category_mode(deny for the hard-lockedhousekeeping/responsecategories) and checked in_dispatch,_dispatch_skill,_author_skill,_request_approval, andrestart_skill. Toggled from the config file orScheduler.set_category_mode(/mode,/api/new-skill-mode; an empty mode clears the override). Traced ascategory_mode_set, plus the approval eventscreation_approval_requested/_approved/_denied/_timeout/_skipped; the gate is deterministic (a human veto or a config value), not a decision row — the SemIf create doors still make and log the routing decision. - Housekeeping meta skills + per-category new-skill modes (Oct 2026): a
built-in
housekeepingcategory of four meta skills that act on the agent's own tree throughctx.admin(the scheduler):delete_skill(confirm, then remove the leaf, registry entry, and folder; durable via adata/deleted_skills.jsontombstone so a deleted seed does not reappear),clear_config(empty the skill's recorded config),regen_skill(ask "What needs to be fixed?" then rewrite the body through the corrective path withreason_kind="manual"), andcancel_build(confirm, then discard a queued/in-flight write and delete the half-built leaf). The target skill is an input variable: the skill resolves it from the request if named ("delete skill nextcloud.foo") and otherwise asks for it ("delete skill" → "Which skill?"), so the routed request never has to carry a task-like skill name. Explicit command forms ("delete skill", "clear config variables for X", "regen skill X", "cancel skill build") are recognized deterministically byparse_meta_commandand routed straight to the housekeeping leaf (tracemeta_command): the pinned 4B decision model reads a task-like name (nextcloud.create_event) as the task itself and misroutes the generic guards, so the explicit command is deterministic while natural-language phrasings still go through navigation (the actionability guard'sactionoption now names skill-management commands). They are built-ins (Skill.origin == "builtin") reachable by natural language and, for operators, by slash-prefixed REPL commands (/delete,/clear-config,/regen,/cancel-build,/mode) and dashboard endpoints/buttons. Their runs are deterministic internal actions:DETERMINISTIC_CATEGORIESskipsassess:outcome/repair, and the category is hard-denied from authoring. Every category carries a new-skill mode in its category config (data/skills/<category>/config.json→{"new_skill_creation": "allow|deny|ask"}), overriding the globalnew_skill_creation; the mode is a deterministic gate (Scheduler._category_mode/_category_locked) checked in_dispatch,_dispatch_skill,_author_skill, andrestart_skill, and toggled from the config file orScheduler.set_category_mode(/mode,/api/new-skill-mode).housekeepingand the closedresponsetree are hard-denied in code (HARD_LOCKED_CATEGORIES/CANNED_CATEGORIES) and can never be changed. The mode is creation-only: existing skills still run and repair/regen of an existing leaf is allowed. - Real integrations, de-identified codegen, fidelity + repair (Sep 2026;
codegen privacy Oct 2026): the codegen endpoint is the primarily-cloud model,
so it is shown only a de-identified spec — the trusted local
llmauthors a reusablegoal(plus a generic service/transport) with every user-specific value stripped; the user's request, question answers, and run output never reach codegen. Bodies must perform the real action via stdlib transports with values fromctx.configand declareINTEGRATION(service/transport/config_vars); a fidelity gate (authoring:fidelity, a SemIf accept/reconsider decision over the whole body + an operation inventory) plus static declaration checks regenerates a simulated body once with the de-identified evidence bundle, then accepts it traced (never a hard authoring failure). A failed real run logs a SemIf repair choice (retry / repair_skill / ask_user / no_repair) surfaced in REPL/dashboard; repair writes carry a de-identified evidence bundle (a generic failure kind, the integration, the goal, and the previous body — never the run's action log/new state or the request) and are bounded bycodegen.repair.max_attempts. Tests are hermetic mechanics checks (loopbackhttp.serverfor HTTP bodies) and never certify the live integration — only a real run does. - Queue persistence (durable across restarts).
- Event/timer intake sources beyond typed input.
- Concurrency: SemIf shared-state mode (
score_shared/SerialPrefixScorer) for parallel decisions; single execution slot remains for processes. - Dashboard: run-requeue cross-linking (child run references its parent), scheduler sim controls (busy/idle/tau) as a first-class panel.
- Data-contract tiered data lookup on skill creation (BRAINSTORM item 1):
the body declares its own flat
CONTRACT(variable name -> semantic description, for user input + SemIf only);contract.jsonis a persisted mirror. The config step searches the full cascade — global config → category config → skill config — via SemIfchoiceper variable, reusing an existing source when one matches (config:search, decision-logged) and auto-populating the skillconfig.json. Variables with no match are asked of the human AFTER code generation, on first fire, via a pre-actneeds_inputpause; each answer gets a SemIfrecord-as-config vs ask-again-each-firechoice (config:record). On successive firings only unresolved variables are asked. Shipped with item 1 (Sep 2026); contract now lives in the body (Sep 2026). - Post-codegen mock-data test (BRAINSTORM item 1): after the body +
contract land, a shared-context testgen call produces
skill.test.pywith fixture data embedded inline (no separate mock_data.json), andrun_skill_testexecutes the test as a subprocess in the skill folder before the leaf is declared runnable. On failure a 3-option SemIf decision (codegen_regen, trace-only) picks code/contract/test to regenerate, feeding the error + existing files back, bounded bycodegen.test_max_attempts— a generated body that can't execute its own data path fails authoring, not the first real request. Shipped with item 1 (Sep 2026). - Skill-code inspection: new skills are labeled as new, and the CLI and
dashboard gain the ability to inspect a skill's generated code body
(read-only view of
data/skills/<category>/<name>/and its trace) so the author can audit what was generated. - Messenger gateway (SimpleX first, then LXMF) (Sep 2026; LXMF Oct 2026):
python -m semif_agent.cli gatewayruns a dedicated process that connects to one or more transports and feeds authorized DM text through the normal queue/dispatch pipeline; results, authoring questions, and repair offers are sent back to the originating chat.gateway/base.pyis the transport contract (GatewayAdapter,InboundMessage,OutboundMessage),gateway/service.pythe platform-aware scheduler glue (single execution slot,(platform, chat)owner maps, pending-run ownership shared across platforms, queue drain),gateway/simplex.pythe SimpleX adapter (lazywebsockets, default-deny allowlist by contactId/display name, rapid-message batching, structured/_send), andgateway/lxmf.pythe LXMF/Reticulum adapter (lazylxmf, in-process via the neutralsemif_agent/lxmf_transport.py, allowlist by LXMF address,threading.Timerbatching). All adapters share one process and one scheduler (--platform simplex,lxmf|all). DMs only for the first cut; groups/attachments/reactions are future work. See "### gateway (messenger intake)". - LXMF voice commands (Sideband push-to-talk) (Oct 2026): the LXMF gateway
accepts voice messages, so a Sideband PTT send is a command like any other.
Sideband delivers a PTT message with an empty body and the audio in
LXMF.FIELD_AUDIO([audio_mode, data]);lxmf_transport.normalize_messageextracts it throughparse_audio_field, which maps theLXMF.AM_*modes to a decodekind(opus_ogg/codec2/unknown) and acodec2_rate, and the adapter transcribes it whengateway.lxmf.voice.enabledis set. HQ PTT is Opus/OGG, decoded and transcribed byvoice_transport.WhisperTranscriber.transcribe_bytes(no separate decode step; faster-whisper bundles PyAV); non-HQ Codec2 is decoded to 8 kHz PCM byvoice_transport.decode_codec2(the optionalpycodec2bindings), wrapped in a WAV, and transcribed the same way. The Opus path needs only faster-whisper (requirements/transcribe.txt) and Codec2 additionallypycodec2(requirements/codec2.txt), not the microphone voice stack, so the install plan'sinstall_transcribeflag (fromgateway.lxmf.voice.enabled) drives a separate bootstrap stage (the Codec2 bindings best-effort, native) and thecheck_requirementsguard stays lxmf-only. Transcription runs on a dedicated single-slot worker thread (the Reticulum callback thread only enqueues, since a slow decode would stall the router); a failure, a missing decoder, an undecodable mode, or a missing transcriber is traced and reported back to the sender rather than silently dropped, and the audio is transient — never stored or exposed, exactly like the voice gateway. See "### gateway (messenger intake)". - LXMF voice replies (Piper -> Sideband PTT) (Oct 2026): a chat that last
messaged by voice is answered with a voice message when
gateway.lxmf.voice.reply_with_voiceis on (the default): the adapter synthesizes the reply text with Piper (voice_transport.build_synthesizerfrom thevoice.ttsblock), encodes it to an OGG/Opus container (voice_transport.pcm_to_opus_oggresamples to 48 kHz and muxes with PyAV's bundled libopus), and the transport sends it back inLXMF.FIELD_AUDIOas a Sideband HQ PTT message (lxmf_transport.audio_fields->[AM_OPUS_OGG, ogg]), with the reply text as the message content so a text-only client still sees it. The reply mode follows the chat's most recent inbound message — a text message reverts it to text replies. Synthesis runs on the outbound pump thread (never the Reticulum callback thread); it needspiper-tts+ PyAV (requirements/tts.txt), never the microphone stack, so the install plan'sinstall_lxmf_ttsflag (fromgateway.lxmf.voice.reply_with_voice) drives its own bootstrap stage. A missing synthesizer, a synthesis failure, or an encode failure is traced and the reply falls back to text — never dropped. The reply length is bounded byvoice.max_speak_chars. See "### gateway (messenger intake)". - Voice gateway (wake word + STT + TTS) (Oct 2026):
gateway/voice.py(VoiceAdapter, platformvoice) is the local microphone front end over the neutralsemif_agent/voice_transport.py: an always-on openWakeWord wake word,webrtcvadendpointing, faster-whisper speech-to-text, and Piper text-to-speech oversounddevice. It is a normalGatewayAdapter, so the single-session routing,needs_inputquestions, repairs, and approvals all work throughGatewayServiceunchanged — a spoken command is just text fromvoice:<chat_id>, and every reply is spoken. No remote peer and no allowlist (physical mic access is the authorization). The wake word is required before every command and is held while the scheduler's single slot is still running the current request (GatewayService.input_ready), so a second command cannot start until the first reaches a result (or pauses for the user's answer). Barge-in (gateway.voice.barge_in.enabled, default on): while a reply is speaking the wake word is still scored, so the user can interrupt — the playback is aborted (chunked streaming with astop_event; the reply is muted until the interrupt is handled so it never resumes over the user) and the following command is captured. A bare "stop"/"cancel" (or a short variant) aborts the spoken reply and drops anything queued behind it; anything else is run as a new command.barge_in.thresholdraises the wake bar for barge-in only (0 = usewake.threshold) so the agent's own TTS cannot self-trigger. Disable for strict half-duplex. The whole voice stack is optional and lazy-imported (requirements/voice.txt, pinned separately from the engine set since it is hardware-dependent); the gateway refuses to start with an install hint.bootstrap.sh --voiceinstalls the deps and downloads its models (the openWakeWord models land in the venv under.runtime/venv, the Piper voice under.runtime/voice/tts, the faster-whisper model in the.runtime/hfcache). See "### gateway (messenger intake)". - Read a book aloud over a voice front end (Oct 2026): a skill that
resolves a long text can ask the front end to read it aloud instead of
returning a bounded summary. The skill asks the scheduler's speech channel
(
ctx.speech,semif_agent/speech.py— the sibling ofctx.timers)supports(source); the gateway service registers the per-source predicate at startup, so a skill only offers a read to a front end that can stream one (a typed request, or a platform with no voice path, keeps the saved-file summary). It then registers aReadAloudand returns immediately;GatewayService.surface()drains it and queues anOutboundMessagewhosestreamfield carries the request to the platform that owns the run (any other platform is tracedgateway_stream_unsupportedand skipped, never handed a message it would drop silently). Two adapters stream it: the local voice gateway plays it through the daemon's Piper voice one chunk at a time (gateway.voice.read.enabled), and the LXMF voice gateway sends it to a voice chat as a sequence of Piper Opus/OGG voice messages (gateway.lxmf.voice.read.enabled; a chat that last messaged by voice). Both usereading.chunk_textwith a chunk size clamped below the platform's speakable budget so a chunk is never truncated, and write the bookmark before each chunk so the position is the interrupted chunk's start. The read is background: it does not hold the scheduler's single slot, so the agent stays free. A run that registers a read is treated as terminal (read_aloud_terminal): the read is the answer, soassess:outcomemust not re-dispatch the request (which otherwise authored a spurious skill). The user stops it like any spoken reply — a wake-word barge-in "stop", or on LXMF a "stop" message (any new command also interrupts it; tracedgateway_read_stop/_interrupted/_doneon voice,lxmf_read_*on LXMF). Position lives in abookmarks.jsonbeside the saved books (semif_agent/reading.py), so a later request resumes where the listener stopped.gutendex.read_bookis the first consumer: it checks the local library (the books folder) first — a book already saved is read from disk (matched by id, or by the name in the request) with no network, and a catalog-resolved book is reused from disk rather than re-downloaded — then over a voice front end reads it aloud, while over any other source it keeps returning the saved-file summary. - Custom Piper voice (train your own) (Oct 2026): the TTS voice is
replaceable with one fine-tuned on the user's own recordings. This is an
optional, off-bootstrap pipeline (
scripts/voice-record.pyrecords an LJSpeech dataset;scripts/voice-train.shfine-tunes from the checkpoint pinned inpins.jsonvoiceand exports ONNX on a GPU host;semif_agent/voice_train.pyholds the neutral recording helpers). Deployment needs no gateway code change:cli._build_gateway_adapteranchorstts.voice_dirto.runtime/voice/tts, so a trained<name>.onnx+<name>.onnx.jsondropped there is selected by settinggateway.voice.tts.voiceto<name>. Only a real spoken reply proves it. The recorder has three modes: interactive (default),--speak-prompts(TTS reads each line) and--read-prompts(prints each line + beeps, no speech). Two field gotchas: a mic that re-enumerates (usually on a USB hub) drops the stream — reads take a--read-timeoutso a take ends instead of hanging, and prefer a direct port; and prompt/reply audio needs the ALSA output unmuted (PortAudio has no volume control). Seedocs/VOICE-TRAIN.md. - Bridge services (SimpleX first) (Sep 2026): messaging UX — invite links,
reading incoming messages, composing sends — is decoupled from the command
gateway.
semif_agent.bridgesis a folder of standalone third-party API bridges, each its own process (cli bridge) against its own service daemon.SimplexBridgeowns a second simplex-chat profile and serves a token-guarded localhost HTTP API;registry.describe_bridges()injects the catalog into the codegen prompts. Gateway isolation is non-negotiable: the gateway must never grow read/send/address surface. See "### bridges (third-party API services)".
Later / open questions
- Safety/authority: which inputs may interrupt high-stakes processes; is interrupt a per-skill permission?
- Calibration: SemIf ships per-workload temperature scaling; adopt it before treating probabilities as confidence.
- Enumerate the intake source taxonomy and per-source gating.
- Decision-engine latency. A single SemIf forward pass over a small prompt
can take seconds on CPU, and a trivial request pays several of them
(actionability + category + scope + leaf + intent + assess), so routing and
assessment dominate end-to-end agent latency — not audio I/O (STT/TTS are
sub-second) and not the network. Before treating latency as a front-end
problem, profile the engine: confirm thread utilization, whether the cost is
prefill vs. per-option scoring, and whether a smaller/faster decision model or
a shared-state (
score_shared) path helps.decision extra.timing(input_tokens/forward_seconds/total_seconds) and the voice latency breakdown (scripts/voice-latency.py) are the measurement hooks.
Constraints & gotchas (learned the hard way)
Decision engine (providers)
- The decision engine is pluggable, selected per machine by
engine.providerin config.json — the same provider pattern asllm/codegen."semif"(default) is the local llama.cpp GGUF (SemIfEngine);"winnow"is a remote Winnow/v1/systemonetyped-decision API (semif_agent.winnow.WinnowEngine, configured by the nestedengine.winnowblock);"ollama"is ollama's native System One/v1/systemoneroute (semif_agent.ollama_systemone.OllamaSystemOneEngine, configured by the nestedengine.ollamablock).cli.build_enginepicks the class;SemIfEngine/WinnowEngine/OllamaSystemOneEngineall satisfyengine.DecisionEngine(call/warm/loaded/generate). winnowandollamaare different edges of the same System One contract. Both map the flat decision onto achoicequestion and validate/normalize the returned distribution over exactly the requested option ids, but theollamaprovider implements the deployment details only ollama has: there is no/health, sowarm()probesGET /api/versionandPOST /api/show(which also proves the model is pulled and advertises thedecisioncapability),engine.ollama.context_tokens: 0follows the model's realnum_ctxfrom/api/show,keep_aliverides on the request, choice criteria descriptions use the ollama subsetstring | null, and a choice question needs at least two options. Decision models do not generate text, soOllamaSystemOneEngine.generateraisesEngineUnavailable— usellm.provider == "ollama"for the chat path.- The engine is always real and every
EngineUnavailableis fatal, whichever provider is selected:WinnowEngine/OllamaSystemOneEngineconvert every network, HTTP, and malformed/unnormalized-distribution failure intoEngineUnavailableso the scheduler's fatal path (and the codegen watchdog / LLM bridge's graceful paths) behave identically to the local engine. There is no fallback model. - The agent's flat decision (
state+question+ typedoptions) maps onto the System Onechoicequestion type (options->criteriaid->description,question->instructions); the returned distribution is validated against exactly the requested option ids and normalized. Forwinnow,generategoes through the same server's/v1/chat/completions, sollm.provider == "semif"keeps working when the decision engine is Winnow. - Swapping the decision model changes routing/assessment behaviour and the
decision-log distribution; that is the intended per-machine choice. The
decision log and
dreamcost are unchanged becauseDecisionResultis the same contract. - Context differs by provider (the local engine's
engine.context_tokensvs the remote server's own decision window, mirrored inengine.winnow.context_tokensor discovered fromengine.ollama's/api/shownum_ctx); a state that overflows is a fatalEngineUnavailable, the same class as the local token limit. Every engine exposes its window ascontext_tokens(aDecisionEngineproperty), which the scheduler uses to size generated artifacts — see "Artifact size budget".
Environment
- 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. It is CPU by default: SemIf's
llamacpp backend hardcodes
n_gpu_layers=0. Settingengine.gpu_layersin config.json offloads to a GPU when llama-cpp-python was built with a GPU backend (Vulkan/ROCm/CUDA). The agent wraps the backend's_cpu_model_paramsso the knob works without patching the re-cloned engine source, and on the GPU path also forces a full cache reset (llama_memory_clear(mem, True)): SemIf's metadata-only clear leaves stale hybrid-attention state on Vulkan, so repeated scores drift otherwise. A GPU build is opt-in — llama.cpp's Vulkan backend splits the graph across CPU and GPU even atn_gpu_layers=0, roughly halving CPU throughput, so a CPU-only host must not get one (bootstrap.sh --gpu vulkan|rocm|cuda, or setengine.gpu_layersand rerun, builds it; the default stays CPU-only). Offload needs the accelerator to itself: the 4B Q4 model needs ~2.9 GiB, so a GPU already holding another model (e.g. ollama) makes the engine slower than CPU and can abort the process withvk::DeviceLostError. ollama is a separate GPU user. - The SemIf tokenizer is fetched from HF (
Qwen/Qwen3.5-4Bat 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
- 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 insidedirect.score). Install with--no-depsand bring only what's needed — the committedrequirements/engine.txtholds the local-engine pins (the union filestaging.txtincludes it):pip install -e <semif-clone> --no-deps, thenCMAKE_BUILD_PARALLEL_LEVEL=6 MAKEFLAGS=-j6 pip install -r requirements/engine.txt(numpy 2.3.5, transformers 5.17.0, tokenizers 0.23.2, huggingface-hub 1.31.0, llama-cpp-python 0.3.35). GPU offload is opt-in: setengine.gpu_layersand runbootstrap.sh --gpu vulkan|rocm|cuda(with--gpu auto, detection picks a backend whenengine.gpu_layersis set), which installs the Vulkan build prereqs (libvulkan-dev glslc spirv-headers glslang-tools) when needed. A CPU-only host keeps the default CPU wheel — a GPU build is slower on CPU. A host whoseengine.provideris"winnow"or"ollama"installs none of this (no clone, no GGUF, no tokenizer, no engine deps). - 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 staging host runs exactly this set — not a bug; do not "fix" them by installing torch.
numpy==2.2.6has no cp314 wheel → pip tries a source build that fails withoutpkg-config+python3-dev. Use numpy 2.3.5 (has cp314 wheels).llama-cpp-python==0.3.35builds from source. With all 32 cores it OOM-kills gcc (internal compiler error: Segmentation fault). Limit parallelism: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. GPU builds: pip's wheel cache serves the prebuilt CPU wheel even whenCMAKE_ARGSrequests a GPU backend, so force a real source build with--force-reinstall --no-cache-dir --no-binary llama-cpp-python(bootstrap does this when the installed build reports no GPU offload).- The pinned GGUF:
Qwen3.5-4B-Q4_K_M.gguffrom bartowski (2.8G), downloaded into.runtime/models/by bootstrap. Load ~34s; score ~0.9s/decision on CPU at 8 threads.
configuration (split + secrets)
- Three layers, mirroring Home Assistant. Declarative structure is committed
(
pack.jsonmanifests + the core schema); per-machine values are the split config; secrets are a separate gitignored file.config.jsonis a thin index ({"include": ["config/core.json", "config/gateway.json", "config/bridges.json", "config/packs/<name>.json", ...]}); fragments are deep-merged in order (later wins).semif_agent/config.pyowns the loader. - Secrets. A value written as
"!secret <key>"resolves from the gitignoredsecrets.jsonat load (the analog of HA's!secret). A missing key resolves to""at load (so startup never hard-fails) and is reported bycheck-config.api_key_envis gone —secrets.jsonis the one place credentials live. - Schema owns defaults.
semif_agent/config.pyCORE_SCHEMA(core sections) plus each pack'sconfigschema (bridge blocks) own every default. The committedconfig.example.jsonis GENERATED from them (check-config --write-example config.example.json); secret keys are emitted as"!secret <name>", never a real value.check-configvalidates a live config (type mismatches and missing secrets are errors; unknown keys warn). - Seeding.
setup(semif_agent/setup.py, thecli setupsubcommand) runs the first-run interview and writes the split layout +secrets.jsonfrom the answers;config-initwrites the schema defaults with no interview. Bootstrap callssetuponce, only whenconfig.jsonis absent (or--reconfigure); afterwards only a human edits it.scripts/config_merge.pyis the stdlib-only merger bootstrap uses before the venv exists. - The install plan.
setupalso emits a JSON plan (.runtime/bootstrap-plan.json) that bootstrap reads to install only what the answers require: the local engine clone/GGUF/tokenizer,requirements/engine.txtvstransports.txt, the simplex-chat binary, the Playwright stack, the voice stack, and which systemd units to render.plan_from_configderives the same plan from an existing config on a rerun. The plan'sgateway_platformsexcludesvoice(foreground-only), which is what thesemif-gateway.serviceunit runs.
ollama
bootstrap.shinstalls no ollama: it expects the target host to already run one forllm(and pullsllm.modelinto it), whilecodegenmay be remote. Thellm/codegenendpoints are set in the setup interview (or by editingconfig.json); a host that leaves authoringdenyneeds neither.- 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 incontent. Through the/v1compat endpoint the CoT consumes the entire reply budget, sogenerate_category/generate_skill_spec's smallmax_tokensreturnsfinish_reason: lengthwithcontent: ""→JSONDecodeErrorand a traceddraft_failed(no category/skill is ever authored — the whole create branch is silently dead).LLMClientsendsreasoning_effort: "none"(llm.disable_thinking, default on) so the model answers the ~30-token JSON directly. Ollama's nativethink:falseis not plumbed through/v1(silently ignored), and/no_thinkin the prompt is ignored too; onlyreasoning_effortworks there. Codegen wants the reasoning, so the knob isllm-only —CodegenClientnever sets it. Unbounded (nomax_tokens) does not help: a reasoning model can loop on this prompt (thousands of reasoning tokens, still emptycontent).
Provisioning (scripts/bootstrap.sh)
- Provision a fresh Ubuntu machine into a running host: clone
semif-agentto a checkout (register its SSH key on your git host first), then runscripts/bootstrap.sh. On a fresh machine it runs the setup interview (semif_agent/setup.py, thecli setupsubcommand) and writes the split config from the answers — decision engine (local SemIf 4B, remote Winnow, or an Ollama System One decision model), new-skill authoring mode (+llm/codegenendpoints when enabled), capability packs, gateways, and timezone — then installs only what those answers require (the install plan drives every conditional stage). Which packs exist is owned by the pack index repo (semif-packs), not this checkout: bootstrap fetches the index first, the interview offers its packs, and bootstrap runs setup in two passes (--answers-outcollects the answers, only the selected packs are cloned, then setup writes the config) so it never clones a pack the user did not choose.--yestakes the minimum working defaults unattended;--answers FILEreplays a saved answer set;--reconfigurere-runs the interview and rewritesconfig/+secrets.json.--voice/--browseradditionally install those optional stacks (requirements/voice.txt+ systemlibportaudio2+alsa-utils;packs/browser/requirements.txt+ a browser) even when the plan did not pick them. The plan'sinstall_transcribeflag (fromgateway.lxmf.voice.enabled) installsrequirements/transcribe.txt(faster-whisper only) and warms its STT model, andinstall_lxmf_tts(fromgateway.lxmf.voice.reply_with_voice) installsrequirements/tts.txt(piper-tts + PyAV) and downloads the reply voice — a rerun picks either up after the operator enables the setting in config. The script must be run from a checkout — it reads pins from that checkout'spins.jsonand never re-clones the agent repo (only the pack index, the selected packs, 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 (a rerun SKIPS the interview and uses the existing config). It installs no ollama:llmis the local ollama (bootstrap pullsllm.modelwhen configured),codegenmay point at a peer host. It WARNs (never auto-pulls) if the codegen host is missing its model, and WARNs only when authoring is enabled butllm.model/codegen.modelare unset. - All installation artifacts live inside the checkout under a gitignored
.runtime/(venv/,engine/,models/,hf/,bin/simplex-chat,simplex/,systemd/, andvoice/for the optional voice models), so an end user can find and debug the whole stack in one tree. Only operationally-forced artifacts live outside: the SSH key (~/.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 the committed
pins.json: theengineblock (semif_repopublic GitHubTheoLeeCJ/SemIf,semif_refpinned commit,gguf_url/gguf_sha256, HF tokenizersource/revision) and thesimplex_chatblock (version, and anassetsmap of per-archbin_url/sha256; bootstrap selects byuname -m,arm64normalized toaarch64). Per-machinesimplex_chatports/display names stay inconfig.json. The python dep pins live inrequirements/split by concern (committed):core.txt(the test runner, always),engine.txt(the local decision engine),transports.txt(websockets/lxmf), plus the optionalvoice.txt(full microphone stack),transcribe.txt(faster-whisper only),tts.txt(piper-tts + PyAV, for LXMF voice replies) andcodec2.txt(pycodec2, native, for LXMF Codec2 voice messages);staging.txtis the union of the non-hardware files. A pack owns the deps its skills/bridge need, shipped atpacks/<name>/requirements.txt(e.g. the browser pack's Playwright pin); the install plan lists the selected/enabled packs that ship one (plan["pack_requirements"]) and bootstrap pip-installs each, so a host that never enables a pack installs nothing for it. Bootstrap installs only the subset the plan requires. The agent readsengine.source/revisionfrompins.jsonand derives the GGUF path fromengine.gguf_urlunder.runtime/models/(an explicitengine.ggufinconfig.jsonoverrides it). Maintenance: bump the pins inpins.json/requirements/, 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 the split config from the interview (
setup:config/core.json,config/gateway.json,config/bridges.json,config/packs/*.json, theconfig.jsonindex, andsecrets.json) whenconfig.jsonis absent (or--reconfigure), and never writes it again otherwise — only a human edits it. The committedconfig.example.jsonis GENERATED from the core + pack schemas and ships the provisioned defaults. The generated config reflects the answers: the minimum path enables onlyessentials,llm.provider = "semif", an emptycodegen.model(no authoring), and every gateway/bridge off; the maximum path enables the chosen packs, gateways, a remote engine, and thellm/codegenendpoints with credentials insecrets.json. Bootstrap renders/enables only the user services the plan needs:semif-simplex.service(the commandsimplex-chatbot daemon,--create-bot-display-nameonsimplex_chat.port, when the simplex gateway is on),semif-gateway.service(.runtime/venv/bin/python -m semif_agent.cli gateway --platform <daemon platforms>; voice is excluded — it is foreground-only),semif-simplex-forward.service(the bridge's own daemon/profile onsimplex_chat.forward_port, when the simplex pack is on) andsemif-bridge.service(.runtime/venv/bin/python -m semif_agent.cli bridge, when any bridge pack is on); a reconfigure retires units it no longer needs. The gateway allowlist (gateway.simplex.allowed_users) and fallback (home_channel) areconfig.jsonfields the operator edits; with an empty allowlist the gateway denies everyone (the safe default until the human adds their contact id).--copy-data SRCrsyncs a prior host'sdata/for continuity. Bootstrap then runspacks/simplex/scripts/simplex-address.pyto create/print the command bot's contact address (and the forwarding bot's, via--ws-url). - First run of the minimum path still downloads the 2.8G GGUF and builds
llama-cpp-pythonfrom source (~10 min on 6 cores); a remote-engine host skips both, and reruns are fast no-ops. - Per-host run/verify commands and addresses:
local/ENVIRONMENT.md.
codegen (skill bodies)
- Skill bodies are written by a separate OpenAI-compatible model, configured
under
codegenin config.json (your configured code-capable model — larger/slower thanllm). Title + description for new skills come from the separate smallllmprovider (its own endpoint/model, shared transport inprovider.py); only the runnable code body uses codegen. Both are optional: an emptycodegen.modelmeans "no authoring path" —build_codegen_clientreturnsNone, the scheduler guards every create door, and a host that leavesnew_skill_creationatdeny(the minimum path) starts with neither endpoint configured.build_llm_clientlikewise returnsNonefor a non-semifprovider with no model. With authoring enabled the setup interview requires the endpoints; a hand-edited config that enables authoring without them fails cleanly (a tracedauthoring_unavailable, not a crash). - Local engine as the
llmprovider:"semif"(provider.SemIfEngineClientllm.SemIfLLMClient). Setllm.provider = "semif"to generate the title/description (and any otherllmtext: gateway result cleanup, the LLM bridge) from the already-loaded SemIf decision model in-process, with no ollama endpoint and nollm.model— the pinned GGUF is the model.engine. SemIfEngine.generateautoregressively samples through the backend's low-level llama.cpp context (chat template withenable_thinking=False, KV cache cleared), holding the same lock ascall, so a reply briefly serializes against routing/assessment on the one loaded model. The adapter is a drop-in sibling ofOpenAICompatClient(samechat(messages, max_tokens=..., temperature=..., ...)surface; HTTP-only args accepted and ignored) and raisesLLMErroron any engine failure, so the scheduler's gracefuldraft_failedpath and the LLM bridge's 502 path are unchanged. Knobs:llm.semif.temperature(0 = greedy) andllm.semif.max_tokens. Only thellmtask supports it (codegen still needs a real code model).
- Alternate hosted provider: OpenCode Console (
console.py). Either endpoint can run against the hosted, authenticated OpenAI-compatible Console inference API instead of local ollama: setllm.provider/codegen.providerto"opencode"(default"ollama"), setmodelto a Chat Completions family id (kimi-k2.7-code,glm-5.3,deepseek-v4.1-flash,qwen3.8-max, the free models, …), and setapi_keyto"!secret <key>"with the key insecrets.json(a literalapi_keyalso works).build_schedulermaps"opencode"→ConsoleLLMClient/ConsoleCodegenClient, which keep the existing error contracts (LLMError/CodegenError/DegenerationError) and the same opt-in sampler behavior (none sent unless configured). TheOpenAICompatClienttransport already speaks the Console's SSE shape (delta.content+delta.reasoning_content+include_usage+[DONE]); the Console subclass adds bearer auth, defaults the base URL tohttps://opencode.ai/inference/openai/v1, and setsquery_context=Falseso no ollama/api/showprobe is sent. It always sends aUser-Agent— the Console gateway returns HTTP 403 for urllib's defaultPython-urllib/<ver>(urllib does not send one; it sends its default, which is blocked) — override withuser_agentif desired. The Consolellmclient also forcesdisable_thinkingoff:LLMClientsendsreasoning_effort: "none"(an ollama-compat knob) and the Console gateway rejects that parameter with HTTP 400. Only the Chat Completions family is drop-in; Claude / OpenAI-Responses / Gemini models use different wire formats and need 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_tokenson the codegen call. A reasoning codegen model reasons first and a cap truncates the hidden reasoning, leavingcontentempty (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 onlycontent, so reasoning is filtered automatically. The client default timeout is 1200s and a slow codegen model can exceed it — the per-machineconfig.jsonsetscodegen.timeout: 3600. Raisecodegen.timeoutin config if a harder prompt needs more. - Bodies are persisted as one folder per skill:
data/skills/<category>/<name>/holdingskill.py,skill.test.py,contract.json, andconfig.json(all gitignored), loaded back at startup viaimportlib, so skills stay runnable and configurable across restarts. The old single-file layout (data/skills/<category>/<name>.py) is not read — clean switch, no compat shim.CODEGEN.mdat the repo root is the contract the codegen model is prompted with — change it only with intent, it shapes every generated body. Bodies declareINTEGRATION(service/transport/config_vars) and must perform the real action via stdlib transports with values fromctx.config. Mocking/testing has its own contract,TESTGEN.md: a hermetic mechanics check (inline fixtures, loopbackhttp.serverfor HTTP bodies, no external network) that never certifies the live integration — only a real run does. The body owns no data; everything comes from the runner viactx.config. - Skill packs. Each pack lives in its own repository (
pack.<name>, listed in thesemif-packspack-index repo);scripts/bootstrap.shclones them into the gitignoredpacks/<name>/. A pack bundles a concern with its skills: apack.jsonmanifest (name, concern,categories→ descriptions,bridgesreferenced by name,requires, and aconfigschema) plusskills/<category>/<name>/in the exact generated-skill folder format (skill.py,contract.json,skill.test.py, plusmanifest.jsonwith the description).semif_agent/packs.pydiscovers them (PackRegistry, scanningskill_packsroots for*/pack.json; a root with no manifest is one implicit pack), andmerge_packsloads every enabled pack into the tree at startup. Pack enable is one switch: an explicitpacks.<name>.enabled, else a bridge pack followsbridges.<bridge>.enabled, elseenabled_by_default. Disabling a pack drops its categories entirely (including generated bodies authored into one) and stops its bridge. Recorded config (credentials collected at first fire) is written to the runtime storedata/skills/, so a pack repo never holds secrets, and a generated body with the same name replaces the pack skill. The shipped packs:nextcloud,simplex,outlook,browser(each owning its bridge), andessentials(the built-in local utilitiestime+calculator+skills; no bridge).nextcloud.create_eventis the authoritative worked example (creates a CalDAV event through the Nextcloud bridge; derives the title/date/time from the query, asks for missing fields and resumes, resolves the target calendar with a SemIf choice over the owned calendars — a strong winner is used, otherwise the configured default);nextcloud.next_eventis the read counterpart (through the Nextcloud bridge, recurring events expanded server-side);nextcloud.create_taskadds a task to a Nextcloud task list through the Nextcloud bridge (GET /tasklistsfor a VTODO-capable target,POST /tasksto create it, the LLM bridge to phrase the summary/description);simplex.next_message(read via the forwarding bridge),simplex.send_message(send to a contact resolved over the bridge's contact list), andsimplex.connect_link(show/create the forwarding bot's contact link) are the messenger pack skills;time.now,time.date,time.set_timer, andtime.set_alarmare the local time utilities (computetransport, empty contract) — they read the host clock and schedule onctx.timers. Local time is the top-leveltimezoneconfig value (an IANA name such asAmerica/Chicago;timers.local_now/resolve_timezoneresolve it viazoneinfo), falling back to the host's own timezone when it is empty or unknown;TimerServiceformats due/fired times in that zone too. The nextcloud pack skills derive "now" the same way, so a request time is parsed in the user's zone rather than the host's;calculator.calculateis the local-arithmetic skill (computetransport, empty contract): bounded to two operands and one operator, the operator is a SemIf choice over addition/ subtraction/multiplication/division/exponents/squares/cubes/square roots/cube roots/fractions/percentages, SemIf picks the operands when the request offers more numbers than the operator consumes, and the answer is spelled out in words for the ear (an inexact result is announced as "approximately ...");skills.list_categoriesandskills.list_skillsare the introspection skills (computetransport, empty contract): they read the agent's own tree through the read-onlyctx.catalog(never the housekeeping-onlyctx.admin) and report the category list, or the leaf names inside a category named in the request (asking for one when it is missing, and reporting an unknown category honestly) — so a voice user can ask "list skill categories" or "list skills in nextcloud". The closedresponsetree is filtered out of both (it is the non-request catchall, not a capability);tests/test_packs.pykeeps every pack skill honest. - Contract provenance. Each authored body records the CODEGEN.md revision it
was written against.
skill_contract_ref()(codegen.py) returns{"ref", "dirty"}:refis the short git commit sha the contract was read under (revive withgit show <ref>:CODEGEN.md) anddirtyrecords whether the working-tree contract differed from that commit; both degrade toNoneoutside a git checkout. Recorded ascontract_ref/contract_dirtyon theskill_writingtrace event; the dashboard showsCODEGEN.md @ <ref>with a*when dirty. Deferred: this pointer covers only the generic pattern now that bridge specifics live in the runtime catalog, not CODEGEN.md — recording a catalog revision on the trace is future work. - Trust boundary: generated skill code is executed locally (it is imported
as a module and its
actruns in-process;skill.test.pyruns as a 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-slotllmdraft worker (small model authors title+description+a de-identified goal) → stub registered + hot-merged into the tree → the body write is queued to a separate single-slot codegen worker (the 12G codegen model can't run twice), the gate stays free for new input. A category request chains the same way in one worker. The codegen worker runs the full authoring pipeline:- codegen body (
generate_skill_body/regenerate_skill_bodyon repair): CODEGEN.md + the de-identified spec (goal + generic service/transport) + tree + bridge catalog — never the request, question answers, or run output; the body is a singleact(ctx, request), reads every operational value fromctx.config, performs the real action, and declaresINTEGRATIONand its own flatCONTRACT(every contract key must be read fromctx.config, and every name the body references must be imported/bound — both enforced byparse_skill_body). - fidelity gate (
authoring:fidelitySemIf decision +integration_findings): a rapid sanity check (accept/reconsider) — does the body contain a concrete, side-effecting operation that really performs its goal (vs simulated/declared-but-unused)? The state carries the whole body plus a deterministic operation inventory and the de-identified goal (never the raw request), and asks the positive question; its threshold is its owncodegen.fidelity.tau. It only triggers a rewrite, never a diagnosis. One corrective regen with the de-identified evidence bundle (codegen.fidelity.max_attempts, inventory + findings included), then accept with a trace rather than hard-failing authoring. - contract (
parse_contract): read from the body's own flatCONTRACTconstant — a single flat object of snake_case variable name -> semantic description, for user input and SemIf only (no types/validation; that lives in the code + test). No separate generation call;materialize_skillrewritescontract.jsonas a mirror. - test (
generate_skill_tests): a shared-context call (seeded with TESTGEN.md +skill.py+ the body'sCONTRACT) producesskill.test.py— hermetic mechanics, loopback fixture injects the endpoint through config, fixtures inline. - auto-run test (
run_skill_test): subprocess in the skill folder,codegen.test_timeout; on failure a 2-option SemIf decision (codegen_regen, trace-only) picks code/test to regenerate (the contract rides in the code), the error + existing files are fed back, bounded bycodegen.test_max_attempts. On success the body is materialized (materialize_skill), hot-merged, the leaf'swritingflag clears, and the original request is re-queued and re-runs navigation onto the new leaf (skill_requeued). The worker drains it withrun_queue_buffered, so the re-run's reply lands in the scheduler's outbox and a front end (drain_outbox) routes it to the chat — the worker must not swallow the answer to the user's own request. On failure (CodegenError/ValueError) the user is notified, the leaf stays a restartable stub, and the request is NOT re-dispatched. A re-dispatched request whose skill is still unwritten reports the pending write instead of authoring a second skill (awaiting_skill_bodymeta guard).create_categoryruns the same chain after authoring the category (create_category→create_skill→ async body → re-dispatch). An empty (stub) or in-progress leaf picked by navigation is reported gracefully — no silent no-op; restart it with therestart <category> <skill>REPL command or the dashboard button on the skill row /skill_write_failedflow node. Codegen failure — including a request timeout — is raised asCodegenErrorby the client, never a rawTimeoutError. The default codegen timeout is 1200s (cli.build_scheduler); a slow codegen model's writes can run 25–45 min, so the per-machineconfig.jsonsetscodegen.timeout: 3600. Raisecodegen.timeoutin config for harder prompts.
- codegen body (
- Config tiering + first-fire collection. After the contract lands, a SemIf
choiceper variable auto-populates the skillconfig.jsonfrom the whole cascade — global config → category config (data/skills/<category>/config.json) → skill config (codegen.contract_search, phaseconfig:search, decision-logged). At runtime the runner merges global -> category -> skill config (+ per-fire answers) intoctx.config; contract variables it cannot satisfy pause the run before act (pre_act), asking the human one at a time. Each answer gets a SemIfrecord-as-config vs ask-again-each-firechoice (phaseconfig:record); recorded values persist to the skillconfig.json. An empty answer (or the literal "skip") skips that variable for the run: it stays unset inctx.configand is never re-asked, and the run proceeds (or asks the next missing variable). An act-drivenneeds_inputalso accepts an empty answer — it is forwarded toactasuser_input=""; a body that then fails for lack of the info is assessed/repair-offered normally. - Resolved-input observation. The
assess:outcomestate includes the resolved contract values (resolved inputs:block), the bounded action log, and the run ledger (steps already taken) so the decision sees the full query → resolution → action → chain path; secret-named variables (pass/token/secret/key/credential/auth) are redacted to***so credentials never reach the decision log. - Codegen privacy (de-identified spec, no elicitation). The codegen endpoint
is the primarily-cloud model, so it is shown only a de-identified spec. The
trusted local
llmauthors a reusablegoal(plus a generic service/transport) from the request, with every user-specific value stripped: names, addresses, emails, phone numbers, dates, times, numbers, account names, hostnames, credentials, and quoted content are removed, and the body derives those fromrequest.textat runtime. The user's request, question answers, and run output are never placed in a codegen prompt (body, retry, regen, or testgen); the repair/fidelity evidence bundles are reduced to a generic failure kind + integration + goal + previous body. The stub'sgoalis persisted in the registry so a restart/regen re-drives codegen without the request. Implementation questions were removed with this change: the spec's service/transport carries what the questions used to; the only remaining question queue is the repairask_userpath (local). - Fidelity gate. After the body lands,
authoring:fidelity— a real SemIf accept/reconsider decision (P(reconsider) >= codegen.fidelity.tauor any staticintegration_findingsfrom the declared transport vs. real calls and declared config_vars actually read) decides whether the body really performs the action. The state carries the whole body, never a prefix, plus a deterministicoperation_inventory(the HTTP verb + path, CLI, mail, file write, or timer it performs) and the de-identified goal; the raw request is not included (it added a remote-engine PII path and no signal — the goal is the reusable action). The question is positive ("is there a concrete operation that realizes the goal?"), which the model answers far more reliably than the old "does it simulate?" on a prefix. It never diagnoses: it only triggers a rewrite, which is handed the de-identified evidence bundle as-is (goal, description, raw INTEGRATION, findings, operation inventory, SemIf verdict+probs, previous body). A rejected body is rewritten once (codegen.fidelity.max_attempts, reason_kindfidelity); a body that still fails is accepted (never hard-fail authoring) but traced (fidelity_review,performs_real_action=false). A decision row is logged under phaseauthoring:fidelity. (An undeclared INTEGRATION is what the dashboard badgesunverified— that isintegration_source, not the fidelity verdict.) - Artifact size budget. A decision ingests a generated artifact whole, so
each is bounded:
parse_skill_body/parse_skill_testreject an over-budget artifact withArtifactTooLong(a hard ceiling, since it is a hard limit), which the codegen retry ladder answers with a shorter-artifact prompt. The ceiling is derived from the active engine's context —engine.context_tokens(local GGUF) orengine.winnow.context_tokens(Winnow; must mirror the server's--ctx-size) — minuscodegen.decision_reserve_tokens(default 1024), the headroom for everything else in the fidelity state (goal, description, integration, findings, inventory, question, options, prefill margin), which is known because codegen runs immediately before the gate.codegen.max_body_tokens/max_test_tokens(0 = derive; a positive value overrides — lower it to avoid a long fidelity evaluation) set each artifact's budget, converted to chars bychars_per_token. This is why the gate never truncates and a body can never exceed what the gate can read. - Repair loop. A failed real run (assessment failure or a raised skill
error) logs a SemIf choice (phase
repair:choice) offeringretry/repair_skill/ask_user/no_repair, recorded as arepair_offeredtrace and surfaced in the REPL (repairs,repair <id> [action]) and the dashboard repair panel. Executing is user-confirmed (a codegen write is slow):retryrequeues the request,repair_skillrewrites the body with the observed failure (run_failurereason_kind) and re-runs it,ask_userposts a repair question whose answer starts the repair. Repairs are bounded bycodegen.repair.max_attemptsper skill; the run itself is never auto-repaired silently. - Engine calls are serialized with a
threading.LockinsideSemIfEngineso the codegen worker's degeneration SemIf checks never race main-thread navigation/scoring on one llama.cpp context. - Set
codegen.stream: trueto echo the codegen output as an SSE token stream to stdout during body writes — including the chain-of-thought, so a long (~30 min) write shows live progress. The client reads reasoning from eitherreasoning(ollama) orreasoning_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. codegen.idle_warn(default 60s) /codegen.idle_timeout(default 180s) surface a silent stream: a wedged generation prints a warning atidle_warnseconds with no tokens, then raisesCodegenError(→ graceful stub) atidle_timeout— instead of blocking on the 1200s total budget. A streaming stall with zero output usually means the ollama ROCm runner wedged;sudo systemctl restart ollamais the recovery.- Token budget + exact accounting. The context window is auto-detected once
from ollama
/api/show(parameters.num_ctx, falling back tomodel_info.<arch>.context_length, then thecontext_windowconfig, then default 100000).codegen.smart_limit/warn_limit/max_fill_ratio/warn_fill_ratiobound total fill (prompt + output);max_outputcaps streamed output (>=1 = absolute tokens, 0<x<1 = fraction of window);chars_per_tokenconverts chars to the token estimate for the output cap. The request always sendsstream_options.include_usage, so the client logs the exactprompt/completion/totaltokens, % of window, and aSMART|WARN|DUMBzone (absolute thresholdssmart_limit/warn_limit) at the end of the stream. Real ollama serves/api/show'sparametersas modelfile text ("num_ctx 100000\n..."), not a dict, so the parser handles both shapes and falls back tomodel_info.<arch>.context_length. The total wall-clocktimeoutis 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: 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_penaltyare not sent by default: aNone/absent value is omitted from the request so the server's model/Modelfile default applies. The provider never guesses a value for the user — set one in thellm/codegenconfig block (or perchatcall) only when you know the right value for the model.config.example.jsonships explicit values as a starting point, so a provisioned host still sends them. When configured, a highpresence_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_kare Modelfile-only). There is no escalated preset: a rejected body retries with a fresh short prompt that resets the context to SMART and reuses the same (configured or omitted) sampler params;max_attempts(default 3) bounds the ladder, then a graceful stub. Degeneration does not retry: the watchdog raisesDegenerationError(CodegenError), which propagates straight to the graceful stub (retry-on-degeneration is left as an open decision). - Degeneration watchdog.
codegen.degeneration.{enabled, threshold=0.9, interval=8000, window=2000, min_chars=4000}: while the body streams, a 2-option SemIf decision (continue/stop) runs everyintervalchars against the lastwindowchars of content+reasoning oncemin_charshave accumulated;P(stop) >= thresholdaborts the write with a graceful stub. Recorded as trace-only events (kindcodegen, with probs andstop_prob) — never in the decision log. Disabled when no engine is available (enableddefaults true; the runtime engine check is what gates it off when no engine is loaded).
gateway (messenger intake)
- Run mode.
python -m semif_agent.cli gateway [--platform simplex,lxmf,voice|all] [--dashboard]builds the normal scheduler (engine lazy) and runs the enabled adapters in the foreground.--platformtakes a comma-separated list orall; default issimplex. All adapters share one process and one scheduler (never run two gateway processes over one skill store) — each gets its own transport thread but they route through a single platform-awareGatewayService.--dashboardco-serves the browser UI from a daemon thread. Config lives undergateway.<platform>inconfig.json;enableddefaults false. The voice platform is foreground-only by design (a headless systemd user service does not share the user's audio session). On a bootstrap-provisioned hostscripts/bootstrap.shrenders and enables thesemif-simplex.servicebot daemon (pinnedsimplex-chatin bot mode, profile under.runtime/simplex/, port fromsimplex_chat.port) and thesemif-gateway.serviceagent process (unit runsgateway --platform all), so the gateway runs across logout/reboot. The gateway is its own process — the REPL and the gateway are independent front ends onto the same on-disk logs/registry. On connect the gateway prints each bot's own address once (the SimpleX contact link via the daemon it already owns,_gateway_address_callback; the LXMF address via_lxmf_address_callback) so a human can reach it without running a separate script — the operator front end prints it; the command adapter itself gains no address surface. - Bot address / v7 relay gotcha. The daemon must NOT run with
--headlessor--relay: in SimpleX Chat v7--headlessmeans "chat relay" (requires--relay) and yields a relay address, not a user contact address. Run bot mode instead (simplex-chat -p PORT --create-bot-display-name NAME). The CLI only pumps WebSocket events while it has a controlling terminal, so the unit wraps it inscript -q -e -c '…' /dev/nullto allocate a PTY: a TTY-less process (plainExecStart=under systemd) accepts the socket but never emitsreceivedContactRequest/newChatItems, so contact requests hang forever.python packs/simplex/scripts/simplex-address.pythen shows (creating on first run, via/_address//_show_address <userId>) the bot's user contact link, which a human adds in their SimpleX app to start a DM.bootstrap.shprints it at the end of provisioning. - Transport contract (
gateway/base.py):GatewayAdapter.run(on_inbound, outbound_queue)blocks, deliveringInboundMessages and draining a stdlibqueue.Queue[OutboundMessage | None]. Scheduler work is synchronous and can block on the decision engine, so the adapter bridges it off its event loop (asyncio.to_thread) and puts replies on the queue. A new platform means a new adapter subclass plus a_build_gateway_adapterbranch and a config block; the platform-aware service routes it unchanged. - SimpleX adapter (
gateway/simplex.py): connects to the localsimplex-chatdaemon atgateway.simplex.ws_url(default port 5226, pinningsimplex_chat.port), XML-JSON WebSocket protocol ({"corrId","cmd"}→{"corrId","resp"}/ events).websocketsis lazy-imported;check_requirements()returns an install hint and the gateway refuses to start without it, so the core stays importable on a websocket-free machine. Default-deny allowlist matches either a numericcontactIdor a display name (allowed_users);allow_all_usersis the dev escape hatch.auto_acceptanswersreceivedContactRequestwith/_accept. InboundnewChatItemsare filtered to direct, non-echo (chatDir.typenot*Snd), text-only items, buffered per contact and flushed aftertext_batch_delay. Outbound uses the structured command/_send @<contactId> json [{"msgContent":{"type":"text","text":...}}]— the@<id> <text>shortcut is silently rejected over WebSocket. Groups, attachments, reactions, and typing are out of scope for this cut. The wire protocol itself lives in the neutralsemif_agent/simplex_ws.py(SimplexDaemon); this adapter adds only the allowlist and batching on top. - LXMF adapter (
gateway/lxmf.py): the Reticulum-based command transport. Unlike SimpleX there is no external daemon — Reticulum and the LXMF router run in-process (semif_agent/lxmf_transport.py,LxmfDaemon).lxmf(andrns) are lazy-imported;check_requirements()returns apip install lxmfhint and the gateway refuses to start without it. The bot's reachable address is its LXMF delivery destination hash (32 hex chars); the identity is persisted undergateway.lxmf.storage_path(default.runtime/lxmf/router) so the address is stable across restarts. Default-deny allowlist matches the peer's LXMF address or a best-effort display name (allowed_users);allow_all_usersis the dev escape hatch. Rapid messages are batched per chat (text_batch_delay) with athreading.Timer(no event loop).desired_methodisdirect(reliable link) oropportunistic(single packet); an optionalpropagation_nodeenables store-and-forward.RNS. ReticulumandLXMF.LXMRouterinstall process signal handlers, which only work on the main thread —run_gatewaycallsdaemon.prepare()on the main thread before the transport threads start, andrun()reuses it. Voice commands (Sideband push-to-talk). A Sideband PTT message arrives as LXMF content with an empty body and the audio inFIELD_AUDIO([audio_mode, bytes]);lxmf_transport.parse_audio_fieldnormalizes it into{"codec","codec_name","data","kind","codec2_rate"}(kind= the decode pathopus_ogg/codec2/unknown) and the adapter's_on_itemroutes it to transcription whengateway.lxmf.voice.enabledis set, dispatching the transcript as an ordinary command (same allowlist, same reply path). A dedicated single-slotlxmf-voice-workerthread does the (slow) transcription off the Reticulum callback thread, which only enqueues; on any failure the sender gets a transport-level notice (_notify) rather than silence. HQ PTT (AM_OPUS_OGG, the default) is decoded byWhisperTranscriber.transcribe_bytes— it needs onlyfaster-whisper(whose bundled PyAV decodes the Opus/OGG container), never the microphone voice stack, socheck_requirementsstays lxmf-only and a missing transcriber degrades gracefully (voice.enabledoff, or a tracedlxmf_voice_unavailable). Non-HQ Codec2 PTT is decoded to 8 kHz PCM byvoice_transport.decode_codec2(the optionalpycodec2bindings,requirements/codec2.txt), wrapped in a WAV bypcm_to_wav, and transcribed the same way; an absent decoder is tracedlxmf_voice_codec2_unavailableand reported, and the binding-less 450 modes aslxmf_voice_unsupported_codec— never silently dropped. The audio is transient and never stored, exactly like the voice gateway. Voice replies (Piper -> Opus/OGG). Whenvoice.reply_with_voiceis on (the default), a chat that last messaged by voice is answered with a voice message:_voice_reply(on the outbound pump thread) synthesizes the reply text with Piper (voice_transport.build_synthesizerfromvoice.tts), encodes it to OGG/Opus withvoice_transport.pcm_to_opus_ogg(48 kHz, PyAV's bundled libopus), andLxmfDaemon.sendattaches it inFIELD_AUDIO(lxmf_transport.audio_fields->[AM_OPUS_OGG, ogg]) with the reply text as the message content (a text-only client still sees it). The reply mode follows the chat's most recent inbound message — a text message reverts it to text replies. It needs onlypiper-tts+ PyAV (requirements/tts.txt), never the microphone stack, socheck_requirementsstays lxmf-only; a missing synthesizer (lxmf_voice_tts_unavailable), a synthesis failure (lxmf_voice_synth_failed), or an encode failure (lxmf_voice_encode_failed) is traced and the reply falls back to text — never dropped. The reply length is bounded byvoice.max_speak_chars. Result-only output:LxmfAdapter.result_only(default true; per-platform configresult_onlyoverrides) makesGatewayServicesend just the skill's result line — scheduler bookkeeping is dropped and the<skill>: ok —wrapper is stripped — so a reply (text or voice) is the answer, not the scheduler's internals. Questions, repair offers, approvals, and timer notifications still pass through. Read-aloud: aReadAloudthe service routes here (a skill posted it viactx.speech) is streamed to the chat as a sequence of voice messages:_streamreads the saved text, Piper-synthesizes each chunk to Opus/OGG, and queues it on the daemon, writing the bookmark before each chunk. It stops when the text ends or the user interrupts — a "stop" message (intercepted in_deliver, never submitted as a request) or any new command. Only a chat that last messaged by voice receives one (speech_stream_ready); a text chat keeps the skill's saved-file summary.gateway.lxmf.voice.read.{enabled,chunk_chars}. - Voice adapter (
gateway/voice.py): the local microphone front end. It is a policy layer over the neutralsemif_agent/voice_transport.py(VoiceDaemon) — openWakeWord wake word →webrtcvadendpointing → faster-whisper speech-to-text, and Piper text-to-speech, all oversounddeviceat 16 kHz mono int16 (capture/playback run at the device's native rate and are resampled to/from 16 kHz; a per-block DC removal handles mics with a constant offset). There is no external daemon and no allowlist: the mic is local, so physical access is the authorization; a single configuredchat_ididentifies the session andhome_channeldefaults to it so background notifications (timers, repair offers) are spoken too.run(on_inbound, outbound)starts an outbound-pump thread (OutboundMessage→speak) and an inbound-worker thread, and blocks in the mic loop. Utterances are handed to the worker, not run on the audio thread: the scheduler is synchronous and can block on the decision engine, so a slow task must not stop the mic being read, and the worker traces + speaks a task error instead of letting it kill the front end. Capture-stream watchdog:_read_framereads withaudio.read_timeout_s; when the stream stalls continuously foraudio.stall_timeout_s(a wedged PortAudio/ALSA callback that never delivers another frame) it tracesvoice_stream_stalledand closes/reopens the input (voice_stream_reopened), so the loop recovers instead of blocking forever. Endpointing tolerates the wake tail: the wake detector can fire inside the wake phrase and the cue beep follows, so the first speech captured is the phrase's tail, not the command — untilvad.min_command_msof speech is in hand the trailing-silence endpoint usesvad.initial_silence_ms, so a natural pause before the command does not end the capture (thenvad.silence_ms). Half-duplex by default, barge-in optional (gateway.voice.barge_in): capture frames are normally discarded while a reply is speaking, so the agent never transcribes itself; withbarge_in.enabledthe wake word is still scored during playback, so the user can interrupt. The daemon'splaystreams the reply in small chunks and watches astop_event, so a barge-in aborts the playback promptly; the daemon then mutes speech (_mute), tells the front end viaon_barge_in(True/False), and captures the following command.barge_in.threshold(0 =wake.threshold) is a separate, usually higher wake bar for barge-in so the agent's own TTS cannot self-trigger. TheVoiceAdaptertags that utterance (raw["barge_in"]): a bare "stop"/"cancel" (_is_stop_command) drops any queued replies and unmutes without submitting, while anything else is run as a new command and unmutes when handled. The wake word is required before every command, and is held while the scheduler slot is busy (GatewayService.input_ready): a wake that fires while the current request is still running is ignored (tracedvoice_wake_blocked), so a second command cannot start until the first reaches a result.max_speak_charstruncates long replies before speaking, and a short sinecuebeep plays on wake (optionally again on transcription) so the user knows they were heard. Result-only output:VoiceAdapter.result_only(default true; per-platform configresult_onlyoverrides) makesGatewayServicespeak just the skill's result line — scheduler bookkeeping is dropped and the<skill>: ok —wrapper is stripped — so the spoken output is the answer, not the scheduler's internals. Questions, repair offers, approvals, and timer notifications are still spoken. Read-aloud: the pump also handles anOutboundMessagewhosestreamcarries aReadAloud(a skill posted it viactx.speech; the service routes it here — see the roadmap entry)._streamreads the saved text and speaks it chunk by chunk through the daemon's Piper voice, writing the bookmark before each chunk; it stops when the text ends, when the user stops it (a barge-in "stop" — the daemon mutes playback, which the loop notices — or a bare "stop" heard between chunks), or when any new command arrives.supports_speech_stream(gateway.voice.read.enabled, default on) gates the whole path;read.chunk_charsbounds one chunk (clamped belowmax_speak_chars). Every heavy dep (sounddevice/openwakeword/faster_whisper/piper/onnxruntime) is lazy-imported;check_requirements()returns an install hint and the gateway refuses to start without the stack. The engine interfaces are plain classes (WakeWordDetector/VadGate/Transcriber/Synthesizer/AudioIO), so tests inject fakes and drive the loop with no hardware. It runs best in the user's audio session (foregroundgateway --platform voice), not a headless systemd user service;bootstrap.sh --voiceinstalls the deps and downloads the models (openWakeWord into the venv's package dir under.runtime/venv, the Piper voice into.runtime/voice/tts, the faster-whisper model into the.runtime/hfcache). - Scheduler glue (
gateway/service.py): inbound text →Scheduler.submit_request(text, source=f"{platform}:{chat_id}"); the returned request id maps to the(platform, chat)(owners), andScheduler.on_request_requeued(a scheduler hook, defaultNone) copies that ownership across an updated request so its completion still routes home. Aneeds_inputpause setspending_ownerfrom the pending run's source; the same chat's next message goes straight toScheduler.answer(no queue/navigation). The answer-side entry points (answer,answer_question,resolve_repair,answer_approval) are guarded likesubmit_request: anEngineUnavailableis fatal-and-reported and any other error returns a reply, so a resume/repair failure never propagates into a front end. A different chat — including a chat on another platform — during that pause is told to wait: the single-slot scheduler must not silently abandon the first chat's run, and one service fronts all adapters so the guard spans them. A background poll drainsScheduler.drain_outbox()(replies a background path buffered — the codegen worker's post-authoring re-run, a repair retry — so an off-gate completion still reaches its chat) thenScheduler.run_queue()(routing each[run_id] summaryto its owner) and surfaces newly posted authoring questions / repair offers (defer_questions = True; the service routes them byrun_id→(platform, chat), falling back to that platform'shome_channel); a chat's plain reply answers the question or picks the repair action (retry/repair/ask/no). The approval/repair vocabulary is matched case- and punctuation-insensitively (_normalize_action), with a first-word fallback: speech-to-text emits "Approve." / "Yes." / "retry.", and an exact lookup silently dropped those intosubmit_request, so the approval timed out and nothing was created. - Optional result cleanup (
gateway/humanize.py): a gateway-only presentation layer that rewrites a completed skill's result line from the scheduler's deterministic<skill>: <ok|failed> — <action_log>into one grounded, friendly sentence. It is generation, never a decision — the success/failure verdict and routing are already settled by SemIf and the runner, and the rewrite is never fed back into assessment, tracing, or the decision log (the runner and REPL keep the raw deterministic summary). The prompt forbids adding/inferring/dropping facts, andHumanizer.humanizealways falls back to the original text on any error, timeout, empty reply, or runaway length, so a cleanup failure never swallows a real result. It reuses the scheduler'sllmclient (endpoint/model/sampler configured once) with a short per-calltimeout(a new optionalchat()argument) so a slow cleanup cannot hold the gateway poll loop for the authoring budget. Off by default:gateway.humanize(enabled/timeout/max_tokens/max_chars) sets the global default and a per-platformgateway.<platform>.humanizebool/{enabled}overrides it. A skill's own recorded config (data/skills/<category>/<name>/config.json->{"humanize": bool}) wins over both, so a skill whose result is already speakable (e.g.time.now) skips the rewrite while a mechanical one keeps it; the gateway reads the skill ref from the structuredSchedulerReply.skill_ref(the scheduler'srun_queue/submit_request/answercarryrun_id,skill_ref, and the unwrappedresultalongside the human-facingtext— no parsing it back out of the summary). Onlykind == "result"lines are touched (questions, repair/approval notices, and status chatter pass through); likeresult_only, an enabled platform unwraps the result detail before cleaning._resolve_platformsskips the reservedhumanizekey. - Gateway isolation (non-negotiable). The gateway exists only to take
commands and send replies. It MUST NOT read a contact's history, show/create
invite links, or compose messages on the user's behalf: no
observer, no inbound buffering/pull mode, no/address, no/inbox, no/send. Those are messaging-UX concerns and live in the standalone bridges (semif_agent.bridges) against their own daemons/profiles. Letting them bleed into the always-connected command bot enlarges its attack surface for nothing. If you are tempted to add read/send/address functionality togateway/, add a bridge instead. - Neutral SimpleX transport (
semif_agent/simplex_ws.py): the wire protocol both front ends share — parsing a direct text item across the v7 wire shapes, the structured/_send,/_accept, and the corrId→Future round-trip used by/_show_address//_address(SimplexDaemon.request_address, thread-safe viarun_coroutine_threadsafe). It carries no policy: no allowlist, no scheduler, no HTTP. - Tests.
tests/test_gateway.py(stdlib): SimpleX adapter allowlist/auth, structured send command, batching (realasyncio), LXMF adapter allowlist/auth and batching (athreading.Timer), LXMF voice-message transcription through an injected fake transcriber (Opus dispatch, Codec2 decode/wrap via a stubbeddecode_codec2, disabled-ignores, unsupported-codec, missing-Codec2-decoder and failure notices, caption fallback) and LXMF voice replies through an injected fake synthesizer (voice-chat marking, text-reverts,reply_with_voiceoff, synthesis-failure fallback, length bound), cross-platform pending-run guard and per-platform reply routing, andGatewayServicerouting against a realScheduler(lazy engine, unreachable LLM).tests/test_humanize.pycovers the optional result cleanup with an injected fakellmclient (rewrite, quote/whitespace normalization, fallback on error/empty/runaway, disabled passthrough, and the global + per-platform gateway enable/disable wiring).tests/test_lxmf_transport.pycovers the neutral LXMF transport's missing-dep contract, default paths, andnormalize_message(including theFIELD_AUDIO/AM_*voice payload viaparse_audio_field; no reallxmfneeded).tests/test_simplex_ws.pycovers the neutral protocol layer (parse shapes, accept ids, corrId round-trips, address show/create).tests/test_bridges.pycovers what stays in the core: the shared LLM bridge (over a real loopback server) and the discovery registry (known_infos/describe_bridges/derived_config_vars).tests/test_packs.pyhermetically tests everypacks/<name>/skills/<category>/<leaf>/package, includingsimplex.next_message,simplex.send_message, andsimplex.connect_link, and runs every pack's bridge test (packs/<name>/bridge/test_<bridge>_bridge.py: the SimpleX bridge over a real loopback server — peek/pop, recipient resolution, outbound routing, token/body validation,/addresssuccess/503/502, daemon close on stop — and the Nextcloud/Outlook/Browser bridges over a loopbackhttp.serverwith a fake service or driver).tests/test_voice_gateway.pydrives the voice loop with injected fake engines (wake gating, endpointing, half-duplex and barge-in — wake-abort, mute, stop/new-command classification,speaktruncation/failure, adapter + CLI wiring) plus the transcribe-only helpers (check_codec2_requirements,decode_codec2over an injected fakepycodec2,pcm_to_wav) and the voice-reply helpers (check_synthesis_requirements,build_synthesizerover a stubbedPiperSynthesizer,pcm_to_opus_ogg's empty-input contract and, when PyAV is importable, its OGG/Opus round-trip) — no hardware, network, or heavy packages.tests/test_voice_record.pycovers the recording helpers (semif_agent/voice_train.py) — prompt loading, WAV I/O, level math, the silence-endpointing loop, and the LJSpeech dataset writer — with a scripted fake audio source. The livewebsocketstransport against a real daemon, the live LXMF transport against a real Reticulum network, and the live voice pipeline against a real microphone are live-integration concerns. - Deps.
websocketsandlxmf/rnsare pinned inrequirements/transports.txt(staging only); both are lazy-imported and the core stays stdlib-only. The voice stack is pinned separately inrequirements/voice.txt(hardware-dependent:sounddevice,openwakeword,faster-whisper,piper-tts,onnxruntime,webrtcvad-wheels, plus the systemlibportaudio2+alsa-utils); it is lazy-imported too, andbootstrap.sh --voiceinstalls it and downloads the models (openWakeWord into the venv package dir, the Piper voice into.runtime/voice/tts, faster-whisper into.runtime/hf). The LXMF gateway's transcribe-only and voice-reply paths pin only what they need (requirements/transcribe.txtfaster-whisper;requirements/tts.txtpiper-tts+ PyAV;requirements/codec2.txtpycodec2), never the microphone stack.
skill packs (bundles)
- The contract.
PACKGEN.mdis the authoritative spec for a new pack —pack.json, itsconfigschema, its bridge reference, and how to author a new bridge to back one. It is the sibling ofCODEGEN.md/TESTGEN.md; read it before adding a pack (each pack is its own repository). - What they are. A pack bundles a concern/product with the skills that serve
it, in
packs/<name>/: apack.jsonmanifest plusskills/<category>/<leaf>/folders (the exact generated-skill format). Each pack is its own repository (pack.<name>, listed in thesemif-packspack-index repo), cloned byscripts/bootstrap.shinto the gitignoredpacks/<name>/. The manifest binds the pieces that used to be scattered by convention:concern/title,categories(id -> scope description, feedingCATEGORY_DESCRIPTIONS),bridges(names the pack ships underbridge/and talks to; the core registry discovers them by convention),requires(optional deps likeplaywright),enabled_by_default, and aconfigschema.semif_agent/packs.pydiscovers them (PackRegistry, which scans theskill_packsroots for*/pack.json; a root with no manifest is one implicit pack, so a plain skills directory works) andmerge_packsloads every enabled pack at startup. - Deps are pack-owned. A pack ships the python deps its skills/bridge need at
packs/<name>/requirements.txt(pip format, pinned) — never in the agent repo'srequirements/.SkillPack.requirements_fileresolves it; the install plan lists the selected/enabled packs that ship one (setup.build_plan/plan_from_config->pack_requirements), andscripts/bootstrap.shpip-installs each into.runtime/venv(so a host that never enables a pack installs nothing for it). Heavy deps are lazy-imported and a missing one is a per-call503, never a crash. SeePACKGEN.md, "Pack python deps". - Enable is one switch.
pack_enabledresolves: an explicitpacks.<name>.enabled, else a bridge pack follows itsbridges.<bridge>.enabled, elseenabled_by_default. Disabling a pack drops its categories entirely (including any generated body authored into one) and stops its bridge — a host never offers a skill whose bridge is off. The switch lives in the pack'sconfig/packs/<name>.jsonfragment. - Config is pack-owned. A pack's
configschema (key ->type/default/doc/secret) owns its defaults and drives bothconfig.example.jsongeneration andcheck-configvalidation. Bridge packs map the schema ontobridges.<name>; a bridge-less pack (e.g.essentials) maps ontopacks.<name>. Shared, skill-less bridges (the LLM bridge) live insemif_agent/config.pySHARED_BRIDGE_SCHEMA. - Shipped packs.
nextcloud,simplex,outlook,browser(each owning its bridge),gutendex(Project Gutenberg book catalog + full-text download; no bridge) andessentials(the built-in local utilitiestime+calculator+skills; no bridge) — each in its own repository. Adding a concern means adding a pack repo, not editingskills.py.
bridges (third-party API services)
- What they are. A bridge service is a standalone process that stands up a
simple, secure localhost HTTP layer in front of one third-party system,
warranted when the system needs state (especially auth state), a native or
heavy protocol, or one sanitized surface; a system with a plain HTTP API needs
no bridge — its skill calls the API directly. When a bridge fronts a service, a
codegen-authored skill body calls the bridge and never speaks that system's
native protocol.
A bridge ships with its pack: the pack declares it in
bridgesand shipspacks/<name>/bridge/<name>.py(+bridge/__init__.pyand any sibling client module); the core registry imports it by convention — there is no coreCATALOGto edit. The one shared, pack-less bridge is the LLM bridge, whoseconfigblock lives in the coreSHARED_BRIDGE_SCHEMA(seesemif_agent/packs.py). The catalog (BridgeInfo: name, service, description, URL config var, other config vars with one-line docs, auth header + token config var, and endpoints with request/response/error shapes) is injected into every codegen prompt (body/retry/regen/testgen) viadescribe_bridges()and is the single source of bridge specifics — CODEGEN.md/TESTGEN.md carry only the generic pattern. The bridge's optional shared secret is mirrored to the top-levelsimplex_bridge_tokenconfig var (bootstrap syncs it) so bodies can send theX-Semif-Tokenheader. - Run mode.
python -m semif_agent.cli bridge [--name simplex]builds the scheduler (engine lazy, used only for trace) and runs the selected + enabled bridges until interrupted. Each bridge owns its service daemon:SimplexBridgeconnects to a second simplex-chat daemon/profile (bridges.simplex.ws_url, default port 5228, pinningsimplex_chat.forward_port), separate from the command gateway's. On a bootstrap-provisioned host,scripts/bootstrap.shrenders and enablessemif-simplex-forward.service(the second daemon) andsemif-bridge.service(cli bridge) alongside the gateway units. - HTTP surface (
bridges/base.py+packs/simplex/bridge/simplex.py): JSON in/out, localhost-bound, optional shared-secretX-Semif-Tokenheader.SimplexBridgebuffers every inbound DM (no allowlist — the user wants to see who reached the bot through its invite link) in a boundedMessagingInboxthat owns the read cursor (each buffered entry keeps the daemonitem_idso a consumer can consume exactly that item), and servesGET /health,GET /contacts(the daemon's contact list, refreshed on (re)connect and on demand — best-effort, falling back to the cached/inbound-learned set when the daemon is unavailable),GET /inbox(peek),GET /inbox/next?contact=<id>(pop oldest),GET /unread(the daemon's persistent unread chats via/_get chats+ChatListQueryunread filter —chatStats{unreadCount, minUnreadItemId}plus each previewedmeta.itemStatus),GET /history?contact=<id>&count=<n>(recent messages for one chat via/_get chat @<id>),GET /address(show/create the forwarding bot's contact link; 503 when the daemon is not connected, 502 when the lookup fails),POST /send{"recipient","text"}(resolves a numeric id or a known display name — refreshing the daemon contact list once on a miss — and enqueues on the bridge's own daemon), andPOST /read{"contact","item_ids"}(marks exactly the listed received items read on the daemon via/_read chat items @<id> <ids>, so they leave its persistent unread state;okonly when the daemon accepted it)./unreadand/historyread the daemon's own state (surviving bridge restarts), unlike the live/inboxbuffer;/readis a real local write on the bridge's own profile (v7/_read chatupdates the localitem_statusonly; no wire read receipt). - Skill-facing config. A body calls a bridge at the address derived from that
bridge's own
bridges.<name>block (host/port/token) — thesimplex_bridge_url/llm_bridge_url/nextcloud_bridge_urlvar (+_token) is injected intoctx.configbybuild_schedulerviabridges.registry.derived_config_vars, so there is no duplicate top-level key to keep in sync and the data-contract config search finds it and auto-populates the skill config. Skills reach a bridge with the ordinaryhttptransport, so their hermetic tests are loopback HTTP like any other HTTP body.simplex.next_message,simplex.send_message, andsimplex.connect_linkare the pack skills. - LLM bridge (
bridges/llm.py). A genericPOST /chat{"messages": [{"role","content"}, ...], "max_tokens"?: int}->{"text": "<model reply>"}(plusGET /health,400bad body,502model error) in front of the agent's language model, so a body can ask for short generated text over HTTP instead of speaking the OpenAI-compatible protocol itself. It does not own the model connection:run_bridgepasses the scheduler's already-configuredllmclient throughrun_bridges/from_configintoLLMBridge, so the endpoint/model/sampler stay configured once in the top-levelllmblock; thebridges.llmblock carries only the local listener (enabled/host/port/token). Bodies reach it via the derivedllm_bridge_url(+ optionalllm_bridge_token). It runs inside the existingsemif-bridge.serviceprocess (all enabled bridges start together); with no client it reports502, never a fabricated reply.nextcloud.create_eventis the first consumer (title + description extraction, cached inrequest.metaacross aneeds_inputresume). - Nextcloud bridge (
packs/nextcloud/bridge/nextcloud.py+nextcloud_client.py). Wraps the account's native protocols — WebDAV files, CalDAV calendar events and tasks (VTODO), CardDAV contacts, and the OCS Notes API — behind one uniform JSON surface, so a body never speaks DAV/OCS directly. It has no service daemon (Nextcloud is plain HTTPS) and is stdlib-only (urllib+xml.etreessl), socheck_requirementsis always(True, None)and it starts instantly inside the existingsemif-bridge.service. HTTP Basic auth uses the username + app password. The connection is configured inbridges.nextcloud(url/username/app_password, plusdefault_calendar/default_addressbookandverify_tls/timeout);NextcloudBridge.from_configalso accepts the top-levelnextcloud_url/nextcloud_username/nextcloud_app_password/nextcloud_default_calendar/nextcloud_default_addressbookas a fallback for a hand-edited config, with a block value winning. Bodies reach it via the derivednextcloud_bridge_url(+ optionalnextcloud_bridge_token); theBridgeInfodeclares only those two config vars.GET /calendarsalso returnsdefault(the configured default calendar name), so a body can reproduce the strong-winner/else-default rule; with a bounded window,GET /calendars/eventsexpands recurrences server-side. Routes (readsGET, mutationsPOST): files (/files,/files/stat,/files/readtext-or-base64,/files/search,/files/write|mkdir|delete|move|copy), calendars (/calendarswith each collection'ssupported-calendar-component-setascomponents,/tasklistsfor VTODO-capable task lists,/calendars/eventslist,POST /calendars/events+/update+/delete), tasks (/taskslist,POST /tasks+/update+/complete+/delete; task routes only target a VTODO-capable calendar and reject an event-only one), contacts (/addressbooks,/contactslist/search,POST /contacts+/update+/delete), notes (/notes,/notes/get,POST /notes+/update+/delete), and/user+/capabilities(OCS). A missing connection is503; a real failure (NextcloudError— transport, HTTP error, or bad reply) is502, never a fabricated success. Event/task updates edit the stored iCalendar properties in place (preserving VALARM/ ATTENDEE), guarded byIf-Match; creates useIf-None-Match: *. Calendar/ addressbook defaults resolve from config when a request names none and the account has several.packs/nextcloud/bridge/test_nextcloud_bridge.pydrives the real client over a loopbackhttp.serverfaking Nextcloud's DAV/OCS shapes.
- Outlook bridge (
packs/outlook/bridge/outlook.py+outlook_client.py). Wraps the user's Microsoft account — Outlook / Microsoft 365 mail, calendar events, Microsoft To Do tasks, contacts, and OneDrive files — behind one uniform JSON surface over Microsoft Graph, so a body never speaks Graph or OAuth directly. Like Nextcloud it has no service daemon (Graph is plain HTTPS) and is stdlib-only (urllib+json+ssl+base64), socheck_requirementsis always(True, None)and it starts instantly insidesemif-bridge.service. Authorization is the OAuth2 device code flow (a public client, no secret):packs/outlook/scripts/outlook-auth.pyruns it once and stores the access + refresh tokens 0600 under the checkout's.runtime/outlook/token.json(override withbridges.outlook.token_path); the client refreshes on expiry/401. The bridge starts without a token — an unauthenticated route returns503telling the operator to run the helper (OutlookAuthRequired), a real Graph failure is502(OutlookError), and a missingclient_idis503. The connection is configured inbridges.outlook(client_id,tenantdefaultcommon,default_calendar/default_task_list/default_mail_folder/default_timezone,verify_tls/timeout); it also acceptsgraph/loginbase URLs (a test seam/defaulting to the real hosts). Bodies reach it via the derivedoutlook_bridge_url(+ optionaloutlook_bridge_token). Routes (readsGET, mutationsPOST):/user, mail (/mail/folders,/mail/messageslist +/mail/messages/get,POST /mail/sendimmediate +/mail/draft), calendar (/calendars,/calendars/eventsviacalendarViewso recurrences expand,POST /calendars/events+/update+/delete), To Do (/tasklists,/tasks,POST /tasks+/update+/complete+/delete), contacts (/contactssearch), and OneDrive (/fileslist,/files/readtext-or-base64,POST /files/write). Graph's@odata.nextLinkpaging and429/Retry-Afterbackoff are handled in the client.packs/outlook/bridge/test_outlook_bridge.pydrives the real client over a loopbackhttp.serverfaking the token endpoint and Graph shapes. - Browser bridge (
packs/browser/bridge/browser.py+browser_client.py). Real browser automation via Playwright — open a URL, read a page's text or links, take a screenshot, and click/fill/press/select to complete a flow — behind one uniform JSON surface, so a body never bundles a browser stack. It is the first bridge with a heavy optional dependency, so it is disabled by default and installed withscripts/bootstrap.sh --browser(packs/browser/requirements.txtpins Playwright — the pack owns its deps; the Chromium binary is downloaded into the checkout's.runtime/browser, and the bridge setsPLAYWRIGHT_BROWSERS_PATHthere at launch). Unlike Nextcloud/Outlook it owns a browser and keeps a persistent profile (.runtime/browser/profile), so a login done once survives across calls and restarts — the browser analog of the SimpleX bridge owning its own daemon (POST /resetwithpurge=truewipes it, andheadless:falseshows the window so the operator can sign in).check_requirements()deliberately always returns ok:run_bridges()aborts all bridges when one's requirements fail and this dependency is optional, so a missing Playwright/browser must be a per-call503(with an install hint), never take down simplex/llm/nextcloud. Install isscripts/bootstrap.sh --browser; whenplaywright installfails (notably on a host with an IPv6 address but no global IPv6 route — Playwright's downloader forcesautoSelectFamily+ a dual-stack resolver that prefers IPv6 and hangs instead of falling back to IPv4), bootstrap falls back topacks/browser/scripts/playwright-browsers.py, which fetches the same pinned artifacts over IPv4 and lays them out where Playwright expects.bridges.browser.channel/executable_pathinstead launch an already-installed browser (a Playwright channel likechrome/msedge, or a specific binary) and skip the managed download entirely. Playwright's sync API is bound to its creating thread and the bridge serves each request on a new one, so the driver runs the async API on one dedicated event-loop thread and serializes whole operations behind anasyncio.Lock, submitting coroutines withrun_coroutine_threadsafe. A real navigation/timeout/selector failure is a502(BrowserError), a missing package/browser a503(BrowserUnavailable), bad input a400— never a fabricated success. Routes (readsGET, mutationsPOST):/health,/state,/content(text|html, bounded),/text,/links,/screenshot(full_page/selector/inline, saved under.runtime/browser/screenshots),/goto,/click(selector or visible text),/fill,/press,/select,/wait,/back,/forward,/reset. Bodies reach it via the derivedbrowser_bridge_url(+ optionalbrowser_bridge_token). Threepacks/browser/skills/browser/*skills ship (open_page,read_page,screenshot).packs/browser/bridge/test_browser_bridge.pyexercises the routes over a loopback HTTP server with an injected fake driver (no browser, no Playwright needed).
Bridge backlog (one session per item)
The bridge read path (simplex.next_message), outbound send
(simplex.send_message), and contact-link lookup (simplex.connect_link) are
covered. Deferred follow-ups:
- 1. Contact-list refresh from the daemon (
packs/simplex/bridge/simplex.py,simplex_ws.py). Shipped:SimplexDaemon.contacts()/request_contacts()query/_contacts <userId>(active user from/user→activeUser.userId, cached, falling back to the configureduser_id) over the existing corrId→Future path;SimplexBridgemerges the result into the inbox on (re)connect via anon_connectedhook and on demand (GET /contacts, and a send-resolution miss), so/sendcan address a contact it has never received from. Best-effort: a disconnected daemon keeps the cached set. - 2. Message history + true unread (
packs/simplex/bridge/simplex.py,simplex_ws.py). Shipped:SimplexDaemon.chats(unread_only, count)/request_chats()query/_get chats <userId> count=<n> {"type":"filters","favorite":false,"unread":true}and parseapiChats(AChat.chatStats{unreadCount, minUnreadItemId, unreadChat}+chatItem.meta.itemStatusrcvNew/rcvRead);chat_history(contact_id, count)/request_chat_history()query/_get chat @<id> count=<n>and parseapiChat.SimplexBridgeexposesGET /unread(persistent unread chats, summaries + previewed messages) andGET /history?contact=<id>&count=<n>(recent messages with per-item status), degrading like/address(503 not connected / 502 lookup failure;/history400 without a contact), plusPOST /read{"contact","item_ids"}which marks exactly the listed items read on the daemon (/_read chat items @<id> <ids>), so a reported message is consumed and not re-reported. The live/inboxbuffer is unchanged. (The pinned v7.0.3 does have/_read chat @<id>,/_read chat items @<id> <ids>, and/_read user <uid>; an earlier note claiming v7 had no mark-read command was wrong.) - 3.
simplex.send_messagepack skill (packs/simplex/skills/simplex/send_message/). The outbound counterpart tosimplex.next_message: resolves the recipient with a SemIf sub-decision over the bridge's/contacts(falling back to the configured default contact), writes the message from the request or the LLM bridge when no literal text is given, sends viaPOST /send, and reports the bridge'scontact_id/ errors honestly. - 4. LLM bridge (
bridges/llm.py). Shipped:LLMBridgeexposes a genericPOST /chatin front of the scheduler's configuredllmclient (threaded throughrun_bridges/from_config, never re-configured), the one shared core built-in, seeded underbridges.llm(its URL is derived from that block).nextcloud.create_eventextracts its title + description through it. - 5. More bridges. Each new third-party API gets its own pack
(
packs/<name>/bridge/<name>.py) + config block; the core registry discovers it by convention and the codegen prompts pick it up automatically throughdescribe_bridges(). Nextcloud shipped (packs/nextcloud/bridge/nextcloud.py+nextcloud_client.py): files/calendars/tasks/contacts/notes over one JSON surface, no daemon, connection frombridges.nextcloudwith a top-levelnextcloud_*fallback. Future bridges follow the same shape. - 6. Outlook / Microsoft Graph bridge (
packs/outlook/bridge/outlook.py+outlook_client.py). Shipped: theOutlookBridgeexposes mail, calendar, Microsoft To Do, contacts, and OneDrive over one JSON surface in front of Graph; OAuth2 device-code + refresh (packs/outlook/scripts/outlook-auth.py, tokens under.runtime/outlook/token.json); sevenpacks/outlook/skills/outlook/*skills (next_message,send_messageconfirm-gated,next_event,create_event,create_task,list_contacts,list_files). Deferred: writing/reusing Outlook app-registration guidance in the docs, and a mail-send seed that attaches files. - 7. Browser bridge (Playwright) (
packs/browser/bridge/browser.py+browser_client.py). Shipped:BrowserBridgeexposes open/read (text/links/screenshot) and act (goto/click/fill/press/select/wait/back/ forward/reset) over one JSON surface in front of a real Playwright browser with a persistent profile; optional heavy dep installed via the pack's ownpacks/browser/requirements.txt+bootstrap.sh --browser, lazy so a missing browser is a per-call 503 and never aborts the other bridges; the async API runs on one dedicated event-loop thread. Threepacks/browser/skills/browser/*skills (open_page,read_page,screenshot). Deferred: arbitrary JSevaluate, file upload/download, multiple tabs/contexts, and a per-URL allowlist.
Code principles
- Contain installation artifacts in the repo. Everything a machine installs
to run the agent (python venv, SemIf engine clone, GGUF, HF cache, the
simplex-chat binary/profile, rendered systemd units) lives inside the checkout
under a gitignored
.runtime/tree — never scattered across$HOME. An end user must be able to find and debug the whole stack with as few steps as possible. Only artifacts that operationally cannot live there are outside (~/.ssh/id_ed25519; the real systemd user dir + linger, which the repo units are symlinked into).scripts/bootstrap.showns this layout; derive paths from the checkout, never hardcode$HOME. - No mocking. The decision engine is always real SemIf. Pure unit tests
touch data-structure math only (queue ordering, dream cost, contract
serialization) or drive scheduling mechanics through the
ScriptedEnginedouble intests/conftest.py; decisions themselves are verified by 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.appendlabels a row with the selected option by default (self-consistent, near-zero cost). Real labels come fromrelabel(human, weight 3x indream) — failures alone don't produce correct labels.- Navigation decisions ARE logged (
navigate:category,navigate:leafin skills.py) and therefore count toward dream cost. This is intended per the design; don't silently drop them. - Queue ordering: strict FIFO (arrival order). There is no urgency score and no preemption; the running process always finishes before the next queued request is dispatched.
- The decision engine is always real and every
EngineUnavailableis fatal:submitrecords it (("fatal", ...)), the scheduler exposesfatal, and the CLI prints it and exits non-zero. There is no degraded/soft-error path. - Keep deps stdlib-only in the core; heavy deps live on the staging venv
(
.runtime/venv, provisioned byscripts/bootstrap.sh).
Testing
python3 -m pytest tests/ -q --ignore=tests/integration— anywhere, fast. Includes the dashboard API tests (tests/test_dashboard_api.py), which spin up the stdlib HTTP server on an ephemeral port with the engine never loaded;tests/test_codegen.pyfor prompt/parse/validate, integration extraction/findings, and body store round-trips;tests/test_housekeeping.pyfor the housekeeping operations (name resolution, store/registry deletion, tombstones, the lock gate, cancel/regen, and the meta-skill act flows); andtests/test_llm.pyfor the_parse_jsonhelper and the LLMClient provider.tests/conftest.py``sScriptedEngine` drives scheduling mechanics (assessment is now a SemIf decision) without a GGUF.tests/test_no_env_leaks.pyguards 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 gitignoredlocal/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
codegen client) use real local endpoints (a loopback
http.server, never a mock); skill bodies must call the user's configured service, never a fixture address. Passing a skill test proves mechanics only; a real run proves the integration.