# PRD v3.0 Structure & Validation Rules

Source: business-analyse step-05-deploy.md

## PRD File Format v3.0

### File Location

```
.ralph/prd-{moduleCode}.json
```

Example: `.ralph/prd-Projects.json`, `.ralph/prd-TimeTracking.json`

---

## Structure Requirements

### 1. Version Field (MANDATORY)

```json
{
  "$version": "3.0.0"
}
```

**Validation:**
- MUST be exactly `"3.0.0"`
- BLOCKING if missing or wrong version

**Common Error:**
```
BLOCKING_ERROR: PRD version must be 3.0.0, got: 2.1.0
Fix: Re-run ss business-analyse-handoff with latest version
```

---

### 2. Implementation Section (MANDATORY)

**CRITICAL:** `filesToCreate` MUST be under `implementation`, NOT at root level.

**Correct Structure:**
```json
{
  "$version": "3.0.0",
  "implementation": {
    "filesToCreate": {
      "domain": [...],
      "application": [...],
      "infrastructure": [...],
      "api": [...],
      "frontend": [...],
      "seedData": [...],
      "tests": [...],
      "documentation": [...]
    }
  }
}
```

**Wrong Structure (v2.x legacy):**
```json
{
  "$version": "3.0.0",
  "filesToCreate": {  // ❌ WRONG - at root level
    "domain": [...]
  }
}
```

**Validation:**
- IF `prd.filesToCreate` exists at root level → BLOCKING ERROR
- IF `prd.implementation.filesToCreate` missing → BLOCKING ERROR

**Fix Command:**
```bash
ss business-analyse-handoff --feature {path} --output .ralph/prd-{moduleCode}.json
```

---

### 2b. PRD v4.0 Structure (spec-oriented)

> **v4 PRDs are generated with `--v4` flag.** They use `expectedFiles` instead of `implementation.filesToCreate`.

```json
{
  "$version": "4.0.0",
  "objectives": [
    { "description": "...", "acceptanceCriteria": ["..."] }
  ],
  "expectedFiles": {
    "domain": [...],
    "application": [...],
    "infrastructure": [...],
    "api": [...],
    "frontend": [...],
    "seedData": [...],
    "tests": [...],
    "documentation": [...]
  },
  "gates": { /* declarative quality gate definitions */ }
}
```

**Key differences from v3:**

| Aspect | v3 (`$version: "3.0.0"`) | v4 (`$version: "4.0.0"`) |
|--------|--------------------------|--------------------------|
| File manifest | `implementation.filesToCreate` | `expectedFiles` (root level) |
| Task model | `tasks[]` (pre-computed) | `objectives[]` (goal-oriented) |
| Execution | Batch iterations (compact-loop) | Continuous (compaction-enabled) |

**Consumer code must handle both:**
```javascript
const fileManifest = prd.$version === '4.0.0'
  ? prd.expectedFiles
  : prd.implementation?.filesToCreate;
```

---

### 3. Eight Categories (MANDATORY)

All PRD files MUST include these 8 categories under `implementation.filesToCreate`:

| Category | Description | Examples |
|----------|-------------|----------|
| **domain** | Domain entities, value objects, domain services | `Project.cs`, `ProjectStatus.cs` |
| **application** | Application services, DTOs, interfaces | `ProjectService.cs`, `CreateProjectDto.cs` |
| **infrastructure** | Data access, repositories, EF Core config | `ProjectRepository.cs`, `ProjectConfiguration.cs` |
| **api** | Controllers, API endpoints | `ProjectsController.cs` |
| **frontend** | React pages, components, hooks | `ProjectsPage.tsx`, `useProjects.ts` |
| **seedData** | Seed data classes | `ProjectSeedData.cs` |
| **tests** | Unit tests, integration tests | `ProjectServiceTests.cs`, `ProjectsControllerTests.cs` |
| **documentation** | Technical docs, user guides, API specs | `doc-data.ts`, `UserGuide.md`, `api-spec.yaml` |

