Guides · Updated October 18, 2026
How to stop runaway Claude Code, Codex and Cursor agent loops
A coding agent that keeps retrying the same failing step can spend more in one unattended hour than in a normal day. Here is how to stop one that is running now, why “please stop after 3 tries” in a prompt is not a real limit, and how to put limits outside the model using the hook systems Claude Code, Codex CLI and Cursor all ship.
What a runaway loop looks like
- The retry loop. Run the tests, see the same failure, make the same edit (or none), run the tests again. The tool call is literally identical each time.
- The re-read loop. The agent keeps re-opening the same files or re-running the same search because it lost track of what it already knows.
- The cost spiral. No single call looks wrong, but every turn re-sends a large context, so spend climbs fast. Long sessions are the usual culprit: the context grows each turn and you pay for it again on every request.
On an API key each of those turns is billed. On a subscription (Claude Pro/Max, ChatGPT plans, Cursor plans) the same loop burns your 5-hour or weekly usage limit instead, which is how people end up locked out mid-week.
Stop it right now
- Claude Code / Codex CLI: press
Escto interrupt the current turn, orCtrl+Cto exit. - Cursor: click Stop in the agent panel.
Then look at what it was doing before you restart it. If the same command failed several times in a row, the agent usually needs new information (the real error, a missing file, a decision from you), not another attempt. Starting a fresh session with a short summary is often cheaper than continuing a huge one.
Why a prompt is not a limit
Instructions such as “stop after three attempts” or “don’t spend more than $5” live inside the model’s context. The model can forget them, reinterpret them, or never see them again after the conversation is compacted. It also has no idea what anything costs. A limit you can rely on has to be enforced by something that runs outside the model and can refuse to let it continue.
The enforcement point: agent hooks
All three agents can run a command of yours before every tool call, and that command can refuse the call:
| Agent | Config file | Block a tool call | End the session |
|---|---|---|---|
| Claude Code | ~/.claude/settings.json | PreToolUse hook returns permissionDecision: "deny" | Return {"continue": false} |
| Codex CLI | ~/.codex/hooks.json | PreToolUse hook exits with code 2, reason on stderr | Keep denying tool calls |
| Cursor | ~/.cursor/hooks.json | preToolUse hook returns {"permission": "deny"} | Keep denying tool calls |
The logic a loop guard needs is simple to describe: fingerprint each tool call (tool name + exact input), count identical fingerprints in a recent time window, and deny once the count passes a threshold. Counting alone also blocks the healthy cycle of run tests → fix → run tests, so a better guard only counts a repeat when nothing changed in between: the same files (for example a fingerprint of git status plus the changed files’ contents) and the same output from the last run. It should also treat cosmetic rewordings, like piping the same test command through tail, as the same call. For spend, read the agent’s own usage log, price the tokens, and deny once the session or the day passes a dollar cap. The hard parts are the details: three different log formats, de-duplicating streamed messages, staying fast enough to run on every tool call, and never breaking the agent when your hook itself has a bug.
Doing it with LoopGuard
LoopGuard is an open-source (MIT) CLI that does exactly the above for Claude Code, Codex CLI and Cursor at once. It reads the usage logs the agents already write (no proxy, no API keys, works on subscriptions) and installs itself as a hook in each agent.
npm i -g loopguard-cli # puts `loopguard` on your PATH (one-off: npx loopguard-cli <command>) loopguard init # detects ~/.claude, ~/.codex, ~/.cursor; backs up each config first loopguard status # today's spend vs caps, which agents are guarded, last 5 trips
Restart any running agent sessions so they pick up the hooks. The default rules (stored in ~/.loopguard/config.json):
| Rule | Default | What happens |
|---|---|---|
| Same tool call repeated with no progress | 5× within 10 min | The call is denied. A repeat only counts if the git working tree and the tool’s output didn’t change since the last identical call, and npm test, npm run test 2>&1 | tail -50 and bash -lc 'npm test' count as the same call. The message tells the agent to stop rerunning, write down what it knows, and find the root cause first. The 3rd denial in a row ends the session. |
| Cost spiral | $10 within 5 min | Denied and the session is halted. |
| Session cap | $25 | Denied and the session is halted. |
| Daily cap (all agents, local day) | $100 | Denied and the session is halted. |
| Warning | 80% of a cap | Claude Code shows a warning message. |
Tune them to how you work:
loopguard config set sessionCapUsd 10 loopguard config set dailyCapUsd 40 loopguard config set loop.maxRepeats 4 loopguard pause 15 # bypass enforcement for 15 minutes when you really mean it loopguard resume
When a rule trips, the agent sees a plain reason, for example LoopGuard: loop detected — the same Bash call ran 5x in 600s with no change to the files or to its output in between. This call was blocked. Don’t rerun it, and don’t rerun the same thing through a different command or wrapper. First write down what you know so far… Every trip is logged to ~/.loopguard/trips.jsonl. loopguard uninstall removes only LoopGuard’s hook entries; loopguard uninstall --restore puts the original config files back byte-for-byte.
Each agent also has its own built-in spend controls (monthly account limits, and for Claude Code a per-run cap in print mode). Tool-by-tool setup, native options first: Claude Code spending limit · limiting Cursor agent costs · capping Codex CLI spend.
For overnight and unattended runs
- Set a session cap you would be comfortable losing while asleep, and a daily cap below your real budget.
- Give long jobs one clear milestone and a test command that decides “done”, so the agent has a stop condition other than your patience.
- With the optional Pro dashboard, run
loopguard syncon a schedule (for example from cron every few minutes). Each sync uploads aggregate usage and new trips, sends trip alerts by email, Slack or Discord, and applies a pause you set from your phone.loopguard sync --dry-runprints exactly what would be sent; prompts and code never leave your machine.
Limits worth knowing
- Costs are estimates at API list prices, computed from local logs. They will not match a subscription bill, but they are a consistent measure of how hard a session is pushing your limits.
- Checks run when the agent calls a tool or finishes a turn. A single long model response is not cut off mid-stream; the limit applies at the next step.
- Codex CLI and Cursor have no documented “halt” field for this, so LoopGuard ends their sessions by repeatedly denying tool calls.
- Hooks only see the agent’s own tool calls. A script the agent wrote that calls a model API in a loop is outside their reach; use your provider’s spend limits for API keys too.
- LoopGuard fails open: if it hits an internal error, your agent keeps working and the error goes to
~/.loopguard/errors.log.
Related
- 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
- Codex stuck in a loop: how to stop it, undo it, and keep it from repeating