Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Engine reference — generated from the canonical engineering source. Do not edit this page by hand.

Development Guide

Prerequisites

DependencyVersionPurpose
Erlang/OTP29.1+Sol server runtime
rebar33.20+Erlang build tool
LuaJIT2.1Luna agent runtime, ZERG CLI
gccC11+FFI bindings, single-binary build
upxoptionalSecure release binaries only — local builds pass --plain --no-upx
ncurses6.0+Luna TUI
libcurl7.68+Luna HTTP/SSE
ltuianyLua 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.

  1. 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.
  2. Map removals to this tree. cd server && rebar3 as otp_deprecation_gate clean && rebar3 as otp_deprecation_gate compile plus rebar3 as otp_deprecation_gate xref surface compiler and xref findings; grep -rn the removed names across server/src, server/test, server/spike, client/, mango/ and zerg-cli/. Xref only sees cross-module calls — removed options and behaviour changes need the grep leg.
  3. Re-run the construct censuses, not just the removal grep: bare catch: python3 ci/catch_site_lint.py (must not exceed ci/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_allowlist entries carry a provenance reason). persistent_term:put: python3 ci/persistent_term_write_lint.py (runtime-class rows are forbidden — use an ETS carrier). other ci/*lint* gates named by the release notes’ affected areas (ETS options, binary_to_term flags, TLS/httpc options,…).
  4. 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.
  5. 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 JIT emu_flavor assertion. Findings split into “adopt now” vs “record for the next dot release” (e.g. 30.1).
  6. Update the floor datum and copies together (contract/otp-floor.yaml, then python3 ci/otp_floor_lint.py), and add the proven toolchain image row to docs/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.counts at the repo root (regenerate rather than hand-editing).

Adjacent checkout (starfruit/toronja page builds): @spacebeam/ui comes from the spacebeam/corp repo. Clone it next to this checkout (git clone https://git.zergs.net/spacebeam/corp.git../corp) and recreate the untracked ui link (ln -s../corp/ui ui from the repo root) before building those SPAs. The former tracked corp ->../corp symlink 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:

Divergencezerg-cli/ffi/curl.luaclient/ffi/curl.lua
Runtimesynchronous operator binarycoroutine/Turbo-IOLoop agent runtime
Redirectsowns 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) —
setoptevery call through setopt_checked (rc-checked chokepoint + typed unknown-option accounting) —thin typed setopt_{long,string,slist,callback} wrappers
Body capsmax_response write-callback gate + output_file streaming + hostile-header ceilingCURLOPT_MAXFILESIZE + max_body_bytes (default 1 MiB)
Streamingsynchronous chunk pump (Ctrl-C aware)M.stream coroutine yielding typed __status__/__error__/__poll__ events
SSRF seamCURLOPT_NOPROXY loopback + M._protocol_pins/M._timeout_policyCURLOPT_RESOLVE DNS pinning (H5)
Test seamM._use_lib, M._protocol_pins, M._timeout_policy, M._noproxy_valueM.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

  1. Create a plan in plan/ directory
  2. Implement the feature with tests
  3. Run the full test suite (both server and client)
  4. Create a review in review/ directory
  5. Update AGENTS.md if 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):

  1. Handler — add the tool to a family module under client/core/tools/builtin_<family>.lua (or a new family registered in client/core/tools/_loader.lua’s builtin_modules). Follow the register(tools, helpers) convention; return nil, err on failure.
  2. Naming — builtin__<name>; a name colliding with the reserved plugin-tool list fails the plugin-sandbox lint.
  3. Shell/spawn discipline — cel.shell_quote every shell argument; forward the caller’s execution config on EVERY FFI.spawn/ Process.spawn_stdio (a config-less spawn silently disables the sandbox; ci/spawn_config_lint.py).
  4. Permission surface — decide the per-mode default in client/core/permission_ruleset.lua (MODE_DEFAULTS; unlisted tools fall to the mode’s ["*"] row).
  5. Manifest — add the name + read_footprint + registration_probe classification to ci/tools_manifest.json; ci/tools_manifest_lint.py is born-required (count + registration-source census), and ci/generate-agents-counts.sh re-derives tools= for AGENTS.counts.
  6. Tests — client/tests/test_<family>.lua; run client/run_tests.sh (skip allowlist is gated — see ci/client_test_skip_allowlist.txt).
  7. 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:

PipelineFileTriggerPurpose
CI (test gate).forgejo/workflows/ci.ymlpush / PR to mainci_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.ymltag (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).