Consolidate the calendar and productivity_management seed categories into one nextcloud category: create_event/next_event move from calendar, and create_nextcloud_task becomes create_task (dropping the redundant prefix). Replace the two CATEGORY_DESCRIPTIONS entries with a single nextcloud description and update every reference across the repo (docs, bridge comments, tests, navigation tuning labels, seed docstrings).
103 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 asks the user a few questions about what they want and how it should connect, generates a new skill, and then does it.
- 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)
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
(`creation_approval`, off by default) 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: elicitation ->
codegen body (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; elicitation asks implementation questions one at a
time (all front ends defer via the question queue, `answer_timeout`
per question); a
failed real run triggers a logged SemIf repair choice
(retry/repair_skill/ask_user/no_repair) surfaced to the user;
housekeeping meta skills (delete/clear-config/regen/cancel-build)
operate on the tree via `ctx.admin`; per-category new-skill locks
(`locks.new_skill` in the category config) gate creation, with
`housekeeping`/`response` hard-locked 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 actionability guard runs first, at the top of navigation,
to arbitrate the response/create boundary), 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_seed_store loads committed starter skills from seeds/ with
their recorded config read from data/skills/;
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
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` success/failure at
tau; on failure `assess:requeue` complete/retry) 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 resolved inputs (secrets redacted); a `DETERMINISTIC_CATEGORIES`
run (housekeeping) skips assessment/repair — it is an internal
mechanical action with a known result, not an external run;
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
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.
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)
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,
elicitation, 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
elicitation integration hint rides on every body/retry/regen
prompt; elicitation questions
+ integration hint; 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 /
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. 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 (SimpleX, the LLM bridge,
and Nextcloud). base.py:
BridgeInfo + BridgeService (shared localhost JSON HTTP layer,
`X-Semif-Token` guard). inbox.py: MessagingInbox (bounded FIFO +
contacts learned from inbound DMs and the daemon contact list,
bridge-owned read cursor). 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.
llm.py: LLMBridge — a generic `POST /chat` in front of the
scheduler's configured `llm` client (reused, not re-configured),
so bodies get short generated text (e.g. an event title +
description) over HTTP.
nextcloud.py + nextcloud_client.py: NextcloudBridge — files
(WebDAV), calendar events + tasks (CalDAV), contacts (CardDAV),
and Notes (OCS) behind one JSON surface, so bodies never speak
DAV/OCS; no service daemon (stdlib-only), connection from
`bridges.nextcloud` with a fallback to the top-level
`nextcloud_*` values the nextcloud seeds use.
outlook.py + outlook_client.py: OutlookBridge — the user's
Microsoft account (Outlook / Microsoft 365) over Microsoft Graph:
mail, calendar events, Microsoft To Do tasks, contacts, and
OneDrive files, plus the OAuth2 device-code + refresh flow. No
daemon (stdlib-only `urllib`); tokens stored under
`.runtime/outlook/token.json` and seeded once with
`scripts/outlook-auth.py`; connection from `bridges.outlook`.
registry.py: CATALOG, describe_bridges() (catalog injected
into the codegen prompts), run_bridges() (threads the scheduler's
`llm` client into the LLM bridge). 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, 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
(capture discarded while speaking) with a follow-up window so a
reply can be answered without the wake word. 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.jsonis gitignored, per-machine, and required (hosts use different LLM/codegen endpoints and models).scripts/bootstrap.shseeds it fromconfig.example.jsononce (only when absent) and nothing writes it afterwards — only a human editsconfig.json.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) 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. 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. 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). 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. - Optional human approval on creation (Oct 2026):
creation_approval(top-level, defaultfalse) is a single boolean. When on, 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.elicitation.wait_timeout. With no deferring front end it denies immediately rather than stalling the worker. Traced ascreation_approval_requested/_approved/_denied/_timeout/_skipped; it is a human veto, not a decision row — the SemIf create doors still make and log the routing decision. - Housekeeping meta skills + per-category new-skill locks (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,/lock) and dashboard endpoints/buttons. Their runs are deterministic internal actions:DETERMINISTIC_CATEGORIESskipsassess:outcome/repair, and the category is hard-locked from authoring. Every category carries a new-skill lock in its category config (data/skills/<category>/config.json→{"locks": {"new_skill": bool}}); the lock is a deterministic boolean gate (Scheduler._category_locked) checked in_dispatch,_dispatch_skill,_author_skill, andrestart_skill, and toggled from the config file orScheduler.set_category_lock(/lock,/api/lock).housekeepingand the closedresponsetree are hard-locked in code (HARD_LOCKED_CATEGORIES/CANNED_CATEGORIES) and can never be unlocked. The lock is creation-only: existing skills still run and repair/regen of an existing leaf is allowed. - Real integrations, implementation questions, fidelity + repair (Sep 2026):
elicitation is on by default and asks implementation questions (which
service/account, how to connect, where the credential comes from, what success
looks like); every front end defers via the question queue
(
/api/questions, worker waitscodegen.elicitation.answer_timeoutper question, one at a time). 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) plus static declaration checks regenerates a simulated body once with the raw evidence bundle, then accepts it badgedunverified. A failed real run logs a SemIf repair choice (retry / repair_skill / ask_user / no_repair) surfaced in REPL/dashboard; repair writes carry the raw observed-failure bundle 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)". - 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). Half-duplex: capture is discarded while a reply is speaking (no barge-in yet); after each reply afollow_up_window_saccepts the next utterance without the wake word. 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)". - 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).cli.build_enginepicks the class;SemIfEngine/WinnowEngineboth satisfyengine.DecisionEngine(call/warm/loaded/generate). - The engine is always real and every
EngineUnavailableis fatal, whichever provider is selected:WinnowEngineconverts 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 Winnow'schoicequestion type (options->criteriaid->description,question->instructions); the returned distribution is validated against exactly the requested option ids and normalized.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--ctx-size); a state that overflows is a fatalEngineUnavailable, the same class as the local token limit.
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 committed manifestrequirements/staging.txtis the single source of truth:pip install -e <semif-clone> --no-deps, thenCMAKE_BUILD_PARALLEL_LEVEL=6 MAKEFLAGS=-j6 pip install -r requirements/staging.txt(numpy 2.3.5, transformers 5.17.0, tokenizers 0.23.2, huggingface-hub 1.31.0, llama-cpp-python 0.3.35, pytest). 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. - 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.
ollama
bootstrap.shinstalls no ollama: it expects the target host to already run one forllm(and pullsllm.modelinto it), whilecodegenmay be remote. Point--llm-url/--codegen-urlat the right daemons.- If generation hangs with no log output, restart the ollama service — the GPU runner can wedge.
- A local reasoning model needs thinking off for
llm. A reasoning model emits hidden chain-of-thought and puts the answer incontent. Through the/v1compat endpoint the CoT consumes the entire reply budget, sogenerate_category/generate_skill'smax_tokens=128returnsfinish_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. With noconfig.jsonyet it seeds one fromconfig.example.json; edit that to setllm.model/codegen.modeland the endpoints. Flags (--llm-url,--codegen-url,--llm-model,--codegen-model) override the values read fromconfig.jsonfor that run only and are never written back.--voiceadditionally installs the optional voice-gateway stack (requirements/voice.txt+ systemlibportaudio2+alsa-utils) and downloads its models into.runtime/voice/viascripts/voice-models.py. The script must be run from a checkout — it reads pins from that checkout'spins.jsonand never re-clones the agent repo (only the SemIf engine and the simplex-chat binary). Idempotent and rerunnable; every stage no-ops on existing state, so it also boots an unknown-state machine. It installs no ollama:llmis the local ollama (bootstrap pullsllm.modelif configured),codegenmay point at a peer host. It WARNs (never auto-pulls) if the remote codegen host is missing its model, and WARNs ifllm.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,bin_url,sha256). Per-machinesimplex_chatports/display names stay inconfig.json. The python dep pins live inrequirements/staging.txt(committed, one versioned artifact — every host provisions from it). 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/staging.txt, rerun the script, re-run the integration tests. The script never guesses. - pip prints expected "dependency conflict" warnings at install time (semif-phase1 declares torch/accelerate/protobuf/sentencepiece/numpy 2.2.6 that we intentionally do not install — the llama.cpp CPU path doesn't need them; numpy 2.3.5 is deliberate, 2.2.6 has no cp314 wheel). Do not "fix" them by installing torch.
- Seeds
config.jsonfromconfig.example.json(only when absent) and never writes it again — only a human editsconfig.json.config.example.jsonships the provisioned defaults, so a seededconfig.jsonalready hascodegen.timeout: 3600, the SimpleX gateway enabled (gateway.simplex.enabled = true,ws_urlfromsimplex_chat.port) and the standalone forwarding bridge enabled (bridges.simplex.enabled = true,ws_urlfromsimplex_chat.forward_port) and the LLM bridge enabled (bridges.llm.enabled = true; it reuses thellmmodel); the operator setsllm.model/llm.base_urlandcodegen.model/codegen.base_url. Bootstrap renders/enables four user services:semif-simplex.service(the commandsimplex-chatbot daemon,--create-bot-display-nameonsimplex_chat.port),semif-gateway.service(.runtime/venv/bin/python -m semif_agent.cli gateway),semif-simplex-forward.service(the bridge's own daemon/profile onsimplex_chat.forward_port) andsemif-bridge.service(.runtime/venv/bin/python -m semif_agent.cli bridge). 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 runsscripts/simplex-address.pyto create/print the command bot's contact address (and the forwarding bot's, via--ws-url). - First run downloads the 2.8G GGUF and builds
llama-cpp-pythonfrom source (~10 min on 6 cores); 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. - 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 giveapi_key(literal) orapi_key_env(env var name — preferred).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. - Seed skills.
seeds/<category>/<name>/ships a real starter integration in the exact generated-skill folder format (skill.py,contract.json,skill.test.py, plusmanifest.jsonwith the description).merge_seed_storeloads them into every tree at startup; recorded config (credentials collected at first fire) is written to the runtime storedata/skills/, so the committed seed never holds secrets, and a generated body with the same name replaces the seed.nextcloud.create_eventis the authoritative worked example (CalDAV PUT; 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 (Nextcloud CalDAV, 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) andsimplex.connect_link(show/create the forwarding bot's contact link) are the messenger seeds;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 seeds derive "now" the same way, so a request time is parsed in the user's zone rather than the host's;tests/test_seed_skills.pykeeps them 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) → 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:
- elicitation (
generate_elicitation): implementation questions + integration hint. Every front end (REPL, dashboard, gateway) setsdefer_questionsand the worker posts them to the question queue one at a time, waitingcodegen.elicitation.answer_timeoutseconds for each (the clock resets on every answer submit; a timeout stops the sequence). - codegen body (
generate_skill_body/regenerate_skill_bodyon repair): CODEGEN.md + request + tree + requirements answers; 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) — is the action real or simulated/declared-but-unused? It only triggers a rewrite, never a diagnosis. One corrective regen with the raw evidence bundle (codegen.fidelity.max_attempts), 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). 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.
- 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:outcome/assess:requeuestate includes the resolved contract values (resolved inputs:block) so the decision sees the full query → resolution → action path; secret-named variables (pass/token/secret/key/credential/auth) are redacted to***so credentials never reach the decision log. - Requirements elicitation (implementation questions, default on).
codegen.elicitation.enabledasks the product owner how the new skill should connect (which service/account, how to connect, where the credential comes from, what success looks like, how failure should behave). Every front end defers — the single-slot worker posts questions toscheduler.questions(GET/POST /api/questions) one at a time and waits up tocodegen.elicitation.answer_timeoutseconds for each (the clock resets on every answer submit, so the next question is only shown after the current is answered; a timeout stops the sequence), then proceeds with whatever answers arrived (questions_timeouttrace). Answers ride on the draft into every body attempt (including retries and regens) and are persisted in the registry so arestartdoes not ask again. The prompt keeps an explicit anti-pattern block: never config-vs-input cadence questions ("should the sender address change?"), never operational data values, never trivia. - Fidelity gate. After the body lands,
authoring:fidelity— a real SemIf accept/reconsider decision (P(reconsider) >= 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 gate never diagnoses: it only triggers a rewrite, which is handed the raw evidence bundle as-is (request, description, requirements, raw INTEGRATION, findings, 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) and badgedunverifiedin the dashboard. A decision row is logged under phaseauthoring:fidelity. - 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 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 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 blocks in the mic loop. Half-duplex: capture frames are discarded while a reply is speaking, so the agent never transcribes itself (no barge-in yet); after a reply afollow_up_window_saccepts the next utterance without the wake word, so answering a question is conversational.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. 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). 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 callsScheduler.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). - 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), 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(no reallxmfneeded).tests/test_simplex_ws.pycovers the neutral protocol layer (parse shapes, accept ids, corrId round-trips, address show/create).tests/test_bridges.pyexercisesSimplexBridgeover a real loopback server (peek/pop, recipient resolution, outbound routing, token/body validation,/addresssuccess/503/502, daemon close on stop, catalog/describe_bridges()).tests/test_seed_skills.pyhermetically tests everyseeds/<category>/<name>/package, includingsimplex.next_messageandsimplex.connect_link.tests/test_voice_gateway.pydrives the voice loop with injected fake engines (wake gating, endpointing, half-duplex, follow-up window,speaktruncation/failure, adapter + CLI wiring) — 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/staging.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).
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 so a
codegen-authored skill body never speaks that system's native protocol.
SimpleX is the first; adding a service means adding a class to
bridges/registry.pyCATALOGand aconfig.example.jsonblock. 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/elicitation/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+bridges/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, 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; read-only),GET /history?contact=<id>&count=<n>(recent messages for one chat via/_get chat @<id>; read-only),GET /address(show/create the forwarding bot's contact link; 503 when the daemon is not connected, 502 when the lookup fails), andPOST /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)./unreadand/historyread the daemon's own state (surviving bridge restarts), unlike the live/inboxbuffer; both are read-only because v7 has no mark-read command (acking is a client-side 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_messageandsimplex.connect_linkare the seeds. - 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/build_bridgeintoLLMBridge, 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 (
bridges/nextcloud.py+bridges/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);build_bridgepasses the top-levelnextcloud_url/nextcloud_username/nextcloud_app_password/nextcloud_default_calendar/nextcloud_default_addressbookas a fallback, so the same account the nextcloud seeds collect is configured once and a block value wins. Bodies reach it via the derivednextcloud_bridge_url(+ optionalnextcloud_bridge_token); theBridgeInfodeclares only those two config vars. 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.tests/test_nextcloud_bridge.pydrives the real client over a loopbackhttp.serverfaking Nextcloud's DAV/OCS shapes.
- Outlook bridge (
bridges/outlook.py+bridges/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):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.tests/test_outlook_bridge.pydrives the real client over a loopbackhttp.serverfaking the token endpoint and Graph shapes.
Bridge backlog (one session per item)
The bridge read path (simplex.next_message) and contact-link lookup
(simplex.connect_link) are covered. Deferred follow-ups:
- 1. Contact-list refresh from the daemon (
bridges/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 (
bridges/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), both read-only and degrading like/address(503 not connected / 502 lookup failure;/history400 without a contact). The live/inboxbuffer is unchanged. Note: v7 has no mark-read command, so acking is via read receipts, not an API call. - 3.
simplex.send_messageseed (seeds/simplex/send_message/). The outbound counterpart tosimplex.next_message: resolve the recipient with a SemIf sub-decision over/contacts, send only on explicit user intent, and report 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/build_bridge, never re-configured), registered inCATALOGand 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
bridges/<name>.py- config block +
CATALOGentry; the codegen prompts pick it up automatically throughdescribe_bridges(). Nextcloud shipped (bridges/nextcloud.py+bridges/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.
- config block +
- 6. Outlook / Microsoft Graph bridge (
bridges/outlook.py+bridges/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 (scripts/outlook-auth.py, tokens under.runtime/outlook/token.json); sevenseeds/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.
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.