> **Note `documentation`:** Cette catégorie peut contenir des fichiers générés par le skill `/documentation` après `/business-analyse-develop`. Elle est obligatoire dans la structure PRD (peut être un tableau vide `[]` si aucune doc n'est prévue, mais DOIT être présente).

**Validation:**
```javascript
const categories = ['domain', 'application', 'infrastructure', 'api', 'frontend', 'seedData', 'tests', 'documentation'];
const missingCategories = categories.filter(cat => !prd.implementation.filesToCreate[cat]);

if (missingCategories.length > 0) {
  BLOCKING_ERROR(`Missing categories: ${missingCategories.join(', ')}`);
}
```

**Common Errors:**
- Missing `tests` category → often forgotten
- Missing `seedData` category → sometimes omitted for modules without seed data
- Missing `documentation` category → must be present even if empty
- Empty arrays allowed (e.g., `"seedData": []`, `"documentation": []`) if genuinely no files needed

---

### 4. File Count Consistency (MANDATORY)

**Validation:** PRD file counts MUST match index.json handoff counts.

```javascript
const featureHandoff = moduleFeature.handoff.filesToCreate;
const categories = ['domain', 'application', 'infrastructure', 'api', 'frontend', 'seedData', 'tests', 'documentation'];

for (const cat of categories) {
  const prdCount = prd.implementation.filesToCreate[cat]?.length ?? 0;
  const featureCount = featureHandoff[cat]?.length ?? 0;

  if (prdCount !== featureCount) {
    BLOCKING_ERROR(`${cat}: prd has ${prdCount} files but index.json has ${featureCount}`);
  }
}
```

**Why this matters:**
- Ensures PRD was derived from the correct index.json
- Catches stale PRD files (derived from old version)
- Validates handoff integrity before business-analyse-develop

**Fix:**
- Re-derive PRD from latest index.json
- Check that index.json handoff section is complete

---

### 5. File Entry Schema

Each file entry in a category array must have:

```json
{
  "path": "src/SmartStack.HumanResources.Domain/Projects/Project.cs",
  "type": "Entity",
  "module": "Projects"
}
```

**Required Fields:**
- `path` (string): Absolute or relative path where file will be created
- `type` (string): File type hint (Entity, Service, Controller, Page, Test, etc.)
- `module` (string): Module code this file belongs to

**Optional Fields:**
- `description` (string): Brief description of what the file does
- `dependencies` (array): Other files this depends on

---

### 6. Specification Files (MANDATORY)

Each PRD MUST include a `specificationFiles` object and 5 companion files in `.ralph/`:

```json
{
  "$version": "3.0.0",
  "implementation": { "filesToCreate": { /* 8 categories */ } },
  "brToCodeMapping": [ /* enriched with statement, example, formula */ ],
  "apiEndpointSummary": [ /* ... */ ],
  "specificationFiles": {
    "entities": "prd-{moduleCode}.entities.json",
    "rules": "prd-{moduleCode}.rules.json",
    "usecases": "prd-{moduleCode}.usecases.json",
    "screens": "prd-{moduleCode}.screens.json",
    "permissions": "prd-{moduleCode}.permissions.json"
  }
}
```

**Companion files** are VERBATIM copies of BA source files, colocated in `.ralph/`:

```
.ralph/
  prd-Employees.json                  # PRD manifest (compact)
  prd-Employees.entities.json         # VERBATIM copy of entities.json
  prd-Employees.rules.json            # VERBATIM copy of rules.json
  prd-Employees.usecases.json         # VERBATIM copy of usecases.json
  prd-Employees.screens.json          # VERBATIM copy of screens.json
  prd-Employees.permissions.json      # VERBATIM copy of permissions.json
```

**Validation:**
```javascript
const specFiles = prd.specificationFiles;
if (!specFiles) {
  BLOCKING_ERROR('specificationFiles missing from PRD');
}
const specKeys = ['entities', 'rules', 'usecases', 'screens', 'permissions'];
for (const key of specKeys) {
  if (!specFiles[key]) {
    BLOCKING_ERROR(`specificationFiles.${key} missing`);
  }
  const filePath = path.join('.ralph', specFiles[key]);
  if (!fs.existsSync(filePath)) {
    BLOCKING_ERROR(`Companion file not found: ${filePath}`);
  }
}
```

**Why companion files matter:**
- `/apex` loads only the specs needed per layer (entities for L0, rules+usecases for L2, screens for L3)
- Context per layer is ~200-500 lines instead of ~2000 lines monolithic
- Zero risk of specs being lost at the bottom of a large context window
- Full BA detail available for oneshot generation (attributes, formulas, screen columns)

---

## Validation Checklist

Use this checklist when validating PRD files:

| Check | Validation | Status |
|-------|-----------|--------|
| **Version** | `$version === "3.0.0"` | PASS/FAIL |
| **Structure** | `implementation.filesToCreate` exists (not root) | PASS/FAIL |
| **Categories** | All 8 categories present | PASS/FAIL |
| **File Counts** | PRD counts match index.json handoff.filesToCreate | PASS/FAIL |
| **File Schemas** | All files have path, type, module | PASS/FAIL |
| **Spec Files** | `specificationFiles` present with 5 paths, all companion files exist | PASS/FAIL |

**All checks must PASS before proceeding to /business-analyse-develop**

---

## Common Errors & Fixes

### Error 1: Wrong Version
```
BLOCKING_ERROR: PRD version must be 3.0.0, got: 2.1.0
```
**Fix:** Re-run `ss business-analyse-handoff` with latest SmartStack.mcp version

### Error 2: filesToCreate at Root Level
```
BLOCKING_ERROR: filesToCreate is at ROOT level (wrong structure)
```
**Fix:** Re-run `ss business-analyse-handoff --feature {path} --output .ralph/prd-{moduleCode}.json`

### Error 3: Missing Categories
```
BLOCKING_ERROR: Missing categories: seedData, tests, documentation
```
**Fix:**
- Check index.json handoff.filesToCreate has all 8 categories
- Re-derive PRD after fixing index.json
- If genuinely no files needed, use empty array: `"seedData": []`, `"documentation": []`

### Error 4: File Count Mismatch
```
BLOCKING_ERROR: api: prd has 8 files but index.json has 12
```
**Fix:**
- PRD is stale (derived from old index.json)
- Re-derive PRD from latest index.json: `ss business-analyse-handoff --feature {path} --output .ralph/prd-{moduleCode}.json`

---

## Generation Command Reference

**Derive PRD from index.json:**
```bash
ss business-analyse-handoff \
  --feature docs/{App}/business-analyse/v1.0/index.json \
  --output .ralph/prd-{ModuleCode}.json
```

**Example:**
```bash
ss business-analyse-handoff \
  --feature docs/HumanResources/business-analyse/v1.0/index.json \
  --output .ralph/prd-Projects.json
```

**Batch generation for all modules:**
```bash
# Typically done in step-05-deploy.md
for module in $(modules); do
  ss business-analyse-handoff --feature {module_feature_path} --output .ralph/prd-${module}.json
done
```

---

## Why PRD Validation Matters

| Risk | Without Validation | With Validation |
|------|-------------------|-----------------|
| **Wrong structure** | business-analyse-develop fails mid-execution | Caught before development starts |
| **Stale PRD** | Generates code from old spec | Detects version mismatch |
| **Missing files** | Incomplete implementation | Ensures all layers covered |
| **Count mismatch** | Silent data loss | Guarantees integrity |

**Bottom line:** Ralph-loop depends on correct PRD structure. Validating upfront saves hours of debugging.

---

## Related Files

- `step-05-deploy.md`: Generates PRD files via `ss business-analyse-handoff`
- `feature-schema.json`: Schema for index.json (source of PRD)
- `/business-analyse-develop` skill: Consumes PRD files for implementation
