@@ -0,0 +1,169 @@
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()`.