Recover from Codex errors and wrong turns
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 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
Section titled “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?
Section titled “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 |
| 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 |
| 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 |
| 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 |
| 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 |
Set a Git checkpoint before a risky task
Section titled “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:
git status # start from a clean tree, or know what is already dirtygit 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.
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.
Fix sandbox and approval blocks in Codex
Section titled “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:
In the terminal, add a writable directory for this session only:
codex --add-dir ../shared-fixturesThe rest of the sandbox stays as it was, and nothing persists to the next session.
If every task in a project needs the network (a package registry, for example), grant only network access in ~/.codex/config.toml:
sandbox_mode = "workspace-write"
[sandbox_workspace_write]network_access = trueOpenAI 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 covers both.
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.
Recover from a failed command
Section titled “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.
-
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.
-
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.
-
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.
-
Write the fact down. Add the correct build, test and lint commands to
AGENTS.mdso the next session starts with them. Keep them near the top: Codex reads at mostproject_doc_max_bytesof project instructions (32 KiB by default in 0.157.1). Write AGENTS.md for Codex shows the layout.
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.
Undo a wrong-direction change
Section titled “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:
If the edits so far are mostly usable, correct the course and let Codex clean up:
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 routehandler pattern, and list every file you changed.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.
In the terminal, choose the granularity:
git diff --stat # what changed since the checkpointgit restore -p src/ # discard chosen hunks interactivelygit restore src/routes/ src/server.ts # discard whole filesgit stash push -u -m "codex: express attempt" # set the whole attempt aside, recoverablyPrefer 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.
Recover a long thread that has lost track
Section titled “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.
-
Check the numbers.
/statusshows the current session configuration and token usage. -
Compact on your terms. Run
/compactat a natural break, such as after a feature passes its tests, rather than letting automatic compaction happen mid-task. -
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. -
Branch instead of overwriting. To try an alternative without losing the current thread, use
/fork, orcodex fork --lastfrom the shell. To come back to yesterday’s session, runcodex resume --last.
For patterns that keep threads short in the first place, see context management across Codex surfaces.
Fix MCP, network and login failures
Section titled “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.
In the terminal:
codex mcp list # every configured servercodex mcp get sentry # one server's full definitionInside 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:
[mcp_servers.sentry]startup_timeout_sec = 30tool_timeout_sec = 120# enabled = false # switch the server off and keep working without itFor 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.
codex login status # are you signed in, and howcodex doctor # install, config, auth and runtime healthcodex login # sign in againcodex 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.
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
Section titled “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.
-
Stop the loop. Press
Escin the CLI, or stop the task on the surface you are using. -
Go back to before the loop. Restore the files to your checkpoint with Git, or
git stashthe attempt. Then run/newso that the failed attempts are no longer in the context. -
Find the first error. Read the error that started the loop, not the latest one.
-
Restart small and fenced. Give Codex the original error, the approach that failed, the approach to take, and a file boundary (prompt below).
-
Verify after each step. Split the work into two or three tasks, and run the tests after each one before you start the next.
How do you prove the recovered change is right?
Section titled “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:
- Scope. Run
/difforgit diff --statand 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. - 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.
- Independent review. Run
/revieworcodex review --uncommittedfor a separate, read-only pass over the change, then triage its findings. Review Codex’s changes before you commit 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
Section titled “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.
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 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
Section titled “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.