Guides · Updated October 23, 2026
Claude Code stuck in a loop: how to break it and stop it repeating the same command
Claude Code runs the same failing command again, gets the same error, and runs it again. Or it flips a file back and forth between two versions. Every one of those turns re-sends the whole conversation, so a loop costs more the longer it goes. This guide covers how to stop one right now, how to undo what it did, how to restart without walking back into it, and how to make Claude Code refuse the next repeat on its own.
What the loop usually looks like
- The same failing command, unchanged. A bug report on the Claude Code repo shows Claude running
ssh … "make run-runner" 2>&1seven times in a row, each time gettingmake: *** No rule to make target, until the user interrupted. - The same command, reworded.
npm test, thennpm run test 2>&1 | tail -50, thenbash -lc 'npm test'. Different text, same run, same failure. - Edit ping-pong. Two edits that undo each other, or the same line rewritten each turn while the test keeps failing.
- Re-reading. Opening the same files and running the same searches because the useful context was compacted away.
The common shape: nothing changes between attempts, so the next attempt can’t go differently. A healthy fix-and-rerun cycle (run the test, edit the code, run the test) is not a loop, and you don’t want to stop that.
Stop it now
From Claude Code’s interactive mode reference:
Escstops the current response or tool call mid-turn so you can redirect it. Claude keeps the work done so far.Ctrl+Cinterrupts a running operation (useful for a hung command). With nothing running, a first press clears the input and a second press exits.- Background commands keep going until they finish or you stop them. Open
/tasksto stop one; Claude Code also cleans up background tasks when it exits.
Then, before typing anything, read the last few tool calls. If the same command produced the same error three times, the next attempt needs new information (the real error, a file it hasn’t read, a decision from you), not another run.
Undo what the loop changed
Press Esc twice with an empty prompt, or run /rewind, to open the rewind menu (checkpointing docs). Pick the prompt from before the loop started, then restore code, conversation, or both. Two limits:
- Files changed only by Bash commands aren’t tracked. If the loop ran a script or a migration that wrote files Claude never edited with its edit tools, rewind won’t revert them. Use git.
- Most subagent edits aren’t captured in your session’s checkpoints either. Again, git is the reliable undo.
That is the practical argument for committing (or at least git stash-ing) before you hand Claude a long debugging task.
Restart without walking back into it
- Give it the missing fact. “The last command exited non-zero with this error: … Read it and tell me the cause before running anything.” Paste the exact output; don’t paraphrase it.
- Forbid the rerun explicitly. “Don’t run the tests again until you’ve changed the code and can explain why the change fixes this failure.”
- Narrow the scope. “Only edit
src/auth/login.ts.” Ping-pong between two files stops when one of them is off limits. - Start clean when the context is polluted. In the rewind menu, Summarize from here compresses the loop into a summary and keeps your earlier instructions. If the whole session is noise, ask Claude for a five-line summary (goal, what was tried, the exact failing output, best hypothesis), then
/clearand paste it into a fresh session.
One more trap: if the session hits your plan’s usage limit mid-loop, Claude Code can wait and continue the interrupted task on its own after the reset (see Claude Code usage limits). A looping session will pick the loop back up and spend the next window the same way, so check what it was doing before you let it continue.
Why “stop after 3 tries” in CLAUDE.md doesn’t hold
An instruction in CLAUDE.md or the prompt is context, not a rule. The model can miss that it is on try number four, especially after compaction, and it can’t see that npm run test | tail is the same run as npm test. A limit you can rely on has to run outside the model, on every tool call, and be able to refuse it. In Claude Code that is a PreToolUse hook: it runs before each tool call and can return permissionDecision: "deny" with a reason Claude reads, or {"continue": false} to end the session. PostToolUse and PostToolUseFailure hooks see each call’s result, which is how a guard can tell “same command, same output” from “same command, new output”.
Make Claude Code 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 Pro and Max as well as API billing.
npm i -g loopguard-cli # puts `loopguard` on your PATH
loopguard init --agent claude # adds PreToolUse, PostToolUse, PostToolUseFailure and Stop hooks
# to ~/.claude/settings.json (original backed up first)
loopguard status # caps, guarded agents, last 5 tripsRestart running Claude Code sessions so they load the hooks. What it does on a loop (version 0.1.3):
- It counts only repeats with no progress. The same tool call 5 times within 10 minutes is denied (
loop.maxRepeats5,loop.windowSec600), but only if nothing changed in between. Withloop.progressAwareon (the default), LoopGuard fingerprints the git working tree on every tool call (git statusplus a hash of each changed file) and hashes each tool’s output with timestamps, durations, temp paths and pids stripped. If you or Claude edited a file, or the output changed (3 failed→2 failed), the count starts over. So run tests → fix → run tests keeps working. - It sees through cosmetic rewording. With
loop.normalizeShellon (the default),npm test,npm run test 2>&1 | tail -50,bash -lc 'npm test',cd <current dir> && npm testandtimeout 300 npm testcount as the same call. Different tools stay different:npx jestandnpm testare not merged. - The block message says what to do instead. Claude is told the call was blocked, not to rerun it through a different command, to write down the goal, what it tried, the exact failing output and its hypotheses (in its reply or in
.loopguard/checkpoint.md), and to find the root cause before running it again. The point is to turn a blind retry into a diagnosis. - The 3rd loop block in a row ends the session, with a message asking Claude to hand what it knows back to you.
It also caps spend: an estimated $10 jump within 5 minutes ends the session (loop.spiralUsd), and there are per-session and daily caps ($25 and $100 by default), priced at API list prices from the transcripts Claude Code writes, subagents included.
loopguard config set loop.maxRepeats 4 # stricter loopguard config set loop.progressAware false # count every identical call, progress or not loopguard pause 15 # bypass enforcement for 15 minutes tail ~/.loopguard/trips.jsonl # every block, with the reason
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, so that loop isn’t caught. A polling command whose output never changes is.
- Outside a git repo there is no file signal, and repeats are counted on the output signal alone.
- Scripts and aliases. Normalization doesn’t look inside a script, or notice a different test runner invoked on the same tests.
- Work outside Claude’s tool calls. A background process or a script the agent wrote that loops on its own runs outside the hooks. Stop those from
/tasksand keep live API keys away from unattended sessions. - Checks run at each tool call, so a single long 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
- 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
- Codex stuck in a loop: how to stop it, undo it, and keep it from repeating