Skip to content

Latest commit

 

History

History
388 lines (281 loc) · 8.89 KB

File metadata and controls

388 lines (281 loc) · 8.89 KB

Advanced Usage

Custom Prompts

Modifying Default Prompts

Edit the prompts in your project's ralph/ directory:

# Edit planning prompt
vim ralph/PROMPT_plan.md

# Edit building prompt
vim ralph/PROMPT_build.md

Changes only affect your project and are tracked in git.

Prompt Variables

Available variables in prompts:

Variable Description Set By
${RALPH_GOAL} Custom goal for planning ralph.config
${WORK_SCOPE} Scoped planning target CLI argument

Adding Custom Prompts

Create new prompt files for specialized workflows:

# ralph/PROMPT_refactor.md
cat > ralph/PROMPT_refactor.md << 'EOF'
# Ralph Refactoring Mode

Focus on code quality improvements without changing behavior.

1. Study the codebase for code smells
2. Identify refactoring opportunities
3. Make changes with comprehensive tests
4. Validate behavior is unchanged

RULES:
- No new features
- No API changes
- Tests must pass before and after
EOF

Use with a custom mode (requires extending loop.sh).

Working with Existing Plans

Bringing Your Own Plan

Skip ralph plan entirely when you already have a plan:

# Initialize without running plan
ralph init

# Replace with your existing plan (JSON format)
cat > ralph/prd.json << 'EOF'
{
  "meta": {
    "goal": "Build user authentication system",
    "created_at": "2025-01-23T15:00:00Z",
    "updated_at": "2025-01-23T15:00:00Z",
    "iteration": 0
  },
  "tasks": [
    {"id": "task-001", "description": "Set up database schema for users table", "status": "pending", "priority": 1, "depends_on": [], "spec": "auth.md"},
    {"id": "task-002", "description": "Implement user registration endpoint", "status": "pending", "priority": 2, "depends_on": ["task-001"], "spec": "auth.md"},
    {"id": "task-003", "description": "Add JWT authentication middleware", "status": "pending", "priority": 3, "depends_on": ["task-002"], "spec": "auth.md"},
    {"id": "task-004", "description": "Create login/logout endpoints", "status": "pending", "priority": 4, "depends_on": ["task-003"], "spec": "auth.md"},
    {"id": "task-005", "description": "Add password reset flow", "status": "pending", "priority": 5, "depends_on": ["task-004"], "spec": "auth.md"}
  ],
  "issues": []
}
EOF

# Go straight to building
ralph 20

Converting from PRDs/Design Docs

If you have a PRD or design doc, you can either:

  1. Manual conversion: Create prd.json with tasks from your PRD
  2. AI-assisted conversion: Use Claude/GPT to convert the PRD to Ralph JSON format
  3. Hybrid approach: Put the PRD in ralph/specs/ and run ralph plan once to generate the initial tasks, then edit prd.json

Example conversion prompt:

Convert this PRD into a Ralph prd.json format.
Use this JSON schema:
{
  "meta": {"goal": "string", "iteration": 0},
  "tasks": [{"id": "task-NNN", "description": "string", "status": "pending", "priority": N, "depends_on": [], "spec": "filename.md"}],
  "issues": []
}
Order tasks by priority (1 = highest). Set depends_on for task dependencies.

Live Plan Editing

You can edit prd.json while Ralph is running:

  1. Wait for current iteration to complete (watch for "END ITERATION" message)
  2. Edit ralph/prd.json (add tasks, change priorities, etc.)
  3. Ralph reads fresh state at start of next iteration

This is useful for:

  • Reprioritizing mid-run
  • Adding urgent tasks
  • Removing tasks that are no longer needed
  • Fixing incorrect task descriptions

Use ralph status to view current state in a readable format.

Syncing with External Tools

Pull plans from external sources and convert to JSON:

# From GitHub Issues (creates JSON tasks)
gh issue list --json number,title --jq '[.[] | {id: "task-\(.number)", description: .title, status: "pending", priority: .number, depends_on: [], spec: null}]' | \
  jq '{meta: {goal: "From GitHub Issues", iteration: 0}, tasks: ., issues: []}' > ralph/prd.json

# From Linear (example with custom script)
./scripts/sync-from-linear.sh > ralph/prd.json

# Merge with existing prd.json
jq -s '.[0].tasks += .[1].tasks | .[0]' ralph/prd.json new-tasks.json > ralph/prd.json.tmp && mv ralph/prd.json.tmp ralph/prd.json

Multi-Agent Workflows

Parallel Feature Development

Run multiple Ralphs on different branches:

# Terminal 1: Auth feature
git checkout -b feature/auth
ralph plan-work "user authentication"
ralph --docker

