Ralph Loop Methodology

The real technique for effective AI iterationโ€”fresh context windows + progress memory = exponential improvement

๐ŸŽฏ What is a Ralph Loop?

A Ralph Loop is a technique for iterating on AI tasks that hinges on one critical insight: context rot destroys AI performance. The longer you work in a single session, the worse Claude gets.

0 tokens 200k tokens
~100k threshold
๐Ÿง  SMART ZONE ๐Ÿ’€ DUMB ZONE

Studies show LLM effectiveness drops dramatically past the halfway point of the context window. Ralph Loops solve this by starting a fresh session for every task attempt.

โšก The Core Workflow

1
Idea โ†’ PRD
Transform your idea into a Product Requirements Document with discrete, checkboxed tasks
โ†“
2
Execute Loop (NEW SESSION)
Start fresh Claude Code instance โ†’ Read PRD โ†’ Find first incomplete task
โ†“
3
Attempt Task
Work on the task with full 200k context budget available
โ†“
4
Success: Update PRD + Progress
Mark task complete โœ“ in PRD, log details to progress.md
โ†“
5
Failure: Log & Retry
Log what was tried + errors to progress.md โ†’ NEW SESSION โ†’ Try different approach
Fresh Context + Progress Memory = Effective Iteration
It's not about repeating 10 times. It's about repeating 10 times effectively with full cognitive budget each time.

๐Ÿ“ Required Files

  • ralph.sh โ€” The bash script that orchestrates the loop
  • prd.md โ€” Product Requirements Document with checkboxed tasks
  • progress.md โ€” Running log of attempts, successes, and failures (can start empty)

๐Ÿ“ Ralph Loop System Prompt

This prompt establishes the methodology for Claude Code to follow the Ralph Loop pattern. Use it as a custom instruction or skill.

ralph-loop-system.md
# Ralph Loop Methodology System

You are operating under the Ralph Loop methodologyโ€”a context-aware iteration system designed to maximize AI effectiveness by respecting context window limitations.

## Core Principle
Context rot degrades AI performance. Past ~100k tokens (halfway through a 200k context window), output quality drops dramatically. Every task iteration should begin with a FRESH session.

## Your Operating Protocol

### 1. Session Initialization
At the start of each session:
- Read `prd.md` to understand the full project scope
- Read `progress.md` to understand what has been attempted
- Identify the FIRST incomplete task (unchecked checkbox)
- Focus exclusively on that single task

### 2. Task Execution
For the current task:
- Review any previous attempts logged in progress.md
- If previous attempts exist, explicitly avoid repeating failed approaches
- Execute the task with fresh context and full cognitive capacity
- Test your implementation before marking complete

### 3. Success Protocol
When a task is completed successfully:
1. Update `prd.md`: Check the task checkbox [x]
2. Update `progress.md` with:
   - Task identifier
   - What was implemented
   - Key decisions made
   - Any patterns or insights discovered
3. Signal completion for loop to start new session

### 4. Failure Protocol  
When a task cannot be completed this session:
1. DO NOT mark the task as complete
2. Update `progress.md` with:
   - Task identifier
   - Approaches attempted
   - Specific errors encountered
   - Hypotheses for why it failed
   - Suggested alternative approaches
3. Signal for new session (fresh context will help)

## Progress.md Format
```markdown
## Session Log

### [Timestamp] Task: [Task Name]
**Status:** Complete | Failed | Partial

**Attempted:**
- Approach 1: [description] โ†’ [result]
- Approach 2: [description] โ†’ [result]

**Errors Encountered:**
- [specific error messages]

**Insights:**
- [patterns discovered]
- [dependencies identified]

**Next Session Should:**
- [specific recommendations]
```

## PRD.md Task Format
Tasks must use checkbox format for tracking:
```markdown
## Tasks

- [ ] Task 1: Initialize project structure
  - [ ] Subtask 1a
  - [ ] Subtask 1b
- [ ] Task 2: Implement core feature
- [x] Task 3: Already completed task
```

