Skip to content
/

Ralph for Claude Code

ralph-claude-code · frankbria/ralph-claude-code · ★ 9.2k · last commit 2026-05-21

Production-grade Claude Code autonomous loop with dual-condition exit gate, rate limiting, circuit breaker, session management, and live monitoring.

Best whenAutonomous loops need engineering-grade safeguards (rate limiting, circuit breakers, structured exit conditions) to be reliable in practice.
Skip ifUsing broad Bash(*) tool permissions (security risk), Large tasks exceeding one context window
vs seeds
claude-flowin operational complexity but without an MCP server — all orchestration is external bash calling Claude Code's CLI. The …
Primitive shape
No installable primitives
00

Summary

Ralph for Claude Code — Summary

Ralph for Claude Code by frankbria is a heavily engineered adaptation of the snarktank Ralph pattern, specifically hardened for production use with Claude Code. Where snarktank/ralph is a ~200-line bash script, this version is a multi-script system with 566 tests, 9 library modules, a dual-condition exit gate, session continuity management, rate limiting, circuit breakers, a live monitoring dashboard (ralph-monitor), an interactive project setup wizard (ralph-enable), CI/CD pipelines, and configurable tool permissions via .ralphrc. The core loop is ralph_loop.sh (bash), which calls Claude Code's CLI with --output-format json, parses structured output via lib/response_analyzer.sh, and exits only when Claude returns BOTH completion indicators AND an explicit EXIT_SIGNAL: true in a RALPH_STATUS block. It ships 9 shell scripts as global commands (ralph, ralph-monitor, ralph-setup, ralph-import, ralph-migrate, ralph-enable, ralph-enable-ci, ralph-stats, ralph_enable_ci). Compared to the snarktank original, this is Archetype 4 (markdown scaffold + scripts) escalated to near-production infrastructure. Compared to seeds, it most closely resembles claude-conductor's structured markdown scaffolding combined with spec-driver's sequential execution, but with far more operational tooling — rate limiting, circuit breakers, session management — that no seed framework provides.

01

Overview

Ralph for Claude Code — Overview

Origin

Created by frankbria (Frank Bria). Version 0.11.5. 9,205 stars, 21 contributors. Active development. Last pushed 2026-05-21.

From the README: "Ralph is an implementation of Geoffrey Huntley's technique for Claude Code that enables continuous autonomous development cycles he named after Ralph Wiggum (ghuntley.com/ralph/). It enables continuous autonomous development cycles where Claude Code iteratively improves your project until completion, with built-in safeguards to prevent infinite loops and API overuse."

Install once, use everywhere - Ralph becomes a global command available in any directory.

Philosophy

The README emphasizes production-grade safeguards that the original snarktank implementation lacks:

  1. Dual-condition exit gate: "Requires BOTH completion indicators AND explicit EXIT_SIGNAL" to prevent premature termination or infinite loops
  2. Rate limiting: 100 calls/hour with configurable hourly reset
  3. Circuit breaker: Two-stage error filtering with multi-line error matching; automatic state transitions CLOSED → HALF_OPEN → OPEN
  4. Session continuity: --resume <session_id> preserves context across iterations; configurable 24-hour expiration
  5. Live monitoring: tmux-based real-time dashboard showing loop status, progress, logs
  6. Three-layer API limit detection: timeout guard → structural JSON → filtered text fallback

Version History Philosophy

Version 0.11.5 changelog shows extensive focus on correctness bugs:

  • "Fixed API limit false positive: Timeout (exit code 124) no longer misidentified as API 5-hour limit"
  • "Fixed progress detection: Git commits within a loop now count as progress"
  • "Fixed checkbox regex: Date entries [2026-01-29] no longer counted as checkboxes"
  • "Fixed session hijacking: Use --resume instead of --continue"

This changelog pattern reveals the complexity of making an autonomous loop reliable in practice.

02

Architecture

Ralph for Claude Code — Architecture

Distribution & Install

  • Distribution type: bash-script-bundle (global install)
  • Install: git clone && ./install.sh → adds global commands to PATH
  • Version: 0.11.5
  • License: MIT
  • Required runtime: bash, Claude Code CLI (≥ 2.0.76), jq, optional: tmux, gtimeout (macOS)

Directory Tree (repo)

