From f9172cc715678f136dd497dbba6fb18f96af3980 Mon Sep 17 00:00:00 2001 From: lotherk Date: Sat, 21 Nov 2026 20:19:10 +0000 Subject: [PATCH] krang: resume the life, and give the impulse a reason Restart persistence. A daemon that forgets its own history on every restart is not one experiment. kreplay_events() reads the append-only event log once at startup and rebuilds the impulse ledger (with ids), token/cost/step totals, the last outcome, the stuck ladder, the blocked clock and the recent-start count. The engine's counters start at zero on each open; the surfaces add them to the restored base, so the dashboard does not reset. A restored blocked goal keeps its hour of quiet, three starts within five minutes back off, and an empty session with a non-empty event log is recorded as session_reset instead of silently looking new. The conductor. Before an impulse the daemon measures its own vitals (context against the window and the compaction threshold, cost, stuck level, turn failures, impulses since the last goal, the age of THREADS.md, session size) and lets five drives compete: survive, reflect, maintain, explore, goal. The winning drive, its reason and the vitals are injected into the prompt and shown on the dashboard. The model still chooses the action; the conductor chooses what the turn is about. This is the control architecture from the body/drives/conductor argument, borrowed without the consciousness claim. Session counting is now incremental: only bytes appended since the last look are scanned, the offset stops at the last newline so a torn tail is recounted, and a truncated file resets the count. Tests: test_replay (synthetic log + two kdaemon_run lifetimes, same birth, ledger ids 1 and 2, cumulative totals), test_mind (goal/maintain/explore/ survive/reflect, prompt and snapshot), test_krang's session counter (append, torn tail, truncation). make check is nine suites; ASAN is green; the root integration still passes on a fresh debootstrap. Docs: AGENTS.md, README.md and docs/DESIGN.md; the latter maps the video's blueprint (body, drives, self-model, conductor, continuous feedback) to krang. --- .gitignore | 3 + AGENTS.md | 63 +++++++---- Makefile | 16 ++- README.md | 43 +++++++- docs/DESIGN.md | 38 +++++++ src/birth.c | 77 +++++++++++-- src/chat.c | 7 ++ src/daemon.c | 147 +++++++++++++++++++++---- src/httpd.c | 9 +- src/krang.h | 50 +++++++++ src/log.c | 1 + src/main.c | 5 + src/mind.c | 183 +++++++++++++++++++++++++++++++ src/replay.c | 254 +++++++++++++++++++++++++++++++++++++++++++ src/session.c | 93 +++++++++++++--- src/state.c | 29 +++-- src/util.c | 17 +++ tests/test_krang.c | 69 ++++++++++++ tests/test_mind.c | 195 +++++++++++++++++++++++++++++++++ tests/test_replay.c | 258 ++++++++++++++++++++++++++++++++++++++++++++ 20 files changed, 1486 insertions(+), 71 deletions(-) create mode 100644 src/mind.c create mode 100644 src/replay.c create mode 100644 tests/test_mind.c create mode 100644 tests/test_replay.c diff --git a/.gitignore b/.gitignore index b37a8a2..b8f02ec 100644 --- a/.gitignore +++ b/.gitignore @@ -8,6 +8,9 @@ /tests/test_sandbox /tests/test_sandbox_engine /tests/test_daemon +/tests/test_timeout +/tests/test_replay +/tests/test_mind # local configuration (only the example is tracked) /krang.conf diff --git a/AGENTS.md b/AGENTS.md index 43944bb..48d53f3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -17,14 +17,15 @@ 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 seven offline suites: config/birth/stuck/state/ +checkout and `make check` passes nine offline suites: config/birth/stuck/state/ HTTP/MCP, a real scripted engine turn, the dashboard and MCP sockets, Landlock plus seccomp, the engine running a turn with both layers active, `kdaemon_run` itself (temp state/workspace, script transport, one birth impulse, no -provider), and a turn cancelled by `max_turn_seconds`. 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. +provider), a turn cancelled by `max_turn_seconds`, a restart that resumes the +ledger and totals from the event log, and the conductor's drive selection. +The root-only phase (debootstrap, mount namespace, chroot, uid drop) is +exercised by `sudo tests/root-integration.sh`, which runs `--prepare-rootfs` +and `--sandbox-test` but never the autonomous daemon. Do not start the daemon as part of a code change. Verification is `make check`, `./krang --check --config krang.conf.example`, `./krang --self-test` and @@ -45,9 +46,11 @@ Do not start the daemon as part of a code change. Verification is `make check`, 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/replay.c restart: ledger, totals, stuck and blocked from the log + src/mind.c vitals and the conductor's competing drives src/httpd.c dashboard, HTTP API, MCP server (TCP and POST /mcp) docs/DESIGN.md prior art and the mapping to this loop - tests/ seven offline test binaries + root-integration.sh + tests/ nine offline test binaries + root-integration.sh `libkrang.a` is every source except `main.c`; the binary and the tests link it. The Makefile uses `SPLINTER ?= ../splinter`; the checkout is a sibling, not @@ -57,7 +60,7 @@ The Makefile uses `SPLINTER ?= ../splinter`; the checkout is a sibling, not make -C ../splinter # once, or after splinter changes make # krang + libkrang.a - make check # seven offline suites + make check # nine offline suites make check-asan # the same under ASAN/UBSAN ./krang --self-test # one scripted turn ./krang --check --config krang.conf.example # config + plan + turn @@ -70,8 +73,13 @@ HTTP routing; MCP tools/list and tools/call; the dashboard and MCP listeners on real sockets; HTTP Host/Origin refusal and token enforcement; Landlock denying a write outside the allowed set; seccomp denying `mount(2)` while fork/execve/network still work; a scripted engine turn with both layers active; -`kdaemon_run` with one birth impulse and a clean stop; and a turn cancelled by -`max_turn_seconds`. It needs no root, no network and no model. +`kdaemon_run` with one birth impulse and a clean stop; a turn cancelled by +`max_turn_seconds`; `kreplay_events()` rebuilding the ledger, totals, stuck +ladder and blocked clock from a synthetic log; a second `kdaemon_run` that +continues the same life with cumulative totals and impulse ids; the +incremental session counter across appends, a torn tail and truncation; and +the conductor choosing goal, maintain, explore and survive from measured +vitals. It needs no root, no network and no model. `tests/root-integration.sh` is the root-only proof: it runs `krang --prepare-rootfs` (debootstrap, network), then `krang --sandbox-test` @@ -94,6 +102,15 @@ An impulse is: cost, duration -> decide: continue now, sleep until T, or mark blocked +Before the prompt is assembled, the **conductor** measures the daemon's own +state - context against the window and the compaction threshold, cost against +the cap, stuck level, turn failures, impulse count, the age of `THREADS.md`, +session size - and lets five drives compete: `survive`, `reflect`, `maintain`, +`explore`, `goal`. The most urgent drive, its reason and the vitals are +injected into the impulse; the dashboard shows the same decision. This is the +internal state that gives an impulse a reason beyond the timer. The model still +chooses the action. + - No human prompt is required to start or continue. External input is an event in the queue, not the driver. - "Do nothing" is a legal outcome. Do not invent work to look busy. @@ -102,8 +119,10 @@ An impulse is: - 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. +- Persist session, goal, impulse ledger, totals and stuck counter. On restart, + resume from the event log; never silently start a new experiment. A restored + blocked goal keeps its hour of quiet, and three starts in five minutes back + off instead of spinning. - Every impulse records whether it was self-initiated or externally triggered. ## One session, one life @@ -140,7 +159,11 @@ session picker, no per-client conversation, no second engine. 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. + any rootfs. At startup `kreplay_events()` reads the event log once and + rebuilds the impulse ledger, token/cost/step totals, the last outcome, the + stuck ladder, the blocked clock and the recent-start count; the engine's + counters are added on top, so a restart does not make the dashboard look + younger than the life. - There is no user. krang never asks a human for permission or clarification, never waits for approval, never ends a turn expecting an answer, and never stops because a goal is finished. `autonomous` is always on and there is no @@ -367,14 +390,18 @@ both logs. Neither starts the autonomous daemon with a provider. - The dashboard/MCP have no TLS. Use loopback, an SSH tunnel, or a terminator. - `tests/root-integration.sh` is manual: it needs root and network and leaves the offline `make check` unchanged. Run it after touching the root phase. -- The impulse ledger, the stuck counter and the token/cost totals live in - memory. The event log keeps the history, but replay at startup is not - implemented; after a restart the dashboard's totals start again at zero. -- `ksession_meta()` counts the whole session file on every turn (via - `sp_session_count`). That is linear per turn and quadratic over a long life; - an incremental offset-based count is the fix. +- The conductor's thresholds are fixed constants (context 80%, cost 80%, notes + 30 minutes, explore every eighth impulse after twenty without a goal). They + are a designed policy, not learned; tuning them is an operator decision. +- `kreplay_events()` reads the whole event log once per start. That is one + linear pass, but the file grows forever; a segmented log would eventually be + the better shape. +- `ksession_history()` still reads the whole session file per API call; only + the per-turn record count is incremental. - HTTP chat (`POST /api/say`) blocks one connection thread until the turn finishes or `say_timeout` expires; MCP clients are better for long turns. +- The blocked/backoff resume branch is exercised through replay, not through a + live daemon restart (that would need a provider or a 300 s test). ## Open decisions diff --git a/Makefile b/Makefile index bd00853..811fd5b 100644 --- a/Makefile +++ b/Makefile @@ -21,12 +21,12 @@ TEST_RPATH = -Wl,-rpath,'$$ORIGIN/../../splinter' \ 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 + src/stuck.c src/state.c src/chat.c src/journal.c src/replay.c \ + src/mind.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 \ - tests/test_timeout + tests/test_timeout tests/test_replay tests/test_mind all: $(BIN) @@ -72,6 +72,14 @@ tests/test_timeout: tests/test_timeout.c $(LIB) $(CC) $(CFLAGS) $(CPPFLAGS) -o $@ tests/test_timeout.c $(LIB) \ $(LIBS) $(TEST_RPATH) +tests/test_replay: tests/test_replay.c $(LIB) + $(CC) $(CFLAGS) $(CPPFLAGS) -o $@ tests/test_replay.c $(LIB) \ + $(LIBS) $(TEST_RPATH) + +tests/test_mind: tests/test_mind.c $(LIB) + $(CC) $(CFLAGS) $(CPPFLAGS) -o $@ tests/test_mind.c $(LIB) \ + $(LIBS) $(TEST_RPATH) + check: $(TESTS) @echo "== tests/test_krang"; ./tests/test_krang @echo "== tests/test_engine"; ./tests/test_engine @@ -80,6 +88,8 @@ check: $(TESTS) @echo "== tests/test_sandbox_engine"; ./tests/test_sandbox_engine @echo "== tests/test_daemon"; ./tests/test_daemon @echo "== tests/test_timeout"; ./tests/test_timeout + @echo "== tests/test_replay"; ./tests/test_replay + @echo "== tests/test_mind"; ./tests/test_mind @echo "all tests passed" check-root: $(BIN) diff --git a/README.md b/README.md index 348db82..88c5988 100644 --- a/README.md +++ b/README.md @@ -49,9 +49,10 @@ 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. +- **Dashboard** `http://127.0.0.1:8096/` — state, goal, the conductor's drive + and reason, 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/`, `POST /mcp`. @@ -66,6 +67,37 @@ deliberate stop is `systemctl stop krang` (or SIGTERM). The model also gets `journal_search` (read-only): it searches the full session log, including the history compaction dropped. +## The conductor + +A timer alone is not a reason. Before every impulse the daemon measures its own +state - context against the window and the compaction threshold, cost against +the cap, stuck level, turn failures, impulse count, the age of `THREADS.md`, +session size - and lets five drives compete: + +| drive | when it wins | what the impulse is for | +| --- | --- | --- | +| `survive` | context or cost is near its limit | the smallest step; write down what compaction must not lose | +| `reflect` | the stuck ladder fired | find the mistake, change the approach | +| `maintain` | notes are missing or stale | bring `THREADS.md` and `skills/` up to date | +| `explore` | twenty impulses without a completed goal, then every eighth | try one new capability, bounded | +| `goal` | nothing more urgent | the smallest useful step on the goal | + +The chosen drive, its reason and the vitals go into the impulse and onto the +dashboard. The model still chooses the action; the conductor only chooses what +the turn is about. This is the engineering version of the body/drives/ +conductor loop: constraints produce drives, drives compete for attention, and +the consequences feed the next decision. + +## Restart + +The event log is the life, not a copy of it. At startup `kreplay_events()` +reads it once and rebuilds the impulse ledger (with ids), the token/cost/step +totals, the last outcome, the stuck ladder, the blocked clock and the +recent-start count. The engine's own counters are added on top, so the +dashboard never starts again at zero. A restored blocked goal keeps its hour +of quiet; three starts within five minutes back off instead of spinning. The +session is opened with `resume`, so there is no second birth. + 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 @@ -106,7 +138,10 @@ sudo tests/root-integration.sh # debootstrap + chroot + drop detection, the snapshot/HTTP/MCP surfaces (including the Host/Origin refusal and token check), a real scripted engine turn, the engine under Landlock + seccomp, `kdaemon_run` itself (one birth impulse on the script transport, then -a clean stop), and a turn cancelled by `max_turn_seconds`. The sandbox tests +a clean stop), a turn cancelled by `max_turn_seconds`, restart replay (ledger, +totals, stuck and blocked) with a second daemon run that continues the first, +incremental session counting across appends, a torn tail and truncation, and +the conductor's goal/maintain/explore/survive decisions. The sandbox tests prove Landlock denies a write outside the allowed set and seccomp denies `mount(2)` while fork/execve/network still work. diff --git a/docs/DESIGN.md b/docs/DESIGN.md index f10a039..3b2450a 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -57,6 +57,44 @@ 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. +## A conscious-machine blueprint, borrowed as control theory + +Video: ("How to BUILD a Conscious +Machine (No... Really!)", transcript read 2026-11-21). The argument, stripped +of the consciousness question: + +- A thermostat processes information but nothing matters to it. DishBrain + learned Pong because the stimulation was structured, not because it cared; + freeze the learning and invert the outputs and it keeps playing the old + policy. Learning a behaviour is not the same as continuously evaluating its + consequences. +- What is missing is a system that evaluates consequences against its own + internal state, decides what it needs to learn, and reorganizes its models. + That requires (1) a body with limited resources and states that can + deteriorate, (2) internal drives - energy, damage avoidance, exploration - + that compete, (3) a hierarchy of predictive models including a model of + itself, and (4) a conductor that monitors the subsystems, notices prediction + error and allocates attention. +- Consciousness, on that account, is something a system continuously does, not + something it has. + +krang is not a claim of consciousness and does not pretend to be one. The +control architecture, however, fits the experiment: + +| blueprint | krang | +| --- | --- | +| body with constraints | chroot, context window, token/cost caps, hourly impulses, rlimits, disk | +| competing drives | `survive`, `reflect`, `maintain`, `explore`, `goal` in `src/mind.c` | +| model of itself | the measured vitals, `THREADS.md`, `self/SYSTEM.md`, re-injected every impulse | +| prediction error | the stuck ladder, turn failures, the last outcome, the goal state | +| conductor | chooses the drive and writes the reason into the impulse | +| consequences feed back | the append-only event log, replayed at startup by `src/replay.c` | + +What is deliberately not taken: the claim that this produces experience, and +the idea that a bigger model is the missing ingredient. The missing ingredient +here is the loop: constraints, a reason to act, attention, and consequences +that survive a restart. + ## The difference The published agents are driven by a task, a game, or a conversation. krang is diff --git a/src/birth.c b/src/birth.c index 2e30635..bebc013 100644 --- a/src/birth.c +++ b/src/birth.c @@ -89,16 +89,21 @@ k_system_prompt(struct krang *k, struct sp_buf *out) "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"); + "are read before the next impulse.\n" + "A conductor chooses what each impulse is for - survive, maintain, " + "explore, reflect, or the goal - from your measured state. Follow " + "its focus first; the goal is still yours.\n"); append_self_prompt(out); } static void -append_threads(struct sp_buf *out) +append_threads(struct krang *k, struct sp_buf *out) { - char threads[4096]; + char threads[4096], path[700]; + const char *p; - read_text(KRANG_IN_THREADS, threads, sizeof(threads)); + p = kthreads_path(k, path, sizeof(path)); + read_text(p, threads, sizeof(threads)); if (threads[0] == '\0') return; (void)sp_buf_puts(out, "\nYour working notes (THREADS.md):\n"); @@ -106,15 +111,59 @@ append_threads(struct sp_buf *out) (void)sp_buf_puts(out, "\n"); } +static void +append_conductor(struct krang *k, struct sp_buf *out, + const struct kdecision *d, const struct kvitals *v) +{ + char notes[32]; + + if (v->threads_age < 0) + snprintf(notes, sizeof(notes), "missing"); + else + snprintf(notes, sizeof(notes), "%ldm old", + (v->threads_age + 59) / 60); + (void)sp_buf_puts(out, "\n[conductor]\n"); + (void)sp_buf_printf(out, "Drive: %s (urgency %d)\n", d->drive, + d->urgency); + (void)sp_buf_printf(out, "Why: %s\n", d->reason); + (void)sp_buf_printf(out, + "Vitals: context %d%% (%zu/%zu), compact %d%%, cost $%.4f, " + "hour %d/%d, stuck %d, failures %d, impulses %lu, tools %lu " + "(%lu failed), notes %s, session %.1f MB\n", + v->ctx_pct, k->st.ctx_used, k->st.ctx_max, v->compact_pct, + v->cost, k->hour_count, k->cfg.max_impulses_per_hour, + v->stuck_level, v->turn_failures, v->impulses, v->tool_calls, + v->tool_failures, notes, + (double)v->session_bytes / (1024.0 * 1024.0)); + (void)sp_buf_puts(out, kconductor_directive(d->drive)); + (void)sp_buf_puts(out, "\n"); +} + +static void +set_drive(struct krang *k, const struct kdecision *d) +{ + pthread_mutex_lock(&k->lock); + snprintf(k->st.drive, sizeof(k->st.drive), "%s", d->drive); + k->st.drive_urgency = d->urgency; + snprintf(k->st.drive_reason, sizeof(k->st.drive_reason), "%s", + d->reason); + pthread_mutex_unlock(&k->lock); +} + void k_impulse_prompt(struct krang *k, const char *cause, struct sp_buf *out) { + struct kvitals v; + struct kdecision d; char now[64], goal[KRANG_GOAL], gstate[16]; char last[KRANG_GOAL]; unsigned long pending; if (k == NULL || out == NULL) return; + kconductor_measure(k, &v); + kconductor_decide(k, &v, &d); + set_drive(k, &d); k_format_time(k_now(), now, sizeof(now)); pthread_mutex_lock(&k->lock); snprintf(goal, sizeof(goal), "%s", k->st.goal); @@ -139,7 +188,8 @@ k_impulse_prompt(struct krang *k, const char *cause, struct sp_buf *out) (void)sp_buf_printf(out, "Unread external messages: %lu (they are in the " "conversation)\n", pending); - append_threads(out); + append_conductor(k, out, &d, &v); + append_threads(k, 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 " @@ -152,8 +202,9 @@ k_impulse_prompt(struct krang *k, const char *cause, struct sp_buf *out) void k_selfcheck_prompt(struct krang *k, struct sp_buf *out) { + struct kdecision d; char goal[KRANG_GOAL], err[KRANG_ERR], tool[64], result[512]; - int level; + int level, attempts; if (k == NULL || out == NULL) return; @@ -163,9 +214,21 @@ k_selfcheck_prompt(struct krang *k, struct sp_buf *out) snprintf(tool, sizeof(tool), "%s", k->st.last_tool); snprintf(result, sizeof(result), "%s", k->st.last_tool_result); level = k->st.stuck_level; + attempts = k->st.stuck_attempts; pthread_mutex_unlock(&k->lock); + snprintf(d.drive, sizeof(d.drive), "reflect"); + d.urgency = 80 + level * 5 + attempts * 2; + if (d.urgency > 100) + d.urgency = 100; + snprintf(d.reason, sizeof(d.reason), + "stuck level %d after %d self-check(s)", level, attempts); + set_drive(k, &d); + (void)sp_buf_puts(out, "[self-check]\n"); + (void)sp_buf_puts(out, "[conductor]\n"); + (void)sp_buf_printf(out, "Drive: reflect (urgency %d)\n", d.urgency); + (void)sp_buf_printf(out, "Why: %s\n\n", d.reason); (void)sp_buf_puts(out, "Goal: "); (void)sp_buf_puts(out, goal[0] != '\0' ? goal : "(not set)"); (void)sp_buf_puts(out, "\n"); @@ -191,6 +254,6 @@ k_selfcheck_prompt(struct krang *k, struct sp_buf *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_threads(k, out); append_self_prompt(out); } diff --git a/src/chat.c b/src/chat.c index f84e68b..a0ea478 100644 --- a/src/chat.c +++ b/src/chat.c @@ -91,6 +91,13 @@ kchat_complete(struct krang *k, unsigned long id, const char *answer, int rc) k->st.chat_out++; if (k->st.chat_pending > 0) k->st.chat_pending--; + { + char rcbuf[16]; + + snprintf(rcbuf, sizeof(rcbuf), "%d", rc); + klog_emit(&k->log, "chat_out", "rc", rcbuf, + "answer", answer != NULL ? answer : "", NULL); + } break; } pthread_cond_broadcast(&k->cond); diff --git a/src/daemon.c b/src/daemon.c index 0dcdc85..8ec340b 100644 --- a/src/daemon.c +++ b/src/daemon.c @@ -48,6 +48,17 @@ set_state(struct krang *k, const char *state) pthread_mutex_unlock(&k->lock); } +static void +set_drive_state(struct krang *k, const char *drive, int urgency, + const char *reason) +{ + pthread_mutex_lock(&k->lock); + snprintf(k->st.drive, sizeof(k->st.drive), "%s", drive); + k->st.drive_urgency = urgency; + snprintf(k->st.drive_reason, sizeof(k->st.drive_reason), "%s", reason); + pthread_mutex_unlock(&k->lock); +} + static int obs_is_error(const char *obs) { @@ -119,20 +130,24 @@ session_refresh(struct krang *k) } static void -record_impulse(struct krang *k, const char *cause, int rc, +record_impulse(struct krang *k, unsigned long id, int rc, unsigned long steps, unsigned long calls, unsigned long tokens_in, unsigned long tokens_out, double cost, const char *answer) { struct kimpulse *imp; - unsigned long id; pthread_mutex_lock(&k->lock); - id = ++k->impulse_seq; + if (id == 0 || id > k->impulse_seq) { + id = ++k->impulse_seq; + imp = &k->impulses[(id - 1) % KRANG_IMPULSE_RING]; + memset(imp, 0, sizeof(*imp)); + imp->id = id; + imp->at = k_now(); + } 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); + if (imp->at == 0) + imp->at = k_now(); imp->rc = rc; imp->steps = steps; imp->tool_calls = calls; @@ -144,6 +159,16 @@ record_impulse(struct krang *k, const char *cause, int rc, pthread_mutex_unlock(&k->lock); } +static void +log_stuck(struct krang *k) +{ + char lvl[16], att[16]; + + snprintf(lvl, sizeof(lvl), "%d", k->stuck.level); + snprintf(att, sizeof(att), "%d", k->stuck.attempts); + klog_emit(&k->log, "stuck", "level", lvl, "attempts", att, NULL); +} + void kengine_close(struct krang *k) { @@ -325,7 +350,7 @@ krun_turn(struct krang *k, const char *prompt, const char *cause, struct sp_event ev; int rc = -1, saw_end = 0, idle_guard = 0, timed_out = 0; unsigned long steps = 0, calls = 0; - unsigned long tin0, tout0, d_in, d_out; + unsigned long tin0, tout0, cached0, d_in, d_out, d_cached, impulse_id; double cost0, d_cost; long started; int mutating = 0; @@ -338,6 +363,7 @@ krun_turn(struct krang *k, const char *prompt, const char *cause, pthread_mutex_lock(&k->lock); tin0 = k->st.tokens_in; tout0 = k->st.tokens_out; + cached0 = k->st.tokens_cached; cost0 = k->st.cost; pthread_mutex_unlock(&k->lock); started = k_now(); @@ -349,7 +375,9 @@ krun_turn(struct krang *k, const char *prompt, const char *cause, return -1; } pthread_mutex_lock(&k->lock); + impulse_id = ++k->impulse_seq; k->st.impulses++; + k->run_impulses++; if (is_external) k->st.external_impulses++; else @@ -358,9 +386,30 @@ krun_turn(struct krang *k, const char *prompt, const char *cause, snprintf(k->st.state, sizeof(k->st.state), "thinking"); copy_trunc(k->last_prompt, sizeof(k->last_prompt), prompt, sizeof(k->last_prompt) - 1); + { + struct kimpulse *imp = + &k->impulses[(impulse_id - 1) % KRANG_IMPULSE_RING]; + + memset(imp, 0, sizeof(*imp)); + imp->id = impulse_id; + imp->at = k->st.last_impulse_at; + snprintf(imp->cause, sizeof(imp->cause), "%s", + cause != NULL ? cause : "timer"); + } pthread_mutex_unlock(&k->lock); - klog_emit(&k->log, "impulse_start", "cause", - cause != NULL ? cause : "timer", "prompt", prompt, NULL); + { + char idbuf[32], drv[16], urg[8]; + + pthread_mutex_lock(&k->lock); + snprintf(drv, sizeof(drv), "%s", k->st.drive); + snprintf(urg, sizeof(urg), "%d", k->st.drive_urgency); + pthread_mutex_unlock(&k->lock); + snprintf(idbuf, sizeof(idbuf), "%lu", impulse_id); + klog_emit(&k->log, "impulse_start", "impulse", idbuf, + "cause", cause != NULL ? cause : "timer", + "drive", drv[0] != '\0' ? drv : "-", "urgency", urg, + "prompt", prompt, NULL); + } for (;;) { int got = 0; @@ -420,6 +469,8 @@ krun_turn(struct krang *k, const char *prompt, const char *cause, pthread_mutex_lock(&k->lock); d_in = k->st.tokens_in >= tin0 ? k->st.tokens_in - tin0 : 0; d_out = k->st.tokens_out >= tout0 ? k->st.tokens_out - tout0 : 0; + d_cached = k->st.tokens_cached >= cached0 ? + k->st.tokens_cached - cached0 : 0; d_cost = k->st.cost >= cost0 ? k->st.cost - cost0 : 0.0; k->st.turns++; k->st.last_turn_rc = rc; @@ -449,6 +500,9 @@ krun_turn(struct krang *k, const char *prompt, const char *cause, k->turn_failures = 0; } kstuck_turn(&k->stuck, rc, calls, mutating); + if (k->stuck.level != k->st.stuck_level || + k->stuck.attempts != k->st.stuck_attempts) + log_stuck(k); pthread_mutex_lock(&k->lock); k->st.stuck_level = k->stuck.level; k->st.stuck_attempts = k->stuck.attempts; @@ -456,7 +510,10 @@ krun_turn(struct krang *k, const char *prompt, const char *cause, if (answer[0] != '\0' && strstr(answer, "GOAL_COMPLETE") != NULL) { struct sp_buf e; + char gid[32]; + k->last_goal_impulse = impulse_id; + snprintf(gid, sizeof(gid), "%lu", impulse_id); sp_buf_init(&e); if (sp_session_set_goal_state(k->session_dir, KRANG_SESSION_ID, "succeeded", &e) == 0) { @@ -466,7 +523,7 @@ krun_turn(struct krang *k, const char *prompt, const char *cause, k->st.goal_completes++; pthread_mutex_unlock(&k->lock); klog_emit(&k->log, "goal_complete", "goal", - k->st.goal, NULL); + k->st.goal, "impulse", gid, NULL); } sp_buf_free(&e); } @@ -476,16 +533,22 @@ krun_turn(struct krang *k, const char *prompt, const char *cause, snprintf(num, sizeof(num), "%d", rc); snprintf(cost, sizeof(cost), "%.6f", d_cost); { - char sk[32], sc[32]; + char sk[32], sc[32], idbuf[32], comp[32], est[32], cac[32]; snprintf(sk, sizeof(sk), "%lu", steps); snprintf(sc, sizeof(sc), "%lu", calls); + snprintf(idbuf, sizeof(idbuf), "%lu", impulse_id); + snprintf(comp, sizeof(comp), "%lu", k->st.compactions); + snprintf(est, sizeof(est), "%lu", k->st.steps); + snprintf(cac, sizeof(cac), "%lu", d_cached); klog_emit(&k->log, "turn_end", "rc", num, "steps", sk, "calls", sc, "tokens_in", tok, "tokens_out", tout, - "cost", cost, "cause", cause != NULL ? cause : "timer", + "tokens_cached", cac, "cost", cost, "impulse", idbuf, + "compactions", comp, "engine_steps", est, + "cause", cause != NULL ? cause : "timer", "answer", answer, "error", error, NULL); } - record_impulse(k, cause, rc, steps, calls, d_in, d_out, d_cost, + record_impulse(k, impulse_id, rc, steps, calls, d_in, d_out, d_cost, answer); if (chat != NULL) { @@ -638,11 +701,25 @@ kdaemon_run(struct krang *k) sp_buf_free(&sp); } + if (kreplay_events(k, k->last_error, sizeof(k->last_error)) != 0) + fprintf(stderr, "krang: replay: %s\n", k->last_error); + 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 (newborn && k->restored.impulses > 0) { + char n[32]; + + /* the event log remembers a life the session no longer has */ + snprintf(n, sizeof(n), "%lu", k->restored.impulses); + klog_emit(&k->log, "session_reset", "restored_impulses", n, + NULL); + fprintf(stderr, + "krang: the session is empty but the event log has %lu " + "impulses; starting the newborn\n", k->restored.impulses); + } if (kengine_open(k, k->script[0] != '\0' ? k->script : NULL, k->last_error, sizeof(k->last_error)) != 0) { @@ -676,6 +753,7 @@ kdaemon_run(struct krang *k) if (newborn) { struct sp_buf birth; + set_drive_state(k, "birth", 100, "the first impulse"); sp_buf_init(&birth); k_birth_prompt(&k->cfg, &birth); klog_emit(&k->log, "birth", "goal", goal, NULL); @@ -684,10 +762,37 @@ kdaemon_run(struct krang *k) 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); + long now = k_now(); + + /* + * A restart resumes the life, not a fresh experiment: if the + * restored goal was blocked, keep the hour of quiet; if the + * process keeps dying, back off instead of spinning. + */ + if (k->stuck.level >= 3 && k->last_blocked_at > 0 && + now < k->last_blocked_at + 3600) { + k->next_at = k->last_blocked_at + 3600; + pthread_mutex_lock(&k->lock); + k->st.next_impulse_at = k->next_at; + snprintf(k->st.state, sizeof(k->st.state), "blocked"); + pthread_mutex_unlock(&k->lock); + klog_emit(&k->log, "blocked_resumed", "unsilence_at", + "the restored goal is still blocked", NULL); + } else if (k->recent_starts >= 3) { + k->next_at = now + 300; + pthread_mutex_lock(&k->lock); + k->st.next_impulse_at = k->next_at; + snprintf(k->st.state, sizeof(k->st.state), + "sleeping"); + pthread_mutex_unlock(&k->lock); + klog_emit(&k->log, "restart_backoff", "starts", + "three starts within five minutes", NULL); + } else { + k->next_at = now; /* a restart continues */ + pthread_mutex_lock(&k->lock); + k->st.next_impulse_at = k->next_at; + pthread_mutex_unlock(&k->lock); + } } while (!krang_stop && !k->stop) { @@ -696,7 +801,7 @@ kdaemon_run(struct krang *k) pthread_mutex_lock(&k->lock); if (k->max_impulses > 0 && - k->st.impulses >= k->max_impulses) { + k->run_impulses >= k->max_impulses) { k->stop = 1; pthread_mutex_unlock(&k->lock); break; @@ -712,6 +817,7 @@ kdaemon_run(struct krang *k) continue; } k->hour_count++; + set_drive_state(k, "chat", 0, "an external message"); set_state(k, "thinking"); (void)krun_turn(k, chat->text, "chat", chat); schedule_next(k, 0); @@ -736,6 +842,7 @@ kdaemon_run(struct krang *k) continue; level = kstuck_should_check(&k->stuck, now); if (level > 0) { + log_stuck(k); pthread_mutex_lock(&k->lock); k->st.stuck_level = k->stuck.level; k->st.stuck_attempts = k->stuck.attempts; @@ -760,8 +867,12 @@ kdaemon_run(struct krang *k) } sp_buf_free(&prompt); if (kstuck_level(&k->stuck) >= 3) { + k->stuck.level = 3; + log_stuck(k); pthread_mutex_lock(&k->lock); k->st.blocked_events++; + k->st.stuck_level = 3; + k->st.stuck_attempts = k->stuck.attempts; snprintf(k->st.state, sizeof(k->st.state), "blocked"); pthread_mutex_unlock(&k->lock); diff --git a/src/httpd.c b/src/httpd.c index 5bed294..d5c6286 100644 --- a/src/httpd.c +++ b/src/httpd.c @@ -438,8 +438,12 @@ dashboard(struct krang *k, struct sp_buf *out) "..." "uptime -" "born -" + "drive -" "model -" - "
goal ...
" + "
" + "
goal ...
" + "
" + "
" "
" "
-
" "
impulses
" @@ -512,6 +516,9 @@ dashboard(struct krang *k, struct sp_buf *out) "E('records',s.session.records);E('compactions',s.compactions);" "E('selfedits',s.self_edits);E('goals',s.goal_completes);" "E('chatcount',s.chat.in+' / '+s.chat.out);" + "E('drive',((s.drive&&s.drive.name)||'goal')+' '+" + "((s.drive&&s.drive.urgency)||''));" + "E('drivereason',(s.drive&&s.drive.reason)||'-');" "E('stuck',s.stuck.level);E('outcome',s.last_outcome||'-');" "E('error',s.last_error||'-');" "E('sandbox',JSON.stringify(s.sandbox,null,1));" diff --git a/src/krang.h b/src/krang.h index 9028342..a20a2b4 100644 --- a/src/krang.h +++ b/src/krang.h @@ -135,6 +135,10 @@ struct kstats { unsigned long goal_completes; unsigned long self_edits; + char drive[16]; /* the conductor's current focus */ + int drive_urgency; + char drive_reason[192]; + int busy; int waiting; @@ -190,6 +194,7 @@ struct klog { pthread_mutex_t lock; unsigned long seq; unsigned long long bytes; + char path[KRANG_PATH]; /* for replay at startup */ char secret[512]; /* redacted from every value */ struct kentry ring[KRANG_EVENT_RING]; size_t head; /* next slot */ @@ -236,6 +241,13 @@ struct krang { int stop; struct kstats st; + struct kstats restored; /* restored from the event log */ + unsigned long run_impulses; /* started by this process */ + unsigned long last_goal_impulse; + unsigned long long sess_off; /* session bytes already counted */ + unsigned long sess_records; + long last_blocked_at; + int recent_starts; /* starts in the last 5 minutes */ struct kimpulse impulses[KRANG_IMPULSE_RING]; unsigned long impulse_seq; @@ -353,6 +365,44 @@ 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); + +/* ---------------------------------------------------------------- replay */ + +int kreplay_events(struct krang *k, char *err, size_t errlen); + +/* ------------------------------------------------------------------ mind */ + +struct kvitals { + int ctx_pct; /* of ctx_max */ + int compact_pct; /* of compact_threshold */ + int cost_pct; /* of max_cost, 0 when no cap */ + int hour_pct; /* of max_impulses_per_hour */ + int stuck_level; + int turn_failures; + unsigned long impulses; + unsigned long turns; + unsigned long tool_calls; + unsigned long tool_failures; + unsigned long self_edits; + unsigned long goal_completes; + unsigned long impulses_since_goal; + unsigned long long session_bytes; + double cost; + long threads_age; /* seconds; -1 when THREADS.md is missing */ + size_t threads_bytes; +}; + +struct kdecision { + char drive[16]; + int urgency; + char reason[192]; +}; + +void kconductor_measure(struct krang *k, struct kvitals *v); +void kconductor_decide(struct krang *k, const struct kvitals *v, + struct kdecision *d); +const char *kconductor_directive(const char *drive); +const char *kthreads_path(struct krang *k, char *buf, size_t cap); int krun_turn(struct krang *k, const char *prompt, const char *cause, struct kchat *chat); diff --git a/src/log.c b/src/log.c index 2f7cd05..6828bd5 100644 --- a/src/log.c +++ b/src/log.c @@ -132,6 +132,7 @@ klog_open(struct klog *l, const char *path, char *err, size_t errlen) memset(l, 0, sizeof(*l)); l->fd = -1; pthread_mutex_init(&l->lock, NULL); + snprintf(l->path, sizeof(l->path), "%s", path); l->fd = open(path, O_RDWR | O_CREAT | O_APPEND | O_NOFOLLOW | O_CLOEXEC, 0600); if (l->fd < 0) { diff --git a/src/main.c b/src/main.c index bcfd2d7..c7df3a5 100644 --- a/src/main.c +++ b/src/main.c @@ -83,8 +83,12 @@ self_test(const char *config_path, int require_config) goto out; } snprintf(k.session_dir, sizeof(k.session_dir), "%s/sessions", dir); + snprintf(k.cfg.workspace, sizeof(k.cfg.workspace), "%s/workspace", + dir); snprintf(logpath, sizeof(logpath), "%s/events.jsonl", dir); (void)mkdir(k.session_dir, 0700); + (void)mkdir(k.cfg.workspace, 0700); + k.cfg.no_sandbox = 1; /* the self-test is hermetic, not a daemon */ if (klog_open(&k.log, logpath, k.last_error, sizeof(k.last_error)) != 0) { fprintf(stderr, "krang: %s\n", k.last_error); @@ -151,6 +155,7 @@ sandbox_test(struct krang *k) "krang: --sandbox-test must start as root; it drops itself\n"); return 1; } + (void)mkdir(k->cfg.state_dir, 0755); snprintf(path, sizeof(path), "%s/sandbox-script.txt", k->cfg.state_dir); f = fopen(path, "w"); diff --git a/src/mind.c b/src/mind.c new file mode 100644 index 0000000..c4a4693 --- /dev/null +++ b/src/mind.c @@ -0,0 +1,183 @@ +/* + * krang -- the conductor: what deserves the next impulse. + * + * Copyright (c) 2026 Konrad Lother + * License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree. + * + * One goal is not a mind. A system that only ever pursues the goal, or only + * ever reacts to errors, has no reason to keep its notes honest, no reason to + * explore, and no reason to conserve when the budget is nearly gone. This + * module measures the daemon's own state (the "vitals") and lets a small set + * of competing drives decide what the next impulse is for. The model still + * decides what to do; the conductor only decides what the turn is about. + * + * The analogy is engineering, not a claim of consciousness: constraints + * produce drives, drives compete for attention, and the consequences feed + * back into the next decision. That is the loop this project is testing. + */ +#include +#include +#include +#include +#include + +#include "krang.h" + +static int +percent(unsigned long used, unsigned long max) +{ + unsigned long long p; + + if (max == 0) + return 0; + p = (unsigned long long)used * 100ULL / max; + return p > 100 ? 100 : (int)p; +} + +void +kconductor_measure(struct krang *k, struct kvitals *v) +{ + struct stat st; + char path[700]; + const char *threads; + + if (k == NULL || v == NULL) + return; + memset(v, 0, sizeof(*v)); + pthread_mutex_lock(&k->lock); + v->impulses = k->st.impulses; + v->turns = k->st.turns; + v->tool_calls = k->st.tool_calls; + v->tool_failures = k->st.tool_failures; + v->self_edits = k->st.self_edits; + v->goal_completes = k->st.goal_completes; + v->session_bytes = k->st.session_bytes; + v->cost = k->st.cost; + v->stuck_level = k->st.stuck_level; + v->ctx_pct = percent(k->st.ctx_used, k->st.ctx_max); + v->compact_pct = k->cfg.compact_threshold > 0 ? + percent(k->st.ctx_used, (unsigned long)k->cfg.compact_threshold) : + 0; + v->cost_pct = k->cfg.max_cost > 0.0 ? + (int)(100.0 * k->st.cost / k->cfg.max_cost) : 0; + v->hour_pct = percent((unsigned long)k->hour_count, + (unsigned long)k->cfg.max_impulses_per_hour); + v->impulses_since_goal = k->st.impulses >= k->last_goal_impulse ? + k->st.impulses - k->last_goal_impulse : 0; + v->turn_failures = k->turn_failures; + pthread_mutex_unlock(&k->lock); + + threads = kthreads_path(k, path, sizeof(path)); + if (stat(threads, &st) == 0) { + long now = k_now(); + + v->threads_age = now > (long)st.st_mtime ? + now - (long)st.st_mtime : 0; + v->threads_bytes = (size_t)st.st_size; + } else { + v->threads_age = -1; + } +} + +void +kconductor_decide(struct krang *k, const struct kvitals *v, + struct kdecision *d) +{ + int us = 0, um = 0, ue = 0; + char rs[192] = "", rm[192] = "", re[192] = ""; + + (void)k; + if (d == NULL || v == NULL) + return; + + if (v->ctx_pct >= 80) { + us = 60 + v->ctx_pct - 80; + snprintf(rs, sizeof(rs), + "context at %d%% of the window; compaction is close", + v->ctx_pct); + } + if (v->compact_pct >= 80 && 60 + v->compact_pct - 80 > us) { + us = 60 + v->compact_pct - 80; + snprintf(rs, sizeof(rs), + "context at %d%% of the compaction threshold", + v->compact_pct); + } + if (v->cost_pct >= 80 && 70 + v->cost_pct - 80 > us) { + us = 70 + v->cost_pct - 80; + snprintf(rs, sizeof(rs), "cost at %d%% of the budget", + v->cost_pct); + } + if (v->threads_age < 0) { + if (v->impulses >= 3) { + um = 50 + (v->impulses > 20 ? 20 : + (int)v->impulses - 3); + snprintf(rm, sizeof(rm), + "THREADS.md is missing after %lu impulses", + v->impulses); + } + } else if (v->threads_age > 1800) { + long extra = (v->threads_age - 1800) / 600; + + um = 40 + (extra > 30 ? 30 : (int)extra); + snprintf(rm, sizeof(rm), + "THREADS.md has not changed in %ld minutes", + (v->threads_age + 59) / 60); + } + /* + * Exploration is a drive, not the default: every eighth impulse after + * twenty without a completed goal, so a long goal still gets room but + * the world does not become invisible. + */ + if (v->impulses_since_goal >= 20 && + (v->impulses_since_goal - 20) % 8 == 0) { + ue = 45; + snprintf(re, sizeof(re), + "%lu impulses since the last completed goal", + v->impulses_since_goal); + } + + snprintf(d->drive, sizeof(d->drive), "goal"); + d->urgency = 30; + snprintf(d->reason, sizeof(d->reason), + "the goal is open; take the smallest useful next step"); + if (um > d->urgency) { + snprintf(d->drive, sizeof(d->drive), "maintain"); + d->urgency = um; + snprintf(d->reason, sizeof(d->reason), "%s", rm); + } + if (ue > d->urgency) { + snprintf(d->drive, sizeof(d->drive), "explore"); + d->urgency = ue; + snprintf(d->reason, sizeof(d->reason), "%s", re); + } + if (us > d->urgency) { + snprintf(d->drive, sizeof(d->drive), "survive"); + d->urgency = us; + snprintf(d->reason, sizeof(d->reason), "%s", rs); + } +} + +const char * +kconductor_directive(const char *drive) +{ + if (drive == NULL) + return ""; + if (strcmp(drive, "survive") == 0) + return "Conserve. Do the smallest useful step; do not start a " + "large read or a long build. Put what matters into " + "THREADS.md now, so compaction cannot lose it."; + if (strcmp(drive, "maintain") == 0) + return "Maintain. Bring THREADS.md up to date - the goal, what " + "is true now, the open threads - and move one reusable " + "procedure into skills/. Do not open new work until the " + "notes are honest."; + if (strcmp(drive, "explore") == 0) + return "Explore. Try one capability you have not used, or map " + "a part of your world you have not inspected. Keep it " + "bounded and record what you learned."; + if (strcmp(drive, "reflect") == 0) + return "Reflect. Find the mistake in the last turns, state " + "the smallest different action, and take it."; + return "Pursue the goal. Take the smallest useful next action, " + "observe the result, and continue."; +} diff --git a/src/replay.c b/src/replay.c new file mode 100644 index 0000000..e15ee0a --- /dev/null +++ b/src/replay.c @@ -0,0 +1,254 @@ +/* + * krang -- restarting without starting a new experiment. + * + * Copyright (c) 2026 Konrad Lother + * License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree. + * + * The event log is the experiment, not a copy of it. When the daemon starts, + * this reads the append-only log once and reconstructs the impulse ledger, the + * cumulative totals, the last outcome, the stuck ladder and the blocked clock. + * The engine's own counters start at zero on every open; the surfaces add the + * restored base to them, so a restart does not make the life look younger. + */ +#include +#include +#include +#include + +#include "krang.h" +#include "mcp.h" + +static unsigned long +arg_ulong(const mcp_json *v, const char *key) +{ + const char *s = mcp_arg_string(v, key); + + if (s != NULL && *s != '\0') + return (unsigned long)strtoul(s, NULL, 10); + return (unsigned long)mcp_arg_num(v, key, 0); +} + +static long +arg_long(const mcp_json *v, const char *key) +{ + const char *s = mcp_arg_string(v, key); + + if (s != NULL && *s != '\0') + return strtol(s, NULL, 10); + return (long)mcp_arg_num(v, key, 0); +} + +static double +arg_cost(const mcp_json *v, const char *key) +{ + const char *s = mcp_arg_string(v, key); + + if (s != NULL && *s != '\0') + return strtod(s, NULL); + return mcp_arg_num(v, key, 0); +} + +static int +replay_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, "/self") != NULL || + strstr(args, "/skills") != NULL; +} + +static void +put_impulse(struct krang *k, unsigned long id, long at, const char *cause, + int rc, unsigned long steps, unsigned long calls, unsigned long tin, + unsigned long tout, double cost, const char *answer) +{ + struct kimpulse *imp; + + if (id == 0) + id = k->impulse_seq + 1; + if (id > k->impulse_seq) + k->impulse_seq = id; + imp = &k->impulses[(id - 1) % KRANG_IMPULSE_RING]; + memset(imp, 0, sizeof(*imp)); + imp->id = id; + imp->at = at; + snprintf(imp->cause, sizeof(imp->cause), "%s", + cause != NULL ? cause : "timer"); + imp->rc = rc; + imp->steps = steps; + imp->tool_calls = calls; + imp->tokens_in = tin; + imp->tokens_out = tout; + imp->cost = cost; + snprintf(imp->answer, sizeof(imp->answer), "%s", + answer != NULL ? answer : ""); +} + +int +kreplay_events(struct krang *k, char *err, size_t errlen) +{ + FILE *f; + char *line = NULL; + size_t cap = 0; + long now = k_now(); + unsigned long pending_id = 0; + long pending_at = 0; + char pending_cause[32] = ""; + struct kstats *b; + + if (k == NULL) + return -1; + b = &k->restored; + memset(b, 0, sizeof(*b)); + memset(k->impulses, 0, sizeof(k->impulses)); + k->impulse_seq = 0; + k->last_blocked_at = 0; + k->recent_starts = 0; + k->stuck.level = 0; + k->stuck.attempts = 0; + + if (k->log.path[0] == '\0') { + k->st = *b; + return 0; + } + f = fopen(k->log.path, "r"); + if (f == NULL) { + if (errno == ENOENT) { + k->st = *b; + return 0; + } + snprintf(err, errlen, "cannot read %s: %s", k->log.path, + strerror(errno)); + return -1; + } + while (getline(&line, &cap, f) > 0) { + mcp_json *v; + const char *kind; + + k_trim(line); + if (line[0] != '{') + continue; + v = mcp_parse(line); + if (v == NULL) + continue; + kind = mcp_arg_string(v, "kind"); + if (kind == NULL) { + mcp_json_free(v); + continue; + } + if (strcmp(kind, "impulse_start") == 0) { + unsigned long id = arg_ulong(v, "impulse"); + const char *cause = mcp_arg_string(v, "cause"); + + if (id == 0) + id = k->impulse_seq + 1; + b->impulses++; + if (cause != NULL && strcmp(cause, "chat") == 0) + b->external_impulses++; + else + b->self_impulses++; + if (cause != NULL && strcmp(cause, "self-check") == 0) + b->stuck_events++; + pending_id = id; + pending_at = (long)mcp_arg_num(v, "ts", 0); + snprintf(pending_cause, sizeof(pending_cause), "%s", + cause != NULL ? cause : "timer"); + put_impulse(k, id, pending_at, pending_cause, 0, + 0, 0, 0, 0, 0.0, ""); + } else if (strcmp(kind, "turn_end") == 0) { + unsigned long id = arg_ulong(v, "impulse"); + unsigned long steps = arg_ulong(v, "steps"); + unsigned long calls = arg_ulong(v, "calls"); + unsigned long tin = arg_ulong(v, "tokens_in"); + unsigned long tout = arg_ulong(v, "tokens_out"); + unsigned long tcac = arg_ulong(v, "tokens_cached"); + unsigned long comp = arg_ulong(v, "compactions"); + unsigned long esteps = arg_ulong(v, "engine_steps"); + double cost = arg_cost(v, "cost"); + int rc = (int)arg_long(v, "rc"); + const char *cause = mcp_arg_string(v, "cause"); + const char *answer = mcp_arg_string(v, "answer"); + const char *error = mcp_arg_string(v, "error"); + + if (id == 0) + id = pending_id; + if (cause == NULL || *cause == '\0') + cause = pending_cause[0] != '\0' ? + pending_cause : "timer"; + b->turns++; + if (mcp_arg(v, "engine_steps") != NULL) { + /* a session total, not a per-turn delta */ + if (esteps > b->steps) + b->steps = esteps; + } else { + b->steps += steps; /* old log */ + } + b->tokens_in += tin; + b->tokens_out += tout; + b->tokens_cached += tcac; + b->cost += cost; + b->last_turn_rc = rc; + if (comp > b->compactions) + b->compactions = comp; + if (answer != NULL && *answer != '\0') + snprintf(b->last_outcome, + sizeof(b->last_outcome), "%s", answer); + else if (error != NULL && *error != '\0') + snprintf(b->last_outcome, + sizeof(b->last_outcome), "error: %s", + error); + if (error != NULL && *error != '\0') + snprintf(b->last_error, sizeof(b->last_error), + "%s", error); + put_impulse(k, id, + pending_at != 0 ? pending_at : + (long)mcp_arg_num(v, "ts", 0), cause, rc, steps, + calls, tin, tout, cost, answer); + pending_id = 0; + pending_cause[0] = '\0'; + } else if (strcmp(kind, "tool") == 0) { + b->tool_calls++; + if (replay_self_edit(mcp_arg_string(v, "name"), + mcp_arg_string(v, "args"))) + b->self_edits++; + } else if (strcmp(kind, "tool_result") == 0) { + const char *ok = mcp_arg_string(v, "ok"); + + if (ok != NULL && strcmp(ok, "0") == 0) + b->tool_failures++; + } else if (strcmp(kind, "approval_denied") == 0) { + b->denials++; + } else if (strcmp(kind, "goal_complete") == 0) { + unsigned long gid = arg_ulong(v, "impulse"); + + b->goal_completes++; + if (gid > 0) + k->last_goal_impulse = gid; + } else if (strcmp(kind, "blocked") == 0) { + b->blocked_events++; + k->last_blocked_at = (long)mcp_arg_num(v, "ts", 0); + } else if (strcmp(kind, "stuck") == 0) { + k->stuck.level = (int)arg_long(v, "level"); + k->stuck.attempts = (int)arg_long(v, "attempts"); + } else if (strcmp(kind, "chat_in") == 0) { + b->chat_in++; + } else if (strcmp(kind, "chat_out") == 0) { + b->chat_out++; + } else if (strcmp(kind, "start") == 0) { + long ts = (long)mcp_arg_num(v, "ts", 0); + + if (ts > 0 && now - ts <= 300) + k->recent_starts++; + } + mcp_json_free(v); + } + free(line); + fclose(f); + + k->st = *b; + k->st.stuck_level = k->stuck.level; + k->st.stuck_attempts = k->stuck.attempts; + return 0; +} diff --git a/src/session.c b/src/session.c index 0df0945..bd8ebf0 100644 --- a/src/session.c +++ b/src/session.c @@ -5,13 +5,77 @@ * License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree. */ #include +#include #include #include #include #include +#include #include "krang.h" +/* + * The session log is append-only and outlives every process. Counting it with + * sp_session_count() on every turn is linear per turn and quadratic over a + * long life, so scan only the bytes that arrived since the last look. The + * offset stops at the last newline: a torn tail is recounted, never silently + * accepted as a record. + */ +static pthread_mutex_t sess_count_lock = PTHREAD_MUTEX_INITIALIZER; + +static int +count_new_records(struct krang *k, const char *path, + unsigned long long size, size_t *records, char *err, size_t errlen) +{ + int fd; + char buf[8192]; + unsigned long long off, last_nl = 0; + unsigned long count = 0; + int saw_nl = 0; + + pthread_mutex_lock(&sess_count_lock); + if (size < k->sess_off) { + /* truncated or replaced: what was counted is gone */ + k->sess_off = 0; + k->sess_records = 0; + } + off = k->sess_off; + if (size > off) { + fd = open(path, O_RDONLY); + if (fd < 0) { + snprintf(err, errlen, "cannot read %s: %s", path, + strerror(errno)); + pthread_mutex_unlock(&sess_count_lock); + return -1; + } + while (off < size) { + ssize_t n; + size_t i; + + n = pread(fd, buf, sizeof(buf), (off_t)off); + if (n < 0 && errno == EINTR) + continue; + if (n <= 0) + break; + for (i = 0; i < (size_t)n; i++) { + if (buf[i] != '\n') + continue; + count++; + last_nl = off + i + 1; + saw_nl = 1; + } + off += (unsigned long long)n; + } + close(fd); + if (saw_nl) + k->sess_off = last_nl; + k->sess_records += count; + } + *records = k->sess_records; + pthread_mutex_unlock(&sess_count_lock); + return 0; +} + static void session_info(struct krang *k, struct sp_session_info *si) { @@ -28,8 +92,7 @@ ksession_meta(struct krang *k, size_t *records, unsigned long long *bytes, { struct sp_session_info si; struct stat st; - char path[640]; - struct sp_buf err; + char path[640], err[512]; if (k == NULL) return -1; @@ -42,18 +105,22 @@ ksession_meta(struct krang *k, size_t *records, unsigned long long *bytes, 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 (stat(path, &st) == 0) { + if (bytes != NULL) + *bytes = (unsigned long long)st.st_size; + if (records != NULL) { + size_t n = 0; + + if (count_new_records(k, path, + (unsigned long long)st.st_size, &n, err, + sizeof(err)) == 0) + *records = n; + } + } else if (records != NULL) { + /* a missing session has no records; drop a stale prefix */ + count_new_records(k, path, 0, records, err, sizeof(err)); + } if (goal != NULL && goalcap > 0) (void)sp_session_get_goal(si.dir, si.id, goal, goalcap); if (gstate != NULL && gstatecap > 0) diff --git a/src/state.c b/src/state.c index 176f09d..c29dd3b 100644 --- a/src/state.c +++ b/src/state.c @@ -60,15 +60,22 @@ kstate_sync(struct krang *k) 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; + /* + * The engine's counters start at zero when it opens; the event log + * restored everything before it. The surface shows the life, not the + * current process. + */ + k->st.tokens_in = k->restored.tokens_in + (unsigned long)es.tokens_in; + k->st.tokens_out = k->restored.tokens_out + (unsigned long)es.tokens_out; + k->st.tokens_cached = k->restored.tokens_cached + + (unsigned long)es.cached_total; + k->st.cost = k->restored.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.steps = k->restored.steps + (unsigned long)es.steps; + k->st.tool_calls = k->restored.tool_calls + (unsigned long)es.calls; + k->st.compactions = k->restored.compactions + + (unsigned long)es.compactions; k->st.busy = es.busy; k->st.waiting = es.waiting; k->st.stuck_level = k->stuck.level; @@ -172,6 +179,14 @@ kstate_json(struct krang *k, struct sp_buf *out) jnum(out, "pending", (long long)s.chat_pending); (void)sp_buf_puts(out, "},"); + (void)sp_buf_puts(out, "\"drive\":{"); + jstr(out, "name", s.drive[0] != '\0' ? s.drive : "goal"); + (void)sp_buf_puts(out, ","); + jnum(out, "urgency", s.drive_urgency); + (void)sp_buf_puts(out, ","); + jstr(out, "reason", s.drive_reason); + (void)sp_buf_puts(out, "},"); + (void)sp_buf_puts(out, "\"stuck\":{"); jnum(out, "level", s.stuck_level); (void)sp_buf_puts(out, ","); diff --git a/src/util.c b/src/util.c index a43ac58..16cdbf1 100644 --- a/src/util.c +++ b/src/util.c @@ -150,6 +150,23 @@ k_format_time(long t, char *buf, size_t cap) snprintf(buf, cap, "-"); } +/* + * Before the chroot the workspace is the host path from the config; after it, + * that path may not exist and the bind mount is at KRANG_IN_WORKSPACE. Prefer + * the configured path when it is readable, else the fixed inside path. + */ +const char * +kthreads_path(struct krang *k, char *buf, size_t cap) +{ + if (k != NULL && buf != NULL && cap > 0 && + k->cfg.workspace[0] != '\0') { + snprintf(buf, cap, "%s/THREADS.md", k->cfg.workspace); + if (k->cfg.no_sandbox || access(buf, F_OK) == 0) + return buf; + } + return KRANG_IN_THREADS; +} + int k_parse_bool(const char *s, int dflt) { diff --git a/tests/test_krang.c b/tests/test_krang.c index 2faf7e9..d6ce4a4 100644 --- a/tests/test_krang.c +++ b/tests/test_krang.c @@ -278,6 +278,74 @@ test_birth_flow(void) sp_buf_free(&k.err); } +static void +test_session_count(void) +{ + struct krang k; + char tmpl[] = "/tmp/krang-count-XXXXXX"; + char *dir, path[800]; + size_t records = 0; + unsigned long long bytes = 0; + FILE *f; + + 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); + kconfig_defaults(&k.cfg); + snprintf(k.session_dir, sizeof(k.session_dir), "%s/sessions", dir); + (void)mkdir(k.session_dir, 0700); + snprintf(path, sizeof(path), "%s/krang.jsonl", k.session_dir); + f = fopen(path, "w"); + CHECK(f != NULL); + if (f == NULL) + return; + fprintf(f, "{\"role\":\"user\",\"text\":\"a\"}\n"); + fprintf(f, "{\"role\":\"assistant\",\"text\":\"b\"}\n"); + fprintf(f, "{\"role\":\"user\",\"text\":\"c\"}\n"); + fclose(f); + CHECK(ksession_meta(&k, &records, &bytes, NULL, 0, NULL, 0) == 0); + CHECK(records == 3); + CHECK(bytes > 0); + + f = fopen(path, "a"); + CHECK(f != NULL); + if (f == NULL) + return; + fprintf(f, "{\"role\":\"assistant\",\"text\":\"d\"}\n"); + fprintf(f, "{\"role\":\"user\",\"text\":\"e\"}\n"); + fclose(f); + CHECK(ksession_meta(&k, &records, &bytes, NULL, 0, NULL, 0) == 0); + CHECK(records == 5); + + /* a torn tail is not a record until its newline arrives */ + f = fopen(path, "a"); + fprintf(f, "{\"role\":\"assistant\""); + fclose(f); + CHECK(ksession_meta(&k, &records, &bytes, NULL, 0, NULL, 0) == 0); + CHECK(records == 5); + f = fopen(path, "a"); + fprintf(f, ",\"text\":\"f\"}\n"); + fclose(f); + CHECK(ksession_meta(&k, &records, &bytes, NULL, 0, NULL, 0) == 0); + CHECK(records == 6); + + /* a truncated file drops the old count, it does not keep it */ + f = fopen(path, "w"); + fprintf(f, "{\"role\":\"user\",\"text\":\"only\"}\n"); + fclose(f); + CHECK(ksession_meta(&k, &records, &bytes, NULL, 0, NULL, 0) == 0); + CHECK(records == 1); + pthread_mutex_destroy(&k.lock); + pthread_cond_destroy(&k.cond); + sp_buf_free(&k.err); +} + static void test_http(void) { @@ -342,6 +410,7 @@ main(void) test_stuck(); test_birth_flow(); test_state(); + test_session_count(); test_http(); test_mcp(); if (failures != 0) { diff --git a/tests/test_mind.c b/tests/test_mind.c new file mode 100644 index 0000000..507f62e --- /dev/null +++ b/tests/test_mind.c @@ -0,0 +1,195 @@ +/* + * krang -- the conductor's drives. + * + * Copyright (c) 2026 Konrad Lother + * License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree. + */ +#include +#include +#include +#include +#include +#include + +#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 +reset_krang(struct krang *k, const char *ws) +{ + memset(&k->st, 0, sizeof(k->st)); + k->st.impulses = 2; + k->st.turns = 2; + k->st.ctx_max = 100000; + k->st.ctx_used = 10000; + k->st.session_bytes = 2 * 1024 * 1024; + k->hour_count = 0; + k->turn_failures = 0; + k->last_goal_impulse = 0; + k->cfg.max_cost = 0.0; + k->cfg.max_impulses_per_hour = 30; + k->cfg.compact_threshold = 60000; + snprintf(k->cfg.workspace, sizeof(k->cfg.workspace), "%s", ws); + snprintf(k->st.goal, sizeof(k->st.goal), "test the conductor"); +} + +static void +touch_notes(const char *ws, long age) +{ + char path[700]; + FILE *f; + + snprintf(path, sizeof(path), "%s/THREADS.md", ws); + f = fopen(path, "w"); + if (f != NULL) { + fprintf(f, "# notes\n"); + fclose(f); + } + if (age > 0) { + struct timeval tv[2]; + + tv[0].tv_sec = k_now() - age; + tv[0].tv_usec = 0; + tv[1] = tv[0]; + (void)utimes(path, tv); + } +} + +int +main(void) +{ + struct krang k; + struct kvitals v; + struct kdecision d; + char tmpl[] = "/tmp/krang-mind-XXXXXX"; + char *ws; + struct sp_buf b; + + ws = mkdtemp(tmpl); + CHECK(ws != NULL); + if (ws == 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); + k.cfg.no_sandbox = 1; + (void)unlink("/tmp/krang-mind-notes-does-not-exist"); + + /* a young session with no special deficit pursues the goal */ + reset_krang(&k, ws); + kconductor_measure(&k, &v); + kconductor_decide(&k, &v, &d); + CHECK(strcmp(d.drive, "goal") == 0); + CHECK(v.threads_age < 0); + CHECK(d.urgency == 30); + + /* after a few impulses, missing notes become a drive */ + k.st.impulses = 5; + kconductor_measure(&k, &v); + kconductor_decide(&k, &v, &d); + CHECK(strcmp(d.drive, "maintain") == 0); + CHECK(d.urgency >= 50); + CHECK(contains(d.reason, "missing")); + + /* fresh notes release it */ + touch_notes(ws, 0); + kconductor_measure(&k, &v); + kconductor_decide(&k, &v, &d); + CHECK(strcmp(d.drive, "goal") == 0); + CHECK(v.threads_age >= 0 && v.threads_age < 120); + + /* stale notes become maintenance again */ + touch_notes(ws, 3600); + kconductor_measure(&k, &v); + kconductor_decide(&k, &v, &d); + CHECK(strcmp(d.drive, "maintain") == 0); + CHECK(contains(d.reason, "minutes")); + + /* context pressure outranks the goal */ + touch_notes(ws, 0); + k.st.ctx_used = 90000; + kconductor_measure(&k, &v); + kconductor_decide(&k, &v, &d); + CHECK(strcmp(d.drive, "survive") == 0); + CHECK(contains(d.reason, "context")); + + /* and the cost cap outranks context */ + k.cfg.max_cost = 1.0; + k.st.cost = 0.95; + kconductor_measure(&k, &v); + kconductor_decide(&k, &v, &d); + CHECK(strcmp(d.drive, "survive") == 0); + CHECK(contains(d.reason, "cost")); + CHECK(d.urgency >= 80); + k.cfg.max_cost = 0.0; + k.st.cost = 0.0; + k.st.ctx_used = 10000; + touch_notes(ws, 0); + + /* a long open goal gets an exploration impulse on the eighth turn */ + k.st.impulses = 20; + k.last_goal_impulse = 0; + kconductor_measure(&k, &v); + kconductor_decide(&k, &v, &d); + CHECK(strcmp(d.drive, "explore") == 0); + CHECK(contains(d.reason, "since the last completed goal")); + + /* the prompt carries the drive, the reason and the measured vitals */ + k.st.goal_state[0] = '\0'; + sp_buf_init(&b); + k_impulse_prompt(&k, "timer", &b); + CHECK(contains(b.p, "[conductor]")); + CHECK(contains(b.p, "Drive: explore")); + CHECK(contains(b.p, "Why:")); + CHECK(contains(b.p, "Vitals:")); + CHECK(contains(b.p, "Explore.")); + CHECK(contains(b.p, "session 2.0 MB")); + CHECK(strcmp(k.st.drive, "explore") == 0); + sp_buf_free(&b); + + /* the self-check path claims the reflect drive */ + k.st.stuck_level = 2; + k.st.stuck_attempts = 2; + sp_buf_init(&b); + k_selfcheck_prompt(&k, &b); + CHECK(contains(b.p, "Drive: reflect")); + CHECK(contains(b.p, "stuck level 2")); + CHECK(strcmp(k.st.drive, "reflect") == 0); + CHECK(k.st.drive_urgency >= 80); + sp_buf_free(&b); + + /* the snapshot carries it to the dashboard */ + sp_buf_init(&b); + kstate_json(&k, &b); + CHECK(contains(b.p, "\"drive\":{\"name\":\"reflect\"")); + CHECK(contains(b.p, "\"urgency\":")); + sp_buf_free(&b); + + 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_mind: ok\n"); + return 0; +} diff --git a/tests/test_replay.c b/tests/test_replay.c new file mode 100644 index 0000000..c0a5d62 --- /dev/null +++ b/tests/test_replay.c @@ -0,0 +1,258 @@ +/* + * krang -- restarting without starting a new experiment. + * + * Copyright (c) 2026 Konrad Lother + * License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree. + * + * Part one replays a synthetic event log through kreplay_events(). Part two + * runs kdaemon_run() twice with a fresh struct each time and proves that the + * second life continues the first: same birth, same ledger ids, cumulative + * totals. + */ +#include +#include +#include +#include +#include + +#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, const char *dir) +{ + char path[800]; + + 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 a restart"); + 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->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; + snprintf(k->session_dir, sizeof(k->session_dir), "%s/sessions", dir); + snprintf(k->script, sizeof(k->script), "%s/script.txt", dir); + (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); +} + +static void +test_synthetic(void) +{ + struct krang w, r; + char tmpl[] = "/tmp/krang-replay-XXXXXX"; + char *dir; + struct sp_buf b; + + dir = mkdtemp(tmpl); + CHECK(dir != NULL); + if (dir == NULL) + return; + init_krang(&w, dir); + klog_emit(&w.log, "start", "newborn", "0", "session", "krang", NULL); + klog_emit(&w.log, "impulse_start", "impulse", "1", "cause", "birth", + "prompt", "wake up", NULL); + klog_emit(&w.log, "tool", "name", "run", + "args", "{\"command\":\"true\"}", NULL); + klog_emit(&w.log, "tool_result", "name", "run", "ok", "1", + "obs", "", NULL); + klog_emit(&w.log, "turn_end", "rc", "0", "steps", "1", "calls", "1", + "tokens_in", "100", "tokens_out", "20", "cost", "0.010000", + "impulse", "1", "compactions", "0", "cause", "birth", + "answer", "first-answer", "error", "", NULL); + klog_emit(&w.log, "impulse_start", "impulse", "2", "cause", "timer", + "prompt", "continue", NULL); + klog_emit(&w.log, "tool", "name", "write", + "args", "{\"path\":\"/var/lib/krang/workspace/self/SYSTEM.md\"}", + NULL); + klog_emit(&w.log, "tool_result", "name", "write", "ok", "0", + "obs", "error: denied", NULL); + klog_emit(&w.log, "turn_end", "rc", "-1", "steps", "2", "calls", "1", + "tokens_in", "50", "tokens_out", "10", "cost", "0.005000", + "impulse", "2", "compactions", "1", "cause", "timer", + "answer", "", "error", "boom", NULL); + klog_emit(&w.log, "stuck", "level", "2", "attempts", "1", NULL); + klog_emit(&w.log, "blocked", "reason", "same approach", NULL); + klog_emit(&w.log, "chat_in", "id", "1", "text", "hello", NULL); + klog_emit(&w.log, "chat_out", "rc", "0", "answer", "hi", NULL); + klog_emit(&w.log, "goal_complete", "goal", "survive a restart", NULL); + klog_close(&w.log); + + init_krang(&r, dir); + CHECK(kreplay_events(&r, r.last_error, sizeof(r.last_error)) == 0); + CHECK(r.restored.impulses == 2); + CHECK(r.restored.self_impulses == 2); + CHECK(r.restored.external_impulses == 0); + CHECK(r.restored.turns == 2); + CHECK(r.restored.steps == 3); + CHECK(r.restored.tool_calls == 2); + CHECK(r.restored.tool_failures == 1); + CHECK(r.restored.self_edits == 1); + CHECK(r.restored.tokens_in == 150); + CHECK(r.restored.tokens_out == 30); + CHECK(r.restored.cost > 0.0149 && r.restored.cost < 0.0151); + CHECK(r.restored.compactions == 1); + CHECK(r.restored.blocked_events == 1); + CHECK(r.restored.chat_in == 1); + CHECK(r.restored.chat_out == 1); + CHECK(r.restored.goal_completes == 1); + CHECK(r.restored.last_turn_rc == -1); + CHECK(contains(r.restored.last_outcome, "error: boom")); + CHECK(contains(r.restored.last_error, "boom")); + CHECK(r.impulse_seq == 2); + CHECK(r.impulses[0].id == 1); + CHECK(r.impulses[0].tokens_in == 100); + CHECK(r.impulses[0].tokens_out == 20); + CHECK(contains(r.impulses[0].answer, "first-answer")); + CHECK(r.impulses[1].id == 2); + CHECK(r.impulses[1].rc == -1); + CHECK(r.impulses[1].tool_calls == 1); + CHECK(r.stuck.level == 2); + CHECK(r.stuck.attempts == 1); + CHECK(r.st.stuck_level == 2); + CHECK(r.last_blocked_at > 0); + CHECK(r.recent_starts == 1); + CHECK(r.st.impulses == 2); + CHECK(r.st.tokens_in == 150); + sp_buf_init(&b); + kstate_impulses_json(&r, &b, 10); + CHECK(contains(b.p, "\"id\":1")); + CHECK(contains(b.p, "\"id\":2")); + sp_buf_free(&b); + klog_close(&r.log); + pthread_mutex_destroy(&r.lock); + pthread_cond_destroy(&r.cond); + sp_buf_free(&r.err); + pthread_mutex_destroy(&w.lock); + pthread_cond_destroy(&w.cond); + sp_buf_free(&w.err); +} + +static void +test_end_to_end(void) +{ + struct krang a, b; + char tmpl[] = "/tmp/krang-restart-XXXXXX"; + char *dir; + char path[800]; + struct sp_buf bjson; + long born1; + FILE *f; + + dir = mkdtemp(tmpl); + CHECK(dir != NULL); + if (dir == NULL) + return; + snprintf(path, sizeof(path), "%s/script.txt", dir); + f = fopen(path, "w"); + CHECK(f != NULL); + if (f == NULL) + return; + fprintf(f, "tool echo {\"text\":\"restart\"}\n"); + fprintf(f, "answer restart-ok\n"); + fclose(f); + + init_krang(&a, dir); + CHECK(ksession_meta(&a, NULL, NULL, NULL, 0, NULL, 0) == 0); + a.max_impulses = 1; + CHECK(kdaemon_run(&a) == 0); + CHECK(a.st.impulses == 1); + CHECK(a.st.turns == 1); + CHECK(a.st.tool_calls == 1); + born1 = a.st.born_at; + CHECK(born1 > 0); + CHECK(contains(a.st.last_outcome, "restart-ok")); + pthread_mutex_destroy(&a.lock); + pthread_cond_destroy(&a.cond); + sp_buf_free(&a.err); + + init_krang(&b, dir); + b.max_impulses = 1; + CHECK(kdaemon_run(&b) == 0); + CHECK(b.st.impulses == 2); + CHECK(b.st.turns == 2); + CHECK(b.st.self_impulses == 2); + CHECK(b.st.tool_calls == 2); + /* one scripted turn is two engine steps (tool round + answer) */ + CHECK(b.restored.steps == 2); + CHECK(b.st.steps == 4); + CHECK(b.st.born_at == born1); + CHECK(contains(b.st.last_outcome, "restart-ok")); + CHECK(b.impulse_seq == 2); + sp_buf_init(&bjson); + kstate_json(&b, &bjson); + CHECK(contains(bjson.p, "\"total\":2")); + sp_buf_free(&bjson); + sp_buf_init(&bjson); + kstate_impulses_json(&b, &bjson, 10); + CHECK(contains(bjson.p, "\"id\":1")); + CHECK(contains(bjson.p, "\"id\":2")); + CHECK(contains(bjson.p, "restart-ok")); + sp_buf_free(&bjson); + { + char logbuf[65536]; + FILE *lf; + size_t n = 0; + + snprintf(path, sizeof(path), "%s/state/events.jsonl", dir); + lf = fopen(path, "r"); + CHECK(lf != NULL); + if (lf != NULL) { + n = fread(logbuf, 1, sizeof(logbuf) - 1, lf); + logbuf[n] = '\0'; + fclose(lf); + } else { + logbuf[0] = '\0'; + } + CHECK(contains(logbuf, "Drive: goal")); + CHECK(contains(logbuf, "Vitals:")); + CHECK(contains(logbuf, "\"drive\":\"goal\"")); + } + pthread_mutex_destroy(&b.lock); + pthread_cond_destroy(&b.cond); + sp_buf_free(&b.err); +} + +int +main(void) +{ + test_synthetic(); + test_end_to_end(); + if (failures != 0) { + fprintf(stderr, "%d test(s) failed\n", failures); + return 1; + } + printf("test_replay: ok\n"); + return 0; +}