How to Use Self-Referential AI Loops for Autonomous Iteration in Claude Code
Claude Code supports self-referential AI loops through the Ralph Wiggum technique, allowing the model to autonomously iterate on complex tasks until emitting a cryptographically verifiable completion tag, all without external scripts or cron jobs.
The anthropics/claude-code repository implements this capability as an internal plugin architecture where the model can reference its own prior outputs and Git history across multiple turns. This technique enables truly autonomous coding workflows where Claude continues refining code, fixing tests, or optimizing performance until a specific success condition is satisfied.
Understanding the Ralph Wiggum Loop Architecture
The self-referential loop relies on a stateful session mechanism that intercepts normal exit behavior and re-injects the original prompt. According to the source code in plugins/ralph-wiggum/, the architecture consists of four coordinated components that manage the iteration lifecycle.
Core Components
/ralph-loopcommand — Defined incommands/ralph-loop.md, this parses the initial task description and creates the state file at.claude/ralph-loop.local.mdbefore activating the loop.- Setup script — Located at
scripts/setup-ralph-loop.sh, this validates command-line options including--max-iterationsand--completion-promise, then writes the YAML front-matter containingiteration,max_iterations, andcompletion_promisefields. - Stop hook — The
hooks/stop-hook.shscript intercepts Claude's normal session exit. It extracts the last assistant output, checks for the<promise>tag, updates the iteration counter, and feeds the same prompt back as a new system message if completion is not detected. - State file — The
.claude/ralph-loop.local.mdfile stores the immutable prompt alongside mutable metadata. The stop hook reads and rewrites this file each cycle to persist iteration counts.
The Iteration Cycle
The autonomous loop follows a deterministic five-step process:
- Initialization — The user executes
/ralph-loopwith a task description and optional constraints. - State Creation —
setup-ralph-loop.shgenerates the state file with loop metadata and the immutable prompt. - Execution — Claude processes the prompt, writes code, runs tests, or performs other actions.
- Completion Check — When Claude attempts to finish the turn,
stop-hook.shparses the state file to extractiteration,max_iterations, andcompletion_promise. It scans the last assistant message for<promise>TEXT</promise>tags. If the extracted text matches the configured promise, the hook deletes the state file and permits exit. Otherwise, it increments the iteration counter, constructs a system message like🔄 Ralph iteration 2 | ..., and blocks the exit by re-injecting the original prompt. - Repetition — Steps 3-4 repeat until the promise is emitted or the iteration limit is reached.
Because the prompt never changes between iterations, Claude sees its own prior files, git commits, and test results on every turn, enabling genuine autonomous refinement without external orchestration.
Safety Mechanisms and Loop Control
The Ralph Wiggum implementation includes several safeguards to prevent infinite loops and false completions:
--max-iterations N— Caps the total number of iterations to avoid runaway computation.--completion-promise "TEXT"— Requires the model to output an exact<promise>TEXT</promise>XML tag, preventing early exit through vague status messages.- State validation — The stop hook validates numeric fields in the state file before arithmetic operations; corruption triggers an immediate abort with a clear warning message.
These mechanisms ensure that self-referential AI loops terminate predictably either through success verification or safety limits.
Practical Implementation Examples
Start a Loop with Completion Promise
Use the /ralph-loop command with explicit termination criteria to build a complete application:
/ralph-loop "Build a todo-list REST API (CRUD, validation, tests). Output <promise>DONE</promise> when all tests pass." \
--completion-promise "DONE" \
--max-iterations 30
The loop continues iterating, fixing failing tests and refining implementations, until the assistant outputs <promise>DONE</promise> or reaches 30 iterations.
Minimal Infinite Loop
For open-ended optimization tasks without safety limits:
/ralph-loop "Refactor the cache layer for better performance."
Warning: Omitting --max-iterations and --completion-promise causes the loop to run indefinitely until manual intervention.
Cancel an Active Loop
Terminate a running loop safely using:
/cancel-ralph
This command removes .claude/ralph-loop.local.md and prevents the stop-hook from feeding the prompt back on the next turn.
Inspect Current State
Monitor loop progress by reading the state file:
head -10 .claude/ralph-loop.local.md
This displays the current iteration count, maximum limit, and the original task prompt.
Proper Promise Format
The model must emit the completion tag exactly as configured:
All tests are now green!
<promise>DONE</promise>
The stop hook extracts text between <promise> tags and performs an exact string comparison against the completion_promise value stored in the state file.
Summary
- Self-referential AI loops in Claude Code use the Ralph Wiggum technique to enable autonomous iteration without external orchestration.
- The loop architecture comprises four components: the
/ralph-loopcommand,setup-ralph-loop.shscript,stop-hook.shintercept hook, and the.claude/ralph-loop.local.mdstate file. - Completion promises via XML tags (
<promise>TEXT</promise>) provide cryptographic verification that the task is truly finished. - Safety mechanisms including
--max-iterationsand state file validation prevent infinite loops and data corruption. - Use
/cancel-ralphto immediately terminate active loops and clean up state files.
Frequently Asked Questions
What is the Ralph Wiggum loop in Claude Code?
The Ralph Wiggum loop is a self-referential AI loop technique implemented in the anthropics/claude-code repository that allows Claude to automatically continue working on a task across multiple session turns. Named after the character's famous "I'm helping" quote, it works by intercepting session exits and re-injecting the original prompt until a specific completion tag is detected.
How does the stop hook prevent infinite iterations?
The hooks/stop-hook.sh script enforces two termination conditions: it checks if the current iteration exceeds the --max-iterations value, and it validates that the assistant's output contains the exact <promise> tag matching the configured completion promise. If either condition is met, the hook deletes the state file and permits the session to end normally.
Can I run multiple Ralph loops simultaneously?
No, the current implementation in plugins/ralph-wiggum/ uses a single state file path (.claude/ralph-loop.local.md) per workspace. Attempting to start a second loop will overwrite the existing state file. You must cancel the current loop with /cancel-ralph before initiating a new autonomous iteration on a different task.
Where are the Ralph loop commands defined?
The command definitions reside in plugins/ralph-wiggum/commands/ralph-loop.md and plugins/ralph-wiggum/commands/cancel-ralph.md. The core loop logic is implemented in plugins/ralph-wiggum/scripts/setup-ralph-loop.sh for initialization and plugins/ralph-wiggum/hooks/stop-hook.sh for iteration management.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →