AgentSkillsCN

ralph-loop

启动自主编码循环,通过小型、渐进式的用户故事逐步实现功能。当您需要将新功能拆解为多个小故事来实施,或在迭代优化中推进任务进展,又或是让 Claude 在具备明确验收标准的全新功能上自主工作时,可使用此技能。此技能不适用于快速修复、调试,或需求尚不明确的场景。

SKILL.md
--- frontmatter
name: ralph-loop
description: Launch an autonomous coding loop that implements features through small, incremental user stories. Use when implementing new features that can be broken into small stories, working on tasks that benefit from iterative refinement, or letting Claude work autonomously on greenfield features with clear acceptance criteria. Not for quick fixes, debugging, or unclear requirements.

Ralph Loop

Autonomous coding loop that implements features through incremental user stories.

Quick Start

bash
# Run the loop (default 25 iterations)
.ralph/bin/ralph.sh

# Or with custom iterations
.ralph/bin/ralph.sh 15

# Or with Python (cross-platform)
python .ralph/bin/ralph.py --iterations 25

# Or with TUI dashboard
python .ralph/tui/main.py

Workflow Overview

  1. Gather intent from user
  2. Analyze feature thoroughly (map user journey, identify touchpoints, trace data flow)
  3. Break into small, testable user stories
  4. Generate PRD (.ralph/runtime/prd.json)
  5. Initialize progress file (.ralph/runtime/progress.txt)
  6. Create feature branch
  7. Present summary and launch
  8. Monitor and notify on completion

Step 1: Gather Intent

Ask the user:

  • What feature/goal?
  • Specific requirements or constraints?
  • Any existing spec or documentation?

Step 2: Feature Analysis (CRITICAL)

Before writing ANY stories, analyze comprehensively. Most failures come from implementing only the "happy path."

2a. Map Complete User Journey

  1. Entry points: How does user discover/access this?
  2. Primary flow: Main action
  3. Feedback loops: How does user know it worked?
  4. Persistent indicators: What shows state across app?
  5. Reverse actions: Undo/modify?
  6. Edge cases: Empty, error, loading states

2b. Identify ALL UI Touchpoints

Create a table:

LocationWhat ChangesData Needed
.........

Ask: "After this ships, how will user know [X]?"

2c. Trace Data Flow

For each touchpoint, identify:

  • New API endpoints needed?
  • Modified existing endpoints?
  • New/modified hooks?
  • Cache invalidation strategy?

If spec doesn't specify data flow, ASK before assuming.

2d. Find Gaps

Check for unspecified:

  • Loading states
  • Error states
  • Empty states
  • Permissions
  • Validation rules
  • Integration with existing features

When gaps found, ASK before assuming.

2e. Document Assumptions

List assumptions explicitly and get user confirmation.

Step 3: Break Into Stories

Only after Step 2, create small testable stories.

Size constraints:

  • Fit in ONE context window
  • Completable in ONE iteration
  • Touch minimal files (ideally 1-3)

Bad: "Build entire X system" Good: "Add X component", "Add X API endpoint", "Wire X to Y"

Acceptance criteria must be explicit:

  • Specific expected behavior
  • Typecheck/test commands pass
  • Reference existing patterns

See .ralph/docs/story-patterns.md for detailed guidance.

Step 4: Generate PRD

4a. Check Configuration

Read .ralph/config/ralph.config.json for:

  • Test/build commands
  • Base branch preference
  • Plan directories

4b. Check for Existing Plan

Check plan directories from config for related specs:

bash
ls [plan-dirs-from-config]

If plan exists:

  • Read task plan and findings for context
  • Link them in planFiles field
  • Reference implementation patterns from plan

4c. Write PRD

Write .ralph/runtime/prd.json:

json
{
  "featureName": "[Feature Name]",
  "branchName": "ralph/[feature-slug]",
  "baseBranch": "main",
  "description": "[What this accomplishes]",
  "planFiles": [
    "docs/plans/[feature]/task_plan.md"
  ],
  "userStories": [
    {
      "id": "US-001",
      "title": "[Short title]",
      "description": "[What this accomplishes]",
      "acceptanceCriteria": ["[Specific criterion]", "Typecheck passes", "Tests pass"],
      "testsToPass": [],
      "priority": 1,
      "passes": false,
      "notes": "[Pattern references]"
    }
  ]
}