ralph-claude-code/
├── ralph_loop.sh           # Main autonomous loop script
├── ralph_monitor.sh        # Live monitoring dashboard
├── setup.sh                # New project initialization
├── ralph_enable.sh         # Interactive wizard for existing projects
├── ralph_enable_ci.sh      # Non-interactive CI version
├── ralph_import.sh         # PRD/spec import tool
├── ralph_stats.sh          # Statistics reporting
├── install.sh              # Global install script
├── uninstall.sh            # Clean removal
├── migrate_to_ralph_folder.sh  # v0.10 migration helper
├── lib/
│   ├── circuit_breaker.sh  # Circuit breaker pattern (CLOSED/HALF_OPEN/OPEN)
│   ├── response_analyzer.sh # JSON/text response parsing; EXIT_SIGNAL detection
│   ├── date_utils.sh       # Cross-platform date/epoch utilities
│   ├── timeout_utils.sh    # Cross-platform timeout (gtimeout on macOS)
│   ├── file_protection.sh  # Required file validation
│   ├── log_utils.sh        # Log rotation (10MB, 4 archives)
│   ├── enable_core.sh      # Shared logic for ralph-enable commands
│   ├── wizard_utils.sh     # Interactive prompt utilities
│   └── task_sources.sh     # Task import (beads, GitHub, PRD)
├── .ralph/                 # Project-specific Ralph state (generated per project)
│   ├── PROMPT.md           # Agent prompt
│   ├── logs/               # Loop logs
│   ├── .claude_session_id  # Session continuity
│   ├── .call_count         # Rate limiting counter
│   └── status.json         # Loop status
├── src/                    # TypeScript response parser (supplemental)
├── templates/              # Project templates
├── specs/                  # Feature specifications
└── tests/                  # 566 test files

Global Commands (installed to PATH)

ralph, ralph-monitor, ralph-setup, ralph-import, ralph-migrate, ralph-enable, ralph-enable-ci, ralph-stats

Target AI Tool

Claude Code exclusively. Calls claude CLI with --output-format json, --allowed-tools, --resume <session_id>.

Key Configuration

.ralphrc per-project:

  • MAX_CALLS_PER_HOUR (default: 100)
  • CLAUDE_TIMEOUT_MINUTES (default: 15)
  • CLAUDE_OUTPUT_FORMAT (default: json)
  • CLAUDE_ALLOWED_TOOLS (granular tool permissions)
  • CLAUDE_MODEL / CLAUDE_EFFORT
  • CLAUDE_SESSION_EXPIRY_HOURS (default: 24)
03

Components

Ralph for Claude Code — Components

Global CLI Commands

Command Purpose
ralph [--monitor] [--live] Run the autonomous loop
ralph --resume <session_id> Resume with session continuity
ralph --output-format json/text Output format selection
ralph --allowed-tools <list> Restrict Claude tool access
ralph --no-continue Disable session continuation
ralph-monitor tmux-based live monitoring dashboard
ralph-setup <project> Initialize new project
ralph-enable Interactive wizard for existing projects
ralph-enable-ci Non-interactive CI version of wizard
ralph-import <prd.md> Convert PRD/specs to Ralph format
ralph-migrate Migrate from pre-v0.10 structure to .ralph/
ralph-stats Show loop statistics

Library Modules (lib/)

Module Purpose
circuit_breaker.sh Three-state circuit breaker (CLOSED/HALF_OPEN/OPEN); stagnation detection
response_analyzer.sh Parse JSON and text Claude output; EXIT_SIGNAL detection; session management
date_utils.sh Cross-platform ISO timestamps and epoch calculations
timeout_utils.sh Detect and use timeout (Linux) or gtimeout (macOS)
file_protection.sh Validate required Ralph files exist before each iteration
log_utils.sh Rotate logs at 10MB, keep 4 archives
enable_core.sh Idempotency checks, project detection, template generation
wizard_utils.sh Interactive prompts for ralph-enable wizard
task_sources.sh Import from beads, GitHub Issues, or PRD markdown

Configuration Files

File Purpose
.ralph/PROMPT.md Agent prompt (generated)
.ralph/status.json Loop status
.ralph/progress.json Progress tracking
.ralph/.claude_session_id Session ID for continuity
.ralph/.call_count Rate limiting counter
.ralphrc Project-specific configuration

Exit Gate Protocol

Claude must respond with a RALPH_STATUS block:

EXIT_SIGNAL: true
STATUS: COMPLETE

The loop exits ONLY when BOTH EXIT_SIGNAL: true AND completion indicators are detected in the JSON output. In text mode, confidence_score >= 70 AND has_completion_signal=true are required.

05

Prompts

Ralph for Claude Code — Prompts

