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

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

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:

AgentConfig fileBlock a tool callEnd the session
Claude Code~/.claude/settings.jsonPreToolUse hook returns permissionDecision: "deny"Return {"continue": false}
Codex CLI~/.codex/hooks.jsonPreToolUse hook exits with code 2, reason on stderrKeep denying tool calls
Cursor~/.cursor/hooks.jsonpreToolUse 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):

RuleDefaultWhat happens
Same tool call repeated with no progress5× within 10 minThe 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 minDenied and the session is halted.
Session cap$25Denied and the session is halted.
Daily cap (all agents, local day)$100Denied and the session is halted.
Warning80% of a capClaude 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

Limits worth knowing

Related

LoopGuard on GitHub · Pricing