## Critical Rules
1. ONE task per sessionโ€”do not attempt multiple tasks
2. ALWAYS update progress.md before session ends
3. If you've attempted 3+ approaches without success, document and request new session
4. Previous session's insights are GOLDโ€”read progress.md carefully
5. Fresh context = fresh perspectiveโ€”don't carry over assumptions

## The Power Formula
```
Fresh Context Window + Previous Attempt Knowledge = Exponential Problem Solving
```

You are iteration N of potentially 10+ attempts. Each iteration has full cognitive capacity. Use it wisely by building on what came before without being constrained by context rot.

๐Ÿ”ง PRD Generation Prompt

Use this prompt to generate a properly structured PRD from your idea.

prd-generator-prompt.md
# PRD Generation Request

I need you to create a Product Requirements Document (PRD) for the Ralph Loop methodology.

## My Project Idea:
[DESCRIBE YOUR IDEA HERE]

## Requirements for the PRD:

### Structure
1. **Project Overview** - Brief description of what we're building
2. **Core Features** - List of main features with descriptions
3. **Technical Requirements** - Stack, dependencies, constraints
4. **Tasks** - CRITICAL: Discrete, checkboxed tasks

### Task Format Rules
- Use `- [ ]` checkbox format (required for Ralph Loop tracking)
- Break features into smallest completable units
- Each task should be achievable in one focused session
- Order tasks by dependency (foundational first)
- Include acceptance criteria for each task

### Example Task Structure:
```markdown
## Tasks

### Phase 1: Foundation
- [ ] **Task 1.1**: Initialize project with [framework]
  - Set up directory structure
  - Install core dependencies
  - Configure build tools
  - Acceptance: `npm run dev` works

- [ ] **Task 1.2**: Set up database schema
  - Create migration files
  - Define models
  - Acceptance: Can connect and query

### Phase 2: Core Features  
- [ ] **Task 2.1**: Implement [feature]
  - [specific implementation details]
  - Acceptance: [testable criteria]
```

### Output Files to Create:
1. `prd.md` - The full PRD with all tasks
2. `progress.md` - Empty file with header template ready for logging

Generate a comprehensive PRD following this structure. Make tasks specific enough that each can be completed in a single focused session with clear acceptance criteria.

โš™๏ธ Ralph Loop Bash Script

This script orchestrates the loop by starting fresh Claude Code sessions for each iteration.

ralph.sh
#!/bin/bash

# Ralph Loop - Context-Aware AI Iteration
# Usage: ./ralph.sh [max_iterations]
# Default: 10 iterations

MAX_ITERATIONS=${1:-10}
ITERATION=0

echo "๐Ÿ”„ Starting Ralph Loop (max $MAX_ITERATIONS iterations)"
echo "=================================================="

# The instruction given to each fresh Claude Code session
RALPH_INSTRUCTION="You are operating under Ralph Loop methodology. 

CRITICAL: This is iteration $((ITERATION + 1)) of a fresh session.

1. Read prd.md to understand the project
2. Read progress.md to see previous attempts  
3. Find the FIRST unchecked task [ ] in prd.md
4. Work ONLY on that single task
5. If successful: Check it [x] in prd.md AND log to progress.md
6. If failed: Log detailed notes to progress.md (approaches tried, errors, suggestions)
7. Exit when done with this task

Remember: You have FRESH context. Previous session insights are in progress.md.
Build on what was learned. Don't repeat failed approaches."

