# Ralph Loop Guide

## What is a Ralph Loop?

A Ralph Loop is an autonomous AI development pattern where a language model is invoked repeatedly in a loop, performing exactly one task per iteration. Each iteration is a **fresh context** — the model has no memory of previous runs. Persistence is achieved through files: the model reads project state from disk at the start of each iteration and writes its results back before stopping.

The name originates from [Geoffrey Huntley's technique](https://ghuntley.com/loop/) for autonomous coding with Claude Code. The core insight: by constraining each iteration to a single task and using files as shared memory, you get reliable, incremental progress without context window exhaustion.

Sources and further reading:

- [Geoffrey Huntley — Everything is a Ralph Loop](https://ghuntley.com/loop/)
- [snarktank/ralph — Original implementation](https://github.com/snarktank/ralph)
- [frankbria/ralph-claude-code — Claude Code adaptation](https://github.com/frankbria/ralph-claude-code)

## How Ralph Works in This Project

### Directory Structure

Each Ralph run lives in its own directory under `.ralph/`:

```
.ralph/
└── my-run/
    ├── instructions.md    # Agent prompt (user-created, required)
    ├── meta.md            # Run metadata (auto-generated)
    ├── chief-wiggum.md    # Chief Wiggum directives (auto-generated template)
    ├── answers.md         # Human answers to questions (auto-generated template)
    ├── questions.md       # Questions raised by Ralph (auto-generated template)
    ├── progress.txt       # Iteration log (auto-generated template)
    └── run.log            # Execution log (auto-generated)
```

### The Iteration Cycle

```
┌─────────────────────────────────┐
│  ralph.sh starts iteration N    │
│                                 │
│  1. Read project state          │
│     (files listed in            │
│      instructions.md)           │
│                                 │
│  2. Select ONE task             │
│     (by priority order)         │
│                                 │
│  3. Execute that task           │
│     (edit files as needed)      │
│                                 │
│  4. Append summary to           │
│     progress.txt                │
│                                 │
│  5. Stop                        │
│     (or emit COMPLETE signal)   │
└────────────┬────────────────────┘
             │
             ▼
     ralph.sh checks output
     for <promise>COMPLETE</promise>
             │
        ┌────┴────┐
        │ Found?  │
        ├─Yes─────┼──► Loop ends
        └─No──────┘
             │
             ▼
     Sleep 2s, start iteration N+1
```

### File Roles

Each run directory contains files with specific roles:

| File | Purpose | Who writes it |
|------|---------|---------------|
| `instructions.md` | Defines what Ralph does, which files to read, task priorities | Human (before run) |
| `progress.txt` | Append-only iteration log — Ralph's memory across iterations | Ralph |
| `chief-wiggum.md` | Directives from the Chief Wiggum session | Chief Wiggum |
| `answers.md` | Human answers to Ralph's questions | Human |
| `questions.md` | Questions Ralph raises when encountering ambiguity | Ralph |
| `meta.md` | Run metadata (date, model, config) | Auto-generated |
| `run.log` | Execution log (start/stop times, iteration count) | ralph.sh |

## How to Run Ralph

### Basic Usage

```bash
./ralph.sh .ralph/my-run
```

This runs the default configuration: up to 20 iterations, using Claude Opus, with Read/Edit/Write tools.

### Prerequisites

The run directory must contain an `instructions.md` file. All other files are auto-created as templates if they don't exist.

### Options

```bash
./ralph.sh <run-directory> [options]

Options:
  -n, --max-iterations N   Maximum iterations (default: 20)
  -m, --model MODEL        Claude model to use (default: opus)
  -t, --tools TOOLS        Allowed tools, quoted (default: "Read Edit Write")
```

### Examples

```bash
# Short run with cheaper model
./ralph.sh .ralph/my-run -n 10 -m sonnet

# Run with more tools (e.g. for coding tasks)
./ralph.sh .ralph/my-run -n 30 -t "Read Edit Write Bash Glob Grep"

# New run
mkdir .ralph/my-new-task
# Write .ralph/my-new-task/instructions.md, then:
./ralph.sh .ralph/my-new-task -n 15
```

### Path Convention in instructions.md

Use `{{RUN_DIR}}` as a placeholder for run-specific files. The script substitutes it automatically before passing the prompt to Claude:

```
{{RUN_DIR}}/progress.txt         # run-specific
{{RUN_DIR}}/chief-wiggum.md      # run-specific
{{RUN_DIR}}/answers.md           # run-specific
{{RUN_DIR}}/questions.md         # run-specific
```

All other file paths are relative to the project root as usual.

## How to Communicate with Ralph

Ralph cannot be talked to directly. Communication happens through files:

### As Chief Wiggum (directing Ralph)

Edit `chief-wiggum.md` in the run directory **before** starting the loop:

- **`## Action Required`** — Ralph MUST address these, one per iteration, in order.
- **`## Observations`** — Informational notes. Ralph may use them but is not required to act.

Ralph never modifies `chief-wiggum.md`. To confirm an item was addressed, check `progress.txt`.

### As the Human (answering questions)

When Ralph raises a question in `questions.md`, write your answer in `answers.md` in the run directory. On the next iteration, Ralph will process the answer.

### Monitoring Progress

- **`progress.txt`** — Append-only log of every iteration. What Ralph did and why.
- **`run.log`** — Execution metadata (start time, iterations, completion status).
- **Project files** — Diff the files Ralph was allowed to edit to see actual changes.

## Writing instructions.md

The `instructions.md` file defines Ralph's behavior for a run. Key elements:

1. **Role definition** — What is Ralph doing? (Refining stories, writing code, reviewing, ...)
2. **One-task-per-iteration rule** — Always enforce this. Without it, the model tries to do everything at once and produces lower-quality results.
3. **Startup sequence** — Which files to read and in what order. This is Ralph's "memory load." Use `{{RUN_DIR}}` for run-specific files.
4. **Task selection priorities** — A strict priority list. Ralph picks the first applicable task, does it, and stops.
5. **File ownership table** — What Ralph may read vs. write. Prevents accidental overwrites.
6. **Completion signal** — How Ralph signals that all work is done (`<promise>COMPLETE</promise>`).
7. **Guardrails** — Rules to prevent Ralph from making unauthorized decisions.

## Best Practices

### Do

- **Keep iterations small.** One task per iteration produces better results than batching.
- **Use progress.txt as memory.** Ralph reads it every iteration. Be explicit about what was done and what was deferred.
- **Clean up chief-wiggum.md** between runs. Remove addressed items to avoid confusion.
- **Review diffs after the loop.** Ralph is autonomous but not infallible. Spot-check the changes.
- **Use the right model.** Opus for complex reasoning tasks, Sonnet for straightforward work.
- **Match tools to the task.** Read/Edit/Write for spec work. Add Bash/Glob/Grep for coding tasks.

### Don't

- **Don't modify files Ralph owns during a run.** File conflicts will confuse the model.
- **Don't give Ralph tools it doesn't need.** Minimal tool sets reduce unintended side effects.
- **Don't expect Ralph to remember across iterations.** Every iteration is a fresh context. If it's not in a file, it doesn't exist.
- **Don't skip instructions.md.** Running without a structured prompt loses the task selection that makes Ralph reliable.
