# Robustness Checks for Business Analysis

> **Authoritative minimums:** See `_shared.md` § "Minimum Counts" for the single source of truth on all minimum thresholds.
> **Objective:** Prevent incomplete specifications and broken references from reaching development.

## Overview

This document consolidates all robustness checks implemented across the business-analyse workflow. Each check serves to catch issues early, before they cause ralph-loop failures or runtime errors.

---

## Phase 1: Module Specification Checklist (Step-03)

> **When:** At end of step-03, before marking module status = "specified"
> **Blocking:** YES - Module CANNOT proceed to consolidation with failing checks

### Purpose

Ensures each module has ALL required components before being marked as "specified". Prevents incomplete modules from reaching step-04 consolidation.

### Checks (31 total)

#### SECTION 1: Data Model (3 checks)

| # | Check | Minimum | Blocking | Rationale |
|---|-------|---------|----------|-----------|
| 1.1 | Entities count | ≥2 | YES | Single-entity modules are rare and likely incomplete |
| 1.2 | Entity attributes | Each entity ≥3 attributes | YES | Entities with <3 attributes are incomplete |
| 1.3 | Entity relationships | All entities have relationships or marked standalone | NO (WARNING) | Standalone entities should be rare |

#### SECTION 2: Business Rules (3 checks)

| # | Check | Minimum | Blocking | Rationale |
|---|-------|---------|----------|-----------|
| 2.1 | Business rules count | ≥4 | YES | Modules need validation/calculation logic |
| 2.2 | BR categories | ≥2 categories (VAL/CALC/WF/SEC/DATA) | YES | Single-category modules likely incomplete |
| 2.3 | BR module prefixes | All BRs use module prefix | YES | Prevents ID collisions in multi-module apps |

#### SECTION 3: Use Cases & Requirements (4 checks)

| # | Check | Minimum | Blocking | Rationale |
|---|-------|---------|----------|-----------|
| 3.1 | Use cases count | ≥6 | YES | CRUD (5) + 1 business-specific minimum |
| 3.2 | UC module prefixes | All UCs use module prefix | YES | Prevents ID collisions |
| 3.3 | Functional requirements count | ≥4 | YES | FRs must cover key functionality |
| 3.4 | UC-FR linkage | Every UC has ≥1 linked FR | NO (WARNING) | Orphan UCs indicate incomplete requirements |
| 3.5 | FR-BR linkage | Every FR has ≥1 linked BR | NO (WARNING) | FRs without BRs may lack validation logic |

#### SECTION 4: Permissions (3 checks)

| # | Check | Minimum | Blocking | Rationale |
|---|-------|---------|----------|-----------|
| 4.1 | Permissions count | ≥5 | YES | CRUD (4) + 1 business action minimum |
| 4.2 | Permission format | Module: `{app}.{module}.{action}` or Section: `{app}.{module}.{section}.{action}` | YES | Wrong format breaks RBAC system |
| 4.3 | Role permissions | All roles have ≥1 permission | YES | Roles without permissions are useless |

#### SECTION 5: UI & Navigation (4 checks)

| # | Check | Minimum | Blocking | Rationale |
|---|-------|---------|----------|-----------|
| 5.1 | Sections count | ≥2 | YES | Modules need list + form minimum |
| 5.2 | Wireframes count | 1 per section | YES | EVERY section MUST have wireframe |
| 5.3 | Navigation entries | ≥1 | YES | Module must be accessible in menu |
| 5.4 | Navigation route patterns | No `/list` or `/detail/:id` suffixes | YES | list route = module route (index), detail route = module + /:id. FORBIDDEN: `/module/list`, `/module/detail/:id` |

#### SECTION 6: I18N & Messages (3 checks)

