Sandbox
@Th0rgal/open-ralph-wiggum

CLI loop for Claude Code, Codex, and OpenCode

Open Ralph Wiggum runs an agent in a repeated prompt loop so the codebase changes from one pass to the next. It supports Claude Code, Codex, Copilot CLI, Cursor Agent, Qwen Code, and OpenCode, with flags for iteration limits, task tracking, status checks, and prompt files.

1,885 stars142 forksTypeScriptUpdated 3mo ago
Who it's for

Builders who want an agent to keep iterating on a coding task while they watch progress from another terminal.

What it delivers

You can hand off a task and come back to code that has been revised, tested, and driven toward a clear completion signal.

What it does

Multi-agent loop

Runs the same workflow with `--agent claude-code`, `codex`, `copilot`, `cursor-agent`, `qwen-code`, or `opencode`.

Task mode

Stores a task list in `.ralph/ralph-tasks.md` and works through one task at a time.

Status monitoring

`ralph --status` shows the active loop, recent iterations, and struggle indicators.

Prompt file support

Reads a task from a file with `--prompt-file`, `--file`, or `-f`.

Codex goal mode

Can send Codex a `/goal` prompt through the `--codex-goal` and `--codex-backend` options.

Mid-loop context

Adds hints for the next iteration with `ralph --add-context "..."` and clears them with `--clear-context`.

How to get it

  1. 1Run
    npm install -g @th0rgal/ralph-wiggum
  2. 2Run
    bun add -g @th0rgal/ralph-wiggum
  3. 3Run
    git clone https://github.com/Th0rgal/open-ralph-wiggum
    cd open-ralph-wiggum
    ./install.sh
  4. 4Run
    git clone https://github.com/Th0rgal/open-ralph-wiggum
    cd open-ralph-wiggum
    .\install.ps1

README

Open Ralph Wiggum

Autonomous Agentic Loop for Claude Code, Codex, Copilot CLI, Cursor Agent, Qwen Code & OpenCode

Open Ralph Wiggum - Iterative AI coding loop for multiple AI coding agents

Works with Claude Code, OpenAI Codex, Copilot CLI, Cursor Agent, Qwen Code, and OpenCode — switch agents with --agent.
Based on the Ralph Wiggum technique by Geoffrey Huntley

MIT License Built with Bun + TypeScript Release

Supported AgentsWhat is Ralph?InstallationQuick StartCommands

Tired of agents breaking your local environment?
🏝️ sandboxed.sh gives each task an isolated Linux workspace. Self-hosted. Git-backed.

💬 Join the community: relens.ai/community


Supported Agents

Open Ralph Wiggum works with multiple AI coding agents. Switch between them using the --agent flag:

AgentFlagDescription
Claude Code--agent claude-codeAnthropic's Claude Code CLI for autonomous coding
Codex--agent codexOpenAI's Codex CLI for AI-powered development
Copilot CLI--agent copilotGitHub Copilot CLI for agentic coding
Cursor Agent--agent cursor-agentCursor Agent CLI for headless AI coding
Qwen Code--agent qwen-codeAlibaba's Qwen Code CLI for headless AI coding
OpenCode--agent opencodeDefault agent, open-source AI coding assistant
# Use Claude Code
ralph "Build a REST API" --agent claude-code --max-iterations 10

# Use OpenAI Codex
ralph "Create a CLI tool" --agent codex --max-iterations 10

# Use Copilot CLI
ralph "Refactor the auth module" --agent copilot --max-iterations 10

# Use Cursor Agent
ralph "Add unit tests" --agent cursor-agent --max-iterations 10

# Use Qwen Code
ralph "Add unit tests" --agent qwen-code --max-iterations 10

# Use OpenCode (default)
ralph "Fix the failing tests" --max-iterations 10

What is Open Ralph Wiggum?

Open Ralph Wiggum implements the Ralph Wiggum technique — an autonomous agentic loop where an AI coding agent (Claude Code, Codex, Copilot CLI, Cursor Agent, Qwen Code, or OpenCode) receives the same prompt repeatedly until it completes a task. Each iteration, the AI sees its previous work in files and git history, enabling self-correction and incremental progress.

