---
name: step-05c-ralph-readiness
description: ULTRATHINK quality review + validation gate before ralph-loop
model: opus
next_step: null
---

> **Context files:** `_shared.md`

# Step 5c: ULTRATHINK Quality Review & Ralph Readiness Check

## MANDATORY EXECUTION RULES

- **ALWAYS** use ULTRATHINK mode for the quality review (section 0b)
- **ALWAYS** run ALL validation checks (NEVER skip)
- **BLOCKING RULE:** If ANY check fails → STOP, DO NOT proceed to ralph-loop
- **ALWAYS** provide actionable fix instructions for failures
- **NEVER** auto-launch ralph-loop (user triggers manually)
- **ALL** PRD files must be generated and validated before proceeding

## YOUR TASK

Perform a deep ULTRATHINK quality review of the entire business analysis output, then run comprehensive structural validation to ensure readiness for /ralph-loop. This is a **BLOCKING** gate — all checks must pass before development can proceed.

---

## EXECUTION SEQUENCE

### 0. Introduction

Display validation banner:

```
═══════════════════════════════════════════════════════════════
  ULTRATHINK QUALITY REVIEW & RALPH READINESS CHECK
  {application_name}
═══════════════════════════════════════════════════════════════
Phase 1: Deep quality review (ULTRATHINK)...
Phase 2: Structural validation (8 checks)...
```

---

### 0b. ULTRATHINK Deep Quality Review (MANDATORY)

> **This section MUST be executed in ULTRATHINK mode.**
> Take the time to deeply analyze the ENTIRE business analysis output.
> This is the last chance to catch quality issues before development begins.

**Objective:** Perform a thorough, deep-thinking review of the business analysis quality — not just structural checks, but semantic coherence, completeness, and production-readiness.

**Process:**

1. **Read ALL module feature.json files** (master + each module)
2. **Activate ULTRATHINK** and analyze the following 6 dimensions:

#### Dimension 1: Specification Coherence

```
For EACH module:
  - Do use cases (UCs) tell a coherent story?
  - Are functional requirements (FRs) logically derived from UCs?
  - Do business rules (BRs) cover all edge cases mentioned in UCs?
  - Are gherkin scenarios testing the RIGHT behaviors (not trivial CRUD)?
  - Do entity relationships make domain sense?

Flag: Orphan FRs (not linked to any UC), UCs with no FR coverage,
      BRs that don't map to any entity/field
```

#### Dimension 2: Permission & Security Model

```
For EACH module:
  - Is the permission hierarchy logical? (admin > manager > contributor > viewer)
  - Are there actions that should be restricted but aren't?
  - Do API endpoints all have permissions assigned?
  - Are there over-permissive roles? (e.g., contributor with delete access)
  - Cross-module: can a user in Module A access data in Module B through indirect routes?

Flag: Endpoints without permissions, roles with excessive access,
      missing permission paths
```

#### Dimension 3: Data Model Integrity

```
For EACH module:
  - Are all entity relationships bidirectional where needed?
  - Are FK references correct (target entity exists, correct field type)?
  - Are there missing audit fields (CreatedAt, UpdatedAt, CreatedBy)?
  - Do lifecycle states cover all business scenarios?
  - Are cascade delete/update rules safe? (no orphan risk)

Cross-module:
  - Are shared entity references correct?
  - Is the dependency graph honest? (no hidden dependencies)

Flag: Missing relationships, unsafe cascades, missing audit fields,
      hidden cross-module dependencies
```

#### Dimension 4: UI/UX Completeness

```
For EACH module:
  - Does every section have at least one wireframe?
  - Do wireframes cover ALL use cases? (no UC without UI representation)
  - Are navigation entries correct and complete?
  - Do wireframe actions map to real API endpoints?
  - Are form fields aligned with entity attributes?
  - Are validation rules defined for all user-input fields?

Flag: UCs with no wireframe, wireframes with unmapped actions,
      missing form validations, navigation gaps
```

#### Dimension 5: i18n & Messages Quality

```
For EACH module:
  - Are all user-facing strings covered by i18n keys?
  - Are error messages specific enough? (not generic "Error occurred")
  - Do validation messages reference the field name?
  - Are success/confirmation messages present for all write operations?
  - Are there missing translations in any language?

Flag: Generic error messages, missing field-specific validations,
      incomplete language coverage
```

#### Dimension 6: Implementation Feasibility

