Skip to content

robert-fahey/cursor-ralph

Repository files navigation

Ralph for Cursor

image

An autonomous AI agent loop that runs Cursor repeatedly until all PRD items are complete. Features an AI-driven Plan Mode that understands your PRD in any format, proposes user stories, asks clarifying questions, and generates structured JSON for execution.

Based on snarktank/ralph, adapted for Cursor AI.

Installation

The easiest way to install is via Homebrew:

# Add the tap
brew tap robert-fahey/cursor-ralph

# Install cursor-ralph
brew install cursor-ralph

After installation, the cursor-ralph command is available globally. Run cursor-ralph --help to get started.

Alternative: Clone this repo and use ./ralph.sh directly for development or customization.

Features

  • Flexible PRD Format: Write your PRD naturally - free-form prose, requirements lists, or structured stories
  • AI-Driven Planning: Cursor Agent analyzes your PRD, proposes stories, and asks for clarification when needed
  • Autonomous Execution: Runs Cursor on each story until all pass
  • Quality Gates: Automatic type checking, linting, and testing
  • Code Review: Each story is reviewed for security, bugs, and code quality before commit
  • Container Mode: Run builds and tests in Docker for sandboxed, isolated execution
  • Context7 Integration: Verifies library usage against up-to-date documentation
  • Progress Tracking: Append-only log of learnings and decisions
  • Automatic Archiving: Previous runs are archived when starting new features

Prerequisites

  • Cursor Agent CLI for autonomous execution (required for automation)
    curl https://cursor.com/install -fsS | bash
  • jq and git (installed automatically with Homebrew, or brew install jq git)

Note: Without cursor-agent, Ralph falls back to interactive mode where you work with the AI in Cursor IDE to plan and implement stories.

What is a PRD?

A PRD (Product Requirements Document) is a document that describes what you want to build. It bridges the gap between an idea and implementation by clearly articulating the problem, goals, and requirements.

Ralph uses your PRD as input and works with Cursor's AI to:

  1. Break it down into implementable user stories
  2. Execute each story autonomously
  3. Verify the implementation meets your requirements

Your PRD can be as simple or detailed as you like - from a few sentences describing a feature to a full specification with acceptance criteria. Ralph's AI will ask clarifying questions if anything is unclear.

Learn More About PRDs

See PRD.md.example for a complete example.

Quick Start

1. Write Your PRD

Create a PRD.md file in your project directory:

# My Feature

Describe what you want to build. Include:
- What problem you're solving
- Key features needed  
- Technical constraints (language, frameworks, APIs)

2. Run Plan Mode

Let the AI analyze your PRD and propose stories:

cursor-ralph --plan

Plan mode will:

  1. Read your PRD (in any format)
  2. Ask clarifying questions if anything is unclear
  3. Propose well-structured user stories
  4. Let you review and adjust the stories
  5. Generate a structured prd.json file

3. Execute

Run the autonomous agent loop:

cursor-ralph --execute

Or combine both in one command:

cursor-ralph --plan --execute

Usage

cursor-ralph [OPTIONS]

Options:
  --plan              Run plan mode (AI analyzes PRD → generates prd.json)
  --execute           Run execute mode (autonomous agent loop)
  --container         Run quality checks in Docker container (sandboxed)
  --project DIR       Project directory for generated code (default: ./project)
  --max-iterations N  Maximum iterations (default: 10)
  --prd-md FILE       Path to PRD markdown file (default: PRD.md)
  --prd FILE          Path to PRD JSON file (default: prd.json)
  --help              Show help message

How It Works

flowchart TD
    subgraph plan [Plan Mode - AI-Driven]
        A[Load PRD.md] --> B[Cursor Agent Analyzes]
        B --> C{Clear enough?}
        C -->|No| D[Ask Clarifying Questions]
        D --> E[User Answers]
        E --> B
        C -->|Yes| F[Propose Stories]
        F --> G[User Reviews]
        G -->|Adjust| F
        G -->|Approve| H[Generate prd.json]
    end

    subgraph execute [Execute Mode]
        I[Pick Next Story] --> J[Invoke Cursor AI]
        J --> K[Run Quality Checks]
        K -->|Fail| L[Fix Issues]
        L --> K
        K -->|Pass| M[Code Review]
        M --> N{Issues Found?}
        N -->|Critical/High| O[Apply Fixes]
        O --> K
        N -->|None/Low| P[Git Commit]
        P --> Q[Mark Complete]
        Q --> R{More Stories?}
        R -->|Yes| I
        R -->|No| S[Done]
    end

    H --> I
Loading

Plan Mode

The AI-driven planning process:

  1. Load your PRD.md (any format - prose, lists, or structured)
  2. Analyze the requirements using Cursor Agent
  3. Clarify by asking questions if anything is ambiguous
  4. Propose right-sized user stories with acceptance criteria
  5. Review with you and adjust as needed
  6. Generate structured prd.json for execution

Execute Mode

Loop until all stories pass or max iterations:

  1. Pick highest priority incomplete story
  2. Invoke Cursor AI with story context
  3. Run quality checks (typecheck, lint, test)
  4. Run code review (security, bugs, documentation)
  5. Apply review fixes and re-run quality checks
  6. Commit if passing
  7. Mark story complete in prd.json
  8. Log progress to progress.txt

