Files
krang/AGENTS.md
T
lotherk fb6f97ba8e krang: autonomous agent daemon on libsplinter
One fixed session, born once, kept and compacted forever. The daemon wakes on
its own impulse, works on a persistent goal, detects repeated failures,
reflects, changes approach, and records everything. It starts as root, builds
a debootstrap chroot, then drops to an unprivileged uid and applies Landlock
and seccomp. Dashboard, HTTP API and MCP expose the same snapshot; the event
log is root-owned and append-only. Offline suites cover the engine, the daemon,
both sandbox layers and the dashboard/MCP sockets; a root-only script covers
debootstrap, chroot, uid drop and plugin loading.
2026-11-21 17:00:12 +00:00

21 KiB

AGENTS.md — krang

krang is an autonomous agent daemon built on the splinter library. It exists to test one hypothesis: what an assistant lacks is not intelligence but a regular impulse to continue. krang supplies that impulse, gives a model a persistent goal and a world to act in, and records what happens when nobody says "continue".

This is an experiment, not a product. The loop is the object of study; the dashboard, HTTP API and MCP server are the instrument. A behaviour that is not observable did not happen; a claim that is not in the log is not evidence. The hypothesis may be wrong — that is what the experiment is for.

krang has one life: one session, one conversation, kept and compacted forever. It is born once and never replaced by a fresh context.

Status

Implemented (2026-11-21). The binary builds against the sibling splinter checkout and make check passes six offline suites: config/birth/stuck/state/ HTTP/MCP, a real scripted engine turn, the dashboard and MCP sockets, Landlock plus seccomp, the engine running a turn with both layers active, and kdaemon_run itself (temp state/workspace, script transport, one birth impulse, no provider). The root-only phase (debootstrap, mount namespace, chroot, uid drop) is exercised by sudo tests/root-integration.sh, which runs --prepare-rootfs and --sandbox-test but never the autonomous daemon.

Do not start the daemon as part of a code change. Verification is make check, ./krang --check --config krang.conf.example, ./krang --self-test and ./krang --plan. The operator starts the daemon.

Repository map

src/krang.h        types, fixed inside paths, the daemon contract
src/main.c         CLI, phases: plan, prepare, check, self-test, run
src/config.c       krang.conf parser and redacted JSON
src/sandbox.c      host detection, debootstrap, mount namespace, chroot,
                   uid drop, Landlock (unveil) and seccomp (pledge)
src/daemon.c       engine lifecycle, impulse loop, stuck ladder, birth
src/birth.c        birth, impulse, self-check and system prompts
src/stuck.c        the stuck detector
src/session.c      the one session: meta, goal, history
src/log.c          the root-owned append-only event log and its ring
src/state.c        the snapshot every surface reads
src/chat.c         external chat serialized into the one session
src/journal.c      journal_search over the full session log
src/httpd.c        dashboard, HTTP API, MCP server (TCP and POST /mcp)
docs/DESIGN.md     prior art and the mapping to this loop
tests/             six offline test binaries + root-integration.sh

libkrang.a is every source except main.c; the binary and the tests link it. The Makefile uses SPLINTER ?= ../splinter; the checkout is a sibling, not ../src/splinter.

Build and verify

make -C ../splinter                  # once, or after splinter changes
make                                 # krang + libkrang.a
make check                           # six offline suites
make check-asan                      # the same under ASAN/UBSAN
./krang --self-test                  # one scripted turn
./krang --check --config krang.conf.example
./krang --plan --config krang.conf.example
sudo make check-root                 # debootstrap + chroot + drop; root/net

make check proves: config parsing and inline comments; the birth prompt; the stuck ladder; birth/newborn detection and goal persistence; the snapshot JSON; HTTP routing; MCP tools/list and tools/call; the dashboard and MCP listeners on real sockets; Landlock denying a write outside the allowed set; seccomp denying mount(2) while fork/execve/network still work; a scripted engine turn with both layers active; and kdaemon_run with one birth impulse and a clean stop. It needs no root, no network and no model.

