# Use Codex

> Use when delegating bounded coding, audit, or review work to codex-cli (OpenAI Codex) for an independent SECOND-OPINION pass that doesn't share Claude's blind spots, or to conserve Claude tokens on heavy content-writing. Codex picker (2026-07-01): gpt-5.5 (frontier/current default), gpt-5.4, gpt-5.4-mini, gpt-5.3-codex-spark (ultra-fast); gpt-5.3-codex and gpt-5.2 dropped from picker. Spec-driven, diff-first audit pattern — best for peer review of non-trivial diffs (money/auth/webhooks/migrations), bulk audits, multi-file content writes to spec. Skip for small edits or live step-through debugging. Sibling skill of use-cursor.

- Skill: `oimiragieo/use-codex` (Agent Skill)
- Install (CLI): `npx skillmds@latest add oimiragieo/use-codex`
- Raw SKILL.md: https://api.skillmd.com/api/skills/oimiragieo/use-codex/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Security
- Author: oimiragieo (https://skillmd.com/u/oimiragieo)
- Updated: 2026-09-17
- Page: https://skillmd.com/skills/oimiragieo/use-codex

---


# Use Codex

## Core rule

**Codex is a bounded peer reviewer + bounded implementation worker. Claude
owns the plan, the prompt file, the audit synthesis, the tests, the commits,
and the final answer to the user.**

The peer-review use case is the killer one: codex doesn't inherit Claude's
session context or rationalizations, so its audit catches what Claude misses.
Use it BEFORE shipping anything non-trivial that touches money, auth,
webhooks, or migrations.

## When to use vs when to skip

| Use codex-cli | Use Claude Agent tool subagent |
|---|---|
| Independent peer review of a non-trivial diff | Audits where Claude's tool context (existing reads) is already loaded |
| "Find bugs the orchestrator missed" pass | Reviews where the deciding rubric is in this codebase's CLAUDE.md only |
| Multi-file content writes following an explicit spec (alternative to cursor) | Reasoning that needs to feed back into THIS conversation |
| Bulk audit of N files where each can be reviewed in isolation | Tasks where Claude needs to inspect the result mid-flight |
| Cross-validation of a fix you're 80% sure is right | Trivial edits — Edit tool is faster |
| ≥3 files of writes; saves Claude output tokens | Anything where 30s of Claude time would beat 5min of codex round-trip |

**Don't use codex for:**
- Small targeted edits (Edit tool is faster)
- Live debugging / step-through reasoning (codex sessions don't yield mid-flight)
- Anything where you need codex's output to immediately influence your next tool call (it's async-friendly, not sync-friendly)
- Tasks that REQUIRE the full Claude conversation context (codex starts cold)

## Available models (ChatGPT Plus auth)

These work on `codex login --chatgpt` accounts. Wrong model name returns
`{"type":"error","status":400,...,"message":"The 'X' model is not supported
when using Codex with a ChatGPT account."}` — misleading; same message for
"doesn't exist" and "needs API auth". Sanity-test before long-running specs.

**Evidence-backed model picker** (full benchmark-backed analysis at
`docs/audits/2026-05-02-cli-model-task-matrix.md`; numbers cite vendor blogs +
Simon Willison + spectrumailab + MarkTechPost):

| Model | Best for | Key benchmarks | Don't use for |
|---|---|---|---|
| `gpt-5.5` | **Frontier review** (auth/billing/migrations), reasoning-heavy debugging, terminal/agentic harness work, cybersecurity audits, greenfield architecture | Terminal-Bench 2.0 **82.7% (SOTA)**, GDPval 84.9%, FrontierMath Tier 4 39.6% (~2× Opus 4.7), SWE-Bench Pro 58.6% | Routine work where 5.4 fits — 5.5 doubles in price above 272K input |
| `gpt-5.4` | **Default everyday coding**, multi-file edits, native computer use, 1M-context analysis under 272K | SWE-Bench Pro 57.7%, Terminal-Bench 2.0 75.1%, OSWorld-Verified 75.0%, GPQA Diamond 93.0% | Frontier reasoning beyond 272K (price cliff) |
| `gpt-5.4-mini` | **Parallel subagent fan-out**, OSWorld/screenshot tasks, bulk small-file audits with short context | OSWorld 72.1% (near full 5.4's 75.0%), τ2-bench telecom 93.4% | **Long-context retrieval — MRCR v2 8-needle 64K-128K collapses to 47.7% vs 86.0% on full 5.4** |
| `gpt-5.3-codex-spark` | **Ultra-fast coding** (slot 4 in the picker): real-time iteration, single-file tweaks, CI/CD codex-exec batches at 1000+ tps. Also the `gpt-5.5`-exhausted fallback (separate capacity) | Vendor claims Terminal-Bench 77.3% parity with the retired 5.3-codex; **independent re-runs measure ~58.4% — 19-point gap** | **NEVER for hard reasoning.** Plus/Team users may see CLI silently route to default — verify with `/status`, not `/model`. |
| ~~`gpt-5.3-codex`~~ **DROPPED from picker (2026-07-01)** | (was: long-horizon agent loops, terminal-heavy) — the non-spark coding variant; probe before use (may `400`) | Terminal-Bench 2.0 77.3%, SWE-Lancer IC Diamond 81.4%, Cybersecurity CTF 77.6% | New work — gone from picker; use `gpt-5.3-codex-spark` or `gpt-5.4` |
| ~~`gpt-5.2`~~ **DROPPED from picker (2026-07-01)** | (was: multi-day agent loops, input-heavy long-context) — probe before use (may `400`) | SWE-Bench Verified 80.0%, AIME 2025 100%, MRCRv2 8-needle 128K-256K 77.0% | New work — gone from picker; superseded by 5.4 |

Default is `gpt-5.5` per `~/.codex/config.toml`. Always specify `-m` explicitly
when scripting — don't rely on the default.

**Model-name precision:** `gpt-5.3-spark` does NOT exist; the real name is
`gpt-5.3-codex-spark`. The full canonical IDs per OpenAI API docs may also
include the alias `gpt-5.3` for the codex variant.

**Canonical `-m` model IDs (verbatim from the `codex` `/model` picker, 2026-07-01):**
```
1. gpt-5.5 (current/default)      Frontier model for complex coding, research, and real-world work.
2. gpt-5.4                        Strong model for everyday coding.
3. gpt-5.4-mini                   Small, fast, and cost-efficient model for simpler coding tasks.
4. gpt-5.3-codex-spark            Ultra-fast coding model.
```
These 4 strings are the current picker values. **DROPPED from the picker since 2026-05-29**
(probe with `codex exec -m <id> --skip-git-repo-check - <<<ping` before relying — may now
return `400 ... model is not supported`): `gpt-5.3-codex` (the non-spark coding variant) and
`gpt-5.2`. Note `gpt-5.3-codex-spark` moved from slot 5 → slot 4. Any name not routable returns
`400 ... model is not supported`. (The benchmark-backed when-to-use picker is the table above;
this block is the authoritative name list to copy from.)

### Fallback chain when `gpt-5.5` is maxed out / rate-limited (READ THIS)

`gpt-5.5` on ChatGPT Plus auth has a **usage cap that exhausts within a heavy
session** — when it does, `codex exec -m gpt-5.5` returns an **empty / zero-byte
result** (no error, just nothing). This silently drops the codex seat from a
thinktank or audit. Receipt: 2026-05-29 — codex returned empty across ~5
consecutive dispatches in one session while gemini/droid worked, because the
5.5 cap was exhausted. **Detection:** the seat's log is empty / has no
`^RECOMMENDED:` (or no substantive output) while sibling seats succeeded.

When `gpt-5.5` is exhausted, do NOT just drop the seat — fall back **in order**:

1. **codex with `gpt-5.3-codex-spark`** — same codex CLI, a different (non-5.5)
   model that draws on separate capacity: `codex exec -m gpt-5.3-codex-spark`.
   Good for second-opinion audits + bounded review; **NOT for hard multi-step
   reasoning** (it drifts — see the table). For a frontier-reasoning slot prefer #2.
2. **copilot with `gpt-5.5`** — GitHub Copilot CLI reaches `gpt-5.5` through a
   SEPARATE quota (Copilot Pro/Business, not the ChatGPT Plus cap), so it keeps
   the frontier 5.5 perspective alive when codex's 5.5 is dead. Use the
   `use-copilot` skill: `copilot -p "<prompt>"` (it routes to a strong default;
   pin 5.5 if the CLI version supports `--model gpt-5.5`). This is the right
   fallback when the task genuinely needs 5.5-class reasoning.
3. Last resort: drop the codex seat and note the missing voice (still get the
   other seats) — only if both #1 and #2 are unavailable.

In a **thinktank dispatch**, wire this as: try `codex -m gpt-5.5`; if its log
comes back empty, re-fire that seat as `copilot -p` (frontier) or
`codex -m gpt-5.3-codex-spark` (fast) rather than synthesizing with a silently
missing seat. (Cross-ref: `use-copilot` skill; apply the same seat-swap rule in any multi-seat council dispatch.)

## Workflow

```dot
digraph codex_workflow {
    "Identify codex-fittable task" -> "Verify codex auth + model availability";
    "Verify codex auth + model availability" -> "Write task spec file";
    "Write task spec file" -> "Launch codex exec in background";
    "Launch codex exec in background" -> "Continue Claude orchestration";
    "Continue Claude orchestration" -> "Wait for codex exit";
    "Wait for codex exit" -> "Audit output";
    "Audit output" -> "Synthesize into Claude's response";
}
```

### 1. Verify codex is available + which model

```bash
codex --version             # 0.128.0 or higher
codex login status          # "Logged in using ChatGPT" expected
cat ~/.codex/config.toml | grep "^model"
```

If `codex` isn't on PATH, the user installs via `npm i -g @openai/codex`;
do not attempt to install yourself.

### 2. Write the task spec file in the repo

Save at `<repo>/.claude/codex_task_<short-name>.md`. Don't put it in `.tmp/`
or anywhere gitignored — the spec should be discoverable in PRs and post-mortems.

**If the task is to write a driver script for a long-running remote job:** the spec should require the sub-agent to validate environment prerequisites (dependency versions, credentials, disk) BEFORE the main work starts, so the job fails fast at setup rather than deep into an expensive run. If you maintain a job-setup/verification convention, cite it in the spec.

Spec shape (parallel to use-cursor; codex tolerates more conversational tone):

```markdown
# codex task: <one-line objective>

You are running as `codex exec` in non-interactive mode against the
`<branch>` branch of `<repo>` at `<absolute path>`. <Constraint sentence —
e.g. "Do not modify any code; produce a markdown audit report.">

## Context (what the orchestrator believes is true)
- Recent shipping history relevant to this task
- F* finding numbers + what they claim to fix
- Tier classifications (CRITICAL / HIGH / MEDIUM / LOW)

## Files to review (focus your attention here)
```
path/to/file.py    # what changed, why it matters
...
```

## What to look for
(severity-ranked checklist of bug classes)

## Output structure
(exact markdown shape for the audit doc, with headers + tables)

## Constraints
- Do NOT modify code (audit only) OR Do NOT push (just edit)
- Do NOT git add/commit/push
- Use model X end-to-end
- Working dir is <path>
- If file > 500 lines, focus on diff regions via `git log -p -- <file>`

## Done criteria
Print: `[codex-audit] DONE <scope> critical=N high=N medium=N low=N file=<path>`
Then exit. Do NOT continue to interactive mode.
```

Be explicit. Codex's exec mode is competent but cold-starts every session, so
spec MUST contain everything it needs (no "as we discussed earlier"). Inline
the orchestrator's existing claims so codex can VALIDATE rather than re-derive.

### 3. Launch codex exec in the background

**ROUTE THROUGH THE HEADLESS WRAPPER** (2026-05-13 fix). The wrapper at
a local headless wrapper script temporarily renames both Superpowers
entrypoints (any auto-loading skill/plugin junctions codex would otherwise pick up) OFF for
the lifetime of `codex exec`, then restores them via try/finally — so the
global skill scan can't auto-load using-superpowers/brainstorming/TDD on every
headless dispatch and hijack the response. The inline skill-bypass preamble in
the spec is now defense-in-depth only; the wrapper is the load-bearing fix.
The wrapper also injects `--ignore-user-config` by default so OAuth MCP servers
from `~/.codex/config.toml` cannot hang a headless run with
`rmcp::transport::worker: Auth(TokenRefreshFailed)`. If the Codex seat truly
needs MCP/user config, pass wrapper-only flag `--with-user-config` and refresh
the specific OAuth server first with `codex mcp login <server>`.

```bash
mkdir -p /tmp/codex_logs
cd <workspace>/REPO    # ← REQUIRED on Windows; do NOT use --cd flag

# WSL path → Windows path for powershell.exe
WIN_REPO=$(pwd | sed 's#^/c/#C:/#; s#/mnt/c/#C:/#; s#/#\\#g')

# PREFER the codex dispatch wrapper (v2 2026-05-13) over the raw headless wrapper
# for spec-from-file dispatches from WSL. Three Windows-specific failure modes
# the raw wrapper hits on multi-KB markdown specs:
#
#  1. `< spec.md` stdin-redirect through `nohup powershell.exe -File` does NOT
#     propagate stdin to codex — codex reads zero bytes then exits cleanly,
#     log shows only the prompt echo with no assistant turn.
#  2. The wrapper's `--ignore-user-config` injection (the MCP-hang defense)
#     strips `model_reasoning_effort` from ~/.codex/config.toml — codex runs
#     at reasoning=none and emits zero tool calls. Must explicitly pass
#     `-c 'model_reasoning_effort="high"'`.
#  3. Get-Content -Raw → positional prompt arg makes PowerShell native-exe
#     arg-passing split on whitespace; any markdown hyphenated token (e.g.
#     `log-frequency` in a docstring) gets interpreted as a clap-rs flag.
#
# the codex dispatch wrapper sidesteps all three: Get-Content -Raw -Encoding UTF8,
# mirrors auto-loading skill junction handling inline (mutex + rename + try/finally),
# explicit reasoning_effort, and pipes prompt via `$prompt | & codex -` (the
# `-` is a string literal positional from inside PowerShell, so the wrapper-
# rejection of leading-dash doesn't apply).
#
# Source: `a local codex dispatch wrapper`
WIN_SPEC="<workspace>/REPO/.claude/codex_task_<name>.md"
WIN_REPO="<workspace>/REPO"
nohup powershell.exe -ExecutionPolicy Bypass \
  -File 'a local codex dispatch wrapper' \
  -SpecPath "$WIN_SPEC" \
  -WorkDir "$WIN_REPO" \
  -Model gpt-5.5 \
  -ReasoningEffort high \
  > /tmp/codex_logs/<name>.log 2>&1 &
echo $! > /tmp/codex_logs/<name>.pid

# If you have a one-shot bounded prompt (no spec file), the raw wrapper still
# works because the prompt is the positional arg (no stdin handling needed):
#
#   powershell.exe -ExecutionPolicy Bypass \
#     -File a local codex headless wrapper \
#     -m gpt-5.5 \
#     -c 'model_reasoning_effort="high"' \
#     --skip-git-repo-check \
#     "Your one-line prompt here"

# Sanity-verify the process is alive past startup (catches the silent-die
# failure mode where codex exits in <1s with the os-error-2 bug):
sleep 3
if kill -0 $(cat /tmp/codex_logs/<name>.pid) 2>/dev/null; then
  echo "alive — workdir line in log:"
  grep "^workdir:" /tmp/codex_logs/<name>.log
else
  echo "DIED AT STARTUP — check log:"
  cat /tmp/codex_logs/<name>.log
fi
```

Flags:
- `-m <model>` — pin the model explicitly (don't trust default)
- `--cd <abs-path>` — set working dir; codex defaults to its own launch dir
  (often a different project!). **Gotcha (proven 2026-05-02):** when launched
  via bash+nohup on Windows, `--cd C:\\dev\\projects\\REPO` (backslash-escaped)
  causes codex to die at startup with `Error: The system cannot find the
  file specified. (os error 2)` and ZERO log output beyond that. Workarounds
  (in priority order): (a) `cd <repo>` in the launching shell first and OMIT
  `--cd` entirely (codex inherits pwd); (b) use forward slashes
  `--cd <workspace>/REPO`; (c) use the cygpath-style `--cd <workspace>/...`
  (UNTESTED). The pwd-inheritance approach is the most reliable.
- `--skip-git-repo-check` — for cases where the spec dir isn't the repo root
- `--dangerously-bypass-approvals-and-sandbox` — required for unattended
  background execution; safe ONLY because the spec forbids destructive ops
  (no commit/push, audit-only). Do NOT pass this for write-mode tasks unless
  you fully trust the spec
- `- < .claude/...md` — read prompt from stdin (cleaner than -p inline arg)

The Bash tool's `run_in_background: true` parameter is an alternative when
you want Claude to be notified on completion via the task-notification
channel.

**Note: codex CLI does NOT need WSL on Windows** (unlike cursor-agent). It
runs natively from bash, PowerShell, or cmd. Windows path separators in `--cd`
need double-escaped backslashes (`C:\\dev\\...`) when invoked from bash.

### 4. Continue Claude orchestration

Codex sessions take 5-15 min for typical multi-file audits with `gpt-5.5`,
or 2-5 min with `gpt-5.3-codex-spark`. Use that time for parallel
Agent-tool subagent dispatches, your own focused work, or other codex jobs
on different scopes. **Never tail the codex log via `cat /tmp/codex_logs/*.log`
in a hot loop** — wastes tokens. Check it once at the end.

For long-horizon waits (>5 min), use the `ScheduleWakeup` tool to set a
wakeup so you're not blocked.

### 5. Wait for codex exit, then **audit the audit**

```bash
while kill -0 $(cat /tmp/codex_logs/<name>.pid) 2>/dev/null; do
  sleep 30
done
echo "exited"
tail -30 /tmp/codex_logs/<name>.log
```

Then:

1. **Read the audit doc codex produced** (NOT the log — the log is noisy
   token-stream output; the audit doc is the structured deliverable).
2. **Diff the audit's findings against your existing understanding.**
   - Findings codex agrees with: validation; mark in your tracker.
   - Findings codex flags as missed: triage by severity; the highest-severity
     ones may require Round N+1 fixes.
   - Findings codex calls WRONG: investigate. Codex doesn't have your full
     context, so it may misread; look at the specific file:line it cites.
3. **Synthesize into your response to the user.** Don't dump the codex doc
   verbatim — extract the verdict + the actionable items.
4. **If you trust the codex finding and it requires a fix:** dispatch a
   Claude Agent subagent (or write the fix directly), reference the codex
   audit doc in the commit message ("found by codex audit
   docs/audits/2026-05-02-codex-backend-audit.md").

### 6. Run-many pattern (audit-by-fanout)

For large audits, run multiple codex jobs in parallel with DIFFERENT scopes
(not the same scope twice — that's redundant). Example split across a
typical backend/web/docs audit fan-out:

- Job A (frontier model): backend audit — API + DB + cron + startup checks
- Job B (fast model): web audit — UI + types + hydration risks
- Job C (mid-tier model): docs audit — claim vs code drift in CLAUDE.md / skills

Each writes to `docs/audits/<date>-codex-<scope>-audit.md`. Diff against
each other for cross-validation; if Job A and Job B both flag the same
boundary issue (e.g., API returns X but web expects Y), it's a real bug.

## Spec shape — required fields

| Field | Why |
|---|---|
| Working dir as absolute path | Codex defaults to its own launch dir (often another project) |
| Model explicit | Default may have shifted; `-m` forces it |
| Branch + repo path | Stops codex from wandering into the wrong worktree |
| Files to review (read-only or write-target) | Bounds blast radius |
| Orchestrator's existing claims | So codex can validate, not re-derive |
| Severity rubric (CRITICAL/HIGH/MEDIUM/LOW with examples) | Codex's calibration drifts without anchors |
| Output file path + structure | The deliverable, not the log |
| "Do NOT git commit/push/add" | Bounds the destructive blast radius |
| "Do NOT switch model mid-session" | Some models silently switch; pin it |
| "Do NOT continue to interactive mode" | Forces clean exit |
| Done-criteria line | Audit anchor for the orchestrator |

## Guardrails

- **NEVER write the literal `e-v-a-l(` (the four-letter identifier
  immediately followed by an open paren) into a codex spec file — even
  inside a "do NOT do this" instruction.** The PreToolUse
  `security_reminder_hook` matches the contiguous 6-character substring
  and BLOCKS the Write tool, regardless of context (Python file, Markdown
  spec, plan doc, JSON, HEREDOC). Recursive trap: documenting the rule
  triggers the rule. **Safe substitutions when telling codex what to
  avoid:**
  - "do not use the model's e-val method (with parens) — use
    `model.train(False)` instead"
  - Quote the method NAME without parens: `model.eval` — and describe
    the call verbally as "calling that method".
  - Or embed the runnable substitute directly in a code fence and skip
    the negative form entirely:
    ```python
    model.train(False)  # equivalent to the e-val method call
    ```
  - For ANY file the orchestrator writes (codex spec, plan doc, skill
    update, memory file, this very SKILL.md), grep the draft for the
    6-char literal before submitting Write. Cost: 5 seconds. Cost of
    a hook block: one wasted Write turn + a context-bloating error
    message in transcript. Receipts: 2026-05-09 (twice — script then
    plan doc), 2026-05-10 (codex spec writing about the trap itself).
    Keep a note of this trap wherever your own project tracks recurring gotchas.
- **Never paste raw markdown into `bash -lc "$(cat ...)"`.** Shell expansion
  can execute prompt text or corrupt the task. Use stdin-from-file (`< spec.md`)
  or `-` argument and let codex read it.
- **No backticks in the launch command's prompt string.** They get evaluated
  by the host shell. Reference the spec file by path.
- **Process pollution check after a bad launch:**
  `ps -ef | grep -E "codex" | grep -v grep`
- **Do not pass HF_TOKEN, OPENAI_API_KEY, or other secrets in the prompt.**
  Codex reads them from `~/.codex/config.toml` or `.env.local`; the spec
  must say so without inlining the value.
- **Codex auth gates which models work.** A spec asking for `gpt-5.3-codex-spark`
  on a ChatGPT account will fail with a misleading error. If you're not sure
  which auth the user has, ask before dispatching, OR test with a 2-token
  sanity ping first through the wrapper:
  `powershell.exe -ExecutionPolicy Bypass -File a local codex headless wrapper -m <model> --ephemeral "say only OK"`.
- **Model-name typo silently kills the session.** Always sanity-test the
  model string before launching a long-running spec.
- **Working-directory mismatch silently kills the session.** Codex's `--cd`
  flag is mandatory for non-default workspaces. The user's status pane will
  show codex's actual directory; verify it matches your spec's intent.
- **`--dangerously-bypass-approvals-and-sandbox` is a safety override.** Use
  ONLY when the spec is audit-only or has explicit no-write/no-commit
  constraints. Never combine with a write-capable spec without also enabling
  Claude-side audit of the diff before any commit.
- **Codex's success report is optimistic.** It says "DONE" even when the
  output file is incomplete. Always verify the deliverable file exists,
  has content, and follows the spec's structure before declaring success.
- **Codex `git commit -m "..."` on Windows silently fails for multi-line
  messages with backticks, single quotes, or embedded newlines.** When
  headless codex runs on Windows via the codex headless wrapper, its `git commit -m "..."`
  invocations route through `pwsh.exe -Command '...'`. PowerShell's
  quote-parser corrupts the message string, the shell exits 0
  (silent success!), and git commits nothing. Codex's DONE report says
  "commits=N" but `git log` shows zero new entries. Files are in the
  working tree as untracked.

  **Receipt:** one codex job wrote 4
  files + 1 test file cleanly. Its `pwsh.exe -Command 'git commit -m
  "..." -m "..."'` with embedded `\`n` and single-quoted inner content
  failed silently. Detected on audit; manually `git add` + `git commit`
  recovered the work. Cost: 5 min audit time, zero rework.

  **The fix.** In codex specs that include commit steps, always include:

  ```markdown
  ## Commit instructions

  Use `git commit -F <message-file>` (write the message to a tmp file
  first). Do NOT use `git commit -m "..."` with an inline multi-line
  message — on Windows this routes through PowerShell whose quote-parser
  silently corrupts embedded newlines, backticks, and single quotes.

  After every `git commit`, run `git log -1 --oneline` and verify the
  expected subject is present. If absent, re-stage and retry with the
  `-F` form. Do NOT print "DONE" until `git log` confirms the commit.
  ```

  Orchestrator-side mitigation: after every codex DONE, run
  `git status --porcelain | grep "^??"` (untracked files = silent
  commit failure) AND `git log --oneline -3` (commit subjects match
  expected). Catches the bug in 2 seconds. If untracked files surfaced
  by codex's spec exist, manual `git add + commit` is the recovery —
  the work itself is intact.

## When to escalate / abort

- Codex exits non-zero or prints `BLOCKER` → read log tail (last 30 lines),
  diagnose, possibly rewrite the spec + relaunch
- Codex's audit doc claims something contradicting an obvious code reality →
  spot-check the cited file:line; if codex is wrong, document your
  counter-finding and DON'T relaunch
- Codex stalls past expected wall (>20 min for typical multi-file audits at
  gpt-5.5; >10 min for spark) → `kill $(cat /tmp/codex_logs/*.pid)`,
  inspect log, decide whether to retry with a tighter spec
- Codex produces an audit doc with NO findings on a surface you KNOW has
  bugs → spec was too narrow; widen the file scope and relaunch

## Windows CreateProcess refresh failure — orchestrator takeover (2026-05-25)

**Symptom:** codex returns `Rejected("Failed to create unified exec process: spawn setup refresh")` immediately, without reading any files or producing output.

**Receipt:** in one session, two separate codex dispatches on the same repo both failed with this error within 30 seconds. Retrying with the same spec failed again. The failure is a Windows-specific issue in the codex CLI's process-spawn layer; it is NOT a spec error, NOT a model error, and NOT a network issue.

**Failure identification:** if `Rejected("Failed to create unified exec process: ...")` appears 2+ times in succession on distinct specs, it is a codex process-spawn state issue, not a spec problem.

**What to do (orchestrator takeover):**

1. Do NOT rewrite the spec or retry codex.
2. Verify the files codex was supposed to audit via `git status` + targeted `Grep`.
3. Run the tests and lint gate yourself:
   ```bash
   black --check --line-length 100 api/app/ api/tests/
   ruff check api/app/ api/tests/
   PYTHONPATH=. pytest api/tests/ -q ...
   ```
4. Commit when tests + lint pass. Codex's review pass is skipped for this slice; document in the commit message: `(codex spawn-failure, orchestrator-verified)`.
5. If a second-opinion review is load-bearing (money/auth/migration), fall back to a gemini `--approval-mode plan` pass (dead post-2026-06-18 -> use agy/droid) or a Claude `general-purpose` Agent audit subagent.

**Recovery attempts that do NOT help:** rewriting the spec, changing model, changing `--cd`, re-running `codex login`, killing + restarting the terminal. Only a full workstation restart or waiting ~5 minutes resets the spawn state.

If you keep a durable-memory file for recurring tool gotchas, log this one there for next time.

## Real-world impact (backend/web/docs audit fan-out)

- **Two-model parallel dispatch worked:** a frontier model on a backend
  audit surface + a fast model on web, in parallel. Total wall time: ~15 min
  vs estimated 30+ min if sequential. Both wrote to separate audit files;
  cross-validation by diff caught one boundary issue (API field name vs web
  expectation) that neither model would have caught alone.
- **Spec precision pays off:** the spec that inlined the orchestrator's
  existing findings verbatim ("finding X registers 5 phantom tools at lines
  Y/Z, validate these registrations exist") got crisp validation findings.
  The spec that said "review recent backend changes" got a generic "looks
  reasonable" audit with no actionable items. Always inline the existing claims.
- **Working-dir gotcha bit us once:** codex defaulted to a sibling project's
  directory and produced an audit on the wrong codebase before the
  orchestrator caught it. `--cd <abs-path>` is mandatory.

## Red flags — STOP and rewrite the spec

- "Audit the codebase" — too open-ended; codex will produce a review of
  whatever file it reads first
- "Find bugs" — needs explicit severity rubric and bug-class examples
- "Validate the fix" — needs the specific file:line + claim of what the fix does
- "Suggest improvements" — codex will rewrite working code
- Multi-step plans without explicit sequencing → split into N specs

## Cross-references

- Sibling skills (the rest of the delegation matrix):
  - `use-cursor` (`~/.claude/skills/use-cursor/SKILL.md`) — bounded WRITE
    work in WSL on auto-model. Complementary (cursor implements, codex audits).
  - `use-gemini` (`~/.claude/skills/use-gemini/SKILL.md`) — third-opinion
    audit via Google Gemini CLI. Pair codex+gemini for cross-vendor
    cross-validation on high-stakes diffs.
  - `use-claude-in-chrome` (`~/.claude/skills/use-claude-in-chrome/SKILL.md`)
    — drives the user's REAL Chrome session (cookies/OAuth/MFA inherited).
    **When codex needs to inspect or interact with an authenticated SaaS
    dashboard, dispatch via this skill** rather than codex's own
    `chrome-devtools-mcp` (which is fresh-headless and lacks the user's
    session). Codex can invoke `mcp__claude-in-chrome__*` tools if the
    orchestrator loads them via ToolSearch first.
- For research/audit work that needs to feed back into the conversation,
  prefer the Claude Agent tool (subagent_type: feature-dev:code-reviewer,
  feature-dev:code-architect, general-purpose with mcp__Exa__*). Agent
  subagents return their report inline; codex commits to a file and you
  audit the file.
- Codex MCP server connectors live in `~/.codex/config.toml` `[mcp_servers]`.
  Currently registered (2026-05-02): context7, github (needs GITHUB_TOKEN),
  chrome-devtools, exa, ref. These are AVAILABLE to codex sessions
  automatically — useful for specs that need exa search or chrome-devtools
  inspection during the audit.