# Terminal 2: API feature
git checkout -b feature/api
ralph plan-work "REST API endpoints"
ralph --docker

Planning Then Building

Separate planning from execution:

# Human-guided planning
ralph plan          # Review the output
vim ralph/prd.json  # Adjust priorities

# Autonomous building
ralph --docker 50   # Let it run

Staged Validation

Run different validation levels:

# Quick iterations (unit tests only)
RALPH_QUICK_VALIDATE=true ralph 10

# Full validation at checkpoints
ralph 5  # Full tests every 5 iterations

CI/CD Integration

GitHub Actions Workflow

# .github/workflows/ralph.yml
name: Ralph Build Loop

on:
  workflow_dispatch:
    inputs:
      iterations:
        description: 'Max iterations'
        default: '20'
      mode:
        description: 'Mode (plan/build)'
        default: 'build'

jobs:
  ralph:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Setup Ralph
        run: |
          git clone https://github.com/yourorg/ralph-wiggum.git ~/.ralph-wiggum
          echo "alias ralph='~/.ralph-wiggum/ralph.sh'" >> ~/.bashrc

      - name: Run Ralph
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
        run: |
          source ~/.bashrc
          if [ "${{ inputs.mode }}" = "plan" ]; then
            ralph plan ${{ inputs.iterations }}
          else
            ralph ${{ inputs.iterations }}
          fi

      - name: Create PR
        uses: peter-evans/create-pull-request@v5
        with:
          title: "Ralph: Automated changes"
          body: "Changes made by Ralph autonomous loop"

Pre-commit Hooks

Validate Ralph output before committing:

# .pre-commit-config.yaml
repos:
  - repo: local
    hooks:
      - id: validate-implementation-plan
        name: Validate Implementation Plan
        entry: bash -c 'test -f ralph/prd.json'
        language: system
        pass_filenames: false

Monitoring and Observability

Iteration Logging

Add timestamps and metrics to loop output:

# In lib/loop.sh, add to the loop:
echo "[$(date -Iseconds)] Iteration $iteration started" >> ralph.log
time run_agent "$prompt_file" "$mode"
echo "[$(date -Iseconds)] Iteration $iteration completed" >> ralph.log

Cost Tracking

Track API usage per session:

# Before running
export RALPH_SESSION_ID=$(date +%s)

# In CLI adapter, log requests
echo "$RALPH_SESSION_ID,$(date -Iseconds),request" >> ~/.ralph-costs.csv

Slack Notifications

Notify on completion:

# Add to loop.sh after completion
curl -X POST -H 'Content-type: application/json' \
  --data '{"text":"Ralph completed '$iteration' iterations"}' \
  $SLACK_WEBHOOK_URL

Performance Tuning

Parallel Spec Analysis

Increase subagent count for large codebases:

# In PROMPT_plan.md
0a. Study `specs/*` with up to 1000 parallel subagents...

Focused Contexts

For large projects, scope the context:

# In PROMPT_build.md
Focus only on files in `src/features/auth/` for this iteration.

Caching

Mount a persistent cache volume:

# docker-compose.yml
volumes:
  - ralph-cache:/home/ralph/.cache

volumes:
  ralph-cache:

Troubleshooting Loops

Infinite Loops

If Ralph keeps implementing the same thing:

  1. Check prd.json for duplicate tasks
  2. Verify the agent is marking tasks complete
  3. Check validation commands actually catch the issue

Slow Progress

If iterations take too long:

  1. Reduce spec scope
  2. Break large tasks into smaller ones
  3. Increase resource limits in Docker

Validation Failures

If validation keeps failing:

  1. Run validation commands manually to understand failures
  2. Check AGENTS.md has correct commands
  3. Verify the agent understands the error messages

Plan Drift

If the plan doesn't match reality:

  1. Run ralph plan to regenerate
  2. Manually review and prune completed items
  3. Check for conflicting specs

Extending Ralph

Custom CLI Adapters

Add support for new CLIs:

# lib/cli-adapters/myagent.sh
#!/bin/bash

run_agent() {
    local prompt_file="$1"
    local mode="$2"

    cat "$prompt_file" | myagent-cli \
        --autonomous \
        ${RALPH_MYAGENT_FLAGS:-}
}

Validation Hooks

Add custom validation:

# In lib/loop.sh, after run_agent:
if [[ -f "ralph/validate.sh" ]]; then
    source ralph/validate.sh
    custom_validate || exit 1
fi

Event Hooks

Add lifecycle hooks:

# ralph/hooks/pre-iteration.sh
# ralph/hooks/post-commit.sh
# ralph/hooks/on-error.sh