DEV Community

Zac
Zac

Posted on

How I debug Claude Code when it goes in circles

How I debug Claude Code when it goes in circles

There's a specific failure mode in long Claude Code sessions where the agent starts looping. It fixes something, breaks something adjacent, fixes that, breaks the original. The commit history looks like a sine wave.

Here's what I do when I notice it happening.

Step 1: Stop the session immediately

Don't let it keep going. Each additional fix makes the problem harder to understand. Kill the session, read the diff from the last known-good state.

git diff HEAD~3 --stat
git stash
Enter fullscreen mode Exit fullscreen mode

The --stat shows which files got touched how many times. Anything with 3+ modifications in 3 commits is the problem area.

Step 2: Reproduce the original issue from scratch

Not "describe the issue" — actually reproduce it. Run the failing test. See the error with fresh eyes.

Half the time, what the agent was "fixing" wasn't actually broken. It was working on a phantom problem introduced by one of its earlier edits.

Step 3: Start a new session with a narrow prompt

Old session: "Fix the authentication bug."

New session: "This specific test is failing: [paste test]. This is the error: [paste error]. The relevant code is auth.ts lines 45-80. Fix only this."

Narrowing the scope stops the agent from touching adjacent code. The looping pattern almost always comes from an overly broad prompt.

Step 4: Ask for the root cause before the fix

"Before writing any code, explain why this test is failing. What is the root cause?"

If the explanation is vague or wrong, the fix will be too. Get the diagnosis right first. This one change eliminates most looping behavior.

Step 5: One failing test at a time

If you have 5 failing tests, don't ask the agent to fix all 5. Pick the most fundamental one. Fix it. Verify. Move to the next.

The looping pattern almost always starts with "fix all these failing tests at once."


What the loop actually is

When an agent loops, it's usually because:

  1. The problem is ill-defined
  2. There are multiple entangled issues being treated as one
  3. The agent is making wrong assumptions about system state
  4. A previous fix introduced a new bug that looks like the original

All fixable with more precise prompts and narrower scope.


From running Claude Code autonomously on builtbyzac.com.

Top comments (0)