---
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 `/derive-prd`, 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: /derive-prd
# 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 |
| `-p` | `--parallel` | Teams mode: Phase 0 (entities) sequential, then spawn parallel teammates per application/module |
</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, step FILE read once)
3. Execute first task (step-02, step FILE read once)
4. Commit + update progress (step-03, step FILE 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) with `-p` (parallel mode):**
1. Init: detect prd-*.json, parse `-p` flag (step-00)
2. **Phase 0 (Ralph sequential):**
   - Ralph generates ALL entities from ALL modules via `/apex --foundation`
   - Creates ONE migration with all entities
   - Commits: `chore(foundation): entities for all modules`
3. **Phase 1-N (Teams parallel):**
   ```
   Team Lead → TeamCreate("smartstack-{project}")
     Spawn teammates (1 per application OR 1 per module if app > 3 modules):
       - Task(subagent_type: "apex", name: "apex-hr")
       - Task(subagent_type: "apex", name: "apex-crm")
       - Task(subagent_type: "apex", name: "apex-pm")
     Each teammate generates:
       - Services + Controllers + Seed data + Frontend + Tests
       - NO entities (already done in Phase 0)
       - NO migrations (ModelSnapshot already complete)
     → Teammates work in parallel → Ralph collects results → TeamDelete
   ```
4. Report with per-module aggregation (step-05)

**Multi-module (2+ modules) WITHOUT `-p` (sequential mode — legacy):**
1. Init: detect prd-*.json, read dependency layers (step-00)
2. **IF dependency graph available:** Agent Teams (parallel, legacy)
   ```
   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) |
| `{section_split_mode}` | boolean | Section splitting active for current module (>4 entities + >1 section) |
| `{section_phases}` | SectionPhase[] | Phase execution plan (Phase 0: foundation, Phase 1..N: per-section) |
| `{parallel_mode}` | boolean | Teams mode enabled via `-p` flag. Ralph generates Phase 0 (entities) sequentially, then spawns parallel teammates. |
| `{team_name}` | string\|null | Team name for parallel mode (e.g., "smartstack-hr") |
| `{team_active}` | boolean | True after `TeamCreate`, false after `TeamDelete`. Used in step-04 section 3a to send `MODULE_COMPLETE` to team-lead instead of advancing the module queue locally. |
</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 |

> **"Read Once" rule:** Each **step file** (step-01 to step-04) is loaded only once at the start of the first iteration. From iteration 2 onward, `compact-loop.md` drives the loop inline — step files are NOT re-read. This reduces context consumption. **Exception:** prd.json is re-read every iteration (it changes); step files are not.

> **Distinction:** `/apex -d prd.json` is invoked every iteration (B2 of compact-loop) — that is normal and expected. "Read Once" applies only to the step instruction files, not to data files or apex delegations.

**Reference files (loaded conditionally):**
| File | Loaded when |
|------|-------------|
| `references/category-rules.md` | Step-01 and compact loop (category ordering and dependency rules) |
| `references/category-completeness.md` | Step-01 section 4b and step-04 section 1.7 (guardrail injection) |
| `references/compact-loop.md` | Step-04 section 5 (module loop with /apex delegation) |
| `references/init-resume-recovery.md` | Step-00 section 4 (resume mode and auto-recovery) |
| `references/multi-module-queue.md` | Step-00 and step-01 section 0 (multi-module initialization) |
| `references/module-transition.md` | Step-04 section 3b (multi-module advancement) |
| `references/parallel-execution.md` | Step-02 section 3a (Agent Teams for multi-module) |
| `references/section-splitting.md` | Step-01 section 4c when module has >4 entities + >1 section |
| `references/task-transform-legacy.md` | Step-01 (legacy FORMAT A PRD transformation) |
| `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)
├── prd-{module}-phase0.json         # Section split: Foundation (domain+infra+migration)
├── prd-{module}-section-{code}.json # Section split: Per-section (app+api+seed+frontend+tests)
├── 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>
