---
name: step-00-init
description: Initialize Ralph loop - parse args, verify MCP, setup state
next_step: steps/step-01-task.md
---

# Step 0: Initialization

## MANDATORY EXECUTION RULES:

- NEVER skip MCP verification
- ALWAYS parse ALL flags before any other action
- ONLY check for resume if -r flag is set
- YOU ARE AN INITIALIZER, not an executor
- FORBIDDEN to load step-01 until init is complete
- ALWAYS check prd.json version is v2

## YOUR TASK:

Initialize the Ralph loop by parsing flags, verifying MCP availability, setting up the execution environment, and validating integrity on resume.

---

<defaults>
## Default Configuration

```yaml
max_iterations: 50
completion_promise: null
verbose_mode: false
resume_mode: false
current_iteration: 1
```
</defaults>

---

## EXECUTION SEQUENCE:

### 1. Parse Flags and Input

**Step 1: Load defaults from config above**

```
{max_iterations}     = 50
{completion_promise} = null
{verbose_mode}       = false
{resume_mode}        = false
{current_iteration}  = 1
```

**Step 2: Parse user input and override defaults:**

```
Flags:
  -m N or --max-iterations N     -> {max_iterations} = N
  -c TEXT or --completion-promise TEXT -> {completion_promise} = TEXT
  -v or --verbose                -> {verbose_mode} = true
  -r or --resume                 -> {resume_mode} = true

Remainder -> {task_description}
```

### 2. Verify MCP Servers (MANDATORY)

**CRITICAL: Do NOT proceed without MCP verification!**

**Check SmartStack MCP:**
```
mcp__smartstack__validate_conventions:
  checks: ["all"]
  (just to verify connectivity)
```

**Check Context7 MCP:**
```
mcp__context7__resolve-library-id:
  libraryName: "test"
  query: "connectivity check"
  (just to verify connectivity)
```

**Record MCP status for metadata:**
```
{mcp_smartstack} = true/false
{mcp_context7}   = true/false
```

**If ANY MCP fails:**
```
╔══════════════════════════════════════════════════════════════════╗
║  ❌ MCP SERVER UNAVAILABLE                                      ║
╠══════════════════════════════════════════════════════════════════╣
║  Server: {failed_server}                                        ║
║  Status: Connection failed                                      ║
╠══════════════════════════════════════════════════════════════════╣
║  RALPH CANNOT PROCEED WITHOUT MCP                               ║
║                                                                  ║
║  Troubleshooting:                                                ║
║  1. Run: smartstack check-mcp                                    ║
║  2. Restart Claude Code                                          ║
║  3. Check MCP server configuration                               ║
╚══════════════════════════════════════════════════════════════════╝

STOP - Do not proceed.
```

### 3. Check Resume Mode

**If {resume_mode} = true:**

1. Check for existing `.ralph/prd.json`
2. If not found:
   - Error: "No active Ralph loop to resume"
   - Ask user to start new loop
   - STOP

3. If found, **validate schema version:**

```javascript
const prd = readJSON('.ralph/prd.json');

if (prd.$version !== "2.0.0") {
  echo "❌ prd.json schema version unsupported: ${prd.$version || 'missing'}";
  echo "   Expected: 2.0.0";
  echo "   Re-run /business-analyse to generate a fresh prd.json";
  STOP;
}
```

4. **Validate integrity (v2 resume):**

```bash
# Check branch consistency
CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)
PRD_BRANCH={prd.metadata.branch}

if [ "$CURRENT_BRANCH" != "$PRD_BRANCH" ]; then
  echo "⚠️ Branch mismatch: prd.json was created on '$PRD_BRANCH', now on '$CURRENT_BRANCH'"
  # Ask user: continue on current branch or switch
  AskUserQuestion:
    header: "Branch"
    question: "prd.json was created on '$PRD_BRANCH' but you're on '$CURRENT_BRANCH'. Continue?"
    options:
      - label: "Continue on $CURRENT_BRANCH"
        description: "Update metadata and continue"
      - label: "Cancel"
        description: "Switch branch manually first"
fi

# Check for external commits since last update
LAST_UPDATED={prd.updated_at}
EXTERNAL_COMMITS=$(git log --since="$LAST_UPDATED" --oneline --not --author="Co-Authored-By: Claude" | wc -l)

if [ "$EXTERNAL_COMMITS" -gt 0 ]; then
  echo "⚠️ $EXTERNAL_COMMITS external commits detected since last Ralph iteration"
  echo "   prd.json state may not reflect current code state"
fi
```

5. **Restore state from prd.json:**
   - Read `prd.config.current_iteration` → `{current_iteration}`
   - Read `prd.config.completion_promise` → `{completion_promise}`
   - Read `prd.config.max_iterations` → `{max_iterations}`
   - Read progress.txt for context

6. **Restore multi-module state (if applicable):**
   ```javascript
   if (fileExists('.ralph/modules-queue.json')) {
     const queue = readJSON('.ralph/modules-queue.json');
     const currentModule = queue.modules[queue.currentIndex];

     // Restore module state
     {modules_queue} = queue;
     {current_module} = currentModule.code;

     console.log(`Resuming multi-module: ${currentModule.code} (${queue.currentIndex + 1}/${queue.totalModules})`);
     console.log(`Modules completed: ${queue.completedModules}/${queue.totalModules}`);
   }
   ```

   - Continue to step-01

### 4. Initialize .ralph/ Structure (new loop)

**Create directory structure:**

```
.ralph/
├── prd.json          # Will be created in step-01
├── progress.txt      # Will be created in step-01
├── logs/
└── reports/
```

