---
name: ralph-loop
description: Iterative AI development loop with MCP validation, progress tracking, and completion promises.
argument-hint: "[-m N] [-c TEXT] [-v] <task description>"
disable-model-invocation: true
---

<objective>
Execute the Ralph Weegund technique - an iterative development methodology where the same prompt is fed repeatedly until completion. Uses progressive step loading with MCP validation and progress persistence.
</objective>

<quick_start>
**Basic usage:**

```bash
/ralph-loop implement user authentication
```

**With completion promise:**

```bash
/ralph-loop -c "COMPLETE" refactor the cache layer
```

**With max iterations:**

```bash
/ralph-loop -m 20 -c "TESTS PASS" add comprehensive tests
```

**Verbose mode:**

```bash
/ralph-loop -v -c "DONE" fix all linting errors
```

**Flags:**

- `-m N` (max): Maximum iterations before auto-stop
- `-c TEXT` (complete): Completion promise text
- `-v` (verbose): Detailed logging

See `<parameters>` for complete flag list.
</quick_start>

<parameters>

<flags>
**Flags:**
| Short | Long | Description |
|-------|------|-------------|
| `-m N` | `--max-iterations N` | Maximum iterations (default: 50) |
| `-c TEXT` | `--completion-promise TEXT` | Text that signals completion |
| `-v` | `--verbose` | Enable detailed logging |
| `-r` | `--resume` | Resume from previous state |
</flags>

<examples>
```bash
# Basic loop
/ralph-loop implement feature X

# With completion signal
/ralph-loop -c "ALL TESTS PASS" fix failing tests

# Limited iterations with completion
/ralph-loop -m 10 -c "REFACTOR COMPLETE" clean up auth module

# Resume previous loop
/ralph-loop -r

# Verbose mode
/ralph-loop -v -m 25 -c "DONE" implement CRUD for products
```
</examples>

<parsing_rules>
**Argument parsing:**

1. `-m N` or `--max-iterations N` -> `{max_iterations}` = N
2. `-c TEXT` or `--completion-promise TEXT` -> `{completion_promise}` = TEXT
3. `-v` or `--verbose` -> `{verbose_mode}` = true
4. `-r` or `--resume` -> `{resume_mode}` = true
5. Remainder -> `{task_description}`
</parsing_rules>

</parameters>

<ralph_concept>
**Core concept:**

The same prompt is fed to Claude repeatedly. The "self-referential" aspect comes from Claude seeing its own previous work in files and git history.

**Each iteration:**
1. Claude receives the SAME prompt
2. Works on the task, modifying files
3. Checks completion criteria
4. If not complete: saves progress, iteration count increments
5. Claude sees previous work in the files
6. Iteratively improves until completion promise is output

**Completion signal:**
```
<promise>{completion_promise}</promise>
```

The loop only stops when this exact tag is output or max iterations reached.
</ralph_concept>

<workflow>
**Standard flow (single module):**
1. Parse flags and task description
2. Verify MCP servers are available (MANDATORY)
3. Initialize .ralph/ structure and state files
4. Load current task from prd.json (or create initial task breakdown with categories, dependencies, and acceptance criteria)
5. Execute ONE task per iteration
6. Commit changes, update progress
7. Check completion criteria
8. If complete: generate final report

**Multi-module flow (from BA handoff):**
1-3. Same as standard flow
4. Detect `prd-*.json` files → create `modules-queue.json`
5. Copy current module's prd to `prd.json`
6. Execute all tasks for current module (standard loop: steps 01→02→03→04)
7. When module complete: advance to next module in queue
8. Repeat steps 5-7 for each module
9. When all modules done: generate cross-module report
</workflow>

<state_variables>
**Persist throughout all steps:**

| Variable | Type | Description |
|----------|------|-------------|
| `{task_description}` | string | The prompt/task to execute |
| `{max_iterations}` | number | Maximum iterations allowed |
| `{completion_promise}` | string | Text that signals completion |
| `{verbose_mode}` | boolean | Enable detailed logging |
| `{resume_mode}` | boolean | Resume from previous state |
| `{current_iteration}` | number | Current iteration count |
| `{tasks_completed}` | number | Number of tasks completed |
| `{tasks_total}` | number | Total tasks in prd.json |
| `{task_status}` | string | Current task status (pending/in_progress/completed/failed/skipped/blocked) |
| `{task_category}` | string | Task category (domain/application/infrastructure/api/frontend/i18n/test/validation) |
| `{files_created}` | string[] | Files created during current task |
| `{files_modified}` | string[] | Files modified during current task |
| `{current_module}` | string\|null | Current module code (multi-module only) |
| `{modules_queue}` | object\|null | Module queue state (multi-module only) |

</state_variables>

<mcp_requirements>
**MANDATORY MCP Validation:**

Before ANY work, verify MCP servers:

1. **SmartStack MCP** - `mcp__smartstack__validate_conventions`
2. **Context7 MCP** - `mcp__plugin_context7_context7__resolve-library-id`