Verbatim Excerpt 1 — CLAUDE.md Agent Prompt (core task loop section)

# Ralph Agent Instructions

You are an autonomous coding agent working on a software project.

## Your Task

1. Read the PRD at `prd.json` (in the same directory as this file)
2. Read the progress log at `progress.txt` (check Codebase Patterns section first)
3. Check you're on the correct branch from PRD `branchName`. If not, check it out 
   or create from main.
4. Pick the **highest priority** user story where `passes: false`
5. Implement that single user story
6. Run quality checks (e.g., typecheck, lint, test - use whatever your project requires)
7. Update CLAUDE.md files if you discover reusable patterns (see below)
8. If checks pass, commit ALL changes with message: `feat: [Story ID] - [Story Title]`
9. Update the PRD to set `passes: true` for the completed story
10. Append your progress to `progress.txt`

Note: The frankbria version uses CLAUDE.md (not AGENTS.md) for pattern storage, reflecting a Claude Code-specific adaptation of the original.

Technique: Explicit numbered action list with Claude Code-specific context (CLAUDE.md instead of AGENTS.md), identical core loop logic to snarktank but adapted for Claude Code's file conventions.

Verbatim Excerpt 2 — Exit Signal Protocol (from lib/response_analyzer.sh behavior, documented in CLAUDE.md)

## Stop Condition

After completing a user story, check if ALL stories have `passes: true`.

If ALL stories are complete and passing, reply with:
<promise>COMPLETE</promise>

Note: The frankbria version implements a dual-condition exit gate on top of this: the RALPH_STATUS block with EXIT_SIGNAL: true is required in addition to the <promise>COMPLETE</promise> signal. The response_analyzer.sh module documents this:

In JSON mode, heuristics are suppressed entirely — only an explicit 
EXIT_SIGNAL: true in a RALPH_STATUS block can set exit_signal=true.
In text mode, exit requires confidence_score >= 70 AND 
has_completion_signal=true.

Technique: Structured stop-condition protocol designed to prevent both premature exits (false positives from completion-adjacent language) and runaway loops (missing exit signal). The dual-condition requirement is an engineering solution to a production reliability problem.

09

Uniqueness

Ralph for Claude Code — Uniqueness & Positioning

Differs from Seeds

Ralph for Claude Code is closest to spec-driver's sequential execution philosophy (one task at a time, commit per task) but operates as production infrastructure rather than a skill-pack overlay. The dual-condition exit gate (EXIT_SIGNAL + completion indicators), circuit breaker, rate limiting, and session management are engineering solutions that no seed framework addresses. Unlike snarktank/ralph's minimal bash script, this implementation rivals claude-flow in operational complexity but without an MCP server — all orchestration is external bash code calling Claude Code's CLI with structured JSON output. The tool permission system (CLAUDE_ALLOWED_TOOLS in .ralphrc) provides a security boundary analogous to kiro's hook authorization model but at the process level. The tmux monitoring dashboard is a unique operational feature not present in any seed.

Comparison with snarktank/ralph (same-batch contrast)

Dimension snarktank/ralph ralph-claude-code
Size ~200 lines bash Multi-file system, 566 tests
Context model Always fresh per iteration Session-based, configurable expiry
Exit detection <promise>COMPLETE</promise> Dual-condition (EXIT_SIGNAL + indicators)
Rate limiting None 100 calls/hour
Circuit breaker None CLOSED/HALF_OPEN/OPEN
Monitoring None tmux dashboard
Project setup Manual copy Interactive wizard (ralph-enable)
AI tools Amp (primary), Claude Code Claude Code only
Pattern storage AGENTS.md CLAUDE.md
CI support None GitHub Actions, ralph-enable-ci

Positioning

Ralph for Claude Code targets developers who want the Ralph pattern's autonomy with production-grade safeguards — rate limits, circuit breakers, session management, monitoring. It is the most operationally mature Ralph variant in the ecosystem.

Observable Failure Modes

  • bash 3.x compatibility: v0.11.5 fixed ${,,} syntax; macOS users with old bash were silently broken
  • Checkbox regex false positives: Date entries like [2026-01-29] were misidentified as task checkboxes (fixed in v0.11.4)
  • Session hijacking risk: --continue flag was deprecated because it could attach to wrong sessions (fixed to --resume <id>)
  • Circuit breaker calibration: Default thresholds may be too aggressive or too permissive for a given project's CI speed
  • Claude Code-only: Cannot be used with Amp, Cursor, or other tools

