@@ -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.