---
name: step-03-specify
description: Iterative per-module specification - sections, entities, BR, permissions, mockups, validation
model: opus
next_step: steps/step-03-specify.md OR steps/step-04-consolidation.md (conditional)
---

# Step 3: Specification (Iterative Per-Module)

## MANDATORY EXECUTION RULES

- ALWAYS use ULTRATHINK mode
- This step is EXECUTED ONCE PER MODULE in topological dependency order
- ALWAYS check workflow state to determine current module
- ALWAYS reference completed modules when specifying current one
- **MANDATORY:** Generate and validate an ASCII/SVG mockup for EVERY section (not optional)
- ALL questions via AskUserQuestion tool
- ALL communication in `{language}`
- NEVER skip per-module validation
- **WIREFRAME RULE:** Every section MUST have a wireframe in `specification.uiWireframes[]`. No section without a validated mockup.

## YOUR TASK

Specify one module completely: walk through its sections and resources with the client, define entities, business rules, use cases, permissions, mockups, and validate before moving to the next module.

---

## EXECUTION SEQUENCE

### 1. Determine Current Module

```
ba-reader.readApplicationContext({feature_id})
→ Read metadata.workflow: moduleOrder, currentModuleIndex, completedModules
→ currentModule = moduleOrder[currentModuleIndex]
→ Display: "═══ Module {currentModuleIndex + 1}/{moduleOrder.length}: {currentModule} ═══"
```

IF module already specified (status = "specified" in master):
  Increment currentModuleIndex, re-check
  IF all modules specified → Load step-04-consolidation.md, STOP

### 2. Initialize Module Feature.json

```
// Create or load module-level feature.json
ba-writer.create({
  scope: "module",
  applicationRef: {feature_id},
  moduleCode: {currentModule.code},
  path: "docs/business/{app}/{module_code}/business-analyse/v1.0/feature.json"
})

// Inherit application roles from master
ba-reader.readApplicationContext({feature_id})
→ Copy cadrage.applicationRoles → module.applicationContext.applicationRoles
```

Update module status in master: "pending" → "in-progress"

### 3. Section Walkthrough with Client

> **This is the key interactive phase aligned with the 5-level SmartStack hierarchy.**
> Level 3 = Module, Level 4 = Section, Level 5 = Resource

#### 3a. Identify Module Sections

For each module, propose standard sections based on module type:

| Module Type | Typical Sections |
|-------------|-----------------|
| data-centric | list, detail, create, edit |
| workflow | list, detail, create, edit, approve, history |
| integration | list, detail, config, sync, logs |
| reporting | dashboard, detail, export, schedule |
| full-module | list, detail, create, edit, approve, history, reports, settings |

Ask via AskUserQuestion:

```
question: "Quelles sections le module {currentModule} doit-il avoir ?"
header: "Sections"
multiSelect: true
options:
  - label: "Liste"
    description: "Page de liste avec filtres, tri et pagination"
  - label: "Détail"
    description: "Page de détail d'un enregistrement"
  - label: "Création/Édition"
    description: "Formulaire de création et de modification"
  - label: "Validation/Approbation"
    description: "Workflow de validation avec changement de statut"
  - label: "Dashboard"
    description: "Tableau de bord avec KPIs, graphiques (Recharts) et métriques clés"
```

#### 3b. For Each Section: Generate MANDATORY ASCII Mockup

> **BLOCKING RULE:** Every section MUST have a wireframe. No section proceeds to entity definition (step 6) without a validated mockup stored in `specification.uiWireframes[]`.

For each confirmed section, generate an ASCII mockup and validate with client:

Example for a list section:

```
╔═══════════════════════════════════════════════════════════╗
║  {Module} > Liste                                 [+ Nouveau] ║
╠═══════════════════════════════════════════════════════════╣
║  🔍 Rechercher...  │ Statut: [Tous ▾]  │ Date: [Ce mois ▾] ║
╠═══════════════════════════════════════════════════════════╣
║  # │ {Field1}  │ {Field2}    │ {Field3} │ Statut  │ ···  ║
║  1 │ VAL-001   │ Exemple 1   │ 12'500.- │ ● Brouillon │ ⋮ ║
║  2 │ VAL-002   │ Exemple 2   │  8'300.- │ ● Envoyé    │ ⋮ ║
╠═══════════════════════════════════════════════════════════╣
║  1-25 de 142  │  ◀  1  2  3  ···  6  ▶                   ║
╚═══════════════════════════════════════════════════════════╝
```

