---
name: step-04b-analyze
description: Analyze permission coherence, semantic validation, E2E flows, and global risks
model: opus
next_step: steps/step-04c-decide.md
---

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

# Step 4b: Analyze - Permission Coherence & Validation

## MANDATORY EXECUTION RULES
- ALWAYS validate permission coherence across modules
- ALWAYS execute semantic validation checks
- E2E flows are OPTIONAL (informational only)

## YOUR TASK
Validate permission coherence, execute semantic checks, identify E2E business flows, and assess global application risks.

---

## EXECUTION SEQUENCE

### 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 one of these patterns:
- Module-level: `business.{app}.{module}.{action}` (4 segments)
- Section-level: `business.{app}.{module}.{section}.{action}` (5 segments)

Check for:
- Inconsistent app prefix → ERROR
- Missing module segment → ERROR
- Fewer than 4 segments (shortcut paths) → ERROR
- More than 5 segments → 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"
```

**3e. Permission-Role Coherence Across Modules (WARNING)**

For each role defined in `cadrage.applicationRoles`, verify the permission PATTERN is consistent across ALL modules:

```javascript
// Build role-to-actions matrix per module
const roleActions = {};
for (const module of completedModules) {
  const pm = module.specification.permissionMatrix;
  for (const ra of pm.roleAssignments || []) {
    const key = ra.role;
    if (!roleActions[key]) roleActions[key] = {};
    roleActions[key][module.code] = ra.permissions.map(p => p.split('.').pop()); // extract action
  }
}

// Detect inconsistencies: role has action X in module A but not in module B
for (const [role, modules] of Object.entries(roleActions)) {
  const allActions = new Set(Object.values(modules).flat());
  for (const [mod, actions] of Object.entries(modules)) {
    for (const action of allActions) {
      if (!actions.includes(action)) {
        // Role has this action in other modules but NOT in this one
        const otherMods = Object.entries(modules).filter(([m, a]) => a.includes(action)).map(([m]) => m);
        console.warn(`WARNING: permission-role-coherence: ${role} has "${action}" in [${otherMods.join(', ')}] but NOT in ${mod}`);
      }
    }
  }
}
```

Store as semantic check with severity WARNING (not ERROR — some permission differences may be intentional):
```json
{
  "check": "permission-role-coherence",
  "status": "WARNING",
  "details": "Contributor has 'create' in [Projects, TimeManagement] but NOT in Employees — verify if intentional"
}
```

### 4. Semantic Validation (MANDATORY)

For EACH module feature.json, execute these checks:

| # | Check | Rule | Severity |
|---|-------|------|----------|
| 1 | Permission orpheline | Every permissionMatrix.permissions[].path is used by at least one useCases[].permission | WARNING |
| 2 | UC sans FR | Every useCases[].id is referenced by at least one functionalRequirements[].linkedUseCases[] | WARNING |
| 3 | Entity sans endpoint | Every entities[].name has at least one endpoint in apiEndpoints[] | WARNING |
| 4 | UC sans scenario | Every useCases[].mainScenario has at least 2 steps | WARNING |
| 5 | Role sans permissions | Every applicationRole has at least one entry in roleAssignments[] | WARNING |
| 6 | Navigation sans traduction | Every navigation.entries[].code has translations in 4 languages in seedDataCore.navigationTranslations[] | ERROR |
| 7 | LifeCycle terminal | Every lifeCycles[].states[] has at least one state with isTerminal: true | WARNING |
| 8 | Schema conformity | No custom fields outside defined schema (no KPIDefinitions, ChartConfigurations, etc.) | ERROR |
| 9 | Wireframe coverage | Every navigation section has a corresponding uiWireframes[].screen | ERROR |
| 10 | Doublon entity | No entity with same name in two different modules (unless shared via dependencyGraph) | ERROR |
| 11 | Permission fantome | Every action used in applicationRoles pattern (read, create, update, delete, assign, export, approve) MUST exist as a permission path in permissionMatrix.permissions[].action for at least one module | ERROR |
| 12 | Dashboard coverage | If cadrage mentions dashboard for a module OR navigation includes "dashboard" section, then specification.dashboards[] MUST NOT be empty | WARNING |
| 13 | Permission-UC alignment | Every permission.action (except "read" and wildcard "*") MUST have at least one UC where that permission is referenced in useCases[].permission | WARNING |

Store results in consolidation.semanticChecks[]:
```json
{
  "check": "permission-orpheline",
  "module": "RepairManagement",
  "status": "PASS|WARNING|ERROR",
  "details": "Permission business.freebike.repairmanagement.export not referenced by any UC",
  "autoFixed": false
}
```

**Blocking rule:**
- 0 ERROR → PASS
- ≥1 ERROR → BLOCK (fix before handoff, ask user for each)
- WARNING only → PASS with user notification

### 4-bis. Structural Schema Conformity Check (MANDATORY)

> **Post-generation validation.** After semantic checks, verify ALL module feature.json files conform to JSON schema.

See [references/consolidation-structural-checks.md](../references/consolidation-structural-checks.md) for the full 6-category structural check:
- **A.** Required Sections Presence (18 sections)
- **B.** Field Name Conformity (forbidden vs correct fields)
- **C.** ID Pattern Conformity (BR, UC, FR, Permissions)
- **D.** Cross-Module ID Uniqueness
- **E.** Wireframe Layout Completeness
- **F.** SeedDataCore Translation Coverage

**Blocking rule:** 0 ERROR → PASS. ≥1 ERROR → BLOCK (attempt auto-fix, re-write, re-check).

### 5. 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
```

### 6. 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 |

### 7. 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}

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

---

## SINGLE-MODULE MODE

When only 1 module:
1. Skip permission coherence check (only one module)
2. Skip E2E flows (single module)
3. Execute semantic validation (still required)
4. Auto-approve global risks (no cross-module complexity)

---

## CONTEXT MANAGEMENT

| Loaded | Not Loaded |
|--------|------------|
| _shared.md | Full module feature.json files |
| Module summaries | Questionnaires |
| consolidation section (from step-04a) | Templates |

---

## NEXT STEP

Load: `./step-04c-decide.md`
