---
name: step-04-consolidation
description: Cross-module consolidation - interactions, permission coherence, E2E flows, final approval
model: sonnet
next_step: steps/step-05-handoff.md
---

# Step 4: Consolidation

## MANDATORY EXECUTION RULES
- ALWAYS load summaries of ALL completed modules
- NEVER duplicate module content - work with summaries only
- ALWAYS validate permission coherence across modules
- This step auto-validates for single-module (trivial consolidation)
- Final client approval is BLOCKING before handoff

## YOUR TASK
Consolidate all specified modules into a coherent application. Detect cross-module interactions, verify permission coherence, trace E2E flows, and obtain final client approval.

---

## EXECUTION SEQUENCE

### 1. Read Module Summaries

```
ba-reader.getCompletedModulesSummary({feature_id})
→ For each module: code, entities[], key BRs, permissions[], dependencies
→ Max 100 lines per module summary

ba-reader.readApplicationContext({feature_id})
→ cadrage.applicationRoles, modules[], dependencyGraph
```

IF status already "consolidated":
  Display: "Consolidation already completed. Loading next step."
  Load: steps/step-05-handoff.md
  STOP

### 2. Cross-Module Interactions

**2a. Foreign Key References**

For each dependency edge in dependencyGraph:
```json
{
  "from": "Orders",
  "to": "Customers",
  "type": "FK",
  "references": [
    {
      "sourceEntity": "Order",
      "sourceField": "CustomerId",
      "targetEntity": "Customer",
      "targetField": "Id",
      "cardinality": "N:1",
      "cascadeDelete": false,
      "required": true
    }
  ]
}
```

Verify each FK reference exists in the corresponding module's entities.
IF missing → WARNING + ask user to confirm or add.

**2b. Shared Entities**

Detect entities referenced by multiple modules:
```json
{
  "sharedEntities": [
    {
      "entity": "Customer",
      "definedIn": "Customers",
      "referencedBy": ["Orders", "Invoices"],
      "referenceType": "FK"
    }
  ]
}
```

**2c. Event-Based Interactions**

Identify event flows between modules:
```json
{
  "events": [
    {
      "producer": "Orders",
      "event": "OrderApproved",
      "consumers": ["Invoices"],
      "description": "When an order is approved, an invoice is auto-generated"
    }
  ]
}
```

**2d. Shared Reference Data**

Identify shared lookup/reference tables:
```json
{
  "sharedReferenceData": [
    {
      "table": "Currency",
      "usedBy": ["Orders", "Invoices"],
      "owner": "shared"
    }
  ]
}
```

### 3. Permission Coherence

> **All modules MUST use the same application-level roles.**

**3a. Role Consistency**

Verify all modules use the applicationRoles defined in cadrage:
```
FOR each module in completedModules:
  FOR each role in module.specification.permissionMatrix.roles:
    IF role NOT IN cadrage.applicationRoles → ERROR
```

**3b. Permission Path Format**

Verify all permission paths follow the pattern:
`business.{app}.{module}.{resource}.{action}`

Check for:
- Inconsistent app prefix → ERROR
- Missing module segment → ERROR
- Shortcut paths (not full format) → ERROR

**3c. Role Hierarchy Coherence**

Verify the role hierarchy is respected across all modules:
```
Admin ⊃ Manager ⊃ Contributor ⊃ Viewer

FOR each module:
  IF Admin has fewer permissions than Manager → ERROR
  IF Manager has fewer permissions than Contributor → ERROR
  IF Contributor has fewer permissions than Viewer → ERROR
```

**3d. Permission Conflicts**

Detect conflicting permission assignments:
```json
{
  "conflicts": [
    {
      "role": "Manager",
      "module1": "Orders",
      "permission1": "business.sales.orders.approve",
      "module2": "Invoices",
      "permission2": "business.sales.invoices.approve",
      "issue": "Manager can approve orders but not invoices - is this intentional?"
    }
  ]
}
```

Present conflicts to user via AskUserQuestion:
```
question: "Le Manager peut approuver les commandes mais pas les factures. Est-ce intentionnel ?"
header: "Permissions"
options:
  - label: "Oui, intentionnel"
    description: "Les factures nécessitent un niveau d'approbation supérieur"
  - label: "Non, corriger"
    description: "Le Manager devrait aussi pouvoir approuver les factures"
```

### 4. End-to-End Flows

Identify business processes that span multiple modules:

```json
{
  "e2eFlows": [
    {
      "name": "Order to Invoice",
      "steps": [
        { "module": "Customers", "action": "Customer exists", "permission": "customers.read" },
        { "module": "Products", "action": "Products selected", "permission": "products.read" },
        { "module": "Orders", "action": "Order created", "permission": "orders.create" },
        { "module": "Orders", "action": "Order approved", "permission": "orders.approve" },
        { "module": "Invoices", "action": "Invoice generated", "permission": "invoices.create" },
        { "module": "Invoices", "action": "Invoice sent", "permission": "invoices.update" }
      ],
      "actors": ["Contributor (create)", "Manager (approve)"],
      "data": "Customer → Order → OrderLines (Products) → Invoice → InvoiceLines"
    }
  ]
}
```

Display each E2E flow as a diagram:
```
Customer ──[read]──→ Order ──[create]──→ Order ──[approve]──→ Invoice ──[create]──→ Invoice ──[send]──→
  (Customers)         (Orders)            (Orders)              (Invoices)            (Invoices)
  Contributor         Contributor          Manager               System                Manager
```

### 5. Global Risk Assessment

Evaluate application-level risks:

| Risk | Metric | Threshold | Status |
|------|--------|-----------|--------|
| Total entities | {sum across modules} | ≤20 | PASS/WARNING |
| Total BRs | {sum across modules} | ≤50 | PASS/WARNING |
| Cross-module dependencies | {edge count} | ≤10 | PASS/WARNING |
| Shared entities | {count} | ≤5 | PASS/WARNING |
| E2E flow length | {max steps} | ≤8 | PASS/WARNING |
| Permission paths | {total} | ≤100 | PASS/WARNING |

### 6. Consolidation Summary

Display comprehensive summary:
```
═══════════════════════════════════════════════════════════
  CONSOLIDATION - {application_name}
═══════════════════════════════════════════════════════════

### Modules ({count})
| Module | Entités | BRs | UCs | Complexité |
|--------|---------|-----|-----|------------|
{for each module}

### Interactions Cross-Module
- FK References: {count}
- Shared Entities: {count}
- Events: {count}
- Shared Data: {count}

### Permissions
- Roles: {count} (coherent: ✓/✗)
- Total paths: {count}
- Conflicts resolved: {count}

### E2E Flows
{for each flow: name, modules involved, actors}

### Risques Globaux
{risk assessment table}

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

### 7. Final Client Approval (BLOCKING)

Ask via AskUserQuestion:
```
question: "La spécification complète de l'application est prête. Validez-vous l'ensemble ?"
header: "Approbation"
options:
  - label: "Approuvé"
    description: "Passer au handoff pour la phase d'implémentation"
  - label: "Réviser un module"
    description: "Retourner à la spécification d'un module spécifique"
  - label: "Modifier les interactions"
    description: "Ajuster les interactions cross-module"
```

IF "Réviser un module":
  Ask which module → set currentModuleIndex to that module → load step-03-specify.md

IF "Modifier les interactions":
  Re-enter section 2-4 of this step

### 8. Write Consolidation

```
ba-writer.enrichSection({
  featureId: {feature_id},
  section: "consolidation",
  data: {
    crossModuleInteractions: { fkReferences, sharedEntities, events, sharedReferenceData },
    permissionCoherence: { roleConsistency, pathFormat, hierarchy, conflicts, resolved },
    e2eFlows: [...],
    globalRiskAssessment: {...}
  }
})

ba-writer.updateStatus({feature_id}, "consolidated")
```

Add changelog entry:
```json
{
  "step": "step-04-consolidation",
  "timestamp": "...",
  "changes": [
    "Cross-module interactions: X FK, Y events, Z shared entities",
    "Permission coherence: validated ({count} paths, {conflicts} conflicts resolved)",
    "E2E flows: {count} identified",
    "Global risk: {level}",
    "Client approval: APPROVED"
  ]
}
```

---

## SINGLE-MODULE MODE

When only 1 module:
1. Skip cross-module interactions (no other modules)
2. Skip permission coherence check (only one module)
3. Skip E2E flows (single module)
4. Auto-approve (no cross-module concerns)
5. Write minimal consolidation section
6. Display: "Module unique - consolidation automatique ✓"
7. Proceed to step-05-handoff.md

---

## CONTEXT MANAGEMENT

| Loaded | Not Loaded |
|--------|------------|
| _shared.md | Full module feature.json files |
| Module summaries (100 lines each) | Questionnaires |
| Master feature.json | Templates |
| cadrage section | React viewer files |

---

## NEXT STEP

Load: `./step-05-handoff.md`