Explicit Antipatterns

  • Large tasks that exceed one context window (same as snarktank)
  • Using broad Bash(*) tool permissions instead of specific subcommands (security risk per README)
04

Workflow

Ralph for Claude Code — Workflow

Phases

Phase Description Artifact
Install (once) ./install.sh adds global commands Global PATH commands
Project init ralph-enable wizard or ralph-setup <project> .ralph/, .ralphrc, PROMPT.md
Task import (optional) ralph-import <prd.md> or wizard with beads/GitHub Task list in PROMPT.md
Loop start ralph [--monitor] Loop begins
Per-iteration: Claude invocation claude --output-format json --allowed-tools ... --resume <id> Structured JSON response
Per-iteration: Exit gate check Parse response; check EXIT_SIGNAL + completion indicators Continue/exit decision
Per-iteration: Rate limit check If > 100 calls/hour, sleep until hourly reset Rate counter
Per-iteration: Circuit breaker Check for stagnation/errors; advance state if needed CLOSED/HALF_OPEN/OPEN
Per-iteration: Progress tracking Update status.json, log files Status artifacts
Completion EXIT_SIGNAL: true + completion indicators → loop exits Final status

Phase-to-Artifact Map

Phase Artifact
Project init .ralph/PROMPT.md, .ralphrc, .ralph/status.json
Per-iteration .ralph/logs/ralph.log (rotated), .ralph/.claude_session_id
Completion .ralph/status.json (COMPLETE state)

Approval Gates

None — fully autonomous. The only human gate is the initial task definition and the .ralphrc configuration.

Session Management

  • Session IDs stored in .ralph/.claude_session_id
  • Sessions expire after 24 hours (configurable via CLAUDE_SESSION_EXPIRY_HOURS)
  • --resume <session_id> preserves context across loop iterations
  • Session auto-reset on: circuit breaker OPEN, manual interrupt, project completion
  • Session history tracked in .ralph/.ralph_session_history (last 50 transitions)

Rate Limiting

  • Default: 100 calls/hour
  • Hourly reset timer
  • 5-hour API limit handling: timeout guard → JSON rate_limit_event → filtered text
  • Unattended mode: auto-waits on API limit instead of exiting
06

Memory Context

Ralph for Claude Code — Memory & Context

State Storage

All Ralph state lives in .ralph/ within the project:

File Purpose
.ralph/PROMPT.md Agent instructions (generated by wizard)
.ralph/status.json Current loop status (RUNNING/COMPLETE/ERROR)
.ralph/progress.json Task completion tracking
.ralph/.claude_session_id Claude Code session ID for continuity
.ralph/.call_count Hourly API call counter
.ralph/.token_count Optional cumulative token counter
.ralph/.last_reset Timestamp of last hourly counter reset
.ralph/logs/ralph.log Loop execution log (rotated at 10MB)
.ralph/.ralph_session Ralph-specific session lifecycle tracking
.ralph/.ralph_session_history Session transition history (last 50)

Session Continuity

--resume <session_id> passes the stored session ID to Claude Code, preserving conversation context across loop iterations. This is the key departure from snarktank/ralph's "fresh context every iteration" philosophy — frankbria offers the option of context continuity (with a 24-hour expiration timeout).

Session auto-reset triggers:

  • Circuit breaker OPEN state
  • Manual interrupt
  • Project completion
  • Session expiry (24h default, configurable)

Cross-Session Handoff

Yes — .ralph/.claude_session_id stores the current session. Re-running ralph reads this file and resumes. Session history in .ralph_session_history tracks transitions.

Context Compaction