This is a CLI tool that wraps any supported AI coding agent in a persistent development loop. No plugins required — just install and run.

# The essence of the Ralph loop:
while true; do
  claude-code "Build feature X. Output <promise>DONE</promise> when complete."  # or codex, copilot, cursor-agent, qwen, opencode
done

Why this works: The AI doesn't talk to itself between iterations. It sees the same prompt each time, but the codebase has changed from previous iterations. This creates a powerful feedback loop where the agent iteratively improves its work until all tests pass.

Multi-Agent Flexibility

Switch between AI coding agents without changing your workflow:

  • Claude Code (--agent claude-code) — Anthropic's powerful coding agent
  • Codex (--agent codex) — OpenAI's code-specialized model
  • Copilot CLI (--agent copilot) — GitHub's agentic coding tool
  • Cursor Agent (--agent cursor-agent) — Cursor's headless AI coding agent
  • Qwen Code (--agent qwen-code) — Alibaba's Qwen Code headless CLI agent
  • OpenCode (--agent opencode) — Open-source default option

Key Features

  • Multi-Agent Support — Use Claude Code, Codex, Copilot CLI, Cursor Agent, Qwen Code, or OpenCode with the same workflow
  • Self-Correcting Loops — Agent sees its previous work and fixes its own mistakes
  • Autonomous Execution — Set it running and come back to finished code
  • Task Tracking — Built-in task management with --tasks mode
  • Live Monitoring — Check progress with --status from another terminal
  • Mid-Loop Hints — Inject guidance with --add-context without stopping

Why Use an Agentic Loop?

BenefitHow it works
Self-CorrectionAI sees test failures from previous runs, fixes them
PersistenceWalk away, come back to completed work
IterationComplex tasks broken into incremental progress
AutomationNo babysitting—loop handles retries
ObservabilityMonitor progress with --status, see history and struggle indicators
Mid-Loop GuidanceInject hints with --add-context without stopping the loop

Installation

Prerequisites:

npm (recommended)

npm install -g @th0rgal/ralph-wiggum

Bun

bun add -g @th0rgal/ralph-wiggum

From source

git clone https://github.com/Th0rgal/open-ralph-wiggum
cd open-ralph-wiggum
./install.sh
git clone https://github.com/Th0rgal/open-ralph-wiggum
cd open-ralph-wiggum
.\install.ps1

This installs the ralph CLI command globally.

Quick Start

# Simple task with iteration limit
ralph "Create a hello.txt file with 'Hello World'. Output <promise>DONE</promise> when complete." \
  --max-iterations 5

# Build something real
ralph "Build a REST API for todos with CRUD operations and tests. \
  Run tests after each change. Output <promise>COMPLETE</promise> when all tests pass." \
  --max-iterations 20

# Use Claude Code instead of OpenCode
ralph "Create a small CLI and document usage. Output <promise>COMPLETE</promise> when done." \
  --agent claude-code --model claude-sonnet-4 --max-iterations 5

# Use Codex instead of OpenCode
ralph "Create a small CLI and document usage. Output <promise>COMPLETE</promise> when done." \
  --agent codex --model gpt-5-codex --max-iterations 5

# Use Codex goal mode through OMX: Ralph owns cross-iteration retries, /goal owns one iteration
RALPH_CODEX_GOAL=1 RALPH_CODEX_BACKEND=omx \
ralph "Complete the task described in .harness/goal.md. Output <promise>COMPLETE</promise> when everything passes." \
  --agent codex --max-iterations 5

# Use Copilot CLI
ralph "Create a small CLI and document usage. Output <promise>COMPLETE</promise> when done." \
  --agent copilot --max-iterations 5

# Use Qwen Code
ralph "Create a small CLI and document usage. Output <promise>COMPLETE</promise> when done." \
  --agent qwen-code --max-iterations 5