Store in specification.uiWireframes[] (**MANDATORY** for every section):

```json
{
  "screen": "{module}-{section}",
  "section": "{section}",
  "description": "Description of the screen",
  "mockupFormat": "ascii",
  "mockup": "╔═══...",
  "elements": ["DataGrid", "FilterBar", "Pagination", "CreateButton"],
  "actions": ["filter", "sort", "create", "view-detail"],
  "permissionsRequired": ["business.{app}.{module}.read"]
}
```

> **REQUIRED fields:** `screen`, `mockup`, `elements`, `section` are all mandatory. A wireframe without these fields will FAIL validation in step 9.

Ask client to validate each mockup via AskUserQuestion (batch 2-3 mockups at once if possible).

> **IF client rejects a mockup:** Revise and re-propose until validated. Do NOT proceed without client approval on the layout.

#### 3b-bis. Wireframe-to-Component Mapping

After client validates the mockup, map each wireframe element to a SmartStack React component:

| Wireframe Element | SmartStack Component | Notes |
|-------------------|---------------------|-------|
| DataGrid | `SmartTable` or `EntityCard` grid | Use EntityCard for card layouts |
| FilterBar | `SmartFilter` | Integrated with SmartTable |
| SearchInput | `SearchInput` | Debounced search |
| Pagination | Built into `SmartTable` | Server-side pagination |
| ActionButton | `Button` + `RequirePermission` | Always wrapped in permission check |
| StatusBadge | `StatusBadge` | Uses entity lifecycle states |
| DetailCard | `EntityDetailCard` | Standard detail layout |
| Form | `SmartForm` | FluentValidation-backed |
| KpiCard | `StatCard` (Recharts) | Dashboard KPI display |
| Chart:bar/line/pie | Recharts `BarChart`/`LineChart`/`PieChart` | CSS variables for colors |

Store the component mapping alongside the wireframe to ensure downstream skills use the correct components.

#### 3c. Identify Resources per Section

For each section, identify what resources/components are needed:

- List section → DataGrid, FilterBar, SearchInput, ExportButton
- Detail section → DetailCard, StatusBadge, ActionButtons, Timeline
- Create section → Form, ValidationMessages, SubmitButton
- Approve section → StatusTransitionPanel, CommentBox, ApproveRejectButtons
- Dashboard section → StatCard, RechartsChart (Bar/Line/Pie/Area), DashboardGrid, FilterBar

#### 3d. Dashboard Specification (if section = dashboard)

When a "dashboard" section is selected, capture structured KPI and chart data **in addition** to the standard ASCII mockup.

1. **Ask client for KPIs** via AskUserQuestion (batch):
   - KPI name and metric description
   - Visualization type: `kpi-card`, `bar`, `line`, `pie`, `area`, `donut`, `stacked-bar`
   - Data source entity
   - Format: `number`, `currency`, `percent`, `duration`
   - Thresholds (warning/critical) if applicable

2. **Ask client for filters:**
   - Date range filter? Default period? (day/week/month/quarter/year)
   - Entity-based filters? (status, category, etc.)

3. **Ask client for refresh mode:**
   - Static (load on page open)
   - Polling (periodic refresh)
   - SignalR (real-time push)

4. **Store in specification.dashboards[]:**

