@@ -1,177 +1,42 @@
1-# Implementation plan
1+# TODO
22
3-## Phase 1 — Foundation (no UI, no LLM)
3+## Bugs — from code review
44
5-- [x] `session.ts` — SQLite schema, CRUD, turn numbering, undo, fork, cumulative stats
6-- [x] `session.test.ts` — 20 tests against real in-memory bun:sqlite
7-- [x] `tools.ts` — `edit` (exact-text replace, new file creation) and `shell` (exec, output truncation)
8-- [x] `tools.test.ts` — 27 tests: edit (13), shell (8), truncateOutput (6)
9-- [x] `git.ts` — branch, dirty counts, ahead/behind, repo root detection (10 tests)
5+### BREAKING MUST FIX
106
11-### Notes from Phase 1
7+- [x] **No streaming feel** — fixed in `src/ui.ts` by rendering completed and in-progress assistant content inside stable top-level containers, with regression coverage in `src/ui.test.ts`.
8+- [ ] **UI Themeing is broken on non-dark background terminals** This is on us, Cel-tui explicit handles the terminal bg and fg, we are just retarded and hardcoded colors, with no tought on what the theme feels or looks like. Aweful work.
129
13-- `session.ts` exports: `openDatabase`, `createSession`, `getSession`, `listSessions`, `deleteSession`, `appendMessage`, `loadMessages`, `undoLastTurn`, `forkSession`, `computeStats`.
14-- Internal row types (`SessionRow`, `MaxTurnRow`, `DataRow`) and a `SQL` constants object keep queries centralized and avoid formatter conflicts.
15-- `@mariozechner/pi-ai` is the only runtime dependency so far. Its `Message`, `AssistantMessage`, `UserMessage`, `ToolResultMessage` types are used for session persistence.
16-- `tools.ts` exports: `ToolExecResult`, `EditArgs`, `executeEdit`, `ShellArgs`, `ShellOpts`, `executeShell`, `truncateOutput`, `editTool`, `shellTool`, `ReadImageArgs`, `executeReadImage`, `readImageTool`. All execute functions return `ToolExecResult` (`{ content: (TextContent | ImageContent)[], isError }`). pi-ai `Tool` definitions use TypeBox schemas.
17-- `git.ts` exports: `getGitState` → `GitState | null`. Runs 4 git commands in parallel. Internal `parseStatus` parses porcelain v1 format (uses `trim=false` to preserve leading-space column).
18-- biome `noNonNullAssertion` rule disabled globally — non-null assertions after explicit null checks are idiomatic in tests.
19-- 57 tests total across 3 files (session: 20, tools: 27, git: 10).
20-- `diff` package added as dependency for unified diffs in edit tool output (Phase 4 UI).
10+### High
2111
22-## Phase 2 — Context assembly
12+- [ ] **Uncaught tool handler exceptions** (`agent.ts`) — if a plugin handler (or a built-in on a filesystem error like EPERM) throws, the agent loop crashes. The exception propagates through `submitMessage` (try/finally, no catch) to a `.catch(console.error)` in `handleInput` — invisible in the TUI. The conversation is left inconsistent: `tool_start` emitted but `tool_end` never fires, tool result message never appended. Fix: wrap the `handler()` call in try/catch, produce an error `ToolExe …
13+- [ ] **`/undo` race condition** (`ui.ts`) — `/undo` aborts the agent loop then immediately calls `undoLastTurn`, but `abort()` is asynchronous. The agent loop may still write an `AssistantMessage` (stopReason "aborted") to the same turn after `undoLastTurn` has deleted it, leaving orphaned messages in the DB. Fix: store the agent loop promise as module state; in `handleUndoCommand`, await it (via `.finally()`) before calling `undoLastTurn`.
14+- [ ] **Invisible submit errors** (`ui.ts`) — `submitMessage` errors only go to `console.error`, invisible in TUI mode. Network errors, malformed responses, or tool handler crashes cause the agent to silently stop. Fix: replace `console.error` with `appendInfoMessage` so the error surfaces in the conversation log.
2315
24-- [x] `skills.ts` — SKILL.md discovery, frontmatter parsing, catalog generation, name collision resolution
25-- [x] `skills.test.ts` — 14 tests: single/multi path discovery, name collision, missing dirs, frontmatter (none, missing fields, multi-line, quoted), catalog XML
26-- [x] `prompt.ts` — AGENTS.md discovery, system prompt construction (base + AGENTS.md + skills + plugins + git footer)
27-- [x] `prompt.test.ts` — 21 tests: AGENTS.md walk (5), git line formatting (6), system prompt assembly (10)
16+### Medium
2817
29-### Notes from Phase 2
18+- [ ] **`readImage` missing try/catch** (`tools.ts`) — `executeReadImage` doesn't catch `readFileSync` exceptions. A permission error (EACCES) after the `existsSync` check throws an uncaught exception. Fix: wrap in try/catch, return text error result.
19+- [ ] **Fragile `tool_end` matching** (`ui.ts`/`agent.ts`) — `tool_end` events match pending tool calls by name + null resultText. Two calls to the same tool in one response (e.g., two `shell` calls) rely on sequential execution order. Fix: add `toolCallId` to `tool_start`/`tool_end` `AgentEvent` types, emit from `agent.ts`, match by id in `ui.ts`.
20+- [ ] **Stale plugin `AgentContext.messages`** (`index.ts`) — `AgentContext.messages` is the same array ref as `state.messages`, which gets reassigned on `/new`, `/session`, `/fork`, `/undo`. Plugins holding the original reference see stale data. Fix: use a getter (`get messages() { return state.messages; }`).
21+- [ ] **OAuth credential reference comparison** (`index.ts`) — `result.newCredentials !== oauthCredentials[oauthProvider.id]` compares by reference, not value. Causes unnecessary disk writes on every startup if `getOAuthApiKey` returns a new object. Fix: unconditionally assign when result is present, or compare serialized form.
3022
31-- `skills.ts` exports: `Skill` interface, `discoverSkills(scanPaths)`, `buildSkillCatalog(skills)`. Minimal YAML frontmatter parser (no dependency) handles `name`, `description`, folded scalars (`>`), quoted values. Falls back to directory name when frontmatter `name` is absent.
32-- `prompt.ts` exports: `AgentsMdFile` interface, `BuildSystemPromptOpts` interface, `discoverAgentsMd(cwd, scanRoot, globalAgentsDir?)`, `formatGitLine(state)`, `buildSystemPrompt(opts)`. Both `discoverSkills` and `discoverAgentsMd` take paths as parameters — the actual scan paths (spec §"Agent Skills" discovery, §"AGENTS.md" scan root priority) are determined by the caller (`index.ts` in Phase 4).
33-- Base instructions in `prompt.ts` match spec.md §"Base instructions" verbatim.
34-- `readImage` is intentionally absent from base instructions per spec — conditionally registered via tool definitions only.
35-- 92 tests total across 5 files (session: 20, tools: 27, git: 10, skills: 14, prompt: 21).
23+### Low (deferred from earlier phases)
3624
37-## Phase 3 — Agent loop
25+- [ ] **Shell output missing exit code** — spec says "Shows the command, head + tail truncated output with a visual marker, and exit code". `ToolExecResult` carries `isError` but not the numeric exit code.
26+- [ ] **CWD truncation on narrow terminals** — spec says truncate from left (`…/mini-coder`). Currently shows the full abbreviated path.
27+- [ ] **`Ctrl+Z` suspend/background** — spec lists it in key bindings but it's not implemented.
28+- [ ] **`/session` delete** — spec says "list, resume, delete" but Select component doesn't expose highlighted item for secondary actions.
3829
39-- [x] `readImage` tool in `tools.ts` — base64 encoding, mime detection, path resolution
40-- [x] `tools.test.ts` — 9 new readImage tests (36 total: edit 13, shell 8, truncateOutput 6, readImage 9)
41-- [x] `agent.ts` — core loop: stream → handle events → execute tools → loop. Interrupt handling.
42-- [x] `agent.test.ts` — 12 tests with faux provider: text response, tool execution, multi-tool, chaining, turn numbering, events, interrupt, error, unknown tool, length stop
43-- [x] `plugins.ts` — plugin types, config loading, init/destroy lifecycle
44-- [x] `plugins.test.ts` — 10 tests with real plugin modules in temp dirs: config loading, init, config passthrough, error handling, tool collection, destroy lifecycle
30+## Phase 4d — Polish
4531
46-### Notes from Phase 3
47-
48-- `readImage` in `tools.ts`: `ReadImageArgs`, `executeReadImage`, `readImageTool`. Returns `ImageContent` on success (base64 + mimeType) or text error, both via `ToolExecResult`.
49-- `agent.ts` exports: `ToolHandler` (function type), `ToolExecResult` (re-exported from `tools.ts`), `AgentEvent`, `RunAgentOpts`, `AgentLoopResult`, `runAgentLoop`. `RunAgentOpts` takes `tools: Tool[]` (definitions for the model) and `toolHandlers: Map<string, ToolHandler>` (dispatch map). The loop streams via `streamSimple`, dispatches tool calls through the handler map, appends all messages to DB with the same turn number, and emits events for UI updates. Unknown tools produce error results s …
50-- `plugins.ts` exports: `AgentContext`, `PluginResult`, `Plugin`, `PluginEntry`, `LoadedPlugin`, `loadPluginConfig`, `initPlugins`, `destroyPlugins`. `PluginResult.tools` is `Tool[]` (pi-ai definitions), `PluginResult.toolHandlers` is `Map<string, ToolHandler>` (optional). Plugins are real modules loaded via dynamic `import()` — tested with actual `.ts` files in temp dirs (no mocks).
51-- Context limit compaction is deferred — the spec notes "the specifics will be refined during development." The agent loop structure supports adding it as a pre-stream check.
52-- Conditional `readImage` registration (only for vision-capable models) will be handled by the caller (`index.ts`) checking `Model.input.includes("image")`.
53-- `cel-tui` (`@cel-tui/core`, `@cel-tui/components`) added as dependencies for the TUI.
54-- 123 tests total across 7 files.
55-
56-## Phase 4 — UI
57-
58-### 4a — Input parsing (TDD, no UI)
59-
60-- [x] `input.ts` — pure logic for parsing user input:
61- - `/command` detection and routing (extract command name + args)
62- - `/skill:name rest of message` → skill body + user text
63- - Image path detection (entire input is an existing image path with valid extension)
64-- [x] `input.test.ts` — 30 tests: command detection (6), skill references (6), image paths (12), plain text (4), priority (2)
65-
66-### Notes from Phase 4a
67-
68-- `input.ts` exports: `COMMANDS` (const tuple), `Command` type, `ParsedInput` discriminated union, `ParseInputOpts`, `parseInput(raw, opts?)`. Pure logic — no IO beyond `existsSync` for image path validation.
69-- `theme.ts` (also implemented here): `Theme` interface, `DEFAULT_THEME`, `mergeThemes(base, ...overrides)`. Uses terminal palette colors (`color01`–`color08`) for automatic light/dark adaptation. 5 tests in `theme.test.ts`.
70-- 158 tests total across 9 files (session: 20, tools: 36, git: 10, skills: 14, prompt: 21, agent: 12, plugins: 10, input: 30, theme: 5).
71-
72-### Notes from Phase 4b
73-
74-- `index.ts` exports: `AppState` (all mutable app state), `init()`, `buildPrompt(state)`, `buildToolList(state)`, `shutdown(state)`. Also re-exports OAuth helpers (`loadOAuthCredentials`, `saveOAuthCredentials`, `DATA_DIR`, `AUTH_PATH`) for `/login` and `/logout` commands.
75-- Provider discovery checks env-based API keys first, then saved OAuth tokens (`~/.config/mini-coder/auth.json`). Refreshes expired tokens and persists updates.
76-- Model selection picks the first model from the first provider with models, or `null` if none. No `process.exit` — the TUI starts regardless so the user can `/login`.
77-- Tool wiring: `buildTools` returns `{ tools: Tool[], toolHandlers: Map<string, ToolHandler> }`. Built-in handlers are a plain record. Plugin tools and handlers are merged from `PluginResult`.
78-- `ToolExecResult` is now the single result type in `tools.ts`. `ToolResult` and `ReadImageResult` were removed. All execute functions return `ToolExecResult` directly.
79-- `AgentTool` wrapper type removed from `agent.ts`. The agent loop takes `tools: Tool[]` + `toolHandlers: Map<string, ToolHandler>` separately.
80-- 158 tests still pass across 9 files.
81-
82-### 4b — App shell (running app, no commands)
83-
84-- [x] `index.ts` — entry point: provider discovery (env + OAuth), model selection (first available, null if none), startup sequence, `main()` wires init → startUI
85-- [x] `ui.ts` — cel-tui layout: conversation log (scrollable, stick-to-bottom), input area (TextInput, submit/newline), status bar (2 lines: cwd+git, model+usage), animated divider
86-- [x] Wire agent loop: submit → build context → stream → render events → tool results → loop
87-- [x] Message rendering: user (bg color), assistant (streamed Markdown), tool calls (shell: bordered output, edit: path + unified diff), errors
88-- [x] Interrupt: Escape during streaming aborts via AbortSignal
89-
90-### Notes from Phase 4b (ui.ts)
91-
92-- `ui.ts` exports: `startUI(state)`. Single entry point that owns the cel-tui lifecycle (`cel.init` / `cel.stop`).
93-- Layout matches the spec diagram: scrollable conversation log (flex: 1) → animated divider → TextInput (maxHeight: 10) → static divider → status bar (height: 2).
94-- Animated divider: scanning pulse (bright `═` segment sweeps across dimmed `─` line) via `setInterval` at 60ms. Starts on agent loop start, stops on completion.
95-- Message rendering: user messages get `bgColor` from theme, assistant messages use `Markdown()` component, tool calls get left border (`│`) with dimmed text. Edit tool calls show unified diff via `structuredPatch` from the `diff` package. Streaming response rendered from accumulation buffers + pending tool call list.
96-- Agent loop wiring: `submitMessage` appends user message to DB (turn auto-assigned by `appendMessage`), refreshes git state, builds prompt + tools, runs `runAgentLoop` with `onEvent` callback. Events update streaming buffers and trigger `cel.render()`.
97-- Key bindings: Enter submits (returns `false` in `onKeyPress` to prevent newline), Escape interrupts running agent, Ctrl+C / Ctrl+D graceful exit.
98-- `Theme` type changed from `string` values to cel-tui `Color` type — eliminates `as any` casts throughout the UI.
99-- `tsconfig.json`: removed `noImplicitReturns` for cel-tui compatibility (their `onKeyPress` callbacks return `false | void`).
100-- `spec.md`: removed `submitKey: "enter"` reference — cel-tui uses the `onKeyPress` return-false pattern instead.
101-- 158 tests still pass across 9 files.
102-
103-### 4c — Commands
104-
105-- [x] `/model` — interactive model selector (Select component, available providers/models)
106-- [x] `/effort` — effort level selector
107-- [x] `/session` — session manager (list, resume). Scoped to CWD.
108-- [x] `/login` — OAuth login via pi-ai (browser-based flow, no manual code input)
109-- [x] Overlay layer system for interactive Select commands
110-- [x] Wire `parseInput()` into Enter handler, route commands vs text
111-- [x] Session truncation — keep max 20 per CWD, runs on init
112-- [x] Fix: pass `apiKey` from `state.providers` through `RunAgentOpts` to `streamSimple` (OAuth providers failed without this)
113-- [x] Fix: pass `effort` (reasoning level) to `streamSimple` (was silently ignored)
114-- [x] `/logout` — OAuth logout (Select of logged-in providers, clear creds, nullify model if needed)
115-- [x] `/new` — new session, reset messages/stats
116-- [x] `/fork` — fork current session, info message
117-- [x] `/undo` — interrupt if running, then remove last turn
118-- [x] `/reasoning` — toggle `showReasoning`
119-- [x] `/verbose` — toggle `verbose`
120-- [x] Info messages separated from `state.messages` — display-only `infoMessages` array, not sent to LLM, cleared on session switch
121-- [x] `/` + Tab — command autocomplete overlay (all 11 commands with descriptions)
122-- [x] `/help` — list commands, providers, model, AGENTS.md files, skills, plugins
123-
124-### Notes from Phase 4c
125-
126-- Overlay system: cel-tui multi-layer viewport. `activeOverlay` module state holds a `SelectInstance` + title. When active, `cel.viewport()` returns `[base, overlayLayer]`. Overlay is a centered modal with `padding: { x: 4 }` and fixed height (`OVERLAY_MAX_VISIBLE + 3`), `bgColor: theme.overlayBg`.
127-- Escape dismissal: cel-tui intercepts Escape at the framework level (unfocuses before `onKeyPress` fires), so overlay dismissal uses `onBlur: dismissOverlay` instead of `onKeyPress`.
128-- `/model` builds items from `getAvailableModels(state)` (new helper in `index.ts`), marks current with `(current)` suffix, `filterText` includes both provider and model id.
129-- `/effort` shows 4 levels (low/medium/high/xhigh), marks current.
130-- `/session` lists sessions via `listSessions(db, cwd)`, labels show relative timestamp (`formatSessionDate`) + model + `(current)` marker. Resume swaps `state.session`, reloads messages and stats.
131-- `truncateSessions(db, cwd, keep)` in `session.ts` — deletes oldest beyond limit per CWD. `listSessions` SQL uses `rowid DESC` tiebreaker for deterministic ordering.
132-- `/login` shows OAuth providers from `getOAuthProviders()` with login status. `performLogin()` calls `provider.login()` with `onAuth` (opens browser via `xdg-open`/`open`), `onProgress` (status in log). `onPrompt` rejects (no manual code input). On success: persists creds, registers API key in `state.providers`, auto-selects model if none.
133-- `/logout` filters `getOAuthProviders()` to those with saved creds. On select: deletes creds, removes from `state.providers`, clears model if it belonged to the provider.
134-- `/new` creates session via `createSession`, clears messages/stats/infoMessages. Guards against running state.
135-- `/fork` calls `forkSession`, reloads messages/stats, shows info message. Guards against running state.
136-- `/undo` aborts agent if running, then `undoLastTurn`, reloads messages/stats.
137-- `/reasoning` and `/verbose` toggle their respective `AppState` booleans and re-render.
138-- `apiKey` added to `RunAgentOpts` and passed to `streamSimple` — required for OAuth providers (env vars not set). `effort` also passed as `reasoning` option.
139-- `handleInput()` routes through `parseInput()` → `handleCommand()` for commands, `submitMessage()` for text. Skill and image cases are stubs for Phase 4d.
140-- `Theme` gained `overlayBg: Color` (default `"color08"`).
141-- `appendInfoMessage()` helper for display-only status messages. Uses separate `infoMessages` array (not `state.messages`) so info text is never sent to the LLM. Cleared on `/new`, `/session` resume, `/fork`.
142-- `/help` renders commands (with descriptions), providers, model, AGENTS.md paths, skills, plugins as a multi-line info message.
143-- `/` + Tab in TextInput triggers `showCommandAutocomplete()` — overlay Select with all 11 commands from `COMMANDS` + `COMMAND_DESCRIPTIONS`. Selection executes the command via `handleInput`. Tab without `/` falls through (file autocomplete deferred to Phase 4d).
144-- All 11 spec commands implemented. Phase 4c complete.
145-- 162 tests across 9 files (session: 24, tools: 36, git: 10, skills: 14, prompt: 21, agent: 12, plugins: 10, input: 30, theme: 5).
146-
147-### Spec review findings (Phase 4c checkpoint)
148-
149-**Bugs (from earlier phases, deferred):**
150-
151-- Assistant messages not visibly streaming — text appears as full blocks instead of incrementally, causing jarring scroll jumps. Likely a rendering or event issue in `ui.ts` streaming path (Phase 4b).
152-- Shell tool rendering doesn't show exit code (spec: "Shows the command, head + tail truncated output with a visual marker, and exit code"). `ToolExecResult` carries `isError` but not the numeric exit code (Phase 4b).
153-- Status bar CWD truncation from the left (`…/mini-coder`) on narrow terminals — not implemented, just shows full abbreviated path (Phase 4b).
154-- `Ctrl+Z` suspend/background — not implemented (spec lists it in key bindings) (Phase 4b).
155-
156-**Design decisions:**
157-
158-- `/session` delete deferred — spec says "list, resume, delete" but Select component doesn't expose highlighted item for secondary actions.
159-- `/login` has no manual code input fallback — `onPrompt` rejects. Browser callback has always worked in practice.
160-
161-### 4d — Polish
162-
163-- [ ] Tab file path autocomplete in input
164-- [ ] `/skill:name` input handling (strip prefix, prepend skill body)
165-- [ ] Image embedding (entire input is image path → embed as ImageContent)
32+- [ ] `/skill:name` input handling (strip prefix, prepend skill body to user message)
33+- [ ] Image embedding (entire input is image path → embed as `ImageContent`)
16634 - [ ] Conditional `readImage` tool registration (only for vision-capable models, re-evaluated on `/model`)
35+- [ ] Tab file path autocomplete in input
16736 - [ ] Context limit compaction (threshold detection, model-generated summary, prompt cache preservation)
16837
16938 ## Future ideas
17039
17140 - [ ] User preferences persistence (model, effort) — not in spec, currently resets to defaults on launch
172-- [ ] Session list preview — show first user message snippet in `/session` selector for easier identification
173-- [ ] Divider theme plugin — customizable divider animations. Candidates designed during Phase 4 UI exploration:
174- - **Scanning pulse** (current default): bright segment sweeps across the dimmed divider
175- - **Breathing**: divider alternates between two dim levels, subtle pulse
176- - **Flowing dots**: dot characters move along the divider like a marquee
177- - **Wave**: characters cycle through `─` / `═` to create a moving wave effect
41+- [ ] Session list preview — show first user message snippet in `/session` selector
42+- [ ] Divider theme plugin — customizable divider animations (scanning pulse, breathing, flowing dots, wave)