---
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`
- CONTEXT BUDGET: Keep output COMPACT
- **NEVER DELEGATE** the main Ralph loop to a sub-agent (single module)
- **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
  current_iteration: 1

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
  Remainder → {task_description}
```

## 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)

> **CRITICAL:** Ralph-loop is FULLY AUTONOMOUS by default.
> It executes ALL tasks from start to finish WITHOUT stopping.
> The user launched `/ralph-loop` — this IS the instruction to execute everything.

**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** stop after the first task to "check quality".

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

```javascript
// NO user prompt. NO mode selection. JUST EXECUTE.
// max_iterations is already set from flags (default: 50).
// If user wants fewer iterations, they use -m N explicitly.
console.log(`Mode: AUTONOMOUS | Max iterations: ${max_iterations}`);
```

### Speed Warning (informational only — does NOT block)

If tests are slow (>30s detected in previous logs), display a one-line warning but **continue execution**:
```
⚠ Slow tests detected. Consider disabling E2E during ralph-loop.
```

## 4. Resume Mode

If `{resume_mode} = true`:

1. Check `.ralph/prd.json` exists → error if not
2. Detect format:
   - `$version === "3.0.0"` → **v3 unified** (native, preferred)
   - `$version === "2.0.0"` → **v2 legacy** (OK, continue)
   - `.project && .requirements && !.$version` → **FORMAT A (DEPRECATED)** — warn and transform via step-01
   - Other → error
3. Check branch consistency: current branch vs `prd.metadata.branch`
4. Restore state: `current_iteration`, `completion_promise`, `max_iterations`
5. If `modules-queue.json` exists: restore multi-module state
6. Continue to step-01

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

```bash
mkdir -p .ralph/logs .ralph/reports
```

### 4a. Auto-Recovery: BA Artifacts Without PRD

If no PRD files exist (neither `prd-*.json` nor `prd.json`):

```javascript
const masterFeature = findFile('docs/business/**/business-analyse/**/feature.json');
if (masterFeature) {
  const master = readJSON(masterFeature);
  if (master.status === 'handed-off' || master.handoff?.status === 'handed-off') {
    console.log('BA artifacts detected without PRD — auto-recovering...');
    exec(`ss derive-prd --application ${masterFeature}`);
    const newPrds = glob('.ralph/prd-*.json');
    if (newPrds.length === 0) { console.log('ss derive-prd failed'); STOP; }
    console.log(`Auto-recovered ${newPrds.length} PRD files`);
  }
}
```

### 4b. Detect Multi-Module PRDs

```javascript
const prdFiles = glob('.ralph/prd-*.json');
const PRD_COUNT = prdFiles.length;

if (PRD_COUNT > 0) {
  // Build module queue (from master feature.json order or alphabetical)
  const modules = [];
  const masterFeature = findFile('docs/business/**/business-analyse/**/feature.json');
  if (masterFeature) {
    const master = readJSON(masterFeature);
    const moduleOrder = master.metadata?.workflow?.moduleOrder || [];
    for (const mod of moduleOrder) {
      if (fileExists(`.ralph/prd-${mod.code}.json`)) {
        modules.push({ code: mod.code, prdFile: `.ralph/prd-${mod.code}.json`, status: 'pending' });
      }
    }
  }
  // Fallback: alphabetical
  if (modules.length === 0) {
    for (const file of prdFiles) {
      const code = file.match(/prd-(.+)\.json$/)[1];
      modules.push({ code, prdFile: `.ralph/${file}`, status: 'pending' });
    }
  }

  // Create modules-queue.json
  modules[0].status = 'in-progress';
  const queue = { modules, currentIndex: 0, totalModules: modules.length, completedModules: 0 };
  writeJSON('.ralph/modules-queue.json', queue);
  console.log(`Multi-module: ${modules.length} modules → ${modules.map(m => m.code).join(' → ')}`);

  {modules_queue} = queue;
  {current_module} = modules[0].code;
}
```

### 4c. Team Orchestration (multi-module, 2+ modules)

```javascript
if (PRD_COUNT > 1) {
  // Read references/team-orchestration.md for full protocol
  // Detect dependency layers from master feature.json
  const layers = master.metadata?.workflow?.dependencyGraph?.layers;

  if (layers) {
    // PARALLEL MODE: Use Agent Teams
    TeamCreate({ team_name: `ralph-${appName}` });

    // For each layer, spawn teammates in parallel
    // Layer 0: foundation modules (spawn, wait for LAYER_READY)
    // Layer 1+: dependent modules (spawn after previous layer completes)
    // See references/team-orchestration.md for teammate prompt template

    // After all layers: cross-module verify → step-05 → TeamDelete
    // STOP here — team orchestration takes over
    return;
  }
  // If no layers: fall through to sequential mode (classic compact loop)
}
```

## 5. Completion Promise (auto-set)

```javascript
// Auto-set if not provided — NEVER ask the user
if (!completion_promise) {
  completion_promise = "COMPLETE";
}
// The promise is output ONLY when ALL tasks are done. No user interaction needed.
```

## 6. Collect Metadata

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

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

## 7. Show Summary

```
RALPH LOOP INITIALIZED
Task: {task_description} | Max: {max_iterations} | Promise: {completion_promise}
MCP: Ready | Branch: {branch} | Schema: v3.0.0
{modules_queue ? `Modules: ${totalModules} (${module_codes.join(' → ')})` : 'Mode: single module'}
-> Loading tasks...
```

**Proceed directly to step-01-task.md**
