The scariest Claude Code sessions we've seen weren't the ones that failed. They were the ones that succeeded — after 45 minutes and $28 of tokens on a task that should have taken 3 minutes and $2. The agent didn't crash, didn't error, produced the right answer. It just took forever to get there, reading the same files over and over, trying variations of the same approach, going in circles that looked productive because each individual step was reasonable.
This is spiraling. It's the failure mode of agentic loops that don't get talked about enough because "agent produced correct answer" is technically success. But if you're paying 10x the cost and 15x the latency for that correct answer, you don't have a working system — you have an expensive lottery ticket that sometimes pays out.
Six months and many spirals later, we settled on a prompt structure that mostly prevents this. Not perfectly — no prompt fully prevents spiraling — but reliably enough that our production loops are now boring. This post is that structure.
Why loops spiral (root causes)
Before the fix, understand the failure. Four things drive spiraling; addressing each is what the prompt structure below does.
Cause 1: No termination condition beyond "task done"
If the only exit from the loop is the agent deciding the task is complete, the agent has infinite runway to try one more approach. When approaches keep partially working but not fully, the agent keeps iterating. Each iteration feels justified locally; the aggregate is a spiral.
Cause 2: Undefined "good enough"
Related but distinct. If the prompt doesn't specify what counts as complete, the agent optimizes for its own sense of quality — which is often "keep improving until stuck." A prompt like "review this PR" doesn't say when the review is done; the agent may keep finding smaller issues indefinitely.
Cause 3: No memory of what's been tried
In long loops, agents lose track of what they've already attempted. They'll try approach A, get partial progress, try B, come back to a variation of A, repeat. Without explicit tracking of attempted approaches, spirals are hard to avoid — the agent literally doesn't remember it tried this already.
Cause 4: Success metrics that can't be satisfied
Sometimes the prompt sets an impossible bar. "Write tests that get 100% coverage of this legacy module" for a module where 100% is impossible (unreachable code paths, mocked externals). The agent tries and fails and tries again, spiraling on an unachievable goal.
The three-part structure
Our loop prompts have three explicit parts. Missing any part is where spirals come from; including all three is what makes them stable.
### PART 1: OBJECTIVE + CONSTRAINTS
- What you're trying to accomplish
- What "done" looks like (specific, checkable)
- What you must NOT do
### PART 2: ITERATION BUDGET + PROGRESS TRACKING
- Maximum iterations allowed
- Track approaches attempted (log to a file)
- Stop conditions beyond "complete"
### PART 3: RECOVERY BEHAVIOR
- What to do if stuck
- When to escalate to human
- How to produce partial resultsEach part addresses a specific root cause. Objective + constraints (Part 1) prevents spirals from undefined "good enough." Iteration budget + tracking (Part 2) prevents infinite runway and repeated attempts. Recovery behavior (Part 3) prevents the "impossible goal" failure by giving the agent a graceful exit.
A concrete template
Here's the actual template we use for agentic loops, with the three parts filled in for a "fix flaky test" task:
# Task: Investigate and fix flaky test
## Part 1: Objective and constraints
**Objective:** Make the test at `tests/api/users_test.py::test_user_creation`
pass reliably 100 consecutive runs.
**Done means:**
- Test passes 100 consecutive runs on this branch
- No changes to unrelated test files
- No changes to production code without an explanation in the PR
**Must NOT:**
- Skip the test (that's the anti-fix)
- Increase timeouts as the primary fix (only if genuinely needed)
- Modify unrelated tests to make this pass
- Delete assertions to make it pass
## Part 2: Iteration budget and tracking
**Max iterations:** 8 attempts. If not passing 100/100 after 8, STOP and
report what you've tried and hypothesis about the actual cause.
**Track attempts:** Before each attempt, append to `.claude-flaky-log.md`:
- Attempt #
- Hypothesis for cause
- Change made
- Result (X/100 passing)
**Also stop if:**
- Same hypothesis appears twice (means you're going in circles)
- More than 4 files modified (out of scope)
- Root cause is clearly outside our code (external service, infrastructure)
## Part 3: Recovery behavior
**If stuck:**
- Produce a written analysis of what you've learned
- List candidate causes ranked by likelihood
- Suggest specific next steps a human should take
- Do NOT keep trying past the iteration budget
**Escalate to human when:**
- Root cause requires infrastructure change
- Fix would break more than 3 other tests
- You've identified a design issue that needs a decision
**Partial results are valid:**
- If you fixed a real bug but the flakiness has a second cause, ship the
first fix as its own PR and report the remaining issue.That's a lot of prompt text for a "fix a flaky test" task. It looks like overhead. In production, it's the difference between a 4-minute investigation ($1.50) and a 40-minute spiral ($15) that ultimately produces a wrong "fix."
The iteration log is the most important part
Of the three parts, the iteration log (in Part 2) is the highest-value single addition. It solves the "no memory of what's tried" problem directly.
Without the log, the agent has to remember its history through its context window — which gets diluted as the loop grows. With the log, the agent explicitly writes down what it tried, why, and the outcome. Before starting a new attempt, it reads the log. This makes "same hypothesis appears twice" a detectable condition instead of an invisible drift.
The log format matters less than that it exists. Ours is markdown because Claude reads it fluently. It could be JSON, structured text, whatever. What matters is the discipline: attempt-hypothesis-change-outcome per iteration. Cheap to maintain; enormously helpful.
In our prompts, we add: "Before starting each new attempt, read the log and verify: (1) you're not repeating a hypothesis, (2) you've made a genuinely different change from the last attempt, (3) the pattern of results suggests you're converging rather than circling." This turns the log from a passive record into an active check.
Setting iteration budgets
The max-iterations number in Part 2 is the fence around cost. It needs to be tuned to the task; too low and legitimate work gets truncated, too high and it doesn't prevent spirals.
Rules of thumb we use:
- Straightforward bug fixes: 5 iterations. Usually fixed in 2-3; extra headroom for tricky ones.
- Investigation tasks: 8 iterations. Root cause work takes more attempts.
- Refactors: 10 iterations. Multi-file changes need more back-and-forth.
- "Just try things" tasks: 6 iterations. Bounded exploration.
For any given task, if you find yourself wanting to raise the budget "just this once," that's a signal the task itself is scoped wrong — probably too broad. Split it or narrow it rather than raising the budget.
Termination conditions beyond "complete"
The stop-also-if conditions in Part 2 are the ones that actually catch spirals. "Complete" is the happy path; the also-stop conditions catch the pathological paths.
The one that catches the most spirals in our experience: "same hypothesis appears twice." When an agent forms hypothesis H, tries it, fails, tries something else, then comes back to a slight variation of H — that's the spiral pattern. Making it a stop condition forces the agent to explicitly acknowledge it's stuck and escalate rather than keep trying.
Other useful stop conditions:
- "More than N files modified" — task is exceeding its intended scope
- "Test still failing after M attempts" — bug is harder than expected
- "Root cause is outside our repo" — the agent has diagnosed but can't fix
- "Confidence in current approach dropped below 50%" — agent is guessing
Not every task needs all of these; pick the ones relevant to the failure modes you've seen for the task type.
Recovery behavior: the graceful exit
Part 3 is what turns "budget exceeded" from "agent gives up unhelpfully" into "agent produces useful output even in failure." Without recovery behavior specified, hitting the iteration budget usually produces a terse "unable to complete" — you've spent the budget and gotten nothing.
With recovery behavior specified, budget-exceeded produces a structured artifact: what was tried, what was learned, what the agent believes the actual issue is, what a human should try next. The budget wasn't wasted; it produced diagnostic information even though it didn't produce a fix.
The "partial results are valid" clause is subtle but important. Without it, agents often refuse to ship incremental progress — they either finish the whole task or fail entirely. With it, agents produce PRs that fix real bugs even if the full task isn't complete, deferring the residual issues to human decision.
Where this doesn't apply
The three-part structure is for agentic loops — tasks where the agent iterates through multiple attempts. For simple one-shot tasks (write this function, format this text, translate this string), the structure is overkill. The prompt just needs the task; no iteration budget needed because there's no iteration.
Rule of thumb: if the task involves more than 3 sequential steps of "try, observe, adjust," it's a loop and the structure helps. If it's "do the thing once," it's not a loop and this is unnecessary ceremony.
Measured impact
When we retrofitted this structure into our existing agentic loops (about 15 of them), the results per loop:
- Average cost per run dropped 55%. Spiraling was the main driver of high cost; capping it captured most of the savings.
- P95 latency dropped 70%. The tail of long runs (the actual spirals) got cut off.
- Task success rate roughly unchanged. The loops that were working continued to work; the ones that had been spiraling now either completed faster or produced structured "here's where I got stuck" reports.
- Human escalation rate went from ~5% to ~15%. This looks worse but is actually better: previously spirals silently produced bad output that humans caught later; now they explicitly escalate.
The escalation number is worth stopping on. When an agent explicitly says "I'm stuck, human help needed," that's a much better outcome than an agent producing a confident wrong answer that a reviewer has to catch. The 5%-to-15% shift is a shift from "silent failures" to "loud failures," which is what you want.
A loop that produces "I'm stuck, here's what I learned" is more valuable than one that produces "here's a confident wrong answer after 40 minutes."
The starting point for your loops
If you have agentic loops in production without this structure, retrofit incrementally. Start with the iteration budget — just add "max iterations: N" to existing prompts. That alone catches the worst spirals. Then add the iteration log. Then the stop-also-if conditions. Then recovery behavior. Each addition composes with the previous ones.
If you're building new loops, use the full structure from the start. It's cheap to add up front, expensive to retrofit after users have adapted to the current behavior. The prompt overhead pays for itself the first time a would-be spiral gets caught.
Get cctk running in one command
85 slash commands, 12 subagents, 12 MCP integrations, 12 hooks. All the patterns from this post are shipped in cctk.