AI coding agent stuck in a loop? How to break it
Three loops account for nearly all of them: the test oscillation, the context-loss rewrite, and the phantom error chase. Each needs a different intervention.
An AI coding agent stuck in a loop is burning money at a rate you can watch. The agent edits a file, runs the tests, sees a failure, edits the same file back, runs the tests, and forty minutes later you are three hundred thousand tokens poorer with an unchanged repository. The instinct is to nudge it: try again, that did not work, think harder. That instinct is wrong, and knowing which of three loops you are in tells you what to do instead.
Loop one: the test oscillation
The signature is A, B, A, B. The agent changes an implementation to satisfy a test, the change breaks a second test, it reverts, the first test breaks again. Every step is locally correct. The pair of constraints is unsatisfiable and nothing in the agent's loop is designed to notice that.
The exit: do not ask for another attempt. Ask for a diagnosis, with no edits permitted.
Stop editing. Do not change any files.
Name the two constraints you are alternating between, quote the exact
assertion in each failing test, and state in one sentence why they
cannot both hold. Then stop and wait.Forbidding edits is the active ingredient. An agent allowed to act will act, because acting is what resolves its uncertainty. Once it states the contradiction out loud, the answer is usually obvious to you in ten seconds: one of the tests encodes an assumption that changed, and a human needs to decide which.
Loop two: the context-loss rewrite
The signature is different. The agent is not oscillating, it is rebuilding. Work it completed thirty minutes ago gets redone slightly differently, then redone again. Function names drift. A helper it wrote and used appears a second time under another name.
This is the long-session failure. Early decisions have fallen out of the working context, so the agent re-derives them, and re-derivation is not deterministic. It is the same underlying problem as keeping an AI coding agent from losing context in a large codebase, showing up as repetition rather than confusion.
The exit: end the session. Do not try to rescue it.
Before you do, ask for a handover note in the repository itself, and keep it short enough to survive:
Write DECISIONS.md at the repo root, maximum 20 lines:
- what the task is, in one sentence
- what is already done, with file paths
- what is not done
- decisions already made that must not be revisited
Then stop.Start a fresh session, point the new agent at that file first, and the rewriting stops. A twenty-line state file in the repo is worth more than any amount of encouragement to a tired session, and it is the same instinct behind writing an AGENTS.md file for the project as a whole.
Loop three: the phantom error chase
The rarest and the most expensive. The agent is fixing something that is not broken. A stale build artifact, a cached dependency, a test that fails for an environmental reason, an error message from a previous run still on screen. The code is fine. The agent keeps producing increasingly baroque changes to make a symptom go away that has nothing to do with the source.
You can spot it by the shape of the edits: they get stranger. Special cases appear. Try-except blocks wrap things that should not need wrapping. A constant gets nudged to make a number match.
The exit: verify the failure yourself, once, in a clean state.
Stop the agent.
Delete build output and caches, reinstall dependencies, restart whatever daemon is involved.
Run the failing command yourself and read the actual output.
If it passes, revert every change the agent made since the loop started. All of them, with
or a hard reset to the last good commit.
That last step is not optional and people resist it, because some of those edits looked reasonable. They were written to satisfy a phantom, and they will fail in ways that make no sense in six weeks. This is precisely the case that rolling back a bad AI coding agent change exists for.
Telling them apart quickly
Symptom | Loop | First move |
|---|---|---|
Same two states alternating | Test oscillation | Ban edits, demand the contradiction |
Work redone under new names | Context loss | End session, write a state file, restart |
Edits getting weirder | Phantom error | Clean the environment, verify by hand, revert |
Agent narrates progress but the diff is empty | Any of the three | Read the diff, not the narration |
That last row deserves attention. An agent's description of what it did is generated text, not a record. When a session feels productive and the repository has not changed, believe the repository.
An AI coding agent stuck in a loop is preventable
Set a hard limit before starting: if the same file is edited more than five times in one session, stop and look.
Ask for the plan before the work, and read it. Most loops are visible in the plan as a step that cannot be verified, which is the argument for
reviewing an AI agent plan before it runs
.
Commit at every working state. A loop that starts from a clean commit costs you one revert. A loop that starts from four hours of uncommitted work costs you the afternoon.
Give tasks with a checkable finish condition. "Make the build pass" is checkable. "Improve error handling" is not, and an agent with no finish line will keep going.
None of this is unique to any one tool. It follows from what these systems are: an agent optimising against a signal will keep optimising, and the loop is what happens when the signal is unreachable. That is also most of why AI writes code that does not work in the first place, and the reason judgment about when to stop remains the part you supply, whichever of the today's AI coding tools you happen to run.
FAQ
Why does an AI coding agent repeat the same failed fix?
Because each attempt is evaluated on its own, against a signal it cannot satisfy. Nothing in the loop compares the current attempt with three attempts ago, so a contradiction between two constraints looks like a fresh problem every time.
Will a better model stop looping?
It loops less often and recovers faster, but the failure mode does not disappear. Unsatisfiable constraints and lost context are properties of the task and the session, not of the model.
Should I just let it keep trying?
Only if you have capped the spend and the work is not on your critical path. An oscillating agent left alone will run until it hits a limit, and the output at the end is rarely better than the output at minute five.
How do I stop an agent looping in an automated pipeline?
Cap iterations and fail loudly. A pipeline that retries indefinitely converts a visible failure into a large invoice, and nobody reads a log that scrolls.
How did this land?
About the author

Staff Engineer, Platform
Carlo works on the platform that turns prompts into running apps. He writes the engineering deep dives and the changelog notes worth reading.


