# Ralph for Claude Code - Deep Dive

> **TL;DR**: Ralph is an autonomous AI development framework (155+ stars) that runs Claude Code in intelligent loops with built-in safeguards. It automates iterative project improvements while preventing API waste through rate limiting, circuit breakers, and semantic exit detection. Think "autopilot for Claude Code" with guardrails that know when to stop. MIT licensed, actively maintained.

---

## What Is Ralph?

**Ralph** (named after the Simpsons character) is a Bash-based framework that transforms Claude Code from a single-execution tool into an autonomous development engine. It runs Claude Code repeatedly, with each iteration improving your project based on a prioritized task list, while intelligently knowing when to stop.

### The Problem It Solves

```
┌─────────────────────────────────────────────────────────────────────┐
│                    THE MANUAL CLAUDE CODE LOOP                       │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│   TYPICAL WORKFLOW WITHOUT RALPH:                                   │
│   ├── Run Claude Code → Review output → Run again                  │
│   ├── Repeat 10-50 times for a feature                             │
│   ├── Manually watch for completion                                │
│   ├── Risk burning API quota on stuck loops                        │
│   └── Hours of babysitting required                                │
│                                                                     │
│   PROBLEMS:                                                         │
│   ├── Tedious manual monitoring                                     │
│   ├── No protection against infinite loops                         │
│   ├── API quota exhaustion risk                                    │
│   ├── No standardized project structure                            │
│   └── Hard to know when "done" is really done                      │
│                                                                     │
│   RALPH'S SOLUTION:                                                 │
│   ├── Autonomous loops with intelligent exit detection             │
│   ├── Rate limiting prevents quota waste                           │
│   ├── Circuit breaker stops stuck loops                            │
│   ├── Live monitoring dashboard                                    │
│   └── Semantic analysis knows when work is complete                │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘
```

---

## Quick Stats

| Metric | Value |
|--------|-------|
| **GitHub Stars** | 155+ |
| **Forks** | 15 |
| **Open Issues** | 33 (organized roadmap) |
| **License** | MIT |
| **Language** | Bash (Shell) |
| **Version** | 0.9.0 (v1.0 target ~4 weeks) |
| **Test Coverage** | 97 tests, 100% pass rate |
| **Primary Author** | frankbria |
| **Created** | August 2025 |

---

## Key Features

### 1. Autonomous Development Loops

Ralph executes Claude Code repeatedly, with each iteration building on the previous:

```
┌─────────────────────────────────────────────────────────────────────┐
│                    RALPH'S AUTONOMOUS LOOP                           │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│   START                                                             │
│     ↓                                                               │
│   ┌─────────────────────────────────────────┐                      │
│   │  1. Check rate limits (calls/hour)      │                      │
│   │  2. Evaluate exit conditions            │                      │
│   │  3. Execute Claude Code with timeout    │                      │
│   │  4. Analyze response for completion     │                      │
│   │  5. Check circuit breaker (stuck?)      │                      │
│   │  6. Log progress and metrics            │                      │
│   └─────────────────────────────────────────┘                      │
│     ↓                                                               │
│   Continue? ──YES──→ Loop back to step 1                           │
│     │                                                               │
│     NO                                                              │
│     ↓                                                               │
│   EXIT (graceful completion)                                        │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘
```

### 2. Intelligent Exit Detection

Ralph doesn't just count loops - it semantically understands when work is done:

| Exit Signal | What It Means |
|-------------|---------------|
| **Multiple "done" signals** | Claude says complete multiple times |
| **Checklist progress** | `@fix_plan.md` items marked complete |
| **Test-only loops** | Only running tests = feature saturation |
| **Strong completion indicators** | Project readiness signals detected |
| **API limit reached** | 5-hour Claude usage ceiling hit |

### 3. Rate Limiting System

Prevents burning through your API quota:

```bash
ralph --calls 100    # Default: 100 calls per hour
ralph --calls 50     # Custom limit for cost control
```

Features:
- Tracks API calls per hour
- Countdown timer when limit reached
- Configurable per-run overrides
- Hourly reset with clear messaging

### 4. Circuit Breaker Pattern

Detects and handles stuck loops automatically:

```
┌─────────────────────────────────────────────────────────────────────┐
│                    CIRCUIT BREAKER LOGIC                             │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│   DETECTION:                                                        │
│   ├── Minimal file changes across iterations                       │
│   ├── Persistent error patterns (multi-line matching)              │
│   ├── Excessive looping without progress                           │
│   └── Two-stage filtering (removes false positives)                │
│                                                                     │
│   RECOVERY STRATEGY:                                                │
│   ├── Attempt 1: Wait 5 minutes, retry                             │
│   ├── Attempt 2: Wait 10 minutes, retry                            │
│   ├── Attempt 3: Wait 15 minutes, retry                            │
│   └── After 3 attempts: Prompt user or exit                        │
│                                                                     │
│   STATE PERSISTENCE:                                                │
│   └── Saves to .circuit_breaker_state file                         │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘
```

