---
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>"
---

<objective>
Execute the Ralph Weegund technique — iterative module orchestration. Ralph reads PRDs from `/business-analyse`, resolves task dependencies, and delegates all code generation to `/apex -d`. Uses progress persistence and Agent Teams for multi-module parallelization.

**Key principle:** Ralph ORCHESTRATES (task selection, module sequencing, PRD state, reporting). All code generation is delegated to `/apex`.
</objective>

<quick_start>

**From Business Analysis (RECOMMENDED):**
```bash
/business-analyse MyFeature
# Then: /ralph-loop -r
```

**Manual start:**
```bash
/ralph-loop implement user authentication
/ralph-loop -c "COMPLETE" -m 20 refactor cache layer
/ralph-loop -r  # Resume previous
```

**Flags:** `-m N` (max iterations), `-c TEXT` (completion promise), `-v` (verbose), `-r` (resume)

</quick_start>

<parameters>
| Short | Long | Description |
|-------|------|-------------|
| `-m N` | `--max-iterations N` | Max iterations (default: 50) |
| `-c TEXT` | `--completion-promise TEXT` | Completion signal text |
| `-v` | `--verbose` | Detailed logging |
| `-r` | `--resume` | Resume from previous state |
</parameters>

<workflow>

**Single module:**
1. Init: parse flags, verify MCP, setup .ralph/ (step-00)
2. Load tasks from prd.json — unified v3 has pre-computed tasks (step-01, READ ONCE)
3. Execute first task (step-02, READ ONCE)
4. Commit + update progress (step-03, READ ONCE)
5. Check completion → enter COMPACT LOOP (step-04)
6. **COMPACT LOOP** (step-04 → references/compact-loop.md):
   - Find eligible → batch by category (max 5) → execute → test → commit → loop
7. Report (step-05)

**Multi-module (2+ modules, from BA handoff):**
1. Init: detect prd-*.json, read dependency layers (step-00)
2. **IF dependency graph available:** Agent Teams (parallel)
   ```
   Team Lead → TeamCreate("ralph-{app}")
     Layer 0: Spawn "mod-employees" (foundation) → wait LAYER_READY
     Layer 1: Spawn "mod-timetracking" + "mod-leavemanagement" (parallel)
     Layer 2: Spawn "mod-reporting"
     → Cross-module verify → Report → TeamDelete
   ```
3. **IF no dependency graph:** Sequential (compact loop per module)
4. Report with per-module aggregation (step-05)

**Task execution cycle:**
```
LOAD → DELEGATE TO /apex -d → VERIFY PRD STATE → COMMIT PRD → NEXT MODULE
```

</workflow>

<state_variables>
| Variable | Type | Description |
|----------|------|-------------|
| `{task_description}` | string | The task to execute |
| `{max_iterations}` | number | Max iterations |
| `{completion_promise}` | string | Completion signal |
| `{current_iteration}` | number | Current iteration |
| `{current_module}` | string\|null | Current module (multi-module) |
| `{modules_queue}` | object\|null | Module queue (multi-module) |
</state_variables>

<mcp_requirements>
**MANDATORY before any work:**
1. `mcp__smartstack__validate_conventions` — verify connectivity
2. `mcp__context7__resolve-library-id` — verify connectivity

**During work:** All MCP tool calls are handled by `/apex` during delegation. Ralph only uses `validate_conventions` for initial connectivity check.
</mcp_requirements>

<execution_guarantee>

## EXECUTION GUARANTEE — READ THIS FIRST

**Ralph-loop executes ALL tasks from start to finish. No exceptions.**

When the user invokes `/ralph-loop`, they are giving you the instruction to:
1. Initialize the loop (step-00)
2. Load ALL tasks (step-01)
3. Execute the FIRST task (step-02)
4. Commit (step-03)
5. Enter the COMPACT LOOP (step-04 → compact-loop.md)
6. **Execute ALL remaining tasks autonomously** (compact loop repeats)
7. Generate the final report (step-05)

