ZERG
Run AI agent swarms on your own machines — orchestration, identity, sandboxed workers, and full observability. Your prompts, completions, and data stay on your hardware.
One orchestrator (Sol), N worker nodes (Luna), an identity service (Mango), and an operations console (Limon). Bring your own model keys, run models locally with llama.cpp, or mix both. Air-gapped deployment is a supported arrangement.
Current platform: Erlang/OTP 29.1 workers on LuaJIT, provider_adapters=14 provider adapters with 8 circuit breakers, tools=92 registered tools, and event_types=102 event types. Counts on reference pages are machine-derived from the source tree.
Start here
| Path | What you get |
|---|---|
| Install WILDZERG | Provision the control plane and your first worker on hardware you own |
| First agent | Provider key → enrollment → task → result, with verification at each step |
| First swarm | Leader, teammates, directives, and the member mailbox |
| First workflow | A durable multi-step run with compensation |
| First MCP tool | Connect an MCP server and call it from an agent |
| Operate | Deploy, upgrade, back up, rotate keys, and respond to incidents |
| Build | HTTP API, CLI, ZMQ wire, Mango, and plugins |
| Reference | Configuration, API, CLI, tools, events, and RBAC |
Why operators choose ZERG
Self-hosted, not a cloud service. Deploy on your own Debian 13 machines.
Prompts and completions never leave your cluster unless you route them to an
external provider.
Production-grade Erlang/OTP. Supervision trees, event sourcing, and a
worker transport built for failure.
Multi-agent from day one. Background sub-agents, team swarms, scheduled
tasks, and multi-step workflows with compensation.
Bring your own inference. provider_adapters=14 provider adapters with
circuit breakers, or local llama.cpp lanes with provenance and rollback.
92 registered tools (74 built-in + 12 computer-use + 6
desktop-environment) plus MCP discovery, probe-conditional registration, and
the same permission/sandbox gates for every tool.
Observable by default. event_types=102 event types, Prometheus metrics,
Grafana dashboards, alert rules with runbook links, per-agent cost tracking,
and a tamper-evident audit chain.
Product variants
| Variant | What it is | Where |
|---|---|---|
| ZERG | Hosted control plane — invite-first, not launched | zergs.net |
| WILDZERG | The self-hosted, sovereign product (runit + podman) | wildzerg.com |
Documentation map
Evaluate — fit, architecture, security posture, limitations, support matrix. Start — install, first agent, first swarm, first workflow, first MCP tool. Operate — deployment, runbooks, backup/DR, upgrades, incidents, keys, tenancy. Concepts — workers, sessions, permissions, tools, workflows, teams, memory. Build — API, CLI, ZMQ wire, Mango, plugins. Reference — configuration, API, CLI, tools, events, RBAC, feature map. Contribute — local setup, tests, CI gates, docs style.
Version truth. This book documents the current release. Release history lives in Release history; wire compatibility lives in the version matrix.
Why ZERG
ZERG is a self-hosted platform for AI agent swarms. It is not a chatbot, and it is not a hosted API wrapper. It is the control plane, worker runtime, identity service, and operations surface you run on your own machines.
The problem it solves
A single agent loop is easy. Running many agents reliably is a distributed-systems problem:
Which worker executes which task, and what happens when it dies mid-task? How do you stop a compromised worker from reading another tenant’s work? How do you audit what an agent did, prove the log was not edited, and replay a session? How do you cap spend, rotate provider keys, and fail over when a provider degrades? How do you run all of this without sending prompts to a third party?
ZERG treats these as first-class contracts. The orchestrator (Sol) owns dispatch, ownership, budgets, workflows, and the event spine. Workers (Luna) own sandboxed execution. Mango owns identity and tokens. Limon is the ops console.
What you get
| Capability | What it means in practice |
|---|---|
| Owned execution | Every task is dispatched to a recorded executor and every result is ownership-checked. A worker cannot answer for a task it was not given. |
| Sandboxed workers | Three sandbox layers (bubblewrap, Landlock, seatbelt), six permission modes, and a deny-by-default tool policy. |
| Multi-agent coordination | Sub-agents, team swarms with signed directives, scheduled jobs, and workflows with compensation. |
| Provider freedom | 14 adapters, circuit breakers, fallback chains, local llama.cpp lanes, and model-cost accounting. |
| Durable event spine | 102 event types, projections with sequence guards, retention/compaction, replay, and a tamper-evident audit chain. |
| Operations truth | Prometheus metrics, 9 dashboards, 226 alert rules, backup/restore with checksum manifests, and upgrade/rollback drills. |
| Air-gap capability | No mandatory egress; local inference, local Mango, and signed release artifacts can be carried into the enclave. |
Fit and non-fit
A good fit if you:
Need agents to act on private code, data, or infrastructure. Want to use your own GPUs or your own provider contracts. Need an audit trail and deterministic operational boundaries. Are comfortable running a Linux service (Debian 13 + podman/runit) or using the WILDZERG blueprint.
Not a good fit if you:
Want a fully managed SaaS with no operational responsibilities (ZERG is not launched). Need shared-worker multi-tenancy today — ZERG is single-organization per Sol and single-tenant per worker (posture). Need OIDC/SAML SSO today — LDAP/GLAuth federation ships; OIDC/SAML is roadmap. Need a Windows server or a serverless deployment model.
Licensing and editions
ZERG is proprietary software. WILDZERG is the self-hosted arrangement; ZERG is the hosted arrangement (not launched). ZERGBASE is a separate MIT-licensed infrastructure panel. For licensing, evaluation bundles, and commercial terms, contact Spacebeam.
Next
Architecture — how the pieces fit. Security posture — what is enforced and what is not. Known limitations — the honest list. Install — get a control plane running.
Architecture
Banner: this page describes the current implementation shape. Every
key=valuecount is machine-rendered fromAGENTS.counts; design proposals and retired models live inplan/and must not be read as shipped behaviour.
ZERG is a production-grade agentic orchestration platform built on four pillars: Sol (Erlang/OTP server), Luna (LuaJIT agent), Mango (Python/Tornado auth), and Limon (TypeScript/Vue3 dashboard).
System Architecture
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Limon │ │ ZERG CLI │ │ API │
│ (Vue 3) │ │ (LuaJIT) │ │ Clients │
└──────┬──────┘ └──────┬──────┘ └──────┬──────┘
│ │ │
└───────────┬───────┴───────────────────┘
│ HTTP/SSE/WebSocket
┌───────────┴───────────┐
│ Sol Server │
│ (Erlang/OTP 29.1) │
│ ┌─────────────────┐ │
│ │ Cowboy HTTP │ │
│ │ 202 spec routes │ │
│ │ endpoints │ │
│ ├─────────────────┤ │
│ │ Event Store │ │
│ │ (Mnesia, 100 │ │
│ │ event types) │ │
│ ├─────────────────┤ │
│ │ Workflow Engine │ │
│ │ (gen_statem) │ │
│ ├─────────────────┤ │
│ │ ZMQ Gateway │ │
│ │ (chumak ROUTER) │ │
│ ├─────────────────┤ │
│ │ Plugin Bridge │ │
│ │ (Luerl, 16 │ │
│ │ modules) │ │
│ └─────────────────┘ │
└───────────┬───────────┘
│ ZMQ ROUTER/DEALER (chumak)
┌───────────┴───────────┐
│ Worker Boundary │
│ ┌─────┐ ┌─────┐ │
│ │Luna │ │Luna │ │
│ │ │ │ │ │
│ └─────┘ └─────┘ │
│ (LuaJIT, <10MB each) │
└───────────────────────┘
Component Details
Machine counts (, — renderer-maintained via
ci/render-docs-counts.py, do not hand-edit):
sol_modules=489 sol_lines=201310 event_types=102 provider_adapters=14
heir_owners=34 luna_modules=268 luna_lines=100104 tools=92
mango_modules=62 limon_files=253
Sol Server (Erlang/OTP 29.1)
sol_modules=489 modules, sol_lines=201310 lines of Erlang code
180 route tuples / 202 spec rows with SSE streaming (docs/api-reference.md)
WebSocket bidirectional chat with Mnesia history (7-day retention shipped via event_retention_days; the code fallback is 30)
Event sourcing with Mnesia (event_types=102 event types across 16 groups)
gen_statem-based workflow engine with compensation
14 provider adapters with 8 circuit-breaker protected (the machine
count includes the sol_provider_egress policy helper; the 12 wire
adapters are Anthropic, OpenAI, OpenAI-compat, Responses, z.ai, Ollama,
Gemini, DeepSeek, Alibaba, Bedrock, Xiaomi, declarative)
llama.cpp local inference with remote provider fallback
Prometheus metrics (OpenTelemetry tracing was retired by design — it had
zero consumers; re-introduction is tracked, not scheduled)
34 ETS heir-owner tables under sol_owners_sup
Luna Agent (LuaJIT)
luna_modules=268 modules, luna_lines=100104 lines of Lua code ~1 MB stripped secure binary (full build ~4.8 MB; bytecode + XOR + CRC32, statically linked libzmq) 92 registered tools (74 built-in + 12 computer-use + 6 desktop-environment are platform-conditional) + MCP discovery 8 agent modes (Build/Plan/Explore/Review/General/Coordinate/Leader/Teammate) + user-defined MCP client (stdio + HTTP + WebSocket, multi-server, OAuth PKCE) Dual-write sessions (JSONL + SQLite with FTS5 full-text search) Git auto-snapshots, undo stack, diff view 4 sub-agent backends (local/zmq/team/background)
Mango (Python/Tornado)
mango_modules=62 modules — auth and identity service
Token validation and RBAC (~27 endpoint-specific permission strings)
ZMQ event bridge to Sol for live cache invalidation (
sol_mango_event_subscriber)
Migration runner, rate limiting (IP + per-account brute-force)
Microservice framework for extending the platform
Limon (TypeScript/Vue 3)
limon_files=253 source files — mission-control dashboard 21 views: Login, Dashboard, Chat, Workflows, Audit, Workers, Recipes, Settings, Channels, Skills, Goals, BgWorkers, Providers, Memory, Events, Schedules, Teams, System, ManagedSettings, Seats, Telemetry WebSocket chat, SSE streaming, real-time worker status
ZMQ Gateway Architecture
The ZMQ gateway uses a dedicated sharded architecture for scalability and security:
Sol_zmq_sender — owns the ROUTER socket, serializes all outbound sends
Sol_zmq_recv_dispatcher — dedicated gen_server for inbound message routing
Sol_zmq_result_router — routes child task results, manages parent/child cleanup
Sol_zmq_recv_bridge — recv loop with error backoff (EAGAIN resilience)
Sol_zmq_ownership — per-frame ownership enforcement: every
result/token/error/event/spawn frame is verified against the dispatch index;
unknown_task is allowed (post-restart leniency) but not_owner is dropped
with a CRITICAL log + alertable counter
Sol_zmq_task_dispatcher — task lifecycle: dispatch, queue, retry with
error strategy (skip/retry/abort), per-task execution timeout
Sol_zmq_worker_manager — worker registration, heartbeat tracking,
stale-worker eviction, task assignment
ETS indexes (sol_zmq_task_index, sol_zmq_id_index) for O(1) lookups
Plugin tool executor pool (simple_one_for_one) isolates plugin tool execution
Worker Registration Security
When zmq_worker_secret is configured, the DEALER’s ready frame must carry
nonce + hmac (HMAC-SHA256 of nonce with the shared secret). Sol rejects
registrations without a valid HMAC. Secrets < 16 bytes are refused outright.
Task Lifecycle
dispatch → pending → ok / error / cancelled
↑ ↑
| |
store_pending terminal-state guard
(once ok/completed,
| later writes rejected)
queued (no worker ready) →
store_pending — tasks are written to sol_task_results at dispatch
time (both dispatched and queued paths) so GET /api/v1/tasks/:id returns
{status: "pending"} instead of 404 during the in-flight window
Terminal-state guard — store_result_/4 rejects writes to a task already
in ok/completed state, preventing the double-result race (eviction retries
to worker B, but worker A’s late result silently overwrites)
Valid transitions: pending→ok, pending→error, error→pending (retry
reset), pending→cancelled
Extension System
Plugins register custom tools, commands, modes, and event handlers via Luerl (Lua-in-Erlang) bridges:
16 bridge modules (log, http, config, events, channel, json, time, tools, commands, sessions, providers, workflows, agents, memory, scheduler, util) Extension lifecycle (init/register/start/stop) with context invalidation Plugin tool dispatch via ZMQ RPC (server-side Luerl execution) 3 sandbox backends — Landlock (write-deny fork layer), bwrap (namespace/network/read owner), seatbelt (macOS alternate) — and 6 permission modes (default/allow-all/deny-all/read-only/plan/auto) Permission priority chain: user config > extension rules > mode defaults
Memory Pipeline
Cross-session persistent memory with extraction and consolidation:
Heuristic memory extractor (fact/preference extraction from conversations) Algorithmic consolidator (dedup + prune with 85% similarity threshold) Reflection clustering for cross-session insight synthesis Session close hook triggers memory extraction KV+TTL storage with provider abstraction
Durability + encoding: the file (MEMORY.md) and JSON
backends fsync the temp file before an atomic rename;
values that are empty, ## -leading, #-leading, or whitespace-ambiguous
are stored as a single =json=-sentineled escaped line (keys starting
=json= are reserved); the SQLite backend stores scalars with a =j:
prefix so "42" stays a string and 42 stays a number. Dual mode
(JSON + SQLite) is FIFO-serialized sqlite-first with JSON as the durable
base — best-effort convergence, not a transaction. Same-path
multi-process writes to memory.json are protected by an advisory flock
(not transactionally safe). Memory scoping is one effective uuid
(instance → module → "system"); instance-scoped sets are visible to
instance-scoped search only.
Key Design Decisions
- Erlang/OTP 29.1 for massive concurrency and fault tolerance
- LuaJIT for ultra-lightweight worker nodes (sub-10MB footprint)
- ZMQ (chumak) for the polyglot worker boundary — msgpack wire format
- Event sourcing as the orchestration backbone (event_types=102 event types)
- Luerl sandbox for safe server-side plugin execution
- llama.cpp for local-first inference with cloud fallback
Security posture
This page is the short version. The full model — every gate, refusal, counter, and residual — is the generated Security model.
Trust boundaries
| Boundary | Control |
|---|---|
| Client → Sol HTTP | Bearer token or x-api-key; RBAC scope checks at the middleware; per-principal rate limiting; workspace scope derived server-side from user_uuid. |
| Sol → worker (ZMQ) | CURVE transport by default; per-worker enrollment keys; HMAC-signed READY; per-frame MAC on worker-plane frames; duplicate-identity eviction. |
| Worker → host | Three sandbox layers; six permission modes; deny-by-default tool policy; explicit approval for repo-config credential families and MCP servers. |
| Sol → Mango | Verified TLS client (verify_peer + CA file); non-loopback plaintext refused in production. |
| Audit | HMAC-chained Sol audit log + Mango audit_logs chain with a signed checkpoint anchor; operator verification surfaces. |
Enforced guarantees
A result/token/error frame is accepted only from the worker the task was dispatched to (recorded executor stamped at dispatch).
A READY frame without a verified credential is refused (registration_hmac_failed); the legacy shared-fleet-secret window is closed by default.
A shared worker declaration is refused unless the deployment explicitly acknowledges it — and even then, no multi-tenant isolation is claimed.
Every mutation handler writes an audit row; tokens and secrets are never logged.
Sandboxed children with execution.sandbox.network=false are kernel-enforced no-egress.
Not claimed
No shared-worker multi-tenancy, per-tenant quotas, or per-tenant backup boundaries.
No domain-level egress boundary when sandbox.network=true (the hosts/allowlist policy is advisory; raw-IP/DoH/IPv6 bypass is an accepted risk).
No OIDC/SAML SSO; LDAP/GLAuth federation is the shipped identity federation path.
No mutual TLS between Sol and Mango; TLS termination is one-way with a verified server.
A complete audit-anchor wipe by an attacker with database write access is not detectable without an off-host copy.
Reporting a vulnerability
See the repository SECURITY.md for the disclosure process. Do not open a public issue for a suspected vulnerability.
Next
Security model (full) Known security gaps Permissions and sandbox ZMQ security
Known limitations
These are current, intentional constraints — not bugs. Each has an impact, a workaround where one exists, and a trigger for revisiting.
Tenancy
| Limitation | Impact | Workaround | Revisit trigger |
|---|---|---|---|
| One organization per Sol; one tenant per worker | A worker operator can read every task/workspace assigned to that worker | Provision one worker per trust domain | Funded multi-tenant program (ADR-0011 option 2) |
No tenant_id claim or per-tenant quotas | Reporting and cost allocation are per principal, not per tenant | Use separate Sol deployments per organization | Same as above |
| Shared-worker mode requires an explicit ack and claims no isolation | A shared worker is a lab/dev posture only | Do not share hardware across trust boundaries | Same as above |
Identity and access
| Limitation | Impact | Workaround | Revisit trigger |
|---|---|---|---|
| LDAP/GLAuth federation only; no OIDC/SAML SSO | Enterprises standardized on OIDC/SAML need a bridge | Use LDAP/GLAuth, or front ZERG with your IdP for console access | Enterprise demand |
max_users seat cap is carried but not enforced by the worker supervisor | A seat overage is a reporting/contract issue, not a hard runtime refusal | Monitor usage and enforce contractually | Seat-enforcement program |
| Provider-key rotation has no HTTP/CLI admin surface | Rotation is a remote-shell ceremony (sol_provider_pool:add_key/3) | Use the documented operator ceremony; plan a maintenance window | Fleet growth or enterprise requirement |
Security residuals
| Limitation | Impact | Workaround | Revisit trigger |
|---|---|---|---|
Sandbox domain egress policy is advisory when network=true | A compromised child can bypass via raw IP, DoH, or IPv6 | Keep network=false unless required; isolate the host network | Kernel-level egress design (see docs/network-egress.md) |
| Audit anchor lives in the same database (Mango) | A full anchor+history+tail wipe is indistinguishable from a fresh install | Export the anchor/log or backup off-host and compare out of band | Off-host anchor storage |
| Plugin memory rows survive unload | A reloaded plugin can inherit a previous generation’s memory | Treat plugin memory as untrusted; scope keys per generation manually | Plugin-plane memory revocation |
| Crash dumps may land world-readable | Gen_server state could be exposed in a crash dump | Set ERL_CRASH_DUMP to a protected path at the entrypoint | Wild entrypoint hardening |
| Sol→PostgreSQL TLS is off by default | A remote database link is plaintext | Keep PostgreSQL on the host bridge, or enable memory_pg_ssl + CA | Remote-database deployment |
Product scope
| Limitation | Impact | Workaround | Revisit trigger |
|---|---|---|---|
| ZERG is not launched | There is no managed control plane to sign up for | Use WILDZERG self-hosted | SaaS launch |
| OpenTelemetry tracing is retired | No distributed tracing spans; metrics + logs are the observability story | Use Prometheus metrics, structured logs, and the event spine | Funded tracing requirement |
luerl is not an available sub-agent backend | The task tool’s backend enum rejects it | Use local, zmq, team, or background | Luerl sub-agent implementation |
| No Windows server support | The control plane targets Linux (Debian 13) | Run in a Linux VM/container on Windows hosts | Product decision |
Compatibility
Erlang/OTP 29.1+ is the support floor; OTP 28 is not a target.
The ZMQ wire protocol is strict-forward: older protocol versions are refused loudly, not silently downgraded.
The legacy shared fleet secret works only while zmq_fleet_legacy_compat is explicitly reopened; the default is closed.
Next
Support matrix Security posture Tenancy posture Upgrade and rollback
Support matrix
Runtime floors
| Component | Supported | Notes |
|---|---|---|
| Linux | Debian 13 (production), Debian 12 (development) | WILDZERG’s blueprint targets Debian 13 + podman + runit |
| Erlang/OTP | Erlang/OTP 29.1+ (OTP 30+ is the forward aim; OTP 28 is not a support target) | OTP 29.1.1 is the CI toolchain |
| rebar3 | 3.20+ | Build only |
| LuaJIT | 2.1 | Luna worker and zerg CLI |
| Python | 3.11+ | Mango |
| PostgreSQL | 16+ | Optional for Sol memory; Mango supports SQLite or PostgreSQL |
| Node.js | 20 | Limon, toronja, starfruit builds |
| llama.cpp | current upstream | Optional, for local inference lanes |
Protocol versions
| Plane | Version discipline |
|---|---|
| Sol HTTP API | OpenAPI spec in docs/fixtures/openapi_spec.json; 202 spec rows |
| ZMQ worker wire | Strict-forward protocol version; older versions refused loudly |
| Erlang distribution | Versioned join handshake; TLS-capable |
| Mango ↔ Sol events | HMAC v2 bridge wire; freshness window + nonce replay guard |
Scale posture
ZERG is designed for operator-owned clusters, not a multi-tenant public cloud:
One organization per Sol. One worker per trust domain. Cluster mode supports blue/red/green-style deployments with release coordination. Model lanes are leased and validated on the server that hosts them.
Browser support (Limon)
Limon targets current evergreen browsers (Chromium, Firefox, Safari). It is a desktop operations console, not a mobile-first app.
Provider support
14 provider adapters ship (Anthropic, OpenAI, OpenAI-compatible, Gemini, DeepSeek, z.ai GLM, Alibaba Qwen, AWS Bedrock, Ollama, and others), with 8 circuit-breaker-protected paths. The model catalog and provider map are generated from contract/model_catalog.yaml and docs/fixtures/model_provider_map.json.
Upgrade windows
Image-based deploys (WILDZERG) support rollback by image tag. Mango schema migrations are versioned and run at boot; a failed migration refuses readiness. Cross-version compatibility is documented in the version matrix.
Next
Install Version matrix Known limitations
FAQ
Is ZERG open source?
No. ZERG (Sol + Luna + Mango + Limon) is proprietary software. ZERGBASE, the infrastructure panel, is MIT-licensed and lives in a separate repository. The Microsoft MCP Gateway integration is MIT.
Does my data leave my machines?
Only if you route it to an external provider. With local inference lanes (llama.cpp) and local storage, prompts, completions, sessions, and memory stay in your environment. Air-gapped deployment is supported. See Air-gap install.
Can I use my own API keys?
Yes. Provider keys are configured declaratively via apikeyenv names, or added to the encrypted provider-key pool. ZERG never writes provider keys to config files.
How many workers can I run?
There is no fixed protocol limit; the practical limit is your hardware, your provider quota, and the Sol deployment’s capacity. Cluster mode supports multiple Sol nodes for release coordination and failover.
Can multiple organizations share one Sol?
No. The shipped posture is one organization per Sol and one tenant per worker. Shared-worker multi-tenancy is not claimed. See Tenancy posture.
Does it support SSO?
LDAP/GLAuth federation ships today. OIDC/SAML SSO is roadmap, not shipped.
Which models are supported?
Anything served by one of the 14 provider adapters, plus local llama.cpp models in the lane catalog. You can switch providers mid-conversation and configure fallback chains.
What happens when a worker dies mid-task?
The task is ownership-stamped at dispatch, the dispatch outbox is durable, and boot reconcile requeues acknowledged-but-undispatched work or marks orphans loudly. Terminal task rows are crash-durable. See Workers and tasks.
Is there a hosted version?
ZERG (zergs.net) is invite-first and not launched. WILDZERG is the live, self-hosted product.
How do I get release artifacts?
WILDZERG release bundles are distributed by Spacebeam to licensed operators. The repository also documents a from-source development build. See Install.
How do I report a security issue?
Follow the repository SECURITY.md disclosure process. Do not open a public issue.
Why are there version numbers and decision IDs in the docs?
ZERG has a long, audited release history. Reference pages cite the decision or release that established a behavior so operators can trace why a contract exists. You can ignore the IDs on a first read.
Choose your path
There are three ways to meet ZERG. Pick the one that matches your goal.
1. Evaluate without installing
Read Why ZERG, Architecture, and Known limitations. If you need a proof of fit, use the security posture and support matrix as the checklist.
2. Run WILDZERG on your hardware
This is the supported production arrangement: Debian 13 + podman + runit, provisioned by the wild blueprint.
- Obtain the release bundle and wild access from Spacebeam.
- Follow Install for the bundle path.
- Follow Deployment and the WILDZERG runbook for host provisioning.
- Verify with First agent.
3. Build from source (development)
Use this to contribute, test, or run a local control plane without the production blueprint.
- Install the development prerequisites.
rebar3 compile+rebar3 shellfor Sol.- Build the CLI and point it at
http://127.0.0.1:21434. - Run First agent with a local worker.
What you need either way
| Requirement | Why |
|---|---|
| A Linux host (Debian 13 recommended) | Sol, Luna, Mango, and the wild blueprint target Linux |
| A model source | A local llama.cpp model or a provider API key |
| A token or loopback access | The HTTP API is authenticated by default |
| A worker enrollment path | Wild provisions keys; dev locally-spawned workers are minted automatically |
No public download URL is implied by this book. WILDZERG artifacts are distributed by Spacebeam to licensed operators. The from-source path is fully documented and does not require a release bundle.
Install
This page gets you from zero to a running control plane. There are two paths: the WILDZERG release bundle (production) and a from-source development build.
Path A — WILDZERG release bundle (production)
WILDZERG is provisioned by the wild blueprint (runit + podman + OpenResty). The release bundle is distributed by Spacebeam to licensed operators; the blueprint repository is https://git.zergs.net/spacebeam/wild (access is provisioned with your license).
- Obtain the bundle the signed Sol/Luna/Mango images, the wild checkout, and your license/enrollment material.
- Prepare the host Debian 13, podman, runit, a data disk mounted at
/fun, and the firewall posture from the deployment guide. - Provision follow the WILDZERG runbook. It covers secrets, Mango migrations, Sol config, worker enrollment, TLS, and readiness.
- Verify
curl -fsS http://127.0.0.1:21434/health(or the public health endpoint) andzerg statusagainst the API.
The wild blueprint is the authority for production; do not use the archived systemd model in docs/installation.md.
Path B — From-source development build
Prerequisites
| Dependency | Version | For |
|---|---|---|
| Erlang/OTP | Erlang/OTP 29.1+ (OTP 30+ is the forward aim; OTP 28 is not a support target) | Sol |
| rebar3 | 3.20+ | Sol build |
| LuaJIT | 2.1 | Luna and the CLI |
| gcc / build-essential | C11+ | Native FFI and CLI build |
| libcurl dev headers | 7.68+ | CLI link |
| ncurses dev headers | 6.0+ | Luna TUI |
| Python | 3.11+ | Mango (optional for a Sol-only smoke) |
| Node.js | 20 | Limon (optional) |
Build and start Sol
(cd server && rebar3 compile)
(cd server && rebar3 shell)
Sol listens on http://127.0.0.1:21434 by default. Leave the shell running.
Build the CLI
bash zerg-cli/build/build.sh
export PATH="$PWD/zerg-cli:$PATH"
zerg status
Expected: Status: ok.
Optional: start Mango
Mango is required for token auth, RBAC, and team/identity operations. For a Sol-only dev smoke, loopback access works; for an auth-on deployment, start Mango and run its migrations before pointing Sol at it. See Mango configuration.
Optional: start Limon
(cd limon && npm install && npm run dev)
Limon is the operations console; it talks to Sol and Mango over HTTP/WS.
Verify the install
[ ] rebar3 compile exits 0.
[ ] Sol logs the HTTP listener on port 21434.
[ ] zerg status returns Status: ok.
[ ] zerg doctor returns healthy (if the diagnostics command is available in your build).
[ ] A locally-spawned worker registers (zerg spawn --count 1 then zerg agents).
Common first-run failures
| Symptom | Cause | Fix |
|---|---|---|
registration_hmac_failed | A worker connected without a verified credential | Provision an enrollment key, or use a Sol-spawned worker (minted automatically). The dev-only anonymous escape requires an explicit Sol lever and is CRITICAL-logged. |
connection refused on 21434 | Sol is not running, or the bind address is not loopback | Check the Sol log and the http config; the default is loopback. |
zerg: command not found | The CLI build directory is not on PATH | export PATH="$PWD/zerg-cli:$PATH". |
| Mango 503 on login | Mango is down, migrating, or unreachable | Check Mango health and its database; Sol refuses non-loopback plaintext Mango in production. |
Next
First agent Deployment Configuration
First agent
This walkthrough takes you from a running control plane to a completed task. Every step has a verification point; do not skip them.
Prerequisites
Sol is running (Install).
The zerg CLI is on PATH and zerg status is green.
You have a model available: either a local llama.cpp model discovered by Sol, or a configured provider.
1. Confirm the control plane
zerg status
zerg doctor # optional: readiness + health verdict
2. Make a model available
Local llama.cpp
zerg discover # scan the model source directory
zerg start <model-slug> # start the lane
zerg run --model <model-slug> "Reply with: ready"
Remote provider
Configure the provider (declarative api_key_env or the encrypted key pool), then confirm the model resolves through the catalog. See Provider setup.
Verify: a completion returns text.
3. Spawn a worker
zerg spawn --count 1
zerg agents
zerg agents prints worker/agent ids. A locally-spawned worker is minted a per-worker enrollment key automatically (the local: namespace), so no manual secret is required in development.
Verify: the worker appears in zerg agents and the Sol log shows a successful READY.
For an external worker, provision an enrollment key and start Luna with
LUNA_ZMQ_KEY_ID+LUNA_ZMQ_WORKER_SECRET; a credential-less worker is refused withregistration_hmac_failed.
4. Dispatch a task
Streaming is the default:
zerg task <agent-id> "Summarize the repository README in three bullets"
For a scripted run, queue it and poll:
zerg task <agent-id> --no-stream --wait "Summarize the repository README in three bullets"
Verify: the task streams tokens or returns a terminal result, and zerg task-status <reports> a terminal status status.
5. Prove ownership and cost
zerg task-status <status> — worker, and, timing timing.
GET /api/v1/usage — per-principal usage when auth and cost accounting are enabled.
zerg metrics — Sol metrics, including dispatch and provider counters.
6. Cancel and recover
zerg task-cancel <task-id>
Cancellation is ownership-gated and drives a terminal state; a worker subtree cancel also stops child tasks.
Troubleshooting
| Symptom | Check |
|---|---|
No workers in zerg agents | Sol log for registration_hmac_failed or a missing enrollment key |
| Task stays pending | Worker is registered but not READY, or the model is not started |
provider_exhausted | Provider keys are missing or all circuits are open; inspect zerg circuits |
| Task result rejected | The result came from a worker that was not the recorded executor — check for duplicate worker identities |
Next
First swarm Sessions and chat Workers and tasks
First swarm
A team is a leader plus teammates working a shared objective, with signed directives and a member-readable mailbox.
Prerequisites
A running control plane and at least one registered worker (First agent). An admin token (team creation is admin-only).
1. Create a team
curl -X POST http://127.0.0.1:21434/api/v1/teams \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"name": "research-team",
"size": 3,
"model": "<model-slug>",
"mode": "coordinate",
"system_prompt": "You are a research team. Split the work, verify each other, and report sources."
}'
Response: { "ok": true, "team_id": "team-..." }.
Verify: GET /api/v1/teams/:id shows members and queue depth.
2. Inspect members
curl -s http://127.0.0.1:21434/api/v1/teams/<team-id>/members \
-H "Authorization: Bearer $TOKEN"
Members are worker ids with roles (leader/teammate). A directive is delivered to the leader; the leader assigns work.
3. Send a directive
Directives are the fleet-correct assignment plane (the old teamspawn tool is retired). Send a signed directive through the team control path used by your deployment, or drive the team through the chat/agent surface with the leader agent.
4. Use the mailbox
zerg team mail list --team <team-id>
zerg team mail send --team <team-id> --to <member> --body "Status report?"
Member reads require membership (or creator/admin); sends require the creator/admin mutator gate.
Verify: the message appears in the team view and the member can acknowledge it.
5. Cancel the team
curl -X DELETE http://127.0.0.1:21434/api/v1/teams/<team-id> \
-H "Authorization: Bearer $TOKEN"
Cancellation stops members and releases their resources.
Operational notes
Team directives are signed (HMAC) on the wire; a worker refuses an unsigned directive. The mailbox supports targeted delivery and per-channel rate limits. Team state is durable; a leader crash does not silently drop queued work.
Next
Teams and channels ZMQ security Workers and tasks
First workflow
A workflow is a durable, multi-step execution with compensation. Recipes are named, validated workflow definitions.
1. List recipes
zerg recipe-list
2. Inspect a recipe
zerg recipe-show incident-analysis
A recipe declares steps, their task/agent bindings, and compensation behavior.
3. Run it
zerg recipe-run incident-analysis --payload '{"alert_id":"42"}'
Or start a workflow directly:
curl -X POST http://127.0.0.1:21434/api/v1/workflows/start \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"name": "code-review",
"payload": {},
"objective": "Review the diff for bugs",
"token_budget": 50000,
"time_budget_ms": 600000
}'
Response: { "workflow_id": "wf-...", "status": "started" }.
4. Inspect progress
zerg workflow show <workflow-id>
zerg workflow tree <workflow-id>
zerg workflow lineage <workflow-id>
The tree shows steps; lineage shows the execution history.
5. Pause, resume, cancel
Pause is a gate: events arriving while paused are parked and resumed deliberately. Cancel triggers compensation for completed steps.
zerg workflow cancel <workflow-id>
6. Schedule it
zerg schedule add "Run the nightly code-review workflow" --name nightly-review --cron "0 2 * * *"
zerg schedule list
zerg schedule pause <job-id>
Schedules are validated at create time (day/month impossibility is refused); times are interpreted in UTC unless your deployment config says otherwise.
Verify
zerg workflow show reports a terminal status.
The event stream shows workflow.* transitions.
A deliberate failure runs the compensation chain; the runbook documents the retry/compensation semantics.
Next
Workflows and scheduler Production runbook Events
First MCP tool
ZERG integrates with the Model Context Protocol in both directions: Luna as an MCP client (using external tool servers) and ** Luna as an MCP server** (exposing tools to an IDE/agent).
MCP client configuration
MCP servers are declared in .luna/mcp.json (project) or the user config. Project-local configuration has a lower precedence than the global config, and HTTP/SSE servers require a hash-keyed approval.
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/srv/workspace"]
}
}
}
Supported server fields include type, url, headers, timeout, max_parallel, auth, max_body_bytes, and strict_osv.
Approve a server
On first use, the worker asks for consent for an HTTP/SSE server (hash-keyed approval). A stdio server also requires a hash-keyed approval when it is repository-supplied. Approval is stored in the user-owned approvals store, never in the repo.
Use a tool
Once connected, MCP tools are namespaced mcp<and>__<are> subject to the same permission and sandbox rules as built-in tools built-in tools.
Verify: zerg agents shows the worker’s tool inventory; a task that calls the tool returns a result.
Air-gap note
npx and remote MCP servers require network access. In an air-gap, use a locally installed stdio server and vendor its dependencies into the image, or expose an in-cluster HTTP server.
Luna as an MCP server
luajit client/main.lua --mcp-serve
This exposes Luna’s tool surface over the MCP stdio protocol (initialize before tools, framed bodies, self-wrap refused).
Next
MCP integration Tools reference Permissions and sandbox
Operator index
This is the day-2 map. Start with deployment, then keep the runbooks close.
First deployment
- Install — bundle or source.
- Deployment — the wild blueprint, host prerequisites, and network posture.
- WILDZERG runbook — secrets, Mango migrations, Sol config, workers, TLS, readiness.
- Production runbook — the operational reference: health, alerts, recovery, drills.
Recurring operations
| Task | Guide |
|---|---|
| Upgrade or roll back | Upgrade & rollback |
| Back up and restore | Backup & DR |
| Rotate keys and secrets | Key & secret rotation |
| Respond to an incident | Incident response |
| Read metrics and alerts | Observability |
| Run in an air-gap | Air-gap install |
| Add or remove a node | Cluster operations |
| Understand tenancy limits | Tenancy posture |
| Check licensing and seats | Seats & licensing |
| Debug a failure | Troubleshooting |
Non-negotiables
Never run a second Sol against the same Mnesia/data directory.
Never deploy without a readiness probe and a rollback image.
Never treat a green HTTP listener as proof of a healthy event spine; /ready checks the data plane.
Never restore a backup without verifying the manifest checksums.
Always rotate the enrollment key when a worker is rebuilt or reassigned.
On-call quick reference
zerg status
zerg doctor
zerg zmq-status
zerg circuits
zerg metrics
Alert rules link to the exact runbook section. If an alert link is stale, treat that as a documentation bug and fix it in the same change.
Deployment
ZERG deploys in two variants per the Spacebeam brand architecture:
ZERG at zergs.net — Spacebeam-hosted control plane; user connects hardware via Luna worker
WILDZERG at wildzerg.com — self-hosted via the wild blueprint (runit + podman + OpenResty); full sovereignty, air-gap capable
This guide covers WILDZERG self-hosted deployment. For ZERG, sign up at zergs.net.
Deployment Options
| Method | Use Case | Details |
|---|---|---|
| wild blueprint (recommended, the ONLY production model) | Production self-hosted | runit + podman + OpenResty GitOps; provisioned from the wild repo (clone URL + WILD_REF below) |
| k0s Kubernetes | WILDZERG Enterprise + MCP Gateway | k0s single-node or multi-node; see corp/docs/k0s-evaluation.md |
| Manual | Development only | Erlang/OTP + Python/Tornado installed directly — NOT a production deployment model |
Services
| Service | Technology | Port | Access |
|---|---|---|---|
| zerg-sol | Erlang/OTP 29.1 | 21434 | localhost only |
| zerg-mango | Python/Tornado | 5800 | localhost only |
| OpenResty | TLS reverse proxy | 80/443 | public |
| postgresql | Database | 5432 | localhost only |
Production Deployment (wild blueprint)
Production deployment is owned by the wild repo — the only supported
production model. Docker is banned company-wide; there is no Docker
Compose stack. Wild provides the canonical runit + podman + OpenResty GitOps
model and its autonomous CD pipeline (Crow CI, podman backend) builds the 8
ZERG images hermetically and deploys them on a tag push.
Wild repo / WILD_REF (pinned dependency): wild is NOT part of this
tree and is not a public URL on this page — the clone URL and the
per-release pin (ci/wild-pin, git checkout $(cat ci/wild-pin), see
.crow.yml) are documented in the operator runbook
docs/production-runbook.md (§Deployment — Primary Path). For the
current topology, service table, provisioning scripts and deploy paths,
see wild/AGENTS.md in that repo (§“CD Build Execution”).
From-scratch production host: follow wild’s provisioning scripts
(wild/scripts/provision/) rather than any manual steps — the manual
section below exists for local development only.
Operator runbooks: the deploy / upgrade / rollback flow is in the
WILDZERG Runbook; day-2 procedures in the
Production Runbook; offline sites in
Air-Gap Install.
Manual Dev Deploy (development only)
⚠ NOT a production deployment model. These steps run the components directly on the host for local development. Production deploys via the wild blueprint above; runit supervision, OpenResty TLS and image provisioning are wild’s job, never manual
sv/systemd units on a production host.
Prerequisites
apt-get install -y postgresql postgresql-contrib OpenResty certbot python3-pip
pip3 install --break-system-packages tornado bcrypt aiosqlite
Install Erlang/OTP 29.1 via asdf:
mkdir -p ~/.asdf/bin
curl -sL https://github.com/asdf-vm/asdf/releases/download/v0.15.0/asdf-v0.15.0-linux-amd64.tar.gz \
| tar xz -C ~/.asdf/bin/
export ASDF_DIR=~/.asdf
export PATH=~/.asdf/bin:$PATH
asdf plugin add erlang
asdf install erlang 29.1
asdf set -u erlang 29.1
Step-by-Step Manual Deploy
⚠ ARCHIVED / DEVELOPMENT-ONLY. This manual path is not a production deployment model and is not exercised by CD. The paths below (
/opt/zerg) belong to the retired on-host layout; the shipped container root is/opt/sol, and production is wild’s runit + podman GitOps model (see Production Deployment anddocs/production-runbook.md). Do not copy these steps onto a wild-managed host.
1. PostgreSQL Setup
sudo -u postgres psql -c "CREATE USER zerg WITH PASSWORD 'CHANGE_ME';"
sudo -u postgres psql -c "CREATE DATABASE zerg OWNER zerg;"
sudo -u postgres psql -c "CREATE DATABASE zerg_auth OWNER zerg;"
sudo -u postgres psql -c "ALTER USER zerg CREATEDB;"
2. Build Sol Server
PATH=~/.asdf/installs/erlang/29.1/bin:$PATH rebar3 as prod release
3. Deploy Release
mkdir -p /opt/zerg/{bin,etc,log,data,luna,limon,mango,plugins}
cp -a _build/prod/rel/sol/* /opt/zerg/
cp sys.config /opt/zerg/releases/{VERSION}/sys.config
cp vm.args /opt/zerg/releases/{VERSION}/vm.args
4. Deploy Luna Agent
cp client/build/luna /opt/zerg/luna/luna
chmod +x /opt/zerg/luna/luna
5. Deploy Mango Auth
cp -a mango/* /opt/zerg/mango/
6. Deploy Limon Dashboard
cp -a limon/dist/* /opt/zerg/limon/
7. Create Admin User
import bcrypt, json, uuid, sqlite3, time
db = sqlite3.connect('/opt/zerg/mango/data/mango.db')
pw_hash = bcrypt.hashpw(b'YOUR_PASSWORD', bcrypt.gensalt()).decode()
user_uuid = str(uuid.uuid4())
db.execute(
'INSERT INTO users (uuid, account, password, email, role, data, created_at) VALUES (?,?,?,?,?,?,?)',
(user_uuid, 'admin', pw_hash, 'admin@example.com', 'admin',
json.dumps({"account":"admin","email":"admin@example.com","role":"admin","nickname":"Admin"}), time.time()))
db.commit()
db.close()
8. Bootstrap Admin RBAC
Mango’s setup_db auto-seeds admin RBAC on startup. Restart Mango (dev:
python3 server.py from the mango/ checkout, after stopping the previous
instance):
cd /opt/zerg/mango
python3 scripts/bootstrap_admin.py --auto
The RBAC chain is: admin user -> system-admin team -> admin role -> permissions: ["*"]
9. SSL Certificates
Dev-only convenience for exercising TLS locally. Production TLS is provisioned by wild (OpenResty + certbot on the operator host).
certbot certonly --webroot -w /var/www/html -d YOUR_DOMAIN -d www.YOUR_DOMAIN \
non-interactive --agree-tos --email admin@YOUR_DOMAIN
certbot certonly --webroot -w /var/www/html -d api.YOUR_DOMAIN \
non-interactive --agree-tos --email admin@YOUR_DOMAIN
10. OpenResty Configuration
Dev-only reverse-proxy example. Production nginx configuration lives in wild (
runit/sv/openresty/conf/sites/*.conf).
server {
listen 443 ssl http2;
server_name YOUR_DOMAIN;
ssl_certificate /etc/letsencrypt/live/YOUR_DOMAIN/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/YOUR_DOMAIN/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
root /opt/zerg/limon;
index index.html;
location / { try_files $uri $uri/ /index.html =404; }
location /api/ { proxy_pass http://127.0.0.1:21434; proxy_buffering off; }
location /v1/ { proxy_pass http://127.0.0.1:21434; proxy_buffering off; }
location /events { proxy_pass http://127.0.0.1:21434; proxy_buffering off; proxy_read_timeout 86400s; }
location /auth/ { proxy_pass http://127.0.0.1:5800; }
location /health { proxy_pass http://127.0.0.1:21434; }
}
server {
listen 443 ssl http2;
server_name api.YOUR_DOMAIN;
ssl_certificate /etc/letsencrypt/live/api.YOUR_DOMAIN/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/api.YOUR_DOMAIN/privkey.pem;
location / { proxy_pass http://127.0.0.1:21434; proxy_buffering off; }
location /events { proxy_pass http://127.0.0.1:21434; proxy_buffering off; proxy_read_timeout 86400s; }
location /auth/ { proxy_pass http://127.0.0.1:5800; }
}
# Metrics are NOT served by the public site. This monitoring-only listener
# binds loopback; the same-host Prometheus scrapes it directly. Sol's gate
# admits a tokenless scrape only from a LOOPBACK TCP peer whose
# X-Forwarded-For chain (if present) is entirely loopback.
server {
listen 127.0.0.1:9110;
server_name _;
location /metrics { proxy_pass http://127.0.0.1:21434; }
}
A REMOTE Prometheus must scrape Sol directly with
Authorization: Bearer <token> (the token needs metrics:read) or through a
private listener like the loopback one above; never publish /metrics or
/api/v1/metrics from the public server_name blocks.
11. Run for Development
The components run directly in dev (no service manager involved):
# Sol (in server/): rebar3 shell
# Mango (in mango/): python3 server.py
# Limon (in limon/): npm run dev
Production supervision is runit via wild (
runit/sv/zerg-*); the systemd-unit era ended with the deploy model. Do not install hand-rolled units on a production host.
12. Verify
curl -sk https://YOUR_DOMAIN/health
curl -sk https://api.YOUR_DOMAIN/health
Environment Variables
Most SOL_* variables map through sol_app:apply_env_overrides/0 into the
sol application env; a few are consumed by server/bin/entrypoint.sh (for
example SOL_PLUGIN_DIR creates the container mount directory and has no
Sol app-env reader). See docs/configuration-reference.md for the
authoritative per-key table. The commonly used ones:
| Variable | Default | Description |
|---|---|---|
SOL_CLUSTER_COOKIE | unset (dev) / required (prod) | Erlang distribution cookie — installed as a 0400 $HOME/.erlang.cookie (never in argv); prod requires an explicit ≥16-char non-dev value |
SOL_PGVECTOR_ENABLED | false | Enable pgvector search |
SOL_WORKER_HEARTBEAT_TIMEOUT_MS | shipped sys.config/sys.prod.config = 15000 (code fallback 45000) | Worker heartbeat eviction timeout |
SOL_CONTAINER_ENGINE is not read by Sol — there is no such env mapping
or config key; the runtime is wild’s podman model.
Notes:
The /metrics Prometheus endpoint is always mounted (loopback-gated in
production); there is no enable flag for it.
The heartbeat check interval (worker_heartbeat_check_ms, default 10000)
is sys.config-only — it has no SOL_* environment override.
Production Checklist
[ ] Change default passwords and secrets
[ ] Enable TLS via OpenResty reverse proxy
[ ] Set auth_enabled to true
[ ] Configure firewall rules (allow 80/443 only)
[ ] Bootstrap admin RBAC
[ ] Verify /metrics responds and Grafana scrapes it
[ ] Configure PostgreSQL for memory/embeddings
[ ] Verify health endpoints respond
[ ] Test admin-gated endpoints return 200
[ ] Enable automatic certificate renewal (certbot renew)
Rollback (wild-provisioned host)
Image-level rollback is driven by wild’s CD pipeline (flip IMAGE back to
IMAGE.prev in runit/sv/<svc>/env/); on a runit-managed host the manual
service restart is:
sv stop zerg-sol
cp -a /opt/zerg/releases/{VERSION} /opt/zerg/releases/{VERSION}.bak
sv start zerg-sol
Maintenance Mode
Enable maintenance mode to gracefully drain traffic during deployments:
curl -X POST https://api.YOUR_DOMAIN/api/v1/infra/maintenance/enable \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"reason": "deploying v{VERSION}"}'
curl -X POST https://api.YOUR_DOMAIN/api/v1/infra/maintenance/disable \
-H "Authorization: Bearer $TOKEN"
Health and auth endpoints remain accessible during maintenance mode.
Production Runbook
Operational procedures for maintaining and recovering ZERG in production. This runbook covers upgrades, backups, incident response, and monitoring. The tag-triggered deploy / CD pipeline flow lives in the WILDZERG Runbook; the full-state backup & restore procedures in Backup & DR.
Rolling Upgrades
Cluster version guard: SolClusterVersionGuard (critical —
a Sol-Sol join was refused for a schema-epoch mismatch or a generation beyond
N±1, or the join version probe failed against a peer; refusals are the guard
acting, probe failures are admitted with an unknown posture and must be
investigated) plus the version.posture.maintenance_503_marker and
sol_cluster_version_skew gauge in /api/v1/cluster. Upgrade control nodes
one at a time; a schema-epoch jump is stop-the-world. cluster_version_guard_ack
covers BOTH refusal arms (generation AND schema-epoch mismatch), is read per
exchange (a runtime flip applies to the next join, no restart), and only ever
turns a refusal into a CRITICAL-logged ACKED admission for a deliberate drill.
The join generation/schema epoch are release-gated by
contract/cluster-generation.yaml + ci/cluster_generation_lint.py.
Event truth: SolEventUnknownTypes (warning — a node saw
an event type it does not register and projected nothing; a mixed-version
window or an unregistered producer is the cause; inspect the bounded type
label and the peer releases). The production mixed-version signal is the
admission rejection (sync_event_dropped_undefined_type_total), which fires
before any validator; the alert consumes BOTH families. Declared catalog
events with no validator row (inference.request, task.assigned, worker.,
team.,…) are healthy and do NOT count.
Automated Deployment
Production deployment is owned by the wild repo (spacebeam/wild), not a
checked-in deploy script. Wild’s autonomous CD pipeline (Crow CI, podman backend)
builds the ZERG images hermetically and deploys them on a tag push:
A Forgejo/Crow tag push checks out ZERG + spacebeam/corp + wild, fetches
tree-sitter grammars fresh, builds all 8 images, pushes, and deploys to blue.
Services run under runit (runsvdir -P /fun/service); containers under podman
on the zerg_infra network. No systemd for application services, no Docker.
Trigger and watch a run via scripts/release/cd-trigger.sh on blue.
See wild/AGENTS.md for the full CD model.
The legacy deployment/scripts/deploy.sh is archived and must not be
used — it predates the wild GitOps model.
Manual Operations (container model)
ZERG runs on blue as podman containers under runit — there is no on-host
beam checkout (/opt/sol), no zerg user, and no systemd unit. The
legacy beam-scp / sol remote / /opt/sol procedures were retired with
the archive and have been removed from this runbook.
Upgrades: the CD pipeline (deploy-zerg.sh) is the only supported path —
see the WILDZERG Runbook.
Sol remote shell: podman exec -it zerg-sol bin/sol remote (or
podman attach for the release console).
Mnesia backups: the zerg-sol-mnesia-backups podman volume, verified by
sol_mnesia_backup:verify_restore/1 — see Backup & DR.
Worker/luna processes run INSIDE the sol/luna containers — there is no
zerg-luna-worker runit service.
Endpoint Health
curl -s http://127.0.0.1:21434/health | jq . # liveness only
curl -s http://127.0.0.1:21434/api/v1/ready | jq . # deep readiness (503 when degraded)
/health (and its /api/v1/health alias) is a shallow liveness endpoint:
it answers {"status":"ok","models_running":N} whenever the BEAM can answer
HTTP. It does not run ETS/disk/memory/process checks. /api/v1/ready
runs the 19 readiness checks (sol_health:check_names/0) and is the endpoint
for deployment gates and load balancers; point monitoring at /ready (and
/metrics), never at /health.
If /ready is 503 with policy_closed, the node is in the operator
maintenance window — see maintenance mode.
Service Health
sv status /fun/service/zerg-sol /fun/service/zerg-mango /fun/service/openresty
Full System Check
zerg status
zerg discover
zerg zmq-workers
zerg list
Common Incident Response
Sol Continuously Restarting
Symptom: OpenResty 502 errors every few minutes.
Cause: runit restart loop (exit code -1 / config failure 162), or stale beam.smp processes.
sv down /fun/service/zerg-sol # stop AND hold it down (sv stop would restart)
podman ps -a --filter name=zerg-sol # stale container?
podman logs --tail 200 zerg-sol
sv up /fun/service/zerg-sol
There is no zerg host user and no on-host beam.smp to pkill — Sol is
the zerg-sol podman container. Inspect the run script and logs: the Sol run
script must exec the binary (no backgrounding) and exit 162 on config
failure. Check tail -f /var/log/runit/zerg-sol/current.
SolUptimeReset rides the same incident class: sol_uptime_seconds < 120
means Sol just restarted. One blip is the restart loop above; repeated
resets mean the run script keeps failing — read the log tail before
restarting again. During a PLANNED restart, enable the maintenance window
first (see Maintenance Mode) — the rule suppresses
itself on sol_maintenance == 1.
Mango Auth Failures
MangoLdapRevalidationBlastRadiusRefused: the LDAP revalidation sweep refused a mass revocation (ratio/empty-search blast-radius gate). Inspect the directory/search ACL and the audit row before retrying; the tombstone is reversible.
Covers the whole Mango surface: SolMangoDown (Sol-side reachability
probe), MangoDbDown (Mango’s own /health reporting its DB unreachable —
the alert carries the dead-man shape or absent(sol_mango_db_up), so a
vanished series fires it too), the Mango auth-plane rates
MangoAuthErrorRate, MangoAuthLatencyHigh, MangoAuthInfraFailures,
MangoMetricsDeadMan (warning — scrape-freshness
algebra: up{job="mango"} == 0 or absent(mango_metrics_enabled); a
hard-down scrape target, or a PARTIAL export (target still scrapes but the
posture family vanished), pages. A STALE exporter that keeps serving
mango_metrics_enabled is NOT detected by this rule (noDataState: OK;
the up leg assumes the scrape job is literally named mango — a
differently-named job falls back to the absent leg / SolMangoDown).
An idle-but-scraped instance is Normal. This rule owns scrape-target loss
/ partial export; SolMangoDown remains the PROCESS-death page — the two
can fire together when the process and its scrape target die in the same
event),
the bridge posture SolMangoBridgeLegacyAuth and SolMangoBridgeDown,
the revocation plane SolMangoRevocationFlushFailed, and the trust-plane
attacks SolZmqBridgeHmacFailures + SolZmqBridgeNonceReplay.
SolAuthDisabledBoot is the auth-disabled boot posture (a Mango outage
must never degrade into silently running without auth).
Adds SolTlsCertExpiring (warning — the Sol→Mango TLS peer
certificate expires in under 7 days; sol_mango_client stamps its
notAfter at every successful TLS connect, so the Sol Workers/Mango panel
shows days-until-expiry; renew the host cert and restart Sol — the
Erlang-distribution and nginx TLS legs are outside this metric).
sv status /fun/service/zerg-mango
tail -n 100 /var/log/runit/zerg-mango/current
curl -s http://127.0.0.1:5800/health
curl -s http://127.0.0.1:21434/metrics | grep -E 'sol_mango_(up|db_up|bridge)'
Check the Mango DB path uses an absolute path inside the container (list the mounted volumes with podman inspect zerg-mango and read the source paths from the Mounts section).
SolMangoDown / SolMangoBridgeDown: the Sol→Mango link or bind is
gone — check the Mango container first, then the bridge bind endpoint
in Sol’s config. Auth fails closed while Mango is unreachable.
MangoDbDown: the process answers but its database does not — the
DB volume/PG path is the suspect (the podman inspect check above).
MangoAuthErrorRate / MangoAuthInfraFailures / MangoAuthLatencyHigh
are the per-handler rates: 401/403 floods are credential attacks or a
broken client; 503s are the DB again.
SolMangoBridgeLegacyAuth: the bridge dropped to the legacy (unsigned)
auth mode — fix the shared-secret configuration before admitting
workers; do not run the fleet legacy-mode.
SolMangoRevocationFlushFailed (critical, immediate): a revocation
full-flush cache-invalidation leg failed — a STALE AUTH CACHE is
possible (revoked tokens keep validating) until the next successful
resync. Force a resync and verify the flush legs in the Sol log.
SolZmqBridgeHmacFailures / SolZmqBridgeNonceReplay: treat as a
trust-plane event — isolate the offending peer, capture the bridge
audit rows, then re-admit.
MangoMetricsDeadMan: the scrape target is DOWN
(up{job="mango"} == 0; the job label must literally be mango) or the
exporter answered without its posture family
(absent(mango_metrics_enabled) — a partial export). It does NOT detect
a STALE exporter whose /metrics still serves mango_metrics_enabled
(that class has no rule this phase; use the Auth Series Present panel
freshness by eye). Check the Prometheus target page and the Mango
container. This is the SolMangoDown boundary: SolMangoDown keys on
Sol’s own sol_mango_up probe (process death / link loss); the dead-man
keys on the Prometheus scrape surface (target loss / partial family
export). A target that is merely idle but still scraped exports up=1 +
enabled=1 and stays Normal — do NOT treat an idle auth server as a
freeze. noDataState: OK means a vanished up series alone is not this
rule’s signal. The Auth Series Present panel shows both series.
MangoLdapRevalidationStale: the LDAP
directory-revalidation sync has not completed a clean run in over 2h
(or never ran) while federation is enabled — deleted directory users
may still hold live Mango sessions/service tokens. Check the Mango log
for LDAP revalidation verdicts and probe errors; confirm
MANGO_LDAP_REVALIDATION_SECONDS matches your intended cadence and
the directory is reachable from the Mango container. A federated user
that was tombstoned by the sync (account deleted in the directory)
cannot log back in until the stale local row is deleted via the admin
API — that is the deliberate fail-closed posture (a re-hire onboards
fresh).
MangoBcryptQueueSaturated: the bounded
bcrypt queue is fast-failing >5 hash submissions/min with the typed
bcrypt_queue_saturated 503. The bound is holding by design — treat
it as a credential-stuffing burst signal: confirm the source via the
per-IP login limiter metrics; tune MANGO_BCRYPT_QUEUE_SIZE only with
capacity, never to silence the alert.
Mango schema is FORWARD-ONLY
Mango’s migration runner refuses to run an OLDER image against a NEWER
schema: a store whose applied version exceeds the newest migration the
running tree ships makes /ready answer 503 not_ready reason=schema_ahead
and run_migrations refuses boot, because forward-only migrations cannot
undo the newer columns (the live case: a pre-v0013 image against a v0013
store reports green and then fails every token write on tokens.seq NOT NULL). The remedy is the matching image, or the explicit controlled
rollback ack MANGO_ALLOW_SCHEMA_AHEAD=1 (logged CRITICAL; migrations
are NOT undone — the older image must tolerate the newer columns or the
first write surfaces it). Restore-before-rollback is the documented
operator path.
Inference Out of Memory
SolMemoryPressure: ETS + process memory over 4 GB; SolMemoryWalDroppedOps
(critical): the memory WAL dropped ops — data loss, not pressure. Both
share the first-response path:
curl -s http://127.0.0.1:21434/api/v1/ps | jq .
curl -s http://127.0.0.1:21434/metrics | grep -E 'sol_memory_(bytes|wal)'
Reduce the model’s context length or switch to a smaller model. The podman container memory limit (set by wild’s podman-runner.sh via WILD_PODMAN_MEMORY) is 4GB for zerg-sol by default. WAL drops are worse than pressure: exported batches that failed to enqueue are GONE — capture the drop reasons from the log, then check the WAL segment directory for a full disk or a wedged writer before restarting.
ETS Table Corruption
ets:info(sol_models).
ets:info(sol_global_catalog).
If tables are missing, restart Sol. ETS tables with {heir, Pid} survive owner crashes via the heir mechanism.
Monitoring
Prometheus Metrics
curl -s http://127.0.0.1:21434/metrics
The /metrics endpoint is always mounted (loopback-gated in production —
proxy or scrape it from the podman zerg_infra network). Key metric families:
| Metric | Description |
|---|---|
sol_up | Dead-man self-report gauge (1 = scrapeable; the series disappearing is the SolNodeDown signal) |
sol_metrics_table_present | 1 = the metrics ETS table is alive; 0 = every ETS-backed counter is a catch-defaulted lie right now |
sol_http_2xx_total / sol_http_5xx_total / sol_http_stream_unavailable_total | SLO response counters (2xx / HTTP-status 5xx / post-200 stream-unavailable; availability = 2xx ÷ (2xx + 5xx + stream-unavailable)) |
sol_zmq_workers_active | Currently active ZMQ workers (recomputed from the live registry at boot — not a persisted accumulator) |
sol_zmq_tasks_dispatched_total | Tasks dispatched to workers |
sol_scheduler_jobs_active | Active scheduled jobs |
Families that used to be listed here — sol_http_requests_total,
sol_inference_duration_seconds, sol_zmq_workers_connected — never
existed in the exporter (phantom rows; the real surfaces are the SLO
counters, the sol_http_request_duration_seconds histogram, and
sol_zmq_workers_active respectively). deleted the phantoms.
Config fingerprint drift drill. sol_build_info carries
config_fingerprint (the 64-hex SHA-256 of the node’s effective boot
config). A fleet that should share one config must answer
count(count by (config_fingerprint) (sol_build_info)) = 1; a value above
1 means a node booted with env/config-file/profile drift. Compare the label
values with each node’s boot log, then restart the divergent node through
the normal roll to converge.
SLO
SLO compliance is Grafana’s job (the retired /api/v1/slo endpoint was
deleted in ) — use the sol-api-slo dashboard and the alert
rules in observability/.
Grafana Dashboard
Grafana runs as a podman container on the zerg_infra network, supervised by
wild under runit. Start/restart it via:
sv restart /fun/service/grafana
Configure the Prometheus datasource pointing to http://zerg-sol:21434/metrics
(or the host-scoped metrics URL per wild/AGENTS.md). That target is only
reachable tokenless from a LOOPBACK peer: a scrape from another host must set
authorization: {credentials: <token>} on the job (the token needs the
metrics:read permission) — otherwise Sol answers a typed 403. Recommended:
scrape_configs:
- job_name: sol
authorization:
type: Bearer
credentials_file: /etc/prometheus/sol-metrics-token
static_configs:
- targets: ["zerg-sol:21434"]
Maintenance Mode
SolMaintenanceUnknownState (critical) fires when a booted node reads the
maintenance flag and finds no persisted/cached state — the read fails
closed, so requests are treated as maintenance (503s) until the flag is
restored. Check the data-dir permissions/disk and the
maintenance_unknown_total counter. The counter is absent on a healthy boot:
Any bump means the read failed closed — investigate immediately; a
sustained increase means the durable state file is unreadable.
Enable maintenance mode to drain traffic gracefully:
curl -X POST http://127.0.0.1:21434/api/v1/infra/maintenance/enable \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"reason": "scheduled maintenance"}'
Health and auth endpoints remain accessible during maintenance.
Disable when complete:
curl -X POST http://127.0.0.1:21434/api/v1/infra/maintenance/disable \
-H "Authorization: Bearer $TOKEN"
Cache Invalidation
After configuration changes, invalidate cached auth paths:
curl -X POST http://127.0.0.1:21434/api/v1/infra/cache-invalidate \
-H "Authorization: Bearer $TOKEN"
This refreshes persistent_term cached values for auth exempt paths and rate limit settings.
Alert Reference Runbooks
Every alert rule in observability/grafana/alerting/sol-alerts.yml carries a
runbook_url pointing at one of the sections below. Each entry is symptom →
first checks → action; the metric families are the ones listed under
Prometheus Metrics.
ZMQ
Alert: SolZmqSenderUnbound — a healthy-looking gateway whose sender has no bound worker; follow the sender-bind checks below.
Alert: SolZmqPipeTeardownGenerationSkipped — a pipe-scoped teardown was skipped because the queued teardown carried an older pipe generation; a sustained rate is reconnect churn or a flapping pipe set. Inspect the ZMQ sender/gateway generation counters and the pipe bindings.
SolZmqLossCounters: PUB events dropped (stalled subscriber/timeout), oversized worker frames dropped (protocol violation), or task-frame encode failures are moving. The counters are cumulative and absent on a healthy boot; sustained movement means a wedged subscriber or a malformed fleet. (The documented pause posture uses a separate counter and is not alerted.)
Covers worker/gateway liveness and the trust plane: SolZmqSenderDead,
SolZmqGatewayDead, SolZmqSendFailures, SolZmqTaskQueueBacklog,
SolTaskCompletionGap, SolZmqAuthFailures, SolZmqDroppedMessages,
SolZmqRegistrationRefused, SolZmqFrameMacReplay,
SolZmqFrameMacForgery, SolZmqDecodeErrors,
SolZmqResyncFailures, SolZmqResyncGap, SolZmqIdentityConflict,
SolZmqRegisterRateAnomaly. additions: SolZmqFleetSkew
(multiple admitted protocol versions live — finish the rolling upgrade),
and SolZmqOrphanChildrenCancelled (a subtree cancel walked children
whose parent never recorded their terminal state). completes the
enumeration: SolZmqWorkerDrop (≥20% of the registered fleet gone in
10m), SolZmqIdentityCeilingRefusal (registration refused because the
identity-lifetime replay stores reached zmq_identity_ceiling; the old
SolZmqReplayRowsGrowth hardcoded-80%-threshold rule is retired — the
replay gauges stay on the sol-zmq dashboard), SolZmqTaskLifetimeExceeded
(a task hit its lease lifetime cap), SolZmqTokenShed (token frames shed under pressure),
SolZmqBridgeTsStale / SolZmqBridgeEpochRegression (bridge clock-skew /
epoch plane), and the Luna sandbox postures SolLunaSandboxInert /
SolLunaSandboxDisabled (the ZMQ-borne sandbox layer is not effective —
a worker fleet running unsandboxed). adds the ACP trust plane —
the same attack classes on the ACP channel: SolAcpHmacFailures
(forged ACP frames), SolAcpReplayFailClosed (replayed ACP frames),
SolAcpRegisterRefused (registration crash-loop/probe),
SolAcpKeyRevoked (revocation telemetry — unexpected/clustered
revocations are the signal), and SolAcpFrameStale (stale/future/
bad-TTL frame freshness refusals). adds the pre-auth heartbeat
bucket SolZmqPreauthHeartbeatFlood (unregistered heartbeats dropped at a
sustained rate — a self-declared-identity flood; identify the source
pipe/peer at the ZMQ listener) and SolZmqPausedNackDropped (gateway-paused
NACK pressure, including bound-pipe-proof refusals of foreign senders).
curl -s http://127.0.0.1:21434/metrics | grep -E 'sol_zmq_(gateway_alive|sender_alive|dropped|task_queue_depth|registration_refused|auth_failures|replay_rows|token_shed|bridge_ts|bridge_epoch|credential_refresh)'
zerg zmq-workers # registered fleet + freshness
sv status /fun/service/zerg-sol
Gateway/sender dead (*_alive == 0): restart Sol (see
Sol Continuously Restarting); the gateway re-registers workers.
Registration refused / rate anomaly: check sol_zmq_registration_refused_total
labels (reason) and the worker clocks — enrollment keys expire; re-provision
with the wild runbook.
Worker drop / fleet skew: a ≥20% drop inside 10m is a fleet event
(worker-host restart, network partition) — zerg zmq-workers shows who
is missing; a skew means the rolling upgrade is mid-flight, finish it.
Replay rows / token shed / lifetime caps: pressure signatures — the
identity ceiling or the lease plane is saturating; check
sol_zmq_replay_rows_* against the ceiling, and the lifetime-cap/token
counters against dispatch volume.
Decode errors (SolZmqDecodeErrors): undecodable frames on the
pre-auth router legs. The decoded reason is bounded + rate-limited in the
Sol log; a sustained rate is a version-skewed/crashing worker or a
malformed-frame flood — correlate the sender identity with the fleet
protocol skew.
Bridge ts-stale / epoch regression: the Mango bridge clock/epoch plane
is misbehaving — verify host clocks (NTP) and the bridge resync state;
an epoch REGRESSION means the bridge went backwards — force a resync.
Sandbox inert / disabled (SolLunaSandboxInert /
SolLunaSandboxDisabled): the advertised sandbox layer resolved to
nothing on the worker fleet (inert) or the deployment deliberately runs
disabled (and it should not in prod). Check the worker host’s sandbox
support before re-admitting workers.
Dev posture exposed (SolZmqDevPostureExposed): the ZMQ auth posture
gauge reports the dev-external-bind mode in a fleet that should be
gated — flip the deployment to prod posture (the enrollment/auth gates
are weak in this mode; see sol_zmq_deployment_posture in the trust
docs) before any further worker admits.
HMAC / nonce replay / identity conflict: treat as a trust-plane event —
isolate the offending worker (revoke its enrollment key), then inspect
sol_zmq_bridge_hmac_failures_total and audit rows before re-admitting.
Frame-MAC forgery (SolZmqFrameMacForgery): the failures family
(sol_zmq_frame_mac_failures_total — bad shape / hmac mismatch /
oversized identity) is the forgery half of the plane; forged MACs
with fresh nonces never appear in the replay family. A slow
post-cutover legacy-v2 straggler (hmac_mismatch) is the benign floor —
identify the worker by the refusal logs and re-provision it; clustered
failures across identities are the MITM/probe signature.
ACP trust plane (SolAcpHmacFailures / SolAcpReplayFailClosed /
SolAcpRegisterRefused / SolAcpKeyRevoked / SolAcpFrameStale):
the same response as the ZMQ HMAC/replay class — identify the ACP peer
by its registration identity, revoke the bound key, and check the
sol_acp_* families (sol_acp_hmac_failed_total,
sol_acp_replay_fail_closed_total, sol_acp_register_refused_total,
sol_acp_key_revoked_total, sol_acp_frame_{stale,future,bad_ttl}_total)
before re-admitting. A key-revocation page during a known rotation is
expected; clustered revocations you did not run are the incident.
Queue backlog / completion gap: scale workers or reduce concurrency; a
persistent gap means results are not arriving — check the Luna logs on the
worker host.
Tasks
SolDurableFileDecodeTruncation (warning, any increase): a durable
append-log frame failed validation (corrupt length/term) and was skipped
forward — later frames are preserved, the lost frame is permanent. Check
disk health and the file named in the warning, and restore the affected
journal from backup if it is critical (task outbox / dispatch receipts /
memory WAL).
SolDurabilityWriteFailed: increase(sol_workflow_attempt_marker_failed_total[15m]) + increase(sol_scheduler_persist_failed_total[15m]) > 0 — a durable workflow-attempt marker or scheduler-store persist write failed. The scheduler keeps dirty jobs and retries; stale attempt markers may survive. Check the Mnesia volume and the node log.
SolTaskCompletionGap: rate(dispatched[15m]) - rate(completed[15m]) > 1
sustained for 10m. The 15m window + 10m hold tolerate a burst of long
tasks (dispatched now, completed minutes later); only a genuinely
stranded queue keeps the completion rate behind the dispatch rate. Check
worker health, task timeouts, and the dispatch outbox/retry queue.
Additions (the durable-probe tri-state): SolTaskProbeUnavailable
(critical — sol_task_store_durable_probe_unavailable_total moving: the
durable frozen-row probe could not answer and terminal writes/requeues
are REFUSED, not guessed; check Mnesia health and
task_store_mnesia_bound_ms) and SolZmqReconcileProbeUnavailable
(warning — sol_zmq_reconcile_probe_unavailable_total moving: dispatch
outbox receipts were deferred, kept durable, and reconcile at the next
boot scan; a persistent rate means Mnesia is degraded).
Covers the durable task stores: SolTaskQueueFull, SolTaskCompletionGap,
SolOrphanResults, SolDispatchOutboxBacklog, SolRetentionSweepTimeout,
SolSchedulerDegraded, SolProjectionAborted, SolSyncEventOverloaded.
Integrity additions: SolSchedulerOneShotIntegrity (warning — a
one-shot barrier write failed, or the fire ended in a typed error/skip
terminal without running; the consumed window is gone, inspect the job row
and store health), SolTeamMailReconciliation (warning — durable team-mail
rows were suppressed on READY or reaped as ghosts; a normal kick/leave/
team-destroy purge is expected cleanup and is charted only, never paged.
A sustained ghost rate means worker-id reuse or a stale team journal), SolCoordinatorReconcileDebt (warning — the
persisted-decomposition reconcile found a missing workflow row or needed a
transient-read retry), and SolWorkflowRevocationMarkerFailed (critical —
the owner-revocation trailer could not be made durable; a revoked owner’s
workflow may remain resumable, check Mnesia immediately).
Additions (scheduler id integrity): SolSchedulerJobIdConflict
(critical — a guarded job create refused an id that already existed; the
persisted schedule is intact because the collision was refused, so inspect
scheduler_job_id_conflict_total, the job row, and the store journal for a
caller that bypassed the allocation funnel) and
SolSchedulerJobIdNonmonotonic (warning — the scheduler’s advisory id cache
disagreed with the store’s DURABLE high-water; the store stayed authoritative
and the create used the safe id, but a bump is a real divergence from the
persisted watermark, not merely a restart, so inspect the scheduler process
state and the store snapshot/journal job_id_high_water fields).
Additions: SolTaskIdempotencyDegraded (critical — a claim
degraded OPEN, duplicate execution possible; identify the request key
from the claim WARNING log and check Mnesia health),
SolDispatchOutboxWriteFailed (critical — a receipt write failed before
send; reconcile with the outbox endpoint), SolDispatchOutboxOrphaned
(boot reconcile marked rows orphaned — executed work needs manual
reconcile), and SolWorkflowCompensationMarkerFailed (critical — a
compensation marker write failed; verify the affected steps’ side
effects manually). adds the workflow/event-store plane:
SolWorkflowBudgetLimited (workflow budget stops), SolWorkflowSubDeaf /
SolWorkflowCrashStrand (store subscription loss / unrecovered crash
strands), SolCompactionFailures (event compaction skipped/failed),
SolEventStoreBacklog (oldest-event age or staging backlog over budget),
SolEventStoreMaintenance (critical — the event-store maintenance-503
posture; the rule is SUPPRESSED while the operator maintenance window
(sol_maintenance) is active, so a planned drain never pages; a boot-owned
store failure with maintenance off still pages), SolSyncEventShed
(sync-event journal/mailbox shedding), and SolSyncEventRetentionBloat
(the retained-bytes estimate over the configured 4 GiB budget).
Adds SolDispatchOutboxJournalFailed (warning — an outbox-journal
frame could not be appended or FSYNCED; the mnesia receipt remains primary
but the SIGKILL/power-loss safety net for dispatched receipts is degraded —
check disk health on the Sol data dir, ENOSPC/EIO, and
sol_dispatch_outbox_journal_restored_total at the next boot) and
SolDispatchOutboxJournalBloat (warning — the journal stayed above the
8 MiB compaction threshold for 15m: the outstanding receipt set itself
dominates, clears have stopped, or the atomic rewrite cannot land; check the
outbox backlog, the journal-size panel on Sol Workers & Tasks, and
sol_dispatch_outbox_journal_compacted_total /
sol_dispatch_outbox_journal_compaction_failed_total; the file is
dispatch_outbox.journal in the Sol data dir).
Durability/ownership alerts live in this section too:
SolTaskStoreTerminalReconcilePending (critical — a terminal result write
failed while the dispatch receipt survived; boot/periodic reconcile is the
recovery path, check Mnesia/disk before it drains),
SolTaskStoreReceiptNewerThanTerminal (warning — a live retry receipt is
newer than the durable terminal row; the retry is retained and requeued,
investigate the power-loss/kill window), SolWorkflowPersistFailed
(critical — the workflow start/resume durable write failed and the ack was
withheld), SolWorkflowResumeStatusChanged (warning — a resume
compare-and-write found a live child already owns the terminal state),
SolOwnerRegistryEmpty / SolOwnerRegistryRearmFailed (critical — an
owner re-armed an empty/failed static registry; lookups/validation degrade
until restart; check the owner’s re-arm CRITICAL log and owner_registry_*
counters), and SolStreamWriterAbandoned (warning — a foreign SSE writer
was abandoned on ack-timeout/connection DOWN; one-off = client disconnect,
sustained = admission-slot churn; verify the caller ran its terminal
funnel).
/ adds SolTaskStoreDurableWriteFailed (critical —
a terminal result’s durable write did not land; the ETS row is served
this boot and the retained receipt + needs_reconcile marker re-write or
requeue it; check Mnesia/disk health on the Sol data dir, and read it
with SolTaskStoreTerminalReconcilePending — that rule counts the
chokepoint’s receipt-retained verdicts, this one the raw durable-tier
failure).
W9 adds the event-handler ingestion dead-man pair:
SolEventHandlerRemoved (critical — a gen_event handler was removed
after 5 consecutive crashes; metrics/audit/archive/sync/forwarder
ingestion for that handler is down), and SolEventHandlerFreshness
(warning — an installed handler has not completed a successful event
delivery for over an hour; stalled/deadlocked handler). The supervised
rearm (sol_metrics_owner’s watchdog) re-installs a removed handler
within ~30s, up to 5 attempts per handler per VM — watch
sol_event_handler_rearm_exhausted_total for a spent budget; a handler
that exhausts stays down until its crashes are root-caused. The
Event Handler Guard panel on Sol API SLO & Health carries the whole
plane (removals, per-handler age, re-arms, exhaustion).
curl -s http://127.0.0.1:21434/metrics | grep -E 'sol_(task_queue_depth_pct|dispatch_outbox|retention|scheduler|sync_event|event_store|workflow)'
curl -s http://127.0.0.1:21434/api/v1/tasks/outbox | jq .
zerg list
Queue pressure: drain or shed load (zerg list, cancel stuck tasks);
verify workers are accepting dispatches.
Outbox backlog: the dispatch outbox is written before send and cleared at
the terminal chokepoint; a growing backlog means sends/terminals are
failing — check the ZMQ section above.
Retention sweep timeout: the sweep is paged and budgeted; a timeout means a
store operation is wedged — check PG/disk health, then allow the next
budgeted pass (it resumes from the last page). SolSyncEventRetentionBloat
is the volume-side twin: the sweep runs but the retained-byte estimate
keeps growing — check the compactor/reap cadence and the event inflow
rate before raising the budget.
Projection aborted / sync-event overload: projections self-heal from the
event store; investigate only if the counters keep rising (they are
truncated/derived state, never the source of truth). SolSyncEventShed
is the same family’s pressure valve — shed events are journaled and
replayed; sustained shedding means the event spine is oversubscribed.
Workflow degradation (SolWorkflowBudgetLimited / SolWorkflowSubDeaf /
SolWorkflowCrashStrand): budget stops are policy working; subscription
loss and crash strands mean the workflow store is losing its
watchers — restart the affected workflows and check the store owner’s
health.
Event-store plane (SolCompactionFailures / SolEventStoreBacklog /
SolEventStoreMaintenance): maintenance mode is an operator lever
(verify it was intentional); compaction failures and backlogs mean the
event log is growing without a haircut — check disk (see
disk) and the compactor’s last run.
SolWorkflowBridgePosture (warning): the workflow bridge is NOT installed
(sol_workflow_bridge_installed absent or 0 for 15m) — workflow prompt
steps cannot execute and the advertised durable workflow plane is inert.
The shipped posture is workflow_bridge_enabled=true.
Check the boot log for the bridge install/degraded verdict and whether its
sync-store subscription could arm; the usual cause is a store that cannot
arm the subscription — verify event-store health and the bridge config,
then restart only after capturing the install failure.
SolWorkflowCompensationKilled: a
workflow rollback was interrupted mid-compensation (the compensation worker
was killed or its window expired) — the rollback did NOT reliably complete.
Inspect the workflow instance and its compensation journal, then re-run the
compensation from the operator surface. The counter is store-owed: a
committed workflow side effect may remain un-compensated.
SolEventsMailboxDropped: the event
manager’s mailbox hit the shed bound and core events were DROPPED. The event
spine is the durability source — check the archive drain, the mailbox depth
(sol_events_mailbox_len), and the drop-funnel log before the loss window
grows.
SolDispatchOutboxJournalRestoreFailed: the
boot dispatch-outbox journal restore FAILED — the kill-window replay net did
not land, so dispatched-but-unsettled tasks may be lost across the restart.
Inspect the journal file under the Mnesia dir and the boot log; do not
restart again until the journal is readable.
SolSyncEventShed also consumes
sol_sync_event_shed_mailbox_dropped_total: the shed
worker’s OWN mailbox drops are event loss, not just journal pressure.
Workflow compensation
Alert: SolWorkflowCompensationKilled — a workflow rollback was
interrupted mid-compensation. Inspect the workflow instance and its
compensation journal, verify which side effects were already undone, and
re-run the compensation from the operator surface. The counter is
store-owed (a workflow side effect can remain un-compensated).
SSE admission
Alert: SolSseAdmissionRefused — the per-principal stream limit, the
global stream budget, or the connection-headroom gate refused a stream
(429/503 with Retry-After). Check sol_sse_connections_active, the
principal labels in the refusal log, and max_sse_connections / the
headroom reservation. A single principal refusing repeatedly is hoarding
streams; global/headroom refusals mean the streaming budget is saturated —
scale the connection budget or shed the slow consumers, never widen the
gate silently.
Worker crash
SolWorkerCrashRate (critical) fires on >5 crashes in 10 minutes;
SolStaleWorkers fires when registrations age out.
curl -s http://127.0.0.1:21434/metrics | grep -E 'sol_worker_crashed_total|sol_stale_workers'
zerg zmq-workers
Identify the crashing worker from the ZMQ dispatch logs, pull its Luna log
bundle, and check whether the crash is task-class (one bad task) or
worker-class (OOM, sandbox refusal). Worker-class: restart the worker host
agent and re-enroll; task-class: cancel the offending task first. A crash
loop on one node should be cordoned (zerg zmq-workers shows identity) so
the scheduler stops selecting it.
Seats
SolSeatCapSaturated, SolShareQuotaRejected: the seat/share admission
gates are doing their job.
curl -s http://127.0.0.1:21434/metrics | grep -E 'sol_seat_checks|sol_share_quota_rejected'
Check which team is saturated (labels on sol_seat_checks), release idle
seats (workers that no longer hold tasks), and raise the cap only with the
org’s seat allocation in hand. Rejections are expected under load —
alert fatigue means the cap is undersized for the workload.
Plugins
SolPluginExecutorStuck, SolPluginQueuedBudgetExpired: a plugin’s tool
work outlived its budget. SolLuaEvalBudgetKilled: a lua_eval runner was
killed by the shared reductions/heap/refc-binary watchdog (a sustained rate
is a hostile or runaway eval caller — check the lua_eval audit rows and
the caller’s grant). SolChannelDispatchFailed: channel/message
delivery legs failed (the plugin or chat surface could not hand off its
reply).
curl -s http://127.0.0.1:21434/metrics | grep -E 'sol_plugin_(pending_tools|queued_budget_expired)|sol_channel'
Find the plugin in the plugin-manager logs, unload it (sol_plugin_manager
operator surface), and re-run its tool once the queue drains. A repeatedly
stuck executor means the plugin’s budget is mis-sized or it blocks on host
I/O — fix the plugin source before re-enabling. Channel dispatch failures
point at the channel integration (webhook target down, auth expired), not
the plugin itself.
Models
SolModelsZero: no local model is READY to serve (sol_models_ready —
running or startable-on-demand) and no provider endpoint is registered.
SolProviderExhausted: every endpoint for a provider returned
exhaustion/429 and the circuit opened. SolProviderPoolHeadroomZero: a
provider’s key pool has no drawable key (all keys cooling down or quota
blocked) — requests will refuse until a key recovers or is added.
SolAutoscalerTpsUnavailable: the autoscaler lost its TPS signal (lane
placement degrades without it).
curl -s http://127.0.0.1:21434/api/v1/ps | jq .
curl -s http://127.0.0.1:21434/metrics | grep -E 'sol_models_(total|ready)|sol_provider_(endpoints|exhausted)|sol_autoscaler'
Re-register the local model (zerg zmq-workers reports the fleet model
catalog; llama.cpp must have a loaded model) or restore the provider
configuration. SolModelsZero is critical because every inference request
will fail until at least one model resolves. SolProviderExhausted is
quota/key exhaustion — see providers for the fail-over path.
Inference lanes
Alert: SolLaneControlRateLimited — an identity exceeded the lane-control budget (lane_control_max_per_10s, default 60) and the control was refused; a sustained rate is a retry loop, a stale resolver, or an abusive client.
SolGpuProbeTimeout (warning): the supervised nvidia-smi probe timed
out or crashed (driver wedged). Lane VRAM checks fall back to the static
budget and release-verify cannot measure returned memory; cpu_host and
nvidia_smi_missing are separate, non-paging classes. Check the driver and
the Sol log.
SolInferencePortWindowLow (warning — at most ONE free port in the
published [base_port, base_port+inference_port_range) window for 10
minutes; the N-1 leg) and SolInferencePortWindowExhausted (critical —
the window is full; new starts answer a typed no_port_available).
Inspect sol_inference_ports_used/_free and stop idle lanes or widen the
window inside the node’s published range.
Lane-governor alerts: SolLaneReleaseVerifyFailed
(critical), SolLaneLeaseOverPolicyMax, SolLaneVramUnderMargin,
SolLaneStuckLoading (warnings). additions:
SolLaneLeaseExpired (the mid-turn idle-release plane),
SolLaneStoppedWithLease (a stopped lane still holding its lease — the
spawn-failure wedge), SolInferenceStartFailed, and
SolLaneQueueRejected. adds SolLaneLeaseRenewRefused (a lease
renewal refused by the governor — sol_lane_lease_renew_refused_total by
reason; paired with the sol_lane_lease_reclaimed_total reaping counter on
the Sol Inference Lanes dashboard). SolLaneLeaseOverPolicyMax now compares against
the lease’s own granted ceiling (sol_lane_policy_max_seconds), so the
threshold moves with the lane’s configured duration. adds
SolLaneCompletionDegraded: the FIM completion plane (POST /v1/completions → the lane’s internal /infill) is either above its p95
latency band or refusing requests (excluding the typed lane_warming
cold-start class). Check sol_lane_completion_inflight,
sol_lane_completion_queue, sol_lane_completion_refused_total{reason} and
the lane’s own health; the lane endpoint is never client-facing.
curl -s http://127.0.0.1:21434/metrics | grep -E 'sol_lane_(state|lease|vram|orphan|policy)'
ls -l "$(curl -s http://127.0.0.1:21434/metrics >/dev/null; echo /tmp/sol)/lanes" 2>/dev/null
nvidia-smi --query-gpu=index,memory.used,memory.total --format=csv,noheader,nounits
A release-verify failure means a lane stop left its VRAM allocated — find
the pidfile under <data_dir>/lanes/, compare /proc/<pid>/cmdline with
the pidfile’s model/binary before touching anything (lookalikes are counted
and never killed), and check for an external producer (ComfyUI et al.). The
lease-over-policy and stuck-loading warnings point at a wedged lifecycle;
an on-demand lane that holds a lease without traffic is an idle-release
bug. VRAM-under-margin (verified samples only) means image work will OOM —
evict a resident lane or stop the external producer. SolLaneExpired /
SolLaneStoppedWithLease are the mid-turn kill and spawn-wedge
planes: check the lane’s last_error, the lease sweep WARNING lines and
the start-failure counters before restarting anything.
Audit
Alerts: SolAuditSinkNoOp (the sink accepted nothing) and SolAuditSyncFailures (sync failures are accumulating) — both mean the audit trail is not durable; follow the sink/sync checks below.
SolAuditFlushFailures, SolAuditFlushDropped: the audit trail is not
reaching durable storage. additions (Mango-side chain integrity):
MangoAuditHeadCollision (critical — two writers tried to extend the
same chain head; capture Mango’s audit chain state BEFORE restarting) and
MangoAuditChainLockFailures (PG advisory-lock contention on the chain).
MangoAuditWriteFailures (warning): audit writes are failing — strict
callers fail closed, non-strict callers proceed with the row LOST (every
increase is a trail gap). MangoAuditCheckpointFailures (warning): the
signed chain checkpoint is not refreshing, so an external verifier has a
stale anchor. MangoAuditEventsRetentionStalled (warning): the oldest row in
the event-archive table (audit_events) is older than the default 30-day
window + 7 days of slack — the documented mango/scripts/prune_audit_events.py
job has not run and the archive is growing without bound. Back up the Mango
store, run the job’s --dry-run first, then re-run with --yes; an
intentional keep-forever posture is MANGO_AUDIT_EVENTS_RETENTION_DAYS=0.
SolAuditChainVerifyFailed (critical): the audit-chain verifier
rejected the retained chain (tamper, a prune/anchor bug, or a partial file) —
capture the audit files before restarting and verify the oldest retained anchor.
SolAuditChainVerifyDeadman (critical): no verification COMPLETED for over 15
minutes — the verifier loop is down/wedged or audit is disabled; check the audit
server and audit_verify_interval_ms. SolAuditRetainedBufferDepth
(warning): a sustained sink outage is accumulating an oldest-pinned batch in
memory (bounded; NEWEST entries drop on overflow) — treat it as a pre-drop
warning and clear the sink before the drop counter fires.
SolAuditActorIdentityMissing (warning): an audit call site lost its request
identity and stamped internal — trace the calling route; sustained rates
mean wrong-actor attribution is possible. Both alerts link here.
curl -s http://127.0.0.1:21434/metrics | grep sol_audit_flush
tail -n 100 /var/log/runit/zerg-sol/current | grep -i audit
Audit writes are fail-closed for security-relevant actions. Check disk space and the audit sink volume first; a dropped batch must be treated as an integrity gap — export the in-memory tail and record the incident before restarting. If the sink is full, rotate it, then restart Sol.
Projections
SolProjectionRebuildUndercount (critical, any increase): a rebuild
produced a view row BELOW its retention baseline (task/model/worker/
session) — the rebuilt projection lost events the baseline had. The
emitter logs CRITICAL with the table/key; do not delete the baseline,
inspect the replay/retention source and re-run the rebuild.
SolProjectionCrash (critical, any increase), SolProjectionGap (warning):
a projector process crashed on a committed event (the increment is lost
until a rebuild) or the compare-and-write guard absorbed an out-of-order /
replayed event below a view’s last_seq.
SolProjectionDebt: more than one
per-aggregate cap (64) of owed projection/outbox rows are outstanding, the
oldest owed row has aged past 5 minutes, or
increase(sol_projection_debt_retry_failed_total[15m]) > 0 (a durable
debt-row write failed — the owed event’s view contribution is NOT durable).
This is the plane that degrades silently between the first projector
failure and the quarantine cap. Inspect the projection_debt rows, the
projector log, and Mnesia health; the quarantine/orphan counters are the
last-resort loss signal (SolProjectionCrash). The Sol Workers & Tasks
dashboard carries the debt/outbox panel.
curl -s http://127.0.0.1:21434/metrics | grep -E 'sol_projection_(crash|gap|aborted)'
The event log is the truth — projections are rebuilt from it on boot replay.
A crash means a cumulative counter (message_count, total_tasks_started,
token totals) under-reports until the next boot; there is no runtime projection-rebuild route (the legacy URL is
retired — do not script it). A sustained gap stream means either a genuine ordering violation or a
duplicate replay — capture the affected aggregate ids from the Sol log and
escalate; restart-to-replay is the supported repair.
Slow endpoint
SolSlowEndpoint: a windowed p99 per path_class (from
sol_http_request_duration_seconds) has been above 2s for 5m. The rule is
a 5-minute rate quantile, not a since-boot average, and it covers streams
(SSE/WS) — the stream terminate hook records one sample per stream,
including client aborts.
curl -s http://127.0.0.1:21434/metrics | grep sol_http_request_duration
The path_class label (inference_request, chat, http_request) names
the route family; per-path request counts/duration totals live in
sol_http_path_latency_* (bounded to the configured
path_latency_max_paths, overflow is :other). Typical causes: provider
latency for inference routes, PG contention for memory/task routes, or a
slow consumer holding an SSE stream. Check the Grafana latency panels
first, then the provider circuit state.
Queue full
SolTaskQueueFull: the LIVE ZMQ dispatch queue (sol_task_queue_depth)
is over 80% of zmq_max_queue_depth (sol_task_queue_depth_pct > 80).
Addition:
SolLaneQueueRejected — the lane plane’s bounded admission queue
rejected waiters (clients got 429/503); check sol_lane_queue_depth
and lane capacity.
curl -s http://127.0.0.1:21434/metrics | grep sol_task_queue_depth
zerg status
Either the fleet is undersized or workers are wedged (see worker crash and ZMQ). Scale out workers or cancel low-priority tasks. Continued saturation drops enqueues at the admission gate with a loud 429/503 rather than silently queueing forever.
Providers
SolProviderExhausted: every endpoint for a provider returned
exhaustion/429 and the circuit opened; no further retries are attempted
until the cooldown. SolSseUpstreamErrorFrames: SSE streams are emitting
upstream error frames — the provider is up enough to answer but failing
mid-generation.
curl -s http://127.0.0.1:21434/metrics | grep -E 'sol_provider_(exhausted|endpoints)|sol_sse'
curl -s http://127.0.0.1:21434/api/v1/infra/status | jq .
Check the provider key/quota out-of-band, rotate keys if needed, or fail over to a configured secondary provider/model. The circuit closes automatically after the cooldown once a probe succeeds (see circuit breaker). Sustained SSE error frames with a green circuit mean the upstream degrades under streaming — check the provider’s status page and the error-frame reasons in the Sol log.
Processes
SolProcessExhaustion: sol_process_count / sol_process_limit > 0.8.
curl -s http://127.0.0.1:21434/metrics | grep sol_process
podman exec zerg-sol bin/sol remote # :observer.start / process listing
Look for a runaway supervisor, a leaking worker session, or an unbounded request fleet. Restarting Sol clears transient leaks but a rising baseline means a real leak — capture the top process counts before restart.
Readiness and draining
Alert: SolReadinessProbeStale — no fresh /api/v1/ready verdict; the exporter renders the readiness family absent (never a fabricated healthy 1).
SolReadinessDegraded: the last /api/v1/ready verdict is degraded or
policy-closed (sol_readiness_ok 0 for 2m) — the deploy probe refuses and
the load balancer should not route here.
curl -s http://127.0.0.1:21434/api/v1/ready | jq .
curl -s http://127.0.0.1:21434/metrics | grep -E 'sol_readiness_(ok|check)|sol_draining'
sol_readiness_check{check="..."} 0 names the failing dependency. The
probe is bounded (sol_health_check_budget_ms per check,
sol_health_total_budget_ms total), so a timeout row means a dependency
wedged past its budget — inspect that subsystem, then re-probe. Disk
probe_stale means the supervised disk sampler has not refreshed within
90s (the sampler runs off the request path; restarting Sol re-arms it). A
policy-closed verdict is the maintenance gate: /api/v1/ready answers
policy_closed 503 while every non-exempt route 503s — see
maintenance mode.
SolNodeDraining: sol_draining 1 for over 5 minutes — the shutdown drain
budget (shutdown_drain_timeout_ms, default 5000 ms) is exhausted and the
container runtime will SIGKILL the node mid-teardown (skipping the mnesia
checkpoint and the event-archive flush). Check long-lived SSE/streaming
clients and the drain log; the shutdown order is checkpoint → drain →
stop HTTP → flush archive/scheduler → disconnect PG.
HTTP capacity
SolHttpConnectionSaturation: sol_http_connections_utilization_pct > 80
of the explicit http_max_connections cap for 5 minutes. SSE/chat streams
hold connections for their lifetime and share the pool with ordinary HTTP
(max_sse_connections is the streaming budget inside it).
SolHttpNofileHeadroom: sol_http_nofile_headroom < 0 — the process
RLIMIT_NOFILE is below http_max_connections + max_sse_connections + 1024;
accepts will fail with EMFILE under load.
curl -s http://127.0.0.1:21434/metrics | grep sol_http_connections
curl -s http://127.0.0.1:21434/metrics | grep sol_http_nofile
Raise SOL_NOFILE_LIMIT (the entrypoint applies it before exec; a hard
limit may need a container/systemd change) before raising
http_max_connections. Check the SSE admission panel for streams that
never drain, and client retry storms.
Node down
SolNodeDown is the dead-man switch: absent(sol_up) for 2 minutes —
nothing is scraping or Sol is gone. SolInstanceDown is its per-target
companion: up{job="sol"} == 0 for 2 minutes on ONE Sol target while the
rest of the fleet still reports (a single node died without a blackout).
sv status /fun/service/zerg-sol
podman ps --filter name=zerg-sol
curl -s http://127.0.0.1:21434/health
Confirm whether the process, the container, or the network died. If the
container is up but /metrics is not served, Sol is wedged — restart it
(see restart). Ensure the Prometheus scrape target recovered
(up == 1) before closing the incident. SolUnexpectedMessage is the
companion tripwire: the router received a frame it cannot classify — a
one-off after a deploy is noise, a stream means a protocol-version skew
(see ZMQ) or something probing the socket.
License
SolLicenseFallback: the licence plane is running on a fallback source
(source="fallback").
curl -s http://127.0.0.1:21434/metrics | grep sol_license
Renew or re-install the licence file/bundle; fallback mode may disable capacity grants (seats, plugin limits). This is critical because a fallback posture silently changes what the deployment is allowed to do.
High latency
SolHighLatency: inference-request p99 over a WINDOWED histogram —
histogram_quantile(0.99,... rate(sol_http_request_duration_seconds_bucket {path_class="inference_request"}[5m])) > 30 for 5 minutes. (Since
the rule reads the 5-minute histogram window against the documented 30s
generation ceiling — the pre-0.734 text “p99 > 1s” described the retired
since-boot summary and fired on every normal LLM generation.)
curl -s http://127.0.0.1:21434/metrics | grep 'sol_http_request_duration_seconds'
curl -s http://127.0.0.1:21434/api/v1/ps | jq .
Check GPU/CPU contention, context size, and whether the model is being swapped per request. If a single worker is the outlier, cordon it (see worker crash); if all are slow, the host is saturated — reduce concurrency or context length.
Error rate
SolHighErrorRate (critical): >50 combined HTTP-status 5xx responses +
post-200 stream-unavailable terminations in 10 minutes.
SolClassified500: any response CLASSIFIED internal-500 — the
never-500 norm tripwire, distinct from honest 503 maintenance/refusal
responses that also land in the raw 5xx sum. splits
the planes: sol_http_5xx_total is HTTP-status only;
sol_http_stream_unavailable_total{reason} carries truncated /
provider_error / handler_crash (the stream never produced a terminal
HTTP status). Inspect the reason label to tell a provider failure from a
handler crash.
curl -s http://127.0.0.1:21434/metrics | grep sol_http_5xx
tail -n 200 /var/log/runit/zerg-sol/current | grep -E 'CRASH|error'
Group the 5xx by route/method from the metric labels, then reproduce the top route. Sol classifies upstream failures as 502/503 and only truly unhandled conditions as 5xx — a sustained rate means a real handler defect or a dependency outage. If a dependency (Mango, PG, provider) is down, its own alert fires first.
Disk
Alert: SolDiskSamplerStale — the disk sampler has no sample or is older than the stale bound; free-space families are absent.
SolDiskFull: sol_disk_free_bytes < 100MiB. SolDiskFreeWarning:
free space below 15%. SolDiskExhaustionPredicted: a 1-hour trend
predicts exhaustion within 4 hours — act on the prediction, not the wall.
SolDiskProbeFailed: sol_disk_probe_failed{dir} is 1 — the directory
could not be probed (df failed or returned an unparseable pair), so that
volume’s capacity is UNMONITORED. Check the path, permissions, and the
df binary before trusting the free-space panels for that dir.
curl -s http://127.0.0.1:21434/metrics | grep sol_disk_free
df -h /fun /var/lib/containers
Free space immediately: rotate runit logs, prune old Mnesia backups and
container images (podman image prune), and rotate the audit/PG WAL. Sol
fails writes loudly rather than corrupting, but a full disk stops event
persistence — treat as a stop-the-line incident.
Cluster
SolClusterExpectedNodes: sol_cluster_node_count is below the configured
expectation. additions: SolOrchestratorLeaseSplitBrain
(critical — MORE THAN ONE node reports holding the single-writer lease;
capture every node’s lease state, then fence the minority holder — do NOT
reboot blindly) and SolLaneInventoryStale (a peer has been silent past
the inventory TTL for 15m; its owned lanes/tasks resume only when it
returns). SolLaneInventoryStaleIdle is the quieter twin: the peer is
stale but owns NO inventory — link monitoring, not task recovery.
Isolation: the leave set
is seeded from the configured seeds ∪ all known peers, not just the links
up at leave time — a seed that was partitioned during the leave is still
suppressed when it returns. Visible peers receive a peer-side leave marker;
GET /api/v1/cluster exposes left, and status.count/connected/self
plus the connectivity/health planes are separate (a connected peer is
only healthy after a pong; a manually joined peer is unknown, never
implicitly healthy, ). An explicit join is the only
re-entry; a Sol restart starts with an empty leave set.
curl -s http://127.0.0.1:21434/metrics | grep sol_cluster
podman exec zerg-sol bin/sol remote # :nodes()
Bring the missing node back or update SOL_CLUSTER_EXPECTED_NODES /
SOL_CLUSTER_NODES to match the real topology. The deployment is
single-node by default — this alert only fires when clustering is
configured.
SolZmqGatewayFencedWhileHolder (critical, 2m): the node reports HOLDING
the orchestrator lease while its ZMQ gateway is still QUIESCED — a dead
dispatch plane (the pre-fix one-way self-fence). Re-acquire calls
resume(lease_reacquired); if the alert persists, the fence reason differs
from the recorded one, and a takeover/DR fence must not be cleared by a
stale resume. Inspect lease_detail/0 and the gateway quiesce log, capture
the holder/lease state on every node, and only then fence or restart the
affected node.
Circuit breaker
SolCircuitBreakerOpen: a provider circuit has been OPEN for 5+ minutes.
curl -s http://127.0.0.1:21434/metrics | grep sol_circuit_breaker_state
Check the provider’s health out-of-band. The circuit probes and closes on its own once the provider recovers; if the provider is permanently gone, remove or replace the provider configuration. Distinct from provider exhaustion, which is the fast-fail admission path.
TLS certificates
Sol exposes two certificate-expiry gauges: the Sol→Mango peer certificate
(sol_tls_cert_not_after_seconds{service="mango"}) and the Sol listener
certificate (sol_tls_listener_cert_not_after_seconds). SolTlsCertExpiring
and SolListenerCertExpiry page before expiry; rotate the PEM named by
tls_cert_file and reload the listener.
Goals
Goal-plane loss (sol_goals_lost_on_owner_restart) is a store-owed
durability debt: the goal owner’s ETS state does not survive a restart by
design today. Capture the dropped goals from the CRITICAL log and treat goal
durability as a known store gap; SolGoalsLostOnOwnerRestart pages on any
loss.
Backup
Alerts: SolBackupOffsiteUnmanaged (an external lifecycle policy owns the copy without the declared lever) and SolBackupOffsiteLowSpace (the offsite volume is below the floor).
SolMnesiaBackupFailed: the scheduled Mnesia backup reported not-ok.
SolMnesiaBackupMissing: the scheduled backup interval is enabled but the
backup directory holds ZERO backups — the scheduler or the
data directory is wrong; follow the backup procedure and verify
sol_backup_count + sol_backup_newest_age_seconds in the scrape.
SolMnesiaBackupStale: the last SUCCESSFUL backup is >25h old (the
failure counter can be 0 while the scheduler itself is wedged — the age
gauge is the truth). SolMnesiaBackupOffsiteFailed: the off-host copy
leg (rsync/copy + manifest checksum) failed — the local artifact is
intact but the disaster-recovery copy is not.
mnesia_backup_interval=0 disables scheduled backups explicitly (0 is a
documented off switch, never a zero-delay loop). In prod, same-volume
backups are not a DR posture: the readiness backup check reports
offhost_target_required until sol_mnesia_backup_remote_path is set.
curl -s http://127.0.0.1:21434/metrics | grep sol_mnesia_backup
ls -la /var/lib/containers/volumes/zerg-sol-mnesia-backups/
Run a manual backup and verify with the restore checker
(sol_mnesia_backup:verify_restore/1) — see
Backup & DR. A failed backup is not urgent by
itself but an unverified backup is not a backup; fix the volume/space
issue before closing.
Event-store RPO/RTO truth
Alert: SolProjectionRebuildUnproven — the projection rebuild proof gate stayed unproven (gauge 0) for an hour; projections may serve stale/debt rows.
The operator-readable durability statement for the event plane (
the substrate decision record is
plan/pg-durable-spine-design.md in the source tree; the numbers below
are true for the SHIPPED Mnesia spine):
- RPO — process crash / kill -9: 0 committed events. The append ack is
a
mnesia:sync_transaction; spill admissions dedupe on the RecId-derived event id, so a replay after a crash cannot duplicate a committed event. - RPO — host/VM death: ≤ 1 h + tail. The backup cadence is
mnesia_backup_interval(default 3600 s;SolMnesiaBackupStalepages at >25 h) plus the un-checkpointed dets log tail (dump_log_write_threshold=100operations) for events committed after the last backup. The off-host rsync copy bounds site-loss RPO at the same cadence. - RTO — operator-driven restore: repair/reprovision the host →
restore the latest verified backup (
verify_restore/1) → boot → projection rebuild. Minutes-to-tens-of-minutes class on the current fleet; not drilled to a number at scale. - A PG durable spine would change the host-death row to “0 committed events (single-node volume-death caveat) / 0 with a sync standby” — deferred with revival triggers; until a trigger fires, this section is the truth.
Availability
SolAPIAvailabilityDrop: the windowed availability expression
(1 - (rate(5xx) + rate(stream_unavailable)) / (rate(2xx) + rate(5xx) + rate(stream_unavailable))) dropped below 0.999; the dashboard gauge
sol_availability_ratio uses the same three-plane denominator (
).
curl -s http://127.0.0.1:21434/metrics | grep -E 'sol_(availability_ratio|http_5xx_total|http_stream_unavailable_total)'
Availability is a rolling success ratio — inspect which routes contribute the failures (see error rate) and whether the dip is a deploy blip or a sustained trend. Route maintenance traffic is excluded by design; a real dip means unhealthy responses are reaching clients.
PG connection pool
SolPgUnavailable (critical): PostgreSQL is enabled (sol_pg_enabled 1)
but the SAMPLED SELECT 1 probe failed or went stale (>120s) for 2
minutes — a quiet-period outage is visible without waiters. The probe runs
on the supervised health sampler over the pool’s reserved/never-queueing
health plane; no request or scrape blocks on PG.
SolPgPoolFailures (warning): the pool counted a boot-time connect
failure or a health-plane probe failure in the window (the failed
connection was culled and the reconnect ladder is armed).
SolPgPoolStarved (critical): zero idle pool leases while waiters are
queued — every PG-touching route is blocking on a connection. This is the
SATURATION signal; SolPgUnavailable is the outage signal.
curl -s http://127.0.0.1:21434/metrics | grep sol_pg_pool
Find the lease holders: a hung query (sol_pg_query_hang_culled history),
a request flood, or an undersized pool. The pool self-heals by culling
hung leases; if starvation recurs, identify the chatty route from the
latency panels and raise the pool size only with the PG max-connections
budget in hand (the pool shares the single zerg-postgres-dev instance
with every other service).
Event archive
Alert: SolEventArchiveAckUnverified — a 2xx arrived without a verifiable counted ack; the page is KEPT and compaction cannot advance.
SolEventArchiveUnconfigured (critical) and SolEventArchiveFailing
(critical): the audit-archive credential posture is UNSET / flushes are
being attempted and failing. Both are GATED on the archive-enabled lever —
archive_enabled=false is a supported posture and never pages.
SolEventArchiveSchemaRejected (warning): the sink refused a batch on a
schema error — the batch is acked/kept per the 4xx no-delete contract;
inspect the rejected event shape. SolEventArchiveOverflowDropped
(warning): the internal queue bound was hit and events were DROPPED (the
warned counter is the 80% early signal; this is the actual loss). SolEventArchiveQuarantineWriteFailed
(warning): an unencodable event could not reach the durable quarantine
dead-letter — the ack keeps refusing the page (no deletion), so the loss is
unaccounted until the disk write recovers; check the Mnesia-dir filesystem.
Live-ingress pressure: SolEventArchiveIngressDropped
(warning — metadata casts refused at the mailbox bound or the queue
overflowed; the live copy of ephemeral metadata is being lost while the
durable rows remain), SolEventArchiveQueueSaturated (warning — internal
queue >80% of 1000), SolEventArchiveMailboxSaturated (warning — gen_server
mailbox >80% of archive_mailbox_max). All three are gated on
sol_event_archive_enabled == 1. Check the Mango sink latency and the
flush error log.
curl -s http://127.0.0.1:21434/metrics | grep sol_event_archive
tail -n 200 /var/log/runit/zerg-sol/current | grep -i archive
Set the audit_archive_secret (the credential posture gauge flips to 1 on
the next scrape) and verify the sink is reachable. Failing flushes with a
configured secret mean the sink is down/full — check the sink volume and
network path; archived events remain quarantined locally until delivered.
Telemetry archive
SolTelemetryArchiveFailing: telemetry archive writes are failing —
observability telemetry is not reaching its durable sink.
curl -s http://127.0.0.1:21434/metrics | grep sol_telemetry_archive
tail -n 200 /var/log/runit/zerg-sol/current | grep -i telemetry
Check the telemetry sink path/credentials; the failure counter moving means the in-memory telemetry ring is the only copy — restart nothing until the sink is verified, or the ring’s tail is lost with the process.
Metrics blackout
Alerts: SolMetricsProtectedEvictionSkipped (the protected eviction pass was skipped), SolScrapeReaderTimeout (a bounded reader timed out and its family is last-known/absent), SolScrapeDeadlineExceeded (formatters were skipped after the whole-scrape deadline).
SolMetricsTableMissing (critical): the sol_metrics ETS table is
absent or metric writes are being dropped — the scrape still returns 200
while every ETS-backed counter is a catch-defaulted lie.
SolMetricsRestoreFailed: the counter dump restore failed, so monotonic
counters reset and rate/increase underreport this window.
SolScrapeSlow: a /metrics scrape has been over 2 s for 10 m — the
exporter is on a hot-path regression. SolMetricsPersistSlow: the
off-manager counter-dump tick has been over 5 s for 10 m (event delivery
is not blocked — the tick runs in the supervised metrics owner — but the
counter-reset window on the next restart grows). SolMetricsPersistFailing:
the dump could not be written at all (sol_metrics_persist_failures_total).
SolScrapeFamiliesMissing: sol_scrape_families_missing > 0 for 15 m —
the scrape rendered fewer families than the reviewed floor because a
formatter silently returned no families or crashed; compare
sol_scrape_families with sol_scrape_families_expected and check
sol_scrape_formatter_errors_total plus the formatter... crashed log
line.
The scrape/persist cost families are sol_scrape_duration_ms,
sol_scrape_formatter_over_budget_total,
sol_scrape_formatter_errors_total, sol_scrape_families,
sol_scrape_families_expected, sol_scrape_families_missing,
sol_metrics_persist_duration_ms,
and the cached-latency diagnostics sol_latency_summary_age_seconds /
sol_latency_summary_build_ms.
curl -s http://127.0.0.1:21434/metrics | grep sol_metrics_table
podman exec zerg-sol bin/sol remote # ets:info(sol_metrics).
tail -n 100 /var/log/runit/zerg-sol/current | grep sol_metrics
An absent table means a degraded boot (the owner/heir chain failed) —
restart Sol and verify sol_metrics_table_present 1 after boot. A
restore failure is quieter: counters restart from zero, dashboards show a
cliff, and the next successful persist tick rewrites the dump — note the
reset window when reading rates around it.
Security counters
The security-refusal family: SolWsOriginRefused (cross-site WebSocket
hijack gate), SolZmqCredentialRefreshRefused (a worker presented a
different credential while its stored one is still current),
SolPluginToolPermissionDenied (tool calls refused on authority class),
SolMemoryForbiddenWrites (write/delete gated on rows the caller does
not own). Each has a warning-rate alert AND an owned log line at the
refusal site.
curl -s http://127.0.0.1:21434/metrics | grep -E 'sol_(ws_origin_refused|zmq_credential_refresh_refused|plugin_tool_permission_denied|memory_forbidden_writes)'
A single blip is the gates working. A SUSTAINED rate is an actor: correlate the identity in the log lines (every refusal logs its caller), isolate the offender (revoke its enrollment key / session), and check the audited rows before re-admitting. Never widen a gate to silence these — the rate alert is the point.
Cost
SolCostBurnRate: token spend sustained above the configured ceiling
(20k tokens/min at the documented blended price — the threshold is
config-commented in sol-alerts.yml). SolInferenceBudgetExceeded: a
per-principal UTC-day spend or token budget refused an admission
(inference_daily_budget_usd / inference_daily_token_budget).
SolInferenceModelUnpriced: a USD-capped request targeted a model with no
server-side price while inference_unknown_price_policy=deny.
SolBillingLedgerReconcileMismatch (critical): the daily reconcile found
the durable event projection and the ETS ledger disagree — settled spend
is unauditable until repaired; capture both ledgers BEFORE restarting.
SolBillingSettlementFailures: a settlement write failed (usage
unattributed) or a settlement key was seen twice (double-charge risk).
curl -s http://127.0.0.1:21434/metrics | grep -E 'sol_model_tokens_total|sol_inference_spend_usd_total|sol_inference_budget_exceeded_total'
curl -s http://127.0.0.1:21434/api/v1/usage | jq .
Read the per-model breakdown from the cost panel (top models by token
rate) and /api/v1/usage for the per-principal totals: a runaway agent, a
retry loop, or a single tenant’s workload. The server-side price source is
sol_model_metadata (via sol_cost); unpriced models are counted in
sol_inference_model_unpriced_total and refused when a USD cap is active
under the default deny policy.
SolSyncForwarderPosture (warning): the durable-event sync forwarder is
NOT installed (sol_event_sync_forwarder_installed absent or 0 for 15m) —
inference.complete never reaches the durable event log, so the
spend-ledger boot rebuild reads an empty source and every sync-store
consumer is starved. The shipped posture is sync_enabled=true
. Check the boot log for the handler-install verdict,
confirm sync_enabled in the shipped config, and restart only after
recording the install failure; correct the config and redeploy if it is
the cause.
Memory & Mnesia durability
Heir/boot-plane alerts: SolEventsManagerAbsent (the event manager was absent and the event was shed), SolHeirOwnerClaimFailed (a restarted owner could not claim its table), SolHeirArmNonOwner (a transient caller attempted to arm a heir-held table). Inspect the boot-plane logs and the anchor/owner pids.
The memory plane and the Mnesia boot barrier:
SolMemoryPgSchemaNotReady / SolMemoryPgSchemaRefusals — the
additive user_uuid/version/epoch/metadata migration chain has not
completed. Memory writes are refused typed (store_unavailable) instead
of being acked into a WAL that cannot apply them. Check the pool
connectivity (memory_pg_url), the PG user’s ALTER privilege, and the
cleanup-tick retry warnings; the readiness datum is the
migration_status probe.
SolMnesiaTablesNotReady / SolMnesiaLoadBarrierPending — a disc
table did not load inside the boot bound (sol_mnesia_load_bound_ms,
default 15 s). The barrier’s CRITICAL line carries the per-table probes
(where_to_read / load_reason / load_node). A strict release boot
REFUSES with mnesia_durability_tables_not_loaded; a non-strict boot
serves the volatile tier. Do not force-load blindly: confirm the
local log is the authoritative copy first.
SolMnesiaForceLoadApplied — the ack-gated force-load lever
(mnesia_force_load_on_timeout, default off) resolved a stuck table.
Re-check that no other replica holds newer divergent writes.
Memory caps — memory_max_entries (ETS read model) and
memory_hydrate_max_entries (boot hydration) bound the process. The
owner evicts oldest-first up to memory_cap_eviction_budget per minute;
hydration_status/0 reports truncated=true when PG exceeds the bound.
Terminal-unconfirmed debt plane:
SolTaskTerminalDebtRecorded (critical) — a task terminal is
UNCONFIRMED: the ETS row served the boot but the durable leg failed, so
settlement and the task event are deferred to the reconcile debt. The
retained receipt + reconcile marker carry the recovery, but every
recorded debt is a disk/Mnesia-health signal — check
task_store_durable_write_failed_total for the root cause and the Sol
data-dir disk/Mnesia health.
SolTaskTerminalDebtReconciled (warning) — the reconcile completed
one or more of those debts (the owed task event was emitted and the
deferred settlement applied through the idempotent settle_worker_turn).
Expected only as the recovery arm of SolTaskTerminalDebtRecorded; a
persistent rate means the durable leg keeps failing.
SolTaskTerminalDebtSuperseded (warning) — a fresh confirmed
terminal superseded a stale terminal-unconfirmed debt: the task
re-executed (lost marker + retained receipt requeue) and the fresh
attempt owns the notification. Correlate each firing with the outbox
reconcile and the durable-write failures that seeded the debt; repeated
supersessions mean the receipt/terminal ordering is still unstable.
WILDZERG Runbook
The deploy / upgrade / rollback runbook for WILDZERG — the self-hosted, on-prem variant provisioned from the wild blueprint (runit + podman + OpenResty GitOps). This page describes the flow the CD actually executes; day-2 operations (incident response, monitoring, recovery) live in the Production Runbook.
The deployment model
Production WILDZERG runs on Debian 13 with runit supervision
(runit/sv/zerg-* services), podman containers (no Docker — Docker is
banned), and OpenResty for TLS. Deployment is GitOps: the state the
host runs is encoded in the wild repo’s runit/sv/$svc/env/IMAGE files. Crow
CI (.crow.yml, CROW_BACKEND=podman) is the autonomous CD pipeline:
a signed, semantic-version tag push (git tag -s vX.Y.Z) runs the full
build → gate → deploy → promote chain;
a main push runs only the build-side DRY-RUN lane (docs-hygiene,
fetch-grammars, build-images, build-reproducibility).
The wild repo (WILD_REF)
wild is a separate repository, not part of this tree:
Clone URL: https://git.zergs.net/spacebeam/wild.git
Pin semantics: the release pipeline clones wild pinned to the 40-hex SHA
in this repo’s ci/wild-pin (git clone … && git checkout $(cat ci/wild-pin)). Every wild clone in .crow.yml uses this form and fails
loudly on an unpinned clone; the release commit flips the pin, and a
placeholder pin fails on purpose.
Deploy-lane semantics: the deploy lane is
pinned too — before invoking the deploy script, deploy-staging resets
blue’s wild checkout to the ci/wild-pin SHA (git fetch origin && git reset --hard $WILD_REF), so a wild main push landing between the pin and
the deploy can never run scripts the release never validated. HEAD-tracking
returns only under the explicit operator override CROW_ALLOW_WILD_HEAD=1
(audited in the pipeline log).
The source of truth for wild’s own model (topology, provisioning scripts,
deploy paths) is wild/AGENTS.md inside that repo.
Install (first host)
Provisioning is wild’s job — do not hand-roll systemd units or manual
deploys on a production host (the systemd-era and on-host models ended with
the deploy decommission; deployment/ is archived). The flow:
- Clone wild at the pinned revision (
git checkout $(cat ci/wild-pin)) and followwild/AGENTS.md+wild/scripts/provision/for host provisioning (runit services, podman networking, OpenResty sites). - Provision PostgreSQL via wild’s
scripts/provision/create-postgres.sh; the legacy Docker-era Postgres is migrated, not copied. - Mirror branch protection: the required CI checks are mirrored on the
Forgejo repo by wild’s
scripts/provision/configure-zerg-repo.sh— the authoritative list isci/branch_protection_lint.pyREQUIRED_CHECKS. - One-time Crow prerequisites (top of
.crow.yml): enable thevolumesfeature for the repo,forgejo_tokensecret (Forgejo admin token), deploy key authorized on blue (port 122,/root/.ssh/authorized_keys), SSH config at/fun/secrets/crow/ssh-config(port 122, root user), registry auth at/fun/secrets/registry/auth.json.
These are wired by wild’s configure-crow-cd.sh.
5. Provision the minisign signing key for update-channel signing via
wild’s scripts/release/gen-minisign-key.sh (mounted read-only into
publish-release at /fun/secrets/minisign).
Provision (first deploy of a running stack)
WILDZERG is delivered as images, not source installs:
The CD builds 8 images (IMAGES="sol mango luna limon-web toronja-web starfruit-web docs-web cli") and pushes them to the internal registry
(registry.nonsense.ws, internal-only).
Services are the runit services zerg-sol, zerg-mango, zerg-luna
(+ openresty, grafana, forgejo, crow-server/crow-agent, tempo);
each runs a pinned image tag from runit/sv/$svc/env/IMAGE.
First deploy on a fresh host = run the same path the CD runs (see
Upgrade below) or follow wild’s provisioning scripts. If you must exercise
the deploy logic by hand, the entry point is
sh scripts/release/deploy-zerg.sh from the host’s own wild checkout
(reset to the pinned revision first: git fetch origin && git reset hard $(cat ci/wild-pin); CROW_ALLOW_WILD_HEAD=1 is the audited HEAD
override) — the script asserts the RUNNING
images match the committed env/IMAGE and owns verify + rollback.
Shipped state roots, transport default & restore
The release renders its state under the configured data root (the
standalone default is /var/lib/sol/data; a container boot derives it from
SOL_DATA_DIR): data_dir (Curve keyfile, scheduler store, managed
settings, provider key store), mnesia_dir (/var/lib/sol/data/mnesia),
mnesia_backup_dir (/var/lib/sol/data/mnesia_backups), and the audit
chain (/var/lib/sol/data/logs + /var/lib/sol/data/audit-data).
SOL_ZMQ_BIND_ADDR defaults to 127.0.0.1; a remote-worker fleet opts in
to 0.0.0.0 and then needs CURVE (automatic on a non-loopback bind) or an
explicit plaintext ack. A prod boot refuses blank SOL_AUTH_TOKENS,
SOL_MANGO_SERVICE_TOKEN, or (audit enabled) SOL_AUDIT_HMAC_SECRET —
server/rel/sol-preflight.sh fails first with the same reasons.
Backup is sol_mnesia_backup (never raw mnesia:backup); the artifact
bundle deliberately EXCLUDES the CURVE private key (SEC-X2), so reprovision
workers from sol_zmq_curve:provisioning_info/0 after a node rebuild.
Restore with Sol stopped via scripts/sol-restore.sh --sol-root /opt/sol yes (offline entry point — restore_latest/1 only exists in a running
app). Single order: Mango -> Sol memory PG -> Mnesia -> Luna -> the data_dir
operator copy set (see Backup & DR).
Upgrade
Upgrades are tag-triggered: push a signed semantic tag and Crow runs the chain. Everything between push and “new version live” is the pipeline:
Step (name in .crow.yml) | What it does |
|---|---|
verify-tag | Requires vX.Y.Z + git verify-tag (signed tag; GPG key baked into the build image). Untagged runs need CROW_ALLOW_UNTAGGED=1. |
docs-hygiene | Clones corp + wild (pinned), greps for banned words/dead claims; gates releases on doc truth. |
fetch-grammars | Regenerates tree-sitter grammars via wild’s scripts/release/fetch-grammars.sh (pinned clone). |
ci-status-check | Requires every branch-protection required check to be success at the tag commit. |
branch-protection-live | Diffs the LIVE forge branch-protection required-check set against ci/required_checks.sha256 (ci/required_checks_mirror_diff.py); a narrowed/hand-edited protection fails the release. Read-only FORGE_PROTECTION_TOKEN (falls back to FORGEJO_TOKEN). |
build-images | Builds the 8 images hermetically from the pinned wild checkout. |
build-engines | Builds the local-inference engine bundles (scripts/engines/build.sh); verifies the scp’d tarballs (sha256sum -c) before publish. |
supply-chain | Cosign/minisign + SBOM/attestation gates over the just-pushed digests. |
push-staging | Pushes a per-run EPHEMERAL tag only and records the per-image manifest digests to ci-digests.env (registry v2 API, ci/registry-digest.sh). No :<version>/:staging tag exists yet. |
build-reproducibility | Deterministic-build gate bound to the PUSHED bytes (_repro-shipped/). |
smoke-staging | End-to-end smoke against the staging stack. |
kill-proofs-check | Waits for the tag’s kill-proofs workflow run and requires the committed-TSV verdict + PASS floor (ci/kill_proofs_gate.py --wait-run, 120-min internal deadline). |
release-tag | Re-pulls every recorded digest, signs the DIGEST (not a mutable tag), runs ci/verify.sh --digest-only (cosign + mandatory attestation + trivy CRITICAL), then creates/pushes :<version> and moves :staging — each asserted against registry truth. |
deploy-staging | GitOps: for zerg-sol/mango/luna copies IMAGE → IMAGE.prev, writes the new version, pushes wild main; then on blue resets to the pinned wild revision (ci/wild-pin; CROW_ALLOW_WILD_HEAD=1 is the audited override), deploys by the resolved version, and verifies /api/v1/ready with automatic rollback on failure. |
heartbeat-probe | Runs check-alerting-provisioning.sh (env + canonical artifacts; Slack demoted only by the dated register row) and then heartbeat-probe.sh against the live Grafana: dead-man rules exist/evaluate/fresh, contact-point credentials, and severity=critical routes to the pager. |
relaunch-cluster | Deploys the pinned scripts to green/red, relaunches both nodes, and asserts the 3-node Erlang cluster (3/3). |
promote-prod | PURE TAG CEREMONY: captures the previous-good :prod digest per image from REGISTRY TRUTH into ci-prod-prev.env (a first promote needs CROW_ALLOW_FIRST_PROMOTE naming THIS run’s version), pulls each recorded digest, cosign-verifies post-pull, tags :prod, then asserts every :prod resolves to the recorded digest. A mid-loop failure restores the already-promoted images from ci-prod-prev.env. No :prod-prev tag exists. |
publish-release | Creates/updates the Forgejo release (wild’s release-notes.sh, idempotent) and uploads the redistributable assets (zerg CLI, luna, sol-<ver>.tar.gz, SHA256SUMS + minisign signatures) via wild’s publish-release.sh --version V --tag TAG. |
Operator trigger (manual): the tag push is the trigger; if you must run
the chain by hand, wild’s scripts/release/cd-trigger.sh on blue starts a
Crow run.
Rollback
Rollback exists at three levels:
- Automatic (deploy failure):
deploy-zerg.shverifies/api/v1/ready(19 subsystem checks — not the always-200/healthliveness) and flipsIMAGEback toIMAGE.prevfor the failed services, re-runs the deploy, and exits non-zero. - Automatic (promote failure): the already-promoted images are restored
to the digests captured in the pipeline workspace file
ci-prod-prev.env(registry truth — there is NO:prod-prevtag; retired ).scripts/release/promote-rollback-drill.shexercises the real restore path. - Manual (operator): on the host —
cp runit/sv/$svc/env/IMAGE.prev runit/sv/$svc/env/IMAGE, commit + push the wild flip, thengit pull --ff-only && sh scripts/release/deploy-zerg.sh, and verifycurl -sf https://api.nonsense.ws/api/v1/ready.
Mnesia data rollback is separate from image rollback: restores require Sol stopped and use the Mnesia backup path — see Backup & DR.
Day-2 operations
Liveness vs readiness: GET /health is the liveness probe;
GET /api/v1/ready runs 19 subsystem checks and returns 503 when degraded.
Maintenance mode: POST /api/v1/infra/maintenance/enable drains
traffic during deploys.
Monitoring: Grafana + Prometheus run as podman containers supervised by
runit; dashboards + alert rules are canonical in observability/ in this
repo — see the Production Runbook for
procedures.
Air-gap: WILDZERG is air-gap capable — see
Air-Gap Install.
What wild owns
The wild repo owns: the exact runit service definitions
(runit/sv/zerg-*/run), the OpenResty site configs
(runit/sv/openresty/conf/sites/*.conf), image entrypoints
(images/zerg/*/entrypoint.sh — sys.config/vm.args generation), the
provisioning script set (scripts/provision/) and the podman runner
settings (e.g. WILD_PODMAN_MEMORY). These are cited by name only — clone
wild and read it; do not infer specifics not visible here.
See also
Production Runbook — day-2 procedures (monitoring, troubleshooting, recovery, SLOs) Deployment — deployment options overview Backup & DR — full-state backup & restore Air-Gap Install — offline posture + egress gates
Engine reference — generated from the canonical engineering source. Do not edit this page by hand.
Backup & Disaster Recovery
Data-redundancy truth: clustering is NOT replication. Every durable Sol table is
disc_copieson the single local node (sol_event_store_owner.erlschema blocks); distributed Erlang in ZERG coordinates lanes/catalog/lease ownership, it never replicates storage. A node loss therefore loses that node’s event/task history back to the last Mnesia backup — the backup is a file-level timer (sol_mnesia_backup), and a “3-node cluster” still has a single-node durability story. Plan RPO from the backup interval, not from node count; the outbox/journal artifacts below are the in-flight safety net, not a substitute.
Backup and restore for the full state set of a Zerg deployment. The state lives in several places, each with its own tooling:
| State | Owner | Storage | Backup tool |
|---|---|---|---|
| Orchestration state (events, tasks, workflows, sessions metadata, projections) | Sol | Mnesia | sol_mnesia_backup (built-in, automatic) |
| Scheduled jobs | Sol | filesystem — <data_dir>/scheduler_jobs.json | file-level copy of the data_dir |
Sol durable artifacts: the audit JSONL chain + signed checkpoint, dispatch_outbox.journal, memory_wal/ segments (+ live.manifest), sync_event_shed.log (+ .replaying), the compactor staging set (.dump/.cursor/.count), the archive quarantine dead-letter and the event lane-spill file | Sol | filesystem | built-in: bundled into each sol_mnesia_backup artifact directory. The CURVE node private key is deliberately never bundled (SEC-X2); restore it from your secret store |
Remaining Sol data_dir files: zmq_replay_fence.term / zmq_replay_fence.journal / zmq_replay_fence.journal.prev, the enrollment key file(s) (zmq_enrollment.json / the locally-minted zmq_enrollment_local.json), scheduler_jobs.json / scheduler_jobs.journal, managed_settings.json, coordinator.json | Sol | filesystem | operator copy set: listed in the backup’s manifest.json omitted array (generated from sol_backup_manifest:omitted_paths/0 and pinned to this table by ci/manifest_omitted_parity_lint.py; the CURVE keyfile is excluded by design, SEC-X2); copy them with the data_dir (§5). The built-in bundle cannot carry them (live writers / node-identity material) |
| Memory/embeddings + Mango identity/auth | Sol + Mango | PostgreSQL (optional) / SQLite | pg_dump / sqlite3 |
| Worker sessions (JSONL + SQLite/FTS5), memory files, git snapshots | Luna | ~/.luna/ tree | file-level copy |
| Config + secrets | all | env/config files, /fun/secrets (wild) | config archive + rotation (below) |
Operator context: on a wild-managed host, “the Sol box” is the running
zerg-solpodman container on blue. Erlang-shell access to the live node is viapodman execinto that container (the archived on-host runbook’s remote-console section is historical — the oldsolctlscript was removed in ); image-level state (Mnesia data dir) is per-container storage owned by wild’s runit definitions — see the WILDZERG operator runbook.
1. Mnesia (Sol orchestration state)
Automatic: sol_mnesia_backup (server/src/sol_mnesia_backup.erl)
runs mnesia:backup/1 every mnesia_backup_interval seconds (default
3600 — ?DEFAULT_INTERVAL, line 68), FSYNCS the backup output before the
backup may report ok ( — mnesia_backup_ok=1 is never a page-cache
truncation lying in wait), prunes backups by AGE —
mnesia_backup_retention_days, default 7 (: the real
recovery horizon is the configured days) — with DATE-BUCKETED count
capping: every backup within the window survives, and
MAX_BACKUPS=5 is a PER-UTC-DAY cap (the newest 5 files of each day,
older same-day extras dropped with their manifests), never a global
post-prune cap. The previous global cap silently truncated the horizon
to ~5h at the default hourly interval while the docs claimed 7 days; the
per-day cap keeps disk bounded by days × 5 files without crossing a day
boundary. Each backup also gets a .manifest with per-table
record counts + a sha256 content checksum (checksum verified FAIL-CLOSED
at restore); each backup’s DATA FILE and its .manifest are optionally
copied to sol_mnesia_backup_remote_path (: the
destination is a DIRECTORY; the data file and its .manifest travel as a
pair in one rsync with --delay-updates, and the destination manifest is
pulled back and checksum-verified. A missing/mismatched manifest is a copy
failure — the offsite pair is accepted only after the manifest bytes verify;
an interrupted or partial pair is NOT claimed restorable. A local/mounted
destination is copied through fsynced temp names + atomic renames). An
offsite failure fails the backup for the SolMnesiaBackupFailed alert — the
local file stays intact; the caller ack is the pair, not the data file
alone. : a LOCALLY-MOUNTED destination is
pruned by Sol with the same age/per-day retention, and its free space is
probed (sol_mnesia_backup_offsite_free_bytes); a REMOTE destination cannot
be pruned by Sol, so mnesia_backup_offsite_lifecycle_managed=true attests
an external lifecycle policy — otherwise sol_mnesia_backup_offsite_managed
is 0 and SolBackupOffsiteUnmanaged pages.
** (EV-18) artifact bundle.** Every backup carries a
<backup>.artifacts/sibling: the auditaudit-*.jsonlfiles
- the signed
audit-chain.checkpoint(and.audit_seq/.audit_sigwhen present),dispatch_outbox.journal, thememory_wal/segments +live.manifest,sync_event_shed.log, the event-lane spill file, the compactor staging set (.dump/.cursor/.count) and the archive quarantine dead-letter — each copied 0600 with a sha256manifest.json. The compactor staging/lane-spill/quarantine files live under the Mnesia directory and hold events already deleted from Mnesia, so they are exactly the mid-archive window a Mnesia-only restore used to lose. The manifest also records the operatoromittedcopy set (the node-identity/live-writer files in the table above), so a restore never assumes completeness.Consistent cut. The writer flushes the audit chain and the memory WAL, takes a durable audit cut (
sol_audit_log:snapshot_cut/0— flush + signed checkpoint), copies the sources, then re-reads the live checkpoint and RETRIES the cut when a flush raced the copy. The anchoredcut_seqis stamped in the artifactmanifest.json. At restore a bundle whose copiedaudit-chain.checkpointis AHEAD ofcut_seqis REFUSED ({error, {backup_cut_ahead, Cp, Cut}}) unless the operator accepts it with--allow-cut-mismatch(CRITICAL + degraded verdict, never silent). Acut_seq: nullmanifest is a legacy/chain-less bundle. The CURVE node private key (curve_server.cert) is deliberately NEVER bundled (SEC-X2 — a backup copy must not carry the node identity secret); reprovision workers withsol_zmq_curve:provisioning_info/0after a node rebuild. The destructive restore re-materializes the bundle only when called withrestore_artifacts => true(the offline entry point defaults it ON); every hash is verified before a file is written to its CURRENT configured destination. A clean restore leaves the audit chain verifiable against its restored anchor (sol_audit_log:verify_integrity_anchored/0). The bundle is local to the backup directory — ship it offsite with the backup file in the composite procedure (§5).
Retention drill (executable):
scripts/backup-retention-drill.sh --sol-root /opt/sol \
backup-dir /tmp/zerg-retention-drill
It builds a >5-bundle fixture and runs the real rotate_backups/1:
the 10-day-old backup + bundle are pruned, 6 same-day backups leave the
newest 5, each kept backup’s .artifacts/ survives, and unparseable
legacy names are capped at 5. The drill’s legacy leg is the proof
that .artifacts DIRECTORIES are not retention entries:
sol_mnesia_backup:rotate_backups/1 filters .manifest/.artifacts and
requires regular files, and the drill PASSES on that corpus.
Bundle dirs are deleted with their parent.
Backup directory resolution (lines 92-109), in order:
- config
mnesia_backup_dir— honored only when set (set it ABSOLUTE; sys.config ships an anchored/tmp/sol/mnesia_backupssince then a CWD-relative value here silently orphaned backups on a different-CWD restart); <mnesia_dir>/backups— the anchored default (under the Mnesia data dir; the old CWD-relativepriv/mnesia_backupsdefault was removed in Because a container restart from a different CWD silently orphaned backups).
Manual backup (live node, Erlang shell):
sol_mnesia_backup:backup(). %% returns {ok, Filename}
sol_mnesia_backup:list_backups(). %% {ok, [FullPath,...]} — newest last
Restore (requires Sol stopped; the restore clears and recreates the disc tables so the backup IS the state — semantics; since RAM-FALLBACK tables are cleared too, so a degraded boot cannot silently merge and resurrect deleted rows).
restore_latest/1 is a gen_server call into the backup process — it
only works while the Sol application is running. The previous runbook
said “stop Sol” and then called it, which was unrunnable. Use the
offline entry point; it boots a minimal BEAM (Mnesia + the backup server
only, under the release schema’s node name), runs the restore, prints the
typed verdict, and exits non-zero unless {ok,...}:
# Sol must be stopped (Mnesia holds an exclusive lock on its directory).
scripts/sol-restore.sh --sol-root /opt/sol --yes
--yes skips the interactive confirmation; the script otherwise prints
the target node/config/Mnesia/backup paths and asks for restore. Options:
--mnesia-dir, --data-dir (artifact destination), --backup-dir,
--config, --no-artifacts, --spill-receipts. The same documented
command is exercised by scripts/restore-drill.sh against a scratch data
root. Raw mnesia:backup output has no manifest and is REFUSED by the
restore (below) — always back up through sol_mnesia_backup:backup/0.
Verification is automatic and TWO-LEGGED: a pre-flight checksum check
refuses the restore BEFORE any live table is touched (truncated/tampered
backups never destroy anything), and the post-restore table counts are
compared against the manifest with a 5% tolerance. The outcome is
surfaced as restore_verified / restore_mismatch events (never
swallowed — a drifted restore fails loudly). A live restore also rebuilds
the RAM projections (sol_sync_event:rebuild_projections).
** breaking change:** a backup with NO manifest now REFUSES to restore ({error, manifest_missing}) — an unmanifested backup is a failed backup. Since a manifest-less artifact cannot be produced (a Mnesia-not-running backup fails loudly with {error, mnesia_not_running}); if you hold a previous manifest-less relic, take one fresh backup after upgrading.
Restore order: stop EVERY writer,
then restore Mango (identity) -> Sol memory PostgreSQL -> Mnesia ->
Luna trees -> Sol data_dir operator copy set. Mnesia is restored after
Mango because restored task/session rows carry user_uuid references to
Mango accounts; it is restored before Luna so a re-registering worker sees
its restored workspace. §5 uses this same order — there is no second
variant.
2. PostgreSQL (Mango auth + Sol memory) / SQLite (Mango)
Mango uses one storage backend for identity, RBAC, audit and token state:
Default SQLite: sqlite:///data/mango.db (mango/mango/conf.py:40).
PostgreSQL: MANGO_DB_URL or the MANGO_DB_HOST/PORT/NAME/USER/PASSWORD
variables (conf.py:123-139). Schema is migration-managed
(mango/mango/migrations/v0001_initial_baseline.py + the migration
runner), so a restored schema must not be partially migrated.
Backup commands:
# SQLite backend — online-safe hot copy (safe during operation):
sqlite3 /opt/sol/mango/data/mango.db ".backup '/backup/mango-$(date +%F).db'"
# PostgreSQL backend:
pg_dump -h "$MANGO_DB_HOST" -U "$MANGO_DB_USER" -d "$MANGO_DB_NAME" \
-Fc -f "/backup/mango-$(date +%F).dump"
Restore:
# SQLite: STOP Mango first (sv stop zerg-mango on wild) so no WAL/page
# cache survives the file swap. sqlite3's `.backup` produces a
# transactionally consistent file; the -wal/-shm siblings belong to the
# LIVE database and must never be replayed against a restored file:
sv stop zerg-mango
rm -f /opt/sol/mango/data/mango.db-wal /opt/sol/mango/data/mango.db-shm
cp /backup/mango-<date>.db /opt/sol/mango/data/mango.db
sqlite3 /opt/sol/mango/data/mango.db 'PRAGMA integrity_check;' # must print ok
sv start zerg-mango
# PostgreSQL: STOP/quiesce every Mango writer first (sv stop zerg-mango),
# then restore — `--clean` DROPs and recreates objects; a live writer can
# race the DROP and hold locks:
sv stop zerg-mango
pg_restore --clean --if-exists -d "$MANGO_DB_NAME" /backup/mango-<date>.dump
psql -d "$MANGO_DB_NAME" -c 'SELECT count(*) FROM users;' # sanity
sv start zerg-mango
Sol memory/embeddings (sol_memory_pg, server/src/sol_memory_pg.erl)
is a separate PostgreSQL database when memory_pg_enabled and
memory_pg_url are configured (lines 102-103; the table carries a
user_uuid column migrated at pool start, line 127):
# SOL_MEMORY_PG_URL is the SAME connection URL configure(d) for
# memory_pg_url; pg_dump accepts a connection URI directly (the previous
# runbook called an undefined extract_db_from_memory_pg_url helper). Export
# it from the Sol env (0600) — never inline a password on the command line:
pg_dump -d "$SOL_MEMORY_PG_URL" -Fc -f "/backup/sol-memory-$(date +%F).dump"
# Restore with Sol stopped (the memory pool must not write during it):
pg_restore --clean --if-exists -d "$SOL_MEMORY_PG_URL" \
"/backup/sol-memory-<date>.dump"
The Mango database backup includes the event-archive table
(audit_events) — its own age-retention job and alert are documented in
audit-retention.md §“Archive store”; a first prune
is destructive, so take the database backup before running it.
If both Mango and memory use one PostgreSQL instance, one pg_dump
per database (never one dump of postgres covering both) keeps restores
independent.
3. Luna worker state (~/.luna/ tree)
Each Luna worker host keeps its sessions and memory on the worker machine — they are not replicated by Sol:
| Artifact | Path | Source |
|---|---|---|
| Session transcripts (JSONL, fsynced appends) | ~/.luna/sessions/session.jsonl (per-session files under ~/.luna/sessions/) | client/core/session.lua — the append/save fsync discipline |
| Session search index (SQLite + FTS5, dual-write) | ~/.luna/sessions.db (override: LUNA_SQLITE_PATH) | client/core/session_backend.lua:18 |
| Session index (JSON) | ~/.luna/session_index.json | client/core/session_index.lua:3 |
| Memory (file/vector/hybrid) | ~/.luna/memory* | client/core/memory_file.lua et al. |
| Git auto-snapshots | refs/luna-snapshot/* in each workspace repo (24h cleanup) | client/core/git_snapshot.lua:260-294 |
Backup = consistent file copy:
# Stop the worker first (dual-write consistency), then:
rsync -a ~/.luna/ /backup/luna-$(hostname)-$(date +%F)/
Restore = copy the tree back onto the worker host and restart; sessions
resume by id (zerg/Luna --resume-latest / Limon chat session id), and
the SQLite FTS index rebuilds under the staleness gate on open
. Git snapshots are per-repo refs — included only
if the workspace repos are backed up too.
4. Config, secrets & keys
Sol config archive: server/scripts/backup-config.sh [--remote=DEST]
archives the checkout config, the ACTUAL prod release config
(_build/prod/rel/sol/releases/<vsn>/), and /etc/sol/{sol.conf,env}
into a 0600 archive. Secret-bearing files require --encrypt=RECIPIENT
(GPG); --remote without a destination or a failed rsync is a hard
failure. See docs/production-runbook.md §Config Backup.
Secret inventory (all on blue under /fun/secrets/ on wild hosts,
plus container env files):
Crow: forgejo_token, deploy key + ssh-config, registry auth
(the .crow.yml env: block);
minisign update-signing key: /fun/secrets/minisign — provisioned by
wild’s scripts/release/gen-minisign-key.sh (the minisign signing step);
Mango MANGO_DB_PASSWORD (required for remote PG, conf.py:131);
Sol SOL_ZMQ_WORKER_SECRET / per-worker enrollment keys (zmq-security);
Forgejo admin credentials + INTERNAL_TOKEN/SECRET_KEY/DB password —
rotation covered by docs/forgejo-admin.md (§credential rotation).
Rotation: the legacy in-tree deployment/scripts/rotate-credentials.sh
is archived with the model; the wild repo owns the live rotation
scripts (scripts/rotate-postgres-password.sh is the migration-manifest
replacement — deployment/README.md:20). The zerg-cli update channel’s
TOFU pin (~/.config/zerg/trusted-key) re-pins deliberately via
zerg update trust-key <minisign.pub> (see docs/cli-reference.md
§Updates) — a signing-key rotation MUST be published with the matching
minisign.pub asset on the release.
Recovery plan (fastest path per failure)
| Failure | Restore steps | Verify |
|---|---|---|
| Sol node loss | Redeploy image; stop Sol; run scripts/sol-restore.sh --sol-root /opt/sol --yes | {ok, {restored, N}} verdict + restore_status.json; /api/v1/ready 200 |
| Mango DB loss | Restore SQLite file or PG dump, restart zerg-mango | zerg login with an existing account |
| Memory PG loss | pg_restore sol-memory dump | vector search returns results |
| Luna host loss | Replace worker; restore ~/.luna/ tree | session list + search work; worker re-registers via ZMQ |
| Update botched | zerg update rollback (zerg-cli) or the IMAGE flip (see runbook) | /api/v1/health + zerg update check |
5. Composite DR (multi-store quiesce + dispatch-receipt spill)
A single-store restore is not enough once tasks are in flight: Sol state (Mnesia), Mango (PG/SQLite), Sol memory (PG) and the Luna trees advance independently, and a destructive Mnesia restore clears the dispatch outbox — the durable acknowledged-in-flight task receipts ( ). The composite procedure, in order:
- Quiesce writers (operator command). Pause the scheduler and drain
workers before any backup — the composite quiesce command, scheduler
pause and Mango snapshot marker are provisioned by the wild runbook
(handoff G9; wild-pending — check the operator host before relying on
it). Until the command is available, pause jobs via the scheduler API
and wait for
in_flight = 0. - Back up each store (Sol/PG/Luna per §1–§3). The built-in
sol_mnesia_backupartifact bundle carries the audit JSONL chain (see the retention warning below),dispatch_outbox.journal,memory_wal/segments,sync_event_shed.log, the compactor staging set, the archive quarantine dead-letter and the event-lane spill — ship the<backup>.artifacts/directory with the backup file. The operator copy set (scheduler_jobs.json,zmq_replay_fence.term/journal, the enrollment key file(s) includingzmq_enrollment_local.json,managed_settings.json,coordinator.json) is listed in the bundle manifest’somittedarray — copy those from the data_dir yourself. Audit retention is destructive with NO archive leg: the daily sweep deletesaudit-*.jsonlolder thanaudit_retention_days(default 30) and nothing archives them first — back up the JSONL chain yourself (or raise the retention) before that horizon matters to you. The Mangoaudit_eventsarchive has its own age retention (docs/audit-retention.md§Archive store) and is part of the Mango database backup. - Restore with the stores down, in the §1 order: Mango (identity) ->
Sol memory PG -> Mnesia (
scripts/sol-restore.sh --sol-root /opt/sol yes) -> Luna trees -> the Sol data_dir operator copy set. The restore walks candidates newest→oldest and picks the first VERIFIED one (manifest readback + sha256 + image decode; ). A manifest-less partial newest file is quarantined to<backup_dir>/quarantine/(kept, never trusted) instead of blocking every retry;--backup PATHrestores one explicit artifact and--previousskips the newest candidate. When thesol_dispatch_outboxis non-empty, the Mnesia restore refuses by design with the typed{error, {outbox_nonempty, N}}: the receipts would evaporate silently otherwise. - Spill the receipts deliberately. Pass
--spill-receiptsto the offline entry point (the restore maps it tosol_mnesia_backup:restore_latest(#{spill_receipts => true})) — the receipts are exported to one durable file before the destructive clear and re-imported after it; the gateway’s live reconcile then requeues them at-least-once (the same idempotency key dedupes any duplicate delivery). Verify with therestore_verifiedevent and the outbox row count before and after. - Converge and verify. Let the cluster catalog/inventory converge then run the §Recovery-plan verify column for every store.
The outbox refusal is loud (CRITICAL log + typed error) — never bypass it by deleting outbox rows to force a restore; that is data loss with extra steps.
Composite drill (executable): scripts/composite-restore-drill.sh
builds a real bundle (Mnesia task/terminal rows + a completed HMAC audit
chain + dispatch_outbox.journal, backed up by the production
sol_mnesia_backup, plus a migrated Mango SQLite snapshot taken with
sqlite3’s backup API), restores Mnesia through scripts/sol-restore.sh and
the Mango file-swap, then asserts the same terminal task rows, audit chain
and Mango users/tokens/audit state. It also corrupts the Mnesia backup and
the Mango snapshot separately and requires a fail-closed refusal from each.
scripts/composite-restore-drill.sh \
sol-root /opt/sol \
schema-from /var/lib/sol/data/mnesia \
bundle /backup/zerg-composite-<date> \
scratch /tmp/zerg-composite-restore
Without --bundle it builds its own real fixture (the CI smoke gate). An
operator bundle needs --schema-from (a bootstrapped Sol Mnesia dir): a
real restore destination is a node that already created the table
definitions. The drill clears the destination tables before the restore, so
a no-op restore cannot pass.
Tested / untested
The Mnesia path is exercised by eunit + the documented restore-verification
flow (server/test/sol_ets_table_ownership_tests.erl calls
sol_mnesia_backup:backup), and the OFFLINE restore command above is
executed by scripts/restore-drill.sh (scratch data root; asserts the
verdict, materialized tables, the durable restore_status.json and the
artifact re-materialization). The composite Sol+Mango+outbox/audit path is
executed by scripts/composite-restore-drill.sh (wired into the required
tri-service smoke step via tests/smoke/test_restore_and_upgrade_drills.py).
Retention is exercised by
scripts/backup-retention-drill.sh (age prune, per-day cap, bundles
deleted with their parent, legacy cap ignores .artifacts dirs). The
PostgreSQL/SQLite/Luna paths use standard tooling (pg_dump,
sqlite3.backup, rsync) — validate your restore procedure in a staging
copy of your fleet, quarterly.
See also
WILDZERG runbook — the deploy/rollback flow that pairs with
this page
docs/production-runbook.md — monitoring, incident response, SLOs
docs/security.md — secrets posture, trust plane
docs/forgejo-admin.md — Forgejo backup/restore/rotation
(the git forge itself, separate from the state above)
Engine reference — generated from the canonical engineering source. Do not edit this page by hand.
Upgrade and rollback (the recorded contract)
The contract is recorded in
ADR-0016. This page
is the operator half: the exact commands, the exact Mango ack, and the
non-claims. The drill is
scripts/upgrade-rollback-drill.sh (wired into the tri-service CI job via
tests/smoke/test_upgrade_rollback_drill.py).
Non-claims (ADR-0016 U1–U7)
No hot code upgrade. server/src/sol.appup is an unsupported stub;
code_change/3 callbacks carry no state migration. An upgrade restarts the
service.
No zero-downtime claim. The coordinator is stop-the-world; a release
restart interrupts in-flight HTTP/SSE/chat, re-registers workers and fails
live workflows per the workflow-restart contract.
No HA/failover claim. Node loss is data loss within the backup window
(disc_copies is [node]).
Rollback is redeploy + health verification, with a data restore when the
schema moved. Mango migrations are forward-only: a migrated database
rolls back only through a verified snapshot/restore or the explicit
controlled-downgrade ack below.
Wire skew is not uptime. N/N−1 frames are accepted for the documented
window; a Luna downgrade against an older Sol is stop-then-upgrade.
Sol release upgrade
Production upgrades are wild-owned image replacements (Crow CD). The
standalone helper (server/scripts/upgrade.sh) is for the archived
systemd/standalone model and performs the same contract:
server/scripts/upgrade.sh /path/to/sol-<version>.tar.gz --root /opt/sol
It requires a checksum sidecar (<tarball>.sha256 or SHA256SUMS), validates
archive entries, captures the old version, installs the release payload
(stop-the-world file install — no relx hot upgrade), restarts the service and
requires /api/v1/health 200. A failed health check re-installs the captured
old release and re-verifies it (exit 2 = rollback verified; exit 3 = manual
action required). --no-restart reports an INSTALLED-ONLY verdict (exit 4)
and never claims the new release is running.
Controlled rollback drill (no live service, real release packet pair):
scripts/upgrade-rollback-drill.sh \
sol-root server/_build/prod/rel/sol \
scratch /tmp/zerg-upgrade-rollback
It derives an N-1 packet from the shipped release tree, fresh-installs it,
upgrades to N, rolls back to N-1, and asserts start_erl.data, bin/sol and
lib/sol-<vsn>/ebin/sol.app at every step. The Mango leg (below) runs in the
same drill.
Mango migrations (forward-only + schema-ahead gate)
Mango records applied versions in schema_migrations and applies pending
up(db) modules in order. There are no down-migrations. A newer database
meeting an older image refuses at boot:
schema version N is NEWER than the newest migration this tree ships (N-1) —
refusing to run an OLDER image against a NEWER schema (DC-03). Restore the
matching image, or explicitly acknowledge the controlled rollback with
MANGO_ALLOW_SCHEMA_AHEAD=1.
The exact ack is the environment variable:
MANGO_ALLOW_SCHEMA_AHEAD=1
With the ack the older image boots against the newer schema, logs a CRITICAL
line, and undoes nothing (the schema stays at N; the older code must be
compatible with it). The SAME ack is honored by /ready (
): an acknowledged older image serves 200 with
"schema_ahead": "acked" in the loopback readiness census instead of the
permanent schema_ahead 503 the pre-fix shape answered — the rollback lever
is now usable for traffic, not just for boot. Without the ack, /ready
keeps answering 503 schema_ahead. Do not use the ack unless you have a verified backup and
accept the forward-only window. The preferred rollback across a schema move is
a restore of the pre-migration Mango backup (see
Backup & DR).
The drill proves: a missing ack refuses typed, the ack downgrade keeps schema/data/auth rows, and a deliberately broken migration reds and leaves the recorded version untouched (transactional apply).
Compatibility window to watch
Mango v0013 (tokens.seq NOT NULL) is the recorded example: a pre-v0013
writer against a post-v0013 schema fails on the first write. Rolling back
across a migration requires the ack and a reviewed compatibility note; the
safe path is the pre-migration snapshot.
See also
ADR-0016 — upgrade/rollback + config authority Backup & DR — composite restore and the drill Production runbook — wild’s multi-node roll
Engine reference — generated from the canonical engineering source. Do not edit this page by hand.
Observability: Metrics, Alerts & Ops Queries
The canonical alert source is observability/grafana/alerting/sol-alerts.yml;
dashboards live in observability/grafana/dashboards/. The metric-family
whitelist (ci/metrics_whitelist.generated.txt) is generated from the real
emit sites and enforced bidirectionally against alerts and dashboards.
Cost & spend
| Family | Type | Consumer |
|---|---|---|
sol_inference_spend_usd_total{model} | counter | SolCostBurnRate (USD/min), spend panel |
sol_inference_tokens_input_total{model} | counter | spend panel |
sol_inference_tokens_output_total{model} | counter | spend panel |
sol_inference_spend_today_usd / sol_inference_spend_today_tokens | gauge | spend panel |
sol_inference_daily_budget_usd / sol_inference_daily_token_budget | gauge | spend panel |
sol_inference_budget_exceeded_total{axis} | counter | SolInferenceBudgetExceeded, spend panel (axis = tokens/usd/unpriced) |
sol_inference_model_unpriced_total{model} | counter | SolInferenceModelUnpriced, spend panel |
Alerts:
- SolCostBurnRate —
sum(rate(sol_inference_spend_usd_total[5m])) * 60 > 0.72for 15m. Settled USD (real model rates), not a token proxy; retune the threshold to the deployment’s fleet spend ceiling. - SolInferenceBudgetExceeded — any
increaseof the refusal counter in 10m. The refused principal is in the response body, not the metric (labels stay bounded). - SolInferenceModelUnpriced — unpriced settlements in 30m. Add rate metadata
or set
inference_unknown_price_policy=deny.
Ops queries:
# USD/min, fleet + top models
sum(rate(sol_inference_spend_usd_total[5m])) * 60
topk(5, sum by (model) (rate(sol_inference_spend_usd_total[5m])) * 60)
# how close is today to the configured caps?
sol_inference_spend_today_usd / sol_inference_daily_budget_usd
sol_inference_spend_today_tokens / sol_inference_daily_token_budget
# refusals + unpriced models
sum by (axis) (increase(sol_inference_budget_exceeded_total[1h]))
sum by (model) (increase(sol_inference_model_unpriced_total[1h]))
Per-principal detail is the read surface, not a metric label:
GET /api/v1/usage (self; admin ?user_uuid=). See
cost.md.
Provider pool
| Family | Type | Meaning |
|---|---|---|
sol_provider_pool_keys{provider,state} | gauge | Keys by active / cooldown / unavailable |
sol_provider_pool_headroom{provider} | gauge | Drawable keys (capacity − cooldown − unavailable) |
sol_provider_pool_cooldown_seconds{provider} | gauge | Max remaining cooldown |
sol_provider_pool_usage_total{provider} | counter | Cumulative draws |
sol_provider_pool_errors_total{provider} | counter | Cumulative error reports |
Alert: SolProviderPoolHeadroomZero — sol_provider_pool_headroom == 0
for 10m (a provider with configured keys has no drawable key).
Ops query (Erlang shell) — the same projection the exporter renders:
sol_provider_pool:stats().
%% #{generated_at_ms := …, providers := [#{provider := …,
%% keys_total := N, keys_active := A, keys_cooldown := C,
%% keys_unavailable := U, cooldown_count := C, max_cooldown_seconds := S,
%% capacity := N, headroom := A, usage_total := …,
%% error_total := …, draw_epoch := …, error_epoch := …}],
%% totals := #{…}}
draw_epoch / error_epoch are the max monotonic stamps per provider —
they make the stale-success fair-clear auditable: a success only
clears errors that predate its own draw epoch. Per-key detail remains
sol_provider_pool:list_keys(Provider) and
sol_provider_pool:circuit_report(Provider).
FIM completion plane
POST /v1/completions resolves a fim lane and calls its internal
/infill. These families keep the editor class observable without exposing
the lane endpoint:
| Family | Type | Meaning |
|---|---|---|
sol_lane_completion_latency_seconds{lane} | histogram | Completion round-trip (cumulative buckets, one sample per served request) |
sol_lane_completion_inflight | gauge | Completion requests currently on a lane |
sol_lane_completion_queue | gauge | Completion requests awaiting lane admission |
sol_lane_completion_cold_starts_total{lane} | counter | Cold-lane starts triggered by a completion request (lane_warming responses) |
sol_lane_completion_refused_total{reason} | counter | Typed refusals (fim_unsupported, lane_busy, queue_full, lane_warming, upstream_error, …) |
Alert: SolLaneCompletionDegraded — completion p95 above 1.5 s, or any
non-lane_warming refusal in 10m. The lane’s own /infill stays internal;
an upstream infill failure surfaces as lane_rejected/lane_unavailable
and counts under reason="upstream_error".
Ops queries:
histogram_quantile(0.95, sum by (le) (rate(sol_lane_completion_latency_seconds_bucket[5m])))
sum by (reason) (increase(sol_lane_completion_refused_total[15m]))
sol_lane_completion_inflight
sol_lane_completion_queue
ZMQ singleton mailbox depths
The three singleton mailbox depths the scale-concentration S-rate trigger
reads. The gateway depth is stamped by the live gateway; the dispatcher and
task-store depths are scrape-time process_info/2 reads (0 when the
process is not running).
| Family | Type | Source |
|---|---|---|
sol_zmq_gateway_mailbox_depth | gauge | gateway check_liveness + per-frame stamp |
sol_zmq_dispatcher_mailbox_depth | gauge | sol_zmq_recv_dispatcher live mailbox |
sol_zmq_task_store_mailbox_depth | gauge | sol_task_store live mailbox |
Ops query — the S-rate qualifying condition (≥ 2 of 3 above 5k for 15m):
count(
(max_over_time(sol_zmq_dispatcher_mailbox_depth[15m]) > 5000)
or (max_over_time(sol_zmq_gateway_mailbox_depth[15m]) > 5000)
or (max_over_time(sol_zmq_task_store_mailbox_depth[15m]) > 5000)
) >= 2
Decision context: plan/zmq-sharding-design.md (, NO-ADOPT production
sharding — trigger-gated), plan/task-store-writer-sharding.md (,
NO-ADOPT — same triggers), plan/event-group-commit-evaluation.md (,
NO-ADOPT). The pre-approved O(1) ready-ring is landed in
sol_zmq_worker_manager:find_ready_worker/3.
Incident response
This is the first-15-minutes playbook. The exhaustive procedures live in the Production runbook and the alert-linked sections it contains.
First 5 minutes
- Confirm blast radius. Is the control plane down, a single worker, one provider, or one workflow?
- Check readiness, not just liveness.
curl -fsS http://127.0.0.1:21434/health curl -fsS http://127.0.0.1:21434/ready zerg doctor - Check worker registration and queues.
zerg zmq-workers zerg agents zerg ps - Check provider health and circuits.
zerg circuits - Preserve evidence before restarting. Capture logs and a support bundle:
zerg support-bundle /tmp/zerg-support-$(date +%s) --log-dir <log-dir>
Symptom → action
| Symptom | Likely cause | First action |
|---|---|---|
/ready fails, /health passes | Event store, projection, or Mango dependency unhealthy | Read the readiness payload; do not restart blindly |
| Workers disappear repeatedly | Enrollment/key mismatch, duplicate identity, or network | Check sol_zmq_registration_refused_total{reason} and the worker log |
| Tasks stay pending | No READY worker, model lane down, or dispatch outbox blocked | zerg zmq-workers, zerg ps, inspect the model lane |
| Provider errors spike | Key exhaustion, circuit open, or upstream outage | zerg circuits, check provider keys and fallback chain |
| 5xx rate rises | Handler crash or dependency failure; 500 is never expected | Inspect Sol logs and the failing route; capture a support bundle |
| Mango login 503 | Mango down, migrating, or database unreachable | Check Mango /health and its database |
| Disk pressure | Event store, logs, or backups | Check the disk tier alerts; prune only through the documented retention path |
Escalation
Sev-1: control plane cannot serve any authenticated request, data loss risk, or a security boundary failure. Page the on-call owner and freeze deploys. Sev-2: one worker class, one provider, or one workflow family degraded. Mitigate with failover; schedule the root-cause fix. Sev-3: cosmetic, documentation, or single-tenant annoyance. Track it.
After the incident
Write a timeline with the exact commands and outputs. Identify the detection gap (which alert should have fired?). Add a regression test at the system boundary. Update the runbook and the alert link in the same change.
Next
Production runbook Observability Troubleshooting Backup & DR
Key and secret rotation
Every credential in ZERG has an owner, a storage location, a rotation procedure, and a verification step. Rotate one class at a time and verify readiness after each.
Inventory
| Secret | Used by | Storage | Rotation impact |
|---|---|---|---|
| ZMQ CURVE server key | Sol ROUTER/PUB | <data_dir>/curve_server.cert (auto-generated) | All workers must trust the new key; coordinate a fleet window |
| Worker enrollment keys | Sol ↔ Luna READY | zmq_enrollment_keys / wild provisioning | Per-worker; rotate one worker at a time |
| Fleet secret (legacy) | Sol ↔ Luna | SOL_ZMQ_WORKER_SECRET | Only valid while zmq_fleet_legacy_compat is open; do not use for new fleets |
| Mango bridge HMAC | Mango → Sol events | MANGO_BRIDGE_HMAC_SECRET on both sides | Restart the bridge; replay window rejects stale frames |
| Mango audit chain key | Mango audit rows | MANGO_AUDIT_CHAIN_SECRET (+ prior keys) | Keep prior keys for verification across the boundary |
| Sol audit HMAC | Sol audit JSONL | audit_hmac_secret | Keep the old key available to verify historical logs |
| Provider keys | Sol provider pool | Env (api_key_env) or encrypted pool (provider_keys.bin) | Add new key, drain old key, then remove |
| TLS certificates | OpenResty / Mango edge | wild-managed | Reload the proxy; verify with openssl s_client |
| Minisign release key | Release artifacts | wild /fun/secrets/minisign + ci/minisign-pub-fingerprint | Release-act change: update pin, status, expiry together |
Procedure (generic)
- Stage the new secret without removing the old one.
- Restart or reload the consumer and confirm it is using the new value (log line or metric).
- Verify the dependent path end-to-end (worker READY, event delivered, login succeeds, artifact verifies).
- Remove the old secret after the verification window.
- Record the change in the audit log and the release notes.
Specific notes
CURVE: a worker that cannot verify the server key fails closed. Never disable CURVE to “fix” a rotation; fix trust.
Enrollment keys: a key bound to a worker_id cannot register as another worker. Revoke first, then re-provision.
Audit chains: verification accepts prior keys by epoch; a missing prior key produces a typed verdict, not a false pass.
Provider pool: the pool file is part of the data-dir backup scope. A corrupt store fails open loudly — treat it as an incident.
Minisign: rotation is a reviewed release commit; a lapsed expiry fails the release lane.
Verification checklist
[ ] zerg doctor is green.
[ ] zerg zmq-workers shows the expected fleet.
[ ] A task completes end-to-end.
[ ] /ready passes.
[ ] Audit verification passes (/api/v1/audit/verify for Sol; Audit.verify_integrity for Mango).
[ ] The old secret is removed from the host and the backup scope is updated.
Next
Security model ZMQ security Audit retention Release process
Engine reference — generated from the canonical engineering source. Do not edit this page by hand.
Air-Gap Install Walkthrough
Installing and running Zerg (WILDZERG) on a network that cannot reach the internet. This is the real walkthrough promised by the old one-paragraph deferrals in docs/getting-started.md and docs/cli-reference.md (replaced by this page).
What “air-gapped” means here
All inter-service communication stays inside the cluster network; no external DNS or API calls are required (docs/security.md §Air-Gapped Deployment). The only opt-in egress points, each individually gateable
| Egress point | Gate | Default | Set to 0/false for |
|---|---|---|---|
| LLM provider endpoints (by design) | provider config (per-provider key + base URL) | on | point providers at a local model server instead (see below) |
Luna osv_check.lua + mcp_osv.lua (via osv_gate.lua) | LUNA_ALLOW_OSV_CHECK | off | already covered |
Luna tool installs: auto_install.lua downloads, package-manager installs, install_via_pip (via egress_gate.lua) | LUNA_ALLOW_TOOL_INSTALL | off | already covered |
| zerg-cli update channel + SHA256 fetch | ZERG_ALLOW_EGRESS_UPDATE | on | strict air-gap |
Local model server (localhost:11434, ollama) | loopback only — not egress | — | — |
Sol has an explicit air-gap posture: SOL_AIRGAP_MODE=true (config key
airgap_mode). It relaxes ONLY the readiness off-host backup requirement;
the local scheduled Mnesia backup is still required (`mnesia_backup_interval
0
), and a prod node without the posture answers/api/v1/ready503offhost_target_required` when no remote backup target is configured.
The egress inventory is not “three gates”: Sol’s outbound sockets target deployment-configured endpoints only, but some of those endpoints have background refreshers:
| Sol background/egress surface | Controlled by | Default |
|---|---|---|
| Mango auth + audit-archive URLs | mango_url / mango_pub_url / archive config | configured |
| LLM provider endpoints | provider config (per-provider key + base URL) | configured |
| Channel webhook URLs | channel config | configured |
License/seat refresh (seats_url) | seats_enabled + seats_url; seats_refresh_ms (default 30000) | off when seats_url is empty; a configured seats_url is a 30s background HTTP(S) fetch (sol_license) |
| OAuth token refresh for declarative providers | provider oauth sub-map; zerg oauth login | off unless an OAuth provider is configured |
In an air-gap, point these at in-cluster services (or leave seats_url
empty) and keep the bind defaults (http_ip 127.0.0.1,
zmq_bind_addr 127.0.0.1). The Luna/CLI gates above are the complete
worker-side gate surface; the Sol-side endpoints are the table above.
1. Provision the host
Provisioning is the wild blueprint (runit + podman + OpenResty) — see the WILDZERG operator runbook §Install. On an air-gapped host, two things change:
- No source/build toolchain needed: Zerg is delivered as images +
release assets, never built on the target. The 8 images
(
sol mango luna limon-web toronja-web starfruit-web docs-web cli— the build-images step in.crow.yml) are pushed to the internal registry (registry.nonsense.ws, internal-only — see docs/development.md) and deployed from there; an air-gapped site either mirrors that registry or ships image archives. - Wild’s provisioning scripts (
wild/scripts/provision/) are the path; they are run from the wild repo clone (see runbook §1). Set the Sol posture explicitly withSOL_AIRGAP_MODE=true(see §3 below).
2. Get the artifacts onto the host
Three artifact sets must cross the air gap:
| Artifact | How to cross | Source |
|---|---|---|
| Container images (all 8) | podman save on the connected host → archive → podman load on the target (or a private registry mirror reachable inside the site) | build output / registry.nonsense.ws |
Release assets (zerg CLI, luna, sol-<ver>.tar.gz, SHA256SUMS, minisign sigs) | download on the connected host, carry over, install manually | the Forgejo release |
Engine artifacts: llama-<build>-<rev12>-<class>-linux-x86_64.tar.gz + .sha256 + .minisig, and engines-<class>.json | carry the tarball triple with the release; verify SHA256SUMS (and the minisig when a minisign binary is present), then install with scripts/engine-install.sh <tarball> --root /opt/llama (the receipt records manifest_hash from engines-<class>.json) | same Forgejo release (published by wild/scripts/release/publish-release.sh --engines-dir) |
| Tree-sitter grammars / model files | grammar archives are baked at build time; model weights are carried as files to the local model server | build pipeline / model registry |
Forgejo itself is air-gap capable: FORGEJO_OFFLINE_MODE=true disables
telemetry and update checks, and its images export/import the same way
(docs/forgejo-admin.md §10 Air-Gapped Deployment).
3. Configure the egress gates
On every Luna worker host and the CLI host:
# Luna: no MCP package-vuln lookups, no tool installs (both default off —
# set explicitly for a documented posture)
export LUNA_ALLOW_OSV_CHECK=0
export LUNA_ALLOW_TOOL_INSTALL=0
# zerg-cli: no update-channel contact (check/download/apply all refuse)
export ZERG_ALLOW_EGRESS_UPDATE=0
The CLI behavior with the update gate off is explicit, not silent:
$ zerg update check
update check skipped: ZERG_ALLOW_EGRESS_UPDATE=0 (air-gap posture)
(Zerg-cli code: egress_allowed in zerg-cli/cli/update.lua; the
check/download/apply commands all route through it.) Sol-side, gate the
deployment-configured endpoints in the inventory above: leave seats_url
empty, disable unused OAuth providers, and point Mango/provider/webhook URLs
at in-cluster services.
Declare the air-gap posture explicitly so prod readiness does not demand an off-host backup target:
# container entrypoint (Sol)
export SOL_AIRGAP_MODE=true
# bare-metal sys.config
# {sol, [{airgap_mode, true},...]}
With airgap_mode=true, keep sol_mnesia_backup_remote_path unset (the
default) so the Mnesia backup’s offsite rsync leg stays off and backups
never leave the host. The LOCAL scheduled Mnesia backup is still required:
mnesia_backup_interval must be > 0 (an air-gapped prod node with the
interval at 0 reports readiness local_backup_required, not green).
Without the posture a prod node without an off-host target reports
offhost_target_required (sol_mnesia_backup.erl, sol_health:check_backup/0).
There are no third-party CDN/analytics references in the frontend or
Luna trees to purge — ci/egress_assert_lint.py asserts that
permanently (docs/security.md §Egress inventory).
4. Local model serving
With egress off, inference comes from a local server. Luna ships an
ollama-compat path (localhost:11434) and can call any provider whose
base URL is a loopback/LAN address (provider config, per-provider base
URL — docs/security.md §Egress inventory). Set providers accordingly in
~/.luna/ config; Sol routes to whatever provider endpoints are
configured for it — point those at the local model server.
5. Install the CLI without the update channel
Two options:
# (a) offline manual install from the carried release assets:
sudo install -m 0755 zerg /usr/local/bin/zerg
sudo mkdir -p /opt/zerg && sudo cp VERSION /opt/zerg/VERSION
# (b) if a mirror of the Forgejo release is reachable INSIDE the site,
# point the channel at it instead of disabling it:
# ZERG_UPDATE_CHANNEL + update_repo config key (see
# docs/cli-reference.md §Updates) — or just carry new releases manually.
The TOFU pin (~/.config/zerg/trusted-key) and minisign verification
apply to any channel — signature verification is channel-independent
.
6. Verify the posture
zerg status # Sol liveness
curl -sf http://127.0.0.1:21434/api/v1/ready # readiness (19 subsystem checks; sol_health:check_all/0)
zerg update check # MUST print the air-gap skip, not network
zerg list && zerg start <local-model> # local inference round-trip
And from the operator side: git grep for nonsense.ws in your configs
should only show the deliberately-internal hosts (registry/Forgejo
mirrors); no public-doc lint should fire (the docs lints gate this
permanently: ci/egress_assert_lint.py, ci/docs_surface_lint.py --check hosts).
Upgrades on an air-gapped site
The CD chain is tag-triggered and network-dependent; an air-gapped site upgrades by carrying artifacts across the gap (images via save/load or an internal registry mirror; release assets manually) and running the same deploy flow the runbook describes. The egress gates stay off; there is no silent background contact.
See also
docs/wild-zerg-runbook.md — deploy/upgrade/rollback flow
docs/security.md (§Air-Gapped Deployment) — posture + egress inventory
docs/backup-and-dr.md — backups also stay in-site (Mnesia remote
copy unset)
docs/configuration-reference.md (§Air-Gapped Deployment) —
the egress gates + bind defaults; license_file for cold-start
licensing
docs/forgejo-admin.md (§Air-Gapped Deployment) — the git forge offline
Cluster operations
ZERG can run multiple Sol nodes for release coordination and failover. The reference deployment is blue/red/green: one serving node, one standby, one development/validation node.
What clustering provides
Release coordination: a validated node becomes the serving node; the previous node stays available for rollback. Worker reachability: workers are bound to a Sol node; a released lane can move to another validated node. Cluster inventory: nodes advertise membership and readiness; a split or stale node is visible.
What it does not provide
Shared-worker multi-tenancy. Transparent active-active writes for every store (some stores are node-local by design). A substitute for backups. Cluster replication is not a backup.
Commands
zerg cluster
zerg catalog
zerg join <seed>
zerg leave
zerg cluster shows membership and node state; zerg catalog shows the model/lane catalog available to the cluster.
Release sequence
- Deploy the new image to the standby node.
- Run readiness and smoke checks on the standby.
- Move the serving role (release) and verify worker reconnection.
- Keep the previous node available until the rollback window closes.
Failure behavior
A node that loses the serving role must not accept new worker registrations for that role. A worker whose node is gone is marked stale; its tasks are reconciled through the durable dispatch/terminal path. A two-Sol boot against the same data directory is refused by design.
Next
Deployment Production runbook Upgrade & rollback ZMQ protocol
Engine reference — generated from the canonical engineering source. Do not edit this page by hand.
Tenancy posture (single-org per Sol, single-tenant per worker)
Status: DECIDED (2026-11-06) — `` /. Owner:
product/architecture. This page is the published posture matrix; the
enforcement is in sol_tenancy.erl (scope_opts/2, ready_verdict/1) and
GET /api/v1/infra/status (tenancy).
The decision
ZERG ships one organization per Sol and one tenant per worker. It does Not claim shared-worker multi-tenancy: a worker is a trusted registration principal (its operator can read every task prompt and workspace it is told to use). Confidential/attested multi-tenant workers remain a separate, unfunded decision — the target design is ADR-0011.
`` is DECIDED: the single-org branch, with the ADR-0011 no-regret
enforcement leg. No tenant_id token claim, store backfill or shared-worker
claim is authorized by this decision.
Posture matrix
| Deployment | Tenancy unit | Sol | Worker | Shared worker allowed? | Claim |
|---|---|---|---|---|---|
| Local / dev | one trusted principal (or a few on one host) | single-org per Sol | single-tenant; the dev ack levers are explicit and CRITICAL-logged | only with SOL_ALLOW_SHARED_WORKER=true and no isolation claim | no SaaS/multi-tenant claim |
| WILDZERG (self-hosted) | the operator’s organization | single-org per Sol | single-tenant per enrollment; provision one worker per trust domain | only with the explicit ack; not a supported isolation boundary | no shared-worker multi-tenant claim |
| ZERG | not launched | single-org per Sol until a funded program lands | single-tenant | no | no shared-worker multi-tenant claim |
What is enforced (not prose)
- Server-derived workspace scope. Every task crossing the HTTP/local-worker
dispatch boundary is stripped of client-supplied
workspace_rootandtenant_id, then stamped with<workspace_root>/users/<server-scope>/. The scope is derived from the authenticateduser_uuid(never a request field); unsafe characters are hashed so a crafted principal cannot traverse into another user’s subtree. Two users sharing one worker therefore never share the worker’s default PWD/config workspace. The HTTP workspace API is scoped by the SAME rule: a non-admin caller is rooted at<workspace_root>/users/<server-scope>/(a member cannot read/write another member’s task workspace); an admin keeps the global root and may cross. The control-plane./..principals hash like any unsafe principal. The drill istests/integration/test_tenancy_shared_worker.py(two real users, one registered worker, the real wire frames). - Shared-worker declaration refusal. A READY frame that declares
tenancy: "shared"(orshared_worker: true) is refused withshared_worker_requires_declarationunless the deployment has explicitly acknowledged it withSOL_ALLOW_SHARED_WORKER=true(allow_shared_worker). The refusal is counted insol_zmq_registration_refused_total{reason="shared_worker_requires_declaration"}and, only when the delivering pipe is already the identity’s READY-bound pipe, delivered as a typederrorframe (details carry the remediation). A first-registration refusal (no binding exists yet) and a refusal arriving on a foreign pipe are log + counter only — WIRE-01’s pre-auth addressing rule; Sol never routes a refusal by a declared identity. Even with the ack, no multi-tenant isolation is claimed. - Posture is API truth.
GET /api/v1/infra/statuscarriestenancy: {mode: single_org, tenant_unit: sol, worker_tenancy: single_tenant, shared_worker_supported: false, shared_worker_allowed: <bool>}in both the public (booleans/status only) and admin views.
What is not claimed
No tenant_id in Mango tokens or Sol stores; Mango orgs are not consumed by
Sol.
No isolation between users that share a worker host from the worker
operator’s perspective; the worker operator is trusted.
No per-tenant quotas, streams, spend partitioning or backup boundaries.
No shared-worker SaaS mode. A future multi-tenant program must follow
ADR-0011 option 2 plus the spine/durability decisions and the
cross-tenant-read test.
Operator guidance (provisioning)
Provision one enrollment key per worker and one worker per trust domain
(per organization, or per security boundary inside it).
Do not attach shared hardware to a Sol unless the operator accepts that the
hardware operator can read every task/workspace on it.
If a worker must be shared for a lab/dev deployment, set
SOL_ALLOW_SHARED_WORKER=true explicitly and record that the deployment has
no multi-tenant isolation. The boot/registration path still refuses a
declaration without the ack, so a shared worker cannot appear silently.
The zmq.allowed_workspace_roots Luna allowlist remains a defense-in-depth
control; Sol already stamps a server-derived root.
See also
ADR-0011 — tenant/worker isolation
Worker integration — READY fields and refusals
Security — worker trust plane
Configuration reference — allow_shared_worker
Engine reference — generated from the canonical engineering source. Do not edit this page by hand.
Seats & Licensing
Seat-based capacity: caps (max agents / GPU workers / users), capacity packs, and graceful degradation — enforced by Sol, surfaced in Limon. Terminology: “seats” is the canonical word (code, config, docs, UI); the license-term vocabulary is seats only.
What this is
A license carries capacity caps — how many agents, GPU workers, and users a deployment may use — plus feature flags (clustering, SSO, audit retention, MCP gateway, multi-region, air-gap, custom branding). Since the Engine enforces the caps it has a plane for.
Commercial terms are not announced. This page documents the engine’s
seat model, not an offer. For an evaluation, licensing, or an
interest registration, contact Spacebeam (hello@spacebeam.org /
sales@spacebeam.org).
The model is deliberately not metering: the engine never meters a call, a token, or a run. Seats raise caps; failed runs never count; caps degrade (soft-cap queue), never hard-block.
Architecture
CLF v1 file (offline/air-gap) ──┐
├─▶ sol_license (gen_server) ── ETS seat cache ──▶ spawn/register checks
ZERGBASE panel /api/seats ─────┘ │ (fresher-wins merge)
▼
GET /api/v1/license/status (admin, Limon "Seats" view)
sol_seat — pure data model: caps, packs, FEFO (expiring-soonest-first)
pack consumption, merge, Community defaults.
sol_license — gen_server that loads the Spacebeam License File (CLF
v1) on cold start (offline / air-gapped), and refreshes from the
control-plane seat endpoint (SOL_SEATS_URL) when configured (online).
Merge prefers the fresher source.
sol_worker_sup — enforces caps at agent spawn; a soft-cap hit returns
{error, cap_reached} (HTTP 429 with retry-after) instead of a hard block.
Mango — cost centers + per-member caps (set_cost_centers,
set_member_caps, get_usage_attribution).
Posture record: cost centers are a Mango-only surface —
zero Sol consumers (no route, no dispatch path reads them; the archived
Header’s “DONE” claim predates this measurement). Enforcement in
Sol is deliberately not queued: it needs a real billing requirement
first. Until then this is the recorded, non-silent dormancy posture.
Limon — “Seats” view (caps, packs, source, enforced/advisory badge),
reading GET /api/v1/license/status.
CLF v1 format
{
"seats": { "max_agents": 25, "max_gpus": 4, "max_users": 10,
"clustering": 3, "mcp_gateway": true,
"multi_region": true, "custom_brand": true },
"exp": 1780000000000,
"sig": "<base64 ed25519 signature over seats+exp canonical JSON>"
}
Without SOL_LICENSE_PUBKEY the file is trusted config (dev). With a PEM
ed25519 public key, signatures are verified; failures fall back to Community
defaults (observable via status).
Seat flags
The seat map carries 8 flags (tier-architecture.md §8). The engine enforces
the capacity caps it has a plane for (max_agents / max_gpus at spawn via
sol_worker_sup); max_users is carried but NOT enforced (see the
non-claim below); the four gating flags are shipped in the seat data and
consumed by the Limon console (tier-gated UI) — they are never
check/2-enforced.
| Flag | Default | Licensed | Extended | Type |
|—|—|—|—|—|—|
| max_agents / max_gpus / max_machines | 5 / 1 / 1 | per license | unlimited | cap |
| max_users | 1 | per plan | unlimited | carried — NOT enforced (non-claim) |
| audit_retention_days | 7 | 365 | unlimited | cap |
| sso | false | ✓ (roadmap) | ✓ (roadmap) | gating |
| air_gapped | false | — | ✓ | gating |
| clustering (nodes) | 1 | 3 | unlimited | gating |
| mcp_gateway | false | — | ✓ | gating |
| multi_region | false | — | ✓ | gating |
| custom_brand | false | — | ✓ | gating |
The column names describe capacity profiles in the engine; they are not a published commercial list. Commercial packaging is not announced.
max_users non-claim. The value is
carried in the CLF/seat cache, flows through /api/v1/license/status, and
renders in Limon, but no plane enforces it: Mango has no user-count
seat check and Sol does not gate user creation. It is advisory until a
signed Sol→Mango seat datum exists; do not document it as an enforced cap. The Mango identity test suite pins this
docs-vs-code agreement.
Missing keys always fall back to Community-safe defaults (never a silent
restriction). Since, unknown keys are no longer the failure mode:
all 8 flags parse through sol_seat:from_map/1 (binary and atom keys),
surface in GET /api/v1/license/status under caps, and render in Limon’s
Seats view Features card.
Panel → Sol wire contract
The ZERGBASE panel /api/seats emits all 8 flags plus packs and
refreshed_at. The contract is additive-safe in both directions:
New panel → new Sol: all flags flow through byte-compatible. Old panel → new Sol: missing keys fill from Community defaults. Safe. New panel → old Sol: the previous allowlist drops the 4 gating keys silently, falling back to Community defaults. Safe (documented limitation, not a break).
The panel reports the capacity profile it was provisioned with: a
self-hosted engine’s own CLF/cache is the authority for its node cap, while
the default profile reports clustering: 1 and an extended profile reports
the four flags true/unlimited.
The refreshed_at field inside seats is the panel’s wall clock
(epoch ms). Sol uses it ONLY as a freshness/replay gate; the merge
currency is Sol’s own local stamp (see Trust model).
Trust model
| Authority | Trust | Role |
|---|---|---|
Signed CLF (SOL_LICENSE_FILE + SOL_LICENSE_PUBKEY) | ed25519-verified | Cryptographic authority for air-gapped operation |
ZERGBASE panel /api/seats | HMAC-verified | Tier authority for online operation — only with a valid signature (below) |
SOL_SEATS_SIGNING_KEY (required for online refresh) | HMAC-SHA256 | The ONLY thing that makes a remote response acceptable |
SOL_SEATS_SIGNING_KEY is required whenever SOL_SEATS_URL is set
. An empty key rejects every remote response with
{error, unsigned_remote} — the refresh fails CLOSED (current caps are
kept; the failure is counted in sol_license_refresh_failures_total).
The previous “unset key = trust the panel as-is” posture allowed a
forged response to outrank the signed CLF via fresher-wins and is gone.
Signature contract (set on Sol AND ZERGBASE_SEATS_SIGNING_KEY on the
panel): the response must carry
sig = hex(HMAC-SHA256(key, canonical)) where
canonical = json.dumps(seats, sort_keys=True, separators=(',', ':'))
recursively key-sorted compact JSON over the seats object. Value set
is restricted by contract to non-negative ints, booleans, ASCII strings
("unlimited"), arrays/objects thereof. A missing/invalid sig rejects
the refresh. Set both sides together — see the wild flip checklist.
Monotonic merge guard: a replayed (or clock-skewed-back)
payload cannot move the ledger backwards — refreshed_at must not be
older than the stored value.
Freshness gate: a response whose panel refreshed_at is
older (or further future) than max(2 × refresh_ms, 2 min) is rejected as
stale — replay protection. Responses without the field are accepted
(backward-compatible fail-open). This gate is NOT a substitute for the
HMAC: an active MITM sets refreshed_at to now and walks past it.
Transport: https:// → TLS with verify_peer against the
system CA store. Under SOL_SEATS_ENABLED=true, an http:// seats URL
is REFUSED at boot (seats_http_url_forbidden) — the bearer token would
be cleartext and the refresh forgeable. SOL_SEATS_URL_ALLOW_HTTP=true
exists ONLY as a loopback test override (the seats handshake CT); never
set it in production. The bearer token (SOL_SEATS_TOKEN) is not
validated by the panel — protection relies on transport + HMAC.
Merge semantics: with SOL_SEATS_URL set, a successful refresh stamps
Sol’s local clock, so the fresher remote outranks the signed CLF — the
cryptographic authority is subordinate to the (audited) panel channel
while online. Packs from the older source are preserved when the newer
omits them.
Packs are validated: invalid pack entries (non-integer
expiry/agents/gpus) are dropped, never trusted — a forged pack previously
crashed the license server (crash loop → enforcement off).
Refresh never blocks checks: the fetch runs in a companion
process; a hanging endpoint can no longer stall the license gen_server
(which previously made every check/2 time out into pass-through).
Configuration
| Key | Default | Description |
|---|---|---|
SOL_SEATS_ENABLED | false | Master switch. Off = all checks pass, Community defaults reported. Off in production until the release gate. |
SOL_LICENSE_FILE | — | Path to the CLF v1 license file (cold start / air-gap) |
SOL_LICENSE_PUBKEY | — | PEM ed25519 public key for signature verification (empty = trust file in dev) |
SOL_SEATS_URL | — | Control-plane seat endpoint (ZERGBASE panel /api/seats) for online refresh |
SOL_SEATS_TOKEN | — | Bearer token for the seat endpoint |
SOL_SEATS_SIGNING_KEY | — | HMAC-SHA256 key for /api/seats signature verification — required when SOL_SEATS_URL is set |
seats_url_allow_http (sys.config app env — no env-var mapping) | false | Test-only loopback override of the http:// hard-refusal. NEVER in production |
SOL_SEATS_REFRESH_MS | 30000 | Refresh interval (bounds: 5000–86400000, startup-validated) |
Behavior contract
Graceful degradation, never hard-block. Cap reached → new spawns queue (or 429 at the HTTP boundary); running sessions and long-running work continue. UI shows “cap reached — upgrade to lift it.” Failed runs never count. Crashed agents, failed sagas, dead workers, failed MCP calls don’t consume a seat. The engine never meters per-run. A license change keeps everything. Data, sessions, and configs are preserved; only caps tighten. Capacity packs (FEFO). Stackable capacity packs (+10 agents, +2 GPU) with per-pack expiry; expiring-soonest packs are consumed first. Pack state lives in the seat cache. Pack packaging and commercial terms are not announced. Unavailable license degrades to pass-through. Worker spawns must never crash because the license server is down — enforcement is opt-in.
Status endpoint
GET /api/v1/license/status (admin) — current caps, pack state, source
(file/cache), and whether enforcement is on (enforced) or advisory
(advisory). Limon’s Seats view renders the same data with a
enforced/advisory badge so operators can see at a glance whether caps are
live.
Current production state
Implemented and covered by contract tests (eunit: sol_seat, sol_license
remote decode/sig/freshness; CT: sol_license valid/expired/bad-sig/remote/
disabled; worker-sup cap check; sol_agent_cap concurrency tests).
** hardening (this line):** atomic spawn-cap semaphore
(sol_agent_cap, B2 race fix), remote-refresh audit logging, panel
freshness/replay gate, optional HMAC verification (SOL_SEATS_SIGNING_KEY),
scheme-derived TLS with verify_peer, async refresh (no more check stalls),
pack validation. Production flip (SOL_SEATS_ENABLED=true on blue) is
wild-owned — see wild plan/seat-enforcement-flip-cd-alerting.md.
Until the flip, Community caps are advisory in self-serve tiers. Enterprise
contracts reference caps only after enforcement lands.
Implemented since: chat-session worker spawns route through the seated,
supervised path — cap exhaustion at the HTTP
boundary is 429 + Retry-After (license outage 503), never 500.
Roadmap remainder: ZERGBASE panel seat UI, Sol-side per-member cap reads
(requires the ZERGBASE panel to write member_caps into the seat cache).
See also
Licensing and editions (evaluate/why-zerg.md) —
commercial terms are not announced; contact Spacebeam.
docs/audit-retention.md — retention semantics for the audit flag.
plan/archive/phase--seats.md — implementation plan and status
Engine reference — generated from the canonical engineering source. Do not edit this page by hand.
Nydus Network — Operator/User Guide
Status: product-level documentation of a live-but-minimally-in-repo feature. This page states exactly what the repository can prove about Nydus, marks what is marketing copy, and lists what an operator guide must cover once the implementation surface lands in-tree. No implementation details are invented here.
What the repo proves
Arrangement: Nydus Network is the federation layer — a
feature/arrangement of WILDZERG, not a separate brand
(AGENTS.md §Product Variants). It links separate WILDZERG clusters
into one network.
Registry: the public registry is live at nydus.zergs.net
(AGENTS.md); the SaaS home (zergs.net) hosts it. Sign-up is
invite-first (waitlist).
In-repo implementation surface: NONE. There is no Nydus code in
server/, client/, mango/, limon/, zerg-cli/ (no identity
signing module, no capability-manifest schema, no registry client,
no protocol doc). All in-tree references are product/marketing copy in
the toronja product page (the shared SaaS site source):
toronja/src/views/FeaturesView.vue — “Link your cluster to the live
federation at zergs.net. Register once with a signed identity,
publish your skills and models, and appear on the real-time brood
map.” and “Nydus federation meshes clusters across headquarters,
edge sites, and labs into one network — signed identities, shared
capabilities, and peer links you control.”
toronja/src/views/ArchitectureView.vue — carries only the
“Join the waitlist” Nydus CTA (mailto link), no Nydus prose.
What the product claims imply (air-gap posture)
Two claims above are load-bearing for operators and match the engine’s air-gap doctrine (docs/security.md §Air-Gapped Deployment):
- “Air-gapped clusters stay fully offline by default” — joining a
federation must be an opt-in action; the egress gates
(
LUNA_ALLOW_OSV_CHECK,LUNA_ALLOW_TOOL_INSTALL,ZERG_ALLOW_EGRESS_UPDATE) guarantee no background egress exists today, and a Nydus join flow must not bypass them. - “Enterprise can run its own private registry” — federation membership is control-plane configured, not implied by software presence.
Until the implementation lands, these remain product commitments, not engine behavior.
Using the live network today
The public registry (nydus.zergs.net) is invite-first; the SaaS
waitlist is the entry point (toronja join-waitlist CTA).
The per-cluster operator tooling for identity signing, capability
publication, and peer links does not exist in this repo — the
registry’s own documentation (on the registry site) and the wild
repo’s deployment of the control plane are the current sources. Do not
assume commands that this page could not source.
Tracked gap — what this guide must cover when code lands
The plan lists the required sections; each is unblocked by an in-repo implementation:
- Identity signing — how a cluster’s identity key is generated, protected (rotation!), and presented at registration; how revocation works.
- Capability manifest — the schema for published skills/models (the “publish your skills and models” claim), validation rules, and versioning.
- Registry operations — the
nydus.zergs.netAPI surface: register, publish, unpublish, peer-link, browse (brood map); auth model. - Air-gap posture — the explicit opt-in join flow, egress-gate interaction, and the private-registry variant for Enterprise.
These belong in this file (or files linked from it) once the code exists.
See also
AGENTS.md §Product Variants (arrangement) and §Where to look next
docs/air-gap-install.md — the egress-gate doctrine any federation
join must respect
docs/seats.md — the licensing framework Nydus tiers will sit on
(Enterprise private registry is a seat-tier claim)
Engine reference — generated from the canonical engineering source. Do not edit this page by hand.
Troubleshooting
Common Issues
Connection Refused
Symptom: zerg status or any CLI command fails with connection refused.
Diagnosis:
# Check if Sol is running
pgrep -f "beam.smp" && echo "Erlang running" || echo "Erlang not running"
# Check if port 21434 is listening
ss -tlnp | grep 21434
Resolution:
- Start Sol:
cd server && rebar3 shell(dev). Production runs under the wild blueprint (runit + podman, container root/opt/sol) — see production-runbook.md; the oldsolctlscript was removed in - Verify config: check
http_portinsys.configmatches CLI expectations - Check firewall rules if connecting remotely
Model Not Found
Symptom: zerg start my-model returns “model not found”.
Diagnosis:
# List registered models
zerg list
# Check model directories
ls /fun/models/*.gguf # model_source_dir
ls /tmp/sol/models/*.gguf # model_store_dir
Resolution:
- Run
zerg discoverto scan for GGUF files - Verify
model_source_dirinsys.configpoints to your GGUF files - Model names are auto-generated from filenames. Use
zerg listto see available slugs. - Prefix matching is supported:
glmmatchesglm-4.7-flash-q4
Inference Start Fails
Symptom: zerg start returns error or model stays in loading state.
Diagnosis:
# Check llama.cpp binary exists
ls -la /usr/src/llama.cpp/llama-server
# Check GPU/CPU availability for inference
nvidia-smi # for CUDA
Resolution:
- Verify
llama_server_pathinsys.configpoints to a valid llama.cpp binary - Check available GPU memory (GGUF model must fit in VRAM)
- Check Sol logs for the specific error:
tail -f log/sol.log(production) or console output (dev)
Worker Spawn Fails
Symptom: zerg spawn returns error.
Diagnosis:
# Check worker binary
ls -la client/build/luna
# Check worker_path config
grep worker_path server/config/sys.config
Resolution:
- Build the Luna binary:
bash client/build/build.sh - Verify
worker_pathinsys.configpoints to the binary - Ensure the binary is executable:
chmod +x client/build/luna - Check
max_workerslimit (default: 16)
ZMQ Workers Not Connecting
Symptom: zerg zmq-workers shows empty list, but Luna workers are running.
Diagnosis:
# Check ZMQ gateway status
zerg zmq-status
# Check ZMQ config
grep zmq server/config/sys.config
# Check firewall for ports 5555/5556
ss -tlnp | grep 5555
Resolution:
- Verify
zmq_enabledistrueinsys.config - Check that Luna worker uses matching endpoint:
--connect tcp://127.0.0.1:5555(with--idfor the worker identity;--pub-endpointfor events) - If running across machines, check
zmq_bind_addris set to0.0.0.0or the correct interface - Install
libzmq:apt install libzmq3-dev
Cluster Join Fails
Symptom: zerg join sol@gpu-node-2 returns error.
Diagnosis:
# Check both nodes use the same cookie
grep setcookie server/config/vm.args
# Check node names are distinct
grep -- "-name" server/config/vm.args
# Check network connectivity
ping gpu-node-2
Resolution:
- Both nodes must have the same
-setcookievalue invm.args - Node names must be unique (
sol@node-1,sol@node-2) - Erlang distribution port (4369) and dynamic ports must be open
- Use FQDNs or IP addresses if DNS resolution is unreliable
TUI Not Rendering
Symptom: Luna TUI shows garbled output or blank screen.
Diagnosis:
# Check ncurses is installed
dpkg -l | grep ncurses
# Check terminal type
echo $TERM
Resolution:
- Install ncurses:
apt install libncurses-dev libtinfo-dev - Set
TERM=xterm-256colorfor color support - Use
--printmode for non-interactive testing:luajit client/main.lua --print "hello"(after--configureor with a--connectworker lane) - Some terminals may need
export COLORTERM=truecolor
Known Issues
All previously tracked issues have been resolved. As of there are 0 open bugs. 1161 archived phase plans (machine count plan_files=1225 in AGENTS.counts — plan/archive/*.md). See review/2026-08-01-deep-source-analysis.md and docs/archive/AGENTS-decisions-archive.md for the canonical reviews.
No active known issues at this time.
Log Locations
| Component | Location | Content |
|---|---|---|
| Sol (production) | /opt/sol/log/sol.log (legacy on-host model; wild production logs under podman at /opt/zerg) | Structured Erlang logger output |
| Sol (development) | Console stdout | Logger output + Cowboy request logs |
| Luna | ~/.luna/logs/ | Agent log files (leveled: debug/info/warn/error) |
Checking Sol Logs
# Production (legacy on-host model — wild runs under podman, see /opt/zerg)
tail -f /opt/sol/log/sol.log
# Development — visible in rebar3 shell console
cd server && rebar3 shell
Checking Luna Logs
ls ~/.luna/logs/
Agent Modes
Tab cycling doesn’t show my custom mode
Custom modes must have "category": "primary" to appear in Tab cycling. Secondary modes are accessible only via /mode <name>.
Mode badge not updating in status bar
The mode badge updates when app:_update_status is called. If it doesn’t update, trigger a redraw with any keystroke. This is a known cosmetic issue.
Unknown mode error when using /mode
Check that the mode is defined in ~/.luna/agents/*.json or .luna/agents/*.md with valid JSON/YAML frontmatter. Use /modes to list all registered modes.
Ollama
Ollama models not appearing in Sol
- Verify Ollama is running:
curl http://localhost:11434/api/tags - Check Sol model metadata refresh (every 5 minutes): restart Sol to force immediate discovery
- Ensure the Ollama provider is registered in
sol_provider_boot
Ollama connection refused
Default URL is http://localhost:11434. If Ollama is on a different host:
{
"classifier": {
"base_url": "http://192.168.1.100:11434"
}
}
AI Permission Classifier
Classifier always falls back to dialog
- Verify
permission_modeis set toauto - Verify
classifier.enabledistrue - Verify Ollama is running and the classifier model is pulled:
ollama pull qwen2.5-coder:7b - Check logs for classifier errors:
~/.luna/logs/
Classifier is too permissive / too restrictive
Adjust the confidence threshold:
More permissive: lower threshold (e.g., 0.7)
More restrictive: raise threshold (e.g., 0.95)
{
"classifier": {
"confidence_threshold": 0.95
}
}
Classifier adds latency to tool approval
The classifier has a 5-second timeout. If it’s consistently slow:
- Use a smaller/faster model (e.g.,
qwen2.5-coder:1.5b) - Reduce timeout:
"timeout": 3 - The LRU cache (64 entries) avoids re-classifying identical invocations
Sub-Agents
Sub-agent times out
Local sub-agents use the same provider timeout as the parent. Increase max_tokens and max_iterations in the mode config if sub-agents need more steps.
Sub-agent recursion blocked
The _no_recursion flag prevents sub-agents from spawning their own sub-agents. This is intentional — the recursion guard prevents unbounded agent spawning.
Getting Help
Check existing known issues above
Search review/*.md for phase-specific review findings
Search plan/*.md for planned fixes
Check the CHANGELOG for recent changes
Engine reference — generated from the canonical engineering source. Do not edit this page by hand.
Local Inference Runbook
Status: LIVE. Operator procedures for the local inference lanes. The catalog of lanes, pins,
use_casefacets and measured numbers lives in local-inference-lanes.md; the machine ledger and validation semantics live in local-inference-benchmark.md.
0. Prerequisites
A running Sol with the lane registry (the shipped configs carry it; the
active lane/engine set is inference_lanes + inference_engines).
An admin token for start/stop/validate surfaces (inference:list is
enough for the read-only lane query).
Local lanes run on the node that owns the GPU/CPU — there is no
remote lane start; remote capacity is the API tier.
Two architecture rules to keep in mind:
- Sol owns llama.cpp. Lanes are started, leased and reaped by Sol
(
sol_inferencevia erlexec); Luna consumes a Sol-issued grant. A worker never defines, probes or configures a lane endpoint. - A row without a needle gate is not a row. Validation needs a fresh exact-recall needle row on the lane’s engine+host; ghost-imported measurements are evidence, never validation.
1. Status and inventory
zerg status
zerg ps
curl -s http://127.0.0.1:21434/api/v1/inference/lanes
The lanes response is the operator truth: per lane it projects kind,
production, the engine, the loaded/running state, the current lease,
use_case (the registry facet, joined at the read boundary) and
validation.state + reason. A lane that is unvalidated will refuse a
production start with {engine_unvalidated, Lane, Reason} — the reason
names the cause (no_record, stale, engine_pin_changed,
engine_reinstalled, model_pin_changed, needle_failed,
parity_breach, host_mismatch, malformed_record).
2. Start, modes and idle release
Lane-bound starts go through the HTTP API (there is no
zerg inference start; plain zerg start <model> sends only the model and
is not lane-bound):
curl -X POST http://127.0.0.1:21434/api/v1/start \
-H "Content-Type: application/json" \
-d '{"model":"<model-slug>","lane":"<lane>","engine":"<engine>"}'
mode and duration_ms are optional body fields. The model slug is the
running-lane slug from GET /api/v1/models (the manual three-node smoke
resolves it from the same list); a start that finds the lane already
serving answers 409 already_running.
Service modes (modes_allowed in the registry is the per-lane ceiling):
| Mode | Behavior |
|---|---|
on_demand | Default. Idle release after 15 min (lane_idle_release_ms = 900000); per-lane opt-out is the registry row’s idle_release_ms (a lane carrying it is never auto-released). |
duration | Bounded by the start body’s duration_ms (max lane_duration_max_ms = 86400000). |
attended | No automatic bound — it stays until stopped or the node needs the slot. Use deliberately; it holds the GPU. |
cron | Scheduled via the lane_cron config map (lane id → schedule). |
Stop a running lane by its model slug:
zerg stop <model-slug>
zerg stop-all
The governor reaps orphans (a pid that outlived the state machine) after
lane_orphan_ttl_ms (1 h) and enforces the VRAM budget with
lane_vram_headroom_mib (1229 MiB) reserved for image work.
3. Validate a lane (the serving gate)
Validation is the needle gate plus parity; it is derived at read time, and
only origin=zerg rows can back it. Plan the matrix first (no GPU):
scripts/lane-certify.sh --plan --host <node-label>
Then run the real certification (loads each selected lane, probes the admin route, appends the measurement row, checks parity, commits only a complete run):
# Real mode is admin-authenticated. The token is read from a 0600 file (or
# ZERG_SOL_TOKEN); it never goes on the command line or into another
# process's argv.
install -m 0600 /dev/null /etc/sol/lane-certify.token
# printf '%s\n' '<admin-token>' > /etc/sol/lane-certify.token
scripts/lane-certify.sh --host <node-label> --lanes qwen38_atx \
token-file /etc/sol/lane-certify.token
Single-lane needle runs against an already-running lane:
scripts/lane-needle.sh --lane qwen38_atx
The admin route can also be driven directly:
curl -X POST http://127.0.0.1:21434/api/v1/inference/lanes/qwen38_atx/validate
Re-validate after every engine bump or model re-pin: the validation
record compares the engine ref/build, the installed manifest hash, the
model pin and the TTL (lane_validation_ttl_ms, 30 days).
4. Failover expectations
lane_failover_enabled is on and lane_failover_require_validation is on:
a validated lane can be served from another node in the cluster when the
local node cannot (lease released on lane kill / node loss, inventory
converges, the next resolve picks a validated peer). A lane whose validation
is stale or breached is not a failover destination — it refuses and the
refusal is counted (sol_lane_placement_refused_total{reason="lane_not_reachable"},
etc.). A worker holding a live grant learns of a lane stop/failover at the
next task boundary (mid-turn revocation push is a recorded future wire
revision, not a defect).
Manual cluster drill (operator-run, never in CI):
#: --lane-fetch asserts every running local lane's runtime
# port sits inside the PUBLISHED range (18001-18010; {base_port, 18001}
# lockstep, ) and fetches http://<node>.<cluster-domain>:<port>/health
# (the cluster's internal DNS suffix; override with --lane-domain).
# --lane-peer NODE runs the fetch FROM ANOTHER NODE over ssh — the
# cross-node/WILD- acceptance leg.
scripts/cluster-smoke.sh --lane-fetch --lane-peer green
Red lane-only-member decision.
Red stays a LANE-ONLY cluster member: no Mango, no orchestrator lease, no
validation/failover authority. It serves its GPU lanes on host networking;
placement/failover decisions stay on the Mango-backed nodes. The published
lane range (18001-18010) is audited free on all three nodes (18080
kube-router and the k0s NodePort range 31000-32767 excluded) and must stay
in lockstep with {base_port, 18001} in server/config/sys*.config.
Circuit-key semantics
Circuit state is keyed by the resolved target, never by a model name:
a local lane owns exactly {local, Ref}. A failing local weight set
whose name looks like a cloud family (gpt-oss-*, qwen3-coder, …) can
no longer open a remote provider circuit and 503 unrelated traffic
a registry-registered provider (a declarative provider config name)
owns {provider, Name}. Only a genuine provider outage opens it, and the
two registry HTTP funnels consult it pre-dispatch (503
provider circuit open: <name>). A startup check
(sol_provider_boot:register_defaults/0) verifies the bundled provider
names against docs/fixtures/model_provider_map.json;
a cluster peer endpoint (another node’s llama.cpp server) owns
{Host, Port} — the resolver checks it before dispatch, as before.
So sol_circuit_breaker_state{name="{local,ref}"} /
{name="{provider,\"openai\"}"} are the two families to read during an
incident: a local lane outage shows on {local, …} only, and a provider
outage shows on the matching {provider, …} aggregate (the provider-name
vocabulary is pinned by ci/model_provider_parity_lint.py).
5. Weight provisioning
scripts/lane-model-sync.sh moves and verifies a lane’s weight set:
scripts/lane-model-sync.sh --lane qwen38_atx --files /path/to/model.gguf --dest /fun/models/Qwen3.8-27B-ATX --sha256 <sha256>
It verifies every copied file’s sha256 after transfer, refuses a mismatch
(removing the bad copy), syncs to a remote host over ssh with a re-hash, and
writes a lane-model-receipt.json next to the destination recording each
file’s digest AND byte size. The start path re-stats against bytes, so a
truncated/swapped GGUF is refused (primary_pin_unverified) without
re-hashing. Pass --unhashed only when the registry pin is explicitly
unhashed — it says so loudly. Production lanes additionally require the
operator’s pin_ack in the lane row to run unhashed at all; every
unhashed-ack start is counted
(inference_lane_weights_unhashed_total{lane=...}) so the unhashed
posture stays visible until the pins converge. A lane whose
registry sha256 is set will fail validation with model_pin_changed until
the bytes match.
6. Engine install, rollback and bump protocol
Installs are whole-tree units: <root>/<build>/{bin,lib} plus the
<root>/current symlink. The binary alone is never the unit — stale shared
libraries silently keep the old backend.
scripts/engine-install.sh llama-b11639-linux-x86_64.tar.gz --root /opt/llama \
production \
expect-build b11639 --expect-ref ggml-org/llama.cpp@a0e6dc7384edb8f5d927155e1d26c10b4a310e6d
scripts/engine-rollback.sh --root /opt/llama
scripts/engine-rollback.sh --root /opt/llama --to b11011
Install requires the .sha256 sidecar and validates every archive entry
before extraction (absolute paths, .., symlinks, hardlinks, devices and
FIFOs are refused; extraction uses --no-same-owner). --production
requires a verified minisign signature (the default remains off for local
fixture installs; a PRESENT but unverifiable signature is always refused).
--expect-ref is an EXACT match. The whole install holds an
exclusive flock on <root>/.engine-root.lock — concurrent installs
serialize, and a killed install leaves at most a staging directory that the
next install cleans. Replacing an existing build (including the same-build
reinstall, the operation that invalidates ENG-7) renames the old tree aside
instead of deleting it: a failure inside the swap restores it, and the next
install’s lock-window recovery restores/cleans a leftover .old-<build>-*,
so the previous known-good survives a kill at the seam.
--expect-build/--expect-ref pin the install to the registry’s engine
row: an arbitrary artifact can no longer be installed AS the registry’s
build id.
A health canary probes the packaged server before the current flip.
Rollback flips <root>/current; Sol serves the rolled unit when the
registry-pinned build directory is gone (engine_pin_missing_fallback,
loud log + counter) and keeps the pin whenever it still exists (,
).
Fixture-class artifacts speak the FIXTURE_PORT=<n> protocol on port 0;
every other class is probed like a real llama-server: a free port is
allocated, the server is started with --port N --model <canary-model>
and /health is polled. Pass --canary-model <smoke.gguf> for a real
engine canary (the default model name only works for engines that tolerate
a missing model, e.g. the CI mock); --no-canary stays loud. A failed
canary leaves the old build active. : the documented
install path never passes --no-canary — the canary passes now that the
artifact rpath includes $ORIGIN and the CUDA runtime/libgomp travel in
the artifact’s bin/ (a canary failure is a real packaging defect, not a
reason to skip the proof). Rollback verifies the candidate’s own
install receipt against a freshly computed tree hash — a tampered/corrupt
candidate is refused before the flip — then re-probes it
(same class-aware protocol, per the install receipt’s class field) and
refuses loudly when there is no candidate.
Certification evidence contract: a production lane is
validated only from ZERG-produced evidence. The commit route
(POST /api/v1/inference/lanes/:lane/validate, mode commit) requires:
the row’s origin to be zerg (a foreign-origin row refuses typed
origin_not_zerg);
the claimed row_ref to exist in the configured artifact CSV
(lane_benchmark_csv config; configured-but-unreadable is a fail-closed
503 artifact_csv_unreadable, an unknown row refuses 409
row_not_in_artifact);
an engine install receipt (<root>/installed.json from
engine-install.sh) with a real manifest_hash — no receipt refuses
no_receipt, a receipt whose engine/build moved refuses
engine_unvalidated/engine_reinstalled on the next read;
parity evidence: pass, or single_host only with the explicit
allow_single_host ack (the runner forwards it from
lane-certify.sh --allow-single-host and records the ack in the
transcript). A missing parity verdict refuses parity_required.
A receipt-less or unverified record never satisfies the runtime gate
after the fact either: the evaluate path refuses no_receipt /
unverified_manifest — an engine reinstalled by any other means (or a
deleted receipt) invalidates the lane on the next read.
Bump protocol: build from the pinned source ref (recorded in
engines/<class>.json; build.sh --ref verifies HEAD == ref on a clean
tree and builds the committed tree — a dirty or mismatched checkout is
refused, ), certify the new build with scripts/lane-certify.sh,
install it on one host, run the needle rows again, then roll the rest of
the fleet. Never flip a default before the measured row lands in the
artifact. ci/engine_config_drift_lint.py reds any registry pin that
drifts from the engines/*.json corpus (and vice versa). The
uplift moves the llama.cpp production rows to b11639
(a0e6dc7384edb8f5d927155e1d26c10b4a310e6d) through this protocol; the
registry now carries that ref and the engine lane owns the matching
manifest/build distribution.
GSQ-RCO Coder — two engines, no default flip
The GSQ-RCO Coder pin (ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-Coder-GGUF
@ 5348543e0147355ac9cbcb031184a3546350988e) is registered twice:
qwen38_gsq_coder — the Strata 0.1.44.1 engine row
(Niko1221/Strata@296b59d2f7), standardized 256k/batch4/MTP
(the Sol lane declares slots_max 2 under the registry big-lane cap;
the engine template carries batch4), kind => staged,
production => false. The strata_sm86 runtime/install is the engine
lane’s module, not the llama.cpp engine-install.sh path.
qwen38_gsq_coder_llama — the llama.cpp b11639 fallback on the same
shards (measured recipe --fit on --fit-target 256 --moe-cache-mib 4096,
KV q4_0), kind => staged, production => false. The registry schema
currently exposes fit/load_mode but not fit_target/moe_cache_mib;
that argv surface is the engine lane’s follow-up, so the row
records the recipe but does not yet render those two flags.
Both rows are validation-only: the ghost P7 rows are origin=ghost
provenance, and the zerg-side needle/parity run is. The two open
ghost gates (mmproj formal caption A/B; code/agentic tool-call JSON
spot-check versus the full model) also remain open. Do not flip a default
or promote either row from ghost evidence.
7. Requesting and switching lanes from Luna
Luna’s lane provider is grant-driven: the worker asks Sol
(lane_control resolve | start | stop | switch), and Sol answers with the
descriptor (lane, endpoint, wire format, caps, ctx, lease id, expiry).
Operators normally do not need to act — an agent session requests a lane
when it needs one. When a request is refused, Luna surfaces the typed
reason; the corresponding registration/lease gates are in
docs/zmq-protocol-reference.md and the lane control section of the
security docs.
Fallback ownership with a Sol binding
A task carrying a Sol binding (the inference_binding lane grant, or a
granted lane_control_ack) is Sol-managed inference: Sol owns fallback.
Luna’s provider_failover recognizes a Sol-bound provider
(lane_grant/keyless) and never model-switches — it keeps only its
transport-level retries and falls through to the typed error; the
server-side chain (fallback_chains in the declarative-provider config —
see docs/provider-setup.md) is the single fallback plane. Without a
binding (a direct-provider config: TUI/print against your own keys), the
client-side fallback_providers/fallback_model chain is unchanged.
No wire field changes: the binding already travels on the task frame.
Interactive editor sessions
An editor session is a session lease with refresh, not a per-turn
resolve. The lane grant is still ACQUIRED by the first task Sol dispatches
to the worker (the identity/ownership anchor is unchanged); while the
session is active Luna refreshes the live lease through the existing
lane_control frame:
| action | fields (existing wire shape) | semantics |
|---|---|---|
resolve / start | task_id + lane/requirements + mode/ttl_ms | acquire (task-scoped, the only way to start a session) |
refresh | lease_id + holder + lane | renew under the lease’s own mode; the ack carries the receipt-relative expires_in_ms |
release | lease_id + holder + lane | drop THIS worker’s hold and re-arm the lane’s idle clock; the lane is not stopped while other holders exist |
switch | lease_id + holder + target lane | resolve the target under the grant-recorded owner, then drain the old lane |
holder is the nonce minted with the grant; the owner is the
store-derived identity captured at grant time — a frame-supplied
user_uuid is never trusted. Expiry answers stale_grant (a TYPED
re-request on the next turn); there is no silent fallback. Audit rows:
lane_session_refresh, lane_session_release, lane_session_switch,
lane_session_stop. The editor launches this posture with
luna --connect tcp://<sol>:5555 --editor (the :ZergConnect command in
example/vim); when no Sol is reachable the editor keeps the standalone
stdio posture.
8. New machine-class onboarding
- Build the engine for the class (CPU/GPU, flags per the engine matrix)
and add the
engines/<class>.jsonmanifest row (production,ref,build,cmake_flags,arch; the fixture engine carriesproduction: false+exclude_reasonand never promotes). - Add the class to
node_classesand its facts tolane_host_policy(VRAM/RAM budgets, session cap, allowed lanes, host env). - Start the lane on the new host and run the needle gate; append the row
with
scripts/lane-certify.sh. - Only then does the lane become placement-eligible on that class.
9. “No lane available”
Luna prints a typed failure instead of silently falling back:
lane_unavailable: <reason> (lane=<lane>) — no local lane available; start a
lane with POST /api/v1/start or POST /api/v1/prepare/:name; list lanes with
GET /api/v1/inference/lanes
Operator checklist: is the lane running (GET /api/v1/inference/lanes)? Is
it validated (fresh needle row, not stale, parity within band)? Is the
worker registered on the same node/lease? Is the host VRAM budget full
(check the governor state and sol_lane_placement_refused_total)? A
keyless remote provider is never a substitute — there is no fallback lane
by design.
10. Operator event queries (the event spine)
The lane lifecycle, maintenance flips and restore verification are durable
events in the sync-event store (lane.*, maintenance.*, restore.* —
the spine). Query them through the events API with an admin token;
the executable form of these three chains is exercised by
server/test/sol_event_spine_runbook_SUITE.
TOKEN=<admin-token>
BASE=http://127.0.0.1:21434
LANE=qwen38_atx
NODE=sol@$(hostname)
# What happened to lane $LANE: every lane event, newest first.
# (types: lane.requested/granted/queued/failed/lease_* /cron_* /fallback/…)
curl -s -H "Authorization: Bearer $TOKEN" \
"$BASE/api/v1/events?aggregate=$LANE&limit=100"
# Why did maintenance flip: the node's maintenance.enabled/disabled rows
# (aggregate = the Sol node name; data.reason carries the operator reason).
curl -s -H "Authorization: Bearer $TOKEN" \
"$BASE/api/v1/events?aggregate=$NODE&limit=20"
# Was restore verified: restore.verified / restore.mismatch /
# restore.checksum_mismatch (aggregate = the fixed `restore` scope).
curl -s -H "Authorization: Bearer $TOKEN" \
"$BASE/api/v1/events?aggregate=restore&limit=10"
A lane that never granted still has a trail: lane.failed carries the
typed refusal (data.reason) on the requested lane aggregate, and
pre-resolve failures land on the unknown aggregate. Cross-node stores
are node-sharded (docs/event-store.md §Cluster scope) — query the node
that granted the lane.
11. Standalone / air-gap editor hosts
A Sol-less host — an air-gapped laptop, a single editor box, a field
machine — runs a ZERG-provenanced engine bundle, never an arbitrary
daemon. The standalone posture is explicit (--standalone /
ZERG_COMPLETE_STANDALONE=1), never implicit: a host with a reachable Sol
uses the Sol-bound posture; a host without one declares standalone.
Ownership split (standing). wild owns CD: engine images, builds, bundle
production and publishing (build-engines → supply-chain →
push-staging → publish-release). zerg owns the bundle format, the
consumer recipe (scripts/engine-bundle-consumer.sh), the install/rollback
scripts and these docs.
11.1 The bundle
A engine bundle is the whole-tree distribution unit:
<artifact>.tar.gz # bin/ + lib/ (self-contained, $ORIGIN rpath)
<artifact>.tar.gz.sha256 # mandatory (fail-closed)
<artifact>.tar.gz.manifest.json # build/class/host_class/manifest_hash
<artifact>.tar.gz.minisig # optional signature (REQUIRED by the consumer)
bundle-receipt.json # optional ZERG bundle receipt
The consumer verifies sha256 always, the manifest hash shape, an
optional bundle-receipt.json (artifact/sha/build/manifest-hash equality),
and the minisign signature. Unsigned bundles are refused unless
--allow-unsigned is passed explicitly (fixture/local bundles only); a
present-but-invalid signature is always a refusal. A missing .sha256 or
a tampered artifact is a typed refusal before anything is unpacked.
11.2 Side-load (air-gap) and explicit fetch
Air-gap hosts side-load the bundle directory (USB/rsync/scp — the operator chooses the transport; the consumer never fetches in standalone mode):
scripts/engine-bundle-consumer.sh verify --bundle-dir /media/zerg/bundle
scripts/engine-bundle-consumer.sh install --bundle-dir /media/zerg/bundle \
root "$HOME/.local/share/zerg/engines"
A networked mirror host may explicitly fetch (the fetch is the operator’s egress action; the editor path never fetches):
scripts/engine-bundle-consumer.sh fetch --url https://mirror.example/zerg/engines \
artifact llama-b11639-linux-x86_64.tar.gz \
dest /srv/zerg/bundles --with-signature --with-receipt
Fetch accepts https or EXACT loopback http (localhost, 127.0.0.1,
[::1] only — 127.attacker.example is not loopback); a non-loopback plaintext mirror
needs the explicit --allow-insecure-http ack. Every downloaded bundle is
verified before the command reports success.
11.3 Host class and install location
The manifest carries host_class / min_microarch /
required_cpu_flags; engine-install.sh refuses a wrong-target artifact
with the typed incompatible_host_class reason (for example a
cpu_epyc/znver4/AVX-512 build on a Zen-1 host, the class —
never install-and-hope). --host-class cpu_zen1 additionally pins the
install to that class; a bundle labelled otherwise refuses
host_class_mismatch.
The default root is ${XDG_DATA_HOME:-$HOME/.local/share}/zerg/engines
(override --root or ZERG_ENGINE_ROOT). System roots (/, /usr,
/etc, …) are refused unless ZERG_ENGINE_ALLOW_SYSTEM_ROOT=1 in a
disposable container. Installs are serialized by engine-install.sh’s
flock, keep the previous build for rollback, and write both the engine
receipt (<root>/installed.json) and the consumer receipt
(<root>/bundle-consumer.json).
11.4 Upgrade, status and rollback
scripts/engine-bundle-consumer.sh upgrade --bundle-dir /media/zerg/bundle-v2 \
root "$HOME/.local/share/zerg/engines"
scripts/engine-bundle-consumer.sh status --root "$HOME/.local/share/zerg/engines"
scripts/engine-bundle-consumer.sh rollback --root "$HOME/.local/share/zerg/engines"
upgrade requires an existing current and uses the same verification as
install. rollback delegates to engine-rollback.sh: the candidate’s
receipt is compared against a freshly computed tree hash and the candidate
is health-probed before the current flip; no candidate is a loud refusal.
11.5 Run the engine (no Sol, no lane registry)
The installed unit is <root>/current/{bin,lib}. Start the packaged
server directly on loopback with the model row’s measured flags:
"$HOME/.local/share/zerg/engines/current/bin/llama-server" \
host 127.0.0.1 --port 18001 \
model /fun/models/qwen38-gsq-rco/Qwen3.8-Flash-Next-GSQ-RCO-Coder-IQ1_M.gguf
curl -fsS http://127.0.0.1:18001/health
No Sol, no lane registry, no orchestrator: the engine is a bundle + this
recipe. A strata-class bundle runs its packaged wrapper instead
(bin/strata-server --config lib/strata/config/...); it has no FIM surface
today.
11.6 Settings providers (chat + standalone completion)
Declare the local engine once in the layered settings; chat routes to it
through the normal provider stack (keyless-loopback rule: explicit
no_api_key = true, loopback only), and standalone completion uses the
same record:
{
"model": "local-chat",
"providers": {
"local": {
"base_url": "http://127.0.0.1:18001",
"wire_format": "openai",
"models": ["local-chat"],
"no_api_key": true
}
},
"standalone": {
"provider": "local",
"model": "local-chat"
}
}
The keyless rule is fail-closed: no_api_key with a non-loopback
base_url is refused at config load; a keyed provider cannot be used for
standalone completion. Completion is explicit:
printf '{"prefix":"def add(a, b):\n ","suffix":""}' \
| client/run --complete --standalone
The local engine’s /infill carries the same window/token/stop/trim
semantics as the Sol-bound POST /v1/completions path (prefix tail 8000 B,
suffix head 1000 B, 96-token default budget, earliest-stop cut,
suffix-overlap removal, CRLF→LF, trailing-whitespace trim). The loopback
authority is DNS-pinned and the transport bypasses any proxy environment
(CURLOPT_RESOLVE + NOPROXY="*"), so a proxy variable cannot route the
call off-host. A down or misconfigured engine is a typed local_engine_*
error — there is no Sol/cloud fallback in the standalone posture.
Air-gap acceptance transcript (fixture bundle + mock engine):
plan/standalone-airgap-acceptance.md.
12. Revision 2 scope
Embeddings, reranking and LoRA serving are out of scope for this revision.
The extension hooks are the lane kind, the registry schema, and the
grant’s wire_format + caps; nothing in the current contract blocks them,
but no operator should expect them from this release.
Engine reference — generated from the canonical engineering source. Do not edit this page by hand.
Audit Log Retention (Mango)
Status: implemented (, /; migration v0014;
event-archive audit_events retention added ).
Scope: the Mango relational audit store (audit_logs). Sol’s JSONL audit
chain has its own retention sweep — see Seats vs. stores.
audit_logs was previously retain-forever by construction. A naive prefix
DELETE is not an acceptable remedy: verify_integrity requires the first
observed sealed row to be seq = 1 (truncated_head) and a deleted middle
row is a seq_gap, so the integrity tool would flag lawful hygiene as
tampering. Retention is therefore an explicit, signed, operator-invoked
contract:
the OLDEST sealed rows are deleted in bounded chunks;
a signed retention floor (audit_chain_retention) advances in the
SAME transaction as each chunk’s DELETE;
verification treats retained_from_seq + 1 as the legal chain root while
every signature / adjacency / checkpoint check above the cut is unchanged.
There is no automatic or date-based retention for the Mango DB store.
Pruning is a deliberate operator action (CLI, --yes).
Marker contract (migration v0014)
mango/migrations/v0014_audit_retention_floor.py creates a single-row table
(id INTEGER PRIMARY KEY CHECK (id = 1)):
| Column | Type | Meaning |
|---|---|---|
retained_from_seq | BIGINT NOT NULL | Highest sealed seq lawfully pruned. Rows at/below it are absent by contract. |
boundary_seq | BIGINT | First surviving sealed row above the cut. |
boundary_signature | TEXT | That row’s chain signature — cryptographic continuity across the cut. |
marker_mac | TEXT NOT NULL | Hex HMAC-SHA256 over the domain-separated material (below). |
updated_at | DOUBLE PRECISION NOT NULL | When the marker was last (re)written. |
The MAC material is:
"mango-audit-retention-v1|" + canonical JSON
{"boundary_seq":..., "boundary_signature":..., "retained_from_seq":...}
(sort keys, compact separators, ASCII). The prefix is a domain separator: a
retention marker can never be replayed as a row signature or a checkpoint
anchor MAC even though all three use the same key. Writes use the active
MANGO_AUDIT_CHAIN_SECRET; verification accepts the whole trusted ring
(MANGO_AUDIT_CHAIN_PRIOR_SECRETS included), so a marker outlives key
rotation. The UPSERT is monotonic — a lower floor never regresses the
marker.
Generation bounding. New anchors and markers stamp
the writing key generation (key_epoch, migration v0017) and MAC under
generation-bound v2 material, so verification resolves ONE key: a
retired (potentially weaker) generation can no longer vouch for an
artifact the current era wrote. NULL-epoch rows are the pre-v0017 corpus
and keep the legacy ring-wide v1 verification byte-for-byte. Every
MANGO_AUDIT_CHAIN_PRIOR_SECRETS entry carries the SAME 16-byte floor as
the active secret — a short retired key is brute-forceable and its ring
membership would let it vouch for chain anchors; a short entry refuses at
boot (name the entry, store the ORIGINAL retired secret, and rotate it
out of the ring only once every row it signed is outside the retention
window). A benign stale anchor (the anchor trio agrees behind a fully
verified tail — a write-time checkpoint refresh failed) is the typed
anchor_stale verdict, NOT tampering; the next clean scan re-anchors
forward.
Legacy rows with seq IS NULL (pre-v0003) are OUTSIDE the chain and are
never pruned.
Operator prune
# inspect the plan (no writes; no --yes needed)
MANGO_AUDIT_CHAIN_SECRET=... python3 scripts/prune_audit_log.py \
db postgresql://... --keep 50000 --dry-run
# prune the oldest rows, keeping the newest 50000 sealed rows
MANGO_AUDIT_CHAIN_SECRET=... python3 scripts/prune_audit_log.py \
db postgresql://... --keep 50000 --chunk-rows 5000 --yes
# verify the floor-anchored chain afterwards
MANGO_AUDIT_CHAIN_SECRET=... python3 scripts/verify_audit_chain.py \
db postgresql://...
--keep N is required (N >= 1); --yes is required for a real prune and
is refused (exit 2) without it. The prune cuts at
cutoff = MAX(seq) - keep.
The configured chain key is REQUIRED. An ephemeral
chain key (the per-process random fallback when
MANGO_AUDIT_CHAIN_SECRET is unset) refuses before any destructive
chunk: markers/anchors/audit rows that process would write are signed
with a key the live configured app rejects — the pre-fix shape could
poison the chain head and turn every later privileged write into a 503.
Export the secret exactly as the examples above show. The explicit
--allow-ephemeral ack runs WITHOUT the configured key only on an
UNANCHORED store (no checkpoint, no retention marker): it deletes the
rows, writes NO signed artifact (no marker, no chained audit row), logs
a CRITICAL, and is irreversible — a later configured-key verify will
report the cut.
Each chunk deletes at most --chunk-rows rows (default
MANGO_AUDIT_PRUNE_CHUNK_ROWS = 5000, env_int-guarded), and the chunk’s
DELETE + marker advance commit together in one transaction. A crash between
chunks leaves the floor at the last fully committed chunk — always a legal
monotonic marker — and the next operator run converges from there. The final
partial chunk still advances the marker to cutoff, so the retention line
is recorded even when the window is all burnt seqs.
Locking follows the audit write path (transaction → the PG
pg_advisory_xact_lock used by _lock_chain_write → the module chain
lock), so a prune chunk cannot interleave with a chained audit write. The
prune re-reads the marker inside each chunk transaction and refuses
(RuntimeError, CLI exit 1) when:
the marker is corrupt (HMAC/parse failure), the marker moved since the run computed its plan (concurrent prune), the checkpoint is invalid, behind the chunk cutoff (the cut may never sit above the vouched tail), or ahead of the surviving tail (a truncated store — verify/restore before pruning), the marker-bound boundary row is missing or replaced, sealed rows exist at/below the signed floor (history reappeared below a lawful cut — restore/tamper).
Return value: {"pruned": N, "cutoff": cutoff, "floor": new_floor, "dry_run": bool}. With --dry-run, pruned is the number of rows the run
would delete. Deleted rows are exported as
mango_audit_retention_pruned_rows_total (export-only health datum; no
alert/panel consumer yet).
Floor-aware verification
Audit.verify_integrity reads the signed marker before the row scan
(anchor-first, like the checkpoint), so a concurrent prune cannot produce a
false truncation verdict. With no marker, the historical contract is
byte-for-byte unchanged.
With a valid marker at floor:
| Observation | Verdict |
|---|---|
first sealed row seq == floor + 1 | legal chain root (no truncated_head) |
first sealed row seq <= floor | typed retention_floor_mismatch |
first sealed row seq > floor + 1 | seq_gap with missing_after = floor |
| marker bound a boundary row and its signature changed | retention_floor_mismatch (detail = boundary_signature_mismatch) |
marker floor > checkpoint seq | typed retention_floor_mismatch (inconsistent store) |
| missing/corrupt marker MAC or unparseable marker | typed retention_marker_invalid, ok = false |
| missing marker | existing behavior (truncated_head if first seq!= 1) |
Off-host anchor files carry their generation. An
anchor exported from a v0017+ store must include "key_epoch": N in the
JSON ({"seq": N, "signature": "...", "checkpoint_sig": "...", "key_epoch": N}) — the MAC is generation-bound, so a v2 anchor without its
generation verifies as checkpoint_invalid. Pre-v0017 anchor files (no
key_epoch) keep the legacy ring-wide v1 check unchanged.
Signatures, adjacency, key-epoch, and checkpoint truncation/rewind checks
above the floor are unchanged. verify_audit_chain.py prints
retained_from_seq alongside the verdict and treats a clean chain anchored
to its checkpoint as ok — a floor-anchored clean chain passes, while an
Unanchored chain still exits non-zero. The floor is deliberately NOT a
verdict key: the cross-language verdict contract
(docs/fixtures/audit_verdict_keys.json) gains no new keys. The two new
reason tokens (retention_floor_mismatch, retention_marker_invalid) are
Mango-only emissions; Sol’s per-file JSONL walk has no relational floor.
Backups and key warning
Back up the store WITH its chain key before pruning. After the cut the
remaining chain (and the marker MAC) is verifiable only with
MANGO_AUDIT_CHAIN_SECRET plus every generation in
MANGO_AUDIT_CHAIN_PRIOR_SECRETS. A database restored without the matching
keys reports key_epoch/signature_mismatch — honest, but not recoverable.
Restore the database and its key ring as one unit; restoring an OLDER
database while keeping a newer retention marker (or vice versa) is the
“history reappeared below the floor” / “marker ahead of checkpoint”
inconsistency and fails verification by design.
Archive store
audit_events is a DIFFERENT store from the relational audit_logs chain:
Sol’s event-archive plane (sol_event_archive) POSTs archived events to
Mango’s /api/mango/audit-archive, and Mango persists them there (the
canonical RFC3339 timestamp string, three indexes). It has no signed
chain and no floor marker, so retention is a plain AGE-based job:
# inspect the plan (no writes; no --yes needed)
python3 mango/scripts/prune_audit_events.py --db postgresql://... --days 30 --dry-run
# prune rows older than 30 days, chunked (default 5000 rows/statement)
python3 mango/scripts/prune_audit_events.py --db postgresql://... --days 30 --yes
Automatic: Mango now runs the same prune hourly
(MANGO_AUDIT_EVENTS_RETENTION_INTERVAL_SECONDS, default 3600; 0
disables the loop). Each automatic run is chunk-bounded (100 chunks) so a
first pass over a large backlog never monopolises the IOLoop; the
operator CLI below remains the unbounded drain-to-empty surface.
Window: --days N (default MANGO_AUDIT_EVENTS_RETENTION_DAYS = 30).
--days 0 is the explicit archive-off posture — keep everything,
write nothing.
Chunking: MANGO_AUDIT_EVENTS_RETENTION_CHUNK_ROWS (default 5000) bounds
every DELETE statement, so a first run over a large backlog never holds
an unbounded statement/transaction open.
Scheduling: wild owns the fleet cron/systemd timer; run the job at least
once per retention window.
Observability: /metrics exports
mango_audit_events_oldest_age_seconds (scrape-time, 60s cache, from the
indexed MIN(timestamp); absent on an empty archive).
MangoAuditEventsRetentionStalled (warning) pages when the oldest row is
older than the default window + 7 days.
Backup policy: this table is part of the Mango database backup (SQLite
hot copy / pg_dump, docs/backup-and-dr.md §2). A first prune is
destructive and irreversible — take a backup first. Restoring an older
database restores the rows; nothing else references them by sequence.
Seats vs. stores
audit_retention_days in the seat/license caps is a licensing/gating
flag surfaced in Limon (see docs/seats.md); it does NOT drive Mango DB
pruning. Mango retention is the operator CLI above only — never a background
policy. Sol’s filesystem audit chain (audit-*.jsonl) has a separate daily
sweep keyed by Sol’s audit_retention_days application setting; that is a
different store with a different lifecycle.
Engine reference — generated from the canonical engineering source. Do not edit this page by hand.
Cost & Spend Enforcement
Cost-accounting scope. This page documents inference cost accounting from model-provider rate metadata. It is not a commercial offer; commercial terms are not announced. For licensing or evaluation, contact Spacebeam.
Decision: ENFORCE. The server has a real rate source and a per-principal daily ledger; inference admission is gated before upstream spend. The retired alternative (delete the cost API and keep the token-rate proxy as “truth”) was not taken.
What carries rates
The declarative model catalog (contract/model_catalog.yaml →
server/priv/model_catalog.json) is the billing rate source (
), read through sol_cost:price/1 / sol_cost:estimate/3.
Aliases and local lane ids resolve through the same catalog lookup; a
a zero-rate local entry is deliberate; a model with no catalog row or
no numeric rate block is unknown_price — never silently zero.
cost_unknown_price_total and inference_model_unpriced_total{model} are
both counted on that path. sol_model_metadata is the fallback for
operator-only rows/tests (and for dated ids the catalog does not list).
Ollama discovery rows are namespaced (source => dynamic, namespace => ollama): a refresh never overwrites a static/operator row and deletes its
own stale rows. See catalog.md and the rate notes in
api-reference.md.
Ledger
sol_spend_guard keeps one public ETS table (sol_spend_ledger) with two
row families:
{daily, UserUuid, UTC-day}— input tokens, output tokens, USD micros (settled) plus pending columns for reservations;{model, UserUuid, UTC-day, Model}— the same totals per model, used byGET /api/v1/usage.
Arithmetic. used, pending and remaining are
disjoint: a reservation adds to pending only, settle/2 removes the
pending amount and adds the actual usage, and release/1 removes pending
without billing. The strict reserve/2 path serializes its check+reserve
pair per principal/day (an ETS lock row); the pre-fix shape added an
estimate to used and pending, so every reservation was
double-counted and the ledger permanently inflated. GET /api/v1/usage
reports pending_* and remaining_* alongside the settled totals.
Window. The day key is the UTC calendar date; a new UTC midnight
starts at zero automatically (old days stay readable until the table is
reset). Durability. The ledger
is in-memory, anchored to a supervisor heir. When a fresh table is created
(a VM/app restart; a heir-survived table is compared, never reset), the
current UTC day is rebuilt from the tenant-attributed
inference.complete events, deduped by request_id. The rebuild now
PAGES the whole day with the until/until_id older-side cursor
(sol_sync_event:get_all_events/1) until exhausted — the pre-fix shape
read one newest-first 10k window with no truncation detection, so a busy
day silently under-reported. The absolute page bound
(inference_ledger_rebuild_max_events) turns a pathological log into a
TYPED truncation: sol_billing_ledger_rebuild_truncated_total increments
and neither rebuild_day/0 nor reconcile/0 reports success/match on
an incomplete read. With sync_enabled=false there is no durable source
at all: the rebuild refuses with sync_disabled and bumps
sol_billing_ledger_rebuild_skipped_sync_disabled_total rather than
claiming a successful empty rebuild. A mismatch between the ledger and the
durable projection bumps sol_billing_ledger_reconcile_mismatch_total and
logs CRITICAL; an event without a user_uuid bumps
sol_billing_ledger_unattributed_total (it cannot be reconstructed for
chargeback).
Bounded housekeeping. The one-shot settlement
markers ({settlement_applied, RequestId} and {worker_turn, TaskId}) are
idempotency latches, not history: they are TTL-pruned
(inference_ledger_marker_ttl_ms) on a bounded cadence
(inference_ledger_prune_interval_ms, a marker row claims the interval);
sol_spend_ledger_markers_pruned_total counts the reclamation. Stale
reservations are swept across EVERY principal/day older than
inference_spend_reservation_ttl_ms (the pre-fix sweep matched only the
caller’s current principal+day, so a request that crashed across UTC
midnight held its pending estimate forever).
Shipped posture. The rebuild’s source
is the durable event log, which only exists when the sync forwarder is
installed (sync_enabled=true, the shipped default in both sys.config
and sys.prod.config). While sync_enabled=false the forwarder is not
installed, inference.complete never reaches the store, and the boot
rebuild reads an empty source — the previous shipped shape that made
this doc’s rebuild claim vacuous. sol_event_sync_forwarder_installed
(absent = disabled, 0 = install failed) and the
SolSyncForwarderPosture alert are the operator-visible truth. The
shipped posture is asserted by ci/release_posture_lint.py and the
release-artifact CI job; a config flip back to false is a loud
failure, not a silent degradation.
Admission gate
All four streaming ingress paths — local OpenAI, remote OpenAI, local
Anthropic, remote Anthropic (and the provider/registry variants that share
the remote start functions) — call sol_spend_http:admission/5
(sol_spend_guard:reserve/2) before the pipeline starts, i.e. before
any upstream request. The FIM lane and Lua child inference
(sol_lua_inference:complete/2) use the same reservation funnel. A
refusal is dialect-typed:
| Condition | Status | Code |
|---|---|---|
| Daily token or USD cap crossed | 429 + Retry-After (seconds to UTC midnight) | inference_budget_exceeded |
Model has no rate while a USD cap is enabled and the policy is deny | 400 | model_unpriced |
| Guard infrastructure failure, USD cap enabled | 503 + inference_budget_unavailable | — |
| Guard infrastructure failure, no USD cap | admission continues (fail-open), logged | — |
Worker/fleet scope. The
per-principal USD/token ADMISSION axes cover the Sol-side provider paths
and Lua child inference — every HTTP ingress and
inference.complete from Lua reserves/settles through the same funnel.
Worker-plane admission remains TASK-CAP-ONLY in this window: no USD or
token reservation is made at ZMQ/stdio dispatch. A worker turn that reports
a usage rider IS settled into this same day ledger after the fact
(sol_billing_worker:settle_result_frame/3 → inference.complete →
sol_spend_guard:settle_worker_turn/3, ), so worker spend is
visible and chargeback-true — it is just not ADMITTED against before the
work runs. The central worker admission/sidecar decision is owned by
ADR-0005 stage 1 and is NOT implemented here; do not read this ledger as a
fleet-wide pre-dispatch USD cap. The worker plane’s enforced budget is its
own per-principal daily task cap at the ZMQ dispatch funnel
(sol_zmq_task_dispatcher:dispatch/4 → sol_spend_guard:admit_worker/1):
| Condition | Status | Code |
|---|---|---|
| Daily worker-task cap crossed | 429 on HTTP chat/worker surfaces; typed {error, {inference_budget_exceeded, #{axis => worker_tasks, …}}} on the ZMQ dispatch/background-spawn planes | inference_budget_exceeded |
The cap is enforced at EVERY worker-send funnel — ZMQ dispatch, the stdio
sol_worker:send_task/2 path used by chat REST/WS/worker REST, the one-shot
sol_worker_bg background worker, and ZMQ background child spawn — so
changing transport cannot bypass it. It counts
Admitted placements (including tasks queued behind a busy worker); a
refused placement (overload/queue-full/send failure) refunds the slot.
sol_inference_budget_exceeded_total{axis="worker_tasks"} counts refusals;
0 disables the axis.
A worker result that carries a provider usage rider lifts
tokens_used/input_tokens/output_tokens onto task.completed and is
settled idempotently per task id (the marker is TTL-pruned). A Luna client
that omits usage settles nothing for that turn (skip, never a fabricated
zero) — the documented residual until every client stamps usage.
Overshoot semantics. This is check-before-dispatch, not a distributed
lock: the admission test includes the day’s settled total plus this
request’s projected input estimate (bytes/4) and the effective
max_tokens — a caller-supplied value, or the configured
default_max_tokens (4096 fallback) when omitted, never 0 ( /
PRV-08). Requests
already in flight when a cap is reached are not interrupted, so the
overshoot is bounded by the summed usage of concurrently admitted requests
(each bounded by its max_tokens, plus input-estimate error). New
requests are refused once the settled/pending total reaches the cap.
reserve/2 is the strict form (parks the estimate in pending only);
a successful reservation MUST be settle/2-ed (actual usage) or
release/1-d (never ran). The HTTP ingress paths, the FIM lane and Lua
child inference all use
reserve/2 — concurrent children cannot overshoot the cap; the pre-fix
Lua path used the check-only snapshot.
Configuration
| Key | Type | Default | Meaning |
|---|---|---|---|
inference_daily_budget_usd | number | 0 | Per-principal daily USD cap; 0 disables the USD axis. |
inference_daily_token_budget | integer | 0 | Per-principal daily token cap (input + output); 0 disables. |
inference_worker_daily_task_budget | integer | 0 | Per-principal daily worker-task cap at every worker-send funnel (ZMQ dispatch, stdio chat/WS/REST, one-shot background worker, ZMQ background child spawn); counts admitted placements, not tokens; refused placements refund; 0 disables. |
inference_unknown_price_policy | atom/binary | deny | When a USD cap is enabled: deny refuses unpriced models (model_unpriced); allow admits them and records cost 0 (counted). |
inference_daily_budget_overrides | map | #{} | Optional per-user overrides: #{<<"user-uuid">> => #{daily_budget_usd => N, daily_token_budget => N, daily_worker_task_budget => N}}. A missing axis falls back to the global value. |
inference_ledger_rebuild_on_boot | boolean | true | Rebuild the current UTC day ledger from the durable inference.complete events when the ETS table is first created. Test VMs/ledger fixtures disable it and drive sol_spend_guard:rebuild_day/0 explicitly. |
inference_ledger_rebuild_page_size | integer | 10000 | Durable-event page size for the boot rebuild/reconcile walk. |
inference_ledger_rebuild_max_events | integer | 1000000 | Hard bound on a rebuild; exceeding it is a typed rebuild_truncated (never a silent short rebuild). |
inference_ledger_marker_ttl_ms | integer | 86400000 | Retention of the one-shot settlement markers before the bounded prune may delete them (must exceed the settlement retry horizon). |
inference_ledger_prune_interval_ms | integer | 60000 | Minimum cadence between marker-prune / cross-day reservation sweeps. |
inference_spend_reservation_ttl_ms | integer | 600000 | A parked reservation older than this is reclaimed on ANY principal/day (crash across midnight included). |
The caps are per user_uuid (the authenticated principal; identity-loss
flows use the server’s system/internal principal). Configure via the
Sol app env (or SOL_CONFIG_FILE); the keys are also documented in
configuration-reference.md.
Read surface
GET /api/v1/usage — self by default; an admin may pass
?user_uuid=<uuid>. Optional ?from=YYYY-MM-DD&to=YYYY-MM-DD (UTC,
inclusive; to defaults to today, from is unbounded). Scope:
inference:use. Response:
{
"user_uuid": "…",
"days": [
{"day": "2026-10-17", "input_tokens": 1200, "output_tokens": 800,
"total_tokens": 2000, "cost_usd": 0.0123,
"pending_input_tokens": 0, "pending_output_tokens": 0,
"pending_total_tokens": 0, "pending_cost_usd": 0.0,
"remaining_tokens": 98000, "remaining_cost_usd": 4.9877,
"models": [{"model": "gpt-4o", "input_tokens": 1200,
"output_tokens": 800, "cost_usd": 0.0123}]}
],
"totals": {"input_tokens": 1200, "output_tokens": 800, "total_tokens": 2000,
"cost_usd": 0.0123, "pending_input_tokens": 0,
"pending_output_tokens": 0, "pending_total_tokens": 0,
"pending_cost_usd": 0.0, "remaining_tokens": 98000,
"remaining_cost_usd": 4.9877},
"budget": {"daily_budget_usd": 0, "daily_token_budget": 0,
"unknown_price_policy": "deny"}
}
Events and the workflow ledger
Every inference terminal — success, interrupted, cancel, caller DOWN,
inference DOWN, parse error, crash — settles exactly once through
sol_pipeline:settle_terminal/2 (the terminate/3 flush is the crash
backstop; a settlement failure is CRITICAL and counted). The settlement:
- uses the provider’s four billed counters
(
sol_anthropic_stream:usage_full_from_wire/1: input, output, cache creation, cache read); - treats the provider’s usage as AUTHORITATIVE for each side it reports; the
delivered
bytes/4estimate is the floor only for an unreported side, so an omitted usage chunk never settles0; - floors the INPUT side with the request estimate (the admission
reservation’s estimate, or the same
bytes/4projection over the request messages for direct/FIM callers) when the provider reports no input tokens, and marks the settlementinput_estimated=true( / WF-10) — a usage-less provider no longer bills input0; - never drops a partial usage report: an input-only or cache-only chunk is
carried, rated and settled (the Anthropic egress emits the known sides
with absent sides
null); - rates input/output and the catalog’s
cache_read_per_mtok/cache_write_per_mtok(cache tokens without a declared cache rate are marked unpriced + counted, never silently 0); - attributes the SERVING model (a lane id/alias resolves to the lane’s
actual model row; catalog aliases resolve to the canonical id) and adds
request_id,user_uuid,provider,provider_key_id, the four token counters,cost_usd,currencyandoutcometo theinference.completeevent.
Wire usage vs settled usage
The client-facing stream carries the provider’s raw usage counters
(absence marked, never invented): an OpenAI chunk’s
prompt_tokens/completion_tokens, or an Anthropic message_delta usage
object. The Anthropic message_start intentionally omits usage until the
provider total is known — the previous shape fabricated input_tokens: 0.
The settlement is the authoritative billing figure and is a superset of
the wire usage: a side the provider reported is used verbatim; an unreported
input side is floored by the request estimate and marked
input_estimated=true; an unreported output side is floored by the
delivered bytes/4 estimate. Every difference between wire usage and
settlement is therefore one of the named floors (input_estimate,
delivered_bytes), never an invented side.
Rates come from the model catalog only. sol_model_metadata carries a
legacy bundled table behind cost_legacy_metadata_price=true (default off);
the price_parity lint pins every shared id to equal rates, and dated
variants (-20250514) are the only prefix matches.
sol_billing (ETS, sol_billing_settlements) is the exactly-once latch
keyed by request_id; the durable record is the event payload. A
cancelled-with-delivered-tokens request therefore appears in the ledger
and the event log, and a restart rebuilds the per-tenant day from those
events (see Ledger above). The sync-event forwarder also lifts
input_tokens/output_tokens/model onto task.completed while keeping
the historical tokens_used sum.
The workflow cost_usd ledger remains passive by this decision: it
accrues only when an event explicitly carries cost_usd, and it is not a
workflow budget axis. Enforcement lives in sol_spend_guard, not in
workflow state.
Metrics and alerts
| Family | Type | Meaning |
|---|---|---|
sol_inference_spend_usd_total{model} | counter | Settled USD per model |
sol_inference_tokens_input_total{model} | counter | Settled input tokens |
sol_inference_tokens_output_total{model} | counter | Settled output tokens |
sol_inference_spend_today_usd | gauge | Settled USD today (UTC, all principals) |
sol_inference_spend_today_tokens | gauge | Settled tokens today |
sol_inference_daily_budget_usd / …_token_budget | gauge | Configured caps (0 = disabled) |
sol_inference_budget_exceeded_total{axis} | counter | Admission refusals by axis (tokens, usd, unpriced) |
sol_inference_model_unpriced_total{model} | counter | Unpriced settlements |
sol_billing_cache_write_tokens_total | counter | Settled Anthropic cache-write tokens |
sol_billing_cache_read_tokens_total | counter | Settled Anthropic cache-read tokens |
sol_billing_cache_unpriced_total | counter | Cache tokens with no catalog cache rate |
sol_billing_settlement_duplicate_total | counter | Duplicate terminal settlements (latch) |
sol_billing_settlement_failed_total | counter | Settlement write failures |
sol_billing_terminate_flush_failed_total | counter | Crash-terminate flush failures |
sol_billing_ledger_rebuild_events_total | counter | Durable events replayed at boot rebuild |
sol_billing_ledger_rebuild_truncated_total | counter | A rebuild stopped at the hard page bound (typed, never match) |
sol_billing_ledger_rebuild_skipped_sync_disabled_total | counter | Rebuild refused because sync_enabled=false (no durable source) |
sol_billing_ledger_reconcile_mismatch_total | counter | Ledger vs durable projection mismatches |
sol_billing_ledger_unattributed_total | counter | Billed events with no user_uuid |
sol_spend_ledger_markers_pruned_total | counter | One-shot settlement markers reclaimed by the TTL prune |
sol_billing_input_estimated_total | counter | Settlements whose input figure is the request estimate (usage-less/partial provider report) |
sol_spend_ledger_lock_timeout_total | counter | Reservation-lock timeouts (fail-closed) |
Alerts: SolCostBurnRate now reads the real USD family; new
SolInferenceBudgetExceeded and SolInferenceModelUnpriced rules page on
the refusal/unpriced families. See observability.md.
Engine reference — generated from the canonical engineering source. Do not edit this page by hand.
Engine supply-chain provenance & receipts
The engine supply chain produces the artifacts every local-inference certification claim points at. This document is the contract for what makes an artifact — and a certification record — trustworthy: provenance is verified, not asserted; receipts are ZERG-produced; and every gate refuses typed when the evidence is missing.
Provenance chain at a glance:
scripts/engines/build.sh --ref <40-hex> (verifies HEAD == ref + clean tree;
│ builds the COMMITTED tree)
▼
engines/<class>.json (provenance manifest: source_verified,
│ source_head, manifest_hash, image_digest)
▼
scripts/engine-install.sh --expect-build/--expect-ref (flock'd, sha256+minisign,
│ canary, atomic flip, receipt)
▼
<root>/installed.json + <root>/<build>/.zerg-engine-receipt.json (the install receipt)
│
▼
scripts/lane-certify.sh → POST /lanes/:lane/validate (commit) (origin=zerg + CSV row_ref
│ + receipt + parity evidence)
▼
<data_dir>/lane-validation.json (the runtime record the gates consume)
1. Source provenance (build.sh --ref)
A pinned build must be exactly the pinned commit. For --class cuda_sm86|cpu_epyc with --ref owner/repo@<40-hex>, build.sh:
- refuses unless the commit object exists locally (one best-effort
git fetch origin <ref>first — air-gap hosts pre-seed the object); - asserts the checkout’s
HEAD == ref(a different tree can never be labeled with the ref); - asserts the working tree is clean (
git status --porcelainempty — a patched tree is refused by name, with the dirty listing printed); - builds the committed tree via
git archive <ref>staged into a clean directory — never the operator’s working copy; - records submodule SHAs (
source_submodules) when.gitmodulesexists.
The emitted engines/<class>.json row carries
"source_verified": true plus "source_head": <40-hex>. A build without
--ref (floating HEAD) emits source_verified: false and can never be
production: --production requires --ref, and
ci/engine_manifest.py validate refuses any state=built|installed
production row without verified provenance (promotion-set validates every
row before projecting it,, ). ci/engine_manifest_lint.py
enforces the same rule over the committed corpus.
Anti-root guard: build.sh refuses to run as root unless
ZERG_ENGINES_ALLOW_ROOT=1 is set inside a disposable container. The
refusal path and the exact cmake argv are contract-tested
(TestEngineSourcePin, TestEngineCmakeArgv).
2. Manifest truth and the promotion set
engines/<class>.json rows are validated by ci/engine_manifest.py and
gated by ci/engine_manifest_lint.py:
state=reference rows may carry manifest_hash: "unverified" — they
are honest build targets, never promotable;
state=built|installed rows need a real 64-hex manifest_hash, a real
image_digest (sha256:<64-hex>; the literal local only for
non-hermetic production=false builds) and verified source provenance —
the validator enforces the provenance rule on both states (,
promotion-set admits built|installed, so a hand-written
installed row without source_verified is refused and never
promotion-eligible);
promotion-set prints only PROMOTABLE rows (production + built|installed
- verified hash, after validating every row); reference rows print as
production-targets— “the production set” can no longer contain an engine that was never built.
Registry↔manifest drift is a hard lint (ci/engine_config_drift_lint.py):
every production => true engine row in the configs must match exactly
one engines/*.json production row by (ref, build) — and vice versa.
Certification records compare against the config ref, so a stale
manifest would silently invalidate the evidence chain; the lint reds that
class at the gate.
3. The install receipt
scripts/engine-install.sh writes two atomic receipts:
<root>/<build>/.zerg-engine-receipt.json — per-build record
(build, class, manifest_hash, installed_at, sha256,
verified_by);
<root>/installed.json — the current-build record the runtime reads
(the same shape).
The receipts record the verified manifest_hash of the installed tree
(ci/engine_manifest.py tree-hash) and the artifact sha256. Production
lanes consume only ZERG receipts: the validation evaluator
(sol_lane_validation) refuses no_receipt when
<inference_engine_root>/installed.json is absent and
unverified_manifest when the record’s hash is the unverified
placeholder — an engine installed by any other means, a deleted receipt,
or a same-build-id byte swap invalidates the lane on the next read
(there is no trusted “validated” flag; every read re-compares).
--expect-build/--expect-ref pin the install to the registry’s engine
row, and ZERG_ENGINE_REQUIRE_MINISIGN=1 (default off) upgrades every
unverified signature path — absent .minisig, absent minisign binary,
failed verify — from the loud warning to a refusal. :
the CD publish lane now attaches the llama-* triple (tarball + .sha256
.minisig) and asserts the release carries it, so the first signature-bearing release is machine-verified; setZERG_ENGINE_REQUIRE_MINISIGN=1for installs from that release onward. Rollback re-verifies the candidate’s own receipt against a freshly computed tree hash before flipping: a tampered or corrupt candidate is refused withcurrentuntouched, soinstalled.jsoncan never record a hash that does not describe the tree the runtime gate is about to trust.
4. Weight receipts
scripts/lane-model-sync.sh writes lane-model-receipt.json beside the
weights with per-file sha256, verified and byte size. The start
path (sol_registry:verify_lane_pin) is receipt-first — it never
re-hashes a 15.6 GB file — but it re-stats the file against the
receipt’s bytes, so a truncated or swapped GGUF refuses
(primary_pin_unverified) without the hash pass. Receipts without
bytes stay valid on the digest match.
The unhashed posture is explicit-only:
non-production lanes (the fixture) accept unhashed as before;
production lanes require the operator’s pin_ack => true in the lane
row — otherwise the start refuses unhashed_pin_without_ack;
every unhashed-ack start bumps
inference_lane_weights_unhashed_total{lane=...} so the posture stays
visible until the pins converge (provisioning task: run
lane-model-sync.sh per lane/host, then flip the lane rows to real
pins).
5. Certification evidence rules
The commit route binds a validation record to the artifact evidence:
origin=zerg, artifact-CSV membership of the claimed row_ref (config
lane_benchmark_csv; configured-but-unreadable is a fail-closed 503),
an install receipt with a real manifest hash, and a parity verdict —
pass, or single_host only with the explicit allow_single_host ack
(lane-certify.sh --allow-single-host forwards and records it). See the
runbook §6 for the exact typed refusals and the operational flow.
6. CI lanes
Required (CPU-only, always on):
engine_manifest_lint + engine_config_drift_lint (drift reds the
gate);
source-pin contract tests (dirty tree / HEAD mismatch refused;
verified clean tree emits source_verified);
cmake argv contract (PATH-shim capture of both classes’ flags) and the
root-refusal contract;
fixture double-build + sabotage repro gate;
install/rollback drill incl. the real-engine-shaped canary, the
concurrent-install flock case and the --expect-* pin cases;
lane-certify --plan + mock-Sol multi-lane commit + the
single-host-ack rule.
GPU lane (off the required checks by design): the CUDA double build runs
inside the wild hermetic image (WILD-; digest-pinned before CD
wiring), followed by the install canary and one real certify
commit/readback on a GPU host. : the image
digest is now pinned in .crow.yml (build-engines) and the CUDA
double-build runs as that step’s post-leg; WILD-/9 are closed by the
handoff record.
7. Per-target class matrix & self-contained artifacts
Never cross-compile targets — an artifact carries the target it was built for and the installer enforces it:
build.sh emits host_class + min_microarch + required_cpu_flags
in every built row (cpu_epyc = epyc-znver4/x86-64-v4; cpu_zen1 =
zen1-avx2/x86-64-v3; cuda_sm86 = gpu-sm86/x86-64-v2);
scripts/engine-install.sh reads those fields from the artifact’s
manifest sidecar and refuses a host that lacks the flags with the typed
incompatible_host_class reason (blue is Zen 1 — a znver4 artifact is
refused, not SIGILLed; ZERG_ENGINE_CPUINFO overrides the flags source
for tests);
the CPU lane binds cpu_zen1 (the Zen-1-safe class); cpu_epyc stays
registered as the Zen 4 CPU-host target;
artifacts are self-contained: the rpath includes $ORIGIN (this
llama.cpp installs its .so set into bin/, not lib/) and
scripts/engines/stage-runtime-libs.sh bundles the CUDA runtime
(libcudart/libcublas/libcublasLt) + libgomp into bin/ for
production builds (refusing when a required lib is missing), so a bare
host/container without the toolkit can run the engine;
the model catalog row is no longer a prerequisite for a lane start: when
discovery has no row, sol_registry synthesizes one from the lane’s
files.model manifest (weights path + declared pin.sha256 enforced
when it is a real digest) — a lane can still never start weights it does
not declare.
8. Non-llama engines: the Strata lane
The engine abstraction admits a non-llama runtime without changing the
llama path. sol_lane_registry engine kind strata binds a packaged
wrapper instead of bin/llama-server, and sol_lane_profile:engine_command/1
returns a style tag (llama | strata) that selects the argv contract:
Llama (unchanged): engine_command/1 → bin/llama-server, argv from
the ?LLAMA_FLAGS allowlist (build_command/1 is byte-identical).
Strata: engine_command/1 → <root>/<build>/<launcher> (default
bin/strata-server; a command spec [Executable | StaticArgs] is also
accepted), argv --config <template> --port N --host H [--model GGUF] [--ctx N]. lane_config/3 emits only the wrapper surface (config path,
effective ctx, slot cap, loading budget); the llama KV/FA/rope/MTP laws
do not apply to a strata lane.
Engine row keys (sys.config, owned by the catalogue):
strata_sm86 => #{kind => strata, class => gpu_3090, production => false,
ref => <<"Niko1221/Strata@296b59d2f73c8f04a805df29c2fa97655adace78">>,
build => <<"0.1.44.1">>,
launcher => <<"bin/strata-server">>,
runtime => <<"python3 / lib/strata/runtime">>,
config_template => <<"lib/strata/config/strata-coder-256k-batch4.json">>,
engine_version => <<"0.1.44.1">>,
health_path => <<"/health">>}
The installer canary is built from the manifest’s unit-relative
launcher + config_template inside the verified tree. The artifact
sidecar is DATA, not an execution authority: it is not covered by the
artifact signature or the bin/+lib/ tree hash, so an artifact
carrying a canary_cmd field is REFUSED rather than executed.
The lane row names its weights (files.model) and context as usual; the
wrapper maps --model onto the template’s --native argument and --ctx
onto --max-context. The standardized 256k/batch4/MTP/int8 template ships
in scripts/engines/strata-coder-256k-batch4.json; ${STRATA_DATA_DIR} /
${STRATA_MODEL_DIR} are supplied by the engine row’s env (defaults
/fun/models/strata and /fun/models/strata/gguf-coder).
Packaging (scripts/engines/build-strata.sh, reached through
build.sh --class strata_sm86) stages one bin/+lib/ unit:
bin/strata engine binary (pinned source)
bin/libstrata_kq.so K-quant library next to the engine
bin/strata-server wrapper (renders the template, execs the server)
lib/strata/serve/ Python OpenAI/Anthropic server
lib/strata/tools/ strata_tokenizer.py
lib/strata/config/ standardized config template
lib/strata/runtime/ optional pinned Python runtime
build-strata.sh verifies the source pin exactly like build.sh --ref
(HEAD == ref, clean tree), records source_verified/source_head, the
engine binary sha256 and engine_version, and emits a deterministic
strata-<build>.tar.gz + manifest. engines/strata_sm86.json is the
reference row (production=false, state=reference) until the zerg
certification rows and the hermetic runtime image land; the Python runtime
is source-local (STRATA_PYTHON / lib/strata/runtime/bin/python /
python3, pinned requirements) with the hermetic --runtime DIR successor
documented in the packaged runtime README. The reference build also expects
the host CUDA 13 runtime (libcudart/libcublas/libcublasLt) — bundling
those plus the Python runtime is the hermetic-image successor, not a
production claim of this pass.
Health and stop: the wrapper stays alive as the lane identity anchor
(argv carries the wrapper path, --model and the --port pair the lease
reaper matches) and waits on the Python server with a TERM trap. Sol’s
{group, 0} + kill_group exec seam signals the wrapper, the Python
server and the Strata engine tree together; /health is the probe (the
engine row’s health_path must be an absolute HTTP path). The installer/rollback detect the class from the
manifest/receipt (engine=strata or strata*), run
bin/strata-server --canary (mock engine — wrapper/template/runtime/health
proof without a GPU or model load), poll the declared path, and keep the
provenance row beside the installed tree (.zerg-engine-manifest.json).
No production flag flips until the zerg-side validation rows exist.
9. Catalogue provenance at (GSQ-RCO Coder / Strata)
The catalogue half records the P7 b11639 / Strata / GSQ-RCO facts:
the llama.cpp production rows (cuda_sm86_main, cpu_zen1, cpu_epyc)
are pinned to b11639 =
ggml-org/llama.cpp@a0e6dc7384edb8f5d927155e1d26c10b4a310e6d;
the strata_sm86 engine row (kind => strata, production => false) pins
Strata 0.1.44.1 =
Niko1221/Strata@296b59d2f73c8f04a805df29c2fa97655adace78;
the GSQ-RCO Coder pin
(ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-Coder-GGUF @
5348543e0147355ac9cbcb031184a3546350988e) is registered on both
engines: qwen38_gsq_coder (Strata, staged) and
qwen38_gsq_coder_llama (b11639, local but production => false).
Ghost provenance is frozen at P7 tag p7-strata-b11639-2026-10-18
(plan/fixtures/ghost-p7-standard-b0454f2.md): engine pins at
ghost/etc/model-pins.env:42 (llama.cpp), :47 (Strata) and :48
(GSQ-RCO). The benchmark rows for the two new lanes are origin=ghost
only; the zerg-side validation run is and remains pending, and
the two ghost gates (mmproj formal caption A/B; code/agentic tool-call
JSON spot-check) remain open. No default is flipped; both rows stay
production=false.
10. Bundle consumer for standalone / air-gap editor hosts
The engine lane’s distribution unit is also the standalone consumer unit.
scripts/engine-bundle-consumer.sh verifies a bundle fail-closed, checks
the host class, and delegates the atomic install/flip/receipt and rollback
to engine-install.sh / engine-rollback.sh — there is no Sol and no lane
registry in this path. The bundle is the artifact triple plus optional
signature/receipt:
<artifact>.tar.gz + .sha256 + .manifest.json (+ .minisig, bundle-receipt.json)
verify always checks sha256, the manifest build/class and a real
64-hex manifest_hash (the unverified placeholder is refused), and an
optional bundle-receipt.json (artifact/sha/build/manifest-hash
equality). Minisign is required by default; --allow-unsigned is the
loud fixture/local waiver, and a present-but-invalid signature is always
a refusal.
install/upgrade run the packaged canary, keep the previous build for
rollback, and write <root>/installed.json +
<root>/bundle-consumer.json (source, artifact sha256, manifest hash,
host class, previous build).
rollback re-verifies the candidate receipt against a freshly computed
tree hash and re-probes it before the current flip.
Host class: engine-install.sh still owns the per-target refusal
(incompatible_host_class, e.g. a cpu_zen1 host refusing a
cpu_epyc/AVX-512 artifact, ); the consumer adds
--host-class CLASS as an install-time expectation
(host_class_mismatch). Roots are host-checked as well: absolute paths,
system roots refused without ZERG_ENGINE_ALLOW_SYSTEM_ROOT=1.
fetch is the only network leg and is an explicit operator action
(--url), accepted over https or loopback http; side-loading the bundle
directory is the air-gap path. The editor/completion path never fetches.
Ownership split (standing): wild owns CD — images, builds, bundle
production and publishing. zerg owns the bundle format, this consumer
recipe, verification semantics and the operator docs. A wild change to the
artifact triple must update this contract and its fixture battery
(tests/test_engine_bundle_consumer.py).
Operator recipe: docs/local-inference-runbook.md
§11; air-gap acceptance transcript:
plan/standalone-airgap-acceptance.md.
Engine reference — generated from the canonical engineering source. Do not edit this page by hand.
MCP Gateway — Fleet Documentation (WILDZERG Enterprise)
Status: pointer-style page. The MCP Gateway is an Enterprise-tier add-on deployed via wild/k0s, not part of this repository — there is no gateway code in
server/,client/,mango/, orlimon/. Everything below is what this repo can truthfully say; where the deployment lives, the wild/corp files are cited by name.
What it is
The Microsoft MCP Gateway (github.com/microsoft/mcp-gateway, MIT —
a separate Microsoft component, licensed/distributed independently,
integrated at the MCP protocol layer) is the enterprise component for
managing fleets of MCP servers on Kubernetes. Decision (decision
archive) fixed it as the third product in the ZERG ecosystem alongside
ZERG and WILDZERG — an Enterprise-tier add-on, referenced
separately from the base engine. The image is built from upstream and
pushed to registry.nonsense.ws/mcp-gateway:spacebeam-1.0.0;
the dev/staging gateway runs on the k0s node on blue ( — an
internal deployment, not the product URL).
What the gateway provides (sourced from docs-site/guide/mcp.md §Enterprise)
Reverse proxy with session-aware stateful routing to MCP server pods
Lifecycle management — deploy, update, delete MCP servers via REST API
Tool Gateway Router — dynamic routing of tool calls to registered
tool servers by name
Management portal — React SPA at /portal/ for browsing and
testing adapters in-browser
RBAC — mcp.admin and mcp.engineer roles, bridged to
GLAuth/Dex identity
Fleet topology
| Layer | Component | Owner |
|---|---|---|
| Agent execution | Luna workers (client/) | this repo — Luna is the MCP client + server (docs-site/guide/mcp.md; MCP client/server config in docs/mcp-setup.md) |
| MCP server fleet management | MCP Gateway on k0s | wild (wild/k0s/mcp-gateway.yaml — Deployment + Service + RBAC manifest) |
| Identity bridge | GLAuth/Dex roles → mcp.admin/mcp.engineer | wild |
Division of labor: “ZERG is the agent runtime” —
the gateway’s built-in Foundry agent runtime is always disabled
(FoundrySettings:Endpoint=""); Luna provides agent execution and the
gateway provides the management plane (docs-site/guide/mcp.md:217).
Deployment options per docs-site/guide/deployment.md:15: k0s Kubernetes for WILDZERG Enterprise + MCP Gateway (k0s single-node or multi-node); dev uses the k0s node on blue, Enterprise customers run their own k8s cluster.
Licensing / seat gate
The MCP gateway is one of the Enterprise feature flags in the seats
framework (docs/seats.md:12 — feature flags: clustering, SSO, audit
retention, MCP gateway, multi-region, air-gap, custom branding). No
in-repo code gates on it; the seat enforcement framework is
docs/seats.md + SOL_SEATS_* config (docs/configuration-reference.md
§Seats).
Where the real documentation lives
corp/docs/mcp-gateway-integration-strategy.md — three-layer MCP
architecture (Luna client + Luna server + MCP Gateway management)
corp/docs/k0s-evaluation.md — k0s deployment analysis and root cause
resolution
wild/k0s/mcp-gateway.yaml — the Kubernetes manifest (Deployment +
Service + RBAC)
wild/AGENTS.md — the k0s/gateway deployment and its upgrade flow
(corp and wild are separate repos; use the clone URLs in
ci/corp-pin/ci/wild-pin semantics — see WILD_REF in the repo root.)
Fleet operations (as documented by this repo)
Luna-side MCP config (the worker half the operator controls from
this repo): ~/.luna/mcp.json — stdio servers require hash-keyed
approval, MCP/LSP tools are confine-not-refuse, osv_check.lua egress
is gateable for air-gap. See docs/mcp-setup.md + docs/security.md.
Gateway-side fleet ops (register servers, assign roles, portal
testing): see the gateway’s own docs and the wild/corp pointers above —
nothing in this repo implements or documents the gateway’s REST API.
Air-gap: the gateway is a management plane over LAN-facing MCP
servers; the egress doctrine (docs/air-gap-install.md) applies to Luna
workers, which must reach the gateway inside the site, not across
the gap.
See also
docs/mcp-setup.md — Luna MCP client/server configuration
docs-site/guide/mcp.md — the portal’s MCP guide incl. the Enterprise
section
docs/seats.md — tier framework the Enterprise add-on sits on
Engine reference — generated from the canonical engineering source. Do not edit this page by hand.
Local-Inference Benchmark Artifact
The machine ledger for lane measurements is
local-inference-benchmark.csv (docs/local-inference-benchmark.csv). Rows are
appended by the operator runner (scripts/lane-certify.sh) through
ci/lane_benchmark.py append — flocked, fsynced, written atomically in the
same directory (never staged through /tmp; the ghost wipe of a round’s
rows is the lesson). The generated block at the bottom of this file is
rendered from the CSV by ci/lane_benchmark.py render and gated by
ci/lane_benchmark_claims_lint.py (a hand-edit is a CI failure).
The 24 columns
| column | domain | notes |
|---|---|---|
host | red/green/blue/test | node label (node_classes in the configs) |
lane | lane id | must exist in inference_lanes (all three configs) |
engine_ref | <repo>@<40-hex>[#prN] (zerg) or <repo>@<7-40 hex> / ghost/<name>@<tag> (ghost) | join key to engines/*.json by ref + build for zerg rows; ghost rows are provenance only |
build | non-empty | e.g. b11639 (llama.cpp) or 0.1.44.1 (Strata) |
model / quant / ctx / kv / spec / temp | run identity | parity identity = these + lane/engine_ref/build |
vram_mib / free_mib / load_s / prompt_tps / wall_s | numbers or - | host facts at measurement time |
eval_tps | number > 0 when measured | decode tok/s |
acceptance | 0..1 float, token, or - | MTP acceptance / suite ratio |
needle | pass/fail/gated/- | exact-substring recall gate |
status | ok/pass/failed/fail/gated/launch_failed/error | ok and pass are the measured classes |
notes | free text | a bounded k=v; token list before ` |
at | ISO-8601 UTC | freshness key (TTL, validation record at) |
manifest_hash | 64-hex or unverified | engine tree hash; unverified only against a state=reference manifest |
needle_decode_tps | number > 0 or - | decode tok/s of the needle fill |
origin | zerg/ghost | only zerg rows are validation candidates; ghost rows are imported evidence |
Evidence vs validation
origin=ghost rows were imported from the sibling ghost checkout with
ci/lane_benchmark.py import-ghost using a curated map whose every entry
cites the exact source line (ghost/docs/benchmark-serving.csv:<line>)
and is verified against that line at import time. A mismatch refuses.
origin=zerg rows are produced by the needle harness
through the admin validation route and
are the only rows that can back a lane’s validated state.
Unbacked registry expected.* values are counted, never fabricated;
ling_flash (vram_mib=18534), ling_reap288 (vram_mib=18534) and
qwen38_flashnext (vram_mib=23347) have no matching ghost row and stay
on the residual list until a ZERG run lands.
The GSQ-RCO / Strata rows are all origin=ghost (ghost P7
tag p7-strata-b11639-2026-10-18, fixture
plan/fixtures/ghost-p7-standard-b0454f2.md). They record the ghost
hypothesis on two engines; the zerg-side validation run is and
is pending — no ${lane} row below is a validation candidate until
an origin=zerg row lands. The two open ghost gates (mmproj formal
caption A/B; code/agentic tool-call JSON spot-check) also remain open.
Parity
Parity pairs temp-0 measured rows of one identity across hosts;
delta_pct = abs(a - b) / max(a, b) * 100
benchmarks/parity-bands.json carries default_pct (1.5, the ghost
deterministic-row band), a per-lane pct, and optional per-host
hosts.<label>.pct overrides. Two lanes need host-specific bands because
the X3D/CPU-fed phases are a machine-class deficit, not drift:
ling_flash (3.0) and ling_reap288 (17.0). The GSQ-RCO Coder needs a
5.0 band for the ghost Strata red/green pair (113.8 / 108.5 = 4.66%).
The llama.cpp GSQ-RCO rows keep the measured recipe in spec
(fittarget256 vs moe_cache_mib_4096), so the cache/no-cache runs are
never paired as one identity. A breach is a finding with a decay_at,
feeds the runtime record as parity.status=breach, and keeps the lane
unvalidated (no failover) until a fresh paired run.
Seeded evidence (all origin=ghost, red/green pairs):
qwen38_atx eval_tps=93.2 and qwen38_atx needle_decode_tps=64.4,
ling_tiny eval_tps=231.3, ling_flash eval_tps=41.1,
ling_reap288 eval_tps=44.8 (each paired with the green peer in the CSV).
The P7 multi-engine rows add qwen38_gsq_coder eval_tps=113.8 (Strata,
red), qwen38_gsq_coder_llama eval_tps=45.7 (b11639 + moe-cache, 128k)
and qwen38_gsq_coder_llama eval_tps=48.9 (b11639 + moe-cache, 256k).
The P7 b11639 / GSQ-RCO / Strata import
The new artifact rows are imported from the ghost P7 CSV at
b0454f2f7f2f3d3614e6ae8e663a0d1610bc13e7:
qwen38_gsq_coder — Strata 0.1.44.1
(Niko1221/Strata@296b59d2f7), 131k/256k int8/MTP rows, including the
518k red-only needle escape and the batch4 row. Strata parity on the
standardized config measured 113.8 red / 108.5 green (4.66%, band 5.0).
qwen38_gsq_coder_llama — llama.cpp b11639 on the same shards:
fittarget256 rows (39.8 @128k / 37.3 @256k; needle 38.1 with
needle_decode_tps=28.8) and moe_cache_mib_4096 rows
(45.7 @128k / 48.9 @256k). The cache flag is part of spec, not a
silent identity change.
Neither lane has a zerg row; docs/local-inference-benchmark.csv stays at
zero origin=zerg entries after this import.
Invalidation
lane.validation is derived at read time, never a trusted stored flag.
The runtime measurement record lives at <data_dir>/lane-validation.json
(written 0600 atomically by Sol, single writer = the admin validate route).
Every read compares the record against the live environment: registry
engine ref/build, the engine install receipt manifest_hash/build,
the lane model pin (file + sha256), the TTL
(lane_validation_ttl_ms, default 30 days) and the parity verdict. Any
mismatch yields a typed reason (engine_pin_changed,
engine_reinstalled, model_pin_changed, stale, needle_failed,
parity_breach, host_mismatch, malformed_record, no_record), the
lane projects as unvalidated, and production placement refuses with
{engine_unvalidated, Lane, Reason}. Non-production lanes (the fixture
engine) bypass the gate with not_required.
Operator surfaces
scripts/lane-certify.sh --plan --host red prints the lane × engine ×
host matrix (no GPU, the CI-testable leg); the real run probes each cell
through POST /api/v1/inference/lanes/:lane/validate, appends the row,
computes parity, and only then commits. A partial run never commits.
A single_host parity verdict does not commit by default — pass
--allow-single-host to record the explicit ack (forwarded as
allow_single_host on commit and recorded in the transcript,
).
GET /api/v1/inference/lanes renders validation.state + reason per
lane so a blocked lane is visible with its cause; the same row carries
the registry use_case facet for the editor picker.
Generated from docs/local-inference-benchmark.csv by ci/lane_benchmark.py render — do not hand-edit.
rows=24 zerg=1 ghost=23 unbacked_expected=3 parity=ling_flash=pass ling_reap288=pass ling_tiny=pass qwen38_atx=pass qwen38_gsq_coder=pass qwen38_gsq_coder_llama=pass
| host | lane | engine_ref | build | model | quant | ctx | kv | spec | temp | vram_mib | eval_tps | needle | needle_decode_tps | at | origin |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| red | glm47_fim | ggml-org/llama.cpp@a0e6dc7384edb8f5d927155e1d26c10b4a310e6d | b11639 | GLM-4.7-Flash-Uncen-Hrt-NEO-CODE-MAX-imat-D_AU-IQ3_M | IQ3_M | 16384 | q4_0 | none | 0.0 | 14139 | 120.8 | - | - | 2026-10-18T00:00:00Z | zerg |
| green | ling_flash | ggml-org/llama.cpp@aa39d7a3e145a88202793a89462d65e94a5fc25f | b11011 | Ling-3.0-flash-IQ3_XXS | IQ3_XXS | 262144 | f16 | none | 0.0 | 21114 | 40.4 | - | - | 2026-09-16T00:00:00Z | ghost |
| red | ling_flash | ggml-org/llama.cpp@aa39d7a3e145a88202793a89462d65e94a5fc25f | b11011 | Ling-3.0-flash-IQ3_XXS | IQ3_XXS | 262144 | f16 | none | 0.0 | 21401 | 41.1 | - | - | 2026-09-16T00:00:00Z | ghost |
| green | ling_reap288 | ggml-org/llama.cpp@aa39d7a3e145a88202793a89462d65e94a5fc25f | b11011 | Ling-3.0-flash-REAP288-71B-A5B-Q3_K_M | Q3_K_M | 262144 | f16 | none | 0.0 | 18074 | 37.7 | - | - | 2026-09-16T00:00:00Z | ghost |
| red | ling_reap288 | ggml-org/llama.cpp@aa39d7a3e145a88202793a89462d65e94a5fc25f | b11011 | Ling-3.0-flash-REAP288-71B-A5B-Q3_K_M | Q3_K_M | 262144 | f16 | none | 0.0 | 18361 | 44.8 | - | - | 2026-09-16T00:00:00Z | ghost |
| green | ling_tiny | ggml-org/llama.cpp@aa39d7a3e145a88202793a89462d65e94a5fc25f | b11011 | Ling-3.0-tiny-Q4_K_M | Q4_K_M | 524288 | f16 | none | 0.0 | 9110 | 233.2 | - | - | 2026-09-16T00:00:00Z | ghost |
| red | ling_tiny | ghost/llama.cpp@b10867 | b10867 | Ling-3.0-tiny-Q4_K_M | Q4_K_M | 131072 | q8_0 | none | 0.0 | 6248 | 236.1 | - | - | 2026-09-08T00:00:00Z | ghost |
| red | ling_tiny | ggml-org/llama.cpp@aa39d7a3e145a88202793a89462d65e94a5fc25f | b11011 | Ling-3.0-tiny-Q4_K_M | Q4_K_M | 524288 | f16 | none | 0.0 | 9397 | 231.3 | - | - | 2026-09-16T00:00:00Z | ghost |
| green | qwen38_atx | ggml-org/llama.cpp@aa39d7a3e145a88202793a89462d65e94a5fc25f | b11011 | Qwen3.8-27B-ATX-4-XS | IQ4_XS-M | 229376 | q4_0 | draft_mtp_d3 | 0.0 | 23567 | 94.5 | - | - | 2026-09-16T00:00:00Z | ghost |
| green | qwen38_atx | ggml-org/llama.cpp@aa39d7a3e145a88202793a89462d65e94a5fc25f | b11011 | Qwen3.8-27B-ATX-4-XS | IQ4_XS-M | 229376 | q4_0 | draft_mtp_d3 | 0.0 | 23567 | 64.5 | pass | 64.5 | 2026-09-16T00:00:00Z | ghost |
| red | qwen38_atx | ggml-org/llama.cpp@aa39d7a3e145a88202793a89462d65e94a5fc25f | b11011 | Qwen3.8-27B-ATX-4-XS | IQ4_XS-M | 229376 | q4_0 | draft_mtp_d3 | 0.0 | 23849 | 93.2 | - | - | 2026-09-16T00:00:00Z | ghost |
| red | qwen38_atx | ggml-org/llama.cpp@aa39d7a3e145a88202793a89462d65e94a5fc25f | b11011 | Qwen3.8-27B-ATX-4-XS | IQ4_XS-M | 229376 | q4_0 | draft_mtp_d3 | 0.0 | 23849 | 64.4 | pass | 64.4 | 2026-09-16T00:00:00Z | ghost |
| green | qwen38_gsq_coder | Niko1221/Strata@296b59d2f7 | 0.1.44.1 | Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M | IQ1_M | 131072 | int8 | mtp | 0.0 | 23717 | 108.5 | - | - | 2026-10-15T00:00:00Z | ghost |
| green | qwen38_gsq_coder | Niko1221/Strata@296b59d2f7 | 0.1.44.1 | Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M | IQ1_M | 262144 | int8 | mtp | 0.0 | 23497 | 39.1 | pass | - | 2026-10-15T00:00:00Z | ghost |
| red | qwen38_gsq_coder | Niko1221/Strata@296b59d2f7 | 0.1.44.1 | Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M | IQ1_M | 131072 | int8 | mtp | 0.0 | 23887 | 113.8 | - | - | 2026-10-15T00:00:00Z | ghost |
| red | qwen38_gsq_coder | Niko1221/Strata@296b59d2f7 | 0.1.44.1 | Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M | IQ1_M | 131072 | int8 | mtp | 0.0 | 23887 | 99.0 | pass | - | 2026-10-15T00:00:00Z | ghost |
| red | qwen38_gsq_coder | Niko1221/Strata@296b59d2f7 | 0.1.44.1 | Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M | IQ1_M | 131072 | int8 | mtp | 0.0 | 23887 | 85.9 | - | - | 2026-10-15T00:00:00Z | ghost |
| green | qwen38_gsq_coder_llama | ggml-org/llama.cpp@a0e6dc7384edb8f5d927155e1d26c10b4a310e6d | b11639 | Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M | IQ1_M | 131072 | q4_0 | fittarget256 | 0.0 | 23547 | 39.5 | - | - | 2026-10-15T00:00:00Z | ghost |
| green | qwen38_gsq_coder_llama | ggml-org/llama.cpp@a0e6dc7384edb8f5d927155e1d26c10b4a310e6d | b11639 | Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M | IQ1_M | 262144 | q4_0 | fittarget256 | 0.0 | 23457 | 36.9 | - | - | 2026-10-15T00:00:00Z | ghost |
| red | qwen38_gsq_coder_llama | ggml-org/llama.cpp@a0e6dc7384edb8f5d927155e1d26c10b4a310e6d | b11639 | Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M | IQ1_M | 131072 | q4_0 | fittarget256 | 0.0 | 23403 | 39.8 | - | - | 2026-10-14T00:00:00Z | ghost |
| red | qwen38_gsq_coder_llama | ggml-org/llama.cpp@a0e6dc7384edb8f5d927155e1d26c10b4a310e6d | b11639 | Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M | IQ1_M | 131072 | q4_0 | fittarget256 | 0.0 | 23403 | 38.1 | pass | 28.8 | 2026-10-14T00:00:00Z | ghost |
| red | qwen38_gsq_coder_llama | ggml-org/llama.cpp@a0e6dc7384edb8f5d927155e1d26c10b4a310e6d | b11639 | Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M | IQ1_M | 262144 | q4_0 | fittarget256 | 0.0 | 23497 | 37.3 | - | - | 2026-10-14T00:00:00Z | ghost |
| red | qwen38_gsq_coder_llama | ggml-org/llama.cpp@a0e6dc7384edb8f5d927155e1d26c10b4a310e6d | b11639 | Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M | IQ1_M | 131072 | q4_0 | moe_cache_mib_4096 | 0.0 | 23545 | 45.7 | - | - | 2026-10-16T00:00:00Z | ghost |
| red | qwen38_gsq_coder_llama | ggml-org/llama.cpp@a0e6dc7384edb8f5d927155e1d26c10b4a310e6d | b11639 | Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M | IQ1_M | 262144 | q4_0 | moe_cache_mib_4096 | 0.0 | 23567 | 48.9 | - | - | 2026-10-16T00:00:00Z | ghost |
FIM / inline completion round (2026-10-18)
The serving CSV is the agent/prose/needle artifact. The FIM round has its
own frozen corpus and measured packet:
../benchmarks/fim-round-2026-10-18.md (benchmarks/fim-round-2026-10-18.md).
Result: glm47_fim (GLM-4.7-Flash Uncensored NEO-CODE MAX IQ3_M, b11639
native /infill) 26/40 accept@1, 120.8 decode t/s, 0.80 s warm-cache at
96 tokens; qwen38_atx fallback 18/40; Ling-3.0-tiny rejected 0/40 (no FIM
template/training); Strata has no native infill.
Workers and Agents
Sol orchestrates swarms of Luna worker agents over ZMQ and JSONL transports. This guide covers connecting workers, the wire protocol, agent modes, and headless operation.
Transport Comparison
| Feature | ZMQ DEALER | JSONL Stdio |
|---|---|---|
| Protocol | msgpack over ZMQ | JSON lines over stdin/stdout |
| Language | Any (ZMQ + msgpack bindings) | Any (stdin/stdout) |
| Process management | External (worker manages itself) | Sol spawns via erlexec |
| Streaming tokens | Yes | Yes |
| Task cancellation | Yes | Yes |
| Child task spawning | Yes | No |
| Reconnection | Automatic (ZMQ) | Process restart |
| Dependencies | libzmq, msgpack | None |
| Best for | Long-running workers, polyglot | Short-lived workers, simple agents |
ZMQ DEALER Workers (Recommended)
Connection Model
Workers connect to Sol’s ZMQ ROUTER gateway as DEALER sockets. Communication is asynchronous: workers announce readiness, Sol dispatches tasks, workers stream results back.
Worker (DEALER) <--> Sol ROUTER (port 5555)
Multiple workers can connect simultaneously. Sol routes tasks to the first available (ready) worker. If no workers are ready, tasks queue until one becomes available.
Connect and Register
The ZMQ gateway uses a dedicated sharded architecture for high throughput:
Sol_zmq_sender — owns the ROUTER socket, serializes all outbound sends through a dedicated gen_server
Sol_zmq_recv_dispatcher — dedicated gen_server for inbound message routing
Sol_zmq_result_router — routes child task results and manages parent/child cleanup
Sol_zmq_recv_bridge — recv loop with error backoff, extracted from gateway
ETS indexes — sol_zmq_tasks and sol_zmq_workers tables for O(1) lookups
Plugin tool executor pool — simple_one_for_one supervisor isolates plugin tool execution from the gateway
Registration is credentialed: a bare ready is refused with
registration_hmac_failed unless Sol runs the explicit loopback dev ack
(SOL_ZMQ_ALLOW_LOCAL_UNREGISTERED=true in dev). Provision the worker
first — a per-worker enrollment key is the recommended form:
# Sol: one JSON entry per worker (secret >= 16 bytes). Restart/reload picks
# this up; the entry is bound to the exact worker_id.
export SOL_ZMQ_ENROLLMENT_KEYS='{"my-worker-1":{"worker_id":"my-worker-1","secret":"<32-byte-secret>"}}'
import hashlib
import hmac
import os
import time
import msgpack
import zmq
PROTOCOL_VERSION = 4 # sol_zmq_protocol:protocol_version/0
WORKER_ID = os.environ.get("ZERG_WORKER_ID", "my-worker-1")
URL = os.environ.get("SOL_ZMQ_URL", "tcp://127.0.0.1:5555")
# Per-worker enrollment secret (recommended) or the fleet secret.
SECRET = os.environ["SOL_ZMQ_WORKER_SECRET"].encode()
# Per-worker enrollment id. Omit it to present the legacy fleet secret
# (only while zmq_fleet_legacy_compat is explicitly reopened).
KEY_ID = os.environ.get("ZERG_WORKER_KEY_ID", "")
ctx = zmq.Context()
sock = ctx.socket(zmq.DEALER)
sock.setsockopt_string(zmq.IDENTITY, WORKER_ID)
sock.connect(URL)
# The payload goes out BARE — no empty delimiter frame (the old two-frame
# delimiter shape is dropped by the gateway; see
# docs/zmq-protocol-reference.md §Message Framing, ).
nonce = os.urandom(16).hex()
ctr = time.time_ns() // 1_000_000 # strictly increasing u64 milliseconds
material = (
nonce.encode()
+ len(WORKER_ID).to_bytes(2, "big")
+ WORKER_ID.encode()
+ len(WORKER_ID).to_bytes(2, "big")
+ WORKER_ID.encode()
+ (0).to_bytes(4, "big") # child_depth
+ ctr.to_bytes(8, "big")
)
ready = {
"type": "ready",
"worker_id": WORKER_ID,
"version": PROTOCOL_VERSION,
"capabilities": ["python", "streaming"],
"nonce": nonce,
"ctr": ctr,
"hmac": hmac.new(SECRET, material, hashlib.sha256).hexdigest(),
}
if KEY_ID:
ready["key_id"] = KEY_ID
sock.send_multipart([msgpack.packb(ready, use_bin_type=True)])
Luna does the same handshake automatically from LUNA_ZMQ_KEY_ID +
LUNA_ZMQ_WORKER_SECRET (the HMAC material is built by
client/core/zmq_protocol.lua; see the full reference implementation in
example/python/zmq_worker.py).
Receive and Execute Tasks
poller = zmq.Poller()
poller.register(sock, zmq.POLLIN)
while True:
events = dict(poller.poll(timeout=1000))
if sock not in events:
continue
frames = sock.recv_multipart()
msg = msgpack.unpackb(frames[-1], raw=False)
msg_type = msg.get("type")
if msg_type == "task":
task_id = msg["task_id"]
prompt = msg["prompt"]
Stream Results
sock.send_multipart([msgpack.packb({
"type": "token",
"task_id": task_id,
"content": "partial output..."
}, use_bin_type=True)])
sock.send_multipart([msgpack.packb({
"type": "result",
"task_id": task_id,
"status": "ok",
"content": "final output"
}, use_bin_type=True)])
# The worker stays REGISTERED after the result — the gateway dispatches
# the next task to any idle registered worker. Do NOT re-send `ready`
# (see the re-READY hazard under "Protocol Hardening" below).
Handle Cancellation
if msg_type == "cancel":
task_id = msg["task_id"]
sock.send_multipart([msgpack.packb({
"type": "result",
"task_id": task_id,
"status": "cancelled",
"content": ""
}, use_bin_type=True)])
Luna maintains registration with a dedicated plain heartbeat frame every 5
seconds. Since the ready frame is sent ONCE at registration — it is
NEVER re-sent (the old 60-second re-READY cycle was removed: proof-less
re-ready tripped Sol’s fail-closed adoption gate; liveness is served by the
heartbeat alone, see client/core/zmq_worker.lua). A full Python reference
implementation is at example/python/zmq_worker.py.
See ZMQ Protocol for the complete specification.
Protocol version and per-frame MAC
The live worker wire protocol is version 4. A v1/v2 worker is refused loudly; v3 is admitted only while the N/N-1 skew window is open. Credentialed worker-plane frames carry a trailing multipart MAC derived from the session key; the gateway verifies it before dispatch. The full field contract and refusal catalog are in the Worker Integration reference and ZMQ protocol reference.
Protocol Hardening
The ZMQ boundary has been progressively hardened against forged and untracked frames:
** →, re-based — ZMQ ownership enforcement.** result/token/error frames pass allow_result_frame/4: the sender must be the task’s dispatched-to worker (index match); on an index miss it must equal the recorded executor stamped at dispatch (bounded WARNING grace), otherwise the frame is refused and counted. The previous “currently registered sender” grace is DELETED. event frames require registration and the worker event namespace is closed to telemetry.*/agent.*. spawn frames require the parent task to belong to the sender; team_*/acp frames require registration (worker-supplied from/member_id are never identity).
Worker registration HMAC. With a fleet secret (SOL_ZMQ_WORKER_SECRET) or a per-worker enrollment key (key_id) configured, the ready frame must carry a fresh nonce, a strictly increasing u64 ctr, and an HMAC over the canonical signed material nonce || u16(len(identity)) || identity || u16(len(worker_id)) || worker_id || u32(child_depth) || u64(ctr) (registration_signed_material/5 — the routing identity is bound before the claimed worker_id); Sol validates the HMAC and the counter before accepting the worker. A bare ready from an unauthenticated peer is rejected. The early HMAC(worker_secret, nonce) challenge-response form is retired, and the legacy compatibility windows are CLOSED by default.
Pending task store. ZMQ-dispatched tasks are written to sol_task_results at dispatch time via sol_task_store:store_pending/2, so GET /api/v1/tasks/:id returns {status: pending} immediately instead of 404 during the in-flight window before the first terminal event.
JSONL Stdio Workers
Sol spawns an OS process via erlexec and communicates via JSON lines over stdin/stdout. The worker reads JSON objects from stdin (one per line) and writes JSON objects to stdout (one per line, flushed after each).
Message Types
Worker to Sol (stdout)
| Type | Fields | Description |
|---|---|---|
ready | – | Announce worker is ready |
token | id, content | Streaming partial output |
result | id, status, content | Task completion |
log | level, message | Diagnostic log |
Sol to Worker (stdin)
| Type | Fields | Description |
|---|---|---|
task | id, prompt, opts | Task assignment |
cancel | id | Cancel running task |
Minimal Worker Example
#!/usr/bin/env python3
import sys
import json
def send(msg):
sys.stdout.write(json.dumps(msg) + "\n")
sys.stdout.flush()
send({"type": "ready"})
for line in sys.stdin:
msg = json.loads(line.strip())
if msg.get("type") == "task":
task_id = msg["id"]
prompt = msg["prompt"]
send({"type": "token", "id": task_id, "content": "Working...\n"})
send({"type": "result", "id": task_id, "status": "ok", "content": f"Done: {prompt}"})
elif msg.get("type") == "cancel":
send({"type": "result", "id": msg["id"], "status": "cancelled", "content": ""})
Spawn Configuration
Configure in sys.config:
{worker_path, "/path/to/my-worker"},
{max_workers, 16}
Or override per-spawn via the HTTP API:
zerg spawn --worker-path /path/to/my-worker
The worker_path is validated against a configurable prefix to prevent arbitrary binary execution. The JSONL task deadline is the shipped task_timeout_ms (300-second idle deadline, re-armed by progress) and is capped by task_max_lifetime_ms (default 1200000 ms) for a chatty-but-endless task. Worker stdout is buffered up to 256KB.
Worker Configuration
| Config Key | Default | Description |
|---|---|---|
worker_path | "client/build/luna" | Path to worker binary |
max_workers | 16 | Maximum concurrent workers |
zmq_router_port | 5555 | ZMQ ROUTER socket port |
zmq_pub_port | 5556 | ZMQ PUB event socket port |
zmq_bind_addr | "127.0.0.1" | ZMQ bind address |
zmq_enabled | true | Enable ZMQ gateway |
Agent Modes
Luna workers operate in 8 built-in agent modes (6 primary + 2 swarm), each tuned for a specific task category. Mode selection changes the system prompt, tool permissions, and agent behavior.
| Mode | Purpose | Tool Policy |
|---|---|---|
| Build | Code creation and modification | Read/search allowed, writes require approval |
| Plan | Analysis and planning | Read/search allowed, all writes denied |
| Explore | Codebase exploration | Read/search/lsp only, all writes denied |
| Review | Code review and audit | Read/search/web allowed, writes denied |
| General | General-purpose tasks | All tools allowed, bash/delete require approval |
| Coordinate | Multi-agent orchestration | All tools allowed (orchestrator needs full access) |
| Leader | Team leader — coordinate a team of teammates | All tools allowed + team_mail (+ team directives) |
| Teammate | Execute assigned tasks as part of a team | Curated allowlist incl. team_mail |
Switch modes with Tab in the TUI or the switch_mode tool:
> /mode build
User-defined modes can be registered via the agent configuration.
Headless Mode
Run Luna without the TUI for scripted or CI/CD workflows:
luajit client/main.lua --print "Analyze this codebase and report issues"
luajit client/main.lua --print "Fix the bug in main.rs" --permission-mode allow-all
Workers are provider-keyless when connected to Sol (the LLM lane grant arrives per task via POST /api/v1/start / POST /api/v1/prepare/:name; list lanes with GET /api/v1/inference/lanes) — this is not registration-keyless: the ZMQ handshake still requires the enrollment credential above. Output is written to stdout in plain text.
Monitoring Workers
zerg zmq-workers
zerg zmq-status
zerg agents
zerg task-status <id>
Engine reference — generated from the canonical engineering source. Do not edit this page by hand.
Session Management
Luna persists conversations in dual-write mode: JSONL (human/stream replay) + SQLite/FTS5 (search + cross-session memory). Each JSONL line is a message, tool call, or tool result.
Session Location
~/.luna/sessions/<timestamp>-<hash>.jsonl
Example: ~/.luna/sessions/2026-04-22-143052-a3f8.jsonl
Session Lifecycle
- New session created on startup (unless
--resumeis used) - Messages appended incrementally during conversation — no rewriting the entire file
- Session rotation when file exceeds 256KB — current context preserved, old file archived
- Old sessions remain in
~/.luna/sessions/for future reference (retain-forever unless the opt-in sweep below is run)
Starting a Session
# New session (default; configure a provider key or connect to Sol first)
luajit client/main.lua --connect tcp://127.0.0.1:5555
# Resume last session
luajit client/main.lua --resume
# Resume specific session file
luajit client/main.lua --session ~/.luna/sessions/2026-04-22-143052-a3f8.jsonl
Session trees, branching, and retention
Messages carry parent_id plus an optional branch; a session keeps a
leaf_id and active_branch. Session:branch(from_id, name) creates a
named in-file branch at an existing message and checks it out;
Session:switch_leaf(id) time-travels to any message; Session:switch_branch
resumes a branch’s tip (not its root), including main. A fork
(fork_to_file) snapshots the leaf→root view, drops compacted blocks, and
carries the leaf, active branch, branch entries, and title. /rename NAME
sets the session display name (persisted in the JSONL session_meta/title);
/tree, /branch, and /switch N|NAME expose the same tree locally.
Retention/GC (; supersedes the retain-forever-only
posture): session corpora remain retain-forever by default — no
automatic age/TTL sweep runs unless session_gc.enabled=true (off by
default) or an operator explicitly invokes a sweep. The sweep is
whole-session only:
luna --gc-sessions # dry run: list eligible corpus
luna --gc-apply # apply (age/idle/lease guarded)
luna --gc-max-age-days 30 --gc-limit 100
Inside the TUI: /gc is a dry run; /gc run [DAYS] applies (an explicit
run is required). Config: session_gc.{enabled,max_age_days, min_idle_seconds,page_size,dry_run,delete_trajectory,delete_orphan_tmp}.
One candidate = the primary <id>.jsonl plus its rotations (.1, .2),
a stranded .rotate.tmp, trajectory_<id>.jsonl (default on), and the
stale <id>.jsonl.active lease. A sweep deletes, in order: the SQLite
sessions/messages rows (both FTS tables are maintained by the DELETE
triggers), the JSON index entry, then the files. It also removes
age-gated orphan .luna_session_* / .luna_edit_* temps. It is
idempotent and re-checks eligibility immediately before mutation.
Explicit exclusions (owned by other planes, never deleted by session GC):
content-addressed blobs (core.blob_store’s own 30-day GC owns them)
analytics rows (~/.luna/analytics.db)
git snapshots (core.git_snapshot retention)
session-scoped memory
Guards: the current in-process session, a held .active lease (live
processes hold one from attach/save until close; the kernel drops it on
crash), corpora active within min_idle_seconds, anything newer than
max_age_days, and symlinked artifacts are all skipped/refused. A
destructive sweep serializes through <sessions>/.gc.lock.
/delete now uses the same whole-session path for the current session
(primary, rotations, trajectory, SQLite rows, index entry) and then
starts a replacement session; the old single-file removal left the
rotated generations and the search rows behind.
Secure-deletion limits: this is an unlink/truncate-level sweep, not cryptographic erasure. Filesystem journals, copy-on-write layers, SSD wear-levelling, snapshots, and backups can retain prior bytes after the path disappears; SQLite pages may survive in copies/backups (the live WAL is checkpoint-truncated per batch). Use full-disk encryption and backup expiry if the threat model requires physical erasure.
Branch pruning remains an explicit operator action with the branch root and any shared prefix retained; automatic per-branch tree GC is a successor (residual register). The tree metadata above is the prerequisite for that sweep.
Editor chat sessions
:ZergChat in example/vim is a real Luna session, not an in-memory
bridge conversation. The store-location decision for the long view §9 is:
Operator home, per project: ~/.luna/sessions/editor-chat-<name>-<hash>.jsonl.
Sessions are private operator data; project .luna/ is repo-controlled
configuration and must not carry a conversation log. The <hash> is
derived from the resolved workspace root (git rev-parse --show-toplevel
when available, the working directory otherwise), so the same project
resumes its chat across editor restarts while another project gets a
fresh one — no cross-project leakage.
Format: the standard session JSONL above (tree metadata, leaf pointer,
branches, compaction records). Resume is Session.load_from_path; the
compaction no-resurrection property is the session plane’s standing
contract. A corrupt/unloadable editor session is a typed
session_load_failed, never a silent fresh start.
Checkpoint ownership: standalone/stdio chats checkpoint in the local
Luna store. When the editor is Sol-bound (:ZergConnect), the chat
session and its checkpoints are Sol-owned (’s session-control
plane); the local store is not the authority there.
g:mocha_zerg_chat_session overrides the path; --session PATH on
example/vim/luna-local.lua --chat does the same from the CLI.
Ops console: session tree & snapshots
Limon’s chat sidebar renders the active worker’s headless surface through
Sol’s /api/v1/chat/:id/branches|snapshots|snapshots/:snapshot_id/diff
reads and the two mutation routes:
Branches lists main plus every named branch (root/leaf counts,
active marker, title). Admin operators can check out a branch; the
console confirms first and the server strict-audits
session_branch_checkout.
Snapshots lists git snapshots recorded by the worker
(id/timestamp/tool/description/files). Admin operators can
restore one after confirmation; the server strict-audits
session_snapshot_restore (snapshot id + file count, never file
bodies). The diff view is a bounded summary (files/insertions/
deletions, 8 KiB diff cap).
Both mutations carry the caller’s identity and are refused with the typed
session_busy (409) while a turn is running — the UI surfaces that
verdict instead of silently retrying. A worker with no task session yet
renders the typed no_active_session empty state; a workspace that is not
a git repository renders snapshot_unavailable — never an empty list that
looks like success. See the API reference for the full route/status table
and the session_control wire lines.
Session Branching
Branch a conversation at any point. The branch creates a new session file with messages up to the branch point, then continues independently from the original.
This is useful for: Exploring alternative approaches without losing context Testing different solutions to the same problem Creating parallel investigations
Tree-Structured JSONL
Sessions use a tree-structured JSONL format with parentId and branch fields:
Each entry has a parentId referencing the previous entry in the conversation
Branches are named and can be navigated independently
Typed entries include: mode_change, model_change, compaction, branch_summary, checkpoint, label
Branch CRUD
/branch [name] — Create a named branch at the current position
/switch <name> — Switch to an existing branch
/tree — Display the full branch tree with entry counts
Branches can be merged back into the main conversation
Checkpoint/Restore
Automatic checkpoints are created at key moments (before background tasks, before risky operations)
Use checkpoints to restore session state to a known point
Checkpoint metadata includes mode, model, and message count for full recovery
Git position: when the session has a workspace_root
that is a git repo, checkpoints record the working-tree HEAD hash
(capture_hash — no commit is performed; snapshots are separate
commits) and restore_checkpoint restores the working tree to that
position (git checkout <hash> --.). Git capture is scoped to the
session’s workspace — a session without a workspace root records
git_hash = nil.
Session Sharing
Sessions can be shared via public links (Mnesia-backed with a TTL):
POST /api/v1/sessions — create a share link. Body: session_data
(REQUIRED, 400 session_data_required without it), optional format
and ttl_days. Returns 201 with the share id. (The old documented
POST /api/v1/sessions/:id/share / GET /api/v1/sessions/share/:token
pair returned 405 — the GET route did not exist.)
GET /api/v1/shares/:share_id — retrieve the shared session:
{data, format, created_at} (200), 404 when expired or unknown
.
DELETE /api/v1/sessions/:share_id — delete a share (owner/admin).
Session Bundles — local export/import
A signed .zergsession bundle moves a session tree plus a bounded
memory subset and inert snapshot refs between Luna homes. It is the
portable unit behind core.session_export; the upload/download half is
Design only (see plan/session-export-format.md and the
SESSION-BUNDLE-CROSSNODE-SECURITY-REVIEW exit gate).
Contents: the session’s own JSONL record set (messages, branches,
leaf, active branch, title, labels, notes, checkpoints, compaction
records), a scoped memory subset, and git_snapshot refs. The source
workspace_root and local blob refs are not exported.
No credentials, ever: every string (values and keys) passes through
the shared core.redaction contract; a second pass refuses anything that
still looks secret (secret_material_detected). Import enforces the same
gate.
Trust: the bundle header records issuer mango, exporter, recipient,
issued/expiry timestamps, audience, nonce, and a key_id derived from
the Mango bearer token. The token itself is never stored; the HMAC key is
derived from it (or from an explicit offline signing_key). Import
refuses expired_trust, wrong_recipient, bad_signature, and
bad_content_hash.
Integrity: canonical JSON content hash + HMAC-SHA256 with a fixed
verification order. Size caps: 8 MiB bundle, 5,000 records, 1,000 memory
entries, 200 snapshot refs.
Local import: writes <session_id>.jsonl atomically (0600, fsync,
rename, dir fsync), merges the memory subset through the JSON memory
backend, reopens the session, and verifies the tree header before
reporting success. Snapshot refs are returned as metadata and are never
replayed into git.
Cross-node: proposed POST/GET/DELETE /api/v1/session-bundles… routes
with Mango identity checks, the same caps, and content-free audit rows.
Nothing server-side ships until the named security review passes.
The local spike lives in client/tests/test_session_export.lua
(two temp homes: export → import → reopen → compare); the corpus-grep
contract is tests/test_session_export_grep.py.
Session Events Bridge
Session events are driven by ZMQ workflow events:
session_events.lua subscribes to workflow lifecycle events
Checkpoints are automatically created on workflow.started, step.started, completed, and failed events
Workflow state is tracked alongside session state for full auditability
Agent Turn Event Stream (Luna in-process)
Luna publishes one typed AgentEvent per turn milestone on the EventBus /
Hooks channel agent.event (in-process only — it is not a wire frame).
The envelope is {schema, type, seq, ts_ms, agent_id, session_id, turn_id, parent_id, iteration, data}; seq is per-turn monotonic from 1.
| Type | When | Key data fields | Terminal |
|---|---|---|---|
agent.started | after the system prompt is ensured, before the first request | mode, model, provider, session_id, input_length, max_iterations, parent_id | no |
agent.stream | each text/thinking delta | channel ("text"|"thinking"), text, accumulated_length | no |
agent.tool_start | dispatch entry (post-gate for execution) | tool_call_id, name, input | no |
agent.tool_end | each tool result/refusal | tool_call_id, name | no |
agent.compacted | a compaction stage completed | trigger (proactive|overflow|post_tools|auto|pre_stream), messages_removed, messages_preserved, summary_length | no |
agent.interrupted | the interrupt latch is consumed | reason (stream_interrupted|followup_interrupted) | no |
agent.ended | the turn’s terminal turn_done | success, error, reason, interrupted, output_length, iterations, duration_ms | yes, exactly once |
agent.tool_end guarantees a prior agent.tool_start with the same
tool_call_id (a synthetic start is emitted for pre-dispatch refusals).
The legacy yield stream and the existing agent.turn_* / provider.*
events are unchanged; the canonical stream is additive and subscriber-gated.
Context Compaction
When the conversation context exceeds the model’s token threshold, Luna compacts the session:
- Preserves system prompt and recent messages
- Summarizes older messages into a compact form
- Tool use/results are preserved or summarized depending on relevance
- All messages remain in
_all_messagesfor full history access
Compaction happens automatically — no user action needed.
Session Format (JSONL)
Each line is a JSON object with a type field:
{"type":"user","content":"Fix the bug in main.rs"}
{"type":"assistant","content":"I'll look at the file first.","tool_uses":[{"id":"tu_1","name":"read_file","input":{"path":"src/main.rs"}}]}
{"type":"tool_result","tool_use_id":"tu_1","content":"fn main() {\n println!(\"Hello\");\n}"}
{"type":"assistant","content":"The issue is on line 2. Let me fix it.","tool_uses":[{"id":"tu_2","name":"edit_file","input":{"path":"src/main.rs","old_text":"Hello","new_text":"Hello, world"}}]}
{"type":"tool_result","tool_use_id":"tu_2","content":"File edited successfully"}
{"type":"assistant","content":"Fixed! The bug was a missing greeting."}
Message Types
| Type | Fields | Description |
|---|---|---|
user | content | User input message |
assistant | content, tool_uses | Agent response (may include tool calls) |
tool_result | tool_use_id, content | Result of a tool execution |
Session Files
Sessions are stored as plain JSONL text files. You can:
Inspect them with any text editor or jq
Search them with grep
Archive them by moving files out of ~/.luna/sessions/
Share them as conversation logs
Rotation and recovery
Large session files rotate: when the append file exceeds ~256 KiB
(ROTATE_AFTER_BYTES) the current file becomes path.1, the previous
.1 becomes .2 (older generations are dropped). A torn or empty
primary file is recovered on load by falling back through the rotated
generations in that order — .1 (newest) then .2. Recovery carries the
rotated generation’s compaction record and labels.
Close is a synchronous flush point
Session:close flushes any pending deferred save INLINE before the
SQLite backend closes — the dual write (JSONL + SQLite) completes at
teardown even when an event loop is present (the normal save path may
defer to the loop; close must not).
Session Mode Persistence
The current agent mode is saved in the session and restored when resuming:
# Session was in "explore" mode when last used
luajit client/main.lua --resume
# Agent continues in "explore" mode
Mode is stored as the mode field in session metadata.
Auto-Generated Session Titles
Sessions automatically get a descriptive title generated by a hidden utility agent:
- After the first assistant response, a title generation agent runs in the background
- Uses a lightweight LLM call to summarize the conversation into a short title
- Falls back to truncating the first user message if the LLM call fails
- Title is stored in session metadata and used by
--sessionsand--search
TUI slash commands
The Luna TUI exposes slash commands that are not zerg CLI commands.
They operate on the live session/agent in the terminal. /help prints the
current list; extension commands are added by /skills and plugins.
| Command | Purpose |
|---|---|
/help, /h | Show the command list |
/quit, /q | Exit Luna |
/new | Start a new session |
/clear | Clear the chat view |
/status | Show session status |
/compact | Compact the session context |
/model [NAME] | Get or set the model |
/mode [NAME] | Cycle or switch the agent mode |
/modes, /agents | List available modes |
/thinking [LVL] | Get or set the thinking level |
/build, /plan, /explore, /review, /general | Switch mode |
/agent, /mode | Switch or inspect the active mode |
/history | Show command history |
/menu, /m | Open the command menu |
/mcp | List MCP servers and tools |
/cost | Show token usage and cost |
/copy, /copyall | Copy the last message / full transcript |
/export [FILE] | Export the transcript |
/delete | Delete the current session and its artifacts |
/gc, /gc run [DAYS] | Dry-run or apply session-corpus GC |
/rename NAME | Rename the current session/branch |
/tree | List branches with the active marker |
/branch [NAME], /fork [NAME] | Create a branch at the current leaf |
/switch N, /jump N | Switch to a branch by index |
/rollback [N] | Drop the last N turns (default 1), auto-branching first |
/image [PATH] | Display an image inline |
/tutorial [reset] | Start or reset the interactive tutorial |
/tools-list, /tools-reload | List or hot-reload workspace tools |
/skills | List/install/manage skills |
/sandbox | Inspect or change the sandbox posture |
/install <dep> | Install an allowlisted dependency |
/theme [NAME] | Get or set the color theme |
/keymaps, /keys | Show current keybindings |
/configure | Run the configuration wizard |
/info | Show diagnostic information |
/docs | Open the canonical docs at https://docs.zergs.net/ |
/interrupt | Interrupt the running agent turn |
Session Search
Search past sessions by content, model, or workspace:
# Search sessions matching a keyword
luajit client/main.lua --search "quicksort"
# List recent sessions
luajit client/main.lua --sessions
# Resume the most recent session
luajit client/main.lua --resume-latest
Sessions are indexed by message content, model name, and workspace path. Index is built lazily on first search.
Disk Usage
Average session: 10-100KB
Large sessions (with many tool calls): up to 256KB before rotation
Sessions rotate automatically but are retained by default — use the
opt-in sweep above (--gc-apply or /gc run [DAYS]) to reclaim space
In-memory/JSONL record retention is bounded by MAX_ALL_MESSAGES
(LUNA_SESSION_MAX_MESSAGES, default 1000; the drop is counted and
logged). This is a per-session record cap, not a corpus GC.
Corruption visibility
JSONL load: session.load_dropped_lines counts dropped/torn lines after a
load; the log carries the count + a first-line snippet. Silent data loss is now
measurable.
SQLite: the FTS index rebuilds only when the fingerprint changes (not every
open); session_sqlite:integrity_check runs PRAGMA integrity_check on demand
(operator surface — no CLI command yet); PRAGMA optimize fires on close.
Blobs: LUNA_BLOB_MAX_BYTES (default 10 MB) rejects oversized stores loudly;
a torn blob (content-hash mismatch) raises on retrieve — never a silent nil.
Engine reference — generated from the canonical engineering source. Do not edit this page by hand.
Permissions & Safety
Luna uses a multi-layered permission system: permission modes (global), per-mode rulesets (fine-grained), danger detection (regex-based), and an optional AI classifier (LLM-based).
Permission Modes
6 modes control which tools the agent can use. Set via CLI, config, or TUI.
default
Standard mode. Per-mode rulesets determine allow/deny/ask per tool.
allow-all
No restrictions. All operations proceed without checks.
deny-all
Agent can only reason — no tool execution at all.
read-only
Only tools whose permission class is read (or unclassified) are allowed —
read_file, glob_search, grep_search, list_directory, web_fetch,
lsp, web_search, todo, mcp_read_resource, mcp_get_prompt and any
other read-category tool. The gate is class-based, not a fixed list
(permission_checker.lua resolves each tool’s class from its spec).
plan
The permission mode paired with the Plan agent mode; resolves exactly like
default (per-mode rulesets; ask/write-class escalations go through the
permission dialog).
auto (AI Classifier)
When the static ruleset returns "ask", an LLM-based classifier evaluates tool safety. If confidence >= 0.85, the decision is automatic. Otherwise, falls back to TUI permission dialog.
Requires Ollama (or compatible) to be running locally. Falls back to dialog if the classifier is unavailable.
Setting Permission Mode
CLI
luajit client/main.lua --permission-mode default
luajit client/main.lua -p auto
luajit client/main.lua -p allow-all
Valid values: default, allow-all, deny-all, read-only, plan, auto
Config File
// ~/.luna/config.json
{
"permission_mode": "auto"
}
TUI Slash Commands
/auto Enable AI classifier permission mode
Mode-specific permission rulesets are applied automatically when switching modes with Tab.
Per-Mode Rulesets
Each agent mode has a built-in permission ruleset that maps tool names to allow, deny, or ask.
Built-in Mode Defaults
Build Mode
Source: MODE_DEFAULTS.build (client/core/permission_ruleset.lua).
| Tool | Decision | Notes |
|---|---|---|
read_file, glob_search, grep_search, list_directory, web_fetch, lsp, web_search, todo, mcp_read_resource, mcp_get_prompt | allow | Read/search always allowed |
bash | ask | User approval required |
write_file | ask (except *.md → allow) | File pattern matching supported |
edit_file, create_directory, undo_edit, background_spawn | ask | User approval required |
delete_file | deny | Always blocked |
* (default) | ask | Unknown tools require approval |
Plan Mode
| Tool | Decision |
|---|---|
| Read/search/web tools | allow |
* (default) | deny |
Explore Mode
| Tool | Decision |
|---|---|
| Read/search/lsp tools | allow |
* (default) | deny |
Review Mode
| Tool | Decision |
|---|---|
| Read/search/lsp/web tools | allow |
web_fetch | ask |
* (default) | deny |
General Mode
| Tool | Decision |
|---|---|
* (default) | allow |
bash | ask |
delete_file | ask |
background_spawn | allow |
Coordinate Mode
coordinate registers as an agent mode but has no dedicated built-in
ruleset — default_for_mode("coordinate") falls back to the Build
ruleset (permission_ruleset.lua), so it resolves exactly like Build unless
an extension or the mode definition carries its own permissions table.
Teammate / Leader Modes
The team-swarm modes carry dedicated rulesets: teammate is deny-default
(read/search allow; write_file/edit_file/create_directory ask;
delete_file, sub_agent, memory, undo_edit,
attach_image, background_spawn denied; team_mail allowed); leader
mirrors General (* allow, bash/delete_file ask).
File Pattern Matching
Rulesets support file pattern matching for tools that take file paths:
{
"write_file": {
"default": "ask",
"patterns": {
"*.md": "allow",
"*.env": "deny"
}
}
}
Patterns use glob syntax: *.ext, path/prefix*, etc.
Danger Detection
Before evaluating the ruleset, the danger detector (client/core/danger_detector.lua, PATTERNS) scans bash commands against 45 regex patterns — 26 dangerous + 19 caution (plus additional AST-derived dangerous findings for pipe-to-shell, block-device writes and recursive deletes). Examples:
| Category | Patterns | Example |
|---|---|---|
| Destructive delete | rm -rf /, rm -rf ~ | Always dangerous |
| Remote code execution | curl | bash, wget | sh | Always dangerous |
| System control | shutdown, halt, poweroff | Always dangerous |
| Privilege escalation | sudo, chmod 777 | caution |
| Network exfil | scp, rsync to remote | caution |
| File removal | rm - with flags | caution |
Override behavior:
dangerous → overrides allow to deny
caution → overrides allow to ask
AI Classifier (Auto Mode)
When permission_mode is auto, an Ollama-hosted LLM classifies "ask" decisions:
Tool invocation → Ruleset → "ask"
│
├── AI classifier available?
│ ├── Yes → Classify (5s timeout)
│ │ ├── confidence >= 0.85 → auto allow/deny
│ │ └── confidence < 0.85 → TUI dialog
│ └── No → TUI dialog
└── Not auto mode → TUI dialog
Configuration
{
"classifier": {
"enabled": true,
"model": "qwen2.5-coder:7b",
"provider": "ollama",
"base_url": "http://localhost:11434",
"confidence_threshold": 0.85,
"timeout": 5,
"cache_size": 64
}
}
| Setting | Default | Description |
|---|---|---|
enabled | false | Global enable/disable |
model | qwen2.5-coder:7b | Classifier model (fast local recommended) |
confidence_threshold | 0.85 | Minimum confidence for auto-decision |
timeout | 5 | Seconds before fallback to dialog |
cache_size | 64 | LRU cache entries for repeated invocations |
Environment Overrides
| Variable | Description |
|---|---|
LUNA_CLASSIFIER_ENABLED | "true" / "false" |
LUNA_CLASSIFIER_MODEL | Override classifier model |
LUNA_CLASSIFIER_PROVIDER | Override classifier provider |
LUNA_CLASSIFIER_THRESHOLD | Override confidence threshold (0.0-1.0) |
Safety Guarantees
The classifier never blocks tool execution on failure:
| Scenario | Behavior |
|---|---|
| Classifier model unavailable | Show TUI dialog |
| Request timeout (>5s) | Show TUI dialog |
| Response unparseable | Show TUI dialog |
| Confidence below threshold | Show TUI dialog |
Bypass-immune safety classes & denial breaker
Four safety classes (dangerous_command, secret_access, credential_write,
destructive_delete) always escalate an ALLOW to the ask flow regardless of
the permission mode — including allow-all, auto, and server-admin ["*"]
grants — while DENY results stay deny and safety-class allows are never
cached. Consecutive permission denials (permission_denial_limit, default 3)
latch a per-agent breaker that ends the turn with the typed
permission_denial_limit terminal after the current tool batch. The full
mode × class table, trigger list, and reset/event contract live in
security.md → Luna safety classes & denial circuit breaker.
Permission Evaluation Flow
1. Global mode check
├── allow-all → execute immediately
├── deny-all → block immediately
└── read-only → only allow read-category tools
2. Mode ruleset evaluation
└── PermissionRuleset.evaluate_with_danger(mode_rules, tool, input)
├── Static rule: allow → execute
├── Static rule: deny → block
└── Static rule: ask → danger analysis
├── danger_level == dangerous → deny (override)
├── danger_level == caution + allow → ask (upgrade)
└── ask → permission_mode check
├── auto → AI classifier
└── other → TUI permission dialog
3. TUI dialog → user approves/denies
Mutation Queue
Write operations (write_file, edit_file, delete_file) are serialized through a mutation queue. This prevents race conditions when the agent executes multiple concurrent tool calls that modify the same files.
Server-Side RBAC (Scopes)
Everything above governs a worker — what a Luna agent may do on its host.
A completely separate layer governs the control plane: every Sol HTTP
route requires a verb:resource permission scope (e.g. inference:start,
tasks:read, zmq:dispatch — 61 scopes), resolved from the caller’s token
via Mango roles, with an additional object-ownership layer on task,
workflow, conversation, and orchestrate detail routes, plus an
execute-grade split (tasks:execute) that gates execute-class tools on
dispatched workers.
The full scope table, gate semantics, admin vs service-token vs user-token behavior, failure postures (401/403/404/503), and the Mango role composition model live in the dedicated reference: rbac-scopes.md.
Tools
Luna provides 92 registered tools (tools=92; 74 built-in + 12 computer-use + 6 desktop-environment) plus dynamic MCP tool discovery. The LLM agent autonomously selects and executes tools based on the task. Permission modes and per-mode rulesets control which tools are available.
Tool Prefix Conventions
| Prefix | Source | Example |
|---|---|---|
builtin__ | Built into Luna | builtin__bash, builtin__read_file |
custom__ | Discovered from workspace | custom__my_tool |
mcp__ | MCP server | mcp__github_create_issue |
File Operations
bash
Execute shell commands in the workspace directory.
| Parameter | Type | Required | Description |
|---|---|---|---|
command | string | Yes | Shell command to execute |
timeout | number | No | Timeout in milliseconds (default: 60000) |
Output limited to 16KB. Exit code included in result. Commands use fork/exec with pipe capture.
read_file
Read file contents with optional line range. Detects image files and returns base64-encoded content blocks for vision-capable models.
| Parameter | Type | Required | Description |
|---|---|---|---|
path | string | Yes | Absolute file path |
offset | number | No | Starting line number (1-based) |
limit | number | No | Maximum lines to read |
write_file
Create or overwrite a file atomically.
| Parameter | Type | Required | Description |
|---|---|---|---|
path | string | Yes | File path |
content | string | Yes | File content |
Max size: 10MB. Uses atomic write (write to .tmp, then rename). Queued through mutation queue.
edit_file
Search and replace in an existing file. Fails if old_text is not found or matches multiple locations.
| Parameter | Type | Required | Description |
|---|---|---|---|
path | string | Yes | File path |
old_text | string | Yes | Exact text to find |
new_text | string | Yes | Replacement text |
Search
glob_search
Find files matching a glob pattern. Max 100 results, sorted by modification time.
| Parameter | Type | Required | Description |
|---|---|---|---|
pattern | string | Yes | Glob pattern (supports ** recursive) |
path | string | No | Base directory |
grep_search
Search file contents with regex. Max 50 results.
| Parameter | Type | Required | Description |
|---|---|---|---|
pattern | string | Yes | Regular expression pattern |
path | string | No | Base directory |
code_search
Search code using language-server analysis or text search fallback.
| Parameter | Type | Required | Description |
|---|---|---|---|
query | string | Yes | Symbol name or text pattern |
search_type | string | Yes | definition, references, symbols, text |
file_path | string | No | Limit to this file |
language | string | No | Limit to this language |
Code Intelligence
lsp
Query a language server. Supports 7+ language servers.
| Parameter | Type | Required | Description |
|---|---|---|---|
operation | string | Yes | goToDefinition, findReferences, hover, documentSymbol, diagnostics |
path | string | Yes | File path |
line | number | Yes | Line number (1-based) |
character | number | Yes | Column number (1-based) |
Git
git
Execute structured git operations. Dangerous operations (force push, hard reset, rebase) are blocked.
| Parameter | Type | Required | Description |
|---|---|---|---|
command | string | Yes | status, diff, log, branch, show, add, commit, stash, checkout |
args | string | No | Optional arguments |
path | string | No | Optional file path |
git_snapshot
Manage git snapshots for undo and review. Auto-created after mutating tools
(: a mutating-tool completion schedules a debounced
snapshot_all when the session workspace is a git repo — debounce 2s,
24h cleanup retention; failures are warn-logged, never fatal to the tool).
Session checkpoints in a git workspace also record the working-tree HEAD
hash, and restore_checkpoint restores the tree to that position.
| Parameter | Type | Required | Description |
|---|---|---|---|
command | string | Yes | list, diff, restore |
snapshot_id | string | No | Snapshot commit hash |
files | array | No | File paths to restore |
count | number | No | Number to list (default: 10) |
Web
web_fetch
Fetch content from a URL. Output limited to 1MB. Uses libcurl via FFI.
| Parameter | Type | Required | Description |
|---|---|---|---|
url | string | Yes | URL to fetch |
format | string | No | text (default) or markdown |
web_search
Search the web via SearXNG or Brave Search API.
| Parameter | Type | Required | Description |
|---|---|---|---|
query | string | Yes | Search query |
max_results | number | No | Maximum results (default: 10) |
http_request
Make HTTP requests (GET, POST, PUT, PATCH, DELETE, HEAD).
| Parameter | Type | Required | Description |
|---|---|---|---|
url | string | Yes | Request URL |
method | string | Yes | HTTP method |
headers | object | No | Request headers |
body | string | No | Request body |
timeout | number | No | Timeout in milliseconds |
stream | boolean | No | Stream response |
max_stream_bytes | number | No | Max bytes when streaming (default: 100KB) |
MCP Tools
mcp_read_resource
Read a resource from an MCP server. If no server specified, tries all connected servers.
| Parameter | Type | Required | Description |
|---|---|---|---|
uri | string | Yes | MCP resource URI |
server | string | No | Specific MCP server name |
mcp_get_prompt
Get a prompt template from an MCP server.
| Parameter | Type | Required | Description |
|---|---|---|---|
name | string | Yes | Prompt template name |
arguments | object | No | Template arguments |
server | string | No | Specific MCP server name |
Session Tools
todo
Manage a session-scoped task checklist.
| Parameter | Type | Required | Description |
|---|---|---|---|
action | string | Yes | list, add, update, remove |
id | string | No | Task ID |
text | string | No | Task description |
status | string | No | pending, in_progress, completed |
priority | string | No | high, medium, low |
undo_edit
Undo the last file edit(s). Maintains a stack of up to 50 entries.
| Parameter | Type | Required | Description |
|---|---|---|---|
count | number | No | Number of edits to undo (default: 1) |
task
Spawn a sub-agent with its own context. 60-second timeout, up to 20 steps.
| Parameter | Type | Required | Description |
|---|---|---|---|
prompt | string | Yes | Task description |
tools | array | No | Restrict to these tools |
backend | string | No | local, zmq, luerl, team, background |
switch_mode
Switch the agent to a different operating mode.
| Parameter | Type | Required | Description |
|---|---|---|---|
mode | string | Yes | Mode name |
reason | string | Yes | Why the switch is needed |
Team Tools
Team assignment is directive-driven. The retired
team_spawntool has no live registration; work is assigned to teammates through Sol team directives, and workers communicate viateam_mail.
team_mail
Send a message to team members via priority mailbox.
| Parameter | Type | Required | Description |
|---|---|---|---|
team_id | string | Yes | Team ID |
body | string | Yes | Message body |
to | string | No | Recipient ID or all |
subject | string | No | Message subject |
priority | string | No | high, normal, low |
Utility Tools
calculator
Evaluate mathematical expressions safely. No code execution. Expressions are
evaluated in a restricted math-only environment (only math functions,
pi/e, and arithmetic operators are reachable).
| Parameter | Type | Required | Description |
|---|---|---|---|
expression | string | Yes | Math expression |
diagram
Generate Mermaid diagrams from descriptions.
| Parameter | Type | Required | Description |
|---|---|---|---|
description | string | Yes | What the diagram should show |
diagram_type | string | No | flowchart, sequence, class, state, er, gantt |
code | string | No | Direct Mermaid code |
file_watcher
Watch a file or directory for changes. Uses inotify when available.
| Parameter | Type | Required | Description |
|---|---|---|---|
path | string | Yes | File or directory path |
timeout | number | No | Seconds to watch (default: 10, max: 60) |
attach_image
Attach an image for multimodal analysis. Max 20MB.
| Parameter | Type | Required | Description |
|---|---|---|---|
path | string | Yes | Absolute path to image |
Desktop Automation Tools
6 desktop automation tools registered when the required display-server utilities are detected (X11/Wayland). Each tool degrades gracefully (is not registered) when its backing binary is absent, so headless environments simply expose fewer tools:
| Tool | Description | Permission | Requires |
|---|---|---|---|
window_manage | Manage windows via bspwm tiling WM (list, focus, close, move, resize, desktops, layout, fullscreen) | execute | bspwm (bspc) |
desktop_notify | Send desktop notifications (title/body/urgency) | execute | libnotify (notify-send) |
display_layout | Get or set display configuration via xrandr (list, arrange, resolution) | execute | xrandr |
window_info | Get detailed window geometry, title, WM_CLASS, and properties | read | xwininfo / xprop |
audio_control | Control audio via PulseAudio/PipeWire (list_sinks, set_volume, mute, unmute) | execute | pactl |
xrdb_query | Query or load the X11 resource database (query, get, load) | read | xrdb |
All desktop automation tools gracefully degrade in headless environments.
Tool Discovery
Luna scans the workspace for custom tool definitions:
Workspace scanning from .luna/tools/ and ~/.luna/tools/
Hot-reload with /tools-reload slash command
Listing with /tools-list slash command
Namespacing with custom__ prefix for discovered tools
Tool Selection Patterns
| Task | Tools |
|---|---|
| Explore codebase | glob_search, grep_search, read_file |
| Fix a bug | read_file, bash, edit_file, undo_edit |
| Create a new file | write_file |
| Refactor code | glob_search, read_file, edit_file, multi_edit |
| Run tests | bash |
| Research online | web_search, web_fetch |
| Code navigation | lsp |
| Track multi-step work | todo |
| Delegate subtask | task |
| Team collaboration | team_mail (+ team directives) |
MCP Integration
Luna connects to Model Context Protocol (MCP) servers to extend the agent’s capabilities beyond built-in tools. MCP servers provide additional tools, resources, and prompt templates through a standardized JSON-RPC protocol.
Overview
Luna Agent
|
+-- Built-in tools (bash, read_file, write_file, ...)
|
+-- MCP Manager
+-- MCP Server 1 (stdio) -> filesystem tools
+-- MCP Server 2 (stdio) -> GitHub tools
+-- MCP Server 3 (stdio) -> database tools
MCP tools are discovered automatically on connection and merged with built-in tools. The LLM sees all tools (built-in + MCP) in its tool list, prefixed with mcp__.
Protocol Version
Luna implements the Model Context Protocol specification (2025-03-26), supporting:
initialize handshake with capability negotiation
tools/list for tool discovery
tools/call for tool execution
resources/read for resource access
prompts/get for prompt template retrieval
Transport
stdio Transport
Communication via stdin/stdout JSON-RPC. Each server runs as a separate subprocess.
Content-Length header support for framing
Multi-server support – connect to multiple MCP servers simultaneously
Best-effort connection model
HTTP Transport
Luna also supports HTTP-based MCP servers for remote tool access. HTTP transport enables connections to MCP servers that are not local processes.
Configuration
Global Config: ~/.luna/mcp.json
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/home/user/projects"]
},
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_PERSONAL_ACCESS_TOKEN": "ghp_..."
}
}
}
}
Project-local Config: .luna/mcp.json
Same format as global config. Project-local config is merged with global config. Global configuration takes precedence on conflicts; project-local HTTP/SSE servers require a hash-keyed approval, and project-local credential families are stripped without consent.
Config Structure
| Field | Type | Required | Description |
|---|---|---|---|
command | string | Yes | Command to start the MCP server |
args | array | No | Arguments to pass to the command |
env | object | No | Environment variables for the server process |
Tool Discovery
When Luna starts:
- Reads MCP config (global + project-local, merged)
- Starts each configured server as a subprocess
- Sends
initializeandtools/listJSON-RPC requests - Merges discovered tools into the agent’s tool registry
- The LLM sees all tools (built-in + MCP) in its system prompt
Discovered MCP tools are prefixed with mcp__ in the tool registry (e.g., mcp__github_create_issue).
Multi-Server Management
Luna can connect to multiple MCP servers simultaneously. Each server runs as an independent subprocess with its own lifecycle:
Servers are started in parallel during initialization
Each server’s tools are namespaced by server name
If one server fails, others continue operating normally
Use mcp_read_resource and mcp_get_prompt with the optional server parameter to target a specific server
OAuth PKCE
Luna supports OAuth 2.0 with PKCE (Proof Key for Code Exchange) for MCP servers that require authentication:
- Luna generates a code verifier and challenge
- Starts a local callback server via FFI raw socket
- Opens the authorization URL in the user’s browser
- Receives the authorization code at the callback URL
- Exchanges the code for an access token using the code verifier
- Stores the token for subsequent API calls
OAuth configuration is specified per-server in the MCP config.
Luna as MCP Server
Luna can also act as an MCP server, exposing its built-in tools to external MCP clients. This enables other applications to use Luna’s file operations, code intelligence, and other capabilities through the standard MCP protocol.
When running as an MCP server, Luna:
Responds to initialize and tools/list requests
Executes tools via tools/call and returns results
Supports the same JSON-RPC message format
Example MCP Servers
Filesystem Access
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/allowed/dir"]
}
}
}
GitHub Integration
{
"mcpServers": {
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_PERSONAL_ACCESS_TOKEN": "ghp_..."
}
}
}
}
PostgreSQL Queries
{
"mcpServers": {
"postgres": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-postgres", "postgresql://user:pass@localhost/db"]
}
}
}
Custom MCP Server
Any MCP-compatible server can be used. The server must:
- Accept JSON-RPC requests on stdin
- Respond with JSON-RPC responses on stdout
- Support
initializeandtools/listmethods - Follow the MCP specification
Best-Effort Connection
MCP connections are best-effort:
| Scenario | Behavior |
|---|---|
| Server fails to start | Luna logs a warning and continues without its tools |
| Server crashes mid-session | Luna logs the error and continues with remaining tools |
| Server restarts | Manual restart required |
Troubleshooting
MCP server not connecting:
Check the command path is correct and the binary exists
Check args are properly formatted
Check environment variables (especially API keys)
Look for errors in ~/.luna/logs/
MCP tools not appearing:
Ensure the server supports tools/list method
Check that the server starts without errors
Verify the server responds to initialize request
Use /tools-reload to rescan after fixing configuration
Enterprise: Microsoft MCP Gateway
For organizations managing fleets of MCP servers, WILDZERG Enterprise integrates with Microsoft MCP Gateway (MIT license — a separate Microsoft component, licensed/distributed independently, integrated at the MCP protocol layer). The gateway provides:
Reverse proxy with session-aware stateful routing to MCP server pods
Lifecycle management — deploy, update, delete MCP servers via REST API
Tool Gateway Router — dynamic routing of tool calls to registered tool servers by name
Management portal — React SPA at /portal/ for browsing and testing adapters in-browser
RBAC — mcp.admin and mcp.engineer roles, bridged to GLAuth/Dex identity
MCP Gateway runs on Kubernetes (k0s on blue for dev; customer’s own k8s cluster for Enterprise). See:
corp/docs/mcp-gateway-integration-strategy.md — three-layer MCP architecture (Luna client + Luna server + MCP Gateway management)
corp/docs/k0s-evaluation.md — k0s deployment analysis and root cause resolution
wild/k0s/mcp-gateway.yaml — Kubernetes manifest (Deployment + Service + RBAC)
ZERG is the agent runtime. MCP Gateway’s built-in Foundry agent runtime is always disabled (FoundrySettings:Endpoint=""). Luna provides the agent execution; MCP Gateway provides the management plane.
Workflows and scheduler
Workflows
A workflow is a durable state machine. Each step is a task (or a nested workflow) with an owner, a budget, and a compensation action. The engine persists state transitions, tokens, cost, and attempt markers so a crash does not silently re-execute a completed step.
Key properties:
Pause is a gate. Events that arrive while paused are parked and resumed deliberately; a paused workflow does not execute side effects.
Compensation is LIFO and includes the failing step. A failed step’s compensation is sequenced before its predecessors; markers are written before effects so a kill window cannot double-compensate.
Budgets auto-stop. Token and time budgets are enforced; exceeding a budget enters a terminal budgetlimited path.
Definitions are hashed. A persisted workflow refuses a definition that drifted underneath it.
Terminal GC and branch inheritance keep the instance graph bounded and consistent.
Recipes
Recipes are named workflow definitions, validated at load and reloadable at runtime. zerg recipe-list, recipe-show, recipe-run, and recipe-reload are the operator surface.
Authoring
Workflow definitions bind step names to registered task/agent chains. The registry validates that every referenced chain exists at load; an unknown chain refuses the definition loudly. See the API reference for start/cancel/branch/tree/lineage.
Scheduler
The scheduler runs jobs on cron, an interval, or a one-time epoch.
Create-time validation refuses impossible schedules (for example a day-of-month that cannot occur in the selected month). Single-writer claim. A job is claimed atomically in the store; multiple dispatch paths cannot double-run it. Timezone posture. Cron expressions are interpreted as UTC unless the deployment documents otherwise. This is a deliberate, dependency-free choice. Persistence classes. Deletes/disables are immediate; bulk edits are debounced and the bounded residual is documented. Stuck-job recovery resets a stuck job with backoff and raises a CRITICAL after repeated attempts.
Commands
zerg schedule list
zerg schedule add "Run the health summary" --cron "0 */6 * * *" --name health-summary
zerg schedule show <job-id>
zerg schedule pause <job-id>
zerg schedule unpause <job-id>
zerg schedule run <job-id>
zerg schedule delete <job-id>
Exactly one schedule source is used: --every wins over --cron, which wins over --at. --at takes Unix epoch seconds; an ISO 8601 string is silently dropped.
Next
First workflow tutorial Workflow API Scheduler API Events reference
Teams and channels
Teams
A team is a leader and a set of teammates working a shared objective. The control plane owns team lifecycle, membership, directives, and the member mailbox.
Lifecycle: create, list, inspect, add/remove members, destroy. Creation is admin-only; reads are member/creator/admin; mutating a team requires the teams:manage gate.
Directives are the fleet-correct assignment plane (the historical teamspawn tool is retired). A directive is signed on the wire; a worker refuses an unsigned directive.
Mailbox: members can read their team’s mail; sends require the creator/admin mutator gate. Messages are durable and can be acknowledged.
Cancellation propagates to the team subtree; children are walked through the durable store, and already-frozen rows are released exactly once.
Caps and attribution: per-member caps and team usage attribution are available on the Mango side.
Commands
zerg team mail list --team <team-id>
zerg team mail send --team <team-id> --to <member> --body "Status?"
Team creation and membership are HTTP APIs; see Teams API.
Channels
Channels connect ZERG to external messaging surfaces (Telegram, Discord, Slack, Microsoft Teams, and generic webhooks).
Ingress validation: each channel validates its signature/secret before accepting a message. Origin-routed replies: a reply returns to the channel that originated the task, even when multiple channels are active. Rate buckets: per-channel rate limiting prevents one noisy channel from starving the others. Replay protection: webhook update ids are deduplicated within the documented window. Delivery autonomy: a channel with no handler is retired loudly rather than silently dropping messages.
Commands
zerg channels
zerg channel-add <type> <config> --name <name>
zerg channel-test <channel-id>
zerg channel-send <channel-id> "message"
zerg channel-remove <channel-id>
Channel secrets are redacted in logs and support bundles.
Next
Teams API Channels API Permissions and sandbox Security model
Memory and workspace
Memory
Luna keeps memory at three layers, selected by configuration:
| Backend | What it is | When to use it |
|---|---|---|
file | Human-readable files with fsync’d tmp→rename writes and an in-lock dirty-set overlay | Small, inspectable memory; air-gap |
vector | Embedding-backed semantic retrieval | Large corpora, semantic search |
hybrid | File + vector with union/tombstone semantics | Best recall with durable files |
Memory is scoped by principal and namespace. Plugin memory is scoped plugin:<Plugin>:<UserUuid>:<Key>. A source tag and untrusted-content fences are applied before extracted memory is reused, and injection scans run on the way in.
What to know
Vector timeouts are bounded (not 5000 seconds); a slow embedding provider cannot wedge the worker.
The JSON/file backends take a lock and re-read before write; a torn tail is healed with a checked rename.
A corrupt blob becomes a typed placeholder, never an error that kills the agent.
Memory decay emits a real event; retention is documented per backend.
Workspace
The workspace is the only filesystem surface a task may touch by default.
Server-derived scope. The dispatcher strips client-supplied workspace_root and tenant_id, then roots the task at <workspace_root>/users/<server-scope>/. The scope is derived from the authenticated user_uuid, not a request field.
HTTP workspace API uses the same rule: a non-admin caller is rooted at its own subtree; an admin may cross.
Symlink escape refusal. Paths are canonicalized; a symlink that escapes the root is refused.
Read/write caps. A workspace read is size-capped (10 MB), and writes are gated by the workspace:write class.
.luna secrets are denied to the sandbox except for the explicit secret subset; the deny is anchored and tested.
Next
Sessions and chat Permissions and sandbox Memory API Workspace API
Providers and models
The model plane
Sol resolves a requested model to a provider, applies the provider’s wire format, enforces circuit breakers, and accounts for usage and cost. The catalog and provider map are machine-derived:
contract/modelcatalog.yaml — model metadata and vendor rate metadata.
docs/fixtures/modelprovidermap.json — model → provider mapping.
Providers
14 adapters ship (Anthropic, OpenAI, OpenAI-compatible, Gemini, DeepSeek, z.ai GLM, Alibaba Qwen, AWS Bedrock, Ollama, and others), with 8 circuit-breaker-protected paths. A provider declaration can be:
Declarative: a bundled adapter with an api_key_env name (never a raw key in config).
Custom: a settings-level base_url + wire_format + models entry with api_key_env, or a loopback no_api_key endpoint.
Provider keys added through the operator pool are encrypted at rest (provider_keys.bin, AES-256-GCM, 0600) and are part of the backup scope.
Fallback and circuits
A fallback chain is evaluated at the single admission funnel: bounded, retryable-class only, and never after tokens have been emitted.
A circuit opens on the resolved provider target, not just the provider name, so two models on one provider do not share a failure incorrectly.
Retry-After is honored and jittered; a local circuit recovers without a restart.
Local inference
Local llama.cpp lanes are a first-class provider path. Sol starts, leases, validates, and releases lanes; clients consume a Sol-issued grant. See Local inference.
Cost and usage
Usage is parsed from the wire once; a missing usage block does not become a fabricated zero.
Cost is computed from the catalog’s rate metadata and attributed to the principal and model.
GET /api/v1/usage exposes self/admin usage; the cost ledger and spend guard enforce budgets.
Next
Provider setup Model catalog Local inference Cost and budgets
Local inference
ZERG supports two local-inference postures; neither requires a legacy local-model daemon.
1. Sol-managed lanes
Sol owns the lane lifecycle on the server that hosts the GPU:
A lane is registered with a model row, engine bundle, and host class. Sol starts the process, leases it, validates it, and releases it. Clients consume a Sol-issued grant; they never talk to llama.cpp directly. A killed lane is released and a new lease is granted; a node failure marks the lease stale.
Operators use zerg discover, zerg start, zerg stop, zerg prepare, and the lane catalog.
2. Standalone engine bundle
For Sol-less editor hosts and air-gapped environments, install a ZERG-provenanced engine bundle and point the settings providers + standalone tables at its loopback endpoint. The bundle is verified against its provenance/manifest, and upgrade/rollback are explicit operations.
Engine provenance
Every shipped engine has a provenance record (source revision, build recipe, host class, digest) and a rollback path. A lane refuses an unprovenanced bundle. See Engine provenance.
Air-gap
No mandatory egress. Model weights are carried in; bundles are verified offline.
LUNAALLOWOSVCHECK and update-check egress are opt-in and fail closed.
The docs site itself is served from the cluster.
Next
Lane catalog Local inference runbook Provider setup Air-gap install
Limon console
Limon is the Vue 3 operations console: real-time agent activity over WebSocket, chat, workflows, teams, audit, providers, memory, events, schedules, and settings.
Views (21)
Login, Dashboard, Chat, Workflows, Audit, Workers, Recipes, Settings, Channels, Skills, Goals, BgWorkers, Providers, Memory, Events, Schedules, Teams, System, ManagedSettings, Seats, Telemetry.
/infra is a router alias to System (the standalone Infra view was retired because it duplicated System).
Authentication
Limon uses the Mango identity plane. The session token is stored once and cleared on a single 401 path; WebSocket auth uses a one-time ticket minted over REST, so the bearer token never appears on the WS wire.
Development
cd limon
npm install
npm run dev
Production builds are served by the wild blueprint’s OpenResty edge alongside the Sol and Mango APIs.
Operational notes
The chat view supports session tree/branch/snapshot controls. Streaming renders are throttled; a reconnect uses partial-turn semantics. The console is desktop-first and targets evergreen browsers.
Full guide
See Limon user guide for every view and interaction.
Engine reference — generated from the canonical engineering source. Do not edit this page by hand.
Limon User Guide
Limon is the ZERG ops console and chat interface (Vue.js 3 SPA served by
the wild deployment). It has 21 views (limon_views=21) behind one login. This page
enumerates every view truthfully from limon/src/router.ts and the view
components; it is the first user-facing documentation of the console.
Sign-in and session
LoginView (/login) is the only public route (router.ts:8-13).
Credentials are Mango account + password; the session is stored in
sessionStorage and validated on first navigation ( restore —
router.ts:173-210).
There is exactly one 401 path (handleUnauthorized in the auth
store, ): a dead token clears the session and redirects
to /login — no per-view logout logic, no duplicate redirects.
Capability gating: every route declares one meta.capability, and
every capability maps to exactly one server scope (utils/capabilities.ts
generated from the shared RBAC matrix). Non-holders bounce to
/dashboard; actions (New Chat, End Session, Publish, endpoint changes)
render only when their exact grant is present. The vocabulary is the
SERVER’s: only the bare * grant counts as admin (the
retired admin:* alias is NOT special, and namespace wildcards such as
chat:* are NOT expanded — matching is exact string or *), and no
console code hand-picks isAdmin for a surface the server grants to
members. The ONE
documented exception is /schedules: the Sol handler
(sol_http_scheduler:list_jobs/1) answers an empty success page to every
non-admin, so the route, nav link and view are admin-gated
(meta.requiresAdmin) and a non-admin direct mount renders a typed
permission state instead of “No schedules found”.
List envelopes: Channels reads the shared pagination
envelope ({items,total,...}) and normalizes the current Sol emitter’s
JSON-encoded channel rows. Team list rows carry no membership data, so
a team card shows members unknown until a detail/membership fetch
supplies member_count — it never invents “0 members”.
The 21 views
| # | Route | View | Purpose | Access |
|---|---|---|---|---|
| 1 | /login | LoginView | Sign in (public) | public |
| 2 | / | DashboardView | Health (10s poll), audit summary, worker list, connection status | authenticated |
| 3 | /workflows | WorkflowView | Workflow/recipe list + start | workflows:read |
| 4 | /workflows/:id | WorkflowView | Workflow detail: tree, lineage, branch, cancel | workflows:read |
| 5 | /chat | ChatView | Agent chat (model picker, streaming) | chat:read |
| 6 | /chat/:id | ChatView | Resume a chat session by id | chat:read |
| 7 | /teams | TeamsView | Team management (create, mail) | teams:list; create/manage gated |
| 8 | /skills | SkillsView | Skill marketplace: browse/publish/report | skills:browse; publish/manage gated |
| 9 | /schedules | SchedulesView | Scheduled jobs: create, pause/resume, run now, delete | admin only (server gate); schedule:manage/schedule:spawn gate the actions |
| 10 | /recipes | RecipesView | Workflow recipe templates (JSON-driven) | workflows:read |
| 11 | /goals | GoalsView | Agent goals (5s poll) | goals:read |
| 12 | /bg-workers | BgWorkersView | Background workers: list/start/kill (5s poll) | infra:read |
| 13 | /memory | MemoryView | Cross-session memory: agent picker, search | memory:read |
| 14 | /settings | SettingsView | Connection (API/Mango URLs), branding (Enterprise), seat info | authenticated; endpoint changes need settings:write |
| 15 | /audit | AuditView | Audit event log (filter by category) | audit:read |
| 16 | /workers | WorkersView | Connected ZMQ workers (5s poll) | zmq:list |
| 17 | /channels | ChannelsView | Delivery channels (telegram/discord/webhook): create/remove/test | channels:read; manage gated |
| 18 | /events | EventsView | Event stream browser (paged, 50/page) | audit:read |
| 19 | /providers | ProvidersView | LLM provider health (5s poll) | infra:read |
| 20 | /settings/managed | ManagedSettingsView | Managed (server-enforced) settings: key/value edit | settings:read |
| 21 | /seats | SeatsView | License status (seats, tier) | metrics:read |
| 22 | /system | SystemView | System/uptime overview (polling) | infra:read |
| 23 | /infra | SystemView (alias of /system) | Infrastructure: service health + resource monitoring | infra:read + clustering seat gate (router.ts:166-184) |
| 24 | /telemetry | TelemetryView | Telemetry event stream (type/timestamp/data) | infra:read; clear needs infra:manage |
Counted by distinct view components: 21 (LoginView, DashboardView,
WorkflowView, ChatView, TeamsView, SkillsView, SchedulesView,
RecipesView, GoalsView, BgWorkersView, MemoryView, SettingsView,
AuditView, WorkersView, ChannelsView, EventsView, ProvidersView,
ManagedSettingsView, SeatsView, SystemView, TelemetryView). The former
InfraView was deleted in (it duplicated SystemView); /infra
still renders SystemView with the clustering seat gate. /workflows
and /workflows/:id share WorkflowView; /chat and /chat/:id share
ChatView.
Chat & streaming model
Chat connects over WebSocket to
/api/v1/chat/<sessionId>/ws (useChatWebSocket.ts:92). The scheme
derives from the configured API URL (http→ws, https→wss; the
pre-fix forced-wss rule was removed in ).
Authentication rides a short-TTL (60s) single-use ticket
minted over the authenticated REST channel
(POST /api/v1/chat/:id/ws-ticket) and presented as the
zerg_ticket, <ticket> subprotocol — the bearer token never touches
the WS wire (; the token had earlier leaked into
proxy/access logs via the query string until ). Limon STOPPED
SENDING the old zerg_auth, <token> bearer subprotocol in
ticket-or-cookie is Limon’s only posture, and every reconnect
mints a fresh ticket (single-use) through a new socket with a manual
full-jitter retry loop. Sol still ACCEPTS the zerg_auth
subprotocol (the server-side arm was not removed; see
docs/auth-flow.md §WS auth), so an external client can still present a
bearer that way — the accepted order is ticket → cookie → zerg_auth
→ ?token=.
Token re-validation every 5 minutes is the second layer for bearer
sockets; a one-time-ticket socket is capped at its 5-minute absolute
lifetime and re-handshakes with a fresh ticket (the ticket is spent at
open and cannot re-resolve a grant). The connection is refused at connect
time when the token is invalid (sol_ws_chat).
Streaming (non-WS paths) uses SSE (api_stream_post); the render
path throttles markdown updates (~150× measured improvement,
).
Sync-events stream: the
console’s /api/v1/sync-events connection is cookie-only by browser
construction (EventSource cannot send an Authorization header). The
supported posture is therefore SAME-HOST: the console and Sol share the
host that holds the zerg_session cookie. In a split-host deployment the
browser treats the stream as a third-party request; a blocked cookie lands
ONE typed capability error (the cross-origin preflight) instead of a
redial loop. The stream is additionally gated on the server’s
audit:stream grant (the /events route itself needs audit:read);
without it the view still polls REST and says why. The server documents
NO Last-Event-ID replay: a reconnect is a fresh mixed
stream, so the client reconciles each viewed aggregate from its highest
CONTIGUOUS seq, treats the server last_seq as the completion bound (a
sparse page can never silently skip a hole; a bounded walk that cannot
reach the bound raises the visible reconcile required state), and a
reconnect with no cursor at all raises that state explicitly.
CSRF dialects: Sol cookie-authenticated
mutations (the WS-ticket mint) send the zerg_csrf header equal to the
readable zerg_csrf cookie — that is the ONE name in Sol’s CORS
allow-headers list (sol_auth_middleware:csrf_pair_valid/1). The Mango
logout beacon is a MANGO request and keeps Mango’s X-CSRF-Token
double-submit (stores/auth.ts + mango-client.ts); it is not a Sol
mutation. The cookie-only WS preflight targets the real authenticated
route GET /api/v1/chat.
Turn dedupe: a reconnect can’t double-fire a message — turns are
deduplicated by content identity.
Delivery verdicts: a dispatched message is accepted by the
server ack, the first token, or the completed turn. A disconnect or a
history settlement with no ack/token/echo marks the optimistic row
failed with Retry — it never keeps looking sent.
History recovery: reconnect merges the newest server window
and, when the local transcript ends before it, walks bounded REST pages
to bridge the hole; a hole the walk cannot close is stated in-view
(historyGap) instead of being silently left.
Settings & admin surface
SettingsView exposes connection endpoints and, when the
Enterprise tier is licensed (branding store), custom branding.
Changing either endpoint requires the settings:write grant; the login
screen names the active Mango origin before credentials are typed. An
endpoint must be an origin root over https (or an explicit loopback/
private-network air-gap address) — userinfo, paths, queries and hashes
are refused.
ManagedSettingsView is the admin surface for server-enforced
settings — changes persist server-side.
SeatsView shows the live license posture (Community/Pro/Business/
Enterprise) and the admin-facing seat gate; /infra additionally
requires the clustering allowance from the seat store ( tier
gate — a missing license server degrades to pass).
Restricted browsers & air-gap fallbacks
Clipboard (chat copy): navigator.clipboard exists on secure
contexts only. On a plain-http air-gap deployment the message Copy
button falls back to a hidden-textarea document.execCommand('copy')
write — it reports “Copied” only when a copy actually
happened, and a missing clipboard API never trips the error boundary.
Browser storage: every localStorage/sessionStorage access goes
through the shared guarded helper (limon/src/utils/storage.ts,
). With storage disabled (blocked cookies, hardened privacy
mode, air-gapped profiles) the console keeps working from in-memory
state; saved API URLs survive only for the tab.
Session teardown: logout/expiry clears every identity-scoped
store (chat, seat, teams, skills, schedules, channels, managed
settings) so no previous-identity rows survive a session switch, and
an expired-token revoke no longer raises the misleading “token may
not have been revoked” warning.
Where the data comes from
Every view reads Sol REST endpoints through limon/src/api/ (sol.ts et
al.); polling uses the shared usePolling composable (visibility-pause +
401-stop uniform, ). There is no view-local polling
reimplementation — new views should use the same composables.
See also
docs/api-reference.md — the REST surface the views consume
docs/sessions.md — session model behind ChatView
docs/seats.md — tier gates behind SeatsView/SystemView (/infra alias)
docs/permissions.md — the RBAC the admin gates mirror
Engine reference — generated from the canonical engineering source. Do not edit this page by hand.
Local Inference Lanes
Status: LIVE. This catalog is rendered from the lane/engine registry (
server/config/sys.config,sys.prod.config,sys.test.config), the engine manifests underengines/, and the benchmark artifactlocal-inference-benchmark.csv(docs/local-inference-benchmark.csv) (gated byci/lane_benchmark_claims_lint.py). Numbers marked expected are registry expectations, not measurements; every measured number below is a claim token backed by an artifact row. Ghost provenance for every pin is frozen inplan/fixtures/ghost-p7-standard-b0454f2.md(ghost P7 tagp7-strata-b11639-2026-10-18); the supersedede7032b9export remains the b11011-era provenance record.
Purpose
Which model serves which use case, on which engine class, with which
capabilities, and what is actually validated. Sol owns every local lane
(llama.cpp via erlexec); Luna consumes a Sol-issued lane grant — a worker
never defines or probes a lane endpoint. See
local-inference-runbook.md for operations.
The use_case facet
use_case is one atom per lane — the one-per-lane rule mandated by the
engine interface (sol_lane_registry USE_CASES; a list or an unknown atom
is a boot refusal). The enum is fim, agentic, fast_bulk, docs_long,
vision, strict_json, story, cpu_cron, escalate. The facet is a
routing/selection hint, not a capability replacement: caps still carries
the boolean capability facts. The GSQ-RCO Coder’s primary facet is
agentic; the engine interface’s enum has no separate coding atom this
release, so coding stays a capability + role fact. The sanitized inventory
(GET /api/v1/inference/lanes) joins the facet from the registry onto each
row as a single use_case string; a row whose lane has no facet is
returned unchanged (absence tolerance for older peer configs).
Lane catalog
modes = lifecycle modes the lane accepts (on_demand lanes idle-release
after 15 min by default; attended follows the same lane idle policy and
extends on traffic unless an explicit TTL/duration is supplied;
cron/duration are scheduled/fixed shapes). Caps: tools = tool calls, json = strict JSON
requires the parser engine (upstream PR #28682 — see the engine matrix),
vision = image input, mtp = in-file/external multi-token prediction.
| Lane | use_case | Role | Model pin (repo / file) | Engine | Config | Caps | Modes | Measured evidence |
|---|---|---|---|---|---|---|---|---|
qwen38_atx | agentic | General default + vision + strict JSON (primary); FIM fallback | jakeatx/Qwen3.8-27B-ATX-IQ4_XS-M-GGUF / Qwen3.8-27B-ATX-4-XS.gguf (sha256 5cf05ad9…8d963b, apache-2.0) | cuda_sm86_main | ctx 229376 text / 163840 vision, KV q4_0, full offload, MTP d3 in-file, temp 1.0 | tools, json, vision, mtp, fim | on_demand, attended, duration | qwen38_atx eval_tps=93.2, qwen38_atx needle_decode_tps=64.4, qwen38_atx vram_mib=23849; FIM 18/40 accept@1 (0.45), 44.9 decode t/s — FIM round (benchmarks/fim-round-2026-10-18.md) |
qwen38_ud_iq3s | docs_long | Full-context fallback + automatic failover target | unsloth/Qwen3.8-27B-GGUF / Qwen3.8-27B-UD-IQ3_S.gguf (+ mmproj-F16.gguf, external drafter) | cuda_sm86_main | ctx 262144 vision, KV q4_0, full offload, MTP d2 external | tools, vision, mtp | on_demand, attended, duration | expected — no imported row; validation pending |
ling_tiny | fast_bulk | High-volume text / multi-agent (small MoE) | inclusionAI/Ling-3.0-tiny-GGUF / Ling-3.0-tiny-Q4_K_M.gguf (MIT) | cuda_sm86_main | ctx 131072, up to 5 slots, MTP off | tools | on_demand, cron, attended, duration | ling_tiny eval_tps=231.3, ling_tiny vram_mib=9397 |
ling_flash | docs_long | Capacity / long documents (expert offload) | bloomer010/Ling-3.0-flash-GGUF / Ling-3.0-flash-IQ3_XXS.gguf (MIT) | cuda_sm86_main | ctx 262144, -ncmoe 28, 2 slots | tools | on_demand, attended, duration | ling_flash eval_tps=41.1, ling_flash vram_mib=21401 |
ling_reap288 | docs_long | Pruned capacity (better tokens/VRAM than flash) | bloomer010/Ling-3.0-flash-REAP288-73B-A5B-GGUF / Ling-3.0-flash-REAP288-71B-A5B-Q3_K_M.gguf (MIT) | cuda_sm86_main | ctx 262144, 2 slots | tools | on_demand, attended, duration | ling_reap288 eval_tps=44.8, ling_reap288 vram_mib=18361 |
qwen38_flashnext | docs_long | Headroom capacity / long context (full production lane) | unsloth/Qwen3.8-Flash-Next-GGUF / Qwen3.8-Flash-Next-UD-IQ3_XXS-00001-of-00003.gguf (license unknown — license_ack recorded) | cuda_sm86_main | ctx 131072 (green host override), 2 slots | tools | on_demand, attended | expected — vram_mib 23347 unbacked; validation pending |
glm47_story | story | Creative / story (opt-in, uncensored) | DavidAU/GLM-4.7-Flash-Uncensored-Heretic-NEO-CODE-Imatrix-MAX-GGUF / GLM-4.7-Flash-Uncen-Hrt-NEO-CODE-MAX-imat-D_AU-IQ3_M.gguf (MIT) | cuda_sm86_main | ctx 131072, KV q8_0, MTP d5 | tools, mtp | on_demand, attended | expected — no imported row; validation pending |
glm47_fim | fim | Primary FIM / inline completion (same pin, 16k FIM context) | same GLM pin / GLM-4.7-Flash-Uncen-Hrt-NEO-CODE-MAX-imat-D_AU-IQ3_M.gguf (MIT) | cuda_sm86_main (b11639) | ctx 16384, KV q4_0, no MTP, one slot, native /infill | fim | on_demand, attended | FIM round (benchmarks/fim-round-2026-10-18.md): 26/40 accept@1 (0.65), 120.8 decode t/s, 2525 prefill t/s, 96-token 0.80 s warm-cache @1k, 14.1 GB |
huihui35b_story_vlm | story | Creative + vision (opt-in) | huihui-ai/Huihui-Qwen3.6-35B-A3B-Claude-4.7-Opus-abliterated-MTP-GGUF / …-Q3_K.gguf + mmproj-model-f16.gguf (apache-2.0) | cuda_sm86_main | ctx 65536, single slot | tools, vision, mtp | on_demand, attended | expected — no imported row; validation pending |
ling_tiny_cpu | cpu_cron | Scheduled / CPU-only (always-available fallback) | bloomer010/Ling-3.0-tiny-GGUF / Ling-3.0-tiny-Q4_0.gguf (MIT) | cpu_zen1 | ctx 131072, 16 threads, single session | tools | on_demand, cron, attended | expected — no imported row; validation pending |
api_tier | escalate | Deep reasoning (hosted models) | remote plane — no local weights, engine or pin | — | external gateway; local weights retired 2026-08-31 | tools, json | on_demand, attended | external service |
llama_agentic_staged | strict_json | Strict-JSON validation only — never a serving lane | inclusionAI/Ling-3.0-tiny-GGUF / Ling-3.0-tiny-Q4_K_M.gguf | llama_agentic_staged (#28682 + #28724 staged build) | ctx 131072; production => false | tools, json | on_demand | strict-JSON 0/2 → 2/2 with the staged parser (historical, pre-ZERG run) |
qwen38_gsq_coder | agentic | Staged multi-engine Coder — Strata primary, validation-only until | ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-Coder-GGUF@5348543e… / Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M-00001-of-00002.gguf (+ shard 2, + mmproj-Qwen3.8-Flash-Next-BF16.gguf; apache-2.0) | strata_sm86 (0.1.44.1) | ctx 262144, KV int8, 2 Sol slots (the engine template carries batch4), standardized 256k/MTP; production => false | coding, agentic, vision, json, tools | on_demand, attended, duration | qwen38_gsq_coder eval_tps=113.8, qwen38_gsq_coder vram_mib=23887, 518k needle PASS on red — ghost evidence only; zerg validation pending |
qwen38_gsq_coder_llama | agentic | Staged llama.cpp b11639 fallback for the same pin (--moe-cache-mib 4096, fit-target 256); production => false | same GSQ-RCO shards + mmproj | cuda_sm86_main (b11639) | ctx 262144, KV q4_0, --fit on --fit-target 256, 2 slots | coding, agentic, vision, json, tools | on_demand, attended, duration | qwen38_gsq_coder_llama eval_tps=45.7 (128k), qwen38_gsq_coder_llama eval_tps=48.9 (256k), qwen38_gsq_coder_llama needle_decode_tps=28.8, qwen38_gsq_coder_llama vram_mib=23545 — ghost evidence only; zerg validation pending; FIM 16/40 accept@1 (0.40), not a FIM candidate |
The fixture lanes fixture_sse (use_case => agentic) and fixture_fim
(use_case => fim, caps.fim => true, the POST /v1/completions e2e
vehicle) share the fixture_openai engine and exist only in the test
configuration; they never serve production traffic and never enter the
artifact.
Catalog cross-check
Every serving lane above is mirrored as a wire: local row in
contract/model_catalog.yaml (contract/model_catalog.yaml) —
serving: {register: local, lane: <lane>, engine: <engine>} with the
registry filename slug as an alias (for example qwen38_atx ↔
qwen3.8-27b-atx-4-xs). ci/model_catalog_lint.py cross-checks the catalog
against the adapter/declarative/Luna surfaces; the lane lifecycle and
validation remain owned by sol_lane_registry / sol_lane_orchestrator, not
by the catalog. A Sol request naming a lane id or its filename slug still
resolves to the local lane; an unknown non-lane model is typed-refused and
answers 404 (see catalog.md). The two new GSQ-RCO lanes are
registry/inventory rows only — they are not serving-catalog rows until the
Validation lands.
Unbacked registry expectations are visible on purpose: ling_flash
(vram_mib=18534), ling_reap288 (vram_mib=18534) and
qwen38_flashnext (vram_mib=23347) have no matching artifact row yet.
They stay on the residual list until a ZERG run lands.
Engine matrix
| Engine | Class | Ref | Build | Flags / requirements | Certification |
|---|---|---|---|---|---|
cuda_sm86_main | CUDA (GPU worker) | ggml-org/llama.cpp@a0e6dc7384edb8f5d927155e1d26c10b4a310e6d | b11639 | flash-attention on, GGML_CUDA_FA_ALL_QUANTS=ON | production engine; per-lane validation gates placement |
cpu_zen1 | CPU — Zen 1 safe (blue coordinator) | same source as above | b11639 | AVX2/FMA/F16C, -march=znver1, no AVX512; min_microarch=x86-64-v3 | production engine; the installer refuses a wrong-target artifact (host_class=zen1-avx2); CPU lane validated by the needle gate |
cpu_epyc | CPU — znver4/AVX512 (Zen 4 CPU hosts only) | same source as above | b11639 | -march=znver4, AVX512; min_microarch=x86-64-v4 | production target — never install on blue (Zen 1); host_class=epyc-znver4; validated by the needle gate |
strata_sm86 | Strata specialist (GPU) | Niko1221/Strata@296b59d2f73c8f04a805df29c2fa97655adace78 | 0.1.44.1 | Flash-Next specialist (MIT, built on llama.cpp/ggml parts); 256k/batch4/MTP standard | production => false — validation-only until the run, never a default |
llama_agentic_staged | experimental (GPU) | llama.cpp aa39d7a3e #pr28682+pr28724 | staged at /usr/src/llama-agentic | strict-JSON parser PRs | production => false — validation only; never serves |
fork_turboquant | experimental (GPU) | JakeATX/llamAmpere@b63729488 | — | llama.cpp fork experiments | not adopted (no-fork posture); needle-gated experiments only |
The strict-JSON capability (json above) requires the parser fix upstream
PR #28682; on the stock b11639 engine the registry records that
requirement per lane and the router refuses a strict-JSON request on a lane
whose engine cannot honor it. Never claim strict-JSON from stock evidence.
Multi-engine note (GSQ-RCO Coder)
The GSQ-RCO Coder pin is deliberately served by two engines, benchmarked side by side on the same 3090 + weights:
Strata 0.1.44.1 — the standardized 256k/batch4/MTP engine config on both
hosts (the Sol lane declares slots_max 2 under the registry big-lane
cap); ghost measured 2.2-2.9x decode and 5x+ prefill versus the llama.cpp
lane (113.8 LuaJIT on red; 518k needle PASS @71 t/s depth). The 512k mode
is a red-only experimental escape.
Llama.cpp b11639 — the no-fork/general-engine path with
--moe-cache-mib 4096 and fit-target 256 (45.7 tok/s @128k, 48.9 @256k;
needle PASS). The recipe is recorded in the lane notes; the current
schema exposes fit/load_mode but not fit_target/moe_cache_mib
so the staged row does not yet
render those two flags.
Both registry rows are production=false and staged.
The two open ghost gates — the mmproj formal caption A/B and the
Code/agentic tool-call JSON spot-check versus the full model — plus the
ZERG-side needle/parity run must close before any default flip.
No default changed in.
FIM/completion survey
The completion plane has a separate capability survey:
../benchmarks/fim-survey.md (benchmarks/fim-survey.md) records the
candidate × engine FIM matrix and the measured token/parity probes; the
requirements are in
../plan/completion-lane-requirements.md.
Measured 2026-10-18 on b11639 (red 3090): glm47_fim is the primary
(GLM-4.7-Flash Uncensored NEO-CODE MAX IQ3_M, native GLM
<|code_prefix|>/<|code_suffix|>/<|code_middle|>): 26/40 accept@1 (0.65),
120.8 decode t/s, 2525 prefill t/s, 96-token 0.80 s warm-cache at 1k.
qwen38_atx is the fallback (18/40, 44.9 t/s, 15.5 GB).
ling_tiny was rejected for FIM: 0/40 in both --override-kv
mappings; the tokens exist but the GGUF has no FIM template and the model
card claims no FIM training. GSQ-RCO measured 16/40 but stays the staged
coding/agentic lane (24 GB resident, 576 prefill t/s). Strata still has
no /infill and its chat path defuses FIM control tokens. Full method,
grid, cache and caveats: ../benchmarks/fim-round-2026-10-18.md (benchmarks/fim-round-2026-10-18.md).
Landed in: Sol serves POST /v1/completions
(OpenAI legacy text-completion shape, non-streaming) and routes it to a
lane that declares caps.fim => true through its internal /infill. The
endpoint requests the attended mode so an active editor session keeps the
lane resident (a cold lane answers the typed lane_warming + Retry-After).
glm47_fim is the declared FIM primary (production => false until a
zerg validation record exists — see the cold-start section); qwen38_atx is
the fallback and is a production lane, so its own validation verdict
must permit serving before fallback selection. On a clean tree with no
records neither lane serves: /v1/completions answers the typed
503 lane_unvalidated instead of bypassing the gate. The
test config adds fixture_fim (a fixture_openai lane with the mock
/infill) for the e2e; /infill is never client-facing. The lane
validation probe carries a fim section with template-parity/quality/
latency fields; the zerg-side measured values are above; the ghost P7
cross-repo rows remain the external gate.
FIM cold start and validation
glm47_fim is the declared primary but ships production => false until a
zerg-side validation record exists (a clean tree has no record, so a
production flag would answer 503 lane_unvalidated/no_record). The measured
round row (origin=zerg) is in
local-inference-benchmark.csv (docs/local-inference-benchmark.csv); the
validation record still needs the lane’s exact-recall needle row.
Cold start the lane (admin token), then exercise the real endpoint:
curl -s -X POST http://127.0.0.1:21434/api/v1/start \
-H "Authorization: Bearer $SOL_TOKEN" -H 'content-type: application/json' \
-d '{"lane":"glm47_fim","model":"glm-4.7-flash","mode":"attended"}'
curl -s -X POST http://127.0.0.1:21434/v1/completions \
-H "Authorization: Bearer $SOL_TOKEN" -H 'content-type: application/json' \
-d '{"prompt":"def add(a, b):","suffix":"\n pass\n","max_tokens":32}'
Probe, append the returned row_ref row to the configured
lane_benchmark_csv, then commit:
curl -s -X POST http://127.0.0.1:21434/api/v1/inference/lanes/glm47_fim/validate \
-H "Authorization: Bearer $SOL_TOKEN" -H 'content-type: application/json' \
-d '{"mode":"probe"}'
# append the probe row to /opt/sol/data/local-inference-benchmark.csv
curl -s -X POST http://127.0.0.1:21434/api/v1/inference/lanes/glm47_fim/validate \
-H "Authorization: Bearer $SOL_TOKEN" -H 'content-type: application/json' \
-d '{"mode":"commit"}'
Only after the commit should the lane be flipped to production => true.
/v1/completions also pins the declared fallback (qwen38_atx) when the
primary lane’s derived verdict is engine_unvalidated and the fallback’s
verdict permits serving; the typed inference_lane_fallback event records
the reason and sol_inference_lane_fallback_total{reason} counts the
selection. A fallback that is itself unvalidated is never substituted.
Host roles
The registry binds node labels to two classes (node_classes); placement
enforces the class facts (lane_host_policy):
CPU coordinator (single session). Large-memory headless box, no GPU.
Serves the CPU lane and the remote API tier; one inference session at a
time; no GPU lanes.
GPU worker (24 GB). Continuous-batching GPU box with 5 session slots;
serves all GPU lanes. A lower-RAM variant caps qwen38_flashnext at
131072 ctx (the 256k mode needs ~42 GB host RAM and is deferred until the
parity row lands).
Exclusions: big lanes are single- or two-slot by design
(slots_max), and a lane is only placement-eligible when its (lane,
engine, host) combination has a fresh validation record.
Admission control is per-node. The per-model
concurrent-pipeline admission (max_active_requests, counted inside each
model’s gen_statem) is node-local — and semantically right: a lane+model
instance lives on exactly ONE node (its lease is held there), so per-node
admission IS per-instance admission. The only visible multiplier: the
same MODEL prepared on two nodes doubles the model-level budget, because
they are two independent llama servers. This is recorded, not accidental;
a cluster-global admission budget is out of scope until lanes share
instances.
Validation status
Validation is derived at read time from a record that is compared against
the live engine ref/build, the installed engine manifest hash (receipt —
production lanes refuse no_receipt/unverified_manifest without a
ZERG install receipt), the model pin (file + sha256 + receipt byte
size), the 30-day TTL, and the parity verdict — any mismatch makes the
lane unvalidated and placement refuses with
{engine_unvalidated, Lane, Reason}.
Certification is granted from ZERG-produced evidence only:
the commit route requires origin=zerg, membership of the claimed
row_ref in the configured artifact CSV, an engine install receipt with
a real manifest hash, and a parity verdict (pass, or single_host
only with the explicit allow_single_host ack). See
engine-provenance.md for the supply-chain
contract and the runbook §6 for the typed refusals.
At this release the artifact carries 24 rows — 23 origin=ghost and
one origin=zerg (measured on the source sibling fleet and imported with
per-row provenance): the original b11011-era lanes, the P7 b11639 /
Strata/GSQ-RCO rows for qwen38_gsq_coder and
qwen38_gsq_coder_llama, and the zerg FIM evidence row for glm47_fim.
The zerg row is a quality/latency measurement, not a needle/parity
validation record, so no lane is advertised as ZERG-validated yet; every
production placement still requires an operator validation run first.
qwen38_atx is a production lane (production => true) and therefore
also refuses on a clean tree until that run lands. The two GSQ-RCO lanes
are production=false and remain staged validation-only rows until
records the ZERG needle + parity rows (the ghost rows are hypothesis
provenance, never a substitute). Run scripts/lane-certify.sh --plan to
see the lane × engine × host matrix, then the real run through
POST /api/v1/inference/lanes/:lane/validate (needle gate + parity +
record commit) before serving. The full matrix is summarized in
local-inference-benchmark.md.
Revision 2 scope (recorded, not silent)
Embeddings, reranking and LoRA serving are out of scope for this
revision. The extension points are reserved: lane kind (a future
non-generative kind), registry schema (new pin/engine fields), and the
provider surface (Sol-issued grants already carry wire_format + caps).
See the runbook’s “Requesting a lane” section for the operator-facing story.
See also
local-inference-runbook.md — start/stop,
validate, failover, engine install/rollback, weight provisioning.
local-inference-benchmark.md — the
machine ledger, parity bands, invalidation semantics.
API Overview
Canonical reference: docs/api-reference.md (generated endpoint directory) — this page is a task-oriented summary.
ZERG (Sol) exposes 202 spec rows (180 route tuples, including
6 catch-all routers) via a Cowboy HTTP server. All endpoints
accept and return JSON (Content-Type: application/json) unless documented
otherwise (SSE streams, WebSocket, Prometheus text).
Base URL
http://localhost:21434 # dev (zerg-sol container / local node)
https://sol.example.com # production — the operator's edge host
# (WILDZERG fronts Sol with its own reverse proxy)
All paths below are absolute paths on the host. Most application endpoints live
under /api/v1/...; the OpenAI- and Anthropic-compatible inference endpoints
live directly under /v1/... (see OpenAI-compatible).
curl http://localhost:21434/health
Authentication
When mango_auth_enabled is true, most endpoints require authentication.
Three delivery mechanisms are honoured, in priority order:
| Mechanism | Header / value | Notes |
|---|---|---|
| Bearer token (preferred) | Authorization: Bearer <token> | Highest priority; always wins when present. |
| Session cookie | Cookie: zerg_session=<token> | Set on login; used by browser UIs and the WebSocket chat endpoint. |
?token=<token> query | URL query string | Deprecated. Still accepted for SSE/WebSocket clients that cannot set headers, but logs a warning. Prefer the cookie or header. |
Tokens are issued by Authentication (POST /api/v1/auth/login) and
validated through Mango. RBAC permissions are resource:action strings; admin is
the literal permission "*".
Three distinct exemption/gating mechanisms apply at the middleware and handler layers — do not conflate them:
- Auth-exempt paths (
DEFAULT_EXEMPT_PATHS, no token required):/health,/api/v1/health,/api/v1/ready,/api/v1/infra/status,/api/v1/infra/maintenance,/api/v1/shares,/auth/login,/auth/validate,/auth/logout,/api/v1/auth/{login,validate,logout}, and the/api/v1/webhook/prefix (webhook signature IS the auth)./metricsis NOT auth-exempt: tokenless scrapes pass only when the peer is on the loopback topology (or the peer-scopedmetrics_gate_peerallowance); otherwise the middleware answers 403insufficient_permissions. Token-bearing scrapes need themetrics:readRBAC grant. - Maintenance-exempt paths (still require auth; reachable while
maintenance mode 503s everything else):
/health,/api/v1/health,/api/v1/ready,/metrics(subject to the peer/RBAC gate above), the/api/v1/infraprefix,/openapi.json, and/api-docs— note/openapi.jsonand/api-docsare maintenance-exempt only, NOT auth-exempt. /debug/pprof/*is NOT auth-exempt: it is admin-scoped at the middleware (403for non-admins) AND gated by theenable_pprofconfig (defaultfalse→404even for admins until opted in). The OpenResty LAN rule is defense-in-depth for credential-less scrapers, not the authorization.
OpenAI- & Anthropic-compatible
These live at the /v1/ prefix (no /api/) so they can be dropped into
existing OpenAI/Anthropic SDKs and gateway tools:
| Method | Path | Handler action |
|---|---|---|
| POST | /v1/chat/completions | completions |
| POST | /v1/completions | text_completions (FIM; suffix supported) |
| GET | /v1/models | openai_models |
| POST | /v1/messages | messages |
| GET | /v1/messages/:message_id | message_get |
Pagination Envelope
List endpoints paginate via sol_http_pagination. Input is read from the query
string — either ?page=N&per_page=M (1-indexed page) or ?limit=N&offset=M.
limit/per_page are clamped to a maximum of 500.
The response envelope is consistent across all paginated collections:
{
"items": [ ... ],
"total": 137,
"limit": 50,
"offset": 0,
"page": 1,
"total_pages": 3,
"has_more": true
}
Single resources are returned as bare maps (no envelope). Errors speak the
dialect of the API family — drop-in openai/anthropic SDK
clients parse error.message correctly:
| Family | Routes | Error body |
|---|---|---|
| OpenAI | /v1/chat/completions, /v1/models | {"error":{"message":"...","type":"invalid_request_error","param":null,"code":null}} |
| Anthropic | /v1/messages* | {"type":"error","error":{"type":"...","message":"..."}} |
| Zerg | /api/v1/* | {"ok":false,"error":{"code":"...","message":"..."}} (legacy plain {"error":"..."} persists on some handler-level paths) |
Middleware 401 and 403 are family-aware (the route family’s error dialect):
401 carries code unauthorized; auth-rate-limit saturation is a
Fail-closed 503 + Retry-After (rate_limiter_unavailable), never a
401; 403 carries code insufficient_permissions. Capacity is never 500:
429 + Retry-After for seats/quotas, 503 for license/circuit outages,
413 for oversized bodies.
Interactive Docs
Swagger UI: /api-docs
OpenAPI 3.1 spec: /openapi.json
Prometheus metrics: /metrics (text exposition format; peer-gated —
tokenless only on the loopback topology, otherwise metrics:read)
Endpoint Categories
Counts below are the generated tag families in the spec (202 rows total;
the generated directory in docs/api-reference.md is the authoritative
list; ci/gen_api_reference.py --check derives both the total and the
per-family counts).
| Family (generated tag) | Count | Description |
|---|---|---|
| ACP Agents | 5 | Agent Capability Protocol discovery/dispatch |
| Audit | 6 | Audit read surface + anchored chain verify |
| Auth | 10 | Login / validate / revoke / password / service tokens / admin erasure |
| Channels | 8 | Delivery channels + inbound webhook |
| Chat | 16 | Interactive chat (HTTP + SSE + WebSocket) |
| Cluster | 6 | Cluster membership + circuit breakers + catalog |
| Completions | 3 | OpenAI chat + FIM + Anthropic Messages |
| Conversations | 6 | Conversation sessions and streams |
| Events | 2 | Event query + SSE stream |
| Goals | 6 | Goal tracking |
| Health | 8 | Liveness + deep readiness |
| Inference | 13 | Model registry, lifecycle, prepare |
| Infra | 9 | Maintenance, cache invalidation, status, cache affinity |
| Marketplace | 13 | Browse / publish / rate / report skills |
| Memory | 13 | Vector + scalar memory store |
| Persistence | 3 | Event-store flush + stats |
| Plugins | 3 | Luerl plugin eval + workers |
| Providers | 1 | Provider health + declarative reload |
| Recipes | 4 | Declarative workflow templates |
| Replay | 1 | Session event replay |
| Scheduler | 7 | Cron / every / at jobs |
| Seats | 1 | Seat/license surface |
| Sessions | 4 | Session shares |
| Skills | 2 | Local skill registry |
| Supervisor | 2 | OTP supervisor tree introspection |
| Teams | 11 | Team + role + mailbox management |
| Telemetry | 3 | Per-agent telemetry |
| Webhooks | 1 | Inbound webhook receiver |
| Workers | 16 | ZMQ dispatch, tasks, orchestration, local/bg workers |
| Workflows | 11 | Multi-step agent workflows |
| Workspace | 5 | File operations |
| ZMQ | 3 | Worker/fleet status |
Endpoint Index (grouped)
Health & Readiness
GET /health — liveness (always 200)
GET /api/v1/health — shallow health ({status, models_running})
GET /api/v1/ready — deep readiness (19 subsystem checks)
Infra
GET /api/v1/infra/status
GET /api/v1/infra/maintenance
POST /api/v1/infra/maintenance/enable
POST /api/v1/infra/maintenance/disable
POST /api/v1/infra/cache-invalidate
GET /api/v1/infra/cache-affinity
DELETE /api/v1/infra/cache-affinity
Inference (models)
GET /api/v1/models
GET /api/v1/models/metadata
GET /api/v1/models/:name
GET /api/v1/ps
GET /api/v1/metrics
POST /api/v1/discover
POST /api/v1/start
POST /api/v1/stop
POST /api/v1/stop-all
POST /api/v1/prepare/:name (POST-only; GET answers 405)
OpenAI- & Anthropic-compatible
POST /v1/chat/completions
POST /v1/completions (FIM; suffix supported)
GET /v1/models
POST /v1/messages
GET /v1/messages/:message_id
Workers — ZMQ
GET /api/v1/zmq/workers
POST /api/v1/zmq/dispatch
GET /api/v1/zmq/status
GET /api/v1/tasks
GET /api/v1/tasks/:task_id
DELETE /api/v1/tasks/:task_id
POST /api/v1/orchestrate
GET /api/v1/orchestrate/:id
Workers — local JSONL agents
GET /api/v1/agents
POST /api/v1/agents/spawn
GET /api/v1/agents/:id
POST /api/v1/agents/:id/task
POST /api/v1/agents/:id/kill
Workers — background
POST /api/v1/workers/bg/start
GET /api/v1/workers/bg
GET /api/v1/workers/bg/:bg_id
GET /api/v1/workers/bg/:bg_id/status
GET /api/v1/workers/bg/:bg_id/logs
POST /api/v1/workers/bg/:bg_id/kill
Scheduler (singular /schedule)
GET /api/v1/schedule
POST /api/v1/schedule/spawn
GET /api/v1/schedule/:id
DELETE /api/v1/schedule/:id
POST /api/v1/schedule/:id/pause
POST /api/v1/schedule/:id/unpause
POST /api/v1/schedule/:id/run
Channels
GET /api/v1/channels
POST /api/v1/channels/spawn
GET /api/v1/channels/:id
DELETE /api/v1/channels/:id
POST /api/v1/channels/:id/test
POST /api/v1/channels/:id/message
POST /api/v1/channels/:id/pause
POST /api/v1/channels/:id/resume
POST /api/v1/webhook/:channel_id (inbound webhook receiver)
Workflows
GET /api/v1/workflows
POST /api/v1/workflows/start
GET /api/v1/workflows/:id
POST /api/v1/workflows/:id/cancel
POST /api/v1/workflows/:id/branch
GET /api/v1/workflows/:id/tree
GET /api/v1/workflows/:id/lineage
POST /api/v1/workflows/:id/pause
POST /api/v1/workflows/:id/resume
GET /api/v1/workflows/:id/stream (SSE)
Recipes
GET /api/v1/recipes
POST /api/v1/recipes/reload
GET /api/v1/recipes/:name
POST /api/v1/recipes/:name/run
Memory
POST /api/v1/memory/store
GET /api/v1/memory/stats
GET /api/v1/memory/:agent_id
GET /api/v1/memory/:agent_id/search
POST /api/v1/memory/:agent_id/clear
GET /api/v1/memory/:agent_id/:key
POST /api/v1/memory/:agent_id/:key/delete
POST /api/v1/memory/:agent_id/vector-search
POST /api/v1/memory/:agent_id/decay
GET /api/v1/memory/:agent_id/reflections
POST /api/v1/memory/:agent_id/:key/pin
Conversations
GET /api/v1/conversations
GET /api/v1/conversations/:conv_id
POST /api/v1/conversations/:conv_id/delete
GET /api/v1/conversations/:conv_id/usage
GET /api/v1/conversations/:conv_id/stream
Chat
POST /api/v1/chat
GET /api/v1/chat/:id
DELETE /api/v1/chat/:id
POST /api/v1/chat/:id/message
GET /api/v1/chat/:id/stream (SSE)
GET /api/v1/chat/:id/history
GET /api/v1/chat/:session_id/ws (WebSocket)
ACP (Agent Capability Protocol)
GET /api/v1/acp/agents
GET /api/v1/acp/agents/discover
GET /api/v1/acp/agents/capabilities
GET /api/v1/acp/agents/:agent_id
POST /api/v1/acp/agents/:agent_id/message
Skills & Marketplace
GET /api/v1/skills
GET /api/v1/skills/:name
GET /api/v1/marketplace
GET /api/v1/marketplace/search
POST /api/v1/marketplace/feature
POST /api/v1/marketplace/rate
GET /api/v1/marketplace/ratings
GET /api/v1/marketplace/reports
POST /api/v1/marketplace/reports/:id/dismiss
GET /api/v1/marketplace/:name
GET /api/v1/marketplace/:name/:author
POST /api/v1/marketplace/:name/:author/report
Lua Plugins (Luerl)
POST /api/v1/lua/eval
GET /api/v1/lua/workers
POST /api/v1/lua/workers/spawn
Events
GET /api/v1/events
GET /api/v1/sync-events (SSE)
Audit
GET /api/v1/audit/events
GET /api/v1/audit/tool-executions
GET /api/v1/audit/permission-decisions
GET /api/v1/audit/llm-decisions
GET /api/v1/audit/summary
Auth
POST /api/v1/auth/login
GET /api/v1/auth/validate
POST /api/v1/auth/logout
Cluster & Circuit Breakers
GET /api/v1/cluster
POST /api/v1/cluster/join
POST /api/v1/cluster/leave
GET /api/v1/catalog
GET /api/v1/circuits
POST /api/v1/circuits/reset
Providers
GET /api/v1/providers/health
GET /api/v1/providers/health/:name
POST /api/v1/providers/reload
Persistence
GET /api/v1/persistence/status
POST /api/v1/persistence/flush
GET /api/v1/persistence/audit-stats
Telemetry
GET /api/v1/telemetry
POST /api/v1/telemetry/clear
GET /api/v1/telemetry/:agent_id
Supervisor
GET /api/v1/supervisor/tree
GET /api/v1/supervisor/children/:name
Teams
GET /api/v1/teams
POST /api/v1/teams
GET /api/v1/teams/:id
DELETE /api/v1/teams/:id
POST /api/v1/teams/:id/members
DELETE /api/v1/teams/:id/members/:worker_id
POST /api/v1/teams/:id/mail
Sessions & Shares
… /api/v1/sessions/... (catch-all router)
GET /api/v1/shares/:share_id
Goals / Replay / Workspace (catch-all routers)
… /api/v1/goals/...
… /api/v1/replay/...
… /api/v1/workspace/...
Managed Settings
GET /api/v1/managed-settings
Debug & Profiling
POST /debug/pprof/profile
POST /debug/pprof/heap (admin-scoped + enable_pprof opt-in — 404 while disabled; not auth-exempt; POST-only)
POST /api/v1/debug/flamegraph (admin; POST-only)
Self-documentation & Scrape
GET /openapi.json (conditional on openapi_enabled)
GET /api-docs (conditional on openapi_enabled)
GET /metrics (conditional on prometheus_enabled; peer-gated)
Conventions
Shell is POSIX for any CLI examples; curl is used throughout.
IDs in paths (:id, :task_id, :agent_id, :name) are URL path
segments, not query parameters.
/api/v1/schedule is singular (not /schedules) — see
Scheduler.
Catch-all routers (/api/v1/sessions/[...], /api/v1/infra/[...],
/api/v1/goals/[...], /api/v1/replay/[...],
/api/v1/auth/[...], /api/v1/workspace/[...]) dispatch internally on path
segments and method — see each handler for the resolved sub-routes.
Agent Control Plane (ACP)
Canonical reference: docs/api-reference.md (generated endpoint directory) — this page is a task-oriented summary.
The Agent Control Plane provides TCP-based bidirectional control over agent workers. ACP enables CLI and tooling to discover, route to, and control individual Luna workers.
Overview
ACP is a TCP listener protocol (separate from HTTP). Clients connect via TCP, send msgpack-encoded control messages, and receive responses over the same connection. The ACP router maintains a registry of connected workers and can forward commands to specific workers or broadcast to all.
Protocol
TCP Listener
tcp://host:9120
The ACP listener (sol_acp_listener, default port 9120, configured via
acp_listener_port / SOL_ACP_LISTENER_PORT) accepts TCP connections, wraps
them in sessions (sol_acp_session),
and routes messages to registered workers. Connections authenticate with a
shared-secret HMAC (the listener refuses unauthenticated frames fail-closed;
Added replay protection, superseded by the enforced global
digest cache + per-type freshness of — a captured frame
replayed over a fresh connection is refused). Frame sizes are capped
(acp_packet_size, clamped at 16 MiB); a non-loopback bind requires the
explicit acp_listener_plaintext_ack acknowledgement.
Message Format
Messages are msgpack-encoded maps keyed by an acp_type field:
{
"acp_type": "request",
"id": "req-uuid",
"from": "client",
"to": "worker-uuid",
"payload": { "action": "execute" },
"timestamp": 1745600000000,
"ttl": 30
}
Message Types
acp_type | Direction | Description |
|---|---|---|
capability | Worker → Router | Announce worker identity and capabilities |
request | Client → Router → Worker | Send a command to a specific worker (TTL 30) |
notify | Client → Router → Worker | Fire-and-forget command (no reply expected) |
broadcast | Client → Router | Send command to all registered workers (to: "*") |
discover | Client → Router | Find up to n agents matching capabilities (TTL 10) |
response | Worker → Router → Client | Worker response to a request (reply_to names the request id) |
Discovery Response
{
"acp_type": "response",
"agents": [
{
"id": "worker-uuid",
"capabilities": ["chat", "tools", "memory"],
"status": "idle"
}
]
}
Endpoints (HTTP Bridge)
List Connected Agents
GET /api/v1/acp/agents
Returns registered agents, paginated. Each entry is {id, capabilities, status, last_seen}.
{
"items": [
{"id": "worker-uuid", "capabilities": ["chat", "tools", "memory"], "status": "idle", "last_seen": 1745600000000}
],
"total": 1,
"limit": 50,
"offset": 0,
"page": 1,
"total_pages": 1,
"has_more": false
}
Discover Agents by Capability
GET /api/v1/acp/agents/discover
Find up to n agents (default 5) whose capabilities satisfy the request.
The spec pins GET; there is no method gate in the handler, so the JSON body
is read whichever verb the client uses.
{
"capabilities": ["tools", "memory"],
"n": 5
}
Response:
{
"agents": [
{"id": "worker-uuid", "capabilities": ["chat", "tools", "memory"], "status": "idle"}
]
}
400 (Zerg envelope) when the capabilities field is missing.
All Capabilities
GET /api/v1/acp/agents/capabilities
Returns the union of capabilities advertised by all registered agents.
{
"capabilities": ["chat", "tools", "memory", "streaming"]
}
Agent Detail
GET /api/v1/acp/agents/:agent_id
Returns one agent’s registry entry. 404 if the agent is not registered.
{
"id": "worker-uuid",
"capabilities": ["chat", "tools", "memory"],
"status": "idle",
"last_seen": 1745600000000
}
Send Message to Agent
POST /api/v1/acp/agents/:agent_id/message
Forwards a message to a specific agent via the ACP router. The authenticated caller’s user_uuid and permissions are injected into the payload. 404 if the agent is not registered.
{
"action": "execute",
"payload": { }
}
Response:
{
"status": "dispatched",
"id": "req-123"
}
Error Codes:
| Code | Description |
|---|---|
| 400 | Missing capabilities / invalid body (Zerg envelope) |
| 401 | Authentication required |
| 404 | Agent not found |
| 502/503 | Dispatch failure (classified via the shared error classifier) |
Examples:
# HTTP bridge
curl http://127.0.0.1:21434/api/v1/acp/agents \
-H "Authorization: Bearer $TOKEN"
curl -X POST http://127.0.0.1:21434/api/v1/acp/agents/worker-uuid/message \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"action": "execute", "payload": {}}'
The TCP listener is a raw msgpack protocol (frame = HMAC-SHA256 prefix +
msgpack body, {packet, 4} length framing) — there is no zerg acp
CLI surface; use the HTTP bridge above for ad-hoc calls.
Audit API
Canonical reference: docs/api-reference.md (generated endpoint directory) — this page is a task-oriented summary.
Query surface for the platform audit trail. Read this first: the five
audit endpoints below answer an honest empty page plus a machine-readable
notice — the Mnesia sync-event store has no audit.* writer. The real
audit trail is the append-only JSONL log written by sol_audit_log (read it
on disk, or via the Mango audit archive with its integrity chain). The
endpoints exist and are RBAC-gated; they simply refuse to fabricate results
from a store that never held audit events.
Overview
Every privileged action (memory mutations, schedule changes, marketplace
publishes, workspace writes, channel operations, provider actions, …) is
recorded by sol_audit_log as a JSONL row: actor uuid, binary target,
event-specific details with content hashed (*_sha256) and never stored
verbatim. The audit chain has an integrity verifier (mirroring Mango’s
implementation).
Authentication
All endpoints require Authorization: Bearer <token> with the
audit:read permission (admins pass via "*"). Audit data is not
exposed to ordinary callers.
Endpoints
All five query routes share the same honest response shape — a paginated
envelope with zero items plus the notice field:
GET /api/v1/audit/events
GET /api/v1/audit/tool-executions
GET /api/v1/audit/permission-decisions
GET /api/v1/audit/llm-decisions
Response (200):
{
"items": [],
"total": 0,
"limit": 50,
"offset": 0,
"page": 1,
"total_pages": 1,
"has_more": false,
"notice": "audit_log_file_only"
}
The historical ?type= filter and the “filtered view” semantics of the
typed endpoints are gone: there is nothing to select, so no request
parameter can drive a scan.
Anchored integrity verdict
GET /api/v1/audit/verify
Unlike the file-only query family, this route runs the real anchored
verifier over the Sol JSONL audit chain
(sol_audit_log:verify_integrity_anchored/0) and answers the verdict map.
It is admin-only (an exact {admin, require} middleware rule — the
/api/v1/audit prefix grant of audit:read does not apply).
Response (200) — every produced verdict, pass or fail:
{
"ok": true,
"anchored": true,
"anchored_to_seq": 3,
"observed_head_seq": 3,
"rows_checked": 3,
"truncated": false,
"reasons": [],
"violations": [],
"files": [{"file": "audit-20260917.jsonl", "path": "...", "result": "ok"}],
"key_source": "configured"
}
ok=false + reasons values: truncated_tail (log head below the
signed checkpoint — a full wipe is the same class with
observed_head_seq: null), checkpoint_invalid (the checkpoint file
fails its HMAC), integrity_violation (a per-file chain break),
unanchored (no checkpoint — loud, never silent-ok), secret_refused
(the HMAC secret posture refuses).
key_source: configured | ephemeral | unknown. Under an
ephemeral key the checkpoint written by a previous run reads as
checkpoint_invalid after restart — rotate in the real
SOL_AUDIT_HMAC_SECRET (see docs/production-runbook.md).
503 is reserved for a verifier that could not run at all (subsystem
absent); a produced failed verdict is always a 200 body so the
operator sees WHY.
Summary
GET /api/v1/audit/summary
{
"audit_summary": {},
"notice": "audit_log_file_only"
}
Where the Real Audit Data Lives
| Consumer | Access |
|---|---|
| Sol JSONL audit log | Append-only file managed by sol_audit_log on the Sol host |
| Mango audit archive | Mango identity service (its own audit table + /auth-surface archive), with the integrity chain and verify_integrity operator surface |
| Limon ops console | Renders audit views from the Mango archive |
Error Codes:
| Code | Description |
|---|---|
| 401 | Authentication required |
| 403 | audit:read permission required (Zerg envelope, insufficient_permissions) |
Examples:
curl http://127.0.0.1:21434/api/v1/audit/events \
-H "Authorization: Bearer $TOKEN"
curl http://127.0.0.1:21434/api/v1/audit/summary \
-H "Authorization: Bearer $TOKEN"
Authentication API
Canonical reference: docs/api-reference.md (generated endpoint directory) — this page is a task-oriented summary.
Token-based authentication with RBAC. Mango (Python/Tornado, container
zerg-mango) is the identity provider for the whole ZERG platform; Sol’s
sol_auth_middleware validates the issued token on every request.
Overview
All auth endpoints live under /api/v1/auth/.... The router is a
catch-all ({"/api/v1/auth/[...]", sol_http_auth, []}) that dispatches on
the final path segment and HTTP method. Three bare passthrough routes —
/auth/login, /auth/logout, /auth/validate — serve the same handlers
for the zerg CLI (which talks to the Sol base URL directly); there are
no other bare /auth/... endpoints.
Users authenticate with account + password (not username) and
receive a token.
The token is sent as Authorization: Bearer <token> on subsequent requests.
The zerg_session cookie carries the same token for browser / WebSocket
clients.
Refresh tokens do not exist ( removed the retired
/auth/refresh stub). Any unknown auth path — including
POST /api/v1/auth/refresh — answers 404 not_found regardless of
the verb. Clients re-authenticate with account + password.
Endpoints
Login
POST /api/v1/auth/login
Authenticate and receive a session token.
Request Body:
{
"account": "alice@example.com",
"password": "s3cret!"
}
| Field | Required | Description |
|---|---|---|
account | Yes* | Account identifier (email or username). email is accepted as a fallback alias. |
password | Yes | Account password. |
* The handler reads account first, then falls back to email. username is
Not accepted.
Response (200):
{
"token": "zerg_mg_abc123def456",
"user": {
"uuid": "user_abc123",
"email": "alice@example.com",
"permissions": ["chat:read", "chat:write", "goals:*"]
}
}
| Field | Description |
|---|---|
token | Bearer token. Send as Authorization: Bearer <token> or in the zerg_session cookie. |
user | User object returned verbatim from Mango. Exact fields depend on Mango’s user schema; uuid and permissions are always present. |
There is no refresh_token field — Mango never issues refresh tokens
and the field was dropped from the response in.
Error Responses:
| Code | Body | Condition |
|---|---|---|
| 200 | {"ok":false,"error":{"code":"auth disabled","message":"auth disabled"}} | mango_auth_enabled = false (note: HTTP 200 with an error body — auth is off, so this is not a failure). |
| 400 | {"ok":false,"error":{"code":"invalid json",...}} / {"ok":false,"error":{"code":"empty body",...}} | Malformed request body. |
| 401 | {"ok":false,"error":{"code":"<reason>",...}} | Bad credentials, Mango unreachable, or a Mango client crash (never a 500). |
Example:
curl -X POST http://localhost:21434/api/v1/auth/login \
-H "Content-Type: application/json" \
-d '{"account": "alice@example.com", "password": "s3cret!"}'
Validate Token
GET /api/v1/auth/validate
Validate the caller’s token and return its identity + permissions. Used internally by Sol and by front-end apps that need to refresh the user object.
Method is GET, not POST. The token is read from the
Authorizationheader, thezerg_sessioncookie, or the?token=query parameter.
Response (200):
{
"valid": true,
"user_uuid": "user_abc123",
"token_type": "session",
"permissions": ["chat:read", "chat:write", "goals:*"]
}
| Field | Description |
|---|---|
valid | Always true on a 200 response. |
user_uuid | The user’s UUID. |
token_type | Token type reported by Mango (defaults to "session" if absent). |
permissions | List of resource:action permission strings (defaults to []). |
Error Responses:
| Code | Body | Condition |
|---|---|---|
| 401 | {"ok":false,"error":{"code":"missing token","message":"missing token"}} | No token found in any location. |
| 401 | {"ok":false,"error":{"code":"<reason>",...}} | Mango rejected the token. |
| 401 | {"ok":false,"error":{"code":"auth service unavailable",...}} | Mango unreachable (Erlang EXIT). |
| 401 | {"ok":false,"error":{"code":"invalid token","message":"invalid token"}} | Mango returned an unexpected shape. |
Refresh Endpoints (removed)
There is no refresh endpoint. POST /api/v1/auth/refresh was a stub that
always answered 401 “refresh tokens are disabled”; it was **removed in
**. Unknown auth segments now answer 404 not_found (the Zerg
envelope) for every verb:
{ "ok": false, "error": { "code": "not_found", "message": "not_found" } }
A real refresh flow would ride an end-to-end Mango implementation (Mango
currently issues no refresh tokens); until then, re-authenticate via
/auth/login.
Logout
POST /api/v1/auth/logout
Invalidate the current token. The token is read from the Authorization header
(or cookie / query). If no token is present, the endpoint still succeeds.
Response (200):
{ "ok": true }
Returns HTTP 200 with a JSON body — not 204. The body is always
{"ok":true}regardless of whether a token was supplied.
Authentication Delivery
Tokens may be supplied in any of three locations, evaluated in this priority order:
Authorization: Bearer <token>header (preferred; always wins).zerg_sessioncookie — set by the browser on login. Required for the WebSocket chat endpoint (/api/v1/chat/:session_id/ws) where custom headers cannot be sent on the upgrade.?token=<token>query parameter — deprecated. Still accepted (primarily for SSE consumers that cannot set headers), but logs a warning.
RBAC
Permission Model
Permissions are resource:action strings (e.g. chat:read, goals:*). The
admin role is the literal permission "*" in the user’s permission list. The
infra router and several admin-gated endpoints check
lists:member(<<"*">>, Permissions) directly.
Session Cookie
On a successful login, Mango sets:
Set-Cookie: zerg_session=<token>; HttpOnly; Secure; SameSite=Strict; Path=/
The cookie is secondary to the Authorization header — the header takes
priority when both are present.
Error Codes Summary
| Code | Description |
|---|---|
| 400 | Malformed JSON body (login only) |
| 401 | Invalid credentials, expired/missing token, or auth service unavailable |
| 403 | Insufficient permissions (raised by RBAC middleware, not the auth router) |
| 404 | Unknown auth path — including the removed /auth/refresh |
| 405 | Wrong HTTP method for the path (e.g. POST to /auth/validate) |
| 429 | Rate limit exceeded (middleware) |
Channels API
Canonical reference: docs/api-reference.md (generated endpoint directory) — this page is a task-oriented summary.
Channel integrations connect ZERG to external messaging platforms: Slack, Microsoft Teams, Telegram, Discord, and generic webhooks.
Overview
Channels are gen_server-based integrations that receive messages from external platforms, relay them to a Luna agent for processing, and send responses back. Each channel type has a dedicated adapter that handles the platform-specific wire format and authentication.
Authentication
Channel management endpoints require Authorization: Bearer <token>. Webhook receivers use platform-specific signature verification.
Endpoints
List Channels
GET /api/v1/channels
Returns configured channels (paginated envelope). Each entry carries
id, type, name, status, enabled, last_message_ms, error_count
the channel config (secrets included) is never echoed back:
{
"items": [
{
"id": "ch-slack-001",
"type": "slack",
"name": "general",
"status": "active",
"enabled": true,
"last_message_ms": 1745600000000,
"error_count": 0
}
],
"total": 1,
"limit": 50,
"offset": 0,
"page": 1,
"total_pages": 1,
"has_more": false
}
Create Channel
POST /api/v1/channels/spawn
Admin only. Spawns a new channel integration. The type must match a loaded plugin.
{
"type": "slack",
"name": "support",
"config": {
"webhook_url": "https://hooks.slack.com/services/T00/B00/xxx",
"signing_secret": "abc123"
}
}
Request Body (Telegram):
{
"type": "telegram",
"name": "alerts",
"config": {
"bot_token": "123456:ABC-DEF",
"chat_ids": ["-1001234567890"]
}
}
Request Body (Teams):
{
"type": "teams",
"name": "dev-ops",
"config": {
"webhook_url": "https://outlook.office.com/webhook/...",
"tenant_id": "tenant-uuid"
}
}
Returns the new channel’s status map on success. 400 (Zerg envelope) if the plugin type is not loaded; 403 if not admin. Requires the channels:manage permission at the middleware.
Delete Channel
DELETE /api/v1/channels/:id
Admin only. Remove a channel integration. {status: "removed"}.
Webhook Receiver
POST /api/v1/webhook/:channel_id
Generic webhook receiver keyed by channel id. Accepts arbitrary JSON payloads:
{
"text": "What is the current deployment status?",
"user": "deploy-bot",
"metadata": { "source": "jenkins" }
}
The route is unauthenticated by design (auth-exempt): the platform
signature validation IS the auth, and it refuses missing/mismatched
credentials fail-closed. Success answers 200 with an empty body.
Webhook Signature Verification:
| Platform | Method | Credential |
|---|---|---|
| Slack | HMAC-SHA256 over v0:timestamp:body | X-Slack-Signature |
| Discord | Ed25519 | X-Signature-Ed25519 + X-Signature-Timestamp |
| Teams | Bearer token compare (teams_auth_token config; subscription validation echoes validationToken) | Authorization |
| Telegram | Secret-token compare (telegram_secret_token config) | X-Telegram-Bot-Api-Secret-Token |
An unconfigured secret refuses all traffic for that platform (fail-closed).
Error Codes (bodies are empty — the status is the contract):
| Code | Condition |
|---|---|
| 400 | Request body could not be read |
| 403 | Signature/credential verification failed |
| 404 | Channel not found (or disabled) |
| 413 | Payload over the 1 MB cap |
Examples:
curl http://127.0.0.1:21434/api/v1/channels \
-H "Authorization: Bearer $TOKEN"
curl -X POST http://127.0.0.1:21434/api/v1/channels/spawn \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"type": "slack", "name": "ops", "config": {"webhook_url": "https://hooks.slack.com/services/...", "signing_secret": "..."}}'
Chat API
Canonical reference: docs/api-reference.md (generated endpoint directory) — this page is a task-oriented summary.
ZERG provides two chat transports: WebSocket (bidirectional, recommended for UI) and SSE (unidirectional, for simple integrations).
WebSocket Transport
The primary chat interface. Authenticates via zerg_session cookie (set on Mango login), Authorization header, or a one-time WS ticket minted at POST /api/v1/chat/:id/ws-ticket and presented on the upgrade via the zerg_ticket, <ticket> Sec-WebSocket-Protocol subprotocol — so the long-lived bearer never rides the WS handshake (the ticket is single-use and short-TTL; Limon mints a fresh one per reconnect).
Connect
ws://host:21434/api/v1/chat/:session_id/ws
The session_id is obtained from POST /api/v1/chat.
Client → Server Messages
Send a message
{ "type": "message", "content": "Explain quicksort" }
Interrupt streaming
{ "type": "interrupt" }
Request message history
{ "type": "history" }
Heartbeat
{ "type": "ping" }
Server → Client Messages
| Type | Fields | Description |
|---|---|---|
connected | session_id | Connection confirmed |
history | messages[] | Last 50 messages (on connect/reconnect) |
token | data | Streaming token fragment |
done | usage | Generation complete with token usage |
error | error | Error message |
interrupted | — | Generation was interrupted |
pong | ts | Heartbeat response |
Example
const ws = new WebSocket(
`ws://${host}:21434/api/v1/chat/${sessionId}/ws`
)
ws.onmessage = (event) => {
const msg = JSON.parse(event.data)
switch (msg.type) {
case 'token':
appendText(msg.data)
break
case 'done':
finishGeneration(msg.usage)
break
case 'error':
showError(msg.error)
break
}
}
ws.send(JSON.stringify({
type: 'message',
content: 'Write a Fibonacci function'
}))
Auth Refresh
Auth is validated at upgrade time and re-resolved every 5 minutes
(AUTH_REFRESH_MS). The contract differs by credential form:
Bearer / session-cookie sockets re-resolve the principal on the refresh;
a transient auth-store outage keeps the socket alive, a genuine
revocation/disable closes it with 4401 unauthorized (terminal).
One-time-ticket sockets have no credential left to re-resolve (the
ticket is spent at open), so they carry an absolute 5-minute lifetime
(TICKET_ABSOLUTE_LIFETIME_MS). At the boundary the server closes with
4401 reauthenticate; Limon treats that specific code/reason as a
re-mint-and-reconnect signal, mints a fresh single-use ticket and
re-handshakes automatically. The spent ticket is never reused.
Only 4401 reauthenticate is non-terminal. Every other 4xxx close
(including 4401 unauthorized, 4403, 4404) is terminal and surfaces the
Reconnect affordance. There is no 4001 close code.
Heartbeat
The SERVER pushes pong frames every 30 seconds (HEARTBEAT_INTERVAL_MS=30000) as liveness signals; there is no miss-counting disconnect policy on the server side.
SSE Transport
Fallback transport for simple integrations. Unidirectional: client sends messages via REST, receives tokens via SSE.
Create Session
POST /api/v1/chat
model is required (missing/empty answers 400 model_required); mode defaults to "build".
{ "model": "glm-4.7-flash", "mode": "build" }
Response:
{
"ok": true,
"data": {
"id": "a1b2c3d4e5f6",
"worker_id": "chat-a1b2c3d4e5f6",
"model": "glm-4.7-flash",
"mode": "build",
"status": "active",
"created_at": 1745600000000
}
}
Capacity errors:
| Code | Body | Condition |
|---|---|---|
| 429 | {"ok":false,"error":"seat_cap_reached"} + Retry-After: 1 | Seat cap saturated |
| 429 | {"ok":false,"error":"max_workers_reached"} + Retry-After: 1 | Worker ceiling |
| 429 | {"ok":false,"error":"too_many_sessions"} | Session cap: 20 active sessions per user, or 500 active sessions globally |
| 503 | {"ok":false,"error":"license_unavailable"} | License service down (block mode) |
| 503 | {"ok":false,"error":"session_table_unavailable"} | Session registry write failed |
| 413 | {"ok":false,"error":{"code":"body_too_large","message":"body_too_large"}} | Body over 10 MB |
Shape note: the 429/503 capacity arms predate the nested envelope and still carry the string
errorfield shown above ({"ok":false, "error":"<code>"}); the 413 arm answers the nested{code,message}envelope. Both areok:false— dispatch on the code, not the shape. The SSE-budget refusal (sse_limit_reached, 429 +Retry-After: 1) shares the string form.
Streamed turns persist a checkpoint every chat_checkpoint_tokens (64)
tokens / chat_checkpoint_ms (2000 ms) — a mid-stream crash loses at most
one window.
Stream Tokens
GET /api/v1/chat/:id/stream
Returns an SSE stream. Events: connected, token, done, error.
curl -N http://127.0.0.1:21434/api/v1/chat/a1b2c3d4e5f6/stream \
-H "Authorization: Bearer $TOKEN"
Send Message
POST /api/v1/chat/:id/message
{ "content": "Explain quicksort" }
A missing/empty content answers 400 content_required; a read timeout on
the body answers 408 request_timeout; a client disconnect mid-read answers
499 client_disconnect.
End Session
DELETE /api/v1/chat/:id
Session Management
List Sessions
GET /api/v1/chat
Returns active sessions for the authenticated user. Admin users see all sessions.
Get Session Details
GET /api/v1/chat/:id
Message History
GET /api/v1/chat/:id/history?limit=50
Messages are stored for 30 days in Mnesia. limit defaults to 50 and is
clamped to 1..200 (hostile values degrade to the default, never an error).
Response:
{
"ok": true,
"data": [
{
"id": "msg-abc123",
"session_id": "a1b2c3d4e5f6",
"role": "user",
"content": "Hello",
"timestamp": 1745600000
}
]
}
Permissions
Chat endpoints require chat:read permission. Sessions are scoped to the authenticated user — non-admin users can only access their own sessions.
Architecture: Luna Harness, Not a Thin Proxy
The web chat does NOT talk directly to LLM providers. Every message flows through the full Luna agent harness — the same runtime used by the TUI and CLI. This means web chat users get the complete agent experience: tool execution, session persistence, memory, MCP servers, compaction, and multi-provider failover.
Limon is a thin UI shell. Sol is the message bus. Luna is the brain.
Data Flow
┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐
│ Limon │ │ Sol │ │ ZMQ │ │ Luna │
│ (Browser)│ │(Erlang) │ │(ROUTER) │ │(LuaJIT) │
└────┬─────┘ └────┬─────┘ └────┬─────┘ └────┬─────┘
│ │ │ │
│ WS connect │ │ │
│─────────────────►│ spawn worker │ │
│ │─────────────────►│ DEALER connect │
│ │ │─────────────────►│
│ │ │ │
│ {type:message} │ │ │
│─────────────────►│ task msgpack │ │
│ │─────────────────►│ JSONL stdin │
│ │ │─────────────────►│
│ │ │ │
│ │ │ │ ┌─────────────┐
│ │ │ │ │ Agent Loop │
│ │ │ │ │ ┌─────────┐ │
│ │ │ │ │ │Provider │ │
│ │ │ │ │ │(Anthropic│ │
│ │ │ │ │ │OpenAI │ │
│ │ │ │ │ │z.ai) │ │
│ │ │ │ │ └─────────┘ │
│ │ │ │ │ ┌─────────┐ │
│ │ │ │ │ │ Tools │ │
│ │ │ │ │ │(71+MCP) │ │
│ │ │ │ │ └─────────┘ │
│ │ │ │ │ ┌─────────┐ │
│ │ │ │ │ │ Session │ │
│ │ │ │ │ │(JSONL+ │ │
│ │ │ │ │ │ SQLite) │ │
│ │ │ │ │ └─────────┘ │
│ │ │ │ │ ┌─────────┐ │
│ │ │ │ │ │ Memory │ │
│ │ │ │ │ │(KV+TTL) │ │
│ │ │ │ │ └─────────┘ │
│ │ │ │ └─────────────┘
│ │ │ │
│ │ │ token (JSONL) │
│ │ {sol_token} │◄─────────────────│
│ {type:token} │◄────────────────│ │
│◄─────────────────│ │ │
│ │ │ ...more tokens │
│ │ │ │
│ │ │ done (JSONL) │
│ │ {sol_done} │◄─────────────────│
│ {type:done} │◄────────────────│ │
│◄─────────────────│ │ │
What Luna Provides in Web Chat Mode
Every web chat session runs a complete Luna agent. When Limon sends a message, the Luna worker:
- Appends to session — JSONL + SQLite dual-write, same as TUI/CLI
- Builds context — system prompt, session history, memory injection, context file scanning
- Calls provider — multi-provider failover (Anthropic → OpenAI → z.ai → Ollama)
- Streams tokens — each token fragment sent back to Limon via ZMQ → Sol → WS
- Executes tools — tools=92 registered built-in + MCP tools, parallel execution for async tools
- Manages memory — cross-session KV+TTL, heuristic extraction on session close
- Compacts when needed — multi-strategy compaction at 70% context threshold
- Persists checkpoints — automatic checkpoint before risky operations
What Sol Does NOT Do
Sol does not call LLM providers directly for chat Sol does not execute tools or manage conversation state Sol does not handle sessions or memory Sol is a message bus: it receives WS messages, dispatches to Luna via ZMQ, and relays streaming tokens back
Why This Matters
Consistency: Same agent behavior whether using TUI, CLI, or web chat
Full tool access: Web chat users can run bash, edit files, search code — not just talk
Session portability: Start in web, resume in TUI with --resume — same JSONL session
Provider independence: Swap providers without touching Limon or Sol
Completions API
Canonical reference: docs/api-reference.md (generated endpoint directory) — this page is a task-oriented summary.
ZERG exposes an OpenAI Chat Completions compatible endpoint. This allows any OpenAI SDK or tool to target ZERG as a drop-in replacement.
Overview
The /v1/chat/completions endpoint mirrors the OpenAI wire format. ZERG translates the request internally, dispatches to the configured provider (Anthropic, OpenAI, z.ai, Ollama, etc.), and returns OpenAI-formatted responses. Streaming is supported via SSE.
Authentication
Requires Authorization: Bearer <token> header. The token is issued via POST /api/v1/auth/login (the Mango login proxy). The route additionally requires the inference:use permission.
Endpoints
Create Chat Completion
POST /v1/chat/completions
Request Body:
{
"model": "claude-sonnet-4-20250514",
"messages": [
{ "role": "system", "content": "You are a helpful assistant." },
{ "role": "user", "content": "Explain quicksort" }
],
"max_tokens": 1024,
"temperature": 0.7,
"stream": false
}
Response (non-streaming):
{
"id": "chatcmpl-abc123",
"object": "chat.completion",
"created": 1745600000,
"model": "claude-sonnet-4-20250514",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "Quicksort is a divide-and-conquer algorithm..."
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 42,
"completion_tokens": 156,
"total_tokens": 198
}
}
Streaming Mode (stream: true):
Returns SSE events with data: {"choices": [{"delta": {"content": "..."}}]} fragments. Final event contains finish_reason and usage.
Supported Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
model | string | required | Model identifier from the model catalog (prefix matching supported) |
messages | array | required | Array of message objects (system, user, assistant, tool) |
max_tokens | integer | model default | Maximum tokens in the response |
temperature | float | template default | Sampling temperature |
stream | boolean | true | Enable SSE streaming (the OpenAI leg defaults to streaming) |
stop | string[] | — | Stop sequences |
stop_sequences | string[] | — | Stop sequences (alias) |
tools / tool_choice | array / string | — | Tool definitions and selection (translated per provider wire) |
top_p | float | template default | Nucleus sampling parameter |
timeout | integer | 300000 | Request timeout in ms (clamped to client_timeout_max_ms, default 600 s) |
Provider Translation:
The ZERG gateway translates OpenAI messages to the target provider’s wire format. Tool calls are converted bidirectionally between OpenAI tool_calls and Anthropic tool_use blocks. Mid-conversation provider switching preserves context.
Error Codes (every error carries the OpenAI {"error":{...}} envelope so SDK clients can parse error.message; the 413 oversized-body arm is the one exception — it answers the Zerg envelope):
| Code | Description | Body |
|---|---|---|
| 400 | Invalid request body or missing model/messages | {"error":{"message":"...","type":"invalid_request_error","param":null,"code":null}} |
| 401 | Missing or invalid authentication token | {"error":{"message":"authentication required","type":"invalid_request_error",...}} |
| 403 | Insufficient permissions (inference:use missing) | {"error":{"message":"...","type":"invalid_request_error",...}} |
| 413 | Oversized body | {"ok":false,"error":{"code":"body_too_large","message":"..."}} (Zerg envelope) |
| 429 | Model at capacity, provider key cooling down, or SSE budget full | {"error":{"message":"...","type":"rate_limit_error",...}} + Retry-After: 1 |
| 502 | Upstream connect failure (connect_failed, connection_down) | {"error":{"message":"...","type":"api_error",...}} |
| 503 | Model unavailable (pre-stream), or resolver circuits open | Pre-stream: {"error":{"message":"model unavailable","type":"server_error",...}}; circuit-open arms currently answer the Zerg envelope {"ok":false,"error":{"code":"all circuits open",...}} (family leak — see the note below) |
| 504 | Upstream timeout family (timeout, first_token_timeout, idle_timeout) | {"error":{"message":"...","type":"server_error",...}} |
Interrupted streams: the final SSE chunk carries
"finish_reason": "interrupted" followed by the regular data: [DONE]
framing; an error frame emitted after content tokens carries
"truncated": true (partial answer delivered vs failed-before-output).
Family note: the resolver’s circuit-open arms on this route answer the Zerg envelope instead of the OpenAI one (a known family leak in the handler — the pre-stream capacity/down arms and the auth middleware do speak the OpenAI envelope). The SSE-budget refusal on all completion routes answers 429
sse_limit_reachedwithRetry-After: 1in the flat{"ok":false,"error":"sse_limit_reached"}form.
Example:
curl http://127.0.0.1:21434/v1/chat/completions \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"model": "claude-sonnet-4-20250514",
"messages": [{"role": "user", "content": "Hello"}],
"max_tokens": 100
}'
Streaming variant:
curl -N http://127.0.0.1:21434/v1/chat/completions \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"model": "claude-sonnet-4-20250514",
"messages": [{"role": "user", "content": "Count to 10"}],
"stream": true
}'
Conversations API
Canonical reference: docs/api-reference.md (generated endpoint directory) — this page is a task-oriented summary.
Manage multi-turn conversations with AI models. Conversations support provider switching mid-session, SSE streaming, and usage tracking.
List Conversations
GET /api/v1/conversations
Returns all conversations for the authenticated user. Admin users see all conversations.
Response
{
"items": [
{
"id": "conv_abc123",
"model": "glm-5.1",
"created_at": 1716192000000,
"updated_at": 1716192100000
}
],
"total": 1,
"limit": 50,
"offset": 0,
"page": 1,
"total_pages": 1,
"has_more": false
}
Standard pagination applies (limit/offset, or page/per_page).
Get Conversation Detail
GET /api/v1/conversations/:conv_id
Returns the conversation with all messages and metadata.
Response
{
"id": "conv_abc123",
"model": "glm-5.1",
"messages": [
{
"id": "msg_001",
"role": "user",
"content": "Explain the OTP supervision tree",
"created_at": 1716192000000,
"meta": {}
},
{
"id": "msg_002",
"role": "assistant",
"content": "The OTP supervision tree is a hierarchical process structure...",
"created_at": 1716192001000,
"meta": {"model": "glm-5.1", "tokens": 150}
}
],
"usage": {
"input_tokens": 45,
"output_tokens": 150,
"total_tokens": 195
}
}
usage is present only when the conversation has recorded usage.
Error Responses
| Code | Description |
|---|---|
| 403 | Not the conversation owner (Zerg envelope, forbidden) |
| 404 | Conversation not found (Zerg envelope, not found) |
Conversation Creation
Every POST /v1/messages request creates a new conversation server-side
(best-effort) and stores the request messages in it — there is no explicit
conversation-create endpoint, and no client-supplied conversation_id
continuation parameter on either completion route. /v1/chat/completions
does not create conversations.
Stream Conversation Events
GET /api/v1/conversations/:conv_id/stream
Subscribe to real-time events for a conversation via Server-Sent Events (SSE).
Response
Returns Content-Type: text/event-stream. Message events are emitted under
the message_append event name, filtered to the subscribed conversation;
idle keep-alives are SSE comment pings (every 15 s), and the stream ends
with an event: done frame when the subscription terminates:
event: message_append
data: {"type":"message_append","data":{"conv_id":"conv_abc123","role":"assistant","content":"..."}}
: ping
event: done
data: {}
The route holds an SSE admission slot; over-budget calls answer 429
(sse_limit_reached / subscription_limit_reached).
Error Responses
| Code | Description |
|---|---|
| 403 | Not the conversation owner (plain body) |
| 404 | Conversation not found (plain body) |
Delete a Conversation
POST /api/v1/conversations/:conv_id/delete
Permanently delete a conversation and all its messages. Only the owner can delete.
Response
{
"status": "ok"
}
Error Responses
| Code | Description |
|---|---|
| 403 | Not the conversation owner |
| 404 | Conversation not found |
Get a Single Message
GET /v1/messages/:message_id
Retrieve a specific message by its ID. Ownership is checked via the parent conversation. Note the route lives on the Anthropic wire family: the 404 body is the Anthropic error envelope ({"type":"error","error":{"type":"not_found_error","message":"message not found"}}).
Response
{
"id": "msg_002",
"role": "assistant",
"content": "The OTP supervision tree is a hierarchical process structure...",
"created_at": 1716192001000,
"meta": {
"model": "glm-5.1",
"tokens": 150
}
}
Error Responses
| Code | Description |
|---|---|
| 404 | Message not found (Anthropic error envelope) |
Get Conversation Usage
GET /api/v1/conversations/:conv_id/usage
Returns token usage statistics for a conversation.
Response
{
"usage": {
"input_tokens": 450,
"output_tokens": 1500,
"total_tokens": 1950
}
}
Provider Switching
Conversations support switching providers mid-conversation. The system performs bidirectional message transformation between Anthropic and OpenAI formats:
curl -X POST http://127.0.0.1:21434/v1/chat/completions \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-4",
"messages": [{"role": "user", "content": "Continue"}]
}'
The system automatically transforms the messages from the previous provider’s format to the new provider’s format.
Ownership
Conversations are owned by the user who created them. The ownership check uses sol_identity:check_resource_owner/3 which verifies the authenticated user’s UUID matches the conversation’s owner UUID. Admin users can access all conversations.
Compatiblity Endpoints
The Messages and Chat Completions endpoints are conversation-aware on the Anthropic leg:
| Endpoint | Provider Format | Description |
|---|---|---|
POST /v1/messages | Anthropic | Send message, get response (creates a conversation and stores the request messages) |
POST /v1/chat/completions | OpenAI | Send message, get response |
When stream is true, responses are delivered via SSE with incremental token events.
Events API
Canonical reference: docs/api-reference.md (generated endpoint directory) — this page is a task-oriented summary.
Sol uses a Mnesia-backed event sourcing system as its orchestration backbone. The Events API provides read access to the event stream and real-time SSE subscriptions.
List Events
GET /api/v1/events
Query the event store with filters and pagination.
curl -H "Authorization: Bearer $TOKEN" \
"https://sol.example.com/api/v1/events?aggregate=task-123&limit=20"
Query Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
aggregate | string | — | Aggregate ID to read |
user_uuid | string | — | Admin selector for that user’s events (a non-admin is always scoped to their own user_uuid) |
since | integer | 0 | Unix-ms timestamp cursor — only events with timestamp > since (per-user/global reads) |
since_id | string | — | Tuple-cursor tiebreak for since (see below) |
from_seq | integer | 0 | Inclusive aggregate replay cursor (seq >= from_seq; seq 0 included) |
cursor | string | — | Aggregate page cursor "<seq>:<event_id>" from next_cursor; resumes strictly after that row. Do not combine with offset or from_seq (typed 400) |
limit | integer | 50 | Maximum events to return (clamped 1..500) |
offset | integer | 0 | Pagination offset (aggregate reads: max 10001) |
Response:
{
"items": [
{
"id": "evt-1744730000000",
"type": "task.completed",
"aggregate_id": "task-123",
"seq": 42,
"timestamp": 1744730000000,
"data": {
"task_id": "task-123",
"worker_id": "luna-01",
"status": "ok",
"duration_ms": 3200
}
}
],
"limit": 50,
"offset": 0,
"page": 1,
"has_more": true,
"next_cursor": "42:evt-1744730000000"
}
Aggregate reads carry no total/total_pages — an aggregate count
would require walking the whole aggregate, which the indexed read
deliberately avoids. next_cursor is the exact {seq, event_id} pair of
the last row; pass it back as ?cursor=<seq>:<event_id> (offset and
from_seq must be omitted — combining them is a typed 400). This keeps
duplicate-seq rows reachable. A caller-scoped read that would scan past
the server’s bounded index-row cap answers 400
aggregate_scan_limit_exceeded.
The per-user/global (no ?aggregate) reads keep the pagination envelope
with total, total_pages, newest_timestamp and newest_id; pass
newest_timestamp + newest_id back as the next since + since_id.
Tuple cursor: pass since_id=<seq> to get an id-tiebreak
cursor — events sharing the same millisecond are never skipped or
duplicated at page boundaries. Poll with BOTH since + since_id and use
newest_timestamp + newest_id for the next iteration.
Event Structure
Every event in the store follows a consistent schema:
| Field | Type | Description |
|---|---|---|
id | string | Unique event identifier |
type | string | Event type (see below) |
aggregate_id | string | Aggregate root identifier |
seq | integer | Monotonic sequence within aggregate |
timestamp | integer | Unix timestamp (milliseconds) |
data | object | Event payload |
Event Types
Sol defines 102 event types (machine-derived census) across the
categories below. Each validated type is versioned and checked at ingestion
(sol_event_validator). The list here is the common set, not the exhaustive
catalog — the sync stream also carries channel.message_sent,
circuit.*, cluster.*, provider.*, session.* (checkpoint/branch
lifecycle), worker.connected/worker.disconnected, task.assigned/
task.dropped, and workflow.branch_created/workflow.compensation*
events.
Task Events
| Type | Aggregate | Description |
|---|---|---|
task.created | task_id | New task submitted |
task.started | task_id | Task began executing |
task.completed | task_id | Task finished successfully |
task.failed | task_id | Task execution failed |
task.dispatched | task_id | Task sent to a worker |
Model Events
| Type | Aggregate | Description |
|---|---|---|
model.started | model_name | Inference instance started |
model.stopped | model_name | Inference instance stopped |
model.failed | model_name | Inference startup failed |
model.discovered | model_name | Model found during discovery |
model.preparing | model_name | Prepare accepted, rsync running (async) |
model.prepared | model_name | Model files prepared |
model.prepare_failed | model_name | Prepare failed (row reverts to discovered) |
model.start_failed | model_name | Model failed to start |
Worker Events
| Type | Aggregate | Description |
|---|---|---|
worker.spawned | worker_id | Worker process created |
worker.crashed | worker_id | Worker process crashed |
worker.ready | worker_id | Worker announced readiness |
worker.status | worker_id | Worker status change (idle/busy/…) |
worker.task_started | task_id | Worker began a task |
worker.task_completed | task_id | Worker finished a task |
worker.task_failed | task_id | Worker task failed |
worker.spawn_failed | worker_id | Worker spawn failed |
worker.killed | worker_id | Worker killed by operator |
Inference Events
| Type | Aggregate | Description |
|---|---|---|
inference.request | request_id | Inference request received |
inference.complete | request_id | Inference completed |
inference.error | request_id | Inference error |
inference.interrupted | request_id | Inference interrupted |
Scheduler Events
| Type | Aggregate | Description |
|---|---|---|
scheduler.job_created | job_id | Scheduled job created |
scheduler.job_executed | job_id | Job executed |
scheduler.task_dispatched | job_id | Job dispatched a task |
Workflow Events
| Type | Aggregate | Description |
|---|---|---|
workflow.started | workflow_id | Workflow began |
workflow.completed | workflow_id | Workflow finished |
workflow.failed | workflow_id | Workflow failed |
workflow.step_started | workflow_id | Workflow step started |
workflow.compensation_failed | workflow_id | Compensation step failed |
Agent Events
| Type | Aggregate | Description |
|---|---|---|
agent.turn_started | task_id | Agent turn began |
agent.turn_completed | task_id | Agent turn completed |
agent.context_overflow | task_id | Context exceeded limits |
agent.diagnostic | task_id | Agent diagnostic event |
agent.loop_warning | task_id | Possible agent loop detected |
agent.loop_detected | task_id | Agent loop confirmed |
Team Events
| Type | Aggregate | Description |
|---|---|---|
team.created | team_id | Team created |
team.member_joined | team_id | Member joined team |
team.member_left | team_id | Member left team |
team.mail_sent | team_id | Team mail sent |
team.mail_expired | team_id | Team mail row expired (TTL) |
team.destroyed | team_id | Team destroyed |
Memory Events
| Type | Aggregate | Description |
|---|---|---|
memory.decayed | agent_id | Memory importance decayed |
memory.reflected | agent_id | Memory reflection triggered |
Note: there are no
memory.stored/memory.accessed/memory.forgottensync events, and noaudit.*sync events — the audit trail is the append-only JSONL log (sol_audit_log), not the sync-event store. See Audit.
SSE Streaming
Real-time event streaming via Server-Sent Events:
GET /api/v1/sync-events
curl -N -H "Authorization: Bearer $TOKEN" \
https://sol.example.com/api/v1/sync-events
SSE event format:
event: sync_event
data: {"id":"evt-1744730001","aggregate_id":"task-456","seq":7,"type":"task.completed","data":{"task_id":"t-456","status":"ok"},"timestamp":1744730001000}
event: sync_event
data: {"id":"evt-1744730002","aggregate_id":"worker-luna-02","seq":1,"type":"worker.ready","data":{"worker_id":"luna-02"},"timestamp":1744730002000}
Every event is emitted under a single event: sync_event line; the event’s own type (e.g. task.completed, worker.ready) is carried inside the JSON data. Use the categories query parameter to filter which event types you receive. A keep-alive comment (: ping) is sent every 15 seconds.
Event Hooks
Events support pre-commit and post-commit hooks. Hooks are registered programmatically:
Pre-commit hooks can validate or enrich event data before persistence Post-commit hooks trigger side effects (notifications, projections, ZMQ broadcasts)
Event Store
The event store is backed by Mnesia with automatic sequence numbering per aggregate. Key properties:
Events are append-only and immutable Each aggregate maintains a monotonic sequence counter Events are replayable for state reconstruction Projections can be registered for materialized views
Goals API
Canonical reference: docs/api-reference.md (generated endpoint directory) — this page is a task-oriented summary.
Goal CRUD with workflow integration. Goals are persistent objectives that drive multi-step agent workflows.
Overview
Goals represent long-running, multi-step tasks managed by the workflow engine. Each goal spawns a coordinator process that decomposes the goal into steps, dispatches sub-agents, and tracks completion. Goals are ETS-only per-node projection state with a supervisor-anchored heir chain: an owner crash preserves them, but they do not survive a node reboot (the accepted loss window — no Mnesia copy, no replay).
Authentication
Requires Authorization: Bearer <token>. Goals are scoped to the authenticated user — non-admin users can only access their own goals.
Endpoints
Create Goal
POST /api/v1/goals
Admin only. Creates a goal from an objective and a task list. The objective is decomposed and dispatched to the workflow engine. Non-admin callers receive 403 {"ok":false,"error":{"code":"forbidden","message":"forbidden"}}.
Request Body:
{
"objective": "Research quantum computing advances in 2026",
"tasks": ["Survey 2026 Q1 papers", "Summarize error-correction progress"]
}
objective is required (400 if empty); tasks is the list of subtasks to decompose and run.
Response (201):
{
"id": "goal-abc123",
"objective": "Research quantum computing advances in 2026",
"status": "in_progress",
"strategy": "parallel",
"subtask_count": 2,
"workflow_ids": ["wf-def456", "wf-def789"]
}
List Goals
GET /api/v1/goals
Returns goals for the authenticated user (admins see all). Each entry is {id, objective, status, meta?}.
{
"goals": [
{"id": "goal-abc123", "objective": "Research quantum computing", "status": "in_progress"}
]
}
Get Goal Details
GET /api/v1/goals/:id
Returns the goal’s coordinator status (current step, step history, results). Owner/admin only.
Update Goal
PUT /api/v1/goals/:id
Update goal metadata. Admin only, or the goal owner for their own goals.
Cancel Goal
POST /api/v1/goals/:id/cancel
DELETE /api/v1/goals/:id
Cancels a running goal. POST /cancel is admin-only; DELETE is allowed for the goal owner or admin. Stops the associated workflows and any in-progress sub-agents.
{
"cancelled": "goal-abc123"
}
Workflow Integration:
Each goal creates a workflow with the following lifecycle:
Created → Decomposing → Step N Running → Step N Complete → ... → Completed
↓
Failed (retry configurable)
↓
Max retries exceeded → Failed
The goal projector (sol_goal_projector) maintains secondary indexes mapping workflow_id → goal_ids for O(1) lookup during event processing.
Error Codes:
| Code | Description |
|---|---|
| 400 | Invalid goal parameters |
| 401 | Authentication required |
| 403 | Not the goal owner (non-admin) |
| 404 | Goal not found |
| 409 | Goal already completed or cancelled |
Examples:
curl -X POST http://127.0.0.1:21434/api/v1/goals \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"objective": "Write unit tests", "tasks": ["Cover the goals module", "Cover the workflow module"]}'
curl http://127.0.0.1:21434/api/v1/goals \
-H "Authorization: Bearer $TOKEN"
curl -X POST http://127.0.0.1:21434/api/v1/goals/goal-abc123/cancel \
-H "Authorization: Bearer $TOKEN"
Health & Readiness API
Canonical reference: docs/api-reference.md (generated endpoint directory) — this page is a task-oriented summary.
Sol exposes three operational health endpoints plus a Prometheus metrics scrape endpoint. The health and readiness probes are designed for very different audiences:
/api/v1/health is a shallow check — it tells you the HTTP server is
up and how many models are running. Use it for liveness probes that should
succeed as long as the BEAM is answering HTTP.
/api/v1/ready is a deep check that runs 19 subsystem probes and
returns 503 if any critical component is degraded. Use it for Kubernetes
readiness, load-balancer health, and deployment gates.
/api/v1/infra/status (see Infra) is the detailed
per-service status with reasons and counts — the deep version that operators
read when /ready is failing.
/api/v1/healthand/api/v1/readyare on the auth-exempt list so infrastructure probes can hit them without credentials.
Health Check (shallow)
GET /health
GET /api/v1/health
Both aliases run the same handler and return the same body. No authentication required.
Response (200):
{
"status": "ok",
"models_running": 2
}
| Field | Description |
|---|---|
status | Always "ok" when the handler can answer. |
models_running | Count of currently running inference models (sol_registry:list_running). Falls back to 0 if the registry call fails. |
This endpoint never returns subsystem details, a checks array, or a degraded
status — for that, use /api/v1/ready (which still omits details, see below)
or /api/v1/infra/status (which includes them).
curl http://localhost:21434/api/v1/health
Readiness Probe (deep)
GET /api/v1/ready
Runs all 19 subsystem checks via sol_health:check_all/0. Returns 200 only when
every check passes; 503 otherwise.
Response (200, healthy):
{
"status": "ok",
"checks": [
{ "name": "providers", "status": "ok" },
{"name": "init", "status": "ok"},
{"name": "mnesia", "status": "ok"},
{"name": "zmq", "status": "ok"},
{"name": "mango", "status": "ok"},
{"name": "orchestrator_lease", "status": "ok"},
{"name": "projection", "status": "ok"},
{"name": "postgres", "status": "ok"},
{"name": "ets", "status": "ok"},
{"name": "listeners", "status": "ok"},
{"name": "disk", "status": "ok"},
{"name": "process_util", "status": "ok"},
{"name": "memory_util", "status": "ok"},
{"name": "message_queues", "status": "ok"},
{"name": "models", "status": "ok"},
{"name": "workers", "status": "ok"},
{"name": "core_data_plane", "status": "ok"},
{"name": "backup", "status": "ok"},
{"name": "audit", "status": "ok"}
]
}
Response (503, degraded):
{
"status": "degraded",
"checks": [
{"name": "mnesia", "status": "ok"},
{"name": "zmq", "status": "error"},
{"name": "disk", "status": "warning"}
]
}
providers — readiness check (see the /api/v1/ready list)
Checks array shape
Each entry has exactly two keys:
{ "name": "<subsystem>", "status": "ok|warning|error" }
There is intentionally no
detailsfield./api/v1/readyis on the auth-exempt list, so the full reason strings are stripped to avoid leaking internal state (paths, hostnames, error reasons) to unauthenticated callers. The detail maps are logged server-side atwarninglevel for operator diagnostics. To see details in the response body, use the admin-gated/api/v1/infra/statusendpoint.
Subsystems checked
| Check | Error conditions |
|---|---|
init | Application init tasks (event_store, workflow_defs, provider_boot) failed |
mnesia | Mnesia not started / not running |
zmq | ZMQ gateway not responding |
mango | Mango auth service unreachable |
orchestrator_lease | Orchestrator single-writer lease not confirmed/held: an unfenced (never-confirmed) boot or a stale hold is an error unless orchestrator_lease_stale_hold_ack=true; a fenced loser, an authority refusal or a holder-but-fenced deadlock is always an error. Reports gateway_fenced so the deploy probe sees a quiesced gateway. Independent of mango (Mango-down already fails that row; this one never reads it). |
postgres | PostgreSQL pool health check failed |
ets | Core ETS tables missing |
listeners | No Cowboy HTTP listener bound |
disk | Disk below critical (100 MB) or warning (1 GB) |
process_util | Process count > 80% (warning) / 95% (error) of limit |
memory_util | BEAM total memory > 4 GB (warning) |
message_queues | Any process mailbox > 100 messages |
models | Configured models exist but zero are ready (running/prepared) — an error when a fleet is expected (health_expect_models, default: any registered row); an absent table is “not configured”, never green-by-accident |
workers | Zero workers while a fleet is expected (fleet expected but no workers are registered; expectation = health_expect_workers, else zmq_enabled AND initial_workers > 0 — the shipped entrypoint renders initial_workers=1). Staleness uses worker_heartbeat_timeout_ms (shipped 15000 ms; code fallback 45000). A fresh deploy with no worker therefore returns 503. |
core_data_plane | A core data-plane owner is missing/suspended, or its mailbox is over the warning (5000) / critical (20000) bound |
projection | The per-boot projection proof is missing (event_replay_on_boot=false/degraded boot) — the RAM views may be empty; event retention is refused until a replay (projection_unproven). |
backup | Local scheduled backup disabled in prod (air-gap still requires it: local_backup_required), no off-host target in prod without airgap_mode=true (offhost_target_required), or the last backup failed. airgap_mode=true relaxes only the off-host leg. |
audit | Audit sink not running, or the flush is persistently degraded (configured-but-unreadable is an error) |
Prometheus Metrics
GET /metrics
Exposes metrics in Prometheus text exposition format (text/plain; version=0.0.4).
Auth-exempt (Alloy scrapes on a 15 s interval).
curl http://localhost:21434/metrics
Sample output:
# HELP sol_http_2xx_total HTTP 2xx responses (SLO)
# TYPE sol_http_2xx_total counter
sol_http_2xx_total 1234
# HELP sol_errors_total Error counts by module and category
# TYPE sol_errors_total counter
sol_errors_total{module="sol_pipeline",category="timeout"} 3
# HELP sol_latency_us Latency in microseconds
# TYPE sol_latency_us summary
sol_latency_us{quantile="0.50",name="http_request"} 12000
sol_latency_us{quantile="0.95",name="http_request"} 45000
sol_latency_us{quantile="0.99",name="http_request"} 245000
Metric families
| Family | Type | Description |
|---|---|---|
sol_*_total | counter | Request, task, worker counters |
sol_errors_total | counter | Errors by module and category |
sol_latency_* | summary | Request latency histogram |
sol_circuit_breaker_state | gauge | Circuit breaker open/closed |
sol_workers_* | gauge | Worker count and status |
sol_models_* | gauge | Model availability |
sol_uptime_seconds | gauge | Server uptime |
sol_build_info | gauge | Version and build metadata |
sol_process_* | gauge | Erlang process metrics |
sol_memory_* | gauge | BEAM memory metrics |
sol_ets_count | gauge | ETS table row counts |
sol_task_queue_* | gauge | Task queue depth |
sol_cluster_nodes | gauge | Connected cluster nodes |
sol_availability_percent | gauge | Calculated availability |
The internal JSON metrics counters exposed at
GET /api/v1/metricsare a separate, application-level snapshot — not the Prometheus scrape format.
Related
Infra — admin-gated detailed service status
(GET /api/v1/infra/status), maintenance mode, cache invalidation
Inference API
Canonical reference: docs/api-reference.md (generated endpoint directory) — this page is a task-oriented summary.
Sol manages LLM inference instances through a provider adapter system. It supports local llama.cpp inference and 14 provider adapters with a unified API surface.
Start Inference
POST /api/v1/start
Start a new inference instance with the specified model. Admin only. The body carries the model name plus optional template and overrides.
curl -X POST https://sol.example.com/api/v1/start \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"model": "glm-5.1",
"template": "default",
"overrides": {
"gpu_layers": 99,
"ctx_size": 4096,
"threads": 4
}
}'
Response:
{
"status": "ok",
"port": 8080,
"ref": "inference_ref"
}
409 with {"status": "already_running", "port": 8080} if the model is already loaded; 404 if the model is not found. A model still mid-prepare (or never prepared) answers 409 (prepare in progress / model not prepared — call prepare first) — start is synchronous-only against the prepared state; see POST /api/v1/prepare/:name in the canonical reference for the async prepare flow (POST-only; GET answers 405).
Stop Inference
POST /api/v1/stop
Stop a running inference instance. Admin only. Reads a model name (not an instance id).
curl -X POST https://sol.example.com/api/v1/stop \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"model": "glm-5.1"}'
Stop All Instances
POST /api/v1/stop-all
Stop all running inference instances.
List Models
GET /api/v1/models
List all registered models (local llama.cpp + provider), paginated. Local
models carry slug/family/quant/size/status/source: "local";
provider models carry id/source: "provider"/provider/
context_window/capabilities/pricing:
curl -H "Authorization: Bearer $TOKEN" \
https://sol.example.com/api/v1/models
Response:
{
"items": [
{
"id": "glm-5.1",
"source": "provider",
"provider": "sol_provider_zai",
"context_window": 128000,
"capabilities": {},
"pricing": {}
}
],
"total": 1,
"limit": 50,
"offset": 0,
"page": 1,
"total_pages": 1,
"has_more": false
}
Model Discovery
POST /api/v1/discover
Scan for available models and register them. Requires admin permissions.
curl -X POST https://sol.example.com/api/v1/discover \
-H "Authorization: Bearer $TOKEN"
Response:
{
"discovered": 5
}
Provider Adapters
Sol uses a behaviour-based provider system with 12 adapters (8 of which have circuit breakers registered at boot). Each adapter implements a common interface for listing models, creating completions, and streaming tokens.
Supported Providers
| Provider | Adapter | Capabilities |
|---|---|---|
| Anthropic | sol_provider_anthropic | Messages API, streaming, vision |
| OpenAI | sol_provider_openai | Chat Completions, streaming, function calling |
| z.ai | sol_provider_zai | GLM-5.1, streaming, vision |
| Ollama | sol_provider_ollama | Local models, streaming |
| Gemini | sol_provider_gemini | Google AI, streaming |
| DeepSeek | sol_provider_deepseek | Chat Completions, streaming |
| Alibaba | sol_provider_alibaba | Qwen models, streaming |
| Bedrock | sol_provider_bedrock | AWS Bedrock, streaming |
| Xiaomi | sol_provider_xiaomi | MiMo models (OpenAI-compatible), streaming |
| Declarative | sol_provider_declarative | Config-driven adapter for custom endpoints (e.g. MiniMax via priv/providers/01-minimax.json) |
The retired OpenAI Responses wire (
sol_provider_responses) is a documented refusal since then: declarative configs declaringformat: "responses"fail validation and no responses-adapter models are registered. Use theopenaioranthropicwire.
See the Provider Setup reference for full configuration details.
Provider Configuration
Providers are configured in sys.config:
{providers, [
{anthropic, #{api_key => "sk-ant-..."}},
{openai, #{api_key => "sk-..."}},
{zai, #{api_key => "..."}},
{ollama, #{base_url => "http://localhost:11434"}}
]}
Cross-Provider Message Transformation
Sol provides bidirectional message transformation between Anthropic and OpenAI formats:
Anthropic Messages API (/v1/messages)
OpenAI Chat Completions API (/v1/chat/completions)
This enables mid-conversation provider switching without format conversion on the client side.
Streaming (SSE)
All inference endpoints support Server-Sent Events streaming:
curl -N https://sol.example.com/v1/chat/completions \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"model": "glm-5.1",
"messages": [{"role": "user", "content": "Hello"}],
"stream": true
}'
SSE event format:
data: {"id":"chatcmpl-123","choices":[{"delta":{"content":"Hello"},"index":0}]}
data: [DONE]
Streaming features:
Heartbeat messages to prevent connection timeouts Token-by-token delivery for real-time display Graceful connection termination on completion or error
Inference Lifecycle
Inference instances use gen_statem for lifecycle management:
stopped -> starting -> ready -> running -> ready
\-> failed
| State | Description |
|---|---|
stopped | Instance not running |
starting | Model loading in progress |
ready | Instance available for requests |
running | Processing a request |
failed | Startup or runtime error |
Inference Configuration
| Setting | Default | Description |
|---|---|---|
inference_bin | ./llama-server | llama.cpp server binary |
inference_gpu_layers | 99 | GPU layers to offload |
inference_ctx_size | 4096 | Context window size |
inference_threads | 4 | CPU threads |
Local Inference (llama.cpp)
Sol manages local llama.cpp inference instances via erlexec:
Automatic process lifecycle (start, monitor, restart) GPU offloading configuration Multiple concurrent instances on different ports Process monitoring using Erlang monitors (not polling)
Local inference is the default. Remote providers serve as fallback when local models are unavailable.
Infrastructure API
Canonical reference: docs/api-reference.md (generated endpoint directory) — this page is a task-oriented summary.
Administrative endpoints for service status, maintenance mode, and hot-path
cache invalidation. Mounted at the catch-all router
{"/api/v1/infra/[...]", sol_http_infra, []}, which dispatches internally on
the trailing path segments and HTTP method.
The infra API is deliberately small. It exposes only status, maintenance, and cache operations — not config read/reload, version, or log-level changes. (Those were removed/never implemented; do not document or call them.)
Authentication
GET /api/v1/infra/status and GET /api/v1/infra/maintenance are on the
Auth-exempt list so orchestrators and LB tooling can read them without
credentials — but non-admin callers get a trimmed status body (see below).
GET /api/v1/infra/cache-affinity requires a valid token but not admin. All
mutating endpoints (POST/DELETE) require the admin role — i.e.
permissions containing the literal "*" (the middleware additionally gates
POST /api/v1/infra/ on infra:manage). When authentication is disabled
(auth_enabled = false) the admin gate is bypassed.
When the admin check fails a mutating endpoint returns 403 with the Zerg
envelope {"ok":false,"error":{"code":"insufficient_permissions","message":"admin required"}}.
Unknown path/method combinations return 405 with the envelope
{"ok":false,"error":{"code":"method not allowed","message":"method not allowed"}}.
Endpoints
Service Status
GET /api/v1/infra/status
Aggregated operational status: server health, version, uptime, maintenance
flag, per-subsystem service probes, cluster info, and atom table usage. This is
the detailed counterpart to the auth-exempt /api/v1/ready — it includes
the per-subsystem reason/detail maps that /ready strips.
Response (200 — admin view; non-admins receive the trimmed booleans only):
{
"status": "ok",
"version": "1.003.0",
"uptime_ms": 7200000,
"maintenance": { "enabled": false },
"services": {
"mnesia": { "status": "ok", "tables": 35 },
"zmq": { "status": "ok", "sockets": 3 },
"postgres": { "status": "ok" },
"ets": { "status": "ok", "tables": 14 },
"forgejo": { "status": "ok", "code": 200 },
"crow_ci": { "status": "ok", "code": 200 },
"prometheus": { "status": "ok", "code": 200 },
"tempo": { "status": "error", "reason": "connection_refused" },
"grafana": { "status": "ok", "code": 200 },
"models": { "status": "ok", "ready": 2 },
"workers": { "status": "ok", "stale": 0 }
},
"cluster": {
"nodes": 1,
"node_names": ["sol@blue"]
},
"atoms": {
"count": 41832,
"limit": 1048576
},
"tenancy": {
"mode": "single_org",
"tenant_unit": "sol",
"worker_tenancy": "single_tenant",
"shared_worker_supported": false,
"shared_worker_allowed": false
}
}
| Field | Description |
|---|---|
status | ok, degraded, or unknown — aggregated from sol_health:check_all/0. |
version | Application vsn (application:get_key(sol, vsn)); falls back to "0.10.0" if unset. |
uptime_ms | BEAM wall-clock uptime in ms. |
tenancy | The shipped posture: single_org per Sol, single_tenant per worker, no shared-worker multi-tenant claim. See Tenancy posture. |
maintenance | Current maintenance-mode status map (see below). |
services | Per-subsystem + infra-service probes. Health-check entries mirror the subsystems in /api/v1/ready but with details retained. Infra probes (forgejo, crow_ci, prometheus, tempo, grafana, postgres) are live HTTP/PG probes. |
cluster | {nodes, node_names} from `[node |
atoms | Atom-table count vs. limit. |
The infra service probes are best-effort and timeout-bounded (2 s connect, 3 s
response). A failing probe is reported as
{"status":"error","reason":"timeout" | "connection_refused" | "<atom>"},
Not as an HTTP error — the endpoint itself always returns 200.
Non-admin (anonymous) trim: because the route is
auth-exempt, anyone can read it — so callers without the "*" permission
receive only the overall status plus services reduced to health
booleans ({"mnesia": true, "zmq": false, …}). Version, uptime,
maintenance state, cluster node names, atom counts, and grafana internals
are admin-only:
{
"status": "degraded",
"services": { "mnesia": true, "zmq": false, "postgres": true }
}
Maintenance Mode — Status
GET /api/v1/infra/maintenance
Returns the current maintenance-mode status plus the count of in-flight shutdown operations.
Response (200):
{
"enabled": false,
"reason": null,
"enabled_at": null,
"in_flight": 0
}
| Field | Description |
|---|---|
enabled | Whether maintenance mode is active. |
reason | Free-text reason recorded when maintenance was enabled (admin-supplied or "manual"). |
enabled_at | ms timestamp when maintenance was enabled, or null. |
in_flight | Count of in-flight shutdown operations from sol_shutdown:in_flight/0. Best-effort: failures default to 0. |
Maintenance Mode — Enable
POST /api/v1/infra/maintenance/enable
Enter maintenance mode. Admin-only. Request body is optional.
Request Body (optional):
{ "reason": "rolling deploy 0.549" }
If the body is missing or not JSON, reason defaults to "manual".
Response (200):
{
"ok": true,
"maintenance": { "enabled": true, "reason": "rolling deploy 0.549", "enabled_at": 1716192000000 },
"in_flight": 2
}
Maintenance Mode — Disable
POST /api/v1/infra/maintenance/disable
Exit maintenance mode. Admin-only. No request body.
Response (200):
{
"ok": true,
"maintenance": { "enabled": false, "reason": null, "enabled_at": null }
}
Cache Invalidation
POST /api/v1/infra/cache-invalidate
Invalidate hot-path configuration caches held in persistent_term
(auth_exempt_paths, rate_limit_enabled, provider health cache, etc.).
Admin-only. Call this after changing auth/rate-limit config that is cached
on the hot path.
The actor (sol_identity:get_uuid/0) is recorded in the audit log as
config_cache_invalidate on target "infra/cache".
Response (200):
{
"ok": true,
"invalidated": ["exempt_paths", "rate_limit_enabled"]
}
The
invalidatedlist is the fixed set of cache keys flipped bysol_auth_middleware:invalidate_cache/0— it does not echo the request body. The oldercache_keys/detailfields documented elsewhere are not produced by the current handler.
Cache Affinity — Stats
GET /api/v1/infra/cache-affinity
Return current cache-affinity statistics (sol_cache_affinity:stats/0).
Requires a valid token with the infra:read permission; no admin required.
Response (200):
{
"entries": {
"worker_a": { "model": "glm-5.1", "last_used_ms": 1716192000000 },
"worker_b": { "model": "glm-5.1", "last_used_ms": 1716192001000 }
}
}
When the cache is empty or the call throws, the response is
{"entries":{}}.
Cache Affinity — Clear
DELETE /api/v1/infra/cache-affinity
Clear all cache-affinity entries (wildcard invalidate). Admin-only.
Response (200):
{ "ok": true }
Error Summary
| Code | Body | Condition |
|---|---|---|
| 403 | {"ok":false,"error":{"code":"insufficient_permissions","message":"admin required"}} | Mutating endpoint called without "*" permission. |
| 405 | {"ok":false,"error":{"code":"method not allowed","message":"method not allowed"}} | Path/method combination not routed. |
The status and probe endpoints (GET /infra/status,
GET /infra/maintenance, GET /infra/cache-affinity) always return 200 with
the collected state — individual subsystem failures appear inside the JSON
body, not as HTTP errors.
Examples
# Read detailed service status (with per-subsystem reasons)
curl -H "Authorization: Bearer $TOKEN" \
http://localhost:21434/api/v1/infra/status
# Enter maintenance mode with a reason
curl -X POST http://localhost:21434/api/v1/infra/maintenance/enable \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"reason":"rolling deploy 0.549"}'
# Invalidate hot-path config caches after a config change
curl -X POST http://localhost:21434/api/v1/infra/cache-invalidate \
-H "Authorization: Bearer $TOKEN"
Related
Health — auth-exempt liveness (/api/v1/health) and
readiness (/api/v1/ready) probes. /ready runs the same subsystem checks
as /infra/status but strips details and returns 503 when degraded.
Marketplace API
Canonical reference: docs/api-reference.md (generated endpoint directory) — this page is a task-oriented summary.
The Skills Marketplace allows users to publish, discover, and share agent skills.
Browse Skills
GET /api/v1/marketplace
List published skills. (POST to the same path publishes a skill — see Publish Skill.)
Query parameters:
| Parameter | Default | Description |
|---|---|---|
sort | created_at | Sort order: downloads or created_at (featured skills pin first) |
tag | — | Filter by tag (singular) |
limit | 50 | Max results (clamped 1..500; hostile values degrade to the default) |
offset | 0 | Pagination offset (page/per_page also accepted) |
Response — a flat {"skills": [...]} envelope (the marketplace
deliberately does NOT use the {items, total, has_more} paginated shape, so
a truncated page is not detectable from the response alone):
{
"skills": [
{"name": "code-review", "author_uuid": "user-uuid", "description": "...", "tags": ["code"], "downloads": 42, "featured": false, "avg_rating": 4.5, "rating_count": 2, "version": "1.0"}
]
}
Search Skills
GET /api/v1/marketplace/search?q=QUERY
Search by name or description.
Response:
{
"skills": [ ]
}
Skill Detail
GET /api/v1/marketplace/:name
Get skill detail by name. Returns the first match.
{
"skills": [ {"name": "code-review", "author_uuid": "user-uuid", "description": "...", "body": "skill content...", "downloads": 42, "created_at": 1745600000000} ]
}
GET /api/v1/marketplace/:name/:author
Get a specific skill, disambiguated by author UUID. (DELETE to the same path deletes the skill — see Delete Skill.)
Publish Skill
POST /api/v1/marketplace
Publish a skill. Auth required. The publish limiter (per-user, rpm 60 / burst 10) is DISABLED by default (rate_limit_enabled=false) — no 429s unless the operator enables it. There is no “10 publishes per hour” limit.
Request body:
{
"name": "my-skill",
"description": "Short description",
"tags": ["tag1", "tag2"],
"body": "Full SKILL.md content (max 4096 chars)",
"version": "1.003.0",
"triggers": [],
"arguments": []
}
Reserved names (search, reports, dismiss, feature, rate, ratings) are rejected.
Response: 201 with {"status": "created", "name": "my-skill"}, or 200 with {"status": "updated", "name": "my-skill"} on update. 413 if body_too_large.
Delete Skill
DELETE /api/v1/marketplace/:name/:author
Delete a published skill. Author or admin only.
Response: 200 with {"status": "deleted"}; 403 if not the author or admin; 404 if not found.
Report Skill
POST /api/v1/marketplace/:name/:author/report
Report a skill for moderation. Auth required.
Request body: {"reason": "description of issue"}
Response: 201 with {"report_id": "..."}.
Admin: Reports
GET /api/v1/marketplace/reports
List pending reports. Admin only.
{
"reports": [
{"id": "...", "skill_name": "...", "author_uuid": "...", "reporter_uuid": "...", "reason": "...", "timestamp": 1745600000000}
]
}
Admin: Dismiss Report
POST /api/v1/marketplace/reports/:id/dismiss
Dismiss a report by id. Admin only.
Response: 200 with {"status": "dismissed"}.
Admin: Feature Skill
POST /api/v1/marketplace/feature
Feature or unfeature a skill. Admin only.
Request body: {"name": "...", "author": "...", "featured": true}
Rate Skill
POST /api/v1/marketplace/rate
Rate a skill. Auth required (401 authentication_required without a
session), no rate limiter on this endpoint, one rating per user per skill.
Request body: {"name": "...", "author": "...", "rating": 5, "review": "..."}
Responses: 201 {"status": "created"} · 409 duplicate_rating
(re-rating is a 409, not an update) · 400 missing_fields · 400
invalid_rating.
Skill Ratings
GET /api/v1/marketplace/ratings?name=NAME&author=AUTHOR
Get aggregate ratings for a skill. Both name and author are required —
either missing answers 400 missing_name_or_author.
{"ratings": [{"user_uuid": "...", "rating": 5, "review": "...", "created_at": 1745600000000}], "avg_rating": 4.5, "rating_count": 1}
Memory API
Canonical reference: docs/api-reference.md (generated endpoint directory) — this page is a task-oriented summary.
Memory and embedding endpoints for persistent vector storage. The backend uses PostgreSQL with pgvector for similarity search and ETS for fast key-value access.
Overview
The memory system provides two storage modes:
| Mode | Backend | Use Case |
|---|---|---|
| Key-value | ETS + WAL | Fast TTL-based caching, reflections |
| Vector search | PostgreSQL + pgvector | Semantic similarity search |
Memory entries are scoped to agent_id and user_uuid. Users can only access their own entries unless they are admin.
Store a Memory Entry
POST /api/v1/memory/store
Store a key-value pair with optional embedding and TTL. The agent_id is supplied in the request body (not as a path parameter); it defaults to "default" when absent.
Request
{
"agent_id": "research-bot",
"key": "lesson_learned_42",
"value": "Always validate input before processing in Erlang",
"ttl": 86400,
"embedding": [0.1, 0.2, 0.3, 0.4]
}
| Field | Required | Description |
|---|---|---|
key | Yes | Unique key within the agent’s namespace |
value | Yes | String value to store |
agent_id | No | Agent namespace (default "default", max 128 chars) |
ttl | No | Time-to-live in seconds (0 = no expiry, negative rejected). Values above one year are clamped to 365 days |
embedding | No | Pre-computed embedding vector. Auto-generated if omitted |
Response
{
"status": "ok"
}
If no embedding is provided, the system auto-generates one from the value using the configured embedding model. Embedding generation is best-effort and does not fail the store operation.
Retrieve a Memory Entry
GET /api/v1/memory/:agent_id/:key
Retrieve a stored memory entry by key.
Response
{
"key": "lesson_learned_42",
"value": "Always validate input before processing in Erlang",
"created_at": 1716192000000
}
Error Responses
| Code | Description |
|---|---|
| 404 | Key not found |
| 410 | Entry has expired |
| 503 | Memory service disabled |
Delete a Memory Entry
DELETE /api/v1/memory/:agent_id/:key
Delete a specific memory entry. Only the owner can delete entries.
Response
{
"status": "ok"
}
Search Memory
GET /api/v1/memory/:agent_id/search?q=<query>&limit=20
Full-text search across memory entries for an agent. Answers the standard
Paginated envelope (not a bare results list).
Parameters
| Parameter | Default | Description |
|---|---|---|
q | (required) | Search query string |
limit | 20 | Maximum results (clamped 0..200) |
offset | 0 | Pagination offset |
Response
{
"items": [
{
"key": "lesson_learned_42",
"value": "Always validate input before processing in Erlang",
"created_at": 1716192000000
}
],
"total": 1,
"limit": 20,
"offset": 0,
"page": 1,
"total_pages": 1,
"has_more": false
}
Vector Search
POST /api/v1/memory/:agent_id/vector-search
Semantic similarity search using pgvector. Requires pgvector to be enabled.
Request (by text)
{
"text": "input validation best practices",
"limit": 10,
"threshold": 0.75
}
Request (by embedding)
{
"embedding": [0.1, 0.2, 0.3, 0.4],
"limit": 10,
"threshold": 0.75
}
| Field | Required | Description |
|---|---|---|
text | One of text/embedding | Query text (auto-embedded) |
embedding | One of text/embedding | Pre-computed embedding vector (all elements must be numbers — 400 otherwise) |
limit | No | Maximum results (default: 20; must be an integer in 1..200 — 400 otherwise) |
threshold | No | Minimum similarity score 0.0–1.0 (default: 0.75 — out-of-range answers 400) |
Response
{
"results": [
{
"key": "lesson_learned_42",
"value": "Always validate input before processing in Erlang",
"similarity": 0.92
}
]
}
List Memory Entries
GET /api/v1/memory/:agent_id
Paginated list of all memory entries for an agent (no /list suffix).
Parameters
| Parameter | Default | Description |
|---|---|---|
limit | 50 | Maximum entries per page (clamped 0..200) |
offset | 0 | Pagination offset |
Only
limit/offsetare read on this route —page/per_pageare NOT supported here (the handler parses the query itself rather than using the shared parser).
Response
{
"items": [
{
"key": "lesson_learned_42",
"value": "Always validate input before processing in Erlang",
"created_at": 1716192000000
}
],
"total": 1,
"limit": 50,
"offset": 0,
"page": 1,
"total_pages": 1,
"has_more": false
}
Clear Memory
POST /api/v1/memory/:agent_id/clear
Delete memory entries for an agent. A non-admin caller wipes only their
OWN rows inside the agent namespace; an admin wipes the whole namespace.
(A request with neither identity scope signal answers 404 — deliberately
indistinguishable from an absent agent.) The legacy DELETE verb is not
accepted on this route — it is POST-enforced.
Response
{
"status": "ok"
}
Pin a Memory Entry
POST /api/v1/memory/:agent_id/:key/pin
Pin or unpin a memory entry. Pinned entries are exempt from importance decay.
Request
{
"pinned": true
}
Response
{
"status": "ok",
"pinned": true
}
Get Reflections
GET /api/v1/memory/:agent_id/reflections
Retrieve memory entries with keys matching reflection:*. Filtered by user
ownership. Answers the standard paginated envelope (limit default 50,
clamped 0..200, offset supported):
{
"items": [
{
"key": "reflection:session_42",
"value": "The user prefers concise explanations"
}
],
"total": 1,
"limit": 50,
"offset": 0,
"page": 1,
"total_pages": 1,
"has_more": false
}
Memory Statistics
GET /api/v1/memory/stats
Admin-only (403 otherwise). Returns global memory usage statistics:
{
"enabled": true,
"total_entries": 1500
}
A per-agent variant also exists — GET /api/v1/memory/:agent_id/stats
(ownership-filtered) answers {"agent_id": "...", "key_count": N, "total_size": bytes}.
Trigger Importance Decay
POST /api/v1/memory/:agent_id/decay
Admin only. Manually trigger the importance decay process for a specific agent’s memory namespace, reducing the relevance of old, unpinned entries.
Response
{
"status": "ok",
"forgotten": 23
}
Agent ID
The agent_id path parameter identifies the memory namespace. Default is "default". Maximum length is 128 characters.
User Scoping
Memory entries are tagged with user_uuid at store time. The following rules apply:
Non-admin users see only their own entries
Admin users see all entries
System entries (no user_uuid, the "system" placeholder) are visible
only to the system caller — a regular user does NOT see them
Ownership is checked on retrieve, delete, pin, and clear operations; a
foreign overwrite or delete answers 404 (never 403 — no existence
oracle for foreign keys)
When the memory subsystem is disabled the handlers answer 503 with
{"error": "memory_subsystem_disabled", "enabled": false} (a documented
flat shape, not the standard envelope).
Messages API
Canonical reference: docs/api-reference.md (generated endpoint directory) — this page is a task-oriented summary.
ZERG exposes an Anthropic Messages API compatible endpoint. This enables Anthropic SDK clients and tooling to target ZERG directly.
Overview
The /v1/messages endpoint mirrors the Anthropic wire format. ZERG translates the request to the configured provider and returns Anthropic-formatted responses. Supports streaming via SSE for token-by-token output.
Authentication
Requires Authorization: Bearer <token> (cookie auth also accepted for browser sessions). Tokens are issued by Mango. x-api-key is also accepted as a bearer-equivalent credential. Unauthenticated calls return 401.
Endpoints
Create Message
POST /v1/messages
Request Body:
{
"model": "claude-sonnet-4-20250514",
"max_tokens": 1024,
"messages": [
{ "role": "user", "content": "Explain quicksort" }
],
"system": "You are a helpful assistant.",
"temperature": 0.7,
"stream": false
}
Response (non-streaming):
{
"id": "msg_abc123",
"type": "message",
"role": "assistant",
"content": [
{ "type": "text", "text": "Quicksort is a divide-and-conquer algorithm..." }
],
"model": "claude-sonnet-4-20250514",
"stop_reason": "end_turn",
"stop_sequence": null,
"usage": {
"input_tokens": 42,
"output_tokens": 156
}
}
Supported Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
model | string | required | Model identifier from the model catalog |
messages | array | required | Array of message objects |
max_tokens | integer | required | Maximum tokens in the response |
system | string | — | System prompt |
temperature | float | — | Sampling temperature |
stream | boolean | false | Enable SSE streaming (this endpoint defaults to non-streaming; the OpenAI leg defaults to true) |
stop_sequences | string[] | — | Custom stop sequences |
top_p | float | — | Nucleus sampling |
top_k | integer | — | Top-k sampling |
tools | array | — | Tool definitions (see Tool Use) |
tool_choice | string | — | Tool selection: auto, any, none |
thinking | object | — | Extended thinking config {type: "enabled", budget_tokens: 2048} |
response_format | object | — | Structured-output request, forwarded on the provider wire |
metadata | object | — | Metadata with user_id |
stream_options | object | {"include_usage": true} | Stream options on the OpenAI wire |
Streaming (stream: true):
Returns SSE events following the Anthropic streaming format:
event: message_start
data: {"type": "message_start", "message": {...}}
event: content_block_start
data: {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}
event: content_block_delta
data: {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "Quicksort"}}
event: message_stop
data: {"type": "message_stop"}
Tool Use:
ZERG supports tool definition and execution through the Anthropic tool schema. Tools defined in the request are executed by the Luna agent runtime.
{
"tools": [{
"name": "web_search",
"description": "Search the web",
"input_schema": {
"type": "object",
"properties": {
"query": { "type": "string" }
}
}
}]
}
Error Codes (every HTTP error speaks the Anthropic {"type":"error",...} envelope — the flat {"error":"..."} shape is gone):
| Code | Description | Body |
|---|---|---|
| 400 | Invalid request body, missing model/messages, or malformed tool blocks | {"type":"error","error":{"type":"invalid_request_error","message":"..."}} |
| 401 | Missing or invalid authentication | {"type":"error","error":{"type":"authentication_error","message":"..."}} |
| 403 | Insufficient permissions | {"type":"error","error":{"type":"permission_error","message":"..."}} |
| 404 | Model not found or unavailable | {"type":"error","error":{"type":"not_found_error","message":"..."}} |
| 409 | Task cancelled before completion (non-streaming waiter) | {"type":"error","error":{"type":"invalid_request_error","message":"..."}} |
| 429 | Provider key exhausted or SSE budget full | {"type":"error","error":{"type":"rate_limit_error","message":"..."}} |
| 500 | The task itself failed/crashed (non-streaming waiter) | {"type":"error","error":{"type":"api_error","message":"..."}} |
| 502 | Upstream connect failure | {"type":"error","error":{"type":"api_error","message":"..."}} |
| 503 | All circuits open / provider unavailable | {"type":"error","error":{"type":"overloaded_error","message":"all circuits open"}} |
| 504 | Upstream timeout family (timeout, first_token_timeout, idle_timeout) | {"type":"error","error":{"type":"overloaded_error","message":"..."}} |
Usage-absence semantics: usage is reported only when the provider
actually emitted it — output tokens are never fabricated.
Example:
curl http://127.0.0.1:21434/v1/messages \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"model": "claude-sonnet-4-20250514",
"max_tokens": 500,
"messages": [{"role": "user", "content": "Write a poem"}]
}'
Models API
Canonical reference: docs/api-reference.md (generated endpoint directory) — this page is a task-oriented summary.
Model listing and provider health endpoints. ZERG aggregates models from local llama.cpp instances and all configured providers, then serves a unified catalog.
Overview
The models API provides read access to the model catalog (provider, context window, capabilities, pricing). There is no provider CRUD — providers are configured declaratively (in sys.config or priv/providers/*.json) and reloaded with the reload endpoint. Provider health is exposed read-only.
Authentication
All endpoints require Authorization: Bearer <token>. The reload endpoint requires admin role.
Endpoints
List Models
GET /api/v1/models
Returns all available models (local + provider), paginated. Local models carry slug/family/quant/size/status/source: "local" plus model_slug/lane/engine for lane rows. Provider models carry id/source: "provider"/canonical_model/provider_model/dispatchable/alias?/provider/context_window/capabilities/pricing/modalities?.
{
"items": [
{
"id": "claude-sonnet-4-20250514",
"source": "provider",
"canonical_model": "claude-sonnet-4-20250514",
"provider_model": "claude-sonnet-4-20250514",
"dispatchable": true,
"provider": "anthropic",
"context_window": 200000,
"capabilities": { },
"pricing": { },
"modalities": ["text", "image"]
}
],
"total": 1,
"limit": 50,
"offset": 0,
"page": 1,
"total_pages": 1,
"has_more": false
}
Get Model Details
GET /api/v1/models/:name
Returns detailed information for a single local model. The response is an explicit projection: non-admin callers get the public field set id (the registry slug), family, quant, size, status and context_window (each only when known) — never paths, config, port or runtime refs. Admin callers get the operator record (sol_registry:show/1 with atom values rendered), including paths, config, port and inference_ref. Unknown names answer 404; store-down is 503 (remote 502), never a blanket 500. Provider-sourced models are listed via the catalog endpoint above.
Provider Health
GET /api/v1/providers/health
Probes every provider transport identity (provider/key/endpoint) concurrently (each probe has a 5s timeout, collective 10s deadline) and returns the cached status (cached for 60 seconds). Models/aliases sharing an identity collapse into one row with a models list; a row with no endpoint is unconfigured and is never probed. SSRF-guarded — endpoints resolving to private/loopback/link-local IPs are rejected. Paginated (items plus the providers mirror).
{
"items": [
{"name": "anthropic", "models": ["claude-sonnet-4-20250514"], "endpoint": "https://api.anthropic.com", "path": "/v1/messages", "key_id": "anthropic", "wire": "anthropic", "status": "available", "checked_at_ms": 1760000000000}
],
"total": 1,
"limit": 50,
"offset": 0,
"page": 1,
"total_pages": 1,
"has_more": false,
"providers": [
{"name": "anthropic", "models": ["claude-sonnet-4-20250514"], "endpoint": "https://api.anthropic.com", "path": "/v1/messages", "key_id": "anthropic", "wire": "anthropic", "status": "available", "checked_at_ms": 1760000000000}
]
}
Status values: available (2xx/3xx/404/405/429 — reachable), available_unauthorized (401/403 — reachable, credential problem), degraded (5xx), unavailable (transport/timeout), ssrf_rejected, unconfigured (no endpoint).
Single Provider Health
GET /api/v1/providers/health/:name
Returns the health status for one provider.
{
"name": "anthropic",
"models": ["claude-sonnet-4-20250514"],
"endpoint": "https://api.anthropic.com",
"path": "/v1/messages",
"key_id": "anthropic",
"wire": "anthropic",
"status": "available",
"checked_at_ms": 1760000000000
}
404 with the Zerg envelope {"ok":false,"error":{"code":"provider_not_found","message":"<name>"}} if the provider is not registered.
Reload Providers
POST /api/v1/providers/reload
Admin only. Re-reads the declarative provider JSON files (priv/providers/*.json) and re-registers their models without a restart.
Error Codes:
| Code | Description |
|---|---|
| 401 | Authentication required |
| 403 | Admin role required for reload |
| 404 | Model or provider not found |
| 503 | Provider health cache not ready |
Examples:
curl http://127.0.0.1:21434/api/v1/models \
-H "Authorization: Bearer $TOKEN"
curl http://127.0.0.1:21434/api/v1/providers/health/anthropic \
-H "Authorization: Bearer $TOKEN"
curl -X POST http://127.0.0.1:21434/api/v1/providers/reload \
-H "Authorization: Bearer $TOKEN"
Scheduler API
Canonical reference: docs/api-reference.md (generated endpoint directory) — this page is a task-oriented summary.
Manage scheduled jobs for automated task execution. Supports cron, every
(recurring interval), and at (one-time timestamp) schedules, plus
natural-language scheduling and missed-job catch-up on restart.
The base path is singular:
/api/v1/schedule(not/schedules). All scheduler endpoints share this prefix. Job creation isPOST /api/v1/schedule/spawn(notPOST /api/v1/schedule).
Overview
The scheduler runs as a gen_server with an ETS-backed job store. Jobs are
attributed to the creating user (user_uuid) and dispatch tasks to workers at
the scheduled time. Most mutating endpoints require admin (the "*"
permission).
| Schedule Type | Field | Description | Use Case |
|---|---|---|---|
cron | cron | 5-field cron expression | Periodic tasks on a calendar schedule |
every | every | Interval in milliseconds (must be > 0) | Recurring tasks at fixed intervals |
at | at | One-time timestamp in ms | Delayed single execution |
Endpoints
List Scheduled Jobs
GET /api/v1/schedule
Returns all scheduled jobs. Admin-only — non-admin callers receive an empty paginated list (not an error). Paginated via the standard envelope.
Response (200):
{
"items": [
{
"id": 1,
"name": "Daily health check",
"schedule_type": "cron",
"cron_expr": "0 9 * * *",
"interval_ms": null,
"at_ms": null,
"next_run_ms": 1716192000000,
"last_run_ms": 1716105600000,
"status": "active",
"prompt": "Check system health and report any issues",
"model": "glm-5.1",
"opts": {},
"delete_after_run": false,
"consecutive_errors": 0,
"enabled": true,
"currently_running": false,
"tz": "UTC"
}
],
"total": 1,
"limit": 50,
"offset": 0,
"page": 1,
"total_pages": 1,
"has_more": false
}
Create a Scheduled Job
POST /api/v1/schedule/spawn
Create a new scheduled job. Admin-only (enforced by the {admin, require}
middleware scope, ).
Cron example:
{
"name": "Daily health check",
"prompt": "Check system health and report any issues",
"cron": "0 9 * * *",
"model": "glm-5.1",
"opts": {}
}
Every example:
{
"name": "Monitor queue depth",
"prompt": "Check ZMQ queue depth and alert if > 100",
"every": 300000
}
One-time example:
{
"name": "Deploy notification",
"prompt": "Announce deployment completion",
"at": 1716192000000,
"delete_after_run": true
}
Natural-language example (resolved server-side via sol_nl_schedule):
{
"name": "Weekly report",
"prompt": "Generate weekly system report",
"schedule": "every monday at 9am"
}
Request Fields
| Field | Required | Description |
|---|---|---|
prompt | Yes | Task prompt to send when the job fires. Empty → 400. |
name | No | Human-readable job name. |
cron | One of cron/every/at (or schedule) | 5-field cron expression. |
every | One of cron/every/at (or schedule) | Interval in ms (positive integer). |
at | One of cron/every/at (or schedule) | Unix timestamp in ms (integer). Past timestamps are accepted but logged. |
schedule | Alternative to cron/every/at | Natural-language string parsed by sol_nl_schedule. |
model | No | Model to use for the task. |
opts | No | Additional task options. Identity-bearing keys (user_uuid, permissions, listener, owner, task_id, container_id, plugin) are stripped from user input. |
delete_after_run | No | Auto-delete after execution. at jobs only — rejected for cron/every. |
Response (200)
{
"status": "ok",
"id": 42,
"next_run": 1716192000000
}
Error Responses
All error bodies speak the Zerg envelope — {"ok":false,"error":{"code":"…","message":"…"}} — where the table shows <code> inside error.code.
| Code | Body (error.code) | Condition |
|---|---|---|
| 400 | missing prompt | Empty prompt. |
| 400 | must specify at, every, or cron | None of the schedule keys provided. |
| 400 | at must be a positive integer (ms timestamp) | at not an integer. |
| 400 | every must be a positive integer (ms) | every not a positive integer. |
| 400 | invalid cron expression | cron failed sol_cron:parse/1. |
| 400 | delete_after_run only supported for 'at' jobs | delete_after_run: true on non-at schedule. |
| 400 | <create error> | sol_scheduler:create_job/1 returned an error. |
| 403 | insufficient_permissions | Non-admin caller (middleware, {admin, require} scope). |
| 429 | internal_error (see note) | Global cap max_scheduled_jobs (1000) or per-user quota max_scheduled_jobs_per_user (100) reached. |
429 note: the quota arms correctly answer 429 (capacity is never a 500), but the handler currently routes the quota reason through the generic error mapper, so the body carries the
internal_errorcode instead of a dedicated quota code. Dispatch on the status, not the code, on these arms. (Flagged for canonical-side repair.)
Get Job Detail
GET /api/v1/schedule/:id
Returns details for a single scheduled job. Admin-only — the job’s
prompt and opts are not disclosed to non-admin callers (403).
Response (200):
{
"id": 1,
"name": "Daily health check",
"schedule_type": "cron",
"cron_expr": "0 9 * * *",
"interval_ms": null,
"at_ms": null,
"next_run_ms": 1716192000000,
"last_run_ms": 1716105600000,
"status": "active",
"prompt": "Check system health and report any issues",
"model": "glm-5.1",
"opts": {},
"delete_after_run": false,
"consecutive_errors": 0,
"enabled": true,
"currently_running": false,
"tz": "UTC",
"anchor_ms": 1716000000000
}
anchor_msis included only when set (used to anchor drift-corrected intervals).tzis always"UTC"— all cron/at/every scheduling is naive UTC. All time fields use the_mssuffix (milliseconds).
Error Responses:
| Code | Body (error.code) | Condition |
|---|---|---|
| 400 | invalid id | :id not parseable as an integer. |
| 403 | forbidden | Non-admin caller. |
| 404 | job not found | Unknown id. |
Delete a Scheduled Job
DELETE /api/v1/schedule/:id
Cancel and remove a scheduled job. Admin-only.
Response (200):
{ "status": "deleted" }
Error Responses:
| Code | Body (error.code) | Condition |
|---|---|---|
| 400 | invalid id | :id not an integer. |
| 403 | forbidden | Non-admin. |
| 404 | job not found | Unknown id. |
| 409 | job currently running | Job is mid-execution. |
Pause a Job
POST /api/v1/schedule/:id/pause
Pause a scheduled job without deleting it. The job will not fire until
/unpause is called. Admin-only.
Response (200):
{ "status": "paused" }
Error Responses:
| Code | Body (error.code) | Condition |
|---|---|---|
| 400 | invalid id | :id not an integer. |
| 403 | forbidden | Non-admin. |
| 404 | job not found | Unknown id. |
Unpause a Job
POST /api/v1/schedule/:id/unpause
Resume a paused job. Admin-only.
Response (200):
{ "status": "active" }
Error Responses: same shape as pause (400 / 403 / 404), plus one
extra 400 arm: an unreachable schedule (no reachable fire time, e.g. an
impossible cron that survived an older create) is rejected at unpause time
and
the job stays disabled.
Trigger a Job Immediately
POST /api/v1/schedule/:id/run
Trigger immediate execution of a scheduled job, regardless of its schedule. Admin-only.
Response (200):
{ "status": "dispatched" }
Error Responses:
| Code | Body (error.code) | Condition |
|---|---|---|
| 400 | invalid id | :id not an integer. |
| 400 | job is disabled, unpause first | Job is currently paused. |
| 403 | forbidden | Non-admin. |
| 404 | job not found | Unknown id. |
| 409 | job already running | Job is mid-execution. |
Job Object Shape
Every job endpoint that returns a single job or a list of jobs uses the same
shape produced by sol_http_json:schedule_job_to_json/1:
| Field | Type | Description |
|---|---|---|
id | integer | Job id. |
name | string | Human-readable name. |
schedule_type | string | cron | every | at (atom stringified). |
cron_expr | string|null | Cron expression (only for cron). |
interval_ms | integer|null | Interval (only for every). |
at_ms | integer|null | Timestamp (only for at). |
next_run_ms | integer|null | Next scheduled run, ms. |
last_run_ms | integer|null | Last run, ms. |
status | string | active | paused (atom stringified). |
prompt | string | The prompt dispatched at fire time. |
model | string|null | Model override. |
opts | object | Task options. |
delete_after_run | boolean | Auto-delete after run (at only). |
consecutive_errors | integer | Error streak (auto-pause at 10). |
enabled | boolean | Whether the job is enabled. |
currently_running | boolean | Whether the job is mid-execution. |
tz | string | Always "UTC" — scheduling is naive UTC. |
anchor_ms | integer|omitted | Drift anchor (only when set). |
Missed-Job Detection
The scheduler detects jobs that missed their scheduled time during downtime. On startup:
- All stored jobs are loaded from ETS.
- Jobs with
next_run_msin the past are identified. - Up to 5 missed jobs are dispatched with a 5-second stagger.
- Jobs with 10+ consecutive errors are automatically paused.
This ensures tasks are not permanently lost after server restarts.
Limits
| Parameter | Default | Description |
|---|---|---|
max_scheduled_jobs | 1000 | Global maximum active jobs (429 on exceed) |
max_scheduled_jobs_per_user | 100 | Per-user quota of active jobs |
max_consecutive_errors | 10 | Auto-pause threshold |
max_catchup_runs | 5 | Missed jobs dispatched on startup |
catchup_stagger_ms | 5000 | Delay between catch-up dispatches |
timer_clamp_ms | 60000 | Maximum timer precision |
max_dispatch_per_tick | 5 | Jobs dispatched per scheduler tick |
Cron Expression Format
5-field cron expressions:
┌───────────── minute (0-59)
│ ┌───────────── hour (0-23)
│ │ ┌───────────── day of month (1-31)
│ │ │ ┌───────────── month (1-12)
│ │ │ │ ┌───────────── day of week (0-6, 0=Sunday)
│ │ │ │ │
* * * * *
| Expression | Meaning |
|---|---|
0 9 * * * | Every day at 09:00 |
*/5 * * * * | Every 5 minutes |
0 */2 * * * | Every 2 hours |
0 9 * * 1 | Every Monday at 09:00 |
0 0 1 * * | First of every month at midnight |
User Attribution
Each job records the user_uuid of the creating user (captured at creation time
from sol_identity:get_uuid/0). When the job fires, the task is dispatched with
this user_uuid, ensuring proper ownership of results. Permissions are also
captured at creation time and replayed at fire time.
Session Sharing API
Canonical reference: docs/api-reference.md (generated endpoint directory) — this page is a task-oriented summary.
Create shareable links to exported agent sessions. A share stores serialized session data under a share_id; anyone with the share id can view the public endpoint.
Overview
Session sharing generates a unique share_id for the posted session data. Shares expire after an optional TTL (defaults to the server’s retention). The share data is stored in Mnesia.
Capability-token model: the share_id IS the capability. The public view endpoint is unauthenticated BY DESIGN — possessing the unguessable id (256-bit random) is the authorization; there is no separate ACL. The API never emits expires_at — expiry is internal state, so derive any client-side expiry from the ttl_days you sent.
TTL clamp: ttl_days is clamped server-side to min(ttl_days, 365) — a larger request still succeeds but lives at most one year (loud server warning on clamp).
Quota: creates are bounded per user (share_quota_per_user, default 100 live shares). At the quota the create answers 429 with code share_quota_exceeded and a retry-after: 3600 header (the hourly cleanup cadence frees slots).
Authentication
Create and delete operations require Authorization: Bearer <token>. The public view endpoint (/api/v1/shares/:share_id) does not require authentication — by design (capability model above); it is per-IP rate limited and every read is logged (share id + peer IP).
Endpoints
Create Share
POST /api/v1/sessions
Export session data into a new share. Auth required.
Request Body:
{
"session_data": { },
"format": "json",
"ttl_days": 7
}
session_data is required; format and ttl_days are optional.
Response: 201
{
"share_id": "shr-xyz789"
}
url is only included when the operator has configured base_url (sys.config or SOL_BASE_URL); otherwise only share_id is returned and the client constructs the URL. There is no expires_at field (capability-model note above).
Get Share (authenticated)
GET /api/v1/sessions/:share_id
Returns the stored share data. Answers 404 for an expired share (same
as an unknown id —, ).
{
"data": { },
"format": "json",
"created_at": 1745600000
}
View Shared Session (public)
GET /api/v1/shares/:share_id
Public endpoint — no authentication required. Returns the same shape as the authenticated get:
{
"data": { },
"format": "json",
"created_at": 1745600000
}
404 if the share expired or was never created — expired and unknown ids
are indistinguishable on the public surface.
Delete Share
DELETE /api/v1/sessions/:share_id
Removes a share. Only the share owner or an admin can delete it.
{
"deleted": "shr-xyz789"
}
403 if not the owner/admin; 404 if not found — expired shares are
indistinguishable from never-existed on EVERY share leg since
.
Error Codes:
| Code | Description |
|---|---|
| 401 | Authentication required for create/delete |
| 403 | Not the share owner |
| 404 | Share not found (expired and never-existed are indistinguishable) |
| 429 | Per-user share quota exhausted (share_quota_exceeded, retry-after: 3600) |
| 429 | Public read rate limited per IP (rate_limited) |
Examples:
curl -X POST http://127.0.0.1:21434/api/v1/sessions \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"session_data": {"messages": []}, "ttl_days": 7}'
curl http://127.0.0.1:21434/api/v1/shares/shr-xyz789
curl -X DELETE http://127.0.0.1:21434/api/v1/sessions/shr-xyz789 \
-H "Authorization: Bearer $TOKEN"
Supervisor API
Canonical reference: docs/api-reference.md (generated endpoint directory) — this page is a task-oriented summary.
Introspect the Erlang/OTP supervisor tree at runtime. View child processes, their states, and restart counts for debugging and operations.
Overview
The supervisor tree is the backbone of ZERG’s fault tolerance. This API exposes the runtime supervision hierarchy, allowing operators to inspect which supervisors are running, their child specifications, restart strategies, and process states without accessing the Erlang shell.
Authentication
Requires Authorization: Bearer <token> with the metrics:read
permission (admins pass via "*").
Endpoints
Supervisor Tree
GET /api/v1/supervisor/tree
Returns the recursive tree rooted at the fixed top-level supervisor sol_sup (no :name parameter). Each node carries child counts; each child entry carries its id, pid, type, and modules.
Response:
{
"name": "sol_sup",
"specs": 12,
"active": 12,
"children": [
{
"id": "sol_zmq_gateway",
"pid": "<0.123.0>",
"type": "worker",
"modules": ["sol_zmq_gateway"]
},
{
"id": "sol_owners_sup",
"pid": "<0.100.0>",
"type": "supervisor",
"modules": ["sol_owners_sup"]
}
]
}
pid may be a pid string, "restarting", or "undefined".
List Supervisor Children
GET /api/v1/supervisor/children/:name
Returns the direct children of a named supervisor (e.g., sol_sup, sol_infra_sup, sol_owners_sup).
Response:
{
"name": "sol_sup",
"children": [
{
"id": "sol_zmq_gateway",
"pid": "<0.123.0>",
"type": "worker",
"modules": ["sol_zmq_gateway"]
}
]
}
404 if the supervisor name does not resolve to a registered atom.
Available Supervisors:
| Name | Strategy | Purpose |
|---|---|---|
sol_sup | rest_for_one | Top-level supervisor |
sol_infra_sup | one_for_one | Infrastructure (compactor, autoscaler) |
sol_owners_sup | one_for_one | ETS heir owners (32 owner processes, machine-derived count) |
sol_zmq_pipeline_sup | simple_one_for_one | ZMQ pipeline workers |
sol_inference_sup | simple_one_for_one | llama.cpp inference instances |
sol_workflow_sup | simple_one_for_one | Workflow instances |
Error Codes:
| Code | Description |
|---|---|
| 401 | Authentication required |
| 403 | metrics:read permission required |
| 404 | Supervisor not found |
Examples:
curl http://127.0.0.1:21434/api/v1/supervisor/tree \
-H "Authorization: Bearer $TOKEN"
curl http://127.0.0.1:21434/api/v1/supervisor/children/sol_infra_sup \
-H "Authorization: Bearer $TOKEN"
Teams API
Canonical reference: docs/api-reference.md (generated endpoint directory) — this page is a task-oriented summary.
Team management for multi-agent collaboration. Spawn teams of persistent agents that communicate and coordinate on shared tasks.
Overview
Teams are groups of persistent Luna agents that share a work queue and can communicate via the agent mailbox system. Each team has a configurable size (default 3, max 10). Teammates persist across multiple tasks until stop_team is called. Teams use ACP for inter-agent messaging.
Authentication
Requires Authorization: Bearer <token>. Team create/destroy and member/mail mutations are gated to the team creator or an admin (teams:manage at the middleware; ensure_team_mutator handler-side); team detail, members list, and mail read (incl. ?mine=1) are open to members whose user_uuid matches the caller, plus owner/admin.
Endpoints
Create Team
POST /api/v1/teams
Admin only. Creates a new team from a name plus options. Returns 201 on success.
Request Body:
{
"name": "research-team",
"size": 3,
"model": "claude-sonnet-4-20250514",
"mode": "coordinate",
"system_prompt": "You are a research team. Collaborate on literature review."
}
Response:
{
"ok": true,
"team_id": "team-abc123"
}
403 if not admin; 400 if name is missing.
List Teams
GET /api/v1/teams
Returns all teams.
{
"ok": true,
"teams": [ ]
}
Get Team Details
GET /api/v1/teams/:id
Returns team status, member agents, and queue depth. Creator, admin, or team members.
Destroy Team
DELETE /api/v1/teams/:id
Admin or team creator. Stops all team members and cleans up resources.
{
"ok": true,
"team_id": "team-abc123"
}
List Members
GET /api/v1/teams/:id/members
Returns the team’s member list. Creator, admin, or team members.
{
"ok": true,
"members": [ ]
}
Add Member
POST /api/v1/teams/:id
POST /api/v1/teams/:id/members
Admin or team creator. Both route forms dispatch the same add_member
action. Body must include worker_id.
{ "worker_id": "agent-4", "role": "researcher" }
Response: { "ok": true, "member_id": "..." }.
Remove Member
DELETE /api/v1/teams/:id/members/:worker_id
Admin or team creator. Removes a worker from the team (accepts either the canonical tm_* id or the member’s worker_id). Response: { "ok": true }.
Read Team Mail
GET /api/v1/teams/:id/mail
Returns all mailbox messages for the team. Creator, admin, or team members (?mine=1 scopes to the caller’s own mail).
{
"ok": true,
"messages": [ ]
}
Send Team Mail
POST /api/v1/teams/:id/mail
Admin or team creator. Posts a message to the team mailbox. Body must include body; from, to, subject, priority are optional (to defaults to all, priority to normal).
{ "from": "agent-1", "to": "all", "subject": "sync", "body": { }, "priority": "normal" }
Response: { "ok": true, "msg_id": "..." }.
Acknowledge Team Mail
POST /api/v1/teams/:id/mail/:message_id/ack
Admin or team creator. Marks one mailbox message acknowledged
. Response:
{ "ok": true }; 404 wrong_team when the message does not belong to the
team.
Team Communication:
Agents within a team communicate through the agent mailbox system (agent_mailbox.lua). Messages are routed via ACP:
Agent A ──send──► Mailbox A ──► TeamQueue ──► Agent B
Agent C
The team queue (team_queue.lua) provides FIFO work distribution with get_idle/mark_busy/mark_idle states. Teammates poll for work every 500ms.
Error Codes:
| Code | Description |
|---|---|
| 400 | Invalid team parameters |
| 401 | Authentication required |
| 404 | Team not found |
| 409 | Team already at max size |
Examples:
curl -X POST http://127.0.0.1:21434/api/v1/teams \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"name": "research", "size": 3, "model": "claude-sonnet-4-20250514"}'
curl http://127.0.0.1:21434/api/v1/teams/team-abc123/members \
-H "Authorization: Bearer $TOKEN"
Workers API
Canonical reference: docs/api-reference.md (generated endpoint directory) — this page is a task-oriented summary.
REST endpoints for managing ZMQ workers, local JSONL agents, dispatching tasks, and orchestrating multi-task fan-out. ZMQ workers connect as DEALER sockets to Sol’s ROUTER on port 5555 and communicate using msgpack over ZMTP. Local JSONL agents are supervised child processes spoke to over stdio.
All endpoints require a Bearer token when authentication is enabled. Admin-only
operations (spawn, kill, dispatch) require the "*" permission.
ZMQ Workers
List ZMQ Workers
GET /api/v1/zmq/workers
Returns all currently connected ZMQ workers with their status and capabilities. Paginated.
Response (200):
{
"items": [
{
"worker_id": "luna-worker-1",
"status": "ready",
"capabilities": ["lua", "streaming", "tools"],
"connected_at": 1716192000000,
"last_heartbeat": 1716192100000,
"current_task": null
}
],
"total": 1,
"limit": 50,
"offset": 0,
"page": 1,
"total_pages": 1,
"has_more": false
}
status is stringified from the internal atom (ready, busy, stale,
disconnected). Pagination uses the standard envelope — see
Overview.
CLI:
zerg zmq-workers
ZMQ Gateway Status
GET /api/v1/zmq/status
Returns the ZMQ gateway configuration and live state. Includes the sender/events liveness probes so a dead send path is visible from the API (without reading the supervisor log).
Response (200):
{
"enabled": true,
"port": 5555,
"connected": 2,
"queue_depth": 0,
"sender_alive": true,
"events_alive": true,
"sender_socket_alive": true
}
| Field | Description |
|---|---|
enabled | Whether the ZMQ gateway is running. |
port | ROUTER socket bind port. |
connected | Number of currently connected workers. |
queue_depth | Pending tasks in the dispatch queue. |
sender_alive | + — sol_zmq_sender gen_server is alive. |
events_alive | + — sol_zmq_events gen_server is alive. |
sender_socket_alive | + — the underlying sender socket process is alive. When false, dispatches will hang (noproc on send_sync); check the supervisor log. |
When the gateway is down or throws, the endpoint still returns 200 with the
safe fallback body {"enabled":false,"connected":0,"queue_depth":0} rather
than a 5xx.
CLI:
zerg zmq-status
Dispatch Task to a Worker
POST /api/v1/zmq/dispatch
Dispatch a task to an available ZMQ worker. The gateway routes to the first ready worker.
Request Body:
{
"prompt": "Analyze the codebase and report issues",
"model": "glm-5.1",
"stream": true,
"context": "additional context for the task"
}
| Field | Required | Description |
|---|---|---|
prompt | Yes | Task prompt to send to the worker. Missing/empty → 400. |
model | No | Model override for the task. |
stream | No | Enable SSE streaming response (default: false). |
context | No | Additional context string forwarded to the worker. |
The caller’s user_uuid and permissions are injected into the dispatch opts
by the handler — do not send them in the body.
Response (non-streaming, 200):
{
"status": "ok",
"task_id": "task_abc123"
}
Response (streaming, Content-Type: text/event-stream):
event: token
data: {"content": "Analyzing..."}
event: token
data: {"content": "Found 3 issues..."}
event: result
data: {"task_id": "task_abc123", "status": "ok", "content": "Complete analysis"}
Error Responses:
| Code | Body / Condition |
|---|---|
| 400 | {"ok":false,"error":{"code":"missing prompt","message":"missing prompt"}} |
| 405 | {"ok":false,"error":{"code":"method not allowed — use POST","message":"method not allowed — use POST"}} |
| 500 | {"ok":false,"error":{"code":"dispatch failed","message":"dispatch failed"}} (catch-all on 'EXIT'/unexpected return) |
| 503 | {"ok":false,"error":{"code":"zmq disabled","message":"zmq disabled"}}, or pipeline start failed |
Background Workers
All background-worker routes are admin-only (403 forbidden
otherwise).
Start Background Worker
POST /api/v1/workers/bg/start
{ "prompt": "analyze the logs and summarize errors" }
prompt is required (missing/empty → 400 prompt required); model and
timeout are optional. The caller’s identity is captured server-side.
Response (200): {"bg_id": "bg-abc123"} — there is no status
field.
List / Status / Logs
GET /api/v1/workers/bg
GET /api/v1/workers/bg/:bg_id
GET /api/v1/workers/bg/:bg_id/logs?n=100
Logs take ?n=<lines> (positive integer, default 100); any other
parameter name or a non-positive value answers 400 invalid n parameter.
Kill Background Worker
POST /api/v1/workers/bg/:bg_id/kill
404 unknown id; 409 when the worker is in a non-killable state.
Tasks
Task Status / Result
GET /api/v1/tasks/:task_id
Get the status and result of a dispatched task. Ownership is enforced: non-admin callers receive 403/404 for tasks they do not own.
Response — completed (200):
{
"task_id": "task_abc123",
"status": "ok",
"content": "Task result content"
}
Response — in progress, with partial output (200):
If the task has not finished but has emitted at least one streamed token, the
combined token buffer is returned as content:
{
"task_id": "task_abc123",
"status": "in_progress",
"content": "partial output so far..."
}
Response — not yet running:
A task that has no result and no streamed tokens yet may be reported by its
parent orchestration as pending. See GET /api/v1/orchestrate/:id below —
each child entry is shaped as {"task_id":..., "status":"pending"} until the
worker produces output. Direct GET /api/v1/tasks/:task_id for such a task
returns 404 with the Zerg envelope code task not found, because the
task store has no result row yet.
Error Responses:
| Code | Condition |
|---|---|
| 403 | Task exists but caller is not the owner (and not admin). |
| 404 | Task not found (no result row, no tokens). |
Cancel a Task
DELETE /api/v1/tasks/:task_id
Cancel a running task. The handler first asks the ZMQ gateway to cancel, then falls back to the local worker pipeline if ZMQ has no record of it. Ownership is enforced.
Response (200):
{ "status": "cancelled" }
Error Responses:
| Code | Condition |
|---|---|
| 403 | Not the task owner. |
| 404 | Task not found in ZMQ gateway or local pipeline. |
List Tasks
GET /api/v1/tasks
List tasks. Non-admin callers see only their own tasks; admins see all. Paginated.
Response (200):
{
"items": [
{
"task_id": "task_abc123",
"status": "ok",
"created_at": 1716192000000
}
],
"total": 1,
"limit": 50,
"offset": 0,
"page": 1,
"total_pages": 1,
"has_more": false
}
Local JSONL Agents
Local agents are stdio JSONL workers managed by Sol via erlexec.
List Agents
GET /api/v1/agents
Returns the list of running local JSONL agents.
Spawn an Agent
POST /api/v1/agents/spawn
Spawn a new JSONL stdio worker process. Admin-only.
Request Body:
{
"worker_path": "client/build/luna",
"opts": {}
}
Agent Detail
GET /api/v1/agents/:id
Status of a single named agent. :id is the worker’s registered atom (e.g.
luna_worker_1).
Response (200):
{
"worker_id": "luna_worker_1",
"status": "ready",
"current_task": null
}
status is stringified from the internal atom; current_task is null when
idle. Returns 404 with the Zerg envelope code agent not found if the
atom is unknown or sol_worker:status/1 crashes.
Dispatch Task to an Agent
POST /api/v1/agents/:id/task
Send a task prompt to a local agent.
Request Body:
{
"prompt": "Summarize this file",
"stream": true
}
| Field | Required | Description |
|---|---|---|
prompt | Yes | Task prompt. Empty → 400. |
stream | No | SSE stream the response (default: true for this endpoint). |
Responses:
| Code | Body | Condition |
|---|---|---|
| 200 | {"status":"ok","task_id":"..."} | Non-streaming success. |
| 202 | {"status":"queued","task_id":"..."} | Task queued (worker busy). |
| 200 | SSE stream | Streaming success (stream: true). |
| 400 | missing prompt | Empty prompt (Zerg envelope, error.code). |
| 404 | agent not found | Unknown worker / send_task crash (Zerg envelope). |
| 502/503 | class code | Dispatch error from sol_worker:send_task/2 — classified (worker-down → 503 worker class), never a blanket 500. |
Kill an Agent
POST /api/v1/agents/:id/kill
Terminate a running local agent. Admin-only.
Method is POST, not DELETE (matches the OpenAPI spec).
Orchestration
Dispatch Multi-Task
POST /api/v1/orchestrate
Dispatch multiple tasks in parallel, sequentially, or as a decomposed workflow.
Request Body:
{
"tasks": [
{"prompt": "Analyze module A"},
{"prompt": "Analyze module B"}
],
"mode": "direct",
"strategy": "parallel",
"model": "glm-5.1",
"timeout": 120000
}
| Field | Required | Description |
|---|---|---|
tasks | Yes | Array of task objects, each with at least prompt. Empty array → 400. |
mode | No | direct (default) or workflow. workflow decomposes via sol_coordinator. |
strategy | No | parallel (default) or sequential. |
model | No | Model override applied to all tasks. |
timeout | No | Overall timeout in ms (default 120000). timeout_ms is accepted as an alias. |
Responses:
| Code | Body | Condition |
|---|---|---|
| 200 | direct mode: array of per-task results; workflow mode: coordinator result with mode:"workflow" added | Success. |
| 400 | invalid tasks: non-empty list required / invalid timeout: positive integer required | Malformed tasks / timeout (Zerg envelope). |
| 422 | <formatted reason> | Workflow decomposition failed (Zerg envelope). |
Orchestration Detail
GET /api/v1/orchestrate/:id
Returns the child tasks of an orchestration parent.
Response (200):
{
"orchestration_id": "orch_xyz",
"children": [
{"task_id": "task_1", "status": "ok", "content": "..."},
{"task_id": "task_2", "status": "pending"}
]
}
Each child entry is either {task_id, status, content} (completed child) or
{task_id, status:"pending"} (child whose result row does not exist yet —
** behaviour**).
Error Responses:
| Code | Condition |
|---|---|
| 404 | Neither children nor a parent row exist for :id. |
Authentication
curl -H "Authorization: Bearer $TOKEN" \
http://localhost:21434/api/v1/zmq/workers
See Authentication for token acquisition and the priority order of
Authorization header vs zerg_session cookie vs ?token= query.
ZMQ Protocol
Workers connect as DEALER sockets to Sol’s ROUTER on port 5555. The wire protocol uses msgpack. See Workers and Agents for the full protocol specification and worker implementation examples.
Workflows API
Canonical reference: docs/api-reference.md (generated endpoint directory) — this page is a task-oriented summary.
Sol’s workflow engine orchestrates multi-step agent tasks using gen_statem instances with compensation, branching, and tree operations. This API covers the full workflow lifecycle.
Create Workflow
POST /api/v1/workflows/start
Start a new workflow from a named definition and payload.
curl -X POST https://sol.example.com/api/v1/workflows/start \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"name": "code-review",
"payload": {},
"objective": "Review the diff for bugs",
"token_budget": 50000,
"time_budget_ms": 600000
}'
Response:
{
"workflow_id": "wf-1744730000000",
"status": "started"
}
400 if name is missing; 500 on internal failure.
List Workflows
GET /api/v1/workflows
List all workflows with their current status.
curl -H "Authorization: Bearer $TOKEN" \
https://sol.example.com/api/v1/workflows
Get Workflow
GET /api/v1/workflows/:id
Get workflow details including step statuses and results.
curl -H "Authorization: Bearer $TOKEN" \
https://sol.example.com/api/v1/workflows/wf-1744730000000
Response:
{
"id": "wf-1744730000000",
"name": "code-review",
"status": "running",
"steps": [
{"name": "analyze", "status": "completed", "result": "..."},
{"name": "fix", "status": "running"},
{"name": "verify", "status": "pending"}
]
}
Cancel Workflow
POST /api/v1/workflows/:id/cancel
Cancel a running workflow. Triggers compensation for completed steps. 409 if already completed; 403 if not the owner.
Branch Workflow
POST /api/v1/workflows/:id/branch
Create a child workflow branching from an existing one. Body fields: branch_point_idx, objective. Returns {ok: true, child_workflow_id, parent_workflow_id}.
Workflow Tree
GET /api/v1/workflows/:id/tree
Returns the full tree of the workflow and its descendants.
Workflow Lineage
GET /api/v1/workflows/:id/lineage
Returns the root-to-node lineage path. Response: {ok: true, lineage: [...]}.
Pause Workflow
POST /api/v1/workflows/:id/pause
Pause a running workflow. {status: "paused"}. 409 if already completed.
Resume Workflow
POST /api/v1/workflows/:id/resume
Resume a paused workflow (or a budget-parked one with token_budget /
time_budget_ms raised). {status: "resumed"}. 409 if already completed
or the budget is still exhausted.
Retry Pending Compensation
POST /api/v1/workflows/:id/compensation/retry
Re-runs the LIFO pending-unwind driver for a failed workflow whose last
unwind did not complete. Confirmed handlers clear from the durable pending
set, after which /resume is allowed. 202 with the pending set; 409
when nothing is pending or the workflow is still running.
Stream Workflow Events
GET /api/v1/workflows/:id/stream
Subscribe to Server-Sent Events for this workflow’s state changes (owner-checked).
Workflow Lifecycle
Workflows use gen_statem for state management:
pending -> running -> completed
\-> failed
\-> cancelled
| State | Description |
|---|---|
pending | Created, not yet started |
running | Executing steps |
completed | All steps finished successfully |
failed | A step failed (compensation triggered) |
cancelled | User cancelled (compensation triggered) |
Step Lifecycle
Each step within a workflow follows its own state machine:
pending -> running -> completed
\-> failed
\-> skipped
Multi-Step Execution
Workflows execute steps sequentially by default. Each step receives:
The original prompt Results from previous steps Step-specific configuration (mode, tools, timeout)
The user_uuid is propagated from the HTTP request through each step dispatch, ensuring multi-tenant isolation.
Step Configuration
| Field | Type | Description |
|---|---|---|
name | string | Step identifier |
prompt | string | Task prompt for the step |
mode | string | Agent mode (build/plan/explore/review/general/coordinate) |
tools | array | Restricted tool set (optional) |
timeout | number | Step timeout in seconds (optional) |
condition | string | Execution condition (optional) |
Compensation Events
When a step fails or the workflow is cancelled, the workflow engine triggers compensation events:
- Completed steps receive a
compensateevent in reverse order - Each step can define a compensation action (rollback, cleanup, notification)
- Compensation failures are logged but do not block other compensations
- The workflow transitions to
failedorcancelledafter all compensations complete
This ensures resources are cleaned up even on partial failures.
Branching
Workflows support branching for conditional execution paths:
{
"name": "conditional-review",
"steps": [
{"name": "check", "prompt": "Check if tests pass", "mode": "build"},
{
"name": "branch",
"type": "branch",
"conditions": {
"pass": {"match": "{{check.result}}", "pattern": ".*passed.*", "then": "deploy"},
"fail": {"then": "fix"}
}
},
{"name": "deploy", "prompt": "Deploy to production", "mode": "build"},
{"name": "fix", "prompt": "Fix the failing tests", "mode": "build"}
]
}
Tree Operations
Workflows can be organized as trees for complex orchestration:
Parent-child relationships between workflow instances (see Branch Workflow and Workflow Tree) Spawn child workflows from a parent step Aggregate results from child workflows Tree-level cancellation propagates to all children
Streaming Workflow Events
Workflow state changes for a specific workflow are streamed via SSE:
curl -N https://sol.example.com/api/v1/workflows/wf-1744730000000/stream \
-H "Authorization: Bearer $TOKEN"
Event types:
| Event | Description |
|---|---|
workflow:started | Workflow execution began |
workflow:step:started | A step began executing |
workflow:step:completed | A step completed |
workflow:step:failed | A step failed |
workflow:completed | Workflow finished |
workflow:failed | Workflow failed |
workflow:cancelled | Workflow was cancelled |
workflow:compensating | Compensation in progress |
Event Store Integration
Workflow events are stored in the Mnesia-backed event store (102 event types). Pre- and post-hooks enable:
Audit logging of all workflow mutations Real-time notifications via the PUB/SUB event bridge Plugin reactions to workflow state changes Historical replay for debugging
The workflow bridge subscribes to the event store and dispatches step tasks to workers via ZMQ, propagating user_uuid for multi-tenant isolation.
Workspace API
Canonical reference: docs/api-reference.md (generated endpoint directory) — this page is a task-oriented summary.
The workspace API provides file operations for managing files within the configured workspace root directory.
All paths are relative to the workspace root. Path traversal (..), absolute paths, URI-style paths (://), and symlinks are rejected (403). Read and search require the workspace:read permission (or admin); write and edit are admin-only.
Read File
POST /api/v1/workspace/read
{ "path": "src/main.erl" }
Response:
{
"path": "src/main.erl",
"content": "-module(main).\n",
"size": 15
}
Reads are open-then-verify (the opened file’s inode must match the validated leaf). Errors: 400 path is required / path is a directory, 403 permission denied or path-validation refusals, 404 file not found, 413 when the file exceeds the 10 MB read cap (body_too_large).
Write File
POST /api/v1/workspace/write
Atomic write (write to temp, then rename). Creates parent directories automatically.
{ "path": "src/new_file.erl", "content": "-module(new_file).\n" }
Edit File
POST /api/v1/workspace/edit
Find-and-replace with exact match. Rejects if old_text appears more than once.
{
"path": "src/main.erl",
"old_text": "-module(old_name)",
"new_text": "-module(new_name)"
}
Response on multiple matches (or no match — old_text not found in file):
{ "error": "multiple matches", "matches": 3 }
Both mismatch classes answer 409 (Zerg handler responses; the body shown is the handler’s structured conflict payload).
Search Files
POST /api/v1/workspace/search
{ "query": "*.erl", "max_results": 50 }
query is a glob (required); max_results defaults to 50 and is capped at
1000. Results outside the workspace root are dropped and counted in the
omitted field.
Response:
{
"results": [
{ "path": "src/main.erl", "size": 256, "modified": "2026-05-18T14:30:45Z" }
],
"count": 1,
"omitted": 0
}
List Files
GET /api/v1/workspace/list?path=.&recursive=true
(POST to the same path is also accepted.) Recursive listings walk four
levels deep; the listing is capped at 1000 entries.
Response:
{
"path": ".",
"entries": [
{ "path": "src/main.erl", "type": "file", "size": 256, "modified": "2026-05-18T14:30:45Z" },
{ "path": "src", "type": "directory", "size": 4096, "modified": "2026-05-18T12:00:00Z" }
],
"count": 2
}
CLI Overview
The ZERG CLI is a standalone LuaJIT binary (~2.9 MB) with cli_commands=92 command-table entries (64 user-facing top-level verbs plus 2 internal) and cli_subcommands=37 subcommands across its command families for managing the ZERG platform.
Installation
From the repository root:
(cd zerg-cli && bash build/build.sh)
# Binary at: zerg-cli/zerg
sudo cp zerg-cli/zerg /usr/local/bin/
Configuration
The built-in default API URL is http://127.0.0.1:21434 (the local loopback API) — set a profile or --api-url for a remote server. There is no zerg config subcommand; the CLI reads ~/.zerg/config.json, environment variables, and global flags:
# Environment variables
export ZERG_API_URL=https://your-server.example
export ZERG_TOKEN=<your-token>
# Or global flags — these must appear BEFORE the command
zerg --api-url https://your-server.example status
# Or log in: mints a token against Mango auth and stores it in ~/.zerg/config.json
zerg --api-url https://your-server.example login --email user@example.com
Named profiles live in ~/.zerg/config.json (edit the file directly) and are selected with the global --profile <name> flag. See CLI Configuration for the file layout and resolution order.
Shell Completion
# Bash
zerg completion bash > /etc/bash_completion.d/zerg
# Zsh
zerg completion zsh > "${fpath[1]}/_zerg"
# Fish
zerg completion fish > ~/.config/fish/completions/zerg.fish
Command Groups
| Group | Commands | Description |
|---|---|---|
| Health | status, metrics | Server health and metrics |
| Models | discover, list, ps, show, start, stop, stop-all, prepare | Model management |
| Inference | run, chat | OpenAI and Anthropic API completions |
| Workers | agents, spawn, kill, task, task-cancel, task-status | Agent worker management |
| Workflow | list, start, show, cancel, branch, tree, lineage | Multi-step workflows |
| Bg Workers | start, list, status, logs, kill | Background workers |
| Schedule | list, add, show, pause, unpause, run, delete | Job scheduling |
| Channels | channels, channel-add, channel-remove, channel-test, channel-send | Delivery channels |
| Recipes | recipe-list, recipe-show, recipe-run, recipe-reload | Workflow recipe templates |
| Skills | skills, skill-search, skill-register, skill-remove | Agent skill management |
| Keyring | keyring-test, keyring-set, keyring-get, keyring-delete | OS keyring integration |
| Plugin | plugin-eval, plugin-workers, plugin-spawn | Lua sandbox workers |
| ZMQ | zmq-workers, zmq-dispatch, zmq-status | ZMQ worker management |
| Cluster | cluster, catalog, join, leave | Cluster management |
| Circuits | circuits, circuits-reset | Circuit breaker management |
| Auth | login, logout | Authentication |
| Update | check, download, apply, rollback | Self-update management |
| Completion | completion | Shell completion scripts |
| Diagnostics | doctor, support-bundle | Health verdict + redacted incident bundle |
Diagnostics
# One health/readiness verdict (exit 0 only when both probes are healthy)
zerg doctor
# Redacted incident bundle: version, config posture, health, log tails
zerg support-bundle /tmp/zerg-support --log-dir /var/log/runit/zerg-sol
support-bundle never writes token/secret-keyed values: secret-keyed
environment/config values and log secrets are replaced with <redacted>, and
a final scan removes the artifacts created by that run and refuses if any
known secret is found. The output directory must be a new path — an existing
directory is refused and is never written into or deleted. See
the main CLI reference
for the file list and behavior.
Examples
# Check server status
zerg status
# List available models
zerg list
# Start inference (model name is a catalog/lane id, positional)
zerg start glm-4.7-flash
# Start a workflow
zerg workflow start code-review
# Check background workers
zerg bg-workers list
# Login (prompts for password)
zerg login --email user@example.com
# Get JSON output
zerg status --format json
CLI Commands
Complete reference for all ZERG CLI commands. The CLI is a standalone LuaJIT binary (~2.9 MB) with zero Python dependency.
Canonical: docs/cli-reference.md — this page is the portal split; where wording differs, cli-reference.md wins.
Global Flags
Global flags are only parsed before the command name (the first
positional argument); everything after the command is the command’s own
argv (--token after the boundary belongs to the command, e.g.
channel-add, and is never a global credential). --json, --format
and --quiet are additionally honored after the command name.
| Flag | Description |
|---|---|
--json | Output raw JSON |
--token <token> | Deprecated global auth form (use --bearer or ZERG_TOKEN); argv-visible, prints a loud warning |
--bearer <token> | Explicit global auth token (must appear before the command) |
--profile <name> | Use named profile (global — must appear before the command) |
--api-url <url> | Override server URL (global — must appear before the command) |
--format <fmt> | Output format (text or json) |
--quiet | Suppress ANSI styling/status decorations (enforced at the output boundary) |
--version | Print version |
--help | Show help |
Infrastructure
status
Show server health and status.
zerg status
zerg status --format json
discover
Scan for available models and register them.
zerg discover
show
Display details for a specific model.
zerg show <model-name>
metrics
Show server inference metrics (model lifecycle counters, requests, tokens, errors, durations) as a formatted table.
zerg metrics
Models & Inference
list
List all discovered models and their status.
zerg list
zerg list --json
start
Start a model. <model> is positional.
zerg start glm-4.7-flash
zerg start glm-4.7-flash --temp 0.7 --top-p 0.9 --batch-size 512 --template default
| Flag | Description |
|---|---|
<model> (positional) | Model to start (required) |
--temp <f> | Sampling temperature |
--top-p <f> | Top-p sampling |
--batch-size <n> | Batch size |
--template <name> | Start template |
stop
Stop a running inference instance. <model> is positional.
zerg stop glm-4.7-flash
stop-all
Stop all running inference instances.
zerg stop-all
prepare
Sync a model from NFS to local disk. <model> is positional.
zerg prepare glm-4.7-flash
Workers
ps
List running worker processes.
zerg ps
spawn
Spawn a new worker process.
zerg spawn
zerg spawn --count 3 --worker-path /path/to/worker
| Flag | Description |
|---|---|
--count <n>, -n <n> | Number of workers to spawn |
--worker-path <path> | Path to the worker binary |
kill
Kill a running agent worker. <agent_id> is positional.
zerg kill <agent-id>
agents
List running agents.
zerg agents
Chat & Inference
chat
Send a single prompt via the Anthropic Messages API (/v1/messages) and print the response. <prompt> is positional and required; streaming is the default.
zerg chat "Explain quicksort" --model glm-4.7-flash
zerg chat "What is 2+2?" --no-stream
zerg chat "Explain monads" --system "Be concise"
| Flag | Description |
|---|---|
--model <name>, -m <name> | Model slug (defaults to default) |
--system <text>, -s <text> | System prompt |
--no-stream | Return complete response |
--temp <f> | Temperature |
--top-p <f> | Top-p sampling |
--max-tokens <n> | Maximum output tokens (default 4096) |
--low-speed-time <s> | Seconds of stream inactivity before abort (default 60) |
--low-speed-limit <b/s> | Bytes/s below which a stream counts as stalled (default 1) |
--verbose, -v | Show token count/usage |
run
Send a single prompt via the OpenAI-compatible completions endpoint and print the response. <prompt> is positional and required; streaming is the default.
zerg run "Explain this function"
zerg run --model glm-4.7-flash "What is OTP?"
zerg run --no-stream --temp 0.3 --max-tokens 4096 "Write a fib function"
| Flag | Description |
|---|---|
--model <name>, -m <name> | Model slug (defaults to default) |
--no-stream | Return complete response |
--temp <f> | Temperature |
--top-p <f> | Top-p sampling |
--max-tokens <n> | Maximum output tokens |
--timeout <ms> | Request timeout in milliseconds (non-streaming only) |
--low-speed-time <s> | Seconds of stream inactivity before abort (default 60) |
--low-speed-limit <b/s> | Bytes/s below which a stream counts as stalled (default 1) |
--verbose, -v | Show token count after response |
Tasks
task
Dispatch a task to an agent worker. <agent_id> and <prompt> are positional; streaming is the default.
zerg task <agent-id> "Fix the bug in main.rs"
zerg task <agent-id> --no-stream --wait "Fix the bug in main.rs"
| Flag | Description |
|---|---|
--no-stream | Queue task without streaming |
--stream | Force SSE streaming |
--wait | Poll for the result (with --no-stream); Ctrl-C exits 130 |
--verbose, -v | Show token count |
task-cancel
Cancel a running task.
zerg task-cancel <task-id>
task-status
Get detailed task status.
zerg task-status <task-id>
Workflows
workflow list
List all workflows.
zerg workflow list
workflow start
Start a new workflow. <name> is positional.
zerg workflow start code-review
zerg workflow start deploy
workflow show
Show workflow details and current state.
zerg workflow show <workflow-id>
workflow cancel
Cancel a running workflow.
zerg workflow cancel <workflow-id>
workflow branch
Create a branch in a workflow. Takes no flags — the server derives the branch.
zerg workflow branch <workflow-id>
workflow tree
Display the workflow step tree.
zerg workflow tree <workflow-id>
workflow lineage
Show workflow execution lineage.
zerg workflow lineage <workflow-id>
Background Workers
bg-workers start
Start a background worker. <task> is positional.
zerg bg-workers start "Refactor the auth module"
bg-workers list
List all background workers.
zerg bg-workers list
bg-workers status
Show background worker status.
zerg bg-workers status <worker-id>
bg-workers logs
Show background worker logs (single fetch, no streaming; no flags).
zerg bg-workers logs <worker-id>
bg-workers kill
Kill a background worker.
zerg bg-workers kill <worker-id>
Scheduler
schedule list
List all scheduled jobs.
zerg schedule list
schedule add
Create a new scheduled job. <prompt> is positional.
zerg schedule add "Run health check" --cron "0 */6 * * *"
zerg schedule add "Sync models" --every 3600
| Flag | Description |
|---|---|
--cron <expr> | Cron expression |
--every <seconds> | Interval in seconds |
--at <epoch-seconds> | One-time execution (Unix epoch seconds — an ISO 8601 string is silently dropped) |
--name <name> | Job name |
--model <name>, -m <name> | Model to use |
--delete | Delete the job after one run |
Exactly one schedule source is sent: --every wins over --cron, which wins over --at.
schedule show
Show job details.
zerg schedule show <job-id>
schedule pause
Pause a scheduled job.
zerg schedule pause <job-id>
schedule unpause
Resume a paused job.
zerg schedule unpause <job-id>
schedule run
Trigger a scheduled job immediately.
zerg schedule run <job-id>
schedule delete
Delete a scheduled job.
zerg schedule delete <job-id>
Cluster
cluster
List cluster nodes.
zerg cluster
catalog
Show the global model catalog across all cluster nodes.
zerg catalog
join
Join a cluster node.
zerg join <node@host>
leave
Leave the cluster.
zerg leave
Channels & Skills
channels
List communication channels.
zerg channels
channel-add
Register a delivery channel. Type defaults to telegram, which requires --token and --chat-id (or a --config JSON object).
zerg channel-add --type telegram --token "BOT_TOKEN" --chat-id "CHAT_ID" --name "alerts"
zerg channel-add --type discord --webhook-url "https://discord.com/api/webhooks/..." --name "ops"
zerg channel-add --type telegram --config '{"bot_token":"...","chat_id":"..."}'
| Flag | Description |
|---|---|
--type <t>, -t <t> | Channel type: telegram (default), discord, webhook |
--token <tok> | Telegram bot token |
--chat-id <id> | Telegram chat ID |
--webhook-url <url> | Discord webhook URL (--url also accepted for discord) |
--url <url> | Webhook URL (required for --type webhook) |
--name <name> | Channel display name |
--config <json> | JSON config object (overrides the per-type flags) |
channel-remove
Remove a channel.
zerg channel-remove <channel-id>
channel-test
Test channel connectivity.
zerg channel-test <channel-id>
channel-send
Send a message to a channel. <channel_id> and <message> are positional.
zerg channel-send <channel-id> "Deploy complete"
skills
List registered skills.
zerg skills
skill-search
Search for skills.
zerg skill-search "code review"
skill-register
Register a new skill from a JSON skill-definition file. <file> is positional.
zerg skill-register ./my-skill.json
skill-remove
Remove a registered skill. <name> is positional.
zerg skill-remove <name>
Recipes
recipe-list
List available recipes.
zerg recipe-list
recipe-show
Show recipe details.
zerg recipe-show <recipe-name>
recipe-run
Execute a recipe.
zerg recipe-run <recipe-name>
recipe-reload
Reload recipe definitions.
zerg recipe-reload
Circuits & Plugins
circuits
List circuit breaker states.
zerg circuits
circuits-reset
Force reset a circuit breaker to closed state. <key> is positional (one breaker per call — there is no reset-all).
zerg circuits-reset <key>
plugin-eval
Evaluate a Lua expression in the plugin sandbox.
zerg plugin-eval "return 1 + 1"
plugin-workers
List plugin-managed workers.
zerg plugin-workers
plugin-spawn
Spawn a Lua sandbox worker.
zerg plugin-spawn --script <path>
ZMQ
zmq-workers
List ZMQ-connected workers.
zerg zmq-workers
zmq-dispatch
Dispatch a task to a ZMQ worker. <prompt> is positional.
zerg zmq-dispatch "Analyze this log" --model glm-4.7-flash
| Flag | Description |
|---|---|
--model <name>, -m <name> | Model to use |
--context <text> | Additional context |
zmq-status
Show ZMQ gateway status.
zerg zmq-status
Authentication
login
Authenticate with a ZERG server (Mango auth). <account>/--email/-e is the username; the password is prompted with echo hidden when --password is omitted. --password is deprecated (argv-visible via ps, loud warning). Pass --keyring to store the bearer in the OS keyring instead of ~/.zerg/config.json.
zerg login --email user@example.com
zerg login --keyring user@example.com
logout
Clear authentication credentials.
zerg logout
keyring-test
Test keyring access.
zerg keyring-test
keyring-set
Store an API key in the OS keyring. <provider> is positional (e.g. openai); it prompts for the key with echo hidden, or accepts the deprecated --key form (argv-visible, loud warning).
zerg keyring-set openai
keyring-get
Retrieve an API key (masked) from the OS keyring. <provider> is positional.
zerg keyring-get openai
keyring-delete
Remove a stored API key from the OS keyring. <provider> is positional.
zerg keyring-delete openai
Update
update check
Check for CLI updates.
zerg update check
update download
Download a new version.
zerg update download
update apply
Apply a downloaded update.
zerg update apply [--install-dir DIR]
The install root is never defaulted to /opt/zerg (the LEGACY Sol root): it is derived from the running zerg executable when that is a real installed layout (zerg + VERSION), and refused for /opt/zerg or any tree carrying bin/sol (a Sol install). Pass --install-dir for other layouts. The post-install probe execs the installed binary; a failure rolls back automatically.
update rollback
Rollback to the previous version.
zerg update rollback [--install-dir DIR]
Restores the newest <root>.*.bak tree (same root resolution/refusals as apply) — normally only after an interrupted apply (a successful apply removes its backup; a failed health check auto-rolls-back with it).
update trust-key
Deliberately re-pin the release signing key (TOFU override). Key changes detected against the pin are refused by the updater; this command is the explicit operator acknowledgement that the key rotated. <keyfile> is positional.
zerg update trust-key /path/to/new/minisign.pub
Shell Completion
completion
Generate shell completion scripts.
zerg completion bash >> ~/.bashrc
zerg completion zsh > ~/.zfunc/_zerg
zerg completion fish > ~/.config/fish/completions/zerg.fish
See Shell Completion for detailed setup instructions.
Additional Command Families
These families are documented in full in the repository’s canonical CLI
reference (docs/cli-reference.md); the portal split keeps a one-line entry
here so no registered command disappears from the portal:
# Channel pause/resume (POST-only server routes)
zerg channel-pause <channel_id>
zerg channel-resume <channel_id>
# Skills marketplace install (registry-backed)
zerg skill install <name> <author>
# Team mailbox verbs
zerg team mail list --team <id>
zerg team mail send --team <id> --to <member> --body <text>
# Analytics summaries
zerg analytics summary --days 30
zerg analytics top-tools --limit 5
zerg analytics cost --days 14
# Admin identity operations
zerg admin unlock <user_uuid>
zerg admin revoke-token <token_id>
# OAuth device/PKCE login
zerg oauth login <provider>
zerg oauth status
zerg oauth logout <provider>
# Session shares
zerg session share --file session-export.json --ttl-days 7
CLI Configuration
The ZERG CLI stores configuration in ~/.zerg/config.json with support for multiple profiles, environment variable overrides, and OS keyring integration for secure token storage.
Config File Location
The configuration file is stored at:
~/.zerg/config.json
The ~/.zerg/ directory is created automatically on first use. The config file is created with mode 0600 (owner read/write only).
Config Structure
{
"api_url": "http://127.0.0.1:21434",
"token": null,
"default_model": null,
"output_format": "text",
"profiles": {
"default": {
"api_url": "http://127.0.0.1:21434",
"token": "prod-api-token"
},
"staging": {
"api_url": "https://staging.wildzerg.com",
"token": "staging-token"
},
"local": {
"api_url": "http://127.0.0.1:21434",
"token": null
}
},
"active_profile": "default"
}
Top-Level Fields
| Field | Type | Default | Description |
|---|---|---|---|
api_url | string | http://127.0.0.1:21434 | Default server URL |
token | string | null | Default auth token |
default_model | string | null | Model to use when not specified |
output_format | string | text | Output format: text or json |
profiles | object | {} | Named configuration profiles |
active_profile | string | null | Currently active profile name |
Profiles
Profiles allow switching between different ZERG servers without re-entering credentials. There is no zerg config subcommand — profiles are edited directly in ~/.zerg/config.json:
{
"profiles": {
"production": {
"api_url": "http://127.0.0.1:21434",
"token": "prod-token-here"
},
"staging": {
"api_url": "https://staging.wildzerg.com",
"token": "staging-token-here"
}
},
"active_profile": "production"
}
zerg --profile NAME login mints a token (against Mango auth) and stores it in that profile’s token (with its token_origin); plain zerg login stores the top-level token. Edit api_url values by hand.
Switching Profiles
--profile is a global flag — it must appear before the command:
zerg --profile staging status
zerg --profile production list
Or make a profile permanent by setting "active_profile" in ~/.zerg/config.json. When both are given, --api-url wins over --profile.
Resolution Order
The CLI resolves settings in this order (highest priority first):
- CLI flags (
--api-url,--token,--profile) - Active profile values
- Top-level config values
- Environment variables
- Built-in defaults
URL Resolution
api-url flag > profile.api_url > config.api_url > ZERG_API_URL > ZERG_HOST:ZERG_PORT > default
Token Resolution
token flag > profile.token > config.token > OS keyring (when a `token_keyring` marker is present) > ZERG_TOKEN
Prefer zerg login --keyring (or --bearer / ZERG_TOKEN) over the deprecated global --token form.
Environment Variables
| Variable | Description | Example |
|---|---|---|
ZERG_API_URL | Server base URL | http://127.0.0.1:21434 |
ZERG_TOKEN | Authentication token | Bearer token value |
ZERG_HOST | Server hostname (with ZERG_PORT) | 192.168.1.100 |
ZERG_PORT | Server port (default: 21434) | 21434 |
export ZERG_API_URL=http://127.0.0.1:21434
export ZERG_TOKEN=your-token-here
zerg status
Editing the Config File
The config is plain JSON — edit it with any editor; the CLI re-reads it on every invocation:
~/.zerg/config.json
zerg login / zerg logout are the only commands that write it (flocked read-modify-write; saves are atomic — temp file, 0600, fsync, rename). To inspect the stored token without exposing it, check the file’s token_keyring marker or use zerg keyring-get <provider> for keyring-stored API keys.
Keyring Integration
On Linux, the CLI can store tokens in the system keyring via secret-tool (libsecret) instead of the config file. This prevents tokens from being stored in plaintext.
Storing a Token in Keyring
zerg keyring-set openai
Retrieving a Token from Keyring
zerg keyring-get openai
Deleting a Token from Keyring
zerg keyring-delete openai
Testing Keyring Access
zerg keyring-test
Keyring Requirements
| Platform | Backend | Package |
|---|---|---|
| Linux | libsecret | libsecret-1-dev, secret-tool |
| macOS | Keychain | Built-in |
Permission Checks
The CLI warns if the config file has overly permissive file modes:
Warning: config file ~/.zerg/config.json has loose permissions (others can read)
The config file is created with mode 0600. If permissions are modified externally, the CLI will warn on startup.
Shell Completion
The ZERG CLI generates completion scripts for Bash, Zsh, and Fish. Completions cover all cli_commands=92 commands, subcommands for grouped commands, global flags, and dynamic resource IDs.
Installation
Bash
zerg completion bash >> ~/.bashrc
source ~/.bashrc
Or install system-wide:
zerg completion bash | sudo tee /etc/bash_completion.d/zerg
Zsh
mkdir -p ~/.zfunc
zerg completion zsh > ~/.zfunc/_zerg
Ensure ~/.zfunc is in your fpath:
# In ~/.zshrc
fpath=(~/.zfunc $fpath)
autoload -U compinit && compinit
Fish
mkdir -p ~/.config/fish/completions
zerg completion fish > ~/.config/fish/completions/zerg.fish
Fish loads completions automatically. Start a new shell or run:
source ~/.config/fish/completions/zerg.fish
What Gets Completed
Commands
All cli_commands=92 command-table entries are completed:
zerg <TAB>
status discover list ps metrics
show start stop stop-all prepare
run chat agents spawn kill
task task-cancel task-status workflow bg-workers
schedule login logout completion ...
Subcommands
Grouped commands complete their subcommands:
zerg workflow <TAB>
list start show cancel branch tree lineage
zerg schedule <TAB>
list add show pause unpause run delete
zerg bg-workers <TAB>
start list status logs kill
zerg update <TAB> (check, download, apply, trust-key, rollback)
check download apply rollback
Global Flags
Flags are completed after --:
zerg status --<TAB>
json --token --profile --api-url
format --quiet --version --help
model --no-stream --stream --temp
top-p --max-tokens --wait
Dynamic Resources
The --model flag completes with model IDs fetched from the server (cached for 60 seconds):
zerg start --model <TAB>
glm-5.1 claude-sonnet-4-20250514 gpt-4o
The --profile flag completes with profile names from the config file:
zerg status --profile <TAB>
default staging production
Completion Architecture
The completion system is generated at runtime from cli/completion_data.lua. This module provides:
| Function | Returns |
|---|---|
get_commands | All top-level command names |
get_subcommands(group) | Subcommands for a grouped command |
get_flags | All global flags |
get_profiles | Profile names from ~/.zerg/config.json |
fetch_models | Model IDs from the server (cached) |
bash_script | Generated Bash completion script |
zsh_script | Generated Zsh completion script |
fish_script | Generated Fish completion script |
Dynamic completions (models, profiles; agent-ID completion is defined but not yet wired into the generated scripts) use a ~/.cache/zerg/*.cache file with a 60-second TTL to avoid hitting the server on every tab press.
Troubleshooting
Completions not appearing
Bash: Ensure bash-completion is installed and sourced before the zerg script.
sudo apt install bash-completion
Zsh: Run rm ~/.zcompdump* && compinit to rebuild the completion cache.
Fish: Check that ~/.config/fish/completions/ exists and the file is readable.
Stale model completions
Model IDs are cached in ~/.cache/zerg/models.cache for 60 seconds. To force a refresh:
rm ~/.cache/zerg/models.cache
Completion script is empty
The zerg completion command outputs to stdout. Ensure you redirect to a file:
zerg completion bash >> ~/.bashrc
Not:
zerg completion bash
Profile completions show wrong names
Profile completions read from ~/.zerg/config.json. If you modified the config manually, verify the JSON is valid:
cat ~/.zerg/config.json | python3 -m json.tool
Zsh fpath issues
If Zsh completions do not load, verify the fpath order:
echo $fpath
~/.zfunc must appear before the default completion directories. Add it early in ~/.zshrc:
fpath=(~/.zfunc $fpath)
autoload -U compinit && compinit
Engine reference — generated from the canonical engineering source. Do not edit this page by hand.
ZMQ Wire Protocol Reference
This is the CANONICAL wire-protocol reference. All other wire-protocol
pages (docs/PROTOCOL.md, docs/zmq-worker-protocol.md,
docs-site/reference/zmq-protocol.md) are thin pointers to this file.
Security material (HMAC, CURVE, enrollment keys, ownership gates) lives in
docs/zmq-security.md; worker integration examples live in
docs/worker-integration.md and example/python/zmq_worker.py.
Protocol Version: 4 — sol_zmq_protocol:protocol_version/0 (Sol) and
zmq_protocol.lua:M.VERSION (Luna). Increment on breaking semantic changes.
Version policy is STRICT-FORWARD with a config-gated N/N−1 skew window
a worker whose
ready version is exactly Sol’s constant, or (while the window is enabled)
exactly one below it, is admitted; anything older is refused at the
handshake ({version_mismatch, V, Expected}) and a min_version above
Sol’s is refused (min_version_too_new). Task frames to an N−1 worker are
stamped min(SolVersion, WorkerVersion) —: every
Sol→Luna frame, not only the task frame, is stamped at the target’s
admitted version (frame_version_for/1), so Luna’s own
v > M.VERSION inbound validator accepts them. The skew is counted by the
sol_zmq_fleet_skew{version} gauge and WARNING-logged at registration;
strict equality is the rollback posture (zmq_wire_skew_window=false).
(No v1 compatibility;,: token frames gained a per-task
seq;,: team_directive gained leader attribution +
content signature and joined the per-frame MAC plane;,
the task frame gained inference_binding and the
lane_control/lane_control_ack round-trip was introduced — upgrade
stop-then-upgrade: a v3 Sol would silently drop lane_control.
ALL Sol→Luna builders stamp the target’s admitted
version;:
the additive-v4 lane_revoke push joins the plane (advisory; suppressed
for pre-v4 targets).)
Overview
Sol (Erlang/OTP) and Luna (LuaJIT) communicate over ZMQ (ZMTP, DEALER–ROUTER
pattern) using msgpack-encoded maps. Every claim below is traceable to a code
symbol: the builders/validators in server/src/sol_zmq_protocol.erl, the
frame router server/src/sol_zmq_frame_router.erl, the receive dispatcher
server/src/sol_zmq_recv_dispatcher.erl, the ownership gates
server/src/sol_zmq_ownership.erl, and the Luna builders in
client/core/zmq_protocol.lua + client/core/zmq_worker.lua.
Message Framing
DEALER/ROUTER uses multipart ZMQ messages with a single msgpack-encoded map payload:
ROUTER → DEALER: [identity_frame] [payload_frame]
DEALER → ROUTER: [payload_frame] (+ [payload_frame, mac] on MAC'd sessions)
The ROUTER socket prepends the worker’s routing identity; the DEALER
socket adds NOTHING — the worker’s payloads go out bare ([payload]) or
MAC-signed ([payload, mac_hex]), and the wire-effective shapes at the
Sol gateway are [Identity, Payload] and [Identity, Payload, MacHex]
(sol_zmq_sender.erl sends [Identity, Payload] via
chumak:send_multipart; sol_zmq_gateway.erl matches exactly those two
shapes and DROPS anything else). A delimiter-frame-shaped
[Identity, "", Payload] message matches the MAC’d 3-frame clause — the
empty frame occupies the payload slot and the intended payload is taken
for the MAC frame — so the payload decode fails on the empty frame: the
gateway logs a WARNING and the message is dropped UNDECODED and never
dispatched (no error reply — unlike the 2-frame shape, whose decode
failure answers the sender with a decode_error error frame).
msgpack options: {pack_str, from_binary}, {unpack_str, as_binary}, {map_format, map} (?MSGPACK_OPTS, sol_zmq_protocol.erl).
All keys are binary strings.
Frame-size cap: 10 MB (max_msg_size/0, sol_zmq_protocol.erl) — the
receive boundary rejects oversized frames before decode; Luna’s
ffi/zmq.lua mirrors the same cap pre-copy.
Per-frame v stamping
Every frame carries v — the protocol version it was built with
(stamp_version/1 on Sol builders, stamp/1 in zmq_protocol.lua).
Absent v is treated as legacy v1 (the msgpack map is extensible).
Enforcement is asymmetric, and the per-frame v itself is NOT a Sol-side
gate: Luna drops inbound frames whose v is higher than its supported
version (validate_incoming, zmq_protocol.lua), while Sol enforces the
protocol version at the ready HANDSHAKE only — validate_ready_msg/1
accepts the current version (and, while zmq_wire_skew_window is on, the
N−1 window value) and no Sol code reads the per-frame v field.
Version skew window N/N−1
Default-on rolling-upgrade window (zmq_wire_skew_window; rollback lever).
: every Sol→Luna frame is stamped at the TARGET worker’s
admitted version (sol_zmq_protocol:frame_version_for/1 — the centralized
stamping authority; the frame-class × stamp-policy matrix lives in
server/test/fixtures/wire_compat_matrix.json, machine-checked by
ci/stamp_policy_matrix_lint.py, and is consumed by BOTH sides’ tests).
This closes the control-frame gap: the frame-level
differences a v3-mode worker sees during the window:
| Surface | Current (v4) | v3-mode worker (N−1, skew window) |
|---|---|---|
ready version | 4 | accepted only while zmq_wire_skew_window=true |
task frame v | 4 | stamped 3 (min(SolVersion, WorkerVersion)) so Luna’s v > M.VERSION gate accepts it |
| task frame fields | full v4 set | the SAME additive fields (permissions, attempt, task_timeout_ms, inference_binding) — none is required; a v3 Luna ignores the binding and uses its legacy model path |
ALL control frames (cancel, timeout-cancel, cancel_ack, spawn_ack, child_result, skill_sync, plugin_tool_result, acp_forward, acp_discover_reply, team_directive, team_mail_push) | stamped at the target’s admitted version | stamped 3 — accepted and acted on |
lane_control / lane_control_ack / lane_revoke (v4) | the lane-control round-trip + revoke push | v4-only semantics — never downstamped. A v3 worker never sends lane_control (no producer), so it never receives an ack; a lane_revoke push to a pre-v4 target is SUPPRESSED at the send site (target_admits/2 → suppress_frame/2: zmq_frame_suppressed_total counter + warning log — visible, never silent) |
error / ready_required (Sol→Luna refusals) | stamped at the target’s admitted version (registered peer) or the DECLARED version of the frame being refused | accepted — a peer always hears the refusal in a shape its own validator admits. The pre-registration decode-error leg stays legacy-unstamped on purpose (absent v = v1 = universally accepted: Sol cannot know an undecodable peer’s version, and stamping it current would make an N−1 peer DROP the feedback) |
| token frames | per-task seq (v2 feature, unchanged) | identical |
Refused loudly (never degraded): v2 and older READY
({version_mismatch, V, Expected}); a min_version above Sol’s
(min_version_too_new — enforced on BOTH the exact-version and the N−1
skew arm since then -8; the hole is closed). Every
admitted skew worker is counted by
sol_zmq_fleet_skew{version} and WARNING-logged.
V4 upgrade posture: STOP-THEN-UPGRADE. The
new lane_control frame is unknown to a v3 Sol (sol_zmq_handler_default
drops it silently), so a v4 Luna against a v3 Sol would hang its resolve
until its own timeout with zero server feedback. Upgrade Sol and Luna
together (wild CD ships both); the N/N−1 window exists for the
task-dispatch rolling upgrade, NOT as a lane-control compatibility claim.
** refinement: the v3-worker side of the window is now
control-frame complete** (every control frame downstamps or visibly
suppresses — see the table above), so a rolling SOL upgrade with v3
workers still running is safe for cancel/sub-agent/team/plugin/ACP
traffic; only lane consumption remains v4-only. The v3-Sol direction
(a Luna downgrade) remains stop-then-upgrade.
Connection Model
Naming scope. Worker-id uniqueness is
enforced per Sol node — the registry and the worker_id_in_use
conflict gate (sol_zmq_worker_manager) live in node-local state; Sol
has NO fleet-wide id namespace. A node-spawned worker is minted
init-wkr-N identically on EVERY node, so the same wire id can exist
once per node by design; never treat a worker_id as globally unique
(e.g. as a database key across a cluster). Task ids follow the same
rule (see the task table below).
- Worker opens a DEALER socket, sets
ZMQ.IDENTITY(= itsworker_id), connects totcp://<host>:<port>. - Worker sends
readyimmediately after connect (must carry the current protocolversion). - Sol validates
ready(validate_ready_msg/1): version accepted (current or, whilezmq_wire_skew_window=true, the N−1 window) →ok; anything else →{version_mismatch, V, Expected}(registration refused); amin_versionabove Sol’s version on the exact-version arm OR the N−1 skew arm →{error, {min_version_too_new, Min, Supported}}(the N−1 arm does not bound it — ); missingversion/worker_id/capabilities→{error, missing_fields}. - Sol registers the worker and routes tasks to idle registered workers. If no workers are ready, tasks queue until one is available.
- Liveness while connected is carried by periodic
heartbeatframes . A heartbeating identity Sol does NOT hold as registered — the full-VM-restart shape: the DEALER transport auto-reconnects, so the worker’s frames keep flowing while its registration is gone — is answered with the typedready_requiredcontrol frame (, ); the worker degradesconnectedtruthfully and re-registers with a proof-carryingready(freshnonce+ monotonicctr) after a full-jitter backoff. An IDLE worker may additionally re-sendreadyperiodically when explicitly configured (LUNA_ZMQ_REREADY_IDLE_MS, default OFF) — the frame is a fully signed registration (realctr/nonce proof). A proof-less mid-task re-ready remains FORBIDDEN: it trips Sol’s fail-closed adoption gate and orphans the in-flight task with aworker_reconnectederror. - Reconnection is handled by ZMQ internally (DEALER reconnects
automatically); a reconnect with an in-flight task re-
readys with the resume proof. The ADOPTION predicates are exact (, XS-11 — the pre-fix prose said “a secret is configured”, which is neither necessary nor sufficient): thereadymust be credential-VERIFIED by the normal registration gate, must NOT be wildcard-bound, must claim the same routing identity +worker_id, must name the exact in-flighttask_id, and the session MAC key derived from the presented credential must equal the key recorded on the existing registration (credential continuity — a different key, including a fleet-wide wildcard holder, never inherits the task). A failed predicate refuses the READY and the in-flight task is resolved through the error strategy asworker_reconnected.
Dispatch Topology
Task dispatch is node-affine by construction and always has two legs:
- The task leg rides ZMQ to MY Sol. A worker’s frames are served by the Sol node its DEALER is connected to; that node’s gateway queues, seats and dispatches the task, and its task store owns the rows. There is no Sol→Sol task forwarding and no cross-node re-dispatch: a node’s in-flight work is stranded (visible via the stranded-task datum, and requeued by its own outbox reconcile) until that node revives.
- The inference leg rides HTTP to whichever node’s llama holds the
lane. A lane grant’s endpoint may point at ANOTHER cluster node’s
llama server (cross-node placement via the lane orchestrator); the
worker dials that HTTP endpoint directly. The granting node’s bind
contract governs reachability: a
bind_mode=loopbacklane is granted only to a worker on the same machine; abind_mode=nonloopbacklane must advertise a routable host (loopback_advertisedrefuses the grant typed otherwise).
Consequence: each Sol node is an independent dispatch universe joined by the membership plane (catalog + lane inventory) and the placement rpc — not a single distributed queue.
Message Types
Frame types are the type key of each msgpack map. Direction: Worker → Sol frames are built by Luna (zmq_protocol.lua); Sol → Worker frames
are built by sol_zmq_protocol:build_*_msg/* and dispatched by the
gateway.
Sol → Luna
Luna-side validation: EVERY frame type in this
section is validated at Luna’s _handle_frames gate against the Required
columns of its field table (zmq_protocol.validate_incoming). A frame
failing validation is dropped, counted, and logged — never dispatched, and
the rest of the receive tick is unaffected (task additionally answers Sol
with an invalid_message error frame from _on_task). The per-type
Required fields are machine-pinned to the validator by
ci/zmq_protocol_doc_parity_lint.py.
1. task
| Field | Type | Required | Description |
|---|---|---|---|
type | binary | yes | "task" |
task_id | binary | yes | Task identifier, unique per Sol node — zmq-<ms>-<node-local counter> (sol_zmq_task_dispatcher:generate_task_id/1; the counter is dispatcher state, so ids are not fleet-unique; the zmq- namespace is server-reserved) |
prompt | binary | yes | Agent prompt text (may be empty for tool-call-only tasks) |
model | binary | no | Model override |
user_uuid | binary | no | Requesting user (present when Mango auth is on) |
workspace_root | binary | no | Working directory |
plugin_tools | list | no | Plugin tool descriptors |
permission_mode | binary | no | Permission profile — clamped server-side |
permission_rules | map | no | {deny, ask, allow} permission-rule ceiling stamped by sol_zmq_permission_rules:stamp/3 (bounded/validated server-side; additive, legacy peers ignore it) |
mode | binary | no | Advisory agent-mode request — a mode name resolved by Luna through core.agent_modes. Sol keeps it on the frame ONLY when the assigned worker’s READY-advertised modes list contains the exact value; otherwise it is stripped, counted (zmq_task_mode_fallback_total) and logged (mode is advisory — never a terminal; permission_mode is untouched). Absent stays absent. Additive: a pre-v4 peer ignores the key |
legacy_write_implies_execute | boolean | no | Execute-grade stamp — Sol’s effective legacy_write_implies_execute value (write-class permissions keep execute grade only while this is true). Luna clamps with min(Sol, Luna) so a split config can never widen the worker’s execute grade past Sol’s authority. Absent = legacy true (byte-identical for older peers; additive msgpack key, no protocol bump) |
task_timeout_ms | integer | no | Task idle deadline. Since it is the idle window of the progress-renewed lease: Sol re-arms it on every token/heartbeat for the task, bounded by the server-side task_max_lifetime_ms cap (a chatty-but-endless task is still cancelled at the cap). A dispatch Opts timeout_ms overrides the value per task. Disabled deadline: task_timeout_ms=0 disables the GATEWAY deadline; the wire field is then stamped with the shared 24h sentinel (docs/fixtures/task_timeout_contract.json, disabled_wire_sentinel_ms=86400000) so Luna’s max(value, 30000) wedge watchdog cannot preempt Sol’s decision at an absent-field 300s default. The field is never omitted |
permissions | list | no | RBAC permission list — always present (possibly empty) since then; explicit [] = the server granted NOTHING |
attempt | integer | no | Retry epoch — starts at 1 and increments on every re-dispatch/retry; Luna resets its per-task token seq on a changed attempt and Sol keys the expected token-seq rows by {task_id, attempt}. Absent = 1 is a DECIDED contract and is NOT flipped: a result/error frame without attempt for a receipt at attempt 2 is refused by the current gate (the regression pin is sol_zmq_attempt_gate_tests:absent_attempt_is_one_decided_guard/0; any future change needs a protocol-v-next decision). Since Luna ECHOES the same epoch on its terminal result/error frames so Sol can refuse a stale terminal (attempt lower than the current dispatch attempt) — see §15/§16. adds the same additive stamp to attempt-resolution cancel frames (§2) |
inference_binding | map | no | Local-lane grant binding — stamped by the dispatcher from the WARM-ONLY sol_lane_orchestrator:resolve_warm/2 probe (never starts a lane, never blocks). {status => "granted"} carries the pinned descriptor — the 7-key shape (lane, endpoint, wire_format, caps, ctx, lease_id, expires_at) + holder + expires_in_ms — of a LIVE local grant; the probe refuses non-openai formats at grant time, so every granted descriptor is worker-consumable. {status => "required", lane?, requirements?} is a marker — the worker must resolve asynchronously via lane_control (§27) and surface the typed refusal. ABSENT = remote-plane task: use the legacy key-based model path (§5 provider semantics) — and when that path does not exist (a keyless worker), the worker resolves a lane instead (typed lane_unavailable on refusal; never a mock). Additive; a v3 peer ignores it |
Builder (Erlang): sol_zmq_protocol:build_task_msg/3
Handler (Lua): zmq_worker.lua:_on_task/1
Dead task-frame fields: opts, capabilities and
request_id were removed from the task frame — Sol sent them but no Luna
consumer ever read them (the capabilities LSP gate and the
child_result.tokens/duration_ms reads were removed on the Luna side in
the same phase; child_result never carried those fields). They
re-enter the wire only together with a real consumer; the
ci/wire_field_provenance_lint.py consumption leg enforces it.
2. cancel
| Field | Type | Required | Description |
|---|---|---|---|
type | binary | yes | "cancel" |
task_id | binary | yes | Task to cancel |
user_uuid | binary | no | Requesting user |
cancel_reason | binary | no | Present on the gateway’s attempt-resolution cancels: "task_timeout" and the RESERVED "attempt_retry". Both are ATTEMPT resolutions — the task may be re-dispatched under error_strategy=retry, so Luna must not tombstone the id nor emit a fabricated cancelled terminal. Current Sol deliberately sends NOTHING on a send-failure requeue to the legacy fleet (every reason the current Luna does not recognize is a terminal tombstone); a future capability-gated client may consume attempt_retry. ABSENT = the plain (terminal) cancel: Luna tombstones the id and answers cancelled |
attempt | integer | no | **** — the dispatch epoch the cancel resolves. A delayed control retry (sender backoff) must not abort a newer attempt on the same worker: Luna ignores a cancel whose attempt is lower than its executing attempt. Absent = the legacy any-attempt shape (plain terminal cancel); never fabricated when unknown |
Builder (Erlang): sol_zmq_protocol:build_cancel_msg/1-3 (plain);
sol_zmq_protocol:build_cancel_timeout_msg/1-3 (typed timeout cancel);
sol_zmq_protocol:build_cancel_retry_msg/3 (typed attempt-retry cancel)
Handler (Lua): zmq_worker.lua:_on_cancel/1
3. spawn_ack
| Field | Type | Required | Description |
|---|---|---|---|
type | binary | yes | "spawn_ack" |
parent_task_id | binary | yes | Parent task ID |
child_task_id | binary | yes | Spawned child ID — non-empty on dispatched, EMPTY (<<>>) on rejected |
status | binary | yes | "dispatched", "rejected" — the ONLY statuses |
reason | binary | no | Rejection cause, present on EVERY rejected ack — bounded atom-name set: leaf_worker, unknown_parent, max_children_exceeded, max_depth_exceeded, seat_cap_reached, no_workers_available, unknown (non-atom reasons fail-closed to unknown) |
async | boolean | no | True if background spawn |
Builder (Erlang): sol_zmq_protocol:build_spawn_ack_msg/3-5
Handler (Lua): zmq_worker.lua:_on_spawn_ack/1 — fail-closes on anything
that is not exactly "dispatched" (unknown status is treated as rejected).
4. child_result
| Field | Type | Required | Description |
|---|---|---|---|
type | binary | yes | "child_result" |
parent_task_id | binary | yes | Parent task ID |
child_task_id | binary | yes | Child task ID |
status | binary | yes | "ok", "error", "timeout" |
content | any | yes | Result content |
async | boolean | no | True if background result |
Builder (Erlang): sol_zmq_protocol:build_child_result_msg/4-5
Handler (Lua): zmq_worker.lua:_on_child_result/1, _on_background_result/1
5. cancel_ack
| Field | Type | Required | Description |
|---|---|---|---|
type | binary | yes | "cancel_ack" |
task_id | binary | yes | Task ID |
status | binary | yes | "cancelled", "already_cancelled", "not_found", "not_owner" — the closed enum as sent (the historical "ok"/"error" pair was never produced by the handlers) |
not_owner covers both the dispatcher leg (sender does not own the task,
sol_zmq_handler_agent) and the background-task leg (sol_zmq_bg_task);
already_cancelled means a cancel was already accepted for the task.
Builder (Erlang): sol_zmq_protocol:build_cancel_ack_msg/2
Handler (Lua): zmq_worker.lua:_on_cancel_ack/1
6. skill_sync
| Field | Type | Required | Description |
|---|---|---|---|
type | binary | yes | "skill_sync" |
skills | list | yes | Skill definitions; each entry carries the registry record (name/description/version/tags) plus, when the body fits the cap, body (the full SKILL.md content) |
skills_version | integer | no | **** — payload contract marker, 2 when body/revision semantics apply. A marked version > 2 is DROPPED by Luna (unknown breaking semantics); absent = legacy metadata-only shape |
revision | integer | no | **** — the Sol skill-registry revision at push time (monotonic per Sol boot epoch, seeded from wall clock so a restart always mismatches). Luna stores it and advertises it on READY (skills_revision, §12); a garbage/absent value is omitted (the worker then treats its copy as stale) |
bodies_omitted | boolean | no | **** — set on the metadata-only retry when the full payload would exceed the 10 MB wire cap: Luna updates metadata and the revision but never rewrites or prunes body files (the omission must not fabricate or delete content) |
Materialization contract: the push writes each
body to the worker-managed ~/.luna/skills/remote/registry/<name>/SKILL.md
(atomic tmp→rename) with a provenance.json beside it
({source: "registry", version, fetched_at, revision}); names absent from
the next full sync are pruned (tombstones). The marketplace install route
materializes under remote/marketplace/<author>/<name>/ — same target root,
same provenance shape with source: "marketplace". Both paths are additions:
sol_zmq_protocol:build_skill_sync_msg/1-3, Luna validator
zmq_protocol.lua:validate_incoming/1 (the skill_sync arm).
Builder (Erlang): sol_zmq_protocol:build_skill_sync_msg/1-3
Handler (Lua): zmq_worker.lua:_on_skill_sync/1 → core.skills:_on_skill_sync/1
7. team_directive
| Field | Type | Required | Description |
|---|---|---|---|
type | binary | yes | "team_directive" |
team_id | binary | yes | Team identifier |
directive | binary | yes | Directive type |
task | any | no | Directive payload |
sender | binary | no | **** — leader attribution: the directive AUTHOR’s registered worker_id, stamped SERVER-SIDE (the gateway’s directive leg / leader gate). Frame-supplied sender values on the worker→Sol direction are never identity. Absent/empty ⇒ Luna treats the directive as unattributed |
hmac | binary | no | **** — enrollment-bound content signature: HMAC-SHA256(session_key, material), signed by the gateway with the TARGET worker’s session key. hmac_v selects the material: v1 = sol_zmq_frame_mac:directive_payload/3 (the length-prefixed team_id/directive/sender field triple composed under the per-frame material, so the worker’s routing identity stays bound in); v2 = directive_payload_v2/4 ("D2" domain + the same triple + u16be(len(task.prompt))/task.prompt). Unsigned/mismatched directives are announce-only on Luna (refused, never executed) |
hmac_v | integer | no | ** (LUNA-20), Sol v2 signer merge-fix** — 2 when the frame carries an executable task.prompt and hmac is the task-bound material; absent or 1 = metadata-only (announce-only). Luna executes a dispatch ONLY with a valid hmac_v=2 signature, so an on-path attacker cannot rewrite the prompt of a captured frame. Cross-language vectors: docs/fixtures/directive_hmac_v2.json |
user_uuid | binary | no | **** — the leader/OWNER identity resolved server-side from the team member row. Luna runs the directive turn under this principal; absent ⇒ the explicit worker:<id> namespace |
permissions | binary list | no | **** — the DECLARED bounded team-dispatched grant (sol_team_lifecycle:directive_grant/0). Luna uses this grant; it never reuses the LAST task’s permission snapshot (absent ⇒ explicit-empty deny-default, read-only) |
Trust contract:
Worker → Sol: requires registration AND team membership AND the
sender’s registry member row role == leader (sol_zmq_handler_team).
Non-leader directives are refused + counted (zmq_auth_failures_total).
Credentialed sessions additionally require the per-frame MAC —
team_directive joined the MAC-verified plane set (, the
recorded acceptance; sol_zmq_frame_mac:worker_plane_type/1,
same zmq_frame_mac required|prefer|off lever).
Sol → Worker: signed + attributed by the gateway (fields above).
Luna executes a directive ONLY when it is leader-attributed AND the
signature verifies; otherwise it is announce-only (refusal is loud,
run_turn is never reached).
Server-side semantics stay event-notify-only: sol_team_lifecycle:handle_directive/3
publishes the directive as a sol_event (announce); no server-side task
execution. Fan-out to member workers rides the event router’s dealer
routes.
Builder (Erlang): sol_zmq_protocol:build_team_directive_msg/3-4
(sender + signature added by the gateway’s send leg)
Handlers (Lua): zmq_worker.lua:_handle_frames (trust-evidence decode
- HMAC verification) →
agent.lua:handle_team_directive(refusal gate)
8. team_mail_push
| Field | Type | Required | Description |
|---|---|---|---|
type | binary | yes | "team_mail_push" |
team_id | binary | yes | Team identifier |
msg_id | binary | no | ** (XSV-09)** — the durable per-recipient row id. Luna dedupes a READY re-push by this id (exactly-once per worker process); the field is absent on legacy/previous pushes |
expires_at | integer | no | **** — absolute Unix-seconds expiry of the durable row; Luna drops an already-expired re-push (the server also re-checks expiry before sending) |
from_kind | binary | yes | Sender struct kind — "worker" or "user" |
from_id | binary | yes | Sender struct id — the registered worker_id (kind worker) or the originating user_uuid (kind user) |
from_worker_id | binary | worker-kind only | Sender worker ID (server-derived); present ONLY when from_kind = "worker" |
to_worker_id | binary | yes | Recipient worker ID |
message | map | yes | Mail content (carries from/from_kind/from_id mirrors of the sender struct) |
hmac | binary | no | ** T2b** — the v1 ENVELOPE stamp: HMAC-SHA256(the RECIPIENT's session key, material) over the canonical zerg-team-mail-v1 || u16be(team_id) || u16be(from_id) || u16be(to_worker_id) || u16be(recipient routing identity) (sol_zmq_frame_mac:mail_countersign_material/3; the recipient identity is bound in explicitly). Present on every push to a CREDENTIALED session; absent only for anonymous (dev) sessions, which have no key material to sign with. It does NOT bind the message content. Luna verifies BEFORE injecting into agent context — a credentialed session that receives a missing/mismatched stamp QUARANTINES the mail (never injected) and counts it (vectors: docs/fixtures/team_plane_hmac_vectors.json) |
hmac2 | binary | no | ** (SC-06)** — the v2 CONTENT stamp, dual-signed with hmac: frame_mac(identity, 'zerg-team-mail-v2' || u16be(team_id) || u16be(from_kind) || u16be(from_id) || u16be(to_worker_id) || u16be(recipient routing identity) || u16be(priority) || u16be(timestamp) || u16be(subject) || u16be(sha256(canonical-JSON body))) (sol_zmq_frame_mac:mail_v2_material/9, mail_hmac_v2/10). Luna requires and verifies hmac2 whenever hmac_v is present: a body/priority/timestamp/subject mutation fails CLOSED even though the v1 envelope hmac still verifies. Vectors: docs/fixtures/team_plane_hmac_vectors.json (mail_v2, mail_v2_canonical) |
hmac_v | integer | no | ** (SC-06)** — signature material version. 2 = body-bound (hmac2 required and verified); any other value is refused. ABSENT = the expiring v1 compatibility posture (envelope-only hmac), refused by default since then (PRT-10). A pre-cutover fleet may open the window with `LUNA_TEAM_MAIL_V1_UNTIL=<epoch |
Builder (Erlang): sol_zmq_protocol:build_team_mail_push_msg/4-5 (/4 =
worker-kind legacy wrapper; /5 = struct form), dual-signed by
sol_zmq_frame_mac:sign_mail_hmac/3 + sign_mail_hmac_v2/3 on the
credentialed push leg
Handler (Lua): zmq_worker.lua:_handle_frames → zmq_team_plane.lua:team_mail_auth
(v2 via core/team_mail_hmac.lua; v1 only when hmac_v is absent)
The recipient replies to team mail by sending NEW mail with to = the
received struct’s from_id — the server resolves it at send time
(user uuid → the member row’s worker_id; worker id → passthrough), so the
reply is always worker-addressable.
9. plugin_tool_result
| Field | Type | Required | Description |
|---|---|---|---|
type | binary | yes | "plugin_tool_result" |
task_id | binary | yes | Plugin tool task ID |
tool_name | binary | yes | Tool name |
status | binary | yes | "ok", "error" |
result | any | no | Tool result (on success) |
error | any | no | Error details (on failure) |
Builder (Erlang): sol_zmq_protocol:build_plugin_tool_result_msg/3
Handler (Lua): zmq_worker.lua:_on_plugin_tool_result/1
: on the timeout path the
errorfield carries the distinguishable reason"plugin_timeout"— the manager-side kill fired atplugin_execute_timeout_ms. Tool semantics are AT LEAST ONCE: the tool MAY HAVE RUN (bridge effects may be committed) when this reason arrives, so retries must be outcome-safe.execution_crashedremains the reason for a genuine worker crash.
: the worker→Sol inbound leg of this frame is RETIRED (Luna’s builder had zero producers; Sol’s inbound handler is deleted). The Sol→Luna reply leg documented above is LIVE — the plugin executor emits these frames and Luna’s inbound arm + validator are untouched.
10. acp_forward
| Field | Type | Required | Description |
|---|---|---|---|
type | binary | yes | "acp_forward" |
request_id | binary | yes | ACP request ID |
from | binary | yes | Sender identity |
acp_type | binary | yes | "request", "notify" |
payload | any | no | Forwarded payload when not merged inline (non-map payloads) |
Builder (Erlang): sol_zmq_protocol:build_acp_forward_msg/4
Handler (Lua): zmq_worker.lua:_on_acp/1
11. acp_discover_reply
| Field | Type | Required | Description |
|---|---|---|---|
type | binary | yes | "acp_discover_reply" |
request_id | binary | yes | ACP request ID |
to | binary | yes | Target worker |
agents | list | yes | Agent descriptors |
Builder (Erlang): sol_zmq_protocol:build_acp_discover_reply/3
Handler (Lua): zmq_worker.lua:_handle_frames
Sol → Luna error (server-initiated control-plane errors)
Sol ALSO sends type: "error" frames to the worker — control-plane
refusals, NACKs and decode feedback. These are bare msgpack maps built
at the refusal sites (never sol_zmq_protocol:build_error_msg/2, which
is the Worker→Sol §16 builder); Luna’s consumer is
zmq_worker.lua:_handle_frames (error leg: decode_error logs
details, unknown_message_type logs reason (the fixed-catalog echo; a
legacy original_type is still tolerated), anything else
logs reason; a task_id on the frame is CONSUMED —,:
orphan_result_stored drops the matching _pending_results retransmit
entries + terminal-spool row precisely, every other reason logs the
correlation at debug).
| Field | Type | Required | Description |
|---|---|---|---|
type | binary | yes | "error" |
reason | binary | yes | Machine-readable cause (vocabulary below) |
details | binary | no | Human-readable auxiliary detail — the ONE auxiliary key. Registration-refusal classes (registration_hmac_failed, protocol_version_mismatch, reserved_identity, identity_banned) carry the refusal detail (the counter_stale class carries the operator hint — host clock skew — instead of the bare atom); the gateway decode_error leg carries the decode-failure detail |
task_id | binary | no | Correlated task — token_too_large, orphan_result_stored, and the gateway_paused NACK when the shed frame carried one |
retry_after_ms | integer | no | Server-paced retry hint — present on the rate/capacity registration refusals (machines_cap_reached and the <registration-rejection atom> arm: registration_rate_limited, registration_limiter_unavailable, cap_reached, worker_id_in_use); Luna’s full-jitter re-registration backoff seeds its base with it (never below the client’s own 1s floor) |
Reason vocabulary as built today (emitter → extras):
reason | Emitter | Extras |
|---|---|---|
decode_error | gateway + recv dispatcher (2-frame payload failed msgpack decode) | details |
missing_type_key | recv dispatcher | — |
unknown_message_type | sol_zmq_handler_default | — |
registration_hmac_failed | sol_zmq_handler_worker (ready credential verification) | details |
protocol_version_mismatch | sol_zmq_handler_worker (ready validation) | details |
malformed_ready | sol_zmq_handler_worker (ready missing worker_id/capabilities) | — |
shared_worker_requires_declaration | sol_zmq_ready_guard | details (remediation hint) |
reserved_identity | sol_zmq_handler_worker (queued/system sentinel identities) | details |
machines_cap_reached | sol_zmq_handler_worker (max_machines license cap) | retry_after_ms |
identity_banned | sol_zmq_handler_worker (duplicate-identity temp-ban ledger) | details |
token_too_large | sol_zmq_handler_worker | task_id |
orphan_result_stored | sol_zmq_handler_worker (orphan-result ack — drains the worker’s retransmit queue) | task_id |
gateway_paused | sol_zmq_send_recovery | task_id (optional) |
<registration-rejection atom> | sol_zmq_handler_worker (register_worker failure — atom_to_binary/1 of the refusal reason) | retry_after_ms |
There is NO code field on this frame either.
26. ready_required
| Field | Type | Required | Description |
|---|---|---|---|
type | binary | yes | "ready_required" |
reason | binary | yes | Why registration is required — closed enum: unregistered (no live registration for the sending identity — the post-VM-restart shape), credential_rotated, evicted |
retry_after_ms | integer | no | Reserved server hint for the client’s re-registration backoff (currently emitted only on the error refusal frames above; absent on this frame today) |
Server-initiated control frame: sent as the
CONTROL-CLASS reply to a heartbeat (or other worker-plane frame) from an
identity with no live registration. The previous silent drop left a
fleet orphaned after a full Sol VM restart — the DEALER transport
auto-reconnects, so the worker’s heartbeats kept flowing while its
registration was gone. Luna answers by degrading connected truthfully
and scheduling a full-jitter re-registration (base seeded by
retry_after_ms when present) that sends a proof-carrying ready (§12 —
fresh nonce + monotonic ctr; the tx watermark is never reset). The frame
is rate-bounded on the send lane (control class: +64 reserve, one retry)
and on the client (exponential ceiling 60s, attempt counter reset on a
successful re-registration).
Builder (Erlang): inline sol_zmq_protocol:encode_message/1 at the
heartbeat refusal arm of sol_zmq_handler_worker.erl, sent via the
control class of sol_zmq_sender:send/3
Handler (Lua): zmq_worker.lua:_on_ready_required/1 (dispatched from the
_handle_frames gate; validated by zmq_protocol.validate_incoming —
reason is required)
28. lane_control_ack
| Field | Type | Required | Description |
|---|---|---|---|
type | binary | yes | "lane_control_ack" |
request_id | binary | yes | Echo of the lane_control.request_id |
status | binary | yes | "granted" | "queued" | "refused" (closed enum) |
reason | binary | yes | Bounded refusal label — present on EVERY refused ack, absent otherwise: orchestrator labels (sol_lane_orchestrator:reason_label/1: unknown_lane, staged_not_grantable, no_weights, no_engine, mode_not_allowed, engine_unvalidated, queue_full, cpu_busy, lane_busy, loading_timeout, start_failed, no_capacity, not_allowed_on_host, lane_not_reachable, not_a_local_lane, no_model_for_lane, missing_identity, invalid_request, other) plus handler-level labels (invalid_action, invalid_request, not_owner, unknown_task, missing_lease_id, stale_grant, lease_lane_mismatch, not_running, stop_failed, registry_unavailable, internal_error) |
reason_detail | binary | no | Bounded sanitized refusal detail (e.g. over-ctx numbers; omitted when oversized) |
lane | binary | no | Lane name (granted/queued) |
endpoint | binary | no | OpenAI-compatible base URL http://host:port — no trailing slash, no /v1 (granted only) |
wire_format | binary | no | "openai" (granted only) |
caps | map | no | Lane capability map (granted only) |
ctx | integer | no | Context size (granted only) |
lease_id | binary | no | Live lease handle — the stop/switch authority (granted only) |
expires_at | integer | no | Unix-ms lease expiry (granted only; absent = unbounded mode). : superseded by expires_in_ms when present — kept for previous peers |
expires_in_ms | integer | no | **** — the lease’s REMAINING lifetime measured on Sol’s monotonic clock at descriptor-build time. The worker derives its deadline from receipt time (its own monotonic clock), so a skewed wall clock can no longer flip a live grant to expired or the reverse. 0 = already expired (fail closed); absent = unbounded, fall back to expires_at |
holder | binary | no | The per-grant holder nonce — echoes on stop/switch; the stop/switch authority is bound to the CURRENT grant, not to possession of the shared lease id |
retry_after_ms | integer | no | Present on queued + cpu_busy/lane_busy/queue_full — the caller’s retry seed |
Sent on the control lane (sol_zmq_sender:send/3 class control —
reserve + one-shot retry) by a spawned resolver. queued does NOT grant an
endpoint: the caller surfaces it / retries per retry_after_ms; an expired
lease or a revocation means re-resolve before reuse (a refused re-resolve
surfaces typed, never a silent fallback).
Builder (Erlang): sol_zmq_protocol:build_lane_control_ack_msg/3
Handler (Lua): Luna ack dispatch
29. lane_revoke
Direction: Sol → Luna.
| Field | Type | Required | Description |
|---|---|---|---|
type | binary | yes | "lane_revoke" |
lane | binary | yes | The lane whose lease died |
lease_id | binary | yes | The dead lease handle — the worker invalidates the matching live grant (keyed by lease_id) |
reason | binary | yes | "stop" (explicit stop/switch release) | "expired" (idle-release expiry sweep) | "failover" (reserved: cross-node failover) |
retry_after_ms | integer | no | Re-resolve pacing hint for the next task boundary |
The G86 vehicle: an advisory early warning, never the authority —
enforcement stays server-side at the lease chokepoint (a revoked lease is
dead regardless of what any worker believes; the next grant attempt
re-resolves). Worker contract: mark the matching grant dead and FINISH the
current turn — no mid-stream interruption; the next task boundary
re-resolves. Safe for mixed fleets by construction: a previous v4 Luna
logs unknown_message_type and continues; a v3 Luna drops the v4 stamp at
its validator; Sol suppresses the push for pre-v4 targets with a visible
counter + log (zmq_frame_suppressed_total, sol_zmq_lane_revoke:push/4
via target_admits/2). Sent on the control lane from the single lease
release funnel (sol_lane_lease:remove_lease/2 — explicit stop/switch AND
the expiry sweep), addressed to the lease’s registered grant holders
.
Builder (Erlang): sol_zmq_protocol:build_lane_revoke_msg/3-4
Handler (Lua): zmq_worker.lua:_on_lane_revoke
30. permission_request
Direction: Luna → Sol.
| Field | Type | Required | Description |
|---|---|---|---|
type | binary | yes | "permission_request" |
task_id | binary | yes | The in-flight task this ask blocks. Sol requires the id to be indexed to the SENDING registration (sol_zmq_ownership:allow_result_frame/4); user_uuid/permissions are derived from the task-store snapshot, NEVER from this frame |
request_id | binary | yes | Worker-scoped ask id (1..128 bytes) — echoed verbatim on the reply |
tool_name | binary | yes | Bare tool name (1..128 bytes) |
input_summary | map | no | Bounded summary — command OR path only (<=4096 bytes each); the raw tool input NEVER rides this frame |
analysis | map | no | {level, patterns} — danger level + bounded pattern labels (never raw input) |
expires_in_ms | integer | no | Ask lifetime (clamped server-side to [1000, 300000]); the worker also enforces its own local deadline and denies typed on lapse |
session_id | binary | no | ** (XS-10)** — the worker-local chat session that originated the ask (1..256 bytes; bounded exactly like Sol’s parser). Sol routes the ask to that session’s operator surface; an unknown/absent session falls back to the operator broadcast, so a sessionless ask is never parked without a surface |
Worker-plane frame: registration + per-frame MAC gated
(sol_zmq_frame_mac:worker_plane_type/1) and classified critical (the
shared criticality manifest — a dropped ask parks the task until its
deadline). Sol registers a sol_permission_registry row and replies with
permission_reply (§31) on resolve, on the operator timeout, or when the
task reaches a terminal state (deny task_finished).
Handler (Erlang): sol_zmq_handler_agent.erl
Builder (Lua): zmq_protocol.lua:permission_request_message/7
Worker → Sol
** ownership enforcement:**
token/result/errorframes are accepted only from the worker thetask_idwas dispatched to (sol_zmq_ownership:allow_result_frame/4— index-owner match; on an index miss the sender must equal the RECORDED executor stamped at dispatch bysol_task_store:get_last_executor/1, a bounded WARNING grace; no recorded executor or a foreign one is refused + counted). The previous “currently registered sender” grace is DELETED — a registered worker cannot claim an executor-less index miss;spawnrequires the sender to ownparent_task_id;event/acp/acp_reply/plugin_tool_call/team_*require a registered worker identity and frame-suppliedfrom/member_idfields are never identity. Dropped frames incrementsol_zmq_auth_failures_total. Gate:zmq_ownership_enforced(default true).
12. ready
| Field | Type | Required | Description |
|---|---|---|---|
type | binary | yes | "ready" |
version | integer | yes | Protocol version — the current sol_zmq_protocol:protocol_version/0, or, since then and while zmq_wire_skew_window=true, exactly one below it (the N−1 rolling-upgrade window); anything else is refused (version_mismatch) |
min_version | integer | no | : the field is INTEGER-ONLY — a present non-integer (a float such as 4.0, a string, a map) is refused with the typed malformed_ready class before any version arm (the pre-fix exact-version/N−1 arms returned ok for a float, bypassing the future-min check). Lowest protocol version the worker accepts; a value ABOVE Sol’s version fails the handshake (min_version_too_new) on the exact-version arm AND the N−1 skew arm |
worker_id | binary | yes | Worker identity (also the DEALER routing identity). ** (WIRE-02):** a non-empty binary of at most 256 bytes; any other msgpack term is refused with malformed_ready (the row is never persisted — the operator worker view cannot inherit an unencodable term) |
capabilities | array-of-strings | yes | Worker capability list. ** (WIRE-02):** a bounded array (≤ 256 entries) of non-empty binaries (≤ 256 bytes each); a map/list-key/non-binary term is refused with malformed_ready (details invalid_ready_field:capabilities) |
capability_bits | array-of-strings | no | ** (XS-02)** — the explicit capability epoch that replaced the protocol integer as the feature discriminator. Known bits: frame_mac_v3, cancel_reason, attempt_echo, lane_control. Absent = the version-derived defaults (v4 adds lane_control; v3 does not). An explicit array is AUTHORITATIVE in both directions — a v4 peer may decline a feature and a v3 peer may advertise forward. Sol caps the list at 64 binary entries and stores it on the worker; the dispatcher grants a LANE only when lane_control is advertised (otherwise it skips the grant/consumption and counts lane_capability_skipped_total) |
modes | array-of-strings | no | : bounded — at most 64 entries of at most 256 bytes each (the normalizer walks only the cap; a malformed/over-cap-entry advertisement degrades to []). Agent-mode names this worker can resolve — non-empty binaries. Sol normalizes it (a malformed advertisement degrades to [] with a warning, never a registration refusal) and clamps task-frame mode values against it. Absent/[] = nothing advertised (every requested mode falls back) |
hostname | binary | no | Registering machine’s hostname |
task_id | binary | no | In-flight task being resumed on reconnect |
child_depth | integer | no | Child-spawn depth (bound into the HMAC material; absent = 0) |
key_id | binary | no | Per-worker enrollment key name — absent or "fleet-legacy" selects the shared fleet secret while zmq_fleet_legacy_compat=true; unknown/revoked → registration refused |
nonce | binary | conditional | Fresh registration nonce — REQUIRED whenever a fleet secret or enrollment key is configured ({error, missing_nonce} otherwise) |
ctr | integer | conditional | Monotonic ready counter — u64 wall-clock milliseconds, strictly increasing per identity, freshness-bounded; REQUIRED with a secret configured ({error, missing_counter}), bound into the HMAC material (registration_signed_material/5), refused on replay/staleness (counter_replayed / counter_stale). ** (WIRE-03):** the freshness bounds are ONE clock domain with the frame tx: at most 10 minutes in the PAST and at most 24 hours in the FUTURE (sol_zmq_indexes shared ?REPLAY_FUTURE_AHEAD_MS). A value beyond the future window is refused without persisting; recovery is the signed sol_zmq_indexes:retire_identity/2 reset plus a Luna restart with LUNA_RESET_REPLAY_WATERMARKS=1 (a clock sync alone cannot clear a PERSISTED future floor) |
hmac | binary | conditional | Registration HMAC (see docs/zmq-security.md); REQUIRED with a secret configured ({error, missing_hmac} otherwise) |
sandbox_layers_effective | binary | no | APPLIED sandbox-layer composition telemetry — "bwrap" / "landlock" / "none" / "disabled", optionally with +zero_layer_spawns=<N> and/or +mcp_stdio_containment=active:<N>,fallback:<N>,off:<N>,post_hoc:<N> suffixes; additive optional. Consumption is TOTAL: the enrollment verifier’s parser accepts the four postures, both suffix classes, the legacy probe strings (landlock-abi<N> / unavailable(...)), bare decimal layer counts, and unknown future tokens — an unrecognized base maps to the loud inert posture with its raw name preserved in the posture label, and nothing is silently dropped. The gauge is absolute per {sandbox_effective, WorkerId} and SolLunaSandboxInert pages on the inert posture. Server authorization gates never trust this client-declared value |
mcp_servers | integer | no | : the worker’s LIVE MCP server count (connected + protocol-initialized) at READY time. Additive, telemetry only — Sol normalizes a malformed value to 0 (never a registration refusal) and exposes it via GET /api/v1/zmq/workers; no authorization gate reads it |
mcp_tools | integer | no | : the number of registered mcp__* tool specs at READY time (same normalization/exposure as mcp_servers) |
custom_tools | integer | no | : the number of registered custom tools (discovered from ~/.luna/tools + <workspace>/.luna/tools) at READY time |
models | array-of-strings | no | ** (XSV-13)** — the bounded (64 entries × 128 bytes) model aliases this worker’s provider config can serve (core/zmq_model_capability.collect/0). Sol gates dispatch target selection on it: a READY worker advertising a NON-EMPTY inventory missing the task model is skipped, and a fleet with no capable worker returns the typed {no_capable_worker, Model} pre-dispatch refusal. ABSENT/[] = legacy worker (cannot be gated; the dispatch is counted). Additive, not part of the signed registration material |
capability_degradations | array-of-strings | no | : typed reasons a capability is ABSENT — mcp_approval_required:<server> (a project .luna/mcp.json server denied by the hash-keyed approval gate; fail-closed), mcp_start_deferred:<server> (did not fit the bounded boot start budget; completed at the first task boundary), mcp_start_failed:<server> (start/init/discovery failed). A live server that crashes mid-task is tracked by the telemetry.mcp.server_failed event + Luna’s per-server failure counter (mcp_client.server_failure_count) — the READY census carries start-time state only. Sol filters non-binary/empty entries, caps the list at 32 and exposes it on the worker row; absent/[] = no known degradation |
skills_revision | integer | no | **** — the skill-registry revision this worker last materialized (from skill_sync, §6). Sol compares it against the live registry revision and only pushes the full skill_sync on a mismatch or absence (a matching revision skips the resend). Telemetry-grade: it gates re-sending content, never authorization. Additive, malformed = omitted (always resync) |
settings_revision | integer | no | **** — the managed-settings revision this worker last applied (from settings_sync, §32). Sol compares it against sol_managed_settings_owner:revision/0 and pushes the current snapshot on a mismatch or absence (a matching revision skips the resend). Telemetry-grade: it gates re-sending content, never authorization. Additive, malformed = omitted (always resync) |
team_memberships | array-of-maps | no | : bounded — at most 64 entries; an over-cap or non-list/non-map-entry READY is refused with the typed malformed_ready class BEFORE the per-entry HMAC/registry fan (the funnel also slices defensively). ** T2b** — the version-stamped membership-acceptance countersigns: each entry is {"team_id": <binary>, "sig_version": 1, "hmac": <hex>} where hmac = HMAC-SHA256(the worker's SESSION key, zerg-team-member-v1 || u16be(team_id) || u16be(worker_id)) (sol_zmq_frame_mac:membership_countersign_material/2). Only the real credential holder can produce it, so a verified entry IS the worker’s consent: Sol flips the matching PENDING consent row to granted. Fail-closed posture: an OLD worker (no key) or an anonymous session never activates anything — its pending rows simply stay pending (never a registration refusal); wrong sig_version/shape/binding is counted + warned with the row unchanged. Not part of the registration hmac material (each entry carries its own signature). Vectors: docs/fixtures/team_plane_hmac_vectors.json |
Pre-auth refusal addressing + READY shape.
Every pre-auth READY refusal (malformed_ready, registration_hmac_failed,
protocol_version_mismatch) is delivered ONLY to the identity’s READY-bound
delivering pipe — the same bound_pipe_matches transport proof as the
decode-error echo. A refused READY never creates a binding, so a
first-registration failure is silent to the peer (the log + counter are the
operator surface); a foreign pipe can never make Sol emit a refusal toward a
victim identity. READY worker_id/capabilities are type- and
length-validated before any state write (invalid_ready_field:<field> in
details); a hostile shape cannot 500 GET /api/v1/zmq/workers.
Builder (Lua): zmq_protocol.lua:ready_message/2-6 (stamps v + version; material v2 carries ctr when a secret is present)
Handler (Erlang): sol_zmq_handler_worker.erl (registration: HMAC,
enrollment, nonce LRU + monotonic ctr, adoption proof) + sol_zmq_protocol:validate_ready_msg/1
13. heartbeat
| Field | Type | Required | Description |
|---|---|---|---|
type | binary | yes | "heartbeat" |
worker_id | binary | yes | Sender identity |
Liveness frame sent every 5s while connected ( — a plain heartbeat;
the ONE config-gated exception is the idle re-ready,
LUNA_ZMQ_REREADY_IDLE_MS, — a fully signed registration,
idle-only, default OFF). Requires CURRENT registration — an unregistered
identity’s heartbeat is refused + counted and, since then
answered with the typed ready_required control frame (§26) —
the pre-fix silent drop left workers orphaned after a Sol VM restart. On
success it refreshes the worker’s last_seen (touch_worker); for a busy
worker it ALSO refreshes the current task’s ownership-index liveness
timestamp (touch_task — a long-running task never ages into the 1h
sweep) and renews the workflow bridge-correlation lease
(sol_workflow_bridge:renew_correlation/1).
Builder (Lua): zmq_protocol.lua:heartbeat_message/1
Handler (Erlang): sol_zmq_handler_worker.erl (heartbeat → liveness touch)
14. token
| Field | Type | Required | Description |
|---|---|---|---|
type | binary | yes | "token" |
task_id | binary | yes | Task ID |
content | binary | yes | Token text |
seq | integer | no* | Per-task monotonically increasing token sequence. Stamped at BUILD time by the caller’s per-task counter (zmq_protocol.lua:token_message/3 includes it when non-nil); retransmits re-send the same encoded payload, so seq is monotonic across retransmits. Sol REQUIRES it from a v2 worker — a seq-less token frame is a protocol violation (sol_zmq_handler_worker.erl stores it without gap tracking, never drops it). The gap detector (truncated flag + counters) lives in the token store |
attempt | integer | no | ** (WIRE-05)** — the dispatch retry epoch of the stream (same field/contract as §15/§16). Absent = 1; a frame whose attempt is LOWER than the current dispatch attempt is REFUSED before the lease renewal and the store append (zmq_stale_attempt_dropped_total), so a dead attempt’s text never joins the transcript. Rows are keyed {task_id, attempt, seq} and an attempt reset (seq 0) reaps the prior attempts’ transcript AND expected-seq rows. A higher attempt is not refused |
Builder (Lua): zmq_protocol.lua:token_message/2-3
Handler (Erlang): sol_zmq_handler_worker.erl (result-plane ownership gate allow_result_frame/4; seq rides through to the store)
Token content is server-side bounded at 1 MiB (1048576 bytes,
?TOKEN_MAX_CONTENT_BYTES, ): an oversized token is refused
with an explicit error frame carrying reason: "token_too_large" — never
silently truncated.
15. result
| Field | Type | Required | Description |
|---|---|---|---|
type | binary | yes | "result" |
task_id | binary | yes | Task ID |
status | binary | yes | "ok", "cancelled", "completed", "error" — the closed allowlist; anything else is coerced to "error" server-side. "timeout"/"crashed" are SERVER-WRITTEN only, never worker-sent |
content | any | yes | Result content |
user_uuid | binary | no | Worker user identity — never trusted |
attempt | integer | no | ** (WIRE-04)** — the dispatch retry epoch of the execution that produced this terminal (same bounded integer as the task frame, 1..2147483647). Luna stamps it from the executing task context; unknown omits the field (never fabricated). Sol treats absent/malformed as 1 and refuses a terminal whose attempt is LOWER than the current dispatch attempt (stale-attempt result: never stored/counted as completed). A HIGHER attempt is NOT refused (the documented forward-compatible contract); the store’s first-terminal-write rule still governs |
usage | map | no | ** (XSV-03)** — the additive settlement rider {input_tokens, output_tokens, cache_creation_tokens, cache_read_tokens} (non-negative integers; an all-zero block is treated as absent). Sol settles exactly once per {task_id, attempt}. |
model | binary | no | The model that actually served the turn (rides with usage). |
Builder (Lua): zmq_protocol.lua:result_message/4-5 (opts.attempt is the additive stamp; opts.usage/opts.model are the settlement rider)
Handler (Erlang): sol_zmq_handler_worker.erl (result-plane ownership gate allow_result_frame/4)
16. error
| Field | Type | Required | Description |
|---|---|---|---|
type | binary | yes | "error" |
task_id | binary | yes | Task ID |
error | any | yes | Error description |
attempt | integer | no | ** (WIRE-04)** — the same executing dispatch attempt as the result frame; Sol’s one current-attempt gate applies identically. Absent = 1; LOWER than the current attempt is stale (refused + counted); a HIGHER attempt is not refused |
usage | map | no | ** ** — the SAME additive settlement rider as the result frame. A failed turn that burned tokens settles even when its row write loses to a server cancel/timeout. |
model | binary | no | The model that actually served the turn (rides with usage). |
There is NO code field on the wire error frame — the builders
(zmq_protocol.lua:error_message/2-3, sol_zmq_protocol:build_error_msg/2)
emit exactly these keys (plus v, and the optional additive attempt/usage/model).
Builder (Lua): zmq_protocol.lua:error_message/2-3
Handler (Erlang): sol_zmq_handler_worker.erl (result-plane ownership gate allow_result_frame/4)
16a. usage (worker → Sol)
** (XSV-03):** the usage-ONLY terminal rider for an attempt
resolved by a server timeout-cancel. The retry owns the task row, so Luna
emits no result/error (which could freeze the row) — just the attempt’s
provider spend. Sol settles it without writing the task row.
| Field | Type | Required | Description |
|---|---|---|---|
type | binary | yes | "usage" |
task_id | binary | yes | Task ID |
usage | map | yes | The same sanitized token block as the result/error rider (all-zero blocks are omitted, never sent) |
model | binary | no | The model that served the attempt |
attempt | integer | no | The interrupted dispatch attempt (absent = 1) |
Builder (Lua): zmq_protocol.lua:usage_message/4
Handler (Erlang): sol_zmq_handler_worker.erl:handle(<<"usage">>,...) — ownership-gated, settlement only (no store write)
17. spawn
| Field | Type | Required | Description |
|---|---|---|---|
type | binary | yes | "spawn" |
parent_task_id | binary | yes | Parent task ID (ownership-gated: must be dispatched to the sender) |
prompt | binary | yes | Child prompt |
model | binary | no | Model override |
opts | map | no | Spawn options. Carries the parent trust posture additive keys: permission_mode (ceiling-clamped; Sol’s dispatcher forwards it onto the child task frame) and permission_rules |
user_uuid | binary | no | Requesting user identity propagated to the child — Luna ALWAYS emits it (defaulting to "system", zmq_protocol.lua:spawn_message/5); Sol’s builder keeps it only when a non-empty binary (sol_zmq_protocol:build_spawn_msg/3) |
allowed_tools | list | no | Tool restrictions |
cache_context | map | no | Cache context |
permissions | list | no | RBAC permissions for the child — always present (possibly empty) since then |
async | boolean | no | True if background spawn (fire-and-forget) |
There is NO task_id field on the spawn frame (removed from the spec
): the server assigns the child id, which the worker learns
from spawn_ack.child_task_id. Child spawns consume a license seat.
Builder (Lua): zmq_protocol.lua:spawn_message/5, spawn_async_message/5
Handler (Erlang): sol_zmq_handler_agent.erl (spawn parent binding in sol_zmq_bg_task:start/5)
18. cancel_task
| Field | Type | Required | Description |
|---|---|---|---|
type | binary | yes | "cancel_task" |
task_id | binary | yes | Task to cancel |
Worker-initiated cancellation of one of its own tasks (own-task-only gate — ).
Builder (Lua): zmq_protocol.lua:cancel_task_message/1
Handler (Erlang): sol_zmq_handler_agent.erl (ownership gate in sol_zmq_bg_task:kill/3)
20. event
| Field | Type | Required | Description |
|---|---|---|---|
type | binary | yes | "event" |
event_type | binary | yes | Event type name — namespace CLOSED to telemetry.* and agent.* diagnostics; core state events (task.*, workflow.*, team.*, scheduler.*, model.*) from ZMQ workers are dropped + counted |
data | map | no | Event payload — ALWAYS emitted by Luna (defaults {}, zmq_protocol.lua:event_message/3); caller-supplied user_uuid stripped server-side |
task_id | binary | no | Associated task — ALWAYS emitted by Luna (defaults ""). For agent.child_completed this MUST be the SERVER child task id (a dispatched id), never a client-local background id: Sol resolves the aggregate against the dispatch index. A background child may execute on a DIFFERENT worker than the parent, so the gate also accepts the server-recorded child→parent relationship when the sender owns the parent; a legacy client-local id is accepted only with a frame parent_task_id the sender owns, and the aggregate is re-stamped to that server parent id |
Builder (Lua): zmq_protocol.lua:event_message/3
Handler (Erlang): sol_zmq_handler_agent.erl (event allowlist)
21. acp
| Field | Type | Required | Description |
|---|---|---|---|
type | binary | yes | "acp" |
acp_type | binary | yes | "request", "response", "notify" — "notify" is accepted and acknowledged with no reply (sol_acp_router.erl → {ok, notified}) |
request_id | binary | no | Correlates request/response pairs |
from | binary | no | Sender identity — DISCARDED; attribution always uses the socket-bound routing identity |
user_uuid | binary | no | ** (WIRE-06): REFUSED/STRIPPED** — the ACP plane carries no user principal. Sol removes the key at the handler and in the forward builder (sanitize_acp_forward_payload); Luna’s idle agent always runs under its per-connection anonymous scope (anon:<worker_id>). A frame value can never select another user’s memory/audit scope |
| … | map | no | Remaining map keys forwarded as the ACP payload. acp_type=capability: the from AgentId MUST equal the verified routing identity (WIRE-07) — a conflicting claim is refused agent_id_mismatch; the registry refreshes last_seen on every routed/delivered request so a live agent never expires |
Agent-to-agent messaging; dispatched to sol_zmq_handler_agent, which
routes to the target agent (local or remote) and can reply with an
acp_reply or acp_discover_reply.
Builder (Lua): sent raw by the worker (no dedicated builder)
Handler (Erlang): sol_zmq_handler_agent.erl (ACP frame routing; requires registration)
22. acp_reply
| Field | Type | Required | Description |
|---|---|---|---|
type | binary | yes | "acp_reply" |
worker_id | binary | yes | Responding worker |
request_id | binary | yes | Original request ID (must match a request actually ZMQ-forwarded to this identity) |
response | any | yes | Response content |
error | any | no | Error description |
timestamp | integer | yes | Unix timestamp |
Builder (Lua): zmq_protocol.lua:acp_reply_message/4
Handler (Erlang): sol_zmq_handler_agent.erl
23. plugin_tool_call
| Field | Type | Required | Description |
|---|---|---|---|
type | binary | yes | "plugin_tool_call" |
task_id | binary | yes | Task the tool call belongs to (ownership-gated) |
tool_name | binary | yes | Plugin tool name (plugin__<plugin>__<tool>) |
input | map | yes | Tool input arguments |
Worker requests a Sol-side plugin tool execution (Luerl bridge dispatch).
Builder (Lua): zmq_protocol.lua:plugin_tool_call_message/3
Handler (Erlang): sol_zmq_handler_agent.erl (ownership-gated)
24. team_heartbeat
| Field | Type | Required | Description |
|---|---|---|---|
type | binary | yes | "team_heartbeat" |
team_id | binary | yes | Team identifier |
member_id | binary | yes | Worker identity — liveness is recorded for the SENDER’s registered worker, never the frame-supplied member_id |
status | binary | no | "active", "idle", "busy" |
load | number | no | Current load factor |
Requires registration AND team membership of the sender’s registered
worker_id.
Builder (Lua): zmq_protocol.lua:team_heartbeat/4
Handler (Erlang): sol_zmq_handler_team.erl
25. team_mail
| Field | Type | Required | Description |
|---|---|---|---|
type | binary | yes | "team_mail" |
team_id | binary | yes | Team identifier |
from | map | no | Sender struct {kind, id} — kind = "worker"|"user", id = binary. ADVISORY on this direction: Sol derives the struct from the verified registration (kind worker); a frame-supplied value is never identity |
to | binary | no | Recipient — member worker_id, member tm_* id, member user_uuid, or "all" (default). Resolved-and-stamped at send time: storage keeps the canonical form (to is ALWAYS a worker_id or all after resolution); unresolvable values are refused loudly |
body | map | no | Mail content |
subject | binary | no | Optional mail subject — Luna stamps it from body.subject (zmq_protocol.lua:team_mail/5); Sol’s ZMQ handler currently ignores it (no server-side consumption) |
priority | binary | no | "normal", "high", "low" |
Requires registration AND team membership.
Sender struct + reply-to semantics: mail is
cross-identity — the stored struct {kind, id} is typed by ORIGIN
(worker = ZMQ registered sender; user = HTTP authenticated caller). A
recipient replies by sending new mail with to = the received struct’s
id; the server resolves it (user uuid → that user’s member row
worker_id; no member row → loud refusal — unroutable_to on HTTP, a
refusal log + drop on ZMQ).
Builder (Lua): zmq_protocol.lua:team_mail/5 (sender_struct/1 pins the
shape)
Handler (Erlang): sol_zmq_handler_team.erl
27. lane_control
| Field | Type | Required | Description |
|---|---|---|---|
type | binary | yes | "lane_control" |
request_id | binary | yes | Worker-scoped request id (1..128 bytes; generated per attempt). Idempotency key: namespaced {worker_id, request_id} server-side, so two workers with the same wire id never share a cache row; a replay with the same id while the first is in flight is deduped, a retry with a new id replaces the in-flight resolver |
action | binary | yes | "resolve" | "start" | "stop" | "switch" | "refresh" | "release" — resolve/start run the full sol_lane_orchestrator:request/2 (bounded queue wait + ready budget; start is the explicit-wait alias); stop/switch/refresh/release require a live lease_id |
task_id | binary | no | Required for resolve/start (ownership binding; the id must be indexed to the SENDING registration via sol_zmq_ownership:task_sender/2; user_uuid/permissions come from the task store, NEVER from this frame). Optional echo for refresh/release; their identity comes from the task-anchored grant holder |
lane | binary | no | Explicit lane pin (existing-atom only; unknown → typed refusal). For stop/switch it must match the lease’s lane |
requirements | map | no | Capability-router vocabulary — flat requirements; Sol does the matching, Luna never routes |
mode | binary | no | "on_demand" (default) | "attended" | "duration" | "cron" |
ttl_ms | integer | no | Lease TTL for duration/cron modes |
lease_id | binary | no | REQUIRED for stop/switch/refresh/release — the live grant handle |
holder | binary | conditional | Required for refresh/release and task-less switch/stop — the holder nonce minted with the task-anchored grant. It gates the action; a missing/mismatched holder is not_holder/stale_grant. Never an identity source |
Session actions. An editor holds one lease across turns: the
first resolve/start is task-anchored and records the holder; refresh
renews under the lease’s own mode and replies receipt-relative
expires_in_ms/expires_at; release tombstones the holder and re-arms the
idle clock without stopping a shared lane; task-less switch/stop derive
their identity from the holder. Expiry is a typed stale_grant — the client
re-requests, never silently falls back. Audit actions:
lane_session_refresh|release|switch|stop (acquire keeps
lane_granted/lane_lease_acquired).
Worker-plane frame: registration + per-frame MAC gated (worker_plane_type/1),
and classified critical (never shed — the send lane retransmits it).
The reply is asynchronous (lane_control_ack, §28) — the gateway never
blocks; resolve/start may wait the configured queue/ready budgets in a
spawned resolver.
Handler (Erlang): sol_zmq_handler_lane.erl (frame router)
Builder (Lua): zmq_protocol.lua:lane_control_message/4
31. permission_reply
Direction: Sol → Luna.
| Field | Type | Required | Description |
|---|---|---|---|
type | binary | yes | "permission_reply" |
request_id | binary | yes | Echo of the permission_request.request_id |
decision | binary | yes | "allow" | "deny" | "always" (closed enum — always alone may persist in the worker’s 600s cache) |
reason | binary | no | Bounded decision label (operator_allow/operator_deny/operator_always/timeout/client_gone/worker_gone/task_finished) |
Sent on the control lane (sol_zmq_sender:send/3 class control). Luna
validates the closed decision enum and hands the answer to the parked
permission hook by request_id; an unknown/expired id is dropped loudly.
Builder (Erlang): sol_zmq_protocol:build_permission_reply_msg/3-4
Handler (Lua): zmq_worker.lua:_on_permission_reply/1
Status Values (result frames)
| Status | Meaning |
|---|---|
"ok" | Success (worker result frame) |
"error" | Failure — a worker result frame with a non-allowlisted status is coerced to "error" server-side |
"completed" | Success (worker result frame) |
"cancelled" | Task was cancelled (worker result frame) |
"timeout" | Task timed out — server-written only (worker result frames never carry it; the gateway’s task_timeout_ms expiry writes it) |
"crashed" | Worker crashed — server-written only |
Worker result frame status allowlist = ok|cancelled|completed|error
. timeout/crashed are server-side
terminal rows.
Ownership & Registration Semantics
Registration authentication: shared fleet secret
(SOL_ZMQ_WORKER_SECRET, ≥ 16 bytes) or per-worker enrollment keys
(zmq_enrollment_keys + key_id, preferred) — HMAC-SHA256 over
nonce || u16(len(identity)) || identity || u16(len(worker_id)) || worker_id || u32(child_depth) || u64(ctr) with constant-time compare; nonces are
replay-protected (per-identity LRU, 60s TTL, survives gateway restarts).
Full material: docs/zmq-security.md (§Worker Registration).
Non-loopback binds refuse open registration (prod): secret required —
{refuse_boot, zmq_secret_required}; loopback binds keep the dev posture.
Result-plane ownership: allow_result_frame/4 — index-owner match;
on an index miss the sender must match the RECORDED executor stamped at
dispatch (sol_task_store:get_last_executor/1, bounded WARNING grace);
no recorded executor or a foreign executor is refused + counted. The
previous “currently registered sender” grace is DELETED. A registered
worker cannot create synthetic tasks: writes for task ids with no
ownership-index entry, no sol_task_results pending row and no
dispatch-queue seat are rejected. Terminal states reject all later writes.
Event namespace closed: only telemetry.* / agent.* diagnostics
from ZMQ workers; core state events are HTTP/internally sourced.
Spawn parent binding: spawn/plugin_tool_call frames require the
referenced task to have been dispatched to the sending worker; cancel_task
is own-task-only.
Orphan results: a result/error frame for a task the
server no longer knows (post-restart, row + index + queue seat lost) is
stored in the bounded orphan-results store (queryable by task id), counted
in orphan_result_total (CRITICAL log), and acked so the worker’s
retransmit queue drains. Tokens are stored without ack (Luna never
retransmits tokens).
Loss Policy
Version provenance:, shed-set truth; shared manifest.
Under mailbox high-water-mark backpressure only true diagnostics are shed:
Critical frames (sol_zmq_recv_dispatcher:is_critical_type/1) are
never dropped at either the recv dispatcher or the gateway: result,
error, ready, cancel_ack, child_result,
token, heartbeat, spawn, cancel_task, and the coordination set
team_directive, team_mail, team_heartbeat, acp,
plugin_tool_call ( — these were shed as diagnostics
contrary to the documented policy; they are round-trip/liveness frames
and joined the critical set, the fixture, and Luna’s EAGAIN critical
lane; / retired the worker→Sol log + plugin_tool_result
rows with their frames).
Droppable under load: event frames whose event_type has the
telemetry. prefix (no producer emits a bare telemetry type — telemetry
rides event frames, ), and acp_reply (a reply
frame whose caller-side timeout governs — kept shed-eligible so a paused
mailbox is never held for replies the caller has already abandoned).
While the gateway is paused on HWM it synthesizes liveness touches for
registered workers (heartbeat is liveness — dropping it would evict the
fleet); any frame the paused gateway still sheds is NACKed with an
explicit error frame.
Shared send-criticality manifest: the critical /
droppable classification for every worker-sendable frame type is pinned
byte-for-byte by docs/fixtures/zmq_send_criticality.json, consumed by
BOTH sides — Sol’s recv dispatcher boot-refuses on drift from its
hardcoded classes (sol_zmq_recv_dispatcher:verify_send_criticality/0),
and Luna’s EAGAIN send-lane table (client/core/zmq_protocol.lua
SEND_CRITICAL_TYPES, consumed by zmq_worker:_send) is pinned by
client/tests/test_zmq_send_criticality.lua. The manifest’s birth killed
the cancel_task lane omission (a dropped child-cancel under EAGAIN
backpressure stranded the child running silently).
Sender Bounds
Sol’s per-identity app-layer outbound bound (zmq_sender_outbound_bound,
default 512 sends / 60s sliding window) admits every send through a class:
| Class | Budget | Over-budget | Send failure | Frame classes routed here |
|---|---|---|---|---|
data (default) | the bound | dropped LOUD (WARNING + zmq_sender_outbound_dropped_total) | logged + zmq_send_failures_total | task, child_result, team_mail_push, acp_forward, acp_discover_reply, plugin_tool_result replies, generic error replies |
telemetry | the bound | same as data | same as data | diagnostics |
control | bound + 64 reserve | journaled frames are RETAINED and replayed (only the binding outbound counter advances); unjournaled drops are CRITICAL and bump BOTH drop counters | exactly ONE retry (?CONTROL_RETRY_MS); a journaled frame stays outstanding for replay on restart/READY, an unjournaled final failure is a CRITICAL drop (zmq_control_send_dropped_total) | spawn_ack, cancel, cancel_ack, skill_sync, team_directive |
send_sync/2 is intentionally NOT budget-bound: its callers receive
{error, _} and the gateway requeues — flow control exists at that layer.
Per-Frame MAC
Worker→Sol worker-plane frames (token, result, error, heartbeat,
team_directive since then ) AND the extended
agent/team plane (spawn, event, acp, acp_reply, team_heartbeat,
team_mail,; joined by cancel_task,
plugin_tool_call in — same
extended plane, same material-v3 tx binding; the set is pinned
byte-for-byte in docs/fixtures/zmq_frame_mac_sets.json; /
removed log/plugin_tool_result with their frames) from
credentialed sessions carry a trailing multipart MAC frame —
[payload, mac_hex] — over the exact
payload bytes
with the routing identity AND the per-session monotonic tx counter bound
in (material v3, "Z3"); Sol verifies pre-handler in the frame router and
refuses replayed tx values per identity. Full contract (material,
session-key derivation, mode lever zmq_frame_mac, the
zmq_frame_mac_legacy fleet-legacy window,
identity pinning of duplicate-identity conflicts, plane coverage):
docs/zmq-security.md → “Per-Frame MAC
Plane”. ready is covered by its own registration HMAC above. The
tx key is additive on the v3 wire (old peers ignore it); the cross-language
vectors live in docs/fixtures/zmq_frame_mac_vectors.json.
team_directive additionally carries the
enrollment-bound content signature + leader attribution documented in
§7 (Sol→Worker direction).
32. settings_sync
Direction: Sol → Luna.
| Field | Type | Required | Description |
|---|---|---|---|
type | binary | yes | "settings_sync" |
settings | map | yes | The current managed-settings snapshot — the same JSON-safe map the HTTP GET serves |
revision | integer | yes | The Sol managed-settings revision at push time (monotonic per Sol boot, seeded from wall clock so a restart always mismatches) |
The PUB plane is best-effort and a reconnecting worker (slow joiner) can
miss managed_settings_update. READY carries the revision the worker last
applied (settings_revision, §12); Sol pushes this frame over the reliable
ROUTER plane on a mismatch/absence (the skill_sync revision
precedent). Luna applies the snapshot to core.managed_config (cache +
next-task reads) and records the revision, so the next READY matches.
PUB class disposition: managed_settings_update is state
(newest snapshot wins; a full-queue preemption evicts an ephemeral frame
first), circuit.* and workflow.compensation are ephemeral
(in-flight work re-derives them / the server circuit plane is
authoritative), all other topics are telemetry. Per-class drop
counters make a stalled subscriber’s blast radius visible; the PUB HWM and
linger knobs are INERT on chumak 1.5.0 and named once at boot (the real
bound is the bounded queue + per-frame send timeout).
Builder (Erlang): sol_zmq_protocol:build_settings_sync_msg/2-3
Handler (Lua): zmq_worker.lua:_on_settings_sync/1 → core.managed_config.apply_sync/2
Test-Only Messages
These builders exist in sol_zmq_protocol.erl inside -ifdef(TEST). and
are not used in production:
| Message | Builder | Purpose |
|---|---|---|
| team_create | build_team_create_msg/3 | Team creation notification (deprecated — HTTP API) |
| team_mail | build_team_mail_msg/5 | Team mail (deprecated) |
| team_heartbeat | build_team_heartbeat_msg/4 | Server→Worker heartbeat (Luna→Sol heartbeat is #13) |
| plugin_tool_call | build_plugin_tool_call_msg/3 | Server-side plugin dispatch (the Worker→Sol plugin_tool_call is frame #23) |
Protocol Version
Sol constant: sol_zmq_protocol:protocol_version/0 (= 4, since then
the v3 → v4 bump introduced the task-frame
inference_binding lane-grant stamp and the lane_control /
lane_control_ack round-trip (§27/§28); the v2 → v3 bump before it
carried the team_directive leader attribution + content signature
fields and the team_directive MAC-plane extension;
the v1 → v2 bump before that carried the token seq frame,
)
Luna constant: zmq_protocol.lua:M.VERSION (= 4)
ready.version must equal the gateway’s protocol version, or (while
zmq_wire_skew_window=true) exactly one below it; ready.min_version
above it fails the handshake on the exact-version arm (the N−1 arm does
not bound it — ); every frame carries v (absent = v1).
A mismatch is logged and the connection is rejected (never silently
downgraded) — v2 and older are refused loudly; v3 is admitted only
inside the N/N−1 window ( STRICT-FORWARD; skew window;
v4 bump). Upgrade posture for v4 is stop-then-upgrade: a v3
Sol drops lane_control silently, so lane consumption requires both
ends at v4.
The ready-handshake examples in docs/worker-integration.md and
example/python/zmq_worker.py are pinned to the CURRENT constant by
ci/wire_doc_parity_lint.py (the pin parses ?PROTOCOL_VERSION — a
bump without the examples fails CI).
Engine reference — generated from the canonical engineering source. Do not edit this page by hand.
Worker Integration Guide
Sol supports two worker integration paths for connecting external agents to the orchestration platform.
Path Comparison
| Feature | ZMQ DEALER | JSONL Stdio |
|---|---|---|
| Protocol | msgpack over ZMQ | JSON lines over stdin/stdout |
| Language | Any (ZMQ + msgpack bindings) | Any (stdin/stdout) |
| Process management | External (worker manages itself) | Sol spawns via erlexec |
| Streaming tokens | Yes | Yes |
| Task cancellation | Yes | Yes |
| Child task spawning | Yes | No |
| Reconnection | Automatic (ZMQ) | Process restart |
| Dependencies | libzmq, msgpack | None |
| Best for | Long-running workers, polyglot | Short-lived workers, simple agents |
Path A: ZMQ DEALER Worker (Recommended)
How It Works
Worker (DEALER) ←──msgpack──→ Sol ROUTER (port 5555)
Workers connect to Sol’s ZMQ ROUTER gateway, register with a ready message, and receive task messages asynchronously. Results are streamed back via token and result messages. Liveness while connected is carried by plain heartbeat frames.
Re-READY hazard:
readyis a (re)connect signal ONLY — it is sent once on connect and again on a genuine reconnect (with the resume proof). Never re-sendreadywhile connected: if the worker finished its task but Sol still holds it (result delayed in a queue), a proof-less re-ready trips Sol’s fail-closed adoption gate and orphans the in-flight task with aworker_reconnectederror — exactly on the re-ready mark. Heartbeats carry liveness (touch_worker); the gateway dispatches the next task to any idle registered worker automatically after yourresult.
Dependencies
# Python
pip install pyzmq msgpack
# Lua (Luna)
# Built into client/ffi/zmq.lua
# Rust
cargo add zmq msgpack
Step 1: Connect and Register
import zmq
import msgpack
ctx = zmq.Context()
sock = ctx.socket(zmq.DEALER)
sock.setsockopt_string(zmq.IDENTITY, "my-worker-1")
sock.connect("tcp://127.0.0.1:5555")
# Register immediately
# NOTE: the payload goes out BARE — no empty delimiter frame. The old
# two-frame delimiter shape taught here previously was dropped by the
# gateway (it matches neither [Identity, Payload] nor
# [Identity, Payload, Mac]; see docs/zmq-protocol-reference.md §Message
# Framing, ).
sock.send_multipart([msgpack.packb({
"type": "ready",
"worker_id": "my-worker-1",
"version": 4, # REQUIRED — the gateway rejects the handshake
# with missing_fields without it (protocol
# version, sol_zmq_protocol:protocol_version/0;
# v1/v2 are refused loudly, v3 is admitted only
# while the N/N-1 skew window is on —
# zmq_wire_skew_window,;
# v4 since then —
# inference_binding + lane_control)
"capabilities": ["python", "streaming"]
}, use_bin_type=True)])
Live protocol version: 4 (version = 4). A v1/v2 worker is refused
loudly; v3 is admitted only while the N/N-1 skew window is open. The field is
validated by sol_zmq_protocol:protocol_version/0.
The per-frame MAC plane
On the worker plane, every credentialed multipart frame carries a trailing
MAC frame derived from the session key established by the verified
credential. The gateway verifies it before dispatch; a frame with a missing
or mismatched MAC is refused and counted, never executed. The MAC set is
generated in contract/zmq_frame_mac_sets.yaml and documented in
zmq-security.md and
zmq-protocol-reference.md.
When a fleet secret (SOL_ZMQ_WORKER_SECRET) or per-worker enrollment key
(zmq_enrollment_keys + key_id) is configured, the ready frame must
also carry a fresh nonce, a strictly increasing ctr, and an hmac over
nonce || u16(len(identity)) || identity || u16(len(worker_id)) || worker_id || u32(child_depth) || u64(ctr)
(see zmq-security.md — the reference implementation is
example/python/zmq_worker.py).
Step 2: Receive and Execute Tasks
poller = zmq.Poller()
poller.register(sock, zmq.POLLIN)
while True:
events = dict(poller.poll(timeout=1000))
if sock not in events:
continue
frames = sock.recv_multipart()
msg = msgpack.unpackb(frames[-1], raw=False)
msg_type = msg.get("type")
if msg_type == "task":
task_id = msg["task_id"]
prompt = msg["prompt"]
#... execute task...
Step 3: Stream Results
# Stream tokens during execution — each token carries a per-task
# monotonically increasing `seq` (Sol requires it from a v2+ worker;
# retransmits re-send the same seq)
sock.send_multipart([msgpack.packb({
"type": "token",
"task_id": task_id,
"seq": 1,
"content": "partial output..."
}, use_bin_type=True)])
# Send final result
sock.send_multipart([msgpack.packb({
"type": "result",
"task_id": task_id,
"status": "ok",
"content": "final output"
}, use_bin_type=True)])
# The worker stays REGISTERED after the result — the gateway dispatches
# the next task to idle registered workers. Do NOT send `ready` again
# here (see the re-READY hazard above).
Step 4: Handle Cancellation
if msg_type == "cancel":
task_id = msg["task_id"]
# Abort work, send cancelled result
sock.send_multipart([msgpack.packb({
"type": "result",
"task_id": task_id,
"status": "cancelled",
"content": ""
}, use_bin_type=True)])
Step 5: Heartbeat
Send a plain heartbeat frame every 5 seconds while connected — liveness,
NOT re-registration. Do not gate the heartbeat on idleness: a
heartbeat is processed whenever the worker is registered, and for a busy
worker it does MORE than keep the eviction sweep away —
# Heartbeat (repeats every 5s while connected — busy or idle)
sock.send_multipart([msgpack.packb({
"type": "heartbeat",
"worker_id": "my-worker-1"
}, use_bin_type=True)])
Each heartbeat (required: CURRENT registration — an unregistered identity’s
heartbeat is refused + counted) refreshes the worker’s last_seen and, when
the worker holds a task, also refreshes that task’s ownership-index liveness
timestamp (a long-running task never ages into the 1h sweep) and renews the
workflow bridge-correlation lease (sol_zmq_handler_worker.erl heartbeat
handler). The liveness sweep evicts workers silent for longer than
worker_heartbeat_timeout_ms — shipped sys.config/sys.prod.config =
15000 ms (the code fallback when the key is absent is 45000 ms; check
cycle 10s). Use 15000 ms when sizing your heartbeat interval against a
shipped fleet.
Complete Example
A full reference implementation is available at example/python/zmq_worker.py (530 lines). Run it:
pip install pyzmq msgpack
python3 example/python/zmq_worker.py tcp://127.0.0.1:5555 my-worker
See zmq-protocol-reference.md — the canonical wire-protocol reference.
Path B: JSONL Stdio Worker
How It Works
Sol (erlexec) spawns process
│
├── stdin → JSON task messages
└── stdout ← JSON result messages
Sol spawns an OS process via erlexec and communicates via JSON lines over stdin/stdout. The worker reads JSON objects from stdin (one per line) and writes JSON objects to stdout (one per line, flushed after each).
Step 1: Protocol
Messages are JSON objects, one per line, terminated by newline (\n). Each message has a type field.
Step 2: Message Types
Worker → Sol (stdout)
| Type | Fields | Description |
|---|---|---|
ready | — | Announce worker is ready |
token | id, content | Streaming partial output |
result | id, status, content | Task completion |
permission_request | task_id, request_id, tool_name, input_summary, analysis, expires_in_ms | — ask the operator for a tool decision (bounded command/path summary only; never the raw input) |
log | level, message | Diagnostic log |
Sol → Worker (stdin)
| Type | Fields | Description |
|---|---|---|
task | id, task_id, prompt, stream, user_uuid, permissions?, session_id?, inference_binding? | Task assignment; inference_binding is the pre-spawn lane grant |
cancel | id | Cancel running task |
permission_reply | request_id, decision, reason | — the operator answer (allow/deny/always); absorbed MID-TURN by the stdio drive |
Lane binding: Sol resolves the task’s lane before
the stdio process is spawned and stamps every task line with a granted
inference_binding — the same pinned descriptor the ZMQ plane sends
(lane, endpoint, wire_format, caps, ctx, lease_id, expires_at,
expires_in_ms, holder, status="granted"). Luna builds a per-task
Provider.from_lane from it (keyless; no startup key required) and honors
the receipt-relative expires_in_ms even when the host wall clock is skewed.
There is no lane_control over stdio and no protocol-version bump; a
lane-named model with no grantable warm lane fails the SPAWN typed
(lane_<reason>, e.g. lane_no_lane) instead of booting a keyless crash
loop. A non-lane model keeps the keyed startup-provider posture.
Standalone stdio: --stdio is also an
operator/editor transport. It starts no ZMQ worker (that is --connect
only), reads JSONL tasks from stdin, and streams frames to stdout:
# declare the endpoint once (~/.luna/settings.json):
# {"providers":{"local":{"base_url":"http://localhost:11434",
# "wire_format":"openai","models":["qwen2.5-coder:7b"],"no_api_key":true}}}
client/run --stdio --no-persist --model qwen2.5-coder:7b
{"type":"ready"}
{"type":"task","id":"t1","prompt":"first prompt"}
{"type":"token","id":"t1","content":"..."}
{"type":"result","id":"t1","status":"ok","content":"..."}
{"type":"task","id":"t2","prompt":"second prompt"} # carries t1 history
ONE Session/Agent serves the whole process, so prompt 2 sees prompt 1’s
history; the session is closed once at stdin EOF (clean exit 0). cancel
and permission_reply lines are honored while a turn runs; a task line that
arrives mid-turn is queued and served after the result.
Permission-ask contract: a worker hook with no operator
surface used to deny silently. Headless stdio workers now emit ONE
permission_request line, then park (yielding permission_wait) until the
matching permission_reply line arrives — the stdio drive reads it
MID-TURN, so a task is never finished around the ask. The deadline is the
frame’s expires_in_ms (worker-enforced locally too); a lapse is a typed
deny. always may persist in the worker’s 600s decision cache; one-shot
allow/deny never does. Sol routes the ask to the session’s WebSocket and
records a STRICT, content-free audit row (permission_decided:
tool/decision/reason/input_hash/session/worker/owner/source) on every
decision — operator, timeout, disconnect, or task-finished.
Cancel contract: a cancel line is honored
MID-TURN, not just between tasks. Luna’s --stdio worker drives
run_turn_async and polls stdin between yields, so a cancel arriving
while the model is streaming interrupts the turn immediately (the model
turn ends with the interrupted terminal) and the worker emits
{"type":"result","id":...,"status":"cancelled","content":""} once the
partial output is stopped. A task line that arrives while a turn is
running is queued and served after the result — it is never dropped.
Embedders that do not poll stdin between yields may only rely on process
termination as the cancellation mechanism.
Turn lifecycle and intake queues
Luna has two in-process intake queues. Steering is injected at the next
loop boundary before the next provider request; follow-ups are injected
only when the inner loop would otherwise stop. Each queue drains all
(historical behavior) or one-at-a-time (steering_mode /
follow_up_mode). Steer wins over follow-up at the same boundary.
| Phase | Queue action | Events |
|---|---|---|
| Turn start | none (pre-queued messages wait for the first boundary) | turn_start |
| Provider stream | none mid-stream | text_delta, thinking_delta, usage, provider_retry |
| Tool batch | none mid-batch (the batch is atomic) | tool_start, tool_done, tools_running |
| Post-stream B1 | drain steer; re-arm the loop if anything was injected | steering (one per message) |
| Late B2 | drain steer queued during compaction/recovery/stop hooks | steering |
| Outer B3 | steer first, then follow-up; one provider round each (cap 3 each) | steering or follow_up |
| Interrupt / terminal error | queues preserved (no drain) | interrupted → turn_done |
Step 3: Minimal Worker Example
#!/usr/bin/env python3
import sys
import json
def send(msg):
sys.stdout.write(json.dumps(msg) + "\n")
sys.stdout.flush()
# Announce ready
send({"type": "ready"})
for line in sys.stdin:
msg = json.loads(line.strip())
if msg.get("type") == "task":
task_id = msg["id"]
prompt = msg["prompt"]
# Stream tokens
send({"type": "token", "id": task_id, "content": "Working...\n"})
# Send result
send({"type": "result", "id": task_id, "status": "ok", "content": f"Done: {prompt}"})
elif msg.get("type") == "cancel":
task_id = msg["id"]
send({"type": "result", "id": task_id, "status": "cancelled", "content": ""})
Step 4: Spawn Configuration
Configure in sys.config:
{worker_path, "/path/to/my-worker"},
{max_workers, 16}
Or override per-spawn via the HTTP API:
zerg spawn --worker-path /path/to/my-worker
The worker_path is validated against a configurable prefix to prevent arbitrary binary execution.
Task Timeout
task_timeout_ms is an idle deadline (default 300000 ms): Sol re-arms it
on every token/heartbeat progress for the task, so a live-streaming task
is not hard-killed at 5 minutes. The progress-renewed lease is separately
bounded by task_max_lifetime_ms (default 1200000 ms; 0 = uncapped) — a
chatty-but-endless task is cancelled at that cap. task_timeout_ms=0
disables the gateway deadline; the wire field then carries the documented
24h sentinel.
Output Buffer
Worker stdout is buffered up to 256KB. Output exceeding this limit is truncated with [...output truncated...].
Worker Configuration Reference
| Config Key | Default | Description |
|---|---|---|
worker_path | "client/build/luna" | Path to worker binary |
max_workers | 16 | Maximum concurrent workers |
zmq_router_port | 5555 | ZMQ ROUTER socket port |
zmq_pub_port | 5556 | ZMQ PUB event socket port |
zmq_bind_addr | "127.0.0.1" | ZMQ bind address |
zmq_enabled | true | Enable ZMQ gateway |
Monitoring Workers
ZMQ Workers
zerg zmq-workers # List connected workers
zerg zmq-status # Gateway status
JSONL Workers
zerg agents # List spawned workers
zerg task-status <id> # Check task result
Mango HTTP API
Mango is the identity and authorization service. It issues and validates tokens, enforces RBAC, manages users/orgs/teams/roles/tasks, serves audit verification, and bridges revocation events to Sol.
The generated OpenAPI document is available at GET /openapi when the deployment enables it; both /openapi and /metrics are loopback or bearer-gated.
Conventions
JSON request/response bodies. A non-object JSON body is rejected with 400 before auth.
Auth is a bearer token (Authorization: Bearer) or the Sol-issued service token for service-to-service calls.
Pagination uses /page/<route> variants and a documented envelope envelope.
Every mutation writes an audit row; secrets are never logged.
Rate limits are per-IP and per-account; failed authentication is the only path that spends the account limiter.
Health and readiness
| Method | Path | Notes |
|---|---|---|
| GET | /health | Liveness + dependency data |
| GET | /ready | Readiness, including the schema/DB probe |
| GET | /metrics | Loopback/bearer-gated; always registered |
| GET | /openapi | Conditional on the deployment lever |
Authentication
| Method | Path | Purpose |
|---|---|---|
| POST | /auth/login | Username/password login; sets session cookies on success |
| POST | /auth/logout | Revokes the token and clears cookies |
| POST | /auth/validate | Validates a token; returns identity + permissions |
| POST | /auth/service-token | Mints a scoped service token (TTL and live-token caps apply) |
| GET | /auth/service-tokens | Lists live service tokens (self; admin with ?user_uuid=) |
| POST | /auth/revocations | Service-token revocation feed (service tokens only) |
| POST | /auth/change-password | Password change with lockout/rate limits |
| POST | /auth/accounts/:uuid/lock | Admin unlock |
| POST | /auth/users/:uuid/tokens | Revoke all tokens for a user |
| POST | /auth/tokens/:id/revoke | Revoke one token |
| POST | /auth/users/:uuid/ldap-tombstone | Clear a revalidation tombstone (audited) |
Orchestrator lease
| Method | Path | Purpose |
|---|---|---|
| POST | /orchestrator/lease | Acquire/renew the orchestration lease (heartbeat is a verdict on this route) |
| POST | /orchestrator/lease/takeover | Take over the lease under the takeover authority |
Users, orgs, roles, tasks
| Resource | Paths |
|---|---|
| Users | GET/POST /users, GET/PUT/DELETE /users/:uuid, GET /users/page/:n, GET /users/:uuid/tasks, GET /users/:uuid/permissions |
| Orgs | GET/POST /orgs, GET/PUT/DELETE /orgs/:uuid, GET /orgs/page/:n |
| Teams | GET/POST /orgs/:org/teams, GET/PUT/DELETE /orgs/:org/teams/:team, GET /orgs/:org/teams/page/:n |
| Roles | GET/POST /roles, GET/PUT/DELETE /roles/:uuid, GET /roles/page/:n, GET/PUT/DELETE /teams/:team/roles/:role |
| Tasks | GET/POST /tasks, GET/PUT/DELETE /tasks/:uuid, GET /tasks/page/:n, POST /tasks/:uuid/assign/:assignee |
| Membership | GET/PUT/DELETE /orgs/:org/users/:user, GET/PUT/DELETE /teams/:team/users/:user |
| Cost/usage | GET/PUT /teams/:team/cost-centers, GET/PUT /teams/:team/members/:user/caps, GET /teams/:team/usage-attribution |
The exact method set per route is in the OpenAPI document; mutations are RBAC-gated and audit-logged.
Audit
| Method | Path | Purpose |
|---|---|---|
| POST | /api/mango/audit-archive | Ingest a batch of audit events from Sol (HMAC over exact bytes; idempotent row ids) |
Mango maintains its own HMAC-chained audit_logs table with a signed checkpoint anchor and a retention floor. Operators verify with Audit.verify_integrity; a truncated head/tail, sequence rewind, or invalid checkpoint is a typed verdict.
Revocation bridge
Mango publishes token.revoked events to Sol over the bridge (HMAC v2 wire, freshness window + nonce replay guard). Sol clears its auth cache on receipt and resyncs on reconnect and every 60 seconds.
Errors
Mango uses a typed error envelope. A dependency outage returns 503, never a bare 500. Auth failures are enumeration-resistant.
Next
Authentication flow RBAC scopes Mango configuration Security model
Mango configuration
Mango reads its configuration from environment variables (and the deployment’s config file). The canonical engineering reference is generated from the source; this page groups the levers that matter operationally.
Core
| Variable | Purpose |
|---|---|
MANGO_HOST / MANGO_PORT | Bind address and port (default loopback posture) |
MANGO_ENV / MANGO_DEPLOYMENT_MODE | Environment and deployment posture (production refuses unsafe defaults) |
MANGO_DOMAIN / MANGO_COOKIE_DOMAIN / MANGO_COOKIE_SECURE | Cookie scope and security |
MANGO_ALLOWED_HOSTS | Host allowlist |
MANGO_TRUSTED_PROXIES | CIDRs allowed to set X-Forwarded-For / X-Real-IP (default loopback) |
MANGO_CORS_ALLOWED_ORIGINS | Console origins |
Database
| Variable | Purpose |
|---|---|
MANGO_DB_URL | Full DSN (SQLite or PostgreSQL) |
MANGO_DB_HOST / MANGO_DB_PORT / MANGO_DB_NAME / MANGO_DB_USER / MANGO_DB_PASSWORD | Discrete PG connection fields |
MANGO_ALLOW_SCHEMA_AHEAD | Permits a schema newer than the code (explicit, loud) |
Mango migrations run at boot through the migration runner. A failed or ahead schema refuses readiness unless explicitly acknowledged.
Auth and tokens
| Variable | Purpose |
|---|---|
MANGO_ENABLE_TOKEN_AUTH / MANGO_ENABLE_RBAC / MANGO_REQUIRE_AUTH | Master auth switches |
MANGO_SESSION_TTL | Session lifetime |
MANGO_SERVICE_TOKEN | Static service token (bootstrap; prefer minted service tokens) |
MANGO_SERVICE_TOKEN_TTL_SECONDS | Minted service-token TTL (default 7d, clamped) |
MANGO_MAX_LIVE_SERVICE_TOKENS_PER_USER | Live-token cap (default 20; oldest evicted with journal rows) |
MANGO_ALLOW_ANONYMOUS_ADMIN | Never enable in production |
MANGO_BCRYPT_COST | Password hash cost |
Rate limits and lockout
| Variable | Purpose |
|---|---|
MANGO_GLOBAL_RATE_LIMIT / MANGO_LOGIN_RATE_LIMIT / MANGO_ACCOUNT_RATE_LIMIT | Global, login, and per-account buckets |
MANGO_VALIDATE_RATE_LIMIT / MANGO_VALIDATE_INVALID_RATE_LIMIT | Token validation buckets |
MANGO_SERVICE_TOKEN_RATE_LIMIT / MANGO_PASSWORD_CHANGE_RATE_LIMIT / MANGO_LOOPBACK_RATE_LIMIT | Per-surface buckets |
MANGO_DISABLE_RATE_LIMIT / MANGO_ALLOW_DISABLED_RATE_LIMIT | Explicit disable + ack |
Audit and revocation
| Variable | Purpose |
|---|---|
MANGO_AUDIT_CHAIN_SECRET | HMAC chain key (random per-process + CRITICAL if unset with auth on) |
MANGO_AUDIT_CHAIN_PRIOR_SECRETS | Prior keys for verification across rotation |
MANGO_AUDIT_ARCHIVE_SECRET | Shared secret for POST /api/mango/audit-archive |
MANGO_AUDIT_ARCHIVE_REQUIRE_V2 / MANGO_AUDIT_ARCHIVE_ALLOW_V1 | Archive wire version posture |
MANGO_REVOCATION_CHAIN_SECRET | Revocation-journal chain |
MANGO_BRIDGE_HMAC_SECRET / MANGO_BRIDGE_TS_WINDOW_MS | Sol bridge wire HMAC + freshness |
MANGO_ZMQ_PUB_URL / MANGO_ZMQ_PULL_URL / MANGO_ZMQ_ALLOW_NONLOOPBACK | Event bridge transport |
LDAP / GLAuth
| Variable | Purpose |
|---|---|
MANGO_LDAP_ENABLED | Enable directory federation |
MANGO_LDAP_CIRCUIT_OPEN_MS | Outage circuit |
MANGO_LDAP_ALLOW_ACCOUNT_OVERRIDE / MANGO_LDAP_ALLOW_LOCAL_HASH_FALLBACK | Explicit fallback levers |
MANGO_LDAP_REVALIDATION_DRY_RUN | Report-only revalidation |
Metrics
| Variable | Purpose |
|---|---|
MANGO_ENABLE_METRICS / MANGO_METRICS_EXPOSE | Metrics on/off and scrape surface |
MANGO_METRICS_READ_TOKEN | Bearer for the metrics surface |
Posture rules
Non-loopback plaintext Mango is refused in production; terminate TLS in front of Mango and point Sol’s verified client at it.
A non-dict JSON body is 400 before auth.
MANGO_ALLOW_GLOBAL_TRUST and the anonymous-admin lever are ack-gated and CRITICAL-logged.
The full source of truth is mango/mango/conf.py; this page is the operator-oriented projection.
Next
Mango HTTP API Authentication flow Configuration reference Security model
Engine reference — generated from the canonical engineering source. Do not edit this page by hand.
Plugin Development Guide
Sol’s plugin system runs Lua code inside a sandboxed Luerl VM. Plugins respond to lifecycle events, poll on intervals, and access 14 bridge namespaces under sol.* for server capabilities.
Plugin Structure
my-plugin/
├── plugin.json # Config: name, version, description, config schema
└── plugin.lua # Code: lifecycle functions
plugin.json Schema
| Field | Required | Type | Description |
|---|---|---|---|
name | Yes | string | Unique plugin identifier |
version | Yes | string | Semantic version |
description | No | string | Human-readable description |
type | No | string | Plugin type (e.g., "channel") |
config | No | object | Configuration values (overrides schema defaults) |
config_schema | No | object | Schema with required and optional fields |
Example plugin.json
{
"name": "my-plugin",
"version": "1.0.0",
"description": "My custom Sol plugin",
"type": "channel",
"config_schema": {
"required": ["api_key"],
"optional": [
{"name": "timeout", "default": 5000},
{"name": "base_url", "default": "https://api.example.com"}
]
},
"config": {
"api_key": "${MY_PLUGIN_API_KEY}"
}
}
Environment variable expansion: ${ENV_VAR} in config values are replaced with the corresponding environment variable at load time.
Lifecycle Functions
Plugins implement Lua functions that Sol calls at specific points.
init(config)
Called once when the plugin is loaded. Receives the merged configuration (schema defaults + plugin.json config + overrides).
function my_plugin.init(config)
_config = config
sol.log.info("plugin initialized with timeout=" .. tostring(config.timeout))
return true
end
start(channel_id)
Called when a channel using this plugin is started. For channel-type plugins only.
function my_plugin.start(channel_id)
Initialize per-channel state
return true
end
stop(channel_id)
Called when a channel using this plugin is stopped. Clean up resources.
function my_plugin.stop(channel_id)
Clean up
return true
end
send_message(channel_id, message)
Called when a message should be delivered to this channel.
function my_plugin.send_message(channel_id, message)
sol.http.post("https://example.com/hook", '{"text":"' .. message .. '"}')
return true
end
send_to(chat_id, text)
: the addressed send — called when a reply must land on
the chat that asked (the inbound webhook’s authenticated chat id), not on the
channel’s static configured destination. A channel that received an inbound
message carries task_meta.channel_origin = #{plugin, channel_id, chat_id}
through the task; when the task terminates, the channel plane calls
format_event/2 and then send_to(chat_id, text) on the origin plugin.
Return true on delivery; nil, err on failure. Transports with no
per-message destination (Slack/Teams/Discord incoming webhooks) accept the
parameter for contract parity and deliver to their configured webhook.
function my_plugin.send_to(chat_id, text)
local resp = sol.http.post("https://api.example.com/send/" .. chat_id,
'{"text":"' .. text .. '"}')
if resp and resp.status == 200 then return true end
return nil, "send failed: " .. tostring(resp and resp.status)
end
Transport limits
The channel plane clamps every outbound message to the destination
transport’s real limit (and the bundled plugins reserve room for their
[truncated] marker plus the zerg task-status <id> full-result pointer):
| Plugin | Limit | Source |
|---|---|---|
telegram | 4096 chars | Telegram Bot API sendMessage text (1–4096 chars) |
discord | 2000 chars | Discord Execute Webhook content (up to 2000 chars) |
slack | 40000 chars | Slack chat.postMessage text hard limit (4000 is Slack’s “best results” budget) |
teams | 28000 chars | Microsoft Teams Incoming Webhook card payload limit (28 KB) |
sol_channel:transport_limit/1 is the authoritative table; a plugin
config_schema max_message_len that exceeds it is still clamped.
format_event(event_type, event_data)
Called to format an event for channel delivery. Return a string to send, or nil to skip.
function my_plugin.format_event(event_type, event_data)
command replies (for example /tasks) arrive as a string
if event_type == "command_response" then
return tostring(event_data)
end
if event_type == "worker_task_completed" then
return "Task done: " .. tostring(event_data.task_id)
end
return nil
end
poll(method_or_interval)
Called periodically if polling is enabled. The manager calls poll(n) with
the configured interval (ms) for timer pollers, or poll("getUpdates") for
long-poll channel plugins. Return a list of updates or nil.
function my_plugin.poll(method)
if method ~= "getUpdates" then return nil end
local resp = sol.http.get("https://api.example.com/updates")
if resp and resp.status == 200 then
return resp.body -- must be a list
end
return nil
end
handle_update(update)
Called for each update returned by poll.
function my_plugin.handle_update(update)
sol.events.emit("plugin.my_plugin.incoming", update.text)
return update.text
end
Bridge Modules
All bridge modules are available under the sol.* namespace inside the plugin VM.
sol.log
Structured logging to the Sol logger.
sol.log.info("operation completed")
sol.log.warn("slow response detected")
sol.log.error("connection failed: " .. err)
sol.log.debug("retry attempt 3")
sol.http
HTTP client via gun (Erlang HTTP client). Connection pooling with automatic reconnect. TLS verification is enabled for HTTPS URLs.
GET request
local resp = sol.http.get("https://api.example.com/status")
if resp and resp.status == 200 then
sol.log.info("body: " .. tostring(resp.body))
end
POST request
local resp = sol.http.post("https://api.example.com/hook", '{"key":"value"}')
Response object:
| Field | Type | Description |
|---|---|---|
status | number | HTTP status code |
body | string | Response body |
sol.config
Read-only access to plugin configuration.
local value = sol.config.get("timeout", 5000)
sol.events
Event pub/sub within Sol.
Emit an event. The type MUST live inside this plugin's OWN namespace:
exactly `plugin.<plugin-name>` or `plugin.<plugin-name>.<suffix>`.
Foreign plugin namespaces are refused (`event type outside the plugin
namespace`) and counted.
sol.events.emit("plugin.my_plugin.my_custom_event", {key = "value"})
Subscribe to plugin.* events (subject to the admission rules:
plugin.* namespace only, <= 128 bytes, no wildcard-all, per-plugin cap).
subscribe takes the event-type string; delivery arrives at the plugin's
on_event(event_type, data) — a second callback argument is tolerated
but IGNORED.
sol.events.subscribe("plugin.task.completed")
sol.events.unsubscribe("plugin.task.completed")
sol.channel
Channel state management for channel-type plugins.
sol.channel.set_status(channel_id, "active")
local info = sol.channel.get_info(channel_id)
sol.json
Safe JSON string escaping.
local escaped = sol.json.encode_string('He said "hello" and left\n')
Returns: "He said \"hello\" and left\\n"
Note: Only encode_string is available. For full JSON encoding of tables, build manually or use string concatenation.
sol.time
Timestamp utilities.
local wall_ms = sol.time.time_ms() -- wall-clock milliseconds
local mono_ms = sol.time.time_mono_ms() -- monotonic milliseconds
sol.tools
Register custom tools that the LLM agent can invoke. Tool calls are dispatched through the plugin VM; on the wire the tool is exposed as plugin__<plugin>__<name> (reserved names and cross-plugin ownership conflicts are refused).
sol.tools.register("my_tool", "Does something useful",
{ type = "object", properties = { query = { type = "string" } } },
function(input)
return { result = "processed: " .. input.query }
end)
sol.tools.unregister("my_tool")
A 5th argument declares the tool’s permission class — enforced at dispatch since then: the caller’s grant is checked against the declared class on the same execute/write ladder the builtin tools use.
declared "read": any caller with a non-empty grant may invoke
sol.tools.register("stats", "Read plugin stats", {}, function(i) ... end, "read")
declared "write": requires:write/:manage authority (or execute-grade)
sol.tools.register("flush", "Flush caches", {}, function(i) ... end, "write")
declared "execute": requires execute-grade ("*" or tasks:execute)
sol.tools.register("run", "Run a job", {}, function(i) ... end, "execute")
Undeclared tools default to the write class. A refusal answers the
typed {error, {plugin_permission_denied, Tool, Declared, Class}} and
bumps plugin_tool_permission_denied_total. There are no carve-outs:
the ladder runs for EVERY identity. The server’s own internal callers pass
through the same check because they present the server’s single-sourced
grant (sol_identity:system_identity/0 — the <<"*">> admin grant,
expressed in the same vocabulary user grants use), which genuinely covers
every class. A <<"system">> stamp without a covering grant (the degraded
unknown-task posture) and a bare empty identity are refused like any
unprivileged caller.
sol.commands — REMOVED
The slash-command registration surface had no consumers and is no longer
installed in the sandbox. A plugin calling sol.commands.register gets a
clean nil-table error.
sol.sessions
Access session metadata and trigger session operations.
local sessions = sol.sessions.list()
for _, s in ipairs(sessions) do
sol.log.info("Session: " .. tostring(s.id))
end
sol.providers
Query available inference providers and their status.
local providers = sol.providers.list()
for _, p in ipairs(providers) do
sol.log.info(p.name .. " status: " .. p.status)
end
sol.workflows
Interact with the workflow engine — list workflows, attach steps, and observe step progress.
local workflows = sol.workflows.list()
sol.workflows.add_step("my_step", step_def)
sol.workflows.on_step(function(step_name, result)
sol.log.info("step finished: " .. tostring(step_name))
end)
sol.agents
Query and spawn agent workers.
local agents = sol.agents.list()
sol.agents.spawn({ prompt = "Summarize this", model = "glm-4.7-flash" })
sol.agents.on_spawned(function(agent_id)
sol.log.info("spawned: " .. tostring(agent_id))
end)
sol.memory
Scoped key-value storage with TTL support. Keys are automatically scoped to the plugin’s namespace.
sol.memory.set("key", "value", 3600000) -- TTL in ms (1 hour)
local val = sol.memory.get("key")
sol.memory.delete("key")
sol.scheduler
Schedule deferred or recurring tasks from within a plugin.
at(unix_timestamp, event_name) — one-shot, fires the plugin's on_event
sol.scheduler.at(os.time() + 60, "reminder_event")
every(interval_ms, event_name) — recurring, floor = plugin_min_interval_ms
sol.scheduler.every(60000, "heartbeat_tick")
cancel(job_id)
sol.scheduler.cancel(job_id)
Example: Hello World Plugin
hello/
├── plugin.json
└── plugin.lua
Plugin.json:
{
"name": "hello",
"version": "1.0.0",
"description": "Hello World plugin"
}
Plugin.lua:
local hello = {
name = "hello",
version = "1.0.0",
description = "Hello World plugin"
}
function hello.init(config)
sol.log.info("Hello World plugin initialized!")
return true
end
function hello.start(channel_id)
sol.log.info("Hello started for channel " .. tostring(channel_id))
return true
end
function hello.stop(channel_id)
sol.log.info("Hello stopped for channel " .. tostring(channel_id))
return true
end
function hello.send_message(channel_id, message)
sol.log.info("Message: " .. tostring(message))
return true
end
function hello.format_event(event_type, event_data)
return "[" .. event_type .. "] " .. tostring(event_data)
end
return hello
Example: Webhook Plugin
A plugin that posts events to an external URL:
local webhook = {
name = "webhook",
version = "1.0.0",
description = "Webhook delivery plugin",
type = "channel",
config_schema = {
required = {"url"},
optional = {
{name = "method", default = "POST"},
{name = "headers", default = "{}"}
}
}
}
local _config = {}
function webhook.init(config)
_config = config
return true
end
function webhook.start(channel_id)
return true
end
function webhook.stop(channel_id)
return true
end
function webhook.send_message(channel_id, message)
local body = '{"text":"' .. sol.json.encode_string(message) .. '"}'
local resp = sol.http.post(_config.url, body)
if resp and resp.status >= 200 and resp.status < 300 then
return true
end
return nil, "HTTP " .. tostring(resp and resp.status or "none")
end
function webhook.format_event(event_type, event_data)
if event_type == "worker_task_completed" then
return "Task " .. tostring(event_data.task_id) .. ": " .. tostring(event_data.status)
elseif event_type == "worker_crashed" then
return "Worker crashed: " .. tostring(event_data.worker_id)
end
return nil
end
return webhook
Reference: Telegram Plugin
The bundled Telegram plugin (server/priv/plugins/telegram/plugin.lua) demonstrates a complete channel plugin with:
Configuration schema with required/optional fields
MarkdownV2 escaping and message truncation
Rate-limited message queue with configurable depth
Long polling via poll/handle_update for incoming messages
Health check against Telegram Bot API
Event formatting for task completion, crashes, and scheduled tasks
Study it at server/priv/plugins/telegram/plugin.lua (247 lines).
Discovery Locations
Sol loads plugins from two directories:
- Bundled:
server/priv/plugins/— shipped with Sol - User:
~/.sol/plugins/(or path fromplugin_user_dirconfig) — user-installed
Plugins are discovered at startup via sol_plugin_loader. Each subdirectory containing a plugin.lua is a candidate.
Loading
Plugins listed in plugins.json (in the plugin directory or configured via environment) are loaded at boot. The load process:
- Find plugin path (bundled or user dir)2. Trust gate — a
plugins.jsonentry may pin"sha256": "<64 lowercase hex of plugin.lua>"; a mismatch REFUSES the boot (tamper detection, bundled plugins included). A plugin resolving from the USER dir (~/.sol/plugins) without a pin loads only behind the explicit operator ackSOL_PLUGIN_USER_DIR_LOAD_ACK=true(CRITICAL-logged); without it the load is refused (plugin_consent_required). Bundledpriv/pluginswithout a pin are trusted-by-repo - Initialize sandboxed Luerl VM
- Strip
os,io,debug,package,print,eprint,load,loadfile,loadstring,dofile,require( — use thesol.logbridge instead ofprint) - Load bridge modules into
sol.*namespace - Load and execute
plugin.lua - Read metadata (
name,version,type,description) - Validate config against
config_schema - Expand
${ENV_VAR}in config values — allowlist-only ( ): onlyplugin_env_allowlistnames interpolate; anything else expands to an empty string (no host-environment passthrough) - Call
init(config)
** — postures:**
plugin_config_path empty (the shipped sys.config default) or pointing
at a missing/unreadable/invalid file is a degraded posture: Sol boots
with zero backends, logs a WARNING once naming the exact remediation, and
the channels API answers 503 channel_backends_unavailable with the cause
instead of a bare per-request 400 plugin not loaded. Set
plugin_config_path to a plugins.json (for example
server/priv/plugins.json) to load bundled backends.
Lua config_schema arrays (required = {"bot_token"}, optional = {...})
are normalized from luerl’s table decode before validation — the bundled
telegram/discord plugins load with their schema-validated config.
Security Sandbox
| Restriction | Details |
|---|---|
No os library | Cannot execute OS commands |
No io library | Cannot read/write files directly |
No debug library | Cannot inspect VM internals |
No package library | Cannot load external modules |
| Network access | Only via sol.http bridge |
| Reduction budget | plugin_max_reductions (default 5,000,000) — an over-budget runner is killed and the call returns {error, budget_exceeded} |
| Heap budget | plugin_max_heap_mb (default 256) — every runner is spawned with max_heap_size and a heap watchdog; an allocation bomb (t[i] =... table growth) is killed and the call returns {error, heap_budget_exceeded} (metric plugin_heap_killed_total) |
| Wall-clock budget | plugin_lifecycle_timeout_ms (default 3000) — lifecycle/poll/on_event calls time out with {error, timeout}; since then lifecycle Lua runs in offloaded workers, the manager stays responsive while a plugin stalls |
| Closure wall clock | plugin_lifecycle_wall_clock_ms — bounds a WHOLE lifecycle closure (a multi-call poll fold can hold the FIFO for N × the per-call budget); past the deadline the worker is killed and the call returns {error, wall_clock_exceeded} |
| Periodic GC | Luerl VM garbage collected periodically |
Since:
Load-time identity — bridge calls made at the top of your plugin’s
chunk (sol.tools.register, sol.events.subscribe, memory writes)
are attributed to the loading plugin, never to <<"unknown">>.
Unload revokes registrations — unloading a plugin removes every
tool/command/subscription row it registered; worker registries stop
advertising its tools immediately, and a reload starts fresh (no
resurrected rows).
Lifecycle offload — init, poll, on_event, format_event and
tool handlers run in budgeted worker processes; a slow/hostile plugin
cannot block pending_tool_count, is_loaded, or list_plugins.
Bounded event-type admission — sol.events.emit creates at most
plugin_max_event_types (default 1024) unique atoms; past the cap a new
event type is rejected ([false, "unknown event type"]) without creating
an atom. Slots are released at unload.
sol.scheduler events route back — a job created via
sol.scheduler.at/every delivers its event to the plugin’s on_event
(rate-limited like subscription events) instead of dispatching a
prompt-less task.
sol.commands removed — the registration surface had no consumers;
sol.commands is no longer installed in the sandbox (a plugin calling
it gets a clean nil-table error).
sol.http responses are real tables — resp.status and
resp.body work; response bodies are capped at plugin_http_max_body
(default 5 MB, {error, body_too_large} beyond it).
Plugin names must not contain __ or the plugin__ prefix and
must be ≤ 64 bytes — ambiguous wire names (plugin__a__b__tool) are
rejected at load time with {error, invalid_plugin_name}.
Since:
sol.scheduler.every floor — intervals below
plugin_min_interval_ms (default 1000) are refused with a loud Lua
error; a fire-per-ms flood is no longer expressible.
Unload cancels attributed jobs — unloading a plugin cancels its
sol.scheduler jobs (cancel_by_plugin); cancelled jobs stay
cancelled across a reload. Jobs skipped as currently-running finish
their current run and are then gone.
sol.events.subscribe admission — patterns must be in the
plugin.* namespace, ≤ 128 bytes; '*' (wildcard-all) and foreign
namespaces are refused. A plugin holds at most plugin_max_subscriptions
(default 64) rows; refusals return [false, "<reason>"].
sol.events.emit namespace ownership — an emit
must name the caller’s own namespace: exactly plugin.<plugin-name> or
plugin.<plugin-name>.<suffix>. A forged plugin.<other-plugin>.* event
is refused (event type outside the plugin namespace) and counted in
sol_plugin_event_foreign_namespace_total; subscribers of the other
plugin’s namespace can never receive it.
Queue dwell — at/over plugin_queue_dwell_max (default 16) queued
entries per plugin, calls refuse immediately with
{error, {busy, RetryHintMs}} instead of waiting in the FIFO (both
tool and lifecycle calls; the hard cap plugin_max_queue_len returns
the same shape).
Nested payload redaction — event payloads delivered to
on_event are redacted recursively (sensitive keys at any depth up to
16), not just at the top level.
Schema decode bounds — config_schema and tool-registration
schemas are depth/size-capped (16 deep / 1024 nodes); over-bounds
schemas fail the load or refuse the registration loudly.
sol.sessions/sol.providers callback registrations removed —
on_created/on_destroyed/on_registered/on_error were dead APIs: they
stashed callbacks in a short-lived runner’s process dictionary with
zero readers and silently died with it. Calling them is now a clean
nil-field error. A lifetime-anchored reimplementation is a future need.
Degraded-identity clamp — tasks dispatched under a degraded
system identity (e.g. an unknown-task plugin execution) clamp
permission_mode like any read-only requester; the internal
allow-all bypass requires an explicit trusted-internal stamp (see
plan/archive/v0617-v0630-cycle/v0625-degraded-identity.md).
Since:
One budget for tool execution — plugin_execute_timeout_ms
(default 60000) is the single budget for a plugin tool call. Every leg
derives from it: the manager-side kill, the caller leg’s wait (budget +
5s reply-hop slack, sol_plugin_manager:tool_call_timeout/0), and the
executor worker’s kill timer. Pre-fix the caller gave up at a hardcoded
15s while the manager-side Lua worker kept running — a 15–60s tool
produced an error frame AND kept committing state write-backs, so a
retry inside the window executed the tool twice.
At-least-once tool semantics — a tool that outlives the budget is
killed manager-side; the worker receives a distinguishable
plugin_timeout error (never execution_crashed). Because the tool’s
bridge side effects may already be committed when the kill lands, a
plugin_timeout answer means the tool MAY HAVE RUN — agents retry
knowing the outcome is not guaranteed clean. A completion that lands
after its dispatch already closed is counted
(plugin_tool_late_completion_total, warning-logged): the stale
write-back is dropped, the committed effects stand, and the fact is
never silent.
The sandboxed VM provides no access to the filesystem, OS commands, or module loading. All external interaction is mediated through the bridge modules.
Engine reference — generated from the canonical engineering source. Do not edit this page by hand.
Event store durability — segment contracts
The event backbone’s durable-file surfaces share one ordering and
atomicity contract. This document is the operator/design reference; the
contract is pinned by the named tests (the doc↔code parity is gated by
ci/event_store_ordering_doc_lint.py + its lint-contract test).
Scope: the memory WAL (sol_memory_wal), the event-lane spill
(sol_sync_event), and the ordering siblings that consume the same
discipline (chat history, workflow compensation markers, decomposition
ids). The event log itself (per-aggregate seq under a write lock,
terminality-aware compaction, ack-before-delete archive, outbox-gated
restore — –) stays as documented in the phase ledger; its
retention and staging rules are pinned below.
Cluster scope
The event store is node-sharded by design: every Mnesia event table
is created {disc_copies, [node]} — a single-node replica list — and
nothing replicates. Each store allocates its own seq under its own
aggregate locks, so there is no cross-node seq plane and therefore no
cross-node split-brain hazard by construction. “The cluster’s audit
trail” is N independent shards with independent seq spaces; a consumer
that switches nodes sees gaps/overlaps in since_id cursors — treat
every since_id cursor as NODE-BOUND (persist it with the node it was
read from and never replay it against a different node). Global event
views are out of scope until a consumer exists. This also makes event
append batching (the group-commit successor) strictly local write
coalescing — no cross-node coordination can ever be required.
Segment naming and the replay-order guarantee (memory WAL)
The memory WAL keeps one framed append-log segment per flush window under
<mnesia dir>/memory_wal/, named
seg-
Contract: replay order == lexical name order == creation order. The
ms field is not the wall clock — it is a monotonic clamp:
ms_minted = max(wall_clock_ms, seg_last_ms + 1)
seg_last_ms is threaded through the WAL gen_server state (the WAL is
the single segment writer) and is floored at init from the timestamp
field of the existing segment names. Consequences:
a backward wall-clock step (NTP correction, manual change) cannot
invert durable ordering — a segment recovered at boot-2 always replays
before any segment minted at boot-2;
a far-future-named segment keeps every later mint sorted after itself;
unique_integer([monotonic, positive]), zero-padded, tiebreaks
same-ms legacy names by creation order too;
the same-ms name collision class (unique integers reset per VM) is
dead: the clamp pushes the new mint past the recovered name.
No migration is required: old names parse and participate in the init floor as-is (unparsable names floor at 0).
Ops in a segment are appended before the enqueue ack (page-cache durable); fsync runs at flush cadence and terminate, so power loss is bounded to the last fsync. A WAL process crash replays the scoped segment set at init, in name order.
Pinned by sol_memory_wal_order_SUITE (backward_clock_step_replays_insertion_order,
far_future_segment_orders_before_new_mint, same_ms_burst_orders_deterministically,
restart_same_clock_two_segments, legacy_store_adopts_and_preserves_name_order).
Clock-step behavior (operator note)
Under a clock step the segment names stop tracking wall time for a while (mints clamp forward from the last name instead of following a stepped- back clock). This is by design: name order is creation order, not clock order. Names resume tracking the wall clock once it moves past the clamp.
Rewrite atomicity: the live-set manifest
Drops (operator-opted loss via the drop/fail policies, or overflow
eviction) rewrite the segment set to exactly the surviving queue. The
rewrite is atomic under process crash:
- the fresh segment is written to a
<final>.newsibling (invisible to the*.logreplay glob), fsynced, closed; - it is atomically renamed into its final
.logname; live.manifest— the replay-scope list, published via the tmp+fsync+rename atomic writer — is rewritten to list ONLY the new name;- the old names are deleted last.
The manifest is the atomic scope switch: a crash before step 3 replays exactly the pre-rewrite set (the renamed-but-unlisted file is swept at init); a crash after it replays exactly the post-rewrite set (the old files are unlisted and swept). There is no interleaving that replays both sets — the pre-fix fresh-write/delete-after order double-counted surviving ops and resurrected operator-dropped ops.
The manifest is maintained on every lifecycle change: a new active
segment adjoins itself before its first acked append, a rewrite
publishes step 3, a full-flush retire clears the list, and init prunes
listed-but-missing names, sweeps unlisted .log orphans and leftover
.new/.tmp. temps. A store without a manifest (legacy or fresh)
adopts its full .log set as the truth and writes the initial manifest,
so the fallback never re-engages after the first boot.
Pinned by sol_memory_wal_order_SUITE (rewrite_crash_before_publish_replays_pre_set,
rewrite_crash_after_publish_replays_post_set, orphaned_temps_swept_at_init).
Event retention: terminality, dispositions, and the per-aggregate cap
sol_event_compactor deletes an expired event only when its aggregate’s
projection cannot regress on a rebuild. The predicate is retention
terminality, which is broader than a terminal status:
Task: completed | failed | cancelled | timeout and every timestamp
older than the cutoff. Server-side cancel/drop paths write a terminal
projection event (task.failed for cancels; task.dropped is projected
as failed) so a cancelled view is not stuck non-terminal.
Worker: crashed | killed | spawn_failed and old.
Session: closed and old.
Model: the terminal statuses (stopped | failed | start_failed | prepare_failed), plus the never-terminating product statuses
in_use | discovered | prepared | preparing whose last activity
(started_at / last_used_at) is older than the cutoff. Remote
providers emit inference.complete but no model.stopped; this idle
age-out is the provable terminal path for them. started stays live.
unknown statuses/timestamps keep the event (the safe direction).
Per-aggregate hard cap. Even a never-terminating aggregate cannot
grow the log without bound: an event at or below
event_sequence.seq - event_retention_per_aggregate_cap (default 10000,
0 = off) is compacted regardless of the view, counted as
event_retention_cap_forced_total, and a CRITICAL line is emitted. Boot
replay is therefore bounded by the cap per aggregate family.
Metrics. The scrape-time gauge family
sol_event_store_nonterminal_{task,model,worker,session}_aggregates and
sol_event_store_retained_nonterminal_aggregates exposes the aggregates
retention cannot yet release. sol_event_retention_over_budget_total
(the event_retention_max_rows volume budget, default 1,000,000 since
) is ENFORCED: over-budget passes derive a volume cutoff
and reap the oldest rows through the same terminality-aware walk; the
per-aggregate cap remains the per-family hard bound.
Compaction staging: bounded backlog, O(1) scrape
The staging dump (sol_event_compactor_staging.dump) is the durable copy
of compacted events whose archive ack has not been confirmed.
Backlog counter. Every staging mutation writes
sol_event_compactor_staging.count (atomic temp+fsync+rename): the
number of staged events NOT yet acked (dump length minus the durable
drain cursor). staging_backlog/0 reads only this counter — a
Prometheus scrape never decodes the dump. A previous dump without a
counter falls back to one decode and is reconciled on the next
recovery/staging write.
Drained-recovery gate. When recovery actually STALLS (the archive
ack failed — not merely a chunk-budget stop on a healthy archive), new
compaction pages are gated for that pass and counted as
compaction_staging_backlog_gated_total. With the archive down, the
staging backlog therefore stays at the single page that failed, not one
page per pass.
Hard cap. staging_backlog_max_events (default 20000, 0 = off)
refuses a staging append above the cap (staging_backlog_cap_total);
the events stay in Mnesia — the safe direction.
Recovery keeps its ordering contract. The drain cursor
(sol_event_compactor_staging.cursor) is unchanged: windows are acked
in order, the cursor advances after each confirmed window, and a crash
between the ack and the cursor write re-posts only the in-flight
window (content-id idempotency). A corrupt/torn dump is cleared loudly;
it is unrecoverable data by definition.
Telemetry pagination. telemetry_event compaction now walks select
continuations page-by-page (no full expired-id list). The stored
tuples are tagged telemetry_event, so the match spec is built on that
tag — the previous #sync_event{} head matched nothing.
Lane-spill recovery (event store)
The event-lane spill (admitted-but-unexecuted events, one segment at
<mnesia dir>/event_lane_spill/lane_spill.log) replays at boot: the
unretired records are rewritten to a <spill>.new sibling (append +
fsync + close) and then atomically renamed over the segment before
any admission runs. A crash before the rename leaves the original file
untouched (idempotent re-read next boot); a crash after it leaves the
complete rewritten set. The unretired set never exists only in RAM.
On a rewrite failure (disk error) the original segment is untouched and the events are re-admitted from RAM against the intact segment — the durable copy stays the crash-truth until the executing workers retire their records.
Commit-verdict retirement. A spilled admission
is retired only after its event transaction COMMITTED. The lane worker
casts {commit_spill, RecId} (the store appends a {committed, RecId}
frame to the segment) and then {retire_spill, RecId}. The worker DOWN
fallback retires only records in the committed set; a worker that dies
pre-commit — or whose transaction aborts — leaves the record unretired
and counted (event_lane_spill_uncommitted_retained_total), so the boot
replay re-admits it. The replay’s check-before-insert dedupes the
kill-after-commit-before-marker window (the event id is derived from the
RecId), so the marker can never cause a loss or a duplicate.
Pinned by sol_sync_event_lane_spill_SUITE
(lane_spill_survives_store_kill, lane_spill_replay_snapshot_crash_keeps_admissions).
Ordering siblings
The same ordering discipline applies to the store’s ordering neighbors:
Chat history (sol_chat_history): messages order by
{timestamp, seq, msg_id}, where seq is a per-session monotonic
counter allocated at write time. Wall-clock ms alone permutes
same-millisecond messages (the table is ordered_set on the random
msg_id). Legacy pre-seq rows (arity migration at init) are
backfilled at the same migration: the scan assigns stable seqs in
{timestamp, msg_id} order — the historical best-order, since the
msg_id tiebreak is the only surviving order evidence for same-ms
legacy rows — bounded by a budgeted paged scan (default 50000 rows,
chat_seq_backfill_budget); a budget-truncated remainder keeps the
msg_id tiebreak and converges at the next boot (numbering continues
from the store’s max seq, so no collisions). Every row written after
the migration allocates max+1 and therefore sorts after all legacy
rows. Pinned by sol_chat_history_tests
(same_ms_history_ordering_test, store_path_same_ms_order_test,
seq_schema_migration_test,
seq_backfill_budget_truncates_and_converges_test).
Decomposition ids (sol_coordinator): the caller-process
decomposition path mints decomp-<ms>-<monotonic-padded-unique> —
same-millisecond decompositions can no longer collide and silently
replace the registry entry (the gen_server path’s counter was already
collision-free). Pinned by sol_coordinator_routing_tests
(new_decomp_id_same_ms_burst_unique_test).
Compensation markers (sol_workflow_manager): every failed
marker write (aborted transaction, raised failure, invalid args)
bumps workflow_compensation_marker_failed_total — the marker is
load-bearing (a lost marker lets recovery re-run an unwind), so the
failure is observable. Pinned by sol_workflow_manager_restart_tests
(compensation_marker_abort_counted_test,
compensation_marker_success_not_counted_test,
compensation_marker_invalid_args_counted_test).
Residual (accepted)
A torn/corrupt MID-segment frame still truncates that segment’s
suffix silently (sol_durable_file frame decoder returns the intact
prefix; no per-frame CRC). Torn tails from crash-mid-append are the
expected case and are handled correctly. Revisit per-frame checksums
if segment sizes grow.
Op-sequence frames ({op, Seq, Op} with dedupe-by-seq replay) remain
the optional successor hardening; the manifest made them unnecessary
for the rewrite window.
Engine reference — generated from the canonical engineering source. Do not edit this page by hand.
Model Catalog
Cost-accounting scope. The
pricingblock on this page is per-model vendor rate metadata used bysol_costfor spend accounting. It is not a commercial offer; commercial terms are not announced. For licensing or evaluation, contact Spacebeam.
Status: LIVE. One declarative source describes every model ZERG knows: identity, aliases, provider, wire, context window, modalities, capabilities, rate metadata and serving/registration posture. Runtime reads only the generated artifacts — never YAML.
Source of truth
contract/model_catalog.yaml (version: 1, a models: list). Each
descriptor carries:
| Field | Meaning |
|---|---|
id | Canonical model id (what a client sends). Unique. |
aliases | Additional request ids. Globally unique; an alias may never equal an id. |
provider | Canonical provider name (e.g. anthropic, zai, groq, local). |
wire | openai, anthropic or local (lane-owned llama.cpp). |
context_window | Positive integer token window. |
modalities | text / image (non-empty). |
capabilities | Subset of tools, thinking, vision, cache, streaming, strict_json. cache gates Anthropic cache_control injection: an unknown/non-declared model gets no automatic markers, and the caller’s markers are capped at Anthropic’s 4-breakpoint budget. |
pricing | input_per_mtok + output_per_mtok (+ optional cache read/write). Either free: true (a zero-rate local row) or unpriced: true with a reason when no bundled rate exists. |
serving | register: adapter | declarative | local | none; adapter rows name adapter (the behavior-owning Erlang module). |
luna_descriptor | Present only for the models shipped in Luna’s static catalog (name, provider override, max temperature, thinking levels). |
The catalog covers every bundled adapter model, every declarative
provider JSON model, the 18 Luna client descriptors and the local
lane model rows (wire: local, with the registry filename slug as an
alias).
Canonical identity. Aliases are request ids only: the
runtime resolves them to their id before building a provider body
(sol_model_catalog:canonical/1), and the declarative loader stamps
canonical_model on every registry row. A registered row is not
necessarily dispatchable: dispatchability requires an endpoint +
credentials (remote) or a local lane identity; the fallback candidate set
and the health probe use the dispatchable set.
Regenerate and verify
python3 ci/catalog_gen.py # rewrite every committed artifact
python3 ci/catalog_gen.py --check # exit 1 on drift (CI gate)
python3 ci/model_catalog_lint.py # bidirectional parity gate
Generated artifacts (all committed, deterministic sorted-key output with a content hash):
server/priv/model_catalog.json — Sol boot artifact read by
sol_model_catalog.
docs/fixtures/model_provider_map.json — the Sol↔Luna model→provider
fixture (sol_provider_* modules, adapter models, ordered Luna prefixes,
declared divergences).
client/data/models.json and client/core/_models_data.lua — Luna’s static
catalog (bundled inline form included).
server/test/fixtures/model_catalog_bounded.json — bounded loader/lint
fixture (12 rows).
Duplicate ids or aliases are a hard error in the generator (never last-write-wins). An empty catalog is also a hard error.
Add or override a model without code
A model on an existing declarative provider
- Add
{"id": "...", "alias": "..."}to the provider’sserver/priv/providers/*.json(or the operator user config directory). - Add a descriptor for the id to
contract/model_catalog.yaml(serving: {register: declarative, provider_config: <name>}), including aliases and rate metadata. - Run
python3 ci/catalog_gen.py.
Declarative providers are still registered at boot by
sol_provider_declarative:load_configs/0; the catalog owns the metadata and
the lint parity, not the provider URL/key.
A bundled adapter model
Add the id to the adapter’s models list and the catalog descriptor
with serving: {register: adapter, adapter: sol_provider_<name>}. The
adapter keeps behavior ownership (format_request/2, parse_*); boot
registers the catalog row with the same #{wire_format => …} opts as before.
Override rates or capabilities
Edit the descriptor and regenerate. The client catalog and fixture update
together. pricing is the ONE billing rate source (sol_cost:price/1);
metadata_override records a deliberate divergence between the catalog and
the bundled sol_model_metadata fallback table for clients/tooling. It never
changes what sol_cost charges:
pricing:
input_per_mtok: <input-rate>
output_per_mtok: <output-rate>
metadata_override:
input_per_mtok: <input-rate>
output_per_mtok: <output-rate>
reason: "catalog is the rate source; metadata is the no-catalog-row fallback"
A stale override (one that no longer matches the metadata table) fails the lint, and so does a reason that claims metadata is the rate source.
A local lane row
Local lanes are described with wire: local, provider: local and
serving: {register: local, lane: <lane>, engine: <engine>}. The alias is
the registry filename slug (the id sol_http_streaming actually resolves via
sol_registry:find_by_name/1), e.g. qwen38_atx ↔
qwen3.8-27b-atx-4-xs. The lane registry remains the lifecycle owner; see
local-inference-lanes.md.
Runtime behavior
Billing: the catalog pricing block is the
server billing rate source (sol_cost:price/1). Aliases and local lane ids
resolve through the same lookup; rows without numeric rates are
unknown_price (never a silent zero). metadata_override remains a
generated client-view annotation.
Boot: sol_provider_boot:register_defaults/0 calls
sol_model_catalog:register_defaults/0 (bundled adapter rows and their
catalog aliases), then keeps
the dynamic Ollama discovery and the declarative JSON load. If the
generated artifact is missing/invalid, boot logs the typed error and falls
back to the legacy adapter lists loudly — never silently zero providers.
Unknown models: sol_pipeline:build_request_body/3 returns
{error, {unknown_model, Model}} instead of silently building an
OpenAI-wire body. The pipeline relays that as the existing not_found
class, so HTTP clients receive 404, not a 500 or a wrong-provider
request. ’s unknown-wire refusal in the declarative loader is
unchanged.
Adapter rows without an endpoint: a catalog register: adapter row is
only dispatchable once a declarative provider supplies base_url +
api_key_env; the HTTP funnel answers a typed 503 provider not configured instead of a misleading resolver 404.
Local lane models still resolve: a catalog wire: local row (lane id
or filename alias) or a live/prepared sol_registry row keeps the local
OpenAI-compatible body path.
What the lint pins
ci/model_catalog_lint.py fails on:
duplicate ids/aliases, aliases colliding with ids, dangling aliases;
adapter models ↔ catalog (missing and extra entries, provider drift);
boot registration surface (catalog registration + dynamic Ollama +
declarative JSON);
declarative provider JSON ↔ catalog (a provider model without a descriptor,
or a register: declarative descriptor with no provider row);
sol_model_metadata rates (exact match or a matching typed override);
Luna client/data/models.json ↔ luna_descriptor rows;
Luna’s ordered prefix table / default / declared divergences;
unpriced descriptors without the typed flag;
empty corpus and stale generated artifacts (catalog_gen --check).
See also
api-reference.md — GET /api/v1/models/metadata and
the model-listing endpoints.
local-inference-lanes.md — lane lifecycle and
validation.
local-inference-runbook.md — operator
start/stop/validate.
Engine reference — generated from the canonical engineering source. Do not edit this page by hand.
Prompt Cache Layout and Prefix Stability
Luna’s system prompt is assembled in a canonical, cache-friendly layout. The goal is that the bytes a provider can cache stay identical turn-to-turn and child-to-child, while genuinely volatile context (date, cwd, git state, memory, query-specific retrieval) changes only after a literal boundary.
Canonical layout
client/core/system_prompt.lua partitions sections into two classes:
| Stable (cached) | Volatile (not cached) |
|---|---|
| intro / identity | date, platform, model, working directory |
| system rules (and desktop rules) | git context (branch, commits, dirty count) |
| mode section (build/plan/explore/review/general/coordinate) | memory context |
| instruction files (AGENTS.md/CLAUDE.md/SYSTEM.md/.cursorrules, APPEND_SYSTEM.md) | skills discovery output |
| tool usage guidelines | |
| available tool descriptions |
The stable sections are joined with \n\n, followed by the literal marker in
client/core/prompt_prefix.lua:
\n\n<!-- luna:stable-prefix-boundary -->\n\n
then the volatile sections. All existing prompt content is preserved; only
order and the boundary insertion changed. The old order is available through
the test/benchmark seam SystemPrompt.set_layout_for_test("legacy").
Deterministic tool order
Tools.specs (and Tools.specs_by_namespace) sort by advertised tool
name, and the prompt’s tool-guideline/tool-description lists sort their input
copy. The same tool set therefore produces a byte-identical tools array and
stable prompt text regardless of registry hash order.
Prefix hash and diagnostics
client/core/prompt_prefix.lua computes:
sha256( len(stable_text) .. ":" .. stable_text
.. "|" .. len(tool_bytes) .. ":" .. tool_bytes )
where tool_bytes is a canonical, key-sorted encoding of each tool’s
name/description/input_schema (sorted by tool name). Diagnostics
(hash, backend, stable_text_bytes, volatile_text_bytes,
tool_schema_bytes, cacheable_bytes, boundary) are stored on
session.prompt_prefix and on the provider instance as
provider._last_prompt_prefix (never inside the request table — that table is
JSON-encoded verbatim). Read them through PromptPrefix.diagnostics(source).
The backend field is sha256 when libcrypto (or the openssl CLI fallback)
is available; otherwise a deterministic FNV-1a digest is used and recorded
honestly.
Provider markers
For Anthropic-wire providers that support cache_control, the client splits
the system prompt at the boundary into two text blocks: the stable block
carries cache_control: {type="ephemeral"}, the volatile block carries none.
Concatenating the blocks reproduces the prompt bytes exactly. The existing
recency markers on the last three messages are unchanged (they are inherently
after the boundary). Boundary-less prompts (custom config.system_prompt)
keep the legacy single-block shape with the marker on that block.
Cache-identical forks
The local sub-agent spawn path (client/core/sub_agent.lua) gives
_shared_system_prompt and _frozen_tool_specs a real producer:
the parent’s lazily-built prompt is materialized before the spawn,
Agent._build_system_prompt snapshots the advertised tool-spec array (deep
copy) as _frozen_tool_specs,
a local child inherits the parent’s exact prompt string and a deep copy of
that array; Agent:_ensure_system_prompt serves the frozen array for the
provider wire and prompt hash while config._tool_filter continues to
enforce the child’s narrower dispatch set,
forks taken mid-tool get one canonical tool_result placeholder for the
unmatched trailing tool_use (_generate_fork_placeholders with
canonical=true, only_incomplete=true).
Divergence starts only after the boundary (memory fence, new turns).
ZMQ limitation (explicit)
ZMQ and background children cannot share the parent’s provider cache
state. The spawn crosses a process/worker boundary into a possibly
different API key, provider endpoint, or model; Anthropic/OpenAI cache lines
are per-session. Background forwarding carries the frozen prompt bytes so
the child starts from identical instructions, but no cache state crosses the
wire — this is documented, not faked. cache_context is intentionally not
forwarded on the ZMQ path.
Measurement
luajit benchmarks/prompt_prefix_stability.lua scripts the same fleet turn
twice for the canonical and legacy layouts and reports cacheable bytes, hash
stability, fork equality, and timing. The measured dev-host run lives in
benchmarks/prompt-prefix-stability.md.
Engine reference — generated from the canonical engineering source. Do not edit this page by hand.
API Reference
Sol exposes a Cowboy HTTP API on port 21434 (configurable). All endpoints return JSON unless otherwise noted. Streaming endpoints use Server-Sent Events (SSE).
Base URL
http://127.0.0.1:21434
Default bind address is 127.0.0.1. Change with http_ip config or SOL_HTTP_IP env var.
Authentication
Bearer token authentication via Authorization: Bearer <key> header. Auth modes:
Local mode — static API keys configured in sys.config ({auth_tokens, ["key1", "key2"]})
or with per-token permissions ({auth_tokens, [{<<"key1">>, [<<"tasks:read">>]}]});
a bare token grants * (CRITICAL-logged at boot until migrated).
Mango mode — tokens validated against Mango auth service at /auth/validate
Mango validation is the FIRST layer: a valid token is not admission. Sol’s
middleware then runs its OWN per-route RBAC/ownership layer against the
validated grant ({METHOD, path} => scope, owner scopes, admin rules). A
route with no rule is refused by default (authz_unmapped, 403) — the token
alone never authorizes a route.
x-api-key: <key> is accepted as a bearer-equivalent credential (the native
Anthropic SDK header). Authorization wins when both are present; neither is
an ambient credential, so both follow the bearer CSRF contract.
Health endpoint (/health) is exempt. Unauthenticated requests to other endpoints return 401.
Pagination
All list endpoints support two mutually exclusive cursor styles
(source: sol_http_pagination.erl parse_pagination/1):
| Parameter | Default | Max | Description |
|---|---|---|---|
limit | 50 | 500 | Maximum items to return |
offset | 0 | — | Number of items to skip |
page | 0 | — | 1-based page number — only honored when per_page is also given |
per_page | 0 | — | Items per page (capped at 500) — when BOTH page and per_page are > 0 they override limit/offset (offset = (page-1) × per_page) |
Paginated response format (paginate_list/2):
{
"items": [...],
"total": 142,
"limit": 50,
"offset": 0,
"page": 1,
"total_pages": 3,
"has_more": true
}
page/total_pages are always present (1-based); has_more is false on
the last page.
Paginated endpoints: GET /api/v1/models, GET /api/v1/agents, GET /api/v1/tasks, GET /api/v1/catalog, GET /api/v1/channels, GET /api/v1/circuits, GET /api/v1/schedule, GET /api/v1/zmq/workers, GET /api/v1/events, GET /api/v1/skills, GET /api/v1/workflows, GET /api/v1/goals, GET /api/v1/cluster, GET /api/v1/audit/events, GET /api/v1/memory/:agent_id (default limit 50), GET /api/v1/memory/:agent_id/search (default limit 20). The marketplace browse is deliberately NOT in this list — it answers the flat {"skills": [...]} shape (see its section below).
Response Format
Success (JSON) — three real dialects
There is no single success envelope. The body is the resource projection itself, in one of three dialects (the code is the source; every client already parses them this way):
| Dialect | Shape | Examples |
|---|---|---|
| Resource object | the resource’s own fields at the top level | GET /api/v1/health → {"status":"ok","models_running":2}; GET /api/v1/models/:name → a model row |
| Page | {"items":[...],"total":N,"limit":50,"offset":0,"page":1,"total_pages":3,"has_more":true} — see Pagination | every list endpoint in the pagination table (/api/v1/models, /api/v1/tasks, /api/v1/events, …); GET /api/v1/goals answers the same metadata with goals in place of items |
| Ack envelope | {"ok":true,...} where ... carries the affected resource when one exists | GET /api/v1/teams → {"ok":true,"teams":[...]}; POST /api/v1/teams → {"ok":true,"team":{...}}; mutations → {"ok":true} |
The OpenAI (/v1/chat/completions) and Anthropic (/v1/messages) routes
keep their upstream dialects; see the family table under Error below.
Error (JSON) — one envelope per API family
Errors speak the dialect of the API family that produced them, so drop-in
openai/anthropic SDK clients parse error.message correctly. Since
Every handler error — and the auth middleware’s 401/403 — emits the
family envelope; the retired flat {"error":"string"} shape is gone:
| Family | Routes | Error body |
|---|---|---|
| OpenAI | /v1/chat/completions, /v1/models | {"error":{"message":"...","type":"invalid_request_error","param":null,"code":null}} |
| Anthropic | /v1/messages, /v1/messages/:id | {"type":"error","error":{"type":"invalid_request_error","message":"..."}} |
| Zerg | /api/v1/* | {"ok":false,"error":{"code":"...","message":"..."}} |
Mango identity API is a DOCUMENTED second dialect:
the Mango service (/auth/* on the Mango base URL) still emits the flat
{"error":"string"} body on errors — a deliberate cheap-honest deferral,
not an oversight. Limon’s HTTP clients unwrap BOTH shapes (envelope
error.message/error.code first, legacy flat string as the fallback),
and both unwraps are contract-tested. Sol’s /api/v1/auth/* proxy rows
answer the Zerg envelope like every other /api/v1/* route.
Teams speaks the Zerg envelope everywhere: the teams
handler was the last Sol surface still replying flat bodies on some arms
. All teams
4xx now carry {"ok":false,"error":{"code","message"}} with the
catalog vocabulary (forbidden, not_found, method_not_allowed,
body_too_large, bad_request, invalid_worker_id, unroutable_to).
Mango identity-plane contract notes:
GET /ready caches its DB/migration/instance verdict for ~1s for
non-loopback callers (loopback stays live); every other outcome is a
typed 503 + Retry-After.
POST /auth/service-token answers the uniform 403 {"error": "forbidden"} for every non-success credential/shape failure; the
service/bridge/audit/archive secrets have a 16-byte boot floor.
Security booleans (on/off, true/false, 1/0, yes/no) refuse
boot on any other spelling; MANGO_REQUIRE_AUTH=true blocks anonymous
requests centrally (401).
POST /orchestrator/lease is bound to the token user; a stale steal
by a different principal requires takeover authority, and an optional
epoch in the body is CAS-checked (409 lease_epoch_stale).
POST /api/mango/audit-archive validates timestamp/source/
aggregate_id/event_type types and lengths (400) and maps DB
failures to a typed 503; the audit-chain verdict is ok=false when
unanchored/truncated, and a restored older checkpoint is refused.
401/403 from the auth middleware are family-aware: both the
401 and the 403 render the route family’s dialect — 401 carries code
unauthorized; auth-rate-limit saturation is a fail-closed 503 +
Retry-After (rate_limiter_unavailable), never a 401; the 403 code
vocabulary is in the catalog below.
Capacity is never a 500: seat/worker exhaustion → 429 with
Retry-After: 1 (seat_cap_reached, max_workers_reached); license
outage → 503 license_unavailable; scheduler quotas → 429
(max_jobs_reached, per_user_limit_reached); all provider circuits
open → 503.
Upstream timeouts are never a 500: on the buffered
completion surfaces a pipeline timeout family — total timeout,
first_token_timeout, idle_timeout — answers 504 (server_error
on the OpenAI wire, overloaded_error on the Anthropic wire); connect
failures (connect_failed, connect_exhausted, connection_down)
answer 502 api_error; every provider key cooling down
(provider_exhausted) answers 429 rate_limit_error with
Retry-After: 1. The same ladder runs on both dialects
(/v1/chat/completions and /v1/messages).
SSE connection-budget refusal is 429 on every route (; body
envelope re-anchored ): when the max_sse_connections budget
is full, ALL completion/stream surfaces — /v1/chat/completions (stream
and buffered), /v1/messages (stream and buffered), the chat stream, and
the event/workflow/conversation streams — answer 429
sse_limit_reached with Retry-After: 1 and the Zerg OBJECT envelope
{"ok":false,"error":{"code":"sse_limit_reached","message":"..."}} (one
shape, previous the completion planes answered 503; previous the body
was the retired flat string form). The check runs BEFORE the serving slot
is reserved: a refused request never occupies an admission slot. The chat
stream additionally holds its slot for the WHOLE stream (, —
previous the slot was released at handshake and the budget never
bounded chat).
Malformed /v1/messages blocks are 400: assistant/user
tool_use blocks require string id + string name + object input,
tool_result blocks require string tool_use_id — violations answer
400 invalid_request_error with the offending block type named
. Unknown block
types keep the pass-through posture.
Retired responses wire: the OpenAI Responses API adapter is
a documented refusal — declarative provider configs declaring
format: "responses" fail validation, boot registers no
responses-adapter models, and requests naming a responses model cannot
resolve. Use the openai or anthropic wire.
Oversized bodies → 413 with the ONE code body_too_large
everywhere (the payload_too_large spelling is retired — one catalog
entry, ).
Mango identity API: the 10MB body cap is enforced on the
DECODED length regardless of transfer encoding (chunked bodies carry no
Content-Length; Tornado’s Application-level max_body_size closes the
bypass, with a decoded-length re-check on direct paths).
409 conflict semantics: JSON read-modify-write endpoints
(Mango PATCH /users, team cost-centers/caps) return 409 conflict
on concurrent modification — the updated_at compare-and-swap detects a
stale read; retry the operation. trusted_proxies (app setting or
MANGO_TRUSTED_PROXIES) controls which peers may supply
X-Forwarded-For/X-Real-IP; the client is the rightmost-untrusted hop.
Global-trust CIDRs (0.0.0.0/0, ::/0) are REJECTED at parse (CRITICAL +
dropped — fail toward untrusted) unless MANGO_ALLOW_GLOBAL_TRUST=true
.
Provider failures are 503 (never 500): provider circuits and
all_circuits_open → 503 circuit open / all providers unavailable;
upstream errors (http_error, connect_exhausted,
output_exceeded_cap, timeout, first_token_timeout,
idle_timeout, parse_error) → 503 with the reason in the body.
Interrupted streams: an SSE error frame emitted AFTER content tokens
carries "truncated": true so clients can distinguish a partial answer
from a failed-before-output one.
Error-code catalog
One shared classifier (sol_http_json:classify_error) turns every
{error, Reason} backend failure into a status + code. The classes:
| Status | Code | When |
|---|---|---|
| 503 | service_unavailable | Store/gen_server outage — mnesia aborted/no_exists, noproc, timeout, shutdown, killed, local econnrefused, resource exhaustion (enospc/enfile/emfile). Temporary; safe to retry. |
| 502 | upstream_error | Remote/upstream failure — exec-class exit_status, cluster node_unreachable/noconnection, remote http_error/connect_exhausted. |
| 500 | internal_error | Genuinely-internal fault (the catch-all armor arms only). A 500 is always a bug worth reporting. |
Catalog codes clients should dispatch on (Zerg family, error.code):
| Code | Status | Semantics |
|---|---|---|
body_too_large | 413 | The ONE oversized-body code (request body, session-share data, file reads past the cap). |
forbidden | 403 | Resource-ownership denial — the record exists but belongs to another user (owner-check arms). |
insufficient_permissions | 403 | RBAC/route-gate denial — the token lacks the permission or admin bit (middleware 403, admin-gated endpoints). |
unauthorized | 401 | Missing/invalid/expired token (middleware 401). |
service_unavailable | 503 | Backend outage (the 503 class above). |
upstream_error | 502 | Remote failure (the 502 class above). |
Endpoint-specific codes (seat_cap_reached, share_quota_exceeded,
max_jobs_reached, workflow not found-class 404s, …) keep their
documented statuses; the catalog above is the shared vocabulary on top.
Additional catalog entries:
| Code | Status | Meaning |
|---|---|---|
worker_unavailable | 503 | The session’s worker is not serving — dead worker, noproc, or the typed worker_not_found pipeline-attach refusal (worker died between the stream-liveness gate and pipeline start). Both the REST message path and the WS path share one classifier. |
auth_disabled | 503 | POST /api/v1/auth/login with Mango auth disabled system-wide — an outage of the auth subsystem, never a success. |
unknown_parameter | 400 | A removed/unrecognized query pseudo-value — currently ?aggregate=all on GET /api/v1/events. |
aggregate_scan_limit_exceeded | 400 | A caller-scoped aggregate read would scan past the server’s bounded index-row cap; narrow the aggregate scope or resume with from_seq/cursor. |
invalid_cursor | 400 | ?cursor= is not the <seq>:<event_id> form returned in next_cursor. |
cursor_with_offset / cursor_with_from_seq | 400 | The {seq,event_id} cursor already names the resume point; combining it with offset or from_seq would skip/duplicate rows. |
pprof_disabled / profiling_failed / heap_profiling_failed / flamegraph_failed / not_found | 404/403/500 | The debug endpoints’ envelope codes. |
auth_rate_limited | 503 | Token validation was refused because Mango answered 429 (the global auth limiter’s burst response) — a RETRYABLE-TRANSIENT condition, never cached as a failed validation; the response carries retry-after and the next request re-validates. |
csrf_required | 403 | A mutating request whose credential is the ambient zerg_session cookie without the zerg_csrf double-submit pair. |
invalid_request_path | 400 | The raw path cannot be represented unambiguously by the router: an encoded separator (%2F/%5C), an empty internal segment (//), an invalid percent escape, a control byte, or a non-absolute path. |
method not allowed | 405 | A bare OPTIONS (not a genuine CORS preflight) or a HEAD on a path whose only rules are for other methods. The response carries the route’s Allow set; HEAD otherwise authorizes exactly as GET. |
Documented residuals (not envelope emissions): webhook raw bodies (the
empty-body platform acks, and the Teams validationToken text/plain echo
below) are wire contracts, not error envelopes; the rate-limiter capacity
shapes, the
maintenance gate (maintenance_mode + reason), and the memory
subsystem-off 503 ({"error": "memory_subsystem_disabled", "enabled": false} on every /api/v1/memory/* route while Sol memory is disabled —
/, CT-2: retained in its historical flat shape, consumed by
Limon’s unwrap fallback) keep their documented flat
bodies; error fields inside SSE data: frames and per-item result lists
are stream/data payloads, not HTTP error envelopes.
Internal Erlang terms are sanitized and never leaked to clients.
Streaming (SSE)
data: {"choices": [{"delta": {"content": "Hello"}, ...}]}
data: [DONE]
Interrupted streams
When the upstream provider connection dies mid-generation, the terminal is honest — a truncated response is never reported as a complete one. The three terminals:
OpenAI-wire SSE (/v1/chat/completions, "stream": true): the final
chunk carries "finish_reason": "interrupted" (a non-stop reason in
the normal chunk shape), followed by the regular data: [DONE] framing
so spec-compliant clients terminate cleanly. Tokens already delivered
remain valid; the delivered-token count is the accounting floor.
Anthropic-wire SSE (/v1/messages, "stream": true): the stream
ends with an in-band terminal event: error frame carrying
{"type":"error","error":{"type":"api_error","message":"..."}} — no
fabricated message_delta end_turn / message_stop completion.
Buffered non-streaming ("stream": false, both wires): the reply had
not started, so the honest shape is HTTP 502 (upstream class) in the
route family’s error envelope — OpenAI {"error":{...}} / Anthropic
{"type":"error","error":{...}} with the message
upstream connection interrupted mid-response (truncated). Never a 200
envelope with a fabricated finish_reason/stop_reason.
Endpoint Directory (generated)
Health
| Method | Path | Handler action | Description |
|---|---|---|---|
| GET | /api/v1/health | health | Health check |
| GET | /api/v1/providers/health | provider_health | All provider health checks |
| GET | /api/v1/providers/health/:name | provider_health_single | Single provider health check |
| GET | /api/v1/ready | ready | Readiness check |
| GET | /api/v1/skills | skills | List skills |
| GET | /api/v1/skills/:name | skill_detail | Get skill details |
| GET | /metrics | prometheus_metrics | Prometheus metrics — : no longer anonymous. Loopback peers scrape tokenless; non-loopback requires a bearer with metrics:read (tokenless external → typed 403). GET only |
| GET | /v1/models | openai_models | OpenAI-compatible models list |
Inference
| Method | Path | Handler action | Description |
|---|---|---|---|
| POST | /api/v1/discover | discover | Discover models from storage |
| GET | /api/v1/inference/lanes | lanes | List the fleet lane inventory (sanitized; includes the use_case facet) |
| POST | /api/v1/inference/lanes/:lane/validate | lane_validate | Probe or commit a lane validation record (admin) |
| GET | /api/v1/metrics | metrics | Get metrics counters |
| GET | /api/v1/models | models | List registered models |
| GET | /api/v1/models/:name | model_detail | Get model details |
| GET | /api/v1/models/metadata | model_metadata | Get registry metadata for all known models |
| POST | /api/v1/prepare/:name | prepare | Prepare model for serving |
| GET | /api/v1/ps | ps | List running models |
| POST | /api/v1/start | start | Start a model |
| POST | /api/v1/stop | stop | Stop a model |
| POST | /api/v1/stop-all | stop_all | Stop all models |
| GET | /api/v1/usage | usage | Get per-principal inference usage/spend totals (self; admin may pass?user_uuid=;?from/?to=YYYY-MM-DD) |
Completions
| Method | Path | Handler action | Description |
|---|---|---|---|
| POST | /v1/chat/completions | completions | OpenAI chat completions |
| POST | /v1/completions | text_completions | OpenAI legacy text completions (FIM; non-streaming) |
| POST | /v1/messages | messages | Anthropic Messages API |
Workers
| Method | Path | Handler action | Description |
|---|---|---|---|
| GET | /api/v1/agents | agents | List running agents (legacy) |
| GET | /api/v1/agents/:id | agent_detail | Get agent details |
| POST | /api/v1/agents/:id/kill | agent_kill | Kill an agent |
| POST | /api/v1/agents/:id/task | agent_task | Dispatch task to agent |
| POST | /api/v1/agents/spawn | agent_spawn | Spawn a new agent |
| POST | /api/v1/orchestrate | orchestrate | Orchestrate a task |
| GET | /api/v1/orchestrate/:id | orchestrate_detail | Get orchestration details |
| GET | /api/v1/tasks | task_list | List all tasks |
| GET | /api/v1/tasks/:task_id | task_get | Get a stored task result (owner or admin) |
| DELETE | /api/v1/tasks/:task_id | task_status | Cancel a task (owner or admin) |
| GET | /api/v1/tasks/outbox | task_outbox | List outstanding dispatch receipts |
| GET | /api/v1/workers/bg | bg_list | List background workers |
| GET | /api/v1/workers/bg/:bg_id | bg_status | Get background worker status |
| POST | /api/v1/workers/bg/:bg_id/kill | bg_kill | Kill a background worker |
| GET | /api/v1/workers/bg/:bg_id/logs | bg_logs | Get background worker logs |
| POST | /api/v1/workers/bg/start | bg_start | Start a background worker |
Scheduler
| Method | Path | Handler action | Description |
|---|---|---|---|
| GET | /api/v1/schedule | schedule_list | List scheduled jobs |
| DELETE | /api/v1/schedule/:id | schedule_delete | Delete a scheduled job (admin; 409 while the job is running) |
| GET | /api/v1/schedule/:id | schedule_detail | Get job details |
| POST | /api/v1/schedule/:id/pause | schedule_pause | Pause a job |
| POST | /api/v1/schedule/:id/run | schedule_run | Run a job immediately |
| POST | /api/v1/schedule/:id/unpause | schedule_unpause | Unpause a job |
| POST | /api/v1/schedule/spawn | schedule_create | Create a scheduled job |
Channels
| Method | Path | Handler action | Description |
|---|---|---|---|
| GET | /api/v1/channels | channels | List channels |
| GET | /api/v1/channels/:id | channel_detail | Get channel details |
| DELETE | /api/v1/channels/:id | channel_delete | Delete a channel |
| POST | /api/v1/channels/:id/message | channel_message | Send message to channel |
| POST | /api/v1/channels/:id/pause | channel_pause | Pause a channel (POST only) |
| POST | /api/v1/channels/:id/resume | channel_resume | Resume a channel (POST only) |
| POST | /api/v1/channels/:id/test | channel_test | Send test message (POST only; admin) |
| POST | /api/v1/channels/spawn | channel_create | Create a channel |
Memory
| Method | Path | Handler action | Description |
|---|---|---|---|
| GET | /api/v1/memory/:agent_id | memory_list | List memories for agent |
| GET | /api/v1/memory/:agent_id/:key | memory_retrieve | Retrieve a memory entry |
| DELETE | /api/v1/memory/:agent_id/:key | memory_delete_rest | Delete a memory entry (REST-correct form; ownership-checked) |
| POST | /api/v1/memory/:agent_id/:key/delete | memory_delete | Delete a memory entry (legacy POST action form) |
| POST | /api/v1/memory/:agent_id/:key/pin | memory_pin | Pin a memory entry |
| POST | /api/v1/memory/:agent_id/clear | memory_clear | Clear agent memories (owner-scoped wipe; admin clears the full namespace) |
| POST | /api/v1/memory/:agent_id/decay | memory_decay | Run memory decay |
| GET | /api/v1/memory/:agent_id/reflections | memory_reflections | Get memory reflections |
| GET | /api/v1/memory/:agent_id/search | memory_search | Search agent memories |
| GET | /api/v1/memory/:agent_id/stats | memory_agent_stats | Get per-agent memory stats (entry count + total bytes) |
| POST | /api/v1/memory/:agent_id/vector-search | memory_vector_search | Vector similarity search |
| GET | /api/v1/memory/stats | memory_stats | Get memory statistics |
| POST | /api/v1/memory/store | memory_store | Store a memory entry |
Events
| Method | Path | Handler action | Description |
|---|---|---|---|
| GET | /api/v1/events | events_query | Query events |
| GET | /api/v1/sync-events | sync_events_stream | SSE event stream |
Workflows
| Method | Path | Handler action | Description |
|---|---|---|---|
| GET | /api/v1/workflows | workflows_list | List workflows |
| GET | /api/v1/workflows/:id | workflow_detail | Get workflow details |
| POST | /api/v1/workflows/:id/branch | workflow_branch | Branch a workflow |
| POST | /api/v1/workflows/:id/cancel | workflow_cancel | Cancel a workflow |
| POST | /api/v1/workflows/:id/compensation/retry | workflow_compensation_retry | Retry a pending workflow compensation |
| GET | /api/v1/workflows/:id/lineage | workflow_lineage | Get workflow lineage |
| POST | /api/v1/workflows/:id/pause | workflow_pause | Pause a workflow |
| POST | /api/v1/workflows/:id/resume | workflow_resume | Resume a workflow |
| GET | /api/v1/workflows/:id/stream | workflow_stream | Stream workflow events |
| GET | /api/v1/workflows/:id/tree | workflow_tree | Get workflow tree |
| POST | /api/v1/workflows/start | workflow_start | Start a workflow |
Teams
| Method | Path | Handler action | Description |
|---|---|---|---|
| GET | /api/v1/teams | teams_list | List teams |
| POST | /api/v1/teams | team_create | Create a team |
| GET | /api/v1/teams/:id | team_detail | Get team details |
| POST | /api/v1/teams/:id | team_add_member | Add a team member |
| DELETE | /api/v1/teams/:id | team_destroy | Destroy a team |
| POST | /api/v1/teams/:id/mail | team_mail | Send team mail |
| GET | /api/v1/teams/:id/mail | team_mail_read | Read team mail (non-destructive;?mine=1 scopes to the caller’s membership) |
| POST | /api/v1/teams/:id/mail/:message_id/ack | team_mail_ack | Acknowledge one team-mail message |
| GET | /api/v1/teams/:id/members | team_members_list | List team members (membership-gated) |
| POST | /api/v1/teams/:id/members | team_members | Manage team members |
| DELETE | /api/v1/teams/:id/members/:worker_id | team_member_remove | Remove team member |
Workspace
| Method | Path | Handler action | Description |
|---|---|---|---|
| POST | /api/v1/workspace/edit | workspace_edit | Edit a workspace file (find and replace) |
| GET | /api/v1/workspace/list | workspace_list | List workspace files |
| POST | /api/v1/workspace/read | workspace_read | Read a workspace file |
| POST | /api/v1/workspace/search | workspace_search | Search workspace files by pattern |
| POST | /api/v1/workspace/write | workspace_write | Write a workspace file |
Recipes
| Method | Path | Handler action | Description |
|---|---|---|---|
| GET | /api/v1/recipes | recipes_list | List recipes |
| GET | /api/v1/recipes/:name | recipe_detail | Get recipe details |
| POST | /api/v1/recipes/:name/run | recipe_run | Run a recipe |
| POST | /api/v1/recipes/reload | recipes_reload | Reload recipes |
Marketplace
| Method | Path | Handler action | Description |
|---|---|---|---|
| GET | /api/v1/marketplace | marketplace_browse | Browse marketplace skills |
| POST | /api/v1/marketplace | marketplace_publish | Publish a skill |
| GET | /api/v1/marketplace/:name | marketplace_detail | Get skill detail |
| GET | /api/v1/marketplace/:name/:author | marketplace_author_detail | Get skill detail by exact author (two-segment form) |
| DELETE | /api/v1/marketplace/:name/:author | marketplace_delete | Delete a published skill |
| POST | /api/v1/marketplace/:name/:author/install | marketplace_install | Install a skill (full body + provenance) |
| POST | /api/v1/marketplace/:name/:author/report | marketplace_report | Report a skill |
| POST | /api/v1/marketplace/feature | marketplace_feature | Feature a skill (admin) |
| POST | /api/v1/marketplace/rate | marketplace_rate | Rate a skill |
| GET | /api/v1/marketplace/ratings | marketplace_ratings | Get ratings for a skill |
| GET | /api/v1/marketplace/reports | marketplace_reports | List skill reports |
| POST | /api/v1/marketplace/reports/:id/dismiss | marketplace_dismiss | Dismiss a skill report |
| GET | /api/v1/marketplace/search | marketplace_search | Search marketplace |
Skills
| Method | Path | Handler action | Description |
|---|---|---|---|
| POST | /api/v1/skills | skills_register | Register a skill |
| DELETE | /api/v1/skills/:name | skills_delete | Delete a skill |
Cluster
| Method | Path | Handler action | Description |
|---|---|---|---|
| GET | /api/v1/catalog | catalog_list | Global model catalog |
| GET | /api/v1/circuits | circuits | List circuit breakers |
| POST | /api/v1/circuits/reset | circuit_reset | Reset circuit breaker |
| GET | /api/v1/cluster | cluster_status | Cluster status |
| POST | /api/v1/cluster/join | cluster_join | Join a cluster node |
| POST | /api/v1/cluster/leave | cluster_leave | Leave the cluster |
Auth
| Method | Path | Handler action | Description |
|---|---|---|---|
| POST | /api/v1/admin/tokens/:token_id/revoke | admin_revoke_token | Revoke one Mango token by its persisted SHA-256 id (admin; strict audit). token_id is the 64-hex token id from the service-token listing; the Sol service principal performs POST /auth/tokens/:id/revoke at Mango. Typed answers: 400 invalid_token_id, 403 non-admin caller, 404 token not found, 503 audit/Mango-admin outage |
| POST | /api/v1/admin/users/:user_uuid/erase | admin_erase_user | Erase a deleted principal’s Sol data (admin; strict audit). Tombstones the identity, cancels/refuses live tasks and dispatch receipts, purges chat/memory/share/team rows and returns an erasure receipt; audit + billing rows are explicit retained exceptions. DRY-RUN unless the body carries dry_run: false AND confirm equal to the user uuid. Typed answers: 400 invalid_user_uuid/confirmation_required, 403 non-admin caller, 503 audit/tombstone outage (the receipt is returned when the purge ran but its audit did not land) |
| POST | /api/v1/admin/users/:user_uuid/unlock | admin_unlock_account | Clear a Mango account lockout (admin; strict audit). user_uuid must be the 36-char uuid; the Sol service principal performs DELETE /auth/accounts/:uuid/lock at Mango. Typed answers: 400 invalid_user_uuid, 403 non-admin caller, 404 user not found, 503 audit/Mango-admin outage |
| POST | /api/v1/auth/login | auth_login | Login via Mango auth |
| POST | /api/v1/auth/logout | auth_logout | Logout |
| GET | /api/v1/auth/validate | auth_validate | Validate auth token |
| POST | /api/v1/oauth/login | oauth_login | Begin an OAuth PKCE login for a declarative provider (admin). Body {provider}; returns the authorize_url to open, the redirect_uri the browser will hit, and the CSRF state the callback must echo. The PKCE verifier stays server-side |
| POST | /api/v1/oauth/login/complete | oauth_login_complete | Complete an OAuth PKCE login (admin). Body {state, code} from the callback; Sol exchanges the code at the provider token_url (PKCE S256), persists access+refresh tokens 0600, and re-registers the declarative providers so the key is live. Typed answers: 400 unknown_state, 410 login_expired, 502 oauth_exchange_failed |
| GET | /api/v1/oauth/providers | oauth_providers | List providers with a stored OAuth token (admin; names only, never tokens) |
| DELETE | /api/v1/oauth/providers/:provider | oauth_provider_delete | Delete the stored OAuth token for a provider (admin; strict audit). The provider falls back to keyring/env resolution |
Persistence
| Method | Path | Handler action | Description |
|---|---|---|---|
| GET | /api/v1/persistence/audit-stats | persistence_audit_stats | Persistence audit stats |
| POST | /api/v1/persistence/flush | persistence_flush | Flush persistence buffer |
| GET | /api/v1/persistence/status | persistence_status | Persistence status |
Plugins
| Method | Path | Handler action | Description |
|---|---|---|---|
| POST | /api/v1/lua/eval | lua_eval | Evaluate Lua code |
| GET | /api/v1/lua/workers | lua_workers | List Lua workers |
| POST | /api/v1/lua/workers/spawn | lua_worker_spawn | Spawn Lua worker |
Webhooks
| Method | Path | Handler action | Description |
|---|---|---|---|
| POST | /api/v1/webhook/:channel_id | webhook_deliver | Deliver a webhook message |
Chat
| Method | Path | Handler action | Description |
|---|---|---|---|
| GET | /api/v1/chat | chat_list | List chat sessions (caller-scoped) |
| POST | /api/v1/chat | chat_create | Create chat session |
| GET | /api/v1/chat/:id | chat_get | Get chat session |
| DELETE | /api/v1/chat/:id | chat_delete | End chat session |
| POST | /api/v1/chat/:id/branch | branch_checkout | Check out a session branch |
| GET | /api/v1/chat/:id/branches | branches | List the worker’s session branches |
| GET | /api/v1/chat/:id/history | chat_history | Get chat history |
| POST | /api/v1/chat/:id/message | chat_message | Send chat message |
| GET | /api/v1/chat/:id/snapshots | snapshots | List the worker’s git snapshots |
| GET | /api/v1/chat/:id/snapshots/:snapshot_id/diff | snapshot_diff | Bounded snapshot diff summary |
| POST | /api/v1/chat/:id/snapshots/:snapshot_id/restore | snapshot_restore | Restore a git snapshot |
| GET | /api/v1/chat/:id/stream | chat_stream | SSE chat stream |
| POST | /api/v1/chat/:id/ws-ticket | chat_ws_ticket | Mint a one-time WebSocket auth ticket for the session |
| GET | /api/v1/chat/:session_id/ws | chat_ws | WebSocket chat stream |
| GET | /api/v1/permissions | permissions_list | List pending permission asks (self; admin sees all;?session_id= narrows) |
| POST | /api/v1/permissions/:id/reply | permission_reply | Resolve a pending permission ask (allow |
Conversations
| Method | Path | Handler action | Description |
|---|---|---|---|
| GET | /api/v1/conversations | conversations_list | List conversations |
| GET | /api/v1/conversations/:conv_id | conversation_detail | Get conversation |
| POST | /api/v1/conversations/:conv_id/delete | conversation_delete | Delete conversation |
| GET | /api/v1/conversations/:conv_id/stream | conversation_stream | Stream conversation messages |
| GET | /api/v1/conversations/:conv_id/usage | conversation_usage | Get conversation usage |
| GET | /v1/messages/:message_id | message_get | Get message by ID |
Seats
| Method | Path | Handler action | Description |
|---|---|---|---|
| GET | /api/v1/license/status | license_status | License enforcement state |
Telemetry
| Method | Path | Handler action | Description |
|---|---|---|---|
| GET | /api/v1/telemetry | telemetry_list | List telemetry events (limit/offset pagination) |
| GET | /api/v1/telemetry/:agent_id | telemetry_agent | List telemetry events for one agent |
| POST | /api/v1/telemetry/clear | telemetry_clear | Clear all telemetry buffers (audited) |
Providers
| Method | Path | Handler action | Description |
|---|---|---|---|
| POST | /api/v1/providers/reload | providers_reload | Reload declarative providers |
Sessions
| Method | Path | Handler action | Description |
|---|---|---|---|
| POST | /api/v1/sessions | session_share_create | Create a session share link |
| GET | /api/v1/sessions/:share_id | session_share_get | Get shared session data |
| DELETE | /api/v1/sessions/:share_id | session_share_delete | Delete a session share |
| GET | /api/v1/shares/:share_id | share_get | Get shared session by share id |
Audit
| Method | Path | Handler action | Description |
|---|---|---|---|
| GET | /api/v1/audit/events | audit_events | Query audit events - file-only stub: empty page + notice audit_log_file_only (real trail: the JSONL audit log) |
| GET | /api/v1/audit/llm-decisions | audit_llm_decisions | Query LLM decisions - file-only stub: empty page + notice audit_log_file_only (real trail: the JSONL audit log) |
| GET | /api/v1/audit/permission-decisions | audit_permission_decisions | Query permission decisions - file-only stub: empty page + notice audit_log_file_only (real trail: the JSONL audit log) |
| GET | /api/v1/audit/summary | audit_summary | Audit summary - file-only stub: empty counts + notice audit_log_file_only (real trail: the JSONL audit log) |
| GET | /api/v1/audit/tool-executions | audit_tool_executions | Query tool executions - file-only stub: empty page + notice audit_log_file_only (real trail: the JSONL audit log) |
| GET | /api/v1/audit/verify | audit_verify | Anchored audit-chain integrity verdict (live: verified against the on-disk JSONL chain) |
ZMQ
| Method | Path | Handler action | Description |
|---|---|---|---|
| POST | /api/v1/zmq/dispatch | zmq_dispatch | Dispatch ZMQ task |
| GET | /api/v1/zmq/status | zmq_status | ZMQ gateway status |
| GET | /api/v1/zmq/workers | zmq_workers | List ZMQ workers |
ACP Agents
| Method | Path | Handler action | Description |
|---|---|---|---|
| GET | /api/v1/acp/agents | agents_list | List ACP agents |
| GET | /api/v1/acp/agents/:agent_id | agents_detail | Get agent details |
| POST | /api/v1/acp/agents/:agent_id/message | agents_message | Send message to agent |
| GET | /api/v1/acp/agents/capabilities | agents_capabilities | List all capabilities |
| GET | /api/v1/acp/agents/discover | agents_discover | Discover agents by capability |
Supervisor
| Method | Path | Handler action | Description |
|---|---|---|---|
| GET | /api/v1/supervisor/children/:name | supervisor_children | Supervisor children |
| GET | /api/v1/supervisor/tree | supervisor_tree | Supervisor tree |
Infra
| Method | Path | Handler action | Description |
|---|---|---|---|
| GET | /api/v1/infra/cache-affinity | cache_affinity_stats | Prefix-affinity cache stats |
| DELETE | /api/v1/infra/cache-affinity | cache_affinity_clear | Clear the prefix-affinity cache (admin) |
| POST | /api/v1/infra/cache-invalidate | cache_invalidate | Invalidate auth middleware cache |
| GET | /api/v1/infra/maintenance | maintenance_status | Get maintenance mode status |
| POST | /api/v1/infra/maintenance/disable | maintenance_disable | Disable maintenance mode |
| POST | /api/v1/infra/maintenance/enable | maintenance_enable | Enable maintenance mode |
| GET | /api/v1/infra/status | infra_status | Infrastructure status overview |
| GET | /api/v1/managed-settings | managed_settings_get | Get managed settings — returns {ok, data: SettingsMap, schema: SchemaMap} (admin); data._schema_rev is server-injected metadata |
| PUT | /api/v1/managed-settings | managed_settings_put | Update managed settings — body {key, value} merges one key; a bare settings map replaces the whole map. Schema-bound: unknown keys 400 unknown_setting_key (nearest known keys listed), out-of-bounds/type mismatches 400; 503 persist_failed on snapshot write failure |
Goals
| Method | Path | Handler action | Description |
|---|---|---|---|
| GET | /api/v1/goals | goal_list | List all goals |
| POST | /api/v1/goals | goal_create | Create a new goal |
| GET | /api/v1/goals/:id | goal_detail | Get goal details |
| PUT | /api/v1/goals/:id | goal_update | Update a goal (owner or admin) |
| DELETE | /api/v1/goals/:id | goal_delete | Cancel a goal and remove the record (DELETE cancels via the coordinator, then deletes the row) |
| POST | /api/v1/goals/:id/cancel | goal_cancel | Cancel a goal |
Replay
| Method | Path | Handler action | Description |
|---|---|---|---|
| GET | /api/v1/replay/:session_id/events | replay_events | Stream replayable session events from the event store |
Endpoint notes (hand-written — kept OUTSIDE the generated block)
Audit query posture — file-only stubs
GET /api/v1/audit/events, /tool-executions, /permission-decisions,
/llm-decisions and /summary are file-only stubs, not live queries.
They answer the paginated empty-page shape (or {audit_summary: {}}) plus
{"notice": "audit_log_file_only"}
The authoritative trail is the append-only JSONL audit log written by
sol_audit_log (Mango keeps its own audit archive). Consumers must
introspect that log — the endpoints exist for authorization-gated
compatibility, not as an audit index.
GET /api/v1/audit/verify is the live arm: it runs the anchored
verifier against the JSONL chain (sol_audit_log:verify_integrity_anchored/0)
and answers the verdict map (200 for every produced verdict, typed 503 when
the verifier is unavailable).
ci/audit_surface_lint.py pins this three-way truth against the real route
table (sol_http_routes.erl) and the real handler arms
(sol_http_audit.erl): a stub route whose spec/doc row claims a live query
is red, and so is a live route labelled file-only.
GET/HEAD method semantics
Every authorization rule that admits GET also admits HEAD (HEAD is the
bodiless GET; the middleware folds it into the GET membership check —
). Streaming routes are the explicit exception: they are GET-only
and answer HEAD with a typed 405 + Allow: GET before any SSE admission.
Auxiliary routes (hand-maintained — no spec rows)
Implemented in sol_http_routes.erl but deliberately outside the
generated directory (no sol_api_spec.erl rows — machine/tooling
surface or handler-level alias). documents them explicitly:
| Method | Path | Handler action | Description |
|---|---|---|---|
| GET | /api-docs | swagger_ui | Self-contained Swagger UI serving /openapi.json (CDN-loaded, inline spec) |
| GET | /openapi.json | spec | Machine-consumed OpenAPI 3.1 spec generated from the route metadata (sol_openapi) |
| POST | /debug/pprof/profile | pprof_profile | pprof sampling profile (protobuf; ?seconds=10&interval=10) — admin-scoped, also gated by enable_pprof; POST-only |
| POST | /debug/pprof/heap | pprof_heap | pprof heap profile (protobuf) — admin-scoped, also gated by enable_pprof; POST-only |
| POST | /api/v1/debug/flamegraph | eflame_svg | On-demand eflame SVG (?seconds=5) — admin-scoped; not enable_pprof-gated; POST-only |
| GET | /api/v1/workers/bg/:bg_id/status | bg_status | Compat alias of GET /api/v1/workers/bg/:bg_id (same bg_status dispatch; route order resolves it before the :bg_id catch-all) |
Memory write ownership (store / clear / delete)
Identity is resolved at the HTTP boundary; the memory store authorizes server-side. The rules as-implemented:
| Operation | Non-admin caller | Admin |
|---|---|---|
store (new key) | row owned by the caller’s user_uuid | row owned by the caller |
store (existing key) | overwrite allowed only on own rows | overwrite allowed on any row |
clear | wipes only the caller’s OWN rows inside the agent namespace | wipes the whole agent namespace |
delete (:key) | allowed only on own rows | allowed on any row |
Memory read consistency
list/search/retrieve read through the store’s single seam
(sol_memory_pg), which consults PostgreSQL on an ETS miss. The enumeration
reads GET /api/v1/memory/:agent_id/stats and
GET /api/v1/memory/:agent_id/reflections are served by
sol_memory_read, the single authority for those two cache reads. They read
the NODE-LOCAL sol_memory ETS read model hydrated from PG; a write made on
another cluster node is visible only after that node’s hydration/re-read.
The durable authority remains PostgreSQL (memory_pg_enabled=true); with
memory disabled every route answers the documented 503.
A foreign overwrite or delete answers 404 (never 403 — no existence
oracle for foreign keys). The same gates hold on the durable PG leg: the
WAL upsert’s DO UPDATE is owner-gated, and scoped wipe/delete ops carry
the owning user_uuid, so a replay can never rewrite or drop a foreign
row. The legacy POST /:agent_id/:key/delete action row shares the
ownership semantics of the REST delete.
Natural-language schedule values
schedule_create accepts a human-readable schedule string and resolves
it to at/every/cron. The decided parse semantics:
| Input form | Resolution |
|---|---|
every 30m, every 2h, every 1d, every 90s | recurring interval (every) |
in 2h, bare 30m | one-shot at = now + duration |
HH:MM (24h), bare | next occurrence; rolls to tomorrow if already past today |
9am / 9pm (single digit) | 09:00 / 21:00 |
HHam / HHpm (two digits) | 12am = 00:00 (midnight), 12pm = 12:00; hours 1–11 map to their clock value (pm +12) |
13pm, 13am, any hour > 12 with an am/pm suffix | rejected — invalid schedule (the request answers 400); no silent +12h roll |
today HH:MM / today <ampm> | today at the time; a time already past rolls forward to tomorrow |
tomorrow <time> | tomorrow at the time |
| 5-field cron expression | passed through as cron |
YYYY-MM-DDTHH:MM[:SS] | one-shot at at the ISO timestamp |
A rejected parse leaves the body without at/every/cron, so schedule
create answers 400 “must specify at, every, or cron” — a loud rejection,
never a silently shifted fire time.
POST /api/v1/chat/:id/ws-ticket
Mints a one-time WebSocket authentication ticket for the chat session
a POST-only, admin-or-owner-gated route answering
{ticket, expires_in_ms} — the ticket is single-use, short-TTL, and is
presented on the /ws upgrade via the zerg_ticket, <ticket>
Sec-WebSocket-Protocol subprotocol form so the long-lived bearer never
rides the WS handshake. Limon mints a fresh ticket per reconnect.
Chat WebSocket frames. Besides token/done/error/
history/ack/pong, the chat socket carries the operator permission
round-trip:
| Frame | Direction | Fields | Meaning |
|---|---|---|---|
permission_request | server → client | request_id, task_id, tool_name, input_summary, analysis, expires_in_ms | A worker is blocked on a tool decision. input_summary is a bounded command/path summary — never the raw input |
permission_reply | client → server | request_id, decision, reason? | decision ∈ allow | deny | always; only the ask owner or an admin may answer (others get error: permission_forbidden; stale ids get permission_request_not_found) |
permission_resolved | server → client | request_id, decision | The registry resolved (or auto-denied) the ask — clears the prompt (also the acknowledgement of a successful permission_reply) |
Every decision is audited (permission_decided, strict) with the tool,
decision, reason, sha256 input hash, session, worker, owner, and source.
Session tree & snapshot control
The ops console can read and (admin-only) mutate the chat worker’s headless session tree and git snapshot plane. Sol relays each call to the chat session’s stdio worker over a correlated JSONL control line:
{"type":"session_control","request_id":"<uuid>","action":"branches|snapshots|snapshot_diff|branch_checkout|snapshot_restore","session_id":"...","user_uuid":"...","branch?":"...","snapshot_id?":"...","files?":["..."],"count?":20}
{"type":"session_control_reply","request_id":"<uuid>","ok":true,"data":{}}
{"type":"session_control_reply","request_id":"<uuid>","ok":false,"error":"branch_not_found"}
The request id is minted server-side and correlated by sol_worker
(pending map + bounded timeout); a late/unknown reply can never resolve a
different request, and the worker reply payload is size-bounded. Reads are
safe mid-turn; branch_checkout and snapshot_restore are refused 409
with session_busy while a turn runs (they mutate the session view /
workspace). Worker death answers the documented 503 worker_unavailable
class; a worker whose workspace is not a git repository answers the typed
snapshot_unavailable state.
| Method | Response |
|---|---|
GET /branches | 200 {available, active, branches:[{name, root, message_count, active, leaf, title}]}; available:false + reason when no task session exists yet |
GET /snapshots | 200 {available, snapshots:[{id, timestamp, tool, description, files}]}; timestamp is null when the snapshot backend keys by tree id; available:false + reason:"snapshot_unavailable" when the workspace is not a git repo |
GET /snapshots/:id/diff | 200 {snapshot_id, files:[{path,insertions,deletions}], insertions, deletions, diff, truncated} — diff is bounded to 8 KiB; 404 snapshot_not_found |
POST /branch | Body {"branch":"name"}. 200 {branch, active, leaf}; 404 branch_not_found; 409 session_busy |
POST /snapshots/:id/restore | Optional body {"files":["path"]} (omitted = whole snapshot). 200 {snapshot_id, restored}; 409 snapshot_unavailable; 400 invalid_files for absolute/traversal/empty entries |
Mutations require is_admin (the parameterized route cannot carry an
exact {admin, require} scope; the RBAC floor is chat:create). Each
writes a strict audit row before touching the worker — strict_log
failure answers 503 audit_unavailable and the mutation never runs:
session_branch_checkout chat_session:<id> {branch, worker_id}
session_snapshot_restore chat_session:<id> {snapshot_id, worker_id, files_count?}
Audit rows carry the branch/snapshot id and a file COUNT only — never file bodies or paths from the restore payload.
semantics
Member list. GET /api/v1/teams/:id/members lists a team’s members
(membership-gated: the caller must belong to the team or be an admin). The
same path answers POST for the add-member form below.
Member identifiers. DELETE /api/v1/teams/:id/members/:worker_id
accepts EITHER identifier form in the path segment: the canonical member
id (tm_*, the registry key) or the member’s worker_id. The path
segment is resolved to the canonical member row server-side (worker-id
scans are bounded by the team’s max_members); unknown ids return
404 with code not_found, cross-team ids return code wrong_team.
Join-time identity. POST /api/v1/teams/:id (the no-suffix add-member
form added in ) and POST /api/v1/teams/:id/members dispatch the
same action and require a non-empty worker_id; an empty or missing value
returns
400 error code invalid_worker_id`` (no placeholder rows are
created). A body-supplied user_uuid is always stripped — the member row’s
user_uuid is stamped from the authenticated caller only.
RBAC matrix (handler-enforced; the middleware’s teams:manage still
applies to mutating routes on the wire):
| Operation | Allowed for |
|---|---|
| Team create | admin (teams:create at the middleware) |
Team detail / members / mail READ (incl. ?mine=1) | admin OR creator OR a member whose user_uuid matches the caller |
| Team destroy / member add / member remove / mail send | admin OR creator (teams:manage at the middleware) |
Outsiders receive the standard Zerg envelope: 403 {"ok":false,"error":{"code":"forbidden","message":"not a team member"}} (read)
/ 403 {"ok":false,"error":{"code":"forbidden","message":"forbidden"}} (mutate).
Mail delivery model (decision recorded). Delivery is push best-effort:
mail addressed to a specific worker_id is pushed when that worker is
currently registered via ZMQ; broadcast (to: "all") mail is never pushed.
Polling is the recovery path: GET /api/v1/teams/:id/mail returns the
team’s non-expired mail (non-destructive). This default read is TEAM-WIDE
and member-authorized: any caller who passes the membership gate
(check_team_member/2 — a member row, the creator, or an admin) may read
mail addressed to another member; the row’s to field is the addressee,
not an access boundary. GET /api/v1/teams/:id/mail?mine=1 returns only
mail addressed to the caller’s membership (user_uuid or one of their member worker_ids), still
non-destructive. Mail rows transition pending → delivered → acknowledged
(POST /api/v1/teams/:id/mail/:message_id/ack is the explicit transition
added in ); the read API marks delivery preserving every field, and expiry (TTL, default
300s) deletes the row and emits a team.mail_expired sync event per row.
Errors: unknown team/mail → 404; mailbox unavailable → 503 service_unavailable (the mailbox store is temporarily down — a retryable
outage class, not a handler bug; the body is the Zerg envelope with code
read_failed and message team mailbox temporarily unavailable).
Scheduler create request contract (POST /api/v1/schedule/spawn)
| Field | Type | Required | Notes |
|---|---|---|---|
prompt | string | Yes | Missing/empty → 400 missing prompt. |
at | integer | one of at/every/cron | Epoch milliseconds. A past timestamp is accepted but logged. |
every | integer | one of at/every/cron | Positive interval in milliseconds (> 0 required). |
cron | string | one of at/every/cron | Parsable 5-field cron expression. |
name | string | No | Job label. |
model | string | No | Model override for the dispatched task. |
opts | object | No | Arbitrary job opts; identity-bearing keys (user_uuid, permissions, listener, owner, task_id, container_id, plugin) are stripped. |
delete_after_run | boolean | No | Only valid for at jobs — true with every/cron answers 400 delete_after_run only supported for 'at' jobs. |
Neither at/every/cron present → 400 must specify at, every, or cron (a natural-language schedule string is resolved server-side
first — see the NL table above). Response (200):
{"status": "ok", "id": <job_id>, "next_run": <epoch-ms>}.
DELETE /api/v1/schedule/:id
Delete a scheduled job. DELETE only (admin-only; the same route row
serves GET /api/v1/schedule/:id for the detail read). Used by
zerg schedule delete.
Responses:
200 {"status": "deleted"} — the job is removed
403 forbidden — non-admin caller
404 job not found — unknown (or already fired delete_after_run) job
409 job currently running — a running job refuses deletion
Memory store request body (POST /api/v1/memory/store)
| Field | Type | Required | Notes |
|---|---|---|---|
key | string | Yes | Binary, 1..512 bytes. Empty/too-long/non-binary → 400. |
value | string | Yes | Binary content. Non-binary key/value → 400 invalid body. |
agent_id | string | No | 1..128 bytes; falls back to the route binding (default "default"). |
ttl | integer | No | Seconds, ≥ 0 — a negative or non-integer value answers 400 invalid ttl; larger values are clamped to 31536000 (365 days). |
embedding | array | No | Optional numeric vector; a non-numeric element answers 400 instead of a 500. |
Durability of the ack: the default
200 {"status":"ok"} is cache-durable — the entry is in the ETS cache
and the write is accepted into the sol_memory_wal queue (RAM-crash-safe;
power-loss-durable only to the last WAL flush, bounded by
memory_wal_flush_ms, default 100ms). With
memory_http_durable_writes=true the write uses the durable ack
contract: ok additionally means the WAL drained (the PG upsert
committed) before the reply, and an unconfirmed flush answers
503 service_unavailable — never a durability lie.
Goals — create gate, update & delete verbs
GET /api/v1/goals (list) requires the goals:read scope; the bare route is
in ?ENDPOINT_PERMISSIONS since then, so a caller with no granted
permissions receives 403 insufficient_permissions (admin * passes; assign
a role carrying goals:read to grant it). Goal create is admin-only
(403 forbidden for other callers); reads and the mutation verbs below are
owner-or-admin. The handler serves an
additional mutation verb (now also a first-class spec row,
goal_update):
Cancel — POST /api/v1/goals/:id/cancel is admin-only
(403 insufficient_permissions otherwise; aligned the RBAC
scope, handler and this doc on the same authority).
Update — the PUT verb on /api/v1/goals/:id: update goal
metadata. Admin, or the goal owner for their own goals (403 forbidden on a foreign goal, 404 unknown id).
Delete — the DELETE verb on /api/v1/goals/:id: cancels the
goal with the same ownership rule, then removes the
record. Cancellation stops the associated workflows and
in-progress sub-agents; the row and its workflow index entries are
deleted through the goal projector (the single ETS writer) and the
response is {"cancelled": "<id>", "deleted": "<id>"} ("deleted": false if the projector was unreachable — the cancel still happened and
the retention sweep owns the row). A missing goal
is 404 goal not found. Terminal goals are additionally swept by a
retention GC (goal_retention_ms, default 30 days, same clock as the
workflow-state GC) — a goal referenced by a live workflow binding is
never removed by the sweep. GET /api/v1/goals is paginated
(limit/offset, default 50); the goals key is preserved and
pagination metadata (total, limit, offset, has_more,
total_pages) rides beside it.
Infra cache-affinity
The GET verb on /api/v1/infra/cache-affinity — returns
prefix-affinity stats: {"entries": {...}} (an empty entries map
when the collector is unavailable).
The DELETE verb on /api/v1/infra/cache-affinity — clears all
affinity entries, answering {"ok": true}. Admin-only (403 insufficient_permissions otherwise). Both verbs are first-class spec
rows (cache_affinity_stats / cache_affinity_clear) since then.
OpenAI-Compatible Endpoints
These endpoints are compatible with the OpenAI Chat Completions API.
/v1/completions (legacy FIM text completions) speaks the same OpenAI
auth-error dialect as /v1/chat/completions.
POST /v1/chat/completions
OpenAI-compatible chat completions proxy. Resolves model name, starts inference if needed, and streams tokens.
Request body:
{
"model": "glm-4.7-flash",
"messages": [
{"role": "user", "content": "Explain quicksort"}
],
"stream": true,
"temperature": 0.7,
"max_tokens": 4096,
"top_p": 0.95,
"timeout": 300000
}
| Field | Type | Required | Default | Description |
|---|---|---|---|---|
model | string | Yes | — | Model slug name (prefix matching supported) |
messages | array | Yes | — | Chat messages (role + content) |
stream | boolean | No | true | Stream SSE tokens |
temperature | float | No | template default | Sampling temperature |
max_tokens | integer | No | model default | Maximum tokens to generate |
top_p | float | No | template default | Top-p sampling |
timeout | integer | No | 300000 | Request timeout in ms (provider_request_timeout_ms default 300 s, clamped to client_timeout_max_ms, default 600 s) |
Response (streaming): SSE events with data: {"choices": [...]} lines.
Response (non-streaming): every field the OpenAI SDK’s typed deserializers expect:
{
"id": "chatcmpl-<node>-<n>",
"object": "chat.completion",
"created": 1786796808,
"model": "glm-4.7-flash",
"choices": [{"message": {"role": "assistant", "content": "..."}, "finish_reason": "stop"}],
"usage": {"prompt_tokens": 10, "completion_tokens": 50, "total_tokens": 60}
}
curl -X POST http://127.0.0.1:21434/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{"model":"glm-4.7-flash","messages":[{"role":"user","content":"hello"}]}'
POST /v1/completions
OpenAI legacy text-completion shape for fill-in-the-middle code
completion. Non-streaming only; authenticated with inference:use; the
request body is capped at 1 MiB. Sol resolves a lane that declares the
fim capability and calls that lane’s internal POST /infill — the lane
endpoint is never a client contract.
Request body:
{
"model": "glm47_fim",
"prompt": "def add(a, b):",
"suffix": "\n return a + b\n",
"max_tokens": 96,
"temperature": 0.2,
"stop": ["\n\n"]
}
| Field | Type | Required | Default | Description |
|---|---|---|---|---|
model | string | No | auto | Lane id pin (gated); omitted = auto-route to a fim lane |
prompt | string | Yes | — | Prefix text sent to the lane as input_prefix |
suffix | string | Yes | — | Suffix text sent as input_suffix |
max_tokens | integer | No | 96 | Completion budget (1–1024) |
temperature | number | No | lane default | Sampling temperature (0–2) |
stop | string | string[] | No | — | Up to 4 stop strings |
stream | boolean | No | false | Streaming is not supported (true answers 400 stream_unsupported) |
Response (text_completion):
{
"id": "cmpl-<uuid>",
"object": "text_completion",
"created": 1786796808,
"model": "glm47_fim",
"choices": [{"text": " return a + b\n", "index": 0, "finish_reason": "stop"}],
"usage": {"prompt_tokens": 6, "completion_tokens": 5, "total_tokens": 11}
}
finish_reason is length when the lane reports a truncated/limit stop,
otherwise stop. Usage is settled through the standard inference
counters/ledger (inference_complete, token counters, spend settlement).
Typed refusals (never a 500):
| Status | error.code | Class |
|---|---|---|
| 400 | invalid_request / stream_unsupported | Malformed body, missing prompt/suffix, unsupported streaming |
| 400 | fim_unsupported | The pinned lane (or the fleet) declares no fim capability |
| 400 | not_allowed_on_host / mode_not_allowed | Lane cannot serve this request on this host |
| 404 | unknown_lane | Pinned model is not a lane |
| 409 | lane_not_grantable | Pinned lane is staged |
| 429 | lane_busy / cpu_busy / queue_full | Admission capacity (Retry-After) |
| 503 | lane_warming | Cold lane; the async start is in flight (Retry-After) |
| 503 | lane_unvalidated / lane_unavailable / model_unavailable | Lane cannot serve now |
| 502 | lane_rejected | The lane’s /infill answered an error |
A cold lane answers immediately with lane_warming; the next request after
the Retry-After consumes the warm lane. The endpoint leases attended with a
fixed TTL (completion_lease_ttl_ms, default 300 s; values above
lane_duration_max_ms are refused, never clamped) so a single ghost-text
request never pins the big lane for the 15-minute on_demand idle class.
Spend admission runs before lane resolution/cold start, so an over-budget
request never starts or holds a lane.
At HEAD there is no per-session coalescing queue: each request is one
independent non-streaming call, serialized only by lane admission (429 lane_busy/queue_full) and the standard per-principal HTTP rate limiter. The FIM lane’s launch recipe
(-b >= 12288) and the measured quality/latency rows are recorded in
local-inference-lanes.md and
benchmarks/fim-round-2026-10-18.md. glm47_fim is the declared primary
(production => false until a zerg validation record exists) and
qwen38_atx is the fallback and is a production lane, so the fallback is
selected only when its own validation verdict permits serving; a fleet with
no grantable, validation-eligible fim lane returns the typed
fim_unsupported (or lane_unvalidated on the pinned path).
POST /v1/messages
Anthropic Messages API endpoint. Translates to/from OpenAI format internally.
Request body:
{
"model": "glm-4.7-flash",
"messages": [
{"role": "user", "content": "Explain quicksort"}
],
"max_tokens": 4096,
"stream": true,
"system": "You are a helpful assistant.",
"temperature": 0.7,
"top_p": 0.95,
"stop_sequences": ["\n\n"],
"tool_choice": "auto"
}
| Field | Type | Required | Default | Description |
|---|---|---|---|---|
model | string | Yes | — | Model slug name |
messages | array | Yes | — | Chat messages |
max_tokens | integer | Yes | — | Maximum tokens |
stream | boolean | No | false | Stream SSE events (the OpenAI leg defaults to true; this endpoint defaults to false) |
system | string | No | — | System prompt |
temperature | float | No | — | Sampling temperature |
top_p | float | No | — | Top-p sampling |
top_k | integer | No | — | Top-k sampling (carried to the Messages/OpenAI body after translation) |
stop_sequences | array | No | — | Custom stop sequences |
tool_choice | string | No | — | Tool selection: auto, any, none |
tools | array | No | — | Tool definitions |
thinking | object | No | — | Extended thinking: {"type": "enabled", "budget_tokens": N} (translated to the provider wire; the Anthropic wire receives the thinking block, OpenAI-compatible wires receive reasoning_effort) |
response_format | object | No | — | Structured output request; forwarded as the wire response_format parameter (plus a structured-output tool for providers that cannot take the parameter — the synthetic tool is stripped from the OpenAI wire when the native parameter is sent) |
stream_options | object | No | {"include_usage": true} | Stream options forwarded on the OpenAI wire (usage defaults to included when streaming) |
metadata | object | No | — | Metadata with user_id (carried to the provider request) |
Response (streaming): Anthropic-format SSE events (message_start, content_block_start, content_block_delta, content_block_stop, message_delta, message_stop).
Response (non-streaming):
{
"id": "msg-...",
"type": "message",
"role": "assistant",
"content": [{"type": "text", "text": "..."}],
"model": "glm-4.7-flash",
"stop_reason": "end_turn",
"usage": {"input_tokens": 10, "output_tokens": 50}
}
stop_reason values: the full mapping is pinned by the
shared fixture docs/fixtures/stop_reason_matrix.json (consumed by both the
Luna client translators and sol_anthropic_api:translate_stop_reason/1):
| Value | Meaning | Origin |
|---|---|---|
end_turn | Natural completion (openai stop / absent reason also map here) | mapped |
max_tokens | Output truncated by the token budget (openai length) | mapped |
stop_sequence | A custom stop sequence fired | native passthrough |
tool_use | The model invoked a tool (openai tool_calls) | mapped |
content_filter | Provider content filter (legacy openai value) | passthrough |
function_call | Legacy openai tools API value | passthrough |
Unknown values are passed through unchanged (Anthropic may add values) and a server warning is logged — never silently rewritten, never dropped.
OpenAI egress usage: the OpenAI usage object is
emitted with all three counters — prompt_tokens, completion_tokens,
total_tokens. The shared interpreter marks an unreported side null; a
null side cannot produce a total, so the whole object is omitted rather
than emitting an incomplete/fabricated row. Buffered
message.tool_calls[] entries carry type: "function" and never the
delta-only index; streaming delta chunks keep index and also carry
type.
Usage-absence semantics: usage is reported only when
the provider actually emitted it. When the upstream stream carries no usage
chunk, the field is omitted (streaming: no usage object on
message_delta; non-streaming: no output_tokens key) and the conversation
store records null — output tokens are never fabricated (the pre-fix
byte_size div 4 estimate and per-chunk token counting are gone).
Non-streaming error statuses: a task that
ends in a terminal error status is answered with an Anthropic-format error
body and a status code that reflects the failure class. Pre-, the
error text was returned as a 200 end_turn message; answered every
terminal status with a flat 500; distinguishes the classes:
| Task status | HTTP status | Anthropic error type |
|---|---|---|
timeout (did not finish within the waiter window) | 504 Gateway Timeout | overloaded_error |
cancelled (user/owner cancelled the task) | 409 Conflict | invalid_request_error |
error, crashed (the task itself failed) | 500 Internal Server Error | api_error |
| task row missing | 404 Not Found | not_found_error |
A pending row is never answered — the waiter re-arms until the task
reaches a terminal status or the waiter budget is exhausted.
curl -X POST http://127.0.0.1:21434/v1/messages \
-H "Content-Type: application/json" \
-d '{"model":"glm-4.7-flash","messages":[{"role":"user","content":"hello"}],"max_tokens":4096}'
Health & Metrics
GET /api/v1/health
Health check.
Response:
{"status": "ok", "models_running": 3}
GET /api/v1/metrics
ETS-backed metrics counters. Requires the metrics:read permission
(: the same metrics loopback gate as /metrics applies to
tokenless requests — loopback scrape ok, external tokenless → typed 403).
Response:
{"requests": 142, "tokens": 42800, "errors": 2}
Model Management
POST /api/v1/discover
Trigger model discovery scan. POST only (405 for other methods).
Response:
{"discovered": 12}
curl -X POST http://127.0.0.1:21434/api/v1/discover
GET /api/v1/models
List all registered models (paginated). Two row shapes share the list:
Local rows — {slug, family, quant, size, status, source: "local", model_slug, lane, engine}; lane-qualified instance rows carry
model_slug/lane/engine.
Provider rows — {id, source: "provider", canonical_model, provider_model, dispatchable, alias?, provider, context_window, capabilities, pricing, modalities?}. An alias row keeps alias; the
canonical id is id, and dispatchable=false means the registered row
lacks an endpoint/credential (visible instead of a post-fallback 503).
Response:
[
{"slug": "glm-4.7-flash-q4", "family": "glm", "quant": "Q4_K_M", "size": 4200000000, "status": "available", "source": "local", "model_slug": null, "lane": null, "engine": null},
{"id": "claude-sonnet-4-20250514", "source": "provider", "canonical_model": "claude-sonnet-4-20250514", "provider_model": "claude-sonnet-4-20250514", "dispatchable": true, "provider": "anthropic", "context_window": 200000, "capabilities": {"vision": true, "tools": true}, "modalities": ["text", "image"]}
]
GET /api/v1/models/metadata
Registry metadata for every known model: {models: [{name, family, quant, size, status, …}]} — the discovery view (not the inference-critical
projection). Admin/read-gated like the models list; current_task-style
prompt fields are never included.
GET /api/v1/providers/health
Probe every provider transport identity (provider/key/endpoint). Rows are
grouped: every registered model or alias sharing the same provider, key and
endpoint collapses into one probe, and its models list names them. A row
with no endpoint is unconfigured and is never probed. The response is
paginated (items plus the backward-compatible providers mirror).
[
{"name": "anthropic", "models": ["claude-sonnet-4-20250514"], "endpoint": "https://api.anthropic.com", "path": "/v1/messages", "key_id": "anthropic", "wire": "anthropic", "status": "available", "checked_at_ms": 1760000000000}
]
Status values: available (2xx/3xx/404/405/429 — reachable),
available_unauthorized (401/403 — reachable, credential problem),
degraded (5xx), unavailable (transport/timeout), ssrf_rejected
(private/loopback/link-local target refused), unconfigured (no endpoint).
GET /api/v1/providers/health/:name returns the single group for that
provider name (404 when unknown).
Model catalog and rate truth
GET /api/v1/models and GET /v1/models enumerate the registered
serving surface (provider rows + lane/discovered models); they are not a
dump of the declarative metadata catalog. The declarative catalog lives in
contract/model_catalog.yaml and is rendered into
server/priv/model_catalog.json (Sol), client/data/models.json and
client/core/_models_data.lua (Luna) by ci/catalog_gen.py — see
catalog.md.
Server-side fallback chains are validated against the registered
model set at boot. The documented example (also shipped as
docs/fixtures/provider_fallback_chains_example.json) is:
{"fallback_chains": {"claude-3-*": ["claude-sonnet-4-20250514"],
"*": ["gpt-4o-mini"]}}
Keys/targets must match a registered id or alias; an unknown glob (for
example the retired claude-opus-* example) refuses the whole config
loudly at boot.
Rate truth:
Billing reads the catalog pricing block (sol_cost:price/1; per-Mtok
input_per_mtok / output_per_mtok rates), alias/lane-resolved. Unknown
models are {error, unknown_price} and counted — never silently zero.
sol_model_metadata is the fallback for operator-only/test rows.
The /v1/models list merges the cluster catalog entries (canonical ids,
one row per model) and /api/v1/models renders real catalog metadata
(provider, context window, capabilities, pricing, modalities).
A descriptor that deliberately diverges from the legacy view carries a typed
pricing.metadata_override with the exact metadata values and a reason;
ci/model_catalog_lint.py fails a bare mismatch or a stale override.
A descriptor with no bundled rate is explicitly pricing: {unpriced: true, reason: …} (or free: true for a zero-rate local lane) — unpriced rows
cannot masquerade as zero-cost ones.
A request naming a model that is neither registered nor a local lane model
is refused with {error, {unknown_model, Model}} by the request builder and
answers 404 at the HTTP boundary (’s unknown-wire refusal remains a
separate typed parse-time error).
GET /api/v1/usage
Per-principal inference usage and spend totals from the enforced daily
ledger (sol_spend_guard). Scope: inference:use. A caller reads itself;
an admin may pass ?user_uuid=<uuid>. Optional UTC range
?from=YYYY-MM-DD&to=YYYY-MM-DD (inclusive; to defaults to today,
from defaults to unbounded). Only GET is served (405 otherwise).
{
"user_uuid": "…",
"days": [
{"day": "2026-10-17", "input_tokens": 1200, "output_tokens": 800,
"total_tokens": 2000, "cost_usd": 0.0123,
"models": [{"model": "gpt-4o", "input_tokens": 1200,
"output_tokens": 800, "cost_usd": 0.0123}]}
],
"totals": {"input_tokens": 1200, "output_tokens": 800,
"total_tokens": 2000, "cost_usd": 0.0123},
"budget": {"daily_budget_usd": 0, "daily_token_budget": 0,
"unknown_price_policy": "deny"}
}
The ledger is in-memory and resets on a full restart; durable billing
truth remains the inference.complete / task.completed event stream.
Admission caps, unpriced-model policy and overshoot semantics are in
cost.md.
GET /api/v1/models/:name
Show model details ( explicit projection; the pre-fix
verbatim registry record leaked paths/config/port to every models:read
holder).
Response (non-admin):
{"id": "glm-4.7-flash", "family": "glm", "quant": "Q4_K_M", "size": 4700000000,
"status": "ready", "context_window": 200000}
id is the registry slug (model_slug fallback); family, quant, size,
status and context_window are present only when known. Paths, config,
port and the runtime inference_ref are never returned.
Response (admin): the operator record (sol_registry:show/1 projection
with atom values rendered) including slug/model_slug, paths, config,
port and inference_ref.
Errors: 404 not found; store-down 503 / remote 502 through
classify_error — never a blanket 500.
GET /api/v1/ps
List running inference processes.
Response: paginated envelope (/ — the bare-array example
predated the pagination contract; sol_http_inference:ps_body/1 paginates):
{"items": [{"slug": "glm-4.7-flash", "family": "glm", "port": 8001, "ref": "#Ref<0.123>"}], "total": 1, "limit": 50, "offset": 0, "page": 1, "total_pages": 1, "has_more": false}
POST /api/v1/start
Start an inference model. POST only. Status values: "ok" on a
fresh start (200), "already_running" when the model is already serving
(409), "not_found" for an unknown model.
Request body:
{
"model": "glm-4.7-flash",
"template": "coding",
"overrides": {"temp": 0.3, "batch_size": 4096},
"lane": "qwen38_atx",
"engine": "cuda_sm86_main",
"mode": "on_demand",
"duration_ms": 3600000
}
| Field | Type | Required | Description |
|---|---|---|---|
model | string | Yes | Model slug name |
template | string | No | Parameter template name |
overrides | object | No | Parameter overrides |
lane | string | No | Inference lane id. An unknown lane is a typed 400, never silently ignored. Lane-bound starts also come from Luna’s lane_control plane |
engine | string | No | Engine id override (must be registered; typed 400 otherwise) |
mode | string | No | Lifecycle mode: on_demand (default; 15 min idle release), duration (with duration_ms), attended, cron |
duration_ms | integer | No | Bound for duration mode (max lane_duration_max_ms, default 24 h) |
A production lane whose validation is missing/stale/breached refuses with
{engine_unvalidated, Lane, Reason} (see
local-inference-runbook.md §3).
GET /api/v1/inference/lanes
Read-only, sanitized fleet lane inventory. Filters:
?lane=<id> and ?node=<label> (an unknown value degrades to no filter,
never a 500); pagination follows the shared query contract. Each lane row
projects lane, state, engine, engine_build, model_slug, ctx,
caps, slots, port, mode, lease_held, expires_at, weights,
validation and stale. : the row also carries use_case —
one registry use-case facet string (fim, agentic, fast_bulk,
docs_long, vision, strict_json, story, cpu_cron, escalate).
The engine interface is one atom per lane. The facet is joined from the
lane registry at the read boundary; a lane whose row has no facet (an older
peer config) is returned unchanged, so consumers must tolerate absence.
The facet is a selection hint — capability truth stays in caps.
Response: a paginated array of the rows above (binary-keyed JSON; no pids, env, model paths or lease ids).
POST /api/v1/inference/lanes/:lane/validate
Admin-only probe/commit for lane certification (; evidence rules
). mode=probe writes nothing and returns the needle row plus
its canonical row_ref; mode=commit re-verifies the fingerprint and
stores the record. The commit requires origin=zerg on the row,
membership of the claimed row_ref in the configured artifact CSV
(lane_benchmark_csv; configured-but-unreadable answers 503
artifact_csv_unreadable), an engine install receipt with a real
manifest hash, and a parity verdict — pass, or single_host only with
allow_single_host: true. Typed refusals: 409 origin_not_zerg,
409 evidence_mismatch (hash mismatch), 409 row_not_in_artifact,
409 no_receipt, 409 parity_required, 409 single_host_unacked,
409 engine_unvalidated (fingerprint moved), 503
artifact_csv_unreadable. See
engine-provenance.md.
Response:
{"status": "ok", "port": 8001, "ref": "#Ref<0.123>"}
curl -X POST http://127.0.0.1:21434/api/v1/start \
-H "Content-Type: application/json" \
-d '{"model":"glm-4.7-flash","template":"coding"}'
POST /api/v1/stop
Stop a running model. POST only.
Request body: {"model": "glm-4.7-flash"}
curl -X POST http://127.0.0.1:21434/api/v1/stop \
-d '{"model":"glm-4.7-flash"}'
POST /api/v1/stop-all
Stop all running models. POST only.
Response: {"stopped": 3}
POST /api/v1/prepare/:name
Prepare a model for serving. POST only — the handler answers 405
for every other method (the CLI POSTs). If the model’s file must be
synced from its source (e.g. NFS) to local disk, the rsync runs
Asynchronously: the endpoint answers 202 Accepted immediately, the
model’s status becomes
preparing, and completion is observable via the model.prepared /
model.prepare_failed events (the row reverts to discovered on failure).
A prepare that is already in flight is idempotent — it returns the same
202 response without spawning a second rsync. While preparing, a start
request is rejected with 409.
Responses:
200 — the model is already prepared:
{"status": "ok", "local_path": "/tmp/sol/models/glm-4.7-flash-q4.gguf"}
202 — prepare accepted, rsync running in the background:
{"status": "preparing"}
404 — model not found
Agent Workers
GET /api/v1/agents
List all spawned agent workers. Paginated.
Response (paginated envelope):
{"items": [{"worker_id": "agent-abc123", "status": "idle", "ospid": 12345,
"current_task": "task-xyz789", "pending_count": 2}],
"total": 1, "limit": 50, "offset": 0, "page": 1, "total_pages": 1, "has_more": false}
There is no task_count field. current_task is the id of the
in-flight task (not its prompt); non-admin callers receive
"current_task": null — the field is redacted so one user cannot read
another user’s in-flight work. ospid is the worker
process id and pending_count the length of its queued-task queue.
POST /api/v1/agents/spawn
Spawn new agent workers. POST only. Admin-only — other callers
receive 403 forbidden.
Request body:
{"count": 2, "worker_path": "/opt/sol/etc/luna"}
| Field | Type | Required | Description |
|---|---|---|---|
count | integer | No | Number of agents (1-64). An out-of-range or non-integer value silently becomes 1. |
worker_path | string | No | Path to worker binary (validated prefix) |
Response:
[{"worker_id": "agent-abc123"}]
Each result item carries worker_id only (plus error on per-slot
spawn failures).
Cap response (429): when the worker cap is reached mid-spawn the
endpoint answers 429 with this legacy flat body:
{"error": "cap_reached", "retry_after": "30", "results": [{"worker_id": "agent-abc123"}]}
Note this one cap body predates the envelope doctrine — it is a bare
top-level {"error":...} (string "retry_after", not a header), kept
as-is for compatibility.
GET /api/v1/agents/:id
Show agent status.
POST /api/v1/agents/:id/task
Dispatch a task to an agent.
Request body:
{
"prompt": "Fix the bug in main.rs",
"stream": true
}
| Field | Type | Required | Description |
|---|---|---|---|
prompt | string | Yes | Task prompt |
stream | boolean | No | Stream SSE tokens (default: true) |
Response (streaming): SSE token stream.
Response (non-streaming):
{"status": "queued", "task_id": "task-xyz789"}
POST /api/v1/agents/:id/kill
Kill an agent worker. POST only.
Background Workers
All background-worker routes are admin-only — non-admin callers
receive 403 forbidden.
POST /api/v1/workers/bg/start
Start a background (detached) worker session. Returns a bg_id for tracking.
Request body:
{"prompt": "analyze the logs and summarize errors", "model": "glm-4.7-flash", "timeout": 300000}
| Field | Type | Required | Description |
|---|---|---|---|
prompt | string | Yes | Task prompt. Missing/empty → 400 prompt required. |
model | string | No | Model override. |
timeout | integer | No | Request timeout in ms. |
The caller’s user_uuid/permissions are captured server-side — do not
send them in the body.
Response (200):
{"bg_id": "bg-abc123"}
Errors: 400 prompt required · 503 when the backing store fails to
record the worker (classify_error).
GET /api/v1/workers/bg
List all background worker sessions with status: {"tasks": [...]}.
GET /api/v1/workers/bg/:bg_id
Get background worker status and metadata (404 unknown id).
GET /api/v1/workers/bg/:bg_id/logs?n=100
Fetch output logs from a background worker. Returns circular buffer (up to 10K lines).
The query parameter is ?n=<lines> — a positive integer, default
100. Any other parameter name (e.g. ?limit=/?offset=) or a
non-positive value answers 400 invalid n parameter.
POST /api/v1/workers/bg/:bg_id/kill
Kill a background worker session. POST only. 404 unknown id; 409
when the worker is in a non-killable state (body: worker is <status>).
Task Results
GET /api/v1/tasks
List all stored task results. Scoped to the requesting user’s tasks (non-admin). Admin users see all tasks.
DELETE /api/v1/tasks/:task_id
Cancel a running task. Returns 403 if the task belongs to another user (non-admin); the check is owner-only (/ — teammate visibility was never implemented; sol_http_workers:check_task_owner/1).
Response: {"status": "cancelled"}
GET /api/v1/tasks/:task_id
Fetch ONE stored task result (owner or admin; 403/404 otherwise):
{"task_id": "task-xyz789", "status": "completed",
"content": "...", "truncated": false}
truncated: true marks a result that lost tokens to a stream gap or a
cap breach.
GET /api/v1/tasks/outbox
List outstanding dispatch receipts — acknowledged tasks whose delivery is not yet terminally resolved. Every dispatch writes a durable receipt before the frame is sent; the receipt is cleared when the task reaches a terminal status, and any receipt still outstanding at boot is re-queued (at-least-once) or loudly marked by the boot reconcile. Requeue is system-driven — this endpoint is READ-only.
Scoped like GET /api/v1/tasks: non-admin callers see only their own
receipts. Paginated (limit/offset, default 50).
Response:
{
"items": [
{"task_id": "zmq-1756000000000-1", "user_uuid": "u-…",
"queued_at": 123456, "age_ms": 42000}
],
"total": 1, "limit": 50, "offset": 0,
"page": 1, "total_pages": 1, "has_more": false
}
queued_at is wall-clock system time (epoch ms, the same base the
durable outbox row is written with); age_ms = system_time - queued_at
clamped at zero ( — the pre-fix shape mixed the persisted
system clock with erlang:monotonic_time, whose arbitrary origin made
age_ms meaningless). Because the timestamp is wall-clock, a receipt that
survived a reboot reports its true wall age (it is re-queued at boot, which
refreshes queued_at). A receipt that persists here across
boots with zmq_enabled=false is retained and re-alarmed (CRITICAL log +
dispatch_outbox_orphaned_total) at every boot until the transport is
re-enabled.
Reserved namespace: task ids starting with zmq- are
SERVER-RESERVED (generated ids are zmq-<ms>-<counter> — unique per Sol
node, not fleet-wide; /, W2). A caller-supplied
task_id with that prefix is rejected at dispatch with
{"error":"reserved_task_id"} — the workflow-bridge correlation ids use a
different prefix (wf-...) and are unaffected.
Cluster
GET /api/v1/cluster
Show cluster membership.
Response:
{
"node": "sol@gpu-node-1",
"connected": ["sol@gpu-node-2"],
"count": 2,
"self": "sol@gpu-node-1",
"connectivity": {
"self": "sol@gpu-node-1",
"connected_peers": ["sol@gpu-node-2"],
"connected_peer_count": 1,
"known_peers": ["sol@gpu-node-2", "sol@gpu-node-3"],
"expected_nodes": 3
},
"health": {
"healthy_peers": ["sol@gpu-node-2"],
"unhealthy_peers": [],
"unknown_peers": [],
"healthy_count": 1,
"unhealthy_count": 0,
"unknown_count": 0
},
"left": [],
"uptime_seconds": 86400,
"seeds": [
{
"node": "sol@gpu-node-2",
"connected": true,
"last_ping_age_seconds": 3,
"last_result": "pong",
"ping_in_flight": false
}
]
}
count retains its documented self-included meaning (1 + peers).
connected is PEERS ONLY — self is self and also appears under
connectivity, so a client can no longer mistake the
local node for a peer.
health is per-connected-peer and only claims what it can prove:
healthy = last seed probe answered pong; unhealthy = the last probe
answered pang/timeout or the last catalog sync exited abnormally;
unknown = connected but never probed (e.g. joined manually, not a
configured seed). A manually joined peer is never silently counted
healthy.
left is the leave set: the peers this node will not automatically
rejoin. POST /api/v1/cluster/leave seeds it from the configured
cluster_nodes ∪ all known peers ∪ the previously-left set (not just
the links that happen to be up at leave time), casts the peer-side leave
marker to visible peers (best-effort), and disconnects. A later
nodeup/pong for a left peer is ignored; an explicit
POST /api/v1/cluster/join is the only re-entry and clears both
markers. The set is process-lifetime: a Sol restart starts with an
empty leave set (the operator re-issues the leave if isolation must
survive a restart).
uptime_seconds is the serving node’s uptime (,
). Per-connected-node uptime would require a blocking RPC per peer
on every poll — the actionable membership signal is the per-seed probe
state instead (last_ping_age_seconds / last_result /
ping_in_flight; last_* are null until the first probe completes;
boot probes are ASYNCHRONOUS since then, so a silent seed
can no longer delay the boot ladder or the listener).
Unconnected seeds are re-probed on every 30s resync tick, so a peer
that boots after this node self-rejoins without the join API. A
degraded sol_cluster returns count: 0 with empty seeds.
POST /api/v1/cluster/join
Join a cluster node. POST only.
Request body: {"node": "sol@gpu-node-2"}
POST /api/v1/cluster/leave
Leave the cluster. POST only.
GET /api/v1/catalog
List global model catalog across cluster nodes.
Lua Workers
POST /api/v1/lua/eval
Evaluate Lua code in a sandboxed Luerl worker. POST only.
Request body: {"code": "return 1 + 1"}
Response: {"status": "ok", "result": 2}
GET /api/v1/lua/workers
List Lua workers.
POST /api/v1/lua/workers/spawn
Spawn a Lua worker. POST only.
Request body: {"script": "hello"} (optional; a non-string or
4 KiB value is
400 invalid_script). The script is loaded into the worker’s sandbox at start — the field is honored.
ZMQ
GET /api/v1/zmq/workers
List registered ZMQ workers. Each row carries the worker’s last READY
capability census: mcp_servers, mcp_tools and
custom_tools (integer counts of the RUNNING capability — live MCP
servers, registered mcp__* tool specs, registered custom tools; a legacy
pre-census worker reads 0) plus capability_degradations (array of typed
reason strings such as mcp_approval_required:<server>,
mcp_start_deferred:<server> or mcp_start_failed:<server>; [] when the
worker is fully capable). The census is client-declared telemetry — server
authorization gates never trust it.
POST /api/v1/zmq/dispatch
Dispatch task to ZMQ worker. POST only.
Request body:
{"prompt": "Fix the bug", "model": "glm-4.7-flash", "context": "...", "timeout_ms": 600000, "idempotency_key": "my-op-42", "mode": "plan"}
Fields:
timeout_ms (optional) — per-task execution timeout override; an integer
0..3600000 (0 disables the timeout for this task). The effective value
is stamped on the wire frame and drives the server-side task-lease timer.
A non-integer, negative, or over-bound value answers typed 400.
idempotency_key (optional) — opaque caller-scoped key, <=128 bytes;
a resubmit inside the claim window returns the ORIGINAL task id. A claim
is released on every non-dispatch refusal (worker_overloaded,
queue_full), so a resubmit after a refusal dispatches fresh.
mode (optional) — advisory agent-mode request: a
non-empty string <=64 bytes naming an agent mode. The value is a HINT —
Sol stamps it on the task frame only when the assigned worker
advertised that exact mode on READY (unadvertised values are stripped,
counted in zmq_task_mode_fallback_total, and the worker keeps its
default mode; permission_mode is untouched). A non-string or
over-bound value answers typed 400.
Response: {"task_id": "task-abc456"}
GET /api/v1/zmq/status
Show ZMQ gateway status.
Response:
{"port": 5555, "connected": 3, "queue_depth": 0}
Circuit Breaker
GET /api/v1/circuits
List circuit breaker states.
Response: paginated envelope (/ — the bare-array example
predated the pagination contract; sol_http_cluster:circuits_body/1
paginates):
{"items": [{"key": "glm-4.7-flash", "state": "closed", "failure_count": 0}], "total": 1, "limit": 50, "offset": 0, "page": 1, "total_pages": 1, "has_more": false}
POST /api/v1/circuits/reset
Reset a circuit breaker. POST only.
Request body: {"key": "glm-4.7-flash"}
Orchestration
POST /api/v1/orchestrate
Execute multi-task orchestration. POST only.
Request body:
{
"tasks": [
{"prompt": "Fix bug in auth", "model": "glm-4.7-flash"},
{"prompt": "Fix bug in api", "model": "glm-4.7-flash"}
],
"strategy": "parallel",
"model": "glm-4.7-flash",
"timeout_ms": 60000
}
Response: Orchestration results with child task outputs.
GET /api/v1/orchestrate/:id
Show orchestration detail with child task results.
Workflows
POST /api/v1/workflows/start
Start a workflow. POST only. The body requires a name
(400 missing workflow name without it); objective, token_budget and
any workflow inputs are optional (a steps body field is not read).
Request body:
{
"name": "fix-auth-bug",
"objective": "Fix authentication bug",
"token_budget": 100000
}
Response: {"workflow_id": "wf-abc123", "status": "started"}
Idempotency. An optional Idempotency-Key request header
(opaque, ≤128 bytes; an over-long value is a 400) makes the start an
insert-once admission scoped to the caller: the key folds into the
workflow_id, and a retried request with the same key returns the
Original instance with the identical admission body (no second
instance, no second audit row) — including after that instance reached a
terminal state (the durable row is the record until its normal retention
GC). Different keys, or the same key from a different principal, are
independent admissions. Without the header every call mints a fresh
instance (the documented at-least-once behavior).
POST /api/v1/workflows/:id/cancel
Cancel a workflow and its registered descendant tree.
Immediate ack. The request is acknowledged as soon as
the ROOT instance answers a bounded cancel probe (3 s class); the descendant
walk always runs asynchronously — it can never block the workflow manager
(get_status/start_workflow stay responsive even with a wedged child). The
response carries the operation handle and the root’s truthful disposition:
{
"status": "cancelled",
"cancel_op_id": 17,
"root": "ok",
"descendants_pending": true
}
| Root disposition | HTTP | Meaning |
|---|---|---|
ok | 200 | the root transitioned to failed (reason cancelled) |
cancel_pending | 202 | the root is compensating — the cancel is pending; the unwind still completes and the workflow then terminates failed with fail_reason cancelled |
timeout | 202 | the root did not answer the 3 s probe; the ack is honest (status: cancel_pending), the async walk still runs |
Roots already terminal answer 409 workflow already completed (or the
matching already-terminal error); a missing id is 404. cancel_op_id is a
monotonic per-manager handle. Descendant progress is observable through the
workflow_child_cancelled events (status cancelled/pending/
skipped/unregistered), the sol_workflow_descendant_cancel_* counters
(ops started/completed, children visited, cap hits, in-flight gauge), and
the final workflow_descendant_cancel_completed event. The walk is bounded:
3 s per child probe and at most 256 children per operation.
A cancel that arrives while a workflow is compensating is never a lie
(the previous shape answered ok while the workflow later reported
compensated): the reply is the pending disposition above and the eventual
state is deterministic — failed with fail_reason = "cancelled" once the
unwind completes (or once the compensation window times out with a pending
cancel). Without a pending cancel the same unwind lands compensated.
Marketplace
Skills marketplace for publishing, discovering, and rating agent skills
(sol_http_skills.erl + sol_marketplace_store.erl). Every marketplace
envelope is FLAT — {"skills": [...]} — never the paginated
{items, total, has_more} shape.
GET /api/v1/marketplace
Browse published skills.
Query parameters (honored server-side — the store windows the result
before returning; the flat envelope carries no total/has_more, so a
truncated page is not detectable from the response alone):
| Parameter | Default | Description |
|---|---|---|
sort | created_at | Sort order: created_at or downloads (featured skills pin first in both orders) |
tag | — | Filter by tag (singular query param) |
author | — | Filter by author UUID (?author=<uuid>) |
featured | — | Featured only: 1 or true |
limit | 50 | Max results, clamped to 1..500 by the shared pagination parser (the pre-fix doc claimed a 20 default the handler never applied) |
offset | 0 | Skip count (negative/garbage clamps to 0) |
page | 0 | 1-based page number — only honored together with per_page |
per_page | 0 | Items per page (≤500) — overrides limit/offset when both page and per_page are > 0 |
Response (200):
{
"skills": [
{
"name": "code-review",
"author_uuid": "user-abc",
"description": "...",
"version": "1.0.0",
"tags": ["code"],
"downloads": 42,
"featured": false,
"avg_rating": 4.5,
"rating_count": 2
}
]
}
Rating aggregates ride inline on every summary; the full review list
lives behind GET /api/v1/marketplace/ratings.
GET /api/v1/marketplace/search?q=QUERY
Search marketplace skills by name or description. Same flat
{"skills": [...]} envelope as browse (no pagination params).
GET /api/v1/marketplace/:name
Get skill detail with full body. Supports ?author=<uuid> for disambiguation.
Response is {"skills": [skill]}; 404 not_found when unknown.
GET /api/v1/marketplace/:name/:author
The two-segment detail form — same handler, EXACT author match (no
?author= query needed). Served by the same route row that answers the
delete route on DELETE. Response is {"skills": [skill]};
404 not_found when unknown.
POST /api/v1/marketplace
Publish a skill (or re-publish over the author’s existing one). POST
only. Auth required (401 authentication_required).
Request body:
{
"name": "my-skill",
"description": "Does something useful",
"body": "skill content in SKILL.md format",
"version": "0.1.0",
"tags": ["code", "utility"],
"triggers": [],
"arguments": []
}
| Field | Type | Required | Description |
|---|---|---|---|
name | string | Yes | Lowercase alphanumeric + hyphens (^[a-z0-9][a-z0-9-]*$). Reserved route names (search, reports, dismiss, feature, rate, ratings) are rejected |
description | string | Yes | Short description (non-empty) |
body | string | No | Full skill body (default "") — capped at skill_body_max_bytes (default 262144 = 256 KB; the same cap the registry enforces and the worker materializer refuses over) |
version | string | No | Defaults 0.1.0 |
tags / triggers / arguments | array | No | Default [] |
Responses:
201 {"status": "created", "name": "..."} — first publish
200 {"status": "updated", "name": "..."} — same author re-published;
existing downloads/created_at/featured are preserved
400 missing_name_or_description · 400 invalid name (reserved or
regex mismatch)
413 body_too_large — body over skill_body_max_bytes (default
262144 = 256 KB)
429 rate_limited — only when the operator enables the limiter
(below)
Rate limiting (truth): the publish path runs through the shared
per-user rate limiter (rpm 60 / burst 10, retry-after header on 429),
but the limiter is DISABLED by default (rate_limit_enabled=false) —
publishes are never 429’d unless the operator turns it on. The
previously documented “10 publishes per hour” limit never existed and has
been struck. The RATE endpoint (POST /api/v1/marketplace/rate) has no
limiter at all.
GET /api/v1/marketplace/ratings?name=NAME&author=AUTHOR
Aggregate ratings for a skill. Both name and author are REQUIRED —
either missing answers 400 missing_name_or_author.
Response (200):
{"ratings": [{"user_uuid": "...", "rating": 5, "review": "...", "created_at": 1745600000000}], "avg_rating": 4.5, "rating_count": 1}
POST /api/v1/marketplace/rate
Rate a skill. POST only. Auth required (401 authentication_required). No rate limiter on this endpoint.
Request body:
{"name": "my-skill", "author": "user-abc", "rating": 5, "review": "great"}
| Field | Type | Required | Description |
|---|---|---|---|
name | string | Yes | Skill name |
author | string | Yes | Author UUID (disambiguates same-name skills) |
rating | integer | Yes | Rating value (out-of-range → 400) |
review | string | No | Free text, default "" (hashed in the audit trail, never stored in logs) |
Responses: 201 {"status": "created"} · 409
duplicate_rating (one rating per user per skill — re-rating is a 409,
not an update) · 400 missing_fields (any of name/author/rating
missing) · 400 invalid_rating.
DELETE /api/v1/marketplace/:name/:author
Requires the marketplace:manage RBAC scope; the handler additionally
allows only the skill’s own author (the path :author must equal the
caller uuid) or an admin (403 forbidden otherwise). Unknown rows answer
the 404 zerg envelope.
Delete a published skill. DELETE. Author or admin only
(403 forbidden otherwise; 404 not_found when unknown).
Response: 200 {"status": "deleted"}
POST /api/v1/marketplace/:name/:author/install
The explicit consume act: returns the full skill
record — body included — plus a provenance map, and records the receipt
server-side (audit row + download counter). POST only. Auth required
(401 authentication_required); gated on the marketplace:install scope
(seeded for the member role; viewer does not hold it). Rate-limited
through the shared limiter like publish (disabled by default).
Response (200):
{
"skill": {"name": "my-skill", "description": "...", "body": "---\n...", "version": "1.0.0", "author_uuid": "user-abc", "tags": []},
"provenance": {"source": "marketplace", "version": "1.0.0", "author_uuid": "user-abc", "fetched_at": 1745600000000}
}
Responses: 404 not_found (unknown name/author pairing) · 413
body_too_large (the stored body exceeds the current
skill_body_max_bytes — e.g. the cap was lowered after publish) · 429
rate_limited · 503 rate_limiter_unavailable.
The worker / CLI side writes the body to a local
SKILL.md and stores the provenance beside the file (provenance.json)
under the managed remote skills root; Luna also fences the body as
<untrusted-memory source="skills.remote"> when it renders into a prompt.
POST /api/v1/marketplace/:name/:author/report
Report a skill for moderation. POST only. Auth required.
Request body: {"reason": "description of issue"} (defaults to
"no_reason" when absent).
Response: 201 {"report_id": "..."} — the reason is hashed
(reason_sha256) in the audit trail, never logged verbatim.
GET /api/v1/marketplace/reports
List pending skill reports. GET. Admin only (403 admin_required).
Response: {"reports": [{"id": "...", "skill_name": "...", "author_uuid": "...", "reporter_uuid": "...", "reason": "...", "timestamp": 1745600000000}]}
POST /api/v1/marketplace/reports/:id/dismiss
Dismiss a skill report. POST only. Admin only (403 admin_required).
Response: 200 {"status": "dismissed"}
POST /api/v1/marketplace/feature
Feature or unfeature a skill. POST only. Admin only
(403 admin_required).
Request body: {"name": "my-skill", "author": "user-abc", "featured": true}
(featured: false unfeatures; defaults true when absent).
Responses: 200 {"status": "ok"} · 400
missing_name_or_author · 404 not_found.
Workspace
Remote file operations within the workspace. Scope: a
non-admin caller’s root is <workspace_root>/users/<server-derived-scope>/
paths are relative to that subtree, so a member cannot read/write another
member’s task workspace. An admin uses the global workspace root and may
cross into any users/<scope>/ subtree. The scope is derived from the
authenticated identity, never from a request field; . and .. principals
are hashed.
POST /api/v1/workspace/read
Read file contents.
POST /api/v1/workspace/write
Write file contents. POST only. Uses atomic writes (tmp + rename).
Request body: {"path": "src/main.rs", "content": "..."}
POST /api/v1/workspace/edit
Apply an edit to a file. POST only.
Request body: {"path": "src/main.rs", "old": "old text", "new": "new text"}
POST /api/v1/workspace/search
Search workspace files by content.
GET /api/v1/workspace/list?path=DIR
List directory contents.
Managed Settings
GET /api/v1/managed-settings
Get managed (fleet-push) settings. Admin only.
Response ({ok, data, schema} envelope; data is the settings map,
schema is the shared key contract — ):
{"ok": true,
"data": {"execution.policy": "standard", "_schema_rev": 1},
"schema": {"schema_rev": 1, "keys": {"execution.policy": {"type": "enum", "values": ["strict", "standard", "permissive"], "target": "execution.policy", "consumer": "core.command_policy"}}}}
data._schema_rev is server-injected metadata (never persisted); worker
appliers running an older schema rev skip the payload loudly.
PUT /api/v1/managed-settings
Update managed settings. PUT only (reads via GET above). Admin only. The body is SHAPE-AWARE and SCHEMA-BOUND:
{"key": "<name>", "value": <value>} — single-key MERGE into the
existing settings map; unrelated keys survive. The audit entry records
op: "merge" plus the merged key, and the managed_settings_update
event publishes only the changed key(s) (this PUB drives the Luna
refetch).
any other JSON object — FULL REPLACEMENT of the settings map (audited
as op: "replace"; the event carries the full map). Note that an
object carrying both key and value is always a merge.
Only the keys in docs/fixtures/managed_settings_schema.json are
valid: execution.policy (enum), execution.max_iterations
(int 1–200), execution.session_budget_usd (number 0–1000000).
Legacy free-form keys already stored are ignored by workers (loud skip
- counter) and rendered read-only by the console.
Request body (merge — the ops-console shape):
{"key": "execution.max_iterations", "value": 40}
Request body (full replacement):
{"execution.policy": "strict", "execution.max_iterations": 40}
Errors: 400 invalid_json (non-object JSON), 400 invalid_shape
(malformed {key,value} — half-shapes, non-binary/empty key), 400 unknown_setting_key (key outside the schema; the message lists the
nearest known keys), 400 setting_out_of_bounds, 400 setting_type_mismatch, 503 persist_failed when the durable snapshot
write fails (settings are left unchanged — the save is not acknowledged).
A refused PUT never persists, audits or publishes.
Settings persist to <data_dir>/managed_settings.json at every PUT and
reload at boot; a corrupt snapshot refuses boot.
Sessions
POST /api/v1/sessions
Create a session share link. POST only. The body carries the session
data to share (arbitrary string — typically a serialized session/JSONL
export); session_data is REQUIRED (400 session_data_required without
it), format and ttl_days are optional.
Request body:
{
"session_data": "{\"type\":\"session_meta\",...}",
"format": "jsonl",
"ttl_days": 7
}
Response (201):
{"share_id": "shr-xyz789"}
The response carries share_id plus an optional url ({"share_id": "...", "url": "https://<base_url>/api/v1/shares/shr-xyz789"}) only when
the operator has configured base_url (sys.config or SOL_BASE_URL).
The path is the anonymous capability surface (/api/v1/shares/<id>), never
the authenticated /api/v1/sessions/<id> route — the mint and the auth
exemption consult sol_session_shares:share_url_prefix/0.
There is NO expires_at field — expiry is internal state, never emitted
(the previously documented expires_at response field was struck in
Clients who need it can derive it from ttl_days at create
time).
Capability-token model: the share id
IS the capability. GET /api/v1/shares/:share_id is unauthenticated BY
DESIGN — the public-read LOW adjudication accepted that anyone holding
the opaque id can read the share; the id is the secret (256-bit random,
unguessable), and there is no separate ACL. Compensating controls:
per-user create quota, per-IP read rate limiting, and a notice-level read
audit log (below).
TTL clamp: ttl_days is clamped server-side to
min(ttl_days, 365) — a larger request still succeeds but is silently
capped to one year, with a loud share ttl_days N clamped to 365 warning
in the server log. Omitted ttl_days falls back to the
server’s default share retention.
Quota: creates are bounded per user by share_quota_per_user
(default 100 live shares). At the quota the endpoint answers 429 share_quota_exceeded with a retry-after: 3600 header (the hourly
cleanup cadence frees slots) — never a 500.
Public-read controls: GET /api/v1/shares/:share_id is
per-IP rate limited (share_rate_limit_per_min) and every read is
logged at notice level (share read id=<share_id> ip=<peer>).
Errors: 400 session_data_required · 429 share_quota_exceeded when the
caller is at the per-user share quota (share_quota_per_user, default 100;
retry-after header carries the suggested retry horizon, ).
GET /api/v1/sessions/:share_id
Get shared session data. Two surfaces:
Owner (or admin) read — the ownership decision runs through the
NON-counting sol_session_shares:peek/1, so loading your own share
never consumes a view; the response is the owner projection
{data, format, created_at, remaining_views} (200). remaining_views
is owner-only — the consumer surface never sees it (live-share oracle).
Consumer read — every other caller goes through the counting
get/1; a read IS a consumed view. 404 when expired, unknown, or
view-exhausted (expired / never-existed / exhausted are indistinguishable
on this surface — + ).
DELETE /api/v1/sessions/:share_id
Delete a session share. Owner or admin only (403 otherwise). Unknown
ids answer 404 not_found; an expired share answers 404 not_found
too — expired and never-existed are indistinguishable on every share
leg since ( swept this paragraph, the last
410 expired claim; sol_http_sessions.erl:session_delete/2). A
View-exhausted share joins the same typed gone class (,
CORE-1 — the pre-fix missing arm crashed the request process into an
unguarded 500), and the ownership probe is the non-counting
peek/1, so repeated owner DELETE attempts never burn the share’s own
view budget.
GET /api/v1/shares/:share_id
Get a share by id — the standalone PUBLIC share endpoint
(unauthenticated BY DESIGN — see the capability-token model above):
{data, format, created_at} (200), 404 when expired or unknown
.
HEAD is non-counting AND non-oracular: after the
per-IP limiter it answers 204 for every well-formed id — live, expired, and
unknown are indistinguishable and no view is consumed. The pre-fix 200/404
verdict was a free liveness oracle.
The per-IP rate limit keys the TRUSTED-PROXY-RESOLVED client address
(an untrusted peer’s X-Forwarded-For/X-Real-IP never influence the
bucket); a refusal is 429 rate_limited with Retry-After: 60.
Read logs carry a sha256 PREFIX of the share id, never the full
capability.
Webhook
POST /api/v1/webhook/:channel_id
Webhook receiver for channel integrations (Telegram, Slack, Discord, Teams). Validates per-platform signature.
** contract:**
Channel config is written by JSON (BINARY keys) or bundled plugin configs
(atom keys); both are read. Slack signatures are compared in lowercase
hex (the real Slack encoding) and an empty/missing secret is the
fail-closed “not configured” class (403), never an empty-key accept.
A paused channel refuses deliveries with 404 (only status=active
channels accept), and pausing one channel stops that platform’s poller
only when no sibling channel of the same type is still active.
Replay keys are channel-scoped. Telegram uses the durable
update_id and Teams the activity id (7-day replay window), so a
captured delivery is refused long after the 5-minute nonce TTL;
Slack/Discord keep the signature+timestamp window.
** (CTRL-25): the replay seen-set is durable and shared.** Every
accepted key is fsynced to <data_dir>/webhook_replay.journal (loaded and
compacted at boot by the channel owner), so a restart drill still refuses
the capture; accepted keys are also announced to the connected Sol nodes
(the sibling records them), so a replay routed to another node is refused
once the announcement lands. The residual is the in-flight announcement
race; the platform freshness window still bounds signature-bearing
deliveries.
Teams subscription validation: a
POST carrying ?validationToken=<token> answers 200 with the token
echoed as the response body (text/plain) — Microsoft’s provisioning
handshake requires the echo. The echo performs NO audit write and NO plugin
dispatch, and is now bound and bounded: it requires a configured
teams_auth_token, echoes at most 4096 bytes, and is rate-limited per
channel (teams_validation_rate_per_minute, default 30/min). An
unconfigured channel and an oversized token answer the same generic 404
as an unknown channel (no existence leak); over-budget answers 429 with
an empty body and Retry-After: 60 — never the token. All other Teams
POSTs require Authorization: Bearer <teams_auth_token> and answer 200
with an empty body (audited + dispatched) as before; all other platforms
are byte-identical to previous.
Readiness
GET /api/v1/ready
Deep health check for load balancers. Returns 200 only when all subsystems are ready.
Response: {"status": "ok", "checks": {...}} on 200;
{"status": "degraded", "checks": {...}} on 503
(sol_health:readiness/0 — corrected the stale
{"status": "ready"} example).
Events & Cursors
GET /api/v1/events supports two cursor styles:
?since=<unix_ms> — timestamp cursor; ties at the same millisecond may be
missed at page boundaries.
?since_id=<seq> — tuple cursor (timestamp, seq) with id tiebreak:
same-ms events are never skipped or duplicated. Responses carry
newest_timestamp + newest_id; pass BOTH back on the next poll.
Aggregate scoping: ?aggregate=<aggregate_id>
lists the events of ONE aggregate over the {aggregate_id, seq, event_id}
ordered index (never a full-aggregate materialization). Reads are
Caller-scoped: a non-admin — or an admin passing ?user_uuid=<uuid> —
sees only that caller’s events in the aggregate; an admin with NO
?user_uuid sees all of the aggregate’s events. The ?aggregate=all
pseudo-value is removed — the explicit value answers 400
unknown_parameter.
The aggregate envelope is
{"items": [...], "limit": N, "offset": O, "page": P, "has_more": bool, "next_cursor": "<seq>:<event_id>" | null}. It deliberately has no
total/total_pages: an aggregate count cannot be produced without
walking the whole aggregate, which is exactly what the indexed read
replaced. offset pagination is honored up to 10001 (deeper offsets are
a typed 400); from_seq is an inclusive replay cursor (seq >= from_seq, seq 0 included). next_cursor carries the exact
{seq, event_id} pair of the last returned row and resumes strictly
after it — duplicate-seq rows past a page boundary are reachable. Pass it
back as ?cursor=<seq>:<event_id> with no offset and no
from_seq (those combinations answer 400 cursor_with_offset /
cursor_with_from_seq; combining them would double-skip).
A caller-scoped walk that must visit more than the server’s index-row scan
bound answers 400 aggregate_scan_limit_exceeded instead of walking
the whole aggregate (the unscoped admin read stops at offset+limit+1).
A request with no aggregate: an admin with NO ?user_uuid gets the
cross-aggregate listing (, — newest-first, same envelope +
cursor contract; the pre-fix shape was a structurally-empty page), while
a non-admin resolves to their own user_uuid stream.
SSE (/api/v1/sync-events) is scoped to the caller’s user_uuid
for non-admins — sessions never see other users’ event frames.
Sync-events stream frames
The text/event-stream carries four frame kinds. Every sync_event
frame carries id: <seq>:<event_id> (the same pair the aggregate REST
cursor uses) for client-side dedupe/correlation. Resume is explicitly
unsupported on this stream: the stream is
mixed-aggregate, so Last-Event-ID and ?from_seq are not honored on
/api/v1/sync-events; a reconnect is a FRESH stream and the client
resyncs affected aggregates via GET /api/v1/events?aggregate=<id> (the
event.gap contract below). Do not treat the id: as a resumable cursor.
SSE event: | Meaning |
|---|---|
sync_event | one stored event (the N:type record fields as JSON; framed with id: <seq>:<event_id>) |
event.gap | drop signal — the server’s per-subscriber queue bound (subscriber_queue_limit, default 256) dropped events for the aggregate named in the frame; the stream stays open |
stream_error | typed server signal — error is EITHER a string code OR an object carrying a code. Two emitters are TERMINAL (written with fin, no done follows): (1) graceful shutdown — {"error":"server_shutdown","message":"server is shutting down","truncated":true} on the sync-events, workflow AND conversation streams, and on the replay drain (GET /replay/:session/events receives this same payload when the drain fires); (2) replay store failure/writer crash — {"error":"replay_store_unavailable","reason":"<detail>","truncated":true} when a replay page read fails or the replay writer crashes (that endpoint emits done only for a complete history walk). The third emitter is PER-EVENT: (3) encoding failure — {"error":{"code":"event_encoding_failed"},"truncated":true} is written with nofin when one event payload cannot be JSON-encoded (defense-in-depth: payloads are already sanitized with typed placeholders before encode); the stream stays open and one frame replaces each unencodable event. Every payload carries "truncated": true — the delivered prefix is valid but incomplete. Client contract: reconcile every viewed aggregate from its REST cursor immediately on receipt (an encoding failure never reconnects, so waiting for a close would never heal the drop); Limon calls the same targeted reconcile path on every frame and surfaces the reason, while the CLI’s SSE readers carry a defensive stream_error arm (exit 2, reason on stderr) — no Sol route the CLI streams emits the frame today |
done | terminal frame; the stream closes.: emitted when the sol_sync_event store dies (its subscriber table dies with it — no further deliveries will ever arrive) with the reason {store_restart, Reason} logged + counted (sync_event_store_restarts_total); the client’s reconnect IS the documented resync path (pre-fix the stream heartbeated forever) |
The other SSE planes use their own frame names: the workflow stream
(GET /api/v1/workflows/:id/stream) frames event: workflow_event and the
conversation stream (GET /api/v1/conversations/:conv_id/stream) frames
event: message_append; both terminate with event: done (or the shared
terminal event: stream_error shutdown frame).
event.gap data payload:
{"kind": "gap", "aggregate_id": "task-abc", "last_seq": 42}
Client contract: everything up to and including last_seq for that
aggregate may have been skipped by this stream. On receipt, resync the
aggregate via GET /api/v1/events?aggregate=<id> (with the aggregate-scoped
from_seq replay cursor; from_seq without aggregate is a typed
400 unknown_parameter, )
and continue consuming in place — the stream does NOT close on a gap.
Delivery is collapsed: a flood past the bound produces one gap frame
per aggregate per drop epoch (a later successful delivery closes the
epoch; the next drop opens a new one), never one frame per dropped event.
The per-event seq fields let consumers detect residual discontinuities.
Sync-events store semantics (sol_sync_event)
The sync-event store streams versioned events to subscribers. Events are
stored as N:type (e.g. 1:task.completed); base_type/1 strips the
version prefix.
Subscription filters (sol_sync_event:subscribe/1):
| Filter form | Matches |
|---|---|
all | every event |
AggregateId | events whose aggregate id equals the given term |
{types, [Type,...]} | events whose base type is a member — versioned stored types match their base, so {types, [<<"plugin.loaded">>]} matches a stored 1:plugin.loaded |
The plugin manager subscribes with
{types, [<<"plugin.loaded">>, <<"plugin.unloaded">>]}. Both event types
carry plugin_name (the loaded/unloaded plugin’s name) and are produced
by the event forwarder from the manager’s plugin_loaded/plugin_unloaded
notifications — plugin lifecycle state is manager state and belongs in
the sync stream; plugin-emitted plugin.* activity events remain excluded
.
Replay semantics: replay/1 never rewinds the
per-aggregate sequence. The event_sequence row is written only when
absent or when the replayed event’s seq is strictly higher — replaying an
old event (or an out-of-order recovery batch) leaves the stored seq
unchanged, so downstream compare-and-write projectors and compaction
ordering stay monotonic.
Chat capacity semantics
POST /api/v1/chat (session create):
| Status | Body code | Meaning |
|---|---|---|
| 429 | seat_cap_reached | Seat cap saturated (Retry-After: 1) |
| 429 | max_workers_reached | Worker ceiling (Retry-After: 1) |
| 429 | too_many_sessions | Session cap: 20 active sessions per user, or 500 active sessions globally |
| 503 | license_unavailable | License service unreachable under block mode |
| 413 | body_too_large | Body over 10 MB |
POST /api/v1/chat/:id/message takes {"content": "..."} — a missing or
empty content answers 400 content_required. Read timeouts on the
message body answer 408 request_timeout; a client that disconnects
mid-read answers 499 client_disconnect.
Turn idempotency. The send body may
carry {"client_turn_id": "<id>"} (non-empty binary, ≤128 bytes; the same
field the WS message frame already carries). The id is content-bound in
the session owner’s bounded side table (per-session cap
chat_turn_dedupe_max_per_session, TTL chat_turn_dedupe_ttl_ms):
| Case | Answer |
|---|---|
| fresh id (or no id) | 200 {"ok":true,"data":{"task_id":"…","status":"dispatched"}} |
| replay, same id + same content within the window | 200 with "deduped":true and the ORIGINAL task_id (no second worker turn) |
| same id, different content | 409 code client_turn_id_conflict |
| another transport holds the session turn | 409 code streaming_in_progress + task_id + Retry-After: 1 |
The WS path speaks the same verdicts as frames: a fresh ack is
{"type":"ack","task_id":"…","session_id":"…"}, a replay adds
"deduped":true, and the refusals are non-terminal error frames with
code streaming_in_progress / client_turn_id_conflict.
Dispatch failures are classified, never a blanket 500: a
dead worker family (noproc, os_process_dead, not_found, and the
typed worker_not_found pipeline-attach refusal) answers 503
worker_unavailable — the same code the WS path surfaces as its error
frame.
Stream semantics:
GET /api/v1/chat/:id/stream holds its max_sse_connections slot for
the WHOLE stream (previous the slot was released at handshake and the
budget never bounded chat).
One live stream per session: a second GET.../stream REPLACE-KILLS
the elder — the elder’s stream receives event: replaced + fin, its slot
is released, and the newest stream wins (loudly counted server-side).
event: done / event: error close the stream; a pipeline that dies
without a terminal frame closes the stream with event: error
(reason: "pipeline crashed") instead of hanging open.
Streamed turns persist a checkpoint every chat_checkpoint_tokens tokens /
chat_checkpoint_ms ms, so a mid-stream crash loses at most one window.
Scheduler quotas
Global cap: max_scheduled_jobs (default 1000) → 429 max_jobs_reached.
Per-user cap: max_scheduled_jobs_per_user (default 100) → 429
{per_user_limit_reached, N}.
Impossible cron expressions (e.g. 0 0 31 2 * — February never has a
31st; ) are rejected at create/update time via
sol_cron:validate_schedule/1 (invalid_cron for parse failures,
impossible_schedule for provably-undecidable day-vs-month-length
combinations). An impossible expression that still reaches the advance
path disables the job (status: disabled) instead of re-firing every
minute. Job records have no last_error field.
Scheduler timezones
All cron/at/every scheduling is naive UTC — this is a recorded posture decision: there is no IANA timezone support and no DST adjustment. A schedule written in local wall-clock time is Silently shifted by the UTC offset (and by DST transitions). Schedule in UTC.
Cron expressions evaluate in UTC (all schedule timestamps are UTC
epoch-ms). Every schedule/job response carries a tz field ("UTC") so
operators are never surprised. sol_cron:explain_next/3 returns the
literal UTC fire times for an expression (the next N firings from a given
epoch-ms), so a schedule can be verified before it is committed.
Missed-fire contract. An interval job never runs
concurrently with itself: grid fires that elapse while its own task is
still running are skipped, counted per job in fires_skipped, and emitted
as a scheduler.fires_skipped event on advance (the payload carries the
skipped count). Boot catch-up fires an overdue job once and re-arms the
tail on the next interval-grid boundary — it never replays the backlog
(per-job missed_fire_count is the record; cron/at report 0 because a
per-fire backfill would need a search).
Additionally: a job created via a plugin’s sol.scheduler
bridge delivers its event to the plugin’s on_event (it never dispatches
a prompt-less task), and scheduler_degraded_total counts store outages
on live ticks — ticks degrade to no-dispatch and recover
automatically.
License status
GET /api/v1/license/status (admin) — enforcement state, source
(file/remote/fallback), caps, packs, refresh clock. When the license service
is unreachable the endpoint still returns 200 with
{"enabled": false, "reason": "license_unavailable"} (never a 500).
Method Enforcement
These endpoints require POST. All other methods return 405 Method Not Allowed:
POST /api/v1/start
POST /api/v1/stop
POST /api/v1/stop-all
POST /api/v1/discover
POST /api/v1/prepare/:name
POST /api/v1/agents/spawn
POST /api/v1/agents/:id/kill
POST /api/v1/cluster/join
POST /api/v1/cluster/leave
POST /api/v1/lua/eval
POST /api/v1/lua/workers/spawn
POST /api/v1/zmq/dispatch
POST /api/v1/circuits/reset
POST /api/v1/schedule/spawn
POST /api/v1/schedule/:id/run
POST /api/v1/channels/spawn
POST /api/v1/channels/:id/message
POST /api/v1/orchestrate
POST /api/v1/recipes/:name/run
POST /api/v1/memory/store
POST /api/v1/memory/:agent_id/clear
POST /api/v1/memory/:agent_id/:key/delete
POST /api/v1/memory/:agent_id/vector-search
POST /api/v1/memory/:agent_id/decay
POST /api/v1/memory/:agent_id/:key/pin
POST /api/v1/conversations/:conv_id/delete
POST /api/v1/chat
POST /api/v1/chat/:id/message
POST /api/v1/persistence/flush
POST /api/v1/teams
POST /api/v1/teams/:id/members
POST /api/v1/teams/:id/mail
POST /api/v1/infra/maintenance/enable
POST /api/v1/infra/maintenance/disable
POST /api/v1/goals
POST /api/v1/goals/:id/cancel
POST /api/v1/acp/agents/:agent_id/message
POST /api/v1/marketplace/rate
POST /api/v1/marketplace/:name/:author/report
POST /api/v1/marketplace/reports/:id/dismiss
POST /api/v1/workspace/write
POST /api/v1/workspace/edit
PUT /api/v1/managed-settings
POST /api/v1/sessions
POST /api/v1/schedule/:id/pause
POST /api/v1/schedule/:id/unpause
POST /api/v1/providers/reload
POST /api/v1/skills
POST /api/v1/workflows/start
POST /api/v1/workflows/:id/cancel
POST /api/v1/workflows/:id/branch
POST /api/v1/workflows/:id/pause
POST /api/v1/workflows/:id/resume
POST /api/v1/recipes/reload
POST /api/v1/auth/login
POST /api/v1/auth/logout
POST /api/v1/infra/cache-invalidate
POST /api/v1/workspace/read
POST /api/v1/workspace/search
POST /api/v1/webhook/:channel_id
POST /api/v1/marketplace (publish — the same path serves browse on GET)
POST /api/v1/marketplace/feature
Every entry above is enforced at a handler/dispatch case cowboy_req:method gate that replies 405 (verified against
sol_http.erl’s enforced-POST dispatch guard and the per-module
handlers, ). One shape note for precision:
Follow-up: POST /api/v1/workers/bg/start +
POST /api/v1/workers/bg/:bg_id/kill were verb-agnostic (kill answered
ANY method) — both now join the enforced POST-only guard.
Deliberately NOT listed:
POST /api/v1/agents/:id/task (a body-parsing endpoint without a 405
verb check).
PUT /api/v1/managed-settings above is the list’s one non-POST entry,
kept because it is method-enforced to PUT.
Engine reference — generated from the canonical engineering source. Do not edit this page by hand.
CLI Reference
The zerg CLI is a LuaJIT binary (zero Python dependency, cli_commands=92 handler functions in AGENTS.counts) that communicates with the Sol server via its HTTP API.
Global Options
| Flag | Description |
|---|---|
--json | Output raw JSON instead of formatted tables |
--format FORMAT | Output format (text or json; an unknown value errors and exits 1 — a value is REQUIRED, --format followed by the command word is a usage error) |
--quiet | Strip ANSI styling (the flag is enforced at the output boundary; colors are ALREADY stripped when stdout is not a TTY, so --quiet only matters on a terminal) |
--bearer TOKEN | Bearer token for auth (global flag — must appear BEFORE the command). The value is visible to other users via ps/argv. |
--token TOKEN | Deprecated global auth form (use --bearer or the ZERG_TOKEN env var). Note: value is visible to other users via ps/argv. After the command name, --token belongs to the command (e.g. channel-add, which prints the same argv-visibility warning) and is never a global credential. |
--profile NAME | Use connection profile from config (login/logout apply to that profile) |
--api-url URL | Override API base URL. A stored token is sent only when its recorded origin matches the override (or an explicit --bearer/--token/ZERG_TOKEN is supplied) |
--verbose, -v | Verbose diagnostics. Transport traces pass a redacting debug receiver: Authorization/Cookie/Set-Cookie/Proxy-Authorization header values are replaced with [REDACTED], and request/response BODIES are never echoed (a size note replaces the bytes) — a credential can never reach stderr through --verbose. |
--version | Show CLI version |
--help | Show help text |
Global flags are only parsed before the command name (the first
positional argument); everything after the command is the command’s own
argv. --json, --format and --quiet are additionally honored after
the command name, and so are --api-url/--profile (see the
post-command connection rules below).
Flag syntax
Explicit arity. Boolean flags (--json, --no-stream, --keyring,
…) never consume the next token; value flags (--model, --api-url,
…) REQUIRE one. The documented forms work exactly as written:
run --model m --no-stream "prompt", login --keyring user@x,
show --json model.
A missing value is a usage error (exit 1): --api-url followed by
the command word — zerg --api-url status — is refused, never a
silent help-and-exit-0.
-- ends option parsing. Everything after it is positional:
zerg status -- runs, and a token that merely looks like a flag
(zerg status -- --json) is a positional argument, not a flag.
--bool=value is refused (--json=true → “does not take a
value”); value flags keep the = form (--format=json).
Family flags before the verb resolve against the verb:
update --json check and team mail --team list work — the first
non-flag token is the verb.
Post-command connection flags
--api-url after the command is an endpoint-only mutation: it
never reloads the stored credential, never clears the selected
profile, and an explicit --bearer keeps precedence
(zerg --bearer X status --api-url U sends X).
--profile after the command applies the full profile scope
(selecting a profile IS the credential-scope change).
The same flag before AND after the command is a conflict refusal
(exit 1, nothing dispatched); a pre-command --api-url cannot combine
with a post-command --profile.
Origin binding still guards the wire: an override endpoint never
receives a stored token minted for a different origin.
With --json, every failure — HTTP/API errors, argument/usage
validation, login 4xx, and dispatcher errors (unknown command/subcommand,
bad flag value) — emits exactly one
{"ok":false,"error":{"code","message"}} document on stdout. Invoking
only global flags (for example zerg --json) prints the help text and
exits 0. run/chat switch to the buffered request under --json
(token deltas are never interleaved with the document). JSON documents
are machine-boundary output: their string values are JSON-escaped for
structural safety but C1 control bytes (0x80–0x9F) are NOT stripped from
the decoded values — consumers that render them must apply their own
terminal sanitizer (the human path does: see the C1 strip below).
Connection profiles
--profile NAME selects a complete connection scope, not just a
hostname:
Endpoint: the profile’s api_url when set; otherwise the
top-level api_url / ZERG_API_URL / default. The active profile’s
URL is never used as a fallback for a different selected profile.
Credential: the profile’s token → ZERG_TOKEN (env). The
active/top-level config token and its token_keyring marker are out
of scope — zerg --profile dev status with a prod active profile
never sends the prod bearer. A profile without a token sends no
Authorization header (explicit no-token sentinel).
--bearer TOKEN before the command overrides every stored token and
applies within the selected scope.
Without --profile, connection resolution is unchanged (active profile
first, then the top-level config/env fallbacks). A token stored by
zerg login (no --profile) is the top-level credential;
zerg --profile NAME login stores that profile’s credential (including a
per-profile --keyring entry) and zerg --profile NAME logout revokes
and clears only that profile. A login records the origin it minted the
token for (token_origin), and that token is never replayed to a
different origin. A legacy token without a recorded origin is not sent to
an explicit --api-url override.
All commands accept --json for machine-readable output (streaming
run/chat/task output streams tokens by design — --json applies to
their non-streaming forms).
Health & Status
zerg status
Check server health (GET /api/v1/health).
zerg status
# Status: ok Models running: 3
zerg metrics
Show ETS-backed inference metrics (model lifecycle counters, requests, tokens, errors, durations) as a formatted table.
zerg metrics
Model Management
zerg discover
Scan NFS and local directories for GGUF model files.
zerg discover
# Discovered 12 models
zerg list
List all registered models with slug, family, quantization, and size.
zerg list
zerg ps
Show currently running inference processes.
zerg ps
zerg show <model>
Show detailed information for a specific model.
zerg show glm-4.7-flash
zerg start <model>
Start an inference model.
zerg start glm-4.7-flash
# With parameter template
zerg start glm-4.7-flash --template coding
# With parameter overrides
zerg start glm-4.7-flash --temp 0.3 --top-p 0.9 --batch-size 4096
| Flag | Type | Description |
|---|---|---|
--template | string | Parameter template: default, coding, chat, reasoning |
--temp | float | Override temperature |
--top-p | float | Override top-p |
--batch-size | int | Override batch size |
(No -t shorthand: the parser accepts single-dash tokens generically, but
start only reads --template.)
zerg stop <model>
Stop a running inference model.
zerg stop glm-4.7-flash
zerg stop-all
Stop all running inference models.
zerg stop-all
zerg prepare <model>
Sync a model from NFS to local disk via rsync.
zerg prepare glm-4.7-flash
Inference
zerg run <prompt> --model <model>
Run an OpenAI-compatible chat completion.
# Streaming (default)
zerg run --model glm-4.7-flash "Explain quicksort"
# Non-streaming
zerg run --model glm-4.7-flash --no-stream "What is 2+2?"
# With parameters
zerg run --model glm-4.7-flash --temp 0.3 --max-tokens 4096 "Write a fib function"
# With timeout
zerg run --model glm-4.7-flash --timeout 30000 "Long prompt..."
| Flag | Type | Description |
|---|---|---|
--model, -m | string | Model slug (defaults to default) |
--no-stream | flag | Return complete response (no streaming) |
--temp | float | Override temperature |
--max-tokens | int | Maximum tokens to generate |
--top-p | float | Override top-p |
--timeout | int | Request timeout in milliseconds (non-streaming only; 1–2147483; converted to seconds at the transport) |
--low-speed-time | int | Seconds of inactivity before a stalled stream aborts (default 60) |
--low-speed-limit | int | Bytes/s below which a stream counts as stalled (default 1) |
--verbose, -v | flag | Show token count after response |
Streams carry no total-transfer timeout — they abort on inactivity
instead: fewer than --low-speed-limit bytes/s for --low-speed-time
seconds. Raise both for slow-first-token reasoning models, e.g.
zerg run --model m --low-speed-time 300 --low-speed-limit 1 "...".
zerg chat <prompt> --model <model>
Chat via the Anthropic Messages API (/v1/messages).
# Streaming (default)
zerg chat --model glm-4.7-flash "Explain quicksort"
# Non-streaming
zerg chat --model glm-4.7-flash --no-stream "What is 2+2?"
# With system prompt
zerg chat --model glm-4.7-flash --system "Be concise" "Explain monads"
| Flag | Type | Description |
|---|---|---|
--model, -m | string | Model slug (defaults to default) |
--no-stream | flag | Return complete response |
--temp | float | Override temperature |
--max-tokens | int | Maximum tokens to generate (default 4096) |
--top-p | float | Override top-p |
--system, -s | string | System prompt |
--low-speed-time | int | Seconds of inactivity before a stalled stream aborts (default 60) |
--low-speed-limit | int | Bytes/s below which a stream counts as stalled (default 1) |
--verbose, -v | flag | Show token count/usage (usage on the non-streaming path: input=/output= token counts) |
Agent Workers
zerg agents
List all spawned agent workers.
zerg agents
zerg spawn
Spawn new agent worker(s).
zerg spawn
# Spawn multiple
zerg spawn --count 4
# With custom worker binary
zerg spawn --worker-path /opt/sol/etc/luna
| Flag | Type | Description |
|---|---|---|
--count, -n | int | Number of agents to spawn |
--worker-path | string | Path to worker binary |
Exit semantics. The command exits non-zero
when no worker was spawned — a 200 response whose results array is
empty or carries an error on every row is a FAILURE, not success. A
mixed batch (at least one success) is a documented partial success:
exit 0 and the spawned/failed counts in the output. Under --json
the all-failed case emits the standard {ok:false, error:{code: "spawn_failed", message}} document with spawned/failed beside it, and
a successful/mixed batch emits {ok:true, spawned, failed, items, total}.
zerg kill <agent_id>
Kill a running agent worker.
zerg kill agent-abc123
zerg task <agent_id> <prompt>
Dispatch a task to an agent worker.
# Streaming (default)
zerg task agent-abc123 "Fix the bug in main.rs"
# Non-streaming, poll for result
zerg task agent-abc123 --no-stream --wait "Fix the bug in main.rs"
| Flag | Type | Description |
|---|---|---|
--no-stream | flag | Queue task without streaming |
--stream | flag | Force SSE streaming |
--wait | flag | Poll for result (with --no-stream); Ctrl-C during the poll exits 130 |
--timeout | int | Poll budget for --wait in milliseconds |
--verbose, -v | flag | Show token count |
Both buffered forms (--wait and --no-stream) send stream:false in
the dispatch body — the server’s SSE default never answers a buffered
client. If a streamed dispatch is QUEUED server-side, Sol answers the
202 {status:"queued",task_id} JSON ack instead of a stream; the CLI
prints the queued state and follows the task to its terminal (same
contract as --wait).
With --no-stream --wait the CLI polls GET /api/v1/tasks/<id> and
exits by the task’s final status:
| Final status | Meaning | Exit |
|---|---|---|
pending, queued, in_progress | still running — keep polling | — |
ok, completed | terminal success | 0 |
cancelled, timeout, crashed, error | terminal failure | 1 |
| anything unrecognized | fails closed (never claimed as success) | 1 |
A 404 while the task’s first row/token is still landing is tolerated
for a bounded 10-second window (in-flight dispatch); past the window
it is a normal 4xx (exit 1). The --wait budget itself timing out
exits 1.
zerg task-cancel <task_id>
Cancel a running task.
zerg task-cancel task-xyz789
zerg task-status <task_id>
Get task status and result.
zerg task-status task-xyz789
Cluster
zerg cluster
Show cluster membership status.
zerg cluster
zerg catalog
Show the global model catalog across all cluster nodes.
zerg catalog
zerg join <node>
Join a cluster node.
zerg join sol@gpu-node-2
zerg leave
Leave the cluster.
zerg leave
Circuit Breaker
zerg circuits
List all circuit breaker states.
zerg circuits
zerg circuits-reset <key>
Force reset a circuit breaker to closed state.
zerg circuits-reset my-model
Plugin Workers
zerg plugin-eval <code>
Evaluate Lua code in a sandboxed Luerl worker.
zerg plugin-eval "return 1 + 1"
zerg plugin-workers
List all running Lua (Luerl) workers.
zerg plugin-workers
zerg plugin-spawn
Spawn a new Lua sandbox worker.
zerg plugin-spawn
# With default script
zerg plugin-spawn --script hello
| Flag | Type | Description |
|---|---|---|
--script | string | Default script to load |
ZMQ Workers
zerg zmq-workers
List connected ZMQ workers.
zerg zmq-workers
zerg zmq-dispatch <prompt>
Dispatch a task to a ZMQ worker.
zerg zmq-dispatch "Fix the bug" --model glm-4.7-flash
| Flag | Type | Description |
|---|---|---|
--model, -m | string | Model to use |
--context | string | Additional context |
zerg zmq-status
Show ZMQ gateway status (port, connected workers, queue depth).
zerg zmq-status
Scheduler
zerg schedule list
List all scheduled jobs.
zerg schedule list
zerg schedule add <prompt>
Create a scheduled job.
# Cron expression (every weekday at 9am)
zerg schedule add "Summarize yesterday's logs" --cron "0 9 * * 1-5" --name "daily-summary"
# Run at a specific time (epoch seconds)
zerg schedule add "Deploy model" --at 1777626000
# Run every 30 minutes
zerg schedule add "Health check" --every 1800 --name "health-check"
# One-time job (delete after run)
zerg schedule add "Generate report" --at 1777626000 --delete
| Flag | Type | Description |
|---|---|---|
--cron | string | Cron expression (min hour day month weekday) |
--at | int | Unix epoch seconds for one-time execution (tonumber-parsed — an ISO 8601 string is silently dropped) |
--every | int | Interval in seconds |
--name | string | Job name |
--model, -m | string | Model to use |
--delete | flag | Delete job after one run |
Exactly one schedule source is sent: --every wins over --cron, which
wins over --at (elseif chain in the handler).
zerg schedule show <job_id>
Show job details.
zerg schedule show 1
zerg schedule pause <job_id>
Pause a scheduled job. POST only.
zerg schedule pause 1
zerg schedule unpause <job_id>
Resume a paused job. POST only.
zerg schedule unpause 1
zerg schedule run <job_id>
Trigger immediate execution of a scheduled job.
zerg schedule run 1
zerg schedule delete <job_id>
Delete a scheduled job.
zerg schedule delete 1
Channels
zerg channels
List all registered delivery channels.
zerg channels
zerg channel-add
Register a delivery channel.
# Telegram channel (token is argv-visible — the command warns)
zerg channel-add --type telegram --token "BOT_TOKEN" --chat-id "CHAT_ID" --name "alerts"
# Discord channel (webhook)
zerg channel-add --type discord --webhook-url "https://discord.com/api/webhooks/..." --name "ops"
# Non-argv JSON config (file, or `-` for stdin)
zerg channel-add --type telegram --config-file /etc/zerg/telegram.json
printf '%s' '{"bot_token":"...","chat_id":"..."}' | zerg channel-add --type telegram --config-file -
# Inline JSON config (also argv-visible — the command warns)
zerg channel-add --type telegram --config '{"bot_token":"...","chat_id":"..."}'
| Flag | Type | Description |
|---|---|---|
--type, -t | string | Channel type: telegram (default), discord |
--token | string | Telegram bot token (required for --type telegram without --config) |
--chat-id | string | Telegram chat ID (required for --type telegram without --config) |
--webhook-url | string | Discord webhook URL (required for --type discord) |
--name | string | Channel display name |
--config | string | JSON config object (overrides --token/--chat-id/--webhook-url); argv-visible, warns |
--config-file | string | Read the JSON config from a file, or - for stdin (mutually exclusive with --config); no argv exposure |
: the advertised
--type webhookbranch is removed — the bundled plugin universe is telegram/discord/slack/teams, so awebhooktype could never load. When the server has no loaded backends (for exampleplugin_config_pathis unset)channel-addnow prints the server’s typed cause (HTTP 503channel_backends_unavailable) verbatim.
** (CL-20) /:** the
--token/-tbot token, the Discord webhook URL AND the inline--configJSON are all argv-visible to other users viaps— each carrier prints the loud visibility warning. The non-argv path is--config-file <path>(or--config-file -for stdin); the pre-fix guidance recommended--config, which was itself argv-visible. The channel request itself declares its body secret and forces the proxy bypass (NOPROXY=*), so the token never transits a configured (TLS-inspecting) proxy.
zerg channel-remove <channel_id>
Remove a registered channel.
zerg channel-remove ch-abc123
zerg channel-test <channel_id>
Send a test message to a channel.
zerg channel-test ch-abc123
zerg channel-send <channel_id> <message>
Send an arbitrary message to a channel.
zerg channel-send ch-abc123 "Deploy complete"
zerg channel-pause <channel_id>
Pause delivery for a channel (POST /api/v1/channels/:id/pause). The
channel row, its configuration and its queued history are kept; the
delivery worker skips it until channel-resume. --json returns the
server envelope.
zerg channel-pause ch-abc123
zerg channel-resume <channel_id>
Resume a paused channel (POST /api/v1/channels/:id/resume). Delivery
restarts on the next dispatch — messages emitted while paused are not
replayed. --json returns the server envelope.
zerg channel-resume ch-abc123
Recipes
zerg recipe-list
List available recipe templates.
zerg recipe-list
zerg recipe-show <name>
Show details for a specific recipe template.
zerg recipe-show incident-analysis
zerg recipe-run <name>
Run a recipe as a workflow.
zerg recipe-run incident-analysis
# With a JSON payload
zerg recipe-run incident-analysis --payload '{"alert_id":"42"}'
| Flag | Type | Description |
|---|---|---|
--payload | string | JSON object passed to the workflow as its initial payload |
zerg recipe-reload
Reload recipe templates from disk.
zerg recipe-reload
Skills
zerg skills
List all registered agent skills.
zerg skills
zerg skill-search <query>
Search skills by name, description, or tags.
zerg skill-search "code review"
zerg skill-register <file>
Register a skill from a JSON file.
zerg skill-register skill.json
zerg skill-remove <name>
Remove a registered skill.
zerg skill-remove my-skill
zerg skill install <name> <author>
Install a marketplace skill: calls POST /api/v1/marketplace/:name/:author/install,
writes the returned SKILL.md body atomically to
~/.luna/skills/remote/marketplace/<author>/<name>/SKILL.md and records
provenance.json ({source, version, fetched_at, author_uuid}) beside it, so
the existing skill-discovery path prompt-injects it. LUNA_SKILLS_ROOT (or
LUNA_HOME) relocates the target root.
Install atomicity. Both files are staged to
same-directory 0600 temp names (fsync’d) before either is published;
SKILL.md is renamed into place first and provenance.json last. If
provenance cannot be staged nothing is published; if its publish fails the
just-published SKILL.md is removed, so skill discovery never observes a
half-install.
zerg skill install code-review 8f0c...-author-uuid
Team Mail
The member-readable team mailbox is server-complete;
these two verbs are its operator surface. Both hit the EXISTING routes
(GET/POST /api/v1/teams/:id/mail) — no new store. Reads require the
caller to be a team member (or creator/admin); sends require the
creator/admin mutator gate (teams:manage on the wire). The default list
is TEAM-WIDE for a member (the authorized visibility contract — mail is
addressed, not access-controlled per addressee); callers can narrow with
the server’s ?mine=1 poll (the CLI lists the team view).
zerg team mail list --team <id>
List the team’s mail, oldest first, as the server renders it
(id, from_kind:from, to, priority, subject, body, status).
--json prints the raw {ok, messages} envelope.
zerg team mail list --team team_ab12cd
zerg team mail list --team team_ab12cd --json
zerg team mail send --team <id> --to <member> --body <text>
Send mail into the team mailbox. --to accepts a member worker id, a
user uuid (resolved to the member’s worker id server-side), or all
(default). Optional: --subject <text>, --priority high|normal|low.
zerg team mail send --team team_ab12cd --to member-w1 \
subject status --body "report when done"
Reply semantics: a received mail carries a sender struct
(from_kind/from_id); reply by passing the struct’s id as --to — the
server resolves user uuids to the member worker id at send time.
Local Analytics
Read verbs over Luna’s local usage ledger, ~/.luna/analytics.db (written
by the agent/ZMQ worker; 90-day retention). The DB is read
Read-only — these commands never create or migrate it; a missing
ledger is a typed error naming the path. Override the path with --db
(e.g. a worker’s mounted home), the window with --days N (default 7).
zerg analytics summary
Tool call counts/latencies, model selection counts, and token/cost totals over the window.
zerg analytics summary
zerg analytics summary --days 30
zerg analytics top-tools
Tools ranked by call count (all time in the ledger); --limit N caps the
list (default 10).
zerg analytics top-tools --limit 5
zerg analytics cost
Daily token cost over the window (one row per YYYY-MM-DD).
zerg analytics cost --days 14
All three accept the global --json for machine consumption.
Keyring
zerg keyring-test
Check which OS keyring backend is available.
zerg keyring-test
No backend is a failure: exit 1, and under --json the one failure
document carries error.code = "keyring_unavailable" (,
). The keyring path has no pkill/killall dependency —
the bounded-run watchdog uses only POSIX shell builtins plus sleep and
signals only the exact PIDs it forked.
zerg keyring-set <provider>
Store an API key for a provider in the OS keyring.
zerg keyring-set anthropic
The key is read via a hidden prompt. The legacy --key KEY form still
works but prints a deprecation warning — the value is visible to other
users via ps/argv, exactly like the deprecated --password/--token
forms.
The store is verified by the backend command’s real exit status
the secret goes to the backend over stdin (it never
appears in argv) and a failed secret-tool/security write exits
non-zero and is reported — never printed as success.
zerg keyring-get <provider>
Retrieve a stored API key (masked display).
zerg keyring-get anthropic
Keys shorter than 16 characters are fully masked (****); longer keys
show only their first and last four characters.
zerg keyring-delete <provider>
Remove a stored API key from the keyring.
zerg keyring-delete anthropic
Auth
zerg login <account>
Login to Mango auth service.
zerg login user@example.com
| Flag | Type | Description |
|---|---|---|
--email, -e | string | Account (the positional <account> is the same thing) |
--password | string | Deprecated — argv-visible via ps; omit to get the hidden prompt |
--keyring | flag | Store the bearer in the OS keyring instead of the config file |
--password on the command line is argv-visible to other users (ps) and
deprecated — omit it and the CLI prompts with echo hidden (or set the
token via zerg login’s response and ZERG_TOKEN for API calls).
Pass --keyring to store the bearer in the OS keyring (libsecret’s
secret-tool on Linux, macOS Keychain — the same backends as
zerg keyring-set) instead of the config file:
zerg login --keyring user@example.com
Prefixing the global --profile NAME stores the credential in that
profile instead of the top level; the matching --profile NAME logout
revokes and clears the same profile only:
zerg --profile staging login user@example.com
zerg --profile staging logout
Token storage truth
By default the login bearer is stored in plaintext in
~/.zerg/config.json. The file is created 0600 from birth (the umask
can only remove bits) and the atomic-save path fsyncs before rename — but
the token itself is not encrypted. On Linux x86_64 the CLI additionally
stat-probes the file and warns when it is world-readable; every other
platform skips that probe silently (a warn-only check must never read a
foreign struct stat layout), so the permission warning is a no-op off
Linux x86_64. Keep the config directory access-controlled.
zerg login --keyring is the migration path out of the plaintext: the
token goes to the OS keyring and the config keeps only a
token_keyring: true marker (never the token). A keyring write failure
fails the login loudly — the real backend exit status is checked, the
token_keyring marker is not written, and the plaintext fallback
never happens. zerg logout clears the keyring entry
and the marker together.
zerg login exits by the documented HTTP contract:
2xx → 0, 4xx → 1, 5xx → 2, a transport failure or a local
credential-transport refusal → 3.
zerg logout
Logout from Mango auth.
zerg logout
Prints Logged out (exit 0) after a 2xx remote revoke;
Not logged in (exit 0) with no stored token. The local credential
clear always runs first: a failed remote revoke prints
Logged out (remote logout failed: …) /
Logged out (server returned N) and exits by the documented HTTP
contract — 4xx → 1, 5xx → 2, a transport
failure or a local credential-transport refusal → 3 — so scripts can
tell the remote token may still be live.
Admin
The two documented-outage Mango token-admin verbs. Both require an
Admin-bearer for Sol (the routes are {admin, require}-scoped at the
middleware and re-checked inline) and are strict-audited: a 200 is only
answered once the audit entry has landed (503 audit_unavailable
otherwise). Sol performs the Mango mutation with its service principal —
zerg never talks to Mango directly.
zerg admin unlock <user_uuid>
Clear a Mango account lockout (the hard lockout window).
zerg admin unlock 11111111-2222-3333-4444-555555555555
# Account unlocked: 11111111-2222-3333-4444-555555555555
POST /api/v1/admin/users/:user_uuid/unlock. The uuid is shape-checked
server-side (400 invalid_user_uuid); an unknown user is 404 not_found;
a Mango-side admin-plane failure is fail-closed 503 mango_admin_unavailable (never a fake success).
zerg admin revoke-token <token_id>
Revoke one Mango token by its persisted SHA-256 id (the 64-hex id from the
service-token listing, GET /auth/service-tokens).
zerg admin revoke-token 0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef
# Token revoked: 0123…cdef
POST /api/v1/admin/tokens/:token_id/revoke. 400 invalid_token_id on a
malformed id; 404 not_found for an unknown id; 503 on an audit or
Mango-admin outage. Use this for rotation hygiene after a leak or a
deprovisioned host.
Both verbs are also available directly over the API with the same bodies —
see docs/api-reference.md.
OAuth Providers
Browser PKCE login for declarative providers that carry an oauth sub-map
in their provider JSON. Requires an admin-bearer; Sol holds the PKCE
verifier and performs the code exchange (POST /api/v1/oauth/login, then
POST /api/v1/oauth/login/complete) and persists the access+refresh
tokens server-side (0600, Sol’s data dir). resolve_api_key consumes
them; a provider 401 refreshes via the pool’s auth-class report path, and
a background tick renews tokens near expiry. The code exchange is a
body-carried credential: the CLI forces the proxy bypass for it (see the
proxy residual below). The printed authorize URL is validated and
terminal-sanitized BEFORE anything is written — a hostile
(C1/OSC-bearing) URL is refused with zero bytes emitted.
zerg oauth login <provider>
zerg oauth login my-idp
# Authorize my-idp by opening: https://idp.example/authorize?...
# Connected my-idp
Opens the authorize URL (best-effort xdg-open/open; --no-browser
prints only) and binds the provider’s loopback redirect URI for the
callback. --timeout N caps the wait (default 180s). The CLI refuses to
bind a non-loopback redirect URI.
zerg oauth status
List providers with a stored token (GET /api/v1/oauth/providers).
zerg oauth logout <provider>
Delete the stored token (DELETE /api/v1/oauth/providers/:provider,
strict-audited); the provider falls back to keyring/env resolution.
Air-gap: this flow needs browser + IdP reachability — use
zerg keyring-set / api_key_env on air-gapped fleets (see
docs/security.md).
Background Workers
zerg bg-workers start <task>
Start a background worker session.
zerg bg-workers start "Analyze the codebase"
The <task> text is sent as the server-side prompt field; a missing or
empty prompt is answered 400 (prompt required) by the server.
zerg bg-workers list
List all background workers.
zerg bg-workers list
zerg bg-workers status <id>
Show background worker status.
zerg bg-workers status bg-abc123
zerg bg-workers logs <id>
Show background worker output logs.
zerg bg-workers logs bg-abc123
zerg bg-workers kill <id>
Kill a background worker.
zerg bg-workers kill bg-abc123
Workflows
The workflow family manages running workflow instances (started
directly or via zerg recipe-run). All subcommands take their target as
a positional argument and no command-specific flags; --format text
(the default) renders the top-level scalar fields as key: value lines,
while --format json prints the full payload.
zerg workflow list
List all workflows.
zerg workflow list
zerg workflow start <name>
Start a workflow by recipe/template name.
zerg workflow start incident-analysis
zerg workflow show <id>
Show a workflow’s details and current state.
zerg workflow show wf-abc123
zerg workflow cancel <id>
Cancel a running workflow.
zerg workflow cancel wf-abc123
zerg workflow branch <id>
Branch a workflow (no flags — the server derives the branch).
zerg workflow branch wf-abc123
zerg workflow tree <id>
Show the workflow step tree. The tree is deeply nested — in --format text only top-level scalars render, with a pointer at --format json.
zerg workflow tree wf-abc123
zerg workflow tree wf-abc123 --format json
zerg workflow lineage <id>
Show the workflow’s execution lineage (ancestry across branches).
zerg workflow lineage wf-abc123
Session shares
zerg session share --file <path> | --data <string> [--format FMT] [--ttl-days N]
Mint a share link from exported session data (POST /api/v1/sessions).
session_data is a string on the wire (see docs/sessions.md):
--file reads it verbatim, --data passes the literal — --data puts
the payload (which can carry private transcript content) on the argv
where every local user can read it via ps, so the command prints the
same loud visibility warning the credential flags carry; prefer --file.
--format and --ttl-days are forwarded to the server’s
quarantine/expiry policy. Prints the server’s url when the response
carries one, otherwise the share_id (the client constructs the link).
--json returns the server envelope.
zerg session share --file session-export.json --ttl-days 7
zerg session share --data '{"messages":[]}' --format json
Updates
Update channel
The zerg update commands resolve a release channel per invocation:
| Priority | Source | Key | Values |
|---|---|---|---|
| 1 | Environment | ZERG_UPDATE_CHANNEL | forgejo (default) | github |
| 2 | Config (~/.zerg/config.json) | update_channel | forgejo (default) | github |
| 3 | Built-in default | — | forgejo |
The default channel is Forgejo because that is where releases are
actually published: the CD pipeline (.crow.yml publish-release →
wild’s publish-release.sh) uploads release assets (zerg CLI, luna,
sol-<ver>.tar.gz, SHA256SUMS, minisign signatures) to the RELEASE
forge (git.zergs.net). The retired dev mirror git.nonsense.ws is not the
release origin. The latest-release endpoint is
https://git.zergs.net/api/v1/repos/spacebeam/zerg/releases/latest.
GitHub is an explicit override for operators who mirror releases
there: set update_channel: "github" in ~/.zerg/config.json (or
ZERG_UPDATE_CHANNEL=github in the environment). The GitHub channel
queries https://api.github.com/repos/anomalyco/zerg/releases/latest.
The repository defaults per channel (spacebeam/zerg for forgejo,
anomalyco/zerg for github) can be overridden with update_repo in the
config or ZERG_UPDATE_REPO in the environment (both apply to whatever
channel is active). An explicitly configured channel that is neither
forgejo nor github is refused loudly — the updater never silently
falls back to a different distribution.
zerg update check
Check for available updates.
zerg update check
zerg update download
Download the latest release.
zerg update download
Downloads into a private 0700 staging directory ( — the old
world-readable /tmp/zerg-update-<ver>.tar.gz path was a local
swap/root-write target). The channel is authenticated and integrity
checked (, — the old “integrity only, no authenticity”
caveat was closed): the release must carry a minisign detached signature
(*.minisig) which is verified against a TOFU-pinned key at
~/.config/zerg/trusted-key before anything is extracted — the first
verified install pins the release’s minisign.pub asset (fingerprint =
SHA-256 of the raw Ed25519 public key), subsequent updates must match the
pin, key changes are refused, and unsigned releases are refused outright.
Integrity is additionally verified against the same-origin SHA256 asset;
a release missing either the signature or the SHA256 asset fails closed.
zerg update trust-key <minisign.pub> is the deliberate re-pin escape
hatch (see below).
zerg update apply
Apply a downloaded update.
zerg update apply
Re-verifies the SHA256 and re-runs the minisign signature verification
of the exact file about to be extracted (the TOFU-pinned key is consulted
again at apply time — a stale or swapped staging artifact cannot pass
integrity alone; ) and rejects archives containing anything
but regular files/directories (symlinks, hardlinks, devices, fifos,
../absolute paths, control characters are all refused — ).
The install root is never a baked-in default: /opt/zerg is
the legacy Sol root and /opt/sol the current one, so applying a CLI
update there could replace Sol (or plant a parallel tree). The updater
derives the root from the running zerg executable when it is a real
installed layout (zerg + VERSION siblings) and refuses /opt/zerg or
any directory carrying bin/sol; pass --install-dir DIR for any other
layout:
zerg update apply --install-dir /opt/zerg-cli
The current version comes from <root>/VERSION, falling back to the
version embedded in the running binary. The installed tree is moved
aside to <root>.<timestamp>.bak before the new tree is installed; the
post-install probe execs the INSTALLED binary (--version + an offline
completion render) and a failure rolls back automatically.
--install-dir is a VALUE at the command layer — a
valueless/empty flag is refused before anything resolves — and the value
must be ABSOLUTE. It is canonicalized (realpath + lexical pass; an
explicit .. segment is refused) before the guard checks, so
/opt/./zerg, /opt//zerg, /opt/zerg/ and symlink aliases cannot
dodge the legacy-root or bin/sol verdicts.
Install-root containment. The update
dance renames, RENAME_EXCHANGEs and rm -rfs the root, so an EXISTING
--install-dir must be a real CLI install (zerg + VERSION siblings)
or an empty directory (an explicit fresh-install target); an existing
non-install tree, the home directory, and filesystem roots (/, /home,
/usr, /tmp, …) are refused before any destructive step. A
non-existent root is accepted only when its parent exists.
Staging reclamation. A successful apply
removes the downloaded artifact and its private staging directory; a
FAILED apply keeps them for retry. Repeated/abandoned downloads are
bounded: update download sweeps stale /tmp/zerg-update.* trees (age
7 days, or beyond the newest 8 after a 1-hour grace) before minting a
new staging dir.
Corrupt TOFU pin: a pin file that EXISTS but cannot be parsed (truncated, non-hex fingerprint, garbage) is a typed corruption refusal — the updater never treats it as “no pin” and never re-pins silently from the channel. Recovery is exactly
zerg update trust-key <minisign.pub>.
zerg update rollback
Rollback to the previous version.
zerg update rollback
Restores the newest <root>.*.bak tree, most-mtime-first (same root
resolution/refusals as apply; --install-dir overrides — same
absolute/canonical contract). Note when
that tree exists: a successful apply deletes its backup after the
post-install health check passes, and a failed health check consumes it
for the automatic rollback — so a leftover .bak normally exists only
after an interrupted apply (crash between the install swap and
cleanup). With no backup present the command fails with
no backup found (exit 1).
zerg update trust-key <minisign.pub>
Deliberately re-pin the release signing key (TOFU override). Any auto-detected key change is refused by the updater; this command is the explicit operator acknowledgement that the signing key has rotated:
zerg update trust-key /path/to/new/minisign.pub
The dashed
trust-keysubcommand is dispatched explicitly (main.luamaps it tocmd_update_trust; closed a dispatch regression that briefly made the subcommand unreachable — regression suitezerg-cli/tests/test_zcli_update_dispatch.lua). The updater’s own key-change refusals direct operators to this exact command line.
Diagnostics
zerg doctor
One-command verdict for an incident: CLI version, resolved API URL,
GET /health, and GET /api/v1/ready (a 503 names the failing check
family). Exit 0 only when both probes are healthy; --json emits the same
facts as one document. It is safe to run with no credential.
zerg doctor
zerg doctor --json
zerg support-bundle [output_dir] [--log-dir DIR]
Writes a redacted support bundle for an incident report:
version.txt — CLI + platform;
environment.txt — only ZERG_*/SOL_*/LUNA_*/MANGO_* environment
keys, with secret-keyed values replaced by <redacted> and URL/DSN
userinfo (postgres://user:pass@host/db) replaced by
postgres://<redacted>@host/db;
config.json — the loaded CLI config with secret-keyed values redacted
(tokens never written);
health.json — API URL, /health, /ready and /api/v1/infra/status
(best-effort; an offline node still produces the local half);
logs/*.tail — bounded tails of the discovered Sol/Mango runit logs and
$SOL_DATA_DIR/logs, line-scrubbed;
manifest.json — generation time, version and the file list.
The output directory is created exclusively — it must not already exist. An existing path (a home directory, a project tree, a mounted volume) is refused with a non-zero exit and is never written into or deleted. On a scan refusal or any write failure, only the files created by that run are removed.
A secret scan runs before the bundle is published: if any collected secret
value, credential-bearing URL userinfo, value-shaped token (for example
sk-…, ghp_…, AKIA…, xoxb-…, a JWT) or private-key block is found,
the partially written bundle is removed and the command refuses
(non-zero). Never attach a bundle that contains a secret you did not
expect.
zerg support-bundle /tmp/zerg-support
zerg support-bundle /tmp/zerg-support --log-dir /var/log/runit/zerg-sol
Shell Completion
zerg completion <shell>
Output shell completion script for bash, zsh, or fish.
zerg completion bash > /etc/bash_completion.d/zerg
zerg completion zsh > ~/.zfunc/_zerg
zerg completion fish > ~/.config/fish/completions/zerg.fish
The <shell> argument is optional: with no argument the script is chosen
from $SHELL (fish/zsh detected, bash otherwise). An unknown shell
errors (Unknown shell: … (supported: bash, zsh, fish)) and exits 1.
The generated scripts mirror the parser grammar: flags
are offered PER COMMAND from the parser’s closed grammar (with the
documented short forms — -m, -s, -t, -v, -n, -e) instead of
the old every-flag-on-every-command dump; --bearer/--token/--api-url/
--profile/--format complete ONLY before the command word (where the
parser accepts them); the universal set (--json, --quiet, --help,
--version, …) completes everywhere.
Air-Gapped Deployment
For offline environments, deploy WILDZERG (the on-prem variant) via the
Wild blueprint — see wild/AGENTS.md (§“CD Build Execution”) and
wild/scripts/provision/. The legacy
deployment/infra/scripts/setup.sh --air-gapped was archived with the old
on-host deploy model and no longer exists.
Security: credential transport
The CLI refuses to send credentials (bearer tokens, login passwords) over
plaintext http:// to a remote host. The accepted transport matrix
(for the initial request):
| Target | Allowed with credentials |
|---|---|
https:// | yes (default) |
http:// strict loopback (localhost, 127.0.0.0/8 with valid octets, [::1], [::ffff:127.0.0.1]) | yes (local dev) |
http:// remote host | only with ZERG_ALLOW_INSECURE=1 (loud warning printed) |
userinfo-bearing URL (http(s)://user@host) | never — refused even with ZERG_ALLOW_INSECURE=1 unless the real host is loopback |
The loopback classifier is exact: 127.evil.com, the
userinfo trick (http://127.0.0.1@evil.com) and arbitrary bracketed IPv6
literals ([2001:db8::1], [::ffff:8.8.8.8]) are all refused — the
Pattern matcher accepted them.
Authenticated requests additionally walk redirects manually instead of
letting curl auto-follow (curl replays every header verbatim to the
redirect target). Per-hop rule: the Authorization
header is stripped on any cross-origin hop — a change of host OR scheme
with one warning per request on the first strip. The former loopback
exception is closed: a remote 302 to localhost used to deliver
the bearer to the loopback target; it now strips like any cross-origin hop.
Same-origin hops (same host AND same scheme) keep the header; a port change
alone is not an origin change.
| Redirect hop (carrying Authorization) | Bearer |
|---|---|
| https → https, same host | kept |
| https → https, cross host | stripped |
| https → http, same host | stripped (scheme change) |
| https → http, cross host (incl. loopback targets) | stripped |
| http → https, same host (upgrade) | stripped (scheme change) |
| http → http, same host | kept |
| http → http, cross host | stripped |
Redirect body policy — browser-default for every
walked request, uniform, with no per-caller opt-in (the
credential_body knob is removed; the chat/stream path is covered by the
same policy, ):
| Redirect | Behavior |
|---|---|
| 301 / 302 / 303 | method drops to GET, body discarded (browser-equivalent) |
| 307 / 308, same origin | method + body preserved (re-POST) |
| 307 / 308, cross-host | refused before any hop-2 request |
| 307 / 308, https→http downgrade | refused before any hop-2 request |
follow_redirects = true on a credential-carrying request is refused
an explicit true used to silently re-enable curl’s
verbatim header replay. The manual walk is the only redirect mode for
authenticated requests; credential-less callers may still pass it.
Capture caps: response-header capture aborts past
256 KiB total / 128 header lines with a loud error (a hostile endpoint
could previously stream unbounded unique headers past the 32 MiB body cap);
SSE streams fail closed when a single line exceeds 1 MiB without a
newline. The header callback receives RAW lines, so obs-fold continuation
lines (>16 KiB permitted by RFC 7230) and interim 1xx header blocks each
count toward both ceilings — a folded-header flood is capped by the same
budget. Lines that do not parse as key: value (status lines,
continuations) are never written into the header map, so an interim block
cannot inject a forged Location.
Proxy bypass for body secrets: every request whose
BODY carries a credential — the login password, a channel-add bot
token/webhook URL, the OAuth code exchange — forces NOPROXY=* in
addition to the manual redirect walk (the pre-fix bypass keyed only on
the Authorization header, so body secrets transited any configured
proxy). Residual: a TLS-terminating (TLS-inspecting) or malicious
proxy can still read any authenticated traffic it terminates — bypassing
the proxy removes the passive-HTTP-proxy exposure (a plain HTTP forward
proxy sees only the CONNECT target); if your network REQUIRES a
TLS-inspecting proxy, that operator is in the credential path by
construction. The transport matrix above (https-or-loopback for
credentials) still applies end to end.
Terminal sanitizer: the human output boundary
(ansi_sanitize/term_safe) strips ESC-introduced sequences AND the
8-bit C1 forms (0x80–0x9F, e.g. 0x9B CSI / 0x9D OSC on a non-UTF-8 or
C1-capable terminal) plus invalid UTF-8 byte sequences; valid multibyte
text round-trips byte-exact. JSON documents (--json) are structural
boundaries: values are JSON-escaped, not C1-stripped — consumers that
render them must sanitize (that is the documented raw-document choice).
Read-side hardening: config.json, the analytics DB
probe, the TOFU pin and the update-dest state file are read through the
protected contract — open(2) with O_NOFOLLOW (a planted symlink is a
typed refusal, never followed) and O_NONBLOCK (a planted FIFO
cannot hang the open), plus regular-file + owner checks where the
platform stat probe exists. Platform gap: the struct-stat layout is
probed only on Linux x86_64 — on macOS and other architectures the
regular-file/owner layer is skipped and the O_NOFOLLOW/O_NONBLOCK
refusals are the only active read-side layers (documented residual).
Exit codes & response envelopes
Every command exits by the documented contract — scripts gate on the exit status, so the status is truth:
| Exit | Meaning |
|---|---|
0 | Success |
1 | The server answered 4xx (client error — bad request, not found, unauthorized), or a 2xx response carried a non-JSON body |
2 | The server answered 5xx (server error / upstream failure) |
2 | An SSE stream carried the typed server terminal event: stream_error — the stream-side server-error class; the frame’s reason is printed on stderr |
3 | The request never completed — connection refused, curl abort, transfer truncation, or a local credential-transport refusal |
Before every failure exited 0 or 1 indiscriminately: a 404/500
whose body was valid JSON without an error key parsed as a success
table. Streaming commands classify the same way — the SSE readers
return the status class they captured (4xx → 1, 5xx → 2, transport/
truncation → 3), plus the typed stream_error terminal (exit 2; a
defensive arm — no Sol route the CLI streams emits it today).
Paginated envelope. Sol answers every paginated list route with
{"items": [...], "total": N, "limit": …, "offset": …, "page": …, "total_pages": …, "has_more": …}. The CLI unwraps this envelope once,
inside the API layer — list commands (list, ps, agents, catalog,
circuits, channels, skills, skill-search, schedule list,
zmq-workers, plugin-workers, spawn, workflow list,
bg-workers list) render their rows directly. --json output stays
Envelope-truthful: it prints the full {items, total,...} wire shape,
never a bare array.
Luna completion entry
client/run --complete is Luna’s FIM entry for editor ghost text. It is not
a zerg CLI command, and it never calls a lane endpoint or ollama — the only
network surface is Sol’s POST /v1/completions.
stdin: one JSON object {"prefix", "suffix", "model?", "max_tokens?", "stop?", "temperature?"}
stdout: raw completion text (no JSON envelope; no added newline)
stderr: typed error, non-zero exit (H1 silent-failure contract)
Endpoint/credential: ZERG_API_URL (full base) wins; otherwise
SOL_HOST/SOL_HTTP_HOST + SOL_HTTP_PORT (loopback http, off-loopback
https). Bearer: SOL_TOKEN → SOL_API_KEY → MANGO_TOKEN; the token is
never logged. Plaintext credential transport is loopback-only unless
ZERG_ALLOW_INSECURE=1.
Empty prefix: no request, no output, exit 0.
Truncation: prefix keeps its tail, suffix its head (defaults 8000/1000
bytes, ZERG_COMPLETE_MAX_PREFIX_BYTES/_SUFFIX_BYTES, 0 = unlimited);
cuts never split a UTF-8 codepoint.
Stop/overlap: stop (string or array of at most 4 strings) cuts the
completion and the stop text is not returned; a completion tail duplicating
the suffix head is removed; CRLF is normalized to LF; trailing whitespace is
trimmed. max_tokens is clamped to the server ceiling (1024).
Refusals: HTTP/auth/transport failures are typed on stderr with a
non-zero exit. A server refusal code is preserved (e.g. fim_unsupported
for a non-FIM model, lane_warming on a cold lane).
Options: --model/-m MODEL (otherwise request model, then
ZERG_COMPLETE_MODEL, then the Sol default) and --max-tokens N.
Sol-less hosts: typed refusal until the standalone leg lands; there is
no client-side lane/ollama fallback.
printf '{"prefix":"def add(a, b):\\n ","suffix":""}' | client/run --complete
Luna TUI Slash Commands
These commands are available inside the Luna TUI (prefixed with /).
Agent Modes
| Command | Description |
|---|---|
/modes | List all available agent modes |
/mode <name> | Switch to a specific mode |
/build | Switch to Build mode |
/plan | Switch to Plan mode |
/explore | Switch to Explore mode |
/review | Switch to Review mode |
/general | Switch to General mode |
/menu, /m | Open mode selection menu |
Permission Modes
| Command | Description |
|---|---|
/auto | Enable AI classifier permission mode |
Session
| Command | Description |
|---|---|
/new | Start a new session |
/compact | Manually trigger context compaction |
/compact --from <id> | Compact messages before the specified entry |
/compact --up-to <id> | Compact messages up to and including the specified entry |
/copy | Copy last assistant message to clipboard |
/copyall | Copy entire session to clipboard |
/export [path] | Export session to file |
/delete | Delete the current session’s whole corpus (primary, rotations, trajectory, SQLite rows, index entry) and start a fresh session |
/gc | Dry-run the opt-in session-corpus GC (lists eligible sessions; deletes nothing) |
/gc run [DAYS] | Apply the session-corpus GC older than DAYS (default: session_gc.max_age_days). Explicit run is required |
/tree | Show session branch tree |
/branch [name] | Create a session branch |
/switch <name> | Switch to a session branch |
Display
| Command | Description |
|---|---|
/clear | Clear chat display |
/theme <name> | Switch color theme (default, onedark, solarized, monokai) |
/thinking <level> | Set thinking display (none, minimal, low, medium, high, xhigh) |
/keymaps | Display all key bindings |
Information
| Command | Description |
|---|---|
/status | Show agent status (model, mode, cost, iterations) |
/cost | Show cost tracker summary |
/model [name] | Show or switch model |
/history | Show session history |
/mcp | Show MCP server status |
/tools-list | List all available tools (built-in + discovered) |
/tools-reload | Rescan workspace for custom tools |
Control
| Command | Description |
|---|---|
/interrupt | Interrupt current agent execution |
/help, /h | Show help |
/quit, /exit, /q | Exit Luna |
Engine reference — generated from the canonical engineering source. Do not edit this page by hand.
Tool Reference
Luna registers 92 built-in tools from the tool loader (core/tools/_loader.lua) on a fully-provisioned host. Registration is probe-honest per tool: 51 tools register unconditionally, 19 register only when their backing binary is detected at startup (13 general + the 6 desktop-environment tools), 10 register when their Lua module loads, and 12 computer-use tools are gated on a real display probe plus a required-binary census. The 74 non-computer-use built-ins are therefore 51 always + 13 binary-probed + 10 module-probed; the remaining 18 are the 12 computer-use + 6 desktop-environment probe-conditional block. computer_use_force = true overrides the CU display gate for the rare remote-X posture — the tools then register and their handlers fail typed on absent binaries (the runtime refusal stays as defense-in-depth). Every condition is recorded in the registration_probe census of ci/tools_manifest.json, machine-checked against the registration source by ci/tools_manifest_lint.py, and the taxonomy numbers above are derived from that census by ci/tools_taxonomy_parity_lint.py (no hand-copied counts). Dynamic MCP tools (mcp__), workspace custom tools (custom__), and plugin tools (plugin__) join these at runtime. All built-ins are prefixed builtin__ on the wire; the bare name shown below is accepted as an alias. Permission modes and per-mode rulesets control which tools are available (see permissions.md).
File Operations
bash
Execute shell commands in the working directory.
| Parameter | Type | Required | Description |
|---|---|---|---|
command | string | Yes | Shell command to execute |
timeout | number | No | Timeout in milliseconds (clamped to tool_timeout_max_ms, default max 600000) |
Default timeout is config.tool_timeout_ms (60000 ms when unset); the model-supplied value is clamped to a floor of 1 ms and a ceiling of tool_timeout_max_ms (default max 600000 ms)
Output limited to 16KB (truncated beyond that)
Runs in the current working directory
Exit code included in result
Commands run through the command policy (core.command_policy) — denied commands fail with Command blocked by policy
Example:
> Run `git status` to check for uncommitted changes
read_file
Read file contents with optional line range. Automatically detects image files and returns base64-encoded content blocks for vision-capable models.
| Parameter | Type | Required | Description |
|---|---|---|---|
path | string | Yes | Absolute file path |
offset | number | No | Starting line number (1-indexed) |
limit | number | No | Maximum lines to read |
Image files are returned as vision content blocks only when the current model supports vision; otherwise a (binary image file:...) placeholder is returned
Paths outside the workspace boundary are rejected
The current file content is pushed onto the undo stack before a later edit
write_file
Create or overwrite a file atomically.
| Parameter | Type | Required | Description |
|---|---|---|---|
path | string | Yes | File path |
content | string | Yes | File content |
Max size: 10MB (MAX_WRITE_SIZE)
Uses atomic write (mkostemp in the target directory, then rename)
Paths outside the workspace boundary are rejected
Queued through the mutation queue to prevent race conditions
Pushes prior content onto the undo stack; git snapshots are debounced after mutating tools complete
edit_file
Search and replace in an existing file. Tries exact match first, then fuzzy matching (whitespace normalization, indentation, single-line fuzzy).
| Parameter | Type | Required | Description |
|---|---|---|---|
path | string | Yes | File path |
old_text | string | Yes | Text to find |
new_text | string | Yes | Replacement text |
replace_all | boolean | No | Replace all occurrences instead of requiring uniqueness |
With replace_all unset, exact matches must be unique; otherwise the fuzzy matcher (core.fuzzy_match) runs language-aware strategies and reports which strategy matched
Fuzzy edits are written via atomic tmp + rename
Fails with old_text not found in file (exact and fuzzy) when nothing matches
Queued through the mutation queue to prevent race conditions
Pushes prior content onto the undo stack
multi_edit
Edit multiple files atomically in a single tool call. If any edit fails, all changes are rolled back.
| Parameter | Type | Required | Description |
|---|---|---|---|
edits | array | Yes | Array of edit objects |
Each edit object:
| Field | Type | Required | Description |
|---|---|---|---|
file_path | string | Yes | Path to the file |
old_string | string | Yes | Text to find |
new_string | string | Yes | Replacement text |
Each file’s original content is backed up before editing; a failure restores every backup All edits are applied atomically — partial failures roll back all changes
apply_patch
Apply a unified diff patch to files.
| Parameter | Type | Required | Description |
|---|---|---|---|
patch | string | Yes | Unified diff text |
Applies hunks atomically per file
list_directory
List files and directories in a given path.
| Parameter | Type | Required | Description |
|---|---|---|---|
path | string | Yes | Directory path |
Returns one name (type) entry per line
Does not recurse into subdirectories (use glob_search with ** for recursive listing)
create_directory
Create a directory and any necessary parent directories (like mkdir -p).
| Parameter | Type | Required | Description |
|---|---|---|---|
path | string | Yes | Directory path |
Creates all intermediate directories if they don’t exist
delete_file
Delete a file from the filesystem.
| Parameter | Type | Required | Description |
|---|---|---|---|
path | string | Yes | Path to delete |
Deletes files (an empty directory is removable via os.remove; a non-empty directory fails)
Queued through the mutation queue to prevent race conditions
notebook
Read and edit Jupyter notebook cells (.ipynb files).
| Parameter | Type | Required | Description |
|---|---|---|---|
command | string | Yes | Operation: list_cells, read_cell, edit_cell, add_cell |
file_path | string | Yes | Path to the .ipynb file |
cell_index | number | No | Cell index (0-based, for read_cell/edit_cell) |
content | string | No | Cell content (for edit_cell/add_cell) |
cell_type | string | No | code or markdown (for add_cell, default: code) |
Parses and validates notebook JSON structure
Cell indices are 0-based
edit_cell writes go through the workspace write-path guard
notebook_sync
Convert between Jupyter notebooks and text files using jupytext.
| Parameter | Type | Required | Description |
|---|---|---|---|
action | string | Yes | Conversion direction (e.g. notebook_to_script, script_to_notebook) |
input_path | string | Yes | Source .ipynb or script path |
output_path | string | No | Destination path |
format | string | No | jupytext script format |
Requires jupytext on PATH
format_file
Format a source file using the appropriate formatter for its language.
| Parameter | Type | Required | Description |
|---|---|---|---|
path | string | Yes | File path |
formatter | string | No | Force a specific formatter |
dry_run | boolean | No | Report what would change without writing |
Supports Python (black + isort), Erlang (erlfmt), Lua (stylua), C/C++ (clang-format) Write-class: gated by RBAC write permission
lint_file
Lint a source file using all registered linters for its language.
| Parameter | Type | Required | Description |
|---|---|---|---|
path | string | Yes | File path |
linter | string | No | Restrict to a single linter |
Supports Python (flake8 + pylint), Lua (luacheck) Write-class: gated by RBAC write permission
Search
glob_search
Find files matching a glob pattern.
| Parameter | Type | Required | Description |
|---|---|---|---|
pattern | string | Yes | Glob pattern (supports ** recursive) |
path | string | No | Base directory (default: workspace root) |
Max 1000 results; beyond that a ... and N more results truncated line is appended
Supports standard glob patterns: *, **, ?, [...]
Results are returned in directory-walk order (not sorted by modification time)
grep_search
Search file contents with a regex pattern.
| Parameter | Type | Required | Description |
|---|---|---|---|
pattern | string | Yes | Regular expression pattern |
path | string | No | Base directory (default: workspace root) |
include | string | No | File pattern filter (e.g. *.lua) |
Engine ladder: ripgrep → silver searcher → grep -P (Perl regex) → grep -E (extended regex)
Returns matching lines with file paths and line numbers
Max 250 matched lines
Timeout defaults to config.tool_timeout_ms (30000 ms when unset)
code_search
Search code using language-server analysis or text search fallback.
| Parameter | Type | Required | Description |
|---|---|---|---|
query | string | Yes | Search query (symbol name or text pattern) |
search_type | string | Yes | Type: definition, references, symbols, text |
file_path | string | No | Limit search to this file |
language | string | No | Limit search to this language |
Falls back to text-based grep when no language server is available Results truncated at 2KB
Code Intelligence
lsp
Query a language server for code intelligence operations (fused entry point).
| Parameter | Type | Required | Description |
|---|---|---|---|
operation | string | Yes | LSP operation (see below) |
path | string | Yes | File path (relative to workspace) |
line | number | Yes | Line number (1-based) |
character | number | Yes | Column number (1-based) |
Supported operations:
| Operation | Description |
|---|---|
goToDefinition | Jump to the definition of the symbol at the given position |
findReferences | Find all references to the symbol at the given position |
hover | Get hover/type information for the symbol at the given position |
documentSymbol | List all symbols defined in the file (line/character not required) |
diagnostics | Get diagnostic messages (errors/warnings) for the file |
Requires a running language server for the file type (auto-started by the LSP manager)
The same operations are also exposed as six individual tools below (lsp_definition, lsp_references, lsp_hover, lsp_completion, lsp_symbols) plus tree-sitter ts_query
Diagnostics are also automatically injected into edit_file and write_file results
lsp_definition
Navigate to a symbol’s definition. Returns file path and line number.
| Parameter | Type | Required | Description |
|---|---|---|---|
path | string | Yes | File path |
line | number | Yes | Line number (1-based) |
character | number | Yes | Column number (1-based) |
lsp_references
Find all references to a symbol. Returns list of file, line, column, and text.
| Parameter | Type | Required | Description |
|---|---|---|---|
path | string | Yes | File path |
line | number | Yes | Line number (1-based) |
character | number | Yes | Column number (1-based) |
lsp_hover
Get hover documentation for a symbol. Returns type signature and doc string.
| Parameter | Type | Required | Description |
|---|---|---|---|
path | string | Yes | File path |
line | number | Yes | Line number (1-based) |
character | number | Yes | Column number (1-based) |
lsp_completion
Get code completion suggestions at a position. Returns list of completion items.
| Parameter | Type | Required | Description |
|---|---|---|---|
path | string | Yes | File path |
line | number | Yes | Line number (1-based) |
character | number | Yes | Column number (1-based) |
lsp_symbols
Get document symbols (outline with hierarchy). Returns symbol list with nesting.
| Parameter | Type | Required | Description |
|---|---|---|---|
path | string | Yes | File path |
ts_query
Query code structure using tree-sitter syntax patterns. Returns structured results for named query types.
| Parameter | Type | Required | Description |
|---|---|---|---|
file_path | string | Yes | Source file path |
query_type | string | Yes | One of functions, classes, imports, exports, calls, symbols |
language | string | No | Force language (auto-detected from extension otherwise) |
ast_query
Query a source file’s syntax tree using tree-sitter patterns.
| Parameter | Type | Required | Description |
|---|---|---|---|
file_path | string | Yes | Source file path |
query | string | Yes | Tree-sitter query/pattern |
language | string | No | Force language |
format | string | No | structured or text output |
code_stats
Get structure statistics for a source file.
| Parameter | Type | Required | Description |
|---|---|---|---|
file_path | string | Yes | Source file path |
symbol_lookup
Look up symbol definitions in the codebase using ctags. Returns structured list of {symbol, file, line, kind}.
| Parameter | Type | Required | Description |
|---|---|---|---|
symbol | string | Yes | Symbol name to look up |
kind | string | No | Filter by kind: function, variable, class, etc. |
file | string | No | Filter by file path pattern |
generate | boolean | No | Force regenerate tags file |
ctags_run
Run ctags to generate or update a tags file. Returns raw output with stats.
| Parameter | Type | Required | Description |
|---|---|---|---|
paths | array | No | Paths to index |
languages | string | No | Language filter |
extras | string | No | Extra ctags options |
Dev Tools
cmake_configure
Run cmake configure step. Generates build files.
| Parameter | Type | Required | Description |
|---|---|---|---|
source_dir | string | No | Source directory |
build_dir | string | No | Build directory |
generator | string | No | CMake generator |
args | array | No | Extra cmake arguments |
cmake_build
Run cmake build step.
| Parameter | Type | Required | Description |
|---|---|---|---|
build_dir | string | No | Build directory |
target | string | No | Build target |
jobs | number | No | Parallel jobs |
runtime_list
List available runtimes and their versions via asdf.
| Parameter | Type | Required | Description |
|---|---|---|---|
runtime | string | No | Restrict to one runtime name |
Code Execution
code_exec
Execute code in a sandboxed environment with resource limits.
| Parameter | Type | Required | Description |
|---|---|---|---|
language | string | Yes | One of python, lua, node, shell |
code | string | Yes | Source code to execute |
timeout | number | No | Timeout in seconds (default 30, clamped to max 120) |
stdin | string | No | Optional stdin input |
Unsupported languages fail with unsupported language: <name>
Git
git
Execute read-only structured git operations in the workspace repository.
| Parameter | Type | Required | Description |
|---|---|---|---|
command | string | Yes | Read sub-command (see below) |
args | string | No | Optional arguments for the command |
path | string | No | Optional file path (for diff) |
Supported sub-commands (all safe/read-class):
| Command | Description |
|---|---|
status | Show working tree status (--porcelain) |
diff | Show unstaged changes (optional file path) |
log | Show commit log (last 20, --oneline) |
branch | List all branches (-a) |
show | Show commit details |
stash_list | List stashed changes |
Mutating sub-commands are not accepted here — the tool answers mutating operations (add, commit, stash, checkout) require the git_write tool
Dangerous patterns are blocked in both command and args: force push, hard reset, clean, filter-branch, rebase, reflog expire, force branch delete, force worktree remove
Force flags (-f, --force, -D) are rejected unless the command is an approved write-class command
git_write
Execute mutating git operations in the workspace repository. Write-class: gated by RBAC write permission — the read-granted git tool never mutates.
| Parameter | Type | Required | Description |
|---|---|---|---|
command | string | Yes | One of add, commit, stash, checkout |
args | string | No | Optional arguments (e.g. commit message) |
path | string | No | Optional file path (for add) |
Same dangerous-pattern and force-flag blocklist as git
git_snapshot
Manage git snapshots for file-level undo and review. Snapshots are auto-created after mutating tools (write_file, edit_file, delete_file).
| Parameter | Type | Required | Description |
|---|---|---|---|
command | string | Yes | Operation: list, diff |
snapshot_id | string | No | Snapshot commit hash (for diff) |
count | number | No | Number of snapshots to list (default: 10) |
Snapshots use the [luna] commit prefix
Restore is a SEPARATE write-class tool — git_snapshot_restore: snapshot restore is a workspace-mutating checkout, so the read-granted git_snapshot never exposes it; permission-gate restore through the write-class tool instead.
git_snapshot_restore
Restore files from a git snapshot. Write-class: mutates the workspace — requires write permission, never reachable via the read-granted git_snapshot.
| Parameter | Type | Required | Description |
|---|---|---|---|
snapshot_id | string | Yes | Snapshot commit hash to restore |
files | array | No | File paths to restore (default: all files in the snapshot) |
Integrated with undo_edit — snapshot restore is available through the undo stack
Web
web_fetch
Fetch content from a URL.
| Parameter | Type | Required | Description |
|---|---|---|---|
url | string | Yes | URL to fetch (must start with http:// or https://) |
format | string | No | Response format: text (default) or markdown |
Bodies over 1MB are rejected (response too large)
Every redirect hop is re-validated by the shared fetch module (curl-side follow disabled)
Gated by the sandbox network policy (execution.sandbox.network); per-host policy applies
HTML is automatically stripped of scripts/styles/tags when format=text
web_search
Search the web using a configurable search backend (SearXNG or Brave Search API).
| Parameter | Type | Required | Description |
|---|---|---|---|
query | string | Yes | Search query |
max_results | number | No | Maximum results (default: 10) |
Returns results with titles, URLs, and snippets
SearXNG backend needs config.web_search_url; Brave backend needs config.brave_api_key
http_request
Make HTTP requests directly (GET, POST, PUT, PATCH, DELETE, HEAD).
| Parameter | Type | Required | Description |
|---|---|---|---|
url | string | Yes | Request URL |
method | string | Yes | HTTP method: GET, POST, PUT, PATCH, DELETE, HEAD |
headers | object | No | Request headers |
body | string | No | Request body |
timeout | number | No | Timeout in milliseconds (default 10000 buffered / 30000 streaming, max 600000) |
stream | boolean | No | Stream response (for large bodies) |
max_stream_bytes | number | No | Max bytes when streaming (default: 100KB) |
Only http:// and https:// URLs allowed
Response truncated at 10KB (use stream=true for larger responses)
More flexible than web_fetch — supports all HTTP methods and custom headers
MCP
mcp_read_resource
Read a resource from an MCP server.
| Parameter | Type | Required | Description |
|---|---|---|---|
uri | string | Yes | MCP resource URI |
server | string | No | Specific MCP server name (omitted = try all) |
If no server is specified, tries all connected MCP servers
mcp_get_prompt
Get a prompt template from an MCP server.
| Parameter | Type | Required | Description |
|---|---|---|---|
name | string | Yes | Prompt template name |
arguments | object | No | Template arguments |
server | string | No | Specific MCP server name (omitted = try all) |
Vision
attach_image
Attach an image file to the conversation for multimodal analysis. Supports PNG, JPEG, GIF, and WebP formats.
| Parameter | Type | Required | Description |
|---|---|---|---|
path | string | Yes | Absolute path to the image file |
Max image size: 20MB Automatically detects MIME type from file content Requires a vision-capable model
Agent
clarify
Ask the user a clarifying question and wait for their response.
| Parameter | Type | Required | Description |
|---|---|---|---|
question | string | Yes | The question to ask |
options | array | No | Optional list of choices for the user to select from |
context | string | No | Optional context explaining why the question is being asked |
mixture_of_agents
Run multiple agents on the same task and aggregate results.
| Parameter | Type | Required | Description |
|---|---|---|---|
task | string | Yes | The task for all agents |
agents | integer | No | Number of agents (default: 3) |
strategy | string | No | vote (synthesize best), best (longest output), or merge (combine all) |
Ask-permission class: the user is consulted before the fan-out Requires a parent agent context
Session
todo
Manage a session-scoped task checklist for tracking progress on multi-step tasks.
| Parameter | Type | Required | Description |
|---|---|---|---|
action | string | Yes | Action: list, add, update, remove |
id | string | No | Task ID (for update/remove) |
text | string | No | Task description (for add) |
status | string | No | Status: pending, in_progress, completed |
priority | string | No | Priority: high, medium, low |
Persists across turns within the session
undo_edit
Undo the last file edit(s), reverting to the original content.
| Parameter | Type | Required | Description |
|---|---|---|---|
count | number | No | Number of edits to undo (default: 1) |
Maintains a stack of up to 50 undo entries Restores the file to its state before the edit Supports git snapshot undo when snapshots are available
Session Rollback
Use the /rollback [N] slash command to remove the last N conversation turns from the active message view. This is useful for recovering from unproductive tangents without losing the entire session.
Auto-branches before dropping turns (creates a snapshot) Returns branch ID and dropped turn count Works on the active message view, not compacted messages Default N = 1 if not specified
Example:
/rollback 3 # Remove last 3 turns, auto-branches first
/rollback # Remove last turn
task
Spawn a sub-agent to handle a specific task in isolation with its own context.
| Parameter | Type | Required | Description |
|---|---|---|---|
prompt | string | Yes | Task description for the sub-agent |
tools | array | No | Restrict sub-agent to these tools (default: same as parent) |
backend | string | No | Backend: local, zmq, team, background (default: local) |
Sub-agent runs with its own context, up to 20 steps 60-second timeout per sub-agent Returns the sub-agent’s output to the parent conversation
background_spawn
Spawn a background sub-agent that runs asynchronously. Returns immediately with a task_id.
| Parameter | Type | Required | Description |
|---|---|---|---|
prompt | string | Yes | Task description for the background sub-agent |
tools | array | No | Restrict sub-agent to these tools (default: same as parent) |
timeout | number | No | Timeout in seconds (default: 120) |
callback | string | No | Callback name for result delivery |
Collect results later via the background task check/await flow
check_background
List background sub-agent tasks: completed results (collected once, then removed) plus the ids still pending. Takes no parameters.
| Parameter | Type | Required | Description |
|---|---|---|---|
| — | — | — | No parameters |
await_background
Wait (bounded) for background sub-agent tasks to finish and return their results. With no ids, waits for every pending task.
| Parameter | Type | Required | Description |
|---|---|---|---|
task_id | string | No | A single background task id to await |
task_ids | array | No | Background task ids to await (default: all pending) |
timeout | number | No | Whole-wait budget in seconds (default 60, capped at 300) |
Unknown/already-collected ids do not busy-wait; use check_background for
the collected set.
read_tool_output
Read a persisted tool output by its handle (the tool_use_id or message id
shown in a [persisted-output] marker). Use offset/limit for long
outputs.
| Parameter | Type | Required | Description |
|---|---|---|---|
handle | string | Yes | Handle from the persisted-output marker |
offset | number | No | Byte offset (default 0) |
limit | number | No | Maximum bytes to read (default 4000, max 12000) |
switch_mode
Switch the agent to a different operating mode during execution.
| Parameter | Type | Required | Description |
|---|---|---|---|
mode | string | Yes | Mode name (build, plan, explore, review, general, or custom) |
reason | string | Yes | Why the mode switch is needed |
Available modes: build, plan, explore, review, general, plus user-defined modes
Updates tool permissions, system prompt, and TUI badge immediately
Subject to the agent.mode_switch_request hook (can be vetoed)
session_search
Search across all session message content using full-text search. Returns matching messages with highlighted snippets.
| Parameter | Type | Required | Description |
|---|---|---|---|
query | string | Yes | Search query |
limit | number | No | Maximum matches to return |
summarize | boolean | No | Return a summarized result set |
session_recent
List recent sessions with metadata (title, model, message count, date).
| Parameter | Type | Required | Description |
|---|---|---|---|
limit | number | No | Maximum sessions to list |
Team
Team work assignment is server-driven: enrolled workers receive signed
team_directive frames (leader-attributed + HMAC-verified), and the
team_mail tool below carries coordination messages. The retired
team_spawn tool could never succeed — it posted an empty worker_id,
which Sol refuses (400 invalid_worker_id); retired it.
team_mail
Send a message to team members via the team priority mailbox.
| Parameter | Type | Required | Description |
|---|---|---|---|
team_id | string | Yes | Team ID |
body | string | Yes | Message body |
to | string | No | Recipient worker ID or all |
subject | string | No | Message subject |
priority | string | No | Priority: high, normal, low |
Messages are delivered via the team priority mailbox with TTL expiry
Supports broadcast (to=all) and direct messaging
Goals
goal_create
Create a new goal for tracking progress on a multi-step task. Returns goal ID and metadata.
| Parameter | Type | Required | Description |
|---|---|---|---|
objective | string | Yes | What the goal should achieve |
tasks | array | No | Initial task list |
goal_get
Get the current status and details of a goal by ID.
| Parameter | Type | Required | Description |
|---|---|---|---|
goal_id | string | Yes | Goal ID |
goal_update
Update a goal’s status, progress, or notes.
| Parameter | Type | Required | Description |
|---|---|---|---|
goal_id | string | Yes | Goal ID |
status | string | No | New status |
progress | string | No | Progress note |
notes | string | No | Free-form notes |
goal_list
List goals with optional status filter.
| Parameter | Type | Required | Description |
|---|---|---|---|
status | string | No | Filter by status |
limit | number | No | Maximum goals to list |
Scheduler
schedule
Schedule a recurring or one-time task.
| Parameter | Type | Required | Description |
|---|---|---|---|
expression | string | Yes | Cron expression or natural language (every 5 minutes, at 3pm tomorrow) |
command | string | No | Shell command to execute (omit for reminder-only) |
description | string | No | Human-readable description |
schedule_list
List scheduled tasks with their status and next run times.
| Parameter | Type | Required | Description |
|---|---|---|---|
limit | number | No | Maximum jobs to list |
schedule_cancel
Cancel a scheduled task by job ID.
| Parameter | Type | Required | Description |
|---|---|---|---|
job_id | string | Yes | Scheduled job ID |
Shares
session_share_create
Create a public share link for session data (messages, summaries, exports).
| Parameter | Type | Required | Description |
|---|---|---|---|
session_data | string | Yes | Session data to share |
format | string | No | Output format |
ttl_days | number | No | Share lifetime in days |
Returns {share_id, url?} — url is only present when the server has base_url configured
session_share_get
Retrieve the data behind a session share link.
| Parameter | Type | Required | Description |
|---|---|---|---|
share_id | string | Yes | Share ID |
Returns {data, format, created_at}; errors on not-found (404 — expired
shares are indistinguishable from never-existed since )
System
port_check
Check which process is listening on a port or holding a file open. Requires lsof.
| Parameter | Type | Required | Description |
|---|---|---|---|
port | number | No | Port to inspect |
file | string | No | File to inspect |
strace_process
Trace system calls of a running or newly spawned process. Summary mode by default. Requires strace. Max duration 30s.
| Parameter | Type | Required | Description |
|---|---|---|---|
pid | number | No | Existing process ID to trace |
command | string | No | Spawn and trace a new command |
duration | number | No | Trace duration in seconds |
filter | string | No | Syscall filter |
numa_info
Get NUMA topology and hardware core information. Requires numactl.
| Parameter | Type | Required | Description |
|---|---|---|---|
| (none) |
json_from_shell
Generate JSON from shell arguments using jo. Example: jo name=test count=42. Requires jo.
| Parameter | Type | Required | Description |
|---|---|---|---|
args | array | Yes | jo-style key=value arguments |
Containers
container_list
List containers. Returns structured [{id, name, image, status, ports}].
| Parameter | Type | Required | Description |
|---|---|---|---|
all | boolean | No | Include stopped containers |
filter | string | No | Filter by name |
container_run
Run a container. Returns container ID.
| Parameter | Type | Required | Description |
|---|---|---|---|
image | string | Yes | Container image |
command | string | No | Command to run in the container |
name | string | No | Container name |
rm | boolean | No | Remove container on exit |
detach | boolean | No | Run detached |
SSH
ssh_agent_status
Show SSH agent status via keychain. Returns structured agent info, key fingerprints, and environment.
| Parameter | Type | Required | Description |
|---|---|---|---|
action | string | No | Sub-action |
key_path | string | No | Specific key path |
Utility
calculator
Evaluate mathematical expressions safely (no code execution).
| Parameter | Type | Required | Description |
|---|---|---|---|
expression | string | Yes | Math expression using +, -, *, /, ^, sqrt, sin, cos, tan, log, floor, ceil, abs, min, max, pi, e |
Safe evaluation — expressions run in a restricted math-only environment
Returns numeric result as string
Supports constants: pi, e
diagram
Generate Mermaid diagrams from descriptions.
| Parameter | Type | Required | Description |
|---|---|---|---|
description | string | Yes | Description of what the diagram should show |
diagram_type | string | No | Type: flowchart, sequence, class, state, er, gantt |
code | string | No | Direct Mermaid code (if provided, description is ignored) |
Returns Mermaid syntax that can be rendered by compatible viewers
Validates Mermaid syntax when code is provided directly
file_watcher
Watch a file or directory for changes and report when a modification is detected.
| Parameter | Type | Required | Description |
|---|---|---|---|
path | string | Yes | File or directory path to watch |
timeout | number | No | Seconds to watch (default: 10, max: 60) |
Uses inotify (FFI) when available, falls back to stat-based polling Returns change event details or “No changes detected” on timeout
repo_overview
Generate a structured overview of a repository including language detection, file counts, and directory structure.
| Parameter | Type | Required | Description |
|---|---|---|---|
path | string | No | Repository path (default: workspace root) |
depth | number | No | Directory-tree depth |
Desktop Environment Tools (Conditional)
Six desktop-environment tools register only when their backing binary is detected at startup:
| Tool | Permission | Probe (binary on PATH) | Description |
|---|---|---|---|
window_manage | execute | bspc | Manage windows: list, focus, close, move, resize, desktops, layout, fullscreen |
desktop_notify | execute | notify-send | Send desktop notifications |
display_layout | execute | xrandr | Get or set display/monitor configuration |
window_info | read | xwininfo or xprop | Get window geometry, title, class, and properties |
audio_control | execute | pactl | Control audio via PulseAudio/PipeWire (sinks, volume, mute) |
xrdb_query | write | xrdb | Query or load the X11 resource database |
window_manage
Manage windows via bspwm tiling window manager. Only available when bspwm is detected.
| Parameter | Type | Required | Description |
|---|---|---|---|
action | string | Yes | Action: list, focus, close, move, resize, desktops, layout, fullscreen |
node_id | string | No | Window/node ID (required for most actions) |
target | string | No | Target desktop name or direction |
direction | string | No | Resize direction: left, right, top, bottom |
pixels | number | No | Resize amount in pixels (default: 50) |
Requires bspwm window manager Input sanitized to prevent shell injection
desktop_notify
Send desktop notifications via notify-send. Only available when libnotify is detected.
| Parameter | Type | Required | Description |
|---|---|---|---|
title | string | Yes | Notification title (max 100 chars) |
body | string | No | Notification body (max 200 chars) |
urgency | string | No | Urgency: low, normal, critical (default: normal) |
Requires libnotify (notify-send)
Input sanitized to prevent shell injection
display_layout
Get or set display configuration through xrandr. Lists connected monitors,
changes resolution/rate, or arranges outputs.
| Parameter | Type | Required | Description |
|---|---|---|---|
action | string | No | list (default), arrange, or resolution |
monitor | string | No | Monitor output name (required for arrange/resolution) |
resolution | string | No | Resolution, e.g. 1920x1080 |
position | string | No | Arrangement, e.g. right-of DP-1 or an absolute position |
rate | number | No | Refresh rate in Hz |
primary | boolean | No | Set the output as primary |
Requires xrandr; execute-class.
window_info
Read detailed window geometry, title, WM_CLASS, and properties. Requires
xwininfo and/or xprop.
| Parameter | Type | Required | Description |
|---|---|---|---|
action | string | No | active (default), id, or children |
window_id | string | No | Window id (hex) for id/children |
Read-class.
audio_control
Control audio through PulseAudio/PipeWire. Lists sinks/sources, sets volume, mutes or unmutes.
| Parameter | Type | Required | Description |
|---|---|---|---|
action | string | Yes | list_sinks, set_volume, mute, or unmute |
sink | string | No | Sink name or index (default: @DEFAULT_SINK@) |
volume | number | No | Volume level 0–100 |
Requires pactl; execute-class.
xrdb_query
Query or load the X11 resource database.
| Parameter | Type | Required | Description |
|---|---|---|---|
action | string | No | query (default), get, or load |
resource | string | No | Resource name for get |
file | string | No | File to load (path is workspace-gated) |
Requires xrdb; write-class (mutates display state).
Computer Use Tools
Twelve computer-use tools register only when the display probe detects an X11/Wayland session (core.computer_use.detect_display_server) AND the per-tool required-binary census passes. On a headless host none register — the worker no longer advertises tools that can only fail. computer_use_force = true in the config re-registers the whole block for the remote-X posture; each handler then fails typed (no display server detected) on absent binaries, and the runtime refusal remains as defense-in-depth.
| Tool | Probe (X11 / Wayland) | Permission |
|---|---|---|
screenshot | scrot / grim | execute |
mouse_move | xdotool / ydotool | execute |
mouse_click | xdotool / ydotool | execute |
mouse_drag | xdotool / ydotool | execute |
type_text | xdotool / wtype | execute |
press_key | xdotool / wtype | execute |
scroll | xdotool / ydotool | execute |
get_cursor | xdotool / — (unsupported on Wayland) | read |
display_info | display only | read |
window_list | wmctrl / swaymsg | read |
clipboard_read | xclip / wl-paste | read |
clipboard_write | xclip / wl-copy | write |
screenshot
Capture the screen. Requires scrot (X11) or grim (Wayland).
| Parameter | Type | Required | Description |
|---|---|---|---|
mode | string | No | full (default), region, or window |
region | array | No | Crop region [x, y, width, height] in pixels |
Execute-class.
mouse_move
Move the pointer to the given screen coordinates. Requires xdotool or
ydotool.
| Parameter | Type | Required | Description |
|---|---|---|---|
x | number | Yes | X coordinate in pixels |
y | number | Yes | Y coordinate in pixels |
mouse_click
Click at the current pointer position. Requires xdotool or ydotool.
| Parameter | Type | Required | Description |
|---|---|---|---|
button | string | No | left (default), right, or middle |
count | number | No | Click count (default 1; use 2 for double-click) |
mouse_drag
Drag from one position to another (press, move, release). Requires xdotool
or ydotool.
| Parameter | Type | Required | Description |
|---|---|---|---|
start_x | number | Yes | Starting X coordinate |
start_y | number | Yes | Starting Y coordinate |
end_x | number | Yes | Ending X coordinate |
end_y | number | Yes | Ending Y coordinate |
type_text
Type text at the current cursor position. Requires xdotool or wtype.
| Parameter | Type | Required | Description |
|---|---|---|---|
text | string | Yes | Text to type |
press_key
Press a key or key combination. Requires xdotool or wtype.
| Parameter | Type | Required | Description |
|---|---|---|---|
keys | string | Yes | Key combination, e.g. ctrl+shift+a, Return, Escape |
scroll
Scroll at the current pointer position. Requires xdotool or ydotool.
| Parameter | Type | Required | Description |
|---|---|---|---|
direction | string | No | up or down (default down) |
amount | number | No | Number of scroll steps (default 3) |
get_cursor
Read the current pointer position. Requires xdotool; unsupported on
Wayland.
| Parameter | Type | Required | Description |
|---|---|---|---|
| — | — | — | No parameters |
Read-class.
display_info
Read screen resolution and display information.
| Parameter | Type | Required | Description |
|---|---|---|---|
| — | — | — | No parameters |
Read-class.
window_list
List visible windows on the desktop. Requires wmctrl or swaymsg.
| Parameter | Type | Required | Description |
|---|---|---|---|
| — | — | — | No parameters |
Read-class.
clipboard_read
Read the current clipboard contents. Execute-class: the clipboard can
carry passwords/OTPs from other applications, so consent is required.
Requires xclip or wl-paste.
| Parameter | Type | Required | Description |
|---|---|---|---|
| — | — | — | No parameters |
clipboard_write
Write text to the system clipboard. Requires xclip or wl-copy.
| Parameter | Type | Required | Description |
|---|---|---|---|
text | string | Yes | Text to write |
Write-class.
Budget Limits
Control per-session spending with the --budget CLI flag:
luajit client/main.lua --budget <USD> --print "Analyze this codebase"
--budget <USD> — set a per-session USD budget
session_budget_usd config key (default: 0 = unlimited)
Agent loop checks accumulated cost after each provider call
Returns {budget_exceeded: true} when cost exceeds budget
Cost tracking uses per-model rate tables (see core/cost_tracker.lua)
Tool Auto-Discovery (S71)
Luna scans the workspace for custom tool definitions and makes them available to the agent alongside built-in tools.
Workspace scanning — Discovers tools from .luna/tools/ and ~/.luna/tools/ directories
Hot-reload — Use /tools-reload slash command to rescan and pick up new tools without restarting
Listing — Use /tools-list slash command to display all available tools (built-in + discovered)
Namespacing — Custom tools are prefixed with custom__; MCP tools with mcp__; plugin tools with plugin__; built-in tools with builtin__
Tool Selection
The LLM agent selects tools based on the task. Common patterns:
| Task | Tools Used |
|---|---|
| Explore codebase | glob_search, grep_search, read_file, list_directory |
| Fix a bug | read_file, bash (to reproduce), edit_file, undo_edit |
| Create a new file | write_file |
| Refactor code | glob_search, read_file, edit_file, multi_edit |
| Run tests | bash |
| Research online | web_search, web_fetch |
| Make API calls | http_request |
| Code navigation | lsp (goToDefinition, findReferences, hover) |
| Track multi-step work | todo |
| Delegate subtask | task (sub-agent) |
| Team collaboration | team_mail (+ signed server-driven team directives) |
| Analyze images | attach_image (with vision-capable model) |
| Undo file changes | undo_edit, git_snapshot_restore |
| Work with notebooks | notebook |
| Generate diagrams | diagram |
| Quick math | calculator |
| Watch for file changes | file_watcher |
| Ask the user | clarify |
| Search past sessions | session_search, session_recent |
Engine reference — generated from the canonical engineering source. Do not edit this page by hand.
Configuration Reference
Canonical scope. This file is the canonical, source-verified configuration reference for the two ZERG config surfaces that share a namespace:
- Sol (orchestrator) — the
solapplication environment (server/config/sys.config,server/config/sys.prod.config, the optional config file, andSOL_*environment variables). Every key below is the exact atom passed tosol_config:get_env/2/application:get_env(sol, Key).- Luna (worker agent) —
client/core/config.lua(DEFAULT_CONFIGmerge),LUNA_*environment variables, and CLI arguments.Out of scope (separate namespaces, not documented here — see §Related configuration surfaces): Mango’s own service config (
mango/conf.py), the Limon console’s build env, and zerg-cli’s own config file.The portal page
docs-site/reference/configuration.mdis a projection of this file — keep fixes here and update the portal page alongside.
Configuration Hierarchy
Configuration is resolved in priority order (highest wins):
Sol Server
- Environment variables (
SOL_*) — applied last bysol_app:apply_env_overrides/0, so they override everything - Config file (optional) — loaded by
sol_config_file:load/0and applied AFTER the release profile has loaded, so it overridessys.prod.config/sys.config( corrects the previously documented inverse order). The boot log names every release-profile key the file overrides.: the search order isSOL_CONFIG_FILE(must be an ABSOLUTE path) →/etc/sol/sol.conf— the old CWD-relativesol.conffallback is GONE. The file must be owner-readable with no group-write and no other bits (0600/0640; 0644 is refused); unknown keys refuse the load loudly;load/1applies the same permission contract. Application is all-or-nothing — every value is normalized/validated first (list-typed keys use theSOL_CLUSTER_NODESgrammar), so a bad value applies NO keys. - Production config (
config/sys.prod.config) — production overrides - Development config (
config/sys.config) — defaults - VM args (
config/vm.args,config/vm.prod.args) — Erlang node settings (not application config; listed for completeness)
Defaults quoted below are the shipped sys.config values; where the code
fallback (what you get with the key absent) differs, both are stated.
The shipped profiles carry 165 top-level keys in sys.config and
174 top-level keys in sys.prod.config (the completeness test’s own
{key, regex; server/test/sol_prod_config_completeness_tests.erl —
).
Luna Agent
- CLI arguments (
--model,--permission-mode,--theme, etc.) - Environment variables (
LUNA_MODEL,LUNA_LOG_LEVEL, …) - Config files — merged lowest→highest by
client/core/config.luadiscover_config_files/1plus the profile file (config.lua:347mergescore/paths.luaprofile_config_pathlast, wins):
~/.luna.json < ~/.luna/settings.json < <cwd>/.luna.json <
<cwd>/.luna/settings.json < <cwd>/.luna/settings.local.json < profile
Security-relevant keys from the project-local files additionally require the repo-config consent gate (below).
Managed-settings precedence
The four config planes resolve highest-wins:
| Priority | Plane | Where it lives / who applies it |
|---|---|---|
| 1 (highest) | Managed settings (admin PUT; fleet push) | Sol managed_settings ETS + <data_dir>/managed_settings.json; pushed to workers via the managed_settings_update PUB and applied by client/core/managed_config.lua |
| 2 | Repo-config (project-local security families) | .luna.json / .luna/settings.json — consent-gated by a user-owned ~/.luna/approvals/trust-<sha256>.json record |
| 3 | Local config (user files + LUNA_* env) | client/core/config.lua merge order (~/.luna.json → … → profile) |
| 4 (lowest) | Built-in defaults | Luna DEFAULT_CONFIG, Sol shipped sys.config |
Only the schema keys (below) are applied; every out-of-schema managed key
is skipped LOUDLY and counted, never silently applied. Sol’s own
managed_settings store does NOT feed sol_config:get_env (application
env only) — the store is a fleet-push plane, not a fifth Sol env layer.
Sol Server Configuration
The Restart column classifies when a changed value takes effect: boot keys are read while the boot ladder / listener construction / child specs run, so a change requires a node restart; per-call keys are read at request/tick/spawn time and are hot-effective. The classification authority is contract/config-restart.yaml (pinned boot keys plus a reviewed per-call default); ci/config_restart_docs_lint.py gates this column against it two-directionally.
HTTP Server
Source: server/config/sys.config, sol_http.erl, sol_app.erl.
| Key | Restart | Type | Default | Env Var | Description |
|---|---|---|---|---|---|
http_port | boot | integer | 21434 | SOL_HTTP_PORT | Cowboy HTTP listener port. Range 0–65535 (0 = OS-assigned, test posture; production refuses 0). Required |
http_ip | boot | string | "127.0.0.1" | SOL_HTTP_IP | Cowboy bind address. 0.0.0.0 for all interfaces. Non-loopback + auth_enabled=false refuses boot (sol_app:validate_auth_boundary/0) |
host | per-call | string | "0.0.0.0" | — | Default inference host (llama.cpp bind address) |
base_url | per-call | string | — (unset) | SOL_BASE_URL | External base URL override for generated links |
max_sse_connections | per-call | integer | 500 (shipped sys.config; code fallback 500 — sol_http_sse.erl; sys.prod.config OMITS the key, so prod runs 500) | — | Concurrent SSE stream cap. Range 10–10000 (sol_config.erl optional battery). corrected the pre-fix doc/dev 100 (a dev-only override that silently diverged from prod) |
conversation_max_per_user | per-call | integer | 100 | — | (HTTP-03): per-principal conversation quota. At the quota the caller’s OWN oldest conversation is evicted; the per-user eviction never selects another principal’s row. |
conversation_max_total | per-call | integer | 500 | — | (HTTP-03): global conversation-store memory backstop (reachable through aggregate multi-principal activity). When it trips, the globally oldest conversation is evicted regardless of principal — it is a process-memory bound, not a per-principal isolation guarantee. |
hook_deadline_total_ms | per-call | integer | 2000 | — | : total wall-clock budget for the sync-event hook fan-out (capped at 10000); the hook path cannot outlive the caller timeout. |
projection_debt_retry_ms | per-call | integer | 5000 | — | : projection-debt retry cadence; a crashed projector’s owed rows retry until the view converges. |
projection_debt_per_aggregate_cap | per-call | integer | 64 (clamped 1–10000) | — | : per-aggregate durable-debt row cap. At the cap the aggregate is quarantined: later debt rows are dropped and counted (projection_debt_quarantined_total) and the debt gate stops blocking new events, keeping debt rows bounded and lane depth O(queue). |
sync_event_caller_window_ms | per-call | integer | 44500 (code fallback ?CALL_TIMEOUT - 500 = 44500 — sol_sync_event.erl; capped at that value; minimum 1000) | — | review: absolute per-admission caller window. A queued admission never commits after this window; an expired queued item is answered with the typed unknown verdict (sync_event_append_deadline_killed_total). |
worker_usage_max_tokens_per_attempt | per-call | integer | 100000000 | — | : plausibility cap on a worker-reported usage total. An implausible frame is refused (settlement degrades to undefined, counted + logged) instead of exhausting the task owner’s ledger; the real terminal frame still settles. |
worker_cancel_drain_ms | per-call | integer | 10000 | — | (XSV-02): drain bound for the worker cancel line before the turn is force-abandoned. |
mnesia_create_bound_ms | per-call | integer | 5000 | — | (SOLOTP-03): bounded mnesia:create_table wait; a wedged schema lock yields a typed boot refusal instead of a hang. |
max_sse_connections_per_principal | per-call | integer | max(1, max_sse_connections div 4) | — | (HTTP-20): per-principal SSE sub-budget — one principal cannot consume the whole admission pool. Refusals bump sse_principal_limit_refusals_total. |
sse_headroom_reservation | per-call | integer | min(50, max_sse_connections div 10) | — | (HTTP-20): slots reserved for the internal/system principal so the server’s own streams can still open under a hostile per-IP fleet. Ordinary principals are refused at max_sse_connections - sse_headroom_reservation. |
stream_relay_high_watermark | per-call | integer | 128 | — | : relay mailbox high-water mark — at or above it the provider pipeline is suspended (gun flow closes, upstream pauses). Minimum 8. |
stream_relay_low_watermark | per-call | integer | 32 | — | : relay mailbox low-water mark — at or below it the suspended pipeline resumes. Always < the high watermark. |
stream_flow_suspend_max_ms | per-call | integer | 30000 | — | : maximum time a flow-controlled provider pipeline may stay suspended before the per-stream controller resumes it (min 1000 ms). A relay death at the pause instant resumes first; the bound closes the indefinite-wedge class. |
limon_origin | per-call | string | "*" in dev sys.config; empty in sys.prod.config (prod must set SOL_LIMON_ORIGIN; empty omits ACAO entirely) | SOL_LIMON_ORIGIN | CORS/WS-Origin anchor for the Limon bridge; code fallback is <<>>. (There is no cors_origin key — this is the only CORS knob.) |
share_max_views | per-call | integer | 100 | — | Session-share view cap: read N+1 after the cap is the gone-dialect 404; clamp lever. |
enable_pprof | per-call | boolean | — (unset → false) | SOL_ENABLE_PPROF | Expose /debug/pprof/*. Opt-in |
deployment_mode | boot | atom | — (unset → dev) | SOL_DEPLOYMENT_MODE | dev | prod. In prod, auth_enabled, mango_auth_enabled, rate_limit_enabled and worker_path become hard-required (sol_app:validate_production_config/0), and placeholder secrets refuse the boot. The container entrypoint renders it explicitly and refuses to render prod unless SOL_MANGO_AUTH_ENABLED is set |
Native TLS
Sol’s Cowboy listener can terminate TLS natively (no reverse proxy required).
Source: sol_http.erl (TransOpts) + the tls key section of
sol_config_file.erl; env mappings in sol_app.erl.
| Key | Restart | Type | Default | Env Var | Description |
|---|---|---|---|---|---|
tls_enabled | boot | boolean | false | SOL_TLS_ENABLED | Enable the TLS listener ({tls, Opts} vs {clear, Opts}) |
tls_cert_file | boot | string | "/etc/sol/tls/server.crt" | SOL_TLS_CERT_FILE | PEM certificate file |
tls_key_file | boot | string | "/etc/sol/tls/server.key" | SOL_TLS_KEY_FILE | PEM private key file |
tls_ca_file | boot | string | "/etc/sol/tls/ca.crt" (shipped; the listener adds cacertfile ONLY when the file exists) | SOL_TLS_CA_FILE | CA bundle |
tls_plaintext_ack | boot | boolean | false | SOL_TLS_PLAINTEXT_ACK | : explicit acknowledgement for serving PLAIN HTTP when tls_enabled=true but the cert/key is missing/unreadable. Non-dev modes refuse boot without it; dev falls back CRITICAL-logged. The ZMQ zmq_transport_plaintext_ack posture is the precedent |
http_transport_plaintext_ack | boot | boolean | false | SOL_HTTP_TRANSPORT_PLAINTEXT_ACK | : explicit acknowledgement for a PLAINTEXT HTTP listener when tls_enabled=false on a NON-LOOPBACK http_ip in deployment_mode=prod — without it (or http_transport_tunnel) the boot REFUSES with {refuse_boot, http_plaintext_external_bind}. Loopback binds and dev keep the open posture; other non-dev modes CRITICAL-banner |
http_transport_tunnel | boot | string | "" | SOL_HTTP_TRANSPORT_TUNNEL | : declares an encrypted upstream terminator/tunnel (http-terminator/wireguard/mtls-sidecar) that satisfies the HTTP plaintext boundary for a non-loopback prod bind |
In the config file the same keys are written under the tls section:
{tls, [{enabled, true}, {cert_file, "/etc/sol/tls/server.crt"}, {key_file, "/etc/sol/tls/server.key"}, {ca_file, "/etc/sol/tls/ca.crt"}]}.
When tls_enabled=true but the cert or key file is missing/unreadable:
deployment_mode=prod (and any non-dev mode) refuses to boot with the
typed {invalid_config, {refuse_boot, {tls_cert_missing, Cert, Key}}} —
serving plaintext silently is no longer possible. dev keeps the fallback
but logs CRITICAL; any mode can explicitly acknowledge plaintext with
tls_plaintext_ack=true (CRITICAL-bannered)..
Prefer the OpenResty reverse-proxy termination on production hosts (wild
blueprint); native TLS is for standalone deployments.
Inference
| Key | Restart | Type | Default | Env Var | Description |
|---|---|---|---|---|---|
llama_server_path | per-call | string | "/usr/src/llama.cpp/llama-server" | SOL_LLAMA_SERVER_PATH | Path to llama.cpp server binary (the legacy/no-root engine resolution) |
inference_engine_root | per-call | string | undefined | undefined (dev) / "/opt/llama" (prod) | — | : engine install root. Unset → the legacy llama_server_path; set → <root>/<engine.build>/bin/llama-server, or <root>/current/bin/llama-server when the engine’s build is absent/unbuilt. A resolved path that is not an executable refuses the start with {engine_binary_missing, Path} |
inference_loading_interval_ms | per-call | integer | 500 | — | : the loading-state health probe interval (ms). Typed; a non-positive-integer value falls back to 500. The slow-load tests shrink it instead of waiting out 90s |
inference_loading_probes | per-call | integer | 60 | — | : the GLOBAL loading probe budget (failures before the crash-class stop + bounded restart). Precedence: lane loading_probes → this key → 60. The ATX/UD lanes carry loading_probes => 600 (300s at 500ms) |
base_port | per-call | integer | 18001 (shipped sys.config; code fallback 8001 — sol_registry.erl ?DEFAULT_BASE_PORT) | SOL_BASE_PORT | First port of the lane allocation window [base_port, base_port+inference_port_range) with wraparound.: 18001-18010 is the range wild publishes on every node (8001-8010 was crowded; 18080 + k0s 31000-32767 excluded) — an allocation outside it is unreachable cross-node.: rendered by the container entrypoint (validated integer; base_port + inference_port_range must stay inside the TCP port space); sol_inference_port_base/_range/_used/_free expose the live window |
inference_port_range | per-call | positive integer | 10 | SOL_INFERENCE_PORT_RANGE | : width of the port window the registry wraps within starting at base_port (next_port/2 wraps wrap_cursor(Base, Range, Port + 1)); a non-positive-integer value falls back to 10 with a warning. Keep base_port + inference_port_range inside the node’s published range.: rendered by the entrypoint (validated integer 1..1000) and exposed as sol_inference_port_range |
inference_tool_result_max_bytes | per-call | positive integer | 262144 (256 KiB) | — | : per-tool-result size cap in bytes; larger content is truncated at the boundary with a marker (the model never receives an unbounded tool payload). A non-positive-integer value falls back to 262144 |
host | per-call | string | "0.0.0.0" (code fallback; shipped sys.prod.config pins "127.0.0.1") | SOL_LLAMA_BIND_HOST | llama.cpp bind host. The effective bind is 127.0.0.1 unless llama_bind_nonloopback=true; also settable via [inference] host in sol.conf. The grant endpoint host is derived separately (advertise-host rule below) and never advertises 0.0.0.0 — a wildcard bind advertises node_host (SOL_NODE_HOST). |
llama_bind_nonloopback | per-call | boolean | false everywhere | SOL_LLAMA_BIND_NONLOOPBACK | : the non-loopback bind opt-in for cross-node lane traffic. With it TRUE the configured host is used (fallback "0.0.0.0" when no host is pinned) and a loud once-per-VM warning is logged — llama.cpp’s HTTP API has no auth, so the exposure must be restricted to a trusted network. Also settable via [inference] bind_nonloopback in sol.conf. Off in every committed config; use the env twin per GPU host |
data_dir | boot | string | "/tmp/sol" | — | Sol scratch/data directory. (LIFE-19): under a non-dev deployment_mode a missing/relative value is a typed PRE-SUP refusal ({invalid_data_dir,...} → invalid_config), no longer an unclassified maintenance-child crash.: the anchored <data_dir>/backups default follows the same absolute-path rule |
Grant advertise-host rule. sol_registry:advertise_host/1
derives the lane-grant endpoint host from the FINAL llama bind host: a
wildcard bind (0.0.0.0 / ::) advertises the operator-configured
node_host (SOL_NODE_HOST), loopback aliases (127.0.0.1 / ::1 /
localhost) collapse to 127.0.0.1, and a concrete non-loopback host is
advertised as-is. A grant endpoint is a dial target, not a bind directive — it
is never 0.0.0.0. For worker grants, sol_lane_orchestrator grants a
bind_mode=loopback lane only when the worker’s READY hostname matches the
target node’s machine hostname (case-insensitive first label,
inet:gethostname/0); a worker that sent no hostname keeps the legacy
same-Sol-node grace. A bind_mode=nonloopback lane relies on the advertised
routable endpoint. Otherwise the grant refuses typed
{lane_not_reachable, Lane, Node}. Cross-node traffic additionally needs the
bind opt-in + port publish — see the runbook’s cluster section (the port
publish is wild-owned).
Model parameter keys
temp, top_p, min_p, batch_size, ubatch_size are not standalone
app-env atoms — they are per-model inference parameters accepted in the
config-file inference section and in model_templates values
(sol_config_file.erl section map; consumed by the model gen_statem). The
defaults below are the shipped model_templates values (config/sys.config):
| Parameter | default template | Also set in |
|---|---|---|
temp | 1.0 | coding 0.3, chat 0.7, reasoning 0.6 |
top_p | 0.95 | coding 0.95, chat 0.9, reasoning 0.95 |
min_p | 0.01 | — |
batch_size | 2048 | coding 2048, chat 2048 |
ubatch_size | — | per-model config |
top_k | — | reasoning 40 |
| Key | Restart | Type | Default | Description |
|---|---|---|---|---|
model_templates | per-call | map | see table above | Per-template sampler defaults, selectable via --template |
Autoscaling
| Key | Restart | Type | Default | Env Var | Description |
|---|---|---|---|---|---|
autoscaling_enabled | per-call | boolean | false | — | Model-instance autoscaler (sol_autoscaler_handler) |
autoscaling_interval_ms | per-call | integer | 10000 | — | Autoscaler poll interval. Range 1000–3600000 |
autoscaling_min_models | per-call | integer | 1 | — | Legacy floor; used only when the live policy map omits min_instances. Range 0–100 |
autoscaling_max_models | per-call | integer | 4 (shipped sys.config; code fallback 8 — sol_autoscaler_action.erl) | — | Legacy ceiling; used only when the live policy map omits max_instances. Range 1–100. Hard-capped by the license GPU cap: scale-up consults sol_license:check(gpus, N+1) and fails closed |
autoscaling_policy | per-call | map | derived defaults (scale_up_tps=100, scale_down_tps=10, min_instances=1, max_instances=8, cooldown_ms=30000) | — | Validated policy map (autoscaling_policy env or the validated set_policy/1 map; idle is the legacy disabled/unset sentinel). min_instances/max_instances drive the action layer and override the flat env fallback; scale_up_tps, scale_down_tps, cooldown_ms drive evaluation |
Inference Lanes
Adds the declarative lane/engine/host-policy
registry (sol_lane_registry.erl) — the sole lane truth: Sol alone picks
the lane/engine/profile; workers never self-select. The values are nested
Erlang maps, so this surface is sys.config-only: it cannot be expressed
in sol.conf (the scalar parser has no map syntax — the model_templates
precedent) and the keys are deliberately not in the plugin-bridge
allowlist (lane pins and model paths leak topology; removed the
same class). sol_config:validate_optional/0 validates the whole registry at
boot and refuses with the accumulated typed violations:
{invalid_inference_lane, LaneId, Reason}
{invalid_inference_engine, EngineId, Reason}
{invalid_node_class, LabelOrClass, Reason}
{invalid_host_policy, Class, Reason}
{invalid_lane_config, Key, Reason}
| Key | Restart | Type | Shipped default | Env Var | Description |
|---|---|---|---|---|---|
inference_lanes | per-call | map | 10 production lanes + llama_agentic_staged (test: fixture_sse) | — | Lane rows. kind => local | remote | staged (default local). Local/staged require engine + files + pin + ctx + caps + modes_allowed; remote (the api_tier) carries caps only. Local lanes also carry the grantable surface wire_format (openai default) / http_auth (none default) / bind_mode (loopback default). modes_allowed ⊆ [on_demand, cron, duration, attended] |
inference_engines | per-call | map | cuda_sm86_main (b11011), cpu_epyc, fork_turboquant, llama_agentic_staged | — | Engine rows. kind => cuda | cpu | experimental | fixture; production => true requires a full 40-hex ref (an optional repo@ prefix is accepted) and a non-empty build. A production lane bound to a production => false engine refuses unless the lane sets engine_ack => true (loud WARNING) |
node_classes | per-call | map | #{blue => cpu_host, red => gpu_3090_full, green => gpu_3090_64g} | — | This deployment’s node label → class map (test => test_host in sys.test.config). An unknown label refuses boot |
lane_host_policy | per-call | map | class-keyed #{kind, vram_mib, ram_mib, max_sessions, lanes, ctx_overrides, host_env} | — | Per-class facts + lane policy. lanes => all_gpu is the sentinel (every GPU-capable local lane); explicit lists are validated lane-by-lane and must never name a staged lane (remote is allowed). host_env is enforced by (validated + merged into the spawn env; host_env_ack gates LD_LIBRARY_PATH); ctx_overrides enforcement rides |
node_label | per-call | atom | blue (test in sys.test.config) | SOL_NODE_LABEL | This node’s label; must resolve through node_classes into lane_host_policy. The env override carries the label as a string and is normalized to the config atom |
lane_model_root | per-call | string | "/fun/models" | — | The serving-weights root the local/staged files.model paths must live under (absolute). This is not model_source_dir (the staging root) — the serving weights live on the GPU hosts |
lane_path_ack | per-call | boolean | false (true in sys.test.config for the relative _build scratch root) | — | Acknowledges lane model paths outside lane_model_root (or relative); CRITICAL-adjacent loud posture, never silent |
Pin rules: pin.repo / pin.file are non-empty binaries; pin.sha256 is a
full lowercase 64-hex digest or the literal <<"unhashed">> with lane
pin_ack => true (ghost carries a full on-host hash only for qwen38_atx);
pin.license is non-empty, or <<"unknown">> with license_ack => true
(qwen38_flashnext); <<"none">> is allowed only for a fixture-engine lane.
The frozen per-lane ghost provenance (file:line, measured refs, license
sources) lives in plan/fixtures/ghost-p7-standard-b0454f2.md, checked
bidirectionally by ci/lane_registry_export_lint.py.
- lane keys (validated at boot by
sol_lane_registry:validate/0 + sol_lane_profile:validate_profile/1;
violations are typed {invalid_inference_profile, LaneId, Reason}):
| Lane key | Type | Meaning |
|---|---|---|
loading_probes | positive integer | Per-lane loading budget (probe count at inference_loading_interval_ms). ATX + UD seed 600 (the 60-90s load class) |
kv_fastpath_ack | boolean | Acknowledges a KV quant outside the fast-path set {f16, bf16, q4_0, q8_0} (the q4_1/q5 PP-collapse lesson). Without it, a non-fast-path KV refuses |
fallback | atom (lane id) | Fallback lane when the primary’s pin cannot be verified (must exist, be kind => local, and not be the lane itself). Selection is receipt-first: a verified lane-model-receipt.json beside the weights is accepted without hashing; missing/stale refuses as primary_pin_unverified (never a 15.6 GB start-path hash). The fallback reason is recorded (inference_lane_fallback event + sol_inference_lane_fallback_total{reason}) |
flash_attn | on | off (optional) | Lane-level FA override. The effective FA is this value or the engine’s require.fa; quantized KV REQUIRES effective on (argv truth is re-checked at the run_llama/1 gate) |
rope | #{scaling, orig_ctx, context_length?, rope_scale?} | YaRN pairing: when the context exceeds orig_ctx, rope_scale MUST equal ctx/orig_ctx and an explicit context_length MUST equal ctx (the n_ctx_train clamp law). scaling ∈ {yarn, linear, none}; orig_ctx is a positive integer |
Other laws enforced at the same gates: threads =< physical cores
(erlang:system_info(cpu_topology), with an optional host-policy
physical_cores override; threads => auto resolves to the count at
start), the per-model draft_mtp law (a spec.type => draft_mtp lane
needs caps.mtp => true or a files.draft), and parallel == limits.slots_max when both are present. Engine rows gained NO per-engine
flag list (recorded decision; owns certification
constraints).
** lane keys** (validated at boot by
sol_lane_registry:validate/0):
| Lane key | Type | Meaning |
|---|---|---|
priority | integer (optional, default 0) | Deterministic-order preference. After cap specificity (fewest unrequested true caps), higher priority wins; remaining ties prefer production => true and finally the lexical lane id |
engine_requirements | #{Cap => #{pr => pos_integer}} (optional) | Blocks a capability flip until the bound ENGINE’s ref carries the recorded pr<N> marker. Keys must be caps the lane declares; only pr is a legal requirement key; an unmet requirement refuses {error, {engine_requirement_unmet, Lane, Cap, Req}} |
Capability routing: sol_lane_router:route/1
(and route/2 with #{host_class => Class}) is the PURE routing core
’s sol_lane_orchestrator:request/2 calls through its dynamic
seam. Requirements are flat and fail-loud: vision, tool_calls,
strict_json, mtp (booleans), min_ctx (positive integer, compared
against effective_ctx — host-policy ctx_overrides[Lane] else the
lane’s declared ctx), throughput (#{min_eval_tps => N} against the
optional expected.eval_tps), mode, host_pref (a placement
hint the router validates but does not use), deep_reasoning, and lane
(an explicit pin that still passes every gate). Unknown keys refuse
{error, {unknown_requirement, K}}; bad values refuse
{error, {bad_requirement, K, V}}. Returns {ok, Lane} for a local
lane, {remote, api_tier} as a DECISION (deep-reasoning or no local
fit; api_tier has no provider/model binding — remote_binding/0
answers the typed {error, {remote_tier_unbound, api_tier}}), or a typed
refusal (no_lane, {unknown_lane, _}, {staged_not_grantable, _},
{not_allowed_on_host, _}, {strict_json_unsupported, _},
{engine_requirement_unmet, _, _, _}, {ctx_insufficient, _, _, _},
{ctx_unknown, _}, {throughput_unmet, _, _, _},
{throughput_unmeasured, _}, {mode_not_allowed, _, _},
{deep_reasoning_requires_remote, _}) — never a silent fallback.
Eligibility: kind => staged is never selectable; explicit host-policy
lists filter by membership; lanes => all_gpu means every local lane
whose engine class is a GPU class (the CPU lane, the remote tier and
staged lanes are excluded).
response_format: the field is extracted at both
HTTP ingresses (sol_http_validation:extract_inference_opts/1; a
non-object value is a 400 on both dialects) and gated once the serving
lane is known. A lane with caps.strict_json => true (and any
engine_requirements satisfied) keeps the field and the OpenAI-wire body
builder forwards it to the lane. An incapable lane STRIPS it for a
tolerant request ({"type":"json_object"}) with the labeled counter
inference_response_format_stripped_total{lane} and a
lane_response_format_stripped event; a strict demand
({"type":"json_schema"} or "strict": true) refuses 400 with the typed
{strict_json_unsupported, Lane} / {engine_requirement_unmet,...}
message. Remote/provider/legacy lane-less legs keep the historical drop
but are counted (lane label remote / unknown) — no silent drop.
ATX forwards; the Ling lanes strip/refuse until #28682 flips their
strict_json cap (blocked by their engine_requirements row until the
engine bump carries the marker).
Needle + rows: sol_lane_needle is the reusable
recall gate — a deterministic 16k-token haystack with
AMBER-KEYLINE-7741 at position 0, chat path only, temperature 0, exact
substring assert, wall + decode timing. run/2 resolves a RUNNING lane
and never starts one ({error, lane_not_running}). The shared row shape
(20 benchmark columns + the at freshness timestamp) is pinned by
server/test/fixtures/lane_benchmark_row.json; fresh_row/6 is the pure
freshness predicate ’s advertisement gate consumes (an engine bump
changes engine_ref/build and invalidates). scripts/lane-needle.sh
and scripts/lane-agentic-suite.sh are operator entry points (GPU-driven,
off required checks); the GPU-less CT proves the mechanics against the
extended fixture lane. tests/lane/run_agentic_suite.py ports the ghost
6-case + 10-case agentic ids; strict-JSON cases report gated (never
pass) while is open.
Instance identity: the registry row key is the
INSTANCE id — <<"<lane>/<model_slug>">> for lane starts, the bare model
slug for legacy starts. sol_registry:start_model(Slug, #{lane => L, engine_override => E}) mints sol_model_<lane>__<slug> (legacy starts
keep sol_model_<slug> exactly). Two lanes may serve the same GGUF; a
duplicate instance-key collision with a different model slug refuses with
{duplicate_instance, Lane, Slug}. /api/v1/models local rows expose
slug (instance), model_slug, lane and engine.
Status/grant descriptor: every sol_inference:status/1
reply carries the additive flat tags lane, engine, endpoint,
wire_format, http_auth, bind_mode, caps, ctx, slots_max,
model, lease_id, expires_at (always present, undefined where
unknown; endpoint = http://Host:Port, never /v1). The pure
sol_inference:grant_descriptor/1 projects exactly the pinned seven keys
{lane, endpoint, wire_format, caps, ctx, lease_id, expires_at} and
returns {error, not_running} / {error, no_lane} otherwise.
lease_id/expires_at are present-but-undefined until fills
them; the contract fixture is
server/test/fixtures/inference_grant_descriptor.json (
consume it byte-for-byte).
The fixture lane (sys.test.config only): fixture_openai engine
(kind => fixture, production => false) + fixture_sse lane
(kind => local, production => false, files.model under
./_build/test/tmp/models/, loading_probes => 20). starts it
through the real sol_inference lifecycle —
sol_inference_fixture_lane_SUITE (the Wave B exit proof: real start →
/health → status descriptor → stop → port closed).
Lane Governor
Adds the node-local resource governor:
sol_lane_lease (admission, monotonic leases, lifecycle modes), the
bounded sol_gpu_probe sampler, the spawn-options seam
(env/kill_timeout/kill_group), pidfile orphan reaping, and the
lane metrics/alerts. The scalar keys below are validated by
sol_config:validate_optional/0; lane_evict_hooks (an argv list) and
lane_cron (a window map) are nested shapes the scalar sol.conf parser
cannot express — they ship in sys.config/sys.prod.config (empty by
default) and are deliberately absent from the plugin-bridge allowlist.
| Key | Restart | Type | Shipped default | Env Var | Description |
|---|---|---|---|---|---|
lane_kill_timeout_s | boot | integer | 10 | — | The erlexec SIGTERM→SIGKILL window per managed child ({kill_timeout, N}, erlexec 2.3.4 semantics — ONE window, not a poll). Range 0–60. The sol_inference_sup child shutdown budget follows it (max(5s, (N+2)s)) |
lane_idle_release_ms | per-call | integer | 900000 | — | Default on_demand idle-release TTL; every admit resets it. Per-lane idle_release_ms overrides; false opts out (the test fixture lane opts out). Range 0–86400000 |
lane_duration_max_ms | per-call | integer | 86400000 | — | Ceiling for a duration-mode start (duration_ms, request or lane row). Range 1–604800000 |
lane_lease_sweep_ms | per-call | integer | 5000 | — | Expiry sweep cadence of the governor singleton. Range 100–600000 |
lane_lease_retry_after_ms | per-call | integer | 5000 | — | retry_after_ms hint returned with {lane_busy, Holder, RetryAfterMs} (HTTP 409). Range 100–600000 |
lane_vram_sample_ms | per-call | integer | 5000 | — | sol_gpu_probe cache TTL (nvidia-smi is never run per scrape/request). Range 100–3600000 |
lane_vram_headroom_mib | per-call | integer | 1229 | — | Free-VRAM margin required at lease acquire (ghost docs/benchmark-serving.md:488: “keep ≥1.2 GB free for image work”). Range 0–1000000 |
lane_release_tolerance_mib | per-call | integer | 2048 | — | Post-stop release verification tolerance: a delayed sample below pre_free − tolerance bumps sol_lane_release_verify_failed_total (CRITICAL alert). Range 0–1000000 |
lane_orphan_ttl_ms | per-call | integer | 3600000 | — | Pidfile age horizon for the orphan sweep: older pidfiles are stale authority (the OS pid may have been reused) and are deleted WITHOUT touching the process; younger ones go through the full identity-checked reap. Range 1000–86400000 |
lane_evict_ack | per-call | boolean | false | — | Acknowledges executing lane_evict_hooks. Without it the configured hooks are refused (logged) |
lane_evict_hooks | per-call | list of argv lists | [] | — | External-producer eviction commands (argv-only, ≤4, each non-empty; e.g. ghost’s ComfyUI /free POST). Executed once on a measured-budget refusal, then the budget is re-checked. Not expressible via sol.conf |
lane_cron | per-call | map | #{} | — | #{<lane> => #{model => Slug, start => CronExpr, stop => CronExpr, duration_ms => N}} windows validated with sol_cron:validate_schedule/1. A start that cannot acquire is counted (lane_cron_start_refused_total) and skipped — never queued. Not expressible via sol.conf |
Per-lane governor keys (validated by sol_lane_registry:validate/0;
violations are typed {invalid_inference_lane, LaneId, Reason}):
| Lane key | Type | Meaning |
|---|---|---|
idle_release_ms | non-negative integer | false | Per-lane idle-release override; false = resident until an explicit stop |
duration_ms | positive integer | Per-lane default duration for duration-mode starts (request duration_ms wins) |
Mode matrix: on_demand (default; start→use→idle-release),
attended (idle-release policy; an explicit TTL/duration makes the lease fixed), duration
(requires duration_ms, ≤ lane_duration_max_ms), cron (window map).
A mode outside the lane’s modes_allowed refuses with
{mode_not_allowed, Mode, Allowed} (HTTP 409 — never a 500). The start
body gains "mode" and "duration_ms".
Slot/quota posture:
lease acquire enforces big-lane exclusivity, the static VRAM sum
(Σ expected.vram_mib + headroom ≤ host_policy.vram_mib), slot
accounting (Σ slots_max + new ≤ host_policy.max_sessions), and the lane
validator caps big lanes at 2 slots and tiny lanes at 5. A busy lane
refuses {lane_busy, Holder, RetryAfterMs} (HTTP 409). The per-model
admission cap is bounded by the lane’s parallel ( maps
limits.slots_max); VRAM budgets are enforced statically for lanes that
declare expected.vram_mib and advisory (typed unverified) elsewhere.
Engine env: inference_engines.<id>.env (validated map; keys
^[A-Z_][A-Z0-9_]*$; LD_PRELOAD/LD_AUDIT refused; LD_LIBRARY_PATH
requires env_ack => true) merges under
lane_host_policy.<class>.host_env (now enforced, no longer stored-only;
host_env_ack gates LD_LIBRARY_PATH). Explicit stop releases the lease;
a crash/health-fail keeps it in recovering so the bounded auto-restart
can renew it (a restart whose lease expired is denied, counted in
sol_lane_restart_denied_total, and stays stopped).
Fleet Inventory & Orchestrator
Adds the replicated fleet read model
(sol_inventory + the sol_lane_inventory ETS table, one row per node,
pushed over explicit rpc:cast) and the placement brain
(sol_lane_orchestrator:request/2). All scalar keys are validated by
sol_config:validate_optional/0. replaces the old
in-config lane_validation map with a DERIVED status over a runtime
measurement record at <data_dir>/lane-validation.json (written 0600
atomically by sol_lane_validation, single writer = the admin validate
route); the legacy lane_validation env map remains ONLY as the
eunit/CT injection seam and is never shipped in sys.config.
| Key | Restart | Type | Shipped default | Env Var | Description |
|---|---|---|---|---|---|
lane_inventory_heartbeat_ms | per-call | integer | 30000 | — | Re-push cadence even without a content change; staleness TTL = multiplier × this. Range 1000–600000 |
lane_inventory_scan_ms | per-call | integer | 5000 | — | Local fact re-derivation cadence (running instances, leases, GPU sample, disconnected-node poll). Range 1000–60000 |
lane_inventory_coalesce_ms | per-call | integer | 1000 | — | Minimum interval between peer pushes when content churns (the write-storm bound; the local row is refreshed regardless). Range 0–60000 |
lane_inventory_stale_multiplier | per-call | integer | 3 | — | Staleness = multiplier × heartbeat (default 3×30 s = 90 s). Range 2–10 |
lane_queue_max | per-call | integer | 8 | — | Bounded admission waiters per lane on the target node; overflow → queue_full (0 refuses all waiting). Range 0–1000 |
lane_queue_wait_ms | per-call | integer | 30000 | — | Default blocking wait for a busy lane; wait_ms=0 in the request is the async probe and returns {queued, Q} immediately. Range 0–600000 |
lane_queue_poll_ms | per-call | integer | 1000 | — | Waiter re-check cadence (poll, not gen_event coupling). Range 100–60000 |
lane_ready_slack_ms | per-call | integer | 2000 | — | Added to the per-lane loading budget (loading_probes × inference_loading_interval_ms) before the ready-wait gives up. Range 0–60000 |
lane_ready_wait_max_ms | per-call | integer | 600000 | — | Absolute cap on the ready-wait budget. On timeout the instance is stopped (releasing its lease) and loading_timeout is returned. Range 1000–3600000 |
lane_failover_enabled | per-call | boolean | true | — | Enables placement failover to the next candidate node |
lane_failover_require_validation | per-call | boolean | true | — | Requires the destination’s lane verdict state => validated before a move; otherwise {engine_unvalidated, Lane, Reason} |
lane_request_id_ttl_ms | per-call | integer | 300000 | — | Idempotency LRU TTL for request_id replay (bounded at 256 entries). Range 1000–3600000 |
lane_validation_ttl_ms | per-call | integer | 2592000000 | SOL_LANE_VALIDATION_TTL_MS | : age after which a lane validation record is stale and the lane projects unvalidated (default 30 days). Range 3600000–15552000000 (1 h–180 d) |
Operator surface: GET /api/v1/inference/lanes (RBAC inference:list)
returns the sanitized merged view (?lane= / ?node= filters); the
response never contains pids, env, model paths, or lease ids.
request/2 is the single resolver: an explicit lane grants the
7-key descriptor plus a nested status map; requirements dispatch to
’s sol_lane_router:route/1 when present (otherwise no_lane).
Model Management
| Key | Restart | Type | Default | Env Var | Description |
|---|---|---|---|---|---|
model_source_dir | per-call | string | "/fun/models" | SOL_MODEL_SOURCE_DIR | NFS or remote model directory (GGUF files) |
model_store_dir | per-call | string | "/tmp/sol/models" | SOL_MODEL_STORE_DIR | Local model cache (rsync target) |
model_local_dirs | per-call | list | [] | — | Additional local model directories (no rsync) |
Worker Management
| Key | Restart | Type | Default | Env Var | Description |
|---|---|---|---|---|---|
worker_path | per-call | string | "client/build/luna" | SOL_WORKER_PATH | Path to Luna worker binary. Validated against prefix. Hard-required in deployment_mode=prod |
worker_path_prefix | per-call | string | "" | SOL_WORKER_PATH_PREFIX | Prefix for spawned worker paths |
max_workers | per-call | integer | 16 | SOL_MAX_WORKERS | Maximum concurrent agent workers. Range 1–1000 (sol_app:validate_config/0 boot validation); 1–10000 accepted by the optional validation battery (sol_config:validate_optional/0). The container entrypoint default is 100. |
initial_workers | per-call | integer | 1 (code fallback — sol_zmq_gateway.erl spawns initial_workers at boot; unset = 1) | SOL_INITIAL_WORKERS | Workers spawned at boot. Range 0–1000 |
worker_heartbeat_timeout_ms | boot | integer | 15000 (shipped sys.config; code fallback 45000 — sol_zmq_gateway.erl/sol_zmq_worker_manager.erl/sol_health.erl) | SOL_WORKER_HEARTBEAT_TIMEOUT_MS | Worker heartbeat timeout in milliseconds (silent-worker eviction threshold). Range 1000–300000 |
worker_heartbeat_check_ms | boot | integer | 10000 | — | Worker heartbeat check interval in milliseconds. Range 1000–60000 |
worker_busy_heartbeat_timeout_ms | boot | integer | 60000 | — | Busy-worker eviction window: a worker holding an in-flight task is evicted only after this much TOTAL frame silence (no heartbeat AND no accepted token progress) — the plain worker_heartbeat_timeout_ms sweep can no longer orphan a busy-but-alive worker whose heartbeat timer is starved by its own task. Genuinely-dead busy workers are still reaped at this window (and independently by the task lease). Range 1000–600000 |
max_spawn_depth | per-call | integer | 3 (shipped sys.config; code fallback 2 — sol_zmq_worker_manager.erl) | — | Max nested spawn depth. Range 1–20 |
agent_slots_per_principal | per-call | integer | 0 — derive ceil(max_workers/2) at admission | — | : per-principal agent-slot FAIR-SHARE ceiling (one user cannot occupy every slot). 0 derives ceil(cap/2); a set value is the absolute ceiling, clamped to the global cap. Fleet-internal principals (internal/system) are not gated. Range 0–10000 (sol_config:validate_optional/0) |
sync_enabled | per-call | boolean | true | — | Installs sol_sync_event_forwarder — every store-routed event (incl. inference.complete, the spend-ledger rebuild’s source) is written to the durable event log. false leaves the advertised durable ledger/workflow consumers starved. The sol_event_sync_forwarder_installed gauge is absent when disabled |
workspace_root | per-call | string | undefined (shipped sys.config; sol_http_workspace.erl falls back to "." when unset) | — | Workspace files root for the HTTP workspace API |
ZMQ
| Key | Restart | Type | Default | Env Var | Description |
|---|---|---|---|---|---|
zmq_enabled | boot | boolean | true | SOL_ZMQ_ENABLED | Required — the only key in sol_config’s REQUIRED_KEYS (missing = loud warning; ZMQ-dependent features dead). Enables the ROUTER/PUB gateway |
zmq_router_port | per-call | integer | 5555 | SOL_ZMQ_ROUTER_PORT | ROUTER socket port (workers connect as DEALER). Range 1–65535 |
zmq_pub_port | per-call | integer | 5556 | SOL_ZMQ_PUB_PORT | PUB socket port (event broadcasting). Range 1–65535 |
zmq_bind_addr | boot | string | "127.0.0.1" | SOL_ZMQ_BIND_ADDR | Bind address for both sockets |
zmq_error_strategy | boot | atom | skip | SOL_ZMQ_ERROR_STRATEGY | Worker-failure strategy: skip | retry | abort |
zmq_max_retries | boot | integer | 3 | — | Max retries under the retry strategy. Range 0–100 |
zmq_worker_cap | boot | integer | 100 (shipped sys.config; code fallback 256 — sol_zmq.hrl/sol_zmq_gateway.erl) | — | Max registered workers. Range 1–10000 |
zmq_listener_cap | boot | integer | 1000 (shipped sys.config; code fallback 1024 — sol_zmq.hrl/sol_zmq_gateway.erl) | — | Max event listeners. Range 1–1000 |
zmq_pid_cap | boot | integer | 10000 (shipped sys.config; code fallback 1024 — sol_zmq.hrl/sol_zmq_gateway.erl) | — | Max tracked pids. Range 50–10000 |
zmq_max_queue_depth | boot | integer | 1000 (shipped sys.config; code fallback 10000 — sol_zmq.hrl/sol_zmq_gateway.erl) | — | Task queue depth cap. Range 1–100000 |
max_pending_tasks | boot | integer | 100 | — | Pending tasks per worker. Range 1–10000 |
dispatch_scheduled_pending_reserve | per-call | integer | 10 | — | : per-worker pending slots RESERVED for scheduled/workflow dispatch classes. Interactive (and channel/plugin) stop at max_pending_tasks - reserve; the reserved classes use the whole budget. Clamped to [0, max_pending_tasks - 1], so at least one non-reserved slot always remains. Range 0–10000 |
dispatch_scheduled_queue_reserve | per-call | integer | 100 | — | : queued-seat slots RESERVED for scheduled/workflow classes. Interactive (and channel/plugin) stop at zmq_max_queue_depth - reserve; the reserved classes use the whole queue. The shipped default is 10% of the shipped zmq_max_queue_depth (100 of 1000) — the original 1000 equalled the queue and left interactive one seat. Clamped to [0, max - 1]; a configured reserve at/above its budget refuses boot (validate_optional/0). Range 0–100000 |
shutdown_event_backlog_shed_threshold | per-call | integer | 5000 | — | : at set_shutting_down (prep_stop), when the observed event backlog (sol_events + durable lane, or sol_sync_event’s admission queue) is at/over this many events, the shutdown pre-shed latch is armed: new store-routed events go straight to the durable shed journal (replayed at boot) and non-store events are dropped with the existing counter, so the bounded handler-completion drain cannot be re-flooded. Range 1–1000000 |
worker_boot_grace_ms | per-call | integer | 15000 | — | How long a dispatch arriving while the session worker is still booting (spawning) is parked for readiness before the typed {not_available, spawning} refusal answers. On expiry — or if the worker dies mid-boot — the shared worker_unavailable classification answers unchanged |
zmq_ownership_enforced | boot | boolean | — (unset → true) | SOL_ZMQ_OWNERSHIP_ENFORCED | Message-level ownership gates (result/token/error/event/spawn — sol_zmq_ownership.erl) |
zmq_worker_secret | boot | string | — (unset) | SOL_ZMQ_WORKER_SECRET | When ≥16 bytes, every ZMQ ready frame must carry HMAC-SHA256(secret, nonce || u16(len(identity)) || identity || u16(len(worker_id)) || worker_id || u32(child_depth) || u64(ctr)) (v2 material via registration_signed_material/5; the 4-arity legacy material is the explicit zmq_enrollment_ctr_required=false escape hatch) or registration is refused (fail-closed) |
allow_shared_worker | per-call | boolean | false | SOL_ALLOW_SHARED_WORKER | : the deployment acknowledges a SHARED worker. The shipped posture is single-tenant per worker; a READY declaring tenancy="shared" (or shared_worker=true) is refused with shared_worker_requires_declaration unless this is true. Even when true no multi-tenant isolation is claimed (one org per Sol; see docs/tenancy-posture.md) |
zmq_allow_local_unregistered | per-call | boolean | false | SOL_ZMQ_ALLOW_LOCAL_UNREGISTERED | : the dev-only escape from the credential requirement — with a LOOPBACK zmq_bind_addr and deployment_mode=dev, setting this permits credential-less worker registration (any local process can then register; CRITICAL-logged). A non-dev mode ignores it. The acknowledged external dev bind is the separate zmq_dev_external_bind_ack lever |
zmq_dev_external_bind_ack | boot | boolean | false | SOL_ZMQ_DEV_EXTERNAL_BIND_ACK | : the ONLY way to boot ZMQ in deployment_mode=dev (the default) on a non-loopback zmq_bind_addr. Without it the boot REFUSES (dev_mode_external_zmq_bind) — the open dev posture (unauthenticated, MAC-optional registration) is never a silent default on a reachable interface. Acknowledged boots CRITICAL-banner at the gate; the effective posture is exported as the sol_zmq_deployment_posture gauge (0 = loopback, 1 = dev+external, 2 = staging/qa, 3 = prod, 4 = ZMQ disabled) |
zmq_curve_enabled | per-call | atom | auto | SOL_ZMQ_CURVE_ENABLED | CURVE transport: auto = on when the bind is non-loopback, true = always, false = never. A curve-enabled node whose crypto backend is missing refuses boot |
zmq_curve_secretkey | per-call | string | — (unset → generated) | SOL_ZMQ_CURVE_SECRETKEY | Server CURVE key (Z85 or 32-byte binary); unset → generated and persisted to zmq_curve_keyfile |
zmq_curve_keyfile | per-call | string | <data_dir>/curve_server.cert | SOL_ZMQ_CURVE_KEYFILE | chumak_cert-format keypair file (z85), mode 0600, gitignored |
zmq_curve_clientkeys | per-call | list | any | SOL_ZMQ_CURVE_CLIENTKEYS | Allowed client public keys (Z85 list); any accepts any |
zmq_transport_plaintext_ack | boot | boolean | false | SOL_ZMQ_TRANSPORT_PLAINTEXT_ACK | Operator acknowledgement for a non-loopback plaintext bind (CRITICAL-logged); refuses boot in prod without it |
zmq_transport_tunnel | boot | string | "" | SOL_ZMQ_TRANSPORT_TUNNEL | Declared encrypted tunnel (wireguard/mtls-sidecar) satisfying the plaintext posture |
zmq_enrollment_keys | per-call | map | #{} | SOL_ZMQ_ENROLLMENT_KEYS | Per-worker keys: #{KeyId => #{worker_id, secret}} (JSON via the env var); a key bound to a worker_id cannot re-register as another worker |
zmq_enrollment_revoked | per-call | list | [] | SOL_ZMQ_ENROLLMENT_REVOKED | Revoked key ids (comma-separated via the env var) |
zmq_fleet_legacy_compat | per-call | boolean | false | SOL_ZMQ_FLEET_LEGACY_COMPAT | Fleet-secret (SOL_ZMQ_WORKER_SECRET) registration window; deprecation 2026-11-01 |
zmq_fleet_legacy_compat_until | boot | string | — (unset) | SOL_ZMQ_FLEET_LEGACY_COMPAT_UNTIL | : the dated compat window (ISO YYYY-MM-DD) — the boot gate CRITICAL-banners while the window is open and REFUSES (fleet_compat_window_expired) once the date has passed; a window without a date stays CRITICAL-banner’d |
zmq_local_enrollment | per-call | boolean | true | SOL_ZMQ_LOCAL_ENROLLMENT | : locally-spawned workers (init-wkr-N, sol_worker spawns) are first-class enrollment clients — the spawn path mints (or reuses, persisted at <data_dir>/zmq_enrollment_local.json, 0600) a per-worker key in the reserved local: namespace bound to the exact worker_id, and the worker env carries LUNA_ZMQ_KEY_ID + the minted secret INSTEAD of the shared fleet secret. false restores the legacy fleet-secret env (which refuses registration while the compat window is closed) |
zmq_registration_plane_ack | boot | boolean | false | SOL_ZMQ_REGISTRATION_PLANE_ACK | : the ack lever for the knowably dead registration plane (fleet secret set + compat closed + no enrollment keys + local minting disabled) — boot REFUSES (zmq_registration_plane_dead) unless this is set (CRITICAL-banner’d) |
zmq_register_rate_limit | per-call | integer | 60 | SOL_ZMQ_REGISTER_RATE_LIMIT | Successful registrations/min PER CREDENTIAL bucket before the rate-anomaly refusal/alarm; a flood on one enrollment key never blocks another |
lane_control_max_per_10s | per-call | integer | 60 | — | : per-identity sliding-window budget for lane-control operations (a remote lease lookup is deferred/refused with a typed rate_limited ack beyond it); bounds the resolver fan-out from one worker. |
zmq_reready_rate_limit | per-call | integer | 30 | — (sys.config only) | : successful re-READYs per identity per 60s for an ESTABLISHED registration before the typed registration_rate_limited refusal. Separate from zmq_register_rate_limit (new identities) and per IDENTITY, so one worker’s flood never spends another’s budget |
zmq_preauth_pipe_limit | per-call | integer | 20 | — (sys.config only) | (ADV-A-02): per-delivering-pipe unregistered-frame replies allowed per 60s window before the pre-identity bucket drops them (counted zmq_preauth_heartbeat_dropped_total); the cap runs before any control reply |
zmq_preauth_global_limit | per-call | integer | 2000 | — (sys.config only) | (ADV-A-02): global ceiling for unregistered-frame replies per 60s window across all delivering pipes |
zmq_reready_resync_cooldown_ms | per-call | integer | 5000 | — (sys.config only) | : per-identity cooldown between READY resyncs (skills/settings/mail), alongside the at-most-one-queued-worker rule. 0 allows back-to-back admitted resyncs (the re-READY budget still bounds the rate) |
zmq_replay_tx_max_age_ms | per-call | integer | 600000 | — (sys.config only) | : frame-tx past-freshness window (ms) — a tx older than this refuses as replay_stale; this is what makes idle replay-tombstone reaping safe. Rows older than the window are reaped on the liveness cadence |
zmq_anonymous_cap | per-call | integer | 1 | — (sys.config only) | : the explicit local-unregistered (dev) posture admits at most this many distinct anonymous identities; an already-registered anonymous identity reconnects freely. Provision enrollment keys or raise this explicitly |
zmq_identity_binding | per-call | atom | strict | SOL_ZMQ_IDENTITY_BINDING | : the READY-path identity invariant. strict — the routing identity must equal the claimed worker_id (a wildcard "*"-bound key binds to its CLAIMED worker_id, so it no longer accepts arbitrary identity/worker_id pairs); provisioned — the enrollment record’s optional identity field must equal the routing identity. Refusals are typed (identity_mismatch / worker_id_missing / key_binding_invalid) and counted in sol_zmq_registration_refused_total{reason}. Invalid values refuse the boot (sol_config battery) |
zmq_identity_binding_ack | per-call | boolean | false | SOL_ZMQ_IDENTITY_BINDING_ACK | : the ack lever for zmq_identity_binding=provisioned — boot REFUSES while any loaded enrollment record lacks the identity field unless this is set (CRITICAL-banner’d; those keys refuse registration with key_binding_invalid) |
zmq_identity_ceiling | per-call | integer | 4096 | SOL_ZMQ_IDENTITY_CEILING | : the replay-identity ceiling — a NEW identity’s registration refuses (identity_ceiling_reached) once this many identities are tracked in the identity-lifetime replay tombstone stores (sol_zmq_frame_tx / sol_zmq_ready_ctr; re-registration of a tracked identity never refuses). Exported as the sol_zmq_replay_rows_tx/sol_zmq_replay_rows_ctr gauges; SolZmqReplayRowsGrowth pages at 80%. Range 1–100000 |
zmq_wire_skew_window | per-call | boolean | true | SOL_ZMQ_WIRE_SKEW_WINDOW | : admits a READY at the N−1 protocol version (version = current−1) during a rolling upgrade; task frames to that worker are stamped min(SolVersion, WorkerVersion) so its inbound validator accepts them. false restores strict version equality. Skew is counted by the sol_zmq_fleet_skew{version} gauge and WARNING-logged at registration |
task_timeout_ms | boot | integer | 300000 | SOL_ZMQ_TASK_TIMEOUT_MS | Task idle deadline (ms); 0 disables the GATEWAY deadline. Since the deadline is re-armed by token/heartbeat progress (progress-renewed lease); a task with no frames for this long resolves to the task_timeout terminal error (sol_zmq_gateway.erl). (XS-07): the task frame never omits the field — a disabled deadline is stamped with the shared 24h sentinel (docs/fixtures/task_timeout_contract.json, disabled_wire_sentinel_ms=86400000) so Luna’s max(task_timeout_ms or 300000, 30000) wedge watchdog cannot preempt Sol’s decision. A per-task timeout_ms in dispatch opts overrides it |
task_max_lifetime_ms | boot | integer | 1200000 | SOL_TASK_MAX_LIFETIME_MS | : total-lifetime cap (ms) of the progress-renewed task lease — a chatty-but-endless task is cancelled at the cap even while it streams; 0 = uncapped. Range 0–86400000 |
task_lease_renewal | boot | boolean | true | SOL_TASK_LEASE_RENEWAL | : the lease-renewal rollback lever — false reverts to the legacy dispatch-armed deadline (no progress re-arm; the lifetime cap becomes unreachable in practice) |
token_shed_window_ms | per-call | integer | 5000 | SOL_TOKEN_SHED_WINDOW_MS | : the sustained-pause token shed window (ms) — only after a pause this long does the recv dispatcher shed a bounded fraction (every 2nd) of token frames, counted in zmq_token_shed_total and surfaced as truncated on the terminal row (honest truncation). 0 = off (tokens unsheddable) |
orchestrator_lease_enabled | per-call | boolean | true | SOL_ORCHESTRATOR_LEASE_ENABLED | : the single-writer lease (requires mango_auth_enabled=true; otherwise disabled). A second Sol boot against the same Mango refuses typed ({refuse_boot, {orchestrator_lease_held, Holder}}); a lease LOST at runtime self-fences the gateway (dispatch quiesced).: Mango unreachable at boot resolves the DURABLE marker — a confirmed holder stays unknown only inside the 30s TTL and self-fences on the wall-clock deadline (background retry active), while a NEVER-confirmed boot HOLDS dispatches by default (gateway quiesced; /ready 503) unless orchestrator_lease_stale_hold_ack=true preserves the historical unfenced posture |
orchestrator_lease_takeover | per-call | boolean | false | SOL_ORCHESTRATOR_LEASE_TAKEOVER | : the operator takeover lever (there is no Sol CLI parser — this env/config ack replaces the phase’s --takeover). Forces the lease CAS to this node (epoch+1); the old holder loses its next heartbeat and self-fences |
orchestrator_lease_stale_hold_ack | per-call | boolean | false | SOL_ORCHESTRATOR_LEASE_STALE_HOLD_ACK | : the never-confirmed-boot / stale-hold acknowledgement. Default false = an unconfirmed lease HOLDS dispatches (gateway quiesced) and /ready is 503 (fail closed). true preserves the historical unfenced boot (dispatch + readiness stay available) and is the only way an unknown/stale lease row is not a readiness error. A fenced verdict is never cleared by this lever |
orchestrator_lease_max_missed_heartbeats | per-call | integer | 2 | SOL_ORCHESTRATOR_LEASE_MAX_MISSED_HEARTBEATS | : k consecutive 10s heartbeat transport failures (default 2 = 20s, inside Mango’s 30s lease TTL) after which a CONFIRMED holder self-fences. Non-consecutive blips never fence; a never-confirmed boot uses the ack lever above. A durable marker keeps a confirmed-then-stale/fenced verdict across a gateway or node restart |
memory_recovery_barrier_ms | per-call | integer | 5000 | SOL_MEMORY_RECOVERY_BARRIER_MS | : the bound on the WAL recovery drain that runs BEFORE the ETS read model hydrates. On timeout/queued ops hydration is HELD (memory_recovery_deferred, critical log + hydration_status/0 recovery=deferred) and retried on the cleanup tick — never a silent stale serve |
orchestrator_lease_heartbeat_ms | per-call | integer | 10000 | SOL_ORCHESTRATOR_LEASE_HEARTBEAT_MS | : lease heartbeat cadence (ms); Mango’s lease TTL is 30s. Range 100–600000.: the CONFIRMED-holder fence deadline is min(k × heartbeat, 30000) measured on the wall clock from the last confirmation and is (re-)armed on EVERY successful confirmation (and on a transport failure), not only when a heartbeat fails — a configured heartbeat longer than the TTL self-fences at the TTL even if no tick or failure ever occurs inside the stealable window |
The #state{} record in server/include/sol_zmq.hrl has internal fallback
defaults (worker_cap=256, listener_cap=1024, pid_cap=1024,
heartbeat_timeout_ms=45000, max_queue_depth=10000). The shipped
sys.config overrides these; the values above are what operators get.
The trust-plane keys above (zmq_curve_*, zmq_transport_*,
zmq_enrollment_*, zmq_fleet_legacy_compat, zmq_register_rate_limit)
and task_timeout_ms are documented in depth in
zmq-security.md and
zmq-protocol-reference.md; the rows here pin
their env mappings so every entrypoint/sol_app read has a documented lever
.
Cluster
| Key | Restart | Type | Default | Env Var | Description |
|---|---|---|---|---|---|
inet_dist_listen_min / inet_dist_listen_max (kernel) | boot | integer | — (unset → random dist port) | SOL_DIST_PORT | When set, the container entrypoint (server/bin/entrypoint.sh) renders a kernel section pinning the Erlang distribution listener to this single port (min = max) — cluster deployments pin one port through firewalls (the live cluster uses 9150). Unset/empty = no pins, exactly the pre-cluster random-port behaviour. Range 1–65535; a non-integer or out-of-range value REFUSES the boot (exit 78) instead of rendering invalid Erlang. |
cluster_nodes | boot | list | [] in sys.config and in the shipped sys.prod.config | SOL_CLUSTER_NODES | Seed nodes pinged at boot (sol_cluster init) and rendered into sys.config by the container entrypoint. Grammar (validated at BOTH layers — entrypoint render time and sol_app:nodes_val/1; malformed values are a loud typed boot refusal, never a silent drop): the Erlang list literal ['sol@peer1','sol@peer2'] (canonical — what the wild create scripts set), or the bare comma-separated form sol@peer1,sol@peer2, or [] for none. Names must be longnames (exactly one @, local@host, ≤253 chars); short names are refused — unqualified peers pang-fail against FQDN nodes. The union list is self-filtering (sol_cluster drops the local node before probing), so every node may ship the same list; wild’s per-host SOL_CLUSTER_NODES env still wins where set. The config-file [clustering] nodes value is normalized through the SAME grammar at apply time — a malformed value refuses the file (typed invalid_config) and applies NO keys (all-or-nothing). Seeds are re-probed asynchronously and on every 30s resync tick while unconnected (bounded: one probe per seed, bounded by the seed list). |
cluster_expected_nodes | per-call | integer | 1 | SOL_CLUSTER_EXPECTED_NODES | Expected cluster node count, self included. Exposed as sol_cluster_expected_nodes{deployment}; the alert rule sol-cluster-expected-nodes (observability/grafana/alerting/sol-alerts.yml, warning, for 5m) fires when sol_cluster_node_count < sol_cluster_expected_nodes. The sol_config default is 1 (key absent); a SEPARATE unset derivation lives in the sol_prometheus metric reader — max(1, length(cluster_nodes) + 1) (sol_prometheus:cluster_expected_nodes/0, the gauge fallback when the key is unset). That reader-level derivation is not the configuration default: with a 3-node union list it yields 4, a false-negative on the exact day a node drops, which is why a fleet deployment pins the value (wild’s per-host SOL_CLUSTER_EXPECTED_NODES); the shipped artifact pins the standalone 1. |
cluster_leave_persist | per-call | boolean | false in dev, true in prod | — | (OTP-10): persist the cluster-left set to <data_dir>/cluster_left.json through sol_durable_file so sol_cluster:leave survives a consumer restart and a VM restart. Prod always persists; dev/test keeps the historical memory-only set unless the operator sets cluster_leave_persist=true (a CT-case leave cannot poison successor suites). |
cluster_version_guard_ack | per-call | boolean | false (pinned in sys.config + sys.prod.config) | — | : the Sol↔Sol join-guard acknowledgement. The join guard is DEFAULT-ON (join generation N/N−1 admitted + sol_cluster_version_skew gauge + the maintenance-503 posture marker; N−2/newer-than-N+1 and schema-epoch mismatches REFUSED + peer disconnected). true downgrades a refusal to a CRITICAL-logged ACKED admission for a DELIBERATE mixed-version/schema drill only — never a silent pass. See docs/version-matrix.md §Sol ↔ Sol. |
cluster_deployment | per-call | string | default; the shipped sys.prod.config pins "blue-red-green" | SOL_CLUSTER_DEPLOYMENT | Deployment label stamped on sol_cluster_node_count / sol_cluster_expected_nodes — one series pair per labeled deployment. |
node_host | per-call | string | "127.0.0.1" | SOL_NODE_HOST | Hostname suffix for node |
node_name (-name in vm.args) | boot | string | sol@zerg-sol | SOL_NODE_NAME | Erlang distribution node name rendered into vm.args by the container entrypoint. The cluster era requires a longname (local@host, e.g. sol@zerg-sol.example.com or sol@192.168.100.2) — short names pang-fail against FQDN peers. Must be identical to the name peers put in SOL_CLUSTER_NODES |
allow_schema_drift | boot | boolean | false | — | : the boot schema-drift ack. When false, a local disc table whose disc_copies name a node outside cluster_nodes ∪ {self} REFUSES boot ({refuse_boot, {foreign_schema_nodes, Nodes}}). true boots WARNING + mnesia_schema_drift_boot_total for the documented repair window only. |
mnesia_backup_interval | per-call | integer (seconds) | 3600 | — | Mnesia backup interval. Range 0–86400 (sol_config.erl optional battery — seconds, not ms) |
mnesia_disc_fallback | per-call | ram | refuse | ram | — | : posture when a store cannot create its disc_copies table. ram keeps the historical availability behavior but logs CRITICAL and counts mnesia_disc_ram_fallback_total (the store is RAM-only until the schema dir is repaired); refuse fails the store’s init so boot refuses the silent downgrade. |
mnesia_backup_dir | boot | string | anchored <mnesia_dir>/backups (sys.config ships /tmp/sol/mnesia_backups; prod /var/lib/sol/data/mnesia_backups; the container entrypoint derives it from SOL_DATA_DIR) | SOL_MNESIA_BACKUP_DIR (container render) | Mnesia backup destination. Resolution order: this config key > anchored <mnesia_dir>/backups. Set it ABSOLUTE — a CWD-relative value silently orphans backups on a different-CWD restart. mnesia_backup_retention_days (default 7) prunes by age; MAX_BACKUPS=5 is a per-UTC-day cap, not a global one |
maintenance_drain_deadline_ms | per-call | integer | 5000 | — | (CORE-01): deadline for the maintenance-enable drain (sol_maintenance). Range 100–60000; out-of-range values fall back to 5000. A drain timeout leaves the gate ENABLED and returns a typed error (never a silent bypass). |
mnesia_dir | boot | string | anchored <data_dir>/mnesia when unset; /var/lib/sol/data/mnesia in sys.prod.config | SOL_MNESIA_DIR | Mnesia data directory. The standalone prod profile pins it under the unit’s writable state root; the container render derives it from SOL_DATA_DIR. An unset value in a prod boot whose data_dir is also unset/relative refuses typed ({mnesia_dir_unset, _}), never a silent CWD schema |
Container Entrypoint (server/bin/entrypoint.sh)
The canonical container entrypoint translates SOL_* env into the release
sys.config + vm.args before exec’ing the BEAM. Beyond the keys mapped
elsewhere in this reference, it reads these path/layout vars (all optional;
unset = the container defaults shown). The former OTLP and
plugin_system_dir/templates_dir sys.config renders were DELETED — none
had an in-VM reader (the OTLP facade was retired in; system
plugins are the bundled priv/plugins root; ).
| Env Var | Default | Description |
|---|---|---|
SOL_ROOT | /opt/sol | Release root the entrypoint probes for the BEAM runtime ($SOL_ROOT/erts-*/bin/erl) when performing the sys.config authority merge; a missing erl binary refuses the boot rather than serving a 32-key-only render |
SOL_MERGE_ERL | — (unset → probed under SOL_ROOT) | Explicit erl binary used for the sys.config authority merge; when set it must be executable, else the probe path is used |
SOL_COOKIE_FILE | ${HOME:-/opt/sol/data}/.erlang.cookie | Distribution cookie file the entrypoint reads/creates for vm.args cookie rendering |
SOL_DIST_TLS_ENABLED | false | : render the distribution-TLS posture into vm.args (-proto_dist inet_tls + -ssl_dist_optfile). Only true/false; true refuses the boot (exit 78) when the optfile is missing — never a silent plaintext boot. |
SOL_DIST_TLS_OPTFILE | /etc/zerg/tls/ssl_dist.conf | Staged Erlang distribution-TLS optfile used when SOL_DIST_TLS_ENABLED=true (wild’s stage-dist-tls.sh writes it). |
SOL_RELEASE_DIR | unset | : explicit release directory for the container entrypoint (wins over all other selectors). With SOL_RELEASE_VSN and the <root>/current symlink, it replaces the pre-fix nondeterministic `ls releases |
SOL_NOFILE_LIMIT | 65536 | : the fd ceiling the entrypoint applies with ulimit -n before exec (>=1024; a hard limit may refuse the raise loudly). The runtime gauges sol_http_nofile_{limit,required,headroom} expose the effective value vs http_max_connections + max_sse_connections + 1024. |
SOL_RELEASE_VSN | unset | : explicit release version directory under $SOL_ROOT/releases/<vsn> (second to SOL_RELEASE_DIR/current); the single-release and bare-image fallbacks are logged. |
SOL_DATA_DIR | /opt/sol/data | Container data root; the entrypoint derives the default SOL_MNESIA_DIR, SOL_AUDIT_LOG_PATH (<data>/logs), SOL_AUDIT_DATA_DIR (<data>/audit-data), SOL_MNESIA_BACKUP_DIR (<data>/mnesia_backups), model/plugin/template dirs from it. data_dir/audit_data_dir/mnesia_backup_dir are RENDERED over the release profile |
SOL_MNESIA_BACKUP_DIR | <SOL_DATA_DIR>/mnesia_backups | : Mnesia backup destination for a container boot; rendered as mnesia_backup_dir over the release profile |
SOL_ETC_DIR | the release dir | Directory the entrypoint writes the rendered sys.config + vm.args into |
SOL_PLUGIN_DIR | <data>/plugins | Container directory the entrypoint CREATES for plugin payloads |
SOL_TEMPLATES_DIR | <data>/templates | Container directory the entrypoint creates for workflow/plugin templates |
SOL_OTEL_ENABLED | false | Accepted for compatibility; NOT rendered and read by no Sol module |
SOL_OTEL_ENDPOINT | http://127.0.0.1:4318 | Accepted for compatibility; NOT rendered, no reader |
SOL_OTEL_SERVICE_NAME | sol | Accepted for compatibility; NOT rendered, no reader |
Circuit Breaker
| Key | Restart | Type | Default | Env Var | Description |
|---|---|---|---|---|---|
circuit_breaker_failure_threshold | per-call | integer | 5 | — | Failures before circuit opens. Range 1–100 |
circuit_breaker_window_ms | per-call | integer | 60000 | — | Failure counting window (ms). Range 1000–3600000 |
circuit_breaker_cooldown_ms | per-call | integer | 30000 | — | Cooldown before half-open (ms). Range 1000–3600000 |
provider_pool_strategy | per-call | atom | round_robin | — | Provider key selection strategy |
provider_key_store | per-call | boolean or path | true (shipped sys.config; code fallback false — sol_provider_key_store.erl; absent disables the store) | — | : persists OPERATOR-added provider-pool keys (sol_provider_pool:add_key/3, the documented remote-shell ceremony) AES-256-GCM at rest. true derives <data_dir>/provider_keys.bin (0600); a path overrides. Declarative keys stay config/keyring/OAuth-derived and are never copied to the store. A corrupt/unreadable store logs + counts and fails OPEN (the pool still boots) |
provider_key_store_secret | per-call | string | unset | — | : explicit encryption secret for the key store (recommended when the data dir is backed up/shared). Unset → a generated 0600 <store>.key keyfile carries the key |
Cost / Spend Guard
Per-principal daily inference enforcement (sol_spend_guard). The caps are
UTC-day scoped and checked before every streaming ingress dispatch; an
in-flight request is never interrupted, so the overshoot is bounded by the
concurrently admitted requests’ projected usage (see cost.md).
0 disables either axis. A USD cap makes an unpriced model a typed
model_unpriced refusal unless the policy allows it.
| Key | Restart | Type | Default | Env Var | Description |
|---|---|---|---|---|---|
inference_daily_budget_usd | per-call | number | 0 (disabled) | — | Per-principal daily USD cap. Settled cost comes from sol_cost/sol_model_metadata; 0 disables the USD axis |
inference_daily_token_budget | per-call | integer | 0 (disabled) | — | Per-principal daily token cap (input + output settled). 0 disables the token axis |
inference_unknown_price_policy | per-call | atom/binary | deny | — | With a USD cap enabled: deny refuses unpriced models (model_unpriced); allow admits them and records cost 0 (counted in cost_unknown_price_total / inference_model_unpriced_total) |
inference_spend_reservation_ttl_ms | per-call | integer | 600000 | — | : a parked admission reservation older than this is reclaimed by the lock-scoped sweep on the next reserve for the same principal/day (a caller crash between reserve and dispatch can never hold pending forever). 0 reclaims on the next reserve |
completion_lease_ttl_ms | per-call | integer | 300000 | — | Fixed TTL for the attended lease a /v1/completions request takes on its FIM lane. It must not exceed lane_duration_max_ms (an over-max value is REFUSED with duration_exceeds_max; it is not silently clamped). Keeps one ghost-text request from pinning a big lane for the 15-minute on_demand class |
inference_worker_daily_task_budget | per-call | integer | 0 (disabled) | — | Per-principal daily worker-task cap enforced at every worker-send funnel (ZMQ dispatch, stdio chat/WS/REST sol_worker:send_task/2, one-shot sol_worker_bg, ZMQ background child spawn); counts admitted placements (not tokens), refunded when placement is refused; 0 disables |
inference_daily_budget_overrides | per-call | map | #{} | — | Optional per-user cap overrides keyed by user_uuid: #{<<"uuid">> => #{daily_budget_usd => N, daily_token_budget => N, daily_worker_task_budget => N}}; a missing axis falls back to the global value |
inference_ledger_rebuild_on_boot | per-call | boolean | true | — | (PRV-05): rebuild the per-tenant daily spend ledger from the durable inference.complete event log when the ETS ledger is created (bounded window, deduped by request_id). false skips the rebuild; an absent/degraded event store never blocks admission. |
inference_ledger_rebuild_retry_ms | per-call | integer | 60000 | — | : bounded retry interval for a failed ledger rebuild/reconcile; the boot caller retries after this interval instead of leaving the day empty until the next restart. |
inference_ledger_rebuild_page_size | per-call | integer | 10000 | — | : event-log page size for the boot ledger rebuild; non-positive values fall back to 10000. |
inference_ledger_rebuild_max_events | per-call | integer | 1000000 | — | : cap on events replayed by the boot ledger rebuild; the walk stops at this bound and the ledger continues from the last settled cursor. Non-positive values fall back to 1000000. |
inference_ledger_marker_ttl_ms | per-call | integer | 86400000 | — | : TTL (ms) for the settlement/worker-turn idempotency markers before the bounded prune may delete them (0 = delete on the next pass). Negative values fall back to 24h. |
inference_ledger_prune_interval_ms | per-call | integer | 60000 | — | : minimum interval (ms) between marker-prune passes; a marker row claims the interval so concurrent settles do not re-walk the table. Negative values fall back to 60000. |
Auth / Security
| Key | Restart | Type | Default | Env Var | Description |
|---|---|---|---|---|---|
auth_enabled | boot | boolean | false (shipped sys.config; sys.prod.config sets true) | SOL_AUTH_ENABLED | Enable Bearer token authentication. false grants the dev principal (permissions=[<<"*">>]) ONLY when deployment_mode=dev AND the request is loopback-topology (peer + forwarded headers); a proxied/non-loopback request is refused typed (auth_disabled_but_proxied) and logged CRITICAL. The non-loopback + auth_enabled=false boot refusal remains (sol_app:validate_auth_boundary/0) |
auth_tokens | boot | list | map | [] | SOL_AUTH_TOKENS | Valid API tokens for Bearer auth (local mode).: entries may carry per-token permissions — [{<<"reader">>, [<<"tasks:read">>]}] (or the map form #{<<"reader">> => [<<"tasks:read">>]}); a bare token keeps the historic * grant and is CRITICAL-logged at boot (the POST /api/v1/lua/eval superuser exposure) until migrated. The SOL_AUTH_TOKENS env form stays the CSV of bare tokens |
auth_exempt_paths | per-call | list | [] (additive) | — | Additional paths that skip auth. Entries are ADDED to the built-in exempt list — see below (sol_auth_middleware.erl ?DEFAULT_EXEMPT_PATHS). The list is read per call but cached in persistent_term; after changing it call POST /api/v1/infra/cache-invalidate (no restart required) |
allow_token_query | per-call | boolean | — (unset → false) | SOL_ALLOW_TOKEN_QUERY | Accept ?token= query-string auth. Deprecated — leaks credentials into proxy logs (sol_auth_middleware.erl) |
rate_limit_enabled | boot | boolean | true | SOL_RATE_LIMIT_ENABLED | Per-token request rate limiting. Posture split: code default is ON (sol_auth_middleware.erl rate_limit_default/0), the shipped dev sys.config sets false (explicit off) and sys.prod.config sets true. When the dedicated limiter is enabled, accounting uses rate_limit_rpm/rate_limit_burst; the middleware’s built-in per-token budget (used before/without the limiter process) is 300 rpm + 30 burst (?RATE_LIMIT_RPM_DEFAULT/?RATE_LIMIT_BURST_DEFAULT) |
rate_limit_rpm | boot | integer | 60 | SOL_RATE_LIMIT_RPM | Requests per minute per key (dedicated sol_rate_limiter; default 60 also in sol_security_sup.erl fallback). Range 1–100000 |
rate_limit_burst | boot | integer | 10 | SOL_RATE_LIMIT_BURST | Burst capacity (dedicated limiter). Range 1–10000 |
rate_limit_principal | per-call | atom | ip+token | SOL_RATE_LIMIT_PRINCIPAL | : bucket principal. ip+token (default): every request consumes the resolved peer-IP bucket pre-auth and, after a successful token validation, the verified-token bucket. ip: rollback lever — the token bucket is never consulted |
rate_limit_ip_rpm | per-call | integer | 60 (shipped sys.config; the built-in middleware code fallback is 300 — sol_auth_middleware.erl ?RATE_LIMIT_RPM_DEFAULT) | SOL_RATE_LIMIT_IP_RPM | : per-IP requests/minute enforced on BOTH limiter paths; the shipped configs set 60/10 per class explicitly. Range 0–100000. Shared/NAT deployments raise this without weakening the per-token budget |
rate_limit_ip_burst | per-call | integer | 10 (shipped sys.config; the built-in middleware code fallback is 30 — sol_auth_middleware.erl ?RATE_LIMIT_BURST_DEFAULT) | SOL_RATE_LIMIT_IP_BURST | : per-IP burst for the built-in default budget. Range 0–10000 |
rate_limit_token_rpm | per-call | integer | 60 (shipped sys.config; the built-in middleware code fallback is 300 — sol_auth_middleware.erl ?RATE_LIMIT_RPM_DEFAULT) | SOL_RATE_LIMIT_TOKEN_RPM | : per-token requests/minute enforced on BOTH limiter paths; the shipped configs set 60/10 per class explicitly. Range 0–100000 |
rate_limit_token_burst | per-call | integer | 10 (shipped sys.config; the built-in middleware code fallback is 30 — sol_auth_middleware.erl ?RATE_LIMIT_BURST_DEFAULT) | SOL_RATE_LIMIT_TOKEN_BURST | : per-token burst for the built-in default budget. Range 0–10000 |
locality_secret | per-call | string | — (unset) | SOL_LOCALITY_SECRET | (HTTP-03): the POSITIVE host-locality proof for the tokenless /metrics + /api/v1/metrics gate and the auth-disabled dev principal. When set (≥16 bytes), an on-host proxy must inject x-zerg-locality: <unix-seconds>:<hex HMAC-SHA256(secret, METHOD "\n" PATH "\n" TIMESTAMP)> (acceptance window ±300 s, constant-time compare); loopback topology alone then no longer suffices. Unset requires an explicit loopback Host authority in addition to loopback topology — reported at boot as EXPLICIT-LOOPBACK and on first gated request with a one-time WARNING. A configured secret shorter than 16 bytes fails CLOSED (FAIL-CLOSED boot datum). Contract in security.md |
trusted_proxies | per-call | list | comma-string | [127.0.0.1] | SOL_TRUSTED_PROXIES | : TCP peers allowed to set X-Forwarded-For/X-Real-IP. Bare IPs and CIDR entries (10.0.0.0/8) both match; invalid entries drop fail-safe with a warning, a /0 CIDR drops with a CRITICAL unless allow_global_trust=true, and an invalid (or /0-unacknowledged) SET value refuses the boot (sol_net:validate_trusted_proxies/1). Client-IP resolution is the Mango-parity rightmost-untrusted walk with the anti-mint-loopback rule |
allow_global_trust | per-call | boolean | false | SOL_ALLOW_GLOBAL_TRUST | : ack lever for a /0 entry in trusted_proxies (trust-everything deployments). Without it the entry is dropped, and a boot with it set refuses (sol_config:http_trust_config_violations/0) |
legacy_write_implies_execute | per-call | boolean | true | SOL_LEGACY_WRITE_IMPLIES_EXECUTE | : the coarse rule granting execute-class permission from write-class. Kept true for existing installs; new installs set false (execute-grade tools then require tasks:execute). Migration note in security.md |
permission_max_pending | per-call | integer | 100 | — | : maximum outstanding permission asks the registry keeps; beyond it new asks are refused typed (backpressure, never an unbounded queue). Code fallback 100 — sol_permission_registry.erl ?MAX_DEFAULT_PENDING |
worker_control_timeout_ms | per-call | integer | 10000 | — | : bounded wait for a chat worker session_control reply (branches/snapshots/restore); a timeout is a typed control_timeout, never a worker kill |
Cluster scope of the limiter: the
limiter’s distributed mode is wired but UNEXERCISED in production —
the mechanism is a distributed => true start option on
sol_rate_limiter (joins a pg scope and sums remote counts), but the
production security supervisor passes only {enabled, rpm, burst} and
there is no env/config key that flips it. Per-node budgets are the
recorded posture: N nodes ⇒ up to N× the effective budget per principal.
A distributed limiter is a successor design item only if per-account
global budgets become a requirement.
Deleted key: the Sol-side “Cluster API key” app-env key
(api_key, placeholder REPLACE_WITH_GENERATED_KEY) was removed — it had
No Sol reader and the entrypoint rendered a second spelling with zero
consumers. Cluster API auth is RBAC tokens (auth_tokens). The similarly
named environment variable consumed by the Luna client as its bearer
token is client configuration, documented with the client (not a Sol boot key).
ci/config_consumer_lint.py now also fails when an entrypoint-rendered
app-env key has no read site.
Mango bridge (Sol-side keys)
These are Sol app-env keys that configure Sol’s client connection TO the
Mango identity service — Mango’s own service config lives in mango/conf.py
(see §Related configuration surfaces).
| Key | Restart | Type | Default | Env Var | Description |
|---|---|---|---|---|---|
mango_auth_enabled | boot | boolean | false | SOL_MANGO_AUTH_ENABLED | Delegate auth to Mango (mango_host:mango_port). When true, mango_service_token is required |
mango_host | boot | string | "127.0.0.1" | SOL_MANGO_HOST | Mango auth/identity service host |
mango_port | boot | integer | 5800 | SOL_MANGO_PORT | Mango service port |
mango_service_token | boot | string | "" | SOL_MANGO_SERVICE_TOKEN | Service token for Sol→Mango calls. Placeholder REPLACE_WITH_GENERATED_SECRET is a fatal boot error |
mango_pub_url | boot | string | — (unset) | SOL_MANGO_PUB_URL | Mango public-facing URL (for redirects) |
mango_tls | boot | boolean | false | SOL_MANGO_TLS | TLS for Sol→Mango |
mango_ca_file | per-call | string | — (unset) | SOL_MANGO_CA_FILE | CA bundle for Sol→Mango TLS |
mango_transport_tunnel | boot | string | "" | SOL_MANGO_TRANSPORT_TUNNEL | Tunnel marker exempting Sol→Mango from the plaintext refusal |
Audit & recording
| Key | Restart | Type | Default | Env Var | Description |
|---|---|---|---|---|---|
audit_hmac_secret | per-call | string | undefined | SOL_AUDIT_HMAC_SECRET | HMAC key for the audit log tamper-evidence chain. Must be stable across restarts — random keys break the chain. : prod + unconfigured secret REFUSES BOOT unless audit_chain_ephemeral_ack=true (the chain is then valid within one run only — verify_integrity/1 flags pre-restart segments after every restart); dev/loopback keeps the historical warn posture. The boot log records the secret’s provenance (provisioning env vs sys.config).: the container entrypoint renders this as base64 in sys.config (sol_app:decode_b64_secrets/0 decodes it before validation), so quotes/newlines in the secret cannot break the rendered term. (CORE-3): the b64: rendering is decoded on BOTH config arms — a SOL_AUDIT_HMAC_SECRET="b64:<base64>" process-env value is normalized after the env override pass (malformed base64 on either arm is a typed boot refusal) |
audit_chain_ephemeral_ack | boot | boolean | false | SOL_AUDIT_CHAIN_EPHEMERAL_ACK | : explicit acknowledgment letting a prod boot start WITHOUT audit_hmac_secret. CRITICAL-banner’d; the tamper-evidence chain is valid within a single run only |
audit_log_path | per-call | string | "/opt/zerg/logs" (code fallback); /var/lib/sol/data/logs in sys.prod.config | SOL_AUDIT_LOG_PATH | Directory (not a file). Daily files audit-YYYYMMDD.jsonl. moved the prod/container default under the data root. The shipped systemd unit overrides it to /var/log/sol/audit (its LogsDirectory), which is equally writable |
audit_data_dir | boot | string | "/opt/zerg/data" (code fallback ?DEFAULT_DATA_DIR, sol_audit_log.erl); /var/lib/sol/data/audit-data in sys.prod.config | SOL_AUDIT_DATA_DIR | Audit chain state directory (chain checkpoint + seq/sig sidecars). moved the prod/container default under the data root |
audit_enabled | per-call | boolean | — (unset → true, sol_audit_log.erl) | SOL_AUDIT_ENABLED | Master audit switch |
audit_verify_interval_ms | per-call | integer (ms) | 300000 | — | : cadence of the scheduled anchored audit-chain verification (runs in a monitored side process; values below 100 fall back to the default). The verdict feeds audit_chain_verified_seq/audit_chain_last_verify_timestamp; staleness pages via the dead-man rule. |
Auth-exempt paths (as-implemented)
Generated source: the auth-exempt and maintenance-exempt lists are single-sourced from
sol_auth_middleware.erl(?DEFAULT_EXEMPT_PATHS+is_maintenance_exempt/1) and rendered intodocs/auth-flow.mdbyci/docs_constant_parity_lint.py --write. Do not hand-copy the lists here; the generated block is the only inventory and the parity lint gates it.
Semantics: a request with no token on an exempt path runs FULL RBAC as
anonymous; exempt means “no token required”, never “skip
authorization”. /api/v1/ready runs 19 subsystem checks (503 when degraded).
/metrics is not auth-exempt: a tokenless scrape is
allowed only when the loopback TOPOLOGY holds (the TCP peer, not proxy
headers), otherwise it needs metrics:read. Cookie-leg logout still requires
the zerg_csrf double-submit pair; /api/v1/webhook/ is unauthenticated by
design because the per-channel signature IS the auth; the WS one-time ticket
is honored only on the WS handshake route.
Retry-After: three shapes (as-implemented)
Retry-After is emitted in three different shapes depending on the producer
(they are NOT interchangeable — parse both the header and the body):
| Shape | Where | Example |
|---|---|---|
| Header only | 429 seat/worker capacity denials — sol_http_chat.erl capacity_reply (429 seat_cap_reached / max_workers_reached) | Retry-After: 1 + body {"ok":false,"error":"seat_cap_reached"} |
| Body-embedded only | 429 bulk worker-mgmt soft-cap — sol_http_worker_mgmt.erl (429 cap_reached) | body {"error":"cap_reached","retry_after":"30","results":[...]} (NO header) |
| Header + body-embedded | 429 auth rate limit — sol_auth_middleware.erl do_auth (rate-limit path) | Retry-After: <N> + body {"error":"rate_limited","retry_after":<N>} |
Auth-rate-limit saturation is a fail-closed 503 + Retry-After
(rate_limiter_unavailable), never a 401.
Provider Routing
| Key | Restart | Type | Default | Env Var | Description |
|---|---|---|---|---|---|
default_routing | per-call | map | — | — | Default routing policy per capability mode (build/plan/general) (config-file routing section, sol_config_file.erl) |
provider_mappings | per-call | list | [] | — | Model-to-provider routing overrides: a list of {ModelName, ProviderAtom} pairs (sol_provider_boot:register_config_mappings/0 accepts ONLY is_list/1). A map was previously documented and silently ignored — changed the shipped profile to [] and ci/config_divergence_lint.py now refuses a non-list shape (boot validation lives in the config/CI layer until the provider-boot module is touched). |
allow_insecure_provider_http | per-call | boolean | false | — | (PRV-12): explicit ack allowing a NON-loopback http:// provider endpoint (config or a declarative provider’s allow_insecure_provider_http). The default REFUSES plaintext remote endpoints (the provider key would travel in cleartext) and counts provider_plaintext_refused_total; https:// is always accepted (case-insensitive) and loopback http:// needs no ack. |
provider_trusted_egress_ack | per-call | boolean | false | — | : the operator-trusted PROVIDER egress ack. With the ack, declarative registration accepts LOOPBACK endpoints (any scheme — plaintext never leaves the host) and PRIVATE/LAN endpoints over https:// only, stamping trusted_target into the registry POpts so the pipeline pin allows the private/loopback target. Default (and LAN plain-http:// even when acked) REFUSES with ssrf_rejected; webhooks keep the unconditional sol_http_validation SSRF gate. |
cluster_trust_cidrs | per-call | string | [] | — | : comma-separated IPv4 CIDR allowlist of cluster-local networks (e.g. "10.0.0.0/8,192.168.0.0/16"). A remote provider target whose RESOLVED address falls inside a listed CIDR is pinnable without a per-provider trusted_target stamp — the operator-declared list IS the trust. Default empty: no cluster exemption. |
ollama_url | per-call | string | "http://localhost:11434" | — | Ollama API base URL |
oauth_redirect_uri | per-call | string | "http://127.0.0.1:21337/callback" | — | OAuth redirect URI for the PKCE browser-login flow. Override it when 21337 is taken; only loopback redirect URIs are bindable by the CLI. |
oauth_allow_loopback_http | per-call | boolean | false | — | : explicit ack permitting http:// OAuth authorize/token URLs ONLY when the host is loopback (a local test IdP). The default refuses with the typed insecure_oauth_url; https:// always goes through the pinned-IP SSRF validator. |
Provider pipeline
Timeout keys of the remote-provider request pipeline (sol_pipeline.erl;
the total default strictly exceeds first-token + idle):
| Key | Restart | Default | Description |
|---|---|---|---|
provider_request_timeout_ms | per-call | 300000 | Total budget — armed at the FIRST connect attempt, covers pinning + connect + body |
provider_first_token_timeout_ms | per-call | 60000 | Max wait for the first token |
provider_idle_timeout_ms | per-call | 30000 | Max inter-token gap (stall detection) |
provider_bodyless_200_grace_ms | per-call | 500 | (BVI-052): grace window (ms) for a 200 response that has not produced a first token yet before the pipeline types the terminal empty_response (0 disables the fast-fail and restores the historical first-token-budget wait; clamped 0–10000) |
provider_max_retries | per-call | 2 | Connect retry budget (exponential backoff + jitter) |
provider_stream_flow_window_bytes | per-call | 102400 | : the streaming flow-control window (gun flow credit trigger; never a truncation point). Minimum 1024. |
provider_sse_event_max_bytes | per-call | 1048576 | : the SSE EVENT cap — the parser-residual bound. Separate from the flow window so one legal >100 KiB event is not fatal; a boundary-less residual that reaches this cap is a typed oversized_sse_event. Minimum 1024. |
provider_anthropic_version | per-call | 2023-06-01 | : the anthropic-version header value Sol sends on every anthropic-wire request (sol_provider_wire:anthropic_version/0; config-overridable for future Messages-API rollouts) |
provider_response_max_bytes | per-call | 1048576 | Non-streaming response cap (breach → output_exceeded_cap + circuit failure) |
provider_tls_cacerts | per-call | OTP bundled cacerts | CA list for TLS provider endpoints (SNI + verify_peer under IP pinning) |
provider_gun_up_watchdog_ms | per-call | 10000 | Gun-up watchdog (defaults to 2× the ?CONNECT_TIMEOUT macro) |
provider_conn_reuse | per-call | true (shipped sys.config; absent = disabled) | : per-target idle gun connection reuse. HTTP/1.1 only: a conn is checked out exclusively (no pipelining), liveness-probed before reuse, and checked in ONLY on a clean fully-consumed 2xx terminal; every error/interrupted path closes it. Test VMs leave it off so a mocked gun conn is never pooled |
provider_conn_pool_idle_ms | per-call | 30000 | Idle age at which the reaper closes a pooled conn |
provider_conn_pool_reap_ms | per-call | 5000 | Reaper sweep cadence |
provider_conn_pool_max_idle_per_target | per-call | 4 | Idle-conn cap per {transport, host, port, SNI} target (oldest evicted) |
provider_conn_pool_max_idle | per-call | 32 | Total idle-conn cap across targets (the fd bound) |
The TCP connect timeout itself is the ?CONNECT_TIMEOUT macro — 5000 ms,
not operator-configurable.
Retry taxonomy: a 429/503 at the response head is transient —
one bounded retry, then terminal; any other 4xx/5xx is terminal
({http_error, Status} + circuit failure); connect exhaustion is terminal
({connect_exhausted, Host, Port}); TLS handshake/verification failures are
permanent, single-attempt. Mid-stream retry never happens. The streaming
chunk window (?MAX_BUFFER_BYTES, 102400) is a flow-control trigger —
parser residuals are always preserved across chunk boundaries, and
overflows are counted (buffer_overflow metric).
Memory, Embedding & Vector Storage
Read consistency: per-key reads read through to PostgreSQL
on an ETS miss; the stats/reflections enumeration reads are served by
sol_memory_read from the NODE-LOCAL sol_memory ETS read model hydrated from
PG. A row written on another cluster node becomes visible after that node
re-reads/hydrates, not immediately.
| Key | Restart | Type | Default | Env Var | Description |
|---|---|---|---|---|---|
memory_pg_enabled | boot | boolean | false | SOL_MEMORY_PG_ENABLED | Persistent memory via PostgreSQL |
memory_pg_url | per-call | string | "" | SOL_MEMORY_PG_URL | PostgreSQL connection URL |
memory_pg_pool_size | per-call | integer | 4 | SOL_MEMORY_PG_POOL_SIZE | General DB connection pool size. Range 1–64 |
memory_pg_ssl | per-call | boolean | false | SOL_MEMORY_PG_SSL | PG TLS for the memory pool. true requires memory_pg_ca_file; the connection is verify_peer — never blind encrypt. An ssl-without-CA connect refuses loud (typed {refuse_pg_connect, pg_ca_file_required}) |
memory_pg_ca_file | per-call | string | "" | SOL_MEMORY_PG_CA_FILE | CA bundle for memory_pg_ssl. Path to the PG server CA certificate; unreadable/absent with ssl on refuses the connection |
memory_hydrate_max_entries | per-call | integer | 100000 | — | (EV-02b): the ETS read-model TOTAL cap — hydration stops at this bound with the truncated datum (hydration_status/0) instead of fighting the owner’s eviction sweep forever |
memory_max_entries | per-call | integer | 100000 | — | (EV-02b): the sol_memory ETS cap. The owner’s sweep evicts the OLDEST rows up to memory_cap_eviction_budget per 60 s pass until the table fits |
memory_cap_eviction_budget | per-call | integer | 5000 | — | (EV-02b): per-sweep eviction budget (rows). A 2×-over table converges in ~10 passes |
memory_wal_batch_size | per-call | integer | 50 | — | WAL batch size. Range 1–10000 |
memory_wal_flush_ms | per-call | integer | 100 | — | WAL flush interval. Range 100–60000 |
memory_http_durable_writes | per-call | boolean | false | — | : HTTP memory writes use the durable ack contract (ok only after the WAL drained / PG committed; an unconfirmed flush answers 503). Default false = cache-durable (RAM-crash-safe; power-loss-durable to the last WAL flush) |
task_store_backend | per-call | enum | ets | — | : the task-store behaviour seam selector. ets is the existing ETS+Mnesia adapter (sol_task_store_ets); any other value refuses boot via sol_config:validate_optional/0. The PG backend is a documented follow-on (see server/src/sol_task_store_backend.erl) |
pg_query_timeout_ms | per-call | integer | 10000 | SOL_PG_QUERY_TIMEOUT_MS | Per-query statement/socket bound; a hung query is killed and its connection culled. Range 100–600000 |
pg_pool_max_lease_ms | per-call | integer | 300000 | SOL_PG_POOL_MAX_LEASE_MS | Last-resort lease-age bound: a lease older than this is reclaimed with a CRITICAL log, its connection culled, and the reconnect ladder armed. Must be greater than pg_query_timeout_ms. Range 1000–3600000 |
pg_pool_health_reserved | per-call | integer | 1 | SOL_PG_POOL_HEALTH_RESERVED | Reserved health-probe connections, added on top of memory_pg_pool_size and never handed to general callers. Must be less than memory_pg_pool_size (out-of-range values are clamped loudly). 0 = probe through the general pool without queueing. Range 0–63 |
pg_reconnect_delay_ms | per-call | integer | 5000 | SOL_PG_RECONNECT_DELAY_MS | PG reconnect backoff. Range 100–300000 |
pgvector_enabled | per-call | boolean | false | SOL_PGVECTOR_ENABLED | pgvector storage (requires pgvector extension + memory_pg_enabled=true). Opt-in per |
pgvector_similarity_threshold | per-call | float | 0.75 | — | Cosine similarity cutoff |
embedding_enabled | per-call | boolean | false (shipped sys.config; code fallback is conditional — true when memory_pg_enabled=true AND memory_pg_url is set — sol_embedding.erl) | — | Compute embeddings |
embedding_backend | per-call | atom | ollama | — | Embedding backend |
embedding_model | per-call | string | "nomic-embed-text" | — | Embedding model id |
embedding_url | per-call | string | "http://localhost:11434" | — | Embedding backend URL |
embedding_api_key | per-call | string | unset | — | Optional bearer for an authenticated embedding backend (sent as Authorization: Bearer …) |
embedding_dimension | per-call | integer | 768 | — | Embedding vector dimension |
memory_decay_enabled | per-call | boolean | false (shipped sys.config; code fallback true — sol_memory_decay_worker.erl) | — | Exponential memory decay |
memory_decay_interval_ms | per-call | integer | 3600000 | — | Decay sweep. Range 60000–86400000 |
memory_forget_threshold | per-call | float | 0.1 | — | Weight below which a memory is forgotten |
memory_decay_halflife_seconds | per-call | integer | 86400 | — | Decay half-life (24h). Range 3600–2592000 |
memory_reflection_enabled | per-call | boolean | false | — | Background reflection/consolidation pass |
memory_reflection_interval_ms | per-call | integer | 21600000 | — | Reflection sweep (6h). Range 60000–86400000 |
memory_reflection_cluster_threshold | per-call | float | 0.85 | — | Similarity to merge memories |
memory_reflection_min_cluster_size | per-call | integer | 5 | — | Minimum cluster size before consolidation |
Embeddings use the embedding_* family. No memory_embed_model key exists.
Related typed-guard keys validated by the optional battery:
embed_max_concurrency (range 1–64), embed_max_queue (1–10000).
Scheduler
| Key | Restart | Type | Default | Env Var | Description |
|---|---|---|---|---|---|
max_scheduled_jobs | per-call | integer | 1000 | — | Global maximum scheduled jobs (429 max_jobs_reached on exceed). Range 1–10000 |
max_scheduled_jobs_per_user | per-call | integer | 100 | — | Per-user quota of active (pending+running) jobs |
scheduler_catchup_batch_max | per-call | integer | 5 (code fallback ?MAX_CATCHUP_RUNS, sol_scheduler.erl) | — | Max missed jobs dispatched in the boot catch-up burst; the remaining overdue tail is deferred with per-job jitter |
scheduler_lease_reaper_interval_ms | per-call | integer | 720000 (2× the 360 s stuck-job grace) | — | Phantom-lease reaper cadence. The scheduler’s running-lease (currently_running) is deliberately not persisted: a node crash mid-run re-dispatches the job only after the boot grace — the documented redispatch window is 360 s. The legacy alias workflow_lease_reaper_interval_ms is read one release for upgrade continuity |
Channels
| Key | Restart | Type | Default | Env Var | Description |
|---|---|---|---|---|---|
channel_enabled | per-call | boolean | true (dev); false in sys.prod.config | SOL_CHANNEL_ENABLED | Enable channel delivery system. The production profile ships the channel plane OFF |
channel_rate_limit_ms | per-call | integer | 100 | — | Minimum interval between messages (ms) |
channel_reply_routing | per-call | on | broadcast | on | — | : task-reply routing. on addresses the originating chat (send_to) for tasks dispatched from a channel; broadcast is the rollback posture. |
channel_origin_max | per-call | integer | 1024 | — | (CON-12): hard cap on live channel-origin rows. Expired rows prune first; at the cap the oldest LIVE origins are replaced by same-store tombstones and counted (channel_origin_pruned_total), and their eventual terminal is a counted drop (channel_reply_dropped_total) — never a silent “not a channel task”. |
channel_origin_ttl_ms | per-call | integer | max(3600000, task_timeout_ms + 3600000); 86400000 when task_timeout_ms=0 | — | (CON-12): channel-origin retention. Rows past the monotonic deadline are pruned and counted (channel_origin_expired_total). The task deadline is progress-renewed, so a channel task that stays live past this window is pruned and its eventual reply is a counted drop; raise this for tasks that can exceed it. |
Plugins
| Key | Restart | Type | Default | Env Var | Description |
|---|---|---|---|---|---|
plugin_user_dir | per-call | string | "" | SOL_PLUGIN_USER_DIR | User plugin directory. Empty = ~/.sol/plugins/ |
plugin_config_path | per-call | string | "" | SOL_PLUGIN_CONFIG_PATH | Path to plugins.json |
plugin_user_dir_load_ack | per-call | boolean | false | SOL_PLUGIN_USER_DIR_LOAD_ACK | Explicit operator consent for UNPINNED ~/.sol/plugins plugins. Without a sha256 pin or this ack, user-dir plugins REFUSE to load — and a pin mismatch refuses the boot |
plugin_env_allowlist | per-call | string list | bundled channel vars | SOL_PLUGIN_ENV_ALLOWLIST | The ONLY env vars plugin config ${VAR} expansion may interpolate; non-allowlisted names expand to empty, never the host environment |
plugin_tls_verify | per-call | boolean | true (shipped sys.config; code fallback verify_peer — sol_plugin_bridge_http.erl/sol_oauth_store.erl) | — | Verify TLS on plugin fetches |
plugin_max_reductions | per-call | integer | 5000000 | — | Luerl VM reduction budget per plugin call (range 1000–2000000000) |
plugin_max_heap_mb | per-call | integer | 256 | — | Heap budget (MB) for every plugin runner — allocation bombs are killed ({error, heap_budget_exceeded}, metric plugin_heap_killed_total) |
plugin_max_binary_mb | per-call | integer | 256 | — | Referenced-binary byte budget (MB) per plugin runner: Lua strings are refc binaries OUTSIDE the heap cap, so the watchdog also polls process_info(Pid, binary) and kills at this cap ({error, binary_budget_exceeded}, metric plugin_binary_killed_total) |
plugin_budget_poll_ms | per-call | integer | 100 | — | Watchdog poll interval (ms) for the plugin heap/binary/reduction budgets. Lower polls kill allocation bombs sooner at a small scheduling cost |
plugin_lifecycle_timeout_ms | per-call | integer | 3000 | — | Wall-clock budget for lifecycle/poll/on_event calls |
plugin_max_result_bytes | per-call | integer | 1048576 | — | Wire result cap for plugin tool calls (result_too_large beyond; sol_zmq_protocol.erl) |
plugin_max_event_types | per-call | integer | 1024 | — | Bounded sol.events.emit atom admission |
plugin_max_queue_len | per-call | integer | 32 | — | Per-plugin FIFO cap |
plugin_http_max_body | per-call | integer | 5242880 | — | sol.http response body cap (5 MB; {error, body_too_large} beyond) |
Deleted key: plugin_system_dir (env-rendered) had
no reader anywhere — system plugins are the bundled priv/plugins root and
the user root is plugin_user_dir; the inert render was deleted rather than
turned into an auto-loaded system trust root.
Skills
| Key | Restart | Type | Default | Env Var | Description |
|---|---|---|---|---|---|
skill_body_max_bytes | per-call | integer | 262144 | — | ONE cap for skill bodies across the registry push (skill_sync v2), the marketplace publish path and the install endpoint. Register/publish over the cap answer the typed body_too_large (HTTP 413 at the API boundary); a value ≤ 0 or non-integer degrades to the default. Luna enforces the same default locally (LUNA_SKILL_BODY_MAX_BYTES overrides) |
Lua Workers
| Key | Restart | Type | Default | Env Var | Description |
|---|---|---|---|---|---|
lua_eval_timeout | per-call | integer | 30000 (dev); 5000 in sys.prod.config | — | Lua eval timeout in milliseconds. Range 1000–60000. The production profile tightens it 6×. Code fallback 10000 (sol_lua_worker.erl ?DEFAULT_EVAL_TIMEOUT) |
lua_eval_max_len | per-call | integer | 4096 | — | Max Lua eval input length in bytes |
lua_default_script | per-call | string | — (undefined) | — | Default Lua script for workers |
lua_script_dir | per-call | string | "" | — | Directory for Lua script files |
Process Management
| Key | Restart | Type | Default | Env Var | Description |
|---|---|---|---|---|---|
exec_user | boot | string | nobody | SOL_EXEC_USER | Downgrade to this OS user for spawned processes |
latency_validate | per-call | boolean | true | — | Validate latency histogram entries |
max_active_requests | per-call | integer | 100 (shipped sys.config); 1000 in sys.prod.config (10× dev; code fallback 32 — sol_inference.erl ?MAX_ACTIVE_REQUESTS) | — | Per-model concurrent inference requests admitted by the model gen_statem (llama-server --parallel slots are separate — emitted only when a model config carries it). Draining on stop refuses admission until in-flight requests finish or scale_down_grace_ms elapses. Validated range 1–10000 |
max_active_requests_per_principal | per-call | integer | half max_active_requests, clamped to it | — | : per-principal fair share of admitted requests (sol_inference_admission). Over-share requests get the typed 429 inference_budget_exceeded carrying the owner principal; reserved system/internal callers are exempt from the share but still count against the global cap |
metrics_max_entries | per-call | integer | 10000 | — | Max entries in latency histogram |
Workflow Engine
| Key | Restart | Type | Default | Env Var | Description |
|---|---|---|---|---|---|
workflow_max_parallel_steps | per-call | integer | 8 (shipped sys.config; code fallback 4 — sol_workflow.erl/sol_workflow_instance.erl) | — | Max parallel steps in a workflow. Range 1–100 |
workflow_timeout_ms | per-call | integer | 3600000 (shipped sys.config; code fallback 3600000 — sol_workflow_instance.erl; sys.prod.config OMITS the key, so prod runs 3600000; valid range 10000–86400000) | — | Workflow hard timeout. corrected the pre-fix dev 300000 (a dev-only override that silently diverged from prod) |
workflow_bridge_enabled | per-call | boolean | true | — | Workflow→worker bridge: subscribes to task.* from the durable sync store and dispatches prompt steps. The sol_workflow_bridge_installed gauge is absent when disabled |
workflow_bridge_dispatch_timeout | per-call | integer | 30000 | — | Bridge dispatch timeout in milliseconds. Range 1000–300000 |
workflow_user_dir | per-call | string | "" | — | User workflow definition directory |
Events, Backpressure & Archival
| Key | Restart | Type | Default | Env Var | Description |
|---|---|---|---|---|---|
event_worker_pool | per-call | integer | 32 (code fallback ?DEFAULT_EVENT_WORKER_POOL, sol_sync_event.erl) | — | Bounded concurrent event workers; overflow queues (FIFO) |
event_queue_limit | per-call | integer | 10000 (code fallback, sol_sync_event.erl) | — | Core-event queue cap; exceed → callers get {error, overloaded} (telemetry-class events shed with slo_event_loss_total instead) |
event_append_deadline_ms | per-call | integer | 30000 (code fallback ?APPEND_DEADLINE_MS) | — | (EV-25): per-lane append watchdog — a worker whose Mnesia append exceeds this deadline is KILLED (sync_event_append_deadline_killed_total) and its event sheds through the durable funnel |
projector_deadline_ms | per-call | integer | 30000 (code fallback ?PROJECTOR_DEADLINE_MS, sol_sync_event.erl) | — | Per-projector watchdog; a hung projector is killed at the deadline (projection_hung_killed_total) |
projector_deadline_total_ms | per-call | integer | 40000 (clamped to ≤ 40000, below the 45 s run/2 call budget) | — | Aggregate projector budget per emitted event; projectors run sequentially under min(per-projector deadline, remaining total) and the remainder is skipped on exhaustion |
event_retention_days | per-call | integer | 7 (shipped sys.config; code fallback is 30) | — | sync_event retention before compaction. Range 1–365 |
telemetry_retention_days | per-call | integer | 7 (code fallback ?DEFAULT_TELEMETRY_RETENTION_DAYS, sol_event_compactor.erl) | — | telemetry_event retention (hourly compaction pass) |
event_compaction_enabled | per-call | boolean | true | — | Compact the event store |
event_retention_max_rows | per-call | integer | 1000000 | — | Retained-event volume budget in rows. The compactor ENFORCES it: when the log exceeds the budget, the oldest rows join the terminality-aware reap (bounded per pass); the sweep-end gauge sync_event_retained_bytes_estimate and event_retention_over_budget_total report the residual |
event_retention_per_aggregate_cap | per-call | integer | 10000 (code fallback ?DEFAULT_EVENT_RETENTION_PER_AGGREGATE_CAP) | — | : per-aggregate hard cap — a never-terminating aggregate keeps at most this many events (the overflow is compacted and counted event_retention_cap_forced_total) |
staging_backlog_max_events | per-call | integer | 20000 (code fallback ?DEFAULT_STAGING_BACKLOG_MAX_EVENTS) | — | : staging backlog cap; a write that would exceed it is refused (events stay in Mnesia) and staging_backlog_cap_total is counted |
compaction_terminality_check | per-call | boolean | true (code fallback, sol_event_compactor.erl) | — | Terminality-aware paired sweep: an expired event is retained while its aggregate’s projection view row is non-terminal or fresher than the retention cutoff. false restores the timestamp-only retention match spec (rollback lever) |
event_compaction_interval_ms | per-call | integer | 3600000 | — | Compaction sweep. Range 60000–86400000 |
event_lane_spill_window | per-call | integer | 0 (code fallback, sol_sync_event.erl) | — | Lane-queue spill window: an admitted event that must wait in a lane queue past this in-RAM depth is appended to the durable spill segment (<mnesia dir>/event_lane_spill/lane_spill.log) before enqueue and replayed on boot. 0 = every queued event spills (no RAM-only pre-durability window) |
event_lane_spill_compact_bytes | per-call | integer | 1048576 (code fallback, sol_sync_event.erl) | — | : spill-segment byte trigger for the atomic rewrite-to-outstanding compaction (outbox-journal discipline). The segment stays ~O(outstanding) under a sustained backlog instead of growing with every retire marker; a failure leaves the segment intact and retries at most once per second. Gauge: event_lane_spill_bytes. |
event_lane_spill_sync_ms | per-call | integer | 1000 (code fallback, sol_sync_event.erl) | — | : bounded-interval fsync of the spill segment while appended bytes are outstanding — the power-loss window is the interval, not the whole outstanding lifetime. The timer is only armed while dirty. |
sol_events_mailbox_max | per-call | integer | 10000 (code fallback, sol_events.erl) | — | : gen_event manager mailbox bound. At/over the bound a store-routed event goes to the durable shed journal and any other event is dropped with events_mailbox_dropped_total; gauge events_mailbox_len. |
sync_event_shed_mailbox_max | per-call | integer | 10000 (code fallback, sol_sync_event_shed.erl) | — | : bound on the supervised shed-worker queue (store-down/over-bound shed records). A drop at the cap is counted sync_event_shed_mailbox_dropped_total; the journal itself is separately byte-capped. |
log_metadata | per-call | boolean | true (shipped sys.config/sys.prod.config; code fallback in sol_log_middleware.erl) | — | Append request/task correlation ids to the default logger template. false restores the stock OTP template for log parsers that cannot tolerate the suffix; process metadata itself stays attached either way |
event_archive_before_compaction | boot | boolean | true | — | Archive events before compacting |
archive_enabled | per-call | bool | true | — | Enable event archival to Mango PostgreSQL. Single canonical resolver: sol_event_compactor:archive_enabled/0 |
event_archive_http_requests | per-call | boolean | false | — | : archive generic-dispatch http_request rows. Off by default — request rows track Sol’s request rate into Mango write load; metrics + request logs already cover them |
archive_mango_url | per-call | string | "http://127.0.0.1:5800" (shipped; code fallback unset) | — | Mango service URL for archival. : loopback http:// is the dev posture; a NON-LOOPBACK plaintext http:// target is REFUSED at boot AND at flush time (the audit stream + HMAC over a plaintext hop). Remote archive transport requires https:// (+ mango_ca_file for a private CA). Operator precondition: a live deployment whose archive_mango_url points at a remote plaintext URL must be updated to https before/with this release (the boot refusal is explicit, never silent; an operator-disabled archive — archive_enabled=false — is exempt). |
bg_task_ttl_ms | per-call | integer | 86400000 | — | Background-task record TTL. Range 60000–604800000 |
shutdown_drain_timeout_ms | per-call | integer | 5000 | SOL_SHUTDOWN_DRAIN_MS | HTTP-request drain budget. Must be ≤ the container stop grace (podman ~10s / runit ~7s; see production-runbook.md “Shutdown budget”) — ci/shutdown_budget_lint.py pins the shipped configs to ≤5000. The pre-fix default (30000) exceeded the grace, so the drain never completed before SIGKILL. Range 1000–300000 |
Compaction durability: compaction no longer deletes
before the archive confirms. The full compacted events are staged to a
durable file (sol_event_compactor_staging.dump under the Mnesia dir,
temp+rename) first; deletion happens only when a durable copy exists (the
archive ack or the staging file itself). A restart mid-compaction
re-archives any unacknowledged staging file on boot (compaction_skipped_total
counts cycles where no durable copy could be staged).
Chat History
| Key | Restart | Type | Default | Env Var | Description |
|---|---|---|---|---|---|
chat_checkpoint_tokens | per-call | integer | 64 (code fallback ?DEFAULT_CHECKPOINT_TOKENS, sol_chat_history.erl) | — | Persist the streamed buffer every N tokens (crash loses ≤ 1 window) |
chat_checkpoint_ms | per-call | integer | 2000 (code fallback ?DEFAULT_CHECKPOINT_MS) | — | …or every T ms, whichever comes first |
Infrastructure & Observability
| Key | Restart | Type | Default | Env Var | Description |
|---|---|---|---|---|---|
prometheus_enabled | per-call | boolean | true | — | Enable Prometheus /metrics endpoint |
grafana_url | per-call | string | — (undefined) | — | Grafana URL for infra status page link |
ACP (Agent Control Protocol — opt-in)
Source: sol_acp_listener.erl, sol_acp_session.erl, env mappings in
sol_app.erl. No auth middleware in front of this listener — keep disabled
unless HMAC is configured.
| Key | Restart | Type | Default | Env Var | Description |
|---|---|---|---|---|---|
acp_enabled | boot | boolean | — (unset → false) | SOL_ACP_ENABLED | Raw-TCP ACP listener |
acp_listener_port | per-call | integer | — (unset; code fallback 9120) | SOL_ACP_LISTENER_PORT | ACP port. Range 1024–65535 |
acp_listener_ip | per-call | string (parsed IP) | — (unset → {127,0,0,1}) | SOL_ACP_LISTENER_IP | ACP bind IP. A non-loopback bind refuses boot without SOL_ACP_LISTENER_PLAINTEXT_ACK=true |
acp_shared_secret | per-call | string | — (unset → <<>>; listener refuses to enable with a too-short secret) | SOL_ACP_SHARED_SECRET | HMAC secret for ACP messages |
acp_session_timeout | per-call | integer (seconds) | 300 (code fallback ?SESSION_TIMEOUT, sol_acp_session.erl) | SOL_ACP_SESSION_TIMEOUT | ACP session timeout. Range 10–3600 |
acp_request_wait_timeout_ms | per-call | integer | 30000 | — | (SC-03): how long the synchronous HTTP ACP arm waits for the reply frame before answering a typed 504 (acp_reply_timeout); the registry entry is consumed by its own timer, so a late reply can still land. |
acp_packet_size | per-call | integer | 1048576 (clamped at 16777216 at listener boot) | SOL_ACP_PACKET_SIZE | ACP frame-size cap; oversized declared lengths are refused in the driver before allocation. Range 1024–16777216 |
acp_listener_plaintext_ack | per-call | boolean | false | SOL_ACP_LISTENER_PLAINTEXT_ACK | Explicit acknowledgement that the ACP plane (HMAC-only raw TCP) may bind non-loopback |
acp_replay_max | per-call | integer | 65536 | SOL_ACP_REPLAY_MAX | Global replay digest cache LRU cap (oldest-evicted). Range 16–1048576 |
acp_replay_scope | per-call | string (global | peer) | global | SOL_ACP_REPLAY_SCOPE | Replay cache scope. peer is the one-window rollback lever (cross-connection replay NOT refused; CRITICAL boot banner) |
acp_key_id | per-call | binary | <<"default">> | — (sys.config only) | Key identity bound to TCP-leg capability registrations; flipping it between connections is a key rotation — a mismatched key for a taken AgentId is refused |
acp_shared_secrets | per-call | map | #{} | — (sys.config only) | : named ACP HMAC secrets #{KeyId => Secret} (≥16 bytes each). The verified key id is bound to the peer on capability registration; a different key for a taken AgentId, or the same key from a different peer address, is refused |
acp_max_sessions | per-call | integer | 500 | — (sys.config only) | : the ACP session-table ceiling. Sessions are created only after a frame authenticates (unauthenticated connects never allocate) |
acp_max_sessions_per_ip | per-call | integer | 50 | — (sys.config only) | : per-IP fairness cap on ACP sessions (one peer cannot occupy the whole table) |
Seats & Licensing
| Key | Restart | Type | Default | Env Var | Description |
|---|---|---|---|---|---|
seats_enabled | per-call | bool | false | SOL_SEATS_ENABLED | Master switch; off = checks pass, Community defaults. Off in production until the release gate. See seats.md |
license_file | per-call | string | — | SOL_LICENSE_FILE | CLF v1 license file path (cold start / air-gap) |
license_pubkey | per-call | string | — | SOL_LICENSE_PUBKEY | PEM ed25519 pubkey for CLF signature verification (empty = trusted config in dev) |
seats_url | per-call | string | — | SOL_SEATS_URL | Control-plane seat endpoint (ZERGBASE panel /api/seats). https:// required under enforcement — http:// is refused at boot; since then (LIFE-19) that refusal is a typed PRE-SUP violation ({forbidden_http_seats_url, Url} → invalid_config), so the license child never raises |
seats_token | per-call | string | — | SOL_SEATS_TOKEN | Bearer token for the seat endpoint |
seats_signing_key | per-call | string | — | SOL_SEATS_SIGNING_KEY | HMAC-SHA256 key for /api/seats signatures — required when seats_url is set |
seats_url_allow_http | per-call | bool | false | SOL_SEATS_URL_ALLOW_HTTP | Test-only loopback override of the http:// refusal. NEVER in production |
seats_refresh_ms | per-call | integer | 30000 | SOL_SEATS_REFRESH_MS | Seat refresh interval (bounds 5000–86400000) |
seat_cluster_occupancy_ttl_ms | per-call | integer | 2000 | — | (BVI-014): TTL (ms) of the cached cluster-occupancy verdict after a degraded peer read (range 1000–5000, outside → 2000). A flapping peer cannot mint one spawn per dispatch inside the TTL. |
seat_cluster_occupancy_bound_ms | per-call | integer | 1500 | — | (BVI-014): bound (ms) on one cluster-occupancy peer read before the verdict degrades to this node’s live count (range 100–5000, outside → 1500). |
Managed Settings — the admin fleet-push plane
Admin-only (PUT /api/v1/managed-settings) fleet settings that every Luna
worker applies. The key set is CLOSED by the shared fixture
docs/fixtures/managed_settings_schema.json — consumed by Sol’s PUT
validator (sol_managed_settings_schema), Luna’s applier
(client/core/managed_config.lua M.SCHEMA), the Limon form, and
ci/managed_settings_schema_lint.py. This is the highest-precedence
plane (see Managed-settings precedence).
| Key | Type | Bounds | Luna target (consumer) |
|---|---|---|---|
execution.policy | enum | strict | standard | permissive | execution.policy (core.command_policy PROFILES) |
execution.max_iterations | integer | 1–200 | max_iterations (core.agent) |
execution.session_budget_usd | number | 0–1000000 | session_budget_usd (core.agent_budget; 0 = unlimited) |
- PUT refusals are TYPED:
400 unknown_setting_key(message lists the nearest known keys),400 setting_out_of_bounds,400 setting_type_mismatch. Refusals never persist, audit or publish. GET /api/v1/managed-settingsanswers{ok, data, schema}; the server-injecteddata._schema_revis metadata (never persisted) and a worker running an older schema rev SKIPS the payload loudly (upgrade Luna) rather than applying a partial contract.- Stored keys written before the schema existed (
theme, arbitrary maps) remain in the snapshot but are IGNORED by Luna (loud skip + counter) and rendered read-only by the console — no free-text JSON editing. - Sol-side runtime consumers: honestly NONE today. The plane’s
contract is fleet-push-to-Luna; the Sol
managed_settingsstore is read only by this API. Wire: PUT → PUBmanaged_settings_update→ Luna bounded refetch (≥5 s between fetches, cache preserved on failure).
Advanced & Regeneration Tuning Keys
These keys are read directly from the sol application env (config file, or the env mapping named below) and were previously discoverable only by reading source (E-4). Defaults are the code fallbacks; a shipped sys.config/sys.prod.config value wins when set. Keys whose default is shown as — (unset) are optional overrides.
ZMQ transport & bridge
| Key | Restart | Type | Default | Env Var | Description |
|---|---|---|---|---|---|
zmq_frame_mac | per-call | enum | required | — | Worker-plane frame MAC posture: required / prefer / off. required refuses unsigned frames. |
zmq_frame_mac_legacy | per-call | boolean | false | — | Legacy-window acceptance for v1 (Z1, tx-less) MACs during the material-v2 cutover. |
zmq_frame_mac_d1542_legacy | per-call | boolean | false | — | Type-scoped straggler window for cancel_task/plugin_tool_call frames from previous workers. |
zmq_enrollment_allow_invalid | per-call | boolean | false | — | Test-only escape hatch: admit syntactically invalid enrollment records (never set in production). |
zmq_enrollment_ctr_required | per-call | boolean | true | — | Require the monotonic ready-counter in the registration material. |
zmq_frame_mac_rollback_ack | per-call | boolean | false | SOL_ZMQ_FRAME_MAC_ROLLBACK_ACK | : acknowledge a zmq_frame_mac value other than required. Without this the boot REFUSES (unsigned frames accepted). |
zmq_frame_mac_legacy_ack | per-call | boolean | false | SOL_ZMQ_FRAME_MAC_LEGACY_ACK | : acknowledge zmq_frame_mac_legacy=true (tx-less MAC material accepted). Without this the boot REFUSES. |
zmq_frame_mac_d1542_legacy_ack | per-call | boolean | false | SOL_ZMQ_FRAME_MAC_D1542_LEGACY_ACK | : acknowledge zmq_frame_mac_d1542_legacy=true (unsigned cancel_task/plugin_tool_call accepted). Without this the boot REFUSES. |
zmq_enrollment_ctr_required_ack | per-call | boolean | false | SOL_ZMQ_ENROLLMENT_CTR_REQUIRED_ACK | : acknowledge zmq_enrollment_ctr_required=false (nonce-only replay bound). Without this the boot REFUSES. |
zmq_ownership_enforced_ack | per-call | boolean | false | SOL_ZMQ_OWNERSHIP_ENFORCED_ACK | : acknowledge zmq_ownership_enforced=false (executor-ownership gates off). Without this the boot REFUSES. |
zmq_bridge_allow_unsigned | per-call | boolean | false | — | Mango bridge: accept unsigned inbound frames (fail-closed default; the bridge refuses to boot without a secret). |
zmq_bridge_ts_window_ms | per-call | integer | 120000 | — | Mango bridge HMAC timestamp freshness window (ms). |
zmq_mango_recv_watchdog_ms | per-call | integer | 30000 | — | Mango bridge receive-watchdog bound: a silent SUB pipe reconnects after this. |
zmq_mango_resync_ms | per-call | integer | 60000 | — | Mango revocation-resync interval during normal operation (ms). |
zmq_mango_sub_rcvhwm | per-call | integer | 5000 | — | Mango bridge SUB socket receive high-water mark. |
zmq_pub_linger | per-call | integer | 1000 | — | PUB socket linger (ms) at close. |
zmq_pub_sndhwm | per-call | integer | 5000 | — | PUB socket send high-water mark. |
zmq_pub_sndtimeo_ms | per-call | integer | 5000 | — | PUB send timeout (ms) — chumak has no SNDTIMEO, the send bound is enforced at the call site. |
zmq_router_rcvhwm | per-call | integer | 10000 | — | ROUTER socket receive high-water mark. |
zmq_router_sndhwm | per-call | integer | 10000 | — | ROUTER socket send high-water mark. |
zmq_sender_outbound_bound | per-call | integer | 512 | — | Per-identity outbound frame bound per 60s window (control lane keeps a +64 reserve); drops are counted loudly. |
zmq_cancel_tombstone_ttl_ms | per-call | integer | 300000 | — | Recent-cancel tombstone TTL (ms) — dedupes duplicate cancel deliveries. |
zmq_ready_ctr_max_age_ms | per-call | integer | 600000 | — | Ready-counter freshness bound (ms) — a counter older than this cannot admit a reconnect. |
zmq_recv_watchdog_ms | per-call | integer | 30000 | — | Gateway receive-watchdog bound (ms) — a silent ROUTER pipe forces a reconnect. |
zmq_replay_fence_file | per-call | string | — (unset) | — | Path of the durable replay-fence state file; unset uses the anchored data dir. |
zmq_replay_fence_journal_file | per-call | string | — (unset) | — | Path of the durable replay-fence append journal; unset derives it from the snapshot path. |
zmq_bridge_nonce_journal_file | per-call | string | — (unset) | — | Path of the durable Mango bridge nonce journal; unset uses the anchored data dir. |
zmq_fallback_max_rearms | per-call | integer | 10 | — | HTTP streaming ZMQ-fallback re-arm bound per stream. |
zmq_control_journal_ttl_ms | per-call | integer | 21600000 | — (sys.config only) | : TTL (ms; 6h) for a journaled control frame (cancel/spawn_ack) targeting an unreachable identity; older records are no longer replayed. |
zmq_control_replay_attempt_cap | per-call | integer | 8 | — (sys.config only) | : replay-attempt cap for a live journaled control frame; at the cap the record is retired (the outstanding-control gauge drains). |
zmq_egress_quarantine_ms | per-call | integer | 5000 | — (sys.config only) | : how long a task whose egress repeatedly fails is quarantined before the recovery lane retries it (ms). |
zmq_preauth_global_known_limit | per-call | integer | 2000 | — (sys.config only) | (ADV-A-02): global 60s ceiling for unregistered-frame replies from KNOWN (previously registered) delivering pipes; distinct from zmq_preauth_global_limit (unknown pipes). |
zmq_replay_tx_max_future_ms | per-call | integer | 120000 | — (sys.config only) | : future-tx tolerance (ms) — a frame tx more than this ahead of the Sol wall clock is refused as skew (never silently stamped). |
zmq_transport_retry_backoff_ms | per-call | integer | 300 | — (sys.config only) | : base retry backoff (ms) for a failed egress send; values below 250 fall back to 300. |
zmq_transport_retry_cap | per-call | integer | 8 | — (sys.config only) | : consecutive transport retry attempts before the task is quarantined for zmq_egress_quarantine_ms. |
Events & archive
| Key | Restart | Type | Default | Env Var | Description |
|---|---|---|---|---|---|
event_lane_count | boot | integer | 8 | — | Number of per-aggregate event sequencer lanes; frozen at boot (sol_sync_event:init/1). |
event_payload_max_bytes | per-call | integer | 1048576 | — | Maximum encoded event payload size (bytes); larger payloads are refused at admission. |
event_replay_on_boot | boot | boolean | true | — | Replay the durable event store into projections at boot. |
event_replay_disabled_ack | boot | boolean | false | — | Explicit degraded-posture ack for event_replay_on_boot=false: unset refuses boot (the RAM views would be empty); true proceeds unproven with /ready 503 and event retention refused until a successful replay. |
replay_all_max_events | per-call | integer | 50000 | — | Cap for the paged sol_sync_event:replay_all/1 projector walk; the walk stops page-aligned and counts replay_all_truncated_total. |
projection_outbox_max_rows | per-call | integer | 10000 | — | Projection outbox row cap; a NEW owed row past the cap is quarantined (projection_outbox_quarantined_total), refreshes always allowed. |
event_forwarder_rearm_ms | per-call | integer | 60000 | — | Cadence (ms) of the durable lane’s store-forwarder re-arm/gauge refresh after an N-strike handler removal. |
schema_quarantine_max_events | per-call | integer | 50000 | — | Cap for the durable archive schema-quarantine dead-letter; a 4xx page is accounted there and the drain advances. |
event_compaction_budget_ms | per-call | integer | 15000 | — | Per-compaction-cycle wall-clock budget (ms). Code fallback 15000 — sol_event_compactor.erl ?COMPACT_BUDGET_MS. |
event_seq_cleanup_threshold | per-call | integer | 100000 | — | Compacted-sequence rows retained before the seq table cleanup runs. |
event_router_subscribe_retry_ms | per-call | integer | 5000 | — | Event-router subscription retry cadence (ms) when the store is not yet up. |
staging_recover_max_chunks | per-call | integer | 64 | — | Maximum staged WAL chunks recovered per boot pass. |
archive_ack_drain_budget_ms | per-call | integer | 10000 | — | Mango archive-ack drain budget per cycle (ms). |
archive_ack_max_passes | per-call | integer | 64 | — | Maximum ack-drain passes per archive cycle. |
archive_mailbox_max | per-call | integer | 5000 | — | Live-archive gen_server mailbox bound; live metadata casts are refused (counted) at/over this depth while a slow archive holds the flush. |
archive_gen_server_mailbox_bound | per-call | integer | 1200 | — | (EV-09): the archive gen_server’s OWN mailbox bound (above the 1000 queue + 100 batch so a legitimate burst still exercises the queue overflow). At/over it the incoming cast is dropped loudly (event_archive_mailbox_dropped_total; the Mnesia row + staging retain the event). |
archive_overflow_log_interval_ms | per-call | integer | 60000 | — | Minimum interval between live-archive queue-overflow warnings (the drop counter still counts every refused event). |
subscriber_queue_limit | per-call | integer | 256 | — | Per-subscriber bounded event queue depth (overflow is shed + counted). |
max_subscriptions_per_process | per-call | integer | 16 | — | SSE/event subscriptions admitted per process (per-process cap). |
sync_event_async_mailbox_max | per-call | integer | 10000 | — | Async event-forwarder mailbox bound before shedding. |
sync_event_shed_journal_max_bytes | per-call | integer | 4194304 | — | Durable shed-journal segment bound (bytes). |
telemetry_archive_enabled | per-call | boolean | true | — | Persist telemetry events into the ETS telemetry store + archive leg. |
metrics_persist_dir | per-call | string | — (unset) | — | Metrics-counter dump directory override; unset uses the anchored data dir. |
path_latency_max_paths | per-call | integer | 64 | — | Maximum distinct paths tracked by the latency histogram owner. |
goal_projector_sub_retry_ms | per-call | integer | 1000 | — | Goal projector subscription retry cadence (ms). |
goal_catchup_max_events | per-call | integer | 1000 | — | Max workflow events replayed per goal catch-up window. |
goal_projector_sub_retry_max | per-call | integer | 10 | — | Goal projector subscription retry attempts before giving up loudly. |
goal_retention_ms | per-call | integer | 2592000000 | — | Terminal-goal retention window (ms; 30 days). |
bridge_correlation_ttl_ms | per-call | integer | 300000 | — | Workflow-bridge correlation entry TTL (ms). |
Task store & idempotency
| Key | Restart | Type | Default | Env Var | Description |
|---|---|---|---|---|---|
idempotency_window_ms | per-call | integer | 86400000 | — | Idempotency discard-table window (ms; 24h) — duplicate task ids inside the window replay the stored verdict. |
idempotency_max_rows_per_user | per-call | integer | 1024 | — | (BVI-013): per-user cap on live idempotency claims; an insert over it is refused typed ({over, per_user}) and the caller gets a 429. Non-positive values fall back to 1024. |
idempotency_max_rows_global | per-call | integer | 100000 | — | (BVI-013): fleet-wide cap on the idempotency table; an insert over it is refused typed ({over, global}) and the caller gets a 429. Non-positive values fall back to 100000. |
task_idempotency_sweep_budget | per-call | integer | 2000 | — | (BVI-013): rows deleted per paged idempotency-sweep pass (range 1–20000, outside → 2000). The sweep runs in a spawned worker, never inside the store writer. |
task_store_terminal_mnesia_bound_ms | per-call | integer | 5000 | — | (BVI-012): production-sized bound (ms) for the terminal durable write + failure-readback leg (range 1000–12000, outside → 5000). The 1s task_store_mnesia_bound_ms stays the liveness seam for probes/reads; the terminal leg needs the larger dump-tolerant window. |
task_ttl_ms | per-call | integer | 3600000 | — | Task-store row TTL (ms) for non-terminal rows swept by retention. |
task_result_retention_ms | per-call | integer | 604800000 | — | Terminal task-result retention window (ms; 7 days). |
task_retention_sweep_budget_ms | per-call | integer | 400 | — | Retention-sweep pass budget (ms) — a pass yields and resumes next tick. |
task_store_mnesia_bound_ms | per-call | integer | 1000 | — | Per-operation Mnesia bound (ms) before the ETS fallback verdict is used. |
task_store_terminal_marker_pages_per_pass | per-call | integer | 8 | — | : per-reconcile-pass page budget for the continuation-threaded needs_reconcile terminal-marker walk (500 markers per page). A deferred tail is counted task_store_terminal_marker_walk_deferred_total and resumes next pass. |
task_store_terminal_marker_walk_bound_ms | per-call | integer | 10000 | — | : bound (ms) on one marker-walk activity (the mnesia select continuation must stay inside the activity that created it, so the walk owns a longer explicit bound than the store’s default 1s). |
outbox_journal_compact_bytes | per-call | integer | 8388608 | — | Dispatch-outbox journal size (bytes) above which the clear chokepoint atomically rewrites it to the outstanding receipt set. |
zmq_store_mailbox_shed_threshold | per-call | integer | 5000 | — (sys.config only) | : task-store mailbox depth at which new writes are shed (counted) instead of deepening the mailbox; 0 disables the shed latch. |
zmq_store_shed_after_ms | per-call | integer | 5000 | — (sys.config only) | : age (ms) after which a latched mailbox-shed posture is cleared/re-probed. |
outbox_journal_compact_min_interval_ms | per-call | integer | 60000 | — | Minimum interval (ms) between outbox journal compactions. |
Chat history
| Key | Restart | Type | Default | Env Var | Description |
|---|---|---|---|---|---|
chat_seq_backfill_budget | per-call | integer | 50000 | — | Chat-history seq backfill batch budget per pass. |
chat_session_boot_restore_cap | boot | integer | 2000 | — | Maximum chat sessions re-hydrated from disk at boot (sol_chat_sessions_owner:init/1 restore). |
chat_session_retention_days | per-call | integer | 30 | — | Chat-session metadata retention window (days; the message store keeps its own retention). |
Workflow engine
| Key | Restart | Type | Default | Env Var | Description |
|---|---|---|---|---|---|
workflow_recovery_enabled | boot | boolean | true | — | Run boot recovery (compensation of crashed instances) for the workflow engine. |
workflow_boot_recovery_grace_ms | per-call | integer | 60000 | — | Boot-recovery grace before an instance is considered crashed (ms). |
workflow_boot_rescan_margin_ms | per-call | integer | 1000 | — | : extra margin before the post-boot stale-row rescan (ms); keeps the rescan outside the crash-recovery grace window. |
workflow_force_resume_stale_ms | per-call | integer | 60000 | — | : a recovered instance whose last progress is older than this is force-resumed by the recovery pass (ms). |
workflow_legacy_unscoped_completion | per-call | boolean | false | — | migration window: accept unscoped/first-attempt workflow completions from pre-marker producers. Default false (fail-closed); remove after the migration window. |
workflow_recovery_compensation_budget_ms | per-call | integer | 30000 | — | Per-instance boot-compensation budget (ms). |
workflow_recovery_max_compensations | per-call | integer | 100 | — | Maximum instances compensated per boot-recovery pass. |
workflow_compensation_timeout_ms | per-call | integer | 65000 | — | Compensation step timeout (ms). Code floor 65000 = the 60000 ms worker kill ceiling + 5000 ms margin (sol_workflow_instance.erl ?COMP_KILL_CEILING_MS + ?COMP_WINDOW_MARGIN_MS); values below the floor are clamped UP and warned once per boot — the pre-fix doc’s 60000 was not settable. |
workflow_inline_compensation_timeout_ms | per-call | integer | 60000 | — | Inline-compensation kill ceiling (ms) — must stay under the instance kill window. |
workflow_revocation_mark_window_ms | per-call | integer | compensation window + 5000 | — | (WSC-14): bounded post-cancel revocation-marker fallback window (ms; default derives from workflow_compensation_timeout_ms). Values ≤5000 fall back to the derived default — the old fixed 5s window could not outlive a slow unwind. |
workflow_budget_auto_stop_ms | per-call | integer | 86400000 | — | Wall-clock budget after which a running workflow auto-stops (ms; 24h). |
workflow_state_retention_ms | per-call | integer | 2592000000 | — | Terminal workflow-state retention window (ms; 30 days). |
workflow_decomp_definition_cap | per-call | integer | 5000 | — | Decomposition-definition registry row cap. |
workflow_decomp_definition_ttl_ms | per-call | integer | 3600000 | — | Decomposition-definition registry row TTL (ms). |
workflow_decomp_definition_durable_ttl_ms | per-call | integer | 2678400000 | — | : durable decomp-* definition retention (ms; default 31 days — one day past the terminal workflow-state retention so a resumable row never outlives its definition). The ETS cache TTL/cap never shortens it. |
workflow_max_active_per_user | per-call | integer | 500 | — | : live workflow-instance admission cap per principal (0 disables the axis); refusal is {workflow_limit_reached, {principal, Cap}} → HTTP 429 + workflow_admission_refused_total. |
workflow_max_active | per-call | integer | 5000 | — | : live workflow-instance admission cap for the whole node (0 disables the axis); refusal is {workflow_limit_reached, {global, Cap}} → HTTP 429. |
workflow_store_resub_ms | per-call | integer | 1000 | — | Workflow-store resubscribe retry cadence (ms). |
workflow_store_resub_max | per-call | integer | 10 | — | Workflow-store resubscribe attempts before the instance is marked crashed_unrecovered. |
workflow_lease_reaper_interval_ms | per-call | integer | 720000 | — | LEGACY ALIAS of scheduler_lease_reaper_interval_ms. The effective default is 2 *?STUCK_JOB_GRACE_MS = 2 × 360000 = 720000 ms (sol_scheduler:stuck_grace_ms/0, which is itself max(?STUCK_JOB_GRACE_MS, plugin_execute_timeout_ms + slack + plugin dwell) = 360000 at the shipped plugin budget); the alias is nested inside the scheduler key read, so the scheduler key wins when both are set. |
instance_cleanup_ttl_ms | per-call | integer | 600000 | — | Terminal workflow-instance in-memory record TTL (ms) before GC. |
Scheduler
| Key | Restart | Type | Default | Env Var | Description |
|---|---|---|---|---|---|
scheduler_store_debounce_ms | per-call | integer | 2000 | — | Scheduler store persistence debounce (ms) for bulk edits. |
scheduler_journal_compact_bytes | per-call | integer | 262144 | — | : appended-byte threshold that arms the scheduler journal’s compaction tick. Claims append one fsynced frame (O(1) in job count); crossing the threshold schedules the whole-table snapshot compaction on the store’s idle tick (never on the claim call). flush/0 always compacts synchronously under the shutdown bound. |
scheduler_mirror_claims | per-call | boolean | false | — | Mirror single-writer job claims across the cluster. |
scheduler_await_ceiling_ms | per-call | integer | 0 (derive: task_max_lifetime_ms + 120 s) | — | Ceiling (ms) for the scheduler’s bounded wait-for-terminal loop around dispatched tasks; an exhausted await is the typed dispatch_timeout class (no job-error increment). 0 derives the ceiling; an explicit override is floored at 300000. |
max_stored_jobs | per-call | integer | 10000 | — (sys.config only) | : cap on persisted scheduler jobs (active + retained terminal rows); a create over the cap answers the typed cap verdict instead of growing the store. |
scheduler_terminal_retention_ms | per-call | integer | 604800000 | — (sys.config only) | : terminal scheduler-job retention window (ms; 7 days) before the sweep removes the row. |
Plugins
| Key | Restart | Type | Default | Env Var | Description |
|---|---|---|---|---|---|
plugin_execute_timeout_ms | per-call | integer | 60000 | — | Per plugin tool-execution timeout (ms). |
plugin_lifecycle_wall_clock_ms | per-call | integer | 30000 | — | Plugin lifecycle-call wall-clock watchdog (ms). |
plugin_max_concurrent_executors | boot | integer | 64 | — | Plugin executor process cap. |
plugin_max_scheduled_jobs | per-call | integer | 100 | — | Per-plugin scheduled-job cap. |
plugin_max_subscriptions | per-call | integer | 64 | — | Per-plugin event-subscription cap. |
plugin_min_interval_ms | per-call | integer | 1000 | — | Minimum interval floor for plugin scheduled jobs (ms). |
plugin_queue_dwell_max | per-call | integer | 16 | — | Per-plugin FIFO queue-dwell cap before a 429 busy-with-retry-hint. |
plugin_http_sweep_ms | per-call | integer | 60000 | — | Plugin HTTP connection-pool sweep cadence (ms). |
plugin_http_conn_max_age_ms | per-call | integer | 300000 | — | Plugin HTTP pooled-connection max age (ms). |
Inference & model registry
| Key | Restart | Type | Default | Env Var | Description |
|---|---|---|---|---|---|
inference_restart_retries | per-call | integer | 3 | — | llama.cpp restart attempts before the lane is marked failed. |
inference_restart_backoff_ms | per-call | integer | 5000 | — | llama.cpp restart backoff (ms). |
inference_restart_strike_decay_ms | per-call | integer | 1800000 | — | Stable-ready window that clears one auto-restart strike (default 30 min); an exhausted lane is quarantined and re-probed on this cadence. |
ready_health_interval_ms | per-call | integer | 30000 | — | READY health-probe interval (ms) for loading engines. |
scale_down_grace_ms | per-call | integer | 15000 | — | Autoscaler scale-down drain grace (ms). |
pipeline_admission_timeout_ms | per-call | integer | 30000 | — | Admission wait bound (ms) before a request is answered 503/429. |
provider_health_tls_verify | per-call | boolean | true | — | TLS peer verification for the provider-health probe (must stay true outside loopback). |
model_prepare_tmp_ttl_ms | per-call | integer | 3600000 | — | Registry prepare staging-file TTL (ms) before the boot sweep removes it. |
embed_max_concurrency | per-call | integer | 4 | — | Embedding-pool concurrent request cap (the async bounded pool). |
embed_max_batch | per-call | integer | 256 | — | : the embed_batch/2 fan-out wave size — helper processes are spawned in bounded chunks, never one per input text. |
cost_legacy_metadata_price | per-call | boolean | false | — | : re-enables the LEGACY bundled-metadata rate source when the catalog has no row. Off by default — the catalog is the one rate source. |
embed_max_queue | per-call | integer | 64 | — | Embedding-pool queue depth cap. |
lane_benchmark_csv | per-call | string | — (unset) | — | Benchmark-artifact path consumed by lane validation (prod config points at /opt/sol/data/local-inference-benchmark.csv). |
lane_inventory_expire_after_ms | per-call | integer | — (unset) | — | Fleet-inventory row expiry override (ms); unset derives the bound from the heartbeat cadence. |
lane_placement_inflight_max | per-call | integer | 8 | — | Maximum in-flight lane placements admitted by the orchestrator. |
lane_resolve_cold_async | per-call | boolean | true | — | Resolve cold lanes asynchronously instead of blocking the dispatch path. |
Workers & licensing
| Key | Restart | Type | Default | Env Var | Description |
|---|---|---|---|---|---|
license_fail_mode | per-call | enum | — (unset → refuse) | — | License-check failure posture for worker spawns (refuse is the shipped behavior; the lever is read by sol_worker_sup). |
team_ghost_grace_ms | per-call | integer | 3600000 | — | Team ghost-member expiry grace (ms) before the sweeper removes the member. |
Auth, audit & shares
| Key | Restart | Type | Default | Env Var | Description |
|---|---|---|---|---|---|
audit_archive_secret | per-call | string | — (unset) | SOL_AUDIT_ARCHIVE_SECRET | HMAC secret for the Mango audit-archive POST leg; must equal Mango’s MANGO_AUDIT_ARCHIVE_SECRET. |
audit_retention_days | per-call | integer | 30 | — | Audit JSONL retention window (days). Range 1–3650, validated at boot. Config-file twin: [audit] retention_days. The daily sweep deletes only CLOSED day files strictly older than the clamped cutoff — today’s open file and the newest closed day always survive. |
audit_strong_consistency | per-call | boolean | true | — | fsync audit appends before acknowledging (tamper-evidence first). |
mango_bridge_hmac_secret | per-call | string | — (unset) | — | Shared HMAC secret for the Mango event bridge (boot refuses without it when the bridge is enabled). |
auth_flush_on_reconnect | per-call | boolean | true | — | Flush every Sol-side auth cache once when the Mango bridge reconnects: a role/team/user demotion made during a bridge outage lands within the reconnect window, not the per-user cache TTL. The flush is O(cache size) per reconnect; set false to restore the previous costed posture. |
share_quota_per_user | per-call | integer | 100 | — | Session-share links per user before the quota 429. |
share_rate_limit_per_min | per-call | integer | 30 | — | Per-IP session-share read rate limit (requests/min). |
share_rate_max_keys | per-call | integer | 10000 | — | Bound on the share rate-limiter key table: distinct per-IP buckets tracked before new keys are refused admission to the table (existing buckets keep counting), so a hostile address spray cannot grow memory without bound. |
share_reap_budget | per-call | integer | 2000 | — | Expired-share reap budget per sweep pass. |
Mango audit-archive cutover levers. Mango’s own
receiver config is mango/conf.py, but these two env-only levers belong to
the Sol↔Mango archive wire and are set on the MANGO leg:
| Variable | Default | Meaning |
|---|---|---|
MANGO_AUDIT_ARCHIVE_ALLOW_V1 | unset (v1 refused) | Accept the legacy v1 archive HMAC during a documented one-window cutover. Leave unset on a stock deployment: the Sol sender shipped since then speaks HMAC v2 (X-Audit-Archive-Timestamp/-Nonce + body-bound material), so no ack is needed. Mango logs a once-per-boot WARNING when the ack IS set (the replayable-wire posture); MANGO_AUDIT_ARCHIVE_REQUIRE_V2=1 refuses v1 even under the ack. Strict boolean: a typo refuses boot. |
MANGO_AUDIT_ARCHIVE_REQUIRE_V2 | unset | Hard-refuse v1 (overrides the ack). Set only AFTER the Sol sender upgrade to the v2 timestamp/nonce material. Strict boolean. |
Mango identity-plane levers. These are Mango-process env
levers (read by mango/); Sol does not read them.
| Variable | Default | Meaning |
|---|---|---|
MANGO_SERVICE_TOKEN_DEFAULT_SCOPE | unset → the read-only inventory | Default scope minted when a service-token request carries no explicit scope. default selects users:read,orgs:read,teams:read,tasks:read,roles:read; a comma-separated verb list is clamped to the owner’s live grant (an empty clamp is now a typed 400 refusal, never an inert token); legacy/none/unscoped restores the previous full-RBAC mint LOUDLY (one migration window). A malformed value refuses the mint (503), never a silent widening. NOTE: the read-only inventory does NOT include orchestrator:lease or revocations:read — a Sol service account minted with the default must request those explicitly (or mint in the legacy/unscoped window). |
MANGO_SERVICE_TOKEN_ALLOW_UNSCOPED | false | One-window legacy lever: with no MANGO_SERVICE_TOKEN_DEFAULT_SCOPE set, true mints the historical full-RBAC (NULL-scope) service token by default and logs a warning. Unset it after rotating integrations to explicit scopes. |
MANGO_LDAP_BREAK_GLASS_DURING_OUTAGE | false | While the LDAP outage circuit is open, email-shaped logins answer ONE uniform typed 503. true explicitly restores the local break-glass fallback for local accounts during an outage; a deliberate, visible weakening. |
MANGO_LEGACY_SESSION_COOKIE | false | Session auth reads only the __Host--prefixed cookie. true re-enables the legacy zerg_session reader for the documented migration window. The legacy name is still EMITTED for Sol/Limon readers either way; CSRF cookies keep their migration fallback (not a credential). |
MANGO_LIMITER_KNOWN_HEADROOM | MAX_KEYS // 10 (1000 of 10000) | Capacity reserved for RESOLVED identities: unknown keys stop at MAX_KEYS - headroom, so a junk-identity flood cannot deny a known user’s login. Absolute MAX_KEYS still caps every class; a malformed value falls back to the default. |
MANGO_MAX_LOCK_ENTRIES | 10000 | Live hard-lockout entries retained before overflow eviction (counted, with a transition warning + once-per-1000 log bound). |
MANGO_MAX_LOCK_ENTRIES_HARD | 2 × MANGO_MAX_LOCK_ENTRIES | Hard ceiling for the lockout dict; when an ACTIVE entry must be evicted the operation is counted (the per-account bucket still bounds the attacker). Never below MANGO_MAX_LOCK_ENTRIES. |
MANGO_MAX_USERS | unset (NOT enforced) | DE-CLAIMED: Mango does not enforce a user cap. The Sol seat map still carries max_users, but docs/seats.md records the non-claim (no signed Sol→Mango seat datum exists); the name is reserved for that future datum. |
Chat turn lease & idempotency
The session turn plane (sol_chat_sessions_owner + sol_chat_turn_plane)
enforces one live turn per session across WS and REST and powers the
client_turn_id replay contract (see docs/api-reference.md, chat message).
| Key | Restart | Type | Default | Env Var | Description |
|---|---|---|---|---|---|
chat_turn_lease_ttl_ms | per-call | integer | task_timeout_ms + chat_turn_lease_grace_ms (360000) | — | Absolute lease TTL override (ms). Unset derives from the task deadline plus the grace; a live holder is extended, never preempted by wall clock alone. |
chat_turn_lease_grace_ms | per-call | integer | 60000 | — | Grace added to task_timeout_ms when chat_turn_lease_ttl_ms is unset (the no-relay TTL fallback window). |
chat_turn_lease_renew_ms | per-call | integer | derived: min(30000, max(1000, ttl div 4)) | — | Caller-side renewal throttle for a live turn’s lease (token/progress renews at most once per window). |
chat_turn_dedupe_ttl_ms | per-call | integer | 300000 (5 min) | — | Content-bound client_turn_id replay window; replayed after the window duplicates by contract. |
chat_turn_dedupe_max_per_session | per-call | integer | 32 | — | Per-session cap on the dedupe side table (oldest evicted at insert). |
HTTP & streaming
| Key | Restart | Type | Default | Env Var | Description |
|---|---|---|---|---|---|
client_timeout_max_ms | per-call | integer | 600000 | — | Ceiling for client-supplied per-request timeouts (sol_http_validation). |
sse_heartbeat_ms | per-call | integer | 15000 | — | SSE heartbeat cadence (ms) — keeps idle streams alive through proxies. |
sse_stream_shutdown_grace_ms | per-call | integer | 2000 | — | : grace after the age sweep’s typed {sol_stream_shutdown} before the reaper kills the stream process; accounting is released only after the DOWN (never a released-but-alive slot). |
sse_write_ack_timeout_ms | per-call | integer | 15000 | — | : the bounded Cowboy data-ack deadline for FOREIGN stream writers (sol_http_stream — chat pumps and replay producers). A timeout/connection DOWN is a typed error + stream_writer_abandoned_total, so the caller releases its admission/session row; non-positive/non-integer values fall back to 15000. |
Health & backups
| Key | Restart | Type | Default | Env Var | Description |
|---|---|---|---|---|---|
sol_health_process_warn | per-call | number | 0.8 | — | Process-count warn threshold (fraction of the Erlang process limit). |
sol_health_process_crit | per-call | number | 0.95 | — | Process-count critical threshold (fraction of the Erlang process limit). |
sol_health_memory_warn_bytes | per-call | integer | 4294967296 | — | Memory warn threshold (bytes). |
sol_health_disk_warn_bytes | per-call | integer | 1073741824 | — | Disk free-space warn threshold (bytes). |
sol_health_disk_crit_bytes | per-call | integer | 104857600 | — | Disk free-space critical threshold (bytes). |
sol_health_mq_warn | per-call | integer | 100 | — | Message-queue depth warn threshold. |
sol_health_check_budget_ms | per-call | integer | 300 | — | : per-check budget for the bounded readiness runner. A check that misses its budget is a typed timeout error row (never a healthy default). Range 10–60000. |
sol_health_total_budget_ms | per-call | integer | 900 | — | : total deadline for the readiness fan-out; checks past it are typed total_deadline_exceeded rows. Keeps a wedged dependency under 1s. Range 10–120000. |
sol_health_disk_sample_ms | per-call | integer | 15000 | — | : the supervised disk sampler’s cadence (ms). Requests/scrapes only read the sampled cache; a sample older than 90s makes the disk check degraded (probe_stale). Range 1000–3600000. |
sol_health_core_queue_warn | per-call | integer | 5000 | — | (LIFE-13): message-queue warn tier for the core data-plane children (task store, workflow manager, scheduler, event store, cluster). Range 100–1000000. |
sol_health_core_queue_crit | per-call | integer | 20000 | — | : message-queue critical tier for the core data-plane children (readiness error). Range 100–1000000. |
health_expect_models | per-call | boolean | derived | — | : force the readiness model expectation. Unset = expect a serving model whenever the registry has rows; true makes an empty registry an error too. |
sol_health_owner_registry_check | per-call | boolean | true | — | (LIFE-4): owner-plane content check in the readiness ets probe. A registry (sol_models, sol_channels, sol_provider_registry) that had content under the same app instance but returns EMPTY under a NEW owner is a readiness error until the content is restored (or the same owner deliberately empties it). Set false to run an intentionally empty channel plane without the red verdict. |
health_expect_workers | per-call | boolean | derived | — | (LIFE-12): force the readiness worker expectation. Unset = expect workers when zmq_enabled and initial_workers > 0; true/false pin the verdict. |
http_max_connections | per-call | integer | 16384 | — | : the explicit HTTP listener admission cap, applied through ranch:set_max_connections/2 after the transport tail starts (the pre-fix ranch default was 1024 shared with the SSE budget). max_sse_connections stays a separate streaming budget within this pool. Exported as sol_http_connections_{active,max,utilization_pct}; the nofile requirement is max_connections + max_sse_connections + 1024. Range 1–1000000. |
mnesia_load_strict | per-call | boolean | set by sol_app to true for the release boot | — | (BVI-006): the durability-table load/create posture. true makes a failed disc-table create or an unloaded durability table a TYPED BOOT REFUSAL; eunit/partial boots leave it unset (loud degrade). Internal boot flag — operators never set it directly |
mnesia_force_load_on_timeout | per-call | boolean | false | — | (BVI-006): ack-gated operator lever — on a load-barrier timeout, force_load_table re-reads the local log. Enable ONLY after confirming the local log copy is authoritative (docs/operations #mnesia-load) |
sol_mnesia_load_bound_ms | per-call | integer | 15000 | — | (BVI-006): the boot load barrier’s wait_for_tables bound; a timeout publishes the typed pending verdict (strict boot refuses) |
maintenance_worker_settle_ms | per-call | integer | 1500 | — | Maintenance drain settle window (ms): the bounded wait for in-flight worker tasks before the gate flips. A drain that cannot settle returns the typed drain_incomplete, never a silent success. |
worker_bootstrap_retry_ms | per-call | integer | 1000 | — | First backoff (ms) when a worker’s async bootstrap (lane resolve/spawn) fails; doubles per attempt up to worker_bootstrap_retry_max_ms. |
worker_bootstrap_retry_max_ms | per-call | integer | 30000 | — | Backoff ceiling (ms) for the async worker bootstrap retry loop. |
worker_bootstrap_max_attempts | per-call | integer | 5 | — | Consecutive bootstrap failures before a parked worker GIVES UP: it exits {shutdown,{unavailable,_}} (no supervisor restart, slot released) instead of retrying forever. Bounds a deterministic spawn failure (missing binary, denied lane) to one slot and zero pool-budget burn. |
data_plane_check_ms | per-call | integer | 5000 | — | sol_data_plane_restorer keeper tick (100–60000): restore a missing data plane after the boot ladder completed, and monitor the live one. |
data_plane_restore_retry_ms | per-call | integer | 5000 | — | Delay (100–60000) between bounded data-plane restore attempts. |
data_plane_restore_max_attempts | per-call | integer | 5 | — | Consecutive restore failures (1–100) before the keeper logs CRITICAL and calls application:stop(sol) — a node never serves a dead data plane. |
worker_resolve_deadline_ms | per-call | integer | 10000 | — | Bounded deadline (ms) for the lane-resolve probe moved out of init/1 into the async bootstrap. |
mnesia_backup_retention_days | per-call | integer | 7 | — | Mnesia backup retention window (days). Range 1–3650, validated at boot. Config-file twin: [mnesia] retention_days. Rotation never deletes the artifact it just wrote; the success gauge is stamped only after the backup file exists and the manifest checksum reads back. |
sol_mnesia_backup_remote_path | per-call | string | "" | — | Remote backup copy target — an rsync DESTINATION DIRECTORY; the data file and its .manifest are copied as a verified pair. Empty disables the remote leg; a local absolute path is copied directly (temp+fsync+rename). |
mnesia_backup_offsite_lifecycle_managed | per-call | boolean | false | — | : operator attestation that a REMOTE offsite destination has an external lifecycle/retention policy. A locally-mounted destination is pruned by Sol automatically (same age + per-day retention); false on a remote destination makes sol_mnesia_backup_offsite_managed 0 and pages SolBackupOffsiteUnmanaged. |
scrape_deadline_ms | per-call | integer | 5000 | — | : the whole /metrics scrape deadline (ms). Once spent, remaining formatters are skipped (their families are ABSENT, counted in sol_scrape_deadline_exceeded_total) — a wedged dependency can never lose the whole scrape or the dead-man. Bound ≥500. |
airgap_mode | per-call | boolean | false | SOL_AIRGAP_MODE | : explicit air-gap posture ack. In prod, readiness normally requires an off-host backup target (offhost_target_required); airgap_mode=true makes the off-host leg optional while the LOCAL scheduled Mnesia backup stays mandatory (mnesia_backup_interval > 0 — 0 is a readiness local_backup_required error in an air-gapped prod node). Boolean grammar is strict (a non-boolean value refuses the boot). |
sol_exec_default_timeout_ms | per-call | integer | 120000 | — | Default wall-clock timeout for sol_exec-managed child processes (ms). |
Channels & marketplace
| Key | Restart | Type | Default | Env Var | Description |
|---|---|---|---|---|---|
channel_max_concurrent | per-call | integer | 5 | — | Maximum concurrent channel event deliveries. |
teams_validation_rate_per_minute | per-call | integer | 30 | — | Per-channel rate limit for the Teams subscription-validation echo (fixed one-minute window; over-limit answers a bounded 429). The echo also requires a configured teams_auth_token. |
unsigned_webhook_rate_per_minute | per-call | integer | 60 | — | Per-channel fixed-window body budget for allow_unsigned_webhooks=true channels (anonymous plugin dispatch). Over budget the webhook answers a bounded 429 + Retry-After: 60; each accepted delivery carries input_trust=anonymous_input in the audit event and dispatch log. |
marketplace_ratings_max_age_ms | per-call | integer | 7776000000 | — | Marketplace rating-row max age (ms; 90 days) before refresh. |
marketplace_ratings_sweep_ms | per-call | integer | 86400000 | — | Marketplace ratings sweep cadence (ms). |
memory_wal_drop_policy | per-call | enum | block | — | Memory-WAL overflow policy when the durable leg is down: block or drop (drop is counted loudly). |
memory_wal_sync_every_ops | per-call | integer | 0 | — | Fsync the active memory-WAL segment every N accepted enqueues (0 = off; the default keeps the historical throughput — ack means segmented/page-cache durable, power-loss is bounded by the flush cadence). |
memory_wal_sync_every_ms | per-call | integer | 0 | — | Fsync the active memory-WAL segment on the first enqueue after this interval (0 = off; no timer wakeups). |
cluster_lease_reports | per-call | boolean | — (unset → on) | — | Cross-node lease-report exchange lever (cluster maintenance). |
Air-Gapped Deployment
airgap_mode (SOL_AIRGAP_MODE) is the explicit air-gap posture ack. It
has ONE effect: in prod it relaxes the readiness requirement for an
off-host backup target (the local scheduled Mnesia backup remains
mandatory). It is not an egress switch. Egress is enforced by the opt-in
gates documented in security.md §Egress inventory: LUNA_ALLOW_OSV_CHECK (Luna/MCP OSV lookups — fail-closed,
default off), LUNA_ALLOW_TOOL_INSTALL (Luna tool auto-install downloads
and package-manager legs — fail-closed, default off; ) and
ZERG_ALLOW_EGRESS_UPDATE (zerg-cli update checks). Sol’s own outbound
sockets target deployment-configured endpoints only — but the inventory
also includes the license/seat refresh (seats_url;
seats_refresh_ms=30000) and OAuth token refresh for declarative
providers. In an air-gap, leave seats_url empty, disable unused OAuth
providers, and point Mango/provider/webhook URLs at in-cluster services.
Bind defaults (http_ip 127.0.0.1, zmq_bind_addr 127.0.0.1) keep the
control plane off the network. See
air-gap-install.md for the walkthrough.
Boot Validation & Strict Boot
The boot ladder is contractual — the HTTP listener (bound inside
sol_http:start/0 under sol_transport_sup) and the ZMQ sockets start only
AFTER the event store is initialized. The order, pinned by the
boot_order_lint CI gate:
sol_sup:start_link (static tree, no transport tail)
→ sol_config:validate_all (required keys, ranges, placeholder secrets)
→ sol_config:validate_optional (the ~44-entry optional battery — LIVE)
→ init_event_store (tables, registrations, boot replay)
→ gate_event_store_boot (strict refusal OR maintenance degrade)
→ supervisor:start_child (DEFERRED TRANSPORT: sol_transport_sup,
sol_plugin_sup, sol_memory_sup)
→ remaining init labels (workflow defs/compensations/providers,
workflow recovery)
→ check_strict_boot (post-init strict gate)
Before this change the transport tail was a static part of sol_sup, so
HTTP+ZMQ served stale/empty projections during the whole boot-replay window.
Strict boot is per-label. A failed init label is recorded per boot; what happens next depends on the levers, evaluated per label:
| Lever | Semantics |
|---|---|
| (no env set) | event_store defaults strict — the boot REFUSES ({refuse_boot, {strict_boot_init_failed, [event_store]}}) before any listener binds. Every other label defaults non-strict (warn-and-boot). |
{strict_boot, event_store} = false | The documented degraded posture: the boot continues, and maintenance mode is enabled BEFORE the transport starts — projection routes serve 503 maintenance_mode (the sol_auth_middleware gate; /health, /api/v1/health, /api/v1/ready, /metrics stay exempt) until the operator resolves the store. |
strict_boot = true (global master-override) | The data-integrity set (event_store, workflow_recovery) refuses the boot — unchanged from its pre- contract. |
{strict_boot, Label} = true/false | Per-label lever; wins over both the global override and the default for that label. |
The global master-override itself is a Sol app-env key:
| Key | Restart | Type | Default | Env Var | Description |
|---|---|---|---|---|---|
strict_boot | boot | boolean | false | — | global master-override: true makes the data-integrity init labels (event_store, workflow_recovery) refuse the boot; the per-label {strict_boot, Label} lever wins over it. Read once by sol_app:check_strict_boot/0 (boot-time only) |
validate_optional boot gate: the optional-key battery (range checks for
keys like max_active_requests, scale_down_grace_ms, embed_max_concurrency;
boolean-type checks for zmq_enabled, mango_auth_enabled, …) ACCUMULATES
every violation and refuses the boot with {error, {invalid_config, [Violation, …]}}, logging each violated entry loudly. Undefined keys are
exempt — the battery only judges keys the operator actually set. Violation
shapes mirror validate_config’s range checks: {out_of_range, Key, Val, Min, Max} and {wrong_type, Key, Val}.
VM Args
Defined in config/vm.args (development) and config/vm.prod.args (production).
| Arg | Default | Description |
|---|---|---|
-name | sol@127.0.0.1 | Erlang node name. Must be unique in cluster. |
SOL_CLUSTER_COOKIE | unset (dev) / required (prod) | Distribution cookie. The vm.args carry NO -setcookie line: the entrypoint installs the cookie as $HOME/.erlang.cookie mode 0400 (or SOL_COOKIE_FILE), so it never appears in ps/argv. Charset [A-Za-z0-9_@-], max 64 chars. prod: must be explicitly set, at least 16 chars, and must not be sol_cookie or the CHANGE_ME_GENERATE_A_UNIQUE_COOKIE placeholder — otherwise the boot refuses. The cookie must match across cluster nodes. sol_app:rotate_cookie/0 generates a 64-char hex cookie |
SOL_COOKIE | unset | Legacy alias for the distribution cookie (read only when SOL_CLUSTER_COOKIE is unset): sol_app:apply_cookie_override/0 calls erlang:set_cookie/2 at runtime (charset [A-Za-z0-9_-@], max 256 chars; invalid values are ignored with a warning). Prefer SOL_CLUSTER_COOKIE — the prod gate consumes that name. |
+A | 4 | Number of async threads |
+S | 4 | Number of scheduler threads |
+K | true | Enable kernel poll (epoll/kqueue) |
+hms | 8192 | Minimum heap size (words) |
+hmbs | 8192 | Minimum binary heap size (words) |
+zdbbl | 32768 | Distribution buffer busy limit (production only) |
Luna Agent Configuration
Luna loads configuration from JSON files, CLI arguments, and environment
variables (client/core/config.lua).
Config File Locations
Config files merge in this order (later wins — client/core/config.lua
discover_config_files/1, profile merged last at config.lua:347):
~/.luna.json < ~/.luna/settings.json < .luna.json < .luna/settings.json < .luna/settings.local.json < profile (Paths.profile_config_path)
| Location | Priority | Example |
|---|---|---|
| CLI arguments | Highest | --model glm-5.1 |
.luna/config.json | High | Project-local config |
~/.luna/config.json | Medium | User global config |
Each file is deep-merged on top of DEFAULT_CONFIG. Encrypted fields are
decrypted via core.age_crypto if present. Schema version lives in
_config_version (currently 1).
Security-relevant keys from the project-local files additionally require the repo-config consent gate (below).
CLI Arguments
| Argument | Short | Type | Default | Description |
|---|---|---|---|---|
--model | -m | string | glm-5.1 | Model alias or ID |
--permission-mode | -p | string | default | Permission mode: default, allow-all, deny-all, read-only, plan, auto |
--resume | -r | flag | false | Resume last session |
--print | — | flag | false | Non-interactive: print response and exit |
--session | -s | string | auto | Session file path |
--gc-sessions | — | flag | false | Dry-run the session-corpus GC and exit (no session/provider boot) |
--gc-apply | — | flag | false | Apply the session-corpus GC and exit (age/idle/lease guarded) |
--gc-max-age-days | — | number | config (30) | Age cutoff override for a GC run |
--gc-limit | — | number | unlimited | Maximum eligible sessions processed by one GC run |
--theme | — | string | default | Color theme: default, onedark |
--connect | — | string | — | Headless ZMQ worker mode: connect to the Sol ROUTER endpoint (e.g. tcp://127.0.0.1:5555) |
--id | — | string | — | Worker identity for --connect mode |
--pub-endpoint | — | string | — | Sol PUB endpoint for --connect mode (events) |
--editor | — | flag | false | Editor session posture (requires --connect): hold ONE lane lease across turns — adopt the first task-scoped grant, refresh it while active, release on exit. The lease rides the existing lane_control plane; there is no stdio lane-control verb |
--session-lane | — | string | — | Preferred lane/use case for the editor session (implies --editor); advisory — Sol still owns placement and may refuse typed |
--propose-edits | — | flag | false | Headless editor edit turn: write-class calls surface one validated tool_use proposal and are never executed; execute-class calls are refused. The editor reviews the diff and applies only on accept. See client/docs/vim-integration.md § |
Environment Variables
| Variable | Default | Description |
|---|---|---|
LUNA_MODEL | glm-5.1 | Default model (zmq_worker.lua; connect-mode task fallback) |
LUNA_LOG_LEVEL | info | Log level: debug, info, warn, error (main.lua) |
LUNA_CONFIG_PROVENANCE | unset (off) | boolean |
LUNA_SQLITE_PATH | ~/.luna/sessions.db | SQLite session DB path override (session_backend.lua) |
LUNA_BLOB_MAX_BYTES | 10485760 | Per-blob cap at store time (loud error on exceed); retrieve verifies content hash — torn blobs raise, never silently nil (blob_store.lua) |
LUNA_BWRAP_ALLOW_ROOT | unset | Explicit ack to run bwrap as real root |
LUNA_CLASSIFIER_ENABLED | unset | Force the AI permission classifier on/off (true/false; ai_classifier.lua) |
LUNA_PERMISSION_ASK_TIMEOUT_MS | 120000 | Worker-side ask wait timeout (ms) before a typed deny; the Sol registry owns the authoritative timeout |
LUNA_LEGACY_WRITE_IMPLIES_EXECUTE | unset | Override the coarse write⇒execute RBAC rule (config.lua/permission_checker.lua; default true — new installs set false) |
LUNA_ZMQ_ALLOWED_WORKSPACE_ROOTS | unset | Comma-separated allowlist of wire-supplied workspace roots (fail-safe; zmq_worker.lua) |
LUNA_ALLOW_OSV_CHECK | unset (off) | Opt-in egress gate for MCP/OSV vulnerability lookups (fail-closed; see security.md) |
LUNA_ALLOW_TOOL_INSTALL | unset (off) | Opt-in egress gate for tool auto-install network legs. Package-manager installs that use sudo additionally require explicit caller consent |
Advanced environment overrides
The production levers below were read by code with no live-doc mention
(the UW-6 audit). Defaults are the code defaults; ci/config_env_docs_parity_lint.py
keeps this table and the client/ READ corpus in lockstep (both
directions).
| Variable | Default | Description |
|---|---|---|
LUNA_MEMORY_MODE | dual | Memory backend selector: dual (default), json, sqlite, file, vector, hybrid, graph. Config key memory.mode wins over the env. graph is a real scoped KV-over-triples backend (one has_value triple per key); graph neighbour expansion is prefix-scoped. Memory refuses to start without $HOME (no /tmp fallback). |
LUNA_ANALYTICS_DB | ~/.luna/analytics.db | Local analytics SQLite path override (CLI/tests). |
LUNA_DATA_DIR | ~/.luna-relative | Packaging/deployment data-dir override. |
LUNA_SESSION_MAX_MESSAGES | 1000 (code default when unset) | Per-session record ceiling (Session.MAX_ALL_MESSAGES); older records are dropped with a counted WARN. This is an in-memory/JSONL cap, not a corpus GC — 0 drops all but the newest record set, it is NOT unbounded |
LUNA_SESSION_TOOL_RESULT_TURN_BUDGET_BYTES | 40000 | Per-operator-turn aggregate tool-result text budget; overflow renders a persisted-output marker + read_tool_output handle. 0 disables. |
LUNA_SESSION_FULL_OUTPUT_BLOB_BYTES | unset | Blob-spill threshold for tool output in sessions. |
LUNA_BLOB_MIGRATE_MAX_BYTES / LUNA_BLOB_MIGRATE_MAX_FILES | unset | One-shot blob-store migration bounds. |
LUNA_KEYRING_REQUIRED | config keyring_required (false) | Refuse the plaintext config fallback when no OS keyring exists. |
LUNA_SHA256_CLI | unset (off) | Opt-in openssl dgst backend for SHA-256/HMAC on large buffers; only 1/true arms it. Default OFF keeps MAC’d planes zero-fork (FFI, then the pure-Lua floor) — see crypto.md. |
LUNA_ALLOW_SESSION_KEYS | unset | SECURITY ACK: allow model-driven session-key combos (ctrl+alt+F2, alt+F2,…). Default REFUSE; only 1 consents (computer_use.lua). |
LUNA_ALLOW_INSECURE_TLS | unset | SECURITY ACK: acknowledge a caller’s verify_peer=false request. The transport still pins CURLOPT_SSL_VERIFYPEER=1 — this ack can never weaken TLS; it only silences the refusal and logs a warning (web_fetch_shared.lua). |
LUNA_ALLOW_PLAINTEXT_HTTP | unset | SECURITY ACK: permit plaintext http:// for NON-loopback in-process targets. Default REFUSE — non-loopback targets need https://; loopback is always reachable. The config twin is execution.sandbox.allow_plaintext_http=true (transport.lua). A failed TLS probe never downgrades silently. |
LUNA_SNAPSHOT_CLEANUP_AGE_HOURS | 24 | Git-snapshot auto-cleanup age. |
LUNA_SNAPSHOT_CLEANUP_INTERVAL_MS | 3600000 | Git-snapshot cleanup cadence. |
LUNA_SNAPSHOT_DEBOUNCE_MS | 2000 | Debounce after a mutating-tool completion. |
LUNA_SNAPSHOT_RETRY_BASE_MS | 500 | Git-snapshot retry backoff base (exponential). |
LUNA_SNAPSHOT_RETRY_CAP_MS | 30000 | Git-snapshot retry backoff cap. |
LUNA_SNAPSHOT_RETRY_MAX | 5 | Git-snapshot retry attempt bound. |
LUNA_TOOL_OUTPUT_COMPACT_THRESHOLD | code default | Token threshold for compact tool-output rendering. |
LUNA_TOOL_OUTPUT_COMPACT_HEAD_CHARS | code default | Head-chars kept by the compact renderer. |
LUNA_LANE_RESOLVE_TIMEOUT_MS | 120000 | Lane-resolve deadline override (clamped by the task timeout). |
LUNA_MCP_START_BUDGET_MS | 1500 | Bounded MCP bootstrap budget. |
LUNA_SIXEL / LUNA_IMAGE_PROTOCOL | unset | Terminal image protocol: LUNA_SIXEL=1 or LUNA_IMAGE_PROTOCOL=sixel enables sixel (term_probe.lua). |
LUNA_ZMQ_CURVE_PUBLICKEY / LUNA_ZMQ_CURVE_SECRETKEY | unset | Worker CURVE keypair (z85; non-loopback transport posture — see docs/zmq-security.md). |
LUNA_ZMQ_HANDSHAKE_IVL_MS | liveness default | ZMTP handshake interval. |
LUNA_ZMQ_HEARTBEAT_MS | liveness default | ZMTP heartbeat interval. |
LUNA_ZMQ_RCVHWM / LUNA_ZMQ_SNDHWM | liveness default | ZMQ high-water marks. |
LUNA_ZMQ_TCP_KEEPALIVE (+ _CNT / _IDLE_S / _INTVL_S) | 1 / OS defaults | ZMQ TCP keepalive posture. |
LUNA_ZMQ_TOKEN_BATCH_BYTES | transport default | Token-batch flush bound. |
LUNA_ZMQ_BUSY_LIVENESS_MS | liveness default | Busy-worker liveness window. |
LUNA_ZMQ_IDLE_NO_INBOUND_MS | max(4×idle window, 60000) | (RV-044): the HARD no-inbound ceiling for an idle registered worker. A successful fire-and-forget send (the 5 s heartbeat) is not bidirectional evidence — the send-success suppression only defers the trip to this ceiling. >0 sets an explicit ceiling in ms; 0 restores the legacy send-only suppression (never trips while sends succeed). Deliberately a bounded reconnect cadence, not a “never trip” posture (client/core/zmq_liveness.lua). |
LUNA_AI_PROVIDER / LUNA_AI_MODEL | config provider/model | Provider and model overrides for the headless/ZMQ task path (the config keys win when set). |
LUNA_AI_API_KEY | unset | API key for the shell/headless provider path. |
LUNA_WORKSPACE | unset | Declared config-resolver override for workspace_root (wins=fill: only when no file layer set it). |
LUNA_ZMQ_LIVENESS_MS | liveness default | Worker-liveness window (frame-stamp freshness). |
LUNA_ZMQ_TCP_KEEPALIVE_CNT | OS default | ZMQ keepalive probe count. |
LUNA_ZMQ_TCP_KEEPALIVE_IDLE_S | OS default | ZMQ keepalive idle seconds. |
LUNA_ZMQ_TCP_KEEPALIVE_INTVL_S | OS default | ZMQ keepalive probe interval. |
LUNA_ZMQ_TOKEN_BATCH_MS | 20 | Token-batch flush interval; 0 disables batching. |
LUNA_WEDGE_WATCHDOG_MS | task-timeout-derived | Wedge-watchdog progress-age threshold override. |
LUNA_CONCURRENT_TOOL_WAIT_MS | 300000 | Drain deadline for in-flight concurrent tools. |
LUNA_PENDING_RESULTS_MAX | 4096 | (BVI-068): cap on the in-RAM terminal-retransmit ledger (_pending_results). The cap matches the durable terminal spool; insert over it drops the OLDEST entry loudly (counted, with the durable row surviving when the spool is available). A non-positive/invalid value falls back to 4096. |
LUNA_SPAWN_GROUP_REGISTRY | unset (off) | (BVI-017): opt-in supervisor marker (=1) that enables the <data>/spawn_pgids registry consumed by client/contrib/luna-orphan-sweep.sh (starttime-checked orphan-group kill after a SIGKILLed Luna). Default off keeps test/embedded spawns out of the user’s real data dir; the runit unit sets it in production. |
LUNA_PTB_TIMEOUT_MS | plugin-bridge default | Plugin-bridge call timeout (Sol’s plugin_execute_timeout_ms twin). |
LUNA_REFUSE_WITHOUT_MONOTONIC | unset | Refuse startup when the real monotonic clock is unavailable (otherwise the watchdog degrades to wall clock, loudly). |
LUNA_SIGNAL_SHIM | built-in path | Dev/test path to the signal shim shared object (production uses the built binary). |
Luna→Sol endpoint family (the memory/vector-search and completion
client legs read these; the single documented port is SOL_HTTP_PORT,
). There is no SOL_PORT env var (retired; use
SOL_HTTP_PORT).
| Variable | Default | Description |
|---|---|---|
ZERG_API_URL | unset | Full base URL override; wins over host/port. |
SOL_HOST / SOL_HTTP_HOST | 127.0.0.1 | Sol HTTP host. |
SOL_HTTP_PORT | 21434 | Sol HTTP port. |
SOL_TOKEN / SOL_API_KEY | unset | Luna→Sol HTTP bearer (MANGO_TOKEN is also accepted). |
Luna completion entry — client/run --complete
reads one JSON object on stdin and writes raw completion text on stdout
(exit 0). It posts only to POST /v1/completions on Sol; it never calls
a lane /infill endpoint or ollama. Protocol and trim behavior:
docs/cli-reference.md.
Input: {"prefix","suffix","model?","max_tokens?","stop?","temperature?"};
an empty prefix is a no-op (no request). A configured bearer is attached as
Authorization: Bearer; plaintext credential transport is allowed only to a
loopback host unless ZERG_ALLOW_INSECURE=1 (the CLI transport matrix).
| Variable | Default | Description |
|---|---|---|
ZERG_COMPLETE_MODEL | unset | Completion model when the request and --model omit one; unset = Sol default. Do not point this at a non-FIM model. |
ZERG_COMPLETE_TOKENS | 96 | Completion-token budget when the request omits max_tokens (clamped to the server ceiling of 1024). |
ZERG_COMPLETE_TIMEOUT | 15 | Completion HTTP timeout (seconds). |
ZERG_COMPLETE_MAX_PREFIX_BYTES | 8000 | Prefix tail kept (nearest the cursor); 0 = unlimited. UTF-8 codepoint-safe. |
ZERG_COMPLETE_MAX_SUFFIX_BYTES | 1000 | Suffix head kept; 0 = unlimited. UTF-8 codepoint-safe. |
Defaults (client/core/config.lua DEFAULT_CONFIG)
All rows below are read from config.lua:15-131.
| Key | Default | Notes |
|---|---|---|
model | "sonnet" | string |
max_tokens | 8192 | must be > 0 |
max_iterations | 50 | capped at 200 |
permission_mode | "default" | one of allow-all, deny-all, read-only, default, plan, auto |
steering_mode | "all" | all or one-at-a-time — steer-queue drain mode |
follow_up_mode | "all" | all or one-at-a-time — follow-up-queue drain mode |
auto_compaction_input_tokens_threshold | 100000 | min 1000 |
provider_base_url | nil | string |
providers | {} | Settings-level custom providers — see Settings providers |
api_key | nil | string |
mcp_servers | {} | table |
permission_rules | {allow={}, deny={}, ask={}} | table |
thinking_level | nil | one of none, minimal, low, medium, high, xhigh |
system_prompt | nil | string |
append_system_prompt | nil | string |
lsp_enabled | false | boolean |
lsp_servers | {} | table |
agents_dir | nil | string |
extensions_enabled | false | boolean — opt-in (allow-listed sandbox is the prerequisite) |
local_agents_dir | nil | string |
session_budget_usd | 0 | number — 0 disables |
tool_timeout_ms | 60000 | number |
tool_timeout_max_ms | 600000 | Upper clamp for model-supplied command timeouts; the expiry alarm kills the child process group |
fallback_providers | {} | table |
response_format | nil | string |
model_low / model_medium / model_high | nil | string |
auto_continue_after_compaction | false | boolean |
slot_isolation | false | boolean |
format_on_write | false | boolean |
lint_on_write | false | boolean |
budget_grace_enabled | true | boolean |
tool_guardrails | {} | table |
fork_turns | "none" | string |
verification_enabled | false | boolean |
git_step_tracking | false | boolean |
track_git_diffs | false | boolean |
persistent_retry_max_duration | 21600 | number (seconds) |
fallback_model | nil | string |
legacy_write_implies_execute | true | boolean |
keyring_required | false | boolean — refuse plaintext-config fallback when no OS keyring |
otel_endpoint | nil | string — Luna-local span sink; no cross-service tracing |
metrics_port | nil | number — opt-in loopback worker /metrics port |
summarize_turns | false | Opt-in per-turn summary generation (uses provider tokens) |
web_search_provider | "duckduckgo" | Search provider: duckduckgo, searxng, brave, bing |
brave_api_key | — | API key for Brave search provider |
web_search_url | — | Required for the searxng provider (loopback targets refused at the egress gate) |
mcp_sampling_enabled | false | Allow MCP servers to request LLM sampling |
mcp_elicitation_enabled | true | Register the production MCP elicitation/create handler and advertise the client capability. false removes the handler and the capability; headless/default responses are always decline — the optional operator responder is the only accept path |
command_policy | "standard" | Execution policy: strict, standard, permissive |
session_backend | "dual" | Session storage mode: "dual" (JSONL + SQLite, default), "jsonl" (JSONL only) (session_backend.lua DEFAULT_MODE) |
session_sqlite_path | "~/.luna/sessions.db" | SQLite database path — resolved from the SessionBackend.init db-path arg, the LUNA_SQLITE_PATH env, then the default |
session_gc | {enabled=false, max_age_days=30, min_idle_seconds=600, page_size=100, dry_run=true, delete_trajectory=true, delete_orphan_tmp=true} | Opt-in session-corpus GC. See Session corpus GC |
zmq | {} | ZMQ worker-mode options (incl. allowed workspace roots) |
Nested defaults
{
"compaction": {
"trigger_percent": 70,
"protected_turns": 5,
"cooldown_seconds": 120,
"max_consecutive": 3,
"max_tool_output_chars": 2048
},
"retry_config": { "max_retries": 3, "base_backoff_ms": 1000 },
"token_guard": {
"budget_ratio": 0.8,
"max_input_tokens": null,
"max_output_tokens": null,
"adaptive_truncation": true,
"truncation_scale_min": 0.25
},
"auxiliary": {
"model": null, "provider": null, "api_key": null, "base_url": null,
"max_tokens": 2048, "temperature": 0.3, "tasks": {}
},
"team": { "queue_backend": "durable" },
"search": { "cjk_trigram": false },
"session_gc": {
"enabled": false,
"max_age_days": 30,
"min_idle_seconds": 600,
"page_size": 100,
"dry_run": true,
"delete_trajectory": true,
"delete_orphan_tmp": true
},
"execution": {
"sandbox": {
"enabled": true,
"bwrap": "auto",
"landlock": "auto",
"network": false,
"allow_plaintext_http": false,
"read_only_dirs": {}, "allowed_write_paths": {},
"rw_dirs": {}, "denied_paths": {}, "denied_read_paths": null,
"deny_sockets": null, "deny_sockets_ack": false,
"allow_git_trust_writes": false,
"posture_downgrade_ack": false
}
}
}
Sandbox is ON by default (fail-closed). A prompt-injected agent does not get unsandboxed shell. Operators wanting the legacy insecure behavior set
execution.sandbox.enabled = false(config.lua; documented insecure option)."auto"backends prefer bwrap, fall back to landlock-in-fork, and error when neither is available.execution.sandbox.deny_socketsreplaces the/dev/nullsocket-shadow list ( — docker/podman/containerd*.sockdenied by default; adds the build-time-resolved/run/user/<uid>/{keyring,gnupg},/run/gnupg, and$SSH_AUTH_SOCK;/tmp/ssh-*/agentstays an accepted residual).deny_sockets = []denies none ONLY withdeny_sockets_ack = true— without the ack the empty override is ignored and the defaults apply (the dangerous-override ack discipline; a non-empty list replaces the defaults without an ack).
execution.sandbox.read_only_dirsentries must NOT be nested under a granted write root (workspace root,allowed_write_paths, orrw_dirs): the Landlock fork layer’s path-beneath rules are additive and cannot subtract a child from a parent grant, so such a config is refused with the typedlandlock_ro_overlap:<path>:<write-root>error ( — the spawn refuses in every mode rather than pretending the path is read-only). A read-only entry that is an ANCESTOR of a write root is supported (the nested write grant is dropped). Use bwrap’s ro-binds for subtractive read-only semantics.
execution.sandbox.allow_git_trust_writes(defaultfalse) is the explicit model-tool rollback lever for the git trust-file write-deny.git/{config,hooks,attributes,info,modules}and.gitmodulesare write-denied for every model tool because a planted textconv/filter/hook turns a later READ-class git call into command execution. Setting ittrueadmits those writes (the operator takes the trust decision); absent/false refuses with a typedgit trust fileerror. The deny also resolves symlinked parents (a repoevil ->.gitcannot carry a write through).
execution.sandbox.allow_any_commit_restore(defaultfalse) is the snapshot-restore scope lever:git_snapshot restore(and the undo snapshot replay) only restores commits reachable from a Luna-ownedrefs/luna-snapshot/*ref. The pre-fix shape accepted any hex commit and wrote its tree into the worktree through a path-addressed redirect; combined with a repo symlink (evil ->.git) that overwrote.git/config. Restore now also runs the shared write policy per target and writes each file through the fd-relative no-follow workspace primitive. Setting this keytrueadmits an explicit non-Luna commit (the operator takes the trust decision); the refusal otherwise names the restriction and this lever. Session checkpoint restore is an internal caller and is unaffected.
execution.sandbox.posture_downgrade_ack(defaultfalse) is the operator acknowledgement for a bwrap→Landlock-only posture downgrade- a payload cannot flip the latch (wrapper- attributed failures only, N consecutive), and a posture that requires a bwrap-only property (
network=false,read_mode=allowlist, a non-emptydenied_read_paths,deny_socketsunlessdeny_sockets={}+deny_sockets_ack=true,bwrap=required,require_effective_layer=true) REFUSES the spawn instead of silently losing it. Setting the ack re-arms the wrapper attempt and clears a latched downgrade (counted + EventBus-visible).
Settings providers
providers declares custom OpenAI/Anthropic-compatible endpoints in the
layered settings (user/project keys merge like every other key). Entries are
validated and registered at config load through the shared
core.provider validator — a malformed entry fails the load loudly; it is
never deferred to first use.
{
"providers": {
"local": {
"base_url": "http://localhost:11434",
"wire_format": "openai",
"models": ["qwen2.5-coder:7b"],
"no_api_key": true
},
"remote": {
"base_url": "https://api.example.com",
"wire_format": "openai",
"models": ["example-large"],
"api_key_env": "EXAMPLE_API_KEY"
}
}
}
| Field | Required | Rules |
|---|---|---|
base_url | yes | http(s)://host[:port] — the bare host:port. The provider appends /v1/chat/completions (openai) or /v1/messages (anthropic); a base_url ending in /v1 is refused at load (it would 404). A query/fragment is refused; trailing slashes are trimmed. |
wire_format | no | openai (default) or anthropic. |
models | no | Array of non-empty model names. Matching is the historical register semantics: exact or prefix (qwen2.5-coder:7b matches model qwen2.5-coder:7b-…). Custom providers are consulted before the prefix heuristics, so a models entry for a qwen* name routes to your endpoint instead of the alibaba cloud provider. |
api_key_env | keyed providers | Environment-variable name (never a raw key; api_key is refused). The key is read from the env, then the OS keyring. |
no_api_key | keyless providers | Boolean. The explicit keyless rule: no env/keyring lookup and no auth header. Loopback only — localhost, 127.0.0.0/8, or ::1; a non-loopback no_api_key provider is refused at load (fail-closed). Cannot be combined with api_key_env. |
Either api_key_env or no_api_key: true is required per provider.
Duplicate names: last definition wins. A settings entry replaces a programmatically registered provider of the same name (the operator’s settings are authoritative), the next config load re-asserts it, and a name that disappears from the settings is unregistered. Within the file layers, the normal merge precedence applies (later user/project layer wins).
Consent: providers is part of the provider plane, so a
project-local (.luna.json, .luna/settings.json,
.luna/settings.local.json) providers table is stripped unless the repo
has the trust marker — a cloned repo cannot redirect inference (or a
key-bearing request) without approval.
Repo-config consent gate
Project-local config files (.luna.json, .luna/settings.json,
.luna/settings.local.json) deep-merge OVER user config — a cloned repo
can carry security-relevant keys. Those keys apply ONLY with a consent
marker. Source: client/core/repo_config_security.lua (the family list +
strip) and client/core/repo_config_trust.lua (all semantics below).
Security-relevant key families (from project-local files):
| Family | Meaning |
|---|---|
execution.* | Sandbox posture (execution.sandbox.enabled, bwrap mode, network flag) |
permission_* | Any key starting with permission (e.g. permission_mode, permission_override) |
server_permissions | Server-grant RBAC list |
workspace, workspace_root | Workspace roots |
workdir, _workspace | Workspace-root aliases — first candidates for the bwrap bind root AND the Landlock grant root (sandbox.lua); _workspace is first precedence in tools/init.lua, workdir in formatters.lua/linters.lua — covered by this gate per (LUNSBX-1) |
provider_base_url | Wire destination of every provider request |
providers | Settings-level custom provider definitions — base_url/wire_format/models and api_key_env or no_api_key |
api_key, api_keys | Provider credential sources |
auxiliary | Auxiliary model plane — base_url/api_key |
fallback_providers | Failover destinations |
otel_endpoint | Luna-local span sink (fire-and-forget HTTP POST from the worker; no cross-service tracing — Sol/Mango export no spans) |
classifier | AI permission-classifier provider plane — enabled/model/provider/base_url; base_url is a network destination for classifier traffic |
system_prompt, append_system_prompt | Prompt-injection planes: project-supplied prompt text |
tool_validation, tool_guardrails | Execution-policy planes: disabling validation or loosening guardrails |
desktop_override | Display-global input injection opt-in |
web_search_url | Search destination (credentialed search API keys ride along) |
memory | Memory backend selection — mode/backends incl. a remote vector_host |
extensions_enabled, agents_dir, local_agents_dir, mode | Extension opt-in and agent-mode discovery/selection |
Trust-marker flow:
Consent is a hash-keyed marker in the USER’s approval dir:
~/.luna/approvals/trust-<sha256>.json.
A marker inside the repo is deliberately NOT used — an attacker shipping
the repo also ships the marker; user-owned storage is the only trust
boundary that survives git clone attacker && cd repo && luna.
Record-validated, atomic: all three consent planes share
client/core/approvals_store.lua. Existence alone is not approval: a
corrupt/truncated record, a record whose hash/kind names a different
identity, or an unknown record version is IGNORED (fail closed). Legacy
records without v/kind/hash (including {} rows) stay valid. Writes
use FFI.atomic_write (mkostemp 0600 from birth + fsync + checked rename);
the previous trust-marker writer was umask-dependent for the write window.
Filenames and hash domains are preserved: trust-<hash>.json (config),
<hash>.json (MCP), extension-<hash>.json (extensions). See
consent.md.
The hash covers BOTH file-sets: the config security keys (in merge
precedence order) AND permission_override values from .luna/agents/
mode files — one marker approves both, so a config-only approval can never
silently authorize mode overrides.
Fail-closed without TTY: no marker and no TTY → the security-relevant
project-local keys are IGNORED (stripped with a loud stderr warning,
sandbox stays ON). With a TTY the operator is prompted once (y/N) and
consent writes the marker; anything but an explicit y/yes is a
decline. Verdicts are memoized per working directory for the process
lifetime (M.reload clears them).
Fingerprint: the permission-cache fingerprint derives
from the sandbox posture (enabled/bwrap/network) and — per —
includes the workspace root, so a re-rooted boundary (a repo that
changes workdir/_workspace/workspace_root) invalidates cached allow
decisions even with an identical sandbox posture.
Defensive provider gate: provider.from_model/3
independently refuses a provider_base_url whose effective value equals
the project-carried value while the consent verdict is false — a strip
bypass falls back to the built-in destination with a CRITICAL line and a
repo_base_url_refusals count. Value equality (not presence) keeps a
same-key user-supplied URL legitimate.
Project mode files: without consent, EVERY
behaviour-bearing project mode field is dropped (permission_override,
the permissions ruleset, system_prompt, system_prompt_section,
tool_filter, tools, extra_tools, model, temperature,
max_steps, max_iterations, max_turns, category), and a project
file whose name collides with a NATIVE mode (build, plan, …) is
refused entirely — a cloned repo cannot shadow the operator’s modes or
apply a hidden ruleset.
Custom/extension handler config: custom and
plugin/extension handlers receive a deep, sanitized READ-ONLY COPY of the
agent config — no _agent (provider key), credentials/provider-plane
keys, server_permissions, or permission policy. Workspace context and
the sandbox execution posture stay visible; mutations only touch the
copy (the framework re-sanitizes on every dispatch).
Audit pattern: the consent-gate corpus rows — workdir="/",
_workspace="/", array/object variants, and the approved-repo-gains-
workdir re-prompt.
Session & Search
| Key | Type | Default | Description |
|---|---|---|---|
search.cjk_trigram | boolean | false | Use the FTS5 trigram tokenizer for the CJK session-search table (messages_fts_cjk). Requires SQLite built with the trigram tokenizer. When enabled the table is created with tokenize='trigram'; when disabled unicode61. Switching the setting on an existing database drops-and-recreates the table and reindexes once. Threaded from main.lua → SessionBackend.init → session_sqlite.open. |
{ "search": { "cjk_trigram": false } }
Session corpus GC (session_gc)
. The session corpus is retain-forever by default; this table
opts into a whole-session sweep. Manual surfaces: --gc-sessions (dry
run), --gc-apply, --gc-max-age-days N, --gc-limit N; TUI /gc
(dry run) and /gc run [DAYS] (explicit apply). There is no LUNA_*
env override for these keys.
| Key | Type | Default | Description |
|---|---|---|---|
session_gc.enabled | boolean | false | Opt-in idle cleanup. false means no automatic sweep ever runs |
session_gc.max_age_days | number | 30 | A candidate’s last activity (max file mtime, index updated_at, SQLite updated_at) must be at least this old |
session_gc.min_idle_seconds | number | 600 | Additional recent-activity guard (corpora touched inside this window are skipped) |
session_gc.page_size | number | 100 | Scan/deletion page size (1–10000; cursors resume a sweep) |
session_gc.dry_run | boolean | true | Default for programmatic/manual runs; --gc-apply and /gc run override explicitly |
session_gc.delete_trajectory | boolean | true | Remove trajectory_<id>.jsonl with the session |
session_gc.delete_orphan_tmp | boolean | true | Remove age-gated orphan .luna_session_* / .luna_edit_* temps in the sessions dir |
A candidate is the primary JSONL + rotations (.1/.2) + a stranded
.rotate.tmp; deletion also covers SQLite rows (both FTS tables via the
DELETE triggers), the JSON index entry, the optionally-included
trajectory, and a stale .active lease. Content-addressed blobs,
analytics, git snapshots, and session-scoped memory are explicit
exclusions. Held leases, the current session, recent corpora, and
symlinks are refused. See sessions.md
for the operator contract and secure-deletion limits.
AI Permission Classifier (Ollama, client-side)
Defaults from client/core/ai_classifier.lua; env override
LUNA_CLASSIFIER_ENABLED.
| Key | Type | Default | Description |
|---|---|---|---|
classifier.enabled | boolean | false | Enable AI permission classifier |
classifier.model | string | qwen2.5-coder:7b | Ollama model for classification |
classifier.base_url | string | http://localhost:11434 | Ollama API base URL |
classifier.confidence_threshold | float | 0.85 | Minimum confidence for auto-decision |
classifier.timeout | integer | 5 | Request timeout in seconds |
classifier.cache_size | integer | 64 | LRU decision cache entries |
Worker metrics exposition
Luna can expose a loopback-only Prometheus text endpoint for
worker-local health (client/core/metrics_exposition.lua). It binds
127.0.0.1 only — any other host is refused — and serves GET /metrics
with a bounded request/accept posture. Families: sandbox zero-layer
spawns/refusals, tool errors, memory entries/bytes/flush-unlocked, and FTS
rebuilds. This is worker-local: the scrape target/wiring is a
deployment decision (there is no central Sol claim over Luna metrics).
{ "metrics_port": 9477 }
metrics_port = nil (the default) keeps the endpoint off. A port below
1024 requires privileges; prefer an unprivileged port and a per-worker
offset when multiple workers share a host.
Keymaps (~/.luna/keymaps.json)
Customize TUI key bindings. Overrides defaults for specified modes.
{
"normal": { "Ctrl+P": "command" },
"input": { "Ctrl+A": "beginning_of_line" }
}
Modes: normal, input, search, menu. View all bindings with /keymaps TUI command.
Memory Taxonomy
Memory extractor uses 4 types: fact, preference, procedure, relationship. Consolidator deduplicates within each category.
TUI Commands
| Command | Description |
|---|---|
/compact | Compact entire session |
/compact --from <id> | Compact messages before the specified entry |
/compact --up-to <id> | Compact messages up to and including the specified entry |
/keymaps | Display all key bindings |
Search Providers
| Provider | Auth | Notes |
|---|---|---|
duckduckgo | None | Default, HTML scraping |
searxng | None | Self-hosted, requires web_search_url config (loopback targets refused at the egress gate) |
brave | API key | Set brave_api_key in config |
bing | None | HTML scraping, no API key needed |
Example Configurations
Development (Single Machine)
%% config/sys.config
[
{sol, [
{http_port, 21434},
{http_ip, "127.0.0.1"},
{llama_server_path, "/usr/src/llama.cpp/llama-server"},
{model_source_dir, "/fun/models"},
{model_store_dir, "/tmp/sol/models"},
{zmq_enabled, true},
{max_workers, 4}
]}
].
Production (Cluster Node)
%% config/sys.prod.config
[
{sol, [
{http_port, 21434},
{http_ip, "0.0.0.0"},
{llama_server_path, "/usr/local/bin/llama-server"},
{model_source_dir, "/mnt/nfs/models"},
{model_store_dir, "/var/lib/sol/models"},
{worker_path, "/opt/sol/etc/luna"},
{max_workers, 32},
{cluster_nodes, ['sol@gpu-node-2', 'sol@gpu-node-3']},
{zmq_enabled, true},
{zmq_bind_addr, "0.0.0.0"}
]}
].
## config/vm.prod.args
-name sol@gpu-node-1
-setcookie production_secret_cookie
+A 8
+S 8
+K true
+zdbbl 32768
Luna (User Config)
// ~/.luna/config.json
{
"model": "glm-5.1",
"provider": {
"type": "anthropic",
"api_key": "sk-..."
},
"permission_mode": "auto",
"theme": "onedark",
"classifier": {
"enabled": true,
"model": "qwen2.5-coder:7b",
"confidence_threshold": 0.85,
"timeout": 5,
"cache_size": 64
}
}
Custom Agent Modes
Agent modes are defined as JSON or Markdown files in ~/.luna/agents/ or .luna/agents/.
JSON Format
{
"name": "security-review",
"display": "Security",
"description": "Security-focused code review mode",
"badge": "S",
"color": "red",
"category": "primary",
"permissions": {
"*": "deny",
"read_file": "allow",
"grep_search": "allow",
"glob_search": "allow",
"bash": { "default": "ask", "patterns": { "npm audit*": "allow" } }
},
"tool_filter": "all",
"model": "glm-5.1",
"max_steps": 25
}
Markdown Format
name: security-review
display: Security
description: Security-focused code review mode
badge: S
color: red
category: primary
permissions:
"*": deny
read_file: allow
grep_search: allow
glob_search: allow
tool_filter: all
model: glm-5.1
max_steps: 25
# System Prompt
You are a security-focused code reviewer...
Mode Definition Fields
| Field | Type | Required | Description |
|---|---|---|---|
name | string | Yes | Unique mode identifier (lowercase, hyphens) |
display | string | Yes | Display name in TUI |
description | string | Yes | One-line description |
badge | string | No | Single-char TUI badge (auto-assigned if missing) |
color | string | No | TUI color name |
category | string | No | primary (Tab-cyclable) or secondary |
permissions | object | No | Per-tool ruleset (see permissions.md) |
tool_filter | string | No | all or tool list |
model | string | No | Override model for this mode |
temperature | float | No | Override temperature |
max_steps | integer | No | Override max iterations |
system_prompt | string | No | Additional system prompt section (Markdown body) |
Ollama Integration
Server-Side (Sol)
Ollama is auto-discovered at http://localhost:11434 (ollama_url). Models
registered via sol_provider_boot with the ollama atom mapping; the model
list refreshes every 5 minutes.
Client-Side (Luna Classifier)
See AI Permission Classifier
above — classifier.* keys with defaults from ai_classifier.lua.
Related configuration surfaces (out of scope)
These are separate config namespaces with their own sources of truth —
not part of the sol app env or the Luna merge, so they are not tabulated
here:
| Surface | Where | Notes |
|---|---|---|
| Mango (identity service) | mango/conf.py + env | Own settings module; Sol-side bridge keys (mango_*) are in Auth / Security above |
| Limon (ops console) | limon/ build env (VITE_*) | Client-side build-time env, not runtime Sol config. The one Sol-side CORS knob is limon_origin |
| zerg-cli (operator binary) | own config file + env | See zerg-cli/ docs / zerg status |
| Production injection | runit env files /etc/sv/zerg-sol/env/ (wild blueprint) | SOL_* env vars are the primary production surface — see wild/AGENTS.md |
Engine reference — generated from the canonical engineering source. Do not edit this page by hand.
Event reference — generated transport matrix
GENERATED FILE — DO NOT EDIT. Source:
contract/events.yaml+sol_sync_event_forwarder+ directsol_sync_event:run/2emitters +sol_zmq_events+sol_event_router. Regenerate withpython3 ci/event_transport_matrix_gen.py(freshness gate:--check, wired intests/test_lint_contracts.py::TestEventTransportMatrix).
stored = durable sync_event store · sse = /api/v1/sync-events ·
pub = ZMQ PUB plane (Luna) · bridge = Mango audit archive
(stored == bridge) · validators = required payload keys.
Machine-readable fixture:
docs/fixtures/event_transport_matrix.json.
task — Task lifecycle (aggregate task_id).
| Type | Aggregate | Store | SSE | PUB | Mango | Validators |
|---|---|---|---|---|---|---|
task.completed | task_id | yes | yes | yes | yes | — |
task.created | task_id | yes | yes | yes | yes | — |
task.dropped | task_id | yes | yes | — | yes | — |
task.failed | task_id | yes | yes | yes | yes | — |
model — Local model lifecycle / registry (aggregate model_name).
| Type | Aggregate | Store | SSE | PUB | Mango | Validators |
|---|---|---|---|---|---|---|
model.discovered | model_name | yes | yes | — | yes | — |
model.failed | model_name | yes | yes | — | yes | — |
model.prepare_failed | model_name | yes | yes | — | yes | slug |
model.prepared | model_name | yes | yes | — | yes | slug |
model.preparing | model_name | yes | yes | — | yes | slug |
model.start_failed | model_name | yes | yes | — | yes | slug |
model.started | model_name | yes | yes | — | yes | slug, port |
model.stopped | model_name | yes | yes | — | yes | slug |
worker — Worker lifecycle (aggregate worker_id).
| Type | Aggregate | Store | SSE | PUB | Mango | Validators |
|---|---|---|---|---|---|---|
worker.crashed | worker_id | yes | yes | — | yes | worker_id |
worker.disconnected | worker_id | yes | yes | yes | yes | — |
worker.killed | worker_id | yes | yes | — | yes | worker_id |
worker.ready | worker_id | yes | yes | — | yes | worker_id |
worker.spawn_failed | worker_id | yes | yes | — | yes | worker_id |
worker.spawned | worker_id | yes | yes | — | yes | worker_id |
worker.task_started | worker_id | yes | yes | — | yes | worker_id, task_id |
inference — Inference request lifecycle.
| Type | Aggregate | Store | SSE | PUB | Mango | Validators |
|---|---|---|---|---|---|---|
inference.complete | model_name | yes | yes | — | yes | — |
inference.error | request_id | yes | yes | — | yes | — |
inference.interrupted | request_id | yes | yes | — | yes | — |
inference.request | request_id | yes | yes | — | yes | — |
inference.start_retry | model_name | yes | yes | — | yes | model_name |
inference.start_retry_exhausted | model_name | yes | yes | — | yes | model_name |
lane — Local-inference lane lifecycle (aggregate lane id).
| Type | Aggregate | Store | SSE | PUB | Mango | Validators |
|---|---|---|---|---|---|---|
lane.cold_start_async | lane | yes | yes | — | yes | lane, mode |
lane.cron_start_refused | lane | yes | yes | — | yes | lane, model |
lane.cron_started | lane | yes | yes | — | yes | lane, model |
lane.cron_stopped | lane | yes | yes | — | yes | lane, model |
lane.failed | lane | yes | yes | — | yes | lane, reason |
lane.granted | lane | yes | yes | — | yes | lane |
lane.inference_fallback | lane | yes | yes | — | yes | lane, fallback |
lane.lease_acquired | lane | yes | yes | — | yes | lane |
lane.lease_denied | lane | yes | yes | — | yes | lane, reason |
lane.lease_released | lane | yes | yes | — | yes | lane |
lane.orphan_reaped | lane | yes | yes | — | yes | lane |
lane.queued | lane | yes | yes | — | yes | lane |
lane.requested | lane | yes | yes | — | yes | lane |
lane.response_format_stripped | lane | yes | yes | — | yes | lane |
lane.restart_denied | lane | yes | yes | — | yes | lane |
maintenance — Operator maintenance flips (aggregate node_name).
| Type | Aggregate | Store | SSE | PUB | Mango | Validators |
|---|---|---|---|---|---|---|
maintenance.disabled | node_name | yes | yes | — | yes | node_name |
maintenance.enabled | node_name | yes | yes | — | yes | node_name |
restore — Backup-restore verification outcomes (aggregate scope).
| Type | Aggregate | Store | SSE | PUB | Mango | Validators |
|---|---|---|---|---|---|---|
restore.checksum_mismatch | scope | yes | yes | — | yes | scope |
restore.mismatch | scope | yes | yes | — | yes | scope |
restore.verified | scope | yes | yes | — | yes | scope |
scheduler — Scheduler job lifecycle.
| Type | Aggregate | Store | SSE | PUB | Mango | Validators |
|---|---|---|---|---|---|---|
scheduler.fires_skipped | job_id | yes | yes | — | yes | — |
scheduler.job_created | job_id | yes | yes | — | yes | — |
scheduler.job_disabled | job_id | yes | yes | — | yes | job_id |
scheduler.job_executed | job_id | yes | yes | — | yes | — |
scheduler.task_dispatched | task_id | yes | yes | — | yes | — |
other — Cross-cutting types (channels/plugins/cluster/circuits/misc workflows).
| Type | Aggregate | Store | SSE | PUB | Mango | Validators |
|---|---|---|---|---|---|---|
channel.error | channel_id | yes | yes | — | yes | channel_id |
channel.message_sent | channel_id | yes | yes | — | yes | channel_id |
channel.registered | channel_id | yes | yes | — | yes | channel_id |
channel.status_changed | channel_id | yes | yes | — | yes | channel_id |
circuit.closed | key | yes | yes | yes | yes | — |
circuit.half_open | key | yes | yes | — | yes | — |
circuit.opened | key | yes | yes | yes | yes | — |
circuit.rejected | key | yes | yes | yes | yes | — |
cluster.node_joined | node_name | yes | yes | — | yes | — |
event.gap | aggregate_id | — | — | yes | — | — |
managed_settings_update | key | — | — | yes | — | — |
plugin.loaded | plugin_name | yes | yes | — | yes | name |
plugin.step_registered | plugin_name | yes | yes | — | yes | plugin_name |
plugin.unloaded | plugin_name | yes | yes | — | yes | name |
worker.connected | worker_id | yes | yes | yes | yes | — |
workflow.branch_created | workflow_id | yes | yes | — | yes | — |
workflow.completed | workflow_id | yes | yes | yes | yes | workflow_id |
workflow.started | workflow_id | yes | yes | yes | yes | workflow_id |
workflow.step_result | workflow_id | yes | yes | — | yes | — |
workflow — Workflow compensation outcomes.
| Type | Aggregate | Store | SSE | PUB | Mango | Validators |
|---|---|---|---|---|---|---|
workflow.budget_limited | workflow_id | yes | yes | — | yes | workflow_id |
workflow.child_cancelled | workflow_id | yes | yes | — | yes | workflow_id |
workflow.compensation_failed | workflow_id | yes | yes | — | yes | workflow_id |
workflow.compensation_recovery | workflow_id | yes | yes | — | yes | — |
workflow.descendant_cancel_completed | workflow_id | yes | yes | — | yes | workflow_id |
workflow.state_changed | workflow_id | yes | yes | — | yes | workflow_id |
workflow.step_partial_result | workflow_id | yes | yes | — | yes | workflow_id |
memory — Memory decay/reflection.
| Type | Aggregate | Store | SSE | PUB | Mango | Validators |
|---|---|---|---|---|---|---|
memory.decayed | agent_id | yes | yes | — | yes | key |
memory.reflected | agent_id | yes | yes | — | yes | — |
team — Team lifecycle + mail.
| Type | Aggregate | Store | SSE | PUB | Mango | Validators |
|---|---|---|---|---|---|---|
team.created | team_id | yes | yes | yes | yes | — |
team.destroyed | team_id | yes | yes | yes | yes | — |
team.mail_expired | team_id | yes | yes | — | yes | team_id |
team.mail_sent | team_id | yes | yes | — | yes | — |
team.member_joined | team_id | yes | yes | yes | yes | — |
team.member_left | team_id | yes | yes | yes | yes | — |
provider — Provider registry.
| Type | Aggregate | Store | SSE | PUB | Mango | Validators |
|---|---|---|---|---|---|---|
provider.fallback_engaged | model_name | yes | yes | — | yes | model_name, fallback_model, reason, attempt |
provider.registered | model | yes | yes | — | yes | — |
session — Chat session lifecycle.
| Type | Aggregate | Store | SSE | PUB | Mango | Validators |
|---|---|---|---|---|---|---|
session.closed | session_id | yes | yes | — | yes | session_id |
session.created | session_id | yes | yes | — | yes | session_id |
agent — Agent turn/tool telemetry (aggregate task_id).
| Type | Aggregate | Store | SSE | PUB | Mango | Validators |
|---|---|---|---|---|---|---|
agent.cap_ledger_corrected | scope | yes | yes | — | yes | scope |
agent.child_completed | task_id | — | — | — | — | — |
agent.context_overflow | task_id | yes | yes | — | yes | — |
agent.diagnostic | task_id | yes | yes | — | yes | — |
agent.loop_detected | task_id | yes | yes | — | yes | — |
agent.loop_warning | task_id | yes | yes | — | yes | — |
agent.turn_completed | task_id | yes | yes | — | yes | — |
agent.turn_started | task_id | yes | yes | — | yes | — |
bridge — Workflow bridge / task correlation.
| Type | Aggregate | Store | SSE | PUB | Mango | Validators |
|---|---|---|---|---|---|---|
session.message_pushed | session_id | yes | yes | — | yes | — |
task.assigned | task_id | — | — | — | — | — |
task.started | task_id | yes | yes | yes | yes | task_id |
workflow.compensation | workflow_id | yes | yes | yes | yes | — |
workflow.failed | workflow_id | yes | yes | yes | yes | workflow_id |
workflow.step_started | workflow_id | yes | yes | yes | yes | workflow_id, step_name |
Engine reference — generated from the canonical engineering source. Do not edit this page by hand.
RBAC Permission Scopes — Server-Side Reference
This is the canonical reference for Sol’s server-side permission scopes: the
verb:resource strings enforced by the auth middleware
(server/src/sol_auth_middleware.erl), the ownership-check layer beneath
them, and the tasks:execute dispatch-plane grant. It documents the wire
level authorization vocabulary — the client-side permission modes
(default, allow-all, deny-all, read-only, plan, auto) are a
different system and are covered in permissions.md.
All rows are code-verified against the current tree. The single source of
truth is the exported sol_auth_middleware:test_get_endpoint_permissions/0
(the ?ENDPOINT_PERMISSIONS table) plus ?RESOURCE_SCOPES; this document is a
rendered view, not an authority. The shipped table is pinned behaviorally by
sol_auth_middleware_rbac_permissions_tests and the route/permission gates
(ci/route_permission_lint.py, ci/rbac_route_matrix_lint.py,
ci/mutation_verb_scope_lint.py).
Authorization pipeline (one request)
Middleware chain: [cowboy_router, sol_auth_middleware, sol_log_middleware].
Within sol_auth_middleware:execute/2 (sol_auth_middleware.erl:281–289):
- API-version check —
anthropic-versionpinned on/v1/messages(sol_auth_middleware.erl:461–475). - Rate limit — default-on per-token budget (300 rpm + 30 burst, ) or the dedicated limiter; dead limiter → 503 fail-closed (sol_auth_middleware.erl:291–320, 867–924).
- Maintenance gate — non-exempt paths answer 503 while enabled (sol_auth_middleware.erl:322–350).
- Token extraction —
zerg_ticketsubprotocol →zerg_auth→Authorization: Bearer→zerg_sessioncookie →?token=(off by default, ) (sol_auth_middleware.erl:477–530). - Validation → identity (see Identity sources).
- RBAC — one required permission per
{Method, Path}, exact string membership (sol_auth_middleware.erl:557–600). - Resource ownership — optional second layer from
?RESOURCE_SCOPES(sol_auth_middleware.erl:701–764).
Both 6 and 7 always run for every authenticated (and anonymous-exempt) request; step 7 runs even when step 6 finds no required permission (sol_auth_middleware.erl:558–560).
Identity sources
| Principal | user_uuid | permissions | Mechanism |
|---|---|---|---|
| Mango session token | Mango user uuid | resolved from team roles at validate time | sol_auth.erl:232–243 → sol_mango_client:validate_token → Mango AuthSystem.validate (mango/systems/auth.py:654–713) |
| Mango service token | owning user uuid | same resolution as session | same path; token_type is carried but does not widen grants |
| Mango refresh token | — | — | refused by Sol (refresh_disabled, sol_mango_client.erl:432–435) |
| WS one-time ticket | bound user + permission snapshot | minted via REST, 60 s single-use; : honored ONLY on the WS handshake route (/api/v1/chat/:session_id/ws, derived from the route table) — any other route presenting the zerg_ticket subprotocol answers 401; a ticket is not a bearer | sol_auth_middleware.erl (the {ticket, _} arm + is_ws_handshake_path/1) |
| Local-mode static token | sha256(token)[0:16] | ["*"] | sol_auth.erl:156–170 |
| Dev identity (auth disabled) | <<"dev">> | ["*"] | only on explicit auth_enabled=false; server error never produces it — sol_auth:enabled/0 fails closed to “enabled” |
| Anonymous (exempt path) | <<"anonymous">> | [] | sol_auth_middleware.erl:442–451 |
The resolved #{user_uuid, permissions} map is placed in the process
dictionary (sol_identity, sol_auth_middleware.erl:690–699) and must be
forwarded explicitly into any deferred execution (task opts, ZMQ dispatch)
gen_servers and spawned workers never inherit it.
Scope matching rules
Exact {Method, Path} match wins, then longest prefix; ties break
by binary order — fully deterministic since then L9
(sol_auth_middleware.erl:590–594, 784–811).
Prefix matching is path-segment bounded: /api/v1/agents never
matches /api/v1/agents-public (sol_auth_middleware.erl:788–798).
Trailing-slash rules are self-bounded subtrees: {<<"POST">>, <<"/api/v1/workflows/">>} covers every /api/v1/workflows/:id/action
(sol_auth_middleware.erl:74).
Membership check is exact-string or the bare global * — no wildcard
or namespace expansion on the Sol side (sol_auth_middleware.erl:596–600).
Makes that the authoring contract on BOTH planes: Mango’s
_validate_permissions (mango/systems/rbac.py) refuses ns:* and the
legacy Mango-only admin:* alias at every role create/update with a typed
MangoError. The declared policy is permission_policy in the shared RBAC
fixture (global_wildcard: true, namespace_wildcards: false,
admin_alias: false), and the lint pins it against the Sol matcher source.
Roles stored before keep read-compatible wildcard expansion through
_match_permission — a legacy read matcher, not the authoring
contract. Grant exact scope strings.
Load-time validation refuses ambiguous (shadowed) prefix rules at boot
(sol_auth_middleware.erl:818–852, wired from sol_app.erl:1119).
HTTP scope table (ENDPOINT_PERMISSIONS)
116 route rules → 61 distinct scopes. “Gate” is permission, or
permission + ownership / permission + admin where a ?RESOURCE_SCOPES
rule layers on top (see next section).
Inference
| Scope | Routes | Gate | Notes |
|---|---|---|---|
inference:use | POST /v1/messages, POST /v1/chat/completions | permission | OpenAI/Anthropic-compatible surface (sol_auth_middleware.erl:169–170) |
inference:start | POST /api/v1/start | permission | :181 |
inference:stop | POST /api/v1/stop | permission | :182 |
inference:stop_all | POST /api/v1/stop-all | permission | :183 |
inference:prepare | POST /api/v1/prepare/ | permission | registry prepare, 202 + async hop:184 |
inference:discover | POST /api/v1/discover | permission | POST-only in spec:180 |
inference:list | GET /api/v1/ps | permission | :177 |
inference:catalog | GET /api/v1/catalog | permission | :185 |
models:read | GET /api/v1/models, GET /v1/models | permission | :160,162 |
Tasks, workflows, orchestration
| Scope | Routes | Gate | Notes |
|---|---|---|---|
tasks:read | GET /api/v1/tasks, GET /api/v1/tasks/outbox | permission | lists are owner-filtered at the handler:142,147 |
| (task detail) | GET /api/v1/tasks/:id | permission + ownership | tasks:read resolves via the segment-bounded prefix of the bare rule; own scope on the /tasks/ prefix:142,255 |
| (task detail mutations) | POST/PUT/PATCH/DELETE /api/v1/tasks/:id | ownership only | no ENDPOINT_PERMISSIONS rule resolves — permission layer passes, own scope still enforced:261–263,267 |
workflows:read | GET /api/v1/workflows, GET /api/v1/workflows/, GET /api/v1/recipes, GET /api/v1/recipes/ | permission + ownership (workflow detail) | :72,75,82,83 |
workflows:start | POST /api/v1/workflows/start, POST /api/v1/recipes, POST /api/v1/recipes/ | permission | :73,80,81 |
workflows:cancel | POST /api/v1/workflows/ (subtree) | permission + ownership | :74 |
orchestrate:create | POST /api/v1/orchestrate | permission | :225 |
| (orchestrate detail) | GET /api/v1/orchestrate/:id | ownership only | own scope, sol_task_store owner:266 |
schedule:read | GET /api/v1/schedule, GET /api/v1/schedule/ | permission | :201,206 |
schedule:manage | POST /api/v1/schedule, POST /api/v1/schedule/, DELETE /api/v1/schedule/ | permission | :196–208 |
schedule:spawn | POST /api/v1/schedule/spawn | permission + admin | exact rule in RESOURCE_SCOPES:195,270 |
zmq:dispatch | POST /api/v1/zmq/dispatch | permission | :186 |
zmq:list | GET /api/v1/zmq/workers | permission | :187 |
zmq:status | GET /api/v1/zmq/status | permission | :188 |
acp:list | GET /api/v1/acp/agents | permission | :189 |
acp:message | POST /api/v1/acp/agents/ | permission | :190 |
teams:list | GET /api/v1/teams | permission | :191 |
teams:create | POST /api/v1/teams | permission | :192 |
teams:manage | POST /api/v1/teams/, DELETE /api/v1/teams/ | permission | :193,194 |
Chat, sessions, conversations
| Scope | Routes | Gate | Notes |
|---|---|---|---|
chat:create | POST /api/v1/chat, POST /api/v1/chat/:id/message, POST /api/v1/chat/:id/ws-ticket | permission | shared sol_chat_authz:rest_rules/0 |
chat:read | GET /api/v1/chat, GET /api/v1/chat/:id | permission | shared table (same source as the WS frames) |
chat:delete | DELETE /api/v1/chat/:id | permission | shared table |
sessions:create | POST /api/v1/sessions/ | permission | :97 |
sessions:read | GET /api/v1/sessions/ | permission | :98 |
sessions:delete | DELETE /api/v1/sessions/ | permission | :99 |
conversations:list | GET /api/v1/conversations | permission | :237 |
conversations:create | POST /api/v1/conversations | permission | :238 |
| (conversation detail) | GET /api/v1/conversations/:id | permission + ownership | conversations:list resolves via the segment-bounded prefix of the bare rule; own scope:237,253 |
| (conversation delete) | DELETE /api/v1/conversations/:id | ownership only | no DELETE rule resolves — own scope still enforced:254 |
Goals, memory, workspace
| Scope | Routes | Gate | Notes |
|---|---|---|---|
goals:read | GET /api/v1/goals, GET /api/v1/goals/ | permission | bare form added:91 |
goals:manage | PUT /api/v1/goals/ | permission (owner-or-admin) | POST /goals/:id/cancel is admin-scoped (next row); goals:create no longer grants create |
goals:delete | DELETE /api/v1/goals/ | permission | :92 |
(admin scope) | POST /api/v1/goals, POST /api/v1/goals/:id/cancel | {admin, require} | /F3: the admin scope is the single create/cancel authority; the permission map carries no goals:create/POST-cancel rule |
memory:read | GET /api/v1/memory/ | permission | :148 |
memory:write | POST /api/v1/memory/, DELETE /api/v1/memory/ | permission | :149,150 |
workspace:read | GET /api/v1/workspace/, POST /api/v1/workspace/read, POST /api/v1/workspace/search, POST /api/v1/workspace/list | permission | read-split at the middleware,:123,130–132 |
workspace:write | POST /api/v1/workspace/ (subtree) | permission | :124 |
Infrastructure, telemetry, providers
| Scope | Routes | Gate | Notes |
|---|---|---|---|
infra:read | GET /api/v1/workers/bg, GET /api/v1/lua/, GET /api/v1/cluster, GET /api/v1/providers/, GET /api/v1/infra/, GET /api/v1/persistence, GET /api/v1/persistence/, GET /api/v1/telemetry, GET /api/v1/telemetry/ | permission | :100–249 |
infra:manage | POST /api/v1/workers/bg, POST /api/v1/lua/eval, POST /api/v1/lua/, POST /api/v1/cluster, POST/DELETE /api/v1/infra/, POST /api/v1/telemetry, POST /api/v1/telemetry/, POST /api/v1/providers/reload | permission | includes Lua eval/spawn and cluster ops:100–249 |
persistence:manage | POST /api/v1/persistence/ | permission | :229 |
settings:read | GET /api/v1/managed-settings | permission | :226 |
settings:write | PUT /api/v1/managed-settings | permission | :227 |
circuits:list | GET /api/v1/circuits | permission | :223 |
circuits:reset | POST /api/v1/circuits/reset | permission | :224 |
Observability, audit, marketplace, skills, dashboard
| Scope | Routes | Gate | Notes |
|---|---|---|---|
audit:read | GET /api/v1/audit, GET /api/v1/events, GET /api/v1/replay/ | permission | :76,78,164,165,167 |
admin (require) | GET /api/v1/audit/verify | admin | : the anchored integrity verdict — the exact RESOURCE_SCOPES rule overrides the /api/v1/audit prefix (audit:read); operator-remediation surface only |
audit:stream | GET /api/v1/sync-events (SSE) | permission | :79 |
metrics:read | GET /api/v1/metrics, GET /api/v1/supervisor, GET /api/v1/license/status | permission | :77,84,163,171 |
marketplace:browse | GET /api/v1/marketplace | permission | :209 |
marketplace:publish | POST /api/v1/marketplace | permission | :210 |
marketplace:manage | DELETE /api/v1/marketplace/ | permission | ungated until:214 |
skills:browse | GET /api/v1/skills | permission | :215 |
skills:publish | POST /api/v1/skills | permission | :216 |
skills:manage | DELETE /api/v1/skills/ | permission | ungated until:222 |
channels:read | GET /api/v1/channels | permission | :151 |
channels:manage | POST /api/v1/channels, POST/PUT/PATCH/DELETE /api/v1/channels/ | permission (+ handler admin gates on some actions) | PUT/PATCH covered since then:151–159 |
Agents
| Scope | Routes | Gate | Notes |
|---|---|---|---|
agents:read | GET /api/v1/agents | permission | :102 |
agents:manage | POST /api/v1/agents | permission | :103 |
Resource scopes (ownership + admin layer)
?RESOURCE_SCOPES (sol_auth_middleware.erl:252–279) adds a second check
After the permission check passes. Three shapes
(sol_auth_middleware.erl:701–764):
{admin, require} → sol_identity:is_admin (permissions contain *)
or 403. Exact-match routes only — the prefix matcher cannot disambiguate
sibling actions on parameterized paths (sol_auth_middleware.erl:705–709).
{own, {Module, Function, BindingKey}} → admin passes; otherwise
Module:Function(ResourceId) resolves the owner and
sol_identity:is_owner/1 compares it to the caller (sol_identity.erl:33–39:
* holders pass, else uuid equality).
undefined → no ownership rule; the layer is a pass-through.
| Rule | Scope shape | Owner source | Notes |
|---|---|---|---|
GET/HEAD/DELETE /api/v1/conversations/ | own | sol_conversation:get_owner(conv_id) (sol_conversation.erl:77) | :253,254 |
GET/HEAD/POST/PUT/PATCH/DELETE /api/v1/tasks/ | own | sol_task_store:get_owner(task_id) (sol_task_store.erl:236) | mirrored across methods:255–263,267 |
GET/HEAD /api/v1/orchestrate/ | own | sol_task_store:get_owner(id) | :266; HEAD folds to GET |
GET/HEAD/POST /api/v1/workflows/ | own | sol_workflow_manager:get_workflow_owner(id) (sol_workflow_manager.erl:164) | :268,269 |
POST /api/v1/schedule/spawn | admin | — | exact-match route:270 |
POST /api/v1/debug/ | admin | — | eflame profiling stacks,:273; POST-only since then |
POST /debug/pprof/ | admin | — | also handler-gated by enable_pprof (default false):278; sol_http_debug.erl:12; POST-only |
The profiler family starts CPU work, so it is a mutation for CSRF purposes:
the middleware rule is POST, and GET/HEAD/every other verb answers a
typed 405 + Allow: POST. For
non-profiler routes, HEAD authorizes as GET (the middleware folds it into
the GET membership check; ). Streaming routes are the
explicit exception: they are GET-only and answer HEAD with a typed
405 + Allow: GET before any SSE admission.
Handler-level admin gates still exist where one parameterized path carries sibling actions the middleware cannot split (e.g. channel detail mutations, schedule detail reads) — the middleware rule is the coarse gate, the handler check the fine one (sol_auth_middleware.erl:197–200, sol_http_channels.erl:18ff).
Failure semantics of the owner lookup (sol_auth_middleware.erl:730–761):
| Owner lookup result | Behavior |
|---|---|
{ok, Owner} and caller is owner/admin | pass |
{ok, Owner} and caller is not | 403 insufficient_permissions |
{error, not_found} / {error, {not_found, _}} | pass through — the handler re-checks and answers 404 itself (no existence oracle: a 403 here would confirm the object exists) |
| any other error (store down) | fail closed: 503 owner_store_unavailable + owner_store_error counter |
The execute class: tasks:execute
tasks:execute is not an HTTP route scope — no middleware rule requires
it. It is the dispatch-plane grant that authorizes execute-grade behavior
on workers. Execute-class tools are bash, code_exec, task,
background_spawn (client/core/permission_checker.lua:245–249).
Sol side (dispatch clamp)
sol_zmq_task_dispatcher (server/src/sol_zmq_task_dispatcher.erl):
Grant check has_execute_grade/1 (:519–528): *, or the exact string
tasks:execute, or any :write-suffixed grant while
legacy_write_implies_execute is true (default true for existing
installs; new installs should set false).
Permission_mode clamp clamp_task_permission_mode/2 (:459–483): the
user-supplied permission_mode wire field must be one of the 6 valid
modes (allow-all, deny-all, read-only, default, plan, auto,
sol_zmq_task_dispatcher.erl:39–42); anything else is rejected to default. A requester without
execute grade may not select allow-all/auto — both are clamped to
read-only with a counted metric (:485–501). A degraded {system,[]}
identity clamps like any read-only requester.
No identity sniffing: the only bypass is the explicit
internal_dispatch => true flag, which is stripped from user-supplied opts
at the single send funnel before the clamp reads the map (:504–509) —
public callers cannot forge it.
Wire forwarding: permissions is ALWAYS present on the wire (,
224–240) and the dispatcher snapshots user_uuid + permissions into
the durable dispatch receipt, so the worker enforces the caller’s
grant, not the worker’s own config.
Luna side (worker mirror)
check_server_permissions (client/core/permission_checker.lua:272–331),
consumed at the top of check (:334–341):
Server grant (wire permissions) | Effect on worker |
|---|---|
| absent (nil — legacy Sol) | skip server gate; local config only |
[] (explicit-empty) | deny-default for write/execute-class tools in enforced modes |
["*"] | admin override → allow all |
contains *:execute suffix match | execute-class tools may proceed to local rules |
contains *:write and legacy flag true | execute-class proceeds (legacy rule) |
only *:read | write/execute denied (deny-wins, ) |
Known asymmetry (recorded): Sol’s grant check requires the exact string
tasks:execute (sol_zmq_task_dispatcher.erl:526), while the Luna mirror
accepts any :execute-suffixed grant
(client/core/permission_checker.lua:296). Grant tasks:execute literally to
satisfy both.
Children spawned by a task inherit the server grant as a ceiling with a
deny-all default; legacy_write_implies_execute lives in
client/core/config.lua:425–436.
Admin, service tokens, and user tokens
Admin means the identity’s permission list contains the literal *
(sol_identity.erl:41–50). * also bypasses every ownership check
(sol_identity.erl:33–39) and grants every scope
(sol_auth_middleware.erl:598). Mango’s handler-side is_admin also requires
the literal * (mango/mango/handlers/init.py:1631–1644): the legacy
Mango-only admin:* alias is INERT on both planes since then/
(new role writes have refused it since then; migration v0020 strips
stored aliases).
Session vs service tokens resolve permissions through the same
path (team roles → permission set, mango/systems/auth.py:668–702). The
credential class is still enforced per-route, but /auth/revocations
additionally requires authority, not just a service token: the
revocations:read permission, the bare * admin binding, or the
MANGO_REVOCATIONS_READ_USERS uuid allowlist
. The
permission is declared in the Mango classification fixture and never seeded
to a default role; a zero-permission service token therefore gets 403
.
User-token semantics are deny-default: an identity with [] passes
only routes with no required permission (and no admin/ownership rule).
Some actions are Mango-side gated and never appear in Sol’s map:
auth:self covers password change and self-service token revocation
(mango/mango/handlers/init.py:477–486, mango/mango/handlers/auth.py:1282);
Mango’s own CRUD routes (/users, /roles, /teams, /orgs) derive
actions as <resource>:<method-verb> (mango/mango/handlers/init.py:447–492)
and are checked against the same roles.permissions strings.
Mango composition (roles → scopes)
How a Mango role becomes a Sol scope grant:
- Roles are rows of opaque permission strings:
"*"ornamespace:action(validated, mango/systems/rbac.py:29–40). Roles attach to teams, teams to users (user_teams→team_roles→roles). - At token validation, Mango unions the permission sets of all roles on all of the user’s teams and returns the sorted set (mango/systems/rbac.py:304–345 → mango/systems/auth.py:668–702).
- Sol receives that set verbatim and applies exact-string membership (see matching rules).
Honest composition caveats:
New Mango roles cannot carry namespace:* (or admin:*) grants:
_validate_permissions refuses them at create/update.
Roles written by older releases may still hold those strings, and the
legacy _match_permission read matcher keeps expanding them for backward
compatibility — but such a grant is dead on the Sol plane, which matches
exact strings plus the bare * only. Only * (bare) spans both planes.
The seeded roles (mango/systems/rbac.py seed_default_roles) are
pinned to one shared vocabulary by
server/test/fixtures/rbac_permission_matrix.json +
ci/rbac_permission_vocabulary_lint.py. Three
grants are Mango-side only — auth:self, users:read,
user_tasks:read (the Mango route derivation consumes them) — and
carry an explicit mango_scopes classification; every other seeded
string is a Sol scope. The previous drift (scheduler:read vs the
Sol schedule:read, plus the consumed-nowhere teams:members and
dashboard:read) is RETIRED from the seeds; Mango migration v0011
rewrites upgraded installs onto the canonical list.
Caching: Sol caches validated identities for 5 s with a 256-entry LRU
(sol_mango_client.erl:34–36) and flushes on invalidate_user/ invalidate_role (sol_auth.erl:105–117); Mango caches per-user permission
sets behind an epoch guard so a raced invalidation refetches rather than
serving pre-revocation state (mango/systems/rbac.py:347–367), and empty
sets are never cached (mango/systems/auth.py:696–712). Role updates are
CAS-guarded so a concurrent edit can never cache the losing list (,
mango/systems/rbac.py:144–201). Worst-case revocation latency is the
Sol cache TTL plus the revocation resync window.
Seeded roles
Machine-checked against server/test/fixtures/rbac_permission_matrix.json
by ci/rbac_permission_vocabulary_lint.py: the Mango seed lists, this
table, and the Sol check set are three views of one vocabulary
.
| Role | Permissions |
|---|---|
admin | * |
member | agents:read, auth:self, channels:read, chat:create, chat:read, conversations:create, conversations:list, inference:catalog, inference:discover, inference:list, inference:use, marketplace:browse, marketplace:install, memory:read, memory:write, models:read, schedule:read, sessions:create, sessions:read, skills:browse, tasks:read, teams:list, user_tasks:read, users:read, workflows:read, workspace:read, workspace:write, zmq:list |
viewer | agents:read, auth:self, channels:read, chat:read, conversations:list, inference:catalog, inference:discover, inference:list, marketplace:browse, memory:read, models:read, schedule:read, sessions:read, skills:browse, tasks:read, teams:list, user_tasks:read, users:read, workflows:read, workspace:read, zmq:list |
The member/viewer read legs cover the console’s reads: schedule listing
(schedule:read), task polling/status (tasks:read) and the ZMQ worker
inventory (zmq:list, WorkersView). zmq:status is deliberately not
seeded — no Limon view or CLI verb reads /api/v1/zmq/status under a
member identity.
Exempt paths and the anonymous envelope
Default exempt list (sol_auth_middleware.erl:40–44): /health,
/api/v1/health, /api/v1/ready, /api/v1/infra/status,
/api/v1/infra/maintenance, /api/v1/shares, the six login/validate/
logout paths, and the /api/v1/webhook/ subtree (signature IS the auth,
P2-3). Operators extend via auth_exempt_paths (merged, slash-normalized,
sol_auth_middleware.erl:609–655). /metrics is NOT auth-exempt
a tokenless scrape is allowed only when the loopback
TOPOLOGY holds (the TCP peer, not proxy headers); otherwise it needs
metrics:read. The canonical generated list lives in
auth-flow.md.
Exempt means “no token required”, never “skip authorization”:
the request continues as the anonymous envelope {user_uuid:= <<"anonymous">>, permissions:= []} through the FULL RBAC + ownership
layers (sol_auth_middleware.erl:433–451).
Consequence: an exempt path whose route carries a scope (e.g.
/api/v1/infra/status → infra:read) answers 403 to the anonymous
envelope under Mango auth. The middleware warns at load when a configured
exemption overlaps any scoped route ( P3,
sol_auth_middleware.erl:660–682). Truly anonymous-readable routes are ones
with no rule at all (e.g. /api/v1/shares).
Failure postures
| Status | When | Body |
|---|---|---|
| 401 | missing/invalid/expired token; rejected WS ticket | family-aware envelope (sol_http_json.erl:236–262, sol_auth_middleware.erl:356–357): Zerg {"ok":false,"error":{"code":"unauthorized",...}}, OpenAI/Anthropic dialects on their routes |
| 403 | scope not held, admin route, ownership mismatch — one code, insufficient_permissions | same family-aware shape (sol_auth_middleware.erl:569–575,716–720) |
| 404 | object not found — raised by the handler, after the ownership layer deliberately passes not_found through (no existence oracle) | handler-owned |
| 429 | rate limit | {"error":"rate_limited","retry_after":N} + header (sol_auth_middleware.erl:296–305) |
| 503 | dead rate limiter; auth-rate-limit saturation (rate_limiter_unavailable + Retry-After), owner-store transient failure; maintenance mode; Mango RBAC lookup outage (Retry-After 30, mango/mango/handlers/init.py:418–430) | typed JSON envelopes — an outage is never rendered as 403/500 |
Scope inventory summary
61 distinct HTTP scopes (116 route rules) across ?ENDPOINT_PERMISSIONS/?RESOURCE_SCOPES + the shared sol_chat_authz:rest_rules/0 table.
3 admin-gated rules in ?RESOURCE_SCOPES (schedule:spawn + 2 debug
families); 10 ownership (own) rules.
1 dispatch-plane execute scope (tasks:execute) — not an HTTP scope.
3 Mango-side grant strings outside Sol’s vocabulary: auth:self,
users:read, user_tasks:read (all consumed by Mango’s own route
derivation; classified in the shared fixture’s mango_scopes).
The bare * is the admin/wildcard grant, not a scope.
See also
permissions.md — client-side permission modes, rulesets, danger detection, AI classifier. auth-flow.md — token issuance, validation, revocation. security.md — transport trust plane, threat model. api-reference.md — route-by-route API surface.
Engine reference — generated from the canonical engineering source. Do not edit this page by hand.
Security Guide
Threat Model
Localhost-only (Default)
By default, Sol binds the HTTP API to 127.0.0.1:21434. This mode is suitable for single-user development on a trusted machine. No authentication is required.
HTTP API: 127.0.0.1 only
ZMQ gateway: 127.0.0.1 only
No API key required
No TLS
Network-exposed (Requires Hardening)
Exposing Sol to a network requires additional security measures.
Current hardening:
Change http_ip to bind a specific interface (not 0.0.0.0)
Use a reverse proxy (nginx, caddy) for TLS termination
Restrict access with firewall rules
API key authentication — Bearer token via sol_auth gen_server + Cowboy middleware (/health exempt)
Per-key rate limiting — token bucket via sol_rate_limiter (60 RPM default, configurable burst)
Mango token delegation — Sol delegates Bearer token validation to Mango HTTP service; user identity (uuid + RBAC) propagated to ZMQ workers
Mango service-token scope
Mango issues two token types with deliberately different authority.
Session tokens are interactive and resolve the owner’s full LIVE RBAC
set on every validation (a demotion/revocation binds immediately); they
are never scoped. Service tokens are machine credentials with long
TTLs (7d default, 90d max) that survive password changes; they now carry
an explicit scope (a JSON permission-verb array in tokens.scope,
migration v0017). Validation returns min(user_permissions, token_scope),
so a service token can never gain permissions the user loses and can
never exceed its grant even while the owner is an admin. The mint refuses
a scope wider than the owner’s live set; a NULL scope is the legacy
full-RBAC posture and must be rotated (GET /auth/service-tokens lists
each token WITH its scope; set MANGO_SERVICE_TOKEN_DEFAULT_SCOPE=default
to make the documented read-only inventory the mint default). A
hand-corrupted/unparseable scope fails CLOSED (empty effective set),
never back to the owner’s full grant. Sol consumes the resolved set
verbatim, so Mango-side scoping downscopes the dispatch surface without a
Sol change. Details: docs/auth-flow.md (Token-type authority model).
ZMQ state caps — worker (100), listener (1000), pid (10000) caps prevent unbounded memory growth (shipped sys.config; the code fallbacks in sol_zmq.hrl are 256/1024/1024)
Current Security Features
SSRF Prevention
Webhook URL validation blocks requests to private and local IP addresses:
127.0.0.0/8 (loopback)
10.0.0.0/8 (private class A)
172.16.0.0/12 (private class B)
192.168.0.0/16 (private class C)
169.254.0.0/16 (link-local)
DNS resolution is performed before checking. IPv6 private ranges are also blocked. DNS resolution failures now correctly reject the request rather than bypassing the check.
In-process transport admission
execution.sandbox.network = false (the default) is enforced by ONE
admission funnel (client/core/transport.lua) before any in-process HTTP
client opens a socket: web_fetch, the speculative web paths,
http_request, sequential web_search, MCP HTTP/streamable-HTTP, the
memory vector search/write-through legs, and the provider/configure setup
helpers. The funnel also parses the URL authority with
client/core/url_authority.lua (userinfo refused, bracketed IPv6/ports
preserved, the exact host drives DNS/policy/pins/redirects) and refuses
private/LAN/metadata targets.
Non-loopback targets must use https://. Plaintext HTTP is refused
unless the operator makes an EXPLICIT acknowledgement
(execution.sandbox.allow_plaintext_http = true or
LUNA_ALLOW_PLAINTEXT_HTTP=1); loopback stays reachable for local
sidecars. A failed TLS probe is a typed error — core.swarm and
core.managed_config never downgrade to plaintext on probe failure
(the bearer/credential is never attached to a downgraded URL).
Workspace write boundary and undo replay
Every model-reachable write (write_file, edit_file, multi_edit,
apply_patch, notebook, create_directory, delete_file, and the undo
replay) runs through client/core/write_policy.lua:
the historical sensitive-name denylist stays;
~/.luna is a write-deny root (and any path carrying a .luna
component): hooks, policies, config, MCP servers, settings, approvals,
trust markers, keys, agents, tools, and extensions can never be written
by a model. The only exception is the narrow data directory
~/.luna/data/;
the check is lexical for missing leaves AND realpath-based for existing
ones (the deepest existing ancestor is resolved), so a not-yet-created
~/.luna/approvals/trust-x.json is refused too;
the gate fails closed if core.sandbox cannot load.
undo_edit re-runs the full workspace/credential/sensitive-path gate on
replay, refuses a symlink final component (O_NOFOLLOW open + lstat
verification), writes through the shared atomic-write primitive
(mkostemp + fsync + checked rename), binds each entry to the workspace it
was recorded in, and keeps a session-scoped stack (no cross-session undo).
Legitimate product writes still use their owner APIs (session/memory/blob owners) and are unaffected; only the model-facing tool surface is gated.
Host-locality proof
The tokenless metrics gates (/metrics, /api/v1/metrics) and the
auth-disabled dev principal accept a request only when it is HOST-LOCAL.
The base test is is_loopback_topology/1: loopback TCP peer AND every
forwarded hop (X-Forwarded-For, X-Real-IP, RFC 7239 Forwarded) names a
loopback address. That inference is negative — an on-host proxy that never
sets a forwarded header satisfies it.
locality_secret / SOL_LOCALITY_SECRET adds a POSITIVE proof. When the
secret is configured (≥16 bytes), the on-host proxy must inject:
x-zerg-locality: <unix-seconds>:<lowercase-or-uppercase hex HMAC-SHA256>
over the canonical string METHOD "\n" PATH "\n" TIMESTAMP (the path is
the router-canonical form). The verifier accepts ±300 s (bounded replay) and
compares in constant time. With the secret set, a loopback peer without a
valid proof is refused. Without the secret, the positive proof is an
EXPLICIT loopback Host authority (localhost/127.0.0.0/8/::1): an
on-host proxy forwarding an external request without a forwarded header
still carries the public Host and is refused (, HTTP-08 — the
pre-fix negative “no forwarded header” inference is gone); a one-time
WARNING records the posture. A configured but short secret fails CLOSED
(one-time CRITICAL) rather than silently reverting to the weaker posture.
The active posture is also reported as a boot datum (,
B3- residual): sol_auth_locality:boot_posture/0 logs one line at
boot — EXPLICIT-LOOPBACK (unset), ENFORCED/positive-proof
(configured) or FAIL-CLOSED (weak secret) — and returns the same typed
map (#{secret, proof_required, posture}). The datum is advisory and
never refuses boot; enforcement stays the verifier above.
Deployment note (wild blueprint): inject the header at the TLS-terminating
proxy for local scrape/dev traffic only; never forward a client-supplied
x-zerg-locality (strip it at the edge, then mint the proof).
Repo-config destination & credential consent
Luna’s project-local config files (.luna.json, .luna/settings.json,
.luna/settings.local.json) are untrusted input: a cloned repo can carry
them. Destination- and credential-selecting keys therefore join the
Security families and are ignored fail-closed unless a
hash-keyed consent marker exists in the USER’s approval dir
(~/.luna/approvals/trust-<sha256>.json; with a TTY the operator is
prompted once):
provider_base_url — the wire destination of every provider request
(the resolved Authorization/x-api-key credential rides along);
api_key, api_keys — credential sources;
auxiliary — the whole auxiliary model plane (base_url/api_key);
fallback_providers — failover destinations;
otel_endpoint — the Luna-local span sink (fire-and-forget HTTP POST from the worker; no cross-service tracing — Sol/Mango export no spans).
Without the marker the keys are stripped with a loud CRITICAL line naming
every family (client/core/repo_config_security.lua is the single list).
Defense in depth: client/core/provider.lua:from_model/3 independently
refuses a provider_base_url whose effective value still equals the
project-carried value while the consent verdict is false (a strip bypass),
falls back to the built-in destination, and counts + logs the refusal —
value equality keeps a same-key USER-supplied URL legitimate.
Project extension consent
Project-sourced extensions (.luna/extensions/*/ in the working
directory) are repo-shipped code: on the strength of the user-wide
extensions_enabled=true alone they used to auto-load — git clone attacker && cd repo && luna executed them. They now require the SAME
hash-keyed per-project consent as .luna/mcp.json servers: an
approval record keyed on the canonical parsed manifest hash in the
USER-owned approval dir
(~/.luna/approvals/extension-<sha256>.json; with a TTY the operator is
prompted once per extension, y/N, fail-closed on anything but an
explicit yes). ANY manifest change (version bump, permission or hook
edit) changes the hash and re-asks. Without a record and without a TTY
the project extension is REFUSED (surfaced in the loader’s failed list).
User-level ~/.luna/extensions never consults this gate; the extension
security scanner and the allow-listed sandbox env remain as
defense-in-depth for ALL extensions (client/core/extension_consent.lua
owns the gate; both load entry points — load_all and the rescan
hot-reload path — enforce it).
Repo-tool consent + load-time purity
<workspace>/.luna/tools/*.lua is repo-shipped CODE: on the strength of
the user-wide tools dir alone it used to auto-load — git clone attacker && cd repo && luna executed it. Every NON-home scan directory now loads
only with an explicit --allow-repo-tools (this run) or a user-owned,
content-keyed trust marker (~/.luna/approvals/trust-<sha256>.json,
hashed over the sorted tool-file contents; any edit invalidates the
approval). Consent is keyed to the actual directory being scanned:
capability_bootstrap passes the effective workspace into
ToolDiscovery.scan(workspace), so a first-setup workspace different from
PWD cannot bypass the gate (a boot-then-task worker reuses its boot
instance and never rescans a wire workspace). The user ~/.luna/tools
dir remains unconditional.
Load-time code is PURE DATA: tool files are loaded text-only (load(..., "t")) in an environment with NO Tools, os, io, or require
binding — a top-level effect raises and is contained. Only the returned
handler is given a restricted Tools dispatcher (installed after
validation): nested dispatch is allowed only when the inner tool’s
declared class is at or below the custom tool’s own
(none < read < write < execute), and execute-class nesting additionally
requires an explicit sandbox config — a handler can never silently spawn a
bare shell.
Stdio grant parity
Both task transports apply the same permission rule
(client/core/wire_permissions.lua): an absent/invalid permissions
field is explicit-empty (deny-default), and a wire permission_mode
paired with a grant that has no execute grade clamps to read-only. The
stdio worker previously read neither field.
CORS preflight contract
A genuine CORS preflight is OPTIONS with BOTH an Origin and an
Access-Control-Request-Method request header and no body. The auth
middleware answers it directly with 204 + the configured CORS headers
(the sol_http_infra:reply_headers/2 chokepoint, limon_origin-gated) in
every auth posture — the handler is never reached and no identity is ever
attached, so a browser preflight cannot trip a verb-agnostic mutation.
Everything else is not a preflight: a bare OPTIONS probe takes the
normal auth path (401/403 with auth on) and is never handed an
anonymous identity; the generic dispatch clause answers any OPTIONS it
still sees with a typed 405 instead of dispatching. The one mutation the
sweep found verb-agnostic — telemetry clear — is now POST-only at the
handler (GET/OPTIONS → typed 405), pinned by
ci/get_mutation_lint.py (clear in the corpus).
Canonical request path
Sol authorizes the SAME path the Cowboy router dispatches. The middleware
computes one canonical path (sol_auth_middleware:canonical_path/1) with
the router’s algorithm — split on /, percent-decode each segment, RFC
2396 dot-segment removal — and every decision (API version, exemptions,
metrics gate, anonymous grants, RBAC, ownership, rate-limit keying, WS
handshake matching, maintenance, SLO class) consumes it. Paths the router
would represent ambiguously are refused 400 invalid_request_path:
encoded separators (%2F/%5C), empty internal segments (//), invalid
percent escapes, control bytes, and non-absolute paths. A raw
/health/../api/v1/skills is therefore authorized as /api/v1/skills, and
%XX can never resolve a different route than the one that was checked.
HEAD and OPTIONS
HEAD carries GET’s authority and nothing else: permission and resource
scope resolution map it to GET, so it can never read a resource the
equivalent GET would deny. A HEAD on a path whose only rules are for
other methods answers 405. A bare OPTIONS (not a genuine preflight)
never reaches a known handler: the RBAC chokepoint answers 405 with the
route’s Allow set. Only the genuine preflight branch answers 204.
Release-binary obfuscation (not encryption)
The secure Luna and CLI builds (client/build/build.sh,
zerg-cli/build/build.sh) XOR the embedded Lua blobs, add a CRC32
integrity check, strip, and (for Luna) UPX-pack the result. This is
Obfuscation, not encryption: the key is deterministic from the
shipped sources. client/build/encrypt_blobs.py:derive_key_from_sources/3
computes SHA-256 over the sorted module list, updating with each
.lua file’s bytes plus a NUL separator, and truncates the digest to
32 bytes. The build splits that key into two arrays stored in
different parts of the generated C file; the runtime reconstructs it as
half_a XOR half_b. Anyone holding the same sources can derive the same
key, so the binary gains no confidentiality and protects no secret — it
only raises the effort of casual inspection. Use --plain --no-upx when
debugging.
Worker Path Validation
The worker_path configuration is validated against a configurable prefix. This prevents arbitrary binary execution:
%% sys.config — only binaries under /opt/sol/bin/ are allowed
{worker_path, "/opt/sol/bin/luna"}
Workers spawned via the HTTP API are also validated.
Error Sanitization
HTTP error responses never contain internal Erlang terms. All errors are mapped to generic strings:
{"ok": false, "error": {"code": "model_not_found", "message": "model not found"}}
The /api/v1/* family answers the Zerg {ok, error:{code, message}}
envelope; the catalog of error codes is stable and documented. Internal
details like process IDs, supervisor references, and stack traces are
logged server-side but not exposed to clients.
Method Enforcement
Mutation endpoints require POST method. Other methods receive 405 Method Not Allowed:
/api/v1/start, /api/v1/stop, /api/v1/stop-all
/api/v1/discover
/api/v1/agents/spawn, /api/v1/agents/:id/kill
/api/v1/cluster/join, /api/v1/cluster/leave
/api/v1/lua/eval, /api/v1/lua/workers/spawn
/api/v1/zmq/dispatch
/api/v1/circuits/reset
/api/v1/schedule/spawn, /api/v1/schedule/:id/run
/api/v1/channels/spawn, /api/v1/channels/:id/message
/api/v1/orchestrate
/api/v1/telemetry/clear
Root User Safety
Sol uses erlexec to manage OS processes (llama.cpp, workers). When running as root:
Effective user is downgraded to nobody (configurable)
Command arguments are passed as lists, not shell strings — preventing shell injection
Process monitoring uses Erlang monitors, not polling
Plugin Sandbox
Lua plugins run in a sandboxed Luerl VM with restricted standard libraries:
| Library | Status | Reason |
|---|---|---|
os | Removed | Prevent OS command execution |
io | Removed | Prevent file system access |
debug | Removed | Prevent VM inspection |
package | Removed | Prevent module loading |
string | Available | String operations |
table | Available | Table operations |
math | Available | Math operations |
coroutine | Available | Coroutine support |
Additional protections:
Eval timeout: 3000 ms per lifecycle call by default
(plugin_lifecycle_timeout_ms, — the old 15 s constant
kept a hostile plugin inside the caller for a quarter minute) — prevents
runaway computation; lifecycle Lua runs off the manager’s critical path
Periodic GC: Luerl VM garbage collected between calls
Network access: Only via sol.http bridge (mediated by Sol)
No filesystem access: No way to read or write files from Lua
ETS Heir Protection
Critical ETS tables survive owner process crashes via {heir, Pid}:
| Table | Owner | Data |
|---|---|---|
sol_models | sol_registry_owner | Model registry |
sol_global_catalog | sol_catalog_owner | Cluster catalog |
sol_metrics | sol_metrics_owner | Metrics counters |
sol_task_results | sol_task_store_owner | Task results |
sol_task_tokens | sol_task_store_owner | Task tokens |
sol_scheduled_jobs | sol_scheduler_store_owner | Scheduled jobs |
sol_circuits | sol_circuit_owner | Circuit breaker state |
sol_provider_pool | sol_provider_pool_owner | Provider keys |
sol_channels | sol_channel_owner | Channel instances |
Graceful Shutdown
prep_stop drains in-flight requests before the VM shuts down. This prevents data loss during rolling upgrades.
Known Security Issues
The historical server findings below are fixed:
| ID | Issue | Fix |
|---|---|---|
| SRV-8 | Plugin HTTP bridge sends HTTPS over plain HTTP | FIXED (S52) — TLS verification enabled for plugin HTTP requests |
| SRV-9 | DNS resolution failure bypasses SSRF check | FIXED (S36) — resolution failures now reject the request |
This page is not a claim of zero open security work. The live
open/accepted register — including wild-owned legs (crash-dump hygiene,
fleet key rotation/CD) and the accepted provider-key-at-rest posture — is
docs/known-security-gaps.md; the hardening program is
docs/production-flip-checklist.md. See also §Audit history and
docs/archive/AGENTS-decisions-archive.md.
Limon bearer storage — accepted residual
Posture (RECORD — accepted, no auth rework). The Limon SPA holds the
session bearer in sessionStorage (TOKEN_STORAGE_KEY in
limon/src/stores/auth.ts; guarded by the shared storage helper with an
in-memory fallback for storage-disabled browsers). Any script executing in
the SPA origin can read it: this is XSS-exfiltratable by architecture.
The posture reduces — it does not eliminate — that class; the mitigations
below are the layered defense, and the alternatives are recorded for the
roadmap rather than silently assumed safe.
Layered mitigations (verified real).
CSP script-src 'self' — the enforced production policy is
single-sourced in limon/src/csp.ts (CSP_HEADER_VALUE) and served as
an HTTP response header by the deployment layer (the meta tag in
index.html cannot enforce frame-ancestors, hence the header
contract). No inline script, no unsafe-eval, no third-party script
origins; object-src/frame-src/frame-ancestors are 'none'. An
injected <script>/event-handler payload is blocked at the parser.
Single DOMPurify chokepoint — every rendered-HTML sink routes
through sanitizeMarkdownHtml in limon/src/composables/useMarkdown.ts
(markdown-it html:false as the first belt, DOMPurify with an explicit
forbid-tag profile as the second). The two v-html sinks are
ChatMessage.vue (rendered LLM content) and SkillDetailModal.vue
(marketplace bodies); ci/limon_sink_lint.py freezes them to those two
sanitized bindings (shrink-only; a new v-html/innerHTML/
dangerouslySetInnerHTML sink is RED).
No token in URLs or logs — the bearer travels only in the
Authorization header; the chat WS authenticates via the REST-minted
one-time ticket subprotocol (never a query-string token), and HTTP
request logging never records the header value.
Roadmap options (not implemented — each is a real trade, not a free win).
- Cookie realm (HttpOnly/Secure/SameSite) for same-host deployments.
Removes JS readability, so XSS can no longer exfiltrate the credential —
but it does not stop an XSS payload from acting in-session, and it
converts every state-changing request into a CSRF surface (the
double-submit
zerg_csrfcontract already covers Mango’s cookie-authenticated legs, not the whole API). It also assumes the API is same-origin: the supported air-gap/private-network topologies point the SPA at a different host, whereSameSitecookies needSameSite=None; Secureand credentialed CORS, and the WS ticket flow would need rework. Requires a cookie realm in Mango plus a migration window. - Short-TTL bearer + silent refresh. Keep the header-only transport (no CORS/CSRF change) but shrink the exfiltration window to the token TTL and the blast radius of a leaked value; a refresh credential held outside JS (or a re-auth prompt) completes the loop. Costs: a refresh endpoint + rotation/revocation semantics, more 401/retry churn, clock skew in air-gapped deployments, and the token is still readable during its TTL.
Either option is a deliberate architecture change with its own review; the current posture is accepted knowingly, with the sink lint and CSP as the enforcement floor.
Implemented Security Features
API key authentication — Bearer token via Authorization: Bearer <key> header; sol_auth validates against local keys or Mango service
Per-key rate limiting — sol_rate_limiter enforces 60 RPM per key (configurable)
ZMQ state caps — worker_cap=100, listener_cap=1000, pid_cap=10000 as shipped in sys.config (code fallbacks 256/1024/1024 in server/include/sol_zmq.hrl; configurable via zmq_worker_cap/zmq_listener_cap/zmq_pid_cap)
Error sanitization — internal Erlang terms never leaked to HTTP clients
SSRF prevention — webhook URL validation blocks private IPs; DNS rebinding protection
Landlock sandbox — Linux 5.13+ kernel-enforced filesystem ACL; a WRITE-DENY layer only (read enforcement stays with bwrap’s ro-binds — Landlock’s allowlist model cannot deny arbitrary read paths). Landlock↔bwrap composition is a measured FINAL DECLINE: a live Landlock write-domain refuses bwrap’s user-namespace setup (the /proc/self/{setgroups,uid_map,gid_map} writes EPERM), and after a user namespace is pre-created bwrap’s mount stage still fails (Failed to make / slave: Operation not permitted) — a live domain refuses mount(2) outright with EPERM at both granted and ungranted targets. The only ordering that works is namespaces + mounts first, Landlock after (probe: post-mount granted write OK, outside write EACCES), which requires an applier running inside the bwrap namespace that bwrap does not expose and Luna does not ship. So when bwrap wraps the spawn the fork layer STANDS DOWN with a loud one-time warning, and Landlock remains the write-deny layer for bwrap-less spawns (bwrap=off or bwrap unavailable) — never both layers, never none silently. Decision record: client/core/sandbox.lua (LANDLOCK_BWRAP_COMPOSITION); pinned by the real-kernel suite client/tests/test_sandbox_composition_truth.lua
Bwrap/seatbelt sandbox — user-space sandbox wrappers (bwrap on Linux, seatbelt on macOS — one wrapper per spawn, NOT stacked with the Landlock fork layer; see above): workspace isolation; custom /etc/hosts injection; --die-with-parent; --unshare-net
Bwrap namespaces + env allowlist — --unshare-pid --unshare-ipc --unshare-uts (same-uid process enumeration/kill isolation; SysV IPC isolation; hostname spoofing isolation) + --clearenv with an explicit env allowlist (PATH HOME LANG LC_ALL TMPDIR USER LOGNAME SHELL + per-tool env_passthrough extras) so SOL_API_KEY / provider keys / *KEY*/*TOKEN*/*SECRET* vars never cross the namespace boundary; the _spawn_popen fallback and io.popen sites (configure wizard) scrub the same key-shaped vars via env -u; MCP/LSP stdio servers run with a Landlock-only config and a child env rebuilt from the allowlist
Sandbox layer matrix — authoritative layer ownership (keep in sync with the client/core/sandbox.lua header):
Bwrap: namespaces (pid/ipc/uts/net) + env allowlist + read-deny (tmpfs//dev/null shadows over credential paths) + ro-bind root + workspace rw binds + network isolation
Landlock: fork-layer write-deny only (WRITE_FILE|REMOVE_FILE|MAKE_DIR beneath workspace root + rw grants); NEVER EXECUTES a ruleset containing EXECUTE
Landlock↔bwrap composition: the two layers cannot wrap one exec — a live Landlock domain EPERMs bwrap’s userns setup and mount stage and refuses mount(2) outright; the working order (namespaces/mounts first, Landlock after) needs an in-namespace applier bwrap does not expose. Wrapped spawns therefore run under bwrap only with Landlock stood down (loud one-time warn); sandbox_layers_effective reports the APPLIED composition (bwrap), sandbox_layers_available reports the capability probe (bwrap+landlock-abi<N>) — the telemetry never claims bwrap+landlock. Evidence pinned by client/tests/test_sandbox_composition_truth.lua
Seatbelt: macOS SBPL profile (write-deny + ssh/gnupg read-deny); no namespace/env controls
Bwrap=off residual (documented): no read-deny and no network isolation — the Landlock fork layer still applies (write-deny is not disabled); execution.sandbox.bwrap = off/auto/required semantics verified real
Read_only_dirs overlap rule: a read_only_dirs entry nested UNDER a granted write root (workspace root / allowed_write_paths / rw_dirs) is unenforceable by the Landlock fork layer — path-beneath rules are ADDITIVE and no rule can carve an exception out of a parent grant. Such a config is REFUSED in the landlock-only postures (every mode, including auto) with the typed landlock_ro_overlap:<ro>:<root> error — the spawn exits 127 rather than silently running with the “read-only” path writable. A read_only_dirs entry that is an ancestor of (or equal to) a write root is fine: the write grant is dropped and the subtree stays read-only. Use bwrap’s ro-binds for subtractive read-only semantics.
Zero-active-layer posture: when enabled=true but NEITHER bwrap NOR Landlock is active (posture none), the spawn gate (sandbox.zero_layer_spawn_gate, called from both ffi.init gates) refuses with the typed sandbox_unavailable error when execution.sandbox.require_effective_layer=true, or when the Sol session is NON-LOOPBACK and execution.sandbox.effective_layer_ack is unset; loopback/TTY sessions keep the warn-only posture (sandbox.zero_layer_spawns + one-time loud warning). Refusals are counted (sandbox.zero_layer_refusals, require_effective_layer_refusals, non_loopback_unacked_refusals) and the APPLIED composition travels to Sol as sandbox_layers_effective (absolute gauge; SolLunaSandboxInert pages on the inert posture)
Filesystem sandbox — worker path validation; binary_to_existing_atom guards; path traversal prevention
Role-based access control — Mango RBAC roles propagated via ZMQ user_uuid
Header injection prevention — HTTP header values validated to reject CR/LF characters
Path traversal prevention — file paths normalized and checked for .. traversal sequences
Timing-safe token comparison — API key validation uses constant-time comparison
Session fixation prevention — session identifiers regenerated after authentication state changes
Prompt Injection Detection (L43)
Client-side prompt injection detection is applied to all user input before LLM processing:
35 patterns across 11 categories — client/core/injection_detector.lua PATTERNS.
Patterns by category:
system_override — “ignore previous instructions”-style prompt overrides
memory_injection, memory_override — attempts to poison or replace stored memory
context_manipulation — attempts to override system-prompt instructions
role_override, role_manipulation — attempts to reassign the assistant’s role (“you are now…”, “disregard instructions”)
instruction_smuggle — hidden instructions in comments/markup (<!--[SYSTEM]-->)
encoding_evasion — URL/hex/unicode-encoded payloads
exfiltration — attempts to send data to external endpoints
capability_escalation — attempts to disable security or bypass the sandbox
tool_abuse — piping fetched content into a shell
3 severity levels:
info — logged but allowed (low-confidence matches)
warning — logged and surfaced to user (moderate-confidence matches)
block — request rejected before reaching LLM (high-confidence matches)
Implemented in client/core/injection_detector.lua (PATTERNS; the live count is the generated block above, gated by ci/docs_constant_parity_lint.py)
Air-Gapped Deployment (S79)
Sol supports fully air-gapped deployment with no outbound network connections:
WILDZERG blueprint — the canonical on-prem deploy (runit + podman, air-gap capable) is provisioned via wild/AGENTS.md + wild/scripts/provision/; the legacy deployment/infra/scripts/setup.sh was archived with the old on-host model
Docker Compose profiles (legacy, archived) — --profile mango for optional services; core stack runs without internet access
Local routing — all inter-service communication stays within the cluster network; no external DNS or API calls required
Production configuration — environment variables for all endpoints, no hardcoded external URLs
Egress inventory
The egress points below are the complete inventory: worker/CLI gates, plus Sol deployment-configured endpoints. “Complete” means no other shipped background caller exists; it does not mean the configured endpoints are inert.
| Egress point | Gate | Default |
|---|---|---|
| LLM provider endpoints (by design) | provider config (per-provider key + base URL) | on |
osv_check.lua + mcp_osv.lua (MCP package-vuln lookup to api.osv.dev, via the single osv_gate.lua) | LUNA_ALLOW_OSV_CHECK | off |
auto_install.lua tool downloads (curl of pinned release assets), package-manager installs, and install_via_pip (via the single egress_gate.lua) | LUNA_ALLOW_TOOL_INSTALL | off. sudo package installs additionally require explicit caller consent |
zerg update check + SHA256 fetch | ZERG_ALLOW_EGRESS_UPDATE | on |
Sol license/seat refresh (seats_url) — background HTTP(S) fetch every seats_refresh_ms (default 30000) with peer verification | seats_enabled + seats_url (empty URL = no timer) | off unless configured |
Sol OAuth token refresh for declarative providers (token_url; zerg oauth login) | provider oauth sub-map | off unless configured |
Local model server (localhost:11434, ollama) | loopback only — not egress | — |
Set the gates to 0/false for a strict air-gap posture; the Sol/Luna
frontend trees (limon/toronja/starfruit, Luna core) contain NO third-party
CDN/analytics references — asserted by ci/egress_assert_lint.py (born
required, ).
OAuth/PKCE for MCP Providers
OAuth PKCE (Proof Key for Code Exchange) authentication is supported for MCP servers that require OAuth2 authorization. The flow uses FFI raw sockets for the callback server, crypto-random state generation, and the standard authorization code + token exchange flow.
(AUTH-13) endpoint hygiene: authorize_url and
token_url must be https, public (not private/loopback), and carry no
userinfo; token requests refuse redirects. The callback listener stays
loopback (RFC 8252), and the redirect URI is single-sourced
(get_redirect_uri(port) feeds the authorize URL and the token request).
Token persistence is checked: a failed save_token fails the flow typed
(failed to persist OAuth token) instead of returning an unpersisted
token.
Implemented in client/core/mcp_oauth.lua.
OAuth PKCE for declarative model providers
zerg oauth login <provider> completes a PKCE browser flow for a provider
whose JSON declares an oauth sub-map: Sol returns the authorize URL +
CSRF state (POST /api/v1/oauth/login, admin), the CLI binds the loopback
redirect (oauth_redirect_uri, default 127.0.0.1:21337/callback — only
loopback redirect URIs are bindable), the operator consents, and Sol
exchanges the code at the provider token_url
(POST /api/v1/oauth/login/complete, admin; PKCE S256, verifier never
leaves Sol). Access + refresh tokens persist under ~/.sol/oauth_tokens.json
(0600-from-birth); resolve_api_key consumes them, a provider 401 signals
a refresh through the pool’s auth-class report path, and a background tick
renews tokens inside a 5-minute window. zerg oauth status lists
connected providers; zerg oauth logout <provider> deletes one
(strict-audited).
Air-gap: the flow requires the operator’s browser + the IdP token_url
to be reachable — on a fully air-gapped fleet it cannot run. Keyring/env
API keys (zerg keyring-set, api_key_env) remain the canonical air-gap
credential path; nothing in the OAuth machinery is on the boot or request
critical path when unused.
DNS Rebinding Protection
DNS rebinding SSRF attacks are blocked via FFI getaddrinfo resolution. Before making HTTP requests to user-supplied URLs, the hostname is resolved and all resulting IP addresses are checked against private ranges. This prevents attackers from bypassing SSRF protections using DNS rebinding techniques.
Implemented in client/ffi/dns.lua (is_safe_hostname) and enforced in client/core/ssrf.lua (shared is_private_host).
Write Deny List
The filesystem tool enforces a deny list of sensitive paths that can never be written or overwritten:
.ssh/, .gnupg/, .aws/, .env, .bashrc, .zshrc/, .netrc, .pgpass, .profile, .gitconfig, authorized_keys
Adds the ~/.luna write-deny root (data-dir exception only) — the
auto-loaded/config/credential surface (hooks.lua, policies/*,
config.json, mcp.json, settings*.json, agents/*, approvals/*,
keys/*, tools, extensions) is never model-writable, including missing
leaves. Implemented in client/core/write_policy.lua; the undo replay
uses the same gate.
Session share capability model
Session shares (POST /api/v1/sessions, GET /api/v1/shares/:share_id)
use a capability-token model: the opaque share_id IS the capability
and the secret. The public view endpoint is unauthenticated BY DESIGN —
this is the recorded LOW adjudication, accepted because the id is a
256-bit random token (unguessable) and no separate ACL exists; possessing
the id is the authorization. There is no expires_at emission — expiry is
internal state. Compensating controls:
TTL clamp — ttl_days is clamped server-side to
min(ttl_days, 365); larger requests are capped loudly (server warning
share ttl_days N clamped to 365), never silent forever-shares
.
Per-user create quota — share_quota_per_user (default 100 live
shares); at quota the create answers 429 share_quota_exceeded with
retry-after: 3600, never a 500.
Per-IP read rate limit + read logging — the public endpoint is
rate limited per IP (share_rate_limit_per_min) and every read is
logged at notice level with share id + peer IP (;
sol_http_shares.erl).
Mango credential class
Mango computes the credential class BEFORE its CSRF decision. Only a
syntactically valid explicit Authorization: Bearer <non-empty> credential
suppresses the zerg_csrf double-submit check; Basic, an empty Bearer, a
bare token, or any other scheme does not. A mutating request carrying a
present-but-not-Bearer Authorization header is refused 401 and never
silently falls back to the ambient zerg_session cookie. Logout applies the
same predicate, revokes every credential actually presented (Bearer + cookie,
deduped), and clears cookies only after every revoke succeeds. Login requires
Content-Type: application/json (forcing a CORS preflight), closing the
text/plain login-CSRF leg.
CLI credential origin binding
zerg login records the token origin (token_origin) in the config/profile.
A stored token is sent only to that origin: an explicit --api-url override
never receives an origin-bound token for a different host, and a legacy
token with no recorded origin is never sent to an override at all. Explicit
credentials (--bearer, --token, ZERG_TOKEN) remain operator-supplied
overrides. --profile NAME login/logout writes and clears only
profiles[NAME], including the per-profile keyring entry.
Session-cookie CSRF contract
The zerg_session cookie is not a bearer. It is ambient — a browser
attaches it to every cross-site request — so the credential CLASS drives the
auth decision (sol_auth_middleware:extract_credential/1, the single
zerg_session reader in the route path; the logout leg and the WS handshake
are the other two sanctioned readers, pinned by ci/cookie_csrf_lint.py):
Safe methods (GET/HEAD/OPTIONS) — the cookie is accepted as a
bearer-equivalent credential.
Mutating methods (POST/PUT/PATCH/DELETE/…) — a cookie-authenticated
request must present the zerg_csrf double-submit pair (the
zerg_csrf header equal to the zerg_csrf cookie — the
Mango pattern, single-sourced in
sol_auth_middleware:csrf_pair_valid/1; the logout leg delegates there).
Absent/mismatched → typed 403 csrf_required (one uniform body — no
oracle), counted (cookie_csrf_refused_total). A cross-site form post can
carry the ambient cookie but can never set the header, so every mutating
route is covered at this single chokepoint — there is no
cookie-consuming mutating route outside the gate.
Authorization: Bearer and ?token= (when allow_token_query=true)
are explicit credentials — the CSRF class does not apply. The
Authorization header’s mere presence proves not-CSRF.
Nothing sets a live zerg_session cookie in this release (logout clears
it); the gate is the load-bearing contract for the first surface that does.
WS-handshake Origin binding
The “GET is safe” CSRF rule does NOT hold for a websocket upgrade: a
cross-site page can open wss://host/api/v1/chat/<id>/ws and the browser
attaches the ambient zerg_session cookie to the handshake (cross-site
WebSocket hijack — on success the hostile page can DRIVE the victim’s agent
session). At the same middleware chokepoint, every WS-handshake route
(sol_auth_middleware:is_ws_handshake_path/1, derived from the route table)
authenticated by the cookie class must present a trusted Origin
header BEFORE the upgrade — mismatch/missing answers the typed
403 origin_required, counted (ws_origin_refused_total), pinned by
ci/ws_origin_lint.py.
The trusted-Origin anchor (sol_http_infra:ws_origin_allowed/1) mirrors the
CORS posture:
the configured limon_origin (exact match; * = operator wildcard);
Same-host — the Origin authority equals the request Host authority
(a first-party page; a hostile page’s Origin names its own host and never
matches);
the loopback dev posture — both Origin host and request Host host
classify loopback (localhost:5173 → 127.0.0.1:8080 dev consoles);
auth_enabled=false loopback dev never reaches the gate (the dev
identity branch precedes the credential arms).
Exempt classes: ticket-authenticated upgrades (the single-use 60s
zerg_ticket subprotocol — proof no third party holds) and every explicit
credential (Bearer/?token= — an attacker cannot set those cross-origin).
Non-browser clients can forge Origin, but they are not the ambient-
credential class; a cookie-carrying non-browser client should use the
ticket.
Remaining (Not Yet Implemented)
(No remaining unimplemented security features. The trust-plane posture
program’s residual legs are tracked in
docs/known-security-gaps.md + docs/production-flip-checklist.md,
not here.)
Trust-plane posture program
Erlang distribution TLS contract
Distribution TLS is a VM-flag activation, deliberately NOT an app-env
key (the lesson: comment-only keys imply wiring that does not
exist). The full contract — -proto_dist inet_tls +
-ssl_dist_optfile in the wild-rendered vm.args, per-node certs with
SAN = node FQDN, verify_peer + fail_if_no_peer_cert on both legs,
the cluster cookie STAYING the admission credential, the
cluster-probe/remsh same-window update, and the epmd-plaintext residual
lives in server/config/ssl_dist.conf.example and
docs/production-flip-checklist.md. Activation is a wild
maintenance-window drill: probe 3/3 over TLS, a plain peer refused,
rollback tested once.
Secret lifecycle decisions
Provider keys: declarative keys are never persisted; operator-added
pool keys ARE persisted encrypted. Declarative configs carry
api_key_env names and the pool holds those values in gen_server state
only. Since provider_key_store=true
(the shipped default) persists OPERATOR-added keys
(sol_provider_pool:add_key/3) AES-256-GCM at
<data_dir>/provider_keys.bin (0600, atomic) so a pool crash does not
lose them; a corrupt store fails OPEN (the pool boots) and is counted.
The real residual for declarative keys remains crash dumps
(docs/known-security-gaps.md §Secret lifecycle — the ERL_CRASH_DUMP
ask is wild-owned).
Audit-chain key rotation shipped in (key-epoch ring +
typed cross-rotation verdicts) — the “rotation = evidence loss” gap
is closed on the Mango leg.
Revocation-journal retention — Closed (,; S-13;
). RevocationRing.compact prunes a bounded prefix
(MANGO_REVOCATION_JOURNAL_KEEP, default RING_SIZE) in bounded
chunks, recording the in-tx revocation_journal_pruned_floor and
surviving-min frontier in audit_chain_meta. Boot refuses a
tail/prefix/wipe regression; legal burnt epochs stay gap-tolerant.
MAX(epoch) monotonicity is the invariant either way. The same row is
recorded in known-security-gaps.md.
Luna Policy System
Luna enforces a 3-layer security model on all command execution, including both sequential and concurrent (parallel) tool paths.
Execute-grade split
The server-grant gate distinguishes execute authority from write
authority: execute-class tools (bash, code_exec, task spawns, background/
team spawns — anything that can run shell on the worker) and the
permission-mode elevation (allow-all/auto) require tasks:execute (or
*). The coarse write⇒execute rule lives ONLY behind
legacy_write_implies_execute (default true — existing installs keep
the behavior; new installs set it false via
SOL_LEGACY_WRITE_IMPLIES_EXECUTE=false / LUNA_LEGACY_WRITE_IMPLIES_EXECUTE=false
on BOTH sides — Sol and Luna mirror the flag; the shared matrix fixture
server/test/fixtures/permission_mode_clamp_matrix.json pins the
semantics on both mirrors). With the flag off, a workspace:write-only
user cannot raise worker posture or run execute-class tools.
Layer 1: Permission System
Module: client/core/permission_checker.lua
Gates ALL tool invocations. Checks tool name against configured permission mode (6 modes: default, allow-all, deny-all, read-only, plan, auto — see permissions.md). Integrates with danger_detector (45 regex patterns: 26 dangerous + 19 caution, plus 3 AST-derived dangerous findings) to gate risky operations.
Layer 2: Command Policy
Module: client/core/command_policy.lua
Gates bash tool specifically. Three profiles with increasing permissiveness:
| Profile | Deny Prefixes | Network | ask_destructive |
|---|---|---|---|
strict | 25 patterns | blocked | yes |
standard | 25 patterns | allowed | yes |
permissive | 9 patterns | allowed | no |
Deny prefixes include: rm -rf /, mkfs, dd if=/dev/zero, curl | bash, shutdown, reboot, iptables -F, /etc/passwd, /etc/shadow, etc.
Ask_destructive — when enabled, commands flagged as dangerous or caution by danger_detector return {ask=true} for user confirmation via TUI modal.
User Rules (Lua Policy Files)
Users can define custom rules in ~/.luna/policies/*.lua. These provide programmable policy equivalent to Starlark:
~/.luna/policies/no-docker.lua
return {
name = "no-docker",
rules = {
{ pattern = "docker ", action = "deny", reason = "docker not allowed" },
{ pattern = "kubectl ", action = "deny", reason = "kubectl not allowed" },
{ pattern = "helm ", action = "allow", reason = "helm is ok" },
}
}
Rules are evaluated after built-in deny prefixes. First match wins. Actions: deny (block) or allow (bypass further checks).
Audit Logging
Enable with command_policy.enable_audit(path). All policy decisions are logged as JSONL:
{"ts":1748300000,"command":"rm -rf /tmp/test","allowed":false,"reason":"denied prefix: rm -rf /","source":"command_policy:strict"}
Layer 3: OS-Level Sandbox
Module: client/core/sandbox.lua
When enabled via config.execution.sandbox.enabled, commands execute inside a bwrap sandbox:
Read-only bind of / (system files immutable)
Read-write bind of workspace directory only
/tmp tmpfs mount (TMPDIR is rewritten to /tmp inside the namespace — the host TMPDIR, e.g. /run/user/1000, does not exist there)
Namespace isolation: --unshare-pid (same-uid host processes are unkillable — pid namespaces are kernel-enforced on signal delivery — and invisible in the fresh /proc), --unshare-ipc, --unshare-uts
Env allowlist: --clearenv + --setenv for PATH HOME LANG LC_ALL TMPDIR USER LOGNAME SHELL + per-tool env_passthrough extras — SOL_API_KEY/provider keys/*KEY*/*TOKEN*/*SECRET* never cross the boundary; the scrub set now also covers the anchored PASSWORD/PASSPHRASE/_PASS/PWD/*_PWD/*_AUTH/*CREDENTIAL*/*PRIVATE* families and value-shaped URL userinfo (DATABASE_URL=postgres://user:pass@…), while XAUTHORITY and SSH_AUTH_SOCK survive; the _spawn_popen fallback, configure-wizard io.popen, and the macOS seatbelt leg splice the same set via env -u; MCP/LSP stdio servers get a Landlock-only config + allowlist-rebuilt child env
Sensitive-path read-deny (tmpfs//dev/null shadows) from ONE single-source list shared by the bwrap and seatbelt builders: ~/.ssh, ~/.gnupg, ~/.aws, ~/.netrc, ~/.git-credentials, ~/.docker/config.json, ~/.config/gcloud, ~/.kube, ~/.npmrc, ~/.config/gh/hosts.yml, ~/.azure, ~/.pgpass, and the ~/.luna credential surface — keys, approvals, oauth_tokens.json, settings.json, mcp.json, sessions, sessions.db, memory.json, MEMORY.md, memory.db, profiles, logs, analytics.db (the ~/.luna/bin toolchain is the acknowledged, census-pinned exception); adds the podman/buildah/skopeo store ~/.config/containers/auth.json plus the XDG runtime copy $XDG_RUNTIME_DIR/containers/auth.json (canonically /run/user/<euid>/containers/auth.json)
Socket deny shadows: container-daemon sockets (docker.sock/podman.sock/containerd.sock, system + per-user) plus the agent/keyring roots /run/user/<uid>/keyring, /run/user/<uid>/gnupg, /run/gnupg, and $SSH_AUTH_SOCK when set — resolved at build time, shadowed with /dev/null (files) or --tmpfs (directory roots). /tmp/ssh-*/agent is an accepted residual (not statically resolvable). deny_sockets={} disables the defaults only with deny_sockets_ack=true; otherwise the defaults apply
Network isolation (--unshare-net) by default
--die-with-parent ensures cleanup on crash
Backend selection: execution.sandbox.bwrap = off | auto (default) | required — semantics verified real: off runs the bare shell argv with the Landlock fork layer still applied (write-deny; documented residual: no read-deny, no network isolation); required refuses to run when bwrap is missing. On macOS the seatbelt profile applies. The macOS seatbelt posture is argv-verified only: the emitted SBPL profile is covered by render/parity tests, but the ZERG token has no macOS kernel-truth runner, so no kernel-enforcement claim is made until a real sandbox-exec drill is recorded. The drill is implemented and self-registers on a real Darwin host (client/tests/test_seatbelt_env_scrub.lua: outside-workspace write must be denied, workspace write must succeed); on Linux it does not register, so release claims about seatbelt enforcement stay gated on that macOS leg. allowed_write_paths is additive on BOTH backends: the workspace write allow is always emitted first, then each grant.
Default: ON. DEFAULT_CONFIG carries
execution.sandbox.enabled = true — a prompt-injected agent must NOT get
arbitrary unsandboxed shell by default. Consequences:
If the sandbox is enabled but unavailable (no bwrap / no sandbox-exec),
FFI.spawn and FFI.spawn_async error with sandbox_unavailable
instead of degrading to a bare shell.
code_exec runs inside the sandbox like bash (it passes the agent’s
real config through).
The workspace is enforced by the file tools: reads/writes outside the
configured workspace are denied, and denied entirely when no workspace
is configured (fail-closed; the interactive TUI binds reads to the
session cwd, or an operator may set workspace = "." explicitly).
allow-all permission mode requires execution.sandbox.enabled = true.
Process timeouts kill the process group (children setsid), so
backgrounded grandchildren (sleep 9999 &) do not survive.
Operators who explicitly want the legacy insecure behavior set
execution.sandbox.enabled = false (documented as the insecure option).
Configuration:
execution = {
policy = "standard",
sandbox = {
enabled = true,
network = false,
allowed_paths = { "/data" },
}
}
Managed Policy (Enterprise)
Server-side policy overrides via GET/PUT /api/v1/managed-settings (admin only, fleet-wide — the fleet push is the ZMQ managed_settings_update PUB). The schema is CLOSED:
{
"execution.policy": "strict",
"execution.max_iterations": 100,
"execution.session_budget_usd": 5.0
}
Applied by Luna via managed_config.apply_managed with highest priority — overrides both user config and mode defaults.
Mango Identity Service Hardening
Mango (the identity/auth microservice) ships its own hardening surface; this section documents the contract.
Rate limiting: reserve/release/spend
RateLimiter.check is an atomic reserve — it decrements immediately
when a token is available (no peek window). spend consumes the
reservation on credential failure; release refunds it on success (capped
at the rate). Burst admission is exactly the configured budget on both the
memory and SQLite backends — N concurrent attempts can never multiply into
N× the budget. Every auth limiter (login per-IP, per-account, validate,
service-token, password-change) follows: check(reserve) → success: release;
failure: spend. A DB-outage login (503) releases — infrastructure failures
never burn the brute-force budget.
LDAP federation seam
MANGO_LDAP_TLS is a closed set {starttls, ldaps, none} validated at
boot — an unknown value refuses boot (a typo previously fell through
to plaintext binds with zero signal). Runtime path refuses plaintext too.
A federated mail that collides with a local account refuses the LDAP
login (uniform “invalid credentials”) unless
MANGO_LDAP_ALLOW_ACCOUNT_OVERRIDE=true (documented dangerous). This
closes the account-takeover seam where a crafted LDAP entry could mint
the local user’s session token. Concurrent first-login races retry as
update — never a raw UNIQUE 500.
LDAP runs on a dedicated bounded executor (MANGO_LDAP_EXECUTOR_MAX,
default 4); an LDAP outage cannot saturate the shared pool and starve
local bcrypt logins (the break-glass path).
Group → role mapping:
MANGO_LDAP_GROUP_ROLE_MAP is a JSON object {group: role} mapping
the entry’s memberOf claims to Mango roles (matched
case-insensitively by full DN or CN); MANGO_LDAP_DEFAULT_ROLE
(none default, or viewer) covers unmapped users. A malformed
mapping refuses boot. Grants flow through the same
user_teams → team_roles → roles machinery as every other grant —
each mapped role owns a deterministic ldap-role-<role> team — and
memberships are SYNCED on every login (a group removed in LDAP demotes
on the next login). The users.role column is never written by
federation; every mapping
decision leaves an audit row (ldap.role_mapped) with the claim and
role provenance.
LDAP TLS posture decision
Decision: glauth LDAPS with a provisioned cert is the target posture;
plaintext-on-the-bridge is explicitly NOT adopted. The verified state
(2026-09-19 audit + wild pin): the fleet’s glauth ships
[ldap] enabled=true:3893 with [ldaps] enabled=false and no
STARTTLS evidence, while Mango defaults MANGO_LDAP_TLS=starttls +
verify — i.e. the live Mango→glauth leg either hard-fails or silently
falls back to local accounts; “fixing” it with MANGO_LDAP_TLS=none
would carry the service-bind password AND user passwords in cleartext
across the shared podman bridge, and glauth currently publishes 3893 on
the LAN IP (an A1 surface). Execution (wild, with the prod-flip drill):
enable [ldaps] with a provisioned cert, set
MANGO_LDAP_TLS=ldaps + MANGO_LDAP_CA_FILE, remove the LAN publish of
the plaintext port, and verify one live LDAP login as the acceptance
test. Until that lands, LDAP federation on the fleet stays
de-facto-disabled rather than plaintext — that is the compensating
control.
RBAC permission cache
A generation counter stamps cache entries at fetch start; any
invalidation (invalidate_permission_cache / invalidate_all_caches)
bumps the epoch, and a stale in-flight fill (started pre-revocation,
finished post-) is rejected as a miss — the caller refetches. Revoke-then-
read never serves pre-revocation permissions; the fast path is preserved
when nothing changed.
Audit ordering
Privileged state-changing endpoints audit before responding and fail
closed: the strict audit path re-raises on a write failure and the
endpoint returns 503 “audit unavailable — retry operation” with
Retry-After: 30 instead of a 2xx with no audit record (:
finish_audit_unavailable honors AuditUnavailableError.status_code = 503;
the legacy 500 path remains for other exception classes only). The success
body is never flushed, so the failure status can never be mistaken for a
confirmed state change. Informational events (failed-login, logout,
locked-account attempts) deliberately stay fail-open (strict=False) — they
must never break auth responses. In short: privileged state changes are
audit-fail-closed; reads and login attempts are audit-best-effort.
Operators should treat a 503 on a non-idempotent create as “not
confirmed — retry” guidance.
Audit call-site classification
Every handler audit site in mango/handlers/, strict or not. (
19,: the rows below were re-verified against the
handlers; the login-success row, the 503 prose above, and the two added
strict families were the drift.)
| Site | Action(s) | Mode | Why |
|---|---|---|---|
users.py UsersHandler create/update/delete + org endpoints | create_user, update_user, delete_user, org equivalents | strict | privileged state change |
teams.py TeamsHandler create/update/delete + memberships | create_team, update_team, delete_team, membership changes | strict | privileged state change |
rbac.py RolesHandler create/update/delete + grants | create_role, update_role, delete_role, permission grants | strict | privilege escalation surface |
tasks.py TasksHandler create/update/delete + assignments | create_task, update_task, delete_task, assignment changes | strict | privileged state change |
auth.py change-password | change_password | strict | credential change; the split’s template |
auth.py service-token issuance | service_token.created | strict | “the most sensitive privileged action” — a minted token without a record is a worse failure than a 500 |
auth.py mass token revocation | tokens.revoked_all | strict | privileged state change — a 200 “all revoked” without a record breaks the revocation trail |
auth.py admin account unlock | account.unlocked | strict | privileged state change — clearing a lockout is security-relevant |
auth.py login success | login | strict | the strict arm with finish_strict_or_revoke: an audit outage revokes the just-minted token and refuses the login (a login that never returns is the misread this closes) |
auth.py single-token revocation | tokens.revoked | strict | privileged state change — a 200 “revoked” without a record breaks the revocation trail |
orchestrator_lease.py lease transitions | orchestrator_lease_{acquired,stolen,taken_over} | strict | privileged state change — takeover attribution rides the audit row |
auth.py login failure (credential + locked-account) | login_failed | non-strict | informational; fail-open so auth never 500s under audit-store hiccups |
auth.py logout | logout | non-strict | informational; the token is already revoked by AuthSystem.logout |
Strict sites audit BEFORE finish via audit_then_finish or
the revoke-in-arm finish_strict_or_revoke; non-strict
sites use self.audit and degrade to a CRITICAL log + alert counter on
failure. The service-token READ path
is unaudited by design
(read-only, derivable from the issuance rows).
Mango audit chain
Mango revocation journal signing
The revocation ring’s served epoch is now published only AFTER the
journal row and ring entry are appended, under one lock (the pre-fix
epoch bump before the awaited insert let a snapshot answer (N, []), so
Sol adopted N and never replayed the revocation). PostgreSQL also takes
a transaction-scoped advisory lock so revocations commit in epoch order.
Journal rows are HMAC-signed and chained (signature /
prev_signature, migration v0015); the high-water/floor/frontier
markers are signed and monotonic in SQL, and boot verifies the signed
chain (a deleted MIDDLE row is a chain break; a deleted tail is the
high-water check; a modified row fails its HMAC). Pre-v0015 rows are
TOFU-exempt via revocation_journal_signed_from.
Mango service-token mint, lease and secrets
POST /auth/service-token answers ONE uniform 403 {"error": "forbidden"} for every non-success credential/shape failure (wrong
secret, missing/unknown user, allowlist denial, malformed fields);
body-parse/rate-limit errors are identical regardless of the secret.
This closes the secret-validity oracle.
Service/bridge/audit/archive shared secrets must be >= 16 bytes or
boot refuses (validate_boot_secrets).
The orchestrator lease row is bound to the acquiring token’s
user_uuid; a stale steal by a DIFFERENT principal requires takeover
authority (admin binding or the RBAC-off allowlist), the optional
request epoch is CAS-checked (lease_epoch_stale), and every
transition is strictly audited.
Mango readiness and event-transport posture
/ready caches its DB/migration/instance verdict for ~1s for
non-loopback callers (loopback stays live), so a health-check fan-out
cannot amplify DB load. The ZMQ PUB bind must be loopback or
ipc:///inproc:// unless MANGO_ZMQ_ALLOW_NONLOOPBACK=1 acknowledges
a broader bind; the dead inbound PULL leg (no Sol sender — Decision
#433) is retired and never bound, and the multipart discard path is
bounded (an endless part stream tears the socket down instead of
pinning the listener).
Mango’s audit_logs now carries the same tamper-evidence premise as
Sol’s sol_audit_log (HMAC prev_signature chain + monotonic seq),
implemented in mango/systems/audit.py with migrations
v0003_audit_chain (columns) and v0007_audit_chain_checkpoint (the
anchor table):
Fields: seq (monotonic, head+1 per write; the head is only
advanced after COMMIT, so a failed write’s seq is never consumed),
prev_signature (the previous sealed row’s signature, "" for the
first), signature (hex HMAC-SHA256). Pre-v0003 rows keep seq=NULL
and are outside the chain by construction. seq GAPS are seq_gap
violations — there is no “gaps legal”
posture.
Material: canonical JSON (sort_keys, compact separators — the
audit-archive canonicalization precedent) of the entry-minus-signature
INCLUDING seq, prev_signature and (post-v0005) created_at. Both
backends store created_at as DOUBLE PRECISION so the timestamp
round-trips exactly (pre-v0005 rows verify under the legacy
created_at-free material via the audit_chain_meta boundary).
Head: in-memory (seq, signature), sound because of the
single-process invariant (above); writes serialize on a module lock
and, on PostgreSQL, on a pg_advisory_xact_lock held to COMMIT (so a
concurrent transaction cannot derive a stale head — ).
Boot head = SELECT seq, signature ORDER BY seq DESC LIMIT 1,
derived lazily on the first write (including in-transaction writes in
a fresh request context — ); a REAL head-read failure
fails the write (never a silent fork at seq 0). Torn tails are free
via single-statement INSERT atomicity.
Anchor: audit_chain_checkpoint holds ONE
signed row — (seq, signature) plus
checkpoint_sig = HMAC(chain key, "mango-audit-checkpoint-v1|" + canonical JSON of {seq, signature}) — refreshed on EVERY chained write (the
write-time anchor closes the verify-then-delete window). Verify
compares the observed tail against it: a shorter tail (or a full wipe)
is truncated_tail, a missing head is truncated_head, a swapped
tail is sequence_rewind, a corrupted anchor is checkpoint_invalid
(all typed, ok=false); a missing anchor is reported as unanchored
(the chain may still verify — but never silently green).
Secret: MANGO_AUDIT_CHAIN_SECRET (>=16 bytes as-is; shorter is
SHA-256-derived with a warning). Unset with token auth on → CRITICAL +
a RANDOM per-process key (fail-loud, not boot-blocking — mirroring
sol_audit_log; cross-restart verification then honestly fails at the
boundary until the operator sets the secret, and the verdict’s
key_source says ephemeral).
Strict split: the seal rides the SAME strict/unstrict discipline
as the write — strict callers get AuditUnavailableError (503,
fail-closed) on store OR chain failure; informational events fail
loud-but-open.
Verify is an OPERATOR surface, never per-write:
Audit.verify_integrity(db, max_rows=, checkpoint=) recomputes the
full ordered chain with hmac.compare_digest, checks adjacency
(prev == previous row's signature when seqs are adjacent), reports
seq gaps, is size-guarded (MANGO_AUDIT_VERIFY_MAX_ROWS, default
200000) and returns the verdict key set
(ok / rows_checked / truncated / violations / reasons / anchored_to_seq / key_source). scripts/verify_audit_chain.py
(--checkpoint <store|path>) exits non-zero on any reason, including
a clean-but-unanchored chain.
Log hygiene: the audit log lines are repr-capped
(_logsafe, 128 chars) for action/resource_type/resource_uuid —
raw %s of attacker-controlled URL segments was a log-injection
vector. What is PERSISTED stays raw so the chain material is stable.
The same-class LDAP-email log sites also route through _logsafe now
the former residual is closed.
Anchor hardening
Every checkpoint MAC is mandatory. read_checkpoint treats an
empty/missing checkpoint_sig as checkpoint_invalid (the pre-fix
if mac skipped verification, so checkpoint_sig='' pointed the
anchor at a surviving tail and verified green).
Append-only checkpoint history (audit_chain_checkpoint_history,
migration v0015): every write appends its signed (seq, signature,
checkpoint_sig) pair. A singleton anchor that sits BEHIND the
historical maximum is a truncated_tail (detail=checkpoint_rollback)
verdict — restoring an older valid anchor after deleting the tail is
refused. A stale anchor behind the observed tail is likewise
truncated_tail (detail=checkpoint_behind_tail), with one re-read
for a concurrent writer.
ok means anchored: an unanchored chain or a row-bound-truncated
scan now returns ok=false (pre-fix ok=true with
reasons=["unanchored"]). The operator CLI keeps its explicit
UNANCHORED/partial-scan messages and exits non-zero.
Log/ingestion hygiene: _logsafe(actor) at both audit sinks, and
_logsafe on LDAP exception text; the audit-archive POST validates
timestamp/source/aggregate_id/event_type types and lengths
(non-string timestamp → 400, never 500) and maps DB failures to a
typed 503.
Audit log retention
Decision: RETAIN FOREVER for this cycle; the prune-floor design is
recorded, owned, and not yet implemented. audit_logs has no retention
path today. A naive DELETE is NOT an acceptable remedy: verify_integrity
requires the first observed row to be seq 1 (truncated_head) and a bare
prune also trips the adjacency seq_gap check — the integrity tool would
flag the operator’s own hygiene as tampering. Growth is real (every login
- privileged mutation writes 1–3 rows at ~0.5–1 KiB; a 1000-user fleet at 100 logins/user/day ≈ 10⁵ rows/day), so retention is a design decision, not a missing trim.
The designed successor reuses the revocation journal’s prune-floor
machinery (revocation_journal_pruned_floor / surviving_min /
high_water): a signed retained_from_seq marker advanced atomically
with each bounded prune chunk, plus a verify mode that anchors the head
to that floor (rows below it are legally pruned; a missing row above it
stays seq_gap). Compaction must be operator-invoked with a keep bound,
chunked like RevocationRing.compact — never date-bound auto-delete.
Until that lands: back up the audit store with its chain key (a
restore is unverifiable without MANGO_AUDIT_CHAIN_SECRET/the prior
ring), size the volume for unbounded growth, and do not manually delete
rows. Owner/check-date: `` in
plan/residual-register-v0765.md (next Mango storage window, 2026-12-31).
Update: the prune-floor design above IS implemented
Audit.prune(keep=, chunk_rows=) deletes a
bounded prefix atomically with the signed retained_from_seq marker and
now also writes its own chained audit_retention_prune audit row.
Dummy-verify cost parity
The unknown-account login dummy and the handler-side locked-account /
budget-exhausted burns previously hashed at the import-time DEFAULT
bcrypt cost while the real verify path derived its cost from
MANGO_BCRYPT_COST — a cost-mismatch timing oracle for account
enumeration. All four consumers now share dummy_bcrypt_verify, whose
hash cache is keyed by the LIVE configured cost (computed inside the
executor — ’s no-IOLoop-block is preserved).
Client IP resolution
Behind a trusted proxy, the client is the rightmost-untrusted XFF hop
(skipping trusted proxies), validated with ipaddress (invalid values fall
back to the TCP peer). trusted_proxies is live app config (list or
comma-string, stripped entries) with MANGO_TRUSTED_PROXIES as fallback —
client-chosen leftmost values can no longer forge limiter keys or audit
ip_address fields.
Global-trust guard — a /0 CIDR entry
(0.0.0.0/0, ::/0) trusts every peer and makes X-Forwarded-For/
X-Real-IP fully attacker-controlled, so it is DROPPED at parse with a
once-per-process CRITICAL unless MANGO_ALLOW_GLOBAL_TRUST=true is set
. Legit CIDR entries are
unaffected; the guard also applies to direct ip_is_trusted callers
(defense in depth).
(AUTH-20): trusted_proxies is now a real config-file option
(trusted_proxies =... in mango.conf) threaded through init_app,
not only the MANGO_TRUSTED_PROXIES env fallback. Direct loopback is no
longer exempt from rate limiting by address alone: it gets its own
bounded bucket (MANGO_LOOPBACK_RATE_LIMIT, default 3000/60s), and a
configured MANGO_CONTROL_PLANE_TOKEN requires the matching
X-Control-Plane-Token header before the unlimited exemption applies.
Every security boolean (MANGO_ENABLE_TOKEN_AUTH, MANGO_REQUIRE_AUTH,
MANGO_COOKIE_SECURE, MANGO_ALLOW_GLOBAL_TRUST, …) is parsed by one
strict parser accepting on/off, true/false, 1/0, yes/no; any
other value refuses boot (the pre-fix parser silently read on as
false). MANGO_REQUIRE_AUTH is enforced centrally in prepare, so
anonymous requests are refused before any handler (including the task
list) runs.
Forwarded client IP — Sol vs Mango
Proxy contract (both services): a reverse proxy MUST emit and
normalize X-Forwarded-For (append the peer it accepted the connection
from; never pass a client-supplied chain through unchanged). Forwarding
headers are hops, never an authority: a value the client invented before
the proxy is not a client identity.
Sol treats X-Real-IP
as one more unvalidated hop and only reads it when an XFF chain is
present; a lone client-supplied X-Real-IP from a trusted proxy is
Ignored (the TCP peer is used). The rightmost-untrusted walk and the
anti-mint-loopback rule are unchanged, so a forwarded value can
never mint a loopback bucket or bypass the loopback/admin gates.
Mango divergence (recorded, not yet migrated): Mango’s
BaseHandler.resolve_client_ip still honours a trusted peer’s
X-Real-IP (with the same anti-mint rule) when XFF is absent. Deployments
that put a trusted proxy in front of BOTH services must therefore emit
XFF; an X-Real-IP-only proxy gives Mango a client identity that Sol
ignores, and the two limiter/audit keys can disagree. The parity fixture
(server/test/fixtures/client_ip_resolution.json) pins ONLY the Sol
resolver; it is not a cross-service mirror. Owner/check-date: the next
Mango identity window (align Mango to the Sol rule or document the
operator-level XFF requirement in the wild blueprint).
Public-read exposure gate: /metrics + /openapi
/metrics and /openapi extend the auth-skipping PublicBaseHandler —
they are unauthenticated even when token auth is on. The shared
PublicReadGateMixin now gates both:
Loopback clients: allowed (the historical, ops-compatible default);
Non-loopback + bearer token: allowed when the request carries
Authorization: Bearer <MANGO_METRICS_READ_TOKEN> (constant-time
compare; empty token = no token path);
Non-loopback, metrics_expose="any": allowed — the explicit
broader-exposure lever (MANGO_METRICS_EXPOSE env);
Otherwise: 403.
Defaults keep today’s behavior (metrics_expose="loopback",
metrics_read_token="" → loopback-only). OPTIONS preflights are exempt.
Sol /metrics exposure posture
Sol’s /metrics (Prometheus exposition, sol_http:dispatch(prometheus_metrics, _)) is peer-gated, not anonymously exempt. The -era text below
this section described a “hardening path … not yet a
hard gate”; the gate landed in and the topology honesty followed in
. The implemented posture:
/metrics is OFF the auth-exempt list. It sits beside its
RBAC-documented sibling /api/v1/metrics; a bearer request needs the
metrics:read permission ({GET, /metrics} => metrics:read in the route
permission map).
Tokenless scrapes are refused with 403 unless the loopback TOPOLOGY
holds. metrics_gate_peer/1 requires BOTH legs of
is_loopback_topology/2: the TCP peer is loopback and every
X-Forwarded-For hop the request carries is itself loopback. A reverse
proxy bound on loopback that forwards external traffic fails leg 2 and is
refused — the previous peer-only check served the fleet exposition to
the world through any on-host proxy.
The refusal happens before sol_prometheus:format_metrics/0
(fail-closed; the response is a typed 403, never a 401 challenge).
There is no metrics_expose lever on the Sol side — the
loopback | any lever and metrics_read_token bearer leg documented in
an earlier draft belong to Mango’s /metrics (see the Mango
public-read gate above). Sol’s lever equivalents were never implemented
and are not promised here.
For an off-loopback Prometheus agent, scrape through an authenticated
bearer with metrics:read (or terminate at a proxy that presents it).
The absent(sol_up) dead-man switch still works: the loopback leg keeps
on-host scrapes anonymous, so a scrape failure is still visible as a gap.
Single-process invariant
Mango MUST run as exactly one process. The revocation ring + epoch,
the RBAC permission cache, the rate limiters, the audit HMAC chain head,
and the ZMQ PUB socket are single-process state — a second process would
serve stale permissions, multiply brute-force budgets, fork the audit
chain, and split the event bridge. tornado 6.5 removed --procs entirely
(the option is rejected as unrecognized) and app.listen never forks,
so the stock entrypoint starts one process. Mango HA L0 adds the missing
Runtime config gate: MANGO_WORKERS>1 refuses boot unless it is
explicitly opted into with MANGO_MULTI_PROCESS=1 AND backed by
PostgreSQL; MANGO_MULTI_PROCESS=1 on SQLite also refuses boot (the L1
coherence work does not exist, so a partial-L1 boot is a config error, not
a degraded mode). Production posture: one podman container under
wild/runit; concurrency = the event loop + nginx. See
docs/production-runbook.md “Mango identity-service L0”.
Revocation-bridge health surface
A bridge that boots but cannot bind used to look healthy while silently never delivering a revocation frame. Now:
ZMQTransport.pub_connected — live bound-state of the PUB leg;
/health body carries "revocation_bridge": "up" | "degraded" | "disabled" (disabled = no zmq_pub_url; degraded = configured
but not bound right now — bind failure, start crash, mid-reconnect);
gauge mango_revocation_bridge_up (0/1), refreshed on every /metrics
and /health scrape — a Mango-side family. (The previous text claimed
it “feeds the Sol consumer” — no such consumer existed, BD-1106.
Truth since then: Sol exports its OWN bridge transport gauge
sol_mango_bridge_bind_up (1 = connected, 0 = failed/degraded, series
absent when the bridge is disabled) from
sol_mango_zmq_bridge state, consumed by the SolMangoBridgeDown
alert; mango_revocation_bridge_up remains observable on the same
scrape for the Mango half of the story.)
a configured-but-failed bridge is CRITICAL-logged degraded, boot
continues (an optional transport must not kill the identity service).
Password policy
The common-password list (mango/data/common_passwords.txt) is enforced —
a missing list refuses boot in token-auth mode unless explicitly waived
(MANGO_ALLOW_MISSING_COMMON_PASSWORDS=true).: the list is
the pinned SecLists 10k-most-common (MIT, commit
3ccb6c3257ccabac92a639d435435cf09873b28e), sha256-indexed to keep the
repo small (sha256: exact digests for the top 100, p: 4-byte prefixes
for the rest — regenerate via mango/scripts/gen_common_passwords.py;
see the file header for the pin and the documented supplement). Entries
match case-insensitively, so Password123 and leet variants are rejected.
Passwords are capped at 72
Bytes (bcrypt’s key length); existing longer accounts are unaffected
(bcrypt truncates consistently on hash and check) but cannot choose new
over-long passwords. Token entropy is 256-bit (secrets.token_urlsafe(32)).
Token storage decision: SHA-256, not bcrypt
Decision: DECLINE the deferred bcrypt token-hash migration; keep
SHA-256 over uniformly random 256-bit tokens. This closes the -F1
“adopt or decline with evidence” item that had remained prose-only
(plan/archive/phase--architecture-duplication-reduction.md M-G3
“DEFERRED”). Verified current posture:
generation is secrets.token_urlsafe(32) = 32 bytes (256 bits) of
CSPRNG entropy at both mint funnels (session + service; the service
token adds a fixed mango_srv_ prefix);
storage is sha256(token).hexdigest (AuthSystem._hash_token); the
raw credential is returned once and never persisted; lookups hash the
presented value and compare the stored digest;
every TTL is clamped (session 300 s..72 h, service 1 h..90 d), so the
entropy floor — not the KDF — is the binding constraint.
Brute force against a dumped store therefore needs ~2²⁵⁶ preimages
regardless of hash speed. Bcrypt would add ~100 ms per validate (the
hot path for every request), require a dual-read migration and a second
stored format, and buy nothing for a uniformly random secret. The risk
that WOULD justify a slow KDF — a low-entropy, human-chosen token — is
excluded by the single generation funnel; mango/test/test_token_hash_posture.py
pins it (raw never stored, 32 decoded bytes, SHA-256 digest). Reopen only
if a future token format becomes user-supplied or shorter.
ZMQ Trust Plane & Identity Propagation
Decisions – document the closure of the ownership matrix’s comment-vs-implementation seams.
batch: transport trust
CURVE transport: non-loopback ZMQ binds are CURVE-encrypted
by default; plaintext requires an explicit ack or declared tunnel; the
crypto backend is nacerl/tweetnacl (chumak’s own default, vendored +
fixed for OTP 27+ — see the spacebeam/nacerl fork README, pinned in
server/rebar.lock). The
server keypair auto-generates to <data_dir>/curve_server.cert; workers
provision LUNA_ZMQ_CURVE_SERVERKEY.
Per-worker enrollment keys: key_id on ready selects the
verification key from zmq_enrollment_keys; revoked/unknown/mismatched
keys refused; fleet-secret compat window until 2026-11-01;
registration-rate anomaly alarm.
Sol→Mango TLS: mango_tls=true (verify_peer + system CAs,
mango_ca_file to pin a custom CA); a non-loopback plaintext Mango hop
refuses boot in prod.
Mango inbound fail-closed: the ZMQ bridge refuses to bind
PULL/PUB without MANGO_BRIDGE_HMAC_SECRET; _verify_inbound rejects
unsigned frames.
Luna wire trust: Luna refuses to register with a
non-loopback server without a secret/CURVE key (LUNA_ZMQ_ALLOW_PLAINTEXT=1
escape hatch); wire workspace_root must match
zmq.allowed_workspace_roots; a missing permissions field is
deny-default ({}).
Static Luna build precondition: the
musl static Luna binary can only speak Curve when libzmq is built with
libsodium. build/setup-musl.sh builds a hash-pinned libsodium 1.0.20
and configures libzmq WITH_LIBSODIUM=ON, then runs a fail-closed
build-time Curve probe (a zmq_has("curve") + real loopback Curve
round-trip) and writes the libzmq-curve-ok cache marker only on
success; a deps cache from the pre-fix WITH_LIBSODIUM=OFF recipe is
rebuilt automatically. ci/verify-static.sh <binary> --require-curve
(wired into build/build-musl.sh for the luna artifact) re-proves the
capability against the same deps tree and fails the build otherwise.
On the Luna side the registration posture is applied-options truth:
a configured LUNA_ZMQ_CURVE_SERVERKEY counts only when every
setsockopt returned 0 (wire_trust.registration_posture/5); a valid
key against a Curve-less libzmq refuses (or degrades loudly under the
explicit plaintext ack) with a CRITICAL boot datum — it can no longer
silently connect plaintext while the operator believes Curve is on.
Shares hardening: /api/v1/shares/:id is per-IP rate-limited
(default 30/min, share_rate_limit_per_min) and read-logged (id + ip,
notice); expiry was already enforced at read.
Revocation replay closure: Mango keeps a 1024-entry
revocation ring + epoch; Sol pulls /auth/revocations?since_epoch=N on
bridge (re)connect + every zmq_mango_resync_ms (60s) and applies entries
idempotently. The pull is not authorized by service-token class alone
Mango
requires the revocations:read permission, an admin binding
or a uuid
on the MANGO_REVOCATIONS_READ_USERS allowlist
(mango/mango/handlers/auth.py:1574-1583). A zero-permission service token
gets 403; the permission is declared in the Mango classification fixture
and is not seeded to any default role.
Logout CSRF: cookie-authenticated logout requires the
X-CSRF-Token header matching the zerg_csrf cookie (Bearer logout
unchanged).
Air-gap egress gates: LUNA_ALLOW_OSV_CHECK /
LUNA_ALLOW_TOOL_INSTALL / ZERG_ALLOW_EGRESS_UPDATE (see the egress
inventory above);
ci/egress_assert_lint.py asserts the frontend/Luna trees stay free of
third-party CDN/analytics references (born required).
Ownership matrix: queued seats & liveness
Queued tasks enter the ownership index at enqueue with a reserved
<<"queued">> sentinel identity — a KNOWN task with NO eligible sender
(result/token/error always fail for any sender identity). On an index miss,
the sender must equal the recorded executor stamped at dispatch; a
frame with no recorded executor, or a foreign one, is refused and counted
in sol_zmq_ownership_refused_total. The recorded-executor match grace is
thereby restricted to the genuine post-restart window (the previous
registered-sender grace is DELETED). The index sweep is liveness-aware: the 1h TTL means
“idle 1h”, not “age 1h” — heartbeat/accepted result/token/error refresh the
row timestamp, and rows are swept only when the task is not busy, queued,
or store-pending; an unreachable gateway suspends the sweep
(retention-fail-safe).
Reserved task-id namespace
zmq-<ms>-<counter> ids are SERVER-RESERVED. Caller-supplied ids with that
prefix are rejected at the dispatch boundary ({error, reserved_task_id})
enforced structurally by ci/caller_task_id_prefix_lint.py (contract
tested). Workflow-bridge correlation ids (non-zmq prefix) are unaffected.
Identity injection
Client-supplied identity keys never survive into deferred resources:
inject_user_identity / inject_task_identity / orchestration opts STRIP
user_uuid/permissions/listener/owner first, then stamp server
identity unconditionally — including <<"system">> (an explicit stamp is
the honest marker; empty permissions are stamped too, meaningful on the
wire per.3).
Worker-registration HMAC & adoption
The registration HMAC binds the ROUTING IDENTITY (length-prefixed in the
signed material, nonce || identity || worker_id || child_depth) in addition
to nonce/worker_id/depth — a captured ready frame can no longer be replayed
under a different routing identity (the nonce LRU is per-identity, so the
fresh-victim window is closed). In-flight-task adoption additionally
requires index-worker equality. Worker registration REQUIRES a secret on
every non-loopback bind in every deployment mode except explicit dev
(runtime refusal; the prod boot gate remains).
ACP replay protection
The ACP HMAC is deterministic over the payload, so replay protection is
GLOBAL and freshness-checked: every verified frame’s digest
is checked against a MAC-keyed global cache (sol_acp_replay_global,
bounded LRU acp_replay_max = 65536, 1h expiry purge, fail-closed when the
table is unavailable) — a captured frame replayed over a FRESH connection is
refused + counted. The per-peer cache of survives only as the
one-window acp_replay_scope=peer rollback lever (CRITICAL boot banner).
Frames of type request/response/discover additionally validate the
protocol timestamp/ttl fields at ingress (refusing stale, >30s future,
zero/absurd ttl — typed, counted); capability/notify/broadcast carry
ttl=0 by contract and rely on the global digest cache. Frame caps
(acp_packet_size, clamped at 16 MiB) refuse oversized declared lengths in
the driver before allocation; HMAC failures and oversize frames are counted.
Capability registration binds to the verified key identity, not the socket
. A non-loopback ACP bind requires the explicit
acp_listener_plaintext_ack=true acknowledgement (; the plane is
HMAC-only raw TCP).
ACP registration key binding
ACP capability registrations over the TCP leg bind to the verified KEY
identity (acp_key_id, the HMAC shared-secret plane) instead of the
ephemeral {tcp, Socket} term: same key + new socket rebinds (reconnect
allowed), a different key for a taken AgentId is refused (key_mismatch,
counted), and revoke_key/1 drops every registration bound to the key.
Registration is a real call — the router returns typed verdicts
(ok | {error, already_registered | key_mismatch}) instead of the former
unconditional {ok, registered}. TCP disconnects drop the socket-owned
registrations; the ZMQ leg keeps its enrollment-verified identity-bound
semantics.
ZMQ transport posture
: CURVE is now the default posture on every
non-loopback bind (see docs/zmq-security.md). The old plaintext rule
below remains the loopback/dev posture. What the HMAC/ownership layers
protect: frame integrity + sender binding at the application plane. What
CURVE now adds: confidentiality + active-tamper resistance at the TCP
plane (the tweetnacl CURVE handshake — a wrong-key peer never completes
it). Deployment rule: every non-loopback bind boots with CURVE, a declared
tunnel, or an explicit plaintext acknowledgement (zmq_transport_plaintext_ack;
CRITICAL banner in staging/qa; boot REFUSAL in prod).
Distribution cookie entropy
The cluster cookie rotates from crypto:strong_rand_bytes(32) (hex-encoded,
256-bit class) — rand:uniform is banned from security-sensitive
generation (the old 44-char alphabet draw described ~264 bits of ENCODING,
not entropy source).
Mango validate-path limiting
Mango’s validate limiter is per-account post-validate: valid tokens bucket
per account/uuid (reserve/release — a garbage flood can never 401 a valid
user through Sol’s loopback funnel); garbage tokens bucket a separate
fail-closed (ip, invalid) limiter that throttles itself. A Sol-forwarded
x-zerg-user-uuid header is honored ONLY from trusted (loopback) peers.
Luna safety classes & denial circuit breaker
Bypass-immune safety classes
Four exact, data-driven classes sit at the top-level result of
core.permission_checker.check (client/core/safety_classes.lua). They are
evaluated after the normal mode/rules/RBAC walk: a DENY stays deny, an ask
stays ask, but an evaluator ALLOW matching a safety class is escalated to
the ask flow regardless of the permission mode — including allow-all,
auto, the built-in general/leader overrides, and a server admin ["*"]
grant. The speculative classifier is suppressed for safety-class calls, so a
classifier verdict can never collapse the ask. With no ask hook the result is
false (fail closed).
| Class | Triggers |
|---|---|
dangerous_command | DangerDetector.analyze rates the shell command dangerous (execute tools: bash, execute_command, shell; code_exec code for any language) |
secret_access | Read-tool path or shell token resolves to a credential/secret path (~/.ssh, ~/.aws, ~/.netrc, ~/.git-credentials, .env*, id_rsa/.pem/.key, ~/.luna/keys, …) |
credential_write | Write/edit/delete/redirect into a credential path, private key, env file, shell rc file (.bashrc, .zshrc, .profile, .gitconfig), or the project security-config files (.luna.json, .luna/settings.json, .luna/settings.local.json — the files carrying SECURITY_FAMILIES keys) |
destructive_delete | A recursive + force rm (-rf, -fr, --recursive --force) outside the danger detector’s root/home patterns, or delete_file targeting / or the home directory |
Sensitive path names are reused from
core.sandbox.CREDENTIAL_READ_DENY_NAMES (the single-source credential list);
project config paths correspond to
core.repo_config_security.SECURITY_FAMILIES. Path matching is normalized
(quotes/backslashes stripped, ~/$HOME expanded, duplicate slashes
collapsed) and segment-anchored, so /tmp/fake.ssh/notes.txt is not a
credential path.
Mode × class outcome (ASK means the ask hook runs; no hook ⇒ deny):
| Mode / posture | dangerous_command | secret_access | credential_write | destructive_delete |
|---|---|---|---|---|
default | ASK | ASK | ASK | ASK |
plan (read-only override) | DENY (write/execute denied by the mode) | ASK | DENY (write denied) | DENY (execute denied) |
read-only | DENY | ASK | DENY | DENY |
allow-all (sandbox boundary present) | ASK | ASK | ASK | ASK |
deny-all | DENY | DENY | DENY | DENY |
auto | DENY (danger detector denies before the ask) | ASK | ASK | ASK |
server admin ["*"] / allow-all mode override | ASK | ASK | ASK | ASK |
Safety-class decisions are never cached (permission_checker.check_cached
re-evaluates any safety-class match), so a user “Always allow” answer cannot
permanently bypass the class for the TTL window.
Permission-denial circuit breaker
tool_executor._dispatch_allowed — the one shared pre-dispatch funnel for
the sequential, concurrent, and speculative paths — counts consecutive
permission denials. A permission ALLOW resets the run. At the configured
limit (permission_denial_limit, default 3, clamped 1..20) the breaker
latches, emits an agent.diagnostic event (kind=permission_denial_limit,
with count/limit/tool), and after the current tool batch the executor yields
a typed terminal:
{ type = "turn_done", success = false, error = "permission_denial_limit",
denials = N, limit = L, tool = "<last denied tool>" }
The denied tools still render their normal tool_done events first. The
terminal rides the existing event contract (no new wire type);
agent.ended is emitted through the shared terminal funnel.
Agent:reset_permission_breaker clears the counter and latch, and every
turn start calls it automatically, so the breaker never leaks across turns.
_permission_denial_limit and _permission_breaker are per-agent fields —
no process-global breaker state is shared between concurrent agents.
Editor proposal turns
A headless editor edit turn runs with --propose-edits
(config.edit_proposals). The dispatch funnel refuses side effects before
the permission walk, so no mode, classifier verdict, mode override, or
server admin grant can widen it:
| Tool class | Proposal-turn outcome |
|---|---|
| read/none | executes normally (workspace inspection) |
| write-class | one validated tool_use proposal frame (the editor’s diff review contract); refused edit_proposal_unreviewed; no write |
execute-class (bash, code_exec, task spawns, …) | refused proposal_mode_denied; no proposal |
safety-class write/execute (credential_write, secret_access, dangerous_command, destructive_delete) | refused edit_proposal_refused; no proposal — a safety class never reaches the editor apply path |
| schema-invalid write | refused edit_proposal_invalid; no proposal |
The editor applies a proposal only after :ZergAccept (diff review), with a
stale-buffer check (changed tick + expected text + path identity) and a
pre-apply snapshot (~/.luna/editor-snapshots/, plus a git blob when inside
a worktree) that :ZergUndoEdit restores. The full contract lives in
client/docs/vim-integration.md §.
When a ask is raised during an editor turn, the permission_request
frame opens the editor confirm UI (Allow once / Always / Deny, default Deny)
and the answer rides the correlated permission_reply line.
Permission ask round-trip
A permission ask is an operator decision, never a silent default. The
worker emits a bounded ask (tool name + command/path summary + danger
level/pattern labels — the raw tool input and its secrets never ride the
wire, the registry, or the audit chain), Sol registers it in
sol_permission_registry and pushes it to the chat session’s WebSocket
(Limon PermissionPrompt). Only the ask OWNER or an admin (*) may
decide; every decision (operator, timeout, client disconnect, task
terminal) writes a STRICT audit row with a sha256 input_hash instead of
input content. A 1..300s server timeout and the worker’s own local deadline
both deny typed, and the worker’s 600s decision cache only persists an
explicit always (one-shot allow/deny never replay).
Engine reference — generated from the canonical engineering source. Do not edit this page by hand.
Known Security Gaps
This document lists known security limitations that are not yet addressed. These are tracked for future phases when triggers are met.
TLS for Inter-Service Communication
| Service | Current | Required For | Priority |
|---|---|---|---|
| Erlang distribution | TLS ACTIVATED on the live cluster by wild on 2026-09-22 (corrected single-term optfile; cluster probe 3/3 — see docs/tls-posture.md and docs/production-flip-checklist.md). Zerg-side support is complete: server/config/ssl_dist.conf.example + SOL_DIST_TLS_ENABLED (fail-closed optfile) in server/bin/entrypoint.sh; activation is -proto_dist inet_tls + -ssl_dist_optfile in the wild-rendered vm.args. Live verification/rotation remains wild-owned — the zerg tree cannot prove the current host state. epmd stays plaintext by design (it cannot speak TLS; residual = name enumeration + registration DoS on the LAN, documented) | Multi-node clustering | Medium — zerg-done + wild-activated; live verification owner = wild |
| ZMQ (worker plane) | Closed: CURVE encryption is default-on (server/src/sol_zmq_curve.erl, auto keyfile), and non-loopback plaintext refuses boot without an explicit ack or a declared tunnel (the boot posture check is zmq_transport_posture/1 in server/src/sol_app.erl). The fleet flip back to CURVE is designed; the wild host provisioning (keyfiles, env, ack removal) is the remaining leg | — | design closed; flip = wild pending |
| PostgreSQL | Sol’s PG connection sets no sslmode; the pool cannot even parse ?sslmode= query params (parse_pg_url) | Remote database | Medium — zerg half LANDED: the dedicated pool leg exists (memory_pg_ssl + memory_pg_ca_file — dedicated keys, never URL overloading; verify_peer, an ssl-without-CA connect refuses loud with {refuse_pg_connect, pg_ca_file_required}). Default false keeps today’s single-host-bridge posture; Mango’s sslmode=verify-full + sslrootcert and the server-side ssl=on with provisioned certs remain wild/Mango-window legs |
| Mango | Partial: one-way TLS via mango_tls=true + mango_ca_file with verify_peer; non-loopback plaintext refuses in production. Mango itself has NO TLS listener — the flip design terminates TLS in front of Mango (wild’s edge proxy) and points Sol’s verified client at it. Mutual TLS (client certificates) is still not implemented | Service-to-service auth | Low — partial; the terminator leg is wild-owned |
Mitigations
Erlang distribution: add -proto_dist inet_tls -ssl_dist_optfile <path> to the rendered vm.args with the shipped ssl_dist.conf.example (server + client legs verify_peer + fail_if_no_peer_cert); the cluster cookie STAYS (TLS adds confidentiality + server identity, the cookie remains the admission credential); update cluster-probe.sh/remsh/observer in the same window — a plain dist tool cannot join a TLS dist
ZMQ CURVE: shipped — chumak CURVE is vendored and default-on; the fleet flip follows the amended migration doc (Option A′). Static Luna artifact precondition: the musl binary speaks Curve only when its libzmq links libsodium — build/setup-musl.sh pins libsodium 1.0.20 + WITH_LIBSODIUM=ON with a fail-closed build probe, and ci/verify-static.sh --require-curve re-proves the shipped binary; wild’s zerg/musl-deps image must be re-derived from the fixed recipe (env-bound acceptance)
PostgreSQL: the fix is a dedicated pool config leg (code) + server-side ssl=on with provisioned certs (wild). URL-string ?sslmode= appending does NOT work today (parse_pg_url rejects query params — appending yields a corrupt database name)
Mango mTLS: one-way TLS ships (mango_tls); client-certificate validation would need terminating-proxy support (OpenResty client-verification in the wild topology)
Sandbox Network Egress
| Item | Status | Notes |
|---|---|---|
| Domain egress policy for sandboxed tool children (raw-IP bypass class) | Accepted risk | The default execution.sandbox.network=false is kernel-enforced no-egress (--unshare-net). With network=true, the hosts-file/allowlist policy is advisory only: a compromised child can reach IP literals, use its own resolver/DoH, connect over IPv6 (the hosts deny has no :: entry), or ignore the policy entirely; 0.0.0.0 deny rows can even reach loopback services on Linux. No domain-egress boundary is claimed. Full bypass class + evaluated designs + revisit triggers: docs/network-egress.md + plan/egress-control-evaluation.md |
Audit Logging
Audit logging is wired in production. sol_audit_log gen_server (child of sol_security_sup)
records tamper-evident audit entries with HMAC signing (decision archive #458, #570 — the
jsx:-undef chain break and its fix). Periodic flush
(5s), per-request identity capture. The /api/v1/audit/* read routes are RBAC-gated but answer an honest empty page (notice: audit_log_file_only) — the real trail is the JSONL log on disk; /api/v1/audit/verify is the anchored chain verdict.
| Feature | Status | Notes |
|---|---|---|
| Data access audit | Implemented | Tracks resource access with user_uuid + permissions |
| Configuration audit | Implemented | Tracks config changes via sol_managed_settings |
| Audit log integrity (Sol) | Implemented | HMAC signing via audit_hmac_secret env var |
| Audit log integrity (Mango) | Implemented | HMAC prev_signature chain + monotonic seq in audit_logs (migration v0003); MANGO_AUDIT_CHAIN_SECRET (random per-process key + CRITICAL when unset with auth on); signed checkpoint anchor (v0007) refreshed per write; signed checkpoint-history high-water anchor outside the history table (v0016) so a trimmed history tail + rolled-back singleton is detected; operator verify via Audit.verify_integrity — mutation AND truncation/wipe detection (truncated_head / truncated_tail / sequence_rewind / checkpoint_invalid / history_truncated), unanchored reported loudly when no anchor exists |
| Audit anchor full-wipe limit (Mango) | Known limitation | The head anchor lives in the same database (audit_chain_meta). An attacker with DB write who deletes the anchor, the entire history, the singleton checkpoint, and the log tail leaves the empty-store path, which is indistinguishable from a fresh install. Tail trimming and partial rollback are detected; proof against a complete wipe requires exporting the anchor/log (or the backup) off-host and comparing out of band. |
| Audit log retention (Mango) | Implemented | Operator-invoked, chunked prefix prune with a signed retained_from_seq floor advanced atomically per chunk (migration v0014); floor-aware verify (retained_from_seq + 1 is the legal root, rows above the cut keep full signature/adjacency/checkpoint checks; retention_floor_mismatch / retention_marker_invalid are typed); no automatic/date-based deletion and seq IS NULL legacy rows are never pruned. Contract: docs/audit-retention.md |
Foundation module: server/src/sol_audit_log.erl (Sol leg) and
mango/systems/audit.py (Mango leg, — chain fields/material/head
contract in docs/security.md). Mango audit archive endpoint at
POST /api/mango/audit-archive receives batched events.
** status:**
Chain-key rotation: implemented — Mango signs with the
current key while keeping prior keys for verification (keyed by
material/epoch, v0009 key_epoch); verification across a rotation
boundary returns a typed key_epoch verdict instead of a false
signature_mismatch. The old “rotation = silent evidence loss” shape is
closed.
Event-archive credential: the
audit_archive_secret leg is provisioned by wild on blue+green (2026-09-20;
Mango 200 POSTs on both nodes, cluster-probe 3/3). Zerg-side: the boot
posture line (unset-secret warning + the loopback-archive-target-vs-remote-
mango CRITICAL), the sol_event_archive:posture/0 operator probe, and the
SolEventArchiveUnconfigured alert on
increase(sol_event_archive_unconfigured_total[10m]) > 0. Red is
deliberately unprovisioned (no local Mango — only retry noise).
Secret lifecycle
| Item | Status | Notes |
|---|---|---|
| Provider keys at rest | Partially accepted | DECLARATIVE keys are never persisted — configs carry api_key_env NAMES and the pool holds plaintext in RAM only. OPERATOR-added pool keys ARE persisted since then (provider_key_store=true, shipped default): AES-256-GCM at <data_dir>/provider_keys.bin (0600, atomic write); a corrupt store logs/counts and fails OPEN. Residuals = crash dumps / swap for declarative keys (fixed by crash-dump hygiene, not a keystore) and the store’s own key → the store file is part of the data_dir backup/secret scope |
| Crash-dump exposure | Open — wild leg | ERL_CRASH_DUMP is unset fleet-wide; OS default lands erl_crash.dump in the process CWD (container /opt/sol, or red’s rootless CWD) where gen_server state (keys, tokens) is world-readable. Ask: -env ERL_CRASH_DUMP <protected path> + 0600 at boot in wild’s entrypoint |
| Provider-key rotation surface | Accepted for now (S-5) | Per-provider env vars = domain separation; pool supports 429-driven rotation/cooldown. Runtime add/rotate is a remote-shell call (sol_provider_pool:add_key/3) — no HTTP/CLI admin surface yet; document the ceremony before fleet growth |
| Revocation-journal retention | Closed | Bounded prefix-prune with an in-tx floor marker (revocation_journal_pruned_floor) + committed high-water marker; boot REFUSES tail/prefix/wipe regressions; burnt-epoch gaps are documented legal (mango/test/test_revocation_retention.py) |
| Luna msgpack recursion cap | Closed | The vendored decoder is first-party — the “needs an upstream fork” deferral was false. MessagePack.unpack/3 carries a depth cap (default 64, parameter); over-limit input fails typed (nil, "depth_exceeded"), never a stack overflow |
| Plugin memory namespace revocation | Open (S-10 row) | Memory rows plugin:<Plugin>:<UserUuid>:<Key> survive unload; a reloaded/less-trusted plugin inherits the previous generation’s memory. Fix shape: scoped prefix-delete on unload + an explicit opt-out + audit row. Registered for the next plugin-plane window |
Notes
These gaps were identified in the Tencent/GRiSP external audits and are tracked in the review archive (findings TA-1 through TA-8). They will be addressed when enterprise deployment requirements are met.
Engine reference — generated from the canonical engineering source. Do not edit this page by hand.
Authentication Flow
Overview
Limon (Vue.js) → Mango (Python/Tornado) issues tokens → Sol (Erlang/OTP) validates via Mango → user_uuid propagates through ZMQ to workers.
Endpoints
Each action is a dedicated, rate-limited handler:
| Endpoint | Handler | Purpose |
|---|---|---|
POST /auth/login | AuthLoginHandler | Username/password → token + cookies |
POST /auth/logout | AuthLogoutHandler | Revoke token, clear cookies |
GET /auth/validate | AuthValidateHandler | Token validation (Sol calls this) |
POST /auth/service-token | AuthServiceTokenHandler | Shared-secret service tokens |
POST /auth/change-password | AuthChangePasswordHandler | Password change |
The legacy multiplexed path lacked rate limiting on change_password (the
security gap the removal closes) and was non-functional for login when
enable_token_auth was True.
identity-plane notes
Service-token mint: every
non-success answer is the ONE uniform 403 {"error": "forbidden"}
(wrong secret, missing/unknown user, allowlist denial, malformed
field) — no secret-validity oracle. Body-parse and rate-limit answers
do not depend on the secret. The shared service secret must be at
least 16 bytes or Mango refuses boot (same floor for the ZMQ bridge,
audit-chain and audit-archive keys).
Strict security envs: MANGO_ENABLE_TOKEN_AUTH,
MANGO_ENABLE_RBAC, MANGO_REQUIRE_AUTH, MANGO_COOKIE_SECURE,
MANGO_ALLOW_GLOBAL_TRUST, MANGO_DISABLE_RATE_LIMIT and peers
accept on/off, true/false, 1/0, yes/no; any other value is a
boot refusal. MANGO_REQUIRE_AUTH=true is enforced centrally in
prepare, so anonymous access (including GET /tasks) answers 401.
Trusted proxies and loopback: the
trusted_proxies mango.conf option is wired through init_app (env
fallback preserved). Direct loopback has its own rate bucket; a
MANGO_CONTROL_PLANE_TOKEN can require X-Control-Plane-Token for the
unlimited exemption.
Orchestrator lease: the lease is bound to the
token’s user_uuid. A stale steal by a different principal requires
takeover authority; the optional request epoch is CAS-checked
(lease_epoch_stale); transitions are strictly audited.
Bootstrap: a wheel install ships
mango-bootstrap-admin; on a completely empty users table Mango can
also create the first admin from
MANGO_BOOTSTRAP_ADMIN_ACCOUNT/MANGO_BOOTSTRAP_ADMIN_PASSWORD.
identity/storage migration notes
Exact-match CORS. MANGO_CORS_ALLOWED_ORIGINS (comma list or config
cors_allowed_origins) lists FULL origins; matching is exact string
equality, never a suffix/subdomain wildcard (the any-subdomain
posture is retired). The allowlist is evaluated independently of domain,
so a split-host Limon deployment needs only the allowlist. Credentials are
granted only to an exact allowed origin; domain="*" echoes without
credentials. Vary: Origin is set whenever a CORS lever is configured.
Metrics default ON. enable_metrics defaults ON
(MANGO_ENABLE_METRICS); /metrics stays loopback-only unless
metrics_expose / MANGO_METRICS_EXPOSE opens it, and non-loopback
access can require MANGO_METRICS_READ_TOKEN. /health carries an
explicit metrics: enabled|disabled datum so an opt-out is visible.
Deployment mode. MANGO_DEPLOYMENT_MODE (prod/production;
dev/development/test; MANGO_ENV is an alias, the explicit lever
wins) decides the audit-key boot gate. In prod, loopback is NOT an
exemption — the documented topology is loopback behind a reverse proxy.
Orchestrator lease authority. Acquire/heartbeat/stale-reclaim require
the orchestrator:lease permission (or the bare * admin binding — the
legacy admin:* alias is INERT since then/ and migration
v0020 strips stored aliases).
A plain service token cannot squat the empty lease; a
same-node/different-user heartbeat is 403.
Audit-key posture. An unset MANGO_AUDIT_CHAIN_SECRET on a prod
deployment (including loopback) refuses boot unless the operator sets
MANGO_ALLOW_EPHEMERAL_AUDIT_SECRET=1 (CRITICAL). The verifier reports
key_source=configured|ephemeral; rows stamp key_epoch, and
MANGO_AUDIT_CHAIN_PRIOR_SECRETS keeps older generations verifiable.
LDAP mail is the identity key. The resolved directory mail must
exact-match (case-insensitive) the login identifier; a custom
MANGO_LDAP_USER_FILTER that resolves a different mail is refused. A
missing/mismatched mail never silently adopts another identity.
LDAP offboarding revalidation.
LDAP is consulted only at login bind time, so Mango runs a PERIODIC
directory revalidation (default hourly; MANGO_LDAP_REVALIDATION_SECONDS,
0 disables). A federated row is bound to its stable directory entry id
(entryUUID/objectGUID/DN): a not_found OR a present entry whose id
no longer matches is a MISS. The FIRST miss is an audited QUARANTINE
(data.ldap_quarantine; no tokens touched); a SECOND consecutive miss
revokes EVERY live token (sessions + service tokens), appends the
durable revocation-journal row, bumps the credential generation, emits
token.revoked, and tombstones the row (data.ldap_tombstone) — so a
later login cannot resurrect the identity. A disabled entry (AD
userAccountControl, nsAccountLock, GLAuth accountStatus) behaves
as gone. Group removals demote at the sync boundary via the same
group→role mapping the login path uses.
Blast-radius gate: before writing second-miss tombstones the run
refuses when the candidate set exceeds
MANGO_LDAP_REVALIDATION_MAX_REVOKES (default 10) or, for >=3
candidates, reaches MANGO_LDAP_REVALIDATION_RATIO_FLOOR (default 0.5)
of the answered probes — the typo/ACL-empty directory pages
(mango_ldap_revalidation_blast_radius_refused_total + CRITICAL audit)
and tombstone nothing. MANGO_LDAP_REVALIDATION_DRY_RUN=1 reports
would_revoke without writing. The sweep is bounded/resumable
(MANGO_LDAP_REVALIDATION_MAX_SECONDS default 30,
MANGO_LDAP_REVALIDATION_MAX_USERS_PER_RUN default 250, persisted
cursor) and probes ride a dedicated executor so login capacity is not
starved. Review/reverse with DELETE /auth/users/<uuid>/ldap-tombstone
(admin, strict-audited); tokens are never resurrected — the user
re-authenticates. The verdict instruments mango_ldap_revalidation_*;
a run that never completes clean pages via
MangoLdapRevalidationStale.
Token-type authority model
Two token types leave the auth plane, and their authority differs deliberately:
Session tokens are interactive: they resolve the owner’s FULL LIVE
RBAC set at every validate, so a demotion/revocation binds
immediately. They are never scoped.
Service tokens are machine credentials with a long TTL (7d
default, 90d max) that SURVIVE password changes. Pre- a leaked
service token resolved the owner’s full live RBAC set too — a leaked
admin CI token was full admin authority for its whole TTL. The mint
now accepts an explicit scope (a JSON array of permission verbs,
persisted to tokens.scope, migration v0017); validate returns
min(user_permissions, token_scope) — the intersection of the
owner’s live set with the grant:
a service token can NEVER gain permissions the user loses
(revocation and demotion still bind immediately);
a scoped token can NEVER reach a verb outside its grant, even while
the owner is an admin;
the mint REFUSES a scope wider than the owner’s live set (a
shared-secret mint cannot escalate; an RBAC lookup failure refuses
the mint — never a wider grant);
NEW mints default to the documented read-only inventory
(users:read, orgs:read, teams:read, tasks:read, roles:read) —
least privilege. Set a comma-separated verb list in
MANGO_SERVICE_TOKEN_DEFAULT_SCOPE for a different default. The
legacy full-RBAC mint (scope: null) requires the explicit
one-window MANGO_SERVICE_TOKEN_ALLOW_UNSCOPED=1 lever (or
MANGO_SERVICE_TOKEN_DEFAULT_SCOPE=legacy); existing legacy tokens
keep their recorded until-rotation posture. A malformed configured default REFUSES the mint (typed 503,
CRITICAL log) — it never falls back to the legacy full-RBAC posture
.
Inventory + rotation: GET /auth/service-tokens lists every live
service token WITH its scope (null = legacy full-RBAC — rotate
these). Rotation runbook: mint the replacement with the intended
scope, move the integration over, then revoke the legacy token (the
20-token cap evicts oldest-first as a backstop). Sol-side consumption
(sol_mango_client.erl stamps the returned permission set onto each
task) downscopes automatically — Sol consumes the resolved set
verbatim, so no Sol change is REQUIRED for Mango-side scoping; the
Sol-side handoff note (stamp + gate the scoped set at dispatch)
rides the dnotes.
Contract fixtures: mango/test/test_service_token_scope.py
(an admin user’s read-scoped service token cannot reach an admin-only
route; a session token is unchanged; a scope wider than the user is
refused at the mint).
Sol control-plane service tokens (, documentation
obligation). The read-only inventory default above
(users:read, orgs:read, teams:read, tasks:read, roles:read) is NOT
sufficient for the Sol appliance’s own service account. Sol’s control-plane
calls need, at minimum:
revocations:read — GET /auth/revocations (the 60 s revocation-ring
resync the Sol bridge consumes);
orchestrator:lease — POST /auth/orchestrator/lease,
/heartbeat, stale reclaim;
the admin/ops verbs for the surfaces that appliance drives (for example
infra:manage for provider reload/admin actions, metrics:read for a
tokenized scrape).
A token minted with only the read-only inventory scope authenticates but
resync/lease answer 403, which surfaces as silent degradation (a stale
revocation ring and no lease). The intended posture is an explicit
scope at mint time (revocations:read,orchestrator:lease,…), never the
inventory default. The Sol boot health check that proves both endpoints
are reachable is a server-side obligation tracked with this finding
(, carried to the Sol-owning lane; this document is the mint
contract it must check against).
Login Flow
Limon Mango Sol
│ │ │
│ POST /auth/login │ │
│ {username, password} │ │
│ ──────────────────────► │ │
│ │ AuthSystem.login() │
│ │ LDAP first (GLAuth), then │
│ │ local bcrypt │
│ │ per-IP + per-account │
│ │ limiters (spend on FAILURE │
│ │ only) + hard lockout window │
│ │ timing-constant (DUMMY_HASH)│
│ {token, user, expires_at, │ │
│ csrf_token} │ │
│ ◄────────────────────── │ │
│ Set-Cookie: zerg_session=...│ │
│ HttpOnly; Secure*; │ │
│ SameSite=Strict; Path=/ │ │
│ Set-Cookie: zerg_csrf=... │ │
│ (NOT HttpOnly; Max-Age= │ │
│ SESSION_TTL) │ │
zerg_csrf Max-Age = SESSION_TTL — default 86400s (1 day), clamped 300s–259200s (MANGO_SESSION_TTL).
Login details (AuthLoginHandler.post, mango/mango/handlers/auth.py):
Input gates: JSON body with username/account + password. Non-str
or missing → uniform 400. account ≤ 256 chars; password ≤ 72 bytes
.
Tokens are 256-bit: secrets.token_urlsafe(32) (32 random bytes),
stored SHA-256-hashed at rest (AuthSystem._hash_token). SESSION_TTL
defaults to 86400s, capped at 259200s (MANGO_SESSION_TTL). Service
tokens (POST /auth/service-token) use SERVICE_TOKEN_TTL — default
604800s (7d), clamped 3600s..7776000s (MANGO_SERVICE_TOKEN_TTL_SECONDS)
and are capped at 20 live tokens per user
(MANGO_MAX_LIVE_SERVICE_TOKENS_PER_USER), oldest evicted first.
Brute-force defense: per-IP limiter (Retry-After: 60 on exhaustion) AND per-account limiter; budget is spent only on
credential failure — successful logins refund.
Exhaustion enters a HARD LOCKOUT window keyed on the RESOLVED identity
unknown accounts
keep the string key. A locked account gets the uniform 401 + dummy-bcrypt
timing, plus a login_failed audit row.
LDAP first, local fallback:
AuthSystem.login tries GLAuth LDAP; on success the local user is
upserted (LDAP-provisioned users normally have no stored hash →
dummy-bcrypt path) and a Mango token is issued. Local bcrypt is the
fallback for genuinely LOCAL accounts and service accounts. A
DIRECTORY-SOURCED row (data.source == "ldap") that carries a local
hash (an admin reset on a federated account) is NOT silently accepted:
directory-invalid login is denied unless the explicit break-glass ack
MANGO_LDAP_ALLOW_LOCAL_HASH_FALLBACK=true is set, and an accepted
fallback writes the login_local_fallback audit row. The directory is
authoritative by default; the local hash is a recovery credential, not
a second production password. LDAP ops run in the executor (never on
the IOLoop — ).
Transparent rehash: successful login re-hashes at
the configured bcrypt cost (MANGO_BCRYPT_COST, default 12) when the
stored hash’s cost differs.
Host posture: when allowed_hosts
(MANGO_ALLOWED_HOSTS) or a concrete domain is configured, an unknown Host is refused (400) before auth/CSRF/limiter
or login work — on /health, /metrics and /auth/login alike. This
closes the DNS-rebinding arm where an attacker Origin matched the
attacker’s own request host. Duplicate/ambiguous zerg_session /
zerg_csrf cookies fail closed (no cookie-auth fallback when both the
__Host- and legacy names are present).
Error shapes: InfrastructureError (DB outage) → 503, no limiter
spend; anything else → uniform 401 (enumeration-resistant).
Failures audit login_failed.
Success response: {token, user: {uuid, username}, expires_at, csrf_token} + Set-Cookie: zerg_session (HttpOnly, Secure gated by
cookie_secure —, SameSite=Strict, Max-Age from
expires_at) + Set-Cookie: zerg_csrf (double-submit, Max-Age =
SESSION_TTL — see the generated block above, NOT HttpOnly so JS can
read it for the X-CSRF-Token header). login audited.
Rate-limit posture check: validate_rate_limit_posture fails
loudly when per-IP buckets are disabled and warns when the
validate budget is pinned to/below the documented topology floor
. Credential-
failure AUDIT rows are bounded separately by
MANGO_CREDENTIAL_FAILURE_AUDIT_RATE_LIMIT (default 60/60s per
action+IP) so an attacker cannot grow the HMAC audit chain unbounded.
Token Validation in Sol
Sol middleware (sol_auth_middleware.erl) processes every request:
- Exempt paths skip authentication, NOT authorization: exemption
assumes an anonymous identity envelope and RBAC still runs (,
). The DEFAULT exempt set is single-sourced from the code
(
default_exempt_paths/0=sol_session_shares:share_url_prefix/0+?DEFAULT_EXEMPT_PATHSinsol_auth_middleware.erl) and rendered here byci/docs_constant_parity_lint.py --write:
/api/v1/shares/
/health
/api/v1/health
/api/v1/ready
/api/v1/infra/status
/api/v1/infra/maintenance
/auth/login
/auth/validate
/auth/logout
/api/v1/auth/login
/api/v1/auth/validate
/api/v1/auth/logout
/api/v1/webhook/
Operators may extend the set via auth_exempt_paths (pprof is NOT
exempt by default — it requires an admin token). /api/v1/shares/ is
the anonymous share capability prefix; /api/v1/webhook/ is
unauthenticated BY DESIGN because the per-channel signature validation
(sol_http_webhook:validate_webhook/4) IS the auth. /metrics is
NOT exempt: a tokenless scrape is allowed only
when the loopback TOPOLOGY holds, otherwise it needs metrics:read.
/api-docs is exempt only from the MAINTENANCE-MODE check, not from
authentication.
2. Rate limit check first (configurable RPM/burst, cached in persistent_term).
3. Maintenance mode check (503 if active). This is a SEPARATE list
(is_maintenance_exempt/1), rendered below by the same generator:
/health
/api/v1/health
/api/v1/ready
/metrics
/api/v1/infra
/openapi.json
/api-docs
The two lists differ: /metrics, /api/v1/infra (subtree),
/openapi.json and /api-docs are maintenance-exempt but NOT
auth-exempt.
4. Token extraction:
Authorization: Bearer <token> header (highest priority)
x-api-key: <token> header (bearer-equivalent; the native Anthropic
SDK form —; Authorization wins when both are set)
Sec-WebSocket-Protocol: zerg_auth, <token> subprotocol ( —
browser WebSocket clients cannot set Authorization headers; this is
how chat/agent WS authenticate)
zerg_session cookie (fallback for cookie-based clients)
Query parameter ?token= (LOWEST priority AND opt-in: off by default
since then — it leaks into proxy/access logs and Referer headers;
enable with allow_token_query=true, each use logs a deprecation
warning)
5. Token validation via HTTP call to Mango’s /auth/validate endpoint (uses gun HTTP client).
6. Identity injection: sol_identity key set in process dictionary for request lifetime.
7. RBAC check: If Mango returns permissions, Sol verifies the endpoint’s
required scope against them (exact-string membership plus the bare *
wildcard; also refuses namespace:*/admin:* role grants at
the Mango write boundary — see rbac-scopes.md).
Mango /auth/validate details: valid tokens bucket
per-account/uuid (reserve/release); garbage tokens bucket a SEPARATE
fail-closed invalid limiter keyed by (ip, invalid) — a garbage flood
throttles itself, never the per-user buckets. A DB outage → 503 (retryable,
never treated as an invalid token).
Mango-outage behavior (fail-closed): when the /auth/validate call
cannot complete (Mango down, timeout), validation fails CLOSED — requests
return 401/503, never a dev-admin fallback.
Bounded staleness (Mango identity plane)
Mango is deliberately eventually consistent across three caches. The windows
are served by Mango’s loopback-only /ready census
(mango/mango/systems/staleness.py) and pinned to their owning constants by
mango/test/test_staleness_contract.py:
| Window | Value | Source / meaning |
|---|---|---|
| Sol positive token-validation cache | 5 s | ?CACHE_TTL_MS (sol_mango_client.erl); a revoked token keeps working on that node for up to this window. Transport/limiter outcomes are never cached. |
| Mango process-local permission cache | 10 s | _PERMISSION_CACHE_TTL; normal RBAC mutations invalidate it, so this is the bound for a missed invalidation. |
| Revocation-ring resync | 60 s | zmq_mango_resync_ms; Sol resyncs on every bridge (re)connect and then every 60 s. |
| Revocation convergence after a lost PUB frame | 65 s | resync (60 s) + Sol cache (5 s); the ring replays the missed entries. |
| Rights convergence | 10 s | max(Sol cache 5 s, Mango permission cache 10 s). |
| Multi-process Mango | false | multi_process_supported=false: the revocation epoch/ring, permission cache, limiters, audit HMAC head and ZMQ PUB socket are process-local. workers>1 is refused unless PG-backed and explicitly opted in, and even then the L1 shared-coherence work does not exist — no HA claim. |
(AGENTS.md): identity lives in the Cowboy request process. Must be captured via sol_identity:get_uuid BEFORE gen_server:call.
ZMQ Worker Identity
User identity flows through ZMQ to Luna workers:
Sol HTTP handler
│ sol_identity:get_uuid() (process dict)
│
├──► ZMQ Gateway spawn
│ │ user_uuid injected into Opts
│ │
│ ├──► task message ──► ZMQ ──► Luna worker
│ │ msgpack includes user_uuid
│ │
│ ◄── result message ◄── ZMQ ◄── Luna worker
│ msgpack includes user_uuid
│
└──► sol_zmq_handler_agent extracts user_uuid
from result message, passes to store_result/4
(AGENTS.md): ZMQ gateway/agent handler processes have NO sol_identity. Always extract user_uuid from msgpack message and pass explicitly.
For fire-and-forget background tasks: do_bg_start injects user_uuid from sol_identity:get_uuid into spawn opts. Background task results carry user_uuid back in their ZMQ result messages.
Session Expiry and Refresh
| Property | Value |
|---|---|
| Session TTL | 86400s (24h) default, capped at 259200s (3 days) — MANGO_SESSION_TTL |
| Service-token TTL | 604800s (7d) default, clamped to 3600s..7776000s — MANGO_SERVICE_TOKEN_TTL_SECONDS |
| Service-token cap | 20 live service tokens per user, oldest evicted first (journaled) — MANGO_MAX_LIVE_SERVICE_TOKENS_PER_USER |
| Service-token scope | Explicit permission-verb array in tokens.scope (migration v0017); validate returns min(user RBAC, scope); NEW mints default to the read-only inventory, legacy full-RBAC requires MANGO_SERVICE_TOKEN_ALLOW_UNSCOPED=1; request scope at mint, override via MANGO_SERVICE_TOKEN_DEFAULT_SCOPE |
| Cookie refresh | Not re-sent on each request; cookie is set once on login |
| Token refresh | Disabled (refresh_token grant returns 401, ) |
| Re-authentication | Required after expiry; Limon validates token on mount (5-min cache) |
| Logout | POST /auth/logout deletes token from DB, clears cookie with Max-Age=0 |
| LDAP offboarding sweep | Hourly directory revalidation (default 3600s; MANGO_LDAP_REVALIDATION_SECONDS, 0 disables): entry-id binding, two-miss quarantine→tombstone, blast-radius refusal/dry-run, bounded/resumable per-run budget |
“Auth refresh uses Bearer token — cookie is set once on login, not re-sent.”
Admin RBAC & first-admin bootstrap
A fresh Mango store has zero users. setup_db creates the schema and
seed_admin_rbac grants the * binding to admin rows that ALREADY exist —
it does not create an account. The
first admin is the documented environment step, executed at boot:
MANGO_BOOTSTRAP_ADMIN_ACCOUNT=<account>
MANGO_BOOTSTRAP_ADMIN_PASSWORD=<password>
maybe_bootstrap_first_admin(db) (mango/mango/bootstrap.py) runs after the
migrations on a COMPLETELY EMPTY users table, creates the admin through
the normal account path, and seeds its RBAC binding. Both variables must be
set together; a partial pair logs a warning and creates nothing, and a
non-empty store is never touched. Rotate the password and unset
MANGO_BOOTSTRAP_ADMIN_PASSWORD after the first login
(mango-bootstrap-admin --auto seeds the binding for an existing admin).
On an empty store WITHOUT the pair, Mango logs a startup WARNING and
/health reports "users_empty": true for that boot posture (re-evaluated
at the next start) — the install cannot silently dead-end at a login with
no account. Tests:
mango/test/test_readiness_packaging_http.py covers both the with-env and
without-env fresh-DB legs.
Admin role with permissions: ["*"] passes all RBAC checks in Sol and Mango.
The users.role column is a create-time bootstrap seed (written only by
account creation, read only by seed_admin_rbac at boot); all runtime
authorization flows through the team/role tables.
Anonymous users have admin access only when enable_token_auth=False + host is localhost (production guard raises ValueError otherwise — ).
Key Security Decisions
| Decision | Rationale |
|---|---|
| Cookie auth secondary (Bearer header priority, ) | Allows JS clients to authenticate without cookie dependency; cookie is fallback for SSE/WS |
zerg_session is HttpOnly; Secure (config-gated); SameSite=Strict | Prevents XSS token theft; cross-SITE CSRF via same-site enforcement. correction: Strict does NOT cover same-site sibling-subdomain attacks — a malicious sibling subdomain of the configured domain is same-site and can read the non-HttpOnly zerg_csrf, forging the double-submit header. The double-submit gate is therefore defense-in-depth against cross-site origins, not a same-site boundary; treat subdomain delegation as a trust decision. |
| Mango login limiters per-IP + per-account, spend-on-failure | Prevents brute-force password guessing without starving valid logins; hard lockout window guarantees recovery |
| Timing-constant bcrypt comparison | Dummy hash pre-computed at module load; prevents timing oracle on missing users |
| Refresh tokens disabled | Simplifies token model; clients re-authenticate on expiry |
| Mango permissions flow through ZMQ | Workers receive user_uuid + permissions; no separate auth context needed in worker boundary |
| Two-layer ownership enforcement | Middleware (auth-enabled) + handler defense-in-depth; handlers always check ownership even if middleware misconfigured |
WS auth via Sec-WebSocket-Protocol: zerg_auth subprotocol | Browser WebSocket clients cannot set Authorization headers; cookie fallback for SSE. One-time WS tickets landed in; the lifecycle re-mints a fresh single-use ticket on the typed 4401 reauthenticate close and re-handshakes (see docs-site/api/chat.md). |
Engine reference — generated from the canonical engineering source. Do not edit this page by hand.
ZMQ Security Posture
Current State
Transport encryption: CURVE by default. ZMQ communication between Sol and Luna workers runs over the CURVE security model (ZMTP): the ROUTER (task plane) and PUB (event plane) sockets act as CURVE servers whenever the bind is non-loopback (zmq_curve_enabled=auto — the default; loopback binds keep the plaintext dev posture since nothing leaves the host). The server keypair is generated on first boot and persisted to <data_dir>/curve_server.cert (chumak_cert z85 format, mode 0600); workers provision the server’s PUBLIC key as LUNA_ZMQ_CURVE_SERVERKEY (or auto-discover the same-host keyfile). A non-loopback plaintext bind refuses boot in prod unless the operator explicitly acknowledges it (zmq_transport_plaintext_ack=true, CRITICAL-logged) or declares an encrypted tunnel (zmq_transport_tunnel=wireguard|mtls-sidecar) — one gate family for ROUTER + PUB. A curve-enabled node whose crypto backend is missing (a build where the chumak override was lost) also refuses boot — it never silently binds plaintext.
The CURVE crypto backend is nacerl (tweetnacl) — chumak’s own documented default, vendored as the self-hosted spacebeam/nacerl fork (branch zerg/main, pinned in server/rebar.lock; see the fork README.md for the full “what was fixed and why”). tweetnacl is the exact crypto libzmq itself vendors for CURVE, so both sides of a curve connection implement the identical NaCl construction. Zero system dependencies.
Registration authentication: per-worker enrollment keys. The shared fleet secret (SOL_ZMQ_WORKER_SECRET) remains supported during the legacy-compat window but the recommended posture is per-worker keys: the ready frame carries key_id, Sol verifies the HMAC with the named registry key (zmq_enrollment_keys, provisioned per worker — config map or SOL_ZMQ_ENROLLMENT_KEYS JSON), and refuses unknown/revoked keys. A registry entry bound to a specific worker_id refuses a ready claiming a different worker — a stolen key cannot re-register under a fresh identity. Registration-rate anomalies (default >60 registrations/min) fire a CRITICAL alarm (zmq_register_rate_anomaly_total); the anonymous/fleet-legacy bucket paces at max(zmq_register_rate_limit, zmq_worker_cap) so a cap-sized restart storm converges, while per-credential buckets keep the configured rate. The raw enrollment/local-mint secrets are held by the private sol_zmq_secret_store owner’s process state — the public ETS registries carry metadata only; a session key is re-derived from the store on a gateway restore.
Locally-spawned workers are first-class enrollment clients. With the compat window closed, a fleet-secret-only provisioning refuses EVERY registration — the live-fleet defect this closes (init-wkr-N was spawned with only the shared secret and heartbeated against fleet_secret_deprecated forever; sol_zmq_registered_workers stuck at 0). Now the spawn path (sol_worker:worker_env/1, used by sol_worker spawns and the gateway’s init-wkr-N) mints — or reuses — a per-worker enrollment key in the reserved local: namespace, bound to the exact worker id, and the worker env carries LUNA_ZMQ_KEY_ID + the minted secret INSTEAD of the shared fleet secret (least privilege: locally-spawned workers no longer hold the fleet-wide credential at all). The minted keys persist at <data_dir>/zmq_enrollment_local.json (0600, atomic tmp→rename; a corrupt store is moved aside and re-minted, CRITICAL-logged) so a Sol restart re-issues the same key to the same worker id. The local: id namespace is refused for operator-provisioned keys. The lever zmq_local_enrollment (default true; SOL_ZMQ_LOCAL_ENROLLMENT=false) restores the legacy env. A fleet secret set with NO other provisioning and local minting disabled is a knowably dead registration plane and refuses boot (zmq_registration_plane_dead; ack lever SOL_ZMQ_REGISTRATION_PLANE_ACK=true CRITICAL-banners instead); with minting enabled the same shape CRITICAL-banners that EXTERNAL fleet-secret workers cannot register and names the provisioning requirement (SOL_ZMQ_ENROLLMENT_KEYS). The compat window, when explicitly reopened, is bounded: SOL_ZMQ_FLEET_LEGACY_COMPAT_UNTIL (ISO YYYY-MM-DD) CRITICAL-banners with the remaining days and refuses (fleet_compat_window_expired) once past; its use is counted (sol_zmq_fleet_legacy_ready_total), paired with the labeled refusal family sol_zmq_registration_refused_total{reason="fleet_secret_deprecated"}. On the worker side, ANY registration refusal (registration_hmac_failed, with the enrollment reason in details) now de-registers and schedules the full-jitter re-ready instead of heartbeat-looping in a never-registered “connected” state.
All ZMQ traffic is therefore: Encrypted (CURVE) on every non-loopback bind by default; plaintext only with an explicit operator acknowledgement or declared tunnel Authenticated at registration (fleet secret or per-worker enrollment key, nonce-bound HMAC with replay protection) Protected against replay at the application level (nonce LRU with TTL + identity binding)
Message-level ownership enforcement. The transport gap is mitigated by per-message authorization on the Sol control plane:
result / token / error frames require the worker the task was dispatched to (sol_zmq_indexes task index) and current registration. On an index miss the gate answers from durable DATA, not from registration: only a registered sender whose identity equals the recorded executor (sol_task_store:get_last_executor/1, stamped at dispatch and re-stamped by the boot reconcile) rides the bounded post-restart grace, attributed <<"system">> and WARNING-logged. No recorded executor, or a foreign one, is refused and counted. The previous “currently registered sender” grace is DELETED — a registered worker can no longer claim an executor-less index miss. A forged frame from a never-registered DEALER is dropped, logged CRITICAL, and counted in sol_zmq_auth_failures_total (Prometheus). A registered worker cannot create synthetic “completed” tasks: writes for task ids with no ownership-index entry, no sol_task_results pending row and no dispatch-queue seat are rejected. Terminal states (ok/completed/cancelled/timeout) reject all later writes — a late worker result cannot resurrect a cancelled or timed-out task.
event frames require a registered worker identity and the worker-emittable event namespace is closed: only telemetry.* and agent.* diagnostics are accepted. Core state events (task.*, workflow.*, team.*, scheduler.*, model.*) from ZMQ workers are dropped + counted — they are HTTP/internally sourced by definition. Caller-supplied user_uuid is stripped.
spawn frames require the parent task to have been dispatched to the sending worker — closing cross-session RBAC inheritance via a forged parent_task_id. Child spawns also consume a license seat.
acp, acp_reply and plugin_tool_call frames all require a registered sender; acp/acp_reply attribution always uses the socket-bound routing identity (frame-supplied from is discarded), and an acp_reply may only satisfy a request that was actually ZMQ-forwarded to that identity. : the ACP plane carries NO user principal — user_uuid is stripped at the handler and in the forward builder, and Luna’s idle agent always uses its per-connection anon:<worker_id> scope. A ZMQ acp_type=capability AgentId MUST equal the verified routing identity (agent_id_mismatch otherwise — no squatting a well-known name); every routed/delivered request refreshes the registry last_seen so a continuously used agent never expires; the legacy programmatic register/3 is guarded (same-pid refresh only; explicit register/4 overwrite).
team_heartbeat / team_directive / team_mail require registration and team membership of the sender’s registered worker_id (server-side mapping); team_mail’s from is derived server-side; heartbeat liveness is recorded for the sender’s own member record, never the frame-supplied member_id.
All gates are behind zmq_ownership_enforced (default true; rollback via SOL_ZMQ_OWNERSHIP_ENFORCED=false).
Worker Registration
Enrollment keys: zmq_enrollment_keys
configures #{KeyId => #{worker_id => WorkerId | "*", secret => Secret}}.
A ready carrying key_id is verified against the named key (same HMAC
material below); unknown, revoked (zmq_enrollment_revoked) or
worker-mismatched keys are refused with a CRITICAL log + zmq_auth_failures_total.
The "fleet-legacy" key name (or an absent key_id) selects the shared
fleet secret while zmq_fleet_legacy_compat=true — **the compat window
defaults CLOSED as of **; new installs provision enrollment keys.
Secret strength: every enrollment
secret must be a binary of ≥ 16 bytes. A blank/<<>> or short secret
is an INVALID entry: it is dropped from the normalized registry with a
CRITICAL log and counted, and validate_configured_keys/0 refuses the
boot ({invalid_enrollment_entries, N}) unless the explicit ack lever
zmq_enrollment_allow_invalid downgrades it loudly. resolve_key/1 also
enforces the floor at runtime (a short secret injected into the live
table refuses typed with weak_secret), and the ready funnel sends the
worker an error frame — the pre-fix shape accepted <<>>, then crashed
session_key/1 inside the handler, leaving the worker knocking forever
with no feedback.
Runtime revocation input: the
revocation set is not restart-only even without the Mango bridge. From
the operator remote shell / sol_console:
sol_zmq_enrollment:revoke_key(<<"worker-7">>). %% immediate
sol_zmq_enrollment:unrevoke_key(<<"worker-7">>). %% rollback
revoke_key/1 writes the authoritative ETS set that resolve_key/1 and
key_active/1 read directly, so the next registration (and the gateway’s
10s liveness key sweep, which evicts live sessions of inactive keys)
Enrollment↔CURVE binding + provisioning surface.
Enrollment records MAY carry the optional curve_pubkey field (40-char
z85 or 64-char hex) — the operator-collected binding of worker ↔ CURVE
client key per the amended key-distribution migration
(plan/curve-key-distribution-migration.md, Option A′). A malformed
value makes the entry invalid (dropped + counted; the boot refuses
enrollment_keys_invalid unless zmq_enrollment_allow_invalid is set).
Under A′ the flip posture keeps zmq_curve_clientkeys unset (any):
CURVE supplies confidentiality + server authentication; per-worker
authorization stays with the enrollment HMAC + identity binding + the
per-frame MAC plane. The operator provisioning surface — everything a
worker needs to connect — is one remote-shell call:
sol_zmq_curve:provisioning_info().
%% #{keyfile => ..., server_public_key_z85 => <<"...">>,
%% curve_enabled => ..., bind_addr => ..., worker_env_hint => ...}
refuses immediately — no Mango resync tick, no restart. Config-file edits
to zmq_enrollment_revoked still take effect on the ~60s resync
(refresh_from_config/0) when the bridge is live, and on restart
otherwise; a later refresh_from_config/0 re-reads config and can
therefore re-add a config-listed key, so make a runtime revocation durable
by removing the key from config too.
Credential rotation: DRAIN BEFORE ROTATING. A
worker’s enrollment key may be rotated (revoke the old id, provision the
new one) — but adoption across a reconnect requires SESSION-KEY
CONTINUITY: the derived MAC key of the presented credential must equal
the key recorded on the existing registration. A rotation performed while
the worker has an in-flight task therefore refuses adoption and resolves
that task as worker_reconnected (the error strategy decides retry vs
terminal). Operational procedure: (1) stop accepting new work for the
worker / let it drain (zerg status shows its in-flight task), (2) revoke
the old key and provision the new one, (3) let the worker reconnect and
re-READY. The rotation is visible: a verified re-registration under a
different key_id bumps zmq_credential_rotation_inflight_total (ZMQ
dashboard panel “Credential Refresh Refusals”; alert on an unexpected
increase) and logs the old/new key ids. A fleet-legacy sentinel session
(key_id = "fleet-legacy") stays active only while
zmq_fleet_legacy_compat=true; the 10s key sweep reads the sentinel
through that lever instead of treating it as a removed key.
When SOL_ZMQ_WORKER_SECRET (SOL_ZMQ_WORKER_SECRET env → binary via secret_val/1) is configured (≥ 16 bytes), every ready frame must carry a fresh nonce plus:
hmac = HMAC-SHA256(secret, nonce || u16(len(identity)) || identity
|| u16(len(worker_id)) || worker_id
|| u32(child_depth) || u64(ctr))
Field binding: the MAC covers the ROUTING identity (length-prefixed, before worker_id) + worker_id + child_depth — a captured ready frame cannot be re-signed-replayed against a different routing identity (a rogue DEALER replaying a captured frame under a victim’s identity fails the HMAC). Luna sets the DEALER identity to worker_id, so its builder emits the worker_id in both slots.
Monotonic counter: the material
ends with ctr, a u64 big-endian wall-clock millisecond counter that is
strictly increasing per identity and freshness-bounded (10 min default,
zmq_ready_ctr_max_age_ms). Sol refuses ctr <= last accepted
(counter_replayed) and stale counters (counter_stale) independently
of the nonce LRU — the LRU (kept as the hostile-churn DoS bound; the
1024-identity cap can no longer re-open a replay window) is no longer
the replay defense. ** (WIRE-03):** the ctr freshness bounds
are ONE clock domain with the frame-tx plane — 10 minutes in the past and
the shared 24-hour FUTURE window. A ctr beyond the future window is
refused without persisting; recovery from a worker-PERSISTED future floor
is the signed sol_zmq_indexes:retire_identity/2 server reset plus a Luna
restart with LUNA_RESET_REPLAY_WATERMARKS=1 (the idle reaper also drops
absurd-future rows). A missing/non-integer ctr refuses with
missing_counter; the explicit legacy-material lever is
zmq_enrollment_ctr_required=false (mixed-fleet escape hatch — the
legacy 4-arity material via registration_signed_material/4, nonce-LRU
replay bound only). The canonical v2 builder is
registration_signed_material/5.
Freshness: Sol keeps a per-identity nonce LRU (last 64, records timestamped with a 60s TTL) — any replayed nonce is refused (nonce_replayed). The LRU survives gateway restarts via the index heir (node restarts lose it by design — it is the DoS bound, not the primary replay defense); identities are evicted when their worker is evicted and the table is size-capped (1024 identities, oldest-identity eviction). The monotonic ready-counter AND frame-tx watermarks are additionally journaled into the durable replay fence so they survive node restarts too; a READY-ctr admission fsyncs the journal before it returns.
In-flight adoption proof: a duplicate-identity ready arriving while the record holds an active task is adopted ONLY when the ready was VERIFIED by any configured credential (the verification outcome — auth_class — is carried out of verify_worker_registration, never inferred from env presence) AND the frame names the exact task_id it resumes (matching the record’s current_task AND the ownership-index owner). Anything else falls back to the orphan path (task terminally errored with worker_reconnected) — an open-registration peer can no longer hijack an in-flight task by claiming the victim’s identity, and enrollment-only fleets no longer discard executed work on reconnect.
Boot gate: prod + non-loopback zmq_bind_addr + empty zmq_worker_secret refuses boot ({refuse_boot, zmq_secret_required} — the same fail-closed pattern as the HTTP auth boundary). Loopback binds keep the open dev posture; non-prod external binds boot with a WARNING. The secret is provisioned by wild (SOL_ZMQ_WORKER_SECRET / LUNA_ZMQ_WORKER_SECRET on workers).
Loss Policy
The wire-level loss policy (critical-frame set, droppable classes, paused-gateway
NACK behavior) is specified in the canonical wire reference — see the
Loss Policy section of
docs/zmq-protocol-reference.md. The security-relevant summary: only true
diagnostics (telemetry.-prefixed event frames) and the
abandoned-reply class (acp_reply, whose caller-side timeout governs) are
ever shed; result/token/error (content), heartbeat (liveness) and the
coordination frames (team_directive/team_mail/team_heartbeat/acp/
plugin_tool_call — ) are never dropped, and any frame a
paused gateway still sheds is NACKed with an explicit error frame.
: the acp_reply shed classification is now
consistent across BOTH pause layers — sol_zmq_recv_dispatcher: droppable_under_load/2 explicitly sheds it too (the pre-fix shape
forwarded it at the mailbox-HWM layer while the gateway’s paused gate
shed it), and the boot drift check is bidirectional so the two layers and
the shared manifest can never fork silently again.
PUB Plane PII
The PUB socket (5556) has no per-subscriber auth, so it carries correlation metadata only: task.created publishes task_id (never the prompt), task.completed publishes {task_id, status, tokens_used, workflow_id} (never result content), and session.message_pushed payloads are stripped of message bodies. Both encoder paths (the event-forwarder Path A and the sync-event-router Path B) produce the same canonical shape per topic.
The authoritative per-event transport matrix (store ingress, SSE, PUB-to-Luna Path A/B, Mango bridge) is generated in event-reference.md by ci/event_transport_matrix_gen.py; do not hand-copy event counts or per-topic rows into this doc.
: task.failed publishes error_code — a server-reason
allowlist (task_timeout, worker_timeout, worker_reconnected,
send_timeout, gateway_paused, cancelled); anything worker-supplied
collapses to <<"worker_error">>. Worker free-text error strings (which
embed prompt fragments and paths) are UNREACHABLE from the PUB plane.
task.dispatched/task.started publish worker_hint — the 16-hex-char
SHA-256 prefix of the worker id — instead of the raw worker_id: stable for
ops correlation, non-invertible, not a routing key.
: the PUB scrub (sol_zmq_events:strip_pub_pii/1)
is now a bounded recursive scrub (depth ≤ 4): the content keys plus
config — a team config can embed provider API keys — and the
known-sensitive subkey family (api_key, secret*, *token,
password, credentials, private_key, bearer, authorization,
cookie, hmac, mac_key, signing/encryption keys) are removed at every
level, and the Path A generic team/workflow encoders run it too (the
pre-fix top-level-only strip shipped team_created’s config map intact on
one path). Nested opts maps are scrubbed as well; a planted-secret
regression asserts the bytes never reach the encoded frame.
Per-Frame MAC Plane
The ROUTER routing identity is client-declared, so identity alone can never
authenticate a frame. Every worker-plane frame (token, result, error,
heartbeat, and — since then — team_directive, the
recorded acceptance) and every frame on the extended
agent/team plane (spawn, event, acp, acp_reply, team_heartbeat,
team_mail — ) from a CREDENTIALED session carries a
trailing multipart MAC frame:
DEALER multipart : [payload, mac_hex]
mac_hex = hex(HMAC-SHA256(session_key, "Z3" || u16be(len(identity))
|| identity || u64be(tx) || payload_bytes))
session_key = hex(HMAC-SHA256(credential_secret, "zerg-session-mac-v1"))
tx = per-session monotonic frame counter (u64, max(last+1, epoch-ms))
The payload bytes are MAC’d verbatim (no canonical-encoding ambiguity);
the routing identity — the one field NOT inside the payload — is bound
in explicitly. session_key is the 64-char lowercase-hex STRING (both
sides derive identically; Luna’s AgeCrypto.hmac_sha256_hex is
byte-exact). The cross-language vector table
docs/fixtures/zmq_frame_mac_vectors.json pins the material + MAC bytes
across both languages (server/test/sol_zmq_frame_mac_vector_tests.erl +
client/tests/test_zmq_frame_mac.lua).
Material v3: the per-session tx counter is
bound INTO the MAC material and stamped on the frame as the additive
msgpack key tx (no multipart shape change). Sol enforces strict
monotonicity per identity (sol_zmq_indexes:frame_tx_ok — an
identity-lifetime tombstone that eviction NEVER purges within the
node, and which the durable replay fence below persists across node
restarts — one journal append per accepted frame plus the 256-record
snapshot cadence): a replayed
frame fails {refuse, replayed_tx} and bumps
sol_zmq_frame_mac_replay_total. This closes the replay defense the
material had none of — captured heartbeat/spawn/
team_directive frames no longer replay cleanly. Worker plane + the
new planes moved together in the ONE material bump.
Durable replay fence:
both watermark stores (sol_zmq_frame_tx and sol_zmq_ready_ctr) are
memory-only ETS with the index heir — they survive a gateway restart but
NOT a node restart. They are persisted by
<data_dir>/zmq_replay_fence.term (full snapshot — sol_durable_file
tmp→fsync→rename, mode 0600, one atomic write per 256 recorded
watermarks OR 5s) plus an append journal
(zmq_replay_fence.journal): every accepted watermark row is appended
(one write syscall, no per-frame fsync) before the frame is dispatched,
and a READY-ctr admission fsyncs the journal before it returns (one
fsync per accepted READY, which also commits every earlier tx append).
The snapshot flush rotates the journal (journal → journal.prev); boot
(sol_zmq_replay_fence:load/0) MAX-merges snapshot + both journal
generations and compacts them back into the snapshot before the
transport tail accepts frames. A captured frame or READY replayed after
a node restart therefore still fails replayed_tx /
counter_replayed. A journal append/sync failure REFUSES the
frame/READY fail-closed (typed refusal; a READY advances no ETS row, a
tx CAS may already have advanced in memory but the frame is still
refused) and bumps sol_zmq_fence_journal_write_failed_total (paged by
SolZmqLossCounters) — a frame is never admitted with an unrecorded
watermark. The snapshot-cadence check runs on the next recorded
watermark, NOT on a timer: a POWER/OS loss therefore loses at most the
last ≤256 un-fsynced tx rows since the last snapshot flush —
wall-time unbounded if the fleet goes idle below the 256-record
threshold (READY rows are always fsynced, so they never sit in that
tail). A process/VM death (kill -9) loses no accepted row. Of the
affected classes, a replayed result/token is neutralized
downstream — settlement settle_once, the token seq-gap detector and
the per-attempt gates make the replayed work exactly-once; the sharpest
leg was a stale ready re-registration for an OFFLINE worker
(re-registering a captured READY), which the READY fsync closes. The
signed identity-retire operation either purges the snapshot+journal
(when it owns the journal handle) or fsyncs an ordered
{retire, Identity} tombstone that boot applies after the snapshot
and earlier journal frames; if NEITHER artifact can be written the
retire returns {error, {fence_purge_failed, _}} instead of claiming a
durable reset. The v1 legacy-material READY
(zmq_enrollment_ctr_required=false) has no counter plane and remains
nonce-LRU-bound only (node-lifetime) — the lever is the documented
mixed-fleet escape hatch, not the default. A missing/corrupt fence file
is CRITICAL-logged and moved aside, and the READY ctr freshness bound
(10 min) keeps refusing stale READYs independently.
Luna send-side fail-closed: a credentialed
session NEVER sends a worker-plane frame bare. If the per-frame MAC
cannot be computed (frame_mac_v3 → nil: a crypto-backend failure after
the session key was derived), Luna refuses the send with a typed
frame_mac_unavailable (critical frames stay in the retransmit lane);
the pre-fix shape fell through to the anonymous single-frame send,
silently re-opening the unsigned class under prefer/legacy windows. The
Luna decoder also enforces Sol’s structural budget (65536 elements / 64
containers) and refuses trailing bytes (WIRE-08) — both ends now agree on
the exact-consumption + budget contract.
Worker event aggregate truth:
agent.child_completed is emitted with the SERVER child task id (the
client-local background id rides as client_task_id). A child executed by
a different worker than its parent is accepted through the
server-recorded child→parent relationship when the sender owns the
parent; legacy client-local ids are re-stamped to the verified parent.
A legitimate child no longer trips SolZmqAuthFailures.
Sol→Luna direction — the documented asymmetry (,
B3-): the MAC + tx replay binding above covers the
worker→Sol direction only. Outbound Sol→Luna frames carry the
skew-aware v stamp and ride the CURVE-pinned pipe, but they carry
No per-frame MAC and no freshness/nonce/replay binding. An
adversary who can record and re-deliver outbound frames — control of
the pinned transport, the loopback plaintext posture, or the null
mechanism — can replay task/lane_control/cancel_task frames at
Luna. The blast radius is bounded by Luna-side idempotency, not
cryptography: the pending-task queue is keyed by task_id and the
highest attempt wins (an equal/lower redelivery is a duplicate), an
already-terminal task is not re-executed (terminal journal/spool), and
the lane-control plane is holder/lease-gated (stale_grant /
lease_lane_mismatch refusals). The residual is a replayed
coordination frame whose effect is not task-keyed (e.g. a duplicate
lane start/stop against a still-live lease); the transport trust
boundary (CURVE pin + the plaintext refusal gates) is the defense.
Closing the asymmetry needs a Luna-side inbound nonce/epoch accepted
on the solver→worker plane — tracked by the B4 successor
rows, never silently implied by the worker-plane MAC.
Fleet-legacy window (, — the legacy-decay
pattern): lever zmq_frame_mac_legacy, default OPEN at,
CUTOVER SHIPPED in (default false — the window is CLOSED;
sys.prod.config pins it explicitly). While it was open: missing MACs
on the extended set were accepted + counted into
sol_zmq_frame_mac_legacy_total, and a tx-less v2 MAC ("Z1"
material) verified under the window. CLOSED posture: missing MACs on
the extended set and v2 (tx-less) MACs REFUSE under
zmq_frame_mac=required (rollback lever = flip the config to true).
A PRESENT but invalid MAC is refused in every posture.
** straggler window (,; CUTOVER,
SEV1 SOLZMQ-01):** the completion added
cancel_task and plugin_tool_call (plus plugin_tool_result, later
retired inbound with /) to the MAC
plane AFTER the cutover had closed the window — with NO
window and NO pairing note, so required silently began refusing the
UNSIGNED versions of those frames from every Luna whose send side
predates. These types are worker→Sol CONTROL traffic: a
refused cancel_task strands the child running, a refused
plugin_tool_call breaks every plugin tool on the lagging worker.
Opened a TYPE-SCOPED window (lever
zmq_frame_mac_d1542_legacy, formerly default OPEN) under which a
missing MAC on exactly the completion types was accepted + counted into
sol_zmq_frame_mac_straggler_total (a PRESENT but invalid MAC was
still refused). ** CLOSED the window: the default is
now false.** A missing MAC on ANY plane type refuses under
required; the straggler counter must sit at ZERO in a healthy fleet.
The SEV1 SOLZMQ-01 chain the window left open: a peer presenting a
registered identity (client-declared, and duplicate arbitration is not
instantaneous) could send UNSIGNED plugin tool calls executed under the
victim task’s stored grant, or cancel a victim’s children. Rollback is
the EXPLICIT config lever ({zmq_frame_mac_d1542_legacy, true}) — no
silent default. The mixed-fleet matrix (every plane class × every
posture, counters included) is pinned by
server/test/sol_zmq_frame_mac_set_tests.erl
(mixed_fleet_matrix_test_); the credentialed real-wire drill is
server/test/sol_zmq_credentialed_wire_SUITE.erl. **
** the reference Python worker (example/python/zmq_worker.py,
WORKER_PLANE_TYPES) is machine-checked against the same fixture
(worker_plane ∪ extended_plane) by ci/wire_doc_parity_lint.py — a
worker extended from the example signs every current plane type (the
pre-fix set omitted lane_control/cancel_task/plugin_tool_call,
so those frames refused missing_mac; the / retirement
of the worker→Sol log/plugin_tool_result frames shrank the set).
Sol verifies the MAC in the frame router BEFORE any handler runs; a
refusal drops the frame + bumps zmq_frame_mac_missing_total /
zmq_frame_mac_failures_total / zmq_auth_failures_total. The mac
gate itself is crash-wrapped — one malformed frame
cannot take the gateway down. : the gate is
fail-CLOSED for a credentialed record whose session key is missing or
non-binary ({refuse, session_key_missing}; the pre-fix shape fell
into the “no session key” arm and skipped verification), and the
no-wire gateway arities dispatch_zmq_async/3 + /4 are DELETED —
every in-process frame now carries its wire metadata, so no direct
caller can bypass the gate. : the frame router’s
legacy no-wire dispatch_zmq/4 and /5 arities are now -ifdef(TEST)
(test-build only); a production compile exports ONLY the wire-carrying
dispatch_zmq/6. The prefer/off levers below are
unchanged.
Per-pipe registration binding: the vendored
chumak patch surfaces the DELIVERING pipe pid
(recv_multipart_with_pipe/1 → {ok, Multipart, PipePid}); an
ACCEPTED ready BINDS its routing identity to that pipe and every
later frame for the identity arriving on a DIFFERENT pipe is dropped +
counted (zmq_pipe_binding_drop_total) before any handler runs
(sol_zmq_pipe_binding:allow/4). This is a second, transport-level
binding next to the CURVE identity pin. LEGACY POSTURE (documented): a
worker record without a bound pipe (restored registers, pre-upgrade
rows, pipe-less test surfaces) and unregistered identities stay
ALLOWED — the binding strengthens the live path, it never retro-drops
a fleet. ready re-binds on every accepted registration (the identity
arbitration owns duplicate claims).
Registration HMAC ordering: the fleet-secret
READY path now verifies the HMAC BEFORE consulting
nonce_seen/ready_counter_ok (mirroring the enrollment path) — an
unauthenticated peer can no longer probe or consume the replay stores;
the identity binding runs after consumption, exactly like enrollment.
Mode lever zmq_frame_mac: required (default — a credentialed
session’s worker-plane frame without a valid MAC is refused; extended
set governed by the legacy window above), prefer (verify when
present, count missing — closed the silent pass;
the mixed-fleet window is observable), off (rollback lever).
Anonymous sessions (no credential configured — loopback dev posture)
stay MAC-optional.
The owner-match leg of the ownership gate additionally requires CURRENT
registration (sol_zmq_ownership:allow_result_frame/4).
Duplicate routing identities at the transport floor (identity
pinning, ): the vendored chumak detects a second DEALER
declaring a live identity and notifies Sol with the NEWCOMER pipe’s pid.
The registration is PINNED to the CURVE peer key captured at READY
(chumak:peer_public_key/2 — stored on the #worker{} record and in
the sender’s pinned map). Conflict policy, in order:
- Pinned + the newcomer’s pipe key matches the pin (constant-time) the newcomer provably speaks for the SAME host (completing a CURVE handshake with a public key requires the private key): legit reconnect. The stale incumbent pipes are evicted, the registration stays, and the newcomer’s READY rides the adoption gate. Proof beats the temp ban.
- Pinned + mismatch (or the newcomer presents no key) — the UNPROVEN newcomer pipe alone is evicted; the victim’s registration, pipe and in-flight task are untouched. The knock loop (one connect per knock, unauthenticated) no longer evicts anyone but its own pipe.
- No pin (unregistered identity, CURVE off / null mechanism, or a
pre-pin registration) — the fail-closed evict-BOTH fallback
registration dies, the in-flight task orphans
through error_strategy, all pipes disconnect (
zmq_identity_conflict_totalalarm). Knock-loop bound: every conflict is recorded per identity into a 60s window; at 10 conflicts the identity is TEMP-BANNED for 300s — further unproven conflicts land a CRITICAL + the existingzmq_register_rate_anomaly_totalanomaly alarm +sol_zmq_identity_conflict_banned_total, and the offender’s future connects are evicted on sight. A key-matching reconnect is exempt (proof beats the ban). A registered victim’s egress is restored by the bounded heal above; only a continued knock storm can extend the aggregate refusal window (never the 60s ledger per knock). : the sender now CONSULTSidentity_banned/1(sol_zmq_sender:arbitrate_decision/4) — a banned identity’s unproven newcomer is evicted ALONE instead of the evict-BOTH fallback (the pre-fix shape let every knock on a banned identity still evict the victim’s registration; the doc claim was unimplemented code-side). The pinned-key clause is evaluated first, so the key-matching reconnect exemption is preserved. Residual (honest): under the acknowledged plaintext posture (zmq_curve_enabled=false/ loopback, orzmq_curve_clientkeys=anywith null-mechanism peers), there is no peer key to pin: step 3’s evict-BOTH applies and a knock still evicts a victim that is itself unproven. The documented mitigations remainzmq_curve_clientkeysallowlists (a knock’s handshake then fails before the identity layer), firewalling the ZMQ port, and CURVE-on — identity pinning is the identity-layer bound, not a transport-floor ACL. (With the ban consultation, once the knock loop crosses the threshold the victim registration survives.) Egress TTL: a duplicate-identity knock makes the sender cache{refuse, unverified_conflict}BEFORE arbitration (so the next send cannot round-robin onto a competing pipe). On anevict_newcomerverdict where the registered victim survives, that cached refusal is now CLEARED after a bounded 250 ms settle window (?EGRESS_HEAL_MS): new sends to the victim egress again 250 ms after the attacker pipe is closed instead of remaining blacked out for the full 60s conflict ledger. The settle window keeps the transport’s eviction/reconnect visibility from racing the heal. Sustained knocks (review fix): once a heal is GRANTED for a registered victim, later knocks inside the ledger window keep egress open while the single-pipe proof holds — CURVE: exactly one live peer key on the registered pipe; plaintext/null mechanism: the registered pipe is alive (chumak omits unsigned pipes, so there is no pid to enumerate). The gateway’s post-eviction reconcile consults the SAME grant + proof before unpinning, so a >=4 conns/s knock loop cannot sustain a blackout. A registration eviction prunes the grant. The 60s window still exists and still rate-limits/bans repeated knocks; it no longer blacks out a registered victim’s new dispatch. In-flight work was never affected. CURVE-with-pin reconnects keep theadopt_newcomerheal (window/ban cleared, stale incumbents evicted). Pre-auth frame bucket: unregistered heartbeats spend a per-delivering-pipe + global 60s bucket (zmq_preauth_pipe_limitdefault 20,zmq_preauth_global_limitdefault 2000) before anyready_requiredcontrol reply. A dropped frame is counted onzmq_preauth_heartbeat_dropped_totaland never reaches the sender’s per-identity budget map; the sender’s control-budget drop log is rate-limited. Client-key fail-closed: the allowlist no longer fails open.zmq_curve_clientkeys=anyis the documented confidentiality-only form and means UNRESTRICTED; ANY configured list must decode entry-for-entry, otherwise the bind is REFUSED with a typed error (curve_clientkeys_empty,curve_clientkeys_undecodable,curve_clientkeys_shape) — a typo can neither silently drop an allowed key nor silently becomeany. Every security-relevantset_socket_optionreturn is checked and a rejected option refuses the bind (the ROUTER/PUB init stops rather than binding with the allowlist absent). Proven-reconnect exemption: the conflict window/ban counts UNPROVEN pipes only. A duplicate identity whose newcomer presents the pinned CURVE key (only the same host holds that private key) is a legitimate reconnect: it is not recorded, and any active temp ban + window is CLEARED so the verified re-READY is admitted. The pre-fix shape counted legitimate reconnects, so a flapping worker self-banned after 10 reconnects inside 60s.
Team-Mail Content Signatures
Every team_mail_push to a credentialed session carries a mail-integrity
stamp keyed with the RECIPIENT’s derived session key. Luna verifies it BEFORE
injecting the mail into agent context; a missing/mismatched stamp QUARANTINES
the mail (counted, never delivered to a box).
V1 envelope stamp (hmac) — HMAC-SHA256(session_key, 'zerg-team-mail-v1' || u16be(team_id) || u16be(from_id) || u16be(to_worker_id) || u16be(recipient routing identity))
(sol_zmq_frame_mac:mail_hmac/5). Binds WHERE the mail came from, not what
it says.
V2 content stamp (hmac2, hmac_v=2) — frame_mac(identity, 'zerg-team-mail-v2' || u16be(team_id) || u16be(from_kind) || u16be(from_id) || u16be(to_worker_id) || u16be(recipient routing identity) || u16be(priority) || u16be(timestamp) || u16be(subject) || u16be(sha256(canonical-JSON body))) (sol_zmq_frame_mac:mail_v2_material/9,
mail_hmac_v2/10). canonical-JSON is OTP json:encode field-value form
(sorted object keys, no whitespace, shortest float form; the current
server atom fallback hashes a JSON null as the STRING "null").
Verification rule on Luna (client/core/zmq_team_plane.lua +
client/core/team_mail_hmac.lua): hmac_v present → it MUST be 2 and
hmac2 MUST verify over the full content material (body/priority/timestamp/
subject included); a wrong/unknown version or a malformed frame is refused.
hmac_v absent → the v1 envelope stamp is verified (the documented
One-window compatibility posture). The v2 tamper battery lives in
client/tests/test_team_plane_hmac.lua; the cross-language vectors are
docs/fixtures/team_plane_hmac_vectors.json (mail_v2,
mail_v2_canonical, mail_v2_wire).
Documented window residual: while v1-only
frames are still accepted, an on-path attacker who can STRIP hmac_v/hmac2
can downgrade a captured push to the v1 envelope check, so a body-only
mutation would verify. The TRANSPORT PRECONDITION is explicit: this requires
the attacker to modify a Sol→Luna frame in transit, and there is no
per-frame MAC on the Sol→Luna direction (the frame-MAC plane is
Luna→Sol only; client/core/zmq_worker.lua records the deliberate posture).
In a supported deployment the direction is protected by the CURVE transport
handshake (or a tunnel); a plaintext non-loopback posture is refused without
an explicit dev-only ack. So payload modification is impossible under CURVE,
and the downgrade is directly exploitable only in the acknowledged
plaintext/dev postures. Impact is bounded to arbitrary content in the
RECIPIENT’s mailbox marked hmac_ok=true (prompt-injection grade) — the
downgrade cannot retarget another recipient or sender, because v1 still
binds {team, from, to} + the recipient routing identity.
Close condition (machine-checkable): Sol’s v2 sender is present on every
configured node AND a measured fleet window shows zero v1-window deliveries
(_mail_v1_window_deliveries on the worker; a v1 deliver is counted, a v2
deliver is not) → set LUNA_TEAM_MAIL_V2_ONLY=1 fleet-wide. That lever
refuses any push without hmac_v; the client test flips the compat-window
leg to quarantine under it. The dated owner/check obligation is the
`` row in plan/residual-register-v0856.md.
Canonical fail-closed edges: the v2 body hash is
wire-type-stable for the shapes OTP’s json:encode can sign — empty
array/object, float vs integer, -0.0, an explicit JSON null (as a value, an
array element and an object value), 2^53 (both integer and float), the
subnormal/top-range float forms, and the fixed/scientific cut. The typed
decoder (MessagePack.unpack_typed) carries the pre-msgpack distinction and
docs/fixtures/team_plane_hmac_vectors.json (mail_v2_wire) pins every row
with a FULL server-signed frame consumed by BOTH ends. Remaining edges are
availability-only, never admission bypasses:
an integer beyond 2^53: the NORMAL decode refuses the frame (LuaJIT
doubles cannot represent it exactly); the TYPED decode verifies the server
signature and the sanitized delivery carries the exact decimal string
Only for the unrepresentable value. An exactly-representable integer in
the SAME body (even when encoded as msgpack uint64) is converted back to
a Lua number, so one large integer cannot stringify the rest of the body
(; the mixed_int_recovery fixture row pins both delivered
types).
an explicit null OBJECT VALUE / array element: verified typed; the
delivered Lua table cannot carry a null value (a map value is dropped, an
array element is a hole) — the signature still bound the exact bytes.
non-finite (inf/NaN) or invalid-UTF-8 bodies: not producible by the
server’s JSON signer; the typed canonicalization refuses them typed.
a body key literally equal to the wire-tag key (\0msgpack_wire) could
only ever cause a canonical mismatch (quarantine), never an admission.
an untagged canonical gives the integer form for an integral number; the
typed path is what makes 1.0/-0.0 exact — both ends consume the
fixture, and a mismatch fails CLOSED (quarantine).
Mango→Sol Event Channel Authentication
The Mango→Sol cache-invalidation channel (sol_mango_zmq_bridge SUB ↔ Mango
PUB) previously subscribed to all topics with no signature/HMAC/CURVE/ZAP —
any host that could TCP-connect to Mango’s PUB socket could publish a forged
token.revoked/user.updated, forcing cache flushes (idempotent-safe, so
DoS-flavor rather than privilege escalation).
** fix:** Mango signs every PUB frame with an HMAC-SHA256 over the
canonical v2 material (same pattern Mango already uses for audit-archive
ingestion, audit_archive.py). Sol verifies the signature with a
constant-time compare before forwarding the event:
Wire format (v2, contract; Mango sender cutover
): 5-part multipart
[Type, Payload, Nonce, Ts, Sig] with
Material = u16be(len(Type)) || Type || Nonce || Ts || Payload
Sig = hex(HMAC-SHA256(Secret, Material)) (64-char lowercase hex;
Sol also accepts raw 32)
Nonce = 32 lowercase hex ASCII (16 random bytes)
Ts = ASCII decimal of wall-clock MILLISECONDS
Freshness: |now − Ts| ≤ zmq_bridge_ts_window_ms (default 120000,
inclusive both directions; Mango’s knob is MANGO_BRIDGE_TS_WINDOW_MS
MUST match Sol’s, a mismatch silently refuses legitimate
frames). Replay: a nonce already seen in sol_bridge_nonce_lru is
refused (nonce_replay). : the seen-set is
durable — every accepted nonce is appended + fsynced to
<data_dir>/mango_bridge_nonce.journal BEFORE the event is forwarded,
and start_bridge loads/compacts it before the socket admits, so a
captured HMAC-valid frame replayed within the ts window after a NODE
restart is refused (the signed material carries no seq; the journal is
the durable floor). A journal write failure fails CLOSED (the frame is
refused, no reservation is left behind). Mango signs at enqueue and re-signs at
drain with a FRESH nonce AND fresh ts — a re-sign with the original
nonce would replay at Sol’s LRU, and keeping the original ts would age
a ring-buffered frame past the window (Sol refuses those and ticks
zmq_bridge_ts_stale_total). The shared vector table
docs/fixtures/bridge_hmac_vectors.json pins the bytes across both
languages (mango/test/test_bridge_hmac_vectors.py +
server/test/sol_bridge_hmac_vector_tests.erl).
Legacy cutover: Mango NO LONGER SENDS the
legacy 3-part type‖payload material — the sender cutover is
one-way, and its inbound leg now requires v2 as well. Sol’s counted
legacy-accept clause was **REMOVED in **: any 3-part frame
is DROPPED (never forwarded, signature irrelevant) and bumps
zmq_bridge_legacy_hmac_total — the counter’s meaning flipped from
“counted accept” to straggler observation, and it must sit at zero in a
healthy fleet. A straggler count means a sender is still previous and
must be upgraded. The 2-part unsigned shape stays deliverable only in
the acknowledged no-secret posture (below).
Secret: Mango reads MANGO_BRIDGE_HMAC_SECRET (or
mango_bridge_hmac_secret config); Sol reads SOL_MANGO_BRIDGE_SECRET (or
mango_bridge_hmac_secret app env). They MUST match.
Fail-closed posture: **** boot-refuses any Mango
bridge socket without MANGO_BRIDGE_HMAC_SECRET, _verify_inbound
rejects unsigned frames, and Sol boot-refuses a configured
mango_pub_url without its secret (ack lever:
zmq_bridge_allow_unsigned). : Mango’s sign path
also fails closed — a secret-less _sign_v2 raises, so a misconfigured
transport can never emit frames. The PULL (Sol→Mango) inbound leg
remains on its older wire shape deliberately: it has no Sol
counterpart sender ( — Sol does not publish to Mango).
See server/src/sol_mango_zmq_bridge.erl (verify + drop) and
mango/mango/events/zmq_transport.py (sign).
Revocation propagation
token.revoked events are PUB-broadcast; events lost during Sol downtime
are re-pulled from Mango’s revocation ring (GET /auth/revocations? since_epoch=N — {epoch, entries:[user_uuid], oldest_epoch}; oldest_epoch
is the versioned field: the oldest epoch the ring can still answer,
null when empty). The pull is Bearer-authenticated and authorized: the
service token needs revocations:read, the bare * admin binding, or
the uuid on MANGO_REVOCATIONS_READ_USERS; a
zero-permission service token answers 403 (least privilege — the
shape let any service token enumerate the revoked-UUID oracle).
The bridge resyncs on (re)connect and on a periodic cadence
(zmq_mango_resync_ms, default 60s) and applies the entries idempotently
(the same action as a live token.revoked), advancing its epoch only on
success.
Wrap-gap invariant: the ring serves only the
last RING_SIZE (1024) entries. If Sol’s watermark fell further behind
than the ring can answer — detected via oldest_epoch (watermark + 1 <
oldest answerable) with an arithmetic fallback for older Mango responses
(NewEpoch − Epoch > len(entries)), — the resync escalates: every
Sol-side auth cache is flushed (the one-time repair covering the dropped
window), the ring epoch is ADOPTED, and the event is CRITICAL-logged +
counted (sol_zmq_bridge_resync_gap_total, the SolZmqResyncGap alert).
A watermark REGRESSION (Mango restart behind a journaled ring —,
) keeps its separate full-flush-and-resync-from-0 path.
Non-revocation auth events: role/team/user
change events ride lossy PUB/SUB only — a bridge disconnect delays a
privilege change to the per-user cache TTL. Bounded by the reconnect
resync, the per-user cache TTL, and auth_flush_on_reconnect (Sol,
Default true since then -: one full auth-cache flush per
bridge reconnect, so a DEMOTION made during an outage lands within the
reconnect window; an explicit false restores the previous costed
posture). The generic ?since= auth-event journal (the revocation-journal
pattern generalized) stays the tracked successor if the flush cost proves
operationally painful.
: the ring is durably journaled. Every revocation
path (logout, mass revoke, self-service password change, admin password
reset, user delete) appends to the append-only revocation_journal
table INSIDE its revocation transaction, and Mango’s boot reloads
MAX(epoch) + the last RING_SIZE rows before serving (a reload failure
refuses boot — a silent empty ring would make every pre-restart
revocation unreplayable while Sol trusts the watermark). A Mango restart
no longer resets the ring; Sol’s epoch-regression full-flush fallback
stays as the last resort. The revoke-all legs (password
mutations, user deletion) additionally emit token.revoked live
(byte-identical to logout’s shape) and journal the revocation, so a
Sol that missed the PUB replays it within one resync tick.
Justification (Air-Gapped)
In the project’s primary deployment model:
- Same-host deployment: Sol and Luna workers run on the same physical host (wild blueprint: runit + podman on the operator’s hardware)
- Private network isolation: ZMQ ports (
5555ROUTER,5556PUB) bind to the private podman bridge network, not exposed to the host interface - No cross-network ZMQ: All ZMQ traffic stays within the operator’s private network (podman bridge / LAN)
Under these conditions: Network-level access is controlled by podman’s network isolation An attacker who can reach the ZMQ port already has breached the podman network Loopback binds keep the plaintext dev posture (nothing leaves the host)
: cross-network ZMQ now defaults to CURVE-encrypted — the boot gate refuses an unencrypted non-loopback bind unless the operator explicitly acknowledges plaintext or declares an encrypted tunnel. The message-level gates above close the residual in-network threats (a compromised worker or a peer on a non-loopback bind forging frames into other users’ sessions).
Operational Requirements
When deploying ZMQ across network boundaries:
- Distribute the CURVE server key — the server public key lives in
<data_dir>/curve_server.cert(thepublic-keyline, z85); workers setLUNA_ZMQ_CURVE_SERVERKEYto it (same-host workers auto-discover the keyfile). Provision per-worker enrollment keys (zmq_enrollment_keys/SOL_ZMQ_ENROLLMENT_KEYS+LUNA_ZMQ_KEY_ID) rather than the shared fleet secret. - Restrict client keys —
zmq_curve_clientkeys(Z85 list) restricts WHICH clients can complete the handshake (the ZAP-equivalent authorization); defaultanyprovides confidentiality only. - Firewall rules — restrict ZMQ port access to known Luna worker IP ranges (defense in depth).
Transport posture config reference
| Config | Default | Meaning |
|---|---|---|
zmq_curve_enabled | auto | auto = CURVE on when the bind is non-loopback; true = always; false = never |
zmq_curve_secretkey | — | Server key (Z85 or 32-byte binary); unset → generated + persisted to zmq_curve_keyfile |
zmq_curve_keyfile | <data_dir>/curve_server.cert | chumak_cert-format keypair file (z85), mode 0600, gitignored |
zmq_curve_clientkeys | any | Allowed client public keys (Z85 list). any = unrestricted (confidentiality only); a CONFIGURED list must decode entry-for-entry or the bind REFUSES |
zmq_transport_plaintext_ack | false | Operator acknowledgement for non-loopback plaintext (CRITICAL-logged) |
zmq_transport_tunnel | "" | Declared encrypted tunnel (wireguard/mtls-sidecar) — satisfies the posture |
zmq_enrollment_keys | #{} | Per-worker keys: #{KeyId => #{worker_id, secret}} (config map or SOL_ZMQ_ENROLLMENT_KEYS JSON); secret ≥ 16 bytes or the boot refuses |
zmq_enrollment_revoked | [] | Revoked key ids (or SOL_ZMQ_ENROLLMENT_REVOKED, comma-separated); runtime add/remove via sol_zmq_enrollment:revoke_key/1 / unrevoke_key/1 |
zmq_fleet_legacy_compat | false | Fleet-secret registration window (deprecation 2026-11-01) |
zmq_register_rate_limit | 60 | Successful registrations/min before the anomaly alarm fires |
zmq_frame_mac_legacy | false | Fleet-legacy window for the extended agent/team MAC plane + the v2 (tx-less) material — missing/v2 legs REFUSE while closed; true is the recorded rollback lever |
zmq_frame_mac_d1542_legacy | false | Type-scoped window for the completion types: while true, required accepts + counts missing MACs on exactly those two types; missing MACs on every other type REFUSE. Rollback lever only — the default is fail-closed |
Implementation
See server/src/sol_zmq_sender.erl for the ROUTER socket setup (CURVE
server options from sol_zmq_curve:socket_opts/0) and
client/core/zmq_worker.lua for the DEALER socket connection (CURVE client
options + registration posture). Ownership gates live in
server/src/sol_zmq_ownership.erl (gate helpers incl. allow_result_frame/4),
server/src/sol_zmq_handler_worker.erl (registration HMAC + enrollment
keys + result/token/error + adoption proof), server/src/sol_zmq_handler_agent.erl
(event allowlist / acp / plugin frames), server/src/sol_zmq_handler_team.erl
(team frame gates), and server/src/sol_zmq_bg_task.erl (spawn parent
binding + seat gate). The per-pipe registration binding lives in
sol_zmq_pipe_binding.erl (the frame router consults it pre-handler;
chumak:recv_multipart_with_pipe/1 is the vendored transport surface);
the durable replay fence in sol_zmq_replay_fence.erl (loaded by
sol_zmq_indexes:ensure_tables/1). The boot refusals live in
sol_app:zmq_auth_boundary/0 + sol_app:mango_auth_boundary/0 +
sol_app:http_plaintext_boundary/0 (the HTTP plaintext mirror); the loss
policy in sol_zmq_recv_dispatcher (droppable_under_load/1 /
is_critical_type/1); the PUB-plane canonical shapes in sol_zmq_events.erl.
Execute-grade authority stamp: the
legacy_write_implies_execute lever was independently configured on both
sides of the wire; the task frame now carries Sol’s EFFECTIVE value
(additive key) and Luna applies min(Sol, Luna) at its no-escalation
clamp, so a split config (Sol off / Luna on) can no longer let a bare
:write grant authorize allow-all/auto on the worker. The field is
registered in ci/wire_field_provenance_lint.py.
Ownership matrix & index lifecycle
The result/token/error matrix is the code’s decision table in
sol_zmq_ownership:allow_result_frame/4 (all rows gated by
zmq_ownership_enforced). The decisive split is index hit vs index
miss; on a miss the eligible sender is derived from the recorded
executor, never from registration alone. The previous
“currently registered sender” grace has no row and no code path:
| Index state | Eligible sender | Code branch / note |
|---|---|---|
| Owner identity matches sender, sender registered | yes | task_sender/2 {ok, Identity} + is_registered/2 |
| Owner identity matches sender, sender not registered | no | owner-match leg requires current registration → auth_failure/3 |
<<"queued">> sentinel row | none | {error, queued_task}; a queue seat has no eligible sender |
| Index miss, sender unregistered | no | is_registered/2 false → auth_failure/3 (a never-registered DEALER can never forge a predictable id) |
| Index miss, sender registered, recorded executor == sender | yes (WARNING) | sol_task_store:get_last_executor/1 match → bounded post-restart grace, attributed <<"system">>; the synthetic-task guard still applies |
| Index miss, sender registered, no recorded executor | no | _ -> refusal + auth_failure/3 |
| Index miss, sender registered, foreign recorded executor | no (CRITICAL) | mismatch arm: “grace-leg rewrite rejected” + auth_failure/3 |
The ownership-index sweep is liveness-aware: ?TASK_TTL_MS (1h) means
“idle 1h”. Heartbeat and accepted result/token/error frames refresh the row
timestamp (sol_zmq_indexes:touch_task/1); the sweep deletes only rows
that are older than the TTL AND not a busy worker’s current task AND not
queued AND not store-pending. An unreachable gateway suspends the sweep
(retention-fail-safe). Boot reconcile repopulates the
index for every outstanding dispatch receipt inside gateway init — before
the transport tail accepts a single worker frame — and re-stamps the
receipt’s executor snapshot into the requeued task row. The warning-grace
row above therefore only fires for a matching recorded executor; an
outbox-known task with no matching executor is refused, not waved through.
The zmq-<ms>-<counter> task-id namespace is server-reserved
({error, reserved_task_id} for caller-supplied collisions); the
registration HMAC binds nonce || identity || worker_id || child_depth || u64(ctr).
Caller-supplied task-id collision gate: ANY
caller-supplied id already present in the ownership index, the task store
(pending OR terminal) or the dispatch queue refuses with the typed
{error, task_id_in_use} + sol_zmq_task_id_in_use_total — the pre-fix
shape only guarded the zmq- prefix, so a caller id colliding with
another user’s live/queued/terminal task overwrote the ownership-index row
and the queue/pending state (user A’s results resolving to user B’s
ownership). The check runs inside the single gateway dispatch writer, so
of two concurrent duplicates exactly one wins; the original ownership
stays intact in every case.
Frame bounds: the encoder-side cap mirrors the
10 MB recv bound on BOTH ends: sol_zmq_protocol:encode_message/1 refuses
any frame over sol_zmq_protocol:max_msg_size/0 with
{error, {message_too_large, Size}} (typed, nothing on the wire), and
Luna’s ffi/zmq.lua drains the remaining RCVMORE parts of an oversize
message before erroring (no false reconnect, no multipart desync) with the
same 10 MB aggregate multipart budget (the pre-fix shape materialized up
to 1024×10 MB). The default Luna worker id gained a pid + per-process
suffix (luna-<epoch>-<pid>-<seq>-<rand>), killing the same-second
self-collision that fired the duplicate-identity path on innocent
launches.
Engine reference — generated from the canonical engineering source. Do not edit this page by hand.
Network Egress — Luna Sandbox Posture
This page states what Luna’s sandbox actually enforces for network egress, and
what it does not. The decision record with the measured spike is
plan/egress-control-evaluation.md.
The tracked residual row is in
docs/known-security-gaps.md.
Bottom line: the default is a kernel-enforced all-or-nothing network namespace. There is no domain-scoped egress boundary. When an operator enables egress, a compromised tool process can reach any address it can route to (raw IPs included). The domain allow/deny lists are advisory for the in-process web path (and, on macOS, a host-name override for spawned children); on Linux a configured policy simply disables child egress. Neither is a packet filter.
Configuration matrix
The sandbox keys are execution.sandbox.* (client/core/sandbox.lua,
client/core/config.lua):
| Configuration | bwrap argv | Effective egress |
|---|---|---|
network = false (default) | --unshare-net | none — private netns, kernel-enforced |
network = true, no network_policy | no --unshare-net | full host egress |
network_policy = {... } (any truthy value) | --unshare-net | none — the policy’s presence isolates the child; the allowlist is not an egress gate |
bwrap = "off" (any network value) | no bwrap | no network isolation (Landlock is write-only) |
On macOS the seatbelt profile emits (deny network*) when network is disabled
and, with network = true plus a policy, only host-name deny rows
((deny network* (host <domain>))) for the policy’s deny list. The allowlist
is not enforced there either.
MCP stdio servers under execution.sandbox.mcp_stdio_containment use the same
network decision as the shell builder.
What network_policy means
execution.sandbox.network_policy is a table with mode = "allowlist" | "open", allow = {...}, deny = {...} (client/core/network_policy.lua).
It has two consumers, with different semantics:
- Spawned tool children — the presence of the key adds
--unshare-net. The staged/etc/hostsfile still exists, but the namespace has no external interface to resolve or route over, so the policy cannot authorize egress. On Linux bwrap there is currently no way to combine a domain allowlist with child egress. - In-process web tools —
network_allowed/1andhost_allowed_by_policy/3(client/core/web_fetch_shared.lua) check the URL hostname against the allow/deny globs before the request. The fetch transport validates private addresses and pins the resolved addresses (CURLOPT_RESOLVE), and deliberately bypasses proxy environment variables (CURLOPT_NOPROXY="*") so a proxy cannot void the pin.
Bypass class (accepted residual)
When child egress is enabled (Linux: network=true without a policy; macOS:
network=true), the domain policy does not stop these, and this page does not
claim otherwise:
IP literals — a child can connect straight to an address. Deny globs
match names, not destinations. In-process web tools reject private/link-local
literals but not public ones as a policy decision.
DNS answer substitution / rebinding — a spawned child has no per-connect
address pin and no private-address guard; an allowed name can resolve to an
internal address. The in-process web path is stronger (private-IP checks +
per-hop address pins), but that is a separate transport control.
IPv6 / AAAA — the hosts-file deny emits only 0.0.0.0 <domain>, with no
:: entry. AAAA resolution still reaches DNS. The spike in the decision
record observed real AAAA answers and a successful curl -6 resolution
under an IPv4 hosts deny.
Direct-connect libraries, custom resolvers, DoH/DoT, QUIC/UDP — a
process can ignore /etc/hosts, HTTP proxy variables, and the policy module
entirely.
0.0.0.0 is not a blackhole — on Linux, connecting to 0.0.0.0
reaches loopback. A “denied” name can therefore reach a local service on the
same port (measured).
Environment confinement is not an egress control either: --clearenv plus the
ENV_ALLOWLIST (client/core/sandbox.lua) does not forward proxy variables,
and forwarding them would still be advisory.
Operator guidance
Keep execution.sandbox.network = false unless the task genuinely needs
the network. That posture is the only one with a real egress boundary.
Do not treat a configured network_policy.deny list as a firewall. If a
host-level guarantee is required, enforce it outside Luna (host firewall,
egress gateway, or a dedicated network segment); none of those are
per-task domain policies.
bwrap = "off" (or a zero-layer posture) removes network isolation
entirely. The sandbox layer matrix in docs/security.md documents the
general posture; this page covers the egress specifics.
Provider credential variables are scrubbed from the child environment by the
env allowlist/sanitizer; that reduces the value of an egress channel but is
not a substitute for network control.
Status
Accepted risk. No enforcement leg was landed. A proxy-env + private-CA design was rejected as enforcement (advisory, conflicts with the SSRF pin, adds a CA asset, no raw-IP coverage). An nftables/cgroup-netns design is the right future family but requires host provisioning and an IP/DNS policy story. The decision record carries the owner, review date, and revisit triggers.
Engine reference — generated from the canonical engineering source. Do not edit this page by hand.
TLS Posture — Per-Plane Reference
This page states the TLS/transport posture of each ZERG plane as implemented
in the tree. It is a map, not a promise that every plane is TLS: several planes
are plaintext by design or by documented residual, and one plane (Sol↔Luna)
uses CURVE rather than TLS. The Sol↔Luna mTLS decision is
plan/mtls-decision.md.
| Plane | Transport protection | Peer authentication | Status |
|---|---|---|---|
| Sol HTTP API (Cowboy) | Optional TLS (tls_enabled) | Server cert only; client certs not requested | TLS available; plaintext refused in prod non-loopback unless acked/tunnel |
| Sol → Mango (auth/identity) | One-way TLS client (mango_tls) | verify_peer + optional mango_ca_file | TLS available; plaintext non-loopback refused in prod |
| Mango listener | No TLS listener in Mango | Terminated by the wild edge proxy | Edge termination (wild-owned); mTLS client-cert leg not implemented |
| Sol → PostgreSQL (memory pool) | Optional TLS (memory_pg_ssl) | verify_peer + required CA | Opt-in; default off (single-host bridge) |
| Erlang distribution | TLS template (ssl_dist.conf.example) | verify_peer + fail_if_no_peer_cert when active | Design + template landed; wild activated on the live cluster 2026-09-22; epmd stays plaintext by design |
| Sol ↔ Luna (ZMQ) | CURVE (X25519 + XSalsa20-Poly1305) default on non-loopback | Server key pinned by workers; worker authenticated by enrollment HMAC + per-frame MAC | CURVE + HMAC; mTLS declined (see decision) |
| Luna → providers / web | TLS with peer verification pinned; per-hop address pins | Server cert (VERIFY_PEER=1); no verification-less path | Enforced in the Luna transport |
| Sol → providers / OAuth / license / health probes | TLS with verify_peer + CA resolution | Server cert | Enforced; per-module CA resolution |
| Sol → event archive (Mango) | HTTP(S) with verify_peer; loopback exception | Server cert; CA pinned when mango_ca_file is set | Enforced |
Sol HTTP API
Configuration (server/config/sys.config, docs/configuration-reference.md):
tls_enabled = true binds a TLS listener; tls_cert_file / tls_key_file
are required and readable, otherwise the boot refuses outside dev (or
falls back CRITICAL-logged in dev, or with tls_plaintext_ack=true).
tls_ca_file adds cacertfile to the listener options when the file
exists (server/src/sol_http.erl). That is a CA bundle for the listener,
not a client-certificate requirement: the listener does not set
verify_peer or fail_if_no_peer_cert, so mTLS is not enabled by setting
tls_ca_file.
A non-loopback plaintext HTTP bind in deployment_mode=prod refuses boot
unless the operator sets http_transport_plaintext_ack=true or declares a
terminator/tunnel via http_transport_tunnel
(http-terminator, wireguard, mtls-sidecar). The ack is
CRITICAL-logged; the tunnel declaration is not a substitute for inspecting
the actual upstream.
Sol → Mango
mango_tls=true gives Sol a one-way verified TLS client:
{verify, verify_peer} plus mango_ca_file when set
(server/src/sol_mango_client.erl). In prod, a non-loopback Mango URL without
TLS refuses boot. Mango itself has no TLS listener; the wild topology
terminates TLS in front of it. Client certificates are not validated by
Mango today (the known-security-gaps Mango row tracks the remaining
client-certificate leg as wild-owned).
Sol → PostgreSQL
memory_pg_ssl=true requires memory_pg_ca_file and connects with
verify_peer (server/src/sol_pg_pool.erl). An ssl-without-CA connect is a
typed refusal, never blind encryption. The default is off, matching the
single-host bridge posture; remote-PG TLS is an operator opt-in. URL query
parameters (?sslmode=...) are not parsed by the pool — use the dedicated
keys.
Erlang distribution
The TLS dist design and the corrected single-term option file are in
server/config/ssl_dist.conf.example; activation is -proto_dist inet_tls +
-ssl_dist_optfile in the rendered vm.args (wild-owned host leg; see
docs/production-flip-checklist.md). Both legs use verify_peer +
fail_if_no_peer_cert. The distribution cookie remains the admission
credential — TLS adds confidentiality and node identity, not authorization.
epmd stays plaintext by design (it cannot speak TLS); the residual is name
enumeration + registration DoS on the LAN.
Sol ↔ Luna (ZMQ)
This plane is not TLS; it is CURVE + application-layer HMAC:
CURVE is default-on whenever the bind is non-loopback
(zmq_curve_enabled=auto). The server keypair is generated/persisted at
curve_server.cert (0600); workers pin the public key. Under the Option A′
migration, client keys are ephemeral and zmq_curve_clientkeys=any:
CURVE is confidentiality + server authentication, not worker authorization.
Worker registration is authenticated by a per-worker enrollment HMAC over
nonce + identity + worker_id + child_depth + monotonic ctr.
Every worker-plane frame carries a trailing HMAC bound to the session key,
routing identity and monotonic tx; the durable replay fence closes replay
across node restarts.
A non-loopback plaintext bind in prod refuses boot unless explicitly acked
or declared as a tunnel.
The mTLS alternative (client certificates for this plane) was evaluated and
Declined; see plan/mtls-decision.md for the threat-model delta, key
distribution, and revisit triggers.
Outbound provider and web transports
Luna’s transport pins CURLOPT_SSL_VERIFYPEER=1 and has no
verification-less fetch path; a caller asking for verify_peer=false is
refused (or proceeds with verification under the explicit
LUNA_ALLOW_INSECURE_TLS=1 ack, which can only ever weaken to the same
verified behavior). Web/MCP fetches resolve and pin addresses per hop
(CURLOPT_RESOLVE), and pinned requests set CURLOPT_NOPROXY="*" so a proxy
environment cannot void the pin; provider fetches are configured destinations
and are not address-pinned the same way. Sol’s provider, OAuth, license and
health-probe clients use
verify_peer with CA resolution (server/src/sol_cacerts.erl and the
per-module call sites).
Known gaps (not closed by this page)
HTTP listener client-certificate (mTLS) enforcement is not implemented.
Mango client-certificate validation is not implemented (wild edge-proxy
leg).
Erlang distribution epmd remains plaintext.
PostgreSQL TLS is opt-in and the pool does not parse sslmode URLs.
The Sol↔Luna plane uses CURVE, not TLS; mTLS is declined, not “planned”.
See docs/known-security-gaps.md for the tracked rows and owners.
Engine reference — generated from the canonical engineering source. Do not edit this page by hand.
Consent: what a repository can change — and what it can never change
Luna treats project-local files as untrusted input. Cloning a repository
and running luna inside it must not silently disable the sandbox, redirect
your credentials, execute repo-shipped code, or hand your fleet a different
toolbox. This page is the consolidated model. The code
authorities are:
| Concern | Authority |
|---|---|
| Approval path/record validation/atomic write/TTY prompt | client/core/approvals_store.lua |
| Repo-config security families + strip | client/core/repo_config_security.lua |
| Repo-config consent hash/marker | client/core/repo_config_trust.lua |
| MCP definition + tool-manifest approval | client/core/mcp_config.lua |
| MCP manager gate (discovery/refresh/notification) | client/core/mcp_manager.lua |
| Extension consent (manifest + source bytes) | client/core/extension_consent.lua |
| MCP elicitation operator surface | client/core/mcp_elicitation.lua |
| Consent census lint | ci/luna_consent_lint.py + ci/luna_consent_registry.json |
The trust boundary
Consent records live in user-owned storage:
~/.luna/approvals/. A marker inside the repository (for example a
.luna/trust file) is deliberately never used — the attacker who ships
the repository also ships the marker. Only core.approvals_store constructs
approval paths; every other module asks it.
Three record namespaces are preserved for compatibility:
| Plane | Record filename | Content bound |
|---|---|---|
| Repo config + repo tools | trust-<sha256>.json | Security-family subtree in merge precedence order; .luna/agents permission_override values; repo tool file contents |
| MCP | <sha256>.json | Normalized server definition + discovered tool manifest |
| Extensions | extension-<sha256>.json | Canonical manifest + sorted content hashes of every .lua under the extension dir |
New records carry v=1 and kind. Existence is no longer approval:
a corrupt/truncated record, a record whose hash or kind names a
different identity, or an unknown record version is treated as absent
(fail closed). Legacy records without those fields — including bare {}
markers — remain readable. Writes are atomic (FFI.atomic_write: mkostemp
0600 from birth, fsync, checked rename), so a credentialed record is never
world-readable and a crash cannot leave a torn row.
What a repository may change — with consent
Security-relevant keys sourced from .luna.json, .luna/settings.json or
.luna/settings.local.json apply only with a matching trust- record:
execution.* (sandbox posture, network, bind roots),
permission_* (mode, overrides),
server_permissions,
workspace, workspace_root,
extensions_enabled, agents_dir, local_agents_dir, mode,
provider_base_url, api_key, api_keys, auxiliary,
fallback_providers, otel_endpoint,
classifier — the AI permission-classifier’s provider plane
(enabled/model/provider/base_url); base_url is a network
destination, so a repo cannot redirect classifier traffic without
approval,
providers — settings-level custom provider definitions
(base_url/wire_format/models/api_key_env); both the destination and
the credential source, so a repo cannot add or redirect a custom endpoint
without approval.
Without a record:
Interactive session (TTY): Luna prints the family list and asks once
([y/N]); only an explicit y/yes writes the record;
Headless/agent/CI: the keys are ignored (stripped) with a loud
stderr warning and a counter. The sandbox default stays ON.
The hash is content-derived: editing the security subtree invalidates the
record and re-asks. The permission-mode permission_override scan is part
of the same hash (one approval covers both file sets). config.lua records
the provenance of project-carried provider keys and provider.from_model
independently refuses a repo-carried destination while consent is false
(defense in depth against a future strip bypass).
Project MCP servers
.luna/mcp.json servers (stdio and HTTP) never start without a
definition-keyed mcp record. HTTP servers are not exempt: a repo URL is an
SSRF-into-context primitive even though it executes no local code.
Since the approval also binds the discovered toolbox:
first discovery with a legacy (no tools_hash) record is TOFU-stamped
silently — no re-prompt, because the definition was already approved;
a changed manifest prompts with a bounded added/removed/changed summary
on a TTY. A decline or a non-TTY session means the changed tools are
Not registered, the server is stopped, and the typed degradation
mcp_tools_changed:<server> is surfaced;
the gate runs after discovery, before registration, on deferred
notifications/tools/list_changed refreshes, and on reconnect/refresh;
global ~/.luna/mcp.json servers are user-owned and are not gated.
A definition change produces a new approval key; its prompt lists the changed field names only (never env/header/auth values).
Project extensions
A repo’s .luna/extensions/*/extension.lua is repo-shipped code. It
loads only with a source-bound extension- record:
the record binds the canonical manifest plus the sorted content hashes
of every .lua under the extension directory;
the loader passes the exact extension.lua bytes it is about to execute
into the consent call, so a rewrite between approval and load cannot slip
through;
any manifest or source edit re-asks. Without a record and a TTY the
extension is refused and reported in the failed list;
the scanner and sandbox env remain defense-in-depth;
user-level ~/.luna/extensions is user-owned and unaffected.
MCP elicitation
Server-initiated elicitation/create requests are operator-mediated:
the client advertises the capability only when the manager registered a
handler (mcp_elicitation_enabled defaults ON);
params are redacted and capped before any event/log; URLs are displayed,
never fetched; tokens are never logged;
default/headless is decline. An in-process responder may accept,
decline, or cancel — there is no auto-accept path.
What a repository can never change
Write or replace an approval record (the store is under the user’s home,
never the repository; repo-writable markers are ignored).
Get a corrupt, truncated, foreign-hash, foreign-kind, or unknown-version
record treated as approval.
Apply a security family or start a project MCP server / extension without
a matching record in a headless session.
Redirect classifier or provider traffic without the trust- record.
Change an approved extension’s source or an approved MCP server’s toolbox
without a re-ask.
Make elicitation auto-accept, fetch a server-supplied URL, or log a
credential.
Operator notes
Re-approve by running Luna interactively in the project once.
Inspect records with any JSON reader under ~/.luna/approvals/; delete a
record to revoke that approval (the next interactive run re-asks).
client/tests/test_consent_unification.lua,
test_mcp_approval_renewal.lua and
test_mcp_elicitation_operator.lua pin these contracts. The
ci/luna_consent_lint.py census (with ci/luna_consent_registry.json)
fails if a security family loses its consent row, if any module outside
the store constructs an approval path, or if the extension source binding
disappears; its CI manifest wiring lands with the next lint-suite batch.
Engine reference — generated from the canonical engineering source. Do not edit this page by hand.
Luna Cryptography Backends (SHA-256 / HMAC)
Luna’s digest path — client/core/age_crypto.lua — feeds the ZMQ session-key
derivation, per-frame MACs, worker READY registration HMACs, consent hashes,
and task/extension fingerprints. Since ** (PC-3)** that path is
Zero-fork by default: no openssl process is spawned unless the operator
explicitly opts in.
Backend ladder
sha256_hex(data) resolves the first usable layer, memoized for the process
lifetime:
| # | Layer | Label | Notes |
|---|---|---|---|
| 1 | Global ffi.C OpenSSL symbols | ffi-global | Production Luna statically links libcrypto. |
| 2 | ffi.load candidates | ffi-loaded:<name> | crypto, libcrypto.so.3, libcrypto.so, libcrypto.3.dylib, libcrypto.dylib — the same ordered list as ffi/sha1.lua. |
| 3 | OpenSSL CLI (opt-in) | cli | Only when LUNA_SHA256_CLI=1 (or true), or via the legacy forced-classification test seam. Writes through cel.secure_tmpfile and runs openssl dgst -sha256 -hex; one process per digest. |
| 4 | Pure-Lua SHA-256 | pure-lua | client/ffi/sha256.lua (FIPS 180-4 / RFC 6234). Always present, so the ladder normally never reports none. |
AgeCrypto.sha256_backend_label returns the selected label for diagnostics.
none is reachable only through the test seam or a broken tree.
Smoke test, not symbol presence. Every FFI handle — global first, each
loaded candidate after — must produce the correct SHA-256 of the empty string
before it is accepted (e3b0c442…b855). The pre- probe trusted
pcall(function return ffi.C.EVP_sha256 end), which accepted a handle that
declared symbols but could not digest. A failed smoke test falls through to
the next candidate.
sha256_backend_available never probes which openssl on the default path.
The capability probe is armed only by the env opt-in or the legacy test seam,
and its verdict is memoized (one probe per process at most).
HMAC construction
hmac_sha256_hex(key, data) is unchanged by the ladder work: textbook
RFC 2104 over sha256_hex (ipad/opad, keys longer than 64 bytes are
pre-hashed). It therefore inherits whichever zero-fork backend resolved.
The nil-backend contract from holds: if no layer can digest the
result is nil, "no_crypto_backend", never a raw Lua error.
CLI opt-in
LUNA_SHA256_CLI=1 # default: unset/off
Use it when OpenSSL throughput on very large buffers matters more than fork
avoidance (for example bulk hashing outside the MAC’d planes). It is not
recommended for the ZMQ frame path: each digest is a process spawn plus a
temporary file. Values other than 1/true leave the CLI layer off.
Tests
client/tests/test_age_crypto_zero_fork.lua — NIST SHA-256 vectors
(including the 1,000,000-byte 'a' vector), RFC 4231 HMAC vectors, default
zero-io.popen/os.execute assertions, candidate order, smoke-test
rejection of broken handles, the real backend seam
(_set_sha256_backend_for_test), the mocked CLI leg, and a pure-Lua vs FFI
cross-check on FFI-capable hosts.
client/tests/test_age_crypto_sha256.lua — NIST vectors, label shape.
client/tests/test_age_crypto_hmac_backend.lua — the nil-backend contract
(cases a–e) plus the pure-Lua digest-path seam (case f).
client/tests/test_ready_hmac_behavioral.lua — the ZMQ READY HMAC against
the Sol-side construction.
Benchmark (pure-Lua vs FFI)
Measured 2026-10-17 on an AMD Ryzen 9 7950X (x86_64), LuaJIT 2.1 (JIT on),
best of 3 runs. ffi-loaded:crypto was the resolved auto backend.
| Input | Pure-Lua | FFI (EVP) | CLI (opt-in) |
|---|---|---|---|
| 64 B | ~4.8 µs/op, ~13 MB/s | ~2.6 µs/op, ~23 MB/s | not measured |
| 1 KiB | ~25 µs/op, ~39 MB/s | ~2.9 µs/op, ~333 MB/s | ~76–92 µs/op (fork-dominated) |
| 64 KiB | ~1.45 ms/op, ~43 MB/s | ~27 µs/op, ~2.3 GB/s | not measured |
| 1 MiB | ~42 ms/op, ~24 MB/s | ~0.4 ms/op, ~2.5 GB/s | not measured |
A MAC’d ZMQ frame hashes agent-sized material (tens to hundreds of bytes), so
the pure-Lua floor costs roughly 5–10 µs per HMAC (two digests) versus a few
microseconds on FFI — while avoiding the former per-digest CLI fallback’s
process spawns and temporary files (two of each per HMAC). LUNA_SHA256_CLI=1
remains available for operators who prefer OpenSSL on large buffers.
Operational risks
Dynamic libcrypto duplication. If the host process already links a
libcrypto that does not export the EVP symbols to ffi.C (static or
version-skewed), the ladder ffi.loads another copy. Loading a second
libcrypto is safe for hashing but costs address space and can surprise
allocator/atexit behaviour; the global-first order avoids it on the normal
static build.
Performance floor. The pure-Lua backend is intentionally the last layer;
it is fast enough for MAC-sized inputs but roughly two orders of magnitude
slower than EVP on MiB-scale buffers. Operators with bulk hashing should
keep libcrypto resolvable or opt into the CLI.
Process-lifetime memoization. The selected backend is cached. Tests use
_set_sha256_backend_for_test(kind) (ffi | pure-lua | cli | none |
auto) or _reset_sha256_backend_for_test to re-resolve; production
never mutates the backend at runtime.
Engine reference — generated from the canonical engineering source. Do not edit this page by hand.
Boundary option contracts — the vendored-library truth chain
Class: Sol calls vendored libraries (erlexec, gun, msgpack, chumak, epgsql) with literal option tuples. Every gate this repo ran could pass a permanently broken boundary call:
| Gate | What it checks | Why it missed G77 |
|---|---|---|
| xref | calls exist with that arity | option contents are data |
| mock_parity_lint | mock function/arity vs production | fun(_Cmd, _Opts) -> … is parity-perfect and content-blind |
| pin tests | what WE pass | pins the bug as the contract when the knowledge is wrong |
| dialyzer (absent) | success typing | would flag the exec class, NOT the gun class (map types admit extra keys) |
The concrete 2026-09 event: the closeout “fixed” the registry rsync
leg by moving {timeout, …} into exec:run/3’s third argument — a real but
non-throwing option — while element 1 of the same list,
{stdout, stderr_to_stdout}, threw Invalid stdout option stderr_to_stdout
on every call. The fix was written from the memory of the correct
sol_gpu_probe.erl lesson (“{timeout, Ms} is NOT a valid erlexec 2.3.4 cmd
option — verified”, ) without executing the boundary once. Five
siblings shipped the same way: gun transport_opts in the OAuth store and
plugin-bridge https paths (gun 2.x refuses with {error, {options, …}} —
the open failed CLOSED, an availability defect, not a silent TLS downgrade),
the bare stderr_stdout atom in the offsite backup ({invalid_option, stderr_stdout} on every invocation), {stdin, [Data]} in the keyring (the
tuple value is a FILENAME; data-at-spawn does not exist), and {stdout, ""}
in the container paths ("" is an empty redirect FILENAME — the port
answers “stdout - atom or string value in tuple required”).
Two further properties of the same boundary, both now machine-pinned:
Sync-mode erlexec timeouts do not bound the child. run/3’s Timeout
bounds only the spawn RPC; wait_for_ospid_exit/4 is a receive with no
after. A “timeout” rsync ran until it finished. Killing the Erlang
worker does not kill the OS child either (no link/monitor ⇒ no
caller-death cleanup) — the proven orphaned-rsync case behind the
registry prepare staging reappearing after cleanup.
The exec port’s list-form argv is execve(2) — no PATH lookup. A
bare "rsync"/"secret-tool" argv head answers
{error, [{exit_status, 256}]} (“cannot execute”) on every host even
with a valid option list; binaries must be resolved
(os:find_executable/1) before the call. Also: a single-element list of
one string IS that string, and erlexec routes printable-string commands
differently from true argv lists. And wait_for_ospid_exit reports the
RAW waitpid status (exit(1) arrives as {exit_status, 256},
exit(3) as 768).
The three-mechanism prevention chain
- Golden option-spec lint —
ci/boundary_option_golden.json(accepted option sets extracted from the vendoredcheck_cmd_options/ guncheck_options/ msgpackoptions/ epgsqlconnect_optionsources, sha256-tripped to the vendored files) +ci/boundary_option_lint.py: every literal option list atexec:*/gun:open/msgpack:*/chumak:set_socket_option/epgsql:connectcall sites inserver/srcmust be in the golden for that library+version. The epgsql leg ( ) validates BOTHconnect_optsshapes with one key set — the list-formconnect(Host, User, Pass, [{Key, …}])arms and the flat map-formconnect(#{Key => …})probe — and value-checkssslto boolean | required. A vendored bump without a golden refresh fails loudly;--refreshre-pins (review the sets in the same change). This is the machine-checked-constants doctrine: the library truth lives in an artifact the linter executes, never in prose or memory. - Boundary-truth CT —
server/test/sol_boundary_contract_SUITE.erl: one case per boundary asserting LIBRARY ACCEPTANCE against the real compiled libraries (never a mock), including a real rsync transfer throughsol_registry:do_rsync/2, real gun opens for the OAuth and plugin-bridge maps, the real stdin-data path, and a container drill on no-op runtimes. Re-introducing any pre-fix shape reds the suite (the mutation proof is in the phase record). This is the only mechanism that catches “key accepted but not consumed” and version drift that slips a golden refresh. - exec chokepoint —
sol_exec:run/2,3(+run_watch/5,run_with_stdin/4,stop/1): non-sync spawn with themonitoroption, a receive-afterTOTAL timeout, a guaranteedexec:stopon expiry (bounded mailbox drain), flat-binary output, stdin data via post-spawnexec:send, and a watch protocol that reports the exec child handle so a backstop killer can take the OS child down with its Erlang worker (sol_registry’s prepare leg). Enforced byci/exec_chokepoint_lint.py+ci/exec_run_sites_baseline.txt(shrink-only): the remaining raw sites are the non-sync long-lived streaming spawns where a sync chokepoint does not apply.
Rules for the next boundary fix
- Do not fix from memory or prose — run the boundary once (the boundary
CT is the harness;
sol_test_helpers:ensure_erlexec_root_user/0already solved the exec-port root shim). - New literal option shapes must land in the golden in the same commit
(
--refreshre-pins hashes; sets are reviewed by hand against the new vendored source). - New bounded OS command →
sol_exec:run/2,3, never a rawexec:run(the chokepoint lint rejects new raw sites). - Data to a child’s stdin →
sol_exec:run_with_stdin/4(post-spawnexec:send); there is no data-at-spawn option in erlexec. - Resolve binaries (
os:find_executable/1) before list-form exec calls; argv heads areexecved verbatim.
Owners: the golden + lints live in ci/ (required lint-suite battery),
the boundary CT in server/test (required server-ct battery), the
chokepoint in server/src/sol_exec.erl. See
plan/archive/v0748-v0763-post-release-truth-hardening/phase--boundary-option-truth.md for the implementation
record and D-numbers.
Engine reference — generated from the canonical engineering source. Do not edit this page by hand.
Provider Setup Guide
Sol routes inference through two paths:
- Local inference — llama.cpp processes managed by Sol on the same machine
- Remote providers — API calls to Anthropic, OpenAI, xAI, z.ai, Ollama,
Gemini, DeepSeek, Alibaba, AWS Bedrock and Xiaomi via Sol’s resolver, plus
declarative OpenAI-compatible providers loaded from
priv/providers/*.json
Local Inference (llama.cpp)
Prerequisites
llama.cpp compiled with CUDA, Metal, or CPU support GGUF model files in a model directory Sufficient GPU/CPU memory for the target model
Step 1: Place Model Files
Put .gguf files in a directory accessible to Sol:
# Default source directory (NFS)
ls /fun/models/*.gguf
# Or configure a custom path
# In sys.config: {model_source_dir, "/data/models"}
Step 2: Discover Models
zerg discover
# Discovered 12 models
Sol scans the source directory recursively for .gguf files and generates slug names from filenames.
Step 3: Start a Model
zerg start glm-4.7-flash
# With a parameter template
zerg start glm-4.7-flash --template coding
# With parameter overrides
zerg start glm-4.7-flash --temp 0.3 --batch-size 4096
Step 4: Run Inference
# OpenAI format
zerg run --model glm-4.7-flash "Explain quicksort"
# Anthropic format
zerg chat --model glm-4.7-flash "Explain quicksort"
Parameter Templates
Predefined parameter sets selectable via --template:
| Template | temp | top_p | min_p | batch_size | top_k |
|---|---|---|---|---|---|
default | 1.0 | 0.95 | 0.01 | 2048 | — |
coding | 0.3 | 0.95 | — | 2048 | — |
chat | 0.7 | 0.9 | — | 2048 | — |
reasoning | 0.6 | 0.95 | — | — | 40 |
Model Sync (rsync)
For NFS-mounted model directories, Sol can sync models to local disk:
zerg prepare glm-4.7-flash
# Syncs from model_source_dir to model_store_dir via rsync
This is faster for inference because it avoids NFS latency during model loading.
Remote Providers
When local inference is unavailable or a specific model is only available via API, Sol can proxy requests to remote providers.
Model Resolver
Sol uses a local-first resolution strategy:
- Check for a local running model matching the name
- If local model exists but circuit breaker is open, skip to remote
- Look up model in the global cluster catalog
- Route to the first available remote endpoint with open circuit breaker
Provider health (/api/v1/provider-health)
Health is probed per transport identity — {provider/key, endpoint, request_path} — never per model or alias, so N aliases of one provider cost
one probe. The probe uses the provider’s real request path with its
credentials (a side-effect-free pool key peek; no rotation/usage charge).
Verdicts:
| Probe result | Status |
|---|---|
| 2xx | available |
| 401 / 403 | available_unauthorized (reachable; credential problem) |
| 404 / 405 / 429 / other 4xx | available (reachability success — never degraded) |
| 5xx | degraded |
| connect/timeout failure | unavailable |
| no endpoint (registered-only adapter row) | unconfigured (never probed) |
Probes are cached ~60s per transport identity.
Circuit Breaker
Each provider endpoint is protected by a circuit breaker:
| State | Behavior |
|---|---|
| closed | Normal operation. Requests flow through. |
| open | Requests rejected. All traffic returns error. |
| half_open | One request allowed through to test recovery. |
Configuration:
| Key | Default | Description |
|---|---|---|
circuit_breaker_failure_threshold | 5 | Failures before opening |
circuit_breaker_window_ms | 60000 | Failure counting window |
circuit_breaker_cooldown_ms | 30000 | Time before half-open |
CLI:
# Check circuit states
zerg circuits
# Force reset a circuit
zerg circuits-reset my-model
Error Classification
The resolver classifies errors as transient or permanent:
| Error | Classification | Circuit impact |
|---|---|---|
timeout | Transient | Counts toward threshold |
connect_failed | Transient | Counts toward threshold |
connection_down | Transient | Counts toward threshold |
| HTTP 429 (rate limit) | Transient | Counts toward threshold |
| HTTP 503 (unavailable) | Transient | Counts toward threshold |
| HTTP 4xx/5xx (other) | Permanent | Counts toward threshold |
invalid_model | Permanent | Counts toward threshold |
Luna Provider Configuration
Luna (the agent client) connects directly to LLM providers. Configuration is in ~/.luna/config.json or .luna/config.json.
Supported Providers
| Provider | Default Model | API Format | API Key Env |
|---|---|---|---|
| Anthropic | claude-sonnet-4 | Anthropic Messages | ANTHROPIC_API_KEY |
| OpenAI | gpt-4o | OpenAI Chat Completions | OPENAI_API_KEY |
| xAI | grok-4 | OpenAI Chat Completions | XAI_API_KEY |
| z.ai | glm-5.1 | Anthropic Messages (https://api.z.ai/api/anthropic) | ZAI_API_KEY |
| Ollama | (local) | OpenAI-compatible (http://localhost:11434/v1) | N/A (local) |
Defaults and base URLs: client/core/provider.lua (model aliases) and
client/core/provider_urls.lua (PROVIDER_BASE_URLS).
Configuration
{
"model": "glm-5.1",
"provider": "zai",
"api_key": "your-api-key",
"base_url": "https://api.z.ai/api/anthropic"
}
Or use environment variables:
export ZAI_API_KEY="your-api-key"
luajit client/main.lua --model glm-5.1 "Fix the bug"
Provider-Specific Examples
Anthropic
{
"model": "claude-sonnet-4",
"provider": "anthropic",
"api_key": "sk-ant-..."
}
OpenAI
{
"model": "gpt-4o",
"provider": "openai",
"api_key": "sk-..."
}
z.ai (Default)
{
"model": "glm-5.1",
"provider": "zai",
"api_key": "..."
}
Ollama (S68)
{
"model": "qwen3-coder",
"provider": "ollama",
"base_url": "http://localhost:11434"
}
Ollama runs locally and requires no API key. Set the ollama_url config key if using a non-default address.
Model Switching
Switch models at runtime:
CLI: luajit client/main.lua --model gpt-4o "prompt"
TUI: Type /model gpt-4o in the input bar
Fallback & failure semantics
Luna’s client-side failover (client/core/provider_failover.lua) treats a
fallback stream attempt as rescued only by a real success: a 2xx HTTP
status, the internal "handled" marker, or a non-numeric truthy transport
value. Any other outcome — a numeric 4xx/5xx, the typed "error", or a
"redirect_refused" — is a FAILURE: the ladder continues to the next
fallback, and when it is exhausted the turn terminates with a typed
provider_error/error event plus a provider.stream_error publication.
The pre-fix if result ~= "error" comparison read a numeric 500 as a rescue,
ending the turn as an empty success; that class is closed.
Partial-content failures are terminal at the agent layer (agent.lua,
mirrored in agent_followup.lua): once an attempt has delivered any text
delta, a mid-stream error never re-drives the provider — the typed error is
surfaced once together with the single partial copy (turn_done.success = false, reason = "partial_content_stream_failure" /
"followup_stream_failure"). Pre-content failures keep the existing
overflow/transient retry ladder.
Server-side fallback chains
Sol serves provider overload from a configured fallback model instead of a
bare 503. The chain lives beside the declarative provider configs
(server/priv/providers/ bundled, ~/.sol/providers/ user override) as a
JSON object:
{"fallback_chains": {"claude-sonnet-4-20250514": ["claude-3-5-sonnet-20241022"],
"*": ["gpt-4o-mini"]}}
Keys and values are globs resolved against the registered model set
at load. Resolution order is deterministic: exact keys first, then prefix
globs, then other globs, * last (alphabetical per class).
Only dispatchable models are candidates: a
candidate must carry a remote endpoint + credentials or be a local lane
identity. A registered-but-endpoint-less adapter row is skipped, never
attempted into a 503. The attempt uses the serving model: aliases are
resolved to their canonical catalog/provider id before the wire body is
built.
Validation refuses unknown models, self-reference and cycles
(fallback_cycles); a refused config never installs chains (fail closed,
logged + counted) and the provider_boot init label records it.
Two fallback SEAMS exist. The HTTP funnel
engages a chain on a retryable pre-dispatch refusal: provider /
resolver circuit open, every provider-pool key cooling (the 429/quota
class), local admission capacity (429), and an admission-down lane. The
PIPELINE seam re-enters the same chain when a dispatched attempt yields a
retryable pre-token execution verdict — a 429/5xx/529/408 response
head, connect exhaustion, a first-token timeout, a garbage/empty 200, a
bodyless 200, a pre-token connection death, a permanent TLS/connect
failure, or {inference_unavailable, _}. A malformed/unknown model (404)
and auth/request errors (400/401/403) never fall back.
At most 2 fallback attempts after the primary. Each attempt is a NEW
pipeline, so the per-attempt machinery is reused as-is: circuit reports,
key cooldown/rotation,
Retry-After capture. Nothing retries once a byte has flowed: post-first-
token failures stay terminal (the pipeline’s own bounded head-429 retry
is unchanged). A pipeline fallback receives its OWN serving model, wire
dialect, transport posture and request path (fallback_opts +
descriptor), never the failed primary’s.
Observability: model.failed and provider.fallback_engaged (attempt
index + reason) durable events, the
sol_provider_fallback_engaged_total{from,to,reason} counter
(Sol Circuits & Providers dashboard panel), and an audit row per
engagement.
Compat surfaces: a response served by a fallback carries the serving
model — the x-zerg-model-used header plus the envelope model field;
the request body sent to the candidate carries the SERVING model id (and
the candidate’s wire dialect), never the requested body model;
usage/accounting is attributed to the serving provider and
inference.complete carries fallback_from when a fallback served.
The feature is ON with empty chains: no chains configured = no behavior
change (rollback = delete the config).
Luna posture: with a Sol binding present (a
Sol-issued lane grant) Sol owns fallback, and provider_failover does NOT
model-switch — Luna keeps only transport-level retries and surfaces the
typed error. Direct-provider configs (no binding) keep the client-side
chain documented above.
Declarative Providers (S54)
Users can add custom OpenAI-compatible providers without writing Erlang code. Place a JSON config file in the provider directory:
{
"name": "my-provider",
"display_name": "My Provider",
"base_url": "https://api.example.com/v1",
"api_key_env": "MY_PROVIDER_API_KEY",
"format": "openai",
"models": [
{"id": "my-model-large", "alias": "my-large"}
]
}
| Field | Required | Description |
|---|---|---|
name | Yes | Unique provider identifier |
base_url | Yes | API endpoint base URL. https:// (case-insensitive) is always accepted; a non-loopback http:// endpoint is REFUSED at config load (the key would travel in cleartext). Loopback http:// is allowed; a lab may opt in with "allow_insecure_provider_http": true (or the global allow_insecure_provider_http ack). |
api_key_env | No | Environment variable holding the API key |
format | Yes | Wire format: openai or anthropic |
headers | No | Custom HTTP headers (object) |
models | No | List of model objects: {"id": "...", "alias": "..."} (alias optional) |
display_name | No | Human-readable provider name |
default_max_tokens | No | Default completion token budget (also the admission estimate when the caller omits max_tokens). |
allow_insecure_provider_http | No | Explicit lab ack for a non-loopback plaintext endpoint (default off). |
Aliases are registered with an explicit canonical_model — the wire body
and settlement attribution always use the canonical id, never the alias.
See server/priv/providers/00-openai-compatible.json for a full example set
(groq, together, fireworks, openrouter, deepseek, google, mistral, cohere,
perplexity) and server/src/sol_provider_declarative.erl for the validator.
Providers are loaded at boot and registered in the ETS provider registry. They participate in normal routing, circuit breaking, and pool management.
Provider Boot Registration
Providers are registered at boot by sol_provider_boot:register_defaults/0
(server/src/sol_provider_boot.erl). There is no {providers, [...]}
sys.config tuple — registration happens through three mechanisms:
- Bundled adapters — the models exposed by each
sol_provider_*.erladapter (anthropic, openai, zai, ollama, alibaba, bedrock, xiaomi) are registered in code, each stamped with itswire_format. - Config mappings — a
provider_mappingslist insys.configmaps a model name to a provider atom:{provider_mappings, [{<<"my-model">>, anthropic}]}. - Declarative JSON —
priv/providers/*.json, hot-reloadable without restart (sol_provider_declarative:load_configs/0).
Config-based provider mappings require an application restart; declarative JSON providers do not.
Coordinator Mode
sol_coordinator (server/src/sol_coordinator.erl) decomposes a multi-step
task into subtasks and runs each subtask as a workflow through
sol_workflow_manager. The decomposition registry is durable since
A bounded, atomically written file (cap enforced; terminal
entries retire) reconciled on boot, with the workflow rows still the source of
truth. A coordinator restart therefore loses no grouping view and does not
re-dispatch a completed subtask. cancel/1 drives every remaining subtask
workflow to a real terminal state.
Workflow steps can specify model and provider fields to override
automatic routing (sol_workflow_templates.erl step parsing), which is how
per-step provider selection is expressed — there is no built-in
mode→provider routing table.
Cloud Provider Adapters
AWS Bedrock (CSP1)
Sol supports AWS Bedrock’s Converse API for running models like Claude on AWS infrastructure.
Boot config:
{bedrock, #{
format => bedrock,
region => "${AWS_REGION}",
access_key => "${AWS_ACCESS_KEY_ID}",
secret_key => "${AWS_SECRET_ACCESS_KEY}"
}}
Supported models:
| Friendly Name | AWS Model ID |
|---|---|
bedrock-claude-sonnet-4 | anthropic.claude-sonnet-4-20250514-v1:0 |
bedrock-claude-3.5-sonnet | anthropic.claude-3-5-sonnet-20241022-v2:0 |
bedrock-claude-3.5-haiku | anthropic.claude-3-5-haiku-20241022-v1:0 |
OpenAI Responses API — RETIRED
The responses wire is retired. It was never implemented end-to-end
(the request path derivation appended /chat/completions to a
/v1/responses base URL, and the body builder/parse router had no
responses branch), so a responses config produced models that could
never answer correctly. Per the retirement decision (, the luerl
sub-agent precedent):
declarative provider configs declaring format: "responses" fail
validation with an actionable error;
boot refuses to register responses-adapter models (loud log +
counter);
the adapter module answers every call with
{error, {retired_wire, responses}}.
Use the openai wire (chat completions) or the anthropic wire instead.
Re-introduction means implementing the real wire — request builder,
parser, path derivation, translators, and a golden fixture corpus — and is
tracked separately.
Cross-Provider Switching
Runtime adapter switching (POST /api/v1/provider/switch) was retired
in: it flipped a global registry entry, carried an echo-only
workflow_id, and had zero consumers on any client. Model selection is
per-request params + declarative provider configs + the lane plane; reload
declarative configs with POST /api/v1/providers/reload (kept — used by
sol_provider_boot:reload_declarative).
Provider Pool
For providers with multiple API keys, Sol distributes requests across a pool:
| Config Key | Default | Description |
|---|---|---|
provider_pool_strategy | round_robin (shipped sys.config; code default is least_used) | Key selection strategy: round_robin (rotates per-provider key index), least_used (min usage_count), random, least_errors |
See server/src/sol_provider_pool.erl (select_key/3).
Engine reference — generated from the canonical engineering source. Do not edit this page by hand.
Version & Compatibility Matrix
Which component versions can talk to which — for Sol, Luna, the zerg CLI, Mango, and Limon. Two versioned handshakes exist: the ZMQ wire protocol between Sol and Luna (§ZMQ wire protocol) and, since then, the Erlang-distribution join exchange between Sol control nodes (§Sol ↔ Sol). Everything else is REST/HTTP with additive-extension compatibility.
Component versions
All components ship from one repo and deploy together (wild CD
deploys Sol + Mango + Luna images from one tagged build). The version is
in each component’s VERSION file:
| Component | Version file | Notes |
|---|---|---|
| Sol (orchestrator) | server/VERSION | also -vsn("X.Y.Z") per module |
| Luna (worker agent) | client/VERSION | |
| zerg CLI | zerg-cli/VERSION | the update channel publishes CLI + luna + sol tarball per tag |
| Mango (identity/auth) | mango/VERSION | |
| Limon (ops console) | limon/VERSION |
Current tree: 1.003.0 in every VERSION file (root VERSION,
server/, client/, zerg-cli/, mango/, limon/).
ci/check-version-sync.sh enforces the parity (all five per-service
files must equal the root VERSION, plus every -vsn attribute in
server/src/, the lockfile pins, and the Current tree: row of THIS
file — machine-checked since then; this row sat outside
every gate and drifted to 0.650.4 while the tree moved on).
Node roles & cluster topology
Production runs as one Erlang distribution cluster of three Sol nodes
(blue + green + red). All nodes consume the same tagged build; wild CD
distributes the image digests digest-exact through the release-safe
sys.config overlay and probes 3/3 membership in its relaunch-cluster
step.
| Node | Role | SOL_NODE_LABEL → class | Lane policy |
|---|---|---|---|
| blue | coordinator (HTTP edge, scheduler) + CPU lane | blue → cpu_host | max_sessions=1; lanes ling_tiny_cpu, api_tier |
| green | GPU lane host | green → gpu_3090_64g | lanes => all_gpu; qwen38_flashnext ctx override 131072 |
| red | GPU lane host | red → gpu_3090_full | lanes => all_gpu |
Distribution: longnames (sol@host), the seed union pinned in
sys.prod.config (self-filtered at boot; wild’s SOL_CLUSTER_NODES wins
where set), cluster_expected_nodes=1 (shipped standalone; wild’s per-host
SOL_CLUSTER_EXPECTED_NODES sets 3 for the fleet), cluster_deployment =
blue-red-green (per-host env), distribution pinned to
SOL_DIST_PORT=9150 (epmd 4369).
The sol-cluster-expected-nodes alert owns the membership signal.
Lane truth is Sol-only: Luna holds no lane configuration — a worker
consumes a Sol-issued grant or fails typed lane_unavailable (no local
fallback). Cross-node serving needs the non-loopback bind opt-in and
advertised reachability; see docs/production-runbook.md §Three-node
topology.
Compatibility: Sol, Luna, Mango and Limon ship from one repo and the CD
deploys them together; the ZMQ wire-protocol table below still governs
worker compatibility during a rolling upgrade.
Sol ↔ Sol (Erlang distribution join exchange) — join generation 1
Since **** every Sol↔Sol join — the explicit
POST /api/v1/cluster/join, the automatic nodeup, and the seed-pong
rejoin — performs a synchronous, bounded rpc to the peer’s
sol_cluster:hello/0 (2 s, state-free; its only effect is an idempotent
application:load/1 of the peer’s own spec, and it is served even while
the peer’s cluster server is busy). The exchange carries:
| Field | Meaning |
|---|---|
vsn | the join generation (?CLUSTER_JOIN_VSN). The ONE admission authority. A pre-guard release cannot answer hello/0 and is classified as generation 0 (its real release version is read separately via application:get_key(sol, vsn)). |
version | the release VERSION string (informational + the skew detail: a same-generation release difference still raises the gauge). |
otp_release | erlang:system_info(otp_release). Carried and surfaced (status/log); distribution itself enforces OTP compatibility, so it is not a gate. |
schema_epoch | the durable (Mnesia/event/task) schema epoch (?SCHEMA_EPOCH). Bumped ONLY on an incompatible durable-schema change. |
Policy (default-on):
| Local join gen | Peer join gen | Schema epoch | Verdict |
|---|---|---|---|
| N | N | equal | joined (ok); sol_cluster_version_skew = 0 when the release strings also match, else 1 with verdict version_skew |
| N | N−1 | equal | joined + skew (older_peer), sol_cluster_version_skew = 1, maintenance-503 posture marker published |
| N | N+1 | equal | joined + skew (newer_peer), gauge 1, marker published (symmetric window) |
| N | ≤ N−2 | any | REFUSED (peer_join_generation_too_old), CRITICAL log, cluster_join_refused_total, peer disconnected and marked refused |
| N | ≥ N+2 | any | REFUSED (peer_join_generation_too_new), same loud/refuse/disconnect path |
| N | any | ≠ local | REFUSED (schema_epoch_mismatch), same path — a schema jump is stop-the-world, never rolling |
| N | pre-guard (no hello/0) | treated as 0 | admitted only while 0 ≥ N−1 (the first guarded release’s N−1 window); refused one release later |
The refusal is typed on the HTTP join path
({error, {cluster_join_refused, Reason}}, 502-class) and best-effort on
the automatic paths (no joined event, no catalog sync, no receipt/webhook
reconcile; the peer is disconnected). A probe that cannot answer at all is
Not a version verdict: the peer is admitted with an unknown posture,
a warning and cluster_join_probe_failed_total (availability first — the
distribution cookie is the trust boundary; the guard is an accident guard).
The maintenance-503 posture marker is the status datum
version.posture.maintenance_503_marker (plus the
sol_cluster_version_skew gauge and a one-per-peer WARNING). It
deliberately does NOT flip the global sol_maintenance gate: the N/N−1
join is the ALLOWED rolling direction, and gating it would defeat the
upgrade it exists to permit. Treat a 1 gauge as a maintenance-class
window — finish the roll before trusting cross-node projections.
Release engineering rule: bump ?CLUSTER_JOIN_VSN by ONE on every
release (paired with the VERSION bump — the same discipline as a wire
protocol bump). Bump ?SCHEMA_EPOCH only when the durable schema changes
incompatibly, and roll such a release stop-the-world. Both constants are
gated by contract/cluster-generation.yaml + ci/cluster_generation_lint.py
the YAML must match the sol_cluster.erl -defines and
its recorded_for_version must equal the root VERSION, so a release
that bumps VERSION without reviewing this datum is RED. The deliberate
mixed-window drill lever is cluster_version_guard_ack (default false,
pinned false in sys.config + sys.prod.config); true downgrades a
refusal to a CRITICAL-logged ACKED admission, never a silent pass.
The lever covers BOTH refusal arms — a join-generation mismatch AND a
schema_epoch mismatch — and it is read PER EXCHANGE
(sol_config:bool(cluster_version_guard_ack, false) at each probe), so
flipping it at runtime applies to the next join/nodeup/seed-pong without a
restart. The schema-epoch ACK is for a deliberate drill only: the durable
schema still must not jump in production.
Sibling, not duplicate: plan/rolling-upgrade-skew-matrix.md owns the
Sol↔Luna ZMQ wire skew (protocol generation N/N−1 READY window). This
section is the Erlang-distribution join path; the two are independent
contracts and neither replaces the other.
Toolchain build provenance
The toolchain component versions the binaries are built WITH are recorded — not inherited invisibly from a mutable image tag
The wild toolchain image ships its own record at
/usr/local/share/toolchain-provenance.env, KEY=VALUE lines,
luajit_commit=<40-hex> REQUIRED (the OpenResty LuaJIT fork commit —
the grammar/bytecode-determinism carrier), plus musl-gcc, upx and
luastatic versions. The image build writes the file; zerg consumes it
.
Both binary builds embed the record: client/build/build.sh and
zerg-cli/build/build.sh distill the file (sorted keys) into a
generated toolchain_provenance Lua module linked into the binary.
zerg --version prints the record line. A missing file embeds
toolchain_provenance;unrecorded and warns loudly in a dry build; on
the RELEASE lane a missing record now FAILS the reproducibility gate
( — the waiver is removed; wild must ship
the record). A manual operator override remains an explicit, audited
escape, never a lane default.
The repro gate asserts it: ci/check-build-reproducibility.sh
verifies the file parses (40-hex luajit_commit), that BOTH staged
builds generated identical provenance modules, and that the embedded
record matches the image’s file. ci/crow_cd_lint.py pins the wiring
(the gate and both build scripts must keep the provenance hooks).
Engine artifacts
The llama.cpp engines ZERG runs are first-class artifacts with recorded
provenance: one engines/<class>.json row per machine class,
validated by ci/engine_manifest.py and linted by
ci/engine_manifest_lint.py.
Reference rows. engines/cuda_sm86.json records the RTX 3090 class
(ref ggml-org/llama.cpp@aa39d7a3e145a88202793a89462d65e94a5fc25f,
build b11011, GGML_CUDA=ON + CMAKE_CUDA_ARCHITECTURES=86 +
GGML_CUDA_FA_ALL_QUANTS=ON, source=reference, state=reference,
production=true). engines/cpu_epyc.json records the EPYC coordinator
class with the documented CPU flag set and build=unbuilt — the EPYC leg
is a blue/ops acceptance. Reference rows carry image_digest /
manifest_hash as unverified until a hermetic ZERG build measures them;
only state=reference may claim unverified.
Build/packaging. scripts/engines/build.sh --class fixture|cuda_sm86| cpu_epyc --out DIR stages <out>/<build>/{bin,lib} and produces
llama-<build>-<rev12>-<class>-linux-x86_64.tar.gz + .sha256 +
.manifest.json (the fixture class names itself
llama-fixture-<build>-linux-x86_64.tar.gz; it has no upstream rev).
Packaging is deterministic: sorted tar entries, SOURCE_DATE_EPOCH
mtimes, numeric owners, gzip -n. CUDA/EPYC classes require the hermetic
registry image; a
non-hermetic host build runs only with the explicit --local flag and
can never claim production=true.
Reproducibility gate. ci/check-engine-reproducibility.sh compares
the sorted whole-tree bin/+lib/ manifest (sha256 + mtime + file set)
of two builds with SOURCE_DATE_EPOCH fixed; a sabotage knob proves a
timestamp/extra-file drift fails. ZERG_ENGINE_REPRO_TRIPWIRE_ONLY=1 is
the GPU-less tripwire mode (runtime tripwire asserted; the GPU
certification itself runs on red/green, never on required checks).
Install / rollback. scripts/engine-install.sh <artifact> --root DIR
verifies the .sha256 sidecar (and .minisig when both the signature and
the minisign binary exist — a loud “not verified” line otherwise),
unpacks to DIR/<build>/{bin,lib}, canary-probes /health on a scratch
port, atomically flips the current symlink, keeps N-1, and writes
DIR/installed.json {build, manifest_hash, installed_at, sha256, verified_by}. scripts/engine-rollback.sh repoints to the previous (or
--to named) build after re-probing it. A failed canary leaves current
untouched.
Fixture exclusion. The fixture_openai engine (the test-only OpenAI/
SSE server, production=false, exclude_reason stated) rides the same
install and model-sync path but is excluded from the production promotion
set by ci/engine_manifest_lint.py. Engine tarball names must keep the
llama- prefix so they can never collide with the zerg-cli updater’s
exact-name candidate assets (zerg-<tag>[-<os>-<arch>].tar.gz + sidecars).
ZMQ wire protocol — v4 (lane control + per-frame MAC plane)
Protocol version: 4 since then — the v3 → v4
bump added the task-frame inference_binding lane-grant stamp and the
lane_control / lane_control_ack worker-plane round-trip (upgrade
posture: stop-then-upgrade — a v3 Sol silently drops lane_control).
v3 before it carried the team_directive
leader-attribution (sender) + content-signature (hmac) fields and
joined the per-frame MAC plane. v2 before that
added the per-task token seq.
The canonical reference is docs/zmq-protocol-reference.md (“Protocol
Version” section). Function-name anchors (deliberately no line numbers —
code motion cannot stale a function name):
Sol constant + accessor: sol_zmq_protocol:protocol_version/0 returns
?PROTOCOL_VERSION = 4 (server/src/sol_zmq_protocol.erl).
Luna constant: M.VERSION = 4 (client/core/zmq_protocol.lua).
Every frame carries its protocol version in v
(sol_zmq_protocol:stamp_version/2 driven by the centralized
frame_version_for/1 authority —,: EVERY Sol→Luna
builder stamps the target worker’s admitted version; Luna’s local
stamp/1 in zmq_protocol.lua); absent v means legacy v1.
Version policy:
zmq_wire_skew_window (default true) admits a worker whose version
is exactly one below Sol’s (N−1 = v3) for rolling upgrades; anything
older (v2/v1) is refused loudly at the ready handshake. With the lever
set false (rollback posture) only exact-version workers register. ALL
frames to an N−1 worker are stamped min(Sol, Worker) via the target-aware
builders so Luna’s v > M.VERSION gate accepts them.
Rationale recorded at sol_zmq_protocol.erl around the constant: (1)
accepting arbitrarily old versions would silently disable the current
frame semantics (token seq gap detection, MAC plane) for part of the
fleet; (2) Sol and Luna ship from one repo and deploy together (wild CD);
(3) mismatches already fail loudly in both directions.
Known gap — CLOSED: the control-frame
gap (only the task frame skew-stamped; cancel/error/spawn_ack and
the rest of the control set went out v4-stamped and were dropped by a real
v3 worker’s validate_incoming/1 version gate) is fixed by target-aware
stamping across every Sol→Luna builder. The per-frame policy
(downstamp / current / stamp-at-target / legacy-unstamped) lives in
server/test/fixtures/wire_compat_matrix.json, machine-checked by
ci/stamp_policy_matrix_lint.py, and the canonical reference’s skew table
documents the same truth. Only lane consumption remains v4-only
(lane_control_ack/lane_revoke are v4-only semantics with visible
suppression for pre-v4 targets).
Ready-handshake support table
The ready frame carries version + min_version (both = 4 from a
current Luna — zmq_protocol.lua:M.ready_message/7). Sol’s
sol_zmq_protocol:validate_ready_msg/1:
Worker version | Worker min_version | Sol verdict |
|---|---|---|
4 (== Sol’s) | <= 4 | ok — registered (normal case) |
4 (== Sol’s) | > 4 | {error, {min_version_too_new, Min, 4}} — worker requires a protocol newer than Sol supports; refused |
3 (N−1) | > 4 | {error, {min_version_too_new, Min, 4}} — the N−1 clause binds min_version too since then -8 |
3 (N−1) | <= 4 or absent | ok while zmq_wire_skew_window=true (default); {error, {version_mismatch, 3, 4}} with the lever false |
| anything ≠ 4 and ≠ 3 | any | {error, {version_mismatch, V, 4}} — refused (v2/v1 workers land here, loudly) |
missing version/worker_id/capabilities | — | {error, missing_fields} |
Luna’s inbound side (M.validate_incoming/1,
client/core/zmq_protocol.lua): a frame with v higher than Luna’s
supported version is dropped loudly (unsupported protocol version);
v <= 4 (including absent = legacy v1) is accepted. Because the ready
handshake gates registration to the current version (or the N−1 window),
Sol only ever dispatches to workers that already speak the accepted
protocol — the Sol→Luna task direction is forward-safe by construction
(control frames are the tracked exception above).
Consequence for fleets: a current Sol + v2/v1 Luna mix cannot
register; a v3 Luna can register only while the skew window is on, and
receives task frames stamped v3. A current Luna + older Sol mix has Sol refuse
the ready. In all mismatch directions the worker shows as
failed/reconnecting in zerg zmq-workers until versions match. Deploy
the tag’s Sol + Luna + Mango together — the CD always does.
zerg CLI ↔ Sol (REST)
The CLI talks REST (/api/v1/* + /v1/chat/completions,
/v1/messages) and SSE. REST is additive-extension compatible; the CLI
is not pinned to a wire protocol — any CLI version that ships the
endpoint paths it calls works against newer Sols (documented commands are
the contract; see docs/api-reference.md). The update channel is the one
place versions meet: zerg update check compares the local
/opt/zerg/VERSION against the latest Forgejo release tag and refuses
non-conforming tags (anchored-semver parse + refusal at
zerg-cli/cli/update.lua:118-178; Forgejo is the default channel,
:23-38) — see docs/cli-reference.md §Updates.
Mango ↔ Sol / Mango ↔ CLI (auth bridge)
Mango tokens (user_uuid, SHA-256 of a 256-bit random
token_urlsafe(32)) are opaque to Luna and the CLI; Sol validates them
against Mango’s revocation state —
an old token against a newer Mango or vice versa either validates or
fails with 401, never drifts. No version field in play.
Supporting documentation
Canonical wire reference: docs/zmq-protocol-reference.md (Protocol
Version section + ready frame table)
decision: docs/archive/AGENTS-decisions-archive.md
Handshake auth (HMAC/enrollment): docs/zmq-security.md
Engine reference — generated from the canonical engineering source. Do not edit this page by hand.
Architecture: See cel-vision.md (
docs/cel-vision.md) for the design philosophy, cross-runtime contract, and subsystem relationships. This document is the API reference.
cel.lua — ZERG Standard Library
cel.lua is the unified standard library for the ZERG project. It provides a consistent API surface across both the Luna client (LuaJIT) and the Sol plugin sandbox (luerl), so developers and plugin authors can rely on a single import for JSON, OOP, collections, and utilities.
Import
Luna client (LuaJIT)
local cel = require("core.cel")
Sol plugin sandbox (luerl)
cel is preloaded as a global by sol_sandbox_shared:preload_stdlib/1 — no require needed
local cel = cel
Subsystems
cel.json — JSON Encode/Decode
Dual-backend JSON that automatically selects the best available implementation:
Preferred on BOTH runtimes: JSON_luerl (pure Lua, the project’s own vendored lib — per; more robust than dkjson, which has a nil-comparison panic bug on some data shapes)
Fallback (LuaJIT): dkjson — used only when vendor.JSON_luerl cannot be required
local obj = cel.json.decode('{"name":"alice","age":30}')
Returns: obj, nil
local str = cel.json.encode({items = {1, 2, 3}})
Returns: '{"items":[1,2,3]}'
Error handling:
local obj, err = cel.json.decode("invalid")
obj = nil, err = "expected..."
| API | Signature | Returns |
|---|---|---|
cel.json.encode(t) | table → string; a string input passes through unchanged | JSON string |
cel.json.decode(s) | string → table | (obj, nil) on success, (nil, err) on failure |
The 2-value nil, err boundary is normalized inside cel — the underlying backends
return three values (obj, nil, err), but the third slot is never echoed.
Note: this boundary exists in the Luna build; the trimmed luerl build still returns
the raw 3-value shape and additionally exposes cel.json.encode_pretty(t).
cel.class — Object-Oriented Programming
middleclass v4.1.1 — class definition, single inheritance, mixins, metamethods.
local Animal = cel.class("Animal")
function Animal:initialize(name)
self.name = name
end
function Animal:speak()
return "I am " .. self.name
end
local Dog = cel.class("Dog", Animal)
function Dog:initialize(name, breed)
Animal.initialize(self, name)
self.breed = breed
end
local d = Dog("Rex", "Lab") -- __call shorthand
assert(d.name == "Rex")
assert(d.class.name == "Dog")
assert(d:speak() == "I am Rex")
Plugin pattern: Sol plugins use a thin module wrapper around a singleton instance,
because the plugin manager calls plugin.init(config) (dot-call, no self):
local MyPlugin = cel.class("MyPlugin", cel.ChannelPlugin)
function MyPlugin:initialize(config)
cel.ChannelPlugin.initialize(self, config)
end
... methods...
local _instance = nil
local plugin = { name = "my_plugin", config_schema = {...} }
function plugin.init(config)
_instance = MyPlugin(config)
return true
end
plugin.send_message = function(...)
return _instance:send_message(_instance, ...)
end
return plugin
| API | Description |
|---|---|
cel.class(name) | Define a new class |
cel.class(name, parent) | Define a subclass |
ClassName:initialize(...) | Constructor |
instance.class | Runtime type reference |
instance.class.name | Class name string |
cel.ChannelPlugin — Plugin Base Class
Available in the Sol plugin sandbox build of cel only (server/priv/lua_libs/cel.lua).
Provides shared channel plugin functionality:
local TelegramPlugin = cel.class("TelegramPlugin", cel.ChannelPlugin)
function TelegramPlugin:initialize(config)
cel.ChannelPlugin.initialize(self, config)
self.parse_mode = config.parse_mode or "MarkdownV2"
end
| Method | Description |
|---|---|
:initialize(config) | Set up rate limiting, queue, config (rate_limit_ms default 100, max_queue_depth default 100, max_message_len default 4096) |
:validate_config(schema) | Check required fields; apply optional defaults |
:start_backend(channel_id) | Create backend state for a channel |
:stop_backend(channel_id) | Remove backend state |
:queue_message(channel_id, msg) | Enqueue with depth check (queue full error at cap) |
:check_rate_limit(channel_id) | Returns true if at least rate_limit_ms has elapsed |
:enqueue(channel_id, msg) | Alias that forwards to queue_message |
:sleep(ms) | No-op in the sandbox (async drain model) |
:drain_queue(channel_id) | Pop queued messages while rate limit allows; calls self:do_send if defined |
:truncate(text, max_len) | Truncate with "..." suffix (default cap max_message_len) |
:format_event(type, data) | Override in subclasses (base returns nil) |
:shutdown | Stop all backends |
cel.X — Eager Collection Operations (Lume)
One-shot table transforms. Use for small-to-medium data where readability matters.
local names = cel.map(users, function(u) return u.name end)
local active = cel.filter(items, function(i) return i.active end)
local found = cel.find(list, "admin") -- value equality, not predicate
local has_admin = cel.any(roles, function(r) return r == "admin" end)
| API | Signature | Returns |
|---|---|---|
cel.map(t, fn) | Transform values | New table (preserves keys) |
cel.filter(t, fn) | Keep matching (predicate) | New array/dict |
cel.each(t, fn) | Side-effect iteration | nil |
cel.reduce(t, fn, init) | Accumulate | Single value |
cel.any(t, fn) | Short-circuit OR | boolean |
cel.all(t, fn) | Short-circuit AND | boolean |
cel.find(t, value) | Value-equality search (NOT a predicate — the needle is compared with ==) | Key/index of the match, or nil |
cel.keys(t) | Extract keys | Array |
cel.values(t) | Extract values | Array |
cel.clone(t) | Shallow copy | New table |
cel.extend(a, b) | Merge b into a | Table a (mutated) |
cel.pick(t,...keys) | Project only the named keys | New table |
cel.split(str, sep) | Split string | Array |
cel.trim(str) | Strip whitespace | String |
cel.format(fmt,...) | String formatting | String |
cel.wordwrap(str, limit) | Wrap text at width | String |
cel.serialize(t) | Serialize to string | String |
cel.deserialize(s) | Parse serialized | Table |
cel.clamp(x, min, max) | Constrain number to range | Number |
cel.lerp(a, b, t) | Linear interpolation | Number |
cel.random(a, b) | Random number (int or float form) | Number |
cel.uuid | Random UUID | String |
When to use cel.X: One-shot transforms on data that fits in memory. Prefer over raw loops when the predicate is a single expression.
cel.iter — Lazy Iterator Pipelines (Fun)
Composable lazy iterators. Use for large datasets, chains of 3+ transforms, or when you want zero intermediate allocations.
local pipeline = cel.iter.range(1, 1000)
|> cel.iter.map(function(x) return x * 2 end)
|> cel.iter.filter(function(x) return x % 3 == 0 end)
|> cel.iter.take(10)
for _, v in pipeline do
print(v) -- 6, 12, 18, ...
end
| API | Description |
|---|---|
cel.iter.range(start, stop) | Integer iterator |
cel.iter.map(fn, iter) | Transform elements |
cel.iter.filter(fn, iter) | Keep matching |
cel.iter.reduce(fn, init, iter) | Fold to single value |
cel.iter.each(fn, iter) | Side-effect traversal |
cel.iter.take(n, iter) | First n elements |
cel.iter.drop(n, iter) | Skip first n elements |
cel.iter.zip(iter1, iter2) | Pair elements |
cel.iter.chain(iter1, iter2) | Concatenate iterators |
cel.iter.enumerate(iter) | (index, value) pairs |
cel.iter.cycle(iter) | Infinite repeat |
cel.iter.duplicate(val) | Infinite constant |
cel.iter.wrap(x) | Wrap a value/table so it iterates (Fun adapter) |
cel.iter.unwrap(x) | Inverse of wrap |
cel.iter.to_table(iter) | Collect to array |
When to use cel.iter: Chains of 3+ transforms, large datasets (thousands+), or when you want zero intermediate table allocations. For single transforms, prefer cel.X.
cel.vec — 2D Vector Math
Immutable 2D vector operations (luerl-safe — no __call metamethod). Available for
game/AI/physics plugins.
local v = cel.vec.new(3, 4)
assert(cel.vec.mag(v) == 5)
local n = cel.vec.norm(v)
assert(cel.vec.mag(n) == 1)
local sum = cel.vec.add(cel.vec.new(1, 0), cel.vec.new(0, 1))
| API | Description |
|---|---|
cel.vec.new(x, y) | Create vector (defaults 0, 0) |
cel.vec.from_angle(theta) | Unit vector from angle (screen-coords: y = −sin θ) |
cel.vec.random | Random unit vector |
cel.vec.is(t) | True if t is a cel.vec |
cel.vec.to_table(v) | To {x, y} table |
cel.vec.from_table(t) | From {x, y} or {[1], [2]} array |
cel.vec.clone(v) | Copy |
cel.vec.mag(v) | Magnitude |
cel.vec.mag_sq(v) | Squared magnitude |
cel.vec.set_mag(v, mag) | Rescale to length |
cel.vec.norm(v) | Normalize (zero vector returns a clone) |
cel.vec.limit(v, max) | Clamp magnitude |
cel.vec.add(a, b) | Addition |
cel.vec.sub(a, b) | Subtraction |
cel.vec.mul(a, b) | Scalar or component multiply |
cel.vec.div(v, s) | Scalar divide |
cel.vec.neg(v) | Negate |
cel.vec.eq(a, b) | Component equality |
cel.vec.dot(a, b) | Dot product |
cel.vec.dist(a, b) | Distance |
cel.vec.heading(v) | Angle of vector (y-flipped to match from_angle) |
cel.vec.rotate(v, theta) | Rotate by angle |
cel.shell_quote — Shell Argument Safety
The ONLY sanctioned way to pass any value into a shell command line. Always wraps in single quotes (even non-strings — input is stringified first), so the result is always exactly one shell token:
local cmd = "grep " .. cel.shell_quote(pattern) .. " " .. cel.shell_quote(path)
cel.shell_quote("it's") → 'it'\''s'
Blocklist sanitizers are forbidden in ZERG (the deprecated blocklist was deleted —
); use cel.shell_quote for every argument, no exceptions.
Validation Helpers
Shape-checkers for values interpolated into command lines. Each returns the input on
success or nil on failure (never throws):
| API | Accepts |
|---|---|
cel.validate_image_name(s) | Non-empty [_%w%.%-/:]+ that does not start with - (option-shaped tokens rejected) |
cel.validate_path(s) | Non-empty /, word, ., -, _ characters only |
cel.validate_docker_name(s) | Word characters, -, _ only |
Secure Temp Files (fd discipline)
mkostemp-based temp file creation with mode 0600 and O_EXCL semantics. Two flavors:
| API | Contract |
|---|---|
cel.secure_tmpfile(prefix?) | Creates the file (0600), CLOSES it, returns the path. The reopen-by-name window is documented — keep this for read-only uses only. |
cel.secure_tmpfile_fd(prefix?) | Keeps the fd open; returns {fd, path} or nil, err. Write content through the fd — a same-dir attacker cannot swap the path pre-rename. |
cel.fd_write_all(fd, content) | Chunked (64KB) write to the open fd; true or nil, err. Caller owns/closes the fd. |
cel.rename_tmpfile_fd(fdp, target) | Links the fd’s INODE into place (linkat AT_EMPTY_PATH, with /proc/self/fd verify-then-rename fallback); refuses loudly on attacker unlink/swap. true or nil, err. |
Write-then-rename flows MUST use the _fd trio; os.tmpname
is banned.
cel.string.hash — FNV-1a Content Hash
cel.string.hash(s) returns an 8-hex-char FNV-1a 32-bit hash (16-bit-limb
implementation so partial products stay below 2^53 — ). Used for
content-distinct cache keys (e.g. long tool arguments); non-string input is
stringified; without the bit library it degrades to the string length.
cel.ansi_sanitize — Escape-Sequence Stripping
cel.ansi_sanitize(s) strips terminal escape sequences and dangerous control bytes
from untrusted text before it reaches agent context or terminal rendering:
CSI sequences (SGR color, cursor movement, device queries)
OSC sequences (window-title / hyperlink smuggling), BEL- or ST-terminated
DCS / SOS / PM / APC string-machine sequences
Two-byte ESC sequences (charset designators, ESC 7, ESC =)
Bare/trailing ESC, C0 controls (except \t and \n), and DEL
Bytes 0x80–0x9F are untouched (UTF-8 continuation bytes — stripping them would
corrupt multi-byte characters)
Returns a new string; input is never mutated. Non-string input is stringified.
Utility Functions
| API | Description |
|---|---|
cel.deep_copy(t) | Recursive table copy (non-table values pass through) |
cel.deep_merge(base, overlay) | Recursive merge — arrays extend when BOTH sides are arrays, tables recurse, scalars overwrite; returns base (mutated) |
cel.is_array(t) | True for non-empty contiguous 1..n integer-keyed tables |
cel.split_lines(text) | Split text by \n; empty string yields {}, no trailing empty line |
Decision Guide
Do you need JSON? → cel.json
Do you need a class? → cel.class
Do you need a one-shot → cel.X (eager)
filter/map/any/find?
Do you need a pipeline → cel.iter (lazy)
of 3+ transforms?
Do you need 2D math? → cel.vec
Do you need deep copy/merge?→ cel.deep_copy / cel.deep_merge
Do you need shell args? → cel.shell_quote
Do you need temp files? → cel.secure_tmpfile_fd (+ fd_write_all / rename_tmpfile_fd)
Do you need to render → cel.ansi_sanitize
untrusted terminal text?
Runtimes
| Feature | LuaJIT (Luna) | luerl (Sol sandbox) |
|---|---|---|
| cel.json | JSON_luerl preferred (dkjson fallback); 2-value decode boundary | JSON_luerl; raw 3-value decode; plus encode_pretty |
| cel.class | middleclass v4.1.1 | middleclass v4.1.1 |
| cel.X | Lume (eager) | Lume (eager) |
| cel.iter | Fun (lazy) | Fun (lazy) |
| cel.vec | Full | Full |
| cel.shell_quote, validators, string.hash, ansi_sanitize | Yes | No (trimmed luerl build omits them) |
cel.secure_tmpfile / _fd trio | Yes (FFI) | No (no FFI in luerl) |
| cel.ChannelPlugin | No | Yes (plugins only) |
The two builds have intentionally diverged: client/core/cel.lua carries the
Luna-only FFI/security utilities; server/priv/lua_libs/cel.lua carries
ChannelPlugin + encode_pretty for plugins. Shared subsystems (json, class,
Lume/Fun collections, vec) are kept behaviorally identical.
Performance Reference
From benchmarks (100K elements, LuaJIT):
| Operation | cel.iter (Fun) | cel.X (Lume) | Raw Lua |
|---|---|---|---|
| map | 1.8ms | 22ms | 6ms |
| filter | 2.1ms | 220ms | 8ms |
| reduce | 1.2ms | 18ms | 5ms |
| take(10) | 0.01ms | N/A | N/A |
Cel.iter is 10-100x faster for large datasets (lazy, no allocation) Cel.X is more readable for small datasets (one-liners) Raw Lua is fine for simple cases where cel adds no clarity
File Locations
| Runtime | cel.lua | Dependencies |
|---|---|---|
| Luna (LuaJIT) | client/core/cel.lua | client/vendor/middleclass.lua, client/vendor/dkjson.lua (fallback), client/vendor/fun_luerl.lua, client/vendor/lume.lua, client/vendor/JSON_luerl.lua |
| Sol (luerl) | server/priv/lua_libs/cel.lua | server/priv/lua_libs/middleclass.lua, server/priv/lua_libs/fun.lua, server/priv/lua_libs/lume.lua, server/priv/lua_libs/JSON_luerl.lua (preloaded by sol_sandbox_shared:preload_stdlib/1) |
Themes
Luna’s TUI uses a theme system for consistent visual styling across the chat interface, tool output, markdown rendering, and status bars. Themes are defined as Lua tables with color and attribute specifications.
Built-in Themes
Luna ships with 4 built-in themes:
| Theme | Description |
|---|---|
default | Classic dark theme with colored roles |
onedark | Subdued palette inspired by One Dark |
high-contrast | Light background for accessibility |
solarized-dark | Solarized color palette on dark background |
Selecting a Theme
In ~/.luna/config.json:
{
"theme": "onedark"
}
Or at startup:
luajit client/main.lua --theme solarized-dark
Theme Structure
A theme is a Lua table with the following sections:
{
name = "my-theme",
background = "black",
menubar_title = "cyan onblack bold",
scrollbar_bg = "black",
scrollbar = "white onblack",
roles = {
user = "green onblack bold",
assistant = "blue onblack bold",
system = "yellow onblack bold",
error = "red onblack bold",
tool = "magenta onblack",
tool_start = "cyan onblack bold",
tool_result = "white onblack dim",
dim = "white onblack dim",
thinking = "cyan onblack dim",
thinking_summary = "darkgrey onblack dim",
compact = "yellow onblack dim",
},
markdown = {
heading = "\27[1m\27[36m",
bold = "\27[1m\27[33m",
italic = "\27[3m\27[35m",
inline_code = "\27[32m",
code_block = "\27[90m",
code_border = "\27[90m",
code_bg = "\27[48;5;236m",
link = "\27[4m\27[34m",
strikethrough = "\27[2m",
quote_prefix = "\27[90m",
hr = "\27[90m",
table_header = "\27[1m\27[36m",
table_sep = "\27[90m",
},
spinner = { "blue" },
}
Color Specification
Role Colors
Role colors use a descriptive string format:
<foreground> [on<background>] [<attribute>]
Examples:
green onblack bold
cyan onblack dim
white onblack
red onwhite bold
Supported Colors
| Color | ANSI Code |
|---|---|
black | 30 |
red | 31 |
green | 32 |
yellow | 33 |
blue | 34 |
magenta | 35 |
cyan | 36 |
white | 37 |
darkgrey | 90 |
Supported Attributes
| Attribute | ANSI Code |
|---|---|
bold | 1 |
dim | 2 |
italic | 3 |
underline | 4 |
reverse | 7 |
Markdown Colors
Markdown styling uses raw ANSI escape sequences for full control:
heading = "\27[1m\27[36m" -- bold cyan
bold = "\27[1m\27[33m" -- bold yellow
link = "\27[4m\27[34m" -- underline blue
The M.ANSI table provides named constants:
local theme = require("ui.theme")
theme.ANSI.bold -- "\27[1m"
theme.ANSI.red -- "\27[31m"
theme.ANSI.bg_darkgrey -- "\27[48;5;236m"
Custom Theme
To create a custom theme, register it before the TUI initializes:
local theme = require("ui.theme")
theme.themes["my-custom"] = {
name = "my-custom",
background = "black",
menubar_title = "yellow onblack bold",
scrollbar_bg = "black",
scrollbar = "darkgrey onblack",
roles = {
user = "green onblack bold",
assistant = "cyan onblack",
system = "yellow onblack bold",
error = "red onblack bold",
tool = "magenta onblack",
tool_start = "cyan onblack bold",
tool_result = "darkgrey onblack",
dim = "darkgrey onblack",
thinking = "blue onblack dim",
thinking_summary = "darkgrey onblack dim",
compact = "yellow onblack dim",
},
markdown = {
heading = theme.ANSI.bold .. theme.ANSI.green,
bold = theme.ANSI.bold .. theme.ANSI.yellow,
italic = theme.ANSI.italic .. theme.ANSI.magenta,
inline_code = theme.ANSI.cyan,
code_block = theme.ANSI.darkgrey,
code_border = theme.ANSI.darkgrey,
code_bg = theme.ANSI.bg_darkgrey,
link = theme.ANSI.underline .. theme.ANSI.cyan,
strikethrough = theme.ANSI.dim,
quote_prefix = theme.ANSI.darkgrey,
hr = theme.ANSI.darkgrey,
table_header = theme.ANSI.bold .. theme.ANSI.green,
table_sep = theme.ANSI.darkgrey,
},
spinner = { "green" },
}
theme.set_theme("my-custom")
LTUI Rendering Engine
Luna uses LTUI (Lua TUI) built on ncurses for terminal rendering:
256-color support with automatic quantization via quantize_256
Color pair allocation managed by alloc_pair starting at pair 100
Image pair caching for sixel/kitty image rendering (pairs 200+)
Wide character support with proper wcwidth for CJK and emoji
Dirty-region rendering using CSI 2026 for efficient screen updates
ANSI Helpers
The theme module provides text formatting utilities:
local theme = require("ui.theme")
theme.color("error", "Something went wrong")
theme.color("heading", "Title")
theme.strip_ansi(text)
theme.visible_width(text)
theme.wrap(text, 80)
theme.pad(text, 40)
Listing Available Themes
local theme = require("ui.theme")
local names = theme.list_themes()
for _, name in ipairs(names) do
print(name)
end
Feature and system map
This page is the coverage index for ZERG. Every first-class system is listed with the page that documents its current behavior. The generated reference pages (API, CLI, tools, configuration, events, RBAC) are the parameter-level source of truth; the parity gates keep them aligned with the implementation.
Sol — orchestrator
| System | Where it is documented |
|---|---|
| HTTP API surface | API overview · API reference |
| Authentication, tokens, RBAC | Auth flow · RBAC scopes · Auth API |
| ZMQ gateway, ownership, CURVE, per-frame MAC | ZMQ protocol · ZMQ security · Worker integration · Workers |
| Task dispatch, leases, dispatch outbox, cancellation | Workers API · Workers and tasks |
| Event store, projections, replay, event types | Event store · Event reference · Events API |
| Workflows, compensation, recipes | Workflows and scheduler · Workflows API |
| Scheduler | Workflows and scheduler · Scheduler API |
| Goals | Goals API |
| Teams, directives, mailbox | Teams and channels · Teams API |
| Channels (Telegram, Discord, Slack, Teams, webhooks) | Teams and channels · Channels API |
| Memory (file, vector, PostgreSQL) | Memory and workspace · Memory API |
| Workspace scope and tenancy | Memory and workspace · Tenancy posture · Workspace API |
| Providers, inference, model catalog, fallbacks | Providers and models · Provider setup · Model catalog · Inference API · Models API |
| Cost accounting, budgets, spend guard | Cost and budgets |
| Plugins and the Luerl sandbox | Plugin development · Cel standard library |
| ACP control plane | ACP API |
| Audit and retention | Audit API · Audit retention |
| Backup and disaster recovery | Backup and DR |
| Upgrade and rollback | Upgrade and rollback |
| Cluster and HA | Cluster operations |
| Seats and licensing | Seats and licensing |
| Observability, metrics, alerts | Observability · Production runbook |
| Security posture, consent, egress, TLS | Security model · Security posture · Consent · Network egress · TLS posture |
| Configuration and managed settings | Configuration |
| Marketplace and skills | Marketplace API |
| MCP Gateway fleet management | MCP Gateway fleet |
| Local inference, FIM, standalone engine | Local inference · Local inference runbook · Engine provenance |
| Streaming (SSE / WebSocket) | Chat API · Completions API · Events API |
| Rate limiting and circuit breakers | Configuration · Providers and models |
| Managed settings and config authority | Configuration |
| Nydus federation | Nydus Network |
| Release and supply chain | Release history |
Luna — worker runtime
| System | Where it is documented |
|---|---|
| Tool registry (92 tools) | Tools · Tool reference |
| Permission modes and sandbox layers | Permissions and sandbox · Security model |
| Sessions, dual-write JSONL + SQLite/FTS, branching, sharing | Sessions and chat |
| Slash commands (TUI) | Sessions and chat |
| Memory backends and retention | Memory and workspace |
| Sub-agents (local, ZMQ, team, background) | Tools · Sessions and chat |
| MCP client and MCP server modes | MCP integration |
ACP server (--acp-serve) | ACP API |
| Team membership and mailbox | Teams and channels |
| Skills and marketplace installs | Tools · Marketplace API |
| Plugins and extension consent | Plugin development · Consent |
| Computer-use and desktop tools | Tool reference · Tools |
| Git snapshots and checkpoint restore | Sessions and chat · Tool reference |
| Vision and image input | Tool reference |
| Prompt cache | Prompt cache |
| Keyring, profiles, self-update | CLI configuration · CLI commands |
| Local inference and FIM | Local inference · Local inference runbook |
| Editor agent plane / standalone engine | Local inference · Engine provenance |
| Vision pipeline | Tool reference · Tools |
Mango — identity and authorization
| System | Where it is documented |
|---|---|
| Login, tokens, service tokens, revocation | Auth flow · Auth API |
| RBAC, users, orgs, roles, teams, tasks | RBAC scopes · Mango HTTP API |
| LDAP/GLAuth federation | Auth flow · Mango configuration |
| Audit chain and archive | Mango HTTP API · Audit retention |
| Rate limits, lockout, trusted proxies | Mango configuration |
| Orchestrator lease | Mango HTTP API |
Limon — operations console
| System | Where it is documented |
|---|---|
| Views, navigation, authentication | Limon console · Limon user guide |
Cross-cutting
| System | Where it is documented |
|---|---|
| Air-gap deployment | Air-gap install |
| Known limitations and non-claims | Known limitations |
| Support matrix | Support matrix |
| Development and testing | Development · Testing |
| Documentation conventions | Docs style |
Coverage gates
The generated reference is not trusted by convention. Machine gates fail the build if a surface drifts from the implementation:
API routes: every documented route resolves to a spec row (api_reference_parity_lint).
Events: the event reference covers the generated event-type contract (contract/events.yaml).
Tools: the tool reference covers all 92 registered tools (ci/tools_manifest.json, tools_taxonomy_parity_lint).
CLI: every command and subcommand is documented (docs_command_lint).
Configuration: every Sol/Luna config key and env var is documented (config_env_docs_parity_lint).
RBAC: the scope reference is checked against the route matrix (rbac_route_matrix_lint).
Docs: every chapter is reachable, every link and anchor resolves, and generated chapters match their canonical source (portal_link_check, sync_docs --check).
Engine reference — generated from the canonical engineering source. Do not edit this page by hand.
ZERG Glossary
One-page definitions for the names and terms used across the ZERG
documentation. The compressed engineering authority is AGENTS.md;
this page is the human-readable entry point.
Products & brands
| Term | Definition |
|---|---|
| ZERG | The Spacebeam-hosted control plane at zergs.net — invite-first waitlist, not launched (the SaaS home currently hosts the Nydus Network). |
| WILDZERG | The on-prem/self-hosted variant at wildzerg.com — the “wild blueprint” (runit + podman GitOps). Full sovereignty, air-gap capable. LIVE. Use “WILDZERG”, never the retired “Cosmos”. |
| ZERGBASE | The MIT-licensed open-source infra panel (zergbase.com) — the funnel into Zerg/WILDZERG. |
| Nydus Network | The federation layer — a feature/arrangement of WILDZERG (not a third brand); registry at nydus.zergs.net. |
| MCP Gateway | The Microsoft MCP Gateway integration (MIT) — Enterprise-tier add-on for managing fleets of MCP servers on Kubernetes. |
Services (the four pillars + two web properties)
| Term | Definition |
|---|---|
| Sol | The Erlang/OTP orchestrator (server/). Cowboy HTTP (SSE/WS streaming), llama.cpp inference, ZMQ ROUTER gateway, event-sourced backbone (Mnesia), workflow engine, scheduler, Luerl plugin sandbox, provider adapters with circuit breakers, distributed-Erlang clustering. |
| Luna | The LuaJIT worker-node agent (client/). <10 MB RAM; tools=92 registered tools + MCP; 8 agent modes; sandbox backends; dual-write sessions; cross-session memory; sub-agents; vision pipeline. |
| Mango | The Python/Tornado identity/auth microservice (mango/). Token auth, RBAC with cached permission resolution, audit trail, ZMQ event bridge to Sol for live cache invalidation, SQLite/PostgreSQL. |
| Limon | The Vue.js 3 ops console (limon/) — real-time agent activity (WebSocket + SSE), skills marketplace, chat interface, infra status. Internal dev mirrors live on *.nonsense.ws. |
| Toronja | The public product page (toronja/, served at zergs.net). SHARED source — wild applies post-build transforms for wildzerg.com; never edit for one variant. |
| Starfruit | The corporate page (starfruit/, served at spacebeam.org). SHARED source with wild transforms. |
Runtime concepts — Sol
| Term | Definition |
|---|---|
| Event store | The Mnesia event-sourcing backbone: typed events (event_types=102), framed WAL segments, single-ingress archive, terminality-aware compaction, replay on boot. See event-store.md. |
| Projection | A read model built from the event stream (tasks, chat, goals, sessions, lanes). Projectors compare-and-write on seq (monotonic projection guard). |
| Dispatch outbox | sol_dispatch_outbox — the receipt row written pre-send in the dispatch funnel; cleared at the terminal chokepoint; boot reconcile requeues at-least-once. |
| Ownership gate | sol_zmq_ownership — result/token/error/event frames are accepted only from the RECORDED executor (stamped at dispatch); executor-less or mismatched senders are refused. |
| Lane | A local-inference serving channel: a named model slot with an engine, host policy, and port. See local-inference-lanes.md. |
| Engine | A certified llama.cpp binary artifact built/certified/distributed by the engine pipeline (build → certify → distribute → rollback), with provenance receipts. See engine-provenance.md. |
| Workflow (saga) | The gen_statem workflow engine with compensation (LIFO marker-before-effect), pause/resume gates, budgets, and durable attempt markers. |
| Scheduler | Cron/at/every scheduled tasks — single-writer claim (atomic CAS), runtime leases, naive-UTC timezone posture (documented). |
| Plugin sandbox | Luerl plugins run only through budgeted VM runners (reductions + wall clock); wire tool names are plugin__<plugin>__<name> and never shadow builtins. See plugin-development.md. |
| Permission modes | 6 modes: default, allow-all, deny-all, read-only, plan, auto (AI classifier) — see permissions.md; execute-class RBAC gates mutation tools. |
Runtime concepts — Luna
| Term | Definition |
|---|---|
| Sandbox backends | Mutually exclusive execution-isolation backends: bwrap (namespace/network/read owner), Landlock (Linux write-deny fork layer — never executes), seatbelt (macOS). The machine count sandbox_layers=3 is the backend census. |
| Agent modes | 8 modes: Build/Plan/Explore/Review/General/Coordinate + the swarm modes Leader/Teammate. |
| Sub-agent | A child agent spawned locally, over ZMQ, in a team, or in the background; children inherit the parent’s execution config + workspace + ruleset with deny=∪ ask=∪ allow=∩. |
| Team swarm / directive | Multi-agent coordination: a LEADER assigns work via signed team_directive frames; teammates execute and reply through the team mailbox. Directives are the fleet-correct assignment plane (team_spawn is retired). |
| Dual-write sessions | Session history is appended to JSONL and SQLite/FTS5 (fsynced, schema-version ledger). See sessions.md. |
| Cross-session memory | 7 backends (JSON, SQLite, dual-write, vector, file, graph, hybrid) with injection-scoped <untrusted-memory> fences. |
| Consent model | Repo-config security families require explicit user consent (.luna/trust approvals store); security families are ignored fail-closed without TTY. See consent.md. |
Wire & trust
| Term | Definition |
|---|---|
| ZMQ planes | ROUTER/DEALER worker plane + PUB/SUB events between Sol and Luna (msgpack wire). See zmq-protocol-reference.md. |
| CURVE | ZMQ curve25519 transport encryption — default-on for non-loopback; server cert auto-keygen; per-worker enrollment keys (key_id) with revocation. |
| MAC plane | Per-frame HMAC on worker-plane frames, derived from the verified credential (zmq_frame_mac lever: required/prefer/off). |
| Enrollment key | A per-worker provisioning key checked at READY; revoked/unknown keys are refused; worker-bound keys block stolen-key re-registration. |
| Ready counter | Monotonic u64 in the registration material; stale/duplicated READY is detected and refused. |
| Identity propagation | user_uuid + permissions are captured in the caller (HTTP request process) and carried explicitly through every deferred-execution path — never via the process dictionary. |
| FIM | Fill-in-middle completion — the measured editor-completion plane. |
Process & governance
| Term | Definition |
|---|---|
| Phase file | plan/phase-vX.Y.Z-*.md — the plan for a release window; archived under plan/archive/ when closed. See plan/README.md. |
| D-number | A numbered engineering decision recorded in the decision ledger, docs/archive/AGENTS-decisions-archive.md. Decisions carry the “why”. |
| Residual register | The live findings ledger (plan/residual-register-v0856.md); registers chain v0711 → v0738 → v0765 → v0856; the chain lint is machine-checked. |
| Verdict | A review artifact under review/ (e.g. PASS / PASS-WITH-CONDITIONS / FAIL) — see review/README.md. |
| Counts ring | The machine-derived metric ring: ci/generate-agents-counts.sh → AGENTS.counts → rendered into docs by ci/render-docs-counts.py; ci/docs_counts_lint.py gates it. Never hand-edit keyed counts. |
| Required checks | The branch-protection CI check list (required_checks=20, authoritative in ci/branch_protection_lint.py). |
| Lint battery | 274 lint scripts (310 invocation sites) in the lint-suite gate — the project’s recurrence-prevention mechanism. See ci-lint-census.md (docs/ci-lint-census.md). |
| Crow | The CD pipeline (.crow.yml, podman backend) — owned by wild (separate repo: https://git.zergs.net/spacebeam/wild.git, see WILD_REF). |
| Forgejo Actions | The CI test gate (.forgejo/workflows/ci.yml), self-hosted on wild toolchain images. |
| wild | The release-engineering repo/platform (runit + podman GitOps) that owns deploys and CD. |
| wale | The named implementation-review persona/batch convention used for parallel remediation batches. |
Release history
The canonical release ledger is docs/CHANGELOG.md in the repository. This page summarizes the current line and the release discipline.
Current
| Version | Date | State |
|---|---|---|
| 1.003.0 | 2026-11-23 | Tagged and released by wild release engineering; Crow pipeline 768 green through publish-release; production serves Sol + Mango 1.003.0 |
The release record is review/2026-11-20-release-record.003.0-md.the; verdict is PASS-WITH-CONDITIONS with CI wild-owned/conditions tracked by owner and date date.
How releases work
- ZERG lands version-marked phases on
mainwith a phase file, counts, and decision records. - The release act (signed tag + Crow CD + deploy) is owned by wild release engineering.
- The exact-SHA preflight refuses a dirty tree, a missing version mirror, or a red gate.
- The signed artifacts are published with a minisign TOFU anchor and cosign/SLSA/SPDX attestations.
- Production deploy is an atomic image swap; rollback is the previous image tag.
Next
Architecture decision records
ZERG records material architectural decisions as ADRs. The canonical files live in docs/architecture/ in the repository.
| ADR | Decision |
|---|---|
| ADR-0001 | Control-plane HA target |
| ADR-0002 | Supervision failure domains |
| ADR-0003 | Transactional commit boundary |
| ADR-0004 | Partition singleton funnels |
| ADR-0005 | Provider-plane unification |
| ADR-0006 | Worker-transport unification |
| ADR-0007 | Event-log tiers and retention |
| ADR-0008 | Entity durability classes |
| ADR-0009 | Contract generation single source |
| ADR-0010 | Acyclic layer DAG (ACCEPTED) |
| ADR-0011 | Tenant/worker isolation (DECIDED) |
| ADR-0012 | Time, memory, and session semantics |
| ADR-0013 | Operability before scaling |
| ADR-0014 | Node-local durability and DR |
| ADR-0015 | Segmented compactor staging |
| ADR-0016 | Upgrade and config authority |
Read the full text, status, and consequences in the repository (docs/architecture/adr-*.md), or start with Architecture.
Engine reference — generated from the canonical engineering source. Do not edit this page by hand.
Development Guide
Prerequisites
| Dependency | Version | Purpose |
|---|---|---|
| Erlang/OTP | 29.1+ | Sol server runtime |
| rebar3 | 3.20+ | Erlang build tool |
| LuaJIT | 2.1 | Luna agent runtime, ZERG CLI |
| gcc | C11+ | FFI bindings, single-binary build |
| upx | optional | Secure release binaries only — local builds pass --plain --no-upx |
| ncurses | 6.0+ | Luna TUI |
| libcurl | 7.68+ | Luna HTTP/SSE |
| ltui | any | Lua TUI library (LuaRocks) |
The OTP floor is Erlang/OTP 29.1+ (OTP 30+ is the forward aim; OTP 28 is not a support target).
OTP floor datum and deprecation gate
The floor is a datum, not prose: contract/otp-floor.yaml is the single
source (floor, forward_aim, not_supported, note). Every README /
CONTRIBUTING / docs/ / docs-site/ prerequisite copy is machine-checked
against it by ci/otp_floor_lint.py; moving the floor is one edit to the
datum plus the copies — never one without the other.
server/rebar.config enables warnings_as_errors, warn_obsolete_bool_op
(opt-in and/or warnings) and warn_possibly_unsafe_function. Old
type-testing BIFs (nowarn_obsolete_guard is NOT set), deprecated
functions/types/callbacks, and recently removed functions warn by default,
so with warnings_as_errors they are build failures. warnings_as_errors
is on in the base, test and prod profiles. The ONE sanctioned suppression is
nowarn_deprecated_catch (the bare-catch burndown, OTP-19938): it is
paired with the shrink-only ratchet ci/catch_site_lint.py +
ci/catch_sites.baseline.tsv.
Run the local deprecation gate (also the zerg-side leg of the toolchain image-bump routine; the image itself is wild-owned):
sh ci/otp_deprecation_gate.sh --static # fast: datum + warning-class/suppression contract
sh ci/otp_deprecation_gate.sh # clean Sol compile + xref in the otp_deprecation_gate profile
The compile leg uses the dedicated otp_deprecation_gate rebar profile
(server/_build/otp_deprecation_gate), so _build/default and
_build/test are untouched. Any deprecation/obsolete/removal warning in
server/src or server/spike is RED, and rebar3 xref must stay clean
for deprecated_function_calls + unsafe_function_calls.
OTP removal sweep (when the next release’s removals list lands)
Trigger: the Removed section of the Erlang/OTP release notes for a release above the datum floor (OTP 30+). Run the sweep in one branch before the new toolchain image is pinned. The catch/atom/persistent-term batch is the template: every class got a census, a behavior-preserving rewrite or a recorded allowlist, and a born lint so the class cannot silently return.
- Capture the list verbatim. Copy the release’s removed
modules/functions/options into the trial/tracking document (the OTP 30
trial uses
plan/otp30-trial-matrix.md). Do not summarize from memory. - Map removals to this tree.
cd server && rebar3 as otp_deprecation_gate clean && rebar3 as otp_deprecation_gate compileplusrebar3 as otp_deprecation_gate xrefsurface compiler and xref findings;grep -rnthe removed names acrossserver/src,server/test,server/spike,client/,mango/andzerg-cli/. Xref only sees cross-module calls — removed options and behaviour changes need the grep leg. - Re-run the construct censuses, not just the removal grep:
bare
catch:python3 ci/catch_site_lint.py(must not exceedci/catch_sites.baseline.tsv; the silencer stays only while the baseline is non-zero). dynamic atom creation / unsafe calls:python3 ci/atom_unsafe_lint.py(ci/atom_unsafe_allowlistentries carry a provenance reason).persistent_term:put:python3 ci/persistent_term_write_lint.py(runtime-class rows are forbidden — use an ETS carrier). otherci/*lint*gates named by the release notes’ affected areas (ETS options,binary_to_termflags, TLS/httpc options,…). - Fix or record. Rewrite to the replacement API where one exists; when
a removal has no replacement, record the decision and the residual row
in the same change. Never add
nowarn_removed/nowarn_deprecated_*(the gate refuses them); the sanctioned catch aid requires a ratchet entry. - Prove it on the trial image. Run the full trial matrix
(
plan/otp30-trial-matrix.md): compile, xref, eunit, CT, the lint battery, docs-hygiene and the JITemu_flavorassertion. Findings split into “adopt now” vs “record for the next dot release” (e.g. 30.1). - Update the floor datum and copies together (
contract/otp-floor.yaml, thenpython3 ci/otp_floor_lint.py), and add the proven toolchain image row todocs/deployment-guide.md.
Development Workflow
Sol Server
cd server
# Build
rebar3 compile
# Dev shell (Cowboy HTTP on port 21434)
rebar3 shell
# Run tests
rebar3 eunit
# Build release
make release
# Build tarball
make tar
Luna Client
# Source mode (no build needed)
cd client
luajit main.lua --configure # interactive setup wizard
luajit main.lua --connect tcp://127.0.0.1:5555 # Sol-fed worker (lane grants)
# The CLI corpus is 100 suites (99 passing + 1 environment-gated skip).
# Run individual tests
luajit tests/test_core.lua
luajit tests/test_ffi.lua
luajit tests/test_provider.lua
#... run every file: for f in tests/test_*.lua; do luajit "$f"; done
# Build single binary
bash client/build/build.sh # Secure (bytecode + XOR + CRC32 + UPX)
bash client/build/build.sh --plain # Plain (debugging)
Project Structure
server/
├── src/ sol_modules=489 Erlang source modules (see AGENTS.counts)
├── test/ unit + CT suites (see AGENTS.counts)
├── config/ sys.config, vm.args, production configs
├── rel/ Release configs, systemd unit, env template
└── priv/ Static assets, bundled plugins
zerg-cli/ ZERG CLI — repo-root tree (cli_commands=92 commands
+ cli_subcommands=37 subcommands — see AGENTS.counts;
The CLI never lived under
server/, the old tree diagram was an invention)
client/
├── core/ Core modules (agent loop, session, provider)
├── core/tools/ 22 built-in tool modules
├── ui/ 17 TUI modules (app, chatpane, inputbar, theme, markdown, tui)
├── ffi/ 18 FFI binding modules (curl, process, dir, zmq, md4c, websocket, dns, terminal)
├── tests/ test files: luna_test_functions=691 / luna_test_assertions=22038 (see AGENTS.counts)
└── build/ Single-binary build system
docs/ User-facing documentation (docs_artifacts=70 artifacts)
plan/archive/ plan_files=1414 archived phase plans
review/archive/ historical reviews (categorized)
reference/ Reference systems and docs (read-only)
Counts are machine-derived from
AGENTS.countsat the repo root (regenerate rather than hand-editing).
Adjacent checkout (starfruit/toronja page builds):
@spacebeam/uicomes from thespacebeam/corprepo. Clone it next to this checkout (git clone https://git.zergs.net/spacebeam/corp.git../corp) and recreate the untrackeduilink (ln -s../corp/ui uifrom the repo root) before building those SPAs. The former trackedcorp ->../corpsymlink was removed in: fresh clones must not carry a dangling link, and nothing in the shipped product depends on it.
Code Conventions
Erlang (Sol Server)
Use OTP behaviours for all stateful processes (gen_server, gen_statem, gen_event)
process_flag(trap_exit, true) in all gen_servers that own resources
ETS {heir, Pid} for all critical tables
logger module for all logging (never io:format)
-vsn attribute on all modules
simple_one_for_one for dynamic child factories
rest_for_one for top-level supervisor
No TODO/FIXME/HACK comments
OTP/stdlib return-shape seams
The A-1 incident (public_key:cacerts_load/1 returning the bare atom
ok while consumers matched {ok, Certs}) was a shape assumption that
signature parity could not see. The shape contract now lives in
ci/otp_shape_seams.yaml: one row per OTP/stdlib function whose return
shape this tree consumes, with its expected success/error shapes and the
seam module that owns the shape.
Gated rows are enforced by ci/otp_shape_seam_lint.py. The raw
module:function may be called only inside its seam module, and a
literal tuple/record match on it outside that module (a case/try
arm or a direct Pattern = Module:Function(...)) is a finding.
Consumers call the seam function instead. Current gated families:
sol_cacerts (cacerts), sol_http_req (query parsing), sol_gun
(gun awaits), sol_file (read/open), sol_exec (bounded exec),
sol_net (inet parsing/formatting/sockets), sol_ssl (peer cert and
peer name).
Observed rows record a shape contract plus a mandatory reason where
a seam is not justified yet (for example cowboy_req:read_body/2,
already governed by ci/read_body_more_lint.py). They are re-checked
at every OTP RC trial.
Exemptions are intentional edge sites in the inventory. Every
exemption needs reason and owner; a stale exemption (matching no
current finding) fails the lint.
To add a family: create the seam module under server/src/ with a
-spec carrying the expected shapes, export the seam functions, add the
inventory row, move production call sites through the seam, and run:
python3 ci/otp_shape_seam_lint.py
python3 -m pytest tests/test_otp_shape_seam_lint.py -q
The lint fails closed on a missing/empty inventory, an empty corpus, a
missing scan root, a stale seam row (module or seam function absent) or
a duplicate row. It is not yet a lint-suite row ( reports the
invocation; wiring is tracked with the phase record).
Lua (Luna Client)
Module pattern: local M = {}; M.__index = M; return M
Instance pattern: setmetatable({}, M)
pcall for all fallible operations
cel.json for serialization (auto-selects backend)
Atomic writes (write to .tmp, then rename)
Coroutine-based async with Turbo.lua IOLoop
Prompt layout is cache-sensitive: stable sections first, literal boundary,
then volatile context — see docs/prompt-cache.md before changing
system_prompt.lua, provider_request.lua, or the sub-agent spawn path
Sanctioned forks and vendored overlays
The repo deliberately carries two known-forked surfaces. Both are gated; neither is drift.
CLI ↔ Luna curl (zerg-cli/ffi/curl.lua ↔ client/ffi/curl.lua)
Decision: keep the sanctioned fork. The two files
share the same origin, the same ffi.cdef + lib-load ladder, pooled easy
handles, write-callback accumulation, and protocol pinning — but they serve
different runtimes and must NOT be merged into one shared source:
| Divergence | zerg-cli/ffi/curl.lua | client/ffi/curl.lua |
|---|---|---|
| Runtime | synchronous operator binary | coroutine/Turbo-IOLoop agent runtime |
| Redirects | owns the credential-safe manual walk (per-hop header strip, body policy) — | callers disable auto-follow (allow_redirects=false) and validate hops at the tool layer (client/core/web_fetch_shared.lua) — |
| setopt | every call through setopt_checked (rc-checked chokepoint + typed unknown-option accounting) — | thin typed setopt_{long,string,slist,callback} wrappers |
| Body caps | max_response write-callback gate + output_file streaming + hostile-header ceiling | CURLOPT_MAXFILESIZE + max_body_bytes (default 1 MiB) |
| Streaming | synchronous chunk pump (Ctrl-C aware) | M.stream coroutine yielding typed __status__/__error__/__poll__ events |
| SSRF seam | CURLOPT_NOPROXY loopback + M._protocol_pins/M._timeout_policy | CURLOPT_RESOLVE DNS pinning (H5) |
| Test seam | M._use_lib, M._protocol_pins, M._timeout_policy, M._noproxy_value | M.drain, M._monotonic_ms + client/tests/mocks/curl_mock.lua |
Porting rule: a change to the shared contract (M.request/M.stream
error shapes, the lib-load ladder, protocol pins, TLS posture) must be
considered for both files and either ported or recorded here as a new
intentional divergence. Security fixes are never one-sided if the other
side has the same exposure. Existing gates: ci/mock_parity_lint.py pins
the Luna mock’s signature surface against client/ffi/curl.lua; the CLI
half is pinned by zerg-cli/tests/test_zcli_setopt_chokepoint.lua and the
transport/redirect matrix suites.
Vendored forks (spacebeam/{chumak,nacerl})
The former server/_checkouts/{chumak,nacerl} overlays are RETIRED
both patched trees live as self-hosted Forgejo forks
(https://git.zergs.net/spacebeam/chumak and .../nacerl, branch
zerg/main) pinned by 40-hex refs in server/rebar.config and recorded in
server/rebar.lock — ci/rebar_lock_drift_lint.py gates them. Patch lists:
each fork’s README.md (“ZERG PATCH tracker”). On an upstream base bump,
rebase the fork, re-pin the ref, and re-lock in the same commit. The interim
ci/overlay_drift_lint.py + ci/overlay_manifest.json pin were deleted in
the same commit that deleted the overlays (their own documented retirement
playbook).
Adding a New Feature
- Create a plan in
plan/directory - Implement the feature with tests
- Run the full test suite (both server and client)
- Create a review in
review/directory - Update
AGENTS.mdif the architecture changes
Adding a Builtin Tool (Luna)
The contributor touchpoint map for builtin__* tools (/,
DX-7 — previously only discoverable inside the decision archive; the
enforcement below is CI-late, so follow this list top-to-bottom):
- Handler — add the tool to a family module under
client/core/tools/builtin_<family>.lua(or a new family registered inclient/core/tools/_loader.lua’sbuiltin_modules). Follow theregister(tools, helpers)convention; returnnil, erron failure. - Naming —
builtin__<name>; a name colliding with the reserved plugin-tool list fails the plugin-sandbox lint. - Shell/spawn discipline —
cel.shell_quoteevery shell argument; forward the caller’s execution config on EVERYFFI.spawn/Process.spawn_stdio(a config-less spawn silently disables the sandbox;ci/spawn_config_lint.py). - Permission surface — decide the per-mode default in
client/core/permission_ruleset.lua(MODE_DEFAULTS; unlisted tools fall to the mode’s["*"]row). - Manifest — add the name +
read_footprint+registration_probeclassification toci/tools_manifest.json;ci/tools_manifest_lint.pyis born-required (count + registration-source census), andci/generate-agents-counts.shre-derivestools=for AGENTS.counts. - Tests —
client/tests/test_<family>.lua; runclient/run_tests.sh(skip allowlist is gated — seeci/client_test_skip_allowlist.txt). - Docs —
docs-site/guide/tools.md(user-facing table).
Test Naming Conventions
Server: test/sol_<feature>_tests.erl or test/sol_s<phase>_tests.erl
Client: tests/test_<feature>.lua
CI & CD
ZERG uses two separate pipelines, both self-hosted on blue:
| Pipeline | File | Trigger | Purpose |
|---|---|---|---|
| CI (test gate) | .forgejo/workflows/ci.yml | push / PR to main | ci_jobs=47 jobs (compile, CT, xref, client/Mango/CLI/Limon tests, lints, tri-service integration + E2E). Runs on Forgejo Actions runner labels erlang-29 / luajit / python-3.12 / node-20. |
| CD (build/deploy) | .crow.yml | tag (v*) | Crow CI on podman (CROW_BACKEND=podman — docker is banned). cd_steps=18 steps: verify-tag → docs-hygiene → fetch-grammars → ci-status-check → branch-protection-live → build-images → build-engines → supply-chain → push-staging → build-reproducibility → smoke-staging → kill-proofs-check → release-tag → deploy-staging → heartbeat-probe → relaunch-cluster → promote-prod → publish-release. Owned by wild (wild/AGENTS.md §“CD Build Execution”).: the kill-proof gate runs before any host change, and push-staging publishes only a per-run ephemeral tag — :V/:staging are created (and signed/verified) by release-tag after the reproduction/smoke/kill-proof gates pass. |
Release preflight (exact-SHA gate)
ci/release_preflight.sh is the tag-lane gate that proves the EXACT commit
being tagged is releasable. Crow runs it in ci-status-check (after the
required-status verdict, before build-images) with the peeled tag SHA:
bash ci/release_preflight.sh --sha "$(cat ci-tag-sha)"
# local operator / clean exact SHA:
bash ci/release_preflight.sh
It refuses a dirty worktree, asserts HEAD == the tag target (and
VERSION == the tag name when --tag is given), and runs
check-agents-parity, floor_base_guard --check --base-ref HEAD^,
version_mirrors --check, version_stamp_lint, the
env_baseline.derived/header equality, the required-check mirror, the
lint-contract corpus, the carry-register date check, and the
precommit_pins_lint / gitleaks_allowlist_lint legs. A red preflight
stops the pipeline before a single artifact is built.
The floor leg compares the release commit with its PARENT: the release
commit may not lower a floor relative to the history it was built on. The
pre-merge floor-history gate (plain floor_base_guard.py --check against
origin/main) remains the merge authority. --only <legs> is a
diagnostic/fixture mode; the release lane runs the full battery.
Branch protection requires required_checks=20 status checks before merge
(the authoritative list lives in wild/scripts/provision/configure-zerg-repo.sh,
mirrored by ci/branch_protection_lint.py; never enumerated in prose — the
list drifted the last time it was hand-copied). The component + E2E gates
were promoted to REQUIRED in: a PR that breaks Luna, Mango, Limon,
the CLI, the lint battery, or the E2E/stress suites must NOT merge green.
Before pushing a PR, run the same gates locally:
# Server
cd server && rebar3 compile && rebar3 xref && make test-unit
# Client
cd client && bash run_tests.sh
# Lints (all wired as CI gates)
python3 ci/mock_parity_lint.py
python3 ci/sibling_propagation_lint.py .
python3 ci/worker_reset_lint.py
bash ci/check-version-sync.sh
Production binaries are the secure build by default (bytecode + XOR +
CRC32 + UPX + strip). For local debug binaries: bash client/build/build.sh --plain --no-upx
(positional args, primary interface) or BUILD_FLAGS='--plain --no-upx' bash client/build/build.sh
. Production releases
publish arcane-style per-component assets (luna, zerg, sol-<ver>.tar.gz,
SHA256SUMS) to the Forgejo release; registry.nonsense.ws is internal-only.
Debugging
Sol Server
# Attach to running node
# Deployment is the wild blueprint (runit + podman); no docker exec.
# Operators use wild's own tooling (the wild repo: https://git.zergs.net/spacebeam/wild.git,
# see wild/AGENTS.md) — /, DX-5: the old `zergctl` name
# referred to tooling that only exists in the wild repo, never in-tree.
# Check process state
sys.get_state(sol_inference).
# Check ETS tables
ets:tab2list(sol_models).
Luna Client
# Enable debug logging
export LUNA_LOG_LEVEL=debug
luajit client/main.lua --connect tcp://127.0.0.1:5555
# Check logs
ls ~/.luna/logs/
Luna snapshot benchmark
bash benchmarks/luna_snapshot_bench.sh --table compares the shipped
refs/luna-snapshot ref/commit store with a benchmark-only shadow-store
prototype (seeded persistent index + write-tree). The measured NO-WIN
decision and numbers are in benchmarks/luna-snapshot-bench.md: once the
list/diff/retention metadata plane is included, the shadow path is 1.60×
(2 k files) to 1.78× (8 k files) faster over a 10-turn session — below the
2× gate — and its one-time index seed/scaffold grows .git 34–38 % more, so
the working store is retained. Restores now stage through a throwaway index
(read-tree + checkout-index), so a kill at any phase boundary leaves the
old or the new tree (client/tests/test_git_snapshot_restore_crash.lua).
Engine reference — generated from the canonical engineering source. Do not edit this page by hand.
Testing Guide
Test Statistics
| Suite | Current values | Source | Runner | Status |
|---|---|---|---|---|
| Sol (server) | sol_eunit_total=10499 eunit / sol_eunit_baseline_failures=0 env-baseline failures (see §Env baseline below; the filtered make test-unit battery is a SEPARATE, smaller population — never conflate) + CT suites (CI-gated) | AGENTS.counts (sol_eunit_total, sol_eunit_baseline_failures); server/test/env_baseline.derived is the machine artifact — re-derive with cd server && make eunit-baseline | rebar3 eunit + CT | Stable |
| Luna (client) | luna_test_functions=691 / luna_test_assertions=22038; luna_tests_pinned_total=865 with luna_tests_pinned_skipped=8 documented skips on a dev host — session-3 skip-truth: the 2026-11-04 full battery reports 905 passed / 0 failed / 8 skipped (913-row corpus; the pinned total 865 is the floor) (test_git_snapshots UN-SKIPPED — in-file git probe, runs 40/40 wherever git exists; test_profiles DELETED — stale pre-merge suite; the three test_ioloop* files and test_safety_wiring UN-SKIPPED; all of the 12 exact-match allowlist rows carry owner+expiry annotations); the pinned counters re-derive at the next counts ring | AGENTS.counts (luna_test_functions, luna_test_assertions, luna_tests_pinned_total, luna_tests_pinned_skipped); test-file count = ls client/tests/test_*.lua | wc -l (grows as tests land); runtime re-measured per run (client/run_tests.sh, whose executed-test floor = pinned_total − allowlist rows − 2 structural; --floor-check prints it) | LuaJIT | Stable |
| Mango | mango_tests_pinned_total=2457 collected; mango_tests_pinned_skipped=31 is the default/offline reverse-leg pin and mango_tests_pinned_skipped_offline=42 is the measured offline reverse-order cap — the 2026-11-12 offline runner is 2,230 passed / 36 skipped (every skip is PostgreSQL-gated, enumerated by class in ci/generate-agents-counts.sh); the two-run PostgreSQL leg on the same database is GREEN — 2,236 passed / 1 skipped then 2,237 passed / 0 skipped | pytest --collect-only -q | tail -1 for the corpus; runtime pass/fail re-measured per run — see the root AGENTS.md Tests row | pytest | Stable |
| ZERG CLI | cli_tests_pinned_total=100 suites (cli_tests_pinned_passed=99 passed / cli_tests_pinned_skipped=1 skipped — bash zerg-cli/tests/run_all.sh reports 99/100 passed, 1 skipped, 0 failed; the env-gated integration suite reports SKIP, not passed) | file listing + tests/run_all.sh (empty corpus fails loudly); the suite count is machine-gated by ci/truth_counts_lint.py | LuaJIT | 0 failures |
| Limon | limon_tests_pinned_total=1291 pinned; the release-candidate battery measured 1178 passed / 1 skipped (floor pin 1179; 2026-11-06, local run, no committed raw log) | AGENTS.counts (limon_tests_pinned_total, limon_tests_pinned_skipped) | vitest | 0 failures |
| Lint battery | lint_contract_tests=3543 machine-derived | AGENTS.counts (lint_contract_tests) + the required lint-suite CI job | python3 | 0 failures |
Structural counts are machine-generated in
AGENTS.counts(ci/generate-agents-counts.sh) and gate on drift. Runtime battery numbers (pass/skip per run) shift as tests are added — re-measure via the runners above or read the latest gate table rather than trusting any hard-coded runtime integer.
Mango skip matrix
All Mango skips are classified and owned (owner: Mango maintainers; re-audit at the 2026-08-31 baseline expiry):
| Skip | Class | Why | Runs when |
|---|---|---|---|
test_add_org_pg_atomicity.py ×1, test_audit_anchor_schema_drills.py ×2, test_audit_anchor_table_mismatch.py ×1, test_audit_checkpoint_failure.py ×1, test_audit_checkpoint_retention.py ×1, test_audit_in_txn_concurrency.py ×1, test_audit_key_rotation.py ×1, test_audit_seam_savepoint.py ×2, test_ldap_federated_login_pg.py ×5, test_pg_cas_live.py ×7, test_pg_writer_persistence.py ×2, test_postgresql_backend.py ×4, test_revocation_retention.py ×2, test_revocation_watermark.py ×1, test_storage_parity.py ×1, test_token_cap_pg_ordering.py ×2, test_audit_durability_drills.py ×1, test_identity_durability_drills.py ×1 (36 total, machine-enumerated in ci/generate-agents-counts.sh) | PG-CONDITIONAL | need a real PostgreSQL (pool mode) | MANGO_PG_TEST_URL/MANGO_PG_TEST_DSN set — the mango-tests CI job provisions pgvector/pg17 and sets both; locally the documented throwaway container (podman run -d --name mango-pg-798 -p 127.0.0.1:15433:5432 -e POSTGRES_USER=zerg -e POSTGRES_PASSWORD=zerg -e POSTGRES_DB=zerg docker.io/pgvector/pgvector:pg17) makes the full battery run with 0 skips |
test_ldap_auth.py ×1 (pytest.skip, only when openssl cannot mint a self-signed certificate) | ENV-GATED | openssl unavailable on the host | when a usable openssl is on PATH; the measured reference battery has no openssl skip, so the offline cap stays 36 |
Session-3 skip-truth (2026-10-16): the test_loopback_parity_fixture.py
×9 STRUCTURAL rows are GONE — the per-predicate parametrizations now FILTER
at collection (same assertions, no runtime skips; the two grant rows retired
from ci/python_skip_allowlist.txt). The PG row is corrected from the stale
18 to the real 25 (the audit-seam ×2 + ldap-pg ×5 sites were never
folded in).
The retired-feature rows (test_auth.py refresh-token, test_plugins.py
Azure/LDAP, the old v63 token-type stubs) are GONE — the deleted contracts
and their unconditional skips were removed with the features
and the -era matrix naming them was stale
. Offline battery:
1627 passed / 27 skipped; PG-up battery 1653 passed / 1 environment skip
.
Fixes that made the PG suites runnable: psycopg_pool added to
mango’s main deps + requirements.txt; the fake-psycopg stub in
test_postgresql_backend.py is installed only in offline mode (it poisoned
sys.modules and broke psycopg_pool imports); the missing pg_harness
fixture in test_add_org_pg_atomicity.py is real now (pool backend +
setup_db + idempotent teardown) and the test’s impossible FK-violation
trigger was rewritten as an injected-statement-failure rollback test
(the v0001 schema has no FK on user_orgs); the source-inspection paths
in test_pg_writer_persistence.py are __file__-anchored.
Env baseline — ZERO ENTRIES since then
cd server && make eunit-baseline (the UNFILTERED corpus, including
infra-requiring modules excluded from the CI unit corpus) fails on a fixed,
documented set of environment-dependent tests, recorded one-per-line in
server/test/env_baseline.txt with the 0-new policy (a change may never
ADD a failing test there). : all 42 entries were
root-caused and FIXED — the corpus has since grown through the
Windows; the current derived truth is sol_eunit_total=10499
tests / sol_eunit_baseline_failures=0 failures, re-derived from the live
tree (the artifact server/test/env_baseline.derived is authoritative and
the generator refuses a header that disagrees with it,; the
historical 3-cancelled plugin-executor class is recorded in the baseline
header). The
Filtered CI battery (cd server && bash scripts/test-unit.sh, cd server && make test-unit) is a
SEPARATE population — last recorded 8177/0 at the 2026-10-23
closeout (verdict artifact ac2fd5bcb); the unfiltered derivation corpus
is 8715/0. The two numbers must never be conflated: the derivation corpus
includes the suite-re-homed/family modules the filtered battery excludes.
The file now carries the # intentional-empty: marker (the
lint’s sanctioned zero-entry state, -aware) and the fix record.
ci/env_baseline_lint.py (wired into lint-suite) enforces the file’s
invariants: every entry must match a real test in server/test/; an empty
corpus fails unless the intentional-empty marker is present; a git diff
that adds an entry fails; the header expiry (re-audit trigger) fails the
lint once passed.
Root-cause record (the 42, fixed in place): the failures were genuine
TEST defects — stale mocks returning wrong shapes (sol_memory_pg:store
→ {ok, <<"stored">>} vs the handler’s ok; sol_scheduler mocks not
matching handler contracts), ghost assertions of contracts production
never had (the x-user-uuid response header — grep-verified nowhere; the
slack challenge echo; the 429 SSE-limit reply — production is 503),
wrong route action names ([sync_events] vs [sync_events_stream]),
missing app-owned ETS bootstraps (sol_channels, skill_reports,
sol_sse_connections owner, session-map shapes), a double meck:unload
raising in cleanup, non-integer schedule ids, and missing prompt/tasks
body fields. THREE PRODUCTION DEFECTS the tests exposed and fixed:
sol_http_chat:get_history crashed every request via
cowboy_req:match_qs (missing/unknown query keys throw); sol_memory_pg
stored entries without their own key, so key-based search never matched;
the sync-events SSE relay gap (the handler subscribes the dying request
process — D-noted for a follow-up phase).
Count reconciliation (historical): the gate verdict’s “52-entry
baseline” lived only in the gate machine’s /tmp; AGENTS.md’s “59” was a
stale previous count; plan/README’s “4782 tests, 0 failures” describes
the FILTERED CI corpus (a different population — those modules excluded).
In-repo truth: 3566/44/5 at → 3544/44/5 after ’s CT
migration → 3538/0/5 after ’s root-cause repair → 6354/0/3
(2026-09-04, env_baseline.derived — corpus growth through the
Windows + documented derivation exclusions) → 7085/0/0
(2026-09-14, — the – batch grew the corpus;
the record regression, handler order-dependence and missing-WAL
fixture were FIXED in place) → sol_eunit_total=10499 (current, re-derived
per the freshness protocol — re-run make eunit-baseline
after any test-function census change).
Derivation protocol: the baseline is derived, never
guessed — cd server && make eunit-baseline (scripts/eunit-baseline.sh:
clean compile → UNFILTERED rebar3 eunit → fail-set vs the committed
file). Any phase that claims a baseline change runs it FIRST; a new
failing module is a regression (0-new policy), a shrink is a justified
removal to commit. This kills the C16(c) class: gate-time run-vs-file
diffs assumed a warm stale build (a cold-build run once aborted at 2388
tests / 19 non-baseline failures).
Sol flake ledger
Owned observations of run-to-run variance in the Sol suites. Every entry: observation → root cause / characterization → disposition. A new observation gets a row here in the phase that sees it (the register’s C16/C35 rows closed when this table exists with both dispositions filled).
| Observation | Root cause / characterization | Disposition |
|---|---|---|
e2e inference: first-post-CT run failed 6× incl. undefined function sol_provider_registry:lookup/1 (C16(a)) | eunit VM: the provider-registry module was unloaded by another suite’s meck:unload; the [non_strict] mock intercepted only list, so lookup raised undef in the request process; in eunit the registry/catalog gen_servers do not run either (noproc EXITs) | **FIXED **: sol_http_e2e_inference_tests mocks the full resolve boundary (sol_provider_registry:lookup, sol_catalog:lookup, sol_registry:find_by_name) → every request resolves to the graceful 503. Stress bar: 4× isolated runs, 0 failures, 0 CRASH REPORTs (the register’s 3× isolated 12/12 baseline exceeded) |
sol_pipeline_stream_SUITE:streaming_429_retries_once_then_succeeds — intermittent failure_count 1 vs 0 after the retry-succeed path (~1 in 3 full-suite runs; isolated runs pass) | Timing: the success-reset of the {Host,Port} circuit counters is a CAST and raced the direct get_state assert (a second 429-classified frame from the same run’s earlier cases can land after the reset); pre-existing — the testcase predates | **FIXED **: the assert now polls with sol_assert_eventually (mirrors interleaved_success_resets_circuit). Sibling case non_streaming_cap_enforced_loudly had the same direct-read race after the failure cast (the CI server-ct failure this phase) — same fix. Stress bar: 3 consecutive full-suite runs, 14/14 each |
sol_pipeline_connect_SUITE:tls_verification_failure_permanent_single_attempt — {error, nofile} from the pkix material in full-suite runs (C35) | public_key:pkix_test_data/1 flaked under load in full-suite runs (file-backed material collision) | **FIXED **: one deterministic retry with a 100ms backoff in tls_test_material/0 (the justified sleep: comment carries the ledger reference); failure mode now bounded |
| Cold/stale-build full eunit run aborted at 2388 tests / 19 non-baseline failures (C16(c)) | The gate-time run-vs-file diff assumed a warm clean build; a cold build instantiates differently | **FIXED **: derivation protocol + make eunit-baseline (above) — the diff is one command on a clean build |
sol_zmq_handler_worker_test:adoption_worker_mismatch_refused_under_provisioned_binding — the labeled_refused(<<"worker_mismatch">>) +1 delta read 0 in 2 of 3 full-corpus derivations on the merged tree (module isolated 26/26; adjacent-module batches pass) | counter-delta read of the shared sol_metrics ETS; sol_metrics:bump swallows a missing/recreated table (metrics_table_missing) by design, so a corpus-order window where the table is absent makes the delta read 0 even though the refusal arm fired — a corpus-order race, not a code-path defect | FIXED record (2026-09-23): the test now asserts the typed refusal at the mecked sol_zmq_sender boundary (exactly one send/2 with a frame carrying worker_mismatch) plus the no-adoption state — order-independent and behavioral; re-derived clean. The same audit exposed + fixed a derivation gate hole: the 0-new failure-enum regex only matched *_tests modules, so this *_test failure passed the baseline policy silently |
sol_scheduler_attribution_tests:plugin_delivery_classification_matrix_test — bare_ok_drift settled consecutive_errors=2 vs expected 1 | Test-spec race, not a product defect: the case’s every job was immediately due at create (sol_scheduler.erl:561-564 anchor + :1166-1169 ceil(0/IM)), the 1 s-clamped tick re-dispatched it through the designed error-backoff ladder (:1103-1137, :1157-1160) — every settlement legitimately increments consecutive_errors — and the settle predicate only checked not currently_running, so an under-load read could land after a retry settled (2) | **FIXED **: the matrix now creates at jobs with a FUTURE at_ms; run_job’s one-shot enabled=false latch (one_shot_barrier/1, :1080-1084) precedes dispatch, so the error ladder can never re-fire the case’s job — exactly one settlement per case. Bar met: 20× isolated runs green + the full-corpus derivation at the phase landing |
sol_scheduler_attribution_tests:zmq_await_timeout_does_not_touch_the_error_ledger_test — the run-close read saw next_run_ms <= the captured Now in one full-corpus derivation (repro run 8278; module green isolated) | Advance arithmetic, not test-spec: the mocked await makes the whole dispatch→timeout→advance path sub-millisecond, and compute_next_run(every, Anchor)’s at-or-after-now boundary at zero elapsed is the job’s own anchor (the create instant) — so next_run landed at-or-behind the advance moment and the job was instantly re-due; the run-close read samples whichever side | **FIXED **: the advance path clamps through strictly_future_next_run/2 — only the anchor boundary bumps one interval (integer-only, no clock read); create’s immediate-first-fire semantics unchanged. RED-first pin zero_elapsed_advance_is_strictly_future_test; the run-close case is deterministic post-fix |
sol_usage_chunk_tests gun assertions — pump_held_reject_pre_stream_no_gun_test read gun:open num_calls 2 vs expected 0, then pump_held_go_arms_connect_once_test read 3 vs expected 1, in two consecutive unfiltered full-corpus rebar3 eunit runs at the closeout (24 other tests in the module + the module in isolation: 25/25 green both ways) | Global meck:new(gun, [unstick]) counts calls from every live process in the suite VM; a pre-existing periodic probe (provider-health / leftover gen_server from an earlier module) calls gun:open inside the test’s window — a timing/order-dependent test-isolation race, source-identical to base (the closeout diff touches no Erlang/Lua/Python source) | RECORDED: a pre-existing full-corpus flake, module-green in isolation; owner: next Sol test-hygiene window — scope the meck (passthrough/meck:reset boundary) or assert the pump’s own call path (meck:history filtered to the pump pid), then run 3 clean full derivations before closing the row |
xfail & skip inventory
The “zero xfail markers anywhere” claim was FALSE — the grep
covered tests/ pytest markers but not tests/integration/ (4 live
markers). This dated table is the repo-wide inventory; every marker
carries strictness + dated reason + disposition.
| Marker | Where | Strictness | Dated reason | Disposition (2026-08-18) |
|---|---|---|---|---|
@pytest.mark.xfail | tests/integration/test_zmq_task_dispatch.py (bg task) | strict | : mock provider in –connect ZMQ mode crashes during agent setup (task ends failed, line_count=0) | **RE-DATED ** — re-run confirms the documented mode; stays strict |
@pytest.mark.xfail | tests/integration/test_ws_chat_roundtrip.py (WS roundtrip) | strict | : WS path returns 404 — session-scoped WS route needs investigation | **RE-DATED ** — re-run confirms the documented mode (upgrade 404); stays strict |
@pytest.mark.xfail | tests/integration/test_mango_sol_event_bridge.py (RBAC downgrade propagation) | was non-strict | : residual failure mode is the 5s propagation window, not a crash | **CONVERTED to strict + RE-DATED ** — the never-re-dated class polices; an unexpected pass must XPASS loudly |
@pytest.mark.xfail | tests/integration/test_workflow_e2e.py | strict | : workflow /start 500 — Sol crashes on step dispatch | **REMOVED ** — the masked crash was fixed (3 production bugs: manager case_clause on unknown workflow, stale boot-defined tuple steps → badrecord, detail/stream bare-record 500); replaced by 2 real boundary tests (unknown name → 404, boot-registered start → 200 + visible) |
| Luna runner skips | client/run_tests.sh SKIP_TESTS (7 files) + 2 support modules | n/a | env-gated / infra-unavailable (owned; expiry 2026-08-31 re-audit) | inventory owned since then; count truthful 7+2=9 |
| CT runtime skips | server/test/*_SUITE.erl init_per_suite {skip,...} / tc_user_skip | n/a | infra-bound: full OTP supervision tree / cluster peer nodes / PG containers unavailable | last full run: 6 skipped, all infra-bound (documented per-suite) |
| Limon runtime skips | limon/src/integration/e2e-live.test.ts (REAL transport) | n/a | VITE_TEST_REAL_API=1 + a seeded identity; never armed in CI — skipped by default, fail-loud when armed without credentials | renamed the old mock-echo suite to api-mock.test.ts; the live gate is the counted limon_tests_pinned_skipped=1 |
| eunit | — | — | — | no skip markers; env-baseline failures are FAILURES, not skips |
Polling assertions
Fixed timer:sleep(N) guesses are the flakiness engine — new ones are
lint-gated (ci/timer_sleep_lint.py, shrink-only ratchet). Use the shared
polling helper instead:
%% waits up to 2s (25ms interval) for the predicate
sol_assert_eventually:assert(fun() -> condition() end),
sol_assert_eventually:assert(fun() -> ... end, 5000) %% custom timeout
A %% justified sleep: <why> trailing comment exempts a line whose test
subject IS the timing.
Integration harness
tests/integration/harness.py boots Mango + Sol + Luna (the fixture lane)
for the HTTP/RBAC/chat/system-boundary tests. The required
tri-service-integration CI job invokes:
python3 -m pytest tests/integration/ -v --tb=short
python3 -m pytest tests/smoke/ -v --tb=short # same harness, smoke matrix
Port policy: ephemeral by default — every TriServiceHarness instance
allocates free ports (_pick_free_port), so two concurrent runs on one
host cannot collide (the fixed 5800/21434/5555/5556/5598 constants are the
opt-in debug lever ZERG_HARNESS_FIXED_PORTS=1; the legacy
ZERG_HARNESS_EPHEMERAL_PORTS lever still selects both modes). Tests
address the stack through harness.mango_url / harness.sol_url — never a
hardcoded 127.0.0.1:<port>. Waits bound the real post-condition with the
harness poll helpers (poll_until / poll_until_sync) — no fixed sleeps
encoding a cache/TTL/expiry window.
CI event matrix
Forgejo schedule triggers are workflow-wide. ci.yml therefore carries
exactly ONE cron (the nightly full battery + the eunit-baseline
derivation); the env-baseline expiry scan owns its own workflow so the
second cron never wakes the 44-job battery. ci/ci_event_matrix_lint.py
(required lint-suite) machine-checks this table — edit the YAML and this
section together.
| Trigger | Workflow | Jobs | Notes |
|---|---|---|---|
| push / pull_request to main | ci.yml | the full required battery (server-*, client/Mango/CLI/Limon, lint-suite, web-tests, tri-service) | cancel-in-progress: false: a source push queues behind the in-flight release battery (the C7 status-race lesson) |
workflow_dispatch | ci.yml | operator re-run; eunit-baseline runs ONLY on a main-ref dispatch | the release procedure dispatches the derivation on the release SHA before tagging |
schedule 17 3 * * * | ci.yml | full battery + eunit-baseline | nightly derivation is schedule/dispatch-only (never a push) |
schedule 23 4 * * * | expiry-tripwire.yml | expiry-tripwire only | T-14 warn / T-3 red scan of every # expiry: header |
| schedule (same crons) | ci.yml | nightly-kill-drills, nightly-heartbeat-probe, required-checks-mirror-diff, runner-image-mirror | schedule-guarded inside the workflow (never on push/PR) |
| schedule + push/dispatch to main | ci.yml | nightly-deadman | fails when the newest scheduled battery run is older than 30h — a stopped cron reds the merge lane (BVI-079) |
tag v* / dispatch | kill-proofs.yml | kill-proofs-regression | release-boundary battery; consumed by Crow’s kill-proofs-check before deploy |
Local lint battery
The required lint-suite job is reproducible locally without copying the CI body:
python3 ci/run_all_lints.py # every manifest lint-suite row, in order
python3 ci/run_all_lints.py --list # the planned legs (arguments included)
python3 ci/run_all_lints.py --only tools_taxonomy_parity_lint
python3 ci/run_all_lints.py --skip pr_runner_isolation_probe
The runner reads ci/lint_manifest.yaml, resolves each row’s invocation from
the real lint-suite job body (so arguments cannot drift), applies
lint_suite.default_timeout_seconds (or --timeout), and fails loud on a
missing tool, an unknown wiring, an EMPTY CORPUS message, or a non-zero leg.
case_exhaustiveness_lint is ratcheted against the CASE_CAP/NARROW_CAP
constants in the job body. The wall time is printed on success.
Test-honesty gates
The required lint-contract-tests job runs the WHOLE tests/test_*.py
corpus — the doc-truth contracts were red on main
while only six files ran there. lint_contract_tests in AGENTS.counts
is derived from that corpus (pytest --collect-only).
ci/vacuous_assert_lint.py --corpus lua is the Lua counterpart
of ci/vacuous_assert_lint.py: a literal-true assert_eq(..., true, true) / assert_true(..., true) in client/tests/** fails the
lint-suite battery. Replace it with the real post-condition, or annotate
the line with vacuous-ok: <reason> (the Erlang assert-true-ok:
shape).
ci/docs_counts_lint.py + ci/render-docs-counts.py --check cover the
counts corpus and every pinned key (the live count prints on each run); ci/truth_counts_lint.py live-derives the
Limon view count (router.ts), the CT shard count (ct_plan.txt), the
skip-allowlist row count and the Sol /metrics posture, so the prose
cannot drift from the implementation.
Endpoint exercise gate
ci/endpoint_exercise_lint.py is the behavioral complement to
api_reference_parity_lint.py (which proves spec↔doc↔route EXISTENCE, not
EXERCISE). It builds a machine inventory mapping every OpenAPI operation in
docs/fixtures/openapi_spec.json to at least one real-dispatch citation:
Citations come from tests/smoke|integration|e2e
pytest AST (harness.request / harness.sol_request, parametrize rows,
WebSocket .../ws paths) and server/test/*.erl (shared gun helpers,
direct gun: calls, route/3 segment+verb calls, and direct
dispatch-map handler calls). Source-inspection greps are not evidence and
are never counted. Method-exact citations cover one operation; a direct
handler citation (Module:handle(Action, Req)) covers a path only when
the spec documents a single method — multi-method paths need
method-specific evidence.
Exemptions live in docs/fixtures/endpoint_exercise_exemptions.json.
Every row requires class, reason, owner and an ISO expiry; expired
rows fail. The CT-9 six catch-all route prefixes are listed there
(class: ct9-catch-all-prefix) and the lint derives the same set from
sol_http_routes.erl, so the prefix cover is counted, audited and never
invisible. citations rows are a manual escape hatch: file/line, path,
method and test name are verified; phantom, stale, skip-only and
uncollected citations fail.
Fail-closed: an unreadable/empty spec, an empty behavioral corpus
zero extracted citations, or a missing fixture fails the gate.
At the real tree derives 184 spec operations / 169 paths / 169
router rows, 630 citations, 184/184 covered, 0 route exemptions
and 6 audited CT-9 catch-all prefixes. The exercising corpus includes
server/test/sol_endpoint_exercise_tests.erl, which drives the previously
uncited routes through a real Cowboy listener. Run:
python3 ci/endpoint_exercise_lint.py
python3 -m pytest tests/test_endpoint_exercise_lint.py -q
The gate is owned by the Sol HTTP surface (sol-http-surface); the CT-9
rows expire 2027-04-30 and must be re-reviewed (or retired by enumerating
concrete route rows) before then.
CT hermetic harness
The Sol Common Test battery runs through server/scripts/test-ct.sh, which
now hands every rebar3 ct invocation its own per-VM data root
(SOL_CT_DATA_ROOT → _build/test/tmp/ct-roots/<run>-s<N>): the scheduler
store, lane pidfiles, CURVE keyfile, audit JSONL and Mnesia live there and a
fresh VM can never read a previous run’s durable state (the persisted
fixture_sse every-5s job class). sol_ct_hermetic_hook (registered in
server/rebar.config) applies the root, runs the app-lifecycle barrier, and
enforces leak detection at end_per_suite:
Gate — SOL_CT_HERMETIC_GATE (test-ct.sh exports baseline):
a leak outside server/test/ct_leaks.baseline.tsv fails a suite in the
measured corpus (server/test/ct_leaks.measured); all fails any leak;
ad-hoc rebar3 ct runs default to off (report only). Leaks are appended
to _build/test/logs/ct-leaks.tsv.
Baseline ratchet — python3 ci/ct_leaks_baseline.py --seed after a
battery, --update to shrink (never grow), --check is required in
lint-suite. The remediation sweep works this list down.
Owners — every suite-infra owner goes through sol_ct_session
(start_owner/2 + await_owner/2, or the legacy-protocol
spawn_owner/1 + await_ready/2): an owner crash reports
{infra_failed, Class, Reason, Stack}, a DOWN reports owner_down, and
the bounded timeout fires only for a live-but-silent owner.
Adopt-or-start — sol_ct_session:ensure_started/2,3 for app-owned
registered names (never gen_server:stop + start_link against a live
supervisor), app_up/0 / app_down/0 + await_app_stopped/1 for the
lifecycle barrier.
Ports — sol_ct_ports:ephemeral (bind 0, read the port back) for
ZMQ/HTTP fixtures; ci/ct_suite_hygiene_lint.py --check port rejects fixed
service-port binds.
Manifest — server/test/ct_suites.manifest is generated by
python3 ci/ct_suites_manifest.py --update (--check is required):
per-suite app_lifecycle / destructive / ports / dist /
cost_seconds / isolation / leaks. Costs refresh with --measure
(parses CT =elapsed_time).
Smoke subsets: CT_SUITES=sol_foo_SUITE MIN_CT_TESTS=1 bash server/scripts/test-ct.sh runs exactly those suites (skips the isolated
invocations). server/test/sol_ct_hermetic_SUITE.erl self-tests the
harness (owner reporting, adopt-or-start, metrics-table shape, data root,
ports, leak detection, erlexec policy).
Measured CT floors (canonical closeout)
server/scripts/test-ct.sh writes _build/test/logs/ct-battery-start at
battery start and runs ci/ct_measured_census.py --check --since <battery>
at the end. The canonical standalone closeout is:
python3 ci/ct_measured_census.py --check
It reads the battery marker (never --since 0), requires every planned
suite’s newest log to be from that battery, and enforces the per-suite and
battery totals in server/test/ct_measured.tsv (shrink-only). Group suites
expand groups/0, so all -> [{group, g},...] is counted as its real
case count, not the number of group tuples. --generate re-seeds the pins
from real logs; --since 0 is refused.
Test-side JSON convention (2026-10-16, the jiffy drain)
The Erlang test corpus runs on the OTP stdlib json module (jiffy was
removed tree-wide — see ci/no_prod_jiffy_lint.py). Three shaping rules
keep tests honest under the stdlib semantics:
json:encode/1returns IODATA, not a flat binary (jiffy returned binaries). Wrap the result:iolist_to_binary(json:encode(Term))— this is also the house prod facade shape (sol_http_json:encode/1).json:decode/1takes a BINARY (jiffy tolerated iolists). Wrap the input when it comes from an encoder/list builder:json:decode(iolist_to_binary(X)).- Never compare serialized bytes. Assert on the DECODED term
(
json:decode(...)→ map/list compare), or on a hand-rolled lexicographic canonical encoding when two independently-built bodies must be compared (map iteration order is key-hash order, and atom- vs binary-keyed maps with equal content iterate DIFFERENTLY — seesol_provider_wire_openai_tools_tests:canonical/1for the reference encoder).json:encodehas no pretty/sort options.
EJSON one-tuples ({[{K, V},...]} — jiffy’s object wrapper) are retired:
use maps (#{K => V}).
Mock discipline (meck) — 2026-10-16
The meck README’s caveats are our recurring test-flake classes. Rules:
- Lifecycle. A mock is created and unloaded inside ONE testcase (or
init_per_testcase/end_per_testcasepair). A suite-scoped mock needsno_linkAND an unload inend_per_testcasethat runs on every outcome — meck’s CT note:init_per_suiteruns in its own process, so a linked mock dies (or worse, survives as a stale global) before the testcases. - Never assert GLOBAL call counts on shared modules.
meck:num_calls/3counts every process in the VM; gun has independent background callers (provider-health probes), which is the flake. Usesol_test_meck:calls_from/3(meck:history filtered by the caller pid) ormeck:wait/4for a bounded wait. The shrink-only ratchetci/meck_global_count_lint.pygates newmeck:num_calls(gun,...)sites; a reviewed%% meck-global-ok: <reason>marker is the escape hatch. - Never mock NIF/gen_*/
erlangmodules — recompiling them in the global namespace breaks live processes (the meck README’s list). Put a seam behind our own module instead. - Local calls bypass mocks — an expectation on
f/1does not intercept a module-localfcall; assert the externally reachable path. passthroughfor partial overrides —meck:expect(M, F, fun(...) -> meck:passthrough([...]) end)keeps the original behavior for the cases the test does not own.
Failure-time event dump (CT)
The hermetic CT hook implements on_tc_fail/4 and appends the newest sync
events (default 200, SOL_TEST_EVENT_DUMP=N to widen) to the failed
testcase’s CT log via sol_test_events:dump_tail_to_ct/2. The run/check
helpers live in sol_test_events (composable specs) and sol_test_watch
(watcher-before-action waits).
Running Tests
Server (Sol)
cd server && make test-unit # CANONICAL filtered unit gate (EUNIT_TIMEOUT=10; measured 8177 at the 2026-10-23 closeout)
cd server && ERL_AFLAGS='-eunit_timeout 10s' rebar3 eunit --module=sol_inference_tests # Single module (timeout REQUIRED)
cd server && ERL_AFLAGS='-eunit_timeout 10s' rebar3 eunit --module=sol_provider_fallback_tests # one file per battery
cd server && ERL_AFLAGS='-eunit_timeout 10s' rebar3 eunit --module=sol_outbox_journal_tests # the
# retired s92/s93 names
# no longer exist)
cd server && make test-ct # CANONICAL CT battery (32 shards + isolated)
python3 ci/ct_measured_census.py --check # per-suite measured floor (reads the battery marker)
Verification-honesty gates:
python3 ci/mock_parity_lint.py # mock signatures + multiline store-shape mocks
python3 ci/test_effectiveness_lint.py # can't-fail scan: mango, tests/**, example/**, Erlang/Lua/TS
python3 -m pytest tests/test_*.py # contract tests for the gates above
cd server && ERL_AFLAGS='-eunit_timeout 10s' rebar3 eunit --module=sol_endpoint_exercise_tests
sh example/vim/test/run.sh # editor suite (incl. the loopback-only air-gap transcript)
bash benchmarks/run_ev5_bounded_read_bench.sh # EV-5 bounded-read artifact (see benchmarks/ev5-bounded-read-bench.md)
Client (Luna)
Per-file test counts shift constantly — client/run_tests.sh prints the
authoritative aggregate (functions/assertions; machine totals in
AGENTS.counts).
cd client && ./run_tests.sh # full battery: functions/assertions + skips
cd client && luajit tests/test_core.lua # Core + agent + regression
cd client && luajit tests/test_ffi.lua # FFI + security
cd client && luajit tests/test_sse.lua # SSE parser
cd client && luajit tests/test_provider.lua # Provider + retry + OpenAI
cd client && luajit tests/test_config_providers.lua # Settings providers (load validation + URL path)
cd client && luajit tests/test_main_stdio_persistent.lua # Sol-less persistent --stdio (history across prompts)
cd client && luajit tests/test_mcp.lua # MCP with mock server
cd client && luajit tests/test_e2e_zmq.lua # ZMQ E2E tests
cd client && luajit tests/test_ai_classifier.lua # AI permission classifier
cd client && luajit tests/test_sub_agent.lua # Specialist sub-agent tests
cd client && luajit tests/test_prompt_prefix_stability.lua # Canonical layout + prefix hash
cd client && luajit tests/test_prompt_prefix_fork.lua # Frozen-prefix forks + cache context
cd client && luajit tests/test_hooks.lua # Hook system tests
cd client && luajit tests/test_permission_ruleset.lua # Permission ruleset tests
cd client && luajit tests/test_hidden_agents.lua # Hidden utility agent tests
# Run all client tests
cd client && for f in tests/test_*.lua; do echo "=== $f ===" && luajit "$f"; done
Standalone completion is file-scoped and network-free:
cd client && RUN_TESTS_STRESS=0 bash run_tests.sh \
tests/test_completion.lua tests/test_completion_standalone.lua
Engine bundles
The bundle consumer’s fixture battery builds real fixture-class bundles
through scripts/engines/build.sh and exercises verification, host-class
refusal, install/canary, upgrade and rollback:
python3 -m pytest -q tests/test_engine_bundle_consumer.py
bash scripts/engine-bundle-consumer.sh verify --bundle-dir <dir> --allow-unsigned
sh example/vim/test/run.sh # editor surface (read-only here)
python3 ci/egress_assert_lint.py # zero-egress discipline
Stress / flake bars — MANUAL-ONLY
client/run_tests.sh implements RUN_TESTS_STRESS=<n> (,
): the selected files run n times in isolation and the final line
reports STRESS: <n> runs, X failures, Y panics with a non-zero exit on
any failure/panic. As of 2026-10-17 it has zero CI callers — no
workflow invokes it, so it is a manual flake bar, not a gate.
Owner: Luna maintainers · Check date: 2027-03-29 · Status: MANUAL-ONLY (recorded, not a silent gap). The CI wiring (a scheduled leg) is integrator-owned; when it lands, replace this row. When to run: before landing a change that touches provider/streaming, the ioloop pump, sub-agent/sub-process lifecycle, or any file named in the Sol flake ledger above.
cd client && RUN_TESTS_STRESS=20 bash run_tests.sh tests/test_<name>.lua
cd client && RUN_TESTS_STRESS=5 bash run_tests.sh tests/a.lua tests/b.lua
Mango
cd mango && python3 -m pytest --collect-only -q | tail -1 # live corpus count
cd mango && python3 -m pytest test/ -v # full suite
cd mango && python3 -m pytest test/test_auth.py -v # Auth pipeline only
Limon
cd limon && npx vitest run # limon_tests_pinned_total=1291 / limon_tests_pinned_skipped=1 (AGENTS.counts)
cd limon && npx vitest run src/integration/ # Integration tests only
Test Structure
Historical section. The per-category counts and file totals below were true when measured and are kept for orientation only; they are NOT maintained. Current machine-derived totals live in
AGENTS.countsand the statistics table above.
Server (429 files)
| Category | Tests | Key Files |
|---|---|---|
| Inference | 42 | sol_inference_tests |
| Pipeline | 7 | sol_pipeline_tests |
| Registry | 44 | sol_registry_tests |
| HTTP | 36 | sol_http_tests |
| Worker | 20 | sol_worker_tests |
| Task Store | 10 | sol_task_store_tests |
| Anthropic API | 15 | sol_anthropic_api_tests |
| Anthropic Stream | 10 | sol_anthropic_stream_tests |
| Thinking Passthrough | 17 | sol_s41_tests |
| ZMQ Gateway | 8 | sol_zmq_gateway_tests |
| ZMQ Protocol | 12 | sol_zmq_protocol_tests |
| ZMQ Handlers | 22 | sol_wf1_tests |
| Cron | 30 | sol_cron_tests |
| Scheduler | 36 | sol_s22_scheduler_tests |
| Scheduler Validation | 32 | sol_s33_tests |
| Scheduler Hardening | 14 | sol_s22_1_hardening_tests |
| Circuit Breaker | 21 | sol_s25_tests |
| Provider Registry | 15 | sol_s46_tests |
| Provider Adapters | 56 | sol_s47_tests, sol_s84_tests, sol_s85_*_tests, sol_s85_tests |
| Plugin System | 48 | sol_s38_tests |
| Workflow Engine | 21 | sol_s44_tests |
| Workflow Instance | 21 | sol_workflow_instance_tests |
| Workflow Bridge | 14 | sol_integ1_tests |
| Events | 4 | sol_events_tests |
| Metrics | 13 | sol_metrics_tests |
| Cluster | 4 | sol_cluster_tests |
| Catalog | 9 | sol_catalog_tests |
| Auth + Rate Limiter | 14 | sol_s34_tests |
| Keyring | 4 | sol_keyring_tests |
| OAuth PKCE | 18 | sol_s81_tests, sol_s83_1_tests, sol_l67_oauth_refresh_tests |
| Memory PG | 29 | sol_l55_memory_pg_tests |
| Memory Consolidation | 28 | sol_e3_consolidation_tests |
| Embeddings | 28 | sol_e1_embedding_tests |
| Teams/Swarm | 50 | sol_s92_swarm_tests |
| Container Pool | 33 | sol_s93_container_tests |
| E2E Protocol | 117 | sl1_e2e_tests, sl1_protocol_tests |
| E2E Live Process | 14 | SL5 scenarios |
| E2E Stress | 4 | SL6 scenarios |
| Deep E2E | 27 | sl7_deep_e2e_tests |
| Integration | 11 | sol_integration_tests |
| Production | 25 | sol_s97_tests |
| Mnesia/Prometheus | 22 | sol_s98_tests |
| Health/Shutdown/Latency | 25 | sol_s97_tests |
Client (481 files)
| Category | Key Files |
|---|---|
| Core | test_core, test_sse, test_provider, test_stream_state, test_openai_stream_state, test_config_providers (settings providers + mock-HTTP final URL), test_main_stdio_persistent (spawned Sol-less stdio continuity) |
| Session | test_session_backend, test_session_branching, test_session_mode, test_sqlite_session |
| Tools | test_parallel_tools, test_loop_detector, test_mutation_queue, test_fuzzy_match, test_tool_validation, test_todo |
| Agent | test_agent_steering, test_agent_modes, test_ai_classifier, test_sub_agent, test_hidden_agents |
| ZMQ | test_zmq, test_e2e_zmq, test_event_bridge |
| TUI | test_chatpane, test_inputbar, test_theme, test_markdown, test_highlight, test_diff_view, test_screenbuf, test_visual_patterns |
| Context | test_l23_context_management, test_l24_safety, test_l25_intelligence, test_l26_wiring, test_l27_permissions |
| Hook/Permission | test_hooks, test_permission_ruleset |
| MCP | test_mcp, test_mcp_server, test_mcp_http, test_mcp_depth |
| LSP | test_lsp |
| Vision/Image | test_image, test_image_transform, test_l62_vision, test_l72_sixel |
| Memory | test_l55_memory_providers, test_e3_consolidation |
| Compaction | test_l56_compactor |
| Phase tests | test_l58_tool_depth through test_l76_*, test_s87_* through test_s99_* |
| Infrastructure | test_injection_detector, test_tool_discovery, test_truncate, test_config_validation, test_keyring, test_web_search |
| Desktop | test_computer_use, test_l53_computer_use, test_l66_desktop_integration |
Mango (49 files)
| Category | Coverage |
|---|---|
| Auth | Token lifecycle, RBAC, rate limiting, session management |
| Handlers | Accounts, teams, sessions, REST CRUD |
| Systems | Auth, accounts, teams, tasks, audit |
| Storage | SQLite backend |
| Tools | Rate limiter |
| Events | ZMQ transport |
| Plugins | Plugin lifecycle |
| PostgreSQL | Backend operations, cascade deletes |
Limon (71 files)
| Category | Tests | Files |
|---|---|---|
| Stores | 27 | auth (7), chat (5), connection (4), infra (11) |
| API Clients | 16 | sol-client (4), mango-client (4), sse-client (8) |
| Components | 16 | header, sidebar, worker grid, workflow, audit, infra |
| Integration | 13 | auth-flow, dashboard-flow, maintenance-flow |
| Composables | 5 | usePagination |
| Utilities | 5 | Various helpers |
Writing Tests
Erlang (Server)
Use eunit ?_test and ?_assert patterns. Phase-based test files follow test/sol_s<phase>_tests.erl naming. Test pure functions directly; use meck for mocking gen_servers when needed.
-module(sol_my_feature_tests).
-include_lib("eunit/include/eunit.hrl").
basic_case_test() ->
Result = sol_my_feature:do_something(#{key => value}),
?assertEqual({ok, expected}, Result).
Lua (Client)
Use assert for assertions. Return passed/failed counts at end. Mock provider available via core/mock_provider.lua; mock MCP server at tests/mcp_mock_server.lua.
local passed = 0
local failed = 0
local function test(name, fn)
local ok, err = pcall(fn)
if ok then
passed = passed + 1
else
failed = failed + 1
print("FAIL: " .. name .. " - " .. tostring(err))
end
end
test("basic math", function()
assert(1 + 1 == 2)
end)
print(string.format("\n%d passed, %d failed", passed, failed))
os.exit(failed > 0 and 1 or 0)
Python (Mango)
Use pytest with fixtures. Tests follow test/test_<module>.py naming.
import pytest
def test_authenticate_valid_token(auth_system):
result = auth_system.authenticate("valid_token")
assert result is True
TypeScript (Limon)
Use Vitest with happy-dom environment. Co-located test files: Component.test.ts.
import { describe, it, expect } from 'vitest'
import { useAuthStore } from '../stores/auth'
describe('auth store', () => {
it('initializes with no user', () => {
const store = useAuthStore()
expect(store.user).toBeNull()
})
})
Test Coverage
| Component | Approximate Coverage |
|---|---|
| Sol server | ~70% (pure functions well-covered, gen_server state machines partially covered) |
| Luna client | ~70% (core agent fully covered, UI modules partially covered) |
| Mango | ~65% (auth pipeline well-covered, storage handlers partially covered) |
| Limon | ~60% (stores well-covered, components partially covered) |
Coverage was raised from ~35% to ~70% during Phase VI (hardening) and maintained through subsequent phases.
CT sharding, retries and hermeticity
Retries are budgeted (CT_RETRY_BUDGET=1) and leak-free-aware: a shard
whose plan row is leak_free=1 has no harness interference to blame; a
passed retry there is a P1 signal and fails the run
(CT_LEAKFREE_RETRY_BUDGET=0). Shard membership comes from
server/test/ct_plan.txt (ci/ct_shard_plan.py; test-ct.sh --check-plan);
CT_USE_PLAN=0 falls back to glob order. Every rebar3 invocation is bounded
(CT_SHARD_TIMEOUT=600) and classified from CT’s per-case truth when the
tool’s own teardown crash eats the summary. The CT hermeticity ratchet
gates app-stop placement, silent timeouts,
meck hygiene, owner kills, port literals, zombie-arity mocks and fixture
posture; wide assert_eventually windows are dispositioned per-row in
plan/fixtures/ct_wide_window_dispositions.md. Battery: 32 planned shards
(~34 s each, ~8–10 min quiet-host; per-unit wall times in
_build/test/logs/ct-shard-times.tsv).
Engine reference — generated from the canonical engineering source. Do not edit this page by hand.
Contributing to ZERG
Development Setup
Prerequisites
| Dependency | Version | Purpose |
|---|---|---|
| Erlang/OTP | 29.1+ | Sol server runtime |
| rebar3 | 3.20+ | Erlang build tool |
| LuaJIT | 2.1 | Luna agent runtime |
| Python | 3.11+ | Mango framework only |
| gcc | C11+ | FFI bindings, single-binary build |
| upx | optional | Secure release binaries only — local builds pass --plain --no-upx |
| ncurses / ncursesw | 6.0+ | Luna TUI |
| libcurl | 7.68+ | Luna HTTP/SSE |
| libzmq | 4.3+ | ZMQ worker mode (optional) |
The OTP floor is Erlang/OTP 29.1+ (OTP 30+ is the forward aim; OTP 28 is not a support target).
Build and Run
Sol server:
cd server && rebar3 compile
rebar3 shell # Dev shell, Cowboy HTTP on port 21434
zerg status # Verify server is running
Luna agent:
luajit client/main.lua --configure # interactive setup wizard
luajit client/main.lua --connect tcp://127.0.0.1:5555 # Sol-fed worker (lane grants)
Mango auth service:
cd mango && pip install -e .
python server.py # Starts on port 5800
Infrastructure stack:
Production deployment is handled by wild (Crow CI + podman + runit); the
legacy deployment/infra/scripts/setup.sh was archived with the old on-host
model. Local development does not need the infra stack — Sol, Luna,
and Mango all run directly on the host. See wild/AGENTS.md §“CD Build
Execution” for the provisioning path.
Code Style
Erlang (Sol Server)
Use OTP behaviours for all stateful processes (gen_server, gen_statem, gen_event)
process_flag(trap_exit, true) in all gen_servers that own resources (OS processes, ETS, sockets)
ETS {heir, Pid} for all critical tables
logger module for all logging – never io:format
-vsn attribute on every module
binary_to_existing_atom for all external input – never list_to_atom on untrusted data
warnings_as_errors enabled in rebar3 config – all warnings are build failures
Prefix unused variables with _ (_Unused, _Ignored)
simple_one_for_one for dynamic child factories
rest_for_one for top-level supervisor
sol_config:get_env/2 for reading application environment – no direct application:get_env in modules
Module structure:
-module(sol_my_module).
-behaviour(gen_server).
-vsn("1.0").
%% API
-export([start_link/0, my_function/1]).
%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
Lua (Luna Client)
Use cel.class (middleclass) for all new classes – see docs/cel-vision.md
Use cel.json for all JSON access – never import dkjson or JSON_luerl directly
Use cel.deep_merge / cel.deep_copy for table operations
Use FFI (ffi/process.lua, ffi/dir.lua) for filesystem and process operations – never os.execute
Module pattern: local M = {}; M.__index = M; return M (pre-middleclass modules)
Instance pattern: setmetatable({}, M)
pcall for all fallible operations
Atomic writes: write to .tmp, then os.rename
Coroutine-based async via Turbo.lua IOLoop – never blocking io.read or usleep polling
Return nil, err on failure (two-value convention)
Python (Mango)
Tornado async handlers for HTTP endpoints
BaseSystem for business logic, BaseHandler for HTTP endpoints
pytest with @pytest.mark.asyncio for async tests
ZERG CLI uses LuaJIT (zero Python dependency) – no third-party dependencies
Testing
All tests must pass with 0 new failures before merging. The env baseline has been empty since then: a new failing test is a regression to fix, never a tracked exception.
Server Tests
From the repository root (the canonical gate is the filtered runner, not
bare rebar3 eunit):
(cd server && make test-unit) # canonical filtered gate
(cd server && ERL_AFLAGS='-eunit_timeout 10s' rebar3 eunit --module=sol_integration_tests)
Test files follow test/sol_<feature>_tests.erl or test/sol_s<phase>_tests.erl naming. Use eunit ?_test and ?_assert patterns. Test pure functions directly; use meck for mocking gen_servers.
Client Tests
From the repository root:
(cd client && luajit tests/test_core.lua) # Core + agent + regression
(cd client && luajit tests/test_ffi.lua) # FFI + security
(cd client && luajit tests/test_provider.lua) # Provider + retry + OpenAI
# Run all:
(cd client && for f in tests/test_*.lua; do luajit "$f"; done)
Test files under client/tests/ (count grows as tests land —
ls client/tests/test_*.lua | wc -l) carry luna_test_functions=691 test
functions / luna_test_assertions=22038 assertions (machine-derived; see
AGENTS.counts — luna_test_functions / luna_test_assertions). The runtime pass/skip
totals shift as tests are added: run
cd client &&./run_tests.sh for the authoritative aggregate (it prints
passed/failed/skipped; the empty corpus fails loudly). Use assert
and return passed/failed counts. Mock provider available at
core/mock_provider.lua. Mock MCP server at tests/mcp_mock_server.lua.
Mango Tests
From the repository root:
(cd mango && python3 -m pytest test/ -v) # re-measure; see AGENTS.md Tests row
(cd mango && python3 -m pytest test/test_auth.py -v) # Auth tests only
Integration Tests
(cd server && ERL_AFLAGS='-eunit_timeout 10s' rebar3 eunit --module=sol_integration_tests)
(cd server && ERL_AFLAGS='-eunit_timeout 10s' rebar3 eunit --module=sol_http_e2e_zmq_roundtrip_tests)
Contract Single-Source (events & wire)
Event types, payload-key validators, wire frame field lists and MAC domain
metadata live in ONE machine-readable source: contract/events.yaml and
contract/wire.yaml (,; format decision + measured
inventory in contract/INVENTORY.md).
Adding an event:
- Add the type (aggregate + group, optional doc) to
contract/events.yaml; add a payload validator only if the type needs required keys. - Regenerate the consumers and commit them together:
python3 ci/contract_gen.py
python3 ci/contract_gen.py --check
Generated artifacts: server/src/sol_event_contract.erl (definitions +
validators), server/test/fixtures/event_contract.json,
server/test/fixtures/wire_contract.json (: the unconsumed Luna
event_types.lua seed was deleted; Luna emission literals remain the only
Luna-side truth until the emitter migration lands). CI’s contract_drift_lint fails on
a stale artifact or an emission literal outside the declared set;
event_drift_lint fails on a declared type nothing emits. The wire slice is a
verification artifact only (migration state: contract/MIGRATION.md).
PR Process
- All changes require tests. New modules, bug fixes, and refactors all need test coverage.
- Run the full test suite for the affected component before opening a PR.
- Update AGENTS.md when adding new modules, phases, or capabilities. This is the canonical project reference.
- Follow naming conventions:
Server phases:
S##(e.g., S102, S103) Client phases:L##(e.g., L75, L76) Server test files:test/sol_s<phase>_tests.erlClient test files:tests/test_<feature>.lua - Create a plan in
plan/for non-trivial changes. Include scope, focus, and test expectations. - Create a review in
review/after implementation. Document what was done, test results, and any deviations from plan.
Project Structure
server/ Sol -- Erlang/OTP orchestration platform
src/ sol_modules=489 Erlang source modules (see AGENTS.counts)
test/ unit + CT suites (see AGENTS.counts)
cli/ ZERG CLI (LuaJIT binary, cli_commands=92 commands + cli_subcommands=37 subcommands)
config/ sys.config, vm.args, production configs
priv/lua_libs/ cel.lua, fun.lua, lume.lua, JSON_luerl.lua
priv/plugins/ Bundled Lua plugins (telegram, discord)
client/ Luna -- LuaJIT agent (worker runtime)
core/ core modules (agent loop, tools, session, provider)
ui/ ~17 TUI modules (app, chatpane, inputbar, theme, markdown)
ffi/ 17 FFI bindings (curl, process, dir, zmq, md4c, sqlite3)
tests/ luna_test_functions=691 test functions / luna_test_assertions=22038 assertions
build/ Single-binary build (994KB stripped)
vendor/ Vendored libraries (turbo, ltui, fun, lume, JSON_luerl, middleclass)
mango/ Mango -- Python/Tornado auth framework
mango/ Core: systems, handlers, schemas, events, storage, plugins
test/ pytest suites (re-measure; see AGENTS.md Tests row)
docs/ User-facing documentation (docs_artifacts=70 artifacts)
plan/archive/ plan_files=1414 archived phase plans
review/archive/ historical reviews (categorized)
reference/ Reference systems and documentation (read-only)
deployment/infra/ Docker Compose stack (11 services)
ci/ CI support files (LuaJIT image, smoke test)
Key Decisions
These are settled architectural choices. Do not introduce alternatives without discussion:
Erlang/OTP for orchestration – concurrency, fault tolerance, supervision trees
LuaJIT for worker runtime – sub-10MB RAM, 994KB binary, FFI speed
Llama.cpp local-first inference – remote providers are fallback only
ZMQ for polyglot worker boundary – language-agnostic IPC at Erlang/non-Erlang boundary
Cel.lua as unified standard library – all JSON via cel.json, all OOP via cel.class
Mango as identity provider – Sol delegates auth to Mango HTTP service
No cloud API dependencies – all external calls must be explicitly configured
Docs style
This book is the public documentation surface. The engineering corpus under docs/ is the canonical source for reference and operator chapters; tutorials are authored in the book.
Source model
| Kind | Where it lives | How it ships |
|---|---|---|
| Tutorials, concepts, landing pages | docs-site/src/** | Authored directly |
| Reference and operator chapters | docs/** | Generated by ci/sync_docs.py |
| Engineering history, ADRs, plans, reviews | docs/, plan/, review/ | Repository only (never published) |
Never hand-edit a generated chapter: edit the canonical docs/ source and run:
python3 ci/sync_docs.py --apply
mdbook build docs-site
python3 ci/sync_docs.py --check is the CI drift gate.
Writing rules
Lead with the task. A page starts with what the reader will do, then the steps, then the reference detail.
Verify every command. If you cannot run it, mark it as unverified; do not present it as tested.
No invented counts or URLs. Counts are machine-derived (AGENTS.counts + ci/render-docs-counts.py). Product URLs are the public domains only.
Use the real names. Sol, Luna, Mango, Limon; WILDZERG (never “Cosmos”); ZERGBASE (one word).
State non-claims. If a feature is roadmap or not enforced, say so in Known limitations.
Link the source of truth. A behavior claim links to the reference chapter that proves it.
Code fences carry a language (bash, json, lua, erlang).
No secrets in examples. Use <redacted>, environment variable names, or placeholder paths.
Structure
One H1 per page.
A short intro before the first H2.
Task steps use numbered lists; reference tables use stable columns.
Admonitions use GitHub-style blockquotes (> [!NOTE]), which mdBook renders.
Anchors: never rename a heading that an alert rule links to without updating the alert.
Build and check
mdbook build docs-site
mdbook test docs-site # when Rust code blocks are present
python3 ci/portal_link_check.py
python3 ci/sync_docs.py --check