```
For EACH module:
  - Is the handoff.filesToCreate list realistic? (no missing files, no impossible paths)
  - Do brToCodeMapping entries have enough detail for generation?
  - Are API endpoint paths following REST conventions?
  - Are DTO structures aligned with entity attributes?
  - Is the seed data sufficient for testing all use cases?
  - Are there any features that would require infrastructure not in the stack?

Flag: Unrealistic file counts, vague BR mappings, non-RESTful routes,
      missing seed data for critical test scenarios
```

3. **Produce Quality Verdict:**

```
═══════════════════════════════════════════════════════════════
  ULTRATHINK QUALITY REVIEW - RESULTS
═══════════════════════════════════════════════════════════════

| Dimension | Score | Issues |
|-----------|-------|--------|
| Specification Coherence | A/B/C/D | {count} issues |
| Permission & Security | A/B/C/D | {count} issues |
| Data Model Integrity | A/B/C/D | {count} issues |
| UI/UX Completeness | A/B/C/D | {count} issues |
| i18n & Messages | A/B/C/D | {count} issues |
| Implementation Feasibility | A/B/C/D | {count} issues |

Overall Quality: {A/B/C/D}
  A = Production-ready (0 critical, ≤3 warnings)
  B = Good (0 critical, >3 warnings)
  C = Needs fixes (1-2 critical issues)
  D = Major rework needed (>2 critical issues)
```

4. **Display Issues (if any):**

```
Critical Issues (MUST fix before /ralph-loop):
  ✗ [Dimension] Issue description
    → Fix: Specific action to resolve

Warnings (SHOULD fix, not blocking):
  ⚠ [Dimension] Issue description
    → Recommendation: How to improve

Suggestions (nice-to-have):
  ℹ [Dimension] Suggestion
```

5. **Decision:**

```
IF overall quality = D:
  BLOCKING ERROR: Major quality issues detected
  → Return to appropriate step to fix critical issues
  → DO NOT proceed to structural validation

IF overall quality = C:
  Ask via AskUserQuestion:
    question: "Des problèmes de qualité ont été détectés. Comment souhaitez-vous procéder ?"
    header: "Qualité"
    options:
      - label: "Corriger les problèmes critiques"
        description: "Retourner aux étapes concernées pour corriger"
      - label: "Continuer malgré les problèmes"
        description: "Accepter les risques et poursuivre la validation structurelle"

IF overall quality = A or B:
  Display: "✓ Quality review passed — proceeding to structural validation..."
  → Continue to section 1
```

---

### 1. Module Status Validation

**Objective:** Verify all modules have completed handoff.

**Process:**

1. Read master feature.json via ba-reader
2. For EACH module in modules[]:
   ```
   a. Check module.status === "handed-off"
   b. If module.featureJsonPath exists, read module feature.json
   c. Verify module feature.json status === "handed-off"
   d. Verify module feature.json handoff section exists and is not empty
   ```

3. Display validation table:

```
| Module | Master Status | Module Status | Handoff Present | Result |
|--------|--------------|---------------|-----------------|--------|
| Projects | handed-off | handed-off | ✓ | PASS |
| TimeTracking | handed-off | handed-off | ✓ | PASS |
| Reporting | specified | specified | ✗ | FAIL |
```

**IF ANY module shows FAIL:**
- **BLOCKING ERROR:** List failed modules
- **FIX:** Return to step-05a-handoff.md for missing modules
- **STOP** - do not proceed to next check

---

### 2. PRD Files Validation

**Objective:** Verify all PRD files are generated and structurally valid.

**Process:**

1. For EACH module in modules[]:
   ```
   a. Locate expected PRD file: .ralph/prd-{moduleCode}.json
   b. Verify file exists
   c. Read PRD file
   d. Verify structure (see [references/prd-generation.md](../references/prd-generation.md))
   ```

