Claude Code & Context Engineering

Debugging Agent Loops: How to Recognise and Break Repeated Edits, Tool Thrash and Runaway Retries

25 November 2026 · Updated 28 November 2026 · 11 min read · by Yang Kai

Your agent is not stuck, it is looping — and loops have signatures. Learn the four loop patterns, what causes each one, and the intervention that actually breaks it.

Checklist inside: Loop-diagnosis checklist

Contents
  1. Signature 1: the edit pendulum
  2. Signature 2: tool thrash
  3. Signature 3: runaway retries
  4. Signature 4: the verification mirage
  5. Signature 5: the hook that won't let go
  6. Loop-diagnosis checklist
  7. Loop diagnosis — run when a session feels circular
  8. Restarting is a tool, not a defeat
  9. How we researched this
  10. Over to you

Every agent user knows the feeling: you glance back at a session and the agent is doing something — files changing, tests running, messages streaming — yet the task is no closer to done than it was ten minutes ago. It is not stuck. Stuck would be mercifully quiet. It is looping: repeating a pattern of actions that feels like progress from the inside and is recognisably circular from the outside.

Loops are worth treating as a debugging discipline of their own, separate from debugging the code the agent is working on. For the code side, the systematic-debugging skill enforces a proper root-cause process. This article is about the agent’s behaviour itself: five loop signatures, the cause underneath each, and the specific intervention that breaks it — because “try harder” is not an intervention, and neither is letting it run.

The hook and compaction mechanics are checked against Anthropic’s Claude Code documentation, November 2026. The signatures are the pattern language; the checklist at the end is the artefact to keep open during a bad session.

The short version:

Signature The tell First intervention
Edit pendulum Same file, diff oscillating between two states Name the two conflicting requirements; pick a winner
Tool thrash Searches and reads that never converge on an edit Supply the missing fact, or bound the search
Runaway retries Same failure, cosmetic variations Demand a hypothesis and a diagnostic before any retry
Verification mirage “Done” declared, check fails, repeat Rewrite “done” as commands before work starts
Hook that won’t let go Agent blocked from stopping, round after round Check stop_hook_active; make the condition achievable

Signature 1: the edit pendulum

The agent changes a file, runs the tests, changes the same file back, runs the tests again. The diff oscillates between two states, each fixing the failure the other causes. In the transcript it looks diligent — every step responds to a real failure — but git diff --stat tells the truth: the net change churns instead of growing.

Root cause: two constraints in genuine tension. Often two tests encoding contradictory expectations, or a fix that satisfies the type checker and breaks runtime behaviour. The agent treats each failure as new information when it is actually the same information wearing the other hat.

Break it by naming the tension. Stop the session and ask: “State the two requirements that conflict, and which one should win.” If you cannot answer either, the conflict is in your spec, not the agent’s competence — no amount of iteration resolves a contradiction, it only rehearses it.

Once decided, write the decision down where it persists. A one-line ruling in the project file stops next week’s session from re-opening the same argument, which is the habit the CLAUDE.md that actually works is built around.

Signature 2: tool thrash

The agent cycles through tools — search, read, search again, a different search, re-reading a file it read four calls ago — without the reads converging into an edit. Ten minutes of activity, zero lines changed.

Root cause is usually a missing fact the agent cannot locate: a function defined somewhere unexpected, a convention that exists nowhere in the repo. Thrash is the agent telling you its map of the codebase has a hole in it.

Break it by supplying the missing fact or shrinking the territory. Point at the file. State the convention. Or, if you do not know either, say so and make finding out the explicit task, with a stopping rule: “Spend at most five searches locating X; if it is not found, report what you ruled out.”

Delegated exploration with a bounded brief is exactly the pattern in writing subagent briefs that get used. It has a second benefit: the thrash burns a subagent’s separate context window, and only the findings return to yours. An unbounded “go look around” in the main session is an invitation to thrash — and to pay for the debris all session.

Signature 3: runaway retries

A command fails; the agent retries it nearly unchanged; it fails identically; the agent retries again with a cosmetic variation. Root cause: the agent has no model of why it failed, so it treats failure as weather — wait and try again.

The identical error text is the tell. The same error twice is not two pieces of evidence; it is one piece of evidence seen twice. Very often the cause is environmental rather than in the code at all — a service that is not running, an environment variable that is not set, a file that does not exist where the config says it should — and no edit to the source will fix it.

This is the loop most likely to burn budget, and the one most amenable to a hard rule: after two identical failures, the third attempt must be preceded by a stated hypothesis about the cause and a diagnostic step that tests it. Put that rule where it persists — in your project’s CLAUDE.md — rather than re-typing it into sessions.

Break it live by asking one question: “What do you believe caused that failure, and what observation would prove you wrong?” An agent that cannot answer does not need another retry; it needs to read the error properly, check the environment, or ask you.

Signature 4: the verification mirage

The agent declares the task nearly done, runs a check, the check fails, it fixes something adjacent, declares done again — a loop around its own completion criteria. Each cycle looks like progress because each fix is real; the loop is in the target, not the work.

Root cause: the definition of done was never mechanical. “Make it work” gives the agent a vibe to aim at; each check invents a new interpretation.

Break it by writing the done criteria as commands before work starts: these tests pass, this build is green, this route returns 200. When the criteria are commands, “done” is a fact the agent can verify in one pass instead of a judgement it re-litigates.

This is also the loop a badly written Stop hook manufactures all by itself — a hook that blocks stopping until some prose condition “looks right” will argue with the agent forever. The hooks deep dive insists blocking conditions be mechanically checkable, for exactly this reason.

