Guides · Updated October 28, 2026
Codex stuck in a loop: how to stop it, undo it, and keep it from repeating
Codex reruns the same failing command, reads the same error, makes a small edit that changes nothing, and runs it again. Each attempt re-sends the whole chat, so on a ChatGPT plan a loop eats your 5-hour or weekly window, and on an API key it eats dollars. This guide covers how to stop a looping Codex CLI session, undo what it did, restart without walking back into it, and make Codex refuse the next no-progress repeat on its own.
What a Codex loop looks like
- The same command, same failure.
npm testfails, Codex edits a line, the test fails the same way, and it runs again. - The same command in different clothes.
bash -lc 'npm test', thennpm run test 2>&1 | tail -50, thennpm test. Different text, same run. - Compaction without progress. The chat keeps showing “Context automatically compacted” while the task doesn’t move. After each compaction Codex has less of what it already tried, so it tries it again.
- Polling. Checking a server, a build or a background terminal over and over for a result that isn’t coming.
The common shape: nothing changes between attempts, so the next attempt can’t go differently. Run tests → fix → run tests is not a loop, and you don’t want to stop that.
Stop it now
Escinterrupts the current turn in the Codex CLI. The chat and the edits made so far stay.Ctrl+Calso interrupts a running task; on an idle prompt it closes the session (same as/exit).- Steer instead of stopping. Pressing
Enterwhile Codex is working adds your message to the current turn. “Stop rerunning the tests. Read the full error and explain the cause first” is often enough. - Background terminals keep running after you interrupt.
/pslists them with their recent output;/stopstops them all. - Long-running goals. If the loop is inside a
/goalrun,/goal pausestops Codex from picking it straight back up.
Source: OpenAI’s Codex CLI command reference and slash commands. Then read the last few tool calls before typing anything. If the same command produced the same error three times, the next attempt needs new information, not another run.
Undo what the loop changed
The Codex CLI has no file checkpoint to rewind to. Pressing Esc twice on an empty composer lets you edit your previous message and fork the chat from that point, but that rewinds the conversation, not your files. For files, use git:
/diffshows everything Codex changed, including untracked files, without leaving the session.git restore <file>(orgit stash) throws away a loop’s edits;git clean -nlists new files it created.- Commands with side effects (migrations, package installs, files written outside the repo) aren’t undone by git. Check what the loop actually ran.
That is the practical case for committing before a long debugging task, or starting it with codex --worktree so the loop happens in a separate checkout.
Restart without walking back into it
- Give it the missing fact. Paste the exact failing output and ask for the cause before any rerun: “Don’t run the tests again until you’ve changed the code and can say why the change fixes this failure.”
- Narrow the scope. “Only edit
src/auth/login.ts.” Edit ping-pong between two files stops when one of them is off limits. - Require approval for commands.
/permissions→ Read Only (or launch with--ask-for-approval on-request) makes every rerun wait for you while you work out what’s wrong. - Start a clean chat when the context is polluted. OpenAI’s own advice for repeated compaction without progress is to stop the task and start a new chat with a short summary of the goal and the work done. Ask for a five-line summary (goal, what was tried, the exact failing output, best hypothesis), then
/newand paste it in./forkkeeps the old chat if you want to compare.
Why “stop after 3 tries” in AGENTS.md doesn’t hold
An instruction in AGENTS.md is context, not a rule. The model can lose count, especially after compaction, and it can’t tell that npm run test | tail is the same run as npm test. A limit you can rely on runs outside the model, on every tool call, and can refuse it. Codex CLI has that: a PreToolUse hook runs before each tool call, and exiting with code 2 blocks the call and shows the reason on stderr to the model. PostToolUse hooks see each call’s result, which is how a guard can tell “same command, same output” from “same command, new output”.
Make Codex refuse the repeat: LoopGuard
LoopGuard is an open-source (MIT) CLI that installs those hooks. It needs no proxy and no API key, so it works on a ChatGPT plan as well as an API key. It has been tested against Codex CLI 0.163.
npm i -g loopguard-cli # puts `loopguard` on your PATH loopguard init --agent codex # adds PreToolUse, PostToolUse and Stop hooks (original config backed up) codex # then run /hooks and trust the three LoopGuard hooks loopguard status # caps, guarded agents, last 5 trips
Trust the hooks. Codex asks you to trust new hooks. Until you do, it skips them, and in codex exec it does so without saying anything. What LoopGuard does on a loop (version 0.1.3):
- It counts only repeats with no progress. The 5th identical tool call within 10 minutes is denied (
loop.maxRepeats5,loop.windowSec600), but only if nothing changed in between. LoopGuard fingerprints the git working tree on every tool call and hashes each tool’s output with timestamps, durations, temp paths and pids stripped. If a file changed or the output changed (3 failed→2 failed), the count starts over. - It sees through cosmetic rewording.
npm test,bash -lc 'npm test',npm run test 2>&1 | tail -50andtimeout 300 npm testcount as the same call. Different tools stay different. - The block message says what to do instead: stop rerunning it (including through a different command), write down the goal, what was tried, the exact failing output and the hypotheses, and find the root cause before running it again.
- How it stops Codex. Codex hooks have no field to end a session, so LoopGuard denies the call (exit code 2, reason on stderr) and keeps denying further repeats. It can block tool calls, not force-quit the session.
It also caps spend: LoopGuard reads the token counts Codex writes to ~/.codex/sessions/**/rollout-*.jsonl, prices them at API list prices, and denies tool calls past a per-session cap ($25 default), a daily cap across agents ($100), or an estimated $10 jump within 5 minutes. On a ChatGPT plan that dollar figure is an estimate of how heavy a session is, not your plan percentage (see Codex usage limits).
loopguard config set loop.maxRepeats 4 # stricter loopguard config set sessionCapUsd 10 # estimated $ per session loopguard pause 15 # bypass enforcement for 15 minutes loopguard report --agent codex --by session # what recent sessions would have cost at API prices
What it won’t catch
- Output that changes every run for reasons the normalizer doesn’t strip (random seeds, shuffled test order) reads as progress.
- Outside a git repo there is no file signal; repeats are judged on output alone.
- Scripts and aliases. A script that reruns the tests, or a different runner on the same tests, looks like a different call.
- Hooks you haven’t trusted, and Codex cloud tasks, which run remotely, outside the hooks in your local
~/.codex. - Checks run at each tool call, so a single long model response isn’t cut off mid-stream.
Related
- How to stop runaway Claude Code, Codex and Cursor agent loops
- How to track AI coding agent token costs per session
- How to set a spending limit for Claude Code
- How to limit Cursor agent usage costs
- How to cap OpenAI Codex CLI spend
- Claude Code usage limit reached: why it happens and how to monitor it
- How to set a hard budget for AI coding agents in CI
- Claude Code stuck in a loop: how to break it and stop it repeating the same command
- Codex usage limit reached: 5-hour and weekly limits explained
- Cursor agent stuck in a loop: how to stop it, roll back, and keep it from repeating
- Why Claude Code uses so many tokens, and how to use fewer
- How to set a budget limit for Aider
- GitHub Copilot agent mode stuck in a loop: how to stop it and keep it from repeating
- Cline stuck in a loop: how to stop it, roll back, and cap what it spends
- Gemini CLI usage limits: daily quotas, the June 2026 change, and keeping costs in check