The Ralph loop — automated iteration that doesn't drift
Ralph is the pattern. The name comes from "run-and-loop" in some communities; the idea is older than Claude Code but Claude Code is what made it practical.
Definition
A Ralph loop is a tight, repeating cycle:
1. Run Claude on a task.
2. Check whether the goal is achieved (mechanically — tests, screenshots, lint).
3. If not, adjust and run again.
4. Repeat until success or budget exhausted.
Step 2 is the key. Without a mechanical check, the loop drifts and quality degrades.
Why it works
- Each iteration is small and testable.
- The check enforces a quality floor.
- Claude's per-iteration cost is low (tokens), so you can afford many iterations.
- Long unattended runs become possible because the loop self-corrects.
Why it fails (when it does)
- Goal can't be checked mechanically. "Make it look professional" is not a Ralph goal. "Pass these 12 visual regression tests" is.
- Iteration drift. Claude makes changes that break things the previous iteration fixed. Mitigation: run all checks, not just the new one.
- Context bloat. Long Ralph sessions accumulate context. Use compaction or restart-with-context-snapshot.
- Cost runaway. No budget cap = no end. Always cap iterations or spend.
The four guardrails
- Mechanical goal. Test command exits 0; visual diff < threshold; lint clean.
- Iteration cap. Max N iterations.
- Cost cap. Max $ spend.
- Stop conditions. "Stop if same test fails twice in a row" → infinite-loop detector.
Concrete example: skeleton
#!/usr/bin/env bash
MAX_ITER=20
i=0
while [ \$i -lt \$MAX_ITER ]; do
i=\$((i+1))
echo "=== Iteration \$i ==="
if pnpm test --silent; then
echo "Tests green. Done."
exit 0
fi
claude -p "Tests are failing. Run \`pnpm test\` to see failures, then make the smallest possible change to fix the first failure. Don't refactor unrelated code." --output-format text
done
echo "Hit max iterations."
exit 1
That's a Ralph loop in 15 lines. We'll tune it next lesson.
What changes when you adopt Ralph
You stop thinking in "the AI either does it right or doesn't." You start thinking in "give the AI a verifiable goal and the patience to retry." This is the agentic engineering mindset shift.
Try it
Pick a small feature with existing tests. Write a Ralph loop in 20 lines of Bash. Run it, walk away for 10 minutes, come back. Note what worked and what drifted.