# Complex project with Tasks Mode
ralph "Build a full-stack web application with user auth and database" \
  --tasks --max-iterations 50

Environment Variables

Configure agent binaries with these environment variables:

VariableDescriptionDefault
RALPH_OPENCODE_BINARYPath to OpenCode CLI"opencode"
RALPH_CLAUDE_BINARYPath to Claude Code CLI"claude"
RALPH_CODEX_BINARYPath to Codex CLI"codex"
RALPH_CODEX_GOALEnable Codex goal mode for --agent codex (1, true, yes, on)unset
RALPH_CODEX_BACKENDGoal-mode backend: codex or omxdetected from configured codex command
RALPH_CODEX_GOAL_NATIVEForce native /goal attempt even when support is not pre-confirmedunset
OMX_RALPH_OMX_BINPath to OMX CLI when RALPH_CODEX_BACKEND=omx"omx"
OMX_RALPH_REASONINGmodel_reasoning_effort passed to omx exec in goal mode"high"
RALPH_COPILOT_BINARYPath to Copilot CLI"copilot"
RALPH_CURSOR_AGENT_BINARYPath to Cursor Agent CLI"cursor-agent"
RALPH_QWEN_CODE_BINARYPath to Qwen Code CLI"qwen"

Note for Windows users: Ralph automatically resolves .cmd extensions for npm-installed CLIs. If you encounter "command not found" errors, you can use these environment variables to specify the full path to the executable.

Commands

Running a Loop

ralph "<prompt>" [options]

Options:
  --agent AGENT            AI agent to use: opencode (default), claude-code, codex, copilot, cursor-agent, qwen-code
  --codex-goal             Run Codex iterations in goal mode; final Codex/OMX prompt starts with /goal
  --codex-backend BACKEND  Backend for --codex-goal: codex or omx (default: detect)
  --codex-goal-native      Force a native /goal attempt even when backend support is unconfirmed
  --min-iterations N       Minimum iterations before completion allowed (default: 1)
  --max-iterations N       Stop after N iterations (default: unlimited)
  --completion-promise T   Text that signals completion (default: COMPLETE)
  --abort-promise TEXT     Phrase that signals early abort (e.g., precondition failed)
  --tasks, -t              Enable Tasks Mode for structured task tracking
  --task-min-iterations N   Require each top-level task to receive N Ralph iterations before completion (default: 1)
  --task-promise T         Text that signals task completion (default: READY_FOR_NEXT_TASK)
  --model MODEL            Model to use (agent-specific)
  --rotation LIST          Agent/model rotation for each iteration (comma-separated)
  --prompt-file, --file, -f  Read prompt content from a file
  --prompt-template PATH   Use custom prompt template (see Custom Prompts)
  --no-stream              Buffer agent output and print at the end
  --verbose-tools          Print every tool line (disable compact tool summary)
  --questions              Enable interactive question handling (default: enabled)
  --no-questions           Disable interactive question handling (agent will loop on questions)
  --no-plugins             Disable non-auth OpenCode plugins for this run (opencode only)
  --no-commit              Don't auto-commit after iterations
  --allow-all              Auto-approve all tool permissions (default: on)
  --no-allow-all           Require interactive permission prompts
  --config PATH            Use custom agent config file
  --init-config [PATH]     Write default agent config to PATH and exit
  --help                   Show help

Codex / OMX Goal Mode

--codex-goal is an opt-in mode for --agent codex. Open Ralph still owns the outer loop: max iterations, process restarts, promise detection, .ralph/ralph-history.json, git/file-system state, and optional auto-commits. Inside each Ralph iteration, the Codex backend receives a final prompt whose first token is /goal, so Codex goal mode can own the single-session push for that iteration.

ralph \
  "Complete the task in .harness/goal.md. Run .harness/checks.sh. Output <promise>COMPLETE</promise> when everything passes." \
  --agent codex \
  --codex-goal \
  --codex-backend omx \
  --max-iterations 5

Equivalent environment form:

RALPH_CODEX_GOAL=1 RALPH_CODEX_BACKEND=omx ralph \
  "Complete the task in .harness/goal.md. Run .harness/checks.sh. Output <promise>COMPLETE</promise> when everything passes." \
  --agent codex \
  --max-iterations 5

Goal-mode iterations write a small durable audit ledger to .ralph/codex-goal-ledger.jsonl. This is intentionally file-system state, not Codex thread state, so later Ralph iterations can start fresh while retaining repo-native progress evidence. If native /goal cannot be pre-confirmed, Ralph prints an explicit warning; simulated fallback is used only when native Codex goal support is not available for the selected backend.

Tasks Mode

Tasks Mode allows you to break complex projects into smaller, manageable tasks. Ralph works on one task at a time and tracks progress in a markdown file.

# Enable Tasks Mode
ralph "Build a complete web application" --tasks --max-iterations 20

# Custom task completion signal
ralph "Multi-feature project" --tasks --task-promise "TASK_DONE"

# Require each top-level task to receive three Ralph iterations before task/final completion
ralph "Multi-feature project" --tasks --task-min-iterations 3 --max-iterations 20

Task Management Commands

# List current tasks
ralph --list-tasks

# Add a new task
ralph --add-task "Implement user authentication"

# Remove task by index
ralph --remove-task 3

# Show status (tasks shown automatically when tasks mode is active)
ralph --status

How Tasks Mode Works

  1. Task File: Tasks are stored in .ralph/ralph-tasks.md
  2. One Task Per Iteration: Ralph focuses on a single task to reduce confusion
  3. Automatic Progression: When a task completes (<promise>READY_FOR_NEXT_TASK</promise>), Ralph moves to the next eligible task
  4. Task Minimum Iterations: --task-min-iterations N requires every top-level task to receive N Ralph outer-loop iterations before task or final completion is accepted. This is separate from global --min-iterations, which gates the whole run.
  5. Task Ledger Fallback: With task minimums enabled, if the selected top-level task is already [x] with all subtasks [x] after its required iterations, Ralph advances from the task ledger even if the agent forgets to emit READY_FOR_NEXT_TASK
  6. Persistent State: Tasks survive loop restarts; per-task attempt counts are stored in .ralph/ralph-task-runs.json when task minimums are enabled
  7. Focused Context: Smaller contexts per iteration reduce costs and improve reliability

Task status indicators:

  • [ ] - Not started
  • [/] - In progress
  • [x] - Complete

Example task file:

# Ralph Tasks

- [ ] Set up project structure
- [x] Initialize git repository
- [/] Implement user authentication
  - [ ] Create login page
  - [ ] Add JWT handling
- [ ] Build dashboard UI

Custom Prompt Templates

You can fully customize the prompt sent to the agent using --prompt-template. This is useful for integrating with custom workflows or tools.

ralph "Build a REST API" --prompt-template ./my-template.md

Available variables:

VariableDescription
{{iteration}}Current iteration number
{{max_iterations}}Maximum iterations (or "unlimited")
{{min_iterations}}Minimum iterations
{{prompt}}The user's task prompt
{{completion_promise}}Completion promise text (e.g., "COMPLETE")
{{abort_promise}}Abort promise text (if configured)
{{task_promise}}Task promise text (for tasks mode)
{{task_min_iterations}}Configured per-task minimum Ralph iterations (for tasks mode)
{{task_id}}Current selected top-level task id when task-min tracking is active
{{task_text}}Current selected top-level task text when task-min tracking is active
{{task_attempt}}Current selected task attempt count when task-min tracking is active
{{task_min_required}}Required attempts for the current selected task
{{task_can_complete}}true when the selected task has met its task minimum
{{task_gate_instruction}}Ready-to-embed task-min guidance for custom templates
{{context}}Additional context added mid-loop
{{tasks}}Task list content (for tasks mode)

Example template (my-template.md):

# Iteration {{iteration}} / {{max_iterations}}

## Task
{{prompt}}

