---
name: step-05-report
description: Generate final report from prd.json structured data
next_step: null
---

# Step 5: Generate Report

## YOUR TASK:

Generate a comprehensive feature report using structured data from prd.json.

---

## 1. Load Data

```javascript
// PRD PATH RESOLUTION
const queuePath = '.ralph/modules-queue.json';
let currentPrdPath = '.ralph/prd.json';
if (fileExists(queuePath)) {
  const queue = readJSON(queuePath);
  // For report, use last module's PRD (or current if still in progress)
  const idx = Math.min(queue.currentIndex, queue.modules.length - 1);
  currentPrdPath = queue.modules[idx].prdFile;
}

const prd = readJSON(currentPrdPath);
const stats = {
  feature: prd.feature, status: prd.status,
  iterations_used: prd.config.current_iteration - 1,
  tasks: {
    total: prd.tasks.length,
    completed: prd.tasks.filter(t => t.status === 'completed').length,
    failed: prd.tasks.filter(t => t.status === 'failed').length,
    blocked: prd.tasks.filter(t => t.status === 'blocked').length
  }
};

// Aggregate files from all tasks (populated by apex during execution)
const filesCreated = [...new Set(prd.tasks.flatMap(t => t.files_changed?.created || []))];
const filesModified = [...new Set(prd.tasks.flatMap(t => t.files_changed?.modified || []))];
const totalDuration = prd.history.reduce((sum, h) => sum + (h.duration_seconds || 0), 0);
```

### 1b. Multi-Module Aggregation

```javascript
const queuePath = '.ralph/modules-queue.json';
let moduleStats = null;
if (fileExists(queuePath)) {
  const queue = readJSON(queuePath);
  moduleStats = { totalModules: queue.totalModules, completedModules: queue.completedModules, modules: [] };
  for (const mod of queue.modules) {
    const modPrd = readJSON(mod.prdFile);
    moduleStats.modules.push({
      code: mod.code, status: mod.status,
      tasks: { total: modPrd.tasks.length, completed: modPrd.tasks.filter(t => t.status === 'completed').length, failed: modPrd.tasks.filter(t => t.status === 'failed').length },
      filesCreated: [...new Set(modPrd.tasks.flatMap(t => t.files_changed?.created || []))].length,
      commits: [...new Set(modPrd.tasks.filter(t => t.commit_hash).map(t => t.commit_hash))].length
    });
  }
}
```

### 1d. Handoff Reconciliation (Post-Execution Validation)

See `report-reconciliation.md` for reconciliation logic (file coverage, business rule coverage, API endpoint coverage, and build/test verification).


### 1c. Test Metrics (from PRD)

> **Note:** Apex already ran tests and recorded results. Source metrics from PRD task data.

```javascript
const testTasks = prd.tasks.filter(t => t.category === 'test');
const testsPassed = testTasks.filter(t => t.status === 'completed').length;
const testsFailed = testTasks.filter(t => t.status === 'failed').length;
```

## 2. Generate Report

Write to `.ralph/reports/{feature-slug}.md` using the template structure from `report-template.md`.

Populate all variables from loaded data (stats, moduleStats, handoffReconciliation, brReconciliation, apiReconciliation, buildStatus, testStatus, permissionWarnings, testTasks, filesCreated, filesModified).

## 3. Finalize

```javascript
// Clean up section-split temporary files
// GUARD: only delete if the overall PRD status is 'completed'.
// If status is 'partial' or 'failed', keep temporary PRD files so the user
// can resume with `-r` — deleting them here would make recovery impossible.
if (prd._sectionSplit?.enabled && prd.status === 'completed') {
  for (const phase of prd._sectionSplit.phases) {
    if (fileExists(phase.prdFile) && phase.prdFile !== currentPrdPath) {
      deleteFile(phase.prdFile);
    }
  }
  delete prd._sectionSplit;
} else if (prd._sectionSplit?.enabled && prd.status !== 'completed') {
  console.log(`Section-split temp files preserved (status: ${prd.status}) — use /business-analyse-develop -r to resume`);
}

prd.updated_at = new Date().toISOString();
writeJSON(currentPrdPath, prd);
```

## 4. Display Summary

```
RALPH LOOP COMPLETE
Feature: {feature} | Status: {status}
Iterations: {n} | Tasks: {completed}/{total}
{moduleStats ? `Modules: ${completedModules}/${totalModules}` : ""}
Files: {created} created, {modified} modified
Report: .ralph/reports/{slug}.md
```

## 5. Completion Promise (if applicable)

```
<promise>{completion_promise}</promise>
```

## 6. Next Steps

```
1. Review report: .ralph/reports/{slug}.md
2. Run full test suite: dotnet test
3. Create PR: /gitflow pr
4. Clean up: rm -rf .ralph/ (optional)
```

---

Ralph loop complete. No more steps.