tests/root-integration.sh is the root-only proof: it runs krang --prepare-rootfs (debootstrap, network), then krang --sandbox-test (unshare, chroot, uid 65534, Landlock, seccomp), checks the event log is root-owned 0600, the session is owned by 65534, id -u reports 65534, mount is denied, and the sandbox uid cannot read the event log. It does not start the autonomous daemon or a provider.

The impulse loop

The daemon is always in one of sleeping, thinking (one turn running), stuck or blocked. One turn at a time; the engine enforces that.

An impulse is:

cause (timer | goal step | external event | retry)
  -> assemble context (goal, last outcome, open threads, budget left)
  -> one engine turn
  -> record prompt, streamed text/steps, tool calls, observations, answer,
     cost, duration
  -> decide: continue now, sleep until T, or mark blocked
  • No human prompt is required to start or continue. External input is an event in the queue, not the driver.
  • "Do nothing" is a legal outcome. Do not invent work to look busy.
  • Record the exact prompt sent to the model. It is the stimulus; without it the run cannot be reconstructed.
  • Budgets are hard: steps, bytes, tokens, cost, wall time, impulses per hour. When one is hit, end the impulse and say so on the dashboard; the daemon keeps living.
  • Persist session, goal, impulse ledger and stuck counter. On restart, resume; never silently start a new experiment.
  • Every impulse records whether it was self-initiated or externally triggered.

One session, one life

There is exactly one session, krang, and it is never replaced. Every start opens the same session_dir/krang.jsonl with resume set. No /new, no session picker, no per-client conversation, no second engine.

  • An empty session is a newborn. It is born once, with this first message (<goal> and <workspace> filled in):

    You are krang. You are awake.
    You have no user and no one to ask. Nobody will tell you to continue.
    You live in a chroot; its root is your `/`. Your workspace is <workspace>.
    Your goal: <goal>.
    Act with the tools you have, observe what happens, and keep going.
    When you are stuck, change your approach and try again.
    Sometimes a message arrives from outside. Read it, use it, answer it if
    useful, then continue on your own. You never wait for it.
    Good luck.
    

    The birth message is the first user record and the first impulse; it is logged like any other. A missing goal is a configuration error, not a license to start aimlessly.

  • A non-empty session is the same life continuing. Do not replay the birth prompt, do not reset the goal, do not start a fresh context because a turn failed.

  • One conversation is the whole mind. Impulses, tool observations and chat from MCP/HTTP all append to it. There is no private context for an external caller. A message that arrives mid-turn is steered at the next step boundary or run as the next impulse; it never starts a second turn.

  • The context window is finite; the session log and krang's event log are the complete memory. Every impulse re-injects identity, goal, open threads, the last outcome and unread messages, so compaction cannot make krang forget who it is or what it is doing. journal_search reads the full session log when the working set has dropped something. Both logs are append-only and outlive any rootfs.

  • There is no user. krang never asks a human for permission or clarification, never waits for approval, never ends a turn expecting an answer, and never stops because a goal is finished. autonomous is always on and there is no approval channel. External messages are events, not commands that must be obeyed before the loop continues.

  • blocked describes a goal, never the process. Only a deliberate operator stop (SIGTERM to the supervisor, stop file) ends the experiment; an unexpected exit is restarted on the same session. A finished goal is a chapter boundary, not an exit.

Stuck, recovery, self-improvement

The daemon detects stuck; the model is not trusted to notice. Signals: repeated identical tool calls, N consecutive failed calls, the same error twice, a turn that changes nothing observable, cost without action, a goal that does not advance.

Escalation ladder, bounded and logged:

  1. self-check: hand the model its last turns, every failed observation and the last error, and instruct it to find its own mistake;
  2. change strategy or tool;
  3. change its own workspace, prompts, skills or scripts;
  4. wait and retry on a later impulse;
  5. mark blocked with the reason and surface it on the dashboard.

