@@ -0,0 +1,341 @@
1+# mini-coder
2+
3+A fast, transparent, config-first terminal coding agent for one user at a time.
4+
5+This document records the intent and the decisions behind the code. The code is
6+the source of truth for behavior; this is the contract for anyone changing it.
7+
8+## Intent
9+
10+- A small, auditable agent core with no hidden machinery.
11+- A minimal system prompt with no injected meta-guidance.
12+- Provider work delegated entirely to `pi-ai`.
13+- Durable, user-owned, readable session logs.
14+- An append-only TUI with a small bounded live region and no full-screen buffer.
15+- First-class local (Ollama / llama.cpp / vLLM) and hosted models on equal footing.
16+
17+Prior art is reference, not template. `x.x.x-archive` holds the previous
18+implementation; `../awl/` (append-only live-region TUI, config-driven design),
19+`../bough/` (layer boundaries), and `../agent-ide/` (session durability, streaming)
20+are references. Extract ideas, do not port code.
21+
22+## Hard constraints
23+
24+- **Node.js directly.** No Bun, no Deno, no `Bun.*`, no Bun package scripts.
25+ Everything must work with `node`/`npm`.
26+- **No TUI library or framework.** No `cel-tui`, `OpenTUI`, `blessed`, `Ink`, or
27+ React. Render with direct `process.stdout` ANSI writes and plain strings.
28+- **`pi-ai` owns the provider layer.** All model requests, provider adapters,
29+ wire formats, streaming, auth resolution, and usage accounting go through
30+ `@earendil-works/pi-ai`. Never re-implement a provider protocol or fork it.
31+- **Do not copy other coding agents' source code.** Pi and `pi-ai` are behavioral references; write original code.
32+- **No sandboxing, no permission layer.** Tools run with the user's permissions.
33+ Isolation is an environment concern (`nono`), not the agent's. No jail,
34+ approval gate, or supervisor.
35+- **No loop limits.** No max turns, tool calls, token budgets, or agent-imposed
36+ timeouts. The user's ability to interrupt is the limit.
37+- **Config-first.** Every user-facing behavior that can vary comes from config
38+ with a sane default.
39+- **Minimal context.** The model sees only the configured system prompt plus
40+ explicitly opted-in resource files. No doom-loop reminders, hidden
41+ `<system-reminder>` blocks, internal-behavior text, or harness meta-text.
42+
43+## Runtime and repo shape
44+
45+- TypeScript, ESM, `"type": "module"`, `strict`, `erasableSyntaxOnly`,
46+ `verbatimModuleSyntax`.
47+- TypeScript runs directly through Node's native type stripping (`node src/cli.ts`).
48+ Use relative imports with explicit `.ts` extensions. Avoid non-erasable syntax
49+ (`enum`, `namespace`, parameter properties, legacy decorators).
50+- `bin/mini-coder.ts` is a thin shebang shim importing `src/cli.ts`.
51+- Module boundaries (names may change, boundaries may not move):
52+ - `cli` — argument parsing, mode selection, process wiring.
53+ - `config` — load, validate, merge, resolve config; build `pi-ai` models.
54+ - `session` — append-only JSONL store; projection to a `pi-ai` `Context`.
55+ - `agent` — streaming loop, tool dispatch, pause/cancel state. No UI, no
56+ provider-specific code.
57+ - `tools` — `edit`, `bash` runners. No UI.
58+ - `prompt` — system-prompt assembly (config, skills, `AGENTS.md`).
59+ - `tui` — terminal live region and input editor; a projection of agent events.
60+- The agent must not import `tui`. The TUI must not own agent or provider
61+ semantics. Headless and TUI are two projections of the same agent events.
62+
63+## Configuration
64+
65+Global config only, at `$XDG_CONFIG_HOME/mini-coder/config.json`
66+(default `~/.config/mini-coder/config.json`). No project-local config, no
67+config-override flags. A missing file is valid and uses defaults.
68+
69+Because `pi-ai` owns the provider catalog, auth env vars, base URLs, wire APIs,
70+and compat detection, model config stays thin. A built-in provider needs only
71+`provider` + `model`; `customProviders` exists only for endpoints `pi-ai` does
72+not ship.
73+
74+Fields and defaults:
75+
76+- `sessionsDir` — root for per-session directories. Default `<cwd>/sessions`.
77+- `systemPrompt` — base system prompt. Default `""`.
78+- `discoverAgentFiles` — include discovered `AGENTS.md`/`CLAUDE.md`. Default `true`.
79+- `skillsDirs` — directories scanned for `SKILL.md`. Default `[]` (no skills).
80+- `tools` — enabled tool names. Default `["edit", "bash"]`.
81+- `provider` — built-in `pi-ai` provider id or a `customProviders[].id`.
82+ Default `"anthropic"`.
83+- `model` — model id within that provider. Default `"claude-sonnet-4-5"`.
84+- `thinkingEffort` — one of `minimal`, `low`, `medium`, `high`, `xhigh`, `max`.
85+ Default `"medium"`.
86+- `customProviders` — array; default `[]`. Each entry:
87+ - `id` (matches the active `provider`),
88+ - `name` (display; defaults to `id`),
89+ - `baseUrl`,
90+ - `api` — explicit `pi-ai` wire id: `openai-completions`,
91+ `openai-responses`, `anthropic-messages`, or `google-generative-ai`. Never
92+ inferred from a name or URL,
93+ - `models` — model ids served there,
94+ - `envKeys` — optional credential env vars; omit for keyless local servers,
95+ - `headers` — optional extra request headers.
96+
97+Decisions:
98+
99+- Built-in models are looked up in `pi-ai`'s catalog. Do not duplicate catalog
100+ data or env vars in mini-coder.
101+- Omitted custom-model metadata uses safe defaults (`reasoning: false`,
102+ `input: ["text"]`, zero cost, 200k context, 32k max tokens). `pi-ai`
103+ auto-detects `compat` from `baseUrl`; add overrides only when a concrete
104+ endpoint misbehaves.
105+- `headers` merge into requests and are kept out of session records.
106+- Unknown `tools` names and unknown config keys are config errors. Validate at
107+ load and name the failing field.
108+
109+## Provider integration
110+
111+Use `pi-ai` entrypoints: `builtinModels()` / `createModels()`,
112+`createProvider({ id, name, baseUrl, auth, models, api })`,
113+`envApiKeyAuth(displayName, envVars)`,
114+`models.streamSimple(model, context, { reasoning, signal, sessionId })`, and the
115+`Type` re-export. Import API implementations only from
116+`@earendil-works/pi-ai/api/<api>.lazy` so unused provider SDKs are not bundled.
117+
118+Decisions:
119+
120+- Register built-ins with `builtinModels()` and custom entries with
121+ `createProvider`. Keyless custom providers get a stub auth that resolves a
122+ placeholder key rather than an env lookup.
123+- Auth is entirely `pi-ai`'s. Credentials resolve from env vars only; stored
124+ credentials, login flows, and a persistent `CredentialStore` are deferred.
125+- Keep the adapter thin. Consume `pi-ai` message/stream types directly; do not
126+ translate them into a parallel model. Keep provider-specific continuation data
127+ (opaque blocks, signatures) intact in the session.
128+
129+## Session persistence
130+
131+`pi-ai` ships no session store. The session layer is a thin append-only JSONL
132+wrapper over `pi-ai`'s own `Context`/`Message` types. Never invent a parallel
133+message model.
134+
135+One JSON object per line; never rewrite or delete committed lines. Records:
136+
137+- `{ type: "session", version: 1, id, cwd, createdAt, title }` — first line,
138+ written once.
139+- `{ type: "request", at, provider, model, api, thinkingEffort, systemPrompt,
140+ tools }` — written before each model request, capturing resolved inputs.
141+- `{ type: "message", at, message }` — each conversation message, stored as a
142+ `pi-ai` `Message` verbatim.
143+
144+Directory and file layout:
145+
146+```
147+<sessionsDir>/<YYYYMMDD>-<HHmmss>-<slug>-<shortid>/session.jsonl
148+```
149+
150+- The directory name is the session `id` and the canonical key. Never rename it.
151+- `YYYYMMDD-HHmmss` is UTC creation time, keeping `ls` chronological.
152+- `slug` comes from the first user message: lowercased, non-alphanumerics
153+ collapsed to `-`, trimmed, truncated to ~40 chars, falling back to `session`.
154+ The same function produces the `title`.
155+- `shortid` is 6 random base36 chars, disambiguating same-second, same-title
156+ sessions.
157+- Ensure `sessionsDir` recursively; create the session directory with exclusive
158+ `mkdirSync` and regenerate `shortid` on `EEXIST` (bounded attempts). No locks.
159+- Create lazily on the first user message so the slug is meaningful; the session
160+ is in-memory before that.
161+- One writer per session directory.
162+- Append with `writeSync` + `fsyncSync` so committed lines survive a crash. A
163+ persistence failure stops the turn; never continue with unrecorded side
164+ effects.
165+- On read, tolerate a truncated final line; reject corruption in committed
166+ history.
167+- Preserve message order and tool-call ↔ tool-result relationships. If partials
168+ are ever persisted, use `AssistantMessageFrameEncoder` /
169+ `reduceAssistantMessageFrames`, not a custom frame format.
170+
171+## Agent loop
172+
173+One loop, no limits. Per turn: assemble `{ systemPrompt, tools, messages }`,
174+`for await` over `streamSimple`, surface text/reasoning/tool-call events, append
175+the final assistant message, then execute any tool calls in order, appending
176+each result, and repeat. Stop when the assistant produces no tool calls, on
177+cancel, or on a surfaced error.
178+
179+Phases: `preparing`, `waitingModel`, `streaming`, `runningTool`, `pausing`,
180+`idle` (plus `cancelled` reachable from active states). Events: `phase`, `text`,
181+`reasoning`, `toolCall`, `toolOutput`, `toolResult`, `message`, `error`,
182+`cancelled`, `complete`.
183+
184+Decisions:
185+
186+- No compaction, summarization, or context rewriting.
187+- No automatic retries. Provider errors are surfaced, not hidden.
188+- No reminders or meta-messages between steps.
189+- The loop is driven by an `AbortSignal` and checks pause state at step
190+ boundaries (top of each iteration and before each tool call).
191+
192+## Tools
193+
194+`edit` and `bash` only. Stateless; recoverable failures return tool-result text,
195+not thrown errors. There is no `read` tool — the model reads files with Unix
196+tooling through `bash`. Tool arguments are untrusted input and are validated at
197+the boundary with Typebox (`Value.Parse`); application logic uses plain types.
198+
199+- **`edit`** — `{ path, oldText, newText }`. Exact find-and-replace. Fails when
200+ `oldText` is missing or matches more than once. Empty `oldText` creates a new
201+ file and fails if it exists. Returns a unified diff via `createTwoFilesPatch`
202+ from the `diff` package. Checks the abort signal before writing.
203+- **`bash`** — `{ command }`. Runs `bash -c` in `process.cwd()` in its own
204+ process group (`detached: true`) so cancellation can kill the whole tree.
205+ Streams stdout/stderr through `onOutput`, then returns combined output plus
206+ exit code. On abort, SIGTERM the group, then SIGKILL after a short grace.
207+ Output is bounded (10k head + 6k tail) and truncation is reported in
208+ `details` (`truncated`, `omittedChars`, `totalChars`) rather than silently
209+ dropped. No default timeout.
210+
211+Only tools named in config `tools` are exposed and may execute. No approval
212+prompts, sandboxing, or per-tool budgets.
213+
214+## System prompt assembly
215+
216+In order: config `systemPrompt`, then skills (when `skillsDirs` is non-empty),
217+then agent files (when `discoverAgentFiles`).
218+
219+- Agent files: load `AGENTS.md` and `CLAUDE.md` from `~/.agents/` and the project
220+ root (`process.cwd()`), trimmed, each under a heading naming its path.
221+- Skills: scan each `skillsDirs` entry for `<dir>/SKILL.md`, read its
222+ frontmatter (`name`, `description`), and advertise the absolute path so the
223+ model can read it with `bash` on demand. Progressive disclosure only — never
224+ inline skill bodies. No directories means no skills; there is no implicit
225+ global or project-local discovery.
226+- No other injected instructions, reminders, or environment blobs.
227+
228+## TUI
229+
230+Normal terminal screen. No alternate screen, no full-screen buffer, no
231+persistent cursor modes. Styling is unconstrained: SGR attributes and colour,
232+live or committed, are the renderer's choice, and `src/tui/` owns it. No flicker:
233+coalesce writes (16ms frame cadence) and never redraw committed output.
234+
235+Two regions:
236+
237+- **Committed history** — printed once to terminal scrollback and never
238+ redrawn. User turns, assistant text, tool calls, and tool results go here. The
239+ terminal owns scrollback, selection, and scrolling.
240+- **Live region** — at most the height of the terminal minus one row, holding
241+ the in-flight line (the current incomplete line of whichever stream is
242+ active), a one-row phase status, and the editor. Only this region is redrawn.
243+ When idle it holds the editor alone: no in-flight line, no status row.
244+
245+Scrollback is append-only and written before the live region is redrawn, never
246+after. Blocks — a user turn, a tool call with its result body, a terminal-state
247+line — are separated by exactly one blank line, never two, and never as the
248+first line. Each tool block is committed as a unit when its result arrives, so a
249+call and its body stay contiguous even when one assistant message announces
250+several calls before any of them runs.
251+
252+Redraw: move to the top of the live region, erase to end of screen, rewrite.
253+Track the region's height exactly: it changes when the status row appears or
254+disappears and when the in-flight line wraps, so erasing it means erasing every
255+occupied row, not one. When content is committed, print it above the live region
256+and shrink the region before the next frame. On `SIGWINCH`, drop the cursor
257+anchor and re-anchor rather than guessing; never erase committed history. Handle
258+wrapping, Unicode width, and tiny terminals without corrupting scrollback.
259+
260+Input editor (notepad-level, not Vim/readline parity): multiline
261+insertion/deletion, cursor movement across lines, reliable typing, backspace,
262+newline, and large bracketed paste. `Enter` submits; `Ctrl+J` inserts a newline
263+(`Shift+Enter` also maps to newline where the terminal sends it). The draft
264+survives redraws, cancellation, and errors. No undo/redo, history search, or
265+path completion.
266+
267+Terminal lifecycle: raw mode only in interactive mode; bracketed paste enabled;
268+restore prior mode, cursor visibility, and modified state on exit, cancel, and
269+`SIGINT`/`SIGTERM`. Re-read size on resize. Use `process.stdout.columns`/`rows`
270+with fallbacks for `0`/undefined. Escape sequences are parsed by a small state
271+machine with a short timeout to distinguish a lone ESC from a sequence.
272+
273+## Interruption and lifecycle
274+
275+- **ESC = polite pause request.** It never interrupts the current step: the
276+ in-flight model request completes and the running tool runs to completion. The
277+ loop then pauses at the next boundary for a steering message, which is
278+ appended before the turn continues.
279+- **CTRL+C = cancel the turn completely.** Abort the model request via
280+ `AbortSignal` and terminate the running tool's process group. Persist the
281+ aborted assistant message (`stopReason: "aborted"`). Return to idle; do not
282+ undo completed side effects.
283+- **CTRL+D = exit**, only when the input is empty. Flush the session, restore the
284+ terminal, exit cleanly.
285+- No max turns, tool-call budget, or automatic stop.
286+
287+## Headless mode
288+
289+`-p` / `--print` is the only CLI interface and the only flag. It runs one prompt
290+to completion non-interactively and prints the final assistant answer to stdout.
291+Accepted spellings: `-p <prompt>`, `--print <prompt>`, `-p=<prompt>`,
292+`--print=<prompt>`; unknown arguments are errors.
293+
294+- Persists the session under `sessionsDir` exactly like interactive mode; the
295+ JSONL log is the durable record. No other machine-readable stdout mode.
296+- Diagnostics, tool progress, and errors go to stderr.
297+- Never emit ANSI escapes or terminal controls when not a TTY; never wait for
298+ prompts.
299+- Exit `0` on success, non-zero on failure/cancel.
300+
301+## Reliability and diagnostics
302+
303+- Persistence failure stops the turn.
304+- Surface provider errors with their message; do not mask, summarize, or retry.
305+- Local diagnostics only. No remote telemetry. Debug output goes to stderr
306+ behind an explicit flag; redact secrets and prompt/tool content by default.
307+- No hidden stalls: every wait (model request, tool, pause) has a visible state
308+ in the TUI and a diagnostic path in headless mode.
309+
310+## Scope boundaries
311+
312+Deferred, not rejected. Do not build unless explicitly promoted:
313+
314+- context compaction / summarization / masking;
315+- prompt templates;
316+- custom agents / subagents / delegation;
317+- an extension or plugin system;
318+- a settings TUI or overlay editors;
319+- custom OAuth or auth implementations (use `pi-ai`'s provider auth);
320+- MCP, image generation, multi-agent orchestration;
321+- sandboxing, approval prompts, permission policies;
322+- tests and CI (standing rule: no tests unless asked);
323+- macOS/Windows behavior and cross-platform abstractions. Target Linux first.
324+
325+## Working agreement
326+
327+- Read `pi-ai`'s README and the reference projects before designing. Trace the
328+ real data flow; apply guards at the narrowest boundary.
329+- Keep the diff small. Do not opportunistically refactor or harden adjacent
330+ code.
331+- Prefer plain functions and objects over classes; keep exports minimal; define
332+ helpers near their use.
333+- Validate untrusted input once at the boundary (config, session records, tool
334+ args) with Typebox, then keep internal code plain-typed. Do not spread
335+ schema-derived types everywhere.
336+- Ask before adding a dependency. `diff` and `typebox` are approved;
337+ supply-chain risk is a real constraint.
338+- Do not add tests unless explicitly asked. Verify manually.
339+- Before finishing, review the diff against the hard constraints and the scope
340+ boundaries, remove anything that added scope, and report any requirement that
341+ could not be satisfied.