### 5. Live Monitoring Dashboard

Real-time visibility into the autonomous loop:

```
┌─────────────────────────────────────────────────────────────────────┐
│                    RALPH MONITOR DASHBOARD                           │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│   ┌─ Current Status ────────────────────────────────────────────┐  │
│   │  Loop: 12                                                   │  │
│   │  Status: Running                                            │  │
│   │  API Calls: 45/100 this hour                               │  │
│   └─────────────────────────────────────────────────────────────┘  │
│                                                                     │
│   ┌─ Claude Code Progress ──────────────────────────────────────┐  │
│   │  ◐ Running... (elapsed: 2m 34s)                            │  │
│   │  Last output: "Implementing user authentication..."        │  │
│   └─────────────────────────────────────────────────────────────┘  │
│                                                                     │
│   ┌─ Recent Activity ───────────────────────────────────────────┐  │
│   │  [14:32:01] Loop 11 completed successfully                 │  │
│   │  [14:30:45] Tests passing: 47/47                          │  │
│   │  [14:28:12] Feature: login form implemented               │  │
│   │  [14:25:33] Loop 10 completed successfully                 │  │
│   └─────────────────────────────────────────────────────────────┘  │
│                                                                     │
│   Refresh: 2s │ Press Ctrl+C to exit                               │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘
```

---

## Architecture

### Core Components

```
┌─────────────────────────────────────────────────────────────────────┐
│                    RALPH ARCHITECTURE                                │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│   COMMANDS (User Interface)                                         │
│   ├── ralph            → Main autonomous loop                      │
│   ├── ralph-setup      → Initialize new project                    │
│   ├── ralph-import     → Convert PRD to Ralph format               │
│   └── ralph-monitor    → Live monitoring dashboard                 │
│                                                                     │
│   CORE ENGINE                                                       │
│   ├── ralph_loop.sh    → Main loop orchestration                   │
│   ├── circuit_breaker.sh → Fault tolerance & recovery              │
│   ├── response_analyzer.sh → Semantic output analysis              │
│   └── date_utils.sh    → Hour boundary calculations                │
│                                                                     │
│   CONTROL FILES (Per Project)                                       │
│   ├── PROMPT.md        → Development instructions for Claude       │
│   ├── @fix_plan.md     → Prioritized task list                     │
│   └── @AGENT.md        → Build/run instructions                    │
│                                                                     │
│   EXECUTION                                                         │
│   └── npx @anthropic/claude-code                                   │
│       └── Runs with timeout protection                             │
│       └── Output captured for analysis                             │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘
```

### Project Structure

Every Ralph project follows this standardized layout:

```
my-project/
├── PROMPT.md              # Main instructions for Claude
├── @fix_plan.md           # Prioritized task checklist
├── @AGENT.md              # Build and execution commands
├── specs/                 # Requirements & specifications
│   └── stdlib/            # Standard library specs
├── src/                   # Source code
├── logs/                  # Execution history
│   └── ralph.log          # Main activity log
├── examples/              # Usage examples
├── docs/                  # Documentation
└── .circuit_breaker_state # Recovery state (auto-generated)
```

The `@` prefix marks Ralph control files that guide the autonomous loop.

---

## Installation

### Prerequisites

| Requirement | Purpose |
|-------------|---------|
| **Bash 4.0+** | Core runtime |
| **Claude Code CLI** | AI execution engine |
| **tmux** | Monitoring dashboard |
| **jq** | JSON processing |
| **Git** | Version control |
| **Node.js/npm** | Claude Code dependency |

### Global Installation (One-Time)

```bash
# Clone the repository
git clone https://github.com/frankbria/ralph-claude-code.git
cd ralph-claude-code

# Run installer
./install.sh
```

**What the installer does:**
1. Verifies all dependencies are installed
2. Creates `$HOME/.ralph` directory with templates
3. Creates `$HOME/.local/bin` for commands
4. Generates wrapper scripts for all commands
5. Adds to PATH (prompts if needed)

### Per-Project Setup

**Option A: New Project**
```bash
ralph-setup my-awesome-project
cd my-awesome-project
# Edit PROMPT.md with your project goals
# Add specs to specs/ folder
ralph  # Start autonomous development
```