2. **PRD Structure Validation:**

   Perform the 4 mandatory PRD structure checks:
   - **Check 1:** Version must be "3.0.0"
   - **Check 2:** filesToCreate must be under `implementation` (NOT root level)
   - **Check 3:** All 7 categories present (domain, application, infrastructure, api, frontend, seedData, tests)
   - **Check 4:** File counts match feature.json handoff counts

   ```javascript
   const prdErrors = validateAllPRDs(modules);

   IF prdErrors.length > 0:
     // CONDITIONAL LOAD: Only load PRD reference on validation failure
     Read references/prd-generation.md
     Display:
       - PRD v3.0 structure requirements
       - Detailed validation logic for failed checks
       - Common errors & fix commands for each failure
       - Generation command reference

     BLOCKING ERROR: {prdErrors.length} PRD file(s) invalid
     → Fix all PRD errors before proceeding

   ELSE:
     All PRD files valid ✓
     → Continue to dependency graph validation
   ```

   **Optimization:** The detailed 300-line prd-generation.md is loaded **only when PRD validation fails** (saves ~12,000 tokens on success path).

3. Display PRD validation table:

```
| Module | PRD File | Version | Structure | File Counts | Result |
|--------|----------|---------|-----------|-------------|--------|
| Projects | ✓ exists | 3.0.0 | ✓ valid | 42/42 match | PASS |
| TimeTracking | ✓ exists | 3.0.0 | ✓ valid | 37/37 match | PASS |
| Reporting | ✗ missing | - | - | - | FAIL |
```

**IF ANY PRD shows FAIL:**
- **BLOCKING ERROR:** List failed PRDs with specific issues
- **FIX:** Re-run `ss derive-prd --feature {path} --output .ralph/prd-{moduleCode}.json`
- **STOP** - do not proceed to next check

---

### 3. Dependency Graph Validation

**Objective:** Verify module dependencies are resolvable and topologically ordered.

**Process:**

1. Read master feature.json dependencyGraph
2. For each edge in dependencyGraph.edges[]:
   ```
   a. Verify source module exists in modules[]
   b. Verify target module exists in modules[]
   c. Verify no circular dependencies
   ```

3. Verify topologicalOrder matches actual dependencies:
   ```
   For each module M in topologicalOrder:
     For each dependency D of M:
       D must appear BEFORE M in topologicalOrder
   ```

4. Display dependency validation:

```
✓ Dependency graph valid
✓ No circular dependencies detected
✓ Topological order correct: [Projects, TimeTracking, LeaveManagement, AbsenceManagement, Reporting]
✓ 4 dependency edges validated
```

**IF validation fails:**
- **BLOCKING ERROR:** Report circular dependencies or invalid edges
- **FIX:** Return to step-02-decomposition.md to fix dependency graph
- **STOP** - do not proceed to next check

---

### 4. Cross-Module References Validation

**Objective:** Verify all cross-module entity references are resolvable.

**Process:**

1. For EACH module feature.json:
   ```
   a. Extract all entity names from analysis.entities[]
   b. Build map: {moduleName -> [entityNames]}
   ```

2. For EACH module feature.json:
   ```
   a. Extract all relationships from analysis.entities[].relationships[]
   b. For each relationship.target:
      - Extract module prefix (first segment before dot)
      - Verify referenced module exists
      - Verify referenced entity exists in target module
   ```

3. Display cross-reference validation:

```
Cross-Module References Validated:
  ✓ TimeTracking.TimeEntry.projectId → Projects.Project.id
  ✓ LeaveManagement.LeaveRequest.employeeId → Projects.Employee.id
  ✓ AbsenceManagement.Absence.employeeId → Projects.Employee.id
  ✓ Reporting.ProjectReport.projectId → Projects.Project.id

Total: 4 cross-module references, all resolvable
```

**IF ANY reference is unresolvable:**
- **BLOCKING ERROR:** List broken references with module and field names
- **FIX:** Return to step-03a1-setup.md for affected modules to fix entity references
- **STOP** - do not proceed to next check

---

### 5. Handoff Completeness Check

**Objective:** Verify all required handoff sections are complete and non-empty.

**Process:**

For EACH module feature.json:

1. **filesToCreate validation:**
   ```
   - handoff.filesToCreate must be an object
   - All 7 categories must exist: domain, application, infrastructure, api, frontend, seedData, tests
   - Each category must be a non-empty array
   - Each file entry must have: path, type, module
   ```

2. **brToCodeMapping validation:**
   ```
   - handoff.brToCodeMapping must be a non-empty array
   - Each entry must have: ruleId, files[], implementation
   - All ruleIds must reference existing BRs in analysis.businessRules[]
   ```

3. **apiEndpointSummary validation:**
   ```
   - handoff.apiEndpointSummary must be a non-empty array
   - Each entry must have: method, path, permission, linkedUC
   - All linkedUCs must reference existing UCs in specification.useCases[]
   ```