| # | Check | Minimum | Blocking | Rationale |
|---|-------|---------|----------|-----------|
| 6.1 | i18n keys count | ≥42 | YES | Entities, fields, messages, validation, navigation |
| 6.2 | i18n languages | All keys have 4 languages (fr/en/it/de) | YES | Missing translations break multi-language |
| 6.3 | Messages count | ≥4 | YES | 1 success, 1 error, 1 warning, 1 info minimum |

#### SECTION 7: Seed Data (2 checks)

| # | Check | Minimum | Blocking | Rationale |
|---|-------|---------|----------|-----------|
| 7.1 | CORE seed data arrays | All 9 arrays present (per `_shared.md` § "Minimum Counts") | YES | Missing CORE data breaks deployment |
| 7.2 | Business seed data | Template defined | NO (WARNING) | Helps with testing |

**CORE arrays required (9 total — see `_shared.md` § "seedDataCore arrays"):**
1. `navigationApplications` — required once per application
2. `applicationRoles` — required once per application
3. `navigationModules` — one per module
4. `navigationSections` — one per section (list, detail, create, etc.)
5. `navigationResources` — optional per resource
6. `navigationTranslations` — 4 languages per nav module
7. `permissions` — CRUD + business actions per module
8. `rolePermissions` — role to permission mappings
9. `permissionConstants` — PascalCase constants for code

#### SECTION 8: API Endpoints (2 checks)

| # | Check | Minimum | Blocking | Rationale |
|---|-------|---------|----------|-----------|
| 8.1 | API endpoints count | ≥5 | YES | CRUD (5) minimum |
| 8.2 | API permissions | Every endpoint has permission | YES | Endpoints without permissions are security holes |

#### SECTION 9: Validations (1 check)

| # | Check | Minimum | Blocking | Rationale |
|---|-------|---------|----------|-----------|
| 9.1 | Validations count | ≥1 | YES | Modules need field validation rules |

#### SECTION 10: Gherkin Scenarios (1 check)

| # | Check | Minimum | Blocking | Rationale |
|---|-------|---------|----------|-----------|
| 10.1 | Gherkin scenarios count | ≥2 | NO (WARNING) | Enables automated testing |

### Failure Handling

**IF ANY blocking check fails:**

1. **STOP** - Do NOT mark module as "specified"
2. **DISPLAY** table of failures with details
3. **ACTIONS:**
   - Fix ALL blocking failures
   - Re-run step-03 module specification
   - Proceed only when ALL blocking checks pass

**Example output:**

```
═══════════════════════════════════════════════════════════════
  MODULE SPECIFICATION INCOMPLETE - Projects
═══════════════════════════════════════════════════════════════

| Section | Check | Required | Actual | Status | Details |
|---------|-------|----------|--------|--------|---------|
| Business Rules | BR categories | ≥2 | 1 | ✗ FAIL | Only VAL category present |
| Use Cases | UC count | ≥6 | 4 | ✗ FAIL | Missing business-specific UCs |
| Wireframes | Count | 3 | 2 | ✗ FAIL | Missing wireframe for "Settings" section |

ACTIONS REQUIRED:
1. Add business rules in ≥1 other category (CALC, WF, SEC, or DATA)
2. Add 2 more use cases (business-specific)
3. Create wireframe for "Settings" section
4. Re-run step-03 validation

DO NOT PROCEED TO CONSOLIDATION UNTIL ALL CHECKS PASS
═══════════════════════════════════════════════════════════════
```

---

## Phase 2: Cross-Module Reference Validation (Step-04)

> **When:** During consolidation, before marking application as "consolidated"
> **Blocking:** YES - Unresolved references BLOCK handoff

### Purpose

Verifies ALL cross-module entity references are resolvable. Prevents FK constraint violations and runtime errors during ralph-loop code generation.

### Process

1. **Build Entity Registry**
   - Extract all entities from all modules
   - Map: `{moduleCode → [entities]}`

2. **Extract Cross-Module References**
   - Scan all `entity.relationships[]` for references to other modules
   - Format: `"ModuleName.EntityName.FieldName"` or `"ModuleName.EntityName"`

