The autonomous loop pattern (popularized as “Ralph Wiggum” in the community) lets Claude work independently in a cycle: build, test, fix, repeat.
The Basic Loop
#!/bin/bash
# autonomous-loop.sh
MAX_ITERATIONS=10
PROMPT="$1"
for i in $(seq 1 $MAX_ITERATIONS); do
echo "=== Iteration $i/$MAX_ITERATIONS ==="
claude -p "$PROMPT" --allowedTools "Read,Write,Edit,Bash" 2>&1
# Circuit breaker: stop if tests pass
if npm test 2>&1 | tail -1 | grep -q "passed"; then
echo "All tests passing. Done."
exit 0
fi
done
echo "Hit max iterations without success."
exit 1
Usage
chmod +x autonomous-loop.sh
./autonomous-loop.sh "Implement the user settings API endpoint. \
Write tests first, then implement until all tests pass. \
Run npm test after each change."
Circuit Breakers
Always include a way to stop the loop:
- Test passing: stop when the test suite is green
- Max iterations: hard cap to prevent runaway costs
- Error threshold: stop after 3 consecutive failures
- Cost cap: check token usage between iterations
Headless Mode Version
claude -p "$PROMPT" \
--allowedTools "Read,Write,Edit,Bash(npm test*)" \
--max-turns 20
The --max-turns flag acts as a built-in circuit breaker for headless mode.
When to Use
- Implementing a feature with a clear test suite
- Fixing a batch of linter errors
- Migrating code to a new pattern across many files
When NOT to Use
- Tasks without clear success criteria (no tests, no linter)
- Architectural decisions that need human judgment
- Anything touching production infrastructure