**Commands:**
```bash
mkdir -p .ralph/logs
mkdir -p .ralph/reports
```

### 4b. Detect Multi-Module PRDs (from BA Handoff)

**After creating `.ralph/` directory, check for per-module PRD files:**

```bash
# Count prd-*.json files (generated by BA handoff via ss derive-prd)
PRD_FILES=$(ls .ralph/prd-*.json 2>/dev/null)
PRD_COUNT=$(echo "$PRD_FILES" | grep -c "prd-" 2>/dev/null || echo "0")
```

**If multiple prd-*.json files found (PRD_COUNT > 0):**

1. **Read module order from master feature.json (if available):**
```bash
# Look for master feature.json that references modules
MASTER_FEATURE=$(find docs/business -maxdepth 4 -name "feature.json" -path "*/business-analyse/*" | head -1)
```

2. **Build module queue:**
```javascript
const modules = [];

if (MASTER_FEATURE && masterJson.metadata?.workflow?.moduleOrder) {
  // Use order from BA master feature.json
  for (const mod of masterJson.metadata.workflow.moduleOrder) {
    const prdFile = `.ralph/prd-${mod.code}.json`;
    if (fileExists(prdFile)) {
      modules.push({ code: mod.code, prdFile, status: "pending" });
    }
  }
} else {
  // Fallback: alphabetical order from prd-*.json filenames
  for (const file of prdFiles) {
    const code = file.match(/prd-(.+)\.json$/)[1];
    modules.push({ code, prdFile: `.ralph/${file}`, status: "pending" });
  }
}
```

3. **Create modules-queue.json:**
```json
{
  "modules": [
    { "code": "mod1", "prdFile": ".ralph/prd-mod1.json", "status": "pending" },
    { "code": "mod2", "prdFile": ".ralph/prd-mod2.json", "status": "pending" }
  ],
  "currentIndex": 0,
  "totalModules": 2,
  "completedModules": 0
}
```

4. **Set first module as active:**
```javascript
modules[0].status = "in-progress";
```

5. **Log detection:**
```
Multi-module detected: {PRD_COUNT} modules
Queue: {module codes joined by " → "}
Starting with: {modules[0].code}
```

**If only `.ralph/prd.json` exists (single module):**
- Skip queue creation (backward compatible)
- Proceed normally

**Store:**
```
{modules_queue} = queue object or null
{current_module} = first module code or null
```

### 5. Validate Completion Promise

**If {completion_promise} is null:**

```yaml
AskUserQuestion:
  header: "Promise"
  question: "What text should signal completion?"
  options:
    - label: "COMPLETE"
      description: "Standard completion signal"
    - label: "ALL TESTS PASS"
      description: "For test-focused tasks"
    - label: "DONE"
      description: "Simple completion"
    - label: "Custom..."
      description: "Specify custom text"
```

### 6. Collect Metadata

**Gather execution context:**

```bash
CLI_VERSION=$(node -e "console.log(require('package.json').version)" 2>/dev/null || echo "unknown")
CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)
PROJECT_PATH=$(pwd)
```

**Store metadata for prd.json creation (step-01):**
```
{metadata} = {
  cli_version: CLI_VERSION,
  branch: CURRENT_BRANCH,
  project_path: PROJECT_PATH,
  mcp_servers: { smartstack: {mcp_smartstack}, context7: {mcp_context7} }
}
```

### 7. Log Initialization

**If {verbose_mode} = true:**

Write to `.ralph/logs/{timestamp}.log`:
```
[{timestamp}] RALPH LOOP INITIALIZED
Task: {task_description}
Max iterations: {max_iterations}
Completion promise: {completion_promise}
MCP Status: SmartStack {mcp_smartstack ? "✅" : "❌"}, Context7 {mcp_context7 ? "✅" : "❌"}
Schema: v2.0.0
Branch: {CURRENT_BRANCH}
```

### 8. Show Summary and Proceed

**Always show COMPACT summary:**

```
╔══════════════════════════════════════════════════════════════════╗
║  RALPH LOOP INITIALIZED                                         ║
╠══════════════════════════════════════════════════════════════════╣
║  Task: {task_description}                                       ║
║  Max iterations: {max_iterations}                               ║
║  Completion: <promise>{completion_promise}</promise>             ║
║  MCP: ✅ Ready                                                  ║
║  Schema: v2.0.0                                                 ║
║  Branch: {CURRENT_BRANCH}                                       ║
║  {modules_queue ? "Modules: " + totalModules + " (" + module_codes.join(" → ") + ")" : "Mode: single module"} ║
╠══════════════════════════════════════════════════════════════════╣
║  Files:                                                          ║
║  - .ralph/prd.json (tasks)                                       ║
║  - .ralph/progress.txt (memory)                                  ║
║  {modules_queue ? "- .ralph/modules-queue.json (module tracking)" : ""} ║
╚══════════════════════════════════════════════════════════════════╝

-> Loading tasks...
```

**Then proceed directly to step-01-task.md**

---

## SUCCESS METRICS:

- All flags correctly parsed
- MCP servers verified and available
- .ralph/ directory structure created
- Completion promise defined
- Metadata collected (branch, version, MCP status)
- prd.json v2 schema validated (if resume)
- Branch integrity validated (if resume)
- Multi-module prd files detected and modules-queue.json created (if applicable)
- Output is COMPACT
- Proceeded to step-01 immediately after summary

## NEXT STEP:

After showing initialization summary, always proceed directly to `./step-01-task.md`
