Architecture Overview
Relevant source files
The following files were used as context for generating this wiki page:The Ralph for Claude Code project is an autonomous AI development system built primarily on Bash scripts. It is designed to execute the Claude Code AI in a continuous loop, allowing it to iteratively develop a software project based on a set of instructions. The architecture includes robust safeguards such as rate limiting, intelligent exit detection, and a circuit breaker to prevent infinite loops and manage API usage effectively.
The system is composed of several core scripts that handle the main loop, project setup, monitoring, and requirement importation. It relies on a file-based state management system and a modular library for complex logic like response analysis and error handling. The entire system can be created from a single bootstrap script, create_files.sh, and new projects are scaffolded using setup.sh.
Core Components
The system is comprised of several key shell scripts that work together to provide the autonomous development environment. The create_files.sh script is responsible for generating all of these components.
| Component | File Path | Description |
|---|---|---|
| Ralph Loop | ralph_loop.sh | The main autonomous loop that repeatedly calls the Claude Code CLI, manages state, and checks for exit conditions. |
| Ralph Monitor | ralph_monitor.sh | A live terminal dashboard for monitoring the status of the Ralph loop, including API call counts and recent logs. |
| Project Setup | setup.sh | A script to initialize a new Ralph-managed project, creating the necessary directory structure and template files. |
| PRD Importer | ralph_import.sh | A tool to convert existing Product Requirement Documents (PRDs) into the Ralph format (PROMPT.md, @fix_plan.md) using Claude Code. |
| Bootstrap Script | create_files.sh | A script that generates the entire Ralph for Claude Code repository structure, including all core scripts and templates. |
Sources: create_files.sh, README.md, CLAUDE.md
This diagram shows the high-level interaction between the main components.
Sources: create_files.sh, ralph_loop.sh, ralph_import.sh, README.md
The Main Execution Loop (ralph_loop.sh)
The ralph_loop.sh script is the heart of the system. It runs an infinite while true loop that orchestrates the entire autonomous development process. Each iteration of the loop performs a series of checks before executing the Claude Code CLI.
The main loop flow is as follows:
- Initialize Tracking: Resets the API call counter if a new hour has started.
- Check Rate Limit: Verifies if the number of API calls is within the
MAX_CALLS_PER_HOURlimit. If the limit is reached, it waits until the next hour. - Check for Graceful Exit: Calls
should_exit_gracefully()to determine if the project is complete. If so, the loop breaks. - Update Status: Writes the current state ("executing", "running") to
status.json. - Execute Claude Code: Calls the
npx @anthropic/claude-codecommand, passing the contents ofPROMPT.mdas input. The output is saved to a timestamped log file in thelogs/directory. - Update Status on Completion/Failure: Updates
status.jsonbased on the execution result. - Pause: A brief
sleepis executed before the next loop to prevent rapid, uncontrolled iterations.
Sources: ralph_loop.sh:305-345
This flowchart illustrates the logic inside the main while loop.
Sources: ralph_loop.sh:305-345
State Management
Ralph uses a simple file-based system for managing state across loop iterations and script executions. These files are typically hidden (prefixed with a dot) or stored in a central location.
| File | Purpose |
|---|---|
status.json | A JSON file containing the real-time status of the loop, including loop count, API calls, and last action. Read by ralph_monitor.sh. |
.call_count | A plain text file containing the number of API calls made in the current hour. |
.last_reset | A plain text file with a timestamp (YYYYMMDDHH) of the last hourly counter reset. |
.exit_signals | A JSON file tracking signals that might indicate project completion, such as test-only loops or "done" signals from the AI. |
.claude_session_id | Stores the session ID from the Claude Code CLI to enable context continuity between loops. |
Sources: ralph_loop.sh:20-27, 85-103, CLAUDE.md:100-104
Intelligent Control Mechanisms
To ensure robust and safe autonomous operation, Ralph implements several control mechanisms.
Rate Limiting
To avoid exceeding API quotas, the loop includes a rate-limiting feature controlled by MAX_CALLS_PER_HOUR (default 100).
can_make_call(): Checks if$(cat .call_count)is less thanMAX_CALLS_PER_HOUR.increment_call_counter(): Increments the number in.call_count.wait_for_reset(): If the limit is reached, this function calculates the time remaining until the next hour and sleeps for that duration, providing a countdown timer to the user.
Sources: ralph_loop.sh:106-163
Graceful Exit Detection
The should_exit_gracefully() function is called at the start of each loop to determine if the project is complete. It checks for several conditions:
- Too many test-only loops: Exits if
MAX_CONSECUTIVE_TEST_LOOPS(default 3) is reached, suggesting no new implementation is happening. - Multiple "done" signals: Exits if
MAX_CONSECUTIVE_DONE_SIGNALS(default 2) is reached, based on AI output analysis. - Strong completion indicators: Exits if the AI provides strong signals of completion.
@fix_plan.mdcompletion: Exits if all tasks in the@fix_plan.mdfile are marked as complete (- [x]).
Sources: ralph_loop.sh:166-218, templates/PROMPT.md:73-83
Circuit Breaker and Response Analysis
Although the full code for lib/circuit_breaker.sh and lib/response_analyzer.sh is not provided in the context, their functionality is described in detail in other files.
lib/response_analyzer.sh: This module is responsible for parsing the output from the Claude Code CLI. It can handle both plain text and structured JSON output. It extracts key signals likestatus,exit_signal,work_type, andfiles_modified. It also manages session continuity by storing and retrieving thesessionId.lib/circuit_breaker.sh: This module implements a circuit breaker pattern to prevent runaway loops stuck on the same error. It operates in three states:CLOSED(normal),HALF_OPEN(monitoring after a fault), andOPEN(halted). It trips based on thresholds likeCB_NO_PROGRESS_THRESHOLD(no file changes) andCB_SAME_ERROR_THRESHOLD(repeated errors).
Sources: CLAUDE.md:31-62, 171-175, CONTRIBUTING.md:41-45
Project Scaffolding and Import
Ralph provides tools to simplify the creation and setup of new projects.
Project Setup (setup.sh)
The setup.sh script scaffolds a new project directory. It:
- Creates a project directory with a standard structure:
specs/,src/,examples/,logs/,docs/generated. - Copies template files (
PROMPT.md,@fix_plan.md,@AGENT.md) into the new project. - Initializes a Git repository with an initial commit.
Sources: create_files.sh:455-485, README.md:154-167
PRD Import (ralph_import.sh)
The ralph_import.sh script automates the conversion of an existing Product Requirements Document (PRD) into the Ralph format. It uses the Claude Code CLI to perform this conversion.
The process is as follows:
- The user provides a source document (e.g.,
my-prd.md). - The script calls
ralph-setupto create a new project directory. - It constructs a detailed prompt (
.ralph_conversion_prompt.md) instructing the AI to analyze the PRD and generatePROMPT.md,@fix_plan.md, andspecs/requirements.md. - It executes the Claude Code CLI, preferably using modern flags like
--output-format jsonfor reliable parsing. - The
detect_response_format()andparse_conversion_response()functions process the output to verify success and log results.
Sources: ralph_import.sh, CLAUDE.md:25-29
This sequence diagram illustrates the PRD import process.
Sources: ralph_import.sh:448-483, README.md:200-234
Template System
The templates/ directory contains the blueprint files used by setup.sh and ralph_import.sh to configure the AI's behavior for a new project.
templates/PROMPT.md: The main instruction set for the AI agent. It defines the context, objectives, key principles, and critical status reporting format that theresponse_analyzerrelies on.templates/fix_plan.md: A prioritized to-do list for the AI. The AI agent is instructed to work through these tasks and update the file as it makes progress. Theshould_exit_gracefullyfunction checks this file for completion.templates/AGENT.md: A file for the AI to maintain build, test, and run instructions for the project it is developing. It also contains quality standards for testing and Git workflows.
Sources: create_files.sh:488-608, templates/PROMPT.md, templates/fix_plan.md, templates/AGENT.md
Conclusion
The architecture of Ralph for Claude Code is a well-defined system of interconnected Bash scripts designed for autonomous software development. Its core strength lies in the simple yet powerful main loop, which is fortified by intelligent control mechanisms like rate limiting, graceful exit detection, and a circuit breaker. The file-based state management and modular library components allow for clear separation of concerns. Finally, the project scaffolding and PRD import tools provide a streamlined user experience for initiating new AI-driven development tasks.