xonecas.io
64875
Mc

mini-coder / commit 3ca540a

refactor: unify context file discovery between banner and system prompt

Extract shared context-files.ts module with canonical candidate paths
for both global (~/.agents/, ~/.claude/) and local (.agents/, .claude/,
root) context files. Both the banner display and system prompt loading
now use the same path list, fixing a divergence where the banner was
missing ~/.claude/CLAUDE.md, <cwd>/.agents/CLAUDE.md, and
<cwd>/.claude/CLAUDE.md.

xonecas2026-03-20 3ca540ad49ed610142e7c1d4eaffe41fa9ea896e parent 1ab7f7e

8 files changed

AUDIT-REPORT.md+98−0
@@ -0,0 +1,98 @@
1+# Audit Report — mini-coder v0.2.0
2+
3+**Date:** 2026-03-20
4+**Auditor:** Claude (via audit skill)
5+**Commit:** HEAD on `main`
6+
7+---
8+
9+## Summary
10+
11+**Phase 1** reviewed all core source files (~15k LoC across 80+ modules) against `mini-coder-idea.md`. All checks pass: 290 tests, 0 lint errors, 0 type errors, 0 knip issues, 0.16% code duplication.
12+
13+**Phase 2** tested 5 provider paths interactively via tmux and one-shot pipes:
14+
15+| Provider path | Model | SDK package | Result |
16+| ----------------------- | ---------------------------- | --------------------------- | --------------------------- |
17+| Anthropic (Zen) | `zen/claude-haiku-4-5` | `@ai-sdk/anthropic` | ✅ Works (without thinking) |
18+| Google (Zen) | `zen/gemini-3-flash` | `@ai-sdk/google` | ✅ Works |
19+| OpenAI responses (Zen) | `zen/gpt-5.4-nano` | `@ai-sdk/openai` | ✅ Works |
20+| OpenAI-compatible (Zen) | `zen/minimax-m2.5` | `@ai-sdk/openai-compatible` | ✅ Works |
21+| Anthropic OAuth | `anthropic/claude-haiku-4-5` | `@ai-sdk/anthropic` | ✅ Works |
22+
23+Each was tested with multi-step, multi-turn prompts exercising tool calls, shell output rendering, and follow-up questions. One-shot mode was verified with piped stdin for Haiku and Gemini.
24+
25+---
26+
27+## Code & Architecture
28+
29+### ✅ Strengths
30+
31+- **Clean separation of concerns**: `agent/`, `cli/`, `llm-api/`, `session/`, `tools/`, `internal/` modules are well-scoped. Files are small and focused.
32+- **System prompt is well-structured**: AGENTS.md/CLAUDE.md discovery, skill metadata injection, and behavioural sections are cleanly composed.
33+- **Provider routing is elegant**: `model-routing.ts` and `providers.ts` cleanly map `<provider>/<model-id>` strings to the right SDK factory with lazy initialization.
34+- **Context management**: Step-aware pruning in `turn-context.ts` is sophisticated — correctly anchors the Anthropic cache prefix and handles the step-0 vs step-1+ distinction.
35+- **Tool rendering**: Shell output is well-presented with contextual glyphs, head/tail truncation, and colored badges. The parallel tool call `↳` markers work correctly.
36+- **Test coverage**: 290 tests covering the important logic (exact-text edits, model routing, stream events, context pruning, etc.) without mocking dependencies.
37+
38+### 🐛 Bugs Found
39+
40+1. **Thinking effort breaks `claude-haiku-4-5` via Zen** — The model info cache (sourced from models.dev) marks `claude-haiku-4-5` as `reasoning: 1`. When a thinking effort is persisted (e.g. `medium`), the app sends `"thinking": {"type": "adaptive"}` which Zen (and likely the Anthropic API) rejects with a 400: _"adaptive thinking is not supported on this model"_. The `supportsThinking()` check is too broad — it trusts the models.dev flag but doesn't validate whether the specific model actua …
41+
42+2. **`zen/claude-3-5-haiku` 404** — The AI SDK auto-resolves `claude-3-5-haiku` to `claude-3-5-haiku-20241022`, which Zen doesn't serve. The Zen endpoint expects exactly `claude-3-5-haiku`. This is an SDK behaviour issue that may need a workaround or documentation.
43+
44+### ⚠️ Issues & Observations
45+
46+3. **Banner vs system prompt context file divergence** — `discoverContextFiles()` in `output.ts` checks 5 paths. `loadGlobalContextFile()` + `loadContextFileAt()` in `system-prompt.ts` check more paths including `~/.claude/CLAUDE.md` and `<cwd>/.agents/CLAUDE.md` and `<cwd>/.claude/CLAUDE.md`. A file could be loaded into the system prompt but not shown in the banner, confusing users.
47+
48+4. **Stale TODO comment** — `agent.ts:103` has `cwd, // TODO: What is this used for?` but `cwd` is actively used by commands (skills loading, banner rendering, forked skill execution). The comment should be removed.
49+
50+5. **Status bar TODOs** — `status-bar.ts` has 3 TODO comments about combining model+thinking effort display and removing `showReasoning` from the status bar (since it's in the banner). These are deferred polish items.
51+
52+6. **`maxOutputTokens` hardcoded to 16384** — Already tracked in TODO.md. Some models (Claude Opus) support up to 32k output tokens.
53+
54+7. **`onError` swallows context** — In `turn-request.ts:87`, the `onError` callback is an empty function with a comment about suppressing SDK stderr logging. While the intent is valid, if the stream encounters an error that doesn't propagate through turn events, it could silently fail.
55+
56+---
57+
58+## UI/UX Alignment
59+
60+### Matches idea expectations
61+
62+- **Banner**: Clean, shows model, cwd, context files, skills count. Matches the idea's "Banner at app start" spec.
63+- **Status bar**: Model, session ID, git branch, token tracking, context usage with % coloring. Well-formatted with progressive truncation for narrow terminals.
64+- **Shell output**: Command-specific glyphs (✎ for writes, $ for runs, ← for reads, ? for searches). Stdout/stderr preview with line counts and head/tail truncation. Matches "Shell tool shows the command called and its output."
65+- **Skill tools**: Compact metadata output as specified.
66+- **MCP tools**: Clearly distinguishable with ⚙ glyph.
67+- **One-shot mode**: Clean — no banner, quiet reporter, just the response text.
68+- **Error recovery**: Returns user to prompt with clear `✖` error messages.
69+- **16 ANSI colors**: Correctly uses yoctocolors with only the base 16 colors.
70+
71+### Minor deviations
72+
73+- **Paste preview** — When pasting text in tmux, the input shows `[pasted: "..."]` preview and requires a separate Enter to submit. This is actually good UX (prevents accidental submissions) but isn't mentioned in the idea file.
74+- **Reasoning display** — The `· reasoning` blocks from MiniMax render well. The live reasoning block for Claude models renders inline. Both work but look slightly different.
75+
76+---
77+
78+## Recommendations
79+
80+### Immediate bugs
81+
82+1. **Fix thinking effort for non-thinking models** — `supportsThinking()` should be more specific. Either: (a) differentiate between "model outputs reasoning traces" and "model accepts adaptive thinking API param", or (b) catch the 400 and retry without thinking params, or (c) maintain a deny-list of models that don't support adaptive thinking despite being marked reasoning-capable.
83+
84+2. **Fix SDK model alias expansion for Zen** — The `claude-3-5-haiku` → `claude-3-5-haiku-20241022` expansion causes 404s. Consider either pinning model IDs in the Zen provider path, or documenting this as a known limitation.
85+
86+### Code changes
87+
88+3. **Unify context file discovery** — Extract a shared `contextFileCandidates(cwd, homeDir)` function used by both `discoverContextFiles()` and the system prompt loaders. This fixes the divergence and removes duplication.
89+
90+4. **Remove stale TODO** — Delete `// TODO: What is this used for? Why is it here?` from `agent.ts:103`.
91+
92+5. **Address status bar TODOs** — Combine model + thinking effort in the status bar display, decide on showReasoning placement.
93+
94+### Polish items
95+
96+6. **Error message for thinking rejection** — When the API rejects thinking params, the generic "API error 400" message doesn't explain why. Extract the error message from the response body and display it in the hint line.
97+
98+7. **The truncation consolidation** noted in TODO.md (several truncation helpers across cli module files) is a valid cleanup target. `tool-render.ts` and `tool-result-renderers.ts` each have their own `truncate`/`truncateOneLine` functions.
TODO.md+2−0
@@ -7,6 +7,8 @@
77
88 # Deferred fixes
99
10+- **Thinking effort breaks `claude-haiku-4-5` via Zen** — The model info cache (sourced from models.dev) marks `claude-haiku-4-5` as `reasoning: 1`. When a thinking effort is persisted (e.g. `medium`), the app sends `"thinking": {"type": "adaptive"}` which Zen (and likely the Anthropic API) rejects with a 400: _"adaptive thinking is not supported on this model"_. The `supportsThinking()` check is too broad — it trusts the models.dev flag but doesn't validate whether the specific model actual …
11+- **`zen/claude-3-5-haiku` 404** — The AI SDK auto-resolves `claude-3-5-haiku` to `claude-3-5-haiku-20241022`, which Zen doesn't serve. The Zen endpoint expects exactly `claude-3-5-haiku`. This is an SDK behaviour issue that may need a workaround or documentation.
1012 - Several truncation helpers accross the cli module files, consolidate in a cli/truncate.ts for rendering truncation.
1113 - When a shell tool call hits max timeout, the turn ends and the parent terminal is left in a broken state.
1214 - **MiniMax empty lines in one-shot** — Investigate empty text deltas. May need to skip rendering deltas that are only whitespace at stream start.
mini-coder-idea.md+1−1
@@ -36,7 +36,7 @@ conventions and not introduce more specs.
3636 - `/new` starts a new session with clean context. Clean UI and fresh session display
3737
3838 - Enriched user prompt:
39- - Rich line editing/history/image paste
39+ - Rich line editing/history/image paste. Enter submits.
4040 - Seamless shell integration with `!` in prompt input. Runs command in subprocess and sends the output to the llm as user message.
4141 - Reference skills from the working directory and global configs with `/` in prompt input, plus autocomplete for skills to include in the prompt.
4242 - Press `ESC` at any point during an assistant response to interrupt it: the partial response is preserved in history with an interrupt stub appended (so the LLM retains context), and the user is returned to the prompt silently. `ctrl+c` exits forcefully. `ctrl+d` (EOF) gracefully exits.
src/agent/agent.ts+1−1
@@ -100,7 +100,7 @@ export async function initAgent(opts: AgentOptions): Promise<{
100100 runner.verboseOutput = verbose;
101101 setPreferredVerboseOutput(verbose);
102102 },
103- cwd, // TODO: What is this used for? Why is it here?
103+ cwd,
104104 undoLastTurn: () => runner.undoLastTurn(),
105105 connectMcpServer: connectAndAddMcp,
106106 startSpinner: (label?: string) => opts.reporter.startSpinner(label),
src/agent/context-files.ts+103−0
@@ -0,0 +1,103 @@
1+import { existsSync, readFileSync } from "node:fs";
2+import { homedir } from "node:os";
3+import { dirname, join, resolve } from "node:path";
4+
5+type ContextCandidate = { abs: string; label: string };
6+
7+const HOME = homedir();
8+
9+function tilde(p: string): string {
10+ return p.startsWith(HOME) ? `~${p.slice(HOME.length)}` : p;
11+}
12+
13+/** Global context file candidates (home directory). */
14+function globalContextCandidates(homeDir: string = HOME): ContextCandidate[] {
15+ return [
16+ {
17+ abs: join(homeDir, ".agents", "AGENTS.md"),
18+ label: "~/.agents/AGENTS.md",
19+ },
20+ {
21+ abs: join(homeDir, ".agents", "CLAUDE.md"),
22+ label: "~/.agents/CLAUDE.md",
23+ },
24+ {
25+ abs: join(homeDir, ".claude", "CLAUDE.md"),
26+ label: "~/.claude/CLAUDE.md",
27+ },
28+ ];
29+}
30+
31+/** Local context file candidates for a single directory. */
32+function dirContextCandidates(dir: string): ContextCandidate[] {
33+ const rel = (p: string) => tilde(resolve(dir, p));
34+ return [
35+ {
36+ abs: join(dir, ".agents", "AGENTS.md"),
37+ label: `${rel(".agents/AGENTS.md")}`,
38+ },
39+ {
40+ abs: join(dir, ".agents", "CLAUDE.md"),
41+ label: `${rel(".agents/CLAUDE.md")}`,
42+ },
43+ {
44+ abs: join(dir, ".claude", "CLAUDE.md"),
45+ label: `${rel(".claude/CLAUDE.md")}`,
46+ },
47+ { abs: join(dir, "CLAUDE.md"), label: `${rel("CLAUDE.md")}` },
48+ { abs: join(dir, "AGENTS.md"), label: `${rel("AGENTS.md")}` },
49+ ];
50+}
51+
52+/**
53+ * All context file candidates: global + local directory.
54+ * For the banner (cwd only, no parent walking).
55+ */
56+export function discoverContextFiles(cwd: string, homeDir?: string): string[] {
57+ const candidates = [
58+ ...globalContextCandidates(homeDir),
59+ ...dirContextCandidates(cwd),
60+ ];
61+ return candidates.filter((c) => existsSync(c.abs)).map((c) => c.label);
62+}
63+
64+// ─── Content loading (for system prompt) ─────────────────────────────────────
65+
66+function tryReadFile(p: string): string | null {
67+ if (!existsSync(p)) return null;
68+ try {
69+ return readFileSync(p, "utf-8");
70+ } catch {
71+ return null;
72+ }
73+}
74+
75+function readCandidates(candidates: ContextCandidate[]): string | null {
76+ const parts: string[] = [];
77+ for (const c of candidates) {
78+ const content = tryReadFile(c.abs);
79+ if (content) parts.push(content);
80+ }
81+ return parts.length > 0 ? parts.join("\n\n") : null;
82+}
83+
84+export function loadGlobalContextFile(homeDir?: string): string | null {
85+ return readCandidates(globalContextCandidates(homeDir));
86+}
87+
88+/**
89+ * Walk from cwd up to the git root (or filesystem root),
90+ * returning content from the nearest directory with context files.
91+ */
92+export function loadLocalContextFile(cwd: string): string | null {
93+ let current = resolve(cwd);
94+ while (true) {
95+ const content = readCandidates(dirContextCandidates(current));
96+ if (content) return content;
97+ if (existsSync(join(current, ".git"))) break;
98+ const parent = dirname(current);
99+ if (parent === current) break;
100+ current = parent;
101+ }
102+ return null;
103+}
src/agent/system-prompt.test.ts+2−1
@@ -2,7 +2,8 @@ import { afterEach, beforeEach, describe, expect, it } from "bun:test";
22 import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
33 import { tmpdir } from "node:os";
44 import { join } from "node:path";
5-import { buildSystemPrompt, loadLocalContextFile } from "./system-prompt.ts";
5+import { loadLocalContextFile } from "./context-files.ts";
6+import { buildSystemPrompt } from "./system-prompt.ts";
67
78 let tmpDir: string;
89 let fakeHome: string;
src/agent/system-prompt.ts+4−57
@@ -1,63 +1,10 @@
1-import { existsSync, readFileSync } from "node:fs";
21 import { homedir } from "node:os";
3-import { dirname, join, resolve } from "node:path";
42 import { tildePath } from "../cli/output.ts";
53 import { loadSkillsIndex } from "../cli/skills.ts";
6-
7-function tryReadFile(p: string): string | null {
8- if (!existsSync(p)) return null;
9- try {
10- return readFileSync(p, "utf-8");
11- } catch {
12- return null;
13- }
14-}
15-
16-function collectFiles(...paths: string[]): string | null {
17- const parts: string[] = [];
18- for (const p of paths) {
19- const content = tryReadFile(p);
20- if (content) parts.push(content);
21- }
22- return parts.length > 0 ? parts.join("\n\n") : null;
23-}
24-
25-function loadGlobalContextFile(homeDir: string): string | null {
26- return collectFiles(
27- join(homeDir, ".agents", "AGENTS.md"),
28- join(homeDir, ".agents", "CLAUDE.md"),
29- join(homeDir, ".claude", "CLAUDE.md"),
30- );
31-}
32-
33-/** Try reading all context files from a single directory. */
34-function loadContextFileAt(dir: string): string | null {
35- return collectFiles(
36- join(dir, ".agents", "AGENTS.md"),
37- join(dir, ".agents", "CLAUDE.md"),
38- join(dir, ".claude", "CLAUDE.md"),
39- join(dir, "CLAUDE.md"),
40- join(dir, "AGENTS.md"),
41- );
42-}
43-
44-/**
45- * Walk from cwd up to the git root (or just cwd if outside a repo),
46- * returning the nearest context file found.
47- */
48-export function loadLocalContextFile(cwd: string): string | null {
49- const start = resolve(cwd);
50- let current = start;
51- while (true) {
52- const content = loadContextFileAt(current);
53- if (content) return content;
54- if (existsSync(join(current, ".git"))) break;
55- const parent = dirname(current);
56- if (parent === current) break;
57- current = parent;
58- }
59- return null;
60-}
4+import {
5+ loadGlobalContextFile,
6+ loadLocalContextFile,
7+} from "./context-files.ts";
618
629 const AUTONOMY = `
6310
src/cli/output.ts+1−18
@@ -1,7 +1,6 @@
1-import { existsSync } from "node:fs";
21 import { homedir } from "node:os";
3-import { join } from "node:path";
42 import * as c from "yoctocolors";
3+import { discoverContextFiles } from "../agent/context-files.ts";
54 import type {
65 AgentReporter,
76 StatusBarData,
@@ -109,22 +108,6 @@ export function renderError(err: unknown, context = "render"): void {
109108
110109 // ─── Banner ───────────────────────────────────────────────────────────────────
111110
112-function discoverContextFiles(cwd: string): string[] {
113- const found: string[] = [];
114- const globalDir = join(HOME, ".agents");
115- const candidates: [string, string][] = [
116- [join(globalDir, "AGENTS.md"), "~/.agents/AGENTS.md"],
117- [join(globalDir, "CLAUDE.md"), "~/.agents/CLAUDE.md"],
118- [join(cwd, ".agents", "AGENTS.md"), ".agents/AGENTS.md"],
119- [join(cwd, "CLAUDE.md"), "CLAUDE.md"],
120- [join(cwd, "AGENTS.md"), "AGENTS.md"],
121- ];
122- for (const [abs, label] of candidates) {
123- if (existsSync(abs)) found.push(label);
124- }
125- return found;
126-}
127-
128111 export function renderBanner(model: string, cwd: string): void {
129112 writeln();
130113 const title = PACKAGE_VERSION