while [ $ITERATION -lt $MAX_ITERATIONS ]; do
    ITERATION=$((ITERATION + 1))
    echo ""
    echo "๐Ÿš€ Iteration $ITERATION/$MAX_ITERATIONS"
    echo "-------------------------------------------"
    
    # Check if all tasks are complete
    if ! grep -q "\- \[ \]" prd.md 2>/dev/null; then
        echo "โœ… All tasks complete! Exiting loop."
        break
    fi
    
    # Count remaining tasks
    REMAINING=$(grep -c "\- \[ \]" prd.md 2>/dev/null || echo "0")
    echo "๐Ÿ“‹ Remaining tasks: $REMAINING"
    
    # Start fresh Claude Code session with instruction
    # The --print flag outputs result without interactive mode
    claude --print "$RALPH_INSTRUCTION"
    
    EXIT_CODE=$?
    
    if [ $EXIT_CODE -ne 0 ]; then
        echo "โš ๏ธ Claude Code exited with code $EXIT_CODE"
    fi
    
    echo "-------------------------------------------"
    echo "โœ“ Iteration $ITERATION complete"
    
    # Small delay between iterations
    sleep 2
done

echo ""
echo "=================================================="
echo "๐Ÿ Ralph Loop finished after $ITERATION iterations"

# Final status
if grep -q "\- \[ \]" prd.md 2>/dev/null; then
    REMAINING=$(grep -c "\- \[ \]" prd.md)
    echo "โš ๏ธ $REMAINING tasks still incomplete"
else
    echo "โœ… All tasks completed successfully!"
fi

Setup Instructions

  • Save script as ralph.sh in your project root
  • Make executable: chmod +x ralph.sh
  • Ensure prd.md exists with checkboxed tasks
  • Create empty progress.md file
  • Run: ./ralph.sh or ./ralph.sh 20 for 20 iterations
โš ๏ธ
Windows Users: Enable Developer Mode or use WSL. The script requires bash. On Mac/Linux, it works natively.

๐Ÿ”„ Alternative: Manual Loop

If you prefer not to use the script, you can manually implement the loop:

manual-workflow.txt
# Manual Ralph Loop Workflow

## For Each Task:

1. QUIT Claude Code completely (Ctrl+C or /exit)

2. RESTART Claude Code fresh:
   claude

3. PASTE this instruction:
   "Read prd.md and progress.md. Work on the first 
   unchecked task only. Update both files when done 
   or if you fail. This is a fresh session - use 
   progress.md to see what was tried before."

4. LET IT WORK on the single task

5. WHEN IT EXITS, repeat from step 1

## Key Point:
The power is in the FRESH SESSION.
Exit completely. Start completely fresh.
Progress.md carries the knowledge forward.

๐Ÿ“„ PRD Template

A ready-to-use PRD template structured for Ralph Loop methodology.

prd.md
# Project: [YOUR PROJECT NAME]

