# How to Use Self-Referential AI Loops for Autonomous Iteration in Claude Code

> Master self-referential AI loops in Claude Code for autonomous iteration. Achieve verifiable completions without external scripts. Explore the Ralph Wiggum technique today.

- Repository: [Anthropic/claude-code](https://github.com/anthropics/claude-code)
- Tags: how-to-guide
- Published: 2026-04-02

---

**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-loop` command** — Defined in [`commands/ralph-loop.md`](https://github.com/anthropics/claude-code/blob/main/commands/ralph-loop.md), this parses the initial task description and creates the state file at [`.claude/ralph-loop.local.md`](https://github.com/anthropics/claude-code/blob/main/.claude/ralph-loop.local.md) before activating the loop.
- **Setup script** — Located at [`scripts/setup-ralph-loop.sh`](https://github.com/anthropics/claude-code/blob/main/scripts/setup-ralph-loop.sh), this validates command-line options including `--max-iterations` and `--completion-promise`, then writes the YAML front-matter containing `iteration`, `max_iterations`, and `completion_promise` fields.
- **Stop hook** — The [`hooks/stop-hook.sh`](https://github.com/anthropics/claude-code/blob/main/hooks/stop-hook.sh) script 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.md`](https://github.com/anthropics/claude-code/blob/main/.claude/ralph-loop.local.md) file 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:

1. **Initialization** — The user executes `/ralph-loop` with a task description and optional constraints.
2. **State Creation** — [`setup-ralph-loop.sh`](https://github.com/anthropics/claude-code/blob/main/setup-ralph-loop.sh) generates the state file with loop metadata and the immutable prompt.
3. **Execution** — Claude processes the prompt, writes code, runs tests, or performs other actions.
4. **Completion Check** — When Claude attempts to finish the turn, [`stop-hook.sh`](https://github.com/anthropics/claude-code/blob/main/stop-hook.sh) parses the state file to extract `iteration`, `max_iterations`, and `completion_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.
5. **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:

```bash
/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:

```bash
/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:

```bash
/cancel-ralph

```

This command removes [`.claude/ralph-loop.local.md`](https://github.com/anthropics/claude-code/blob/main/.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:

```bash
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:

```markdown
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-loop` command, [`setup-ralph-loop.sh`](https://github.com/anthropics/claude-code/blob/main/setup-ralph-loop.sh) script, [`stop-hook.sh`](https://github.com/anthropics/claude-code/blob/main/stop-hook.sh) intercept hook, and the [`.claude/ralph-loop.local.md`](https://github.com/anthropics/claude-code/blob/main/.claude/ralph-loop.local.md) state file.
- **Completion promises** via XML tags (`<promise>TEXT</promise>`) provide cryptographic verification that the task is truly finished.
- **Safety mechanisms** including `--max-iterations` and state file validation prevent infinite loops and data corruption.
- Use `/cancel-ralph` to 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`](https://github.com/anthropics/claude-code/blob/main/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`](https://github.com/anthropics/claude-code/blob/main/.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`](https://github.com/anthropics/claude-code/blob/main/plugins/ralph-wiggum/commands/ralph-loop.md) and [`plugins/ralph-wiggum/commands/cancel-ralph.md`](https://github.com/anthropics/claude-code/blob/main/plugins/ralph-wiggum/commands/cancel-ralph.md). The core loop logic is implemented in [`plugins/ralph-wiggum/scripts/setup-ralph-loop.sh`](https://github.com/anthropics/claude-code/blob/main/plugins/ralph-wiggum/scripts/setup-ralph-loop.sh) for initialization and [`plugins/ralph-wiggum/hooks/stop-hook.sh`](https://github.com/anthropics/claude-code/blob/main/plugins/ralph-wiggum/hooks/stop-hook.sh) for iteration management.