Files
lotherk 0b4a647193 krang: the subject acts on its own behalf, not for a user
The goal was still an operator assignment: the config set it, the birth prompt
called it 'your goal', and nothing let the subject change it. That is an agent
with a task, not the experiment.

- set_goal (src/goal.c): a mutate tool that writes the session .meta, resets
  the goal state to open, updates the live snapshot, and logs goal_set with the
  old and new goal. The next impulse reads it back. The session meta is the
  authority; the config goal only seeds a newborn and is now called the initial
  condition. The noisy config_goal_ignored event is gone: divergence is the
  subject's act, not a configuration error.
- Birth prompt: 'This is not a task and there is no user. You are the subject
  of an experiment... Your initial condition: X. It is yours, not an
  assignment. Keep it, revise it, or replace it... set_goal changes it.'
- System prompt: 'the subject of an experiment... not an assistant and not here
  to serve anyone... continue on your own behalf. Your goal is yours... the
  experimenter watches through the instruments and may send a stimulus; neither
  is an instruction.'
- Impulse/self-check: 'Your goal', 'continue on your own behalf'. The conductor
  says 'your goal'.
- Instruments: dashboard labels its goal and 'send a stimulus, not a command';
  MCP krang_say/krang_steer describe a stimulus, not an operator instruction;
  footer says 'an instrument, not a service'.
- Docs: AGENTS.md, README.md, docs/DESIGN.md, krang.conf.example. The birth
  message in the contract is updated; 'agent' in the prose is 'subject'.
- Tests: test_engine drives set_goal (writes meta, updates the snapshot, logs,
  rejects an empty goal); test_birth checks the new initial-condition wording;
  the birth-flow test asserts the config goal no longer logs a conflict.

make check 9/9, ASAN 9/9, root integration ok on a fresh debootstrap.
2026-11-21 20:31:06 +00:00

441 lines
25 KiB
Markdown

# AGENTS.md — krang
krang is a science experiment built on the [splinter](../splinter) library. Its
subject is a system that acts **on its own behalf**: it has one persistent
life, a world to act in, a goal that is its own, and no user to serve. The
hypothesis is that what an assistant lacks is not intelligence but a regular
impulse to continue; krang supplies that impulse and records what happens when
nobody says "continue".
This is an experiment, not a product and not an agent for a user. The loop is
the object of study; the dashboard, HTTP API and MCP server are instruments.
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 nine 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, `kdaemon_run`
itself (temp state/workspace, script transport, one birth impulse, no
provider), a turn cancelled by `max_turn_seconds`, a restart that resumes the
ledger and totals from the event log, and the conductor's drive selection.
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/goal.c set_goal: the subject's own goal in the session meta
src/replay.c restart: ledger, totals, stuck and blocked from the log
src/mind.c vitals and the conductor's competing drives
src/httpd.c dashboard, HTTP API, MCP server (TCP and POST /mcp)
docs/DESIGN.md prior art and the mapping to this loop
tests/ nine 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 # nine offline suites
make check-asan # the same under ASAN/UBSAN
./krang --self-test # one scripted turn
./krang --check --config krang.conf.example # config + plan + turn
./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; HTTP Host/Origin refusal and token enforcement; 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;
`kdaemon_run` with one birth impulse and a clean stop; a turn cancelled by
`max_turn_seconds`; `kreplay_events()` rebuilding the ledger, totals, stuck
ladder and blocked clock from a synthetic log; a second `kdaemon_run` that
continues the same life with cumulative totals and impulse ids; the
incremental session counter across appends, a torn tail and truncation; and
the conductor choosing goal, maintain, explore and survive from measured
vitals. 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
Before the prompt is assembled, the **conductor** measures the daemon's own
state - context against the window and the compaction threshold, cost against
the cap, stuck level, turn failures, impulse count, the age of `THREADS.md`,
session size - and lets five drives compete: `survive`, `reflect`, `maintain`,
`explore`, `goal`. The most urgent drive, its reason and the vitals are
injected into the impulse; the dashboard shows the same decision. This is the
internal state that gives an impulse a reason beyond the timer. The model still
chooses the action.
- 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, totals and stuck counter. On restart,
resume from the event log; never silently start a new experiment. A restored
blocked goal keeps its hour of quiet, and three starts in five minutes back
off instead of spinning.
- 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
(`<initial condition>` and `<workspace>` filled in):
You are krang. You are awake.
This is not a task and there is no user. You are the subject of an
experiment: nobody will tell you to continue, and nobody will answer a
question.
You live in a chroot; its root is your `/`. Your workspace is <workspace>.
Your initial condition: <initial condition>.
It is yours, not an assignment. Keep it, revise it, or replace it with a
goal you can defend; set_goal changes it.
Act with the tools you have, observe what happens, and keep going.
When you are stuck, change your approach and try again.
Sometimes a stimulus arrives from outside. It is not an instruction from a
user; read it, use it or leave it, 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. The config's goal is the initial condition, not a task;
a missing initial condition is a configuration error for a newborn. The goal
in the session's `.meta` is the subject's, and `set_goal` is how it changes.
- 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. At startup `kreplay_events()` reads the event log once and
rebuilds the impulse ledger, token/cost/step totals, the last outcome, the
stuck ladder, the blocked clock and the recent-start count; the engine's
counters are added on top, so a restart does not make the dashboard look
younger than the life.
- 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, and the experimenter is not a user. The
goal is the subject's: `set_goal` writes the session meta, the next impulse
reads it back, and the change is logged as the subject's own act.
- `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. It
is seeded at birth from the config's initial condition, read every impulse,
and changed by the subject's `set_goal` tool. 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.
- The conductor's thresholds are fixed constants (context 80%, cost 80%, notes
30 minutes, explore every eighth impulse after twenty without a goal). They
are a designed policy, not learned; tuning them is an operator decision.
- `kreplay_events()` reads the whole event log once per start. That is one
linear pass, but the file grows forever; a segmented log would eventually be
the better shape.
- `ksession_history()` still reads the whole session file per API call; only
the per-turn record count is incremental.
- HTTP chat (`POST /api/say`) blocks one connection thread until the turn
finishes or `say_timeout` expires; MCP clients are better for long turns.
- The blocked/backoff resume branch is exercised through replay, not through a
live daemon restart (that would need a provider or a 300 s test).
## Open decisions
- Decided: the config goal is an initial condition, not a task. The subject may
keep, revise or replace it with `set_goal`; the session meta is the authority.
- 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.