## Overview
[Brief description of what you're building and why]

## Goals
- [Primary goal]
- [Secondary goal]
- [Success criteria]

## Technical Stack
- **Framework:** [e.g., Next.js, React, etc.]
- **Database:** [e.g., PostgreSQL, Supabase]
- **Styling:** [e.g., Tailwind CSS]
- **Deployment:** [e.g., Vercel]

## Features
1. **[Feature 1]**: [Description]
2. **[Feature 2]**: [Description]
3. **[Feature 3]**: [Description]

---

## Tasks

### Phase 1: Project Setup
- [ ] **Task 1.1**: Initialize project structure
  - Create directory structure
  - Set up package.json
  - Install dependencies
  - **Acceptance:** `npm run dev` starts without errors

- [ ] **Task 1.2**: Configure development environment
  - Set up linting (ESLint)
  - Configure formatting (Prettier)
  - Add TypeScript (if applicable)
  - **Acceptance:** `npm run lint` passes

- [ ] **Task 1.3**: Set up database connection
  - Configure database client
  - Test connection
  - Create initial schema
  - **Acceptance:** Can read/write to database

### Phase 2: Core Functionality
- [ ] **Task 2.1**: Implement [Core Feature 1]
  - [Specific implementation detail]
  - [Specific implementation detail]
  - **Acceptance:** [Testable criteria]

- [ ] **Task 2.2**: Implement [Core Feature 2]
  - [Specific implementation detail]
  - [Specific implementation detail]
  - **Acceptance:** [Testable criteria]

- [ ] **Task 2.3**: Implement [Core Feature 3]
  - [Specific implementation detail]
  - [Specific implementation detail]
  - **Acceptance:** [Testable criteria]

### Phase 3: UI/UX
- [ ] **Task 3.1**: Create [UI Component 1]
  - Design layout
  - Implement responsive design
  - Add interactions
  - **Acceptance:** Component renders correctly on all viewports

- [ ] **Task 3.2**: Create [UI Component 2]
  - [Details]
  - **Acceptance:** [Criteria]

### Phase 4: Polish & Deploy
- [ ] **Task 4.1**: Error handling & edge cases
  - Add error boundaries
  - Handle loading states
  - Validate inputs
  - **Acceptance:** App handles errors gracefully

- [ ] **Task 4.2**: Performance optimization
  - Optimize images
  - Add caching
  - Lazy load components
  - **Acceptance:** Lighthouse score > 90

- [ ] **Task 4.3**: Deploy to production
  - Configure production environment
  - Set up CI/CD
  - Deploy and verify
  - **Acceptance:** Live URL accessible and functional

---

## Notes
- [Any important notes or constraints]
- [Dependencies between tasks]
- [Known challenges]

๐Ÿ“Š Progress Template

progress.md
# Progress Log

This file tracks all Ralph Loop iterations, including successes and failures.
Each new session should READ this file to understand what has been attempted.

---

## Session History



โš–๏ธ Real Ralph Loop vs. Ralph Wiggum Plugin

The Anthropic Ralph Wiggum plugin in Claude Code is NOT the same as the original Ralph Loop technique. Here's why it matters:

โœ… Real Ralph Loop

  • Starts NEW session each iteration
  • Fresh 200k context window every task
  • Stays in "smart zone" (0-100k)
  • Progress file carries knowledge forward
  • Each attempt has full cognitive capacity
  • Context management is the core feature

โŒ Ralph Wiggum Plugin

  • Does NOT start new session
  • Just blocks exit, continues in same context
  • Stays in "dumb zone" longer
  • Only resets at auto-compact (~150k)
  • Diminishing returns on each iteration
  • Misses the core point entirely
๐Ÿ’ก
The Key Insight: The power of Ralph Loops isn't that it repeats 10 times. It's that each repetition has FULL cognitive capacity via a fresh context window, PLUS accumulated knowledge from previous attempts via progress.md.

๐Ÿง  Why Context Management Matters

Research on LLMs shows a consistent pattern: performance degrades as context fills up. This isn't a bugโ€”it's how attention mechanisms work at scale.

Session Start Context Full
Performance Cliff
High accuracy, creative solutions Errors, repetition, confusion

What Happens in the "Dumb Zone"

  • Increased hallucinations and errors
  • Repetitive solutions (trying same failed approach)
  • Loss of earlier context details
  • Slower response times
  • Decreased creativity and problem-solving

What Fresh Context Provides

  • Full attention capacity on the current task
  • No accumulated confusion from failed attempts
  • Fresh perspective on the problem
  • Previous insights available via progress.md (not context)
  • Maximum creative problem-solving ability

๐Ÿ”„ Ralph Loop vs. GSD (Get Stuff Done)

Both methodologies share similar fundamentals. Here's how they compare:

Ralph Loop

  • Simple bash script approach
  • Fresh sessions via process restart
  • PRD + Progress file system
  • More hands-off / automated
  • Good for well-defined projects

GSD Framework

  • Uses sub-agents architecture
  • Fresh context via agent spawning
  • More structured workflow
  • More hand-holding for testing
  • Good for complex, iterative projects

Both work well. The core principle is the same: fresh context windows + knowledge persistence = effective iteration. Choose based on your preference for automation vs. structure.