---
name: step-02-execute
description: Delegate module execution to /apex
next_step: steps/step-03-commit.md
---

# Step 2: Delegate to /apex

> **CONTEXT OPTIMIZATION:** Read ONCE (first iteration). Subsequent iterations use compact-loop.md.

## YOUR TASK:

Delegate the current module's tasks to `/apex -d` for code generation. Ralph handles orchestration only.

**ULTRA THINK about the delegation context.**

---

## EXECUTION RULES:

1. **VERIFY DEPENDENCIES** — All task dependencies must be completed
2. **DELEGATE TO /apex** — All code generation via `/apex -d`
3. **TRACK RESULTS** — Verify PRD state after apex returns
4. **NEVER GENERATE CODE** — Ralph orchestrates, apex generates

---

## EXECUTION SEQUENCE:

### 1. Verify Dependencies

```javascript
// PRD PATH RESOLUTION
const queuePath = '.ralph/modules-queue.json';
let currentPrdPath = '.ralph/prd.json';
if (fileExists(queuePath)) {
  const queue = readJSON(queuePath);
  currentPrdPath = queue.modules[queue.currentIndex].prdFile;
}

const prd = readJSON(currentPrdPath);
const task = prd.tasks.find(t => t.id === {current_task_id});
for (const depId of task.dependencies) {
  const dep = prd.tasks.find(t => t.id === depId);
  if (!dep || dep.status !== 'completed') {
    task.status = 'blocked'; task.error = `Dependency ${depId} not completed`;
    writeJSON(currentPrdPath, prd);
    STOP — return to step-01
  }
}
```

### 2. Mark In-Progress

```javascript
task.status = 'in_progress';
task.started_at = new Date().toISOString();
writeJSON(currentPrdPath, prd);
```

### 3. Delegate to /apex

#### 3a. Parallel Mode (if `-p` flag)

See `references/parallel-execution.md` for complete parallel protocol:

**IF `{parallel_mode}` == true:**

1. Phase 0 (Ralph sequential): Generate ALL entities from ALL modules + ONE migration
2. Phase 1-N (Teams parallel): Spawn teammates per application/module for services/controllers/frontend/tests
3. Collect results from teammates
4. Cleanup team, proceed to step-03

**ELSE (not parallel mode):**

Continue with section-split mode or standard mode below.

#### 3a+. State Persistence (before delegation)

```javascript
// Write state BEFORE delegating to apex so position survives context compression
writeJSON('.ralph/ralph-state.json', {
  currentStep: 'step-02-execute',
  nextStep: 'step-03-commit',
  currentModule: {current_module},
  phase: 'apex-delegating',
  timestamp: new Date().toISOString()
});
```

#### 3b. Section-Split Mode

```javascript
if (prd._sectionSplit?.enabled) {
  // Find next pending phase with dependencies met
  const nextPhase = prd._sectionSplit.phases.find(p => p.status === 'pending');

  if (!nextPhase) {
    // All phases done — skip to step-04 completion check
    goto STEP_04;
  }

  const depsOk = nextPhase.dependsOn.every(depIdx =>
    prd._sectionSplit.phases[depIdx].status === 'completed'
  );

  if (!depsOk) {
    console.warn(`Phase ${nextPhase.phase} blocked — dependencies incomplete`);
    goto STEP_04;
  }

  const phaseLabel = nextPhase.type === 'foundation'
    ? 'Phase 0: Foundation (all entities + migration + module seed data)'
    : `Phase ${nextPhase.phase}: Section "${nextPhase.sectionCode}" (services + controllers + pages + tests)`;
  console.log(`SECTION SPLIT: ${phaseLabel}`);

  // ↓ MANDATORY: invoke apex now (not pseudo-code — execute this skill call)
```

**INVOKE `/apex -d {nextPhase.prdFile}`**

Apex sees a focused (smaller) PRD covering only this phase's scope and executes normally.
After apex returns: merge results into master PRD.
Read `references/section-splitting.md` sections 7-9 for execution, merging, and failure handling.

```javascript

  nextPhase.status = 'completed';
  prd._sectionSplit.currentPhase = nextPhase.phase;
  writeJSON(currentPrdPath, prd);

  // Continue to step-03 (commit), then step-04 loops back for next phase
}
```

> See `references/section-splitting.md` for full detection, mapping, PRD construction, and merge logic.

#### 3c. Standard Mode (no split, no parallel)

**INVOKE `/apex -d {currentPrdPath}`**

This delegates ALL remaining tasks for the current module to apex:

- Apex reads the PRD, extracts context (`app_name`, `module_code`, `entities`, `sections`)
- Apex executes ALL layers: domain → infrastructure → migration → application → api → seed data → frontend → tests
- Apex runs full POST-CHECKs (50 checks from `references/post-checks.md`)
- Apex commits per layer (atomic commits)
- Apex validates with MCP (`validate_conventions`)
- Apex updates task statuses in the PRD file directly

> **FLAGS:** `-d` implies `-a` (auto, no user confirmation) and `-e` (economy, no nested teams).
> Ralph manages parallelism via team orchestration, not apex.

### 4. Verify Post-Apex Results

```javascript
// Re-read PRD after apex execution
const updatedPrd = readJSON(currentPrdPath);
const moduleTasks = updatedPrd.tasks.filter(t => t.module === {current_module});

const completed = moduleTasks.filter(t => t.status === 'completed').length;
const failed = moduleTasks.filter(t => t.status === 'failed').length;
const pending = moduleTasks.filter(t => t.status === 'pending').length;

if (failed > 0) {
  console.log(`WARNING: ${failed} tasks failed during apex execution`);
  // Failed tasks will be retried in compact loop
}

if (pending > 0) {
  console.log(`INFO: ${pending} tasks still pending — will be handled in compact loop`);
}

console.log(`Apex completed: ${completed}/${moduleTasks.length} tasks`);
```

### 5. Update Progress

```javascript
// Append to progress file
const progressEntry = `
[Iteration ${prd.config.current_iteration}] Delegated to /apex
  Module: ${prd.project.module}
  Completed: ${completed}/${moduleTasks.length}
  Failed: ${failed}
  Pending: ${pending}
`;
appendFile('.ralph/progress.txt', progressEntry);
```

---

## CONSTRAINTS:

- **DO:** Delegate to apex, verify results, maintain PRD state
- **DON'T:** Generate code directly, run inline POST-CHECKs, invoke MCP tools for generation
- **DON'T:** Stop to ask the user anything — fully autonomous

---

## NEXT STEP:

Proceed to `./step-03-commit.md`