**Option B: Import Existing PRD**
```bash
ralph-import requirements.md project-name
cd project-name
ralph  # Start autonomous development
```

---

## Usage

### Basic Commands

```bash
# Start autonomous loop (default settings)
ralph

# Custom rate limit (50 calls/hour instead of 100)
ralph --calls 50

# Use alternative prompt file
ralph --prompt custom-instructions.md

# Set execution timeout (30 minutes)
ralph --timeout 30

# Verbose progress updates
ralph --verbose

# Combined with live monitoring
ralph --monitor
```

### Monitoring

```bash
# Standalone monitoring dashboard
ralph-monitor

# Or integrated with execution
ralph --monitor
```

### Project Management

```bash
# Initialize new project
ralph-setup project-name

# Import existing requirements document
ralph-import requirements.md project-name
```

---

## Control Files Explained

### PROMPT.md - The Brain

Your main instructions to Claude. Example:

```markdown
# Project: Task Management API

## Goal
Build a REST API for task management with authentication.

## Tech Stack
- Node.js + Express
- PostgreSQL
- JWT authentication

## Quality Requirements
- 85%+ test coverage
- All tests passing
- Conventional commits
- Updated documentation
```

### @fix_plan.md - The Task List

Prioritized checklist that Ralph monitors for completion:

```markdown
# Fix Plan

## Priority 1: Core Features
- [x] User registration endpoint
- [x] Login with JWT
- [ ] Task CRUD operations
- [ ] Task assignment

## Priority 2: Polish
- [ ] Input validation
- [ ] Error handling
- [ ] Rate limiting
```

### @AGENT.md - The Instructions

Build and run commands for the project:

```markdown
# Agent Instructions

## Build
npm install

## Test
npm test

## Run
npm start

## Lint
npm run lint
```

---

## How Ralph Integrates with Claude Code

```
┌─────────────────────────────────────────────────────────────────────┐
│                    RALPH + CLAUDE CODE INTEGRATION                   │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│   RALPH PROVIDES:                                                   │
│   ├── Loop orchestration (when to run Claude)                      │
│   ├── Exit detection (when to stop)                                │
│   ├── Rate limiting (quota protection)                             │
│   ├── Circuit breaker (stuck loop prevention)                      │
│   ├── Monitoring (visibility)                                       │
│   └── Project structure (organization)                             │
│                                                                     │
│   CLAUDE CODE PROVIDES:                                             │
│   ├── AI reasoning and code generation                             │
│   ├── File manipulation                                             │
│   ├── Command execution                                             │
│   ├── Test running                                                  │
│   └── Documentation updates                                         │
│                                                                     │
│   TOGETHER:                                                         │
│   └── Autonomous, safe, monitored development                      │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘
```

### Quality Standards Enforced

Ralph expects Claude to maintain:

| Standard | Requirement |
|----------|-------------|
| **Test Coverage** | Minimum 85% on new features |
| **Test Pass Rate** | 100% (no exceptions) |
| **Commit Messages** | Conventional commits format |
| **Documentation** | Updated with changes |
| **Code Comments** | Clear, reflecting implementation |

---

## Safeguards Deep Dive

### Rate Limiting

```
┌─────────────────────────────────────────────────────────────────────┐
│                    RATE LIMITING FLOW                                │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│   Each Iteration:                                                   │
│   ├── Read call counter file                                       │
│   ├── Check: calls_made < max_calls_per_hour?                      │
│   │   ├── YES → Proceed, increment counter                         │
│   │   └── NO → Calculate wait time until next hour                 │
│   │            Display countdown timer                             │
│   │            Option to wait or exit                              │
│   └── Reset counter at hour boundary                               │
│                                                                     │
│   Default: 100 calls/hour                                           │
│   Override: ralph --calls N                                         │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘
```

### Error Detection (Two-Stage Filtering)

```
Stage 1: Identify Potential Errors
├── Scan Claude output for error patterns
├── Match against known error signatures
└── Flag suspicious outputs

Stage 2: Filter False Positives
├── Check for JSON formatting artifacts
├── Verify actual execution errors
├── Distinguish warnings from errors
└── Special handling for 5-hour API limit

Result: High-confidence error detection
```

### Circuit Breaker States

| State | Description | Action |
|-------|-------------|--------|
| **CLOSED** | Normal operation | Continue looping |
| **OPEN** | Failure detected | Stop, wait, retry |
| **HALF-OPEN** | Testing recovery | Cautious execution |

---

## Comparison with Alternatives