Fields:

  • planFiles: Optional. Links to existing plan docs
  • baseBranch: Branch to create feature branch from (from config or default)
  • testsToPass: Optional. Specific tests that must pass (format: file:test name)
  • Priority: Lower = higher priority. Dependencies first (schema -> API -> hooks -> UI).

Step 5: Initialize Progress

Create .ralph/runtime/progress.txt:

markdown
# Ralph Progress Log
Started: [DATE]
Feature: [FEATURE_NAME]

## Codebase Patterns
- [Patterns from project's CLAUDE.md if available]

## Key Files
- [file] - [purpose]

## Commands (from .ralph/config/ralph.config.json)
- Typecheck: [command]
- Test: [command]
- Build: [command]
---

Step 6: Create Branch

bash
git checkout [baseBranch] && git pull && git checkout -b ralph/[feature-slug]

Step 7: Present Summary & Launch

Present structured summary:

markdown
## Ralph Loop Ready

### Feature: [Name]
[1-2 sentence description]

### User Stories ([N] total)
| # | Story | Description |
|---|-------|-------------|
| 1 | US-001: [Title] | [Brief] |

### Branch
`ralph/[feature-slug]`

### Estimated Cost
- Stories: [N]
- Iterations: [N + 5 buffer]
- Cost: $[X]-$[Y] (~$2-5/iteration)

Then ask user:

  • "Yes, run in background" -> Run with run_in_background: true
  • "No, I'll run manually" -> Provide command: .ralph/bin/ralph.sh [iterations]

Step 8: Monitor & Notify

When background task completes:

  1. Check output file for status
  2. Check .ralph/runtime/prd.json for story completion
  3. Report: "Ralph finished! PR at [URL]" or "Completed [X/Y] stories. Continue?"

Step 9: Archive PRD

After PR is created/merged, archive the PRD for historical reference:

bash
# Create archive directory
ARCHIVE_DIR="docs/ralph-history/[feature-slug]-$(date +%Y%m%d)"
mkdir -p "$ARCHIVE_DIR"
cp .ralph/runtime/prd.json "$ARCHIVE_DIR/prd.json"
cp .ralph/runtime/progress.txt "$ARCHIVE_DIR/progress.txt"
git add "$ARCHIVE_DIR"
git commit -m "docs: archive ralph PRD for [feature-name]"

Step 10: Finalize

PR created automatically targeting base branch. Review and merge.

Resume Failed/Incomplete Loop

bash
# Check status
cat .ralph/runtime/prd.json

# Resume with more iterations
.ralph/bin/ralph.sh [remaining + 5]

File Structure

code
your-project/
└── .ralph/                        # Ralph installation
    ├── bin/
    │   ├── ralph.sh              # Bash runner
    │   ├── ralph.ps1             # PowerShell runner
    │   └── ralph.py              # Python runner (cross-platform)
    ├── agent/
    │   └── prompt.md             # Agent instructions
    ├── config/
    │   ├── ralph.config.json     # Your project config
    │   ├── ralph.config.example.json
    │   └── prd-template.json     # PRD template
    ├── docs/
    │   └── story-patterns.md     # Story writing guide
    ├── skill/
    │   ├── SKILL.md              # This file
    │   └── ralph-manager.md      # Setup/management agent
    ├── tui/
    │   ├── main.py               # TUI entry point
    │   └── requirements.txt      # Python dependencies
    └── runtime/                   # Per-feature files
        ├── prd.json              # Current PRD (generated)
        └── progress.txt          # Progress log (generated)

Checklist Before Running

  • .ralph/config/ralph.config.json exists and is configured
  • .ralph/runtime/prd.json has user stories
  • .ralph/runtime/progress.txt initialized
  • Stories are small (1 context window each)
  • Each story has explicit, testable criteria
  • Dependencies ordered by priority
  • Summary presented to user
  • User confirmed launch