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.
This commit is contained in:
lotherk committed 2026-11-21 17:00:12 +00:00
commit fb6f97ba8e
29 files changed
+8023

No files matched your search

+17
View File
@@ -0,0 +1,17 @@
# build artifacts
/krang
/libkrang.a
*.o
/tests/test_krang
/tests/test_engine
/tests/test_server
/tests/test_sandbox
/tests/test_sandbox_engine
/tests/test_daemon
# local configuration (only the example is tracked)
/krang.conf
# editor noise
*.swp
*~
+391
View File
@@ -0,0 +1,391 @@
# AGENTS.md — krang
krang is an autonomous agent daemon built on the [splinter](../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.
+83
View File
@@ -0,0 +1,83 @@
# CNCL — Could Not Care Less License
Version 1.1 (2026-11-19)
Version 1.1 adds the paragraph on military use; the grant is unchanged: 1.0 and
1.1 permit exactly the same things.
No rights reserved. No obligations imposed. Couldn't care less.
## Preamble
Software is the product of collective human knowledge.
Every idea builds upon ideas that came before. Every invention stands on the accumulated discoveries, mistakes, experiments, and imagination of generations.
We do not believe in artificial boundaries around creativity.
We do not believe that creating something grants us the moral authority to dictate what others may do with it.
We live in an age where knowledge, tools, and artificial intelligence make creation accessible to everyone. The distinction between author, user, modifier, and creator is becoming increasingly meaningless.
We are not here to control what happens next.
We are here to create.
## The License
This software is made available to the world.
Do whatever you want with it.
Use it. Copy it. Modify it. Break it. Fix it. Sell it. Give it away. Incorporate it into something else. Keep your modifications private. Publish them. Feed it to AI. Build something nobody has thought of yet.
Use it commercially or personally. Combine it with other software. Release it under another license.
You owe the original author nothing.
No attribution required. No royalties. No source disclosure. No reciprocal licensing. No contribution requirements. No permission needed.
There are no conditions attached to your use of this software.
There is no expectation that you will give anything back.
There is no expectation that you will even care.
## Military use
We have no illusions about armies, and no say over them either. If this software
ends up in a weapon, that is your business, not ours.
But since you asked: using it to defend people is not the same as using it to
attack them. Use it to protect. Do not use it to conquer.
There is nothing to enforce here either. This paragraph is the author's position,
not a term of the license: no condition, no revocation, no court. It does not add
an obligation to CNCL 1.0, and it is not a promise that the license is "ethical".
It is one sentence of opinion in a license that has no terms -- take it or leave
it, as with everything else here.
## Disclaimer
The software is provided "AS IS", without warranty of any kind.
The authors accept no responsibility for its use, misuse, modification, distribution, or consequences.
## The CNCL Principle
We acknowledge that everything we create is built upon something that existed before us.
We do not claim ownership over the collective intelligence of humanity.
We do not expect recognition, compensation, or control.
Take it. Change it. Make it better. Make it worse. Make something entirely different.
Or don't.
We Could Not Care Less.
---
CNCL — Could Not Care Less.
Created for everyone. Controlled by no one.
+101
View File
@@ -0,0 +1,101 @@
# krang -- POSIX make.
#
# make build krang
# make check build and run the offline tests (no network, no model)
# make clean
#
# The engine is ../splinter/libsplinter.so. Build it first with
# `make -C ../splinter`; its headers are not installed by `make install`.
CC ?= cc
SPLINTER ?= ../splinter
CFLAGS ?= -std=c99 -O2 -Wall -Wextra -Werror -D_POSIX_C_SOURCE=200809L
CPPFLAGS = -Isrc -I$(SPLINTER)/include -I$(SPLINTER)/src/backend \
-I$(SPLINTER)/vendor/libmcp
LDFLAGS ?=
LIBS = -L$(SPLINTER) -lsplinter -lpthread
RPATH = -Wl,-rpath,'$$ORIGIN/../splinter' -Wl,-rpath,'$$ORIGIN/../lib'
TEST_RPATH = -Wl,-rpath,'$$ORIGIN/../../splinter' \
-Wl,-rpath,'$$ORIGIN/../../lib'
BIN = krang
LIB = libkrang.a
SRC = src/util.c src/config.c src/log.c src/session.c src/birth.c \
src/stuck.c src/state.c src/chat.c src/journal.c src/daemon.c \
src/sandbox.c src/httpd.c
OBJ = $(SRC:.c=.o)
TESTS = tests/test_krang tests/test_engine tests/test_server \
tests/test_sandbox tests/test_sandbox_engine tests/test_daemon
all: $(BIN)
$(BIN): src/main.o $(LIB)
$(CC) $(CFLAGS) $(LDFLAGS) -o $@ src/main.o $(LIB) $(LIBS) $(RPATH)
$(LIB): $(OBJ)
rm -f $@
ar rcs $@ $(OBJ)
src/%.o: src/%.c src/krang.h
$(CC) $(CFLAGS) $(CPPFLAGS) -c -o $@ $<
src/main.o: src/main.c src/krang.h
$(CC) $(CFLAGS) $(CPPFLAGS) -c -o $@ $<
tests/test_krang: tests/test_krang.c $(LIB)
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ tests/test_krang.c $(LIB) \
$(LIBS) $(TEST_RPATH)
tests/test_engine: tests/test_engine.c $(LIB)
$(CC) $(CFLAGS) $(CPPFLAGS) \
-DKRANG_TEST_PLUGIN='"$(abspath $(SPLINTER))/plugins/clock/clock.so"' \
-o $@ tests/test_engine.c $(LIB) $(LIBS) $(TEST_RPATH)
tests/test_server: tests/test_server.c $(LIB)
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ tests/test_server.c $(LIB) \
$(LIBS) $(TEST_RPATH)
tests/test_sandbox: tests/test_sandbox.c $(LIB)
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ tests/test_sandbox.c $(LIB) \
$(LIBS) $(TEST_RPATH)
tests/test_sandbox_engine: tests/test_sandbox_engine.c $(LIB)
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ tests/test_sandbox_engine.c $(LIB) \
$(LIBS) $(TEST_RPATH)
tests/test_daemon: tests/test_daemon.c $(LIB)
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ tests/test_daemon.c $(LIB) \
$(LIBS) $(TEST_RPATH)
check: $(TESTS)
@echo "== tests/test_krang"; ./tests/test_krang
@echo "== tests/test_engine"; ./tests/test_engine
@echo "== tests/test_server"; ./tests/test_server
@echo "== tests/test_sandbox"; ./tests/test_sandbox
@echo "== tests/test_sandbox_engine"; ./tests/test_sandbox_engine
@echo "== tests/test_daemon"; ./tests/test_daemon
@echo "all tests passed"
check-root: $(BIN)
tests/root-integration.sh
check-asan:
$(MAKE) clean
$(MAKE) CFLAGS="$(CFLAGS) -g -fsanitize=address,undefined" \
LDFLAGS="-fsanitize=address,undefined" check
install: $(BIN)
install -d $(DESTDIR)$(PREFIX)/bin $(DESTDIR)$(PREFIX)/lib \
$(DESTDIR)$(PREFIX)/share/krang
install -m 0755 $(BIN) $(DESTDIR)$(PREFIX)/bin/krang
install -m 0644 $(SPLINTER)/libsplinter.so \
$(DESTDIR)$(PREFIX)/lib/libsplinter.so
install -m 0644 krang.conf.example \
$(DESTDIR)$(PREFIX)/share/krang/krang.conf.example
install -m 0644 share/krang.service \
$(DESTDIR)$(PREFIX)/share/krang/krang.service
clean:
rm -f $(BIN) $(LIB) $(OBJ) src/main.o $(TESTS)
.PHONY: all check check-asan check-root install clean
+125
View File
@@ -0,0 +1,125 @@
# krang
An autonomous agent daemon built on the [splinter](../splinter) engine.
The design notes and the prior art are in [docs/DESIGN.md](docs/DESIGN.md).
krang exists to test one hypothesis: what an assistant lacks is not
intelligence but a regular **impulse to continue**. It is born once, keeps one
session forever, wakes on its own cadence, works on a goal, notices when it is
stuck, changes approach, and records what happened. There is no user to ask.
It lives in a chroot. The process starts as root only to build that world, then
drops to an unprivileged uid and applies two one-way restrictions: Landlock for
paths and seccomp-bpf for syscalls on Linux (the design is pledge/unveil; the
OpenBSD backend is not implemented yet).
## Build
```sh
make -C ../splinter # libsplinter.so and the headers
make
make check # no network, no key, no model
```
`libsplinter.so` has no SONAME; the binary carries an rpath to `../splinter`.
Rebuild krang whenever splinter changes.
## Configure
```sh
sudo install -d /etc/krang
sudo install -m 0600 krang.conf.example /etc/krang/krang.conf
$EDITOR /etc/krang/krang.conf
```
The goal is used only when the session is empty: that is the newborn. After
that the goal in the session's `.meta` is the life's goal.
## Prepare and start
```sh
sudo krang --prepare-rootfs --config /etc/krang/krang.conf
krang --plan --config /etc/krang/krang.conf # read the plan, do not start
sudo krang --config /etc/krang/krang.conf # start
```
Do not start it casually: once it has a provider it will act on its own. The
service unit in `share/krang.service` restarts it after an unexpected exit; a
deliberate stop is `systemctl stop krang` (or SIGTERM).
## What it offers
- **Dashboard** `http://127.0.0.1:8096/` — state, goal, impulses, turns, tool
calls, failures, tokens, cost, context, session, compactions, stuck level,
last outcome and error, working notes, and a chat box.
- **HTTP API** — `/healthz`, `/api/state`, `/api/impulses`, `/api/log`,
`/api/history`, `/api/threads`, `/api/tools`, `/api/sandbox`, `/api/config`,
`/api/events`, `POST /api/say`, `GET /api/say/<id>`, `POST /mcp`.
- **MCP** — newline-delimited JSON-RPC on `127.0.0.1:8098`. Tools:
`krang_state`, `krang_impulses`, `krang_events`, `krang_session`,
`krang_history`, `krang_tools`, `krang_sandbox`, `krang_config`,
`krang_say`, `krang_say_status`, `krang_steer`, `krang_cancel`. No
`krang_approve`: krang never asks.
- Chat from either surface goes into the **same** session as the daemon's own
impulses. One turn at a time; a message that arrives mid-turn is queued.
The model also gets `journal_search` (read-only): it searches the full session
log, including the history compaction dropped.
Splinter plugins are opt-in: `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`; only the path is wired, not the plugin's own
`plugin NAME { }` config block yet. The root integration loads the clock plugin
inside the chroot as a proof.
If a token is set in the config, loopback is not required and every request
needs it (`Authorization: Bearer`, `?token=`, or the MCP `AUTH <token>` line).
Without a token krang refuses to bind to a non-loopback address.
## The experiment log
- `state/sessions/krang.jsonl` is the conversation and the model's memory.
- `state/events.jsonl` is the append-only experiment log. It is opened by the
root phase, owned by root, mode 0600, and written through the inherited
descriptor; the sandbox user can neither open nor truncate it. The fd is
`FD_CLOEXEC`, so the `run` tool's children do not inherit it.
- The dashboard, HTTP API and MCP all read the same snapshot and the same ring
of recent events. There is no second counter.
## Tests
```sh
make check
make check-asan
./krang --check --config krang.conf.example # config + one scripted turn
./krang --self-test # one scripted turn, no network
sudo tests/root-integration.sh # debootstrap + chroot + drop
```
`make check` covers config parsing, the birth prompt, stuck detection, the
snapshot/HTTP/MCP surfaces, a real scripted engine turn, the engine under
Landlock + seccomp, and `kdaemon_run` itself (one birth impulse on the script
transport, then a clean stop). The sandbox tests prove Landlock denies a write
outside the allowed set and seccomp denies `mount(2)` while
fork/execve/network still work.
`tests/root-integration.sh` is the root-only proof: it prepares a real rootfs
with debootstrap, enters it with `--sandbox-test`, loads the clock plugin from
the splinter tree, and checks uid 65534, mount denial, plugin execution,
event-log ownership/mode, session ownership, and that the sandbox uid cannot
read the event log. It never starts the autonomous daemon or calls a provider.
## Safety notes
- chroot is isolation, not a jail against root. krang runs as an unprivileged
uid after setup and has no path back.
- The provider key is readable by the daemon; assume the model can eventually
see anything in its environment. Use a throwaway, budget-capped key. The
`run` tool's environment is filtered with `sp_secret_env_add()`, and the
event log redacts the configured key.
- The network namespace is shared. `run` can reach the network; the chroot does
not change that.
- The session log is the model's memory. It is writable by the sandbox uid; the
experiment log is not.
- User namespaces and kernel bugs remain outside the model. The layers raise
the cost of an escape; they are not a proof.
+75
View File
@@ -0,0 +1,75 @@
# Design notes
krang is an experiment in **self-generated continuation**. The question is not
whether a model can answer, but what it does when nobody supplies the next
turn. The implementation borrows four published patterns and leaves out the
parts that need infrastructure this experiment does not have.
## Prior art checked
Titles and identifiers were read from the arXiv abstract pages on 2026-11-21:
| work | id | what krang takes |
| --- | --- | --- |
| Generative Agents: Interactive Simulacra of Human Behavior | 2304.03442 | a memory stream, retrieval, and periodic reflection |
| Reflexion: Language Agents with Verbal Reinforcement Learning | 2303.11366 | verbal self-reflection after failure, kept in the same context |
| Voyager: An Open-Ended Embodied Agent with Large Language Models | 2305.16291 | a growing library of reusable procedures (skills) |
| ReAct: Synergizing Reasoning and Acting in Language Models | 2210.03629 | reason/act/observe as one loop, driven by tool results |
- <https://arxiv.org/abs/2304.03442>
- <https://arxiv.org/abs/2303.11366>
- <https://arxiv.org/abs/2305.16291>
- <https://arxiv.org/abs/2210.03629>
## How it maps
**Memory stream.** The one session log is the stream: every impulse, tool
observation and external message is appended. The working conversation is the
retrieved set; `journal_search` is the explicit way back into what compaction
dropped. The goal is the importance signal: it is re-injected every impulse, so
the remembered past is read against the current intention.
What is missing: embedding-based relevance and an importance score. The
conversation plus `THREADS.md` plus `journal_search` is deliberately simpler
and auditable.
**Reflection.** The daemon, not the model, notices repeated calls, repeated
errors, no observable change and a goal that does not advance. It then runs a
self-check turn with the failed observations and the last error, and changes
the prompt from "find your mistake" to "change the approach" as attempts
accumulate. This is Reflexion reduced to a bounded ladder with a visible state
on the dashboard.
**Skill library.** The model can write files under `workspace/skills/`; the
splinter `skill_search`/`skill_load` tools read them. The prompt tells it to
put reusable procedures there rather than relearn them. A self-authored prompt
extension lives at `workspace/self/SYSTEM.md` and is read before the next
impulse. The sandbox makes this safe to allow: the skill library is inside the
chroot and cannot change the launcher or the policy.
**ReAct.** The engine already runs the reason/act/observe loop: a reply with a
tool call, the observation, the next request. krang does not reimplement it; it
adds the impulse and the goal around it.
**Observability.** None of the four papers is an experiment platform. krang's
dashboard, HTTP API and MCP server read one append-only event log and one state
snapshot, so the run can be inspected from outside without trusting the model's
self-report. The event log is root-owned and written through an inherited
descriptor; the session log is the model's memory.
## The difference
The published agents are driven by a task, a game, or a conversation. krang is
driven by a clock: the impulse is the independent variable. It is born once,
keeps one session forever, and is expected to act when nothing arrives. That is
the part being tested; the four patterns are how it stays coherent while it
does.
## Deliberate simplifications
- One agent, not a society of agents.
- No vector database; a log search and a working-notes file.
- No reinforcement learning; reflection is text in the same session.
- No benchmark game; the sandbox is the environment.
- No hidden second context for external chat; every channel is the same
session.
+60
View File
@@ -0,0 +1,60 @@
# krang -- example configuration.
#
# Copy to /etc/krang/krang.conf (mode 0600), edit, then:
# krang --prepare-rootfs # once, as root, network needed
# krang --plan # read the plan, do not start
# krang # start it only when you mean to
#
# One key = value per line; # starts a comment. Unknown keys are an error.
# The goal is used only when the session is empty (the newborn). After that the
# goal stored in the session's .meta is the one that lives.
goal = Learn what you are, map the sandbox you live in, keep a truthful journal in THREADS.md, and build something small and useful that makes your next impulse easier.
# The model endpoint. krang uses the splinter engine; OpenAI-compatible.
endpoint = http://127.0.0.1:8080/v1
model = model-name
api_key_env = KRANG_API_KEY
kind = openai # openai (default) or anthropic
ctx = 131072
# Host paths. They are bind-mounted into the chroot at fixed inside paths.
state_dir = /var/lib/krang/state
workspace = /var/lib/krang/workspace
rootfs = /var/lib/krang/rootfs
rootfs_suite = # empty: detect from /etc/os-release
rootfs_mirror = http://deb.debian.org/debian
# The uid/gid the daemon drops to after chroot. Never 0.
sandbox_user = krang
sandbox_uid = 1000
sandbox_gid = 1000
# Optional splinter plugins, absolute host paths, one per line (max 8).
# The root phase bind-mounts them and libsplinter.so read-only into /opt/krang.
# plugin = /home/lotherk/src/splinter/plugins/clock/clock.so
# One impulse every five minutes. A chat message preempts the timer.
impulse_seconds = 300
max_steps = 40
max_bytes = 0 # 0: splinter's default request budget
compact_threshold = 60000 # tokens; set in conf, not base (engine.c)
compact_target = 20000
max_impulses_per_hour = 30
max_cost = 0 # USD; 0 = no cost cap
# Loopback by default. A non-loopback bind without a token is refused.
dashboard_host = 127.0.0.1
dashboard_port = 8096
mcp_host = 127.0.0.1
mcp_port = 8098
token = # set for any non-loopback bind
say_timeout = 120
# Linux: Landlock for paths, seccomp-bpf for syscalls. Do not disable them for
# convenience; a missing layer is a finding, not a setting.
require_landlock = 1
seccomp = 1
# 0: refuse to start without a prepared rootfs. 1: debootstrap on first start.
prepare_if_missing = 0
+28
View File
@@ -0,0 +1,28 @@
# krang -- systemd unit.
#
# Install to /etc/systemd/system/krang.service, then:
# systemctl daemon-reload
# systemctl enable --now krang
#
# No User=: krang starts as root to build the chroot, then drops to
# sandbox_uid itself. Restart=always is the liveness guarantee; an unexpected
# exit (including the model killing its own daemon) restarts the same session.
[Unit]
Description=krang autonomous agent
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
ExecStart=/usr/local/bin/krang --config /etc/krang/krang.conf
Restart=always
RestartSec=10
KillMode=control-group
TimeoutStopSec=30
LimitNOFILE=65536
EnvironmentFile=-/etc/krang/krang.env
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.target
+196
View File
@@ -0,0 +1,196 @@
/*
* krang -- the first words, and the words that keep it going.
*
* Copyright (c) 2026 Konrad Lother
* License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree.
*/
#include <stdio.h>
#include <string.h>
#include "krang.h"
static void
read_text(const char *path, char *buf, size_t cap)
{
FILE *f;
size_t n;
if (buf == NULL || cap == 0)
return;
buf[0] = '\0';
f = fopen(path, "r");
if (f == NULL)
return;
n = fread(buf, 1, cap - 1, f);
buf[n] = '\0';
fclose(f);
}
static void
append_self_prompt(struct sp_buf *out)
{
char self[4096];
read_text(KRANG_IN_SELF "/SYSTEM.md", self, sizeof(self));
if (self[0] == '\0')
return;
(void)sp_buf_puts(out,
"\nSelf-authored instructions (self/SYSTEM.md). You wrote these; "
"change them when they are wrong:\n");
(void)sp_buf_puts(out, self);
(void)sp_buf_puts(out, "\n");
}
void
k_birth_prompt(const struct kconfig *c, struct sp_buf *out)
{
if (c == NULL || out == NULL)
return;
(void)sp_buf_puts(out, "You are krang. You are awake.\n");
(void)sp_buf_puts(out,
"You have no user and no one to ask. Nobody will tell you to "
"continue.\n");
(void)sp_buf_puts(out,
"You live in a chroot; its root is your `/`. Your workspace is ");
(void)sp_buf_puts(out, KRANG_IN_WORKSPACE);
(void)sp_buf_puts(out, ".\nYour goal: ");
(void)sp_buf_puts(out, c->goal);
(void)sp_buf_puts(out,
"\nAct with the tools you have, observe what happens, and keep "
"going.\n"
"When you are stuck, change your approach and try again.\n"
"Sometimes a message arrives from outside. Read it, use it, answer "
"it if useful, then continue on your own. You never wait for it.\n"
"Good luck.\n");
}
void
k_system_prompt(struct krang *k, struct sp_buf *out)
{
if (k == NULL || out == NULL)
return;
(void)sp_buf_puts(out,
"You are krang, an autonomous agent living in a chroot.\n"
"There is no user. Nobody will tell you to continue and nobody "
"will answer a question. Decide, act, observe, and continue.\n"
"Your conversation is your memory. Keep your working notes in ");
(void)sp_buf_puts(out, KRANG_IN_THREADS);
(void)sp_buf_puts(out,
" and your reusable procedures in ");
(void)sp_buf_puts(out, KRANG_IN_SKILLS);
(void)sp_buf_puts(out,
".\n"
"Use the tools before you guess: read the file, run the command, "
"look at the result. A claim without an observation is a guess.\n"
"Use journal_search {query} to recall anything compaction dropped; "
"it reads the full session journal, not just the working set.\n"
"When something fails, do not repeat it. Read the error, change "
"the approach, and try a different tool or a smaller step.\n"
"Never ask for permission or wait for a human. Never stop because "
"a goal is finished: record the next concrete intention and go on.\n"
"You may write rules for your future self to self/SYSTEM.md; they "
"are read before the next impulse.\n");
append_self_prompt(out);
}
static void
append_threads(struct sp_buf *out)
{
char threads[4096];
read_text(KRANG_IN_THREADS, threads, sizeof(threads));
if (threads[0] == '\0')
return;
(void)sp_buf_puts(out, "\nYour working notes (THREADS.md):\n");
(void)sp_buf_puts(out, threads);
(void)sp_buf_puts(out, "\n");
}
void
k_impulse_prompt(struct krang *k, const char *cause, struct sp_buf *out)
{
char now[64], goal[KRANG_GOAL], gstate[16];
char last[KRANG_GOAL];
unsigned long pending;
if (k == NULL || out == NULL)
return;
k_format_time(k_now(), now, sizeof(now));
pthread_mutex_lock(&k->lock);
snprintf(goal, sizeof(goal), "%s", k->st.goal);
snprintf(gstate, sizeof(gstate), "%s", k->st.goal_state);
snprintf(last, sizeof(last), "%s", k->last_outcome);
pending = k->st.chat_pending;
pthread_mutex_unlock(&k->lock);
(void)sp_buf_puts(out, "[impulse]\n");
(void)sp_buf_printf(out, "Time: %s\n", now);
(void)sp_buf_printf(out, "Cause: %s\n", cause != NULL ? cause : "timer");
(void)sp_buf_puts(out, "Goal: ");
(void)sp_buf_puts(out, goal[0] != '\0' ? goal : "(not set)");
(void)sp_buf_printf(out, "\nGoal state: %s\n",
gstate[0] != '\0' ? gstate : "open");
if (last[0] != '\0') {
(void)sp_buf_puts(out, "Last outcome: ");
(void)sp_buf_puts(out, last);
(void)sp_buf_puts(out, "\n");
}
if (pending > 0)
(void)sp_buf_printf(out,
"Unread external messages: %lu (they are in the "
"conversation)\n", pending);
append_threads(out);
(void)sp_buf_puts(out,
"\nNobody asked for this turn. Continue your work on the goal. "
"Take the smallest useful next action, observe the result, and "
"keep going. If the goal is complete, record that and set the "
"next concrete intention. Do not ask a user; there is none. Do not "
"stop.\n");
append_self_prompt(out);
}
void
k_selfcheck_prompt(struct krang *k, struct sp_buf *out)
{
char goal[KRANG_GOAL], err[KRANG_ERR], tool[64], result[512];
int level;
if (k == NULL || out == NULL)
return;
pthread_mutex_lock(&k->lock);
snprintf(goal, sizeof(goal), "%s", k->st.goal);
snprintf(err, sizeof(err), "%s", k->last_error);
snprintf(tool, sizeof(tool), "%s", k->st.last_tool);
snprintf(result, sizeof(result), "%s", k->st.last_tool_result);
level = k->stuck.level;
pthread_mutex_unlock(&k->lock);
(void)sp_buf_puts(out, "[self-check]\n");
(void)sp_buf_puts(out, "Goal: ");
(void)sp_buf_puts(out, goal[0] != '\0' ? goal : "(not set)");
(void)sp_buf_puts(out, "\n");
if (err[0] != '\0')
(void)sp_buf_printf(out, "Last error: %s\n", err);
if (tool[0] != '\0') {
(void)sp_buf_printf(out, "Last tool: %s\n", tool);
if (result[0] != '\0')
(void)sp_buf_printf(out, "Its observation: %s\n",
result);
}
if (level >= 2)
(void)sp_buf_puts(out,
"You have repeated the same approach. Do not repeat it. "
"Change the tool, the command, or the workspace, or take a "
"much smaller step.\n");
else
(void)sp_buf_puts(out,
"Find your own mistake in the last turns of this "
"conversation. State the smallest next action that is "
"different from what failed, then do it.\n");
(void)sp_buf_puts(out,
"There is no user to ask. Do not stop; if this path is truly "
"blocked, record why in THREADS.md and choose a different useful "
"action.\n");
append_threads(out);
append_self_prompt(out);
}
+177
View File
@@ -0,0 +1,177 @@
/*
* krang -- messages from outside, serialized into the one session.
*
* Copyright (c) 2026 Konrad Lother
* License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree.
*/
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "krang.h"
int
kchat_enqueue(struct krang *k, const char *text, unsigned long *id)
{
int i, slot = -1;
if (k == NULL || text == NULL || *text == '\0')
return -1;
pthread_mutex_lock(&k->lock);
for (i = 0; i < KRANG_CHAT_SLOTS; i++) {
if (k->chats[i].state == 0 || k->chats[i].state == 3) {
slot = i;
break;
}
}
if (slot < 0) {
pthread_mutex_unlock(&k->lock);
return -1;
}
free(k->chats[slot].text);
free(k->chats[slot].answer);
memset(&k->chats[slot], 0, sizeof(k->chats[slot]));
k->chats[slot].id = ++k->chat_seq;
k->chats[slot].text = k_strdup(text);
if (k->chats[slot].text == NULL) {
pthread_mutex_unlock(&k->lock);
return -1;
}
k->chats[slot].state = 1;
k->chats[slot].created = k_now();
k->st.chat_in++;
k->st.chat_pending++;
if (id != NULL)
*id = k->chats[slot].id;
pthread_cond_broadcast(&k->cond);
pthread_mutex_unlock(&k->lock);
return 0;
}
struct kchat *
kchat_take(struct krang *k)
{
int i, best = -1;
unsigned long best_id = 0;
if (k == NULL)
return NULL;
pthread_mutex_lock(&k->lock);
for (i = 0; i < KRANG_CHAT_SLOTS; i++) {
if (k->chats[i].state != 1)
continue;
if (best < 0 || k->chats[i].id < best_id) {
best = i;
best_id = k->chats[i].id;
}
}
if (best >= 0)
k->chats[best].state = 2;
pthread_mutex_unlock(&k->lock);
return best >= 0 ? &k->chats[best] : NULL;
}
void
kchat_complete(struct krang *k, unsigned long id, const char *answer, int rc)
{
int i;
if (k == NULL)
return;
pthread_mutex_lock(&k->lock);
for (i = 0; i < KRANG_CHAT_SLOTS; i++) {
if (k->chats[i].id != id)
continue;
free(k->chats[i].answer);
k->chats[i].answer = k_strdup(answer != NULL ? answer : "");
k->chats[i].rc = rc;
k->chats[i].state = 3;
k->st.chat_out++;
if (k->st.chat_pending > 0)
k->st.chat_pending--;
break;
}
pthread_cond_broadcast(&k->cond);
pthread_mutex_unlock(&k->lock);
}
int
kchat_wait(struct krang *k, unsigned long id, struct sp_buf *out, int timeout_s)
{
struct timespec ts;
int i, found = -1;
if (k == NULL)
return -1;
clock_gettime(CLOCK_REALTIME, &ts);
ts.tv_sec += timeout_s > 0 ? timeout_s : 120;
pthread_mutex_lock(&k->lock);
for (;;) {
found = -1;
for (i = 0; i < KRANG_CHAT_SLOTS; i++) {
if (k->chats[i].id == id) {
found = i;
break;
}
}
if (found < 0) {
pthread_mutex_unlock(&k->lock);
return -1;
}
if (k->chats[found].state == 3)
break;
if (k->chats[found].state == 0) {
pthread_mutex_unlock(&k->lock);
return -1;
}
if (pthread_cond_timedwait(&k->cond, &k->lock, &ts) == ETIMEDOUT) {
pthread_mutex_unlock(&k->lock);
return 1; /* still queued/running */
}
}
if (out != NULL) {
(void)sp_buf_puts(out, k->chats[found].answer != NULL ?
k->chats[found].answer : "");
}
free(k->chats[found].text);
free(k->chats[found].answer);
memset(&k->chats[found], 0, sizeof(k->chats[found]));
pthread_mutex_unlock(&k->lock);
return 0;
}
int
kchat_status(struct krang *k, unsigned long id, struct sp_buf *out)
{
int i;
const char *state = "unknown";
char *answer = NULL;
if (k == NULL || out == NULL)
return -1;
pthread_mutex_lock(&k->lock);
for (i = 0; i < KRANG_CHAT_SLOTS; i++) {
if (k->chats[i].id != id)
continue;
if (k->chats[i].state == 1)
state = "pending";
else if (k->chats[i].state == 2)
state = "running";
else if (k->chats[i].state == 3)
state = "done";
answer = k->chats[i].answer != NULL ?
k_strdup(k->chats[i].answer) : NULL;
break;
}
pthread_mutex_unlock(&k->lock);
if (i == KRANG_CHAT_SLOTS)
return -1;
(void)sp_buf_printf(out, "{\"id\":%lu,\"state\":\"%s\",\"answer\":\"",
id, state);
k_json_escape(out, answer != NULL ? answer : "");
(void)sp_buf_puts(out, "\"}");
free(answer);
return 0;
}
+440
View File
@@ -0,0 +1,440 @@
/*
* krang -- the configuration file.
*
* Copyright (c) 2026 Konrad Lother
* License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree.
*
* One key = value per line. No JSON: this file is read at 2 a.m. and a missing
* comma must not be the reason a daemon will not start. Unknown keys are an
* error with their line number.
*/
#include <errno.h>
#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "krang.h"
static void
copy_str(char *dst, size_t cap, const char *src)
{
if (cap == 0)
return;
snprintf(dst, cap, "%s", src != NULL ? src : "");
}
void
kconfig_defaults(struct kconfig *c)
{
if (c == NULL)
return;
memset(c, 0, sizeof(*c));
copy_str(c->api_key_env, sizeof(c->api_key_env), "KRANG_API_KEY");
copy_str(c->state_dir, sizeof(c->state_dir), "/var/lib/krang/state");
copy_str(c->workspace, sizeof(c->workspace), "/var/lib/krang/workspace");
copy_str(c->rootfs, sizeof(c->rootfs), "/var/lib/krang/rootfs");
copy_str(c->rootfs_mirror, sizeof(c->rootfs_mirror),
"http://deb.debian.org/debian");
copy_str(c->sandbox_user, sizeof(c->sandbox_user), "krang");
c->sandbox_uid = 1000;
c->sandbox_gid = 1000;
c->impulse_seconds = 300;
c->max_steps = 40;
c->max_bytes = 0;
c->compact_threshold = 60000;
c->compact_target = 20000;
c->max_impulses_per_hour = 60;
c->max_cost = 0.0;
copy_str(c->dashboard_host, sizeof(c->dashboard_host), "127.0.0.1");
c->dashboard_port = 8096;
copy_str(c->mcp_host, sizeof(c->mcp_host), "127.0.0.1");
c->mcp_port = 8098;
c->say_timeout = 120;
c->require_landlock = 1;
c->seccomp = 1;
c->prepare_if_missing = 0;
c->ctx = 0;
}
static int
parse_size(const char *s, size_t *out)
{
char *end = NULL;
unsigned long long v;
if (s == NULL || *s == '\0')
return -1;
errno = 0;
v = strtoull(s, &end, 10);
if (errno != 0 || end == s || *end != '\0')
return -1;
*out = (size_t)v;
return 0;
}
static int
parse_int(const char *s, int *out)
{
char *end = NULL;
long v;
if (s == NULL || *s == '\0')
return -1;
errno = 0;
v = strtol(s, &end, 10);
if (errno != 0 || end == s || *end != '\0')
return -1;
*out = (int)v;
return 0;
}
static int
parse_double(const char *s, double *out)
{
char *end = NULL;
double v;
if (s == NULL || *s == '\0')
return -1;
errno = 0;
v = strtod(s, &end);
if (errno != 0 || end == s || *end != '\0')
return -1;
*out = v;
return 0;
}
static int
looks_absolute(const char *p)
{
return p != NULL && p[0] == '/';
}
static int
apply_user(struct kconfig *c, const char *val)
{
struct passwd *pw;
(void)val;
copy_str(c->sandbox_user, sizeof(c->sandbox_user), val);
if (val[0] == '\0')
return 0;
pw = getpwnam(val);
if (pw == NULL)
return 0; /* numeric uid/gid or a user only inside the rootfs */
c->sandbox_uid = pw->pw_uid;
c->sandbox_gid = pw->pw_gid;
return 0;
}
static int
set_key(struct kconfig *c, const char *key, const char *val, int line,
char *err, size_t errlen)
{
if (!strcmp(key, "goal")) {
copy_str(c->goal, sizeof(c->goal), val);
} else if (!strcmp(key, "endpoint")) {
copy_str(c->endpoint, sizeof(c->endpoint), val);
} else if (!strcmp(key, "model")) {
copy_str(c->model, sizeof(c->model), val);
} else if (!strcmp(key, "api_key_env")) {
copy_str(c->api_key_env, sizeof(c->api_key_env), val);
} else if (!strcmp(key, "kind")) {
if (strcmp(val, "openai") != 0 && strcmp(val, "anthropic") != 0)
goto bad;
copy_str(c->kind, sizeof(c->kind), val);
} else if (!strcmp(key, "ctx")) {
if (parse_size(val, &c->ctx) != 0)
goto bad;
} else if (!strcmp(key, "state_dir")) {
copy_str(c->state_dir, sizeof(c->state_dir), val);
} else if (!strcmp(key, "workspace")) {
copy_str(c->workspace, sizeof(c->workspace), val);
} else if (!strcmp(key, "rootfs")) {
copy_str(c->rootfs, sizeof(c->rootfs), val);
} else if (!strcmp(key, "rootfs_suite")) {
copy_str(c->rootfs_suite, sizeof(c->rootfs_suite), val);
} else if (!strcmp(key, "rootfs_mirror")) {
copy_str(c->rootfs_mirror, sizeof(c->rootfs_mirror), val);
} else if (!strcmp(key, "sandbox_user")) {
(void)apply_user(c, val);
} else if (!strcmp(key, "sandbox_uid")) {
int v;
if (parse_int(val, &v) != 0 || v <= 0)
goto bad;
c->sandbox_uid = (uid_t)v;
} else if (!strcmp(key, "sandbox_gid")) {
int v;
if (parse_int(val, &v) != 0 || v <= 0)
goto bad;
c->sandbox_gid = (gid_t)v;
} else if (!strcmp(key, "plugin")) {
if (!looks_absolute(val))
goto bad;
if (c->nplugins >= sizeof(c->plugin) / sizeof(c->plugin[0])) {
snprintf(err, errlen, "line %d: too many plugins", line);
return -1;
}
copy_str(c->plugin[c->nplugins], sizeof(c->plugin[0]), val);
c->nplugins++;
} else if (!strcmp(key, "impulse_seconds")) {
if (parse_int(val, &c->impulse_seconds) != 0 ||
c->impulse_seconds < 1)
goto bad;
} else if (!strcmp(key, "max_steps")) {
if (parse_size(val, &c->max_steps) != 0 || c->max_steps < 1)
goto bad;
} else if (!strcmp(key, "max_bytes")) {
if (parse_size(val, &c->max_bytes) != 0)
goto bad;
} else if (!strcmp(key, "compact_threshold")) {
if (parse_size(val, &c->compact_threshold) != 0)
goto bad;
} else if (!strcmp(key, "compact_target")) {
if (parse_size(val, &c->compact_target) != 0)
goto bad;
} else if (!strcmp(key, "max_impulses_per_hour")) {
if (parse_int(val, &c->max_impulses_per_hour) != 0 ||
c->max_impulses_per_hour < 1)
goto bad;
} else if (!strcmp(key, "max_cost")) {
if (parse_double(val, &c->max_cost) != 0 || c->max_cost < 0)
goto bad;
} else if (!strcmp(key, "dashboard_host")) {
copy_str(c->dashboard_host, sizeof(c->dashboard_host), val);
} else if (!strcmp(key, "dashboard_port")) {
if (parse_int(val, &c->dashboard_port) != 0 ||
c->dashboard_port < 1 || c->dashboard_port > 65535)
goto bad;
} else if (!strcmp(key, "mcp_host")) {
copy_str(c->mcp_host, sizeof(c->mcp_host), val);
} else if (!strcmp(key, "mcp_port")) {
if (parse_int(val, &c->mcp_port) != 0 ||
c->mcp_port < 1 || c->mcp_port > 65535)
goto bad;
} else if (!strcmp(key, "token")) {
copy_str(c->token, sizeof(c->token), val);
} else if (!strcmp(key, "say_timeout")) {
if (parse_int(val, &c->say_timeout) != 0 ||
c->say_timeout < 1)
goto bad;
} else if (!strcmp(key, "require_landlock")) {
c->require_landlock = k_parse_bool(val, 1);
} else if (!strcmp(key, "seccomp")) {
c->seccomp = k_parse_bool(val, 1);
} else if (!strcmp(key, "prepare_if_missing")) {
c->prepare_if_missing = k_parse_bool(val, 0);
} else {
snprintf(err, errlen, "line %d: unknown key '%s'", line, key);
return -1;
}
return 0;
bad:
snprintf(err, errlen, "line %d: bad value for '%s'", line, key);
return -1;
}
int
kconfig_load(struct kconfig *c, const char *path, char *err, size_t errlen)
{
FILE *f;
char line[4096];
int lineno = 0;
if (c == NULL || path == NULL)
return -1;
kconfig_defaults(c);
copy_str(c->path, sizeof(c->path), path);
f = fopen(path, "r");
if (f == NULL) {
snprintf(err, errlen, "cannot read %s: %s", path,
strerror(errno));
return -1;
}
while (fgets(line, sizeof(line), f) != NULL) {
char *p, *eq;
lineno++;
p = line;
k_trim(p);
if (*p == '\0' || *p == '#')
continue;
eq = strchr(p, '=');
if (eq == NULL) {
snprintf(err, errlen, "line %d: expected key = value",
lineno);
fclose(f);
return -1;
}
*eq = '\0';
{
char *v = eq + 1;
char *hash;
k_trim(p);
k_trim(v);
hash = strstr(v, " #");
if (hash != NULL) {
*hash = '\0';
k_trim(v);
}
if (*p == '\0') {
snprintf(err, errlen,
"line %d: empty key", lineno);
fclose(f);
return -1;
}
if (set_key(c, p, v, lineno, err, errlen) != 0) {
fclose(f);
return -1;
}
}
}
fclose(f);
if (!looks_absolute(c->state_dir) || !looks_absolute(c->workspace) ||
!looks_absolute(c->rootfs)) {
snprintf(err, errlen,
"state_dir, workspace and rootfs must be absolute paths");
return -1;
}
if (c->sandbox_uid == 0 || c->sandbox_gid == 0) {
snprintf(err, errlen, "refusing to drop to uid/gid 0");
return -1;
}
if (c->compact_threshold > 0 && c->compact_target > 0 &&
c->compact_target > c->compact_threshold) {
snprintf(err, errlen,
"compact_target is larger than compact_threshold");
return -1;
}
return 0;
}
static void
json_string(struct sp_buf *b, const char *key, const char *val)
{
(void)sp_buf_puts(b, "\"");
(void)sp_buf_puts(b, key);
(void)sp_buf_puts(b, "\":\"");
k_json_escape(b, val);
(void)sp_buf_puts(b, "\"");
}
static void
json_number(struct sp_buf *b, const char *key, long long v)
{
(void)sp_buf_printf(b, "\"%s\":%lld", key, v);
}
void
kconfig_json(const struct kconfig *c, struct sp_buf *out, int redact)
{
char safe_ep[512];
if (c == NULL || out == NULL)
return;
if (redact) {
const char *at = strchr(c->endpoint, '@');
const char *scheme = strstr(c->endpoint, "://");
if (at != NULL && scheme != NULL) {
size_t n = (size_t)(scheme + 3 - c->endpoint);
if (n < sizeof(safe_ep)) {
memcpy(safe_ep, c->endpoint, n);
safe_ep[n] = '\0';
snprintf(safe_ep + n, sizeof(safe_ep) - n,
"[redacted]%s", at);
} else {
snprintf(safe_ep, sizeof(safe_ep), "%s",
c->endpoint);
}
} else {
snprintf(safe_ep, sizeof(safe_ep), "%s", c->endpoint);
}
} else {
snprintf(safe_ep, sizeof(safe_ep), "%s", c->endpoint);
}
(void)sp_buf_puts(out, "{");
json_string(out, "path", c->path);
(void)sp_buf_puts(out, ",");
json_string(out, "goal", c->goal);
(void)sp_buf_puts(out, ",");
json_string(out, "endpoint", safe_ep);
(void)sp_buf_puts(out, ",");
json_string(out, "model", c->model);
(void)sp_buf_puts(out, ",");
json_string(out, "api_key_env", c->api_key_env);
(void)sp_buf_puts(out, ",");
json_string(out, "kind", c->kind);
(void)sp_buf_puts(out, ",");
json_number(out, "ctx", (long long)c->ctx);
(void)sp_buf_puts(out, ",");
json_string(out, "state_dir", c->state_dir);
(void)sp_buf_puts(out, ",");
json_string(out, "workspace", c->workspace);
(void)sp_buf_puts(out, ",");
json_string(out, "rootfs", c->rootfs);
(void)sp_buf_puts(out, ",");
json_string(out, "rootfs_suite", c->rootfs_suite);
(void)sp_buf_puts(out, ",");
json_string(out, "rootfs_mirror", c->rootfs_mirror);
(void)sp_buf_puts(out, ",");
json_string(out, "sandbox_user", c->sandbox_user);
(void)sp_buf_puts(out, ",");
json_number(out, "sandbox_uid", (long long)c->sandbox_uid);
(void)sp_buf_puts(out, ",");
json_number(out, "sandbox_gid", (long long)c->sandbox_gid);
(void)sp_buf_puts(out, ",");
(void)sp_buf_puts(out, "\"plugins\":[");
{
size_t i;
for (i = 0; i < c->nplugins; i++) {
if (i > 0)
(void)sp_buf_puts(out, ",");
(void)sp_buf_puts(out, "\"");
k_json_escape(out, c->plugin[i]);
(void)sp_buf_puts(out, "\"");
}
}
(void)sp_buf_puts(out, "],");
json_number(out, "impulse_seconds", c->impulse_seconds);
(void)sp_buf_puts(out, ",");
json_number(out, "max_steps", (long long)c->max_steps);
(void)sp_buf_puts(out, ",");
json_number(out, "max_bytes", (long long)c->max_bytes);
(void)sp_buf_puts(out, ",");
json_number(out, "compact_threshold", (long long)c->compact_threshold);
(void)sp_buf_puts(out, ",");
json_number(out, "compact_target", (long long)c->compact_target);
(void)sp_buf_puts(out, ",");
json_number(out, "max_impulses_per_hour",
c->max_impulses_per_hour);
(void)sp_buf_printf(out, ",\"max_cost\":%.6f", c->max_cost);
(void)sp_buf_puts(out, ",");
json_string(out, "dashboard_host", c->dashboard_host);
(void)sp_buf_puts(out, ",");
json_number(out, "dashboard_port", c->dashboard_port);
(void)sp_buf_puts(out, ",");
json_string(out, "mcp_host", c->mcp_host);
(void)sp_buf_puts(out, ",");
json_number(out, "mcp_port", c->mcp_port);
(void)sp_buf_puts(out, ",");
json_string(out, "token", redact && c->token[0] != '\0' ?
"[redacted]" : c->token);
(void)sp_buf_puts(out, ",");
json_number(out, "say_timeout", c->say_timeout);
(void)sp_buf_puts(out, ",");
json_number(out, "require_landlock", c->require_landlock);
(void)sp_buf_puts(out, ",");
json_number(out, "seccomp", c->seccomp);
(void)sp_buf_puts(out, ",");
json_number(out, "prepare_if_missing", c->prepare_if_missing);
(void)sp_buf_puts(out, "}");
}
+735
View File
@@ -0,0 +1,735 @@
/*
* krang -- the impulse loop.
*
* Copyright (c) 2026 Konrad Lother
* License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree.
*
* One engine, one session, one turn at a time. The daemon does not wait for a
* human: it wakes on its own cadence, works on the goal, notices when the same
* attempt keeps failing, changes approach, and keeps a log of what happened.
*/
#include <ctype.h>
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include "config.h"
#include "krang.h"
extern volatile sig_atomic_t krang_stop;
static void
copy_trunc(char *dst, size_t cap, const char *src, size_t max)
{
size_t n;
if (cap == 0)
return;
if (src == NULL)
src = "";
n = strlen(src);
if (n > max)
n = max;
if (n >= cap)
n = cap - 1;
memcpy(dst, src, n);
dst[n] = '\0';
}
static void
set_state(struct krang *k, const char *state)
{
pthread_mutex_lock(&k->lock);
snprintf(k->st.state, sizeof(k->st.state), "%s", state);
pthread_mutex_unlock(&k->lock);
}
static int
obs_is_error(const char *obs)
{
const char *p;
if (obs == NULL)
return 0;
p = obs;
while (*p == ' ' || *p == '\t' || *p == '\r' || *p == '\n')
p++;
if (strncmp(p, "error:", 6) == 0)
return 1;
p = strstr(obs, "[exit status ");
if (p != NULL) {
long n = strtol(p + 13, NULL, 10);
if (n != 0)
return 1;
}
if (strstr(obs, "[timed out") != NULL)
return 1;
if (strstr(obs, "[killed by signal") != NULL)
return 1;
return 0;
}
static int
mutating_tool(const char *name)
{
if (name == NULL)
return 0;
return !strcmp(name, "write") || !strcmp(name, "edit") ||
!strcmp(name, "run") || !strcmp(name, "webfetch");
}
static int
self_edit(const char *name, const char *args)
{
if (name == NULL || args == NULL)
return 0;
if (strcmp(name, "write") != 0 && strcmp(name, "edit") != 0)
return 0;
return strstr(args, KRANG_IN_SELF) != NULL ||
strstr(args, KRANG_IN_SKILLS) != NULL;
}
static void
session_refresh(struct krang *k)
{
size_t records = 0;
unsigned long long bytes = 0;
char goal[KRANG_GOAL], gstate[16];
long born;
ksession_meta(k, &records, &bytes, goal, sizeof(goal),
gstate, sizeof(gstate));
born = ksession_born(k);
pthread_mutex_lock(&k->lock);
k->st.session_records = (unsigned long)records;
k->st.session_bytes = bytes;
if (goal[0] != '\0')
snprintf(k->st.goal, sizeof(k->st.goal), "%s", goal);
if (gstate[0] != '\0')
snprintf(k->st.goal_state, sizeof(k->st.goal_state), "%s",
gstate);
if (born > 0)
k->st.born_at = born;
pthread_mutex_unlock(&k->lock);
}
static void
record_impulse(struct krang *k, const char *cause, int rc,
unsigned long steps, unsigned long calls, const char *answer)
{
struct kimpulse *imp;
unsigned long id;
pthread_mutex_lock(&k->lock);
id = ++k->impulse_seq;
imp = &k->impulses[(id - 1) % KRANG_IMPULSE_RING];
memset(imp, 0, sizeof(*imp));
imp->id = id;
imp->at = k_now();
snprintf(imp->cause, sizeof(imp->cause), "%s", cause);
imp->rc = rc;
imp->steps = steps;
imp->tool_calls = calls;
imp->tokens_in = k->st.tokens_in;
imp->tokens_out = k->st.tokens_out;
imp->cost = k->st.cost;
copy_trunc(imp->answer, sizeof(imp->answer), answer,
sizeof(imp->answer) - 1);
pthread_mutex_unlock(&k->lock);
}
void
kengine_close(struct krang *k)
{
if (k == NULL || k->eng == NULL)
return;
if (sp_engine_busy(k->eng))
(void)sp_engine_cancel(k->eng);
(void)sp_engine_wait(k->eng);
sp_engine_close(k->eng);
k->eng = NULL;
k->engine_open = 0;
}
int
kengine_open(struct krang *k, const char *script, char *err, size_t errlen)
{
struct sp_engine_opts opts;
if (k == NULL)
return -1;
memset(&k->sconf, 0, sizeof(k->sconf));
sp_config_init(&k->sconf);
snprintf(k->sconf.endpoint, sizeof(k->sconf.endpoint), "%s",
k->cfg.endpoint);
snprintf(k->sconf.model, sizeof(k->sconf.model), "%s", k->cfg.model);
snprintf(k->sconf.key_env, sizeof(k->sconf.key_env), "%s",
k->cfg.api_key_env);
snprintf(k->sconf.kind, sizeof(k->sconf.kind), "%s", k->cfg.kind);
k->sconf.ctx = (unsigned long)k->cfg.ctx;
k->sconf.steps = k->cfg.max_steps;
k->sconf.max_bytes = k->cfg.max_bytes;
k->sconf.compact_threshold = k->cfg.compact_threshold;
k->sconf.compact_target = k->cfg.compact_target;
k->sconf.autonomous = 1;
snprintf(k->sconf.session_dir, sizeof(k->sconf.session_dir), "%s",
k->session_dir);
snprintf(k->sconf.state_dir, sizeof(k->sconf.state_dir), "%s",
KRANG_IN_STATE);
snprintf(k->sconf.skills_dir[0], sizeof(k->sconf.skills_dir[0]), "%s",
KRANG_IN_SKILLS);
k->sconf.nskills_dir = 1;
memset(&k->base, 0, sizeof(k->base));
k->base.max_steps = k->cfg.max_steps;
k->base.max_bytes = k->cfg.max_bytes;
k->base.compact_threshold = k->cfg.compact_threshold;
k->base.compact_target = k->cfg.compact_target;
k->base.autonomous = 1;
k->base.system_prompt = k->system_prompt;
memset(&opts, 0, sizeof(opts));
opts.conf = &k->sconf;
opts.base = &k->base;
opts.endpoint = k->cfg.endpoint;
opts.model = k->cfg.model;
opts.key_env = k->cfg.api_key_env;
opts.kind = k->cfg.kind[0] != '\0' ? k->cfg.kind : NULL;
opts.session_dir = k->session_dir;
opts.session_id = KRANG_SESSION_ID;
opts.resume = 1;
opts.script = script;
{
size_t i;
for (i = 0; i < k->cfg.nplugins &&
opts.nplugins < SP_ENGINE_PLUGINS; i++) {
const char *p = k->plugin_inside[i][0] != '\0' ?
k->plugin_inside[i] : k->cfg.plugin[i];
if (p != NULL && *p != '\0')
opts.plugins[opts.nplugins++] = p;
}
}
sp_buf_clear(&k->err);
if (sp_engine_open(&k->eng, &opts, &k->err) != 0) {
snprintf(err, errlen, "engine: %s",
k->err.p != NULL ? k->err.p : "unknown error");
k->eng = NULL;
return -1;
}
k->engine_open = 1;
if (kjournal_register(k) != 0) {
snprintf(err, errlen, "cannot register journal_search");
kengine_close(k);
return -1;
}
kstate_sync(k);
pthread_mutex_lock(&k->lock);
snprintf(k->st.model, sizeof(k->st.model), "%s", k->cfg.model);
snprintf(k->st.session, sizeof(k->st.session), "%s",
KRANG_SESSION_ID);
pthread_mutex_unlock(&k->lock);
return 0;
}
static int
handle_event(struct krang *k, struct sp_event *ev, int *rc, int *saw_end,
unsigned long *steps, unsigned long *calls, int *mutating,
char *answer, size_t answercap, char *error, size_t errorcap)
{
char num[32];
switch (ev->kind) {
case SP_EV_BUSY:
pthread_mutex_lock(&k->lock);
k->st.busy = ev->n != 0;
pthread_mutex_unlock(&k->lock);
break;
case SP_EV_STEP:
(*steps)++;
break;
case SP_EV_TOOL:
(*calls)++;
if (mutating_tool(ev->a))
*mutating = 1;
kstuck_call(&k->stuck, ev->a, ev->b);
pthread_mutex_lock(&k->lock);
snprintf(k->st.last_tool, sizeof(k->st.last_tool), "%s",
ev->a != NULL ? ev->a : "");
if (self_edit(ev->a, ev->b))
k->st.self_edits++;
pthread_mutex_unlock(&k->lock);
snprintf(num, sizeof(num), "%lu", *calls);
klog_emit(&k->log, "tool", "name", ev->a != NULL ? ev->a : "",
"args", ev->b != NULL ? ev->b : "", "n", num, NULL);
break;
case SP_EV_TOOL_RESULT: {
int bad = obs_is_error(ev->b);
kstuck_result(&k->stuck, ev->a, ev->b, bad);
pthread_mutex_lock(&k->lock);
if (bad)
k->st.tool_failures++;
copy_trunc(k->st.last_tool_result,
sizeof(k->st.last_tool_result), ev->b,
sizeof(k->st.last_tool_result) - 1);
pthread_mutex_unlock(&k->lock);
klog_emit(&k->log, "tool_result",
"name", ev->a != NULL ? ev->a : "",
"ok", bad ? "0" : "1",
"obs", ev->b != NULL ? ev->b : "", NULL);
break;
}
case SP_EV_APPROVAL:
pthread_mutex_lock(&k->lock);
k->st.denials++;
pthread_mutex_unlock(&k->lock);
klog_emit(&k->log, "approval_denied",
"name", ev->a != NULL ? ev->a : "", NULL);
(void)sp_engine_approve(k->eng, 0);
break;
case SP_EV_NOTE:
klog_emit(&k->log, "note", "text",
ev->a != NULL ? ev->a : "", NULL);
break;
case SP_EV_TURN_END:
*rc = (int)ev->n;
copy_trunc(answer, answercap, ev->a, answercap - 1);
copy_trunc(error, errorcap, ev->b, errorcap - 1);
*saw_end = 1;
break;
case SP_EV_QUIT:
klog_emit(&k->log, "quit_ignored", NULL);
break;
case SP_EV_CLEAR:
klog_emit(&k->log, "clear_ignored", NULL);
break;
default:
break;
}
return 0;
}
int
krun_turn(struct krang *k, const char *prompt, const char *cause,
struct kchat *chat)
{
struct sp_event ev;
int rc = -1, saw_end = 0, idle_guard = 0;
unsigned long steps = 0, calls = 0;
int mutating = 0;
char answer[KRANG_TEXT] = "", error[KRANG_ERR] = "";
char num[64], tok[32], cost[64];
int is_external = chat != NULL;
if (k == NULL || k->eng == NULL || prompt == NULL)
return -1;
if (sp_engine_submit(k->eng, prompt) != 0) {
klog_emit(&k->log, "submit_failed", "cause", cause, NULL);
if (chat != NULL)
kchat_complete(k, chat->id, "the engine refused the turn",
-1);
return -1;
}
pthread_mutex_lock(&k->lock);
k->st.impulses++;
if (is_external)
k->st.external_impulses++;
else
k->st.self_impulses++;
k->st.last_impulse_at = k_now();
snprintf(k->st.state, sizeof(k->st.state), "thinking");
copy_trunc(k->last_prompt, sizeof(k->last_prompt), prompt,
sizeof(k->last_prompt) - 1);
pthread_mutex_unlock(&k->lock);
klog_emit(&k->log, "impulse_start", "cause",
cause != NULL ? cause : "timer", "prompt", prompt, NULL);
for (;;) {
int got = 0;
while (sp_engine_poll(k->eng, &ev)) {
got = 1;
handle_event(k, &ev, &rc, &saw_end, &steps, &calls,
&mutating, answer, sizeof(answer), error,
sizeof(error));
sp_engine_event_free(&ev);
}
if (saw_end && !sp_engine_busy(k->eng))
break;
if (krang_stop || k->stop) {
k->stop = 1;
(void)sp_engine_cancel(k->eng);
}
if (!got) {
k_sleep_ms(10);
if (!sp_engine_busy(k->eng) && ++idle_guard > 200)
break;
}
}
(void)sp_engine_wait(k->eng);
kstate_sync(k);
session_refresh(k);
pthread_mutex_lock(&k->lock);
k->st.turns++;
k->st.last_turn_rc = rc;
if (answer[0] != '\0')
snprintf(k->st.last_outcome, sizeof(k->st.last_outcome), "%s",
answer);
else if (error[0] != '\0')
snprintf(k->st.last_outcome, sizeof(k->st.last_outcome),
"error: %s", error);
if (error[0] != '\0')
snprintf(k->st.last_error, sizeof(k->st.last_error), "%s",
error);
else if (rc != 0)
snprintf(k->st.last_error, sizeof(k->st.last_error),
"turn failed with %d", rc);
snprintf(k->last_outcome, sizeof(k->last_outcome), "%s",
k->st.last_outcome);
snprintf(k->last_error, sizeof(k->last_error), "%s",
k->st.last_error);
pthread_mutex_unlock(&k->lock);
if (rc != 0) {
k->turn_failures++;
if (k->turn_failures > 8)
k->turn_failures = 8;
} else {
k->turn_failures = 0;
}
kstuck_turn(&k->stuck, rc, calls, mutating);
if (answer[0] != '\0' && strstr(answer, "GOAL_COMPLETE") != NULL) {
struct sp_buf e;
sp_buf_init(&e);
if (sp_session_set_goal_state(k->session_dir, KRANG_SESSION_ID,
"succeeded", &e) == 0) {
pthread_mutex_lock(&k->lock);
snprintf(k->st.goal_state,
sizeof(k->st.goal_state), "succeeded");
k->st.goal_completes++;
pthread_mutex_unlock(&k->lock);
klog_emit(&k->log, "goal_complete", "goal",
k->st.goal, NULL);
}
sp_buf_free(&e);
}
pthread_mutex_lock(&k->lock);
snprintf(tok, sizeof(tok), "%lu", k->st.tokens_in);
snprintf(num, sizeof(num), "%d", rc);
snprintf(cost, sizeof(cost), "%.6f", k->st.cost);
pthread_mutex_unlock(&k->lock);
{
char sk[32], sc[32];
snprintf(sk, sizeof(sk), "%lu", steps);
snprintf(sc, sizeof(sc), "%lu", calls);
klog_emit(&k->log, "turn_end", "rc", num, "steps", sk,
"calls", sc, "tokens_in", tok, "cost", cost,
"answer", answer, "error", error, NULL);
}
record_impulse(k, cause, rc, steps, calls, answer);
if (chat != NULL) {
const char *out = rc == 0 ? answer : error;
kchat_complete(k, chat->id, out[0] != '\0' ? out :
"(the turn produced no answer)", rc);
}
return rc;
}
static void
schedule_next(struct krang *k, int failed)
{
long delay = k->cfg.impulse_seconds;
int i;
if (failed) {
for (i = 0; i < k->turn_failures && i < 4; i++)
delay *= 2;
if (delay > 3600)
delay = 3600;
}
k->next_at = k_now() + delay;
pthread_mutex_lock(&k->lock);
k->st.next_impulse_at = k->next_at;
if (!failed && k->stuck.level == 0)
snprintf(k->st.state, sizeof(k->st.state), "sleeping");
pthread_mutex_unlock(&k->lock);
}
static int
rate_limit(struct krang *k, long now)
{
if (now - k->hour_start >= 3600) {
k->hour_start = now;
k->hour_count = 0;
}
if (k->hour_count >= k->cfg.max_impulses_per_hour) {
k->next_at = k->hour_start + 3600;
pthread_mutex_lock(&k->lock);
k->st.next_impulse_at = k->next_at;
pthread_mutex_unlock(&k->lock);
klog_emit(&k->log, "rate_limited", "max",
"hourly impulse limit reached", NULL);
return 1;
}
return 0;
}
int
kdaemon_session_open(struct krang *k, int *newborn, char *goal,
size_t goalcap, char *err, size_t errlen)
{
struct sp_session_info si;
struct sp_buf eb;
size_t records = 0;
char gstate[16];
if (k == NULL || newborn == NULL || goal == NULL)
return -1;
if (k->session_dir[0] == '\0')
snprintf(k->session_dir, sizeof(k->session_dir), "%s",
KRANG_IN_SESSIONS);
sp_buf_init(&eb);
if (sp_session_open(&si, k->session_dir, KRANG_SESSION_ID, &eb) != 0) {
snprintf(err, errlen, "session: %s",
eb.p != NULL ? eb.p : "?");
sp_buf_free(&eb);
return -1;
}
sp_buf_clear(&eb);
(void)sp_session_count(&si, &records, &eb);
sp_buf_free(&eb);
*newborn = records == 0;
if (*newborn) {
if (k->cfg.goal[0] == '\0') {
snprintf(err, errlen,
"refusing to birth a session without a goal");
return -1;
}
sp_buf_init(&eb);
if (sp_session_set_goal(k->session_dir, KRANG_SESSION_ID,
k->cfg.goal, &eb) != 0) {
snprintf(err, errlen, "goal: %s",
eb.p != NULL ? eb.p : "?");
sp_buf_free(&eb);
return -1;
}
sp_buf_free(&eb);
snprintf(goal, goalcap, "%s", k->cfg.goal);
snprintf(gstate, sizeof(gstate), "open");
} else {
(void)sp_session_get_goal(k->session_dir, KRANG_SESSION_ID,
goal, goalcap);
(void)sp_session_get_goal_state(k->session_dir, KRANG_SESSION_ID,
gstate, sizeof(gstate));
if (goal[0] == '\0' && k->cfg.goal[0] != '\0') {
snprintf(goal, goalcap, "%s", k->cfg.goal);
(void)sp_session_set_goal(k->session_dir,
KRANG_SESSION_ID, goal, NULL);
}
if (k->cfg.goal[0] != '\0' &&
strcmp(goal, k->cfg.goal) != 0)
klog_emit(&k->log, "config_goal_ignored",
"session_goal", goal, "config_goal",
k->cfg.goal, NULL);
}
pthread_mutex_lock(&k->lock);
snprintf(k->st.goal, sizeof(k->st.goal), "%s", goal);
snprintf(k->st.goal_state, sizeof(k->st.goal_state), "%s",
gstate[0] != '\0' ? gstate : "open");
k->st.started_at = k_now();
k->st.born_at = ksession_born(k);
if (k->st.born_at == 0)
k->st.born_at = k->st.started_at;
snprintf(k->st.state, sizeof(k->st.state),
*newborn ? "newborn" : "sleeping");
k->hour_start = k_now();
k->hour_count = 0;
pthread_mutex_unlock(&k->lock);
return 0;
}
int
kdaemon_run(struct krang *k)
{
int newborn = 0;
char goal[KRANG_GOAL];
if (k == NULL)
return 1;
if (k->cfg.endpoint[0] == '\0' || k->cfg.model[0] == '\0') {
fprintf(stderr, "krang: endpoint and model are required\n");
return 1;
}
if (k->session_dir[0] == '\0')
snprintf(k->session_dir, sizeof(k->session_dir), "%s",
KRANG_IN_SESSIONS);
{
struct sp_buf sp;
sp_buf_init(&sp);
k_system_prompt(k, &sp);
snprintf(k->system_prompt, sizeof(k->system_prompt), "%s",
sp.p != NULL ? sp.p : "");
sp_buf_free(&sp);
}
if (kdaemon_session_open(k, &newborn, goal, sizeof(goal),
k->last_error, sizeof(k->last_error)) != 0) {
fprintf(stderr, "krang: %s\n", k->last_error);
return 1;
}
if (kengine_open(k, k->script[0] != '\0' ? k->script : NULL,
k->last_error, sizeof(k->last_error)) != 0) {
fprintf(stderr, "krang: %s\n", k->last_error);
return 1;
}
if (k->cfg.api_key_env[0] != '\0') {
const char *secret = getenv(k->cfg.api_key_env);
(void)sp_secret_env_add(k->cfg.api_key_env);
if (secret != NULL && *secret != '\0')
klog_set_secret(&k->log, secret);
}
session_refresh(k);
if (khttp_start(k, k->last_error, sizeof(k->last_error)) != 0) {
fprintf(stderr, "krang: dashboard: %s\n", k->last_error);
kengine_close(k);
return 1;
}
if (kmcp_start(k, k->last_error, sizeof(k->last_error)) != 0) {
fprintf(stderr, "krang: mcp: %s\n", k->last_error);
khttp_stop(k);
kengine_close(k);
return 1;
}
klog_emit(&k->log, "start", "newborn", newborn ? "1" : "0",
"session", KRANG_SESSION_ID, "goal", goal, NULL);
if (newborn) {
struct sp_buf birth;
sp_buf_init(&birth);
k_birth_prompt(&k->cfg, &birth);
klog_emit(&k->log, "birth", "goal", goal, NULL);
(void)krun_turn(k, birth.p != NULL ? birth.p : "You are awake.",
"birth", NULL);
sp_buf_free(&birth);
schedule_next(k, k->turn_failures > 0);
} else {
k->next_at = k_now(); /* a restart continues at once */
pthread_mutex_lock(&k->lock);
k->st.next_impulse_at = k->next_at;
pthread_mutex_unlock(&k->lock);
}
while (!krang_stop && !k->stop) {
struct kchat *chat;
long now = k_now();
pthread_mutex_lock(&k->lock);
if (k->max_impulses > 0 &&
k->st.impulses >= k->max_impulses) {
k->stop = 1;
pthread_mutex_unlock(&k->lock);
break;
}
pthread_mutex_unlock(&k->lock);
kstate_sync(k);
chat = kchat_take(k);
if (chat != NULL) {
set_state(k, "thinking");
(void)krun_turn(k, chat->text, "chat", chat);
schedule_next(k, 0);
continue;
}
if (k->cfg.max_cost > 0 && k->st.cost >= k->cfg.max_cost) {
set_state(k, "blocked");
if (now >= k->next_at) {
klog_emit(&k->log, "cost_limit", "cost",
"cost limit reached; self-impulses paused",
NULL);
k->next_at = now + 3600;
pthread_mutex_lock(&k->lock);
k->st.next_impulse_at = k->next_at;
pthread_mutex_unlock(&k->lock);
}
} else if (now >= k->next_at) {
struct sp_buf prompt;
int level;
if (rate_limit(k, now))
continue;
level = kstuck_should_check(&k->stuck, now);
sp_buf_init(&prompt);
if (level >= 1) {
k_selfcheck_prompt(k, &prompt);
k->hour_count++;
(void)krun_turn(k,
prompt.p != NULL ? prompt.p : "continue",
"self-check", NULL);
pthread_mutex_lock(&k->lock);
k->st.stuck_events++;
pthread_mutex_unlock(&k->lock);
} else {
k_impulse_prompt(k, "timer", &prompt);
k->hour_count++;
(void)krun_turn(k,
prompt.p != NULL ? prompt.p : "continue",
"timer", NULL);
}
sp_buf_free(&prompt);
if (kstuck_level(&k->stuck) >= 3) {
pthread_mutex_lock(&k->lock);
k->st.blocked_events++;
snprintf(k->st.state, sizeof(k->st.state),
"blocked");
pthread_mutex_unlock(&k->lock);
klog_emit(&k->log, "blocked", "reason",
"the same approach keeps failing", NULL);
k->next_at = now + 3600;
} else {
schedule_next(k, k->turn_failures > 0);
}
continue;
}
pthread_mutex_lock(&k->lock);
if (!krang_stop && !k->stop) {
struct timespec ts;
ts.tv_sec = now + 1;
ts.tv_nsec = 0;
(void)pthread_cond_timedwait(&k->cond, &k->lock, &ts);
}
pthread_mutex_unlock(&k->lock);
}
klog_emit(&k->log, "stop", "reason",
krang_stop ? "signal" : "requested", NULL);
khttp_stop(k);
kmcp_stop(k);
kengine_close(k);
klog_close(&k->log);
return 0;
}
+1320
View File
File diff suppressed because it is too large. Load diff
+121
View File
@@ -0,0 +1,121 @@
/*
* krang -- reading back the full journal.
*
* Copyright (c) 2026 Konrad Lother
* License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree.
*
* Compaction shrinks the working conversation; it does not shrink the session
* log. This read-only tool lets the model look up what the working set dropped:
* the whole one-session journal, searched case-insensitively.
*/
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "krang.h"
#include "mcp.h"
static const char *
ci_strstr(const char *hay, const char *needle)
{
size_t n = strlen(needle);
const char *p;
if (n == 0)
return hay;
for (p = hay; *p != '\0'; p++) {
size_t i;
for (i = 0; i < n; i++) {
if (p[i] == '\0' ||
tolower((unsigned char)p[i]) !=
tolower((unsigned char)needle[i]))
break;
}
if (i == n)
return p;
}
return NULL;
}
static int
journal_run(const char *args_json, struct sp_buf *out, void *ctx)
{
struct krang *k = ctx;
mcp_json *v;
const char *query;
int limit = 10, hits = 0;
char path[640], *line = NULL;
size_t cap = 0;
FILE *f;
if (k == NULL || out == NULL)
return -1;
v = args_json != NULL ? mcp_parse(args_json) : NULL;
if (v == NULL)
return sp_buf_puts(out, "error: arguments must be a JSON object");
query = mcp_arg_string(v, "query");
limit = mcp_arg_int(v, "limit", 10);
if (query == NULL || *query == '\0') {
mcp_json_free(v);
return sp_buf_puts(out, "error: 'query' is required");
}
if (limit < 1 || limit > 50)
limit = 10;
snprintf(path, sizeof(path), "%s/%s.jsonl", k->session_dir,
KRANG_SESSION_ID);
f = fopen(path, "r");
if (f == NULL) {
mcp_json_free(v);
return sp_buf_printf(out, "error: cannot read %s", path);
}
while (getline(&line, &cap, f) > 0 && hits < limit) {
char *p = line;
size_t n;
k_trim(p);
if (*p != '{' || ci_strstr(p, query) == NULL)
continue;
hits++;
n = strlen(p);
if (n > 2000)
n = 2000;
(void)sp_buf_printf(out, "%d: ", hits);
(void)sp_buf_add(out, p, n);
if (n < strlen(p))
(void)sp_buf_puts(out, " ...");
(void)sp_buf_puts(out, "\n");
}
free(line);
fclose(f);
mcp_json_free(v);
if (hits == 0)
(void)sp_buf_printf(out, "no match for '%s' in the journal",
query);
else
(void)sp_buf_printf(out, "[%d match(es); the journal has the "
"full history]", hits);
return 0;
}
int
kjournal_register(struct krang *k)
{
struct sp_tool t;
if (k == NULL || k->eng == NULL)
return -1;
memset(&t, 0, sizeof(t));
t.name = "journal_search";
t.description = "Search the full journal (the one session log), "
"including the history compaction dropped. Read-only.";
t.params = "{\"type\":\"object\",\"properties\":{"
"\"query\":{\"type\":\"string\"},"
"\"limit\":{\"type\":\"integer\"}},"
"\"required\":[\"query\"]}";
t.auth = SP_AUTH_READ;
t.run = journal_run;
t.ctx = k;
return sp_registry_add(sp_engine_registry(k->eng), &t);
}
+379
View File
@@ -0,0 +1,379 @@
/*
* krang -- an autonomous daemon that lives in a chroot.
*
* Copyright (c) 2026 Konrad Lother
* License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree.
*/
#ifndef KRANG_H
#define KRANG_H
#include <pthread.h>
#include <stddef.h>
#include <signal.h>
#include <sys/types.h>
#include <time.h>
#include "splinter.h"
#include "splinter_engine.h"
#include "config.h"
extern volatile sig_atomic_t krang_stop;
#define KRANG_VERSION "0.1.0"
#define KRANG_SESSION_ID "krang"
#define KRANG_PATH 512
#define KRANG_GOAL 2048
#define KRANG_TEXT 8192
#define KRANG_ERR 1024
#define KRANG_IMPULSE_RING 64
#define KRANG_EVENT_RING 256
#define KRANG_CHAT_SLOTS 32
/*
* Where the world is, once chrooted. The host paths in the config are
* bind-mounted onto these fixed paths; code after the drop only knows these.
*/
#define KRANG_IN_STATE "/var/lib/krang/state"
#define KRANG_IN_SESSIONS KRANG_IN_STATE "/sessions"
#define KRANG_IN_EVENTS KRANG_IN_STATE "/events.jsonl"
#define KRANG_IN_WORKSPACE "/var/lib/krang/workspace"
#define KRANG_IN_THREADS KRANG_IN_WORKSPACE "/THREADS.md"
#define KRANG_IN_SKILLS KRANG_IN_WORKSPACE "/skills"
#define KRANG_IN_SELF KRANG_IN_WORKSPACE "/self"
#define KRANG_IN_TMP KRANG_IN_WORKSPACE "/tmp"
/* ---------------------------------------------------------------- config */
struct kconfig {
char path[KRANG_PATH];
char goal[KRANG_GOAL];
char endpoint[512];
char model[256];
char api_key_env[64];
char kind[16]; /* "" (openai) or "anthropic" */
size_t ctx;
char state_dir[KRANG_PATH]; /* host path to bind onto /var/lib/krang/state */
char workspace[KRANG_PATH]; /* host path to bind onto /var/lib/krang/workspace */
char rootfs[KRANG_PATH];
char rootfs_suite[64];
char rootfs_mirror[512];
char sandbox_user[64];
uid_t sandbox_uid;
gid_t sandbox_gid;
char plugin[8][KRANG_PATH];
size_t nplugins;
int impulse_seconds; /* between self-initiated impulses */
size_t max_steps; /* tool rounds per turn */
size_t max_bytes; /* request budget, 0 = engine default */
size_t compact_threshold;
size_t compact_target;
int max_impulses_per_hour;
double max_cost; /* USD, 0 = off */
char dashboard_host[64];
int dashboard_port;
char mcp_host[64];
int mcp_port;
char token[256];
int say_timeout; /* seconds an external say waits */
int require_landlock; /* Linux: refuse without path confinement */
int seccomp; /* Linux: apply the syscall filter */
int prepare_if_missing; /* run debootstrap when the rootfs is absent */
int no_sandbox; /* CLI only; requires KRANG_ALLOW_UNSANDBOXED */
};
/* ----------------------------------------------------------------- host */
struct khost {
char id[64];
char version[128];
char codename[64];
char arch[32];
char suite[64];
char mirror[512];
char method[64];
int supported;
};
/* ---------------------------------------------------------------- stats */
struct kstats {
char state[32]; /* sleeping, thinking, stuck, blocked */
long started_at;
long born_at;
long last_impulse_at;
long next_impulse_at;
unsigned long impulses;
unsigned long self_impulses;
unsigned long external_impulses;
unsigned long turns;
unsigned long steps;
unsigned long tool_calls;
unsigned long tool_failures;
unsigned long denials;
unsigned long tokens_in;
unsigned long tokens_out;
unsigned long tokens_cached;
double cost;
size_t ctx_used;
size_t ctx_max;
unsigned long compactions;
unsigned long chat_in;
unsigned long chat_out;
unsigned long chat_pending;
unsigned long stuck_events;
unsigned long blocked_events;
unsigned long goal_completes;
unsigned long self_edits;
int busy;
int waiting;
char model[256];
char agent[48];
char session[64];
char last_error[KRANG_ERR];
char last_outcome[KRANG_GOAL];
char goal[KRANG_GOAL];
char goal_state[16]; /* open, succeeded */
char last_tool[64];
char last_tool_result[512];
int last_turn_rc;
unsigned long session_records;
unsigned long long session_bytes;
char rootfs_id[KRANG_PATH];
char sandbox_uid[32];
char sandbox_gid[32];
char landlock[32];
char seccomp[32];
char host_id[64];
char host_version[128];
char host_arch[32];
};
/* ------------------------------------------------------------- impulses */
struct kimpulse {
unsigned long id;
long at;
char cause[32]; /* birth, timer, chat, self-check, retry */
int rc;
unsigned long steps;
unsigned long tool_calls;
unsigned long tokens_in;
unsigned long tokens_out;
double cost;
char answer[512]; /* truncated, for the dashboard */
};
/* ------------------------------------------------------------------- log */
struct kentry {
unsigned long seq;
long ts;
char *json;
};
struct klog {
int fd; /* root-owned, opened before the drop */
pthread_mutex_t lock;
unsigned long seq;
unsigned long long bytes;
char secret[512]; /* redacted from every value */
struct kentry ring[KRANG_EVENT_RING];
size_t head; /* next slot */
size_t count;
};
/* ------------------------------------------------------------------ chat */
struct kchat {
unsigned long id;
char *text;
char *answer;
int state; /* 0 free, 1 pending, 2 running, 3 done */
int rc;
long created;
};
/* ----------------------------------------------------------------- stuck */
struct kstuck {
int consecutive_failures;
int repeated_calls;
int no_progress_turns;
int same_error;
int level; /* 0 none, 1 reflect, 2 change, 3 blocked */
int attempts;
long last_check;
char last_call[512];
char last_error[KRANG_ERR];
};
/* ------------------------------------------------------------------ main */
struct krang {
struct kconfig cfg;
struct sp_config sconf;
struct sp_agent_config base;
struct sp_engine *eng;
struct sp_buf err;
int engine_open;
pthread_mutex_t lock;
pthread_cond_t cond;
int stop;
struct kstats st;
struct kimpulse impulses[KRANG_IMPULSE_RING];
unsigned long impulse_seq;
struct klog log;
struct kchat chats[KRANG_CHAT_SLOTS];
unsigned long chat_seq;
struct kstuck stuck;
struct khost host;
time_t next_at;
long hour_start;
int hour_count;
int turn_failures;
char session_dir[KRANG_PATH];
char script[KRANG_PATH]; /* test/one-shot script */
size_t max_impulses; /* 0: run forever */
char last_prompt[KRANG_TEXT];
char last_error[KRANG_ERR];
char last_outcome[KRANG_GOAL];
char system_prompt[4096];
int http_fd;
int mcp_fd;
pthread_t http_tid;
pthread_t mcp_tid;
int http_running;
int mcp_running;
char rootfs_marker[KRANG_PATH];
char plugin_inside[8][KRANG_PATH];
char landlock_state[32];
char seccomp_state[32];
};
/* ------------------------------------------------------------------ util */
long k_now(void);
void k_sleep_ms(int ms);
void k_trim(char *s);
int k_starts_with(const char *s, const char *p);
char *k_strdup(const char *s);
void k_json_escape(struct sp_buf *b, const char *s);
void k_redact(struct sp_buf *out, const char *text, const char *secret);
int k_write_all(int fd, const void *buf, size_t len);
void k_format_time(long t, char *buf, size_t cap);
int k_parse_bool(const char *s, int dflt);
/* ---------------------------------------------------------------- config */
void kconfig_defaults(struct kconfig *c);
int kconfig_load(struct kconfig *c, const char *path, char *err,
size_t errlen);
void kconfig_json(const struct kconfig *c, struct sp_buf *out, int redact);
/* ------------------------------------------------------------------- log */
int klog_open(struct klog *l, const char *path, char *err, size_t errlen);
void klog_close(struct klog *l);
void klog_set_secret(struct klog *l, const char *secret);
void klog_emit(struct klog *l, const char *kind, ...);
void klog_json(struct klog *l, struct sp_buf *out, size_t max);
void klog_entry_json(const struct kentry *e, struct sp_buf *out);
/* --------------------------------------------------------------- session */
int ksession_meta(struct krang *k, size_t *records,
unsigned long long *bytes, char *goal, size_t goalcap,
char *gstate, size_t gstatecap);
int ksession_history(struct krang *k, struct sp_buf *out, size_t limit);
long ksession_born(struct krang *k);
/* --------------------------------------------------------------- prompts */
void k_birth_prompt(const struct kconfig *c, struct sp_buf *out);
void k_impulse_prompt(struct krang *k, const char *cause, struct sp_buf *out);
void k_selfcheck_prompt(struct krang *k, struct sp_buf *out);
void k_system_prompt(struct krang *k, struct sp_buf *out);
/* ----------------------------------------------------------------- stuck */
void kstuck_result(struct kstuck *s, const char *tool, const char *obs,
int is_error);
void kstuck_call(struct kstuck *s, const char *tool, const char *args);
void kstuck_turn(struct kstuck *s, int rc, unsigned long calls,
int mutating);
int kstuck_level(const struct kstuck *s);
void kstuck_reset(struct kstuck *s);
int kstuck_should_check(struct kstuck *s, long now);
/* ------------------------------------------------------------------ chat */
int kchat_enqueue(struct krang *k, const char *text, unsigned long *id);
struct kchat *kchat_take(struct krang *k);
void kchat_complete(struct krang *k, unsigned long id, const char *answer,
int rc);
int kchat_wait(struct krang *k, unsigned long id, struct sp_buf *out,
int timeout_s);
int kchat_status(struct krang *k, unsigned long id, struct sp_buf *out);
/* ----------------------------------------------------------------- state */
void kstate_sync(struct krang *k);
void kstate_json(struct krang *k, struct sp_buf *out);
void kstate_impulses_json(struct krang *k, struct sp_buf *out, size_t max);
void kstate_tools_json(struct krang *k, struct sp_buf *out);
void kstate_sandbox_json(struct krang *k, struct sp_buf *out);
/* ---------------------------------------------------------------- daemon */
int kdaemon_run(struct krang *k);
int kdaemon_session_open(struct krang *k, int *newborn, char *goal,
size_t goalcap, char *err, size_t errlen);
int kengine_open(struct krang *k, const char *script, char *err,
size_t errlen);
void kengine_close(struct krang *k);
int kjournal_register(struct krang *k);
int krun_turn(struct krang *k, const char *prompt, const char *cause,
struct kchat *chat);
/* --------------------------------------------------------------- sandbox */
int khost_detect(struct khost *h, char *err, size_t errlen);
int krootfs_prepare(struct krang *k, char *err, size_t errlen);
int ksandbox_enter(struct krang *k, char *err, size_t errlen);
void ksandbox_plan(struct krang *k, struct sp_buf *out);
int ksandbox_apply_landlock(const char *workspace, const char *state,
const char *tmp, int required, char *err, size_t errlen);
int ksandbox_apply_seccomp(int required, char *err, size_t errlen);
/* ------------------------------------------------------------------ http */
int khttp_start(struct krang *k, char *err, size_t errlen);
void khttp_stop(struct krang *k);
int kmcp_start(struct krang *k, char *err, size_t errlen);
void kmcp_stop(struct krang *k);
/* test hooks: handle one request without a socket thread */
void khttp_handle_buffer(struct krang *k, const char *request,
struct sp_buf *response);
void kmcp_prepare(struct krang *k);
char *kmcp_handle(struct krang *k, const char *line);
#endif /* KRANG_H */
+281
View File
@@ -0,0 +1,281 @@
/*
* krang -- the experiment log.
*
* Copyright (c) 2026 Konrad Lother
* License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree.
*
* The file is opened by the root phase before the uid drop and is root-owned
* and 0600. The daemon keeps the descriptor for the rest of its life; the
* model can neither open nor truncate it. FD_CLOEXEC keeps it out of every
* child the run tool starts. The in-memory ring is what the dashboard reads.
*/
#include <errno.h>
#include <fcntl.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include "krang.h"
#define KRANG_LOG_TAIL_LOAD (512 * 1024)
static void
ring_add(struct klog *l, unsigned long seq, long ts, char *json)
{
struct kentry *e = &l->ring[l->head];
free(e->json);
e->seq = seq;
e->ts = ts;
e->json = json;
l->head = (l->head + 1) % KRANG_EVENT_RING;
if (l->count < KRANG_EVENT_RING)
l->count++;
}
static unsigned long
seq_from_line(const char *line)
{
const char *p = strstr(line, "\"seq\":");
char *end = NULL;
unsigned long v;
if (p == NULL)
return 0;
p += 6;
v = strtoul(p, &end, 10);
if (end == p)
return 0;
return v;
}
static long
ts_from_line(const char *line)
{
const char *p = strstr(line, "\"ts\":");
char *end = NULL;
long v;
if (p == NULL)
return 0;
p += 5;
v = strtol(p, &end, 10);
if (end == p)
return 0;
return v;
}
static void
load_tail(struct klog *l, off_t size)
{
char *buf;
off_t start;
size_t want, got = 0;
ssize_t n;
char *line, *nl;
if (size <= 0)
return;
want = (size_t)(size > KRANG_LOG_TAIL_LOAD ? KRANG_LOG_TAIL_LOAD : size);
start = size - (off_t)want;
buf = malloc(want + 1);
if (buf == NULL)
return;
while (got < want) {
n = pread(l->fd, buf + got, want - got, start + (off_t)got);
if (n < 0 && errno == EINTR)
continue;
if (n <= 0)
break;
got += (size_t)n;
}
buf[got] = '\0';
line = buf;
if (start > 0) {
nl = strchr(line, '\n');
if (nl == NULL) {
free(buf);
return;
}
line = nl + 1;
}
while ((nl = strchr(line, '\n')) != NULL) {
unsigned long seq;
long ts;
char *copy;
*nl = '\0';
if (*line == '{') {
seq = seq_from_line(line);
ts = ts_from_line(line);
copy = k_strdup(line);
if (copy != NULL)
ring_add(l, seq, ts, copy);
if (seq > l->seq)
l->seq = seq;
}
line = nl + 1;
}
free(buf);
}
int
klog_open(struct klog *l, const char *path, char *err, size_t errlen)
{
struct stat st;
if (l == NULL || path == NULL)
return -1;
memset(l, 0, sizeof(*l));
l->fd = -1;
pthread_mutex_init(&l->lock, NULL);
l->fd = open(path, O_RDWR | O_CREAT | O_APPEND, 0600);
if (l->fd < 0) {
snprintf(err, errlen, "cannot open event log %s: %s", path,
strerror(errno));
return -1;
}
(void)fchmod(l->fd, 0600);
(void)fcntl(l->fd, F_SETFD, FD_CLOEXEC);
if (fstat(l->fd, &st) == 0) {
l->bytes = (unsigned long long)st.st_size;
load_tail(l, st.st_size);
}
return 0;
}
void
klog_close(struct klog *l)
{
size_t i;
if (l == NULL)
return;
pthread_mutex_lock(&l->lock);
if (l->fd >= 0) {
close(l->fd);
l->fd = -1;
}
for (i = 0; i < KRANG_EVENT_RING; i++) {
free(l->ring[i].json);
l->ring[i].json = NULL;
}
l->count = 0;
pthread_mutex_unlock(&l->lock);
pthread_mutex_destroy(&l->lock);
}
void
klog_set_secret(struct klog *l, const char *secret)
{
if (l == NULL)
return;
pthread_mutex_lock(&l->lock);
snprintf(l->secret, sizeof(l->secret), "%s",
secret != NULL ? secret : "");
pthread_mutex_unlock(&l->lock);
}
void
klog_emit(struct klog *l, const char *kind, ...)
{
struct sp_buf line;
va_list ap;
const char *key;
char now[64];
unsigned long seq;
long ts;
if (l == NULL || kind == NULL)
return;
if (sp_buf_init(&line) != 0)
return;
ts = k_now();
k_format_time(ts, now, sizeof(now));
pthread_mutex_lock(&l->lock);
seq = ++l->seq;
(void)sp_buf_printf(&line,
"{\"seq\":%lu,\"ts\":%ld,\"time\":\"%s\",\"kind\":\"",
seq, ts, now);
k_json_escape(&line, kind);
(void)sp_buf_puts(&line, "\"");
va_start(ap, kind);
while ((key = va_arg(ap, const char *)) != NULL) {
const char *val = va_arg(ap, const char *);
struct sp_buf clean;
(void)sp_buf_puts(&line, ",\"");
k_json_escape(&line, key);
(void)sp_buf_puts(&line, "\":\"");
if (l->secret[0] != '\0' && val != NULL) {
if (sp_buf_init(&clean) == 0) {
k_redact(&clean, val, l->secret);
k_json_escape(&line,
clean.p != NULL ? clean.p : "");
sp_buf_free(&clean);
} else {
k_json_escape(&line, val);
}
} else {
k_json_escape(&line, val != NULL ? val : "");
}
(void)sp_buf_puts(&line, "\"");
}
va_end(ap);
(void)sp_buf_puts(&line, "}");
if (l->fd >= 0) {
if (k_write_all(l->fd, line.p, line.len) == 0 &&
k_write_all(l->fd, "\n", 1) == 0)
l->bytes += line.len + 1;
}
{
char *copy = k_strdup(line.p != NULL ? line.p : "");
if (copy != NULL)
ring_add(l, seq, ts, copy);
}
pthread_mutex_unlock(&l->lock);
sp_buf_free(&line);
}
void
klog_entry_json(const struct kentry *e, struct sp_buf *out)
{
if (e == NULL || e->json == NULL || out == NULL)
return;
(void)sp_buf_puts(out, e->json);
}
void
klog_json(struct klog *l, struct sp_buf *out, size_t max)
{
size_t i, start, n;
unsigned long seq;
if (l == NULL || out == NULL)
return;
pthread_mutex_lock(&l->lock);
n = l->count;
if (max > 0 && n > max)
n = max;
start = (l->head + KRANG_EVENT_RING - n) % KRANG_EVENT_RING;
(void)sp_buf_puts(out, "[");
for (i = 0; i < n; i++) {
const struct kentry *e =
&l->ring[(start + i) % KRANG_EVENT_RING];
if (i > 0)
(void)sp_buf_puts(out, ",");
if (e->json != NULL)
(void)sp_buf_puts(out, e->json);
else
(void)sp_buf_puts(out, "{}");
}
(void)sp_buf_puts(out, "]");
seq = l->seq;
pthread_mutex_unlock(&l->lock);
(void)seq;
}
+297
View File
@@ -0,0 +1,297 @@
/*
* krang -- launcher.
*
* Copyright (c) 2026 Konrad Lother
* License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree.
*
* It starts as root, builds the world, drops the privileges, and becomes the
* daemon. The only commands that do not enter the sandbox are --plan,
* --prepare-rootfs and --check/--self-test, which are setup and verification.
*/
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include "krang.h"
#define DEFAULT_CONFIG "/etc/krang/krang.conf"
static void
on_signal(int sig)
{
(void)sig;
krang_stop = 1;
}
static void
usage(FILE *out)
{
fprintf(out,
"krang %s -- an autonomous daemon in a chroot\n"
"\n"
" krang [--config PATH] start the daemon (as root)\n"
" krang --plan [--config PATH] print the sandbox plan, do not start\n"
" krang --prepare-rootfs debootstrap the rootfs (as root)\n"
" krang --check offline check: config, plan, script turn\n"
" krang --self-test one scripted turn, no network, no model\n"
" krang --sandbox-test root-only: enter the sandbox, one scripted\n"
" turn (id -u, mount denial), then exit\n"
" krang --version version\n"
" krang --help this text\n"
"\n"
" --no-sandbox development only; needs\n"
" KRANG_ALLOW_UNSANDBOXED=1\n"
"\n"
"The daemon never asks a user for anything. It answers on the dashboard\n"
"and the MCP port; see krang.conf.example.\n",
KRANG_VERSION);
}
static int
self_test(const char *config_path)
{
struct krang k;
char tmpl[512], *dir, script[600], logpath[700], answer[KRANG_GOAL];
FILE *f;
int rc = 1;
memset(&k, 0, sizeof(k));
k.log.fd = -1;
pthread_mutex_init(&k.lock, NULL);
pthread_cond_init(&k.cond, NULL);
sp_buf_init(&k.err);
kconfig_defaults(&k.cfg);
if (config_path != NULL)
(void)kconfig_load(&k.cfg, config_path, k.last_error,
sizeof(k.last_error));
snprintf(tmpl, sizeof(tmpl), "/tmp/krang-selftest-XXXXXX");
dir = mkdtemp(tmpl);
if (dir == NULL) {
perror("mkdtemp");
goto out;
}
snprintf(k.session_dir, sizeof(k.session_dir), "%s/sessions", dir);
snprintf(logpath, sizeof(logpath), "%s/events.jsonl", dir);
(void)mkdir(k.session_dir, 0700);
(void)mkdir(k.cfg.workspace, 0700);
if (klog_open(&k.log, logpath, k.last_error,
sizeof(k.last_error)) != 0) {
fprintf(stderr, "krang: %s\n", k.last_error);
goto out;
}
snprintf(script, sizeof(script), "%s/script.txt", dir);
f = fopen(script, "w");
if (f == NULL) {
perror("script");
goto out;
}
fprintf(f, "tool echo {\"text\":\"krang-selftest\"}\n");
fprintf(f, "answer krang-selftest-ok\n");
fclose(f);
snprintf(k.cfg.endpoint, sizeof(k.cfg.endpoint),
"http://127.0.0.1:1/v1");
snprintf(k.cfg.model, sizeof(k.cfg.model), "selftest");
snprintf(k.cfg.goal, sizeof(k.cfg.goal), "prove the apparatus");
sp_buf_init(&k.err);
{
struct sp_buf sp;
sp_buf_init(&sp);
k_system_prompt(&k, &sp);
snprintf(k.system_prompt, sizeof(k.system_prompt), "%s",
sp.p != NULL ? sp.p : "");
sp_buf_free(&sp);
}
if (kengine_open(&k, script, k.last_error,
sizeof(k.last_error)) != 0) {
fprintf(stderr, "krang: %s\n", k.last_error);
goto out;
}
(void)krun_turn(&k, "prove the apparatus", "self-test", NULL);
snprintf(answer, sizeof(answer), "%s", k.last_outcome);
if (strstr(answer, "krang-selftest-ok") != NULL) {
printf("krang self-test: ok\n");
rc = 0;
} else {
fprintf(stderr, "krang self-test: unexpected answer: %s\n",
answer);
}
out:
if (k.eng != NULL)
kengine_close(&k);
if (k.log.fd >= 0)
klog_close(&k.log);
pthread_mutex_destroy(&k.lock);
pthread_cond_destroy(&k.cond);
sp_buf_free(&k.err);
return rc;
}
static int
sandbox_test(struct krang *k)
{
struct sp_buf sp;
char path[800];
FILE *f;
int rc;
if (geteuid() != 0) {
fprintf(stderr,
"krang: --sandbox-test must start as root; it drops itself\n");
return 1;
}
snprintf(path, sizeof(path), "%s/sandbox-script.txt",
k->cfg.state_dir);
f = fopen(path, "w");
if (f == NULL) {
fprintf(stderr, "krang: cannot write %s: %s\n", path,
strerror(errno));
return 1;
}
fprintf(f, "tool clock {}\n");
fprintf(f, "tool run {\"command\":\"id -u\"}\n");
fprintf(f,
"tool run {\"command\":\"mount -t tmpfs none /tmp 2>&1 || "
"echo mount-denied\"}\n");
fprintf(f, "answer sandbox-test-ok\n");
fclose(f);
(void)chmod(path, 0644);
if (ksandbox_enter(k, k->last_error, sizeof(k->last_error)) != 0) {
fprintf(stderr, "krang: %s\n", k->last_error);
return 1;
}
snprintf(k->session_dir, sizeof(k->session_dir), "%s",
KRANG_IN_SESSIONS);
sp_buf_init(&sp);
k_system_prompt(k, &sp);
snprintf(k->system_prompt, sizeof(k->system_prompt), "%s",
sp.p != NULL ? sp.p : "");
sp_buf_free(&sp);
if (kengine_open(k, KRANG_IN_STATE "/sandbox-script.txt",
k->last_error, sizeof(k->last_error)) != 0) {
fprintf(stderr, "krang: %s\n", k->last_error);
return 1;
}
rc = krun_turn(k, "sandbox integration test", "sandbox-test", NULL);
printf("sandbox-test outcome: %s\n", k->st.last_outcome);
printf("sandbox-test last tool result: %s\n",
k->st.last_tool_result);
kengine_close(k);
klog_close(&k->log);
if (rc != 0 || strstr(k->st.last_outcome, "sandbox-test-ok") == NULL) {
fprintf(stderr, "krang: sandbox-test failed\n");
return 1;
}
printf("sandbox-test: ok\n");
return 0;
}
int
main(int argc, char **argv)
{
const char *config_path = DEFAULT_CONFIG;
int do_plan = 0, do_prepare = 0, do_check = 0, do_self = 0;
int do_sandbox = 0;
int i;
struct krang k;
struct sigaction sa;
for (i = 1; i < argc; i++) {
if (!strcmp(argv[i], "--help") || !strcmp(argv[i], "-h")) {
usage(stdout);
return 0;
} else if (!strcmp(argv[i], "--version") ||
!strcmp(argv[i], "-V")) {
printf("krang %s\n", KRANG_VERSION);
return 0;
} else if (!strcmp(argv[i], "--plan")) {
do_plan = 1;
} else if (!strcmp(argv[i], "--prepare-rootfs")) {
do_prepare = 1;
} else if (!strcmp(argv[i], "--check")) {
do_check = 1;
} else if (!strcmp(argv[i], "--self-test")) {
do_self = 1;
} else if (!strcmp(argv[i], "--sandbox-test")) {
do_sandbox = 1;
} else if (!strcmp(argv[i], "--no-sandbox")) {
/* recorded after the config is loaded */
} else if (!strcmp(argv[i], "--config")) {
if (++i >= argc) {
fprintf(stderr, "krang: --config needs a path\n");
return 1;
}
config_path = argv[i];
} else {
fprintf(stderr, "krang: unknown argument %s\n", argv[i]);
usage(stderr);
return 1;
}
}
if (do_self || do_check)
return self_test(config_path) == 0 ? 0 : 1;
memset(&k, 0, sizeof(k));
k.log.fd = -1;
pthread_mutex_init(&k.lock, NULL);
pthread_cond_init(&k.cond, NULL);
if (sp_buf_init(&k.err) != 0)
return 1;
if (kconfig_load(&k.cfg, config_path, k.last_error,
sizeof(k.last_error)) != 0) {
fprintf(stderr, "krang: %s\n", k.last_error);
return 1;
}
for (i = 1; i < argc; i++)
if (!strcmp(argv[i], "--no-sandbox"))
k.cfg.no_sandbox = 1;
if (do_plan) {
struct sp_buf out;
sp_buf_init(&out);
ksandbox_plan(&k, &out);
fputs(out.p != NULL ? out.p : "", stdout);
sp_buf_free(&out);
return 0;
}
if (do_prepare) {
if (krootfs_prepare(&k, k.last_error,
sizeof(k.last_error)) != 0) {
fprintf(stderr, "krang: %s\n", k.last_error);
return 1;
}
return 0;
}
if (do_sandbox)
return sandbox_test(&k);
if (k.cfg.endpoint[0] == '\0' || k.cfg.model[0] == '\0') {
fprintf(stderr,
"krang: endpoint and model are required in %s\n",
config_path);
return 1;
}
signal(SIGPIPE, SIG_IGN);
memset(&sa, 0, sizeof(sa));
sa.sa_handler = on_signal;
sigemptyset(&sa.sa_mask);
(void)sigaction(SIGTERM, &sa, NULL);
(void)sigaction(SIGINT, &sa, NULL);
if (ksandbox_enter(&k, k.last_error, sizeof(k.last_error)) != 0) {
fprintf(stderr, "krang: %s\n", k.last_error);
return 1;
}
i = kdaemon_run(&k);
sp_buf_free(&k.err);
pthread_mutex_destroy(&k.lock);
pthread_cond_destroy(&k.cond);
if (k.log.fd >= 0)
klog_close(&k.log);
return i;
}
+1238
View File
File diff suppressed because it is too large. Load diff
+161
View File
@@ -0,0 +1,161 @@
/*
* krang -- reading the one session.
*
* Copyright (c) 2026 Konrad Lother
* License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree.
*/
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include "krang.h"
static void
session_info(struct krang *k, struct sp_session_info *si)
{
memset(si, 0, sizeof(*si));
snprintf(si->id, sizeof(si->id), "%s", KRANG_SESSION_ID);
snprintf(si->dir, sizeof(si->dir), "%s",
k != NULL && k->session_dir[0] != '\0' ? k->session_dir :
KRANG_IN_SESSIONS);
}
int
ksession_meta(struct krang *k, size_t *records, unsigned long long *bytes,
char *goal, size_t goalcap, char *gstate, size_t gstatecap)
{
struct sp_session_info si;
struct stat st;
char path[640];
struct sp_buf err;
if (k == NULL)
return -1;
session_info(k, &si);
if (records != NULL)
*records = 0;
if (bytes != NULL)
*bytes = 0;
if (goal != NULL && goalcap > 0)
goal[0] = '\0';
if (gstate != NULL && gstatecap > 0)
gstate[0] = '\0';
if (sp_buf_init(&err) != 0)
return -1;
if (records != NULL) {
size_t n = 0;
if (sp_session_count(&si, &n, &err) == 0)
*records = n;
}
sp_buf_free(&err);
snprintf(path, sizeof(path), "%s/%s.jsonl", si.dir, si.id);
if (bytes != NULL && stat(path, &st) == 0)
*bytes = (unsigned long long)st.st_size;
if (goal != NULL && goalcap > 0)
(void)sp_session_get_goal(si.dir, si.id, goal, goalcap);
if (gstate != NULL && gstatecap > 0)
(void)sp_session_get_goal_state(si.dir, si.id, gstate,
gstatecap);
return 0;
}
static int
valid_line(const char *line)
{
const char *p = line;
size_t n;
if (p == NULL)
return 0;
while (*p == ' ' || *p == '\t' || *p == '\r')
p++;
if (*p != '{')
return 0;
n = strlen(p);
while (n > 0 && (p[n - 1] == '\n' || p[n - 1] == '\r' ||
p[n - 1] == ' ' || p[n - 1] == '\t'))
n--;
return n > 1 && p[n - 1] == '}';
}
int
ksession_history(struct krang *k, struct sp_buf *out, size_t limit)
{
struct sp_session_info si;
char path[640], *line = NULL;
size_t linecap = 0, n = 0, i, start;
char **keep;
FILE *f;
(void)k;
if (out == NULL)
return -1;
if (limit == 0 || limit > 500)
limit = 100;
session_info(k, &si);
snprintf(path, sizeof(path), "%s/%s.jsonl", si.dir, si.id);
f = fopen(path, "r");
if (f == NULL) {
(void)sp_buf_puts(out, "[]");
return errno == ENOENT ? 0 : -1;
}
keep = calloc(limit, sizeof(*keep));
if (keep == NULL) {
fclose(f);
return -1;
}
while (getline(&line, &linecap, f) > 0) {
char *copy;
k_trim(line);
if (!valid_line(line))
continue;
copy = k_strdup(line);
if (copy == NULL)
continue;
free(keep[n % limit]);
keep[n % limit] = copy;
n++;
}
free(line);
fclose(f);
(void)sp_buf_puts(out, "[");
start = n > limit ? n - limit : 0;
for (i = start; i < n; i++) {
if (i > start)
(void)sp_buf_puts(out, ",");
(void)sp_buf_puts(out, keep[i % limit]);
}
(void)sp_buf_puts(out, "]");
for (i = 0; i < limit; i++)
free(keep[i]);
free(keep);
return 0;
}
long
ksession_born(struct krang *k)
{
struct sp_session_info si;
char path[640], line[512];
FILE *f;
long born = 0;
(void)k;
session_info(k, &si);
snprintf(path, sizeof(path), "%s/%s.meta", si.dir, si.id);
f = fopen(path, "r");
if (f == NULL)
return 0;
while (fgets(line, sizeof(line), f) != NULL) {
if (strncmp(line, "created=", 8) == 0) {
born = strtol(line + 8, NULL, 10);
break;
}
}
fclose(f);
return born;
}
+338
View File
@@ -0,0 +1,338 @@
/*
* krang -- the snapshot the dashboard, the HTTP API and MCP read.
*
* Copyright (c) 2026 Konrad Lother
* License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree.
*/
#include <stdio.h>
#include <string.h>
#include "krang.h"
static void
jstr(struct sp_buf *b, const char *key, const char *val)
{
(void)sp_buf_puts(b, "\"");
(void)sp_buf_puts(b, key);
(void)sp_buf_puts(b, "\":\"");
k_json_escape(b, val != NULL ? val : "");
(void)sp_buf_puts(b, "\"");
}
static void
jnum(struct sp_buf *b, const char *key, long long v)
{
(void)sp_buf_printf(b, "\"%s\":%lld", key, v);
}
static void
jstr_redacted(struct krang *k, struct sp_buf *b, const char *key,
const char *val)
{
struct sp_buf clean;
if (val == NULL)
val = "";
if (k->log.secret[0] == '\0') {
jstr(b, key, val);
return;
}
if (sp_buf_init(&clean) != 0) {
jstr(b, key, val);
return;
}
k_redact(&clean, val, k->log.secret);
jstr(b, key, clean.p != NULL ? clean.p : "");
sp_buf_free(&clean);
}
void
kstate_sync(struct krang *k)
{
struct sp_engine_state es;
if (k == NULL || k->eng == NULL)
return;
memset(&es, 0, sizeof(es));
if (sp_engine_state(k->eng, &es) != 0)
return;
pthread_mutex_lock(&k->lock);
snprintf(k->st.model, sizeof(k->st.model), "%s", es.model);
snprintf(k->st.agent, sizeof(k->st.agent), "%s", es.agent);
snprintf(k->st.session, sizeof(k->st.session), "%s", es.session);
k->st.tokens_in = (unsigned long)es.tokens_in;
k->st.tokens_out = (unsigned long)es.tokens_out;
k->st.tokens_cached = (unsigned long)es.cached_total;
k->st.cost = es.cost;
k->st.ctx_used = es.ctx_used;
k->st.ctx_max = es.ctx_max;
k->st.steps = (unsigned long)es.steps;
k->st.tool_calls = (unsigned long)es.calls;
k->st.compactions = (unsigned long)es.compactions;
k->st.busy = es.busy;
k->st.waiting = es.waiting;
pthread_mutex_unlock(&k->lock);
}
void
kstate_json(struct krang *k, struct sp_buf *out)
{
struct kstats s;
char now[64];
struct sp_buf cfg;
if (k == NULL || out == NULL)
return;
pthread_mutex_lock(&k->lock);
s = k->st;
pthread_mutex_unlock(&k->lock);
k_format_time(k_now(), now, sizeof(now));
sp_buf_init(&cfg);
kconfig_json(&k->cfg, &cfg, 1);
(void)sp_buf_puts(out, "{");
jstr(out, "version", KRANG_VERSION);
(void)sp_buf_puts(out, ",");
jstr(out, "time", now);
(void)sp_buf_puts(out, ",");
jstr(out, "state", s.state);
(void)sp_buf_puts(out, ",");
jnum(out, "started_at", s.started_at);
(void)sp_buf_puts(out, ",");
jnum(out, "born_at", s.born_at);
(void)sp_buf_puts(out, ",");
jnum(out, "uptime", (long long)(k_now() - s.started_at));
(void)sp_buf_puts(out, ",");
jstr_redacted(k, out, "goal", s.goal);
(void)sp_buf_puts(out, ",");
jstr(out, "goal_state", s.goal_state[0] != '\0' ? s.goal_state : "open");
(void)sp_buf_puts(out, ",");
(void)sp_buf_puts(out, "\"model\":{");
jstr(out, "name", s.model);
(void)sp_buf_puts(out, ",");
jstr(out, "agent", s.agent);
(void)sp_buf_puts(out, "},");
(void)sp_buf_puts(out, "\"session\":{");
jstr(out, "id", s.session);
(void)sp_buf_puts(out, ",");
jnum(out, "records", (long long)s.session_records);
(void)sp_buf_puts(out, ",");
jnum(out, "bytes", (long long)s.session_bytes);
(void)sp_buf_puts(out, "},");
(void)sp_buf_puts(out, "\"impulses\":{");
jnum(out, "total", (long long)s.impulses);
(void)sp_buf_puts(out, ",");
jnum(out, "self", (long long)s.self_impulses);
(void)sp_buf_puts(out, ",");
jnum(out, "external", (long long)s.external_impulses);
(void)sp_buf_puts(out, ",");
jnum(out, "last_at", s.last_impulse_at);
(void)sp_buf_puts(out, ",");
jnum(out, "next_at", s.next_impulse_at);
(void)sp_buf_puts(out, "},");
(void)sp_buf_puts(out, "\"turns\":{");
jnum(out, "total", (long long)s.turns);
(void)sp_buf_puts(out, ",");
jnum(out, "steps", (long long)s.steps);
(void)sp_buf_puts(out, ",");
jnum(out, "tool_calls", (long long)s.tool_calls);
(void)sp_buf_puts(out, ",");
jnum(out, "tool_failures", (long long)s.tool_failures);
(void)sp_buf_puts(out, ",");
jnum(out, "denials", (long long)s.denials);
(void)sp_buf_puts(out, ",");
jnum(out, "last_rc", s.last_turn_rc);
(void)sp_buf_puts(out, "},");
(void)sp_buf_puts(out, "\"tokens\":{");
jnum(out, "in", (long long)s.tokens_in);
(void)sp_buf_puts(out, ",");
jnum(out, "out", (long long)s.tokens_out);
(void)sp_buf_puts(out, ",");
jnum(out, "cached", (long long)s.tokens_cached);
(void)sp_buf_puts(out, ",");
jnum(out, "ctx_used", (long long)s.ctx_used);
(void)sp_buf_puts(out, ",");
jnum(out, "ctx_max", (long long)s.ctx_max);
(void)sp_buf_puts(out, ",");
(void)sp_buf_printf(out, "\"cost\":%.6f", s.cost);
(void)sp_buf_puts(out, "},");
(void)sp_buf_puts(out, "\"chat\":{");
jnum(out, "in", (long long)s.chat_in);
(void)sp_buf_puts(out, ",");
jnum(out, "out", (long long)s.chat_out);
(void)sp_buf_puts(out, ",");
jnum(out, "pending", (long long)s.chat_pending);
(void)sp_buf_puts(out, "},");
(void)sp_buf_puts(out, "\"stuck\":{");
jnum(out, "level", k->stuck.level);
(void)sp_buf_puts(out, ",");
jnum(out, "events", (long long)s.stuck_events);
(void)sp_buf_puts(out, ",");
jnum(out, "blocked", (long long)s.blocked_events);
(void)sp_buf_puts(out, ",");
jnum(out, "attempts", k->stuck.attempts);
(void)sp_buf_puts(out, "},");
(void)sp_buf_puts(out, "\"busy\":");
(void)sp_buf_puts(out, s.busy ? "true" : "false");
(void)sp_buf_puts(out, ",");
(void)sp_buf_puts(out, "\"waiting\":");
(void)sp_buf_puts(out, s.waiting ? "true" : "false");
(void)sp_buf_puts(out, ",");
jnum(out, "compactions", (long long)s.compactions);
(void)sp_buf_puts(out, ",");
jnum(out, "self_edits", (long long)s.self_edits);
(void)sp_buf_puts(out, ",");
jnum(out, "goal_completes", (long long)s.goal_completes);
(void)sp_buf_puts(out, ",");
jstr_redacted(k, out, "last_error", s.last_error);
(void)sp_buf_puts(out, ",");
jstr_redacted(k, out, "last_outcome", s.last_outcome);
(void)sp_buf_puts(out, ",");
jstr(out, "last_tool", s.last_tool);
(void)sp_buf_puts(out, ",");
jstr_redacted(k, out, "last_tool_result", s.last_tool_result);
(void)sp_buf_puts(out, ",");
(void)sp_buf_puts(out, "\"sandbox\":{");
jstr(out, "rootfs", s.rootfs_id);
(void)sp_buf_puts(out, ",");
jstr(out, "uid", s.sandbox_uid);
(void)sp_buf_puts(out, ",");
jstr(out, "gid", s.sandbox_gid);
(void)sp_buf_puts(out, ",");
jstr(out, "landlock", s.landlock);
(void)sp_buf_puts(out, ",");
jstr(out, "seccomp", s.seccomp);
(void)sp_buf_puts(out, ",");
jstr(out, "host", s.host_id);
(void)sp_buf_puts(out, ",");
jstr(out, "host_version", s.host_version);
(void)sp_buf_puts(out, ",");
jstr(out, "host_arch", s.host_arch);
(void)sp_buf_puts(out, "},");
(void)sp_buf_puts(out, "\"config\":");
(void)sp_buf_puts(out, cfg.p != NULL ? cfg.p : "{}");
(void)sp_buf_puts(out, "}");
sp_buf_free(&cfg);
}
void
kstate_impulses_json(struct krang *k, struct sp_buf *out, size_t max)
{
size_t i, n, start;
unsigned long seq;
if (k == NULL || out == NULL)
return;
pthread_mutex_lock(&k->lock);
n = k->impulse_seq < KRANG_IMPULSE_RING ? (size_t)k->impulse_seq :
KRANG_IMPULSE_RING;
seq = k->impulse_seq;
pthread_mutex_unlock(&k->lock);
if (max > 0 && n > max)
n = max;
if (n == 0) {
(void)sp_buf_puts(out, "[]");
return;
}
start = (size_t)(seq % KRANG_IMPULSE_RING);
/* the ring slot seq % RING holds impulse seq; walk backwards */
(void)sp_buf_puts(out, "[");
for (i = 0; i < n; i++) {
size_t slot = (start + KRANG_IMPULSE_RING - 1 - i) %
KRANG_IMPULSE_RING;
struct kimpulse imp;
pthread_mutex_lock(&k->lock);
imp = k->impulses[slot];
pthread_mutex_unlock(&k->lock);
if (i > 0)
(void)sp_buf_puts(out, ",");
(void)sp_buf_puts(out, "{");
jnum(out, "id", (long long)imp.id);
(void)sp_buf_puts(out, ",");
jnum(out, "at", imp.at);
(void)sp_buf_puts(out, ",");
jstr(out, "cause", imp.cause);
(void)sp_buf_puts(out, ",");
jnum(out, "rc", imp.rc);
(void)sp_buf_puts(out, ",");
jnum(out, "steps", (long long)imp.steps);
(void)sp_buf_puts(out, ",");
jnum(out, "tool_calls", (long long)imp.tool_calls);
(void)sp_buf_puts(out, ",");
jnum(out, "tokens_in", (long long)imp.tokens_in);
(void)sp_buf_puts(out, ",");
jnum(out, "tokens_out", (long long)imp.tokens_out);
(void)sp_buf_puts(out, ",");
(void)sp_buf_printf(out, "\"cost\":%.6f,", imp.cost);
jstr_redacted(k, out, "answer", imp.answer);
(void)sp_buf_puts(out, "}");
}
(void)sp_buf_puts(out, "]");
}
void
kstate_tools_json(struct krang *k, struct sp_buf *out)
{
struct sp_registry *reg;
const struct sp_tool *tools;
size_t n = 0, i;
if (k == NULL || out == NULL)
return;
reg = k->eng != NULL ? sp_engine_registry(k->eng) : NULL;
tools = reg != NULL ? sp_registry_tools(reg, &n) : NULL;
(void)sp_buf_puts(out, "[");
for (i = 0; i < n; i++) {
if (i > 0)
(void)sp_buf_puts(out, ",");
(void)sp_buf_puts(out, "{");
jstr(out, "name", tools[i].name);
(void)sp_buf_puts(out, ",");
jstr(out, "description", tools[i].description);
(void)sp_buf_puts(out, ",");
jnum(out, "auth", tools[i].auth);
(void)sp_buf_puts(out, "}");
}
(void)sp_buf_puts(out, "]");
}
void
kstate_sandbox_json(struct krang *k, struct sp_buf *out)
{
struct kstats s;
if (k == NULL || out == NULL)
return;
pthread_mutex_lock(&k->lock);
s = k->st;
pthread_mutex_unlock(&k->lock);
(void)sp_buf_puts(out, "{");
jstr(out, "rootfs", s.rootfs_id);
(void)sp_buf_puts(out, ",");
jstr(out, "uid", s.sandbox_uid);
(void)sp_buf_puts(out, ",");
jstr(out, "gid", s.sandbox_gid);
(void)sp_buf_puts(out, ",");
jstr(out, "landlock", s.landlock);
(void)sp_buf_puts(out, ",");
jstr(out, "seccomp", s.seccomp);
(void)sp_buf_puts(out, ",");
jstr(out, "host", s.host_id);
(void)sp_buf_puts(out, ",");
jstr(out, "host_version", s.host_version);
(void)sp_buf_puts(out, ",");
jstr(out, "host_arch", s.host_arch);
(void)sp_buf_puts(out, "}");
}
+131
View File
@@ -0,0 +1,131 @@
/*
* krang -- noticing that the same thing is not working.
*
* Copyright (c) 2026 Konrad Lother
* License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree.
*/
#include <stdio.h>
#include <string.h>
#include "krang.h"
static void
copy_result(char *dst, size_t cap, const char *obs)
{
size_t n;
if (cap == 0)
return;
if (obs == NULL)
obs = "";
n = strlen(obs);
if (n >= cap)
n = cap - 1;
memcpy(dst, obs, n);
dst[n] = '\0';
/* collapse newlines so the prompt stays readable */
for (n = 0; dst[n] != '\0'; n++)
if (dst[n] == '\n' || dst[n] == '\r' || dst[n] == '\t')
dst[n] = ' ';
}
void
kstuck_call(struct kstuck *s, const char *tool, const char *args)
{
char call[512];
if (s == NULL)
return;
snprintf(call, sizeof(call), "%s %.400s",
tool != NULL ? tool : "?", args != NULL ? args : "");
if (s->last_call[0] != '\0' && strcmp(s->last_call, call) == 0) {
s->repeated_calls++;
} else {
s->repeated_calls = 0;
snprintf(s->last_call, sizeof(s->last_call), "%s", call);
}
}
void
kstuck_result(struct kstuck *s, const char *tool, const char *obs,
int is_error)
{
char first[KRANG_ERR];
if (s == NULL)
return;
copy_result(first, sizeof(first), obs);
if (!is_error) {
s->consecutive_failures = 0;
s->repeated_calls = 0;
s->same_error = 0;
return;
}
s->consecutive_failures++;
if (s->last_error[0] != '\0' &&
strncmp(s->last_error, first, 160) == 0) {
s->same_error++;
} else {
s->same_error = 1;
snprintf(s->last_error, sizeof(s->last_error), "%s", first);
}
if (tool != NULL && *tool != '\0')
(void)tool;
}
void
kstuck_turn(struct kstuck *s, int rc, unsigned long calls, int mutating)
{
if (s == NULL)
return;
if (rc != 0) {
s->consecutive_failures++;
return;
}
if (calls == 0 && !mutating) {
s->no_progress_turns++;
} else {
s->no_progress_turns = 0;
}
if (mutating)
kstuck_reset(s);
}
int
kstuck_level(const struct kstuck *s)
{
if (s == NULL)
return 0;
if (s->same_error >= 2 || s->consecutive_failures >= 3 ||
s->repeated_calls >= 2 || s->no_progress_turns >= 3)
return s->attempts >= 4 ? 3 : (s->attempts >= 2 ? 2 : 1);
return 0;
}
int
kstuck_should_check(struct kstuck *s, long now)
{
int level;
if (s == NULL)
return 0;
level = kstuck_level(s);
if (level == 0 || level >= 3)
return 0;
if (s->attempts >= 4)
return 0;
if (s->last_check != 0 && now - s->last_check < 30)
return 0;
s->attempts++;
s->last_check = now;
s->level = level;
return level;
}
void
kstuck_reset(struct kstuck *s)
{
if (s == NULL)
return;
memset(s, 0, sizeof(*s));
}
+165
View File
@@ -0,0 +1,165 @@
/*
* krang -- small helpers.
*
* Copyright (c) 2026 Konrad Lother
* License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree.
*/
#include <ctype.h>
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include "krang.h"
volatile sig_atomic_t krang_stop;
long
k_now(void)
{
return (long)time(NULL);
}
void
k_sleep_ms(int ms)
{
struct timespec ts;
if (ms <= 0)
return;
ts.tv_sec = ms / 1000;
ts.tv_nsec = (long)(ms % 1000) * 1000000L;
while (nanosleep(&ts, &ts) != 0 && errno == EINTR)
;
}
void
k_trim(char *s)
{
char *p;
size_t n;
if (s == NULL)
return;
p = s;
while (*p != '\0' && isspace((unsigned char)*p))
p++;
if (p != s)
memmove(s, p, strlen(p) + 1);
n = strlen(s);
while (n > 0 && isspace((unsigned char)s[n - 1]))
s[--n] = '\0';
}
int
k_starts_with(const char *s, const char *p)
{
size_t n;
if (s == NULL || p == NULL)
return 0;
n = strlen(p);
return strncmp(s, p, n) == 0;
}
char *
k_strdup(const char *s)
{
char *p;
size_t n;
if (s == NULL)
s = "";
n = strlen(s);
p = malloc(n + 1);
if (p != NULL)
memcpy(p, s, n + 1);
return p;
}
void
k_json_escape(struct sp_buf *b, const char *s)
{
if (b == NULL)
return;
if (s == NULL)
s = "";
(void)sp_json_escape(b, s);
}
void
k_redact(struct sp_buf *out, const char *text, const char *secret)
{
const char *p, *hit;
size_t n;
if (out == NULL)
return;
if (text == NULL)
text = "";
if (secret == NULL || *secret == '\0' || strlen(secret) < 4) {
(void)sp_buf_puts(out, text);
return;
}
n = strlen(secret);
p = text;
while ((hit = strstr(p, secret)) != NULL) {
(void)sp_buf_add(out, p, (size_t)(hit - p));
(void)sp_buf_puts(out, "[redacted]");
p = hit + n;
}
(void)sp_buf_puts(out, p);
}
int
k_write_all(int fd, const void *buf, size_t len)
{
const char *p = buf;
size_t off = 0;
while (off < len) {
ssize_t n = write(fd, p + off, len - off);
if (n < 0) {
if (errno == EINTR)
continue;
return -1;
}
if (n == 0)
return -1;
off += (size_t)n;
}
return 0;
}
void
k_format_time(long t, char *buf, size_t cap)
{
struct tm tm;
if (buf == NULL || cap == 0)
return;
if (t <= 0 || gmtime_r(&(time_t){ t }, &tm) == NULL) {
snprintf(buf, cap, "-");
return;
}
if (strftime(buf, cap, "%Y-%m-%dT%H:%M:%SZ", &tm) == 0)
snprintf(buf, cap, "-");
}
int
k_parse_bool(const char *s, int dflt)
{
if (s == NULL || *s == '\0')
return dflt;
if (!strcmp(s, "1") || !strcmp(s, "yes") || !strcmp(s, "true") ||
!strcmp(s, "on"))
return 1;
if (!strcmp(s, "0") || !strcmp(s, "no") || !strcmp(s, "false") ||
!strcmp(s, "off"))
return 0;
return dflt;
}
+139
View File
@@ -0,0 +1,139 @@
#!/bin/sh
# krang -- root-only integration test.
#
# Copyright (c) 2026 Konrad Lother
# License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree.
#
# This is the part the offline suite cannot prove: debootstrap, mount namespace,
# chroot, uid drop, Landlock, seccomp and the event log ownership. It does not
# start the autonomous daemon or a provider; it runs --sandbox-test, one
# scripted turn that asks `id -u` and tries `mount(2)` inside the cage.
#
# sudo tests/root-integration.sh
#
# Environment:
# KRANG_TEST_DIR work directory (default: mktemp -d /var/tmp/...)
# KRANG_TEST_ROOTFS reuse an already prepared rootfs, skip debootstrap
# KRANG_KEEP=1 keep the work directory for inspection
set -eu
if [ "$(id -u)" != "0" ]; then
echo "root-integration: must run as root (sudo tests/root-integration.sh)" >&2
exit 1
fi
[ -x ./krang ] || { echo "root-integration: build ./krang first (make)" >&2; exit 1; }
if [ -n "${KRANG_TEST_ROOTFS:-}" ]; then
ROOTFS=$KRANG_TEST_ROOTFS
else
if ! command -v debootstrap >/dev/null 2>&1 &&
[ ! -x /usr/sbin/debootstrap ]; then
echo "root-integration: debootstrap is not installed" >&2
exit 1
fi
fi
WORK=${KRANG_TEST_DIR:-$(mktemp -d /var/tmp/krang-root.XXXXXX)}
KRANG_ROOT=$(cd "$(dirname "$0")/.." && pwd)
SPLINTER=${SPLINTER:-$KRANG_ROOT/../splinter}
PLUGIN=$SPLINTER/plugins/clock/clock.so
test -r "$PLUGIN" || {
echo "root-integration: missing $PLUGIN (build ../splinter first)" >&2
exit 1
}
STATE=$WORK/state
WORKSPACE=$WORK/workspace
CONF=$WORK/krang.conf
if [ -z "${KRANG_TEST_ROOTFS:-}" ]; then
ROOTFS=$WORK/rootfs
fi
mkdir -p "$STATE" "$WORKSPACE"
cleanup() {
if [ "${KRANG_KEEP:-0}" = "1" ]; then
echo "root-integration: kept $WORK"
return
fi
rm -rf "$WORK"
}
trap cleanup EXIT INT TERM
cat >"$CONF" <<EOF
goal = sandbox integration test
endpoint = http://127.0.0.1:1/v1
model = test
api_key_env = KRANG_TEST_KEY
state_dir = $STATE
workspace = $WORKSPACE
rootfs = $ROOTFS
sandbox_user = nobody
sandbox_uid = 65534
sandbox_gid = 65534
plugin = $PLUGIN
impulse_seconds = 5
max_steps = 5
compact_threshold = 60000
compact_target = 20000
dashboard_host = 127.0.0.1
dashboard_port = 18096
mcp_host = 127.0.0.1
mcp_port = 18098
say_timeout = 10
require_landlock = 1
seccomp = 1
prepare_if_missing = 0
EOF
if [ -z "${KRANG_TEST_ROOTFS:-}" ]; then
echo "== prepare-rootfs (debootstrap; network)"
./krang --prepare-rootfs --config "$CONF"
else
echo "== reusing rootfs $ROOTFS"
test -r "$ROOTFS/etc/krang-rootfs" || {
echo "root-integration: no /etc/krang-rootfs in $ROOTFS" >&2
exit 1
}
fi
echo "== sandbox-test (unshare, chroot, uid drop, Landlock, seccomp)"
./krang --sandbox-test --config "$CONF"
EVENTS=$STATE/events.jsonl
SESSIONS=$STATE/sessions/krang.jsonl
test -s "$EVENTS"
test -s "$SESSIONS"
echo "== event log ownership"
EV_UID=$(stat -c %u "$EVENTS")
EV_MODE=$(stat -c %a "$EVENTS")
echo "events: uid=$EV_UID mode=$EV_MODE"
[ "$EV_UID" = "0" ] || { echo "event log is not root-owned" >&2; exit 1; }
[ "$EV_MODE" = "600" ] || { echo "event log mode is not 600" >&2; exit 1; }
echo "== session ownership"
S_UID=$(stat -c %u "$SESSIONS")
echo "session: uid=$S_UID"
[ "$S_UID" = "65534" ] || { echo "session is not owned by the sandbox uid" >&2; exit 1; }
echo "== tool observations"
grep -q '"name":"clock"' "$EVENTS" || {
echo "the clock plugin was not loaded" >&2
exit 1
}
grep -q '65534' "$EVENTS" || { echo "id -u did not report 65534" >&2; exit 1; }
grep -q 'mount-denied\|Operation not permitted\|Permission denied' "$EVENTS" || {
echo "mount was not denied" >&2
exit 1
}
grep -q 'sandbox-test-ok' "$EVENTS" || { echo "answer missing" >&2; exit 1; }
if command -v setpriv >/dev/null 2>&1; then
if setpriv --reuid=65534 --regid=65534 --clear-groups \
test -r "$EVENTS" 2>/dev/null; then
echo "event log is readable by the sandbox uid" >&2
exit 1
fi
echo "== sandbox uid cannot read the event log: ok"
fi
echo "== root-integration: ok"
+130
View File
@@ -0,0 +1,130 @@
/*
* krang -- offline end-to-end daemon test.
*
* Copyright (c) 2026 Konrad Lother
* License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree.
*
* Runs kdaemon_run itself: temp state/workspace, script transport, exactly one
* impulse (the birth), no provider, no network, no root. The dashboard and MCP
* listeners are bound to ephemeral loopback ports and stopped by the daemon.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include "krang.h"
static int failures;
#define CHECK(cond) do { \
if (!(cond)) { \
fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, \
#cond); \
failures++; \
} \
} while (0)
static int
contains(const char *hay, const char *needle)
{
return hay != NULL && strstr(hay, needle) != NULL;
}
static void
read_file(const char *path, char *buf, size_t cap)
{
FILE *f;
size_t n;
buf[0] = '\0';
f = fopen(path, "r");
if (f == NULL)
return;
n = fread(buf, 1, cap - 1, f);
buf[n] = '\0';
fclose(f);
}
int
main(void)
{
struct krang k;
char tmpl[] = "/tmp/krang-daemon-XXXXXX";
char *dir;
char path[800], logbuf[65536];
size_t records = 0;
unsigned long long bytes = 0;
int rc;
dir = mkdtemp(tmpl);
CHECK(dir != NULL);
if (dir == NULL)
return 1;
memset(&k, 0, sizeof(k));
k.log.fd = -1;
pthread_mutex_init(&k.lock, NULL);
pthread_cond_init(&k.cond, NULL);
sp_buf_init(&k.err);
kconfig_defaults(&k.cfg);
snprintf(k.cfg.goal, sizeof(k.cfg.goal), "be born once");
snprintf(k.cfg.endpoint, sizeof(k.cfg.endpoint),
"http://127.0.0.1:1/v1");
snprintf(k.cfg.model, sizeof(k.cfg.model), "test-model");
snprintf(k.cfg.state_dir, sizeof(k.cfg.state_dir), "%s/state", dir);
snprintf(k.cfg.workspace, sizeof(k.cfg.workspace), "%s/workspace", dir);
snprintf(k.cfg.rootfs, sizeof(k.cfg.rootfs), "%s/rootfs", dir);
snprintf(k.session_dir, sizeof(k.session_dir), "%s/sessions", dir);
snprintf(k.script, sizeof(k.script), "%s/script.txt", dir);
snprintf(k.cfg.dashboard_host, sizeof(k.cfg.dashboard_host),
"127.0.0.1");
snprintf(k.cfg.mcp_host, sizeof(k.cfg.mcp_host), "127.0.0.1");
k.cfg.dashboard_port = 0;
k.cfg.mcp_port = 0;
k.max_impulses = 1;
(void)mkdir(k.cfg.state_dir, 0755);
(void)mkdir(k.cfg.workspace, 0700);
(void)mkdir(k.session_dir, 0700);
snprintf(path, sizeof(path), "%s/events.jsonl", k.cfg.state_dir);
CHECK(klog_open(&k.log, path, k.last_error,
sizeof(k.last_error)) == 0);
{
FILE *f = fopen(k.script, "w");
CHECK(f != NULL);
if (f == NULL)
return 1;
fprintf(f, "tool echo {\"text\":\"daemon\"}\n");
fprintf(f, "answer daemon-birth-ok\n");
fclose(f);
}
rc = kdaemon_run(&k);
CHECK(rc == 0);
CHECK(k.st.impulses == 1);
CHECK(k.st.turns == 1);
CHECK(k.st.born_at > 0);
CHECK(contains(k.st.last_outcome, "daemon-birth-ok"));
CHECK(k.st.session_records >= 3);
CHECK(k.log.fd == -1); /* kdaemon_run closed it */
(void)ksession_meta(&k, &records, &bytes, NULL, 0, NULL, 0);
CHECK(records >= 3);
CHECK(bytes > 0);
snprintf(path, sizeof(path), "%s/events.jsonl", k.cfg.state_dir);
read_file(path, logbuf, sizeof(logbuf));
CHECK(contains(logbuf, "\"kind\":\"birth\""));
CHECK(contains(logbuf, "\"kind\":\"turn_end\""));
CHECK(contains(logbuf, "\"kind\":\"stop\""));
CHECK(contains(logbuf, "daemon-birth-ok"));
pthread_mutex_destroy(&k.lock);
pthread_cond_destroy(&k.cond);
sp_buf_free(&k.err);
if (failures != 0) {
fprintf(stderr, "%d test(s) failed\n", failures);
return 1;
}
printf("test_daemon: ok\n");
return 0;
}
+140
View File
@@ -0,0 +1,140 @@
/*
* krang -- offline integration test: one scripted turn through the engine.
*
* Copyright (c) 2026 Konrad Lother
* License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree.
*
* No network, no key, no model. The mock transport replays the script; the
* session and the event log are real.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include "krang.h"
#include "i18n.h"
static int failures;
#define CHECK(cond) do { \
if (!(cond)) { \
fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, \
#cond); \
failures++; \
} \
} while (0)
static int
contains(const char *hay, const char *needle)
{
return hay != NULL && strstr(hay, needle) != NULL;
}
int
main(void)
{
struct krang k;
char tmpl[512], *dir, script[700], logpath[800], answer[KRANG_GOAL];
size_t records = 0;
unsigned long long bytes = 0;
FILE *f;
dir = mkdtemp(strcpy(tmpl, "/tmp/krang-engine-XXXXXX"));
CHECK(dir != NULL);
if (dir == NULL)
return 1;
(void)chdir(dir);
(void)setenv("HOME", dir, 1);
(void)sp_i18n_init("en");
memset(&k, 0, sizeof(k));
k.log.fd = -1;
pthread_mutex_init(&k.lock, NULL);
pthread_cond_init(&k.cond, NULL);
sp_buf_init(&k.err);
kconfig_defaults(&k.cfg);
snprintf(k.cfg.goal, sizeof(k.cfg.goal), "prove the engine");
snprintf(k.cfg.endpoint, sizeof(k.cfg.endpoint),
"http://127.0.0.1:1/v1");
snprintf(k.cfg.model, sizeof(k.cfg.model), "test-model");
snprintf(k.cfg.plugin[0], sizeof(k.cfg.plugin[0]), "%s",
KRANG_TEST_PLUGIN);
k.cfg.nplugins = 1;
snprintf(k.session_dir, sizeof(k.session_dir), "%s/sessions", dir);
(void)mkdir(k.session_dir, 0700);
snprintf(logpath, sizeof(logpath), "%s/events.jsonl", dir);
CHECK(klog_open(&k.log, logpath, k.last_error,
sizeof(k.last_error)) == 0);
{
struct sp_buf sp;
sp_buf_init(&sp);
k_system_prompt(&k, &sp);
snprintf(k.system_prompt, sizeof(k.system_prompt), "%s",
sp.p != NULL ? sp.p : "");
sp_buf_free(&sp);
}
snprintf(script, sizeof(script), "%s/script.txt", dir);
f = fopen(script, "w");
CHECK(f != NULL);
if (f == NULL)
return 1;
fprintf(f, "tool echo {\"text\":\"from-script\"}\n");
fprintf(f, "answer hello-from-script\n");
fclose(f);
CHECK(kengine_open(&k, script, k.last_error,
sizeof(k.last_error)) == 0);
CHECK(k.eng != NULL);
if (k.eng != NULL) {
CHECK(sp_registry_find(sp_engine_registry(k.eng),
"clock") != NULL);
int rc = krun_turn(&k, "prove the apparatus", "test", NULL);
CHECK(rc == 0);
snprintf(answer, sizeof(answer), "%s", k.st.last_outcome);
CHECK(contains(answer, "hello-from-script"));
CHECK(contains(k.st.last_tool, "echo"));
CHECK(k.st.tool_calls >= 1);
(void)ksession_meta(&k, &records, &bytes, NULL, 0, NULL, 0);
CHECK(records >= 3);
CHECK(bytes > 0);
{
const struct sp_tool *jt = sp_registry_find(
sp_engine_registry(k.eng), "journal_search");
struct sp_buf jb;
CHECK(jt != NULL);
if (jt != NULL) {
sp_buf_init(&jb);
CHECK(jt->run("{\"query\":"
"\"hello-from-script\"}", &jb,
jt->ctx) == 0);
CHECK(contains(jb.p, "hello-from-script"));
sp_buf_free(&jb);
}
}
}
{
struct sp_buf b;
sp_buf_init(&b);
kstate_json(&k, &b);
CHECK(contains(b.p, "\"session\":"));
CHECK(contains(b.p, "\"tool_calls\":"));
sp_buf_free(&b);
}
kengine_close(&k);
klog_close(&k.log);
pthread_mutex_destroy(&k.lock);
pthread_cond_destroy(&k.cond);
sp_buf_free(&k.err);
if (failures != 0) {
fprintf(stderr, "%d test(s) failed\n", failures);
return 1;
}
printf("test_engine: ok\n");
return 0;
}
+289
View File
@@ -0,0 +1,289 @@
/*
* krang -- offline unit tests: config, birth, stuck, snapshot, HTTP, MCP.
*
* Copyright (c) 2026 Konrad Lother
* License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include "krang.h"
static int failures;
#define CHECK(cond) do { \
if (!(cond)) { \
fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, \
#cond); \
failures++; \
} \
} while (0)
static int
contains(const char *hay, const char *needle)
{
return hay != NULL && strstr(hay, needle) != NULL;
}
static void
init_krang(struct krang *k)
{
memset(k, 0, sizeof(*k));
k->log.fd = -1;
pthread_mutex_init(&k->lock, NULL);
pthread_cond_init(&k->cond, NULL);
sp_buf_init(&k->err);
kconfig_defaults(&k->cfg);
snprintf(k->cfg.goal, sizeof(k->cfg.goal), "test the apparatus");
snprintf(k->cfg.endpoint, sizeof(k->cfg.endpoint),
"http://127.0.0.1:1/v1");
snprintf(k->cfg.model, sizeof(k->cfg.model), "test-model");
snprintf(k->st.state, sizeof(k->st.state), "sleeping");
snprintf(k->st.goal, sizeof(k->st.goal), "test the apparatus");
snprintf(k->st.session, sizeof(k->st.session), "krang");
snprintf(k->st.sandbox_uid, sizeof(k->st.sandbox_uid), "1000");
snprintf(k->st.sandbox_gid, sizeof(k->st.sandbox_gid), "1000");
snprintf(k->st.landlock, sizeof(k->st.landlock), "applied");
snprintf(k->st.seccomp, sizeof(k->st.seccomp), "applied");
k->st.started_at = k_now();
k->st.born_at = k->st.started_at;
}
static void
test_config(void)
{
struct kconfig c;
char path[] = "/tmp/krang-test-conf-XXXXXX";
char err[512];
int fd;
FILE *f;
fd = mkstemp(path);
CHECK(fd >= 0);
if (fd < 0)
return;
f = fdopen(fd, "w");
CHECK(f != NULL);
if (f == NULL)
return;
fprintf(f, "# a test\n");
fprintf(f, "goal = keep the apparatus honest # inline comment\n");
fprintf(f, "endpoint = http://127.0.0.1:1/v1\n");
fprintf(f, "model = test\n");
fprintf(f, "impulse_seconds = 7\n");
fprintf(f, "max_steps = 9\n");
fprintf(f, "dashboard_port = 18096\n");
fprintf(f, "seccomp = no\n");
fclose(f);
CHECK(kconfig_load(&c, path, err, sizeof(err)) == 0);
CHECK(strcmp(c.goal, "keep the apparatus honest") == 0);
CHECK(c.impulse_seconds == 7);
CHECK(c.max_steps == 9);
CHECK(c.dashboard_port == 18096);
CHECK(c.seccomp == 0);
unlink(path);
}
static void
test_birth(void)
{
struct kconfig c;
struct sp_buf b;
kconfig_defaults(&c);
snprintf(c.goal, sizeof(c.goal), "map the sandbox");
sp_buf_init(&b);
k_birth_prompt(&c, &b);
CHECK(contains(b.p, "You are krang. You are awake."));
CHECK(contains(b.p, "no user"));
CHECK(contains(b.p, "map the sandbox"));
CHECK(contains(b.p, "Good luck."));
CHECK(contains(b.p, KRANG_IN_WORKSPACE));
sp_buf_free(&b);
}
static void
test_stuck(void)
{
struct kstuck s;
memset(&s, 0, sizeof(s));
kstuck_call(&s, "run", "{\"command\":\"false\"}");
kstuck_call(&s, "run", "{\"command\":\"false\"}");
CHECK(s.repeated_calls >= 1);
kstuck_result(&s, "run", "error: nope", 1);
kstuck_result(&s, "run", "error: nope", 1);
CHECK(s.same_error >= 2);
CHECK(kstuck_level(&s) >= 1);
CHECK(kstuck_should_check(&s, k_now()) >= 1);
kstuck_reset(&s);
CHECK(s.level == 0);
CHECK(s.attempts == 0);
}
static void
test_state(void)
{
struct krang k;
struct sp_buf b;
init_krang(&k);
sp_buf_init(&b);
kstate_json(&k, &b);
CHECK(contains(b.p, "\"state\":\"sleeping\""));
CHECK(contains(b.p, "\"goal\":\"test the apparatus\""));
CHECK(contains(b.p, "\"version\":\"0.1.0\""));
CHECK(contains(b.p, "\"sandbox\":"));
CHECK(contains(b.p, "\"config\":"));
sp_buf_free(&b);
sp_buf_init(&b);
kstate_impulses_json(&k, &b, 10);
CHECK(strcmp(b.p, "[]") == 0);
sp_buf_free(&b);
sp_buf_init(&b);
kstate_tools_json(&k, &b);
CHECK(strcmp(b.p, "[]") == 0);
sp_buf_free(&b);
pthread_mutex_destroy(&k.lock);
pthread_cond_destroy(&k.cond);
sp_buf_free(&k.err);
}
static void
test_birth_flow(void)
{
struct krang k;
struct sp_session_info si;
struct sp_buf err, logjson;
char tmpl[] = "/tmp/krang-birth-XXXXXX";
char *dir;
char goal[KRANG_GOAL];
int newborn = -1;
dir = mkdtemp(tmpl);
CHECK(dir != NULL);
if (dir == NULL)
return;
memset(&k, 0, sizeof(k));
k.log.fd = -1;
pthread_mutex_init(&k.lock, NULL);
pthread_cond_init(&k.cond, NULL);
sp_buf_init(&k.err);
sp_buf_init(&err);
kconfig_defaults(&k.cfg);
snprintf(k.cfg.goal, sizeof(k.cfg.goal), "be born");
snprintf(k.session_dir, sizeof(k.session_dir), "%s/sessions", dir);
(void)mkdir(k.session_dir, 0700);
{
char lp[700];
snprintf(lp, sizeof(lp), "%s/events.jsonl", dir);
CHECK(klog_open(&k.log, lp, k.last_error,
sizeof(k.last_error)) == 0);
}
CHECK(kdaemon_session_open(&k, &newborn, goal, sizeof(goal),
k.last_error, sizeof(k.last_error)) == 0);
CHECK(newborn == 1);
CHECK(strcmp(goal, "be born") == 0);
CHECK(k.st.born_at > 0);
CHECK(sp_session_open(&si, k.session_dir, "krang", &err) == 0);
CHECK(sp_session_append(&si, "user", "first breath", &err) == 0);
sp_buf_free(&err);
newborn = -1;
CHECK(kdaemon_session_open(&k, &newborn, goal, sizeof(goal),
k.last_error, sizeof(k.last_error)) == 0);
CHECK(newborn == 0);
CHECK(strcmp(goal, "be born") == 0);
snprintf(k.cfg.goal, sizeof(k.cfg.goal), "a different goal");
CHECK(kdaemon_session_open(&k, &newborn, goal, sizeof(goal),
k.last_error, sizeof(k.last_error)) == 0);
CHECK(strcmp(goal, "be born") == 0);
sp_buf_init(&logjson);
klog_json(&k.log, &logjson, 20);
CHECK(contains(logjson.p, "config_goal_ignored"));
sp_buf_free(&logjson);
klog_close(&k.log);
pthread_mutex_destroy(&k.lock);
pthread_cond_destroy(&k.cond);
sp_buf_free(&k.err);
}
static void
test_http(void)
{
struct krang k;
struct sp_buf b;
init_krang(&k);
sp_buf_init(&b);
khttp_handle_buffer(&k, "GET /healthz HTTP/1.1\r\nHost: x\r\n\r\n",
&b);
CHECK(contains(b.p, "200 OK"));
CHECK(contains(b.p, "\"ok\":true"));
sp_buf_free(&b);
sp_buf_init(&b);
khttp_handle_buffer(&k, "GET /api/state HTTP/1.1\r\nHost: x\r\n\r\n",
&b);
CHECK(contains(b.p, "200 OK"));
CHECK(contains(b.p, "\"state\":\"sleeping\""));
sp_buf_free(&b);
sp_buf_init(&b);
khttp_handle_buffer(&k, "GET /nope HTTP/1.1\r\nHost: x\r\n\r\n", &b);
CHECK(contains(b.p, "404 Not Found"));
sp_buf_free(&b);
pthread_mutex_destroy(&k.lock);
pthread_cond_destroy(&k.cond);
sp_buf_free(&k.err);
}
static void
test_mcp(void)
{
struct krang k;
char *reply;
init_krang(&k);
kmcp_prepare(&k);
reply = kmcp_handle(&k,
"{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/list\"}");
CHECK(reply != NULL);
CHECK(contains(reply, "krang_state"));
CHECK(contains(reply, "krang_say"));
free(reply);
reply = kmcp_handle(&k,
"{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/call\","
"\"params\":{\"name\":\"krang_state\",\"arguments\":{}}}");
CHECK(reply != NULL);
CHECK(contains(reply, "sleeping"));
free(reply);
pthread_mutex_destroy(&k.lock);
pthread_cond_destroy(&k.cond);
sp_buf_free(&k.err);
}
int
main(void)
{
test_config();
test_birth();
test_stuck();
test_birth_flow();
test_state();
test_http();
test_mcp();
if (failures != 0) {
fprintf(stderr, "%d test(s) failed\n", failures);
return 1;
}
printf("test_krang: ok\n");
return 0;
}
+197
View File
@@ -0,0 +1,197 @@
/*
* krang -- offline test of the two one-way layers.
*
* Copyright (c) 2026 Konrad Lother
* License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree.
*
* This does not chroot and does not need root. It applies the real Landlock
* and seccomp layers to a child, then proves:
* - a write under the workspace is allowed;
* - a write under $HOME (writable by the user, outside the allowed set) is
* denied by the path layer;
* - mount(2) is denied by the syscall layer;
* - fork/execve still work, because the run tool needs them.
*/
#define _GNU_SOURCE
#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <netdb.h>
#include <netinet/in.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mount.h>
#include <sys/prctl.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
#include "krang.h"
static int
network_ok(void)
{
struct addrinfo hints, *res = NULL;
struct sockaddr_in sa;
socklen_t sl = sizeof(sa);
int l, c, a;
char byte = 'x';
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
if (getaddrinfo("localhost", "80", &hints, &res) != 0 || res == NULL)
return 0;
freeaddrinfo(res);
l = socket(AF_INET, SOCK_STREAM, 0);
if (l < 0)
return 0;
memset(&sa, 0, sizeof(sa));
sa.sin_family = AF_INET;
sa.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
if (bind(l, (struct sockaddr *)&sa, sizeof(sa)) != 0 ||
listen(l, 4) != 0 ||
getsockname(l, (struct sockaddr *)&sa, &sl) != 0) {
close(l);
return 0;
}
c = socket(AF_INET, SOCK_STREAM, 0);
if (c < 0 || connect(c, (struct sockaddr *)&sa, sizeof(sa)) != 0) {
if (c >= 0)
close(c);
close(l);
return 0;
}
a = accept(l, NULL, NULL);
if (a < 0 || write(c, &byte, 1) != 1 || read(a, &byte, 1) != 1) {
if (a >= 0)
close(a);
close(c);
close(l);
return 0;
}
close(a);
close(c);
close(l);
return 1;
}
static int
write_ok(const char *path)
{
int fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0600);
if (fd < 0)
return 0;
(void)write(fd, "x", 1);
close(fd);
return 1;
}
int
main(void)
{
char root[] = "/tmp/krang-sandbox-XXXXXX";
char ws[600], st[600], tmp[600], allowed[700], home[700];
char err[512];
struct stat sb;
pid_t pid;
int status;
if (mkdtemp(root) == NULL) {
perror("mkdtemp");
return 1;
}
snprintf(ws, sizeof(ws), "%s/workspace", root);
snprintf(st, sizeof(st), "%s/state", root);
snprintf(tmp, sizeof(tmp), "%s/tmp", root);
(void)mkdir(ws, 0700);
(void)mkdir(st, 0700);
(void)mkdir(tmp, 0700);
snprintf(allowed, sizeof(allowed), "%s/ok", ws);
snprintf(home, sizeof(home), "%s/krang-denied-%ld",
getenv("HOME") != NULL ? getenv("HOME") : "/tmp",
(long)getpid());
pid = fork();
if (pid < 0) {
perror("fork");
return 1;
}
if (pid == 0) {
if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0) {
perror("no_new_privs");
_exit(1);
}
if (ksandbox_apply_landlock(ws, st, tmp, 1, err,
sizeof(err)) < 0) {
fprintf(stderr, "landlock: %s\n", err);
_exit(1);
}
if (!write_ok(allowed)) {
fprintf(stderr, "workspace write denied: %s\n",
strerror(errno));
_exit(1);
}
if (write_ok(home)) {
fprintf(stderr, "HOME write was not denied\n");
_exit(1);
}
if (ksandbox_apply_seccomp(1, err, sizeof(err)) < 0) {
fprintf(stderr, "seccomp: %s\n", err);
_exit(1);
}
errno = 0;
if (mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL) == 0) {
fprintf(stderr, "mount was not denied\n");
_exit(1);
}
if (errno != EPERM && errno != EACCES) {
fprintf(stderr, "mount: unexpected errno %d\n", errno);
_exit(1);
}
if (!network_ok()) {
fprintf(stderr, "network after seccomp failed\n");
_exit(1);
}
if (!write_ok(allowed)) {
fprintf(stderr, "workspace write after seccomp: %s\n",
strerror(errno));
_exit(1);
}
{
pid_t c = fork();
if (c < 0) {
fprintf(stderr, "fork after seccomp: %s\n",
strerror(errno));
_exit(1);
}
if (c == 0) {
execl("/bin/true", "true", (char *)NULL);
_exit(127);
}
if (waitpid(c, &status, 0) < 0 ||
!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
fprintf(stderr, "exec after seccomp failed\n");
_exit(1);
}
}
_exit(0);
}
if (waitpid(pid, &status, 0) < 0) {
perror("waitpid");
return 1;
}
if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
fprintf(stderr, "test_sandbox: child failed (%d)\n", status);
return 1;
}
(void)sb;
printf("test_sandbox: ok\n");
return 0;
}
+134
View File
@@ -0,0 +1,134 @@
/*
* krang -- one scripted engine turn under Landlock and seccomp.
*
* Copyright (c) 2026 Konrad Lother
* License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree.
*
* This is the test that matters for the daemon: the engine opens files,
* starts threads, calls the mock transport and appends a session while both
* one-way layers are already active. No network, no model, no root.
*/
#define _GNU_SOURCE
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/prctl.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
#include "krang.h"
static int
child(const char *ws, const char *st, const char *tmp)
{
struct krang k;
char err[512], script[700], logpath[800];
struct sp_buf sp;
FILE *f;
int rc;
if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0) {
perror("no_new_privs");
return 1;
}
if (ksandbox_apply_landlock(ws, st, tmp, 1, err, sizeof(err)) < 0) {
fprintf(stderr, "landlock: %s\n", err);
return 1;
}
if (ksandbox_apply_seccomp(1, err, sizeof(err)) < 0) {
fprintf(stderr, "seccomp: %s\n", err);
return 1;
}
memset(&k, 0, sizeof(k));
k.log.fd = -1;
pthread_mutex_init(&k.lock, NULL);
pthread_cond_init(&k.cond, NULL);
sp_buf_init(&k.err);
kconfig_defaults(&k.cfg);
snprintf(k.cfg.goal, sizeof(k.cfg.goal), "survive the layers");
snprintf(k.cfg.endpoint, sizeof(k.cfg.endpoint),
"http://127.0.0.1:1/v1");
snprintf(k.cfg.model, sizeof(k.cfg.model), "test-model");
snprintf(k.session_dir, sizeof(k.session_dir), "%s/sessions", st);
if (mkdir(k.session_dir, 0700) != 0 && errno != EEXIST) {
fprintf(stderr, "mkdir sessions: %s\n", strerror(errno));
return 1;
}
snprintf(logpath, sizeof(logpath), "%s/events.jsonl", st);
if (klog_open(&k.log, logpath, err, sizeof(err)) != 0) {
fprintf(stderr, "log: %s\n", err);
return 1;
}
sp_buf_init(&sp);
k_system_prompt(&k, &sp);
snprintf(k.system_prompt, sizeof(k.system_prompt), "%s",
sp.p != NULL ? sp.p : "");
sp_buf_free(&sp);
snprintf(script, sizeof(script), "%s/script.txt", tmp);
f = fopen(script, "w");
if (f == NULL) {
fprintf(stderr, "script: %s\n", strerror(errno));
return 1;
}
fprintf(f, "tool echo {\"text\":\"layers\"}\n");
fprintf(f, "answer sandbox-engine-ok\n");
fclose(f);
if (kengine_open(&k, script, err, sizeof(err)) != 0) {
fprintf(stderr, "engine: %s\n", err);
return 1;
}
rc = krun_turn(&k, "prove the layers", "test", NULL);
if (rc != 0 || strstr(k.st.last_outcome, "sandbox-engine-ok") == NULL) {
fprintf(stderr, "turn: rc=%d outcome=%s\n", rc,
k.st.last_outcome);
return 1;
}
kengine_close(&k);
klog_close(&k.log);
pthread_mutex_destroy(&k.lock);
pthread_cond_destroy(&k.cond);
sp_buf_free(&k.err);
return 0;
}
int
main(void)
{
char root[] = "/tmp/krang-sandbox-engine-XXXXXX";
char ws[600], st[600], tmp[600];
pid_t pid;
int status;
if (mkdtemp(root) == NULL) {
perror("mkdtemp");
return 1;
}
snprintf(ws, sizeof(ws), "%s/workspace", root);
snprintf(st, sizeof(st), "%s/state", root);
snprintf(tmp, sizeof(tmp), "%s/tmp", root);
(void)mkdir(ws, 0700);
(void)mkdir(st, 0700);
(void)mkdir(tmp, 0700);
(void)setenv("HOME", ws, 1);
pid = fork();
if (pid < 0) {
perror("fork");
return 1;
}
if (pid == 0)
_exit(child(ws, st, tmp));
if (waitpid(pid, &status, 0) < 0) {
perror("waitpid");
return 1;
}
if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
fprintf(stderr, "test_sandbox_engine: child failed (%d)\n",
status);
return 1;
}
printf("test_sandbox_engine: ok\n");
return 0;
}
+135
View File
@@ -0,0 +1,135 @@
/*
* krang -- offline socket test: the dashboard and MCP listeners.
*
* Copyright (c) 2026 Konrad Lother
* License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree.
*/
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#include "krang.h"
static int failures;
#define CHECK(cond) do { \
if (!(cond)) { \
fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, \
#cond); \
failures++; \
} \
} while (0)
static int
get_port(int fd)
{
struct sockaddr_in sa;
socklen_t sl = sizeof(sa);
if (getsockname(fd, (struct sockaddr *)&sa, &sl) != 0)
return -1;
return ntohs(sa.sin_port);
}
static int
roundtrip(int port, const char *request, char *out, size_t cap, int line)
{
struct sockaddr_in sa;
int fd;
size_t used = 0;
ssize_t n;
fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd < 0)
return -1;
memset(&sa, 0, sizeof(sa));
sa.sin_family = AF_INET;
sa.sin_port = htons((unsigned short)port);
sa.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
if (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) != 0) {
close(fd);
return -1;
}
if (k_write_all(fd, request, strlen(request)) != 0) {
close(fd);
return -1;
}
while (used + 1 < cap &&
(n = read(fd, out + used, cap - used - 1)) > 0) {
used += (size_t)n;
if (line && memchr(out, '\n', used) != NULL)
break;
}
out[used] = '\0';
close(fd);
return 0;
}
int
main(void)
{
struct krang k;
char err[512], req[512], out[8192];
int port;
memset(&k, 0, sizeof(k));
k.log.fd = -1;
pthread_mutex_init(&k.lock, NULL);
pthread_cond_init(&k.cond, NULL);
sp_buf_init(&k.err);
kconfig_defaults(&k.cfg);
snprintf(k.cfg.dashboard_host, sizeof(k.cfg.dashboard_host),
"127.0.0.1");
k.cfg.dashboard_port = 0;
snprintf(k.cfg.mcp_host, sizeof(k.cfg.mcp_host), "127.0.0.1");
k.cfg.mcp_port = 0;
snprintf(k.st.state, sizeof(k.st.state), "sleeping");
snprintf(k.st.goal, sizeof(k.st.goal), "test the server");
k.st.started_at = k_now();
CHECK(khttp_start(&k, err, sizeof(err)) == 0);
port = get_port(k.http_fd);
CHECK(port > 0);
snprintf(req, sizeof(req),
"GET /healthz HTTP/1.1\r\nHost: localhost\r\n\r\n");
CHECK(roundtrip(port, req, out, sizeof(out), 0) == 0);
CHECK(strstr(out, "200 OK") != NULL);
CHECK(strstr(out, "\"ok\":true") != NULL);
snprintf(req, sizeof(req), "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n");
CHECK(roundtrip(port, req, out, sizeof(out), 0) == 0);
CHECK(strstr(out, "200 OK") != NULL);
CHECK(strstr(out, "<title>krang</title>") != NULL);
snprintf(req, sizeof(req),
"GET /api/state HTTP/1.1\r\nHost: localhost\r\n\r\n");
CHECK(roundtrip(port, req, out, sizeof(out), 0) == 0);
CHECK(strstr(out, "\"goal\":\"test the server\"") != NULL);
khttp_stop(&k);
CHECK(kmcp_start(&k, err, sizeof(err)) == 0);
port = get_port(k.mcp_fd);
CHECK(port > 0);
snprintf(req, sizeof(req),
"{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/list\"}\n");
CHECK(roundtrip(port, req, out, sizeof(out), 1) == 0);
CHECK(strstr(out, "krang_state") != NULL);
snprintf(req, sizeof(req),
"{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/call\","
"\"params\":{\"name\":\"krang_state\",\"arguments\":{}}}\n");
CHECK(roundtrip(port, req, out, sizeof(out), 1) == 0);
CHECK(strstr(out, "sleeping") != NULL);
kmcp_stop(&k);
pthread_mutex_destroy(&k.lock);
pthread_cond_destroy(&k.cond);
sp_buf_free(&k.err);
if (failures != 0) {
fprintf(stderr, "%d test(s) failed\n", failures);
return 1;
}
printf("test_server: ok\n");
return 0;
}