# Semantic Validation Checks for Analysis

Complete reference for step-04 semantic validation, permission coherence, and complexity assessment.

## Semantic Validation Checks (13 checks total)

Execute for EACH module in step-04:

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

## Result Storage Format

```json
{
  "check": "permission-orpheline",
  "module": "RepairManagement",
  "status": "PASS|WARNING|ERROR",
  "details": "Permission freebike.repairmanagement.export not referenced by any UC",
  "autoFixed": false
}
```

## Blocking Rules

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

## Complexity Calculation

For each module in index.json modules[], calculate:

```json
{
  "complexity": "simple|medium|complex",
  "complexityDetails": {
    "entities": {count},
    "useCases": {count},
    "businessRules": {count},
    "calculated": "{level} (≤X entities, ≤Y UCs, ≤Z BRs)"
  }
}
```

### Criteria

| Criteria | Simple | Medium | Complex |
|----------|--------|--------|---------|
| Entities | ≤3 | ≤6 | >6 |
| Use Cases | ≤5 | ≤12 | >12 |
| Business Rules | ≤10 | ≤20 | >20 |

**Global complexity** = highest complexity across all modules.

## Permission Coherence Checks

### 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: `{app}.{module}.{action}` (3 segments)
- Section-level: `{app}.{module}.{section}.{action}` (4 segments)

Check for:
- Inconsistent app prefix → ERROR
- Missing module segment → ERROR
- Fewer than 3 segments (shortcut paths) → ERROR
- More than 4 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": "sales.orders.approve",
      "module2": "Invoices",
      "permission2": "sales.invoices.approve",
      "issue": "Manager can approve orders but not invoices - is this intentional?"
    }
  ]
}
```

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

## Global Risk Assessment Metrics

| 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 |

## E2E Flow Template

```json
{
  "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"
}
```

## Single-Module Mode Simplifications

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)