3. **Validate References**
   - ✓ Target module exists
   - ✓ Target entity exists in target module
   - ✓ Target field exists (if specified)

4. **Validate Dependency Graph Alignment**
   - For each cross-module reference, verify dependency edge exists
   - Auto-fix: add missing edges (with warning)

5. **Detect Circular Dependencies**
   - BLOCKING ERROR if cycles detected
   - User must break cycles manually

### Checks

| # | Check | Blocking | Failure Action |
|---|-------|----------|----------------|
| 1 | Target module exists | YES | BLOCKING ERROR - list invalid references |
| 2 | Target entity exists | YES | BLOCKING ERROR - list invalid references |
| 3 | Target field exists | NO (WARNING) | Assume PK ("Id") if not specified |
| 4 | Dependency edge exists | NO (WARNING) | Auto-fix: add missing edge |
| 5 | No circular dependencies | YES | BLOCKING ERROR - user must fix |

### Example Output

**Success:**

```
═══════════════════════════════════════════════════════════════
  CROSS-MODULE REFERENCES VALIDATED
═══════════════════════════════════════════════════════════════

| Source Module | Source Entity | Target | Type | Status |
|---------------|---------------|--------|------|--------|
| TimeTracking | TimeEntry | Projects.Project.Id | FK (N:1) | ✓ RESOLVED |
| LeaveManagement | LeaveRequest | Projects.Employee.Id | FK (N:1) | ✓ RESOLVED |
| AbsenceManagement | Absence | Projects.Employee.Id | FK (N:1) | ✓ RESOLVED |
| Reporting | ProjectReport | Projects.Project.Id | FK (N:1) | ✓ RESOLVED |

Total: 4 cross-module references
All references RESOLVED ✓
No circular dependencies ✓
═══════════════════════════════════════════════════════════════
```

**Failure (unresolved reference):**

```
═══════════════════════════════════════════════════════════════
  CROSS-MODULE REFERENCES FAILED
═══════════════════════════════════════════════════════════════

BLOCKING ERRORS:

1. Module "TimeTracking": Entity "TimeEntry" references non-existent entity "Task" in module "Projects"
   - Source: TimeEntry.taskId
   - Target: Projects.Task (NOT FOUND)
   - Fix: Either create "Task" entity in Projects module, or remove reference

2. Module "Reporting": Entity "ProjectReport" references non-existent module "Analytics"
   - Source: ProjectReport.analyticsId
   - Target: Analytics.Report (module does not exist)
   - Fix: Either create "Analytics" module, or remove reference

ACTIONS REQUIRED:
1. Fix ALL unresolved references listed above
2. Return to step-03 for affected modules
3. Re-run step-04 consolidation

DO NOT PROCEED TO HANDOFF UNTIL ALL REFERENCES RESOLVED
═══════════════════════════════════════════════════════════════
```

**Failure (circular dependency):**

```
═══════════════════════════════════════════════════════════════
  CIRCULAR DEPENDENCIES DETECTED
═══════════════════════════════════════════════════════════════

BLOCKING ERROR: Cycles found in dependency graph

Cycle 1: Orders → Invoices → Payments → Orders
Cycle 2: Customers → Contacts → Customers

ACTIONS REQUIRED:
1. Break cycles by:
   - Moving shared entities to a separate "Core" module
   - Using event-driven communication instead of FK
   - Removing unnecessary dependencies
2. Return to step-02 decomposition
3. Fix dependency graph
4. Re-run step-03 module specification
5. Re-run step-04 consolidation

DEVELOPMENT CANNOT PROCEED WITH CIRCULAR DEPENDENCIES
═══════════════════════════════════════════════════════════════
```

---

## Phase 3: Ralph Readiness Validation (Step-05)

> **When:** After artifacts deployed (step-05), before launching /ralph-loop
> **Blocking:** YES - Development blocked if critical checks fail

### Purpose

