# Recover from Codex errors and wrong turns

URL: https://developertoolkit.ai/en/codex/quick-start/error-recovery/
Description: Diagnose a Codex failure, apply the right fix, and roll back with Git: sandbox blocks, failed commands, wrong-direction edits, long threads, MCP and login.

Codex error recovery means matching a failure to one of five types (a sandbox or approval block, a failed command, a wrong-direction change, a long thread that has lost track, or a broken connection) and applying its fix. Backtracking rewinds the conversation, not your files: in Codex CLI 0.157.1 the per-turn `undo` snapshot feature is removed, so Git restores files.

This page is for developers who have run their [first Codex task](/en/codex/quick-start/first-task/) and have now watched one go wrong. Codex ran `npm install` in a pnpm repository, the lockfile changed, and the build broke. Or it answered a type error with three rounds of casts, each worse than the last. Or it refactored a module you did not ask it to touch. Each of those takes minutes to undo when you know which kind of failure it is, and an afternoon when you do not.

## What a Codex recovery routine gives you

- A triage table that maps the symptom you see to the fix section below.
- A Git checkpoint habit that makes every other recovery cheap.
- The exact approval choices, flags and config keys for Codex CLI 0.157.1, including the narrow grants that fix a sandbox block without opening the sandbox.
- Five copy-paste prompts: plan first, fix the root cause, redirect, hand off a long thread, and break an error loop.
- A three-check routine that proves the recovered result works without reading every line.

## Which kind of Codex failure are you looking at?

Read the symptom first. Most wasted recovery time comes from applying the right fix to the wrong failure, such as starting a new thread when the real problem is a missing network grant.