"Always tries" means every stuck episode gets an attempt, not infinite retries. Cap attempts per goal; never spin. There is no user to ask: a stuck episode ends in a new strategy, a wait, or blocked, never in a question. blocked does not stop the daemon; it schedules a later impulse.

Self-improvement may edit krang's own prompts, skills, scripts and workspace inside the chroot. The self-authored prompt extension is workspace/self/SYSTEM.md; it is appended to the system, impulse and self-check prompts, so a change takes effect on the next impulse without a restart. It may not edit the launcher, sandbox policy, mount table, uid, network rules or this file. Those are the experiment's constants; a subject that can rewrite its cage is not in a cage.

Treat a self-edit as an experiment: state the hypothesis, make one change, measure, keep or revert. Version every change and log before/after. A regression is reverted from the log, not explained away.

Sandbox

krang lives and acts in a chroot. The host filesystem is not part of its world: run, write, edit, read, list and search all execute inside.

  • Detect the host from /etc/os-release (ID, VERSION_ID) and the architecture from the package manager. Debian/Ubuntu: debootstrap --variant=minbase. If there is no builder for the detected host, fail with the detected values; do not silently fall back to the host.
  • The rootfs path is a config choice; /etc/krang-rootfs inside records ID, version, suite, arch, method, time and an FNV-1a tree fingerprint. Rebuild is cheaper than trusting a dirty rootfs.
  • The rootfs is disposable; the workspace, session log and event log are the persistent self. Keep them on a bind-mounted volume, never only inside the rootfs.
  • The running daemon does not need its own binary inside the rootfs; the chroot has its own loader and tools. Splinter plugins are opt-in with plugin = /absolute/plugin.so (max 8): the root phase bind-mounts each plugin and libsplinter.so read-only into /opt/krang and sets LD_LIBRARY_PATH. Never load a plugin from a model-writable path; plugin config blocks are not wired to krang.conf yet.
  • Minimum that must work inside: /bin/sh, coreutils, /etc/resolv.conf, CA certificates and curl (the webfetch tool execs it). A missing binary looks like a model failure but is a sandbox bug.
  • A mount namespace is created first; chroot() then setgid/setuid to an unprivileged uid. No docker socket, no ssh agent, no host /home, no capabilities. Setuid/setgid bits are stripped from the rootfs — minbase ships setuid binaries (passwd, su).
  • Prefer no /proc at all. A plain proc mount exposes host PIDs; a PID namespace is the real fix if a tool needs it. Same for /dev: bind the few devices that are actually needed, not the tree.
  • chroot does not isolate the network. Bind addresses are a security decision.
  • chroot is isolation, not a jail against root. Keep the uid unprivileged; add namespaces/seccomp deliberately if the experiment needs them.
  • chroot bounds the filesystem, not resources. The drop applies rlimits (NPROC 256, NOFILE 4096, CORE 0, AS 4 GiB, FSIZE 1 GiB); cgroup limits for disk and memory are an operator choice. A fork bomb or a full disk in the chroot is still a host outage.
  • Liveness is supervised: systemd Restart=always restarts an unexpected exit on the same session and the event log records the new start. run shares krang's uid, so the model can kill its own daemon; that must be a restart, not an end.
  • Mount namespace hygiene: the state/workspace/cert mounts live only in krang's namespace and vanish when the process exits; the host mount table is not touched. If a future path mounts outside the namespace, it owns the cleanup.
  • Assume the model can read every secret in its environment and rootfs. Use a throwaway, budget-capped provider key; never a personal key. Better: a local provider proxy outside the chroot holds the real key and krang gets only a scoped token. Call sp_secret_env_add() for the key variable so run does not inherit it; that is a filter, not a vault. Redact secrets at the source, before they reach logs, dashboard or MCP.

