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

### 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}                                       ║
╠══════════════════════════════════════════════════════════════════╣
║  Files:                                                          ║
║  - .ralph/prd.json (tasks)                                       ║
║  - .ralph/progress.txt (memory)                                  ║
╚══════════════════════════════════════════════════════════════════╝

-> 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)
- Output is COMPACT
- Proceeded to step-01 immediately after summary

## NEXT STEP:

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