@@ -1,112 +1,69 @@
11 # Mini Coder — Agent Instructions
22
3-- **Spec-driven development**: `spec.md` is the single source of truth for design and behavior. Read it before making changes. Do not deviate from the spec without discussion.
4-- **TDD**: write tests first, then implement. Tests validate the spec's defined behaviors.
3+- **Spec-driven development**: `spec.md` is the source of truth for behavior and design. Read it before changing code. Do not deviate without discussion.
4+- **TDD**: write tests first, then implement.
55 - Use Conventional Commits formatting for commit messages.
66 - Before committing code changes, review the diff with the user and get approval for the commit.
77
8-## Repo
8+## Session bootstrap
99
10-- Runtime: Bun. Use `bun run` for scripts, `bun test` for tests, `bun install` for deps, `bunx` instead of `npx`.
11-- Toolchain split: **prettier** owns all formatting, **biome** owns linting + import sorting (formatter disabled to avoid conflicts). Both fail CI on violations.
12- - `bun run check` — biome: lint rules + organize imports.
13- - `bun run format` — prettier: check formatting.
14- - `bun run typecheck` — tsc --noEmit.
15- - `bun test` — bun test runner.
16- - `bun run check:fix` / `bun run format:fix` — auto-fix.
17-- Lefthook pre-commit runs all four steps sequentially (`--silent`, `parallel: false`).
18-- App data directory: `~/.config/mini-coder/`.
19-- Local manual CLI testing on this machine uses `bun add -g /home/xonecas/src/mini-coder`, which links the working tree into `~/.bun/bin/mc` without publishing. Re-run that after changing bin wiring if the global command needs to be refreshed.
20-- The rewrite's published CLI entrypoint is `mc` via the checked-in Bun launcher at `bin/mc.ts` (importing `src/index.ts`). Do not point `package.json#bin` at a `dist/` file unless the publish flow actually generates that artifact.
21-- All exports should have JSDoc comments (descriptions, `@param`, `@returns`). Interface fields get single-line JSDoc. See `session.ts` for the established pattern.
22-- Key dependency source code for reference:
23- - pi-ai: `~/src/pi-mono/packages/ai/` — LLM provider SDK. See `src/types.ts` for core types, `src/stream.ts` for streaming API, `src/utils/oauth/` for OAuth, `src/providers/faux.ts` for test provider.
24- - cel-tui: `~/src/cel-tui/` — TUI framework. See `spec.md` for full API, `examples/chat.ts` for the chat UI pattern, `packages/components/src/markdown.ts` for Markdown component.
10+- Read `spec.md`, then `TODO.md`, then inspect `git status --short` / `git diff`.
11+- Treat `TODO.md` as the current verified work queue. For spec-alignment work, confirm the mismatch in code before editing.
12+- Keep `TODO.md` minimal and current; remove completed items instead of accumulating history.
2513
26-## Code style
14+## Code map
2715
28-- Do not inline `import` calls. Don't duplicate code. Don't leave dead code behind.
29-- Don't re-implement helpers that already exist, always consolidate.
30-- Keep it minimal — don't add abstractions for hypothetical futures.
31-- Performance matters. Prefer fast paths.
16+- `src/index.ts` — startup, providers, settings, AGENTS.md/skills/plugins loading, theme assembly, shared app state.
17+- `src/agent.ts` — streaming model loop, tool dispatch, agent events.
18+- `src/tools.ts` — built-in tools and truncation logic.
19+- `src/session.ts` — SQLite persistence, turn numbering, undo/fork, prompt history, cumulative stats.
20+- `src/prompt.ts`, `src/skills.ts`, `src/plugins.ts` — prompt assembly and external context discovery/loading.
21+- `src/ui.ts` — cel-tui lifecycle and top-level orchestration.
22+- `src/ui/agent.ts` — input submission, streaming state, agent-loop wiring.
23+- `src/ui/commands.ts` — slash commands and Select overlays.
24+- `src/ui/conversation.ts`, `src/ui/status.ts`, `src/ui/input.ts`, `src/ui/help.ts`, `src/ui/overlay.ts` — focused rendering/helpers.
3225
33-## Working with dependencies
26+## Repo
3427
35-- **Study before using.** Before writing code against a dependency, read its examples, types, and tsconfig. Match the dependency's conventions — don't fight them.
36-- **Match tsconfig constraints.** If a dependency ships `.ts` source (e.g., cel-tui), our tsconfig must be compatible with theirs. Relax our config to match, not the other way around. Never add lint-ignore comments or type casts to work around mismatched strictness settings.
37-- **Follow established patterns.** Dependencies with examples (e.g., `cel-tui/examples/chat.ts`) define the canonical usage patterns. Copy those patterns exactly before customizing. Don't invent alternative approaches.
38-- **Verify visual correctness.** For UI code, think through rendering on both light and dark terminals. Test color choices against both backgrounds. The spec says "adapts to the user's terminal color scheme" — that means colors must be legible in both contexts.
39-- **Understand layout before rendering.** For TUI frameworks, understand how the layout engine determines dimensions (intrinsic vs fixed vs flex vs fill). Never hardcode dimensions that the framework should compute.
28+- Runtime: Bun. Use `bun run`, `bun test`, `bun install`, `bunx`.
29+- Toolchain split: **prettier** formats, **biome** lints + sorts imports. CI runs `bun test`, `bun run check`, `bun run format`, and `bun run typecheck`. Lefthook runs the same steps sequentially.
30+- App data dir: `~/.config/mini-coder/`.
31+- Local manual CLI testing on this machine uses `bun add -g /home/xonecas/src/mini-coder`, which links the working tree into `~/.bun/bin/mc`.
32+- Published CLI entrypoint is `mc` via `bin/mc.ts` → `src/index.ts`. Do not point `package.json#bin` at `dist/` unless publish actually produces it.
33+- All exports need JSDoc; interface fields get single-line JSDoc. See `session.ts` for the pattern.
34+- Dependency references:
35+ - pi-ai: `~/src/pi-mono/packages/ai/` (`src/types.ts`, `src/stream.ts`, `src/utils/oauth/`, `src/providers/faux.ts`)
36+ - cel-tui: `~/src/cel-tui/` (`~/src/cel-tui/spec.md`, `examples/chat.ts`, `packages/components/src/markdown.ts`)
4037
41-## Lessons learned
38+## Project rules
4239
43-- **Never rush an implementation.** A broken implementation that compiles is worse than no implementation — it wastes review time, erodes trust, and the rework costs more than doing it right the first time.
44-- **Don't suppress lint warnings for future code.** If code doesn't exist yet, don't add `biome-ignore` or `// @ts-ignore` comments for it. Add them when the code actually exists.
45-- **Dead guards are lies.** Type guards for impossible types (e.g., `typeof c !== "string"` when the type is `TextContent | ThinkingContent | ToolCall`) suggest the type can contain those values. They mislead readers and should not exist.
46-- **Event APIs must carry their data.** When an event handler needs data from the event source (e.g., tool call arguments), the event must carry that data. Walking external state to reconstruct it is fragile and breaks with duplicate entries.
47-- **Async callbacks must handle errors.** When a sync callback invokes an async function, the returned promise must be caught. Dropping it silently turns errors into unhandled rejections.
48-- **Respect the phased plan.** Each TODO.md phase has explicit scope. Do not implement features from later phases — even if they feel "easy" or "related." Scope creep wastes review time, introduces bugs from untested code paths, and erodes trust. If something isn't listed in the current phase, it doesn't exist yet.
49-- **Understand callback return semantics.** In cel-tui's `onKeyPress`, returning `false` means "prevent the default action" — returning it unconditionally blocks all typing. Only return `false` for keys you explicitly intercept. Let all other keys fall through with no return.
50-- **Use the dependency's types, not weaker ones.** If a dependency defines a specific type (e.g., cel-tui's `Color`), use it in your own interfaces. Don't weaken to `string` and then cast with `as any` everywhere — that defeats type safety and creates lint noise.
51-- **Read the framework's key dispatch code.** cel-tui intercepts Escape at the framework level (unfocuses before `onKeyPress` fires). Use `onBlur` for dismiss-on-Escape instead of `onKeyPress`. Don't assume events reach component handlers without checking the framework's dispatch order.
52-- **Pass all required options through the call chain.** pi-ai's `streamSimple` needs `apiKey` in options for OAuth providers (env vars aren't set). When adding a new field to a dependency's options, trace the full call path from UI → agent loop → provider to ensure it arrives.
53-- **Display-only state must not leak into model context.** Info messages (login progress, fork confirmation) belong in a separate display array, not `state.messages`. Anything in `state.messages` gets sent to the LLM as conversation history.
54-- **Compatibility policy is a product decision.** Before 1.0, prefer correct, simple semantics over speculative backward-compatibility shims. If a change may affect existing data or behavior, raise it explicitly, but do not implement migrations or compatibility layers unless the spec or user asks for them.
55-- **Breaking changes still need to be called out.** Pre-1.0 is not a license to surprise the user. If a change intentionally trades compatibility for correctness or simplicity, say so explicitly in discussion and keep TODO/release notes aligned.
56-- **TUI changes need real terminal validation.** For rendering, streaming, scrolling, resize, focus, or input changes, passing tests is not enough. Validate the behavior manually in `tmux` before calling the change done.
57-- **Work must stay within the agreed scope.** If you discussed and agreed with a user on the work to be done, don't deviate from it. Don't add scope, or deviate from the agreement.
40+- No inline `import` calls, duplicated helpers, dead code, or speculative abstractions.
41+- Performance matters. Prefer fast paths.
42+- Study dependency examples, types, and tsconfig before integrating them. Match their patterns instead of fighting them.
43+- Use dependency-defined types, not weaker substitutes. Do not hide type/config mismatches with casts or ignores.
44+- For UI work, verify both light/dark terminal legibility and let the layout engine size things.
45+
46+## Durable lessons
47+
48+- Don't add future-facing `biome-ignore`, `@ts-ignore`, or impossible type guards.
49+- Event APIs must carry the data handlers need; do not reconstruct it from unrelated state.
50+- Async callbacks must catch returned promises.
51+- In cel-tui `onKeyPress`, return `false` only for keys you explicitly intercept. Escape often needs `onBlur`, not `onKeyPress`.
52+- When adding provider/tool options, trace them through the full call chain (for example `apiKey` into `streamSimple`).
53+- UI/info messages may live in the persisted log and in `state.messages`, but they must stay marked as UI-only (`role: "ui"`, `turn = NULL`) and always be filtered out of model context.
54+- Prompt context has explicit reload boundaries: AGENTS.md content, discovered skills, and plugin prompt suffixes are stable within a session and should refresh only at boundaries like `/new` or CWD change.
55+- Tool safety truncation and UI `/verbose` preview are separate layers. Do not conflate them.
56+- The plugin API is still in spec-alignment cleanup. Current repo reality is `tools` plus `toolHandlers`; treat that as temporary, not settled design.
57+- Before 1.0, prefer correct/simple semantics over speculative compatibility shims, but call out intentional breaking changes.
58+- TUI changes need real terminal validation in `tmux`; passing tests is not enough.
59+- Stay within the agreed TODO scope. Do not pull in adjacent items without discussion.
5860
5961 ## Testing strategy
6062
61-We test our logic at the boundaries. Never test dependencies (pi-ai, cel-tui, bun:sqlite). Never use mocks or stubs.
62-
63-**Tools** (`tools.ts` — `shell`, `edit`, `readImage`):
64-
65-- `edit`: exact-text match/replace, multi-match failure, missing text failure, new file creation, parent dir creation, existing-file guard, line ending preservation (LF/CRLF), UTF-8 handling, relative/absolute path resolution.
66-- `shell`: stdout/stderr capture, exit code passthrough, output truncation (head + tail with marker), abort signal, cwd propagation.
67-- `truncateOutput`: pure function — within limit, head+tail+marker, no overlap, empty/single-line/exact-limit edge cases.
68-- `readImage`: base64 encoding, mime type detection, unsupported format rejection, missing file handling, relative/absolute path resolution.
69-
70-**Git** (`git.ts`):
71-
72-- Real temp git repos (no mocks). Tests: outside-repo null, repo root, branch name, untracked/modified/staged counts, mixed states, ahead/behind with local bare remote, subdirectory support.
73-
74-**Session persistence** (`session.ts`):
75-
76-- CRUD operations against a real bun:sqlite in-memory database. No mocks.
77-- Turn numbering: user message gets MAX+1, subsequent messages share the turn.
78-- Undo: deletes correct turn, leaves others intact.
79-- Fork: copies all messages, new session id, preserves turn order.
80-- Truncation: keeps most recent N sessions per CWD, cascades to messages.
81-- Cumulative stats computation from message history.
82-
83-**System prompt construction** (`prompt.ts`):
84-
85-- Assembly order: base + AGENTS.md + skills + plugins + footer.
86-- Git line formatting: branch, dirty counts, ahead/behind, omission rules.
87-- Skills catalog XML generation.
88-- Conditional readImage exclusion from prompt text.
89-
90-**Community standards discovery** (`skills.ts`, AGENTS.md loading):
91-
92-- Skill discovery: scan paths, SKILL.md parsing, frontmatter extraction, name collision resolution.
93-- AGENTS.md discovery: walk to scan root, ordering, `~/.agents/` inclusion.
94-- Use temp directories with controlled file trees.
95-
96-**Agent loop** (`agent.ts`):
97-
98-- Use pi-ai's `faux` provider for end-to-end loop tests.
99-- The loop takes `tools: Tool[]` (definitions for the model) and `toolHandlers: Map<string, ToolHandler>` (dispatch map). Tests build both via helper functions.
100-- Verify: tool calls are executed, messages are appended in correct order, turns are numbered, interrupt preserves partial response, error handling, unknown tool self-correction, length stop reason.
101-
102-**Input parsing** (`input.ts`):
103-
104-- `/command` detection and routing (all 11 commands, case-sensitive, unknown commands fall through).
105-- `/skill:name rest of message` → skill name + user text extraction.
106-- Image path detection (entire input is an existing image path with valid extension, requires `supportsImages` opt-in).
107-- Priority ordering: commands > skills > images > plain text.
108-
109-**Theme** (`theme.ts`):
110-
111-- Default theme has all required keys, including `statusPrimaryBg`, `statusSecondaryBg`, and `overlayBg`.
112-- `mergeThemes` applies partial overrides left-to-right without mutating the base.
63+- Test boundaries, not dependencies. Use real Bun/git/sqlite/pi-ai faux behavior. No mocks or stubs.
64+- `tools.ts`: edit exact-match/create/path/newline preservation; shell exit/abort/truncation/cwd; readImage mime/errors/path handling.
65+- `session.ts`: CRUD, turn numbering, undo/fork, truncation, prompt history, cumulative stats.
66+- `prompt.ts` / `skills.ts`: prompt assembly order, AGENTS.md ordering/scan-root behavior, skill discovery/catalog, conditional `readImage` omission.
67+- `agent.ts`: faux-provider end-to-end loop tests for tool execution, ordering, interrupts, and errors.
68+- UI tests live in `src/ui*.test.ts` plus focused `src/ui/*.ts` module tests; TUI rendering/input changes still need manual terminal validation.
69+- `input.ts` and `theme.ts`: command/skill/image priority, theme completeness, merge semantics.