4. **Metadata validation:**
   ```
   - handoff.complexity must be "simple|medium|complex"
   - handoff.totalFiles must be > 0
   - handoff.totalTasks must be > 0
   - handoff.handedOffAt must be valid ISO timestamp
   ```

5. Display completeness summary:

```
Handoff Completeness:
  Module: Projects
    ✓ filesToCreate: 7 categories, 42 files total
    ✓ brToCodeMapping: 8 business rules mapped
    ✓ apiEndpointSummary: 12 endpoints documented
    ✓ complexity: medium
    ✓ metadata complete

  Module: TimeTracking
    ✓ filesToCreate: 7 categories, 37 files total
    ✓ brToCodeMapping: 10 business rules mapped
    ✓ apiEndpointSummary: 15 endpoints documented
    ✓ complexity: complex
    ✓ metadata complete
```

**IF ANY module has incomplete handoff:**
- **BLOCKING ERROR:** List missing or invalid sections per module
- **FIX:** Return to step-05a-handoff.md for affected modules
- **STOP** - do not proceed to next check

---

### 6. i18n Keys Validation

**Objective:** Verify all required i18n keys are defined for all 4 languages.

**Process:**

For EACH module feature.json:

1. Extract all i18n keys from specification.i18nKeys[]
2. Verify each key has translations for: fr, en, it, de
3. Check for common missing patterns:
   ```
   - Entity names (singular + plural)
   - Field labels
   - Validation error messages
   - Success/error messages
   - Navigation labels
   - Button labels
   ```

4. Display i18n validation:

```
i18n Keys Validation:
  Module: Projects
    ✓ 42 keys defined
    ✓ All keys have 4 languages (fr, en, it, de)
    ✓ Entity keys complete
    ✓ Validation message keys complete
    ✓ Navigation keys complete

  Module: TimeTracking
    ⚠ 37 keys defined
    ⚠ Missing translation for "timeEntry.validation.overlapping" in DE
    ✓ Entity keys complete
```

**IF ANY missing translations:**
- **WARNING:** List missing translations (not blocking, but should be fixed)
- **RECOMMEND:** Add missing translations before proceeding
- Allow user to continue or fix

---

### 7. Master Feature Validation

**Objective:** Verify master feature.json has all required application-level data.

**Process:**

1. Read master feature.json
2. Verify status === "handed-off"
3. Verify handoff section exists with:
   ```
   - implementationStrategy defined
   - moduleOrder matches modules[]
   - totalFilesToCreate === sum of all module totalFiles
   - totalTasks === sum of all module totalTasks
   - prdFiles array has entry for each module
   ```

4. Display master validation:

```
Master Feature Validation:
  ✓ Status: handed-off
  ✓ Implementation strategy: module par module
  ✓ Module order: [Projects, TimeTracking, LeaveManagement, AbsenceManagement, Reporting]
  ✓ Total files: 183 (matches sum of modules)
  ✓ Total tasks: 247 (matches sum of modules)
  ✓ PRD files: 5 (one per module)
```

**IF master validation fails:**
- **BLOCKING ERROR:** List missing or invalid sections
- **FIX:** Return to step-05a-handoff.md to fix master handoff
- **STOP** - do not proceed

---

### 8. Progress Tracker Validation

**Objective:** Verify progress.txt is generated and complete.

**Process:**

1. Verify file exists: `.ralph/progress.txt`
2. Read file and verify structure:
   ```
   - Has header with application name
   - Has summary section
   - Has section for each module
   - Each module section has tasks by layer
   - Has completion checkboxes ([ ] format)
   ```

3. Count total tasks and verify matches master.handoff.totalTasks

4. Display progress tracker validation:

```
Progress Tracker Validation:
  ✓ File exists: .ralph/progress.txt
  ✓ Size: 12.3 KB
  ✓ Modules: 5 sections present
  ✓ Tasks: 247 checkboxes (matches master)
  ✓ Structure: valid markdown format
```

**IF progress tracker invalid:**
- **WARNING:** Progress tracker issues (not blocking)
- **RECOMMEND:** Re-generate via step-05b-deploy.md
- Allow user to continue

---

### 9. Final Readiness Report

**Objective:** Display comprehensive readiness summary and next steps.

**Process:**

1. Aggregate all validation results (quality review + 7 structural checks)
2. Calculate readiness score:
   ```
   passedChecks / totalChecks * 100
   Quality gate: overall quality must be A or B
   ```

