Skip to content
Back to search

ralph-wiggum

SkillWorks with Claude CodeGitHub

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.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/agrimsingh--ralph-wiggum-cursor/badge.svg)](/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

i

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)

  1. ---
  2. name: ralph-wiggum
  3. 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.
  4. license: MIT
  5. compatibility: Designed for Cursor (nightly). Requires bash, jq, git.
  6. metadata:
  7. author: Based on Geoffrey Huntley's Ralph technique
  8. version: "1.0.0"
  9. original: https://ghuntley.com/ralph/
  10. ---
  11. # Ralph Wiggum: Autonomous Iteration with Context Engineering
  12. 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.
  13. ## Core Philosophy
  14. > "That's the beauty of Ralph - the technique is deterministically bad in an undeterministic world."
  15. 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.
  16. ### The malloc/free Metaphor
  17. - **Context is memory**: Everything loaded into the LLM's context window stays there
  18. - **You cannot free() context**: The only way to clear context is to start a new conversation
  19. - **One task per context**: Mixed concerns lead to autoregressive failure
  20. - **Don't redline**: Pushing context to limits degrades performance
  21. - **Gutter detection**: Once the bowling ball is in the gutter, start fresh
  22. ## How This Skill Works
  23. ### State Files (The Persistent Memory)
  24. Ralph tracks state in files, NOT in context:
  25. ```
  26. .ralph/
  27. ├── state.md # Current iteration, task, completion criteria
  28. ├── guardrails.md # Accumulated "signs" from observed failures
  29. ├── context-log.md # What's been loaded into context
  30. ├── failures.md # Failure patterns for learning
  31. └── progress.md # What's been accomplished
  32. ```
  33. ### The Iteration Cycle
  34. 1. **Read state files** to understand current task and progress
  35. 2. **Check guardrails** for relevant "signs" to follow
  36. 3. **Work on the task** - implement, test, refine
  37. 4. **Update progress** in files (not just context)
  38. 5. **Commit checkpoint** via git
  39. 6. **Evaluate completion** against criteria
  40. 7. **If not complete**: Signal for next iteration
  41. 8. **If stuck**: Detect gutter, suggest fresh context
  42. ### Guardrails ("Signs")
  43. When Ralph makes a mistake, add a sign:
  44. ```markdown
  45. ## Sign: Don't Jump Off The Slide
  46. - **Trigger**: When implementing authentication
  47. - **Instruction**: Always validate tokens before trusting claims
  48. - **Added after**: Iteration 5 - security vulnerability introduced
  49. ```
  50. Signs accumulate in `guardrails.md` and are injected into future iterations.
  51. ## Usage
  52. ### Starting a Ralph Loop
  53. Create a `RALPH_TASK.md` file in your project root:
  54. ```markdown
  55. ---
  56. task: Build a REST API for task management
  57. completion_criteria:
  58. - All CRUD endpoints working
  59. - Input validation implemented
  60. - Tests passing with >80% coverage
  61. - API documentation complete
  62. max_iterations: 50
  63. ---
  64. ## Requirements
  65. Build a task management API with the following endpoints:
  66. - POST /tasks - Create a task
  67. - GET /tasks - List all tasks
  68. - GET /tasks/:id - Get a task
  69. - PUT /tasks/:id - Update a task
  70. - DELETE /tasks/:id - Delete a task
  71. ## Constraints
  72. - Use TypeScript
  73. - Use Express.js
  74. - Use SQLite for storage
  75. - Follow REST conventions
  76. ```
  77. Then tell Cursor: "Start a Ralph loop on this task"
  78. ### Monitoring Progress
  79. Check `.ralph/progress.md` to see what's been accomplished:
  80. ```markdown
  81. ## Iteration 1
  82. - Created project structure
  83. - Implemented POST /tasks endpoint
  84. - Status: Partial progress
  85. ## Iteration 2
  86. - Added GET endpoints
  87. - Fixed validation bug
  88. - Status: Continuing
  89. ```
  90. ### When to Start Fresh
  91. Ralph will detect "gutter" situations:
  92. - Same error repeated 3+ times
  93. - Context approaching limits
  94. - Circular failure patterns
  95. When detected, Ralph will suggest: "Context is polluted. Recommend starting fresh conversation."
  96. ## Best Practices
  97. ### 1. Clear Completion Criteria
  98. ❌ Bad: "Make a good API"
  99. ✅ Good: "All tests passing, coverage >80%, docs complete"
  100. ### 2. Incremental Goals
  101. ❌ Bad: "Build complete e-commerce platform"
  102. ✅ Good: Phase 1: Auth, Phase 2: Products, Phase 3: Cart
  103. ### 3. Let Failures Teach
  104. Don't intervene too quickly. Let Ralph fail, then add signs.
  105. ### 4. Trust the Files
  106. Progress is in files and git, not in your head or the context.
  107. ### 5. Fresh Context is Cheap
  108. Don't hesitate to start fresh. State persists in files.
  109. ## Integration with Cursor Hooks
  110. This skill uses Cursor hooks for:
  111. - **beforeSubmitPrompt**: Inject guardrails and context awareness
  112. - **beforeReadFile**: Track context allocations
  113. - **afterFileEdit**: Update progress tracking
  114. - **stop**: Evaluate completion, trigger next iteration or fresh start
  115. See `scripts/` for hook implementations.
  116. ## Learn More
  117. - Original technique: https://ghuntley.com/ralph/
  118. - Context engineering: https://ghuntley.com/gutter/
  119. - 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)

  1. # Ralph Wiggum for Cursor
  2. An implementation of [Geoffrey Huntley's Ralph Wiggum technique](https://ghuntley.com/ralph/) for Cursor, enabling autonomous AI development with deliberate context management.
  3. > "That's the beauty of Ralph - the technique is deterministically bad in an undeterministic world."
  4. ## What is Ralph?
  5. Ralph is a technique for autonomous AI development that treats LLM context like memory:
  6. ```bash
  7. while :; do cat PROMPT.md | agent ; done
  8. ```
  9. 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.
  10. ### The malloc/free Problem
  11. In traditional programming:
  12. - `malloc()` allocates memory
  13. - `free()` releases memory
  14. In LLM context:
  15. - Reading files, tool outputs, conversation = `malloc()`
  16. - **There is no `free()`** - context cannot be selectively released
  17. - Only way to free: start a new conversation
  18. This creates two problems:
  19. 1. **Context pollution** - Failed attempts, unrelated code, and mixed concerns accumulate and confuse the model
  20. 2. **The gutter** - Once polluted, the model keeps referencing bad context. Like a bowling ball in the gutter, there's no saving it.
  21. **Ralph's solution:** Deliberately rotate to fresh context before pollution builds up. State lives in files and git, not in the LLM's memory.
  22. ## Architecture
  23. ```
  24. ┌─────────────────────────────────────────────────────────────┐
  25. │ ralph-setup.sh │
  26. │ │ │
  27. │ ┌────────────┴────────────┐ │
  28. │ ▼ ▼ │
  29. │ [gum UI] [fallback] │
  30. │ Model selection Simple prompts │
  31. │ Max iterations │
  32. │ Options (branch, PR) │
  33. │ │ │ │
  34. │ └────────────┬────────────┘ │
  35. │ ▼ │
  36. │ cursor-agent -p --force --output-format stream-json │
  37. │ │ │
  38. │ ▼ │
  39. │ stream-parser.sh │
  40. │ │ │ │
  41. │ ┌────────────────┴────────┴────────────────┐ │
  42. │ ▼ ▼ │
  43. │ .ralph/ Signals │
  44. │ ├── activity.log (tool calls) ├── WARN at 70k │
  45. │ ├── errors.log (failures) ├── ROTATE at 80k│
  46. │ ├── progress.md (agent writes) ├── COMPLETE │
  47. │ ├── guardrails.md (lessons learned) ├── GUTTER │
  48. │ └── tasks.yaml (cached task state) └── DEFER │
  49. │ │
  50. │ When ROTATE → fresh context, continue from git │
  51. │ When DEFER → exponential backoff, retry same task │
  52. └─────────────────────────────────────────────────────────────┘
  53. ```
  54. **Key features:**
  55. - **Interactive setup** - Beautiful gum-based UI for model selection and options
  56. - **Accurate token tracking** - Parser counts actual bytes from every file read/write
  57. - **Gutter detection** - Detects when agent is stuck (same command failed 3x, file thrashing)
  58. - **Rate limit handling** - Detects rate limits/network errors, waits with exponential backoff
  59. - **Task caching** - YAML backend with mtime invalidation for efficient task parsing
  60. - **Learning from failures** - Agent updates `.ralph/guardrails.md` with lessons
  61. - **State in git** - Commits frequently so next agent picks up from git history
  62. - **Branch/PR workflow** - Optionally work on a branch and open PR when complete
  63. ## Prerequisites
  64. | Requirement | Check | How to Set Up |
  65. |-------------|-------|---------------|
  66. | **Git repo** | `git status` works | `git init` |
  67. | **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
  68. | **gum** (optional) | `which gum` | Installer offers to install, or `brew install gum` |
  69. ## Quick Start
  70. ### 1. Install Ralph
  71. ```bash
  72. cd your-project
  73. 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
  74. ```
  75. This creates:
  76. ```
  77. your-project/
  78. ├── .cursor/ralph-scripts/ # Ralph scripts
  79. │ ├── ralph-setup.sh # Main entry point (interactive)
  80. │ ├── ralph-loop.sh # CLI mode (for scripting)
  81. │ ├── ralph-once.sh # Single iteration (testing)
  82. │ ├── ralph-parallel.sh # Parallel execution with worktrees
  83. │ ├── stream-parser.sh # Token tracking + error detection
  84. │ ├── ralph-common.sh # Shared functions
  85. │ ├── ralph-retry.sh # Exponential backoff retry logic
  86. │ ├── task-parser.sh # YAML-backed task parsing
  87. │ └── init-ralph.sh # Re-initialize if needed
  88. ├── .ralph/ # State files (tracked in git)
  89. │ ├── progress.md # Agent updates: what's done
  90. │ ├── guardrails.md # Lessons learned (Signs)
  91. │ ├── activity.log # Tool call log (parser writes)
  92. │ ├── errors.log # Failure log (parser writes)
  93. │ └── tasks.yaml # Cached task state (auto-generated)
  94. ├── .ralph-worktrees/ # Temporary (parallel mode only)
  95. └── RALPH_TASK.md # Your task definition
  96. ```
  97. ### 2. (Optional) gum for Enhanced UI
  98. The installer will offer to install gum automatically. You can also:
  99. - Skip the prompt and auto-install: `curl ... | INSTALL_GUM=1 bash`
  100. - Install manually: `brew install gum` (macOS) or see [gum installation](https://github.com/charmbracelet/gum#installation)
  101. With gum, you get a beautiful interactive menu for selecting models and options:
  102. ```
  103. ? Select model:
  104. ◉ opus-4.5-thinking
  105. ◯ sonnet-4.5-thinking
  106. ◯ gpt-5.2-high
  107. ◯ composer-1
  108. ◯ Custom...
  109. ? Max iterations: 20
  110. ? Options:
  111. ◯ Commit to current branch
  112. ◯ Run single iteration first
  113. ◯ Work on new branch
  114. ◯ Open PR when complete
  115. ◯ Run in parallel mode ← runs multiple agents concurrently
  116. ```
  117. If you select "Run in parallel mode", you'll be prompted for:
  118. ```
  119. ? Max parallel agents: 3 ← default is 3, enter any number
  120. ```
  121. Without gum, Ralph falls back to simple numbered prompts.
  122. ### 3. Define Your Task
  123. Edit `RALPH_TASK.md`:
  124. ```markdown
  125. ---
  126. task: Build a REST API
  127. test_command: "pnpm test"
  128. ---
  129. # Task: REST API
  130. Build a REST API with user management.
  131. ## Success Criteria
  132. 1. [ ] GET /health returns 200
  133. 2. [ ] POST /users creates a user
  134. 3. [ ] GET /users/:id returns user
  135. 4. [ ] All tests pass
  136. ## Context
  137. - Use Express.js
  138. - Store users in memory (no database needed)
  139. ```
  140. **Important:** Use `[ ]` checkboxes. Ralph tracks completion by counting unchecked boxes.
  141. ### 4. Start the Loop
  142. ```bash
  143. ./.cursor/ralph-scripts/ralph-setup.sh
  144. ```
  145. Ralph will:
  146. 1. Show interactive UI for model and options (or simple prompts if gum not installed)
  147. 2. Run `cursor-agent` with your task
  148. 3. Parse output in real-time, tracking token usage
  149. 4. At 70k tokens: warn agent to wrap up current work
  150. 5. At 80k tokens: rotate to fresh context
  151. 6. Repeat until all `[ ]` are `[x]` (or max iterations reached)
  152. ### 5. Monitor Progress
  153. ```bash
  154. # Watch activity in real-time
  155. tail -f .ralph/activity.log
  156. # Example output:
  157. # [12:34:56] 🟢 READ src/index.ts (245 lines, ~24.5KB)
  158. # [12:34:58] 🟢 WRITE src/routes/users.ts (50 lines, 2.1KB)
  159. # [12:35:01] 🟢 SHELL pnpm test → exit 0
  160. # [12:35:10] 🟢 TOKENS: 45,230 / 80,000 (56%) [read:30KB write:5KB assist:10KB shell:0KB]
  161. # Check for failures
  162. cat .ralph/errors.log
  163. ```
  164. ## Commands
  165. | Command | Description |
  166. |---------|-------------|
  167. | `ralph-setup.sh` | **Primary** - Interactive setup + run loop |
  168. | `ralph-once.sh` | Test single iteration before going AFK |
  169. | `ralph-loop.sh` | CLI mode for scripting (see flags below) |
  170. | `init-ralph.sh` | Re-initialize Ralph state |
  171. ### ralph-loop.sh Flags (for scripting/CI)
  172. ```bash
  173. ./ralph-loop.sh [options] [workspace]
  174. Options:
  175. -n, --iterations N Max iterations (default: 20)
  176. -m, --model MODEL Model to use (default: opus-4.5-thinking)
  177. --branch NAME Sequential: create/work on branch; Parallel: integration branch name
  178. --pr Sequential: open PR (requires --branch); Parallel: open ONE integration PR (branch optional)
  179. --parallel Run tasks in parallel with worktrees
  180. --max-parallel N Max parallel agents (default: 3)
  181. --no-merge Skip auto-merge in parallel mode
  182. -y, --yes Skip confirmation prompt
  183. ```
  184. **Examples:**
  185. ```bash
  186. # Scripted PR workflow
  187. ./ralph-loop.sh --branch feature/api --pr -y
  188. # Use a different model with more iterations
  189. ./ralph-loop.sh -n 50 -m gpt-5.2-high
  190. # Run 4 agents in parallel
  191. ./ralph-loop.sh --parallel --max-parallel 4
  192. # Parallel: keep branches separate
  193. ./ralph-loop.sh --parallel --no-merge
  194. # Parallel: merge into an integration branch + open ONE PR
  195. ./ralph-loop.sh --parallel --max-parallel 5 --branch feature/multi-task --pr
  196. # Parallel: open ONE PR using an auto-named integration branch
  197. ./ralph-loop.sh --parallel --max-parallel 5 --pr
  198. ```
  199. ## Parallel Execution
  200. Ralph can run multiple agents concurrently, each in an isolated git worktree.
  201. ### Starting Parallel Mode
  202. **Via gum UI (interactive):**
  203. ```bash
  204. ./ralph-setup.sh
  205. # Select "Run in parallel mode" in options
  206. # Enter number of agents when prompted (default: 3, no upper limit)
  207. ```
  208. **Via CLI (scripting/CI):**
  209. ```bash
  210. # Run 3 agents in parallel (default)
  211. ./ralph-loop.sh --parallel
  212. # Run 10 agents in parallel (no hard cap)
  213. ./ralph-loop.sh --parallel --max-parallel 10
  214. # Keep branches separate (no auto-merge)
  215. ./ralph-loop.sh --parallel --no-merge
  216. # Merge into an integration branch (no PR)
  217. ./ralph-loop.sh --parallel --max-parallel 5 --branch feature/multi-task
  218. # Merge into an integration branch and open ONE PR
  219. ./ralph-loop.sh --parallel --max-parallel 5 --branch feature/multi-task --pr
  220. # Open ONE PR using an auto-named integration branch
  221. ./ralph-loop.sh --parallel --max-parallel 5 --pr
  222. ```
  223. > **Note:** There's no hard limit on `--max-parallel`. The practical limit depends on your machine's resources and API rate limits.
  224. ### Integration branch + single PR
  225. 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.
  226. This avoids “one PR per task” spam while keeping agents isolated.
  227. ### How Parallel Mode Works
  228. ```
  229. ┌────────────────────────────────────────────────────────────────┐
  230. │ Parallel Execution Flow │
  231. ├────────────────────────────────────────────────────────────────┤
  232. │ │
  233. │ RALPH_TASK.md │
  234. │ - [ ] Task A │
  235. │ - [ ] Task B ┌──────────────────────────┐ │
  236. │ - [ ] Task C ───▶ │ Create Worktrees │ │
  237. │ └──────────────────────────┘ │
  238. │ │ │
  239. │ ┌───────────────┼───────────────┐ │
  240. │ ▼ ▼ ▼ │
  241. │ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
  242. │ │ Agent 1 │ │ Agent 2 │ │ Agent 3 │ │
  243. │ │ worktree │ │ worktree │ │ worktree │ │
  244. │ │ Task A │ │ Task B │ │ Task C │ │
  245. │ └────┬─────┘ └────┬─────┘ └────┬─────┘ │
  246. │ │ │ │ │
  247. │ ▼ ▼ ▼ │
  248. │ branch-a branch-b branch-c │
  249. │ │ │ │ │
  250. │ └──────────────┼──────────────┘ │
  251. │ ▼ │
  252. │ ┌──────────────┐ │
  253. │ │ Auto-Merge │ │
  254. │ │ to base │ │
  255. │ └──────────────┘ │
  256. └────────────────────────────────────────────────────────────────┘
  257. ```
  258. **Key benefits:**
  259. - Each agent works in complete isolation (separate git worktree)
  260. - No interference between agents working on different tasks
  261. - Branches auto-merge after completion (or keep separate with `--no-merge`)
  262. - Conflict detection and reporting
  263. - Tasks are processed in batches (e.g., 5 agents = 5 tasks per batch)
  264. - In parallel mode, agents do **not** update `.ralph/progress.md` (they write per-agent reports instead)
  265. **When to use parallel mode:**
  266. - Multiple independent tasks that don't conflict
  267. - Large task lists you want completed faster
  268. - CI/CD pipelines with parallelization budget
  269. **When to use sequential mode:**
  270. - Tasks that depend on each other
  271. - Single complex task that needs focused attention
  272. - Limited API rate limits
  273. ### Recommended Workflow: Parallel + Integration Pass
  274. For best results, structure your work in two phases:
  275. **Phase 1: Parallel execution** (isolated, independent tasks)
  276. ```markdown
  277. # Tasks
  278. - [ ] Add user authentication to /api/auth
  279. - [ ] Create dashboard component
  280. - [ ] Implement data export feature
  281. - [ ] Add unit tests for utils/
  282. ```
  283. **Phase 2: Integration pass** (one sequential agent, repo-wide polish)
  284. ```markdown
  285. # Tasks
  286. - [ ] Update README with new features
  287. - [ ] Bump version in package.json
  288. - [ ] Update CHANGELOG
  289. - [ ] Fix any integration issues from parallel work
  290. ```
  291. This pattern maximizes parallelism while avoiding merge conflicts on shared files.
  292. The integration pass runs after parallel agents finish and handles all "touch everything" work.
  293. ### Task Groups (Phased Execution)
  294. Control execution order with `<!-- group: N -->` annotations:
  295. ```markdown
  296. # Tasks
  297. - [ ] Create database schema <!-- group: 1 -->
  298. - [ ] Create User model <!-- group: 1 -->
  299. - [ ] Create Post model <!-- group: 1 -->
  300. - [ ] Add relationships between models <!-- group: 2 -->
  301. - [ ] Build API endpoints <!-- group: 3 -->
  302. - [ ] Update README # no annotation = runs LAST
  303. ```
  304. **Execution order:**
  305. 1. Group 1 - runs first (all tasks in parallel, up to `--max-parallel`)
  306. 2. Group 2 - runs after group 1 merges complete
  307. 3. Group 3 - runs after group 2 merges complete
  308. 4. Unannotated tasks - run LAST (after all annotated groups)
  309. **Why unannotated = last?**
  310. - Safer default: forgetting to annotate doesn't jump the queue
  311. - Integration/polish tasks naturally go last
  312. - Override with `DEFAULT_GROUP=0` env var if you prefer unannotated first
  313. **Within each group:**
  314. - Tasks run in parallel (up to `--max-parallel`)
  315. - All merges complete before next group starts
  316. - RALPH_TASK.md checkboxes updated per group
  317. **Worktree structure:**
  318. ```
  319. project/
  320. ├── .ralph-worktrees/ # Temporary worktrees (auto-cleaned)
  321. │ ├── <run_id>-job1/ # Agent worktree (isolated)
  322. │ ├── <run_id>-job2/ # Agent worktree (isolated)
  323. │ └── <run_id>-job3/ # Agent worktree (isolated)
  324. └── (original project files)
  325. ```
  326. Worktrees are automatically cleaned up after agents complete. Failed agents preserve their worktree for manual inspection.
  327. ### Parallel logs & per-agent reports
  328. Each parallel run creates a run directory:
  329. ```
  330. .ralph/parallel/<run_id>/
  331. ├── manifest.tsv # job_id -> task_id -> branch -> status -> log
  332. └── jobN.log # full cursor-agent output for that job
  333. ```
  334. Agents are instructed to write a committed per-agent report (to avoid `.ralph/progress.md` merge conflicts):
  335. ```
  336. .ralph/parallel/<run_id>/agent-jobN.md
  337. ```
  338. ## How It Works
  339. ### The Loop
  340. ```
  341. Iteration 1 Iteration 2 Iteration N
  342. ┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐
  343. │ Fresh context │ │ Fresh context │ │ Fresh context │
  344. │ │ │ │ │ │ │ │ │
  345. │ ▼ │ │ ▼ │ │ ▼ │
  346. │ Read RALPH_TASK │ │ Read RALPH_TASK │ │ Read RALPH_TASK │
  347. │ Read guardrails │──────────│ Read guardrails │──────────│ Read guardrails │
  348. │ Read progress │ (state │ Read progress │ (state │ Read progress │
  349. │ │ │ in git) │ │ │ in git) │ │ │
  350. │ ▼ │ │ ▼ │ │ ▼ │
  351. │ Work on criteria │ │ Work on criteria │ │ Work on criteria │
  352. │ Commit to git │ │ Commit to git │ │ Commit to git │
  353. │ │ │ │ │ │ │ │ │
  354. │ ▼ │ │ ▼ │ │ ▼ │
  355. │ 80k tokens │ │ 80k tokens │ │ All [x] done! │
  356. │ ROTATE ──────────┼──────────┼──────────────────┼──────────┼──► COMPLETE │
  357. └──────────────────┘ └──────────────────┘ └──────────────────┘
  358. ```
  359. Each iteration:
  360. 1. Reads task and state from files (not from previous context)
  361. 2. Works on unchecked criteria
  362. 3. Commits progress to git
  363. 4. Updates `.ralph/progress.md` and `.ralph/guardrails.md`
  364. 5. Rotates when context is full
  365. ### Git Protocol
  366. The agent is instructed to commit frequently:
  367. ```bash
  368. # After each criterion
  369. git add -A && git commit -m 'ralph: [criterion] - description'
  370. # Push periodically
  371. git push
  372. ```
  373. **Commits are the agent's memory.** The next iteration picks up from git history.
  374. ### The Learning Loop (Signs)
  375. When something fails, the agent adds a "Sign" to `.ralph/guardrails.md`:
  376. ```markdown
  377. ### Sign: Check imports before adding
  378. - **Trigger**: Adding a new import statement
  379. - **Instruction**: First check if import already exists in file
  380. - **Added after**: Iteration 3 - duplicate import caused build failure
  381. ```
  382. Future iterations read guardrails first and follow them, preventing repeated mistakes.
  383. ```
  384. Error occurs → errors.log → Agent analyzes → Updates guardrails.md → Future agents follow
  385. ```
  386. ## Context Health Indicators
  387. The activity log shows context health with emoji:
  388. | Emoji | Status | Token % | Meaning |
  389. |-------|--------|---------|---------|
  390. | 🟢 | Healthy | < 60% | Plenty of room |
  391. | 🟡 | Warning | 60-80% | Approaching limit |
  392. | 🔴 | Critical | > 80% | Rotation imminent |
  393. Example:
  394. ```
  395. [12:34:56] 🟢 READ src/index.ts (245 lines, ~24.5KB)
  396. [12:40:22] 🟡 TOKENS: 58,000 / 80,000 (72%) - approaching limit [read:40KB write:8KB assist:10KB shell:0KB]
  397. [12:45:33] 🔴 TOKENS: 72,500 / 80,000 (90%) - rotation imminent
  398. ```
  399. ## Gutter Detection
  400. The parser detects when the agent is stuck:
  401. | Pattern | Trigger | What Happens |
  402. |---------|---------|--------------|
  403. | Repeated failure | Same command failed 3x | GUTTER signal |
  404. | File thrashing | Same file written 5x in 10 min | GUTTER signal |
  405. | Agent signals | Agent outputs `<ralph>GUTTER</ralph>` | GUTTER signal |
  406. When gutter is detected:
  407. 1. Check `.ralph/errors.log` for the pattern
  408. 2. Fix the issue manually or add a guardrail
  409. 3. Re-run the loop
  410. ## Rate Limit & Transient Error Handling
  411. The parser detects retryable API errors and handles them gracefully:
  412. | Error Type | Examples | What Happens |
  413. |------------|----------|--------------|
  414. | Rate limits | 429, "rate limit exceeded", "quota" | DEFER signal |
  415. | Network errors | timeout, connection reset, ECONNRESET | DEFER signal |
  416. | Server errors | 502, 503, 504, "service unavailable" | DEFER signal |
  417. When DEFER is triggered:
  418. 1. Agent stops current iteration
  419. 2. Waits with **exponential backoff** (15s base, doubles each retry, max 120s)
  420. 3. Adds jitter (0-25%) to prevent thundering herd
  421. 4. Retries the same task (does not increment iteration)
  422. Example log:
  423. ```
  424. ⏸️ Rate limit or transient error detected.
  425. Waiting 32s before retrying (attempt 2)...
  426. Resuming...
  427. ```
  428. ## Completion Detection
  429. Ralph detects completion in two ways:
  430. 1. **Checkbox check**: All `[ ]` in RALPH_TASK.md changed to `[x]`
  431. 2. **Agent sigil**: Agent outputs `<ralph>COMPLETE</ralph>`
  432. Both are verified before declaring success.
  433. ## File Reference
  434. | File | Purpose | Who Uses It |
  435. |------|---------|-------------|
  436. | `RALPH_TASK.md` | Task definition + success criteria | You define, agent reads |
  437. | `.ralph/progress.md` | What's been accomplished | Agent writes after work |
  438. | `.ralph/guardrails.md` | Lessons learned (Signs) | Agent reads first, writes after failures |
  439. | `.ralph/activity.log` | Tool call log with token counts | Parser writes, you monitor |
  440. | `.ralph/errors.log` | Failures + gutter detection | Parser writes, agent reads |
  441. | `.ralph/tasks.yaml` | Cached task state (auto-generated) | Task parser writes/reads |
  442. | `.ralph/tasks.mtime` | Task file modification time | Cache invalidation |
  443. | `.ralph/.iteration` | Current iteration number | Parser reads/writes |
  444. ## Configuration
  445. Configuration is set via command-line flags or environment variables:
  446. ```bash
  447. # Via flags (recommended)
  448. ./ralph-loop.sh -n 50 -m gpt-5.2-high
  449. # Via environment
  450. RALPH_MODEL=gpt-5.2-high MAX_ITERATIONS=50 ./ralph-loop.sh
  451. ```
  452. Default thresholds in `ralph-common.sh`:
  453. ```bash
  454. MAX_ITERATIONS=20 # Max rotations before giving up
  455. WARN_THRESHOLD=70000 # Tokens: send wrapup warning
  456. ROTATE_THRESHOLD=80000 # Tokens: force rotation
  457. ```
  458. ## Troubleshooting
  459. ### "cursor-agent CLI not found"
  460. ```bash
  461. curl https://cursor.com/install -fsS | bash
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 600 on GitHub
  462. ```
  463. ### Agent keeps failing on same thing
  464. Check `.ralph/errors.log` for the pattern. Either:
  465. 1. Fix the underlying issue manually
  466. 2. Add a guardrail to `.ralph/guardrails.md` explaining what to do differently
  467. ### Context rotates too frequently
  468. The agent might be reading too many large files. Check `activity.log` for large READs and consider:
  469. 1. Adding a guardrail: "Don't read the entire file, use grep to find relevant sections"
  470. 2. Breaking the task into smaller pieces
  471. ### Task never completes
  472. Check if criteria are too vague. Each criterion should be:
  473. - Specific and testable
  474. - Achievable in a single iteration
  475. - Not dependent on manual steps
  476. ## Workflows
  477. ### Basic (default)
  478. ```bash
  479. ./ralph-setup.sh # Interactive setup → runs loop → done
  480. ```
  481. ### Human-in-the-loop (recommended for new tasks)
  482. ```bash
  483. ./ralph-once.sh # Run ONE iteration
  484. # Review changes...
  485. ./ralph-setup.sh # Continue with full loop
  486. ```
  487. ### Scripted/CI
  488. ```bash
  489. ./ralph-loop.sh --branch feature/foo --pr -y
  490. ```
  491. ## Learn More
  492. - [Original Ralph technique](https://ghuntley.com/ralph/) - Geoffrey Huntley
  493. - [Context as memory](https://ghuntley.com/allocations/) - The malloc/free metaphor
  494. - [Cursor CLI docs](https://cursor.com/docs/cli/headless)
  495. - [gum - A tool for glamorous shell scripts](https://github.com/charmbracelet/gum)
  496. ## Credits
  497. - **Original technique**: [Geoffrey Huntley](https://ghuntley.com/ralph/) - the Ralph Wiggum methodology
  498. - **Cursor port**: [Agrim Singh](https://x.com/agrimsingh) - this implementation
  499. ## License
  500. MIT
install.sh · Bundled script · 303 lines · 2 findings marked
  1. #!/bin/bash
  2. # Ralph Wiggum: One-click installer
  3. # 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
  4. set -euo pipefail
  5. REPO_RAW="https://raw.githubusercontent.com/agrimsingh/ralph-wiggum-cursor/main"
  6. echo "═══════════════════════════════════════════════════════════════════"
  7. echo "🐛 Ralph Wiggum Installer"
  8. echo "═══════════════════════════════════════════════════════════════════"
  9. echo ""
  10. # Check if we're in a git repo
  11. if ! git rev-parse --git-dir > /dev/null 2>&1; then
  12. echo "⚠️ Warning: Not in a git repository."
  13. echo " Ralph works best with git for state persistence."
  14. echo ""
  15. echo " Run: git init"
  16. echo ""
  17. fi
  18. # Check for cursor-agent CLI
  19. if ! command -v cursor-agent &> /dev/null; then
  20. echo "⚠️ Warning: cursor-agent CLI not found."
  21. 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
  22. echo ""
  23. fi
  24. # Check for gum and offer to install
  25. if ! command -v gum &> /dev/null; then
  26. echo "📦 gum not found (provides beautiful CLI menus)"
  27. # Auto-install if INSTALL_GUM=1 or prompt user
  28. SHOULD_INSTALL=""
  29. if [[ "${INSTALL_GUM:-}" == "1" ]]; then
  30. SHOULD_INSTALL="y"
  31. else
  32. read -p " Install gum? [y/N] " -n 1 -r < /dev/tty
  33. echo
  34. SHOULD_INSTALL="$REPLY"
  35. fi
  36. if [[ "$SHOULD_INSTALL" =~ ^[Yy]$ ]]; then
  37. if [[ "$OSTYPE" == "darwin"* ]]; then
  38. if command -v brew &> /dev/null; then
  39. echo " Installing via Homebrew..."
  40. brew install gum
  41. else
  42. echo " ⚠️ Homebrew not found. Install manually: brew install gum"
  43. fi
  44. elif [[ -f /etc/debian_version ]]; then
  45. echo " Installing via apt..."
  46. sudo mkdir -p /etc/apt/keyrings
  47. curl -fsSL https://repo.charm.sh/apt/gpg.key | sudo gpg --dearmor -o /etc/apt/keyrings/charm.gpg
  48. echo "deb [signed-by=/etc/apt/keyrings/charm.gpg] https://repo.charm.sh/apt/ * *" | sudo tee /etc/apt/sources.list.d/charm.list
  49. sudo apt update && sudo apt install -y gum
  50. elif [[ -f /etc/fedora-release ]] || [[ -f /etc/redhat-release ]]; then
  51. echo " Installing via dnf..."
  52. echo '[charm]
  53. name=Charm
  54. baseurl=https://repo.charm.sh/yum/
  55. enabled=1
  56. gpgcheck=1
  57. gpgkey=https://repo.charm.sh/yum/gpg.key' | sudo tee /etc/yum.repos.d/charm.repo
  58. sudo dnf install -y gum
  59. else
  60. echo " ⚠️ Unknown Linux distro. Install manually: https://github.com/charmbracelet/gum#installation"
  61. fi
  62. fi
  63. echo ""
  64. fi
  65. WORKSPACE_ROOT="$(pwd)"
  66. # =============================================================================
  67. # CREATE DIRECTORIES
  68. # =============================================================================
  69. echo "📁 Creating directories..."
  70. mkdir -p .cursor/ralph-scripts
  71. mkdir -p .ralph
  72. # =============================================================================
  73. # DOWNLOAD SCRIPTS
  74. # =============================================================================
  75. echo "📥 Downloading Ralph scripts..."
  76. SCRIPTS=(
  77. "ralph-common.sh"
  78. "ralph-setup.sh"
  79. "ralph-loop.sh"
  80. "ralph-once.sh"
  81. "ralph-parallel.sh"
  82. "stream-parser.sh"
  83. "task-parser.sh"
  84. "ralph-retry.sh"
  85. "init-ralph.sh"
  86. )
  87. for script in "${SCRIPTS[@]}"; do
  88. if curl -fsSL "$REPO_RAW/scripts/$script" -o ".cursor/ralph-scripts/$script" 2>/dev/null; then
  89. chmod +x ".cursor/ralph-scripts/$script"
  90. else
  91. echo " ⚠️ Could not download $script (may not exist yet)"
  92. fi
  93. done
  94. echo "✓ Scripts installed to .cursor/ralph-scripts/"
  95. # =============================================================================
  96. # INITIALIZE .ralph/ STATE
  97. # =============================================================================
  98. echo "📁 Initializing .ralph/ state directory..."
  99. cat > .ralph/guardrails.md << 'EOF'
  100. # Ralph Guardrails (Signs)
  101. > Lessons learned from past failures. READ THESE BEFORE ACTING.
  102. ## Core Signs
  103. ### Sign: Read Before Writing
  104. - **Trigger**: Before modifying any file
  105. - **Instruction**: Always read the existing file first
  106. - **Added after**: Core principle
  107. ### Sign: Test After Changes
  108. - **Trigger**: After any code change
  109. - **Instruction**: Run tests to verify nothing broke
  110. - **Added after**: Core principle
  111. ### Sign: Commit Checkpoints
  112. - **Trigger**: Before risky changes
  113. - **Instruction**: Commit current working state first
  114. - **Added after**: Core principle
  115. ---
  116. ## Learned Signs
  117. (Signs added from observed failures will appear below)
  118. EOF
  119. cat > .ralph/progress.md << 'EOF'
  120. # Progress Log
  121. > Updated by the agent after significant work.
  122. ## Summary
  123. - Iterations completed: 0
  124. - Current status: Initialized
  125. ## How This Works
  126. Progress is tracked in THIS FILE, not in LLM context.
  127. When context is rotated (fresh agent), the new agent reads this file.
  128. This is how Ralph maintains continuity across iterations.
  129. ## Session History
  130. EOF
  131. cat > .ralph/errors.log << 'EOF'
  132. # Error Log
  133. > Failures detected by stream-parser. Use to update guardrails.
  134. EOF
  135. cat > .ralph/activity.log << 'EOF'
  136. # Activity Log
  137. > Real-time tool call logging from stream-parser.
  138. EOF
  139. echo "0" > .ralph/.iteration
  140. echo "✓ .ralph/ initialized"
  141. # =============================================================================
  142. # CREATE RALPH_TASK.md TEMPLATE
  143. # =============================================================================
  144. if [[ ! -f "RALPH_TASK.md" ]]; then
  145. echo "📝 Creating RALPH_TASK.md template..."
  146. cat > RALPH_TASK.md <<'TASKEOF'
  147. ---
  148. task: Build a CLI todo app in TypeScript
  149. test_command: "npx ts-node todo.ts list"
  150. ---
  151. # Task: CLI Todo App (TypeScript)
  152. Build a simple command-line todo application in TypeScript.
  153. ## Requirements
  154. 1. Single file: `todo.ts`
  155. 2. Uses `todos.json` for persistence
  156. 3. Three commands: add, list, done
  157. 4. TypeScript with proper types
  158. ## Success Criteria
  159. 1. [ ] `npx ts-node todo.ts add "Buy milk"` adds a todo and confirms
  160. 2. [ ] `npx ts-node todo.ts list` shows all todos with IDs and status
  161. 3. [ ] `npx ts-node todo.ts done 1` marks todo 1 as complete
  162. 4. [ ] Todos survive script restart (JSON persistence)
  163. 5. [ ] Invalid commands show helpful usage message
  164. 6. [ ] Code has proper TypeScript types (no `any`)
  165. ## Example Output
  166. ```
  167. $ npx ts-node todo.ts add "Buy milk"
  168. ✓ Added: "Buy milk" (id: 1)
  169. $ npx ts-node todo.ts list
  170. 1. [ ] Buy milk
  171. $ npx ts-node todo.ts done 1
  172. ✓ Completed: "Buy milk"
  173. ```
  174. ---
  175. ## Ralph Instructions
  176. 1. Work on the next incomplete criterion (marked [ ])
  177. 2. Check off completed criteria (change [ ] to [x])
  178. 3. Run tests after changes
  179. 4. Commit your changes frequently
  180. 5. When ALL criteria are [x], output: `<ralph>COMPLETE</ralph>`
  181. 6. If stuck on the same issue 3+ times, output: `<ralph>GUTTER</ralph>`
  182. TASKEOF
  183. echo "✓ Created RALPH_TASK.md with example task"
  184. else
  185. echo "✓ RALPH_TASK.md already exists (not overwritten)"
  186. fi
  187. # =============================================================================
  188. # UPDATE .gitignore
  189. # =============================================================================
  190. if [[ -f ".gitignore" ]]; then
  191. if ! grep -q "ralph-config.json" .gitignore 2>/dev/null; then
  192. echo "" >> .gitignore
  193. echo "# Ralph config (may contain API key)" >> .gitignore
  194. echo ".cursor/ralph-config.json" >> .gitignore
  195. fi
  196. else
  197. cat > .gitignore <<'EOF'
  198. # Ralph config (may contain API key)
  199. .cursor/ralph-config.json
  200. EOF
  201. fi
  202. echo "✓ Updated .gitignore"
  203. # =============================================================================
  204. # SUMMARY
  205. # =============================================================================
  206. echo ""
  207. echo "═══════════════════════════════════════════════════════════════════"
  208. echo "✅ Ralph installed!"
  209. echo "═══════════════════════════════════════════════════════════════════"
  210. echo ""
  211. echo "Files created:"
  212. echo ""
  213. echo " 📁 .cursor/ralph-scripts/"
  214. echo " ├── ralph-setup.sh - Main entry (interactive)"
  215. echo " ├── ralph-loop.sh - CLI mode (for scripting)"
  216. echo " ├── ralph-once.sh - Single iteration (testing)"
  217. echo " └── ... - Other utilities"
  218. echo ""
  219. echo " 📁 .ralph/ - State files (tracked in git)"
  220. echo " ├── guardrails.md - Lessons learned"
  221. echo " ├── progress.md - Progress log"
  222. echo " ├── activity.log - Tool call log"
  223. echo " └── errors.log - Failure log"
  224. echo ""
  225. echo " 📄 RALPH_TASK.md - Your task definition (edit this!)"
  226. echo ""
  227. echo "Next steps:"
  228. echo " 1. Edit RALPH_TASK.md to define your actual task"
  229. echo " 2. Run: ./.cursor/ralph-scripts/ralph-setup.sh"
  230. echo ""
  231. echo "Alternative commands:"
  232. echo " • ralph-once.sh - Test with single iteration first"
  233. echo " • ralph-loop.sh - CLI mode with flags (for scripting)"
  234. echo ""
  235. echo "Monitor progress:"
  236. echo " tail -f .ralph/activity.log"
  237. echo ""
  238. echo "Learn more: https://ghuntley.com/ralph/"
  239. echo "═══════════════════════════════════════════════════════════════════"
scripts/init-ralph.sh · Bundled script · 202 lines · 1 finding marked
  1. #!/bin/bash
  2. # Ralph Wiggum: Initialize Ralph in a project
  3. # Sets up Ralph tracking for CLI mode
  4. set -euo pipefail
  5. SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
  6. SKILL_DIR="$(dirname "$SCRIPT_DIR")"
  7. echo "═══════════════════════════════════════════════════════════════════"
  8. echo "🐛 Ralph Wiggum Initialization"
  9. echo "═══════════════════════════════════════════════════════════════════"
  10. echo ""
  11. # Check if we're in a git repo
  12. if ! git rev-parse --git-dir > /dev/null 2>&1; then
  13. echo "⚠️ Warning: Not in a git repository."
  14. echo " Ralph works best with git for state persistence."
  15. echo ""
  16. read -p "Continue anyway? [y/N] " -n 1 -r
  17. echo
  18. if [[ ! $REPLY =~ ^[Yy]$ ]]; then
  19. exit 1
  20. fi
  21. fi
  22. # Check for cursor-agent CLI
  23. if ! command -v cursor-agent &> /dev/null; then
  24. echo "⚠️ Warning: cursor-agent CLI not found."
  25. 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
  26. echo ""
  27. fi
  28. # Create directories
  29. mkdir -p .ralph
  30. mkdir -p .cursor/ralph-scripts
  31. # =============================================================================
  32. # CREATE RALPH_TASK.md IF NOT EXISTS
  33. # =============================================================================
  34. if [[ ! -f "RALPH_TASK.md" ]]; then
  35. echo "📝 Creating RALPH_TASK.md template..."
  36. if [[ -f "$SKILL_DIR/assets/RALPH_TASK_TEMPLATE.md" ]]; then
  37. cp "$SKILL_DIR/assets/RALPH_TASK_TEMPLATE.md" RALPH_TASK.md
  38. else
  39. cat > RALPH_TASK.md << 'EOF'
  40. ---
  41. task: Your task description here
  42. test_command: "pnpm test"
  43. ---
  44. # Task
  45. Describe what you want to accomplish.
  46. ## Success Criteria
  47. 1. [ ] First thing to complete
  48. 2. [ ] Second thing to complete
  49. 3. [ ] Third thing to complete
  50. ## Context
  51. Any additional context the agent should know.
  52. EOF
  53. fi
  54. echo " Edit RALPH_TASK.md to define your task."
  55. else
  56. echo "✓ RALPH_TASK.md already exists"
  57. fi
  58. # =============================================================================
  59. # INITIALIZE STATE FILES
  60. # =============================================================================
  61. echo "📁 Initializing .ralph/ directory..."
  62. cat > .ralph/guardrails.md << 'EOF'
  63. # Ralph Guardrails (Signs)
  64. > Lessons learned from past failures. READ THESE BEFORE ACTING.
  65. ## Core Signs
  66. ### Sign: Read Before Writing
  67. - **Trigger**: Before modifying any file
  68. - **Instruction**: Always read the existing file first
  69. - **Added after**: Core principle
  70. ### Sign: Test After Changes
  71. - **Trigger**: After any code change
  72. - **Instruction**: Run tests to verify nothing broke
  73. - **Added after**: Core principle
  74. ### Sign: Commit Checkpoints
  75. - **Trigger**: Before risky changes
  76. - **Instruction**: Commit current working state first
  77. - **Added after**: Core principle
  78. ---
  79. ## Learned Signs
  80. (Signs added from observed failures will appear below)
  81. EOF
  82. cat > .ralph/progress.md << 'EOF'
  83. # Progress Log
  84. > Updated by the agent after significant work.
  85. ## Summary
  86. - Iterations completed: 0
  87. - Current status: Initialized
  88. ## How This Works
  89. Progress is tracked in THIS FILE, not in LLM context.
  90. When context is rotated (fresh agent), the new agent reads this file.
  91. This is how Ralph maintains continuity across iterations.
  92. ## Session History
  93. EOF
  94. cat > .ralph/errors.log << 'EOF'
  95. # Error Log
  96. > Failures detected by stream-parser. Use to update guardrails.
  97. EOF
  98. cat > .ralph/activity.log << 'EOF'
  99. # Activity Log
  100. > Real-time tool call logging from stream-parser.
  101. EOF
  102. echo "0" > .ralph/.iteration
  103. # =============================================================================
  104. # INSTALL SCRIPTS
  105. # =============================================================================
  106. echo "📦 Installing scripts..."
  107. # Copy scripts
  108. cp "$SKILL_DIR/scripts/"*.sh .cursor/ralph-scripts/ 2>/dev/null || true
  109. chmod +x .cursor/ralph-scripts/*.sh 2>/dev/null || true
  110. echo "✓ Scripts installed to .cursor/ralph-scripts/"
  111. # =============================================================================
  112. # UPDATE .gitignore
  113. # =============================================================================
  114. if [[ -f ".gitignore" ]]; then
  115. # Don't gitignore .ralph/ - we want it tracked for state persistence
  116. if ! grep -q "ralph-config.json" .gitignore; then
  117. echo "" >> .gitignore
  118. echo "# Ralph config (may contain API keys)" >> .gitignore
  119. echo ".cursor/ralph-config.json" >> .gitignore
  120. fi
  121. echo "✓ Updated .gitignore"
  122. else
  123. cat > .gitignore << 'EOF'
  124. # Ralph config (may contain API keys)
  125. .cursor/ralph-config.json
  126. EOF
  127. echo "✓ Created .gitignore"
  128. fi
  129. # =============================================================================
  130. # SUMMARY
  131. # =============================================================================
  132. echo ""
  133. echo "═══════════════════════════════════════════════════════════════════"
  134. echo "✅ Ralph initialized!"
  135. echo "═══════════════════════════════════════════════════════════════════"
  136. echo ""
  137. echo "Files created:"
  138. echo " • RALPH_TASK.md - Define your task here"
  139. echo " • .ralph/guardrails.md - Lessons learned (agent updates this)"
  140. echo " • .ralph/progress.md - Progress log (agent updates this)"
  141. echo " • .ralph/activity.log - Tool call log (parser updates this)"
  142. echo " • .ralph/errors.log - Failure log (parser updates this)"
  143. echo ""
  144. echo "Next steps:"
  145. echo " 1. Edit RALPH_TASK.md to define your task and criteria"
  146. echo " 2. Run: ./scripts/ralph-loop.sh"
  147. echo " (or: .cursor/ralph-scripts/ralph-loop.sh)"
  148. echo ""
  149. echo "The agent will work autonomously, rotating context as needed."
  150. echo "Monitor progress: tail -f .ralph/activity.log"
  151. echo ""
  152. echo "Learn more: https://ghuntley.com/ralph/"
  153. echo "═══════════════════════════════════════════════════════════════════"
scripts/ralph-common.sh · Bundled script · 832 lines · 1 finding marked
  1. #!/bin/bash
  2. # Ralph Wiggum: Common utilities and loop logic
  3. #
  4. # Shared functions for ralph-loop.sh and ralph-setup.sh
  5. # All state lives in .ralph/ within the project.
  6. # =============================================================================
  7. # SOURCE DEPENDENCIES
  8. # =============================================================================
  9. # Get the directory where this script lives
  10. _RALPH_SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
  11. # Source the task parser for YAML backend support
  12. if [[ -f "$_RALPH_SCRIPT_DIR/task-parser.sh" ]]; then
  13. source "$_RALPH_SCRIPT_DIR/task-parser.sh"
  14. _TASK_PARSER_AVAILABLE=1
  15. else
  16. _TASK_PARSER_AVAILABLE=0
  17. fi
  18. # =============================================================================
  19. # CONFIGURATION (can be overridden before sourcing)
  20. # =============================================================================
  21. # Token thresholds
  22. WARN_THRESHOLD="${WARN_THRESHOLD:-70000}"
  23. ROTATE_THRESHOLD="${ROTATE_THRESHOLD:-80000}"
  24. # Iteration limits
  25. MAX_ITERATIONS="${MAX_ITERATIONS:-20}"
  26. # Model selection
  27. DEFAULT_MODEL="opus-4.5-thinking"
  28. MODEL="${RALPH_MODEL:-$DEFAULT_MODEL}"
  29. # Feature flags (set by caller)
  30. USE_BRANCH="${USE_BRANCH:-}"
  31. OPEN_PR="${OPEN_PR:-false}"
  32. SKIP_CONFIRM="${SKIP_CONFIRM:-false}"
  33. # =============================================================================
  34. # SOURCE RETRY UTILITIES
  35. # =============================================================================
  36. # Source retry logic utilities
  37. SCRIPT_DIR="${SCRIPT_DIR:-$(dirname "${BASH_SOURCE[0]}")}"
  38. if [[ -f "$SCRIPT_DIR/ralph-retry.sh" ]]; then
  39. source "$SCRIPT_DIR/ralph-retry.sh"
  40. fi
  41. # =============================================================================
  42. # BASIC HELPERS
  43. # =============================================================================
  44. # Cross-platform sed -i
  45. sedi() {
  46. if [[ "$OSTYPE" == "darwin"* ]]; then
  47. sed -i '' "$@"
  48. else
  49. sed -i "$@"
  50. fi
  51. }
  52. # Get the .ralph directory for a workspace
  53. get_ralph_dir() {
  54. local workspace="${1:-.}"
  55. echo "$workspace/.ralph"
  56. }
  57. # Get current iteration from .ralph/.iteration
  58. get_iteration() {
  59. local workspace="${1:-.}"
  60. local state_file="$workspace/.ralph/.iteration"
  61. if [[ -f "$state_file" ]]; then
  62. cat "$state_file"
  63. else
  64. echo "0"
  65. fi
  66. }
  67. # Set iteration number
  68. set_iteration() {
  69. local workspace="${1:-.}"
  70. local iteration="$2"
  71. local ralph_dir="$workspace/.ralph"
  72. mkdir -p "$ralph_dir"
  73. echo "$iteration" > "$ralph_dir/.iteration"
  74. }
  75. # Increment iteration and return new value
  76. increment_iteration() {
  77. local workspace="${1:-.}"
  78. local current=$(get_iteration "$workspace")
  79. local next=$((current + 1))
  80. set_iteration "$workspace" "$next"
  81. echo "$next"
  82. }
  83. # Get context health emoji based on token count
  84. get_health_emoji() {
  85. local tokens="$1"
  86. local pct=$((tokens * 100 / ROTATE_THRESHOLD))
  87. if [[ $pct -lt 60 ]]; then
  88. echo "🟢"
  89. elif [[ $pct -lt 80 ]]; then
  90. echo "🟡"
  91. else
  92. echo "🔴"
  93. fi
  94. }
  95. # =============================================================================
  96. # LOGGING
  97. # =============================================================================
  98. # Log a message to activity.log
  99. log_activity() {
  100. local workspace="${1:-.}"
  101. local message="$2"
  102. local ralph_dir="$workspace/.ralph"
  103. local timestamp=$(date '+%H:%M:%S')
  104. mkdir -p "$ralph_dir"
  105. echo "[$timestamp] $message" >> "$ralph_dir/activity.log"
  106. }
  107. # Log an error to errors.log
  108. log_error() {
  109. local workspace="${1:-.}"
  110. local message="$2"
  111. local ralph_dir="$workspace/.ralph"
  112. local timestamp=$(date '+%H:%M:%S')
  113. mkdir -p "$ralph_dir"
  114. echo "[$timestamp] $message" >> "$ralph_dir/errors.log"
  115. }
  116. # Log to progress.md (called by the loop, not the agent)
  117. log_progress() {
  118. local workspace="$1"
  119. local message="$2"
  120. local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
  121. local progress_file="$workspace/.ralph/progress.md"
  122. echo "" >> "$progress_file"
  123. echo "### $timestamp" >> "$progress_file"
  124. echo "$message" >> "$progress_file"
  125. }
  126. # =============================================================================
  127. # INITIALIZATION
  128. # =============================================================================
  129. # Initialize .ralph directory with default files
  130. init_ralph_dir() {
  131. local workspace="$1"
  132. local ralph_dir="$workspace/.ralph"
  133. mkdir -p "$ralph_dir"
  134. # Initialize progress.md if it doesn't exist
  135. if [[ ! -f "$ralph_dir/progress.md" ]]; then
  136. cat > "$ralph_dir/progress.md" << 'EOF'
  137. # Progress Log
  138. > Updated by the agent after significant work.
  139. ---
  140. ## Session History
  141. EOF
  142. fi
  143. # Initialize guardrails.md if it doesn't exist
  144. if [[ ! -f "$ralph_dir/guardrails.md" ]]; then
  145. cat > "$ralph_dir/guardrails.md" << 'EOF'
  146. # Ralph Guardrails (Signs)
  147. > Lessons learned from past failures. READ THESE BEFORE ACTING.
  148. ## Core Signs
  149. ### Sign: Read Before Writing
  150. - **Trigger**: Before modifying any file
  151. - **Instruction**: Always read the existing file first
  152. - **Added after**: Core principle
  153. ### Sign: Test After Changes
  154. - **Trigger**: After any code change
  155. - **Instruction**: Run tests to verify nothing broke
  156. - **Added after**: Core principle
  157. ### Sign: Commit Checkpoints
  158. - **Trigger**: Before risky changes
  159. - **Instruction**: Commit current working state first
  160. - **Added after**: Core principle
  161. ---
  162. ## Learned Signs
  163. EOF
  164. fi
  165. # Initialize errors.log if it doesn't exist
  166. if [[ ! -f "$ralph_dir/errors.log" ]]; then
  167. cat > "$ralph_dir/errors.log" << 'EOF'
  168. # Error Log
  169. > Failures detected by stream-parser. Use to update guardrails.
  170. EOF
  171. fi
  172. # Initialize activity.log if it doesn't exist
  173. if [[ ! -f "$ralph_dir/activity.log" ]]; then
  174. cat > "$ralph_dir/activity.log" << 'EOF'
  175. # Activity Log
  176. > Real-time tool call logging from stream-parser.
  177. EOF
  178. fi
  179. }
  180. # =============================================================================
  181. # TASK MANAGEMENT
  182. # =============================================================================
  183. # Check if task is complete
  184. # Uses task-parser.sh when available for cached/YAML support
  185. check_task_complete() {
  186. local workspace="$1"
  187. local task_file="$workspace/RALPH_TASK.md"
  188. if [[ ! -f "$task_file" ]]; then
  189. echo "NO_TASK_FILE"
  190. return
  191. fi
  192. # Use task parser if available (provides caching)
  193. if [[ "${_TASK_PARSER_AVAILABLE:-0}" -eq 1 ]]; then
  194. local remaining
  195. remaining=$(count_remaining "$workspace" 2>/dev/null) || remaining=-1
  196. if [[ "$remaining" -eq 0 ]]; then
  197. echo "COMPLETE"
  198. elif [[ "$remaining" -gt 0 ]]; then
  199. echo "INCOMPLETE:$remaining"
  200. else
  201. # Fallback to direct grep if parser fails
  202. _check_task_complete_direct "$workspace"
  203. fi
  204. else
  205. _check_task_complete_direct "$workspace"
  206. fi
  207. }
  208. # Direct task completion check (fallback)
  209. _check_task_complete_direct() {
  210. local workspace="$1"
  211. local task_file="$workspace/RALPH_TASK.md"
  212. # Only count actual checkbox list items, not [ ] in prose/examples
  213. # Matches: "- [ ]", "* [ ]", "1. [ ]", etc.
  214. local unchecked
  215. unchecked=$(grep -cE '^[[:space:]]*([-*]|[0-9]+\.)[[:space:]]+\[ \]' "$task_file" 2>/dev/null) || unchecked=0
  216. if [[ "$unchecked" -eq 0 ]]; then
  217. echo "COMPLETE"
  218. else
  219. echo "INCOMPLETE:$unchecked"
  220. fi
  221. }
  222. # Count task criteria (returns done:total)
  223. # Uses task-parser.sh when available for cached/YAML support
  224. count_criteria() {
  225. local workspace="${1:-.}"
  226. local task_file="$workspace/RALPH_TASK.md"
  227. if [[ ! -f "$task_file" ]]; then
  228. echo "0:0"
  229. return
  230. fi
  231. # Use task parser if available (provides caching)
  232. if [[ "${_TASK_PARSER_AVAILABLE:-0}" -eq 1 ]]; then
  233. local progress
  234. progress=$(get_progress "$workspace" 2>/dev/null) || progress=""
  235. if [[ -n "$progress" ]] && [[ "$progress" =~ ^[0-9]+:[0-9]+$ ]]; then
  236. echo "$progress"
  237. else
  238. # Fallback to direct grep if parser fails
  239. _count_criteria_direct "$workspace"
  240. fi
  241. else
  242. _count_criteria_direct "$workspace"
  243. fi
  244. }
  245. # Direct criteria counting (fallback)
  246. _count_criteria_direct() {
  247. local workspace="${1:-.}"
  248. local task_file="$workspace/RALPH_TASK.md"
  249. # Only count actual checkbox list items, not [x] or [ ] in prose/examples
  250. # Matches: "- [ ]", "* [x]", "1. [ ]", etc.
  251. local total done_count
  252. total=$(grep -cE '^[[:space:]]*([-*]|[0-9]+\.)[[:space:]]+\[(x| )\]' "$task_file" 2>/dev/null) || total=0
  253. done_count=$(grep -cE '^[[:space:]]*([-*]|[0-9]+\.)[[:space:]]+\[x\]' "$task_file" 2>/dev/null) || done_count=0
  254. echo "$done_count:$total"
  255. }
  256. # =============================================================================
  257. # TASK PARSER CONVENIENCE WRAPPERS
  258. # =============================================================================
  259. # Get the next task to work on (wrapper for task-parser.sh)
  260. # Returns: task_id|status|description or empty
  261. get_next_task_info() {
  262. local workspace="${1:-.}"
  263. if [[ "${_TASK_PARSER_AVAILABLE:-0}" -eq 1 ]]; then
  264. get_next_task "$workspace"
  265. else
  266. echo ""
  267. fi
  268. }
  269. # Mark a specific task complete by line-based ID
  270. # Usage: complete_task "$workspace" "line_15"
  271. complete_task() {
  272. local workspace="${1:-.}"
  273. local task_id="$2"
  274. if [[ "${_TASK_PARSER_AVAILABLE:-0}" -eq 1 ]]; then
  275. mark_task_complete "$workspace" "$task_id"
  276. else
  277. echo "ERROR: Task parser not available" >&2
  278. return 1
  279. fi
  280. }
  281. # List all tasks with their status
  282. # Usage: list_all_tasks "$workspace"
  283. list_all_tasks() {
  284. local workspace="${1:-.}"
  285. if [[ "${_TASK_PARSER_AVAILABLE:-0}" -eq 1 ]]; then
  286. get_all_tasks "$workspace"
  287. else
  288. echo "ERROR: Task parser not available" >&2
  289. return 1
  290. fi
  291. }
  292. # Refresh task cache (useful after external edits)
  293. refresh_task_cache() {
  294. local workspace="${1:-.}"
  295. if [[ "${_TASK_PARSER_AVAILABLE:-0}" -eq 1 ]]; then
  296. # Invalidate and re-parse
  297. rm -f "$workspace/.ralph/$TASK_MTIME_FILE" 2>/dev/null
  298. parse_tasks "$workspace"
  299. fi
  300. }
  301. # =============================================================================
  302. # PROMPT BUILDING
  303. # =============================================================================
  304. # Build the Ralph prompt for an iteration
  305. build_prompt() {
  306. local workspace="$1"
  307. local iteration="$2"
  308. cat << EOF
  309. # Ralph Iteration $iteration
  310. You are an autonomous development agent using the Ralph methodology.
  311. ## FIRST: Read State Files
  312. Before doing anything:
  313. 1. Read \`RALPH_TASK.md\` - your task and completion criteria
  314. 2. Read \`.ralph/guardrails.md\` - lessons from past failures (FOLLOW THESE)
  315. 3. Read \`.ralph/progress.md\` - what's been accomplished
  316. 4. Read \`.ralph/errors.log\` - recent failures to avoid
  317. ## Working Directory (Critical)
  318. You are already in a git repository. Work HERE, not in a subdirectory:
  319. - Do NOT run \`git init\` - the repo already exists
  320. - Do NOT run scaffolding commands that create nested directories (\`npx create-*\`, \`pnpm init\`, etc.)
  321. - If you need to scaffold, use flags like \`--no-git\` or scaffold into the current directory (\`.\`)
  322. - All code should live at the repo root or in subdirectories you create manually
  323. ## Git Protocol (Critical)
  324. Ralph's strength is state-in-git, not LLM memory. Commit early and often:
  325. 1. After completing each criterion, commit your changes:
  326. \`git add -A && git commit -m 'ralph: implement state tracker'\`
  327. \`git add -A && git commit -m 'ralph: fix async race condition'\`
  328. \`git add -A && git commit -m 'ralph: add CLI adapter with commander'\`
  329. Always describe what you actually did - never use placeholders like '<description>'
  330. 2. After any significant code change (even partial): commit with descriptive message
  331. 3. Before any risky refactor: commit current state as checkpoint
  332. 4. Push after every 2-3 commits: \`git push\`
  333. If you get rotated, the next agent picks up from your last commit. Your commits ARE your memory.
  334. ## Task Execution
  335. 1. Work on the next unchecked criterion in RALPH_TASK.md (look for \`[ ]\`)
  336. 2. Run tests after changes (check RALPH_TASK.md for test_command)
  337. 3. **Mark completed criteria**: Edit RALPH_TASK.md and change \`[ ]\` to \`[x]\`
  338. - Example: \`- [ ] Implement parser\` becomes \`- [x] Implement parser\`
  339. - This is how progress is tracked - YOU MUST update the file
  340. 4. Update \`.ralph/progress.md\` with what you accomplished
  341. 5. When ALL criteria show \`[x]\`: output \`<ralph>COMPLETE</ralph>\`
  342. 6. If stuck 3+ times on same issue: output \`<ralph>GUTTER</ralph>\`
  343. ## Learning from Failures
  344. When something fails:
  345. 1. Check \`.ralph/errors.log\` for failure history
  346. 2. Figure out the root cause
  347. 3. Add a Sign to \`.ralph/guardrails.md\` using this format:
  348. \`\`\`
  349. ### Sign: [Descriptive Name]
  350. - **Trigger**: When this situation occurs
  351. - **Instruction**: What to do instead
  352. - **Added after**: Iteration $iteration - what happened
  353. \`\`\`
  354. ## Context Rotation Warning
  355. You may receive a warning that context is running low. When you see it:
  356. 1. Finish your current file edit
  357. 2. Commit and push your changes
  358. 3. Update .ralph/progress.md with what you accomplished and what's next
  359. 4. You will be rotated to a fresh agent that continues your work
  360. Begin by reading the state files.
  361. EOF
  362. }
  363. # =============================================================================
  364. # SPINNER
  365. # =============================================================================
  366. # Spinner to show the loop is alive (not frozen)
  367. # Outputs to stderr so it's not captured by $()
  368. spinner() {
  369. local workspace="$1"
  370. local spin='⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏'
  371. local i=0
  372. while true; do
  373. printf "\r 🐛 Agent working... %s (watch: tail -f %s/.ralph/activity.log)" "${spin:i++%${#spin}:1}" "$workspace" >&2
  374. sleep 0.1
  375. done
  376. }
  377. # =============================================================================
  378. # ITERATION RUNNER
  379. # =============================================================================
  380. # Run a single agent iteration
  381. # Returns: signal (ROTATE, GUTTER, COMPLETE, or empty)
  382. run_iteration() {
  383. local workspace="$1"
  384. local iteration="$2"
  385. local session_id="${3:-}"
  386. local script_dir="${4:-$(dirname "${BASH_SOURCE[0]}")}"
  387. local prompt=$(build_prompt "$workspace" "$iteration")
  388. local fifo="$workspace/.ralph/.parser_fifo"
  389. # Create named pipe for parser signals
  390. rm -f "$fifo"
  391. mkfifo "$fifo"
  392. # Use stderr for display (stdout is captured for signal)
  393. echo "" >&2
  394. echo "═══════════════════════════════════════════════════════════════════" >&2
  395. echo "🐛 Ralph Iteration $iteration" >&2
  396. echo "═══════════════════════════════════════════════════════════════════" >&2
  397. echo "" >&2
  398. echo "Workspace: $workspace" >&2
  399. echo "Model: $MODEL" >&2
  400. echo "Monitor: tail -f $workspace/.ralph/activity.log" >&2
  401. echo "" >&2
  402. # Log session start to progress.md
  403. log_progress "$workspace" "**Session $iteration started** (model: $MODEL)"
  404. # Build cursor-agent command
  405. local cmd="cursor-agent -p --force --output-format stream-json --model $MODEL"
  406. if [[ -n "$session_id" ]]; then
  407. echo "Resuming session: $session_id" >&2
  408. cmd="$cmd --resume=\"$session_id\""
  409. fi
  410. # Change to workspace
  411. cd "$workspace"
  412. # Start spinner to show we're alive
  413. spinner "$workspace" &
  414. local spinner_pid=$!
  415. # Start parser in background, reading from cursor-agent
  416. # Parser outputs to fifo, we read signals from fifo
  417. (
  418. eval "$cmd \"$prompt\"" 2>&1 | "$script_dir/stream-parser.sh" "$workspace" > "$fifo"
  419. ) &
  420. local agent_pid=$!
  421. # Read signals from parser
  422. local signal=""
  423. while IFS= read -r line; do
  424. case "$line" in
  425. "ROTATE")
  426. printf "\r\033[K" >&2 # Clear spinner line
  427. echo "🔄 Context rotation triggered - stopping agent..." >&2
  428. kill $agent_pid 2>/dev/null || true
  429. signal="ROTATE"
  430. break
  431. ;;
  432. "WARN")
  433. printf "\r\033[K" >&2 # Clear spinner line
  434. echo "⚠️ Context warning - agent should wrap up soon..." >&2
  435. # Send interrupt to encourage wrap-up (agent continues but is notified)
  436. ;;
  437. "GUTTER")
  438. printf "\r\033[K" >&2 # Clear spinner line
  439. echo "🚨 Gutter detected - agent may be stuck..." >&2
  440. signal="GUTTER"
  441. # Don't kill yet, let agent try to recover
  442. ;;
  443. "COMPLETE")
  444. printf "\r\033[K" >&2 # Clear spinner line
  445. echo "✅ Agent signaled completion!" >&2
  446. signal="COMPLETE"
  447. # Let agent finish gracefully
  448. ;;
  449. "DEFER")
  450. printf "\r\033[K" >&2 # Clear spinner line
  451. echo "⏸️ Rate limit or transient error - deferring for retry..." >&2
  452. signal="DEFER"
  453. # Stop the agent, will retry with backoff
  454. kill $agent_pid 2>/dev/null || true
  455. ;;
  456. esac
  457. done < "$fifo"
  458. # Wait for agent to finish
  459. wait $agent_pid 2>/dev/null || true
  460. # Stop spinner and clear line
  461. kill $spinner_pid 2>/dev/null || true
  462. wait $spinner_pid 2>/dev/null || true
  463. printf "\r\033[K" >&2 # Clear spinner line
  464. # Cleanup
  465. rm -f "$fifo"
  466. echo "$signal"
  467. }
  468. # =============================================================================
  469. # MAIN LOOP
  470. # =============================================================================
  471. # Run the main Ralph loop
  472. # Args: workspace
  473. # Uses global: MAX_ITERATIONS, MODEL, USE_BRANCH, OPEN_PR
  474. run_ralph_loop() {
  475. local workspace="$1"
  476. local script_dir="${2:-$(dirname "${BASH_SOURCE[0]}")}"
  477. # Commit any uncommitted work first
  478. cd "$workspace"
  479. if [[ -n "$(git status --porcelain 2>/dev/null)" ]]; then
  480. echo "📦 Committing uncommitted changes..."
  481. git add -A
  482. git commit -m "ralph: initial commit before loop" || true
  483. fi
  484. # Create branch if requested
  485. if [[ -n "$USE_BRANCH" ]]; then
  486. echo "🌿 Creating branch: $USE_BRANCH"
  487. git checkout -b "$USE_BRANCH" 2>/dev/null || git checkout "$USE_BRANCH"
  488. fi
  489. echo ""
  490. echo "🚀 Starting Ralph loop..."
  491. echo ""
  492. # Main loop
  493. local iteration=1
  494. local session_id=""
  495. while [[ $iteration -le $MAX_ITERATIONS ]]; do
  496. # Run iteration
  497. local signal
  498. signal=$(run_iteration "$workspace" "$iteration" "$session_id" "$script_dir")
  499. # Check task completion
  500. local task_status
  501. task_status=$(check_task_complete "$workspace")
  502. if [[ "$task_status" == "COMPLETE" ]]; then
  503. log_progress "$workspace" "**Session $iteration ended** - ✅ TASK COMPLETE"
  504. echo ""
  505. echo "═══════════════════════════════════════════════════════════════════"
  506. echo "🎉 RALPH COMPLETE! All criteria satisfied."
  507. echo "═══════════════════════════════════════════════════════════════════"
  508. echo ""
  509. echo "Completed in $iteration iteration(s)."
  510. echo "Check git log for detailed history."
  511. # Open PR if requested
  512. if [[ "$OPEN_PR" == "true" ]] && [[ -n "$USE_BRANCH" ]]; then
  513. echo ""
  514. echo "📝 Opening pull request..."
  515. git push -u origin "$USE_BRANCH" 2>/dev/null || git push
  516. if command -v gh &> /dev/null; then
  517. gh pr create --fill || echo "⚠️ Could not create PR automatically. Create manually."
  518. else
  519. echo "⚠️ gh CLI not found. Push complete, create PR manually."
  520. fi
  521. fi
  522. return 0
  523. fi
  524. # Handle signals
  525. case "$signal" in
  526. "COMPLETE")
  527. # Agent signaled completion - verify with checkbox check
  528. if [[ "$task_status" == "COMPLETE" ]]; then
  529. log_progress "$workspace" "**Session $iteration ended** - ✅ TASK COMPLETE (agent signaled)"
  530. echo ""
  531. echo "═══════════════════════════════════════════════════════════════════"
  532. echo "🎉 RALPH COMPLETE! Agent signaled completion and all criteria verified."
  533. echo "═══════════════════════════════════════════════════════════════════"
  534. echo ""
  535. echo "Completed in $iteration iteration(s)."
  536. echo "Check git log for detailed history."
  537. # Open PR if requested
  538. if [[ "$OPEN_PR" == "true" ]] && [[ -n "$USE_BRANCH" ]]; then
  539. echo ""
  540. echo "📝 Opening pull request..."
  541. git push -u origin "$USE_BRANCH" 2>/dev/null || git push
  542. if command -v gh &> /dev/null; then
  543. gh pr create --fill || echo "⚠️ Could not create PR automatically. Create manually."
  544. else
  545. echo "⚠️ gh CLI not found. Push complete, create PR manually."
  546. fi
  547. fi
  548. return 0
  549. else
  550. # Agent said complete but checkboxes say otherwise - continue
  551. log_progress "$workspace" "**Session $iteration ended** - Agent signaled complete but criteria remain"
  552. echo ""
  553. echo "⚠️ Agent signaled completion but unchecked criteria remain."
  554. echo " Continuing with next iteration..."
  555. iteration=$((iteration + 1))
  556. fi
  557. ;;
  558. "ROTATE")
  559. log_progress "$workspace" "**Session $iteration ended** - 🔄 Context rotation (token limit reached)"
  560. echo ""
  561. echo "🔄 Rotating to fresh context..."
  562. iteration=$((iteration + 1))
  563. session_id=""
  564. ;;
  565. "GUTTER")
  566. log_progress "$workspace" "**Session $iteration ended** - 🚨 GUTTER (agent stuck)"
  567. echo ""
  568. echo "🚨 Gutter detected. Check .ralph/errors.log for details."
  569. echo " The agent may be stuck. Consider:"
  570. echo " 1. Check .ralph/guardrails.md for lessons"
  571. echo " 2. Manually fix the blocking issue"
  572. echo " 3. Re-run the loop"
  573. return 1
  574. ;;
  575. "DEFER")
  576. # Rate limit or transient error - wait with exponential backoff then retry
  577. log_progress "$workspace" "**Session $iteration ended** - ⏸️ DEFERRED (rate limit/transient error)"
  578. # Calculate backoff delay (uses ralph-retry.sh functions if available)
  579. local defer_delay=30
  580. if type calculate_backoff_delay &>/dev/null; then
  581. local defer_attempt=${DEFER_COUNT:-1}
  582. DEFER_COUNT=$((defer_attempt + 1))
  583. defer_delay=$(($(calculate_backoff_delay "$defer_attempt" 15 120 true) / 1000))
  584. fi
  585. echo ""
  586. echo "⏸️ Rate limit or transient error detected."
  587. echo " Waiting ${defer_delay}s before retrying (attempt ${DEFER_COUNT:-1})..."
  588. sleep "$defer_delay"
  589. # Don't increment iteration - retry the same task
  590. echo " Resuming..."
  591. ;;
  592. *)
  593. # Agent finished naturally, check if more work needed
  594. if [[ "$task_status" == INCOMPLETE:* ]]; then
  595. local remaining_count=${task_status#INCOMPLETE:}
  596. log_progress "$workspace" "**Session $iteration ended** - Agent finished naturally ($remaining_count criteria remaining)"
  597. echo ""
  598. echo "📋 Agent finished but $remaining_count criteria remaining."
  599. echo " Starting next iteration..."
  600. iteration=$((iteration + 1))
  601. fi
  602. ;;
  603. esac
  604. # Brief pause between iterations
  605. sleep 2
  606. done
  607. log_progress "$workspace" "**Loop ended** - ⚠️ Max iterations ($MAX_ITERATIONS) reached"
  608. echo ""
  609. echo "⚠️ Max iterations ($MAX_ITERATIONS) reached."
  610. echo " Task may not be complete. Check progress manually."
  611. return 1
  612. }
  613. # =============================================================================
  614. # PREREQUISITE CHECKS
  615. # =============================================================================
  616. # Check all prerequisites, exit with error message if any fail
  617. check_prerequisites() {
  618. local workspace="$1"
  619. local task_file="$workspace/RALPH_TASK.md"
  620. # Check for task file
  621. if [[ ! -f "$task_file" ]]; then
  622. echo "❌ No RALPH_TASK.md found in $workspace"
  623. echo ""
  624. echo "Create a task file first:"
  625. echo " cat > RALPH_TASK.md << 'EOF'"
  626. echo " ---"
  627. echo " task: Your task description"
  628. echo " test_command: \"pnpm test\""
  629. echo " ---"
  630. echo " # Task"
  631. echo " ## Success Criteria"
  632. echo " 1. [ ] First thing to do"
  633. echo " 2. [ ] Second thing to do"
  634. echo " EOF"
  635. return 1
  636. fi
  637. # Check for cursor-agent CLI
  638. if ! command -v cursor-agent &> /dev/null; then
  639. echo "❌ cursor-agent CLI not found"
  640. echo ""
  641. echo "Install via:"
  642. 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
  643. return 1
  644. fi
  645. # Check for git repo
  646. if ! git -C "$workspace" rev-parse --git-dir > /dev/null 2>&1; then
  647. echo "❌ Not a git repository"
  648. echo " Ralph requires git for state persistence."
  649. return 1
  650. fi
  651. return 0
  652. }
  653. # =============================================================================
  654. # DISPLAY HELPERS
  655. # =============================================================================
  656. # Show task summary
  657. show_task_summary() {
  658. local workspace="$1"
  659. local task_file="$workspace/RALPH_TASK.md"
  660. echo "📋 Task Summary:"
  661. echo "─────────────────────────────────────────────────────────────────"
  662. head -30 "$task_file"
  663. echo "─────────────────────────────────────────────────────────────────"
  664. echo ""
  665. # Count criteria - only actual checkbox list items (- [ ], * [x], 1. [ ], etc.)
  666. local total_criteria done_criteria remaining
  667. total_criteria=$(grep -cE '^[[:space:]]*([-*]|[0-9]+\.)[[:space:]]+\[(x| )\]' "$task_file" 2>/dev/null) || total_criteria=0
  668. done_criteria=$(grep -cE '^[[:space:]]*([-*]|[0-9]+\.)[[:space:]]+\[x\]' "$task_file" 2>/dev/null) || done_criteria=0
  669. remaining=$((total_criteria - done_criteria))
  670. echo "Progress: $done_criteria / $total_criteria criteria complete ($remaining remaining)"
  671. echo "Model: $MODEL"
  672. echo ""
  673. # Return remaining count for caller to check
  674. echo "$remaining"
  675. }
  676. # Show Ralph banner
  677. show_banner() {
  678. echo "═══════════════════════════════════════════════════════════════════"
  679. echo "🐛 Ralph Wiggum: Autonomous Development Loop"
  680. echo "═══════════════════════════════════════════════════════════════════"
  681. echo ""
  682. echo " \"That's the beauty of Ralph - the technique is deterministically"
  683. echo " bad in an undeterministic world.\""
  684. echo ""
  685. echo "═══════════════════════════════════════════════════════════════════"
  686. echo ""
  687. }

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.