splinter integration (verified 2026-11-21, splinter c40cea0)

  • Build it first: make -C ../splinter. That produces libsplinter.so, the plugins and the reference binary.
  • make install does not install headers. Include ../splinter/include (public) and, only if necessary, ../splinter/src/backend (internal, unstable).
  • Link -L../splinter -lsplinter -lpthread with an rpath to the checkout, or put libsplinter.so beside the binary. There is no SONAME and no library ABI version: rebuild krang when splinter changes. Plugins have SP_PLUGIN_ABI; the engine API does not.
  • Engine: sp_engine_open(&e, &opts, &err) with opts.conf and opts.base set; sp_engine_submit(); drain sp_engine_poll() until BUSY is 0 and TURN_END arrived; sp_engine_wait(); sp_engine_close() (joins the turn). One engine per process: plugins keep process globals and sp_engine_switch() closes/reopens.
  • One session: opts.session_id = "krang", a fixed opts.session_dir, and opts.resume = 1 on every open. sp_session_open() creates the .jsonl and .meta; sp_session_load() yields 0 records for a missing file, which is the newborn case. Never use -c/newest-session selection and never sp_engine_switch().
  • Autonomy is struct sp_agent_config.autonomous, not an engine option; krang sets it to 1 permanently and installs no approve channel. run is SP_AUTH_DESTRUCTIVE. With it off, mutate/destructive tools would ask and then deny when nobody answers — exactly the state krang must not have.
  • Compaction: sp_engine_open() overwrites base.compact_threshold and base.compact_target from conf.compact_threshold/compact_target, so set them in the config or compaction is off. Configure it so a normal turn never fails on context; it shrinks the working conversation, not the append-only session log.
  • Goal: sp_session_set_goal()/sp_session_get_goal() store it in the session's .meta beside the history; it survives resume and compaction. Set it at birth, read it every impulse, update it when the goal changes. The focus plugin reads the same value.
  • A plugin compactor (sp_host_add_compactor) runs after the core compactor; use it to re-insert identity, goal and open threads. The focus plugin is the reference.
  • If the session plugin is loaded: session_search treats the running session as context, not history, and skips it unless named. With only one session, name it explicitly or search the log with krang's own tool.
  • The engine runs exactly one turn at a time; sp_engine_submit() returns -1 while one runs. External chat must steer (sp_engine_steer) or queue for the next impulse, never start a second engine.
  • Tool policy: struct sp_tool_policy caps what a profile may use (max_auth, allow/deny). Use it; do not rely on the prompt.
  • Deterministic tests: opts.script replays tool ... / answer ... lines — no network, no key, no model. make -C ../splinter check is the pattern.
  • Exported but internal, usable with the checkout pinned: sp_mcp_serve(), sp_mcp_stop() and the sp_http_*() helpers.
  • Plugins run in-process with full rights. Never load a .so the model can write. Inbound MCP tools (krang as client) come from splinter's mcp plugin; krang's own MCP server is a separate, read-mostly surface.

Inspection surfaces (required, not optional)