File Structure

File Purpose
ralph.sh Main entry point and orchestrator
plan.sh Plan mode: AI-driven story planning
execute.sh Execution loop with code review
container.sh Container management (start/stop/exec)
Dockerfile Development container definition
docker-compose.yml Container orchestration config
prompt.md Instructions for Cursor during execution
review-prompt.md Instructions for code review phase
plan-prompt.md Instructions for AI planning agent
PRD.md Your PRD in any format (input)
PRD.md.example Example PRD formats
prd.json Generated structured PRD (output)
prd.json.example Example JSON format for reference
progress.txt Append-only log of learnings
.cursorrules Project conventions (auto-updated)
.env Environment variables (CONTEXT7_API_KEY)
project/ Generated code directory (default)

Writing Your PRD

Any Format Works

Ralph's AI understands natural language. You can write your PRD as:

  • Prose: Describe what you want in plain English
  • Requirements list: Bullet points of features
  • User stories: Pre-structured if you prefer
  • Mix: Combine all of the above

Tips for Better Results

Be specific about technology choices:

Use React with TypeScript, Tailwind for styling, and React Query for data fetching.

Mention constraints:

Must work offline. Should support IE11. Max bundle size 200KB.

Include context:

This is for an existing Next.js app. Follow the patterns in src/components/.

Describe edge cases:

Handle empty states, loading states, and error states for all data fetching.

The AI Will Ask Questions

If your PRD is ambiguous, the AI will ask clarifying questions before proposing stories:

Before I can propose user stories, I have some questions:

1. What authentication provider should we use (Auth0, Firebase, custom)?
2. Should the API support pagination, and if so, what page size?
3. Is there an existing design system to follow, or should I propose one?

Answer these questions, and the AI will incorporate your answers into the stories.

Writing Good Stories

The AI will propose stories, but understanding what makes a good story helps you review them:

Right-Sized Stories

Each story should be completable in a single context window. Good examples:

  • Add a single API endpoint
  • Create one UI component
  • Add a database migration
  • Implement one business logic function

Too large (the AI should split these):

  • "Build the entire dashboard"
  • "Add authentication"
  • "Refactor the API layer"

Clear Acceptance Criteria

Criteria should be specific and testable:

Good:

  • "Button displays 'Submit' text"
  • "Form validates email format using regex"
  • "API returns 404 for missing resources"
  • "Component is located in src/components/Button.tsx"

Bad:

  • "Should work properly"
  • "Looks good on mobile"
  • "Performs well"

Quality Checks

Ralph automatically detects and runs quality checks based on your project:

Project Type Typecheck Lint Test
TypeScript/Node npm run typecheck or tsc --noEmit npm run lint or ESLint npm test
Rust cargo check cargo clippy cargo test
Go go build ./... golangci-lint or go vet go test ./...
Python mypy . ruff or flake8 pytest

Ralph also checks for Makefile targets (make test, make lint, make typecheck) as fallbacks.

Override with environment variables:

TYPECHECK_CMD="npm run type-check" \
LINT_CMD="npm run lint:fix" \
TEST_CMD="npm run test:ci" \
cursor-ralph --execute

Code Review

Each story is automatically code reviewed before being committed. The review checks for:

  • Security: Exposed secrets, auth vulnerabilities, injection attacks
  • Documentation: Library usage verified against latest docs (via Context7)
  • Bugs: Logic errors, race conditions, memory leaks, N+1 queries
  • Code Quality: TypeScript any, React hooks, error handling

Severity Levels

Level Description Action
Critical Security vulnerabilities, system-breaking bugs Must fix
High Significant bugs, incorrect auth logic Must fix
Medium Code quality issues, minor bugs Should fix
Low Style issues, minor improvements Optional

Review Configuration

Control review cycles with environment variables:

# Maximum number of review/fix cycles before proceeding (default: 3)
MAX_REVIEW_CYCLES=5 cursor-ralph --execute

Container Mode (Sandboxed Execution)

Ralph can run quality checks, tests, and builds inside a Docker container for isolation and security. This prevents generated code from accidentally modifying your host system.

Prerequisites

  • Docker installed and running (brew install --cask docker on macOS)

Quick Start

# Start the development container
./container.sh start

# Run Ralph with container mode
cursor-ralph --execute --container

# Or set environment variable
export RALPH_USE_CONTAINER=true
cursor-ralph --execute

What Gets Sandboxed

Component Runs In
Ralph orchestration Host
cursor-agent Host
npm install / pip install Container
Type checking Container
Linting Container
Tests Container
Git operations Container

Container Management

Use container.sh to manage the development container:

./container.sh start    # Build and start the container
./container.sh stop     # Stop the container
./container.sh restart  # Restart the container
./container.sh shell    # Open interactive shell in container
./container.sh exec <cmd>  # Run a command in container
./container.sh status   # Check if container is running
./container.sh logs     # View container logs
./container.sh clean    # Remove container and images

Manual Container Commands

