---
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 RULES:

- **FULLY AUTONOMOUS** — execute ALL tasks without stopping or asking the user
- NEVER skip MCP verification
- ALWAYS parse ALL flags before any action
- ONLY check resume if -r flag is set
- **NEVER ask the user** to choose a mode, confirm execution, or select options
- **NEVER set max_iterations = 1** — unless the user explicitly passed `-m 1`
- **Multi-module (2+ modules):** Use Agent Teams for parallel execution

## YOUR TASK:

Initialize the Ralph loop: parse flags, verify MCP, setup environment, detect multi-module.

---

## 1. Parse Flags

```yaml
Defaults:
  max_iterations: 50
  completion_promise: null
  verbose_mode: false
  resume_mode: false
  parallel_mode: false

Flags:
  -m N / --max-iterations N → {max_iterations} = N
  -c TEXT / --completion-promise TEXT → {completion_promise} = TEXT
  -v / --verbose → {verbose_mode} = true
  -r / --resume → {resume_mode} = true
  -p / --parallel → {parallel_mode} = true
  Remainder → {task_description}
```

**If `-p`:** set parallel_mode = true. Ralph executes Phase 0 (entities) sequentially, then spawns parallel teammates.

## 2. Verify MCP (MANDATORY)

```
mcp__smartstack__validate_conventions: checks: ["all"] → {mcp_smartstack} = true/false
mcp__context7__resolve-library-id: libraryName: "test" → {mcp_context7} = true/false
```

If ANY fails: show error, suggest `smartstack check-mcp`, STOP.

## 3. Execution Mode (FULLY AUTONOMOUS)

Ralph-loop is FULLY AUTONOMOUS by default. It executes ALL tasks from start to finish WITHOUT stopping.

**DO NOT** ask the user to confirm, choose a mode, or approve execution.
**DO NOT** set max_iterations = 1 or any reduced value.
**DO NOT** display a progress report and then ask "shall I continue?" or present numbered options.
**DO NOT** pause because the scope seems large — 500+ files across 11 modules is NORMAL. Execute ALL of it.

The loop runs autonomously until:
- ALL tasks are completed (success)
- max_iterations is reached (user set via `-m N`)
- Dead-end detected (all remaining blocked/failed)
- User Ctrl+C (external interrupt)

### Speed Warning (informational only)

If tests are slow (>30s in logs), display warning but **continue execution**:
```
⚠ Slow tests detected. Consider disabling E2E during business-analyse-develop.
```

## 4. Resume or Initialize

See `references/init-resume-recovery.md` for complete Resume Mode, Auto-Recovery, and Ralph State Recovery logic.

**Quick:**
- If `-r` flag: restore state from .ralph/prd.json + .ralph/ralph-state.json
- Else if `.ralph/ralph-state.json` exists: recover position (step, module, iteration) — see init-resume-recovery.md "Ralph State Recovery"
- Else if BA artifacts exist: auto-recover PRDs via `ss business-analyse-handoff`
- Else: fresh start

---

## 4b. Detect Multi-Module PRDs

See `references/multi-module-queue.md` for queue initialization.

Quick: `glob('.ralph/prd-*.json').length > 1` → create modules-queue.json

### 4b+. Normalize modules-queue.json (backward-compat with handoff v1 format)

```javascript
const queuePath = '.ralph/modules-queue.json';
if (fileExists(queuePath)) {
  const raw = readJSON(queuePath);
  let dirty = false;

  // RC1: Rename "queue" → "modules" property (handoff v1 used "queue")
  if (raw.queue && !raw.modules) {
    raw.modules = raw.queue;
    delete raw.queue;
    dirty = true;
  }

  // RC2: Rename "moduleCode" → "code" in each entry (handoff v1 used "moduleCode")
  for (const mod of (raw.modules || [])) {
    if (mod.moduleCode && !mod.code) {
      mod.code = mod.moduleCode;
      delete mod.moduleCode;
      dirty = true;
    }
  }

  // RC3: Add missing fields
  if (raw.currentIndex === undefined) { raw.currentIndex = 0; dirty = true; }
  if (raw.completedModules === undefined) { raw.completedModules = 0; dirty = true; }
  if (raw.totalModules === undefined) { raw.totalModules = raw.modules?.length || 0; dirty = true; }
  for (const mod of (raw.modules || [])) {
    if (!mod.prdFile) { mod.prdFile = `.ralph/prd-${mod.code}.json`; dirty = true; }
    if (!mod.status) { mod.status = 'pending'; dirty = true; }
  }
  // Set first module to in-progress if none started
  if (raw.modules?.length && !raw.modules.some(m => m.status !== 'pending')) {
    raw.modules[0].status = 'in-progress';
    dirty = true;
  }

  if (dirty) {
    writeJSON(queuePath, raw);
    console.log('modules-queue.json normalized (format v2)');
  }
}
```

