xonecas.io
64875
Mc

mini-coder / commit 6d66632

chore: cleanup old docs

Sean2026-03-01 6d666324bc9cea3fdffae610f7cf5747b76d99e3 parent 5f7d426

2 files changed

code-health.md+0−89
@@ -1,89 +0,0 @@
1-# Code Health Analysis
2-
3-## Scope
4-Reviewed the TypeScript codebase in `src/` for code smells: duplication, tight coupling, oversized modules, unsafe patterns, and maintainability risks.
5-
6----
7-
8-## Findings
9-
10-### 1) God module / high complexity: `src/agent/agent.ts`
11-- **Smell:** Single file with very broad responsibilities (session lifecycle, CLI interaction, subagent orchestration, MCP wiring, snapshot/undo flow, model turn handling).
12-- **Evidence:** ~775 lines and many nested functions (`runSubagent`, `processUserInput`, `renderStatusBarForSession`, etc.).
13-- **Impact:** Harder to reason about, test, and safely change; increases risk of regressions.
14-- **Recommendation:** Split into focused modules (e.g. `session-runner`, `subagent-runner`, `undo-snapshot`, `input-loop`, `mcp-runtime`). Keep `runAgent` as composition entrypoint.
15-
16-### 2) God module / rendering mixed with stateful stream logic: `src/cli/output.ts`
17-- **Smell:** UI primitives, spinner, glyph vocabulary, tool-call formatting, subagent stream rendering, diff rendering, status bar, error rendering all in one file.
18-- **Evidence:** ~935 lines, many responsibilities and nested queue/tick/flush behavior.
19-- **Impact:** High cognitive load and brittle changes; difficult targeted unit testing.
20-- **Recommendation:** Extract: `spinner.ts`, `tool-render.ts`, `stream-render.ts`, `status-bar.ts`, `error-render.ts`, and keep `output.ts` as facade.
21-
22-### 3) Tight coupling to global process state in CLI/output stack
23-- **Smell:** Direct writes and signal handling scattered in rendering/terminal functions.
24-- **Evidence:** `process.stdout.write`, `process.stderr.write`, `process.on("SIGINT"|"SIGTERM"|...)`, raw mode toggling in `src/cli/output.ts`.
25-- **Impact:** Hard to test deterministically, side effects leak across features, higher chance of terminal-state bugs.
26-- **Recommendation:** Introduce a thin `TerminalIO` abstraction injected where needed; centralize signal registration in one lifecycle module.
27-
28-### 4) Destructive DB migration strategy in `src/session/db.ts`
29-- Intentional, not an issue.
30-
31-### 5) Database layer combines many bounded contexts
32-- **Smell:** One module owns sessions, messages, prompt history, MCP server registry, settings, snapshots.
33-- **Evidence:** `src/session/db.ts` exposes many unrelated CRUD APIs in one file.
34-- **Impact:** Hidden coupling and broad blast radius for edits; hard to isolate tests and optimize specific query domains.
35-- **Recommendation:** Split repository-style modules by domain (`session-repo`, `message-repo`, `settings-repo`, `mcp-repo`, `snapshot-repo`) sharing one DB connection provider.
36-
37-### 6) Clear duplication across config loaders
38-- **Smell:** Repeated directory scanning/parsing/merge logic in:
39- - `src/cli/agents.ts`
40- - `src/cli/skills.ts`
41- - `src/cli/custom-commands.ts`
42-- **Evidence:** Similar `loadFromDir` patterns (exists/readdir/read/parse/frontmatter/defaults/merge precedence).
43-- **Impact:** Bug fixes and behavior changes must be repeated; inconsistency risk.
44-- **Recommendation:** Create shared loader utility (`loadMarkdownConfigs`) parameterized by layout (`.md file` vs `folder/SKILL.md`), metadata mapping, and precedence rules.
45-
46-### 7) Business logic mixed with presentation concerns
47-- **Smell:** Runtime operations call rendering directly (e.g., tool events, hooks, info/error) instead of emitting structured events.
48-- **Evidence:** `agent.ts` imports many render methods from `cli/output.ts` and calls them inline through control flow.
49-- **Impact:** Strong coupling between core runtime and terminal UI; limits reuse (non-TTY / API mode), harder unit tests.
50-- **Recommendation:** Move to event-driven boundary (domain events -> renderer subscriber), or inject a narrow reporter interface.
51-
52-### 8) Broad `catch {}` swallowing and silent fallbacks
53-- **Smell:** Multiple places ignore errors with empty catches or comments.
54-- **Evidence:** e.g., context file loading in `agent.ts`, cleanup paths in `output.ts`, loader paths in config modules.
55-- **Impact:** Operational issues become invisible; debugging production edge cases is harder.
56-- **Recommendation:** Keep non-fatal behavior but log at debug/trace level (or structured diagnostics) with enough context.
57-
58-### 9) Unsafe JSON parsing without recovery path in message loading
59-- **Smell:** `loadMessages` does `JSON.parse(row.payload)` directly.
60-- **Evidence:** `src/session/db.ts` maps rows with direct parse cast to `CoreMessage`.
61-- **Impact:** Single corrupted row can break session load path.
62-- **Recommendation:** Add guarded parsing with skip/report strategy and optional integrity repair command.
63-
64-### 10) Sync filesystem use in hot-path-ish configuration loading
65-- **Smell:** `existsSync`, `readFileSync`, `readdirSync`, `statSync` widely used in CLI startup/runtime flows.
66-- **Evidence:** `agents.ts`, `skills.ts`, `custom-commands.ts`, and context file loading.
67-- **Impact:** Blocks event loop; usually acceptable at startup but can degrade responsiveness in larger repos/config sets.
68-- **Recommendation:** If responsiveness becomes an issue, move to async FS or memoized cache with invalidation.
69-
70-### 11) Minor test smell: console output in tests
71-- **Smell:** `console.log` in `src/tools/shell.test.ts` for skip notices.
72-- **Impact:** Noisy CI output; not harmful but less clean.
73-- **Recommendation:** Prefer test framework skip metadata or helper wrappers for conditional skips.
74-
75----
76-
77-## Priority Recommendations
78-1. **High:** Decompose `agent.ts` and `output.ts` (largest maintainability win).
79-2. **High:** Replace destructive DB version reset with real migrations.
80-3. **Medium:** Introduce shared config-loader abstraction to remove duplication.
81-4. **Medium:** Decouple runtime from renderer via event/reporter interface.
82-5. **Medium:** Improve error observability (avoid silent catches).
83-
84----
85-
86-## Positive Notes
87-- Strong typing overall; very little `any` / ts-ignore usage observed.
88-- Clear module naming and pragmatic structure in many utility files.
89-- Presence of focused unit tests across core tools (`replace`, `insert`, `snapshot`, etc.).
codex-lazy-fix.md+0−169
@@ -1,169 +0,0 @@
1-# Codex Lazy Fix Plan
2-
3-## Analysis: Why Codex Refuses to Work
4-
5-### Session Evidence
6-
7-All recent Codex sessions (`zen/gpt-5.3-codex`) were examined from the DB (`~/.config/mini-coder/sessions.db`). The pattern is consistent across every session:
8-
9-1. **Model receives task** → calls a tool or two (usually `glob` or `read`) showing initial compliance.
10-2. **Stalls immediately after first exploration** → instead of continuing to implement, outputs a verbose multi-paragraph response saying it *will* do the work, then hands control back to the user.
11-3. **Ralph mode doesn't help** — In ralph mode the session just re-starts clean each iteration, so the model sees the original prompt again, does 1-2 tool calls, then stalls again and outputs the planning text. The loop repeats without progress. In one session (12 messages), the model read three files and stopped five times asking to "proceed" before the user gave up.
12-
13-#### Concrete Example (session `mm7yk178-ctvsx`)
14-```
15-user: [long plan] "please implement this plan, start working on each turn"
16-assistant: [glob tool call] → [3x read tool calls]
17-assistant: "I can't complete that in one pass safely. This is a large multi-workstream refactor...
18- Reply **"proceed"** and I'll start implementing batch 1 immediately."
19-```
20-
21-The model never wrote a single file. It read files, described what it *would* do, then stopped and asked for permission. Every Codex session ends this same way.
22-
23----
24-
25-### Root Cause: Three Compounding Problems
26-
27-#### 1. Wrong API endpoint — Chat Completions instead of Responses API
28-
29-**mini-coder** uses `@ai-sdk/openai` via `createOpenAI()`, which defaults to the **Chat Completions** endpoint (`/v1/chat/completions`).
30-
31-**OpenAI's own Codex CLI**, **opencode**, and the official [Codex Prompting Guide](https://developers.openai.com/cookbook/examples/gpt-5/codex_prompting_guide/) all use the **Responses API** (`/v1/responses`). The Responses API is the only supported pathway for GPT-5.x Codex models — the prompting guide explicitly states: *"This model is only supported with the Responses API."*
32-
33-In opencode's `provider.ts`, for the `openai` provider:
34-```ts
35-openai: async () => {
36- return {
37- autoload: false,
38- async getModel(sdk: any, modelID: string) {
39- return sdk.responses(modelID) // ← Responses API, not sdk.chat()
40- },
41- }
42-}
43-```
44-
45-In mini-coder's `providers.ts`:
46-```ts
47-function zenOpenAI() {
48- _zenOpenAI = createOpenAI({ apiKey: ..., baseURL: ZEN_BASE })
49- // createOpenAI()(...) defaults to chat completions, not responses
50-}
51-```
52-
53-The `@ai-sdk/openai` SDK v3+ exposes `.responses(modelId)` to select the Responses API. mini-coder never calls it — so Codex receives requests on the wrong endpoint. This alone can cause the model to fail or fall back to a degraded behaviour mode.
54-
55-#### 2. System prompt delivered in wrong position
56-
57-The Responses API treats the `instructions` field as a high-authority system prompt. A `system`-role message in the `input` array is treated as a lower-priority user turn and **deprioritised** by the model.
58-
59-mini-coder's `turn.ts` already has partial mitigation — it sends `instructions` via `providerOptions.openai.instructions` for GPT models:
60-```ts
61-const useInstructions = systemPrompt !== undefined && isOpenAIGPT(modelString)
62-// ...
63-providerOptions: { openai: { instructions: systemPrompt + GPT_CONTINUATION } }
64-```
65-
66-However, `isOpenAIGPT` only returns `true` for `zen/*` and `openai/*` prefixes with model IDs starting with `"gpt-"`. The model id `gpt-5.3-codex` does start with `gpt-`, so this *should* be active. But if the Responses API isn't being invoked at all (problem #1), this is moot — the `instructions` field has no effect on Chat Completions.
67-
68-#### 3. System prompt content drives the stall behaviour
69-
70-The mini-coder system prompt is terse and generic:
71-```
72-Be concise and precise. Avoid unnecessary preamble.
73-Prefer small, targeted edits over large rewrites.
74-...
75-When in doubt, ask the user before making destructive changes.
76-```
77-
78-GPT-5.3-Codex is a **reasoning model tuned for agentic autonomy**. Its training specifically rewards:
79-- Asking for confirmation before proceeding
80-- Breaking large tasks into batches and requesting approval
81-- Hedging about "one pass" safety
82-
83-This is why it keeps stopping and asking "Reply 'proceed'". Its training RLHF pushes it toward collaborative, permission-seeking behaviour unless the system prompt explicitly overrides this with **strong autonomy and persistence directives**.
84-
85-The official Codex prompting guide is emphatic:
86-> *"Remove all prompting for the model to communicate an upfront plan, preambles, or other status updates during the rollout, as this can cause the model to stop abruptly before the rollout is complete."*
87-> *"You should also remove any prompting for the model to communicate an upfront plan, preambles, or other status updates during the rollout."*
88-
89-mini-coder's prompt has no autonomy directives. The `GPT_CONTINUATION` hint (`"Always make tool calls rather than describing them. Keep going until the task is complete, then stop."`) is a good start, but it's appended to instructions that never reach the model through the correct channel.
90-
91----
92-
93-## Fix Plan
94-
95-### Fix 1 — Wire the Responses API for Codex/GPT models (critical)
96-
97-In `src/llm-api/providers.ts`, the `zenOpenAI` and `directOpenAI` factory functions must call `.responses(modelId)` instead of the default `.chat()`:
98-
99-```ts
100-// Current (wrong for Codex):
101-createOpenAI({ apiKey, baseURL })("gpt-5.3-codex")
102-// → resolves to chat completions endpoint
103-
104-// Correct:
105-createOpenAI({ apiKey, baseURL }).responses("gpt-5.3-codex")
106-// → resolves to Responses API endpoint
107-```
108-
109-The `@ai-sdk/openai` provider exposes `sdk.responses(modelId)` to opt into the Responses API. We need to route `gpt-*` models through `.responses()` and leave others on the default.
110-
111-**Implementation:**
112-- Add a helper `isGPTModel(modelId: string): boolean` — returns true for `gpt-` prefixed IDs.
113-- In `resolveModel()`, when provider is `zen` or `openai` and model is a GPT, call `.responses(modelId)` on the created SDK instance.
114-
115-This mirrors exactly what opencode does in its `CUSTOM_LOADERS.openai` and what official Codex CLI does.
116-
117-### Fix 2 — Strengthen the Codex-specific system prompt (critical)
118-
119-Add a Codex-aware system prompt variant in `src/agent/agent.ts` (or a new `src/llm-api/codex-prompt.ts`). When the model is a Codex model, append (or replace) the system prompt with autonomy-first directives drawn from the official Codex prompting guide:
120-
121-Key additions:
122-- **Autonomy and persistence**: "Once given a direction, proactively gather context, plan, implement, test, and refine without waiting for additional prompts. Persist until the task is fully handled end-to-end."
123-- **Bias to action**: "Default to implementing with reasonable assumptions. Do not end your turn with clarifications unless truly blocked."
124-- **No preambles / no plans**: "Do not output an upfront plan, preambles, or status updates before working. Start working immediately."
125-- **No asking permission**: "Do not ask 'shall I proceed?' or 'shall I start?'. Start working."
126-
127-A helper `isCodexModel(modelString: string): boolean` should gate this (e.g., `modelId.includes("codex")`).
128-
129-### Fix 3 — Add `reasoningEffort` for Codex models (important)
130-
131-opencode sets `reasoningEffort: "medium"` by default for `gpt-5.*` models, and supports `high`/`xhigh` for Codex. The official guide recommends `"medium"` as the all-around default and `"high"`/`"xhigh"` for hardest tasks.
132-
133-In `turn.ts`, when building `streamOpts` for a Codex model, include:
134-```ts
135-providerOptions: {
136- openai: {
137- instructions: ...,
138- store: false,
139- reasoningEffort: "medium",
140- }
141-}
142-```
143-
144-### Fix 4 — Strip `itemId` from Responses API messages (correctness)
145-
146-opencode strips the `itemId` field from items in the `input` array when re-submitting to the Responses API (following what Codex CLI itself does). Without this, the API may reject or misbehave on multi-turn conversations. This should be done at the fetch layer or message serialisation layer.
147-
148----
149-
150-## Implementation Order
151-
152-1. **Fix 1** — Responses API wiring in `providers.ts` (unblocks everything)
153-2. **Fix 2** — Codex system prompt additions in `agent.ts` / `turn.ts`
154-3. **Fix 3** — `reasoningEffort: "medium"` default in `turn.ts`
155-4. **Fix 4** — Strip `itemId` from outbound messages (multi-turn correctness)
156-
157-Fixes 1 and 2 together should be sufficient to get Codex performing. Fixes 3 and 4 are polish/correctness.
158-
159----
160-
161-## Files to Change
162-
163-| File | Change |
164-|---|---|
165-| `src/llm-api/providers.ts` | Route `gpt-*` through `.responses()` for `zen`/`openai` providers |
166-| `src/llm-api/turn.ts` | Add `reasoningEffort`, update `isOpenAIGPT` to cover codex, strip itemIds |
167-| `src/agent/agent.ts` | Add Codex-specific autonomy directives to system prompt when Codex model detected |
168-
169-No new dependencies needed — `@ai-sdk/openai` already exposes `.responses()`.