You can also run commands directly:

# Run npm install in container
./container.sh exec npm install

# Run tests in container
./container.sh exec npm test

# Interactive shell
./container.sh shell

Container Configuration

The container includes:

  • Node.js 20 (LTS)
  • Python 3
  • Go 1.22
  • Rust (latest stable)
  • Git
  • Common build tools
  • TypeScript, ESLint, Prettier (globally installed)

To customize, edit Dockerfile and rebuild:

./container.sh stop
./container.sh start  # Rebuilds automatically

Security Benefits

  1. Filesystem isolation: Generated code cannot access files outside ./project
  2. Package safety: Malicious npm/pip packages cannot escape the container
  3. Easy cleanup: ./container.sh clean removes everything
  4. Reproducible: Same environment across machines

Context7 Integration

The code review uses Context7 to verify library usage against up-to-date documentation. This helps catch:

  • Deprecated API methods
  • Incorrect library usage patterns
  • Breaking changes in dependencies
  • Security best practices for specific libraries

Setup Context7

  1. Get an API key from Context7
  2. Add it to your .env file:
CONTEXT7_API_KEY=your-api-key-here

Ralph automatically loads from .env in the current directory or the Ralph script directory.

Alternatively, set it as an environment variable:

export CONTEXT7_API_KEY="your-api-key-here"
cursor-ralph --execute

How It Works

During code review, Ralph will:

  1. Detect libraries from package.json, requirements.txt, go.mod, and imports in the diff
  2. Fetch documentation from Context7 API for each library (up to 5)
  3. Include docs in review prompt so the reviewer can verify correct usage

Without Context7

Code review will still work without Context7, but documentation verification will be skipped. You'll see a warning:

[WARNING] CONTEXT7_API_KEY not set - skipping documentation lookup

The review will still check for security issues, bugs, and code quality.

Debugging

Check Current State

# See the generated JSON
cat prd.json | jq '.'

# See which stories are complete
cat prd.json | jq '.userStories[] | {id, title, passes}'

# View progress log
cat progress.txt

# Check git history
git log --oneline -10

Common Issues

"PRD file not found"

  • Create a PRD.md file or specify path with --prd-md

"Could not extract valid JSON from agent output"

  • The AI is probably asking clarifying questions - answer them
  • Try making your PRD more specific
  • Check that cursor-agent is working: cursor-agent --version

"No quality checks configured"

  • Add test/lint scripts to package.json, or set environment variables

"Cursor CLI not available"

  • Install Cursor CLI, or Ralph will prompt for manual implementation

Story keeps failing

  • Check progress.txt for error patterns
  • The story might be too large - ask to split it
  • Add more specific acceptance criteria

Example Workflows

New Project

# 1. Initialize your project with git
mkdir my-todo-app && cd my-todo-app
git init
git remote add origin git@github.com:yourname/my-todo-app.git

# 2. Create your PRD (write naturally!)
cat > PRD.md << 'EOF'
# Simple Todo App

Build a basic todo application with React and TypeScript.

Features needed:
- Add new todos with a text input
- Mark todos as complete (checkbox)
- Delete todos
- Filter by: all, active, completed
- Persist to localStorage

Keep it simple - no backend needed.
EOF

# 3. Run plan mode - AI will propose stories
cursor-ralph --plan

# 4. Execute the autonomous loop
cursor-ralph --execute

# Or do both at once
cursor-ralph --plan --execute

# 5. Push completed work to remote
git push -u origin main

Existing Repository

# 1. Navigate to your existing project
cd ~/Projects/my-existing-app

# 2. Create a feature branch (optional but recommended)
git checkout -b feature/add-user-dashboard

# 3. Create a PRD for the new feature
cat > PRD.md << 'EOF'
# User Dashboard

Add a dashboard page to the existing app that shows:
- User profile summary
- Recent activity feed
- Quick action buttons

## Technical Context
- This is a Next.js 14 app using the App Router
- Follow existing patterns in src/app/ directory
- Use the existing Tailwind config and component library
- Auth is already set up via NextAuth in src/lib/auth.ts
EOF

# 4. Run cursor-ralph
cursor-ralph --plan --execute

# 5. Review and push
git log --oneline -5        # Review commits
git push -u origin feature/add-user-dashboard

# 6. Clean up PRD files (optional)
rm PRD.md prd.json progress.txt

Monorepo (specific package/app)

# 1. Navigate to your monorepo
cd ~/Projects/my-monorepo

# 2. Create PRD at the root (or in a docs folder)
cat > PRD.md << 'EOF'
# API Authentication

Add JWT authentication to the API package.

## Technical Context
- Target package: packages/api
- Use existing shared types from packages/types
- Follow patterns in packages/api/src/middleware/
EOF

# 3. Run cursor-ralph with --project pointing to the target
cursor-ralph --plan --project ./packages/api
cursor-ralph --execute --project ./packages/api

# 4. Push changes
git push origin main

Contributing

Contributions welcome! Please:

  1. Fork the repository
  2. Create a feature branch
  3. Write clear acceptance criteria
  4. Submit a pull request

License

MIT

Credits

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Packages

 
 
 

Contributors