**You MUST NOT:**
- Stop after the first task to "ask for confirmation"
- Set `max_iterations = 1` or any reduced value
- Ask the user to choose between supervised/autonomous mode
- Ask the user to choose a completion promise
- Wait for user input between iterations
- Delegate the loop to sub-agents (except team mode and /apex delegation)

**The ONLY valid stop conditions are:**
- ALL tasks completed (→ step-05 report)
- `max_iterations` reached (user set via `-m N`)
- Dead-end (all remaining blocked/failed)
- User Ctrl+C

**If you stop for any other reason, you have VIOLATED this guarantee.**

</execution_guarantee>

<entry_point>
**FIRST ACTION:** Load `steps/step-00-init.md` — then execute ALL steps through to step-05 without stopping.
</entry_point>

<step_files>
| Step | File | Purpose | Target Lines |
|------|------|---------|-------------|
| 00 | `steps/step-00-init.md` | Parse args, verify MCP, init state, team setup | ~150 |
| 01 | `steps/step-01-task.md` | Load/create tasks from prd.json | ~365 |
| 02 | `steps/step-02-execute.md` | Delegate module to /apex -d | ~120 |
| 03 | `steps/step-03-commit.md` | Commit, update prd.json/progress.txt | ~135 |
| 04 | `steps/step-04-check.md` | Check completion, compact loop entry | ~185 |
| 05 | `steps/step-05-report.md` | Generate final report | ~150 |

**Reference files (loaded conditionally):**
| File | Loaded when |
|------|-------------|
| `references/category-rules.md` | Step-01 and compact loop (category ordering and dependency rules) |
| `references/compact-loop.md` | Step-04 section 5 (module loop with /apex delegation) |
| `references/team-orchestration.md` | Step-00 when multi-module detected (2+ PRDs) |
</step_files>

<file_structure>
```
.ralph/
├── prd.json              # Active task list (unified v3: reference data + pre-computed tasks)
├── progress.txt          # Persistent memory
├── modules-queue.json    # Multi-module tracking (if applicable)
├── prd-{module}.json     # Per-module PRDs (from ss derive-prd, unified v3 format)
├── logs/
└── reports/
    └── {feature}.md
```
</file_structure>

<execution_rules>

### NON-NEGOTIABLE — Autonomous Full Execution
- **EXECUTE ALL TASKS** — from first to last, no user interaction, no pause, no confirmation
- **NEVER ask the user** — no mode selection, no completion promise choice, no "shall I continue?"
- **NEVER stop after first task** — the first task is just the beginning, NOT the end
- **NEVER set max_iterations = 1** — unless the user explicitly passed `-m 1`

### Loop Mechanics
- **Single module:** Main agent runs compact loop (NEVER delegate to sub-agent)
- **Multi-module (2+):** Team lead + module workers via TeamCreate (see references/team-orchestration.md)
- **Load step files ONCE** — after first iteration, use compact-loop.md
- **VERIFY MCP FIRST** — never skip
- **BATCH** same-category tasks (max 5 per iteration)
- **COMMIT** after each batch (not per task)
- **NEVER fake completion** — only output promise when truly done
- **NEVER stop the loop** — autonomous until complete, max iterations, or dead-end
- **CONTEXT BUDGET** — compact output during loop (1-2 lines per task)
- **MODULE COMPLETENESS** — all layers (domain, infra, app, api, frontend, test) before advancing
- **MIGRATION MANDATORY** — after EF configs, before tests (no DB = no tests)
- **TESTS BLOCKING** — 100% pass before proceeding to next task

</execution_rules>

<success_criteria>
- All tasks completed (or skipped) in prd.json
- MCP validations pass
- Git commits atomic with commit_hash tracked
- Tests pass (dotnet test + npm test)
- Migrations created and applied
- Seed data complete (navigation, permissions, roles via MCP)
- Frontend in correct hierarchy (Context/App/Module)
- Report generated in .ralph/reports/
- Multi-module: all modules processed, cross-module report
</success_criteria>

<available_commands>
- `/ralph-loop:cancel-ralph` — Cancel active loop
- `/ralph-loop:help` — Show documentation
</available_commands>