| Feature | Ralph | Raw Claude Code | CI/CD Systems |
|---------|-------|-----------------|---------------|
| **Autonomous Loops** | Built-in, intelligent | Manual | Configured |
| **Exit Detection** | Semantic analysis | None | Explicit conditions |
| **API Protection** | Rate limiting + circuit breaker | None | None |
| **Monitoring** | Real-time dashboard | Terminal output | Logs |
| **Project Structure** | Opinionated, standardized | Flexible | Varies |
| **Learning Curve** | Low (4 commands) | Low | Medium-High |
| **Cost Control** | Built-in | Manual tracking | External |

### When to Use Ralph

**Good fit:**
- Iterative feature development
- Bug fixing cycles
- Spec-driven development
- Projects with clear completion criteria
- Cost-conscious API usage

**Not ideal for:**
- One-off tasks (use Claude Code directly)
- Non-deterministic exploration
- Projects without clear goals
- Real-time applications

---

## Development Roadmap

### Current Status: v0.9.0

| Phase | Status | Details |
|-------|--------|---------|
| **Phase 1: Foundation** | ✅ Complete | 35 unit tests, core functionality |
| **Phase 2: Integration** | ⏳ In Progress | ~54 integration tests planned |
| **Phase 3: Features** | 🔄 Partial | Log rotation, dry-run, config files |
| **Phase 4: Polish** | 📋 Planned | Notifications, backup/rollback |

### Planned Features

| Feature | Issue | Description |
|---------|-------|-------------|
| **JSON Config** | #36 | `.ralphrc.json` support |
| **Dry-Run Mode** | TBD | Preview without execution |
| **Metrics Tracking** | TBD | Historical performance data |
| **Notifications** | TBD | Slack/email on completion |
| **Agent SDK Integration** | #32-35 | Anthropic Agent SDK support |
| **Structured Output** | #28 | `--output-format json` |
| **Session Continuity** | #30 | `--continue` flag |

---

## Testing

Ralph has comprehensive test coverage:

```bash
# Run all tests
bats tests/

# Current results
# 97 tests, 100% pass rate

# Test distribution:
# - 35 unit tests (rate limiting, exit detection)
# - 13 error detection tests
# - 9 stuck loop detection tests
# - 20 edge case tests
# - Integration tests (in progress)
```

---

## Tips for Success

### 1. Write Clear Specs

```markdown
# Good: Specific and testable
- User can register with email/password
- Registration returns JWT token
- Invalid emails return 400 error

# Bad: Vague
- Make user system work
- Handle errors
```

### 2. Start with Small Task Lists

Begin with 3-5 items in `@fix_plan.md`, not 50.

### 3. Use Verbose Mode for Debugging

```bash
ralph --verbose
```

### 4. Monitor Your First Few Runs

```bash
ralph --monitor
```

### 5. Set Appropriate Rate Limits

```bash
# Development/testing: lower limit
ralph --calls 30

# Production push: higher limit
ralph --calls 100
```

---

## How This Connects to Our Other Deep Dives

| Deep Dive | Connection |
|-----------|------------|
| **CCPM** | Both solve context persistence; Ralph focuses on loops, CCPM on project management |
| **OpenHands** | Both automate AI coding; Ralph is Claude-specific with safeguards |
| **Vibe Kanban** | Visual orchestration vs. Ralph's CLI automation |
| **SWE-agent** | Both autonomous coding; SWE-agent for bugs, Ralph for features |
| **Continue** | IDE integration vs. Ralph's autonomous loops |

---

## Key Links

| Resource | URL |
|----------|-----|
| **GitHub** | https://github.com/frankbria/ralph-claude-code |
| **Issues/Roadmap** | https://github.com/frankbria/ralph-claude-code/issues |
| **License** | MIT |

---

## Bottom Line

Ralph is the **autopilot for Claude Code** - it takes the tedious manual loop of "run Claude, check output, run again" and automates it with intelligent safeguards.

**Why it matters:**
- **Time savings** - No more babysitting Claude Code sessions
- **Cost control** - Rate limiting prevents API quota waste
- **Safety** - Circuit breaker stops stuck loops before they burn resources
- **Visibility** - Real-time dashboard shows what's happening
- **Structure** - Opinionated project layout keeps things organized

**The key insight**: Autonomous AI development is powerful, but without guardrails it's dangerous and expensive. Ralph provides those guardrails while keeping the power of Claude Code's autonomous capabilities.

**Best for**: Developers who want to leverage Claude Code for iterative development without the manual overhead and risk of runaway API costs.

---

*Document created: January 2026*
*Source: [GitHub - frankbria/ralph-claude-code](https://github.com/frankbria/ralph-claude-code)*
