
You give the agent a clear task, it starts strong, then it circles the same broken test for forty minutes. The fix it applies breaks something else, so it reverts, then tries the same broken fix again. This is the most common way AI coding agents waste your time, and it is almost always fixable in under five minutes once you know what is happening inside the loop.
An AI coding agent is not thinking. It is predicting the next token based on everything in its context window. When that window fills with failed attempts, error logs, and contradictory edits, the model starts repeating what looked plausible before. The loop is a memory problem, not a stupidity problem.
Three things push an agent into a loop:
The fastest way out is to interrupt, shrink the context, and give the agent one concrete goal instead of a vague destination. A loop rarely means the model cannot solve the problem. It means the model cannot see the problem through the pile of failed attempts stacked on top of it.
Most agents let you stop mid-run. In Claude Code, press Escape or Ctrl-C to interrupt the current action. Then use /rewind to roll back to a checkpoint from before the loop started. This is the single highest-leverage move: it discards the corrupted context without discarding your whole session.
If you do not have a checkpoint you trust, /clear the conversation and re-open the file fresh. You lose the chat history, but you also lose the poisoned memory that was causing the loop. I reach for a full clear whenever an agent has made more than three failed attempts at the same block.
For Cursor users, the same principle applies. Stop the run, open the chat history, and delete the messages from the failed attempt onward. Starting from a clean slate beats arguing with a stuck model.
Once the loop is stopped, the context is still full of junk. Claude Code ships a /compact command that summarizes the conversation and drops the raw noise. The trick most people miss is the focus string.
Run /compact keep the auth flow and the failing test only instead of a plain /compact. You tell the model exactly what matters, so the summary keeps the signal and throws away the forty lines of retry output. A focused compact turns a 200,000-token mess into a 20,000-token summary that actually points at the bug.
This matters because the agent makes its next decision from the compacted summary. If that summary still says “tried X, failed”, it will try X again. Force the focus onto the observable failure, not the failed attempts. I keep a short note of the exact error message and paste it into the focus string, because the raw text beats any summary the model writes for itself.
A practical pattern: compact after every completed sub-task, not just when things break. Each clean summary trims the junk before it can accumulate. Agents that compact between steps stay on track far longer than agents that carry the whole session from line one.
If you run agents autonomously, a loop can burn budget while you are away. Claude Code supports lifecycle hooks that fire at specific points. The Stop hook runs when the agent tries to exit, and you can use it to enforce a cap.
Wire a Stop hook that emits {"continue": false, "stopReason": "iteration cap reached"} once the session passes your limit. The agent halts instead of spiraling. This is the difference between a $0.20 mistake and a $4.00 one that also corrupted three files.
For local setups, Cursor exposes model overrides in the config file. Setting a tighter contextWindow for the model forces smaller, more focused context per turn, which reduces the drift that causes loops. A narrower window means less room for the model to lose the thread.
When an agent is stuck on one feature, the rest of your codebase is contaminated context. Git worktrees let you spin up an isolated copy of the repo where the agent can experiment without dragging in unrelated files.
Create a worktree for the failing feature, point the agent at it, and let it loop in a sandbox. When it succeeds, merge the worktree back. When it fails, delete the worktree and your main branch is untouched. This is how you let an agent “think out loud” without paying for it to re-read your entire project on every turn.
Worktrees also make the failure reproducible. The agent works against one small, fixed surface instead of guessing which of 400 files caused the error.
A looping agent is usually responding to bad signals. Fix the signal:
node_modules or __pycache__ artifacts return old errors that no longer match the code. The agent debugs a ghost.The goal is to make the next token prediction easy. Clear input, clear success condition, small context. The agent is a mirror of the signals you feed it: give it noise and it returns noise in a loop; give it one clean failing test and it returns a fix.
When an agent loops, run this order instead of typing another prompt:
Nine times out of ten the second run solves it in two attempts. The first run poisoned its own context; the second run starts clean and stays clean.
Both tools loop, but they hand you different escape hatches. Pick based on how much control you want.
| Defense | Claude Code | Cursor |
|---|---|---|
| Manual rewind | /rewind to checkpoint | Delete chat messages |
| Context trim | /compact with focus string | New chat, paste summary |
| Hard cap | Stop hook emits iteration limit | ai.modelOverrides contextWindow |
| Isolation | Git worktrees | Branch + separate window |
| Best for | Autonomous long runs | Interactive short tasks |
Neither tool prevents loops on its own. The prevention lives in how you set the task, the context, and the exit condition before the agent starts.
/rewind and a focused /compact recover a stuck session faster than any prompt.Debugging an AI coding agent is less about coding and more about context hygiene. The model will happily repeat itself forever if you let it, because repetition looked right once. Your job is to break the repetition: rewind, compact, cap, isolate. Do those four things and the agent that looped for an hour yesterday writes clean code in one pass today.
Why does my agent keep reverting its own changes? It reverts because the test still fails after the edit, so the model concludes the edit was wrong and undoes it, then retries the same logic. Break the cycle by fixing the test signal, not the code, first.
Is a smaller context window always better? No. Too small and the agent loses the project structure it needs. The win comes from trimming failed attempts and noise, not from starving the model of real context. Keep the architecture, drop the retries.
Should I just switch models when it loops? Switching models resets the context, which is why it sometimes works, but it also loses your progress. Rewind and compact first; switch only if the same loop survives a clean context.
Do these fixes work for browser agents like Bolt or Lovable? The principles do. You may not have a Stop hook, but you can fork the project, work in a copy, and restart the chat with a focused summary pasted in. Isolation and context reset are tool-agnostic.
Start by adding a Stop hook to your next autonomous run. It is the one guardrail that protects you when you are not watching, and it costs nothing but a few lines of config.