ralph-wiggum
Implements the Ralph Wiggum autonomous iteration technique with deliberate context management. Use when building greenfield projects, iterating on well-defined tasks, or when continuous autonomous development is needed. Manages context like memory - tracks allocations, prevents redlining, and knows when to start fresh.
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Badge for your README
Markdown
[](/listings/agrimsingh--ralph-wiggum-cursor)HTML
<a href="/listings/agrimsingh--ralph-wiggum-cursor"><img src="/api/listings/agrimsingh--ralph-wiggum-cursor/badge.svg" alt="findsafeskills safety rating" /></a>Install
Install instructions from the README
As written by the repo's author. findsafeskills has not verified these steps.
These steps run a script from the network that findsafeskills does not scan.
1. Install Ralph
cd your-project curl -fsSL https://raw.githubusercontent.com/agrimsingh/ralph-wiggum-cursor/main/install.sh | bash
This creates:
your-project/ ├── .cursor/ralph-scripts/ # Ralph scripts │ ├── ralph-setup.sh # Main entry point (interactive) │ ├── ralph-loop.sh # CLI mode (for scripting) │ ├── ralph-once.sh # Single iteration (testing) │ ├── ralph-parallel.sh # Parallel execution with worktrees │ ├── stream-parser.sh # Token tracking + error detection │ ├── ralph-common.sh # Shared functions │ ├── ralph-retry.sh # Exponential backoff retry logic │ ├── task-parser.sh # YAML-backed task parsing │ └── init-ralph.sh # Re-initialize if needed ├── .ralph/ # State files (tracked in git) │ ├── progress.md # Agent updates: what's done │ ├── guardrails.md # Lessons learned (Signs) │ ├── activity.log # Tool call log (parser writes) │ ├── errors.log # Failure log (parser writes) │ └── tasks.yaml # Cached task state (auto-generated) ├── .ralph-worktrees/ # Temporary (parallel mode only) └── RALPH_TASK.md # Your task definition
2. (Optional) gum for Enhanced UI
The installer will offer to install gum automatically. You can also: - Skip the prompt and auto-install: `curl ... | INSTALL_GUM=1 bash` - Install manually: `brew install gum` (macOS) or see [gum installation](https://github.com/charmbracelet/gum#installation)
With gum, you get a beautiful interactive menu for selecting models and options:
? Select model: ◉ opus-4.5-thinking ◯ sonnet-4.5-thinking ◯ gpt-5.2-high ◯ composer-1 ◯ Custom... ? Max iterations: 20 ? Options: ◯ Commit to current branch ◯ Run single iteration first ◯ Work on new branch ◯ Open PR when complete ◯ Run in parallel mode ← runs multiple agents concurrently
If you select "Run in parallel mode", you'll be prompted for:
? Max parallel agents: 3 ← default is 3, enter any number
Without gum, Ralph falls back to simple numbered prompts.
3. Define Your Task
Edit `RALPH_TASK.md`:
--- task: Build a REST API test_command: "pnpm test" --- # Task: REST API Build a REST API with user management. ## Success Criteria 1. [ ] GET /health returns 200 2. [ ] POST /users creates a user 3. [ ] GET /users/:id returns user 4. [ ] All tests pass ## Context - Use Express.js - Store users in memory (no database needed)
**Important:** Use `[ ]` checkboxes. Ralph tracks completion by counting unchecked boxes.
4. Start the Loop
./.cursor/ralph-scripts/ralph-setup.sh
Ralph will: 1. Show interactive UI for model and options (or simple prompts if gum not installed) 2. Run `cursor-agent` with your task 3. Parse output in real-time, tracking token usage 4. At 70k tokens: warn agent to wrap up current work 5. At 80k tokens: rotate to fresh context 6. Repeat until all `[ ]` are `[x]` (or max iterations reached)
5. Monitor Progress
# Watch activity in real-time tail -f .ralph/activity.log # Example output: # [12:34:56] 🟢 READ src/index.ts (245 lines, ~24.5KB) # [12:34:58] 🟢 WRITE src/routes/users.ts (50 lines, 2.1KB) # [12:35:01] 🟢 SHELL pnpm test → exit 0 # [12:35:10] 🟢 TOKENS: 45,230 / 80,000 (56%) [read:30KB write:5KB assist:10KB shell:0KB] # Check for failures cat .ralph/errors.log
What was scanned
The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.
SKILL.md · Manifest · 169 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
- ---
- name: ralph-wiggum
- description: Implements the Ralph Wiggum autonomous iteration technique with deliberate context management. Use when building greenfield projects, iterating on well-defined tasks, or when continuous autonomous development is needed. Manages context like memory - tracks allocations, prevents redlining, and knows when to start fresh.
- license: MIT
- compatibility: Designed for Cursor (nightly). Requires bash, jq, git.
- metadata:
- author: Based on Geoffrey Huntley's Ralph technique
- version: "1.0.0"
- original: https://ghuntley.com/ralph/
- ---
- # Ralph Wiggum: Autonomous Iteration with Context Engineering
- Ralph is a technique for autonomous AI development. In its purest form, Ralph is a loop that repeatedly feeds the same prompt to an AI agent, letting it iterate on a task until completion. The key insight is that **context is like memory** - when you `malloc()` data into the context window, it cannot be `free()`'d except by starting fresh.
- ## Core Philosophy
- > "That's the beauty of Ralph - the technique is deterministically bad in an undeterministic world."
- Ralph will make mistakes. That's expected. Each mistake is an opportunity to add a "sign" (guardrail) that prevents that mistake in the future. Like tuning a guitar, you adjust Ralph until it plays the right notes.
- ### The malloc/free Metaphor
- - **Context is memory**: Everything loaded into the LLM's context window stays there
- - **You cannot free() context**: The only way to clear context is to start a new conversation
- - **One task per context**: Mixed concerns lead to autoregressive failure
- - **Don't redline**: Pushing context to limits degrades performance
- - **Gutter detection**: Once the bowling ball is in the gutter, start fresh
- ## How This Skill Works
- ### State Files (The Persistent Memory)
- Ralph tracks state in files, NOT in context:
- ```
- .ralph/
- ├── state.md # Current iteration, task, completion criteria
- ├── guardrails.md # Accumulated "signs" from observed failures
- ├── context-log.md # What's been loaded into context
- ├── failures.md # Failure patterns for learning
- └── progress.md # What's been accomplished
- ```
- ### The Iteration Cycle
- 1. **Read state files** to understand current task and progress
- 2. **Check guardrails** for relevant "signs" to follow
- 3. **Work on the task** - implement, test, refine
- 4. **Update progress** in files (not just context)
- 5. **Commit checkpoint** via git
- 6. **Evaluate completion** against criteria
- 7. **If not complete**: Signal for next iteration
- 8. **If stuck**: Detect gutter, suggest fresh context
- ### Guardrails ("Signs")
- When Ralph makes a mistake, add a sign:
- ```markdown
- ## Sign: Don't Jump Off The Slide
- - **Trigger**: When implementing authentication
- - **Instruction**: Always validate tokens before trusting claims
- - **Added after**: Iteration 5 - security vulnerability introduced
- ```
- Signs accumulate in `guardrails.md` and are injected into future iterations.
- ## Usage
- ### Starting a Ralph Loop
- Create a `RALPH_TASK.md` file in your project root:
- ```markdown
- ---
- task: Build a REST API for task management
- completion_criteria:
- - All CRUD endpoints working
- - Input validation implemented
- - Tests passing with >80% coverage
- - API documentation complete
- max_iterations: 50
- ---
- ## Requirements
- Build a task management API with the following endpoints:
- - POST /tasks - Create a task
- - GET /tasks - List all tasks
- - GET /tasks/:id - Get a task
- - PUT /tasks/:id - Update a task
- - DELETE /tasks/:id - Delete a task
- ## Constraints
- - Use TypeScript
- - Use Express.js
- - Use SQLite for storage
- - Follow REST conventions
- ```
- Then tell Cursor: "Start a Ralph loop on this task"
- ### Monitoring Progress
- Check `.ralph/progress.md` to see what's been accomplished:
- ```markdown
- ## Iteration 1
- - Created project structure
- - Implemented POST /tasks endpoint
- - Status: Partial progress
- ## Iteration 2
- - Added GET endpoints
- - Fixed validation bug
- - Status: Continuing
- ```
- ### When to Start Fresh
- Ralph will detect "gutter" situations:
- - Same error repeated 3+ times
- - Context approaching limits
- - Circular failure patterns
- When detected, Ralph will suggest: "Context is polluted. Recommend starting fresh conversation."
- ## Best Practices
- ### 1. Clear Completion Criteria
- ❌ Bad: "Make a good API"
- ✅ Good: "All tests passing, coverage >80%, docs complete"
- ### 2. Incremental Goals
- ❌ Bad: "Build complete e-commerce platform"
- ✅ Good: Phase 1: Auth, Phase 2: Products, Phase 3: Cart
- ### 3. Let Failures Teach
- Don't intervene too quickly. Let Ralph fail, then add signs.
- ### 4. Trust the Files
- Progress is in files and git, not in your head or the context.
- ### 5. Fresh Context is Cheap
- Don't hesitate to start fresh. State persists in files.
- ## Integration with Cursor Hooks
- This skill uses Cursor hooks for:
- - **beforeSubmitPrompt**: Inject guardrails and context awareness
- - **beforeReadFile**: Track context allocations
- - **afterFileEdit**: Update progress tracking
- - **stop**: Evaluate completion, trigger next iteration or fresh start
- See `scripts/` for hook implementations.
- ## Learn More
- - Original technique: https://ghuntley.com/ralph/
- - Context engineering: https://ghuntley.com/gutter/
- - malloc/free metaphor: https://ghuntley.com/allocations/
README.md · README · 658 lines · 3 findings marked
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
- # Ralph Wiggum for Cursor
- An implementation of [Geoffrey Huntley's Ralph Wiggum technique](https://ghuntley.com/ralph/) for Cursor, enabling autonomous AI development with deliberate context management.
- > "That's the beauty of Ralph - the technique is deterministically bad in an undeterministic world."
- ## What is Ralph?
- Ralph is a technique for autonomous AI development that treats LLM context like memory:
- ```bash
- while :; do cat PROMPT.md | agent ; done
- ```
- The same prompt is fed repeatedly to an AI agent. Progress persists in **files and git**, not in the LLM's context window. When context fills up, you get a fresh agent with fresh context.
- ### The malloc/free Problem
- In traditional programming:
- - `malloc()` allocates memory
- - `free()` releases memory
- In LLM context:
- - Reading files, tool outputs, conversation = `malloc()`
- - **There is no `free()`** - context cannot be selectively released
- - Only way to free: start a new conversation
- This creates two problems:
- 1. **Context pollution** - Failed attempts, unrelated code, and mixed concerns accumulate and confuse the model
- 2. **The gutter** - Once polluted, the model keeps referencing bad context. Like a bowling ball in the gutter, there's no saving it.
- **Ralph's solution:** Deliberately rotate to fresh context before pollution builds up. State lives in files and git, not in the LLM's memory.
- ## Architecture
- ```
- ┌─────────────────────────────────────────────────────────────┐
- │ ralph-setup.sh │
- │ │ │
- │ ┌────────────┴────────────┐ │
- │ ▼ ▼ │
- │ [gum UI] [fallback] │
- │ Model selection Simple prompts │
- │ Max iterations │
- │ Options (branch, PR) │
- │ │ │ │
- │ └────────────┬────────────┘ │
- │ ▼ │
- │ cursor-agent -p --force --output-format stream-json │
- │ │ │
- │ ▼ │
- │ stream-parser.sh │
- │ │ │ │
- │ ┌────────────────┴────────┴────────────────┐ │
- │ ▼ ▼ │
- │ .ralph/ Signals │
- │ ├── activity.log (tool calls) ├── WARN at 70k │
- │ ├── errors.log (failures) ├── ROTATE at 80k│
- │ ├── progress.md (agent writes) ├── COMPLETE │
- │ ├── guardrails.md (lessons learned) ├── GUTTER │
- │ └── tasks.yaml (cached task state) └── DEFER │
- │ │
- │ When ROTATE → fresh context, continue from git │
- │ When DEFER → exponential backoff, retry same task │
- └─────────────────────────────────────────────────────────────┘
- ```
- **Key features:**
- - **Interactive setup** - Beautiful gum-based UI for model selection and options
- - **Accurate token tracking** - Parser counts actual bytes from every file read/write
- - **Gutter detection** - Detects when agent is stuck (same command failed 3x, file thrashing)
- - **Rate limit handling** - Detects rate limits/network errors, waits with exponential backoff
- - **Task caching** - YAML backend with mtime invalidation for efficient task parsing
- - **Learning from failures** - Agent updates `.ralph/guardrails.md` with lessons
- - **State in git** - Commits frequently so next agent picks up from git history
- - **Branch/PR workflow** - Optionally work on a branch and open PR when complete
- ## Prerequisites
- | Requirement | Check | How to Set Up |
- |-------------|-------|---------------|
- | **Git repo** | `git status` works | `git init` |
- | **cursor-agent CLI** | `which cursor-agent` | `curl https://cursor.com/install -fsS \| bash` |
- Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
- Line 84 on GitHub
- | **gum** (optional) | `which gum` | Installer offers to install, or `brew install gum` |
- ## Quick Start
- ### 1. Install Ralph
- ```bash
- cd your-project
- curl -fsSL https://raw.githubusercontent.com/agrimsingh/ralph-wiggum-cursor/main/install.sh | bash
- Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
- Line 93 on GitHub
- ```
- This creates:
- ```
- your-project/
- ├── .cursor/ralph-scripts/ # Ralph scripts
- │ ├── ralph-setup.sh # Main entry point (interactive)
- │ ├── ralph-loop.sh # CLI mode (for scripting)
- │ ├── ralph-once.sh # Single iteration (testing)
- │ ├── ralph-parallel.sh # Parallel execution with worktrees
- │ ├── stream-parser.sh # Token tracking + error detection
- │ ├── ralph-common.sh # Shared functions
- │ ├── ralph-retry.sh # Exponential backoff retry logic
- │ ├── task-parser.sh # YAML-backed task parsing
- │ └── init-ralph.sh # Re-initialize if needed
- ├── .ralph/ # State files (tracked in git)
- │ ├── progress.md # Agent updates: what's done
- │ ├── guardrails.md # Lessons learned (Signs)
- │ ├── activity.log # Tool call log (parser writes)
- │ ├── errors.log # Failure log (parser writes)
- │ └── tasks.yaml # Cached task state (auto-generated)
- ├── .ralph-worktrees/ # Temporary (parallel mode only)
- └── RALPH_TASK.md # Your task definition
- ```
- ### 2. (Optional) gum for Enhanced UI
- The installer will offer to install gum automatically. You can also:
- - Skip the prompt and auto-install: `curl ... | INSTALL_GUM=1 bash`
- - Install manually: `brew install gum` (macOS) or see [gum installation](https://github.com/charmbracelet/gum#installation)
- With gum, you get a beautiful interactive menu for selecting models and options:
- ```
- ? Select model:
- ◉ opus-4.5-thinking
- ◯ sonnet-4.5-thinking
- ◯ gpt-5.2-high
- ◯ composer-1
- ◯ Custom...
- ? Max iterations: 20
- ? Options:
- ◯ Commit to current branch
- ◯ Run single iteration first
- ◯ Work on new branch
- ◯ Open PR when complete
- ◯ Run in parallel mode ← runs multiple agents concurrently
- ```
- If you select "Run in parallel mode", you'll be prompted for:
- ```
- ? Max parallel agents: 3 ← default is 3, enter any number
- ```
- Without gum, Ralph falls back to simple numbered prompts.
- ### 3. Define Your Task
- Edit `RALPH_TASK.md`:
- ```markdown
- ---
- task: Build a REST API
- test_command: "pnpm test"
- ---
- # Task: REST API
- Build a REST API with user management.
- ## Success Criteria
- 1. [ ] GET /health returns 200
- 2. [ ] POST /users creates a user
- 3. [ ] GET /users/:id returns user
- 4. [ ] All tests pass
- ## Context
- - Use Express.js
- - Store users in memory (no database needed)
- ```
- **Important:** Use `[ ]` checkboxes. Ralph tracks completion by counting unchecked boxes.
- ### 4. Start the Loop
- ```bash
- ./.cursor/ralph-scripts/ralph-setup.sh
- ```
- Ralph will:
- 1. Show interactive UI for model and options (or simple prompts if gum not installed)
- 2. Run `cursor-agent` with your task
- 3. Parse output in real-time, tracking token usage
- 4. At 70k tokens: warn agent to wrap up current work
- 5. At 80k tokens: rotate to fresh context
- 6. Repeat until all `[ ]` are `[x]` (or max iterations reached)
- ### 5. Monitor Progress
- ```bash
- # Watch activity in real-time
- tail -f .ralph/activity.log
- # Example output:
- # [12:34:56] 🟢 READ src/index.ts (245 lines, ~24.5KB)
- # [12:34:58] 🟢 WRITE src/routes/users.ts (50 lines, 2.1KB)
- # [12:35:01] 🟢 SHELL pnpm test → exit 0
- # [12:35:10] 🟢 TOKENS: 45,230 / 80,000 (56%) [read:30KB write:5KB assist:10KB shell:0KB]
- # Check for failures
- cat .ralph/errors.log
- ```
- ## Commands
- | Command | Description |
- |---------|-------------|
- | `ralph-setup.sh` | **Primary** - Interactive setup + run loop |
- | `ralph-once.sh` | Test single iteration before going AFK |
- | `ralph-loop.sh` | CLI mode for scripting (see flags below) |
- | `init-ralph.sh` | Re-initialize Ralph state |
- ### ralph-loop.sh Flags (for scripting/CI)
- ```bash
- ./ralph-loop.sh [options] [workspace]
- Options:
- -n, --iterations N Max iterations (default: 20)
- -m, --model MODEL Model to use (default: opus-4.5-thinking)
- --branch NAME Sequential: create/work on branch; Parallel: integration branch name
- --pr Sequential: open PR (requires --branch); Parallel: open ONE integration PR (branch optional)
- --parallel Run tasks in parallel with worktrees
- --max-parallel N Max parallel agents (default: 3)
- --no-merge Skip auto-merge in parallel mode
- -y, --yes Skip confirmation prompt
- ```
- **Examples:**
- ```bash
- # Scripted PR workflow
- ./ralph-loop.sh --branch feature/api --pr -y
- # Use a different model with more iterations
- ./ralph-loop.sh -n 50 -m gpt-5.2-high
- # Run 4 agents in parallel
- ./ralph-loop.sh --parallel --max-parallel 4
- # Parallel: keep branches separate
- ./ralph-loop.sh --parallel --no-merge
- # Parallel: merge into an integration branch + open ONE PR
- ./ralph-loop.sh --parallel --max-parallel 5 --branch feature/multi-task --pr
- # Parallel: open ONE PR using an auto-named integration branch
- ./ralph-loop.sh --parallel --max-parallel 5 --pr
- ```
- ## Parallel Execution
- Ralph can run multiple agents concurrently, each in an isolated git worktree.
- ### Starting Parallel Mode
- **Via gum UI (interactive):**
- ```bash
- ./ralph-setup.sh
- # Select "Run in parallel mode" in options
- # Enter number of agents when prompted (default: 3, no upper limit)
- ```
- **Via CLI (scripting/CI):**
- ```bash
- # Run 3 agents in parallel (default)
- ./ralph-loop.sh --parallel
- # Run 10 agents in parallel (no hard cap)
- ./ralph-loop.sh --parallel --max-parallel 10
- # Keep branches separate (no auto-merge)
- ./ralph-loop.sh --parallel --no-merge
- # Merge into an integration branch (no PR)
- ./ralph-loop.sh --parallel --max-parallel 5 --branch feature/multi-task
- # Merge into an integration branch and open ONE PR
- ./ralph-loop.sh --parallel --max-parallel 5 --branch feature/multi-task --pr
- # Open ONE PR using an auto-named integration branch
- ./ralph-loop.sh --parallel --max-parallel 5 --pr
- ```
- > **Note:** There's no hard limit on `--max-parallel`. The practical limit depends on your machine's resources and API rate limits.
- ### Integration branch + single PR
- Parallel `--pr` creates **one integration branch** (either your `--branch NAME` or an auto-named `ralph/parallel-<run_id>`), merges all successful agent branches into it, then opens **one PR** back to the base branch.
- This avoids “one PR per task” spam while keeping agents isolated.
- ### How Parallel Mode Works
- ```
- ┌────────────────────────────────────────────────────────────────┐
- │ Parallel Execution Flow │
- ├────────────────────────────────────────────────────────────────┤
- │ │
- │ RALPH_TASK.md │
- │ - [ ] Task A │
- │ - [ ] Task B ┌──────────────────────────┐ │
- │ - [ ] Task C ───▶ │ Create Worktrees │ │
- │ └──────────────────────────┘ │
- │ │ │
- │ ┌───────────────┼───────────────┐ │
- │ ▼ ▼ ▼ │
- │ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
- │ │ Agent 1 │ │ Agent 2 │ │ Agent 3 │ │
- │ │ worktree │ │ worktree │ │ worktree │ │
- │ │ Task A │ │ Task B │ │ Task C │ │
- │ └────┬─────┘ └────┬─────┘ └────┬─────┘ │
- │ │ │ │ │
- │ ▼ ▼ ▼ │
- │ branch-a branch-b branch-c │
- │ │ │ │ │
- │ └──────────────┼──────────────┘ │
- │ ▼ │
- │ ┌──────────────┐ │
- │ │ Auto-Merge │ │
- │ │ to base │ │
- │ └──────────────┘ │
- └────────────────────────────────────────────────────────────────┘
- ```
- **Key benefits:**
- - Each agent works in complete isolation (separate git worktree)
- - No interference between agents working on different tasks
- - Branches auto-merge after completion (or keep separate with `--no-merge`)
- - Conflict detection and reporting
- - Tasks are processed in batches (e.g., 5 agents = 5 tasks per batch)
- - In parallel mode, agents do **not** update `.ralph/progress.md` (they write per-agent reports instead)
- **When to use parallel mode:**
- - Multiple independent tasks that don't conflict
- - Large task lists you want completed faster
- - CI/CD pipelines with parallelization budget
- **When to use sequential mode:**
- - Tasks that depend on each other
- - Single complex task that needs focused attention
- - Limited API rate limits
- ### Recommended Workflow: Parallel + Integration Pass
- For best results, structure your work in two phases:
- **Phase 1: Parallel execution** (isolated, independent tasks)
- ```markdown
- # Tasks
- - [ ] Add user authentication to /api/auth
- - [ ] Create dashboard component
- - [ ] Implement data export feature
- - [ ] Add unit tests for utils/
- ```
- **Phase 2: Integration pass** (one sequential agent, repo-wide polish)
- ```markdown
- # Tasks
- - [ ] Update README with new features
- - [ ] Bump version in package.json
- - [ ] Update CHANGELOG
- - [ ] Fix any integration issues from parallel work
- ```
- This pattern maximizes parallelism while avoiding merge conflicts on shared files.
- The integration pass runs after parallel agents finish and handles all "touch everything" work.
- ### Task Groups (Phased Execution)
- Control execution order with `<!-- group: N -->` annotations:
- ```markdown
- # Tasks
- - [ ] Create database schema <!-- group: 1 -->
- - [ ] Create User model <!-- group: 1 -->
- - [ ] Create Post model <!-- group: 1 -->
- - [ ] Add relationships between models <!-- group: 2 -->
- - [ ] Build API endpoints <!-- group: 3 -->
- - [ ] Update README # no annotation = runs LAST
- ```
- **Execution order:**
- 1. Group 1 - runs first (all tasks in parallel, up to `--max-parallel`)
- 2. Group 2 - runs after group 1 merges complete
- 3. Group 3 - runs after group 2 merges complete
- 4. Unannotated tasks - run LAST (after all annotated groups)
- **Why unannotated = last?**
- - Safer default: forgetting to annotate doesn't jump the queue
- - Integration/polish tasks naturally go last
- - Override with `DEFAULT_GROUP=0` env var if you prefer unannotated first
- **Within each group:**
- - Tasks run in parallel (up to `--max-parallel`)
- - All merges complete before next group starts
- - RALPH_TASK.md checkboxes updated per group
- **Worktree structure:**
- ```
- project/
- ├── .ralph-worktrees/ # Temporary worktrees (auto-cleaned)
- │ ├── <run_id>-job1/ # Agent worktree (isolated)
- │ ├── <run_id>-job2/ # Agent worktree (isolated)
- │ └── <run_id>-job3/ # Agent worktree (isolated)
- └── (original project files)
- ```
- Worktrees are automatically cleaned up after agents complete. Failed agents preserve their worktree for manual inspection.
- ### Parallel logs & per-agent reports
- Each parallel run creates a run directory:
- ```
- .ralph/parallel/<run_id>/
- ├── manifest.tsv # job_id -> task_id -> branch -> status -> log
- └── jobN.log # full cursor-agent output for that job
- ```
- Agents are instructed to write a committed per-agent report (to avoid `.ralph/progress.md` merge conflicts):
- ```
- .ralph/parallel/<run_id>/agent-jobN.md
- ```
- ## How It Works
- ### The Loop
- ```
- Iteration 1 Iteration 2 Iteration N
- ┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐
- │ Fresh context │ │ Fresh context │ │ Fresh context │
- │ │ │ │ │ │ │ │ │
- │ ▼ │ │ ▼ │ │ ▼ │
- │ Read RALPH_TASK │ │ Read RALPH_TASK │ │ Read RALPH_TASK │
- │ Read guardrails │──────────│ Read guardrails │──────────│ Read guardrails │
- │ Read progress │ (state │ Read progress │ (state │ Read progress │
- │ │ │ in git) │ │ │ in git) │ │ │
- │ ▼ │ │ ▼ │ │ ▼ │
- │ Work on criteria │ │ Work on criteria │ │ Work on criteria │
- │ Commit to git │ │ Commit to git │ │ Commit to git │
- │ │ │ │ │ │ │ │ │
- │ ▼ │ │ ▼ │ │ ▼ │
- │ 80k tokens │ │ 80k tokens │ │ All [x] done! │
- │ ROTATE ──────────┼──────────┼──────────────────┼──────────┼──► COMPLETE │
- └──────────────────┘ └──────────────────┘ └──────────────────┘
- ```
- Each iteration:
- 1. Reads task and state from files (not from previous context)
- 2. Works on unchecked criteria
- 3. Commits progress to git
- 4. Updates `.ralph/progress.md` and `.ralph/guardrails.md`
- 5. Rotates when context is full
- ### Git Protocol
- The agent is instructed to commit frequently:
- ```bash
- # After each criterion
- git add -A && git commit -m 'ralph: [criterion] - description'
- # Push periodically
- git push
- ```
- **Commits are the agent's memory.** The next iteration picks up from git history.
- ### The Learning Loop (Signs)
- When something fails, the agent adds a "Sign" to `.ralph/guardrails.md`:
- ```markdown
- ### Sign: Check imports before adding
- - **Trigger**: Adding a new import statement
- - **Instruction**: First check if import already exists in file
- - **Added after**: Iteration 3 - duplicate import caused build failure
- ```
- Future iterations read guardrails first and follow them, preventing repeated mistakes.
- ```
- Error occurs → errors.log → Agent analyzes → Updates guardrails.md → Future agents follow
- ```
- ## Context Health Indicators
- The activity log shows context health with emoji:
- | Emoji | Status | Token % | Meaning |
- |-------|--------|---------|---------|
- | 🟢 | Healthy | < 60% | Plenty of room |
- | 🟡 | Warning | 60-80% | Approaching limit |
- | 🔴 | Critical | > 80% | Rotation imminent |
- Example:
- ```
- [12:34:56] 🟢 READ src/index.ts (245 lines, ~24.5KB)
- [12:40:22] 🟡 TOKENS: 58,000 / 80,000 (72%) - approaching limit [read:40KB write:8KB assist:10KB shell:0KB]
- [12:45:33] 🔴 TOKENS: 72,500 / 80,000 (90%) - rotation imminent
- ```
- ## Gutter Detection
- The parser detects when the agent is stuck:
- | Pattern | Trigger | What Happens |
- |---------|---------|--------------|
- | Repeated failure | Same command failed 3x | GUTTER signal |
- | File thrashing | Same file written 5x in 10 min | GUTTER signal |
- | Agent signals | Agent outputs `<ralph>GUTTER</ralph>` | GUTTER signal |
- When gutter is detected:
- 1. Check `.ralph/errors.log` for the pattern
- 2. Fix the issue manually or add a guardrail
- 3. Re-run the loop
- ## Rate Limit & Transient Error Handling
- The parser detects retryable API errors and handles them gracefully:
- | Error Type | Examples | What Happens |
- |------------|----------|--------------|
- | Rate limits | 429, "rate limit exceeded", "quota" | DEFER signal |
- | Network errors | timeout, connection reset, ECONNRESET | DEFER signal |
- | Server errors | 502, 503, 504, "service unavailable" | DEFER signal |
- When DEFER is triggered:
- 1. Agent stops current iteration
- 2. Waits with **exponential backoff** (15s base, doubles each retry, max 120s)
- 3. Adds jitter (0-25%) to prevent thundering herd
- 4. Retries the same task (does not increment iteration)
- Example log:
- ```
- ⏸️ Rate limit or transient error detected.
- Waiting 32s before retrying (attempt 2)...
- Resuming...
- ```
- ## Completion Detection
- Ralph detects completion in two ways:
- 1. **Checkbox check**: All `[ ]` in RALPH_TASK.md changed to `[x]`
- 2. **Agent sigil**: Agent outputs `<ralph>COMPLETE</ralph>`
- Both are verified before declaring success.
- ## File Reference
- | File | Purpose | Who Uses It |
- |------|---------|-------------|
- | `RALPH_TASK.md` | Task definition + success criteria | You define, agent reads |
- | `.ralph/progress.md` | What's been accomplished | Agent writes after work |
- | `.ralph/guardrails.md` | Lessons learned (Signs) | Agent reads first, writes after failures |
- | `.ralph/activity.log` | Tool call log with token counts | Parser writes, you monitor |
- | `.ralph/errors.log` | Failures + gutter detection | Parser writes, agent reads |
- | `.ralph/tasks.yaml` | Cached task state (auto-generated) | Task parser writes/reads |
- | `.ralph/tasks.mtime` | Task file modification time | Cache invalidation |
- | `.ralph/.iteration` | Current iteration number | Parser reads/writes |
- ## Configuration
- Configuration is set via command-line flags or environment variables:
- ```bash
- # Via flags (recommended)
- ./ralph-loop.sh -n 50 -m gpt-5.2-high
- # Via environment
- RALPH_MODEL=gpt-5.2-high MAX_ITERATIONS=50 ./ralph-loop.sh
- ```
- Default thresholds in `ralph-common.sh`:
- ```bash
- MAX_ITERATIONS=20 # Max rotations before giving up
- WARN_THRESHOLD=70000 # Tokens: send wrapup warning
- ROTATE_THRESHOLD=80000 # Tokens: force rotation
- ```
- ## Troubleshooting
- ### "cursor-agent CLI not found"
- ```bash
- curl https://cursor.com/install -fsS | bash
- Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
- Line 600 on GitHub
- ```
- ### Agent keeps failing on same thing
- Check `.ralph/errors.log` for the pattern. Either:
- 1. Fix the underlying issue manually
- 2. Add a guardrail to `.ralph/guardrails.md` explaining what to do differently
- ### Context rotates too frequently
- The agent might be reading too many large files. Check `activity.log` for large READs and consider:
- 1. Adding a guardrail: "Don't read the entire file, use grep to find relevant sections"
- 2. Breaking the task into smaller pieces
- ### Task never completes
- Check if criteria are too vague. Each criterion should be:
- - Specific and testable
- - Achievable in a single iteration
- - Not dependent on manual steps
- ## Workflows
- ### Basic (default)
- ```bash
- ./ralph-setup.sh # Interactive setup → runs loop → done
- ```
- ### Human-in-the-loop (recommended for new tasks)
- ```bash
- ./ralph-once.sh # Run ONE iteration
- # Review changes...
- ./ralph-setup.sh # Continue with full loop
- ```
- ### Scripted/CI
- ```bash
- ./ralph-loop.sh --branch feature/foo --pr -y
- ```
- ## Learn More
- - [Original Ralph technique](https://ghuntley.com/ralph/) - Geoffrey Huntley
- - [Context as memory](https://ghuntley.com/allocations/) - The malloc/free metaphor
- - [Cursor CLI docs](https://cursor.com/docs/cli/headless)
- - [gum - A tool for glamorous shell scripts](https://github.com/charmbracelet/gum)
- ## Credits
- - **Original technique**: [Geoffrey Huntley](https://ghuntley.com/ralph/) - the Ralph Wiggum methodology
- - **Cursor port**: [Agrim Singh](https://x.com/agrimsingh) - this implementation
- ## License
- MIT
install.sh · Bundled script · 303 lines · 2 findings marked
- #!/bin/bash
- # Ralph Wiggum: One-click installer
- # Usage: curl -fsSL https://raw.githubusercontent.com/agrimsingh/ralph-wiggum-cursor/main/install.sh | bash
- Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
- Line 3 on GitHub
- set -euo pipefail
- REPO_RAW="https://raw.githubusercontent.com/agrimsingh/ralph-wiggum-cursor/main"
- echo "═══════════════════════════════════════════════════════════════════"
- echo "🐛 Ralph Wiggum Installer"
- echo "═══════════════════════════════════════════════════════════════════"
- echo ""
- # Check if we're in a git repo
- if ! git rev-parse --git-dir > /dev/null 2>&1; then
- echo "⚠️ Warning: Not in a git repository."
- echo " Ralph works best with git for state persistence."
- echo ""
- echo " Run: git init"
- echo ""
- fi
- # Check for cursor-agent CLI
- if ! command -v cursor-agent &> /dev/null; then
- echo "⚠️ Warning: cursor-agent CLI not found."
- echo " Install via: curl https://cursor.com/install -fsS | bash"
- Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
- Line 26 on GitHub
- echo ""
- fi
- # Check for gum and offer to install
- if ! command -v gum &> /dev/null; then
- echo "📦 gum not found (provides beautiful CLI menus)"
- # Auto-install if INSTALL_GUM=1 or prompt user
- SHOULD_INSTALL=""
- if [[ "${INSTALL_GUM:-}" == "1" ]]; then
- SHOULD_INSTALL="y"
- else
- read -p " Install gum? [y/N] " -n 1 -r < /dev/tty
- echo
- SHOULD_INSTALL="$REPLY"
- fi
- if [[ "$SHOULD_INSTALL" =~ ^[Yy]$ ]]; then
- if [[ "$OSTYPE" == "darwin"* ]]; then
- if command -v brew &> /dev/null; then
- echo " Installing via Homebrew..."
- brew install gum
- else
- echo " ⚠️ Homebrew not found. Install manually: brew install gum"
- fi
- elif [[ -f /etc/debian_version ]]; then
- echo " Installing via apt..."
- sudo mkdir -p /etc/apt/keyrings
- curl -fsSL https://repo.charm.sh/apt/gpg.key | sudo gpg --dearmor -o /etc/apt/keyrings/charm.gpg
- echo "deb [signed-by=/etc/apt/keyrings/charm.gpg] https://repo.charm.sh/apt/ * *" | sudo tee /etc/apt/sources.list.d/charm.list
- sudo apt update && sudo apt install -y gum
- elif [[ -f /etc/fedora-release ]] || [[ -f /etc/redhat-release ]]; then
- echo " Installing via dnf..."
- echo '[charm]
- name=Charm
- baseurl=https://repo.charm.sh/yum/
- enabled=1
- gpgcheck=1
- gpgkey=https://repo.charm.sh/yum/gpg.key' | sudo tee /etc/yum.repos.d/charm.repo
- sudo dnf install -y gum
- else
- echo " ⚠️ Unknown Linux distro. Install manually: https://github.com/charmbracelet/gum#installation"
- fi
- fi
- echo ""
- fi
- WORKSPACE_ROOT="$(pwd)"
- # =============================================================================
- # CREATE DIRECTORIES
- # =============================================================================
- echo "📁 Creating directories..."
- mkdir -p .cursor/ralph-scripts
- mkdir -p .ralph
- # =============================================================================
- # DOWNLOAD SCRIPTS
- # =============================================================================
- echo "📥 Downloading Ralph scripts..."
- SCRIPTS=(
- "ralph-common.sh"
- "ralph-setup.sh"
- "ralph-loop.sh"
- "ralph-once.sh"
- "ralph-parallel.sh"
- "stream-parser.sh"
- "task-parser.sh"
- "ralph-retry.sh"
- "init-ralph.sh"
- )
- for script in "${SCRIPTS[@]}"; do
- if curl -fsSL "$REPO_RAW/scripts/$script" -o ".cursor/ralph-scripts/$script" 2>/dev/null; then
- chmod +x ".cursor/ralph-scripts/$script"
- else
- echo " ⚠️ Could not download $script (may not exist yet)"
- fi
- done
- echo "✓ Scripts installed to .cursor/ralph-scripts/"
- # =============================================================================
- # INITIALIZE .ralph/ STATE
- # =============================================================================
- echo "📁 Initializing .ralph/ state directory..."
- cat > .ralph/guardrails.md << 'EOF'
- # Ralph Guardrails (Signs)
- > Lessons learned from past failures. READ THESE BEFORE ACTING.
- ## Core Signs
- ### Sign: Read Before Writing
- - **Trigger**: Before modifying any file
- - **Instruction**: Always read the existing file first
- - **Added after**: Core principle
- ### Sign: Test After Changes
- - **Trigger**: After any code change
- - **Instruction**: Run tests to verify nothing broke
- - **Added after**: Core principle
- ### Sign: Commit Checkpoints
- - **Trigger**: Before risky changes
- - **Instruction**: Commit current working state first
- - **Added after**: Core principle
- ---
- ## Learned Signs
- (Signs added from observed failures will appear below)
- EOF
- cat > .ralph/progress.md << 'EOF'
- # Progress Log
- > Updated by the agent after significant work.
- ## Summary
- - Iterations completed: 0
- - Current status: Initialized
- ## How This Works
- Progress is tracked in THIS FILE, not in LLM context.
- When context is rotated (fresh agent), the new agent reads this file.
- This is how Ralph maintains continuity across iterations.
- ## Session History
- EOF
- cat > .ralph/errors.log << 'EOF'
- # Error Log
- > Failures detected by stream-parser. Use to update guardrails.
- EOF
- cat > .ralph/activity.log << 'EOF'
- # Activity Log
- > Real-time tool call logging from stream-parser.
- EOF
- echo "0" > .ralph/.iteration
- echo "✓ .ralph/ initialized"
- # =============================================================================
- # CREATE RALPH_TASK.md TEMPLATE
- # =============================================================================
- if [[ ! -f "RALPH_TASK.md" ]]; then
- echo "📝 Creating RALPH_TASK.md template..."
- cat > RALPH_TASK.md <<'TASKEOF'
- ---
- task: Build a CLI todo app in TypeScript
- test_command: "npx ts-node todo.ts list"
- ---
- # Task: CLI Todo App (TypeScript)
- Build a simple command-line todo application in TypeScript.
- ## Requirements
- 1. Single file: `todo.ts`
- 2. Uses `todos.json` for persistence
- 3. Three commands: add, list, done
- 4. TypeScript with proper types
- ## Success Criteria
- 1. [ ] `npx ts-node todo.ts add "Buy milk"` adds a todo and confirms
- 2. [ ] `npx ts-node todo.ts list` shows all todos with IDs and status
- 3. [ ] `npx ts-node todo.ts done 1` marks todo 1 as complete
- 4. [ ] Todos survive script restart (JSON persistence)
- 5. [ ] Invalid commands show helpful usage message
- 6. [ ] Code has proper TypeScript types (no `any`)
- ## Example Output
- ```
- $ npx ts-node todo.ts add "Buy milk"
- ✓ Added: "Buy milk" (id: 1)
- $ npx ts-node todo.ts list
- 1. [ ] Buy milk
- $ npx ts-node todo.ts done 1
- ✓ Completed: "Buy milk"
- ```
- ---
- ## Ralph Instructions
- 1. Work on the next incomplete criterion (marked [ ])
- 2. Check off completed criteria (change [ ] to [x])
- 3. Run tests after changes
- 4. Commit your changes frequently
- 5. When ALL criteria are [x], output: `<ralph>COMPLETE</ralph>`
- 6. If stuck on the same issue 3+ times, output: `<ralph>GUTTER</ralph>`
- TASKEOF
- echo "✓ Created RALPH_TASK.md with example task"
- else
- echo "✓ RALPH_TASK.md already exists (not overwritten)"
- fi
- # =============================================================================
- # UPDATE .gitignore
- # =============================================================================
- if [[ -f ".gitignore" ]]; then
- if ! grep -q "ralph-config.json" .gitignore 2>/dev/null; then
- echo "" >> .gitignore
- echo "# Ralph config (may contain API key)" >> .gitignore
- echo ".cursor/ralph-config.json" >> .gitignore
- fi
- else
- cat > .gitignore <<'EOF'
- # Ralph config (may contain API key)
- .cursor/ralph-config.json
- EOF
- fi
- echo "✓ Updated .gitignore"
- # =============================================================================
- # SUMMARY
- # =============================================================================
- echo ""
- echo "═══════════════════════════════════════════════════════════════════"
- echo "✅ Ralph installed!"
- echo "═══════════════════════════════════════════════════════════════════"
- echo ""
- echo "Files created:"
- echo ""
- echo " 📁 .cursor/ralph-scripts/"
- echo " ├── ralph-setup.sh - Main entry (interactive)"
- echo " ├── ralph-loop.sh - CLI mode (for scripting)"
- echo " ├── ralph-once.sh - Single iteration (testing)"
- echo " └── ... - Other utilities"
- echo ""
- echo " 📁 .ralph/ - State files (tracked in git)"
- echo " ├── guardrails.md - Lessons learned"
- echo " ├── progress.md - Progress log"
- echo " ├── activity.log - Tool call log"
- echo " └── errors.log - Failure log"
- echo ""
- echo " 📄 RALPH_TASK.md - Your task definition (edit this!)"
- echo ""
- echo "Next steps:"
- echo " 1. Edit RALPH_TASK.md to define your actual task"
- echo " 2. Run: ./.cursor/ralph-scripts/ralph-setup.sh"
- echo ""
- echo "Alternative commands:"
- echo " • ralph-once.sh - Test with single iteration first"
- echo " • ralph-loop.sh - CLI mode with flags (for scripting)"
- echo ""
- echo "Monitor progress:"
- echo " tail -f .ralph/activity.log"
- echo ""
- echo "Learn more: https://ghuntley.com/ralph/"
- echo "═══════════════════════════════════════════════════════════════════"
scripts/init-ralph.sh · Bundled script · 202 lines · 1 finding marked
- #!/bin/bash
- # Ralph Wiggum: Initialize Ralph in a project
- # Sets up Ralph tracking for CLI mode
- set -euo pipefail
- SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
- SKILL_DIR="$(dirname "$SCRIPT_DIR")"
- echo "═══════════════════════════════════════════════════════════════════"
- echo "🐛 Ralph Wiggum Initialization"
- echo "═══════════════════════════════════════════════════════════════════"
- echo ""
- # Check if we're in a git repo
- if ! git rev-parse --git-dir > /dev/null 2>&1; then
- echo "⚠️ Warning: Not in a git repository."
- echo " Ralph works best with git for state persistence."
- echo ""
- read -p "Continue anyway? [y/N] " -n 1 -r
- echo
- if [[ ! $REPLY =~ ^[Yy]$ ]]; then
- exit 1
- fi
- fi
- # Check for cursor-agent CLI
- if ! command -v cursor-agent &> /dev/null; then
- echo "⚠️ Warning: cursor-agent CLI not found."
- echo " Install via: curl https://cursor.com/install -fsS | bash"
- Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
- Line 30 on GitHub
- echo ""
- fi
- # Create directories
- mkdir -p .ralph
- mkdir -p .cursor/ralph-scripts
- # =============================================================================
- # CREATE RALPH_TASK.md IF NOT EXISTS
- # =============================================================================
- if [[ ! -f "RALPH_TASK.md" ]]; then
- echo "📝 Creating RALPH_TASK.md template..."
- if [[ -f "$SKILL_DIR/assets/RALPH_TASK_TEMPLATE.md" ]]; then
- cp "$SKILL_DIR/assets/RALPH_TASK_TEMPLATE.md" RALPH_TASK.md
- else
- cat > RALPH_TASK.md << 'EOF'
- ---
- task: Your task description here
- test_command: "pnpm test"
- ---
- # Task
- Describe what you want to accomplish.
- ## Success Criteria
- 1. [ ] First thing to complete
- 2. [ ] Second thing to complete
- 3. [ ] Third thing to complete
- ## Context
- Any additional context the agent should know.
- EOF
- fi
- echo " Edit RALPH_TASK.md to define your task."
- else
- echo "✓ RALPH_TASK.md already exists"
- fi
- # =============================================================================
- # INITIALIZE STATE FILES
- # =============================================================================
- echo "📁 Initializing .ralph/ directory..."
- cat > .ralph/guardrails.md << 'EOF'
- # Ralph Guardrails (Signs)
- > Lessons learned from past failures. READ THESE BEFORE ACTING.
- ## Core Signs
- ### Sign: Read Before Writing
- - **Trigger**: Before modifying any file
- - **Instruction**: Always read the existing file first
- - **Added after**: Core principle
- ### Sign: Test After Changes
- - **Trigger**: After any code change
- - **Instruction**: Run tests to verify nothing broke
- - **Added after**: Core principle
- ### Sign: Commit Checkpoints
- - **Trigger**: Before risky changes
- - **Instruction**: Commit current working state first
- - **Added after**: Core principle
- ---
- ## Learned Signs
- (Signs added from observed failures will appear below)
- EOF
- cat > .ralph/progress.md << 'EOF'
- # Progress Log
- > Updated by the agent after significant work.
- ## Summary
- - Iterations completed: 0
- - Current status: Initialized
- ## How This Works
- Progress is tracked in THIS FILE, not in LLM context.
- When context is rotated (fresh agent), the new agent reads this file.
- This is how Ralph maintains continuity across iterations.
- ## Session History
- EOF
- cat > .ralph/errors.log << 'EOF'
- # Error Log
- > Failures detected by stream-parser. Use to update guardrails.
- EOF
- cat > .ralph/activity.log << 'EOF'
- # Activity Log
- > Real-time tool call logging from stream-parser.
- EOF
- echo "0" > .ralph/.iteration
- # =============================================================================
- # INSTALL SCRIPTS
- # =============================================================================
- echo "📦 Installing scripts..."
- # Copy scripts
- cp "$SKILL_DIR/scripts/"*.sh .cursor/ralph-scripts/ 2>/dev/null || true
- chmod +x .cursor/ralph-scripts/*.sh 2>/dev/null || true
- echo "✓ Scripts installed to .cursor/ralph-scripts/"
- # =============================================================================
- # UPDATE .gitignore
- # =============================================================================
- if [[ -f ".gitignore" ]]; then
- # Don't gitignore .ralph/ - we want it tracked for state persistence
- if ! grep -q "ralph-config.json" .gitignore; then
- echo "" >> .gitignore
- echo "# Ralph config (may contain API keys)" >> .gitignore
- echo ".cursor/ralph-config.json" >> .gitignore
- fi
- echo "✓ Updated .gitignore"
- else
- cat > .gitignore << 'EOF'
- # Ralph config (may contain API keys)
- .cursor/ralph-config.json
- EOF
- echo "✓ Created .gitignore"
- fi
- # =============================================================================
- # SUMMARY
- # =============================================================================
- echo ""
- echo "═══════════════════════════════════════════════════════════════════"
- echo "✅ Ralph initialized!"
- echo "═══════════════════════════════════════════════════════════════════"
- echo ""
- echo "Files created:"
- echo " • RALPH_TASK.md - Define your task here"
- echo " • .ralph/guardrails.md - Lessons learned (agent updates this)"
- echo " • .ralph/progress.md - Progress log (agent updates this)"
- echo " • .ralph/activity.log - Tool call log (parser updates this)"
- echo " • .ralph/errors.log - Failure log (parser updates this)"
- echo ""
- echo "Next steps:"
- echo " 1. Edit RALPH_TASK.md to define your task and criteria"
- echo " 2. Run: ./scripts/ralph-loop.sh"
- echo " (or: .cursor/ralph-scripts/ralph-loop.sh)"
- echo ""
- echo "The agent will work autonomously, rotating context as needed."
- echo "Monitor progress: tail -f .ralph/activity.log"
- echo ""
- echo "Learn more: https://ghuntley.com/ralph/"
- echo "═══════════════════════════════════════════════════════════════════"
scripts/ralph-common.sh · Bundled script · 832 lines · 1 finding marked
- #!/bin/bash
- # Ralph Wiggum: Common utilities and loop logic
- #
- # Shared functions for ralph-loop.sh and ralph-setup.sh
- # All state lives in .ralph/ within the project.
- # =============================================================================
- # SOURCE DEPENDENCIES
- # =============================================================================
- # Get the directory where this script lives
- _RALPH_SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
- # Source the task parser for YAML backend support
- if [[ -f "$_RALPH_SCRIPT_DIR/task-parser.sh" ]]; then
- source "$_RALPH_SCRIPT_DIR/task-parser.sh"
- _TASK_PARSER_AVAILABLE=1
- else
- _TASK_PARSER_AVAILABLE=0
- fi
- # =============================================================================
- # CONFIGURATION (can be overridden before sourcing)
- # =============================================================================
- # Token thresholds
- WARN_THRESHOLD="${WARN_THRESHOLD:-70000}"
- ROTATE_THRESHOLD="${ROTATE_THRESHOLD:-80000}"
- # Iteration limits
- MAX_ITERATIONS="${MAX_ITERATIONS:-20}"
- # Model selection
- DEFAULT_MODEL="opus-4.5-thinking"
- MODEL="${RALPH_MODEL:-$DEFAULT_MODEL}"
- # Feature flags (set by caller)
- USE_BRANCH="${USE_BRANCH:-}"
- OPEN_PR="${OPEN_PR:-false}"
- SKIP_CONFIRM="${SKIP_CONFIRM:-false}"
- # =============================================================================
- # SOURCE RETRY UTILITIES
- # =============================================================================
- # Source retry logic utilities
- SCRIPT_DIR="${SCRIPT_DIR:-$(dirname "${BASH_SOURCE[0]}")}"
- if [[ -f "$SCRIPT_DIR/ralph-retry.sh" ]]; then
- source "$SCRIPT_DIR/ralph-retry.sh"
- fi
- # =============================================================================
- # BASIC HELPERS
- # =============================================================================
- # Cross-platform sed -i
- sedi() {
- if [[ "$OSTYPE" == "darwin"* ]]; then
- sed -i '' "$@"
- else
- sed -i "$@"
- fi
- }
- # Get the .ralph directory for a workspace
- get_ralph_dir() {
- local workspace="${1:-.}"
- echo "$workspace/.ralph"
- }
- # Get current iteration from .ralph/.iteration
- get_iteration() {
- local workspace="${1:-.}"
- local state_file="$workspace/.ralph/.iteration"
- if [[ -f "$state_file" ]]; then
- cat "$state_file"
- else
- echo "0"
- fi
- }
- # Set iteration number
- set_iteration() {
- local workspace="${1:-.}"
- local iteration="$2"
- local ralph_dir="$workspace/.ralph"
- mkdir -p "$ralph_dir"
- echo "$iteration" > "$ralph_dir/.iteration"
- }
- # Increment iteration and return new value
- increment_iteration() {
- local workspace="${1:-.}"
- local current=$(get_iteration "$workspace")
- local next=$((current + 1))
- set_iteration "$workspace" "$next"
- echo "$next"
- }
- # Get context health emoji based on token count
- get_health_emoji() {
- local tokens="$1"
- local pct=$((tokens * 100 / ROTATE_THRESHOLD))
- if [[ $pct -lt 60 ]]; then
- echo "🟢"
- elif [[ $pct -lt 80 ]]; then
- echo "🟡"
- else
- echo "🔴"
- fi
- }
- # =============================================================================
- # LOGGING
- # =============================================================================
- # Log a message to activity.log
- log_activity() {
- local workspace="${1:-.}"
- local message="$2"
- local ralph_dir="$workspace/.ralph"
- local timestamp=$(date '+%H:%M:%S')
- mkdir -p "$ralph_dir"
- echo "[$timestamp] $message" >> "$ralph_dir/activity.log"
- }
- # Log an error to errors.log
- log_error() {
- local workspace="${1:-.}"
- local message="$2"
- local ralph_dir="$workspace/.ralph"
- local timestamp=$(date '+%H:%M:%S')
- mkdir -p "$ralph_dir"
- echo "[$timestamp] $message" >> "$ralph_dir/errors.log"
- }
- # Log to progress.md (called by the loop, not the agent)
- log_progress() {
- local workspace="$1"
- local message="$2"
- local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
- local progress_file="$workspace/.ralph/progress.md"
- echo "" >> "$progress_file"
- echo "### $timestamp" >> "$progress_file"
- echo "$message" >> "$progress_file"
- }
- # =============================================================================
- # INITIALIZATION
- # =============================================================================
- # Initialize .ralph directory with default files
- init_ralph_dir() {
- local workspace="$1"
- local ralph_dir="$workspace/.ralph"
- mkdir -p "$ralph_dir"
- # Initialize progress.md if it doesn't exist
- if [[ ! -f "$ralph_dir/progress.md" ]]; then
- cat > "$ralph_dir/progress.md" << 'EOF'
- # Progress Log
- > Updated by the agent after significant work.
- ---
- ## Session History
- EOF
- fi
- # Initialize guardrails.md if it doesn't exist
- if [[ ! -f "$ralph_dir/guardrails.md" ]]; then
- cat > "$ralph_dir/guardrails.md" << 'EOF'
- # Ralph Guardrails (Signs)
- > Lessons learned from past failures. READ THESE BEFORE ACTING.
- ## Core Signs
- ### Sign: Read Before Writing
- - **Trigger**: Before modifying any file
- - **Instruction**: Always read the existing file first
- - **Added after**: Core principle
- ### Sign: Test After Changes
- - **Trigger**: After any code change
- - **Instruction**: Run tests to verify nothing broke
- - **Added after**: Core principle
- ### Sign: Commit Checkpoints
- - **Trigger**: Before risky changes
- - **Instruction**: Commit current working state first
- - **Added after**: Core principle
- ---
- ## Learned Signs
- EOF
- fi
- # Initialize errors.log if it doesn't exist
- if [[ ! -f "$ralph_dir/errors.log" ]]; then
- cat > "$ralph_dir/errors.log" << 'EOF'
- # Error Log
- > Failures detected by stream-parser. Use to update guardrails.
- EOF
- fi
- # Initialize activity.log if it doesn't exist
- if [[ ! -f "$ralph_dir/activity.log" ]]; then
- cat > "$ralph_dir/activity.log" << 'EOF'
- # Activity Log
- > Real-time tool call logging from stream-parser.
- EOF
- fi
- }
- # =============================================================================
- # TASK MANAGEMENT
- # =============================================================================
- # Check if task is complete
- # Uses task-parser.sh when available for cached/YAML support
- check_task_complete() {
- local workspace="$1"
- local task_file="$workspace/RALPH_TASK.md"
- if [[ ! -f "$task_file" ]]; then
- echo "NO_TASK_FILE"
- return
- fi
- # Use task parser if available (provides caching)
- if [[ "${_TASK_PARSER_AVAILABLE:-0}" -eq 1 ]]; then
- local remaining
- remaining=$(count_remaining "$workspace" 2>/dev/null) || remaining=-1
- if [[ "$remaining" -eq 0 ]]; then
- echo "COMPLETE"
- elif [[ "$remaining" -gt 0 ]]; then
- echo "INCOMPLETE:$remaining"
- else
- # Fallback to direct grep if parser fails
- _check_task_complete_direct "$workspace"
- fi
- else
- _check_task_complete_direct "$workspace"
- fi
- }
- # Direct task completion check (fallback)
- _check_task_complete_direct() {
- local workspace="$1"
- local task_file="$workspace/RALPH_TASK.md"
- # Only count actual checkbox list items, not [ ] in prose/examples
- # Matches: "- [ ]", "* [ ]", "1. [ ]", etc.
- local unchecked
- unchecked=$(grep -cE '^[[:space:]]*([-*]|[0-9]+\.)[[:space:]]+\[ \]' "$task_file" 2>/dev/null) || unchecked=0
- if [[ "$unchecked" -eq 0 ]]; then
- echo "COMPLETE"
- else
- echo "INCOMPLETE:$unchecked"
- fi
- }
- # Count task criteria (returns done:total)
- # Uses task-parser.sh when available for cached/YAML support
- count_criteria() {
- local workspace="${1:-.}"
- local task_file="$workspace/RALPH_TASK.md"
- if [[ ! -f "$task_file" ]]; then
- echo "0:0"
- return
- fi
- # Use task parser if available (provides caching)
- if [[ "${_TASK_PARSER_AVAILABLE:-0}" -eq 1 ]]; then
- local progress
- progress=$(get_progress "$workspace" 2>/dev/null) || progress=""
- if [[ -n "$progress" ]] && [[ "$progress" =~ ^[0-9]+:[0-9]+$ ]]; then
- echo "$progress"
- else
- # Fallback to direct grep if parser fails
- _count_criteria_direct "$workspace"
- fi
- else
- _count_criteria_direct "$workspace"
- fi
- }
- # Direct criteria counting (fallback)
- _count_criteria_direct() {
- local workspace="${1:-.}"
- local task_file="$workspace/RALPH_TASK.md"
- # Only count actual checkbox list items, not [x] or [ ] in prose/examples
- # Matches: "- [ ]", "* [x]", "1. [ ]", etc.
- local total done_count
- total=$(grep -cE '^[[:space:]]*([-*]|[0-9]+\.)[[:space:]]+\[(x| )\]' "$task_file" 2>/dev/null) || total=0
- done_count=$(grep -cE '^[[:space:]]*([-*]|[0-9]+\.)[[:space:]]+\[x\]' "$task_file" 2>/dev/null) || done_count=0
- echo "$done_count:$total"
- }
- # =============================================================================
- # TASK PARSER CONVENIENCE WRAPPERS
- # =============================================================================
- # Get the next task to work on (wrapper for task-parser.sh)
- # Returns: task_id|status|description or empty
- get_next_task_info() {
- local workspace="${1:-.}"
- if [[ "${_TASK_PARSER_AVAILABLE:-0}" -eq 1 ]]; then
- get_next_task "$workspace"
- else
- echo ""
- fi
- }
- # Mark a specific task complete by line-based ID
- # Usage: complete_task "$workspace" "line_15"
- complete_task() {
- local workspace="${1:-.}"
- local task_id="$2"
- if [[ "${_TASK_PARSER_AVAILABLE:-0}" -eq 1 ]]; then
- mark_task_complete "$workspace" "$task_id"
- else
- echo "ERROR: Task parser not available" >&2
- return 1
- fi
- }
- # List all tasks with their status
- # Usage: list_all_tasks "$workspace"
- list_all_tasks() {
- local workspace="${1:-.}"
- if [[ "${_TASK_PARSER_AVAILABLE:-0}" -eq 1 ]]; then
- get_all_tasks "$workspace"
- else
- echo "ERROR: Task parser not available" >&2
- return 1
- fi
- }
- # Refresh task cache (useful after external edits)
- refresh_task_cache() {
- local workspace="${1:-.}"
- if [[ "${_TASK_PARSER_AVAILABLE:-0}" -eq 1 ]]; then
- # Invalidate and re-parse
- rm -f "$workspace/.ralph/$TASK_MTIME_FILE" 2>/dev/null
- parse_tasks "$workspace"
- fi
- }
- # =============================================================================
- # PROMPT BUILDING
- # =============================================================================
- # Build the Ralph prompt for an iteration
- build_prompt() {
- local workspace="$1"
- local iteration="$2"
- cat << EOF
- # Ralph Iteration $iteration
- You are an autonomous development agent using the Ralph methodology.
- ## FIRST: Read State Files
- Before doing anything:
- 1. Read \`RALPH_TASK.md\` - your task and completion criteria
- 2. Read \`.ralph/guardrails.md\` - lessons from past failures (FOLLOW THESE)
- 3. Read \`.ralph/progress.md\` - what's been accomplished
- 4. Read \`.ralph/errors.log\` - recent failures to avoid
- ## Working Directory (Critical)
- You are already in a git repository. Work HERE, not in a subdirectory:
- - Do NOT run \`git init\` - the repo already exists
- - Do NOT run scaffolding commands that create nested directories (\`npx create-*\`, \`pnpm init\`, etc.)
- - If you need to scaffold, use flags like \`--no-git\` or scaffold into the current directory (\`.\`)
- - All code should live at the repo root or in subdirectories you create manually
- ## Git Protocol (Critical)
- Ralph's strength is state-in-git, not LLM memory. Commit early and often:
- 1. After completing each criterion, commit your changes:
- \`git add -A && git commit -m 'ralph: implement state tracker'\`
- \`git add -A && git commit -m 'ralph: fix async race condition'\`
- \`git add -A && git commit -m 'ralph: add CLI adapter with commander'\`
- Always describe what you actually did - never use placeholders like '<description>'
- 2. After any significant code change (even partial): commit with descriptive message
- 3. Before any risky refactor: commit current state as checkpoint
- 4. Push after every 2-3 commits: \`git push\`
- If you get rotated, the next agent picks up from your last commit. Your commits ARE your memory.
- ## Task Execution
- 1. Work on the next unchecked criterion in RALPH_TASK.md (look for \`[ ]\`)
- 2. Run tests after changes (check RALPH_TASK.md for test_command)
- 3. **Mark completed criteria**: Edit RALPH_TASK.md and change \`[ ]\` to \`[x]\`
- - Example: \`- [ ] Implement parser\` becomes \`- [x] Implement parser\`
- - This is how progress is tracked - YOU MUST update the file
- 4. Update \`.ralph/progress.md\` with what you accomplished
- 5. When ALL criteria show \`[x]\`: output \`<ralph>COMPLETE</ralph>\`
- 6. If stuck 3+ times on same issue: output \`<ralph>GUTTER</ralph>\`
- ## Learning from Failures
- When something fails:
- 1. Check \`.ralph/errors.log\` for failure history
- 2. Figure out the root cause
- 3. Add a Sign to \`.ralph/guardrails.md\` using this format:
- \`\`\`
- ### Sign: [Descriptive Name]
- - **Trigger**: When this situation occurs
- - **Instruction**: What to do instead
- - **Added after**: Iteration $iteration - what happened
- \`\`\`
- ## Context Rotation Warning
- You may receive a warning that context is running low. When you see it:
- 1. Finish your current file edit
- 2. Commit and push your changes
- 3. Update .ralph/progress.md with what you accomplished and what's next
- 4. You will be rotated to a fresh agent that continues your work
- Begin by reading the state files.
- EOF
- }
- # =============================================================================
- # SPINNER
- # =============================================================================
- # Spinner to show the loop is alive (not frozen)
- # Outputs to stderr so it's not captured by $()
- spinner() {
- local workspace="$1"
- local spin='⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏'
- local i=0
- while true; do
- printf "\r 🐛 Agent working... %s (watch: tail -f %s/.ralph/activity.log)" "${spin:i++%${#spin}:1}" "$workspace" >&2
- sleep 0.1
- done
- }
- # =============================================================================
- # ITERATION RUNNER
- # =============================================================================
- # Run a single agent iteration
- # Returns: signal (ROTATE, GUTTER, COMPLETE, or empty)
- run_iteration() {
- local workspace="$1"
- local iteration="$2"
- local session_id="${3:-}"
- local script_dir="${4:-$(dirname "${BASH_SOURCE[0]}")}"
- local prompt=$(build_prompt "$workspace" "$iteration")
- local fifo="$workspace/.ralph/.parser_fifo"
- # Create named pipe for parser signals
- rm -f "$fifo"
- mkfifo "$fifo"
- # Use stderr for display (stdout is captured for signal)
- echo "" >&2
- echo "═══════════════════════════════════════════════════════════════════" >&2
- echo "🐛 Ralph Iteration $iteration" >&2
- echo "═══════════════════════════════════════════════════════════════════" >&2
- echo "" >&2
- echo "Workspace: $workspace" >&2
- echo "Model: $MODEL" >&2
- echo "Monitor: tail -f $workspace/.ralph/activity.log" >&2
- echo "" >&2
- # Log session start to progress.md
- log_progress "$workspace" "**Session $iteration started** (model: $MODEL)"
- # Build cursor-agent command
- local cmd="cursor-agent -p --force --output-format stream-json --model $MODEL"
- if [[ -n "$session_id" ]]; then
- echo "Resuming session: $session_id" >&2
- cmd="$cmd --resume=\"$session_id\""
- fi
- # Change to workspace
- cd "$workspace"
- # Start spinner to show we're alive
- spinner "$workspace" &
- local spinner_pid=$!
- # Start parser in background, reading from cursor-agent
- # Parser outputs to fifo, we read signals from fifo
- (
- eval "$cmd \"$prompt\"" 2>&1 | "$script_dir/stream-parser.sh" "$workspace" > "$fifo"
- ) &
- local agent_pid=$!
- # Read signals from parser
- local signal=""
- while IFS= read -r line; do
- case "$line" in
- "ROTATE")
- printf "\r\033[K" >&2 # Clear spinner line
- echo "🔄 Context rotation triggered - stopping agent..." >&2
- kill $agent_pid 2>/dev/null || true
- signal="ROTATE"
- break
- ;;
- "WARN")
- printf "\r\033[K" >&2 # Clear spinner line
- echo "⚠️ Context warning - agent should wrap up soon..." >&2
- # Send interrupt to encourage wrap-up (agent continues but is notified)
- ;;
- "GUTTER")
- printf "\r\033[K" >&2 # Clear spinner line
- echo "🚨 Gutter detected - agent may be stuck..." >&2
- signal="GUTTER"
- # Don't kill yet, let agent try to recover
- ;;
- "COMPLETE")
- printf "\r\033[K" >&2 # Clear spinner line
- echo "✅ Agent signaled completion!" >&2
- signal="COMPLETE"
- # Let agent finish gracefully
- ;;
- "DEFER")
- printf "\r\033[K" >&2 # Clear spinner line
- echo "⏸️ Rate limit or transient error - deferring for retry..." >&2
- signal="DEFER"
- # Stop the agent, will retry with backoff
- kill $agent_pid 2>/dev/null || true
- ;;
- esac
- done < "$fifo"
- # Wait for agent to finish
- wait $agent_pid 2>/dev/null || true
- # Stop spinner and clear line
- kill $spinner_pid 2>/dev/null || true
- wait $spinner_pid 2>/dev/null || true
- printf "\r\033[K" >&2 # Clear spinner line
- # Cleanup
- rm -f "$fifo"
- echo "$signal"
- }
- # =============================================================================
- # MAIN LOOP
- # =============================================================================
- # Run the main Ralph loop
- # Args: workspace
- # Uses global: MAX_ITERATIONS, MODEL, USE_BRANCH, OPEN_PR
- run_ralph_loop() {
- local workspace="$1"
- local script_dir="${2:-$(dirname "${BASH_SOURCE[0]}")}"
- # Commit any uncommitted work first
- cd "$workspace"
- if [[ -n "$(git status --porcelain 2>/dev/null)" ]]; then
- echo "📦 Committing uncommitted changes..."
- git add -A
- git commit -m "ralph: initial commit before loop" || true
- fi
- # Create branch if requested
- if [[ -n "$USE_BRANCH" ]]; then
- echo "🌿 Creating branch: $USE_BRANCH"
- git checkout -b "$USE_BRANCH" 2>/dev/null || git checkout "$USE_BRANCH"
- fi
- echo ""
- echo "🚀 Starting Ralph loop..."
- echo ""
- # Main loop
- local iteration=1
- local session_id=""
- while [[ $iteration -le $MAX_ITERATIONS ]]; do
- # Run iteration
- local signal
- signal=$(run_iteration "$workspace" "$iteration" "$session_id" "$script_dir")
- # Check task completion
- local task_status
- task_status=$(check_task_complete "$workspace")
- if [[ "$task_status" == "COMPLETE" ]]; then
- log_progress "$workspace" "**Session $iteration ended** - ✅ TASK COMPLETE"
- echo ""
- echo "═══════════════════════════════════════════════════════════════════"
- echo "🎉 RALPH COMPLETE! All criteria satisfied."
- echo "═══════════════════════════════════════════════════════════════════"
- echo ""
- echo "Completed in $iteration iteration(s)."
- echo "Check git log for detailed history."
- # Open PR if requested
- if [[ "$OPEN_PR" == "true" ]] && [[ -n "$USE_BRANCH" ]]; then
- echo ""
- echo "📝 Opening pull request..."
- git push -u origin "$USE_BRANCH" 2>/dev/null || git push
- if command -v gh &> /dev/null; then
- gh pr create --fill || echo "⚠️ Could not create PR automatically. Create manually."
- else
- echo "⚠️ gh CLI not found. Push complete, create PR manually."
- fi
- fi
- return 0
- fi
- # Handle signals
- case "$signal" in
- "COMPLETE")
- # Agent signaled completion - verify with checkbox check
- if [[ "$task_status" == "COMPLETE" ]]; then
- log_progress "$workspace" "**Session $iteration ended** - ✅ TASK COMPLETE (agent signaled)"
- echo ""
- echo "═══════════════════════════════════════════════════════════════════"
- echo "🎉 RALPH COMPLETE! Agent signaled completion and all criteria verified."
- echo "═══════════════════════════════════════════════════════════════════"
- echo ""
- echo "Completed in $iteration iteration(s)."
- echo "Check git log for detailed history."
- # Open PR if requested
- if [[ "$OPEN_PR" == "true" ]] && [[ -n "$USE_BRANCH" ]]; then
- echo ""
- echo "📝 Opening pull request..."
- git push -u origin "$USE_BRANCH" 2>/dev/null || git push
- if command -v gh &> /dev/null; then
- gh pr create --fill || echo "⚠️ Could not create PR automatically. Create manually."
- else
- echo "⚠️ gh CLI not found. Push complete, create PR manually."
- fi
- fi
- return 0
- else
- # Agent said complete but checkboxes say otherwise - continue
- log_progress "$workspace" "**Session $iteration ended** - Agent signaled complete but criteria remain"
- echo ""
- echo "⚠️ Agent signaled completion but unchecked criteria remain."
- echo " Continuing with next iteration..."
- iteration=$((iteration + 1))
- fi
- ;;
- "ROTATE")
- log_progress "$workspace" "**Session $iteration ended** - 🔄 Context rotation (token limit reached)"
- echo ""
- echo "🔄 Rotating to fresh context..."
- iteration=$((iteration + 1))
- session_id=""
- ;;
- "GUTTER")
- log_progress "$workspace" "**Session $iteration ended** - 🚨 GUTTER (agent stuck)"
- echo ""
- echo "🚨 Gutter detected. Check .ralph/errors.log for details."
- echo " The agent may be stuck. Consider:"
- echo " 1. Check .ralph/guardrails.md for lessons"
- echo " 2. Manually fix the blocking issue"
- echo " 3. Re-run the loop"
- return 1
- ;;
- "DEFER")
- # Rate limit or transient error - wait with exponential backoff then retry
- log_progress "$workspace" "**Session $iteration ended** - ⏸️ DEFERRED (rate limit/transient error)"
- # Calculate backoff delay (uses ralph-retry.sh functions if available)
- local defer_delay=30
- if type calculate_backoff_delay &>/dev/null; then
- local defer_attempt=${DEFER_COUNT:-1}
- DEFER_COUNT=$((defer_attempt + 1))
- defer_delay=$(($(calculate_backoff_delay "$defer_attempt" 15 120 true) / 1000))
- fi
- echo ""
- echo "⏸️ Rate limit or transient error detected."
- echo " Waiting ${defer_delay}s before retrying (attempt ${DEFER_COUNT:-1})..."
- sleep "$defer_delay"
- # Don't increment iteration - retry the same task
- echo " Resuming..."
- ;;
- *)
- # Agent finished naturally, check if more work needed
- if [[ "$task_status" == INCOMPLETE:* ]]; then
- local remaining_count=${task_status#INCOMPLETE:}
- log_progress "$workspace" "**Session $iteration ended** - Agent finished naturally ($remaining_count criteria remaining)"
- echo ""
- echo "📋 Agent finished but $remaining_count criteria remaining."
- echo " Starting next iteration..."
- iteration=$((iteration + 1))
- fi
- ;;
- esac
- # Brief pause between iterations
- sleep 2
- done
- log_progress "$workspace" "**Loop ended** - ⚠️ Max iterations ($MAX_ITERATIONS) reached"
- echo ""
- echo "⚠️ Max iterations ($MAX_ITERATIONS) reached."
- echo " Task may not be complete. Check progress manually."
- return 1
- }
- # =============================================================================
- # PREREQUISITE CHECKS
- # =============================================================================
- # Check all prerequisites, exit with error message if any fail
- check_prerequisites() {
- local workspace="$1"
- local task_file="$workspace/RALPH_TASK.md"
- # Check for task file
- if [[ ! -f "$task_file" ]]; then
- echo "❌ No RALPH_TASK.md found in $workspace"
- echo ""
- echo "Create a task file first:"
- echo " cat > RALPH_TASK.md << 'EOF'"
- echo " ---"
- echo " task: Your task description"
- echo " test_command: \"pnpm test\""
- echo " ---"
- echo " # Task"
- echo " ## Success Criteria"
- echo " 1. [ ] First thing to do"
- echo " 2. [ ] Second thing to do"
- echo " EOF"
- return 1
- fi
- # Check for cursor-agent CLI
- if ! command -v cursor-agent &> /dev/null; then
- echo "❌ cursor-agent CLI not found"
- echo ""
- echo "Install via:"
- echo " curl https://cursor.com/install -fsS | bash"
- Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
- Line 778 on GitHub
- return 1
- fi
- # Check for git repo
- if ! git -C "$workspace" rev-parse --git-dir > /dev/null 2>&1; then
- echo "❌ Not a git repository"
- echo " Ralph requires git for state persistence."
- return 1
- fi
- return 0
- }
- # =============================================================================
- # DISPLAY HELPERS
- # =============================================================================
- # Show task summary
- show_task_summary() {
- local workspace="$1"
- local task_file="$workspace/RALPH_TASK.md"
- echo "📋 Task Summary:"
- echo "─────────────────────────────────────────────────────────────────"
- head -30 "$task_file"
- echo "─────────────────────────────────────────────────────────────────"
- echo ""
- # Count criteria - only actual checkbox list items (- [ ], * [x], 1. [ ], etc.)
- local total_criteria done_criteria remaining
- total_criteria=$(grep -cE '^[[:space:]]*([-*]|[0-9]+\.)[[:space:]]+\[(x| )\]' "$task_file" 2>/dev/null) || total_criteria=0
- done_criteria=$(grep -cE '^[[:space:]]*([-*]|[0-9]+\.)[[:space:]]+\[x\]' "$task_file" 2>/dev/null) || done_criteria=0
- remaining=$((total_criteria - done_criteria))
- echo "Progress: $done_criteria / $total_criteria criteria complete ($remaining remaining)"
- echo "Model: $MODEL"
- echo ""
- # Return remaining count for caller to check
- echo "$remaining"
- }
- # Show Ralph banner
- show_banner() {
- echo "═══════════════════════════════════════════════════════════════════"
- echo "🐛 Ralph Wiggum: Autonomous Development Loop"
- echo "═══════════════════════════════════════════════════════════════════"
- echo ""
- echo " \"That's the beauty of Ralph - the technique is deterministically"
- echo " bad in an undeterministic world.\""
- echo ""
- echo "═══════════════════════════════════════════════════════════════════"
- echo ""
- }
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.