Files
splinter/CHAOS.md
Konrad f574313ad5 splinter: CHAOS.md — every idea from the three agent-harness attempts
Collected on 2026-11-06 while planning an own harness: MikroAgent (92 items
across transport, loop, persistence, tools, compaction, budget, limits,
audit, endpoint policy, build/test), OpenITT (invariants, disk-backed
streaming, compression with retrieval, session format, memory accounting,
long-input + linecomp + notes loop) and agentk (context-engine vtable, LCM
pipeline, summary DAG, structural pre-cleanup, ObservationPack, prompt
cache, threaded reactor), plus the points where the three disagree and the
tool-call robustness gap measured on the MacBook.
2026-11-07 05:13:15 +00:00

26 KiB
Raw Permalink Blame History

CHAOS — every idea from the three harness attempts

Stand: 2026-11-06. Collected while planning a new agent harness of our own. Everything below was read out of the existing trees, not invented. Line counts and file references are what the trees actually contain at this date.

Provenance — what was read

Tree Location Size / state
MikroAgent ~/src/MikroAgent (kitt) 12,530 lines C99, 17 test binaries, make check green, 100,768 B binary, ~4 MB RSS, 0 CPU idle, 2 commits (e21a11c Phase 11, b880a40 Phase 10)
OpenITT ~/src/OpenITT (kontron) single binary + libopenitt.a, 381 tests / 0 failures, docs ≈3,000 lines, not a git repo
agentk ~/src/agentk (kitt) no code: 852-line plan refs/agentk-implementation-plan.md, 15 skills under .agents/skills/, 26 research refs, 5 open tasks in .tasks/