Final gate to ensure business analysis is 100% ready for implementation. Catches issues before ralph-loop starts, preventing failed development attempts.

### Checks (9 categories)

| # | Category | Checks | Blocking | Purpose |
|---|----------|--------|----------|---------|
| 1 | Module Status | All modules status = "handed-off" | YES | Incomplete modules break ralph-loop |
| 2 | PRD Files | All .ralph/prd-{module}.json files exist, valid structure, file counts match index.json | YES | Ralph-loop reads PRDs for tasks |
| 3 | Dependency Graph | Valid, no cycles, topological order correct | YES | Determines module implementation order |
| 4 | Cross-Module References | All references resolvable | YES | Prevents FK constraint errors |
| 5 | Handoff Completeness | All 8 file categories, brToCodeMapping, apiEndpointSummary | YES | Missing data breaks code generation |
| 6 | i18n Keys | All keys have 4 languages | NO (WARNING) | Missing translations won't block dev |
| 7 | Master Feature | Status = "handed-off", handoff complete | YES | Ralph-loop needs master handoff |
| 8 | Progress Tracker | File exists, structure valid, task count matches | NO (WARNING) | Used for progress tracking |
| 9 | Final Readiness | Aggregate all checks, calculate score | YES if <100% | All critical checks must pass |

### Readiness Score

```
Readiness Score = (passed critical checks / total critical checks) × 100%
```

**Thresholds:**
- **100%** → READY FOR DEVELOPMENT ✓
- **<100%** → NOT READY - FIX REQUIRED ✗

### Example Output

**Ready:**

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

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

Readiness Score: 100% (7/7 critical checks passed, 1 warning)

Status: READY FOR DEVELOPMENT ✓

Next Steps:
  1. Address warnings (optional, recommended)
  2. Review progress tracker: .ralph/progress.txt
  3. Launch development: /ralph-loop
     (Use /ralph-loop -r ONLY to resume an interrupted loop)
═══════════════════════════════════════════════════════════════
```

**Not Ready:**

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

Status: NOT READY FOR DEVELOPMENT ✗

Critical Issues Found:
  ✗ Module status validation: FAIL (1/5 modules incomplete)
    - Reporting module status is "specified", must be "handed-off"
    - Fix: Return to step-05-deploy.md for Reporting module

  ✗ PRD files validation: FAIL (1/5 files invalid)
    - prd-Reporting.json has wrong structure (filesToCreate at root level)
    - Fix: Re-run ss derive-prd --feature {path} --output .ralph/prd-Reporting.json

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

DO NOT PROCEED TO /RALPH-LOOP UNTIL ALL CRITICAL CHECKS PASS
═══════════════════════════════════════════════════════════════
```

---

## Common Patterns & Best Practices

### 1. Fail Fast, Fail Clear

**Principle:** Detect issues as early as possible, provide clear error messages with actionable fixes.

**Example:**
- ✗ BAD: "Validation failed" (vague, no action)
- ✓ GOOD: "Entity 'Task' not found in Projects module. Fix: Create Task entity or remove reference from TimeEntry.taskId"

### 2. Progressive Validation

**Principle:** Validate at each step, not just at the end.

**Checkpoints:**
- Step-03d: Module completeness (before marking "specified")
- Step-04: Cross-module coherence (before marking "consolidated")
- Step-05c: Development readiness (before /ralph-loop)

### 3. Auto-Fix vs. Manual Fix

**Auto-fix (safe):**
- Add missing dependency edges (with warning)
- Auto-correct casing (PascalCase, camelCase)
- Fill default values (e.g., PK = "Id" if not specified)

**Manual fix (requires user decision):**
- Circular dependencies (how to break?)
- Unresolved entity references (create or remove?)
- Permission conflicts (intentional or error?)

### 4. Severity Levels