```json
{
  "code": "{module}-dashboard",
  "title": "{Module} Dashboard",
  "description": "Vue d'ensemble des métriques {module}",
  "linkedUCs": ["UC-XXX"],
  "refreshMode": "static",
  "defaultPeriod": "month",
  "kpis": [
    {
      "code": "total-items",
      "label": "Total Items",
      "metric": "COUNT(entity)",
      "format": "number",
      "visualization": "kpi-card",
      "dataSource": "Entity"
    },
    {
      "code": "items-by-status",
      "label": "Items by Status",
      "metric": "COUNT(entity) GROUP BY status",
      "format": "number",
      "visualization": "pie",
      "dataSource": "Entity",
      "dimensions": ["status"]
    }
  ],
  "filters": [
    { "field": "dateRange", "type": "dateRange", "label": "Période" },
    { "field": "status", "type": "multiselect", "label": "Statut" }
  ],
  "permissionsRequired": ["business.{app}.{module}.read"]
}
```

5. **ALSO generate the standard ASCII mockup** for the dashboard with KPI cards + chart placeholders:

```
╔═══════════════════════════════════════════════════════════════╗
║  {Module} > Dashboard              Période: [Ce mois ▾]     ║
╠═══════════════════════════════════════════════════════════════╣
║  ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌──────────┐    ║
║  │ KPI #1   │  │ KPI #2   │  │ KPI #3   │  │ KPI #4   │    ║
║  │  1,234   │  │  567     │  │  89.2%   │  │  12,400  │    ║
║  │  ↑ +12%  │  │  ↓ -3%  │  │  → 0%   │  │  ↑ +5%   │    ║
║  └──────────┘  └──────────┘  └──────────┘  └──────────┘    ║
╠═══════════════════════════════════════════════════════════════╣
║  ┌─────────────────────────┐  ┌─────────────────────────┐    ║
║  │  [Bar Chart]            │  │  [Pie Chart]            │    ║
║  │  Items by Month         │  │  Items by Status        │    ║
║  │  ████                   │  │      ████████           │    ║
║  │  ████ ████              │  │   ███      ███          │    ║
║  │  ████ ████ ████         │  │  ██   42%    ██         │    ║
║  └─────────────────────────┘  └─────────────────────────┘    ║
╚═══════════════════════════════════════════════════════════════╝
```

Store the mockup in specification.wireframes[] AS WELL (for visual reference).

### 4. Conditional Questionnaires

Based on module type, load questionnaires per-module:

| Condition | Category | Questionnaire |
|-----------|----------|---------------|
| Always | 04 | `questionnaire/04-data.md` |
| Has UI sections | 07 | `questionnaire/07-ui.md` |
| Has lifecycle | 11 | `questionnaire/11-data-lifecycle.md` |
| Has migration needs | 12 | `questionnaire/12-migration.md` |
| References other modules | 13 | `questionnaire/13-cross-module.md` |
| Documentation needed | 10 | `questionnaire/10-documentation.md` |

Ask via AskUserQuestion, 1-2 batches per category.

#### Store Documentation Requirements

If questionnaire 10 was loaded, persist answers in feature.json:

```
ba-writer.enrichSection({
  featureId: {feature_id},
  section: "documentation",
  data: {
    userDocRequired: {Q10.1 answer == "Yes"},
    techDocRequired: {Q10.2 answer == "Yes"},
    status: "pending"
  }
})
```

This data will be consumed by `/application` step-08 to auto-generate in-app documentation.

### 5. Cross-Module References

> Reference completed modules to help define current one.

```
completedModules = ba-reader.getCompletedModulesSummary({feature_id})
→ Returns max 100 lines summary: entity names, key BRs, permissions

Display: "Modules déjà spécifiés : {completedModules.map(m => m.code).join(', ')}"
```

For each completed module's entities, ask:

```
question: "Le module {currentModule} référence-t-il des entités de {completedModule} ?"
header: "Références"
multiSelect: true
options:
  - label: "{Entity1} (FK)"
    description: "Référence directe via clé étrangère"
  - label: "{Entity2} (Lookup)"
    description: "Table de référence / lookup"
  - label: "Aucune"
    description: "Pas de référence à {completedModule}"
```

### 6. Entity Definition

Define entities for this module (business attributes, not technical):

For each entity:

```json
{
  "name": "PascalCase",
  "description": "1-2 sentences",
  "attributes": [
    { "name": "attributeName", "type": "string|int|decimal|datetime|enum|FK", "required": true/false, "rules": "validation description" }
  ],
  "relationships": [
    { "target": "OtherEntity", "type": "1:N", "description": "description" }
  ]
}
```

### 7. Business Rules Extraction

Extract business rules specific to this module:

Format: BR-{CATEGORY}-NNN where CATEGORY is VAL/CALC/WF/SEC/DATA

```json
{
  "id": "BR-VAL-001",
  "rule": "Description of the rule",
  "category": "Validation",
  "priority": "Must",
  "condition": "When X happens",
  "action": "Then Y must be true",
  "examples": [{ "input": "...", "expected": "..." }],
  "linkedRules": ["BR-WF-002"]
}
```

### 8. Full Specification

Generate the complete specification for this module:

#### 8a. Actors

Inherited from application roles → mapped to module permissions

#### 8b. Use Cases (UC-NNN)

Per section: list, create, read, update, delete, approve, etc.

#### 8c. Functional Requirements (FR-NNN)

Linked to BRs and UCs

#### 8d. Permission Matrix

Roles × resources × operations with full paths: `business.{app}.{module}.{resource}.{action}`

#### 8e. Navigation

Module → Sections → Resources (levels 3-4-5 of the hierarchy)

#### 8f. SeedData Core

5 mandatory files:

1. NavigationModuleConfiguration (from navigation entries)
2. NavigationTranslationConfiguration (4 languages)
3. PermissionConfiguration (full path format)
4. RolePermissionConfiguration (role → permission mapping)
5. Permissions.cs constants (PascalCase)

#### 8g. Gherkin Scenarios

BDD acceptance tests per UC

#### 8h. Validations

Field validation rules

#### 8i. Business Messages

Minimum 4: success, error CRUD, error validation, error permission

#### 8j. Entity Lifecycle

State machines for entities with status/state

#### 8k. API Endpoints

RESTful routes following SmartStack patterns

#### 8l. i18n Keys

Translation keys for all UI text (4 languages: fr, en, it, de)

### 9. Per-Module Validation

> **Fused from old step-03-validate.md, run INLINE after specification.**

#### 9a. Completeness Checks

| Section | Minimum | Status |
|---------|---------|--------|
| actors | 2 | PASS/FAIL |
| useCases | 2 | PASS/FAIL |
| functionalRequirements | 4 | PASS/FAIL |
| permissionMatrix | 1 resource × 2 roles | PASS/FAIL |
| entities | 1 | PASS/FAIL |
| wireframes | 1 per section (BLOCKING) | PASS/FAIL |
| gherkinScenarios | 2 per UC | PASS/FAIL |
| validations | 1 | PASS/FAIL |
| messages | 4 | PASS/FAIL |
| lifeCycles | 1 (if entity has status) | PASS/FAIL |
| seedDataCore | 5 sections present | PASS/FAIL (BLOCKING) |

#### 9b. Consistency Checks

- Every UC has ≥1 linked FR
- Every FR has ≥1 linked BR
- All BR references exist in analysis.businessRules
- All actors appear in permissionMatrix
- Permission paths use full format: `business.{app}.{module}.{resource}.{action}`
- rolePermissions paths match permissions paths
- API routes use consistent prefix

#### 9c. Convention Checks

- UC-NNN format
- FR-NNN format
- BR-{CATEGORY}-NNN format
- Entity names PascalCase
- Field names camelCase
- Permission paths dot-separated lowercase

#### 9d. Decision

IF validation PASS:
  Display summary, ask client for confirmation

IF validation FAIL:
  Display errors, offer:
  ```
  options:
    - label: "Auto-corriger"
      description: "Corriger automatiquement les erreurs détectées"
    - label: "Réviser manuellement"
      description: "Revenir aux sections problématiques"
    - label: "Forcer la validation"
      description: "Accepter malgré les erreurs (risqué)"
  ```

### 10. Module Summary with Roles & Permissions

Display comprehensive summary:

```
═══════════════════════════════════════════════════════════
  MODULE SPÉCIFIÉ: {currentModule} ({currentModuleIndex + 1}/{total})
═══════════════════════════════════════════════════════════

| Aspect | Valeur |
|--------|--------|
| Entités | {count} ({entity names}) |
| Business Rules | {count} (VAL: X, CALC: Y, WF: Z) |
| Use Cases | {count} (UC-001 → UC-NNN) |
| Exigences | {count} FRs |
| Sections | {count} ({section names}) |
| Maquettes | {count} wireframes |
| Permissions | {count} paths |
| Tests Gherkin | {count} scénarios |
| Messages | {count} |

### Rôles & Permissions pour {currentModule}
| Rôle | Permissions |
|------|------------|
| {App} Admin | business.{app}.{module}.* |
| {App} Manager | read, create, update, assign |
| {App} Contributor | read, create, update |
| {App} Viewer | read |

→ Validation: {PASS/FAIL}
═══════════════════════════════════════════════════════════
```

Ask via AskUserQuestion:

```
question: "Le module {currentModule} est-il correctement spécifié ?"
header: "Module"
options:
  - label: "Validé"
    description: "Passer au module suivant"
  - label: "Réviser"
    description: "Modifier des éléments du module"
```

### 11. Write Module Feature.json

```
ba-writer.enrichSection({
  featureId: {module_feature_id},
  section: "specification",
  data: { ...all specification sections... }
})

ba-writer.enrichSection({
  featureId: {module_feature_id},
  section: "analysis",
  data: { entities, businessRules, processFlow }
})

ba-writer.updateStatus({module_feature_id}, "specified")

// Update master
ba-writer.updateModuleStatus({feature_id}, {currentModule.code}, "specified")
```

### 12. Loop Decision

```
ba-writer.advanceModuleLoop({feature_id})
→ Increments currentModuleIndex
→ Updates completedModules
→ Updates currentModule

IF currentModuleIndex < moduleOrder.length:
  Display: "→ Module suivant: {nextModule} ({currentModuleIndex + 1}/{total})"
  Load: steps/step-03-specify.md (RE-ENTER this step)

IF currentModuleIndex >= moduleOrder.length:
  Display: "═══ Tous les modules spécifiés! Passage à la consolidation... ═══"
  ba-writer.updateStatus({feature_id}, "specified")
  Load: steps/step-04-consolidation.md
```

---

## SINGLE-MODULE MODE

When only 1 module in moduleOrder:

- Same full specification flow
- Skip cross-module references (section 5)
- After validation → direct to step-04-consolidation.md (auto-consolidation)

---

## RESUME SUPPORT

IF the step is resumed (e.g., after interruption):

```
Read metadata.workflow.currentModuleIndex
Read metadata.workflow.currentModule
→ Resume at the correct module
→ If module has partial data, show what exists and continue from there
```

---

## CONTEXT MANAGEMENT

| Loaded | Not Loaded |
|--------|------------|
| _shared.md | Other module feature.json (full) |
| feature-schema.json | Questionnaires not needed |
| Questionnaires for this module | Templates |
| Completed modules summary (100 lines max) | React viewer files |

---

## STATE VARIABLES

| Variable | Description |
|----------|-------------|
| `{currentModule}` | Current module being specified |
| `{currentModuleIndex}` | Index in moduleOrder |
| `{completedModules}` | Array of already specified module codes |
| `{module_feature_id}` | Feature ID for the module-level feature.json |

---

## SUCCESS METRICS

- All sections walked through with client
- ASCII mockups generated and validated for EVERY section (1 wireframe per section minimum)
- Entities defined with business attributes
- Business rules extracted and categorized
- Per-module validation PASS
- Client confirmed module specification
- Module feature.json written
- Master updated with module status
- Loop advanced correctly

## FAILURE MODES

- Validation FAIL → offer auto-correct / manual revise / force
- Client rejects → revise specific sections
- Cross-module reference error → clarify with client
- Interruption → resumable via workflow state

---

## NEXT STEP

Conditional:

- IF modules remaining → Re-load `./step-03-specify.md`
- IF all modules done → Load `./step-04-consolidation.md`