**If ANY MCP unavailable:**
- DO NOT proceed
- Log failure to `.ralph/logs/`
- Output error message
- Suggest: `smartstack check-mcp`

**Throughout work, use:**
- `mcp__smartstack__validate_conventions` - Before commits
- `mcp__smartstack__check_migrations` - Before EF Core changes
- `mcp__smartstack__scaffold_extension` - For code generation
</mcp_requirements>

<entry_point>

**FIRST ACTION:** Load `steps/step-00-init.md`

</entry_point>

<step_files>
**Progressive loading - only load current step:**

| Step | File | Purpose |
|------|------|---------|
| 00 | `steps/step-00-init.md` | Parse args, verify MCP, initialize state |
| 01 | `steps/step-01-task.md` | Load current task from prd.json |
| 02 | `steps/step-02-execute.md` | Execute ONE task |
| 03 | `steps/step-03-commit.md` | Commit, update prd.json/progress.txt |
| 04 | `steps/step-04-check.md` | Check completion, decide next action |
| 05 | `steps/step-05-report.md` | Generate final report |

</step_files>

<file_structure>
**Ralph creates these files:**

```
.ralph/
├── prd.json              # Task list with status (current module or single)
├── progress.txt          # Persistent memory between iterations
├── modules-queue.json    # Multi-module tracking (only if multiple prd-*.json exist)
├── prd-{module1}.json    # Per-module PRD from BA handoff (source, not modified)
├── prd-{module2}.json    # Per-module PRD from BA handoff (source, not modified)
├── logs/
│   └── {timestamp}.log
└── reports/
    └── {feature-name}.md
```

**modules-queue.json structure (multi-module only):**
```json
{
  "modules": [
    {
      "code": "module-code",
      "prdFile": ".ralph/prd-module-code.json",
      "status": "pending|in-progress|completed|failed|partial"
    }
  ],
  "currentIndex": 0,
  "totalModules": 3,
  "completedModules": 0
}
```

**prd.json structure:**
```json
{
  "$version": "2.0.0",
  "feature": "{task_description}",
  "status": "in_progress",
  "created": "2026-01-30T15:00:00.000Z",
  "updated_at": "2026-01-30T16:30:00.000Z",
  "metadata": {
    "cli_version": "1.36.0",
    "branch": "feature/user-auth",
    "project_path": "/path/to/project",
    "mcp_servers": { "smartstack": true, "context7": true }
  },
  "config": {
    "max_iterations": 50,
    "completion_promise": "COMPLETE",
    "current_iteration": 1
  },
  "source": {
    "type": "ba-handoff",
    "handoff_path": "path/to/4-development-handoff.md",
    "feature_json_path": null
  },
  "tasks": [
    {
      "id": 1,
      "description": "Create User entity in Domain layer",
      "status": "pending",
      "category": "domain",
      "dependencies": [],
      "acceptance_criteria": "Entity compiles, properties match handoff spec",
      "started_at": null,
      "completed_at": null,
      "iteration": null,
      "commit_hash": null,
      "files_changed": { "created": [], "modified": [] },
      "validation": null,
      "error": null
    }
  ],
  "history": []
}
```

> **Schema v2 notes:**
> - `$version`: Schema version for forward migration
> - `status` (top-level): `pending` | `in_progress` | `completed` | `failed` | `partial`
> - `source.type`: `ba-handoff` | `direct` | `feature-full` — `null` when tasks are created directly by Ralph Loop
> - `task.status`: `pending` | `in_progress` | `completed` | `failed` | `skipped` | `blocked`
> - `task.category`: `domain` | `application` | `infrastructure` | `api` | `frontend` | `i18n` | `test` | `validation` | `other`
> - `task.dependencies`: Array of task IDs that must be `completed` before this task can start
> - `history`: Structured iteration journal (replaces unstructured progress.txt for traceability)
</file_structure>

<execution_rules>

- **Load one step at a time** - Only load the current step file
- **VERIFY MCP FIRST** - Never skip MCP validation
- **ONE TASK PER ITERATION** - Don't batch tasks
- **COMMIT AFTER EACH TASK** - Atomic progress
- **UPDATE progress.txt** - Persist learnings
- **NEVER fake completion** - Only output promise when truly done
</execution_rules>

<success_criteria>

- All tasks in prd.json have `status: "completed"` (or `"skipped"`)
- No tasks with `status: "blocked"` remain
- MCP validations pass
- Git commits atomic per task with `commit_hash` tracked
- `history[]` contains entry for every completed task
- Completion promise output when genuinely complete
- Final report generated in `.ralph/reports/`
- `prd.json` top-level `status` set to `"completed"` or `"partial"`
- **Multi-module:** All modules in `modules-queue.json` processed sequentially
- **Multi-module:** Cross-module aggregation in final report
</success_criteria>

<available_commands>
**Related commands:**
- `/ralph-loop:cancel-ralph` - Cancel active loop
- `/ralph-loop:help` - Show documentation
</available_commands>
