CLI Reference: ralph_loop.sh
Relevant source files
The following files were used as context for generating this wiki page:
The ralph_loop.sh script is the core engine of the Ralph for Claude Code system. It provides an autonomous development loop that repeatedly executes the Claude Code CLI against a set of project requirements. The script is designed to run continuously, managing API rate limits, tracking progress, and intelligently determining when the project is complete to gracefully exit.
This script orchestrates the entire autonomous cycle, from reading instructions in PROMPT.md to logging outputs and updating a public status file. It integrates with other components like the ralph-monitor for live dashboards and is initialized by the ralph-setup command for new projects.
Sources: create_files.sh:10-12, README.md:15-18, CLAUDE.md:8-9
Usage and Options
The script is executed via the ralph command, which is a globally installed wrapper. It accepts several command-line flags to configure its behavior.
Sources: create_files.sh:413-455, README.md:329-344
Command-Line Arguments
| Flag (Short) | Flag (Long) | Parameter | Description | Default Value |
|---|---|---|---|---|
-h | --help | - | Show the help message and exit. | - |
-c | --calls | NUM | Set the maximum number of Claude Code API calls per hour. | 100 |
-p | --prompt | FILE | Specify the path to the prompt file. | PROMPT.md |
-s | --status | - | Display the current status from status.json and exit. | - |
-m | --monitor | - | Start with a tmux session and live monitor. | - |
-v | --verbose | - | Show detailed progress updates during execution. | - |
-t | --timeout | MIN | Set the Claude Code execution timeout in minutes (1-120). | 15 |
--output-format | FORMAT | Set the output format (json or text). | json | |
--allowed-tools | TOOLS | Set allowed Claude tools. | Write,Bash(git *),Read | |
--no-continue | - | Disable session continuity for isolated loops. | - | |
--reset-circuit | - | Reset the circuit breaker state. | - | |
--circuit-status | - | Show the circuit breaker status. | - | |
--reset-session | - | Reset the session state manually. | - |
Sources: create_files.sh:413-455, README.md:329-344
Argument Parsing Flow
The following diagram illustrates how command-line arguments are parsed when the script starts.
This diagram shows the argument parsing logic within ralph_loop.sh.
Sources: create_files.sh:413-455
Core Architecture
The script's architecture is centered around a main while loop that orchestrates the entire autonomous development process.
Sources: create_files.sh:329-386
Main Loop
The main function contains an infinite while true loop that represents one full cycle of development. Each iteration performs the following steps:
- Initialization: Increments the loop counter and initializes API call tracking for the current hour.
- Rate Limit Check: Verifies if the number of API calls has exceeded the hourly limit using
can_make_call. If the limit is reached, it callswait_for_resetand continues to the next iteration. - Graceful Exit Check: Calls
should_exit_gracefullyto determine if the project is complete. If so, it breaks the loop. - Status Update: Updates
status.jsonto "executing". - Execution: Calls
execute_claude_codeto run the Claude Code CLI. - Post-Execution: Updates
status.jsonbased on the execution result (success or error) and sleeps for a short duration before the next loop.
This flow is illustrated in the diagram below.
This diagram shows the primary execution flow within the main function of ralph_loop.sh.
Sources: create_files.sh:329-386
Signal Handling
The script uses a trap to catch SIGINT and SIGTERM signals (e.g., from Ctrl+C). When a signal is caught, the cleanup function is executed, which updates the status to "interrupted" before exiting.
Sources: create_files.sh:322-327
Configuration
The script's behavior is controlled by a combination of shell variables, configuration files, and state-tracking files.
Configuration Variables
These variables are defined at the top of the script and can be overridden by command-line arguments.
| Variable | Description | Default Value |
|---|---|---|
PROMPT_FILE | The main prompt file for Claude Code. | "PROMPT.md" |
LOG_DIR | Directory to store execution logs. | "logs" |
DOCS_DIR | Directory for generated documentation. | "docs/generated" |
STATUS_FILE | JSON file for external status monitoring. | "status.json" |
CLAUDE_CODE_CMD | The command to execute the Claude Code CLI. | "npx @anthropic/claude-code" |
MAX_CALLS_PER_HOUR | Hourly API call limit. | 100 |
EXIT_SIGNALS_FILE | JSON file for tracking exit signals. | ".exit_signals" |
MAX_CONSECUTIVE_TEST_LOOPS | Exit if this many consecutive loops are test-only. | 3 |
MAX_CONSECUTIVE_DONE_SIGNALS | Exit if this many "done" signals are received. | 2 |
Sources: create_files.sh:15-31
Control & State Files
The loop reads from and writes to several files to manage its state and configuration.
| File Path | Purpose |
|---|---|
PROMPT.md | (Input) The main instructions for the AI agent. |
@fix_plan.md | (Input) A prioritized list of tasks. The script checks this for completion. |
status.json | (Output) A JSON file containing the real-time status of the loop. |
.call_count | (State) A hidden file storing the number of API calls made in the current hour. |
.last_reset | (State) A hidden file storing the timestamp of the last rate-limit counter reset. |
.exit_signals | (State) A hidden JSON file tracking signals that might trigger a graceful exit. |
logs/ralph.log | (Output) A central log file for all status messages. |
logs/claude_output_*.log | (Output) Timestamped logs of the raw output from each Claude Code execution. |
Sources: create_files.sh:15-31, README.md:297-308, CLAUDE.md:105-113
Rate Limiting
The script includes a robust mechanism to avoid exceeding API rate limits. This is managed by a set of dedicated functions and tracking files.
Sources: create_files.sh:110-181
Rate Limiting Flow
The following diagram shows how a rate limit check is performed.
This sequence diagram illustrates the rate limiting logic, including checking, waiting, and resetting the call counter.
Sources: create_files.sh:110-181
Key Functions
init_call_tracking(): Initializes or resets the call counter (.call_count) at the beginning of a new hour.can_make_call(): Returns0(true) if the current call count is less thanMAX_CALLS_PER_HOUR, and1(false) otherwise.increment_call_counter(): Increments the value in.call_count.wait_for_reset(): Calculates the remaining time until the next hour, displays a countdown, and sleeps until the rate limit window resets.
Sources: create_files.sh:49-71, 110-181
Intelligent Exit Detection
A key feature of ralph_loop.sh is its ability to stop automatically when it determines the project is complete. This logic is encapsulated in the should_exit_gracefully function.
Sources: create_files.sh:184-243
Exit Conditions
The script will trigger a graceful exit if any of the following conditions are met:
- Test Saturation: The number of recent test-only loops reaches
MAX_CONSECUTIVE_TEST_LOOPS. This suggests no new features are being implemented. - Completion Signals: The number of "done" signals from the AI reaches
MAX_CONSECUTIVE_DONE_SIGNALS. - Strong Indicators: The number of strong completion indicators (a separate signal type) reaches
2. - Plan Completion: All checklist items in the
@fix_plan.mdfile are marked as complete (- [x]).
The .exit_signals file stores a JSON object that tracks the history of these signals from recent loops.
Sources: create_files.sh:184-243, README.md:144-150
Exit Logic Flow
This diagram outlines the decision-making process for the graceful exit feature.
Sources: create_files.sh:184-243
State and Logging
The script maintains its state and provides detailed logging for monitoring and debugging.
Status File (status.json)
The status.json file provides a real-time, machine-readable summary of the loop's state. It is updated at various points in each loop.
| Field | Type | Description |
|---|---|---|
timestamp | string | ISO 8601 timestamp of the last update. |
loop_count | number | The current loop iteration number. |
calls_made_this_hour | number | API calls used in the current hourly window. |
max_calls_per_hour | number | The configured maximum calls per hour. |
last_action | string | The last major action performed (e.g., "executing", "completed"). |
status | string | The current high-level status (e.g., "running", "stopped", "error"). |
exit_reason | string | If exited gracefully, the reason for stopping. |
next_reset | string | The time for the next hourly rate-limit reset. |
Sources: create_files.sh:86-100, tests/helpers/fixtures.bash:204-216
Logging
- Console Output: The script prints color-coded status messages to the terminal for real-time feedback.
logs/ralph.log: All status messages are appended to this file with timestamps and log levels (INFO,WARN,ERROR,SUCCESS,LOOP).logs/claude_output_*.log: The rawstdoutandstderrfrom everyclaude-codecommand execution are saved to a unique, timestamped file in this directory. This is crucial for debugging AI behavior.
The log_status function is responsible for handling all logging.
Sources: create_files.sh:74-83, 260-277
Summary
ralph_loop.sh is the autonomous heart of the Ralph for Claude Code project. It provides a structured, resilient, and intelligent loop for AI-driven software development. Its key features—configurable execution, robust rate limiting, intelligent completion detection, and comprehensive status reporting—make it a powerful tool for automating coding tasks. The script is designed for both interactive use with its colorful console output and for integration into larger automated systems via the status.json file.
Sources: create_files.sh, README.mdThinking Process:
-
Deconstruct the Request:
- Role: Expert code analyst and technical writer.
- Task: Create a comprehensive technical wiki page in Markdown.
- Topic:
CLI Reference: ralph_loop.sh. - Source Files: Must use at least 5 files from the provided context. The initial list has only one (
ralph_loop.sh), so I need to find more. - Critical Start Instruction: The response must begin with a
<details>block listing the source files. No preamble. - Heading: The main title must be
# CLI Reference: ralph_loop.sh. - Content Structure:
- Introduction (1-2 paragraphs).
- Detailed Sections (H2/H3 headings).
- Extensive use of Mermaid diagrams.
- Use of Markdown tables.
- Optional code snippets.
- Crucial: Cite sources for every piece of information with
Sources: [filename:line-range](https://github.com/Alonso-pixel/ralph-claude-code/blob/HEAD/filename%3Aline-range).
- Technical Accuracy: Information must be solely from the provided files. No external knowledge.
- Style: Direct, concise, professional, technical.
- Language: English.
-
File Selection Strategy:
- The user provided
ralph_loop.sh. However, the source filecreate_files.shliterally contains the entire source code forralph_loop.shwithin acatheredoc. This makescreate_files.shthe most authoritative source for the script's content. I will use it as my primary source. - I need at least 4 more files. I'll scan the provided file list for relevance to
ralph_loop.sh.README.md: Excellent source. It has a "Command Reference" section, feature descriptions, and high-level explanations of how the loop works (rate limiting, exit detection).CLAUDE.md: Also excellent. It's a technical guide for the AI, detailing the architecture, core scripts (ralph_loop.shis listed first), configuration, and exit conditions.install.sh: Relevant. It shows howralph_loop.shis installed globally, how its path is modified for global use, and how theralphcommand wrapper is created.CONTRIBUTING.md: Good for context. It describes the project structure and development workflow, placingralph_loop.shas a "Main loop script".ralph_import.sh: Shows interaction. It sets up a project directory whereralph_loop.shwould then be run. It's a good secondary source for ecosystem context.tests/helpers/fixtures.bash: Very useful. It contains functions to create sample files thatralph_loop.shinteracts with, likestatus.jsonand@fix_plan.md. This gives me concrete examples of the data structures.TESTING.md: Describes how the system, including the loop, is tested. Less about the loop's functionality and more about its validation, but still relevant.
- Final Selection (to meet the >=5 requirement):
create_files.sh(Primary source for the code itself)README.md(User-facing documentation and CLI reference)CLAUDE.md(Technical architecture and specifications)install.sh(Installation and global context)CONTRIBUTING.md(Project structure and role of the script)ralph_import.sh(Ecosystem interaction)tests/helpers/fixtures.bash(Data structure examples)
- This is a strong set of 7 files that will allow for a comprehensive and well-cited document.
- The user provided
-
Structuring the Wiki Page (Mental Outline):
<details>block: List the 7 selected files.- H1:
# CLI Reference: ralph_loop.sh - Introduction:
- What is it? The core autonomous loop.
- What does it do? Executes Claude, manages limits, tracks progress, exits intelligently.
- How does it fit in? Works with
ralph-monitor, set up byralph-setup. - Cite
create_files.sh,README.md,CLAUDE.md.
- Section: Usage and Options:
- Create a table for CLI flags. I'll pull these from the
show_helpfunction increate_files.shand the command reference inREADME.md. TheREADMEhas more modern flags (--monitor,--timeout, etc.) that aren't in theshow_helpfunction increate_files.sh, so I'll merge them. - Create a Mermaid flowchart for argument parsing logic based on the
whileloop at the end ofcreate_files.sh. - Cite
create_files.shandREADME.md.
- Create a table for CLI flags. I'll pull these from the
- Section: Core Architecture:
- Focus on the
mainfunction and thewhile trueloop. - Create a detailed Mermaid flowchart of the loop's logic: init, check calls, check exit, execute, handle result, sleep, repeat.
- Mention the
trapforcleanup. - Cite
create_files.sh.
- Focus on the
- Section: Configuration:
- Table for shell variables (
PROMPT_FILE,LOG_DIR, etc.) from the top of the script increate_files.sh. - Table for control/state files (
PROMPT.md,status.json,.call_count, etc.). - Cite
create_files.sh,README.md,CLAUDE.md.
- Table for shell variables (
- Section: Rate Limiting:
- Explain the concept.
- List the key functions:
init_call_tracking,can_make_call,increment_call_counter,wait_for_reset. - Create a Mermaid
sequenceDiagramto show the interaction between the loop, the functions, and the filesystem files (.call_count). - Cite
create_files.sh.
- Section: Intelligent Exit Detection:
- Explain the
should_exit_gracefullyfunction. - List the specific conditions (test loops, done signals, plan completion) from the code.
- Create a Mermaid flowchart for this decision logic.
- Cite
create_files.shandREADME.md.
- Explain the
- Section: State and Logging:
- Describe
status.json. Usecreate_files.sh(theupdate_statusfunction) andtests/helpers/fixtures.bash(for a concrete example) to build a table of its fields. - Explain the
log_statusfunction and the different log files (ralph.log,claude_output_*.log). - Cite
create_files.sh.
- Describe
- Conclusion: A brief summary paragraph reiterating the script's importance.
-
Drafting and Citing (Iterative Process):
- I'll write each section, keeping the source files open.
- For each paragraph, table, or diagram, I'll immediately add the citation. This is critical.
- Example: When writing about
MAX_CALLS_PER_HOUR, I'll find the line increate_files.shwhere it's defined (MAX_CALLS_PER_HOUR=100) and citeSources: [create_files.sh:20](https://github.com/Alonso-pixel/ralph-claude-code/blob/HEAD/create_files.sh#L20). - Mermaid Diagrams: I'll draft the Mermaid syntax in a text editor to ensure it's correct before embedding it. I'll keep the nodes concise and use
flowchart TDfor top-down flow. - Tables: I'll use Markdown table syntax. For the CLI options, I'll combine information from
create_files.sh'sshow_helpandREADME.md's reference for a complete list. - Review and Refine: After drafting, I'll re-read the entire document to check for flow, clarity, and accuracy. I'll double-check that every claim is backed by a citation and that I've used at least 5 different source files. I've planned to use 7, so that's covered. The language will be kept formal and technical. I will ensure there is no preamble before the
<details>block.
This systematic approach ensures all constraints of the prompt are met, resulting in a high-quality, accurate, and well-structured technical document.