## Instructions
1. Check beads for current status
2. Decide what to do next
3. When the epic in beads is complete, output:
   <promise>{{completion_promise}}</promise>

{{context}}

Monitoring & Control

# Check status of active loop (run from another terminal)
ralph --status

# Add context/hints for the next iteration
ralph --add-context "Focus on fixing the auth module first"

# Clear pending context
ralph --clear-context

Status Dashboard

The --status command shows:

  • Active loop info: Current iteration, elapsed time, prompt
  • Pending context: Any hints queued for next iteration
  • Current tasks: Automatically shown when tasks mode is active (or use --tasks)
  • Iteration history: Last 5 iterations with tools used, duration
  • Struggle indicators: Warnings if agent is stuck (no progress, repeated errors)
╔══════════════════════════════════════════════════════════════════╗
║                    Ralph Wiggum Status                           ║
╚══════════════════════════════════════════════════════════════════╝

🔄 ACTIVE LOOP
   Iteration:    3 / 10
   Elapsed:      5m 23s
   Promise:      COMPLETE
   Prompt:       Build a REST API...

📊 HISTORY (3 iterations)
   Total time:   5m 23s

   Recent iterations:
   🔄 #1: 2m 10s | Bash:5 Write:3 Read:2
   🔄 #2: 1m 45s | Edit:4 Bash:3 Read:2
   🔄 #3: 1m 28s | Bash:2 Edit:1

⚠️  STRUGGLE INDICATORS:
   - No file changes in 3 iterations
   💡 Consider using: ralph --add-context "your hint here"

Mid-Loop Context Injection

Guide a struggling agent without stopping the loop:

# In another terminal while loop is running
ralph --add-context "The bug is in utils/parser.ts line 42"
ralph --add-context "Try using the singleton pattern for config"

Context is automatically consumed after one iteration.

Troubleshooting

Plugin errors

This package is CLI-only. If OpenCode tries to load a ralph-wiggum or open-ralph-wiggum plugin, remove it from your OpenCode plugin list (opencode.json), or run:

ralph "Your task" --no-plugins

ProviderModelNotFoundError / Model not configured

If you see ProviderModelNotFoundError or "Provider returned error", you need to configure a default model:

For OpenCode:

  1. Edit ~/.config/opencode/opencode.json:
    {
      "$schema": "https://opencode.ai/config.json",
      "model": "your-provider/model-name"
    }
    
  2. Or use the --model flag: ralph "task" --model provider/model

For other agents: Use the --model flag to specify the model explicitly.

"command not found" on Windows

Ralph automatically tries .cmd extensions on Windows. If you still have issues:

  1. Set the full path using environment variables:
    $env:RALPH_OPENCODE_BINARY = "C:\path\to\opencode.cmd"
    
  2. Or add the CLI to your PATH

"bun: command not found"

Install Bun: https://bun.sh

Writing Good Prompts

Include Clear Success Criteria

❌ Bad:

Build a todo API

✅ Good:

Build a REST API for todos with:
- CRUD endpoints (GET, POST, PUT, DELETE)
- Input validation
- Tests for each endpoint

Run tests after changes. Output <promise>COMPLETE</promise> when all tests pass.

Use Verifiable Conditions

❌ Bad:

Make the code better

✅ Good:

Refactor auth.ts to:
1. Extract validation into separate functions
2. Add error handling for network failures
3. Ensure all existing tests still pass

Output <promise>DONE</promise> when refactored and tests pass.

Always Set Max Iterations

# Safety net for runaway loops
ralph "Your task" --max-iterations 20

Recommended PRD Format

Ralph treats prompt files as plain text, so any format works. For best results, use a concise PRD with:

  • Goal: one sentence summary of the desired outcome
  • Scope: what is in/out
  • Requirements: numbered, testable items
  • Constraints: tech stack, performance, security, compatibility
  • Acceptance criteria: explicit success checks
  • Completion promise: include <promise>COMPLETE</promise> (or match your --completion-promise)

Example (Markdown):