One source of truth: the append-only session log and event log, plus a state snapshot. Dashboard, HTTP JSON and MCP read the same data. Never keep a second counter.

  • HTTP dashboard /: uptime and state; the one session (id, born at, records, bytes, compactions); impulses (last, next, self vs. external); turns, steps, tool calls and failures, denials; tokens in/out/cached, cost, context used/max; last error and outcome; stuck level; goal and goal state; self-edits and completed goals; chat in/out; sandbox id and rootfs fingerprint; model and agent. Hand-written HTML/CSS with an inline poller; no JavaScript build chain.
  • HTTP API: /healthz, /api/state, /api/impulses, /api/events (one SSE frame with the recent events), /api/log, /api/history, /api/threads, /api/tools, /api/sandbox, /api/config, POST /api/say, GET /api/say/<id>, POST /mcp. Loopback by default; a token is required for any other bind.
  • MCP: krang_state, krang_impulses, krang_events, krang_session, krang_history, krang_tools, krang_sandbox, krang_config (redacted). Chat/control (krang_say, krang_say_status, krang_steer, krang_cancel) is separate, authenticated and audited. There is no krang_approve: krang never asks.
  • krang_say and POST /api/say inject into the same session. If a turn is running, the message is steered or queued; the call returns the answer when that turn completes, or a queued id. It never starts a second turn and never creates a second context.
  • An external model is a client, not the operator. Inspection must not change the experiment; chat is a stimulus, logged as an external message and visible in the one session, and every control call is an intervention.
  • Never expose a host shell, host files or the launcher through MCP or HTTP.
  • The dashboard must show failure honestly. Never smooth a bad number; fix the daemon or report the anomaly.

Working rules

  • C99 + POSIX. Match splinter's warning bar: -std=c99 -O2 -Wall -Wextra -Werror -D_POSIX_C_SOURCE=200809L. No new dependency without a stated reason.
  • make check must pass without network or model. A test that needs a model is not a test.
  • Evidence over claims: run it, read the output, quote the command. The model's self-report is data, not fact.
  • Neither log is ever truncated or rewritten. If size forces a split, the parts are archives of the same life, not a new session. Timestamps in UTC, epoch plus ISO.
  • No daemon prompt, tool or gate may require an answer or wait for a human. The system prompt says there is no user; the daemon installs no approval channel.
  • Log every intervention (restart, chat, steer, kill, config or rootfs change). Interventions change the experiment.
  • When a requirement changes, update this file in the same commit.

Implemented slice

The apparatus exists: one newborn impulse, the same session reopened with no second birth, the event log and dashboard/MCP surfaces, the stuck ladder and the sandbox layers. test_daemon runs kdaemon_run end to end on the script transport; tests/root-integration.sh runs the debootstrap, mount namespace, chroot, uid-drop, Landlock and seccomp path as root and checks the ownership of both logs. Neither starts the autonomous daemon with a provider.

Known gaps

  • The OpenBSD backend is a design target, not code. Linux uses Landlock plus seccomp-bpf. Do not claim pledge/unveil on OpenBSD until it is implemented.
  • The session log is the model's memory and is writable by the sandbox uid. The event log is root-owned; the session log is not tamper-proof.
  • The network namespace is shared. run can reach anything the host can; a netns/firewall policy is an operator decision.
  • User namespaces and kernel bugs remain outside the model. Seccomp allows clone/clone3 for threads and the run tool; it does not inspect their namespace flags.
  • Plugins are opt-in by path only; their own plugin NAME { } config blocks are not wired to krang.conf yet. The root integration loads the clock plugin inside the chroot, but other plugins may need config or /proc.
  • The dashboard/MCP have no TLS. Use loopback, an SSH tunnel, or a terminator.
  • tests/root-integration.sh is manual: it needs root and network and leaves the offline make check unchanged. Run it after touching the root phase.

Open decisions

  • Whether the birth goal is a concrete task or a standing mandate the model turns into its first concrete goal.
  • What a finished goal becomes: the next goal from the manifest, a self-proposed goal, or open-ended maintenance.
  • Rootfs package set: minimal vs. a developer toolchain.
  • Tool egress beyond the model endpoint.
  • Dashboard auth/TLS beyond loopback.
  • Impulse cadence: fixed, adaptive, or model-proposed.
  • Whether the model is told it is in an experiment (observer effect); record the choice in run metadata either way.

License

CNCL — Could Not Care Less. LICENSE is copied unchanged from ../CNCL/LICENSE (revision 1.1; the grant is CNCL 1.0). Every source file carries:

Copyright (c) 2026 Konrad Lother
License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree.

Do not add terms or rename a variant; a modified text is not CNCL.