xonecas.io
79113
Ma

mini-coding-agent / commit 419db24

feat: initial docs

xonecas2026-10-04 419db249db09c43a551592ce9107e63f5259976d

2 files changed

AGENTS.md+177−0
@@ -0,0 +1,177 @@
1+# mini-z-agent (`mza` for short)
2+
3+A fast, transparent, config-first terminal coding agent for one user at a time.
4+A careful Zig port of mini-coder.
5+
6+This file holds intent, direction, and guardrails — not a description of the
7+code. The source is the source of truth for behavior. If a fact can be learned
8+by reading the code, it does not belong here; keep this file short.
9+
10+## Intent
11+
12+- A small, auditable core with no hidden machinery.
13+- A minimal system prompt with no injected meta-guidance.
14+- Provider work implemented in-tree over a small set of wire protocols.
15+- Durable, user-owned, readable session logs.
16+- An append-only TUI with a bounded live region and no full-screen buffer.
17+- Local models (Ollama / llama.cpp / vLLM) and hosted models treated as equals.
18+- One `zig build` produces one static binary. No runtime, no interpreter, no
19+ Node, no `node_modules`, no post-install scripts, no supply chain beyond what
20+ the code needs.
21+
22+## Provenance
23+
24+This project is a port. Its references are behavioral and structural, not
25+templates to copy:
26+
27+- `../mini-coder/` — the TypeScript implementation. The behavior specification.
28+ Port its behavior, never its code.
29+- `../tiny-c-agent/` — a careful C port of the same design. The detail reference
30+ for the low-level work: the four wire protocols, streaming reassembly, diff
31+ capture, UTF-8 and base64 handling, session durability. Consult its structure
32+ and its comments when porting those layers.
33+- `../zig-agent-kanso/` — an experimental one-shot Zig port. The idiom reference
34+ for current Zig: the allocator wiring, `std.http.Client` for SSE streaming,
35+ the tree-sitter module integration, `build.zig.zon` dependency pinning. It is
36+ a starting point for language technique, not for correctness or completeness —
37+ it has known gaps in the provider layer and it swallows errors.
38+
39+## Direction
40+
41+Deferred, not rejected. Do not build unless explicitly promoted:
42+
43+- context compaction / summarization / masking;
44+- reading or resuming sessions (the JSONL log is write-only today);
45+- prompt templates; custom agents / subagents / delegation;
46+- an extension or plugin system; a settings TUI; overlay editors;
47+- OAuth and any custom auth flow (environment keys and stored credentials only);
48+- MCP, image generation, multi-agent orchestration;
49+- sandboxing, approval prompts, permission policies;
50+- tests and CI (standing rule: no tests unless asked);
51+- macOS/Windows support and cross-platform abstractions. Target Linux first.
52+
53+## Guardrails
54+
55+Hard constraints. Do not cross these without explicit direction:
56+
57+- **Zig only.** One `zig build` produces one binary. No Node, Bun, Deno, npm, or
58+ any JS/TS step. A C dependency is allowed only when explicitly approved.
59+- **No TUI library or framework.** Render with direct ANSI writes to stdout:
60+ append-only scrollback plus a bounded live region. No alternate screen, no
61+ full-screen cell grid.
62+- **The provider layer is in-tree.** Implement the wire protocols directly —
63+ `openai-completions`, `openai-responses`, `anthropic-messages`,
64+ `google-generative-ai`. Never depend on another harness's provider code.
65+- **Write original code.** `../mini-coder/` is a behavioral reference only.
66+- **No sandbox or permission layer.** Tools run with the user's permissions;
67+ isolation is an environment concern, not the agent's.
68+- **No loop limits.** No max turns, tool calls, token budgets, or agent-imposed
69+ timeouts. The user's ability to interrupt is the limit.
70+- **Config-first.** Every user-facing behavior that can vary comes from config
71+ with a sane default. Global config only — no project-local config, no
72+ config-override flags — and never duplicate a provider's catalog or env vars.
73+- **Minimal context.** The model sees the configured system prompt plus
74+ explicitly opted-in resource files — never reminders, hidden blocks, or
75+ harness meta-text.
76+- **The agent never imports the TUI.** Headless and TUI are two projections of
77+ the same agent events; the TUI owns no agent or provider semantics.
78+
79+## Invariants
80+
81+- Sessions are append-only JSONL, one message per line, fsynced on write. Never
82+ rewrite or delete committed lines. A persistence failure stops the turn. Every
83+ model step also records the exact request: system prompt, tools, provider,
84+ model, api, and thinking effort.
85+- The loop has no compaction, no retries, and no meta-messages between steps.
86+ Provider errors surface as-is, never masked or summarized. Steering typed at a
87+ pause lands at the next step boundary, never between a turn and its results.
88+- `edit`, `read`, and `bash` only. Tool arguments are untrusted and validated
89+ once at the boundary. `read` returns image blocks only for models that declare
90+ image input.
91+- `bash` runs detached and kills its process group on cancel. Filesystem
92+ snapshots before and after produce diffs for display only; they never reach
93+ the model.
94+- Terminal output is fully specified: truecolor, an explicit palette for every
95+ cell, no resets that could fall back to the host terminal, and untrusted text
96+ sanitized of every escape sequence except SGR.
97+- Interruption: ESC politely pauses at the next step boundary; Ctrl+C cancels the
98+ turn (abort the request, kill the tool's process group, persist the aborted
99+ message); Ctrl+D exits on an empty draft. Completed side effects are never
100+ undone.
101+- Diagnostics are local only. No telemetry, no hidden stalls.
102+
103+## Memory
104+
105+The port's reason for existing is that manual memory bookkeeping was the C port's
106+largest fragility. Do not reintroduce it.
107+
108+- One allocator, chosen at startup, threaded explicitly. Long-lived state and
109+ per-turn scratch are separate lifetimes, not one global pool.
110+- A turn's transient objects — stream accumulators, tool result text, images,
111+ diffs, serialization buffers — die with the turn. Prefer arena or explicit
112+ lifetime over scattered frees.
113+- **Never swallow an allocation failure.** A dropped message, a silently
114+ truncated stream, or a `catch {}` on an append is a lost turn. Surface it
115+ through the event stream as an error the user can see.
116+- No hidden global mutable state beyond the process-wide allocator and IO
117+ handle, and those are set once at startup.
118+
119+## Verification
120+
121+Verify against the real provider. Do not stand up mock servers, fixture
122+endpoints, or replay files; they stall and prove nothing. Use the
123+`OPENCODE_API_KEY` environment variable and a scratch `XDG_CONFIG_HOME` with a
124+`mini-coder/config.json` that declares the provider under test.
125+
126+OpenCode Zen serves all four wire protocols. Base URLs and the working models:
127+
128+- `openai-completions` — base `https://opencode.ai/zen/go/v1`, model
129+ `deepseek-v4.1-flash` (the daily path, also `opencode-go` in the config).
130+- `openai-responses` — base `https://opencode.ai/zen/go/v1`, model
131+ `gpt-6-luna`.
132+- `anthropic-messages` — base `https://opencode.ai/zen`, model
133+ `claude-haiku-4-5`.
134+- `google-generative-ai` — base `https://opencode.ai/zen/v1`, model
135+ `gemini-3.8-flash`.
136+
137+Every Zen request needs the `x-opencode-session` header; set it via the custom
138+provider's `headers`. Not every catalog model is enabled for the account (for
139+example `claude-opus-5` is disabled and returns `Model access is disabled`), so
140+use the models above. Run a real tool call, not just a text turn.
141+
142+## Driving the TUI with kitty
143+
144+There is no `tmux` here; drive the TUI through kitty's remote control on a
145+private socket, one window per session:
146+
147+ kitty --detach --listen-on unix:/tmp/mz-<name>.sock \
148+ -o allow_remote_control=yes -o remember_window_size=no \
149+ -o initial_window_width=100c -o initial_window_height=30c \
150+ --title mz-<name> env PS1='\n$ ' bash --norc --noprofile -i
151+
152+Run every `kitty @ --to unix:/tmp/mz-<name>.sock` call through that socket; the
153+window id comes from `ls`, don't assume it. Run the app (`./zig-out/bin/mza`)
154+with a scratch cwd so its tool calls write nowhere that matters.
155+
156+- `send-text` types literal text and never submits — Enter is its own key,
157+ `send-key enter`, and it does nothing while a turn is active.
158+- `send-key` for named keys: `enter escape ctrl+c ctrl+d shift+enter tab`.
159+- `get-text -m id:N --extent=all --ansi` returns the pane with the app's
160+ truecolor SGR — assert colors from those escapes, not from pixels;
161+ `--extent=screen` is the live screen alone.
162+- `screenshot -m id:N out.png` for the visual check; `identify` it and look at
163+ it before trusting it.
164+
165+## Working agreement
166+
167+- Trace the real data flow before designing; apply guards at the narrowest
168+ boundary.
169+- Keep the diff small. Do not opportunistically refactor or harden adjacent code.
170+- Prefer plain functions and explicit allocators; keep exports minimal; define
171+ helpers near their use.
172+- Validate untrusted input once at the boundary, then keep internal code
173+ plain-typed with no runtime checks.
174+- Ask before adding a dependency.
175+- Do not add tests unless explicitly asked; verify manually.
176+- Before finishing, review the diff against the direction and guardrails, remove
177+ anything that added scope, and report any requirement you could not satisfy.
port-prompt.md+147−0
@@ -0,0 +1,147 @@
1+# Task: port mini-coder to Zig as `mini-z-agent`
2+
3+You are starting `mini-z-agent` (`mza`), a Zig port of `mini-coder`. Read
4+`AGENTS.md` in this directory first and follow it. It is the law. This document
5+is the work order; `AGENTS.md` governs every decision.
6+
7+## Context you need
8+
9+`mini-coder` (`../mini-coder/`) is a TypeScript terminal coding agent that works.
10+It is the behavior specification. Below it in this conversation there is a
11+history: two earlier ports of it exist.
12+
13+- `../tiny-c-agent/` — a careful C port. It translated the design faithfully and
14+ is the best low-level detail reference available: the four wire protocols,
15+ streaming reassembly, diff capture, UTF-8 and base64 handling, session
16+ durability. It is also the cautionary tale. Moving to C meant reimplementing,
17+ by hand, everything the TypeScript version got from its runtime and from
18+ `pi-ai`: HTTP, JSON, an SSE parser, a diff engine, a UTF-8 validator, base64.
19+ That produced 10,207 lines against the reference's 3,575, 552 `free()` calls,
20+ 33 `abort()` calls, and a commit titled `fix: memory fixes`.
21+- `../zig-agent-kanso/` — an experimental, one-shot Zig port. It proves the
22+ language fit: one `zig build`, four hash-pinned tree-sitter dependencies, no
23+ `pkg-config` on the host, 6,745 lines, nine deinit sites, zero `abort()`.
24+ `std.http.Client` replaced libcurl, `std.json` replaced a C JSON library, and
25+ one startup allocator replaced the manual free bookkeeping entirely. It is
26+ also incomplete and less careful than tiny: the provider layer has gaps, and it
27+ silently swallows errors in several places (`catch {}` on message and session
28+ appends).
29+
30+Your job is to combine them: mini's behavior, tiny's care, and kanso's Zig.
31+
32+## The goal, stated plainly
33+
34+One static binary with no runtime, no interpreter, no `node_modules`, no
35+post-install scripts, and a dependency surface only as large as the work needs.
36+Small in all aspects. This is the reason the project exists. Weigh every decision
37+against it.
38+
39+## What is fixed
40+
41+These are inherited and are not open for redesign. Port them as they are:
42+
43+- Three tools: `read`, `edit`, `bash`.
44+- The four wire protocols: `openai-completions`, `openai-responses`,
45+ `anthropic-messages`, `google-generative-ai`.
46+- Append-only JSONL sessions, fsynced, one message per line, plus a request
47+ record per model step. Never rewrite a committed line.
48+- The agent loop's shape: no compaction, no retries, no meta-messages. Steering
49+ lands at a step boundary, never between an assistant turn and its tool results.
50+- Interruption: ESC pauses politely at the next boundary, Ctrl+C cancels the turn
51+ and kills the tool's process group, Ctrl+D exits on an empty draft.
52+- The event stream as the single seam between the agent and its two projections,
53+ headless and TUI. The agent never imports the TUI.
54+- Config-first, global config only.
55+- The TUI's appearance and behavior: append-only scrollback, a bounded live
56+ region, truecolor with an explicit palette for every cell, no resets that fall
57+ back to the host terminal, untrusted text sanitized of every non-SGR escape.
58+
59+## What you must decide and own
60+
61+### Memory
62+
63+This is the point of the port, so treat it as a design decision, not a detail.
64+
65+- Choose the allocator strategy at startup and thread it explicitly. Long-lived
66+ state and per-turn scratch are different lifetimes.
67+- Do not copy kanso's single global pool. It avoids `free()` by never releasing,
68+ which is not the same as being correct.
69+- Per-turn transient objects — stream accumulators, tool result text, images,
70+ diffs, serialization buffers — should die with the turn. Arena or explicit
71+ lifetime, your choice, but the code must show the lifetime.
72+- **Never swallow an allocation failure.** `catch {}` on a message or session
73+ append loses a turn silently. Every such failure reaches the event stream as a
74+ visible error. This is a hard rule in `AGENTS.md` and it is the specific
75+ mistake kanso made.
76+
77+### Provider layer
78+
79+This is the largest and highest-risk part. Port the encoders and the streaming
80+reassembly from tiny's structure, because tiny's comments encode decisions that
81+are not visible in mini's behavior and are easy to reintroduce as bugs:
82+
83+- Untrusted stream indices are hints, never sizes. Bound them.
84+- Image blocks among a run of tool results are placed so a user message never
85+ lands between an assistant turn and its tool results.
86+- Provider errors surface as-is, never masked or summarized.
87+- Provider-specific continuation data is kept intact.
88+
89+Validate the wire formats against reality, not against your reading of them.
90+
91+### Dependencies
92+
93+Keep the set small and justified. `std` replaces most of what tiny needed C
94+libraries for. tree-sitter and its grammars are the known external need. Any
95+addition beyond that is a decision to raise, not to take.
96+
97+## Order of work
98+
99+Do not port wide. This is a port of a working product, and the risk is breadth.
100+
101+Build one vertical slice first and make it work end to end:
102+
103+1. `zig build` skeleton: `build.zig`, `build.zig.zon`, one binary named `mza`,
104+ the allocator chosen at startup, config loading, the `--print` headless path,
105+ and the `read` tool. Prove a single turn streams text and persists a session
106+ with `openai-completions`, because opencode-go uses it and it is the daily
107+ path (Key is available to use in env `OPENCODE_API_KEY`, and a suggested
108+ config in `~/.config/mini-coder`).
109+2. Add `edit` and `bash`, the filesystem snapshot diff, and the headless event
110+ projection.
111+3. Build the TUI on the same event stream: append-only scrollback, bounded live
112+ region, themes, syntax highlighting via tree-sitter, diff rendering.
113+4. Add the remaining three wire protocols, one at a time, each verified on its
114+ own before the next.
115+
116+Each step must build, run, and be usable at its end. Do not land a step that is
117+half-done.
118+
119+## Verification
120+
121+The oracle discipline is what made the C port careful, and it is load-bearing
122+here because you will read Zig less fluently than TypeScript. Use it.
123+
124+- `../mini-coder/` is the behavioral oracle. Run the same prompt through both and
125+ compare the session JSONL and the visible output.
126+- For the provider layer, `../tiny-c-agent/` is a second oracle. Its four API
127+ modules are the careful translation; compare request bodies and assembled
128+ messages where you can.
129+- Verify the TUI with the kitty remote-control procedure in `../mini-coder/AGENTS.md`.
130+- Tests and CI are deferred by standing rule. Verify manually. Do not add a test
131+ suite.
132+
133+## Non-goals
134+
135+Do not build these; they are deferred by explicit decision in `AGENTS.md`:
136+compaction, resume, prompt templates, subagents, plugins, a settings TUI,
137+OAuth, MCP, sandboxing, macOS/Windows support, tests, CI.
138+
139+## Report
140+
141+When you finish a step, report:
142+
143+- The files you added or changed and the shape of each.
144+- The memory strategy you chose and why it fits the lifetimes.
145+- Any place you made a judgment call between mini's behavior and tiny's
146+ structure, and which you followed.
147+- Any requirement in `AGENTS.md` or this document you could not satisfy.