# PRD: Add Export Button

## Goal
Let users export reports as CSV from the dashboard.

## Scope
- In: export current report view
- Out: background exports, scheduling

## Requirements
1. Add "Export CSV" button to dashboard header.
2. CSV includes columns: date, revenue, sessions.
3. Works for reports up to 10k rows.

## Constraints
- Keep current UI styling.
- Use existing CSV utility in utils/csv.ts.

## Acceptance Criteria
- Clicking button downloads a valid CSV.
- CSV opens cleanly in Excel/Sheets.
- All existing tests pass.

## Completion Promise
<promise>COMPLETE</promise>

JSON Feature List (Recommended for Complex Projects)

For larger projects, a structured JSON feature list works better than prose. Based on Anthropic's research on effective agent harnesses, JSON format reduces the chance of agents inappropriately modifying test definitions.

Create a features.json file:

{
  "features": [
    {
      "category": "functional",
      "description": "Export button downloads CSV with current report data",
      "steps": [
        "Navigate to dashboard",
        "Click 'Export CSV' button",
        "Verify CSV file downloads",
        "Open CSV and verify columns: date, revenue, sessions",
        "Verify data matches displayed report"
      ],
      "passes": false
    },
    {
      "category": "functional",
      "description": "Export handles large reports up to 10k rows",
      "steps": [
        "Load report with 10,000 rows",
        "Click 'Export CSV' button",
        "Verify export completes without timeout",
        "Verify all rows present in CSV"
      ],
      "passes": false
    },
    {
      "category": "ui",
      "description": "Export button matches existing dashboard styling",
      "steps": [
        "Navigate to dashboard",
        "Verify button uses existing button component",
        "Verify button placement in header area"
      ],
      "passes": false
    }
  ]
}

Then reference it in your prompt:

Read features.json for the feature list. Work through each feature one at a time.
After verifying a feature works end-to-end, update its "passes" field to true.
Do NOT modify the description or steps - only change the passes boolean.
Output <promise>COMPLETE</promise> when all features pass.

Why JSON? Agents are less likely to inappropriately modify JSON test definitions compared to Markdown. The structured format keeps agents focused on implementation rather than redefining success criteria.

When to Use Ralph

Good for:

  • Tasks with automatic verification (tests, linters, type checking)
  • Well-defined tasks with clear completion criteria
  • Greenfield projects where you can walk away
  • Iterative refinement (getting tests to pass)

Not good for:

  • Tasks requiring human judgment
  • One-shot operations
  • Unclear success criteria
  • Production debugging

How It Works

┌─────────────────────────────────────────────────────────────┐
│                                                             │
│   ┌──────────┐    same prompt    ┌──────────┐     

Files in the repo

Repository payload19 top-level entries
  • .github
  • bin
  • contrib
  • docs
  • scripts
  • skills
  • tests
  • .gitignore
  • bun.lock
  • completion.ts
  • install.ps1
  • install.sh
  • LICENSE
  • package.json
  • ralph.ts
  • README.md
  • screenshot.webp
  • uninstall.ps1
  • uninstall.sh

Discussion (0)

Ask about usage, or say what you built with it

Sign in to join the discussion.

No comments yet. Be the first to say what this is good for.

More tools

JuliusBrussee/
caveman

🪨 why use many token when few token do trick — Claude Code skill that cuts 65% of tokens by talking like caveman

105k
1 add
MemPalace/
mempalace

The best-benchmarked open-source AI memory system. And it's free.

59k
stablyai/
orca

Orca is the ADE for working with a fleet of parallel agents. Run any coding agent with your own subscription. Available on desktop, mobile and remote runtime.

66k

A cross-platform desktop All-in-One assistant for Claude Code, Codex, OpenCode, OpenClaw, Grok Build & Hermes Agent. Only official website: ccswitch.io

132k

Never stop coding. Free MIT AI gateway: one endpoint, 352 providers (150+ free), 1200+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 550+ contributors

64k
headroomlabs-ai/
headroom

Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.

71k