---

## 4c. Team Orchestration (multi-module LEGACY — dependency layer mode only)

> **MANDATORY:** Load `references/team-orchestration.md` BEFORE creating any team.
> The full spawn protocol (teammate prompts, wait logic, layer coordination, cleanup)
> is defined there. Creating a team without loading it results in an empty team with no teammates.

> **PARALLEL MODE (`-p`):** Team creation does NOT happen here. It happens in step-02 section 3a,
> after step-01 loads the tasks. Sections 5-7 below (completion promise, metadata, summary) must
> still be executed. Do NOT return early when `{parallel_mode}` is true.

```javascript
if (PRD_COUNT > 1) {
  // STEP 1: Load references/team-orchestration.md NOW (before any TeamCreate call)
  // This file contains: mode selection, Phase 0 protocol (parallel), layer protocol (legacy), cleanup.

  const layers = master.metadata?.workflow?.dependencyGraph?.layers;

  if (layers && !{parallel_mode}) {
    // DEPENDENCY LAYER MODE (legacy, no -p flag): team orchestration takes over here.
    // TeamCreate + spawn logic are defined in references/team-orchestration.md section "Dependency Layer Mode".
    // STOP here — legacy team orchestration handles everything from this point.
    return;
  }
  // PARALLEL MODE (-p): fall through to sections 5-7, team created later in step-02 section 3a.
  // NO -p, NO layers: fall through to sequential mode (compact loop per module).
}
```

---

## 5. Completion Promise (auto-set)

```javascript
if (!completion_promise) {
  completion_promise = "COMPLETE";
}
// Output ONLY when ALL tasks done
```

## 6. Collect Metadata

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

```javascript
{metadata} = {
  cli_version: CLI_VERSION,
  branch: CURRENT_BRANCH,
  project_path: PROJECT_PATH,
  mcp_servers: { smartstack: {mcp_smartstack}, context7: {mcp_context7} }
}
```

## 6b. Detect PRD Version

```javascript
const prdFile = readJSON('.ralph/prd.json') || readJSON(glob('.ralph/prd-*.json')[0]);
const prd_version = prdFile?.$version || '3.0.0';

if (prd_version === '4.0.0') {
  // v4 spec-oriented: continuous execution, compaction manages context
  // → Load step-01-v4-execute.md instead of step-01-task.md
} else {
  // v3 task-oriented: batch iterations, compact-loop
  // → Load step-01-task.md (legacy)
}
```

## 7. Show Summary

```
RALPH LOOP INITIALIZED
Task: {task_description} | Max: {max_iterations} | Promise: {completion_promise}
MCP: Ready | Branch: {branch} | PRD: v{prd_version}
{modules_queue ? `Modules: ${totalModules} (${module_codes.join(' → ')})` : 'Mode: single module'}
{prd_version === '4.0.0' ? '→ v4 continuous mode (compaction-enabled)' : '→ v3 batch mode (compact-loop)'}
-> Loading spec...
```

### 7b. Initialize State File (context compression defense)

> **ralph-state.json is written here AND updated by step-02, compact-loop, and module-transition.**
> On resume or after context compression, `init-resume-recovery.md` reads it back to route
> to the correct step instead of always restarting from step-01.

```javascript
writeJSON('.ralph/ralph-state.json', {
  currentStep: 'step-01-task',
  currentModule: {current_module},
  iteration: 1,
  prdVersion: {prd_version},
  modulesQueuePath: fileExists('.ralph/modules-queue.json') ? '.ralph/modules-queue.json' : null,
  timestamp: new Date().toISOString()
});
```

**Step routing:** If ralph-state recovery (section 4) provided a different target step, load THAT step.
Otherwise, proceed to step-01-task.md.