| Symptom | Failure type | First check | Go to |
| --- | --- | --- | --- |
| An approval prompt appears, or a command fails with "permission denied" or a DNS error | Sandbox or approval block | Is the task asking for something outside the workspace? | [Fix sandbox and approval blocks](#fix-sandbox-and-approval-blocks-in-codex) |
| A shell command exits non-zero: install, build or test errors | Failed command | Does `AGENTS.md` name the right package manager and test command? | [Recover from a failed command](#recover-from-a-failed-command) |
| The code compiles, maybe passes tests, but solves the wrong problem | Wrong direction | Did Codex state a plan before it started editing? | [Undo a wrong-direction change](#undo-a-wrong-direction-change) |
| Codex repeats work or contradicts an earlier decision | Long thread | What does `/status` show for token usage? | [Recover a long thread that has lost track](#recover-a-long-thread-that-has-lost-track) |
| An MCP tool is missing or times out, or you see authentication errors | Connection | What do `codex mcp list` and `codex doctor` report? | [Fix MCP, network and login failures](#fix-mcp-network-and-login-failures) |

## Set a Git checkpoint before a risky task

Every recovery below ends in the same place: your files back at a known-good state. Git is what gets them there. The Codex CLI no longer takes its own per-turn snapshots — `codex features list` in 0.157.1 lists `undo` with the stage `removed` — so the checkpoint has to be yours.

In the terminal, before you hand Codex a refactor, a dependency change or anything that touches more than a few files:

```bash
git status                        # start from a clean tree, or know what is already dirty
git add -A && git commit -m "checkpoint: before codex auth refactor"
```

For larger or exploratory work, keep Codex out of your main checkout entirely. `codex --worktree` starts the session in a new managed Git worktree, and `/worktree` does the same from inside a session. A wrong turn in a worktree costs you a directory you can delete. The full workflow is in [isolated Codex tasks with Git worktrees](/en/codex/automate/worktrees/).

The cheapest recovery is the one you never need. A plan before any edits catches most wrong-direction work while it is still a paragraph of text.

**Copy-paste prompt: plan before you edit**

```text
Before you change any file, read AGENTS.md and the files you expect to touch, then
reply with a plan of 3-5 bullets: which files change, which libraries and patterns
you will use, and which command proves the change works. Do not edit anything until
I reply "go".
```

## Fix sandbox and approval blocks in Codex

Once you have answered the trust prompt for a repository, and unless your config says otherwise, Codex runs commands under the `on-request` approval policy with the `workspace-write` sandbox (checked against the 0.157.1 source). It can edit files inside the workspace and run commands there. Writing outside the workspace, or reaching the network, needs your approval. A command that fails with a DNS or connection error inside the sandbox is usually the sandbox doing its job, not a problem with your network.

When Codex asks to cross the boundary, the approval prompt in Codex CLI 0.157.1 offers choices such as these:

- **Yes, proceed** runs this one command.
- **Yes, and don't ask again for this command in this session** stops the repeat prompts for a command you trust, such as your test runner.
- **No, and tell Codex what to do differently** cancels the command and lets you redirect in the same step.

Choose the last option more often than feels natural. When Codex wants to write to `/usr/local` or install a global package, the right fix is usually a different approach, not a wider sandbox.

If the task genuinely needs more access, grant the narrowest thing that unblocks it:

**One extra directory**

In the terminal, add a writable directory for this session only:

```bash
codex --add-dir ../shared-fixtures
```

The rest of the sandbox stays as it was, and nothing persists to the next session.

**Network for one project**

If every task in a project needs the network (a package registry, for example), grant only network access in `~/.codex/config.toml`:

```toml
sandbox_mode = "workspace-write"

[sandbox_workspace_write]
network_access = true
```

OpenAI now prefers permission profiles (beta), selected with `default_permissions` and switched in the TUI with `/permissions`. Profiles and the legacy sandbox settings do not compose, so pick one system per setup. [Configure Codex](/en/codex/quick-start/configuration/) covers both.

**Automatic review**

If you run Codex with `--approve-for-me`, a reviewer model decides sandbox-boundary requests for you. When it denies a request you know is safe, `/approve` retries that one denial. Nothing else about the policy changes.

`--dangerously-bypass-approvals-and-sandbox` removes both the approvals and the sandbox. Use it only inside a disposable, network-restricted environment such as a throwaway container, never on your own machine to get past a single prompt.

**Copy-paste prompt: find a path inside the sandbox**

```text
The sandbox blocked your last command. Do not ask for wider access yet. Explain what
the command needed from outside the workspace, then propose a way to reach the same
result inside this repository: a local config file, a project-level dependency, or a
script under scripts/. Only if no such path exists, tell me the single narrowest
permission you need and why.
```

## Recover from a failed command

A failed command is the most common Codex error and the easiest one to fix. Codex usually reads the error output and tries again on its own.

1. **Give Codex one attempt.** Codex reads the exit code and the error output, and often fixes a typo or a missing import without help. Intervene if the second attempt repeats the first.

2. **Read the first error yourself.** The line that matters is usually the first one, not the last. A cascade of 40 type errors often comes from one wrong import.

3. **Supply the missing fact.** Codex guessed the package manager, the test command or the database state. Tell it, in one sentence, with the exact command.

4. **Write the fact down.** Add the correct build, test and lint commands to `AGENTS.md` so the next session starts with them. Keep them near the top: Codex reads at most `project_doc_max_bytes` of project instructions (32 KiB by default in 0.157.1). [Write AGENTS.md for Codex](/en/codex/quick-start/agents-md/) shows the layout.

**Copy-paste prompt: fix the root cause, not the symptom**

```text
The last command failed. Do not re-run it unchanged. Quote the first error line,
state the root cause in one sentence, and fix that cause rather than silencing the
error: no type casts, no @ts-ignore, no skipped or deleted tests. Then re-run the same
command and paste its exit code and summary line.
```

If the command fails because a service is missing (a database, a queue, a local API), the fix is outside Codex. Start the service, or tell Codex to use the test double the project already has. For a systematic hunt through a real bug, use [debugging and bug hunting with Codex](/en/codex/test/bug-hunting/).

## Undo a wrong-direction change

A wrong-direction change is the failure that costs the most, because nothing goes red. Codex used Express in a Fastify service, or added a REST endpoint where the project uses GraphQL. Catch it early: watch the first few file edits, and press `Esc` as soon as the direction looks wrong. Codex stops the turn and prompts you to tell the model what to do differently.

Then choose how far back to go:

**Redirect in place**

If the edits so far are mostly usable, correct the course and let Codex clean up:

```text
Stop. This service uses Fastify, not Express (see package.json and src/server.ts).
Remove the Express code you added, re-implement the route with Fastify's route
handler pattern, and list every file you changed.
```

**Rewind the conversation**

Press `Esc` twice on an empty composer to browse your earlier prompts. Use the arrow keys to pick one, then press `Enter`. Codex reverts the thread to just before that prompt and puts it back in the composer, so you can rewrite it with the missing constraint.

A rewind changes the conversation, not your files. Run `/diff` afterwards: if edits from the abandoned turns are still there, restore the files with Git.

**Restore files with Git**

In the terminal, choose the granularity:

```bash
git diff --stat                            # what changed since the checkpoint
git restore -p src/                        # discard chosen hunks interactively
git restore src/routes/ src/server.ts      # discard whole files
git stash push -u -m "codex: express attempt"   # set the whole attempt aside, recoverably
```

Prefer `git stash` over `git reset --hard`: a stash keeps the failed attempt, including new untracked files, in case one part of it was worth keeping. `git reset --hard` discards tracked changes permanently and leaves new files behind.

**Copy-paste prompt: restart with the missing constraint**

```text
Your last change solved the wrong problem, and I have reverted it. What I need: the
/invoices endpoint returns 404 instead of 500 when the invoice does not exist, with no
change to the response shape for existing invoices. Constraints: change only files
under src/invoices/, use the existing NotFoundError class, and add one test for the
missing-invoice case. Reply with your plan first and wait for my "go".
```

## Recover a long thread that has lost track

Long threads degrade quietly. Codex compacts older history automatically when the conversation approaches its token limit (`model_auto_compact_token_limit` in `config.toml` tunes the threshold). A compacted summary can drop a decision you made an hour ago. The symptoms are repeated work, reopened decisions and ignored constraints.

1. **Check the numbers.** `/status` shows the current session configuration and token usage.

2. **Compact on your terms.** Run `/compact` at a natural break, such as after a feature passes its tests, rather than letting automatic compaction happen mid-task.

3. **Hand off to a fresh thread when compaction is not enough.** Ask Codex to write the state to a file (prompt below), run `/new`, and start the new thread from that file.

4. **Branch instead of overwriting.** To try an alternative without losing the current thread, use `/fork`, or `codex fork --last` from the shell. To come back to yesterday's session, run `codex resume --last`.

**Copy-paste prompt: hand off a long thread**

```text
Write docs/handoff.md for a fresh session that has none of this conversation. Include:
the goal in one sentence; decisions made and why; files changed; commands that prove
the current state (test, type check) with their last result; what is left, as a
numbered list; and any constraint I gave you that is not in AGENTS.md. Keep it under
60 lines. Do not change any other file.
```
After `/new`, start the fresh thread with: `Read docs/handoff.md and AGENTS.md, summarise what you understand in five bullets, and wait for my go before you continue.`

For patterns that keep threads short in the first place, see [context management across Codex surfaces](/en/codex/build/context-patterns/).

## Fix MCP, network and login failures

Connection failures stall a task without a clear error message, so check the plumbing before you blame the model.

**MCP server**

In the terminal:

```bash
codex mcp list            # every configured server
codex mcp get sentry      # one server's full definition
```

Inside a session, `/mcp verbose` shows which tools each server actually exposed. A slow server is often a timeout, not a crash. Raise its limits, or switch it off without deleting its config, in `~/.codex/config.toml`:

```toml
[mcp_servers.sentry]
startup_timeout_sec = 30
tool_timeout_sec = 120
# enabled = false         # switch the server off and keep working without it
```

For scripted runs, `required = true` makes `codex exec` exit with an error when that server fails to start, instead of carrying on without it. Setup details are in [set up MCP servers in Codex](/en/codex/quick-start/mcp-setup/).

**Login and install**

```bash
codex login status        # are you signed in, and how
codex doctor              # install, config, auth and runtime health
codex login               # sign in again
```

`codex doctor --json` prints a redacted report you can attach to a bug report. Sign-in methods and API-key use are covered in [authenticate Codex](/en/codex/quick-start/authentication/).

**Stalled model request**

If Codex stops producing output, press `Esc` to interrupt the turn and send a short follow-up, for example "continue from where you stopped". If it keeps stalling, run `codex doctor`, and check `/warnings` for retained diagnostic details before you restart the session.

## Break an error loop

The worst failure combines two others: Codex fixes an error, the fix causes a new one, and each round moves further from working code. More turns make it worse, because every failed attempt stays in the context.

1. **Stop the loop.** Press `Esc` in the CLI, or stop the task on the surface you are using.

2. **Go back to before the loop.** Restore the files to your checkpoint with Git, or `git stash` the attempt. Then run `/new` so that the failed attempts are no longer in the context.

3. **Find the first error.** Read the error that started the loop, not the latest one.

4. **Restart small and fenced.** Give Codex the original error, the approach that failed, the approach to take, and a file boundary (prompt below).

5. **Verify after each step.** Split the work into two or three tasks, and run the tests after each one before you start the next.

**Copy-paste prompt: break an error loop**

```text
A previous attempt at this failed in a loop. The original error was:
TypeError: Cannot read properties of undefined (reading 'userId') at src/auth/session.ts:42
The earlier fix added optional chaining everywhere and broke three tests. Do not do
that. Find where the session object is created without a user, fix it there, and
change only files under src/auth/. After the change, run the auth tests and paste
the summary. If they fail, stop and report instead of trying again.
```

## How do you prove the recovered change is right?

A recovered session feels finished before it is. Codex's summary ("all tests pass") is a claim, not evidence. Three checks prove the result without a line-by-line read:

1. **Scope.** Run `/diff` or `git diff --stat` and compare the file list with the plan. A file that is not in the plan is either a leftover from the failed attempt or new scope. Explain it or revert it.
2. **Gates.** Run the project's own test, type-check and lint commands yourself, in your terminal, and read the exit codes. Pay attention to tests that were deleted, skipped or weakened during the recovery.
3. **Independent review.** Run `/review` or `codex review --uncommitted` for a separate, read-only pass over the change, then triage its findings. [Review Codex's changes before you commit](/en/codex/quick-start/review-workflow/) walks through the loop.

You sign off, not Codex. Commit only when all three checks are clean, and keep the checkpoint commit until the change is merged.

## When Codex recovery itself goes wrong

**The rewind worked but the files still show the bad change.** Backtracking reverts the thread, not the working tree. Restore the files with Git, as shown in [Undo a wrong-direction change](#undo-a-wrong-direction-change).

**`Esc` twice does not open earlier prompts.** Codex cannot revert in the middle of a turn: interrupt the turn first, then try again. In a side conversation, editing previous prompts is unavailable. Return to the main thread.

**Codex keeps ignoring your correction.** An instruction given late in a long thread competes with everything before it. Start a new thread with `/new` and put every constraint in the first message, or add the constraint to `AGENTS.md` so every thread starts with it.

**There is no Git checkpoint.** If the repository has uncommitted work from before the task, do not run `git restore` on everything. Use `git restore -p` to discard only the hunks Codex wrote, and review each hunk as it appears.

**A Codex cloud task produced the wrong diff.** A cloud task runs in its own environment, so your checkout is unchanged until you apply its diff with `codex apply <task-id>` or merge its pull request. Do neither. Close the pull request, fix the prompt or the environment, and start a new task. [Codex cloud environments](/en/codex/automate/cloud-environments/) covers environment setup.

**The same failure happens in every session.** The fix belongs in configuration, not in another prompt: the command in `AGENTS.md`, the grant in `config.toml`, or the timeout on the MCP server.

## Where to go after the Codex quick start

This page closes the Codex quick start. You can install, sign in, configure, write `AGENTS.md`, connect MCP servers, run and review tasks, and recover when they fail.

- [Review Codex's changes before you commit](/en/codex/quick-start/review-workflow/) — The gates-plus-review loop that decides whether a change ships.
- [Debugging and bug hunting with Codex](/en/codex/test/bug-hunting/) — Reproduce, isolate and fix real bugs with a failing test first.
- [Isolated Codex tasks with Git worktrees](/en/codex/automate/worktrees/) — Run risky or parallel work where a wrong turn costs one directory.
- [Error recovery in Claude Code](/en/claude-code/quick-start/error-recovery/) — The same failure types in Claude Code, where checkpoints and /rewind restore files.
