The real technique for effective AI iterationโfresh context windows + progress memory = exponential improvement
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.
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.
This prompt establishes the methodology for Claude Code to follow the Ralph Loop pattern. Use it as a custom instruction or skill.
# 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.
Use this prompt to generate a properly structured PRD from your idea.
# 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.
This script orchestrates the loop by starting fresh Claude Code sessions for each iteration.
#!/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
ralph.sh in your project rootchmod +x ralph.shprd.md exists with checkboxed tasksprogress.md file./ralph.sh or ./ralph.sh 20 for 20 iterationsIf you prefer not to use the script, you can manually implement the loop:
# 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.
A ready-to-use PRD template structured for Ralph Loop methodology.
# 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 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
The Anthropic Ralph Wiggum plugin in Claude Code is NOT the same as the original Ralph Loop technique. Here's why it 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.
Both methodologies share similar fundamentals. Here's how they compare:
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.