Signature 5: the hook that won’t let go

The fifth loop is not the agent’s fault at all. A Stop hook that blocks on a condition the agent cannot meet — tests that need a database that is not running, a file the agent has no permission to write — will block every stop attempt: the agent tries, fails, tries to stop, gets blocked, and tries again.

The mechanics matter here. A Stop hook blocks by exiting with code 2, and its stderr becomes the agent’s next instruction. The hook’s input carries a stop_hook_active field that is true when the agent is already continuing because a Stop hook blocked — that flag exists precisely so a hook can ask once and then let go. Claude Code also has a backstop: after eight consecutive blocks it overrides the hook and ends the turn, and CLAUDE_CODE_STOP_HOOK_BLOCK_CAP changes that number. Eight rounds of nagging is still eight rounds of tokens, though.

Break it in the hook, not the session:

The platform guards against its own version of this failure: when a huge file or tool output refills the context window immediately after every compaction summary, Claude Code stops auto-compacting after a few attempts and shows an error instead of looping. Tooling that can force continuation needs the same discipline, whichever side of the hook it sits on. The full event reference is in Claude Code hooks by event.

Loop-diagnosis checklist

## Loop diagnosis — run when a session feels circular
1. NAME THE SIGNATURE
   [ ] Edit pendulum (same file, oscillating diff)
   [ ] Tool thrash (searches/reads not converging on an edit)
   [ ] Runaway retries (same failure, cosmetic variations)
   [ ] Verification mirage (done declared, check fails, repeat)
   [ ] Hook loop (Stop hook blocking on an unmet condition)
2. CHECK THE CLOCK AND THE DIFF
   [ ] `git diff --stat` — is net change growing or churning?
   [ ] Same error text twice? Copy it exactly; do not paraphrase.
3. INTERVENE BY SIGNATURE
   [ ] Pendulum → state the two conflicting requirements; pick a winner
   [ ] Thrash   → supply the missing fact, or bound the search (5 calls max)
   [ ] Retries  → demand a hypothesis + a diagnostic before any retry
   [ ] Mirage   → rewrite "done" as commands; rerun from a clean state
   [ ] Hook     → check stop_hook_active handling; make the condition achievable
4. DECIDE: CONTINUE OR RESTART
   [ ] Continue if the intervention produced NEW information
   [ ] Restart the session if context is polluted with failed attempts —
       brief the fresh session with the failure summary, not the transcript
5. PREVENT THE SEQUEL
   [ ] Missing fact → add it to CLAUDE.md or a memory file
   [ ] Recurring loop → add the two-failure rule / done criteria to the project file

Restarting is a tool, not a defeat

The hardest judgement is when to kill a looping session. Long sessions accumulate the debris of every failed attempt, and the agent keeps tripping over its own earlier reasoning — a context problem as much as a behaviour problem. The discipline in managing context across long projects applies inside a single bad afternoon too: summarise what is known, what failed and why, and hand that — not the transcript — to a fresh session.

A restart with a good brief routinely finishes in minutes a task that an hour of looping could not. The cost of restarting is one short summary; the cost of not restarting is the rest of the session’s budget spent re-reading failed attempts — the rent problem the context budget audit prices for standing files applies to transcripts too.

Watch for loops the way you watch for compiler warnings: not as proof the agent is bad at its job, but as the earliest, cheapest signal that a fact, a constraint, or a definition is missing. Supply the missing piece, and the circle straightens into a line.

How we researched this

Desk research, checked November 2026. The Stop hook behaviour — exit code 2 blocking, the stop_hook_active flag, the eight-block override and its CLAUDE_CODE_STOP_HOOK_BLOCK_CAP setting — and the auto-compaction refill guard come from Anthropic’s Claude Code documentation and hooks reference. The four behavioural signatures and the checklist are this site’s own framework; no session results are claimed for them.

Over to you

The one principle: a loop is a missing piece of information wearing a disguise. A fact the agent cannot find, a constraint nobody stated, a definition of done that was never made mechanical, a hook condition that cannot be met. Diagnose the signature first, supply the missing piece, and only then let the agent run.

If loops keep recurring on the same project, the missing pieces usually belong in files, not in your patience — the context budget audit shows how to decide what earns a permanent place.

Learn more:

FAQ

Why does my coding agent keep making the same edit back and forth? Usually two constraints genuinely conflict — often two tests encoding opposite expectations. Name both requirements, decide which wins, and give the agent the decision; iteration alone cannot resolve a contradiction.

How do I tell a loop from slow, honest progress? Watch the diff and the error text. Progress produces new information: a growing net change, a different failure than last time. A loop produces the same error, or a diff that returns to a state it already visited.

When should I restart a looping agent session instead of intervening? When the intervention produces no new information, or the session’s context is polluted with failed attempts. Restart with a short brief — what is known, what failed and why — not with the full transcript.

What is the best rule to prevent runaway retries? A two-failure rule in your project file: after two identical failures, the agent must state a hypothesis about the cause and run a diagnostic before any further attempt.

Can a Stop hook cause a loop? Yes — it is the most mechanical loop of all. If the hook blocks on a condition the agent cannot meet, it blocks every stop. Check the stop_hook_active field and exit 0 when it is true; Claude Code overrides the hook after eight consecutive blocks, but the hook should never need the backstop.

Category: Claude Code & Context Engineering · Tags: #claude-code #testing #ai-agents #tutorial

Next step: this article is part of Claude Code guides, which covers the full topic from first setup to advanced use.

Related guides