3. Display final report:

```
═══════════════════════════════════════════════════════════════
  RALPH READINESS CHECK - COMPLETE
═══════════════════════════════════════════════════════════════

ULTRATHINK Quality Review:
  Quality Score: {A/B} — {Production-ready / Good}
  Dimensions: {6/6 reviewed}
  Critical issues: {0}
  Warnings: {count}

Structural Validation Summary:
  ✓ Module status validation: PASS ({n}/{n} modules)
  ✓ PRD files validation: PASS ({n}/{n} files)
  ✓ Dependency graph validation: PASS ({n} edges)
  ✓ Cross-module references validation: PASS ({n} references)
  ✓ Handoff completeness check: PASS ({n}/{n} modules)
  ⚠ i18n keys validation: WARNING ({n} missing translation)
  ✓ Master feature validation: PASS
  ✓ Progress tracker validation: PASS

Readiness Score: 100% (8/8 checks passed, {n} warnings)

═══════════════════════════════════════════════════════════════

Status: READY FOR DEVELOPMENT ✓

Next Steps:
  1. Address warnings (recommended but not blocking):
     - {list warnings from quality review + structural checks}

  2. Review progress tracker: .ralph/progress.txt

  3. When ready, launch development:

     /ralph-loop

     Note: Use /ralph-loop -r ONLY to resume an interrupted loop.
           After a fresh /business-analyse, always use /ralph-loop (without -r).

  4. Ralph-loop will:
     - Process modules in topological order: [{module list}]
     - Generate {n} files across 7 layers
     - Execute {n} tasks tracked in progress.txt

═══════════════════════════════════════════════════════════════
```

**IF readiness score < 100% OR quality = C/D (critical checks failed):**

```
═══════════════════════════════════════════════════════════════
  RALPH READINESS CHECK - FAILED
═══════════════════════════════════════════════════════════════

Status: NOT READY FOR DEVELOPMENT ✗

{IF quality = C/D:}
Quality Issues Found:
  ✗ ULTRATHINK quality review: {C/D} — {Needs fixes / Major rework}
    - {List critical quality issues from section 0b}
    - Fix: Return to appropriate step (see quality review details above)

{IF structural checks failed:}
Structural Issues Found:
  ✗ {check name}: FAIL ({details})
    - {specific issue}
    - Fix: {specific action}

Required Actions:
  1. Fix all critical issues listed above
  2. Re-run validation: load step-05c-ralph-readiness.md
  3. Only proceed to /ralph-loop when all checks pass AND quality ≥ B

DO NOT PROCEED TO /ralph-loop UNTIL ALL CHECKS PASS
═══════════════════════════════════════════════════════════════
```

---

## SELF-VERIFICATION

Before displaying final report, VERIFY:

1. **ULTRATHINK quality review executed** (6 dimensions analyzed)
2. **Quality verdict displayed** with scores per dimension
3. **ALL 8 structural validation checks executed** (never skip)
4. **Results clearly marked** (PASS/FAIL/WARNING)
5. **Actionable fixes provided** for all failures
6. **Readiness score calculated** correctly
7. **Next steps displayed** with exact commands
8. **Blocking errors prevent progression** (no false positives)

---

## SUCCESS CRITERIA

- ULTRATHINK quality review completed with overall score A or B
- All 8 critical validation checks executed (quality review + 7 structural)
- Clear PASS/FAIL/WARNING status for each check
- Readiness score displayed (100% = all critical checks passed)
- Actionable fix instructions for all failures
- User can proceed to /ralph-loop only if readiness score = 100% AND quality ≥ B
- Warnings documented but not blocking

---

## NOTES

**Why this gate matters:**

- **ULTRATHINK catches semantic issues** that structural checks miss (orphan UCs, incoherent permissions, missing UI flows)
- Prevents incomplete handoffs from reaching development
- Catches structural issues early (PRD validation)
- Verifies cross-module integrity before code generation
- Ensures ralph-loop has all required data to proceed
- Reduces failed development attempts and rework

**When to run this gate:**

- **Automatically at end of step-05b-deploy.md (MANDATORY)**
- After fixing any handoff issues to re-validate

**What happens if checks fail:**

- Development is BLOCKED until issues are fixed
- User returns to appropriate step to fix issues
- Re-run validation after fixes
- Only proceed when all critical checks pass AND quality review passes