| Level | Symbol | Meaning | Action |
|-------|--------|---------|--------|
| PASS | ✓ | Check passed | Continue |
| WARNING | ⚠ | Non-blocking issue | Recommend fix, allow continue |
| ERROR | ✗ | Blocking issue | STOP, fix required |

### 5. Display Standards

**Always include in error messages:**
1. **What failed** - Clear identification of the issue
2. **Why it matters** - Impact if not fixed
3. **How to fix** - Specific actionable steps
4. **Where to go** - Which step to return to

**Example:**

```
✗ BLOCKING ERROR: Cross-module reference unresolved

WHAT: TimeTracking.TimeEntry references Projects.Task (NOT FOUND)
WHY: This will cause FK constraint violation in database
HOW TO FIX:
  Option 1: Create "Task" entity in Projects module
  Option 2: Remove reference from TimeEntry (change taskId to projectId)
WHERE: Return to step-03-specify.md for TimeTracking module
```

---

## Troubleshooting Guide

### Issue: Module Fails Specification Checklist

**Symptoms:**
- Module has < minimum required components
- Step-03d validation fails

**Diagnosis:**
1. Check which sections failed (entities, UCs, BRs, wireframes, etc.)
2. Review minimum requirements per section

**Fix:**
1. Add missing components until minimums met
2. Re-run step-03 validation
3. Proceed only when ALL blocking checks pass

---

### Issue: Cross-Module Reference Unresolved

**Symptoms:**
- Step-04 reports "entity not found"
- Cross-module FK references fail validation

**Diagnosis:**
1. Identify source module + entity
2. Identify target module + entity
3. Check if target entity exists in target module

**Fix:**
1. **If target entity missing:**
   - Create target entity in target module
   - OR remove reference from source entity
2. **If target module missing:**
   - Create target module
   - OR remove reference from source entity
3. Re-run step-04 consolidation

---

### Issue: Circular Dependencies Detected

**Symptoms:**
- Step-04 reports "circular dependencies"
- Dependency graph has cycles

**Diagnosis:**
1. Identify cycle path (A → B → C → A)
2. Analyze relationships causing cycle

**Fix:**
1. **Option 1: Create Core module**
   - Move shared entities to new "Core" module
   - Other modules depend on Core (no cycle)
2. **Option 2: Use events instead of FK**
   - Replace direct FK with event-driven communication
   - Breaks dependency link
3. **Option 3: Remove unnecessary dependency**
   - Review if dependency is truly needed
   - Remove if redundant
4. Return to step-02-structure, fix dependency graph
5. Re-run step-03-specify for affected modules
6. Re-run step-04-consolidate

---

### Issue: Ralph Readiness Check Fails

**Symptoms:**
- Step-05c reports readiness score < 100%
- Critical checks failed

**Diagnosis:**
1. Review failed checks in summary
2. Identify missing/invalid artifacts

**Fix:**
- **Module status incomplete:** Return to step-05-deploy for affected module
- **PRD files invalid:** Re-run `ss derive-prd` for affected module
- **Handoff incomplete:** Return to step-05-deploy, complete handoff section
- **Cross-module refs broken:** Return to step-04-consolidate, fix references
- Re-run step-05-deploy after fixes

---

## Metrics & Success Criteria

### Module Specification Checklist

**Target:**
- 100% blocking checks passed
- 0-5 warnings acceptable

**Success:**
- Module marked as "specified"
- Ready for consolidation

### Cross-Module Validation

**Target:**
- 100% references resolved
- 0 circular dependencies

**Success:**
- Application marked as "consolidated"
- Ready for handoff

### Ralph Readiness (Step-05)

**Target:**
- 100% critical checks passed
- Warnings addressed or documented

**Success:**
- Application ready for /ralph-loop
- Development can proceed with full confidence

---

**Last Updated:** 2026-02-08
**Version:** 1.0
**Author:** SmartStack CLI Team
**Based on:** Analysis of BA session 03b76b8b-ea1c-4f1e-a636-bd46b0c33e02