Handled at the session level via CLAUDE_SESSION_EXPIRY_HOURS. After expiration, a fresh session starts (equivalent to snarktank's always-fresh-context model). No token-level compaction.

Memory Compared to snarktank/ralph

Feature snarktank/ralph frankbria/ralph-claude-code
Cross-iteration context Always fresh Session-based (with expiry)
Loop state prd.json + progress.txt .ralph/status.json + progress.json
Pattern storage AGENTS.md CLAUDE.md
Rate tracking None .call_count + .token_count
07

Orchestration

Ralph for Claude Code — Orchestration

Multi-Agent Support

No — single agent per invocation. The loop calls Claude Code once per iteration. No parallel agents, no subagent delegation.

Orchestration Pattern

Sequential (continuous-ralph variant). Same story-by-story sequential pattern as snarktank/ralph, but with production-grade safeguards wrapped around it.

Execution Mode

Continuous-ralph — the loop continues autonomously until the dual-condition exit gate is satisfied, rate limits are hit, the circuit breaker opens, or the human interrupts.

Isolation Mechanism

None — Claude Code runs in the project directory without worktree isolation. However, CLAUDE_ALLOWED_TOOLS in .ralphrc provides a tool permission boundary:

CLAUDE_ALLOWED_TOOLS="Write,Read,Edit,Bash(git add *),Bash(git commit *),Bash(git diff *),..."

This prevents Claude from running destructive git commands (e.g., git clean, git rm) via the Bash tool.

Multi-Model Support

Yes — CLAUDE_MODEL and CLAUDE_EFFORT env vars / .ralphrc settings allow model and effort override. However, all iterations use the same model; no role-based routing.

Crash Recovery

Yes — .ralph/status.json and .ralph/.claude_session_id allow loop resumption. The circuit breaker prevents runaway loops; rate limiting prevents API exhaustion.

Circuit Breaker Pattern

Three states:

  1. CLOSED — normal operation
  2. HALF_OPEN — monitoring after potential stagnation
  3. OPEN — loop halted; session reset triggered

Transitions based on: consecutive no-progress iterations, repeated error patterns, question-only loops (when Claude asks questions instead of working).

Quality Gates

  • Commits within a loop iteration count as progress (resets circuit breaker)
  • API timeout (exit code 124) is NOT treated as API limit (v0.11.5 fix)
  • JSON output mode: only EXIT_SIGNAL: true triggers exit (no heuristic false positives)
08

Ui Cli Surface

Ralph for Claude Code — UI & CLI Surface

Global CLI Commands (installed)

ralph, ralph-monitor, ralph-setup, ralph-import, ralph-migrate, ralph-enable, ralph-enable-ci, ralph-stats

The ralph command is a bash script (not compiled), but it is installed globally via ./install.sh. It supports flags:

  • --monitor — starts loop inside a tmux monitoring session
  • --live — streams Claude Code output in real time
  • --resume <session_id> — resume with session continuity
  • --output-format json|text — output format
  • --allowed-tools <list> — tool permissions
  • --no-continue — disable session continuation
  • --notify — desktop notifications on completion/failure
  • --backup — automatic git backup before each loop

Live Monitoring Dashboard

ralph-monitor creates a tmux-based live dashboard showing:

  • Current loop status (RUNNING/COMPLETE/ERROR)
  • Iteration count and progress
  • Rate limit counters
  • Live log stream from .ralph/logs/ralph.log
  • Circuit breaker state

Accessed via tmux split panes. No web interface.

Interactive Setup Wizard (ralph-enable)

5-phase wizard:

  1. Environment Detection — project type (TypeScript, Python, Rust, Go), framework (Next.js, FastAPI)
  2. Task Source Selection — beads, GitHub Issues, or PRD document
  3. Configuration — model, timeout, tools
  4. File Generation — .ralph/PROMPT.md, .ralphrc, CLAUDE.md
  5. Verification — checks required files exist

CI version (ralph-enable-ci): same functionality via CLI flags, JSON output for machine parsing.

Observability

  • .ralph/logs/ralph.log — rotated execution log (10MB limit, 4 archives)
  • .ralph/status.json — machine-readable loop status
  • .ralph/.ralph_session_history — last 50 session transitions
  • ralph-stats — statistics report

Target Tool

Claude Code exclusively. Claude Code minimum version 2.0.76 is enforced at startup.

Related frameworks

same archetype · same primary tool · same memory type

Claude-Flow / Ruflo ★ 55k

Eliminates single-agent context limits and sequential bottlenecks by orchestrating fault-tolerant swarms of specialized AI agents…

Hermes Agent (NousResearch) ★ 168k

Self-improving personal AI agent with closed learning loop, 7 terminal backends, and messaging gateway — not tied to any AI…

OpenCode ★ 165k

Terminal-first AI coding agent with multi-model routing, native desktop app, and a typed .opencode/ configuration system for…

OpenHands ★ 75k

Open-source AI software development platform (open-source Devin alternative) with Docker sandbox isolation, 77.6% SWE-bench…

DeerFlow ★ 70k

Long-horizon superagent that researches, codes, and creates by orchestrating parallel sub-agents with isolated contexts in Docker…

oh-my-openagent (omo) ★ 60k

Multi-provider AI agent orchestration for OpenCode: escape vendor lock-in by routing Sisyphus (Claude/Kimi/GLM) and Hephaestus…