Read in full: MikroAgent/docs/{design.md,architecture.md,performance.md}, MikroAgent/AGENTS.md, OpenITT/OPENITT-OVERVIEW.md, OpenITT/specs/{compression-algorithm.md,long-input-design.md,notes-loop-pitch.md}, OpenITT/TOOLS.md, agentk/refs/agentk-implementation-plan.md (selected sections), agentk/.tasks/*.md.


A. MikroAgent — the engine that already runs

Transport layer

  1. Transport vtable: send() → {status, body}, optional send_stream() handing raw bytes to a callback. The transport never parses JSON or SSE, so a mock, a libcurl adapter and any future provider share one seam.
  2. Deterministic mock transport: replies queued FIFO; send_stream() replays a queued body in caller-chosen chunk sizes; records the last request body and a request count. This is how fragmented-argument handling is tested with no network and no paid endpoint.
  3. SSE framer is the only module that knows \n\n: buffers partial lines across reads, ignores comments and non-data fields, strips an optional \r, reports an unterminated final event.
  4. Wire isolation: only model/openai.c knows the OpenAI shape; tool-call fragments are merged by index, and a fragment never yields a call until the stream finishes.
  5. Raw arguments kept as a JSON string, never parsed into an object at parse time — preserves exactly what the model sent for the audit trail and defers parsing to execution, because the API states arguments may be invalid JSON.

Agent loop

  1. Budget checked before every request; authorization callback before every non-read tool; never a call without its result.
  2. Authorization as a callback with fail-closed default: with no callback, reads run and everything else is denied — the denial is delivered to the model as the tool's observation. Enforcement lives in the tool-execution layer, never in the system prompt (the prompt explains, it never decides).
  3. Three policies: read-only, confirm-mutations (default), configured autonomous. The prompt shows tool name, class and the exact arguments JSON; anything but y/yes is denial; no stdin (-p plus a mutating tool) fails closed.

Persistence

  1. One directory per session: meta as key = value, written atomically (meta.tmp → rename()); messages.jsonl opened O_APPEND.
  2. Crash model: a crash can only truncate the tail, so recovery replays complete lines and discards one partial line, reporting a recovered flag. A complete line that is not a valid message object is corruption and fails the load.
  3. Session ids default to sess-<time>-<pid>; an existing session is resumed even without --resume (history is never silently dropped), while --resume of a missing id is an error.
  4. System prompt inserted only into an empty history — never reordered, never duplicated on resume, and deliberately not stored in meta, because reconstructing it there would risk drift from what the model actually saw.

Tools

  1. read_file (offset/limit bytes, MA_AUTH_READ, max_read_bytes, marks truncation), write_file (atomic temp + rename in the target directory), list_dir (sorted, directories suffixed /), run_command (MA_AUTH_DESTRUCTIVE, /bin/sh -c in the workspace root, stdout+stderr merged, output capped, waitpid status reported, timeout kills the child process group and is reported explicitly).
  2. No shell for git: git = closed allowlist (status|diff|log|show|ls-files|branch) with fixed flags, log bounded to --oneline -n 50, core.pager=cat so a pager can never swallow output; git_commit = MA_AUTH_MUTATE, paths validated and passed after add --.
  3. Option-smuggling defence: user strings become single argv entries, must not start with -, must contain no whitespace or control characters — refused before any fork. Rule behind it: the approved action and the executed action must be byte-identical.
  4. subproc helper shared by every exec-style tool: pipe+fork, dup2 merged output, setpgid + kill-group on deadline, non-blocking drain into a buffer with byte cap and explicit truncated flag, waitpid with EINTR retry, structured result (status, signal, timeout). Callers phrase the observation; the helper never annotates.

Compaction

  1. Compaction is a runtime window, never a rewrite: view_start is runtime-only, monotonic, pair-safe (a cut never lands on a tool message), bounded (never cuts at the current user turn), and a failed attempt restores the previous window.
  2. The wire carries only the count of omitted messages in a system marker — no model-written summary, because a summary that paraphrases dropped text is fabrication.
  3. Stored history and the session log stay untouched, so a resume sees everything and compaction is recomputed from scratch.

Budget and tokens

  1. 32k default context, output_reserve 4096; the budget refuses rather than letting the endpoint truncate.
  2. Three-tier token counting as a pluggable vtable: verified tokenizer > calibration from server-reported usage > conservative estimator.
  3. Usage-calibrated counter: the latest (estimate, prompt_tokens) pair anchors a linear rescale ceil(P × E'/E) × (1 + margin), pure integer with saturating overflow. A report ≤ 0 never moves the anchor; an absurd report saturates so the budget fails closed. Overwritten, never compounded, never persisted.
  4. Never requests stream_options.include_usage — it is an extension some compatible backends reject; usage is taken when volunteered.

Runaway protection

  1. Identical-failure limit (default 3): 64-bit FNV-1a over (name, arguments, observation) in a fixed 8-slot recycling window. It counts only harness-classified failures — unknown tool, unparseable arguments, policy denial, missing implementation, run() failure. A delivered [exit status 3] is a successful call; grepping output for error: would couple the loop to phrasing no contract promises.
  2. Including the observation in the signature means a same-argument retry whose situation changed resets the count: the limit stops repetition without progress, not retries.
  3. Turn deadline (max_turn_ms, default 600000, CLOCK_MONOTONIC) checked only at safe boundaries: before building each request and before executing each call of a batch. A mid-batch cut answers every remaining call with error: turn time limit reached instead of dropping it, so call/result pairing survives.
  4. A failed clock read fails closed (budget reported spent) rather than running unbounded.

Operator control and audit

  1. Cancel latch: volatile sig_atomic_t polled inside the curl write callbacks. The handler is installed in every mode, including replacing an inherited SIG_IGN — a backgrounded -p run otherwise never sees SIGINT. (This was a real bug caught by an end-to-end test.)
  2. Distinguishes cancelled=2 (operator) from cancelled=1 (consumer parse abort) so error text never misattributes the cause.
  3. The turn persists its tail before printing; Ctrl-C prints [interrupted -- the session is saved] and exits 0.
  4. Two audit event kinds in audit.jsonl: decision (tool, class, approved/denied, reason, args) and result (timestamp, tool, call id, observation byte count, UTF-8-safe 200-byte prefix). Read-class results are audited too; full observations stay in messages.jsonl.
  5. Observation hook fires once per completed call (executed, denied, unknown, bad arguments) before the result is appended — the auditor records exactly what the model will see.

Display

  1. Streaming shows only accepted content deltas, never tool-argument fragments (partial JSON is not assistant speech), via suffix diffing per SSE event.
  2. Display-only authority: history is appended exactly once from the merged result. If the stream breaks, the user saw text that no history entry received — visible as a turn error, never as a silent lie.
  3. Harness output (approval prompts, tool events, [error:]) always starts on a fresh row; model text and harness text never share a line.

Endpoint security

  1. endpoint.c owns the never-downgrade rule in pure C, testable without libcurl: https for any host; plaintext http only for localhost, 127.0.0.0/8, [::1]; credentials in the URL (@), query, fragment, spaces, control characters and percent-encoded hosts are rejected; the bearer token comes only from a named environment variable.
  2. libcurl adapter: TLS verification set explicitly so a later edit cannot disable it by accident; FOLLOWLOCATION = 0 because a redirect could move the bearer token to another host; CURLOPT_TIMEOUT_MS, NOSIGNAL; the key is copied at open and never reaches an error string (only curl_easy_strerror).
  3. A non-zero return from the consumer callback aborts the transfer — the agent never sees a partially delivered success.

Build and test

  1. ./configure is POSIX sh, compiles and links probe programs instead of checking version strings, preserves CC/CFLAGS/CPPFLAGS/LDFLAGS/LIBS, and writes config.mk.
  2. Makefile is POSIX make + ?= only — runs under GNU make and bmake; no $(shell), no ifeq, no target-specific variables, no $^.
  3. Flags: -std=c99 -Wall -Wextra -Wpedantic -Werror -D_POSIX_C_SOURCE=200809L.
  4. DEPS hammer: every object pinned to every internal header, because POSIX suffix rules carry no header dependencies. This bit them for real — a test binary linked against a stale object with the old struct layout and read cfg.compact past the field count.
  5. Test suite: plain C programs with a failures counter, no framework. The mock covers normal text, single/multiple tool calls, fragmented arguments, malformed arguments, unknown tools, tool failure, 401/429, context overflow, step and tool-call limits. The curl adapter is tested against a forked loopback HTTP server; git tests skip cleanly when git is absent.
  6. Performance as a regression contract: idle REPL 0 CPU ticks, ~4 MB RSS, ~5 ms local work per turn, ~2.4 ms startup, ~100 KB binary — with the rejected optimizations documented so nobody optimizes them back in.

B. OpenITT — the data model and the low-memory discipline

The five core invariants

  1. External data has no inherent size limit — model output, reasoning, tool output, stdout, stderr, MCP output, files read, session history. "A 1 KiB result and a 1 GiB result must follow the same architectural path."
  2. Disk-backed output, RAM-bounded conversation: the complete artifact may exist on disk while only a bounded representation is in the model conversation.
  3. No silent truncation: any reduction must be explicit and documented; accidental truncation is a bug. Their own bug history is the argument — 255-byte tool-argument truncation, 4096-byte SSE line loss, 512-byte digest truncation.
  4. Session data is durable truth, RAM is working state. Compression changes what is loaded, never what is stored.
  5. Reasoning is separate from visible content: provider-supplied reasoning_content is streamed, persisted to <session>.reasoning, not printed, and not part of the next request unless exposed through a tool. There is no NLP thought-detector — if a provider puts reasoning into content, it is content.

Data flow

  1. Streaming rule: delta → append to disk + bounded metadata + conversation update. Never grow an unbounded RAM buffer → write the file afterwards. A stream may be arbitrarily large while RAM stays flat.
  2. chat_t is a working set, not the archive: role, type, identifier, size, bounded head, bounded tail, disk reference. It must not silently become an unbounded cache of session contents.
  3. Turn as a pipeline: bounded conversation → provider → stream → content to spool, reasoning to reasoning spool, tool calls to the dispatcher → tool execution → output spool → bounded result back into the conversation → next round. A turn ends when the model answers without another tool call.

Compression with retrieval

  1. Collapse: older rounds are replaced in the active conversation by a structured digest preserving tool name, call id, full arguments, exit status, output size, bounded head, bounded tail and a retrieval id.
  2. Trim: if the active round alone exceeds the budget and no older round is left, only the active representation is reduced to head/tail. The durable record is untouched.
  3. Compression must never make information permanently unreachable: every compressed artifact keeps a stable id the history tool can use to fetch the original or further portions back.
  4. Context ordering from measured prompt-cache behaviour: the digest sits at the start of the collapsible region, complete rounds are never split, and the live date block sits at the end. Documented as measured behaviour, not as a universal API assumption.

Session format and tooling

  1. Sessions are human-readable plain text: [checkpoint id=… pos=…], [message type=user], [tool id=… command=… output=stdout rc=0], [compress]. Grep-able, tail-able, recoverable without a database, no binary serialization.
  2. session_load_chat reconstructs only the active window; the file remains the complete historical record.
  3. Tool set: system (shell), notes, history (search past sessions and retrieve archived output), skill (instruction files), mcp, reasoning (retrieve stored provider reasoning), output (control streaming behaviour).
  4. Tools are lazy: nothing enters the conversation merely because it exists on disk; the model requests it when needed.
  5. Notes under .openitt/notes/, skills under .openitt/skills/ — plain files the model loads explicitly.

Providers and diagnostics

  1. Provider abstraction covering OpenAI-compatible (default), Ollama, Anthropic, xAI/OpenCode; named model blocks with api_url and model; environment overrides including OPENITT_MODEL, OPENITT_CTX_LIMIT, OPENITT_MCP_URL, OPENITT_TRACE, OPENITT_MAX_TURNS, OPENITT_STREAM_STDOUT.
  2. Seven trace levels: turn, HTTP, body, wire, state, budget, everything. Diagnostics are a first-class feature, not a debug relic.

Memory accounting (designed, not implemented)

  1. Memory is a first-class observable property, not a single RSS number: per-module current bytes, per-module peak bytes, allocation and free counts, categories — and lifecycle snapshots at startup, configuration loaded, model initialized, session opened, conversation loaded, request started, stream active, tool started, tool output spooling, tool completed, compression, turn completed, shutdown.
  2. Process RSS measured separately from library-level allocation accounting. The accounting must not become a significant part of the footprint it measures. An optional debug mode adds address, size, file, line, lifetime and outstanding allocations.
  3. Targets: working set below 1 MiB where practical; 2–3B CPU models as the primary development target with 4B as the practical ceiling; 8k default context but configurable to 1M — OpenITT imposes no artificial maximum.

Architecture split and housekeeping

  1. libopenitt + thin clients: the library owns the agent and has zero UI assumptions (no curses, no X11, no terminal drawing). openitt is the CLI/curses client with curses imported from kibson/curses rather than written; xopenitt is a later X11/Motif client. Clients must not duplicate agent logic.
  2. FD discipline: spools are open/write/close, not a FILE * held per spool for a whole round — avoids FD accumulation and stdio buffers. Unlinked temp spools at 0600 where appropriate.
  3. Export: --export <session> --format=ini|json|raw operating on the complete session rather than the reduced chat_t, preserving archived tool output, stderr, compression records and reasoning. Read-only.

Explicit non-goals

  1. No automatic model delegation, no orchestrator, no per-task model routing. No reasoning classifier. No artificial 8k maximum. No UI in the core library. No database.

Testing and benchmarking philosophy

  1. No test framework; project-local CHECK_* macros. Every module tested for normal, empty, large, malformed, partial, allocation failure, EOF, repeated operations, cleanup and boundaries.
  2. Content-length scaling test: same behaviour at 1 KiB, 64 KiB, 1 MiB, 16 MiB, 256 MiB — memory must stay approximately constant. An output-size-proportional heap allocation is declared an architectural failure.
  3. bench.sh measures wall clock, provider latency, context size, compression behaviour, current and peak memory, tool output size, spool behaviour, allocation count and open-FD behaviour; trace level 7 is the diagnosis path.

Long input — the idea with the highest value for us

  1. Input is staged into the session file with POSIX open/write/seek; the model reads a 2048-token window at a time, knows it is only the beginning of a huge input, takes notes to disk with offsets and checkpoints, compresses locally after each window, and can seek back and forth between checkpoints to re-check things.
  2. Proposed 8k split: 1k fixed behaviour, 2k compressed memory, 2k next chunk, 2k room for the new note, 1k headroom (the author's own words: "i have no idea", i.e. a starting point, not a contract).
  3. It ends by writing a report into report/ that fits the output limit — instead of today's behaviour, where a 100k-token input is cut to head+tail and the model answers from roughly 10 KB of it.
  4. The hard line: compression is never an LLM call. A deterministic local algorithm in C, same input → same output, runs on the box forever.
  5. The specified algorithm (deterministic log clustering):
    • Phase 1 line splitting, every line carrying a byte offset and a line number;
    • Phase 2 structural hashing — numbers → <NUM>, 0x… → <HEX>, paths → <PATH>, so lines that differ only in variable parts share a template;
    • Phase 3 class aggregation — count, one sample, first offset, and a signal flag (ERROR, WARN, FAIL, denied, blocked, panic, segfault, out of memory, cannot, fatal; case-insensitive);
    • Phase 4 blob with [header][signal][noise][head_tail];
    • Phase 5 budget enforcement that drops the noisiest noise classes first, highest count and lowest uniqueness, and never drops signal classes.
    • Tuning: signal_keywords, noise_class_min_count, head_tail_bytes (default 500), max_noise_classes (default 50).
    • O(n) single pass, hash table for grouping, seekable, 100k lines → maybe 50 classes → a tiny blob.
  6. The notes loop: two phases. Phase 1 is an investigation loop with its own budget that reads 100 % of the input in 4 KB windows, writing notes plus a look-back directive each turn; Phase 2 is the real conversation, which pays only for the conclusion. The user prompt stays fixed during the investigation; one extra API call per turn to the same model; the extra call's tokens are counted in the budget pass so the window cannot blow out silently.
  7. Why it matters: the reasoning lives on disk as notes, so a model without a reasoning feature still gets a full investigation — and the reasoning is inspectable, diffable, and independent of the model's own reasoning budget.

C. agentk — the compaction theory

  1. ContextEngine vtable as the swappable core: on_session_start() → per call update_from_response(usage) → per turn should_compress() / compress(messages, current_tokens, focus_topic, force) → on_session_end() (real session boundaries only). The usage struct carries prompt/completion/total plus optional input/output/cache_read/cache_write/ reasoning tokens.
  2. LCM-style leaf-compaction pipeline: structural pre-cleanup → ingest into an append-only store (replay-safe view) → fresh-tail anchoring → loop selecting the oldest leaf chunk → dependency-filtered summarizer input → SummaryNode into a DAG → condense leaves into higher nodes → assemble → bump compression_count.
  3. SummaryNode carries depth (0 = leaf, 1+ = condensed), summary text, token count, source token count, source ids (store ids or node ids), source type, created/earliest timestamps — lineage survives at every level.
  4. Rescue path on summarizer failure: deterministic recompile, retry with a smaller chunk, then L1/L2/L10 truncation as fallback — never uncontrolled output.
  5. Structural pre-cleanup before any LLM compaction — the highest-ROI step: dedup identical tool results and re-reads (keep the newest), canonicalize whitespace and timestamps, purge resolved error messages, mark repeated intermediate states. 15–30 % cut, lossless, zero model calls.
  6. ObservationPack (from NVIDIA SoL-Pi): repeated large tool results become a stable handle with exact paged recall — ls over 100 files collapses to [ObservationPack: 100 entries, 48k tokens] plus agentk_pack_page(handle, offset, limit). Paired with an evidence-preserving reducer: a long log becomes "receipts" only if every kept quote matches the archived source.
  7. Structured summary template as the core trick: ## Session Intent, ## Files Modified (full paths), ## Key Decisions, ## Active Goals, ## Next Steps, fed as custom_instructions. Justification: freeform summarization scores 2.19–2.45/5 on artifact tracking (Factory.ai benchmark), while a checklist forces explicit "empty" answers instead of silent omission.
  8. Prompt-cache rules: byte-stable system prefix with the cache_control breakpoint at the end; append-only history, never editing earlier turns; a cache_control marker on the compaction block itself; and no dynamic content in the prefix — timestamps, session ids and user metadata belong in the last user message. Compaction events and prefix validation get logged.
  9. Files over tools: filesystem-based context engineering (shell + files) met intent 45 % → 75 % versus tool explosion (Azure SRE). Fewer, more general tools; let the filesystem carry the structure.
  10. Threaded reactor (Konrad's later decision, contradicting OpenITT's "no pthread"): the loop thread is the sole state writer, tool threads post results through an mpsc queue, pipes are length-framed, abort is SIGKILL plus a cooperative two-stage cancel.
  11. Client protocol layer planned as agentk (curses) + xagentk (X11), with ACP schemas collected in refs/research/acp-*.
  12. Working method worth keeping unchanged: every .tasks/*.md card carries finding, evidence (the actual commands and their output), goal-ref, acceptance, owner. A claim without a command is not a card.

D. Where the three disagree — decisions a new harness must settle

  • Compaction. MikroAgent keeps originals and shrinks only the wire view with a count marker; OpenITT collapses into retrievable digests; agentk goes further into an LLM-summarized DAG. They can be stacked in that order (window → digest + retrieval → optional LLM summary), but not all at once.
  • No LLM in compression (OpenITT's hard line) versus DAG summaries by the model (agentk). Both are defensible for different inputs: log-scale reading wants the deterministic linecomp, conversation history wants structure.
  • Threads. OpenITT forbids them; agentk requires the reactor. A reactor with one state-writing thread and length-framed pipes is the only version that stays portable C99/POSIX and still lets a tool block without freezing the UI.
  • Memory accounting. Only OpenITT takes it seriously, and it is exactly the property that makes a harness trustworthy on an 8 GiB box.
  • Tool-call robustness — the gap that killed Pi on the MacBook today, and that none of the three addresses. Measured there: the model emitted <tool>{...}</tool> while the template and the parser expect <tool_call>, so tool_calls came back null even with tool_choice: "required". A new harness can fix that cheaply: accept all three shapes (<tool>, <tool_call>, native tool_calls), retry once on a malformed call with the parse error as the observation, and log which format the model actually used.

Summary of the pile: MikroAgent is the engine that already runs, OpenITT has the data model and the low-memory discipline, agentk has the compaction theory. A new harness that ignores any of the three will rebuild it badly.