---
name: step-03b-ui
description: Per-module specification - state machines, wireframes, layouts, dashboards (UI & visualization phase)
model: opus
next_step: steps/step-03c-compile.md
---

> **Context files:** `_shared.md` | `_module-loop.md`

# Step 3b: Specification - UI & Visualization

## MANDATORY EXECUTION RULES

- ALWAYS use ULTRATHINK mode
- This step is EXECUTED ONCE PER MODULE, after step-03a1-setup.md and step-03a2-analysis.md
- **WIREFRAME RULE:** Every section MUST have a wireframe in `specification.uiWireframes[]`. No section without a validated mockup.

## MODE DETECTION (inherited from step-03a1)

> **CRITICAL: Re-check your execution mode before proceeding.**

**IF you are running as a TEAM AGENT** (your prompt contains `PROPOSE & REVIEW` or `team-lead` as recipient):
  → **NEVER** use `AskUserQuestion` — replace ALL wireframe validations with ULTRATHINK self-review
  → Generate wireframes autonomously, self-validate them, move on
  → Do NOT ask the user to validate mockups — the team lead handles review after PROPOSAL_READY

**IF you are running in the MAIN CONVERSATION** (classic inline mode):
  → Normal interactive mode — display wireframes then ask for validation via `AskUserQuestion`
- **ID NAMING RULE (MANDATORY, NO EXCEPTION):**
  All IDs MUST include a module prefix to guarantee application-wide uniqueness.
  The prefix is derived from the module code initials (2-4 chars):
    UserManagement → UM | VehicleManagement → VM | PartsInventory → PI
    RepairManagement → RM | MaintenanceSchedule → MS | DataSync → DS
    Notifications → NT | Dashboard → DB | Orders → OR | Customers → CU

  Patterns:
    UC-{PREFIX}-{NNN}        → UC-RM-001, UC-PI-003
    BR-{CAT}-{PREFIX}-{NNN}  → BR-VAL-RM-001, BR-CALC-PI-002
    FR-{PREFIX}-{NNN}        → FR-RM-001
    OBJ-{PREFIX}-{NNN}       → OBJ-RM-001
    AC-{PREFIX}-{NNN}        → AC-RM-001
    RISK-{PREFIX}-{NNN}      → RISK-RM-001

  NEVER use bare IDs (UC-001, BR-VAL-001) in multi-module mode.
- **SCHEMA CONFORMITY RULE:**
  ALL data MUST fit within the defined feature-schema.json structure.
  NEVER create custom top-level fields (KPIDefinitions, ChartConfigurations, etc.)
  Dashboard modules MUST use specification.dashboards[] (it exists in the schema).
  If truly needed, use specification.extensions: {} (additionalProperties: true).

## YOUR TASK

Define the UI layer for the current module: state machines for entities with status fields, wireframes for every section, component mapping, structural layouts, and dashboards.

---

## EXECUTION SEQUENCE

### 3a-state. Define Entity State Machine (Full Depth)

> **For full depth modules with entities that have a status/enum field, define the complete state machine.**
> **This drives conditional actions, badges, and transition effects throughout the UI.**

For each entity with a status-like attribute:

1. **Identify states** from the enum values or business rules:
```
Ask client: "Quels sont les états possibles pour {Entity}.{statusField} ?"
```

2. **Define transitions** - for each state, ask:
```
Ask client: "Depuis l'état {state}, quelles transitions sont possibles ?"
```

3. **For each transition**, capture:
   - `action`: verb label (submit, approve, reject, cancel, archive)
   - `permission`: which permission is required
   - `guards`: which BR must pass (reference existing BR-XXX from analysis)
   - `effects`: what happens after (notification, email, field update)
   - `confirm`: does the user need to confirm?

4. **Assign colors** to states for badge rendering:
   - Draft/New → gray
   - In Progress/Submitted → blue
   - Approved/Active → green
   - Warning/Pending → yellow
   - Error/Rejected → red
   - Archived/Cancelled → purple

5. **Store** in `specification.lifeCycles[]`:
```json
{
  "entity": "{Entity}",
  "field": "status",
  "initialState": "{firstState}",
  "states": [
    { "id": "draft", "displayName": "Brouillon", "color": "gray", "allowedTransitions": ["submitted"], "isTerminal": false }
  ],
  "transitions": [
    {
      "from": "draft", "to": "submitted", "action": "submit",
      "permission": "{app}.{module}.submit",
      "guards": ["BR-VAL-{PREFIX}-001"],
      "effects": [{ "type": "notification", "target": "role:manager", "template": "{module}-submitted" }],
      "confirm": true
    }
  ]
}
```

6. **Cross-validate:** Every `allowedTransitions` entry must have a matching `transitions[]` entry.

### 3a-bis. Structure Sections with Resources (Levels 4 & 5)

> **DEPTH GATE:** Execute this section for **full** depth, or for individual sections flagged for customization in **override** depth. For **convention** depth, sections are auto-generated by 3a-infer — skip to 3b.

For EACH section confirmed in 3a, build the `specification.sections[]` structure:

1. For each resource in the section, determine:
   - The SmartStack component type (SmartTable, SmartForm, DetailCard, KpiPanel, Chart, Map, Timeline, etc.)
   - The entity it operates on
   - Columns/fields based on entity attributes
   - Permission (inherit from section or more specific)
   - Available actions

2. Link use cases to sections:
   - Each UC MUST belong to exactly ONE section
   - Map UC to section based on the primary action (list → UC-XX-001, create → UC-XX-003, etc.)

3. Link business rules to sections:
   - Each BR can belong to one or more sections
   - Map BR based on where it's enforced (validation BR → create/edit section, calc BR → detail section)

4. Build the section object:

See [references/ui-resource-cards.md](../references/ui-resource-cards.md) for exact JSON formats of `specification.sections[]` (SmartTable + SmartForm resources).
**MANDATORY for SmartTable:** `columnDefs`, `rowActions`, `defaultSort`, `emptyState`
**MANDATORY for SmartForm:** `fields` with `component` type, `formLayout`
**FORM FIELD COMPLETENESS RULE:** SmartForm `fields[]` MUST include ALL entity attributes EXCEPT system/audit fields (Id, CreatedAt, CreatedBy, ModifiedAt, ModifiedBy, IsDeleted, TenantId). Missing fields = incomplete form = FAIL.

5. Write `specification.sections[]` via ba-writer.enrichSection()

**VALIDATION:** Every UC must appear in exactly one section.useCases[]. No orphan UCs.

### 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[]`.
> **HTML INTEGRATION:** These wireframes are also rendered in the interactive HTML document (`ba-interactive.html`) deployed at handoff. The client can review and annotate mockups directly in their browser.

**Procedural sequence (MANDATORY — follow in exact order):**

1. **Generate** an ASCII mockup for each confirmed section
2. **Display** each mockup in the conversation output with a markdown header:
   ```
   ### {SectionName} — Wireframe
   ```
   followed by the ASCII art in a code block. **ALL mockups MUST be visible text in the conversation.**
3. **Only THEN** call `AskUserQuestion` to ask the client to validate the displayed mockups (batch 2-3 at once if possible)

> **BLOCKING RULE:** You MUST NOT call AskUserQuestion for wireframe validation until ALL mockups are displayed as visible text in the conversation. The client cannot validate what they cannot see.

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

See [references/ui-resource-cards.md](../references/ui-resource-cards.md) for exact JSON format of `specification.uiWireframes[]`.
**REQUIRED fields:** `screen`, `mockup`, `mockupFormat`, `elements`, `section`, `actions`, `componentMapping`, `layout`, `permissionsRequired` are ALL mandatory.
A wireframe without `componentMapping` or `layout` will FAIL validation in step 9.

> **STRUCTURE CARD: specification.uiWireframes[]** — ALL fields are MANDATORY. Do NOT omit any.
> ```json
> {
>   "screen": "{module}-{section}",                // MANDATORY — unique screen ID (NOT "name" or "id")
>   "section": "list|detail|create|approve|...",   // MANDATORY — section code
>   "description": "Description en français",
>   "mockupFormat": "ascii",                       // MANDATORY — "ascii" or "svg"
>   "mockup": "┌───...┘",                         // MANDATORY — ASCII art string
>   "elements": [                                  // MANDATORY — array of element objects
>     { "id": "elem-grid", "type": "SmartTable", "label": "Grille" }
>   ],
>   "actions": [                                   // MANDATORY — user interactions
>     { "trigger": "Click row", "action": "Navigate to detail" }
>   ],
>   "componentMapping": [                          // MANDATORY — array of mapping objects
>     { "wireframeElement": "DataGrid", "reactComponent": "SmartTable" }
>   ],
>   "layout": {                                    // MANDATORY — object with regions (NOT a string)
>     "type": "page",
>     "regions": [{ "id": "main", "position": "main", "span": 12, "components": [...] }]
>   },
>   "permissionsRequired": ["read"]                // MANDATORY — required permissions
> }
> ```
> **FORBIDDEN FORMAT:** wireframe with only `name` + `mockup` + `layout: "grid"` (string).
> Every wireframe MUST have ALL fields above. Missing metadata causes empty frames in the HTML documentation.
>
> **FORBIDDEN FIELD NAMES (will cause EMPTY wireframes in HTML):**
> - `"ascii"` → use `"mockup"` (the HTML deploy maps `mockup` → `content`)
> - `"title"` → use `"screen"` (the HTML deploy maps `screen` → `screen`)
> - `"content"` → use `"mockup"` (source field must be `mockup`, `content` is the HTML-side name)
> - `"name"` → use `"screen"` (source field must be `screen`, `name` is a fallback only)
> The agent MUST write wireframes using the EXACT field names in the STRUCTURE CARD above.

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

### 3b-detail. Generate Detail Page Wireframe (MANDATORY for each list section)

> **BLOCKING RULE:** Every module with a `list` section MUST also have a detail page wireframe. The detail page is NOT a separate navigation entry — it is reached by clicking a row in the list. Its wireframe goes in `specification.uiWireframes[]` with `section: "detail"`.

**Procedural sequence (MANDATORY):**

1. **Determine detail tabs** from these sources (in priority order):
   a. `coverageMatrix[].detailTabs` from cadrage (if specified)
   b. Entity relationships: one tab per 1:N relationship (SmartTable of children)
   c. Auto-inferred: Info tab (always first), History tab (if entity has lifeCycles)

2. **Generate** an ASCII mockup for the detail page with tabbed layout:

```
╔═══════════════════════════════════════════════════════════╗
║  ← Retour à la liste                                     ║
╠═══════════════════════════════════════════════════════════╣
║  {Entity} : {code} — {name}          ● {Statut}  [✏️ 🗑️] ║
╠═══════════════════════════════════════════════════════════╣
║  [ Informations ]  [ {Relation1} ]  [ Historique ]        ║
╠═══════════════════════════════════════════════════════════╣
║                                                           ║
║  ┌── Informations ────────────────────────────────────┐   ║
║  │  Code         │ VAL-001                            │   ║
║  │  Nom          │ Exemple de nom                     │   ║
║  │  Type         │ Standard                           │   ║
║  │  Responsable  │ Jean Dupont                        │   ║
║  │  Date début   │ 15.01.2026                         │   ║
║  │  Description  │ Lorem ipsum dolor sit amet...      │   ║
║  └────────────────────────────────────────────────────┘   ║
║                                          [ Modifier ]     ║
║                                                           ║
╚═══════════════════════════════════════════════════════════╝
```

Adaptation rules for the detail mockup:
- **Header**: entity code + name + status badge (if lifeCycles) + action buttons (edit, delete)
- **Back button**: navigates to `/{app}/{module}`
- **Tabs**: one per identified tab (Info + relations + history)
- **Info tab content**: all entity attributes as label:value pairs (read-only by default)
- **Edit button**: toggles the Info tab into SmartForm edit mode
- **Relation tab content**: show a SmartTable for each 1:N child entity filtered by parent ID
- **History tab content**: Timeline/audit log (only if entity has lifeCycles)

3. **For entities with state machine (lifeCycles)**, add transition buttons in the header:
```
║  {Entity}: {code} — {name}    ● Brouillon  [Soumettre] [✏️] ║
```
Transition buttons are contextual: only show actions allowed from the current state.

4. **Display** the detail mockup in conversation with header `### {Module} — Détail — Wireframe` and validate with client alongside the list wireframe.

5. **Store** in `specification.uiWireframes[]` with `section: "detail"`.
   See [references/ui-resource-cards.md](../references/ui-resource-cards.md) "Detail Page Wireframe" for exact JSON format.

6. **Create the detail section** in `specification.sections[]` with `navigation: "hidden"` and route `/{app}/{module}/:id`.
   See [references/ui-resource-cards.md](../references/ui-resource-cards.md) "Detail Page section" for exact JSON format.

### 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 |
| DetailHeader | `EntityDetailHeader` | Entity title + status badge + actions |
| BackButton | `BackButton` | Navigate back to list |
| TabPanel | `Tabs` | Tabbed content container |
| Timeline | `AuditTimeline` | History/audit log display |
| 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.

### 3b-ter. Generate Structural Layout

For EACH wireframe generated in 3b, generate a `layout` object alongside the ASCII mockup:

1. From the ASCII mockup, extract the visual regions (header, toolbar, main content, sidebar, etc.)
2. For each region, map the visual elements to SmartStack component types
3. Build the layout structure:
```json
{
  "type": "page",
  "regions": [
    { "id": "toolbar", "position": "top", "components": [
      { "type": "FilterBar", "resourceRef": "{module}-filters" },
      { "type": "ActionMenu", "resourceRef": "{module}-actions", "permission": "{app}.{module}.create" }
    ]},
    { "id": "content", "position": "main", "span": 12, "components": [
      { "type": "SmartTable", "resourceRef": "{module}-grid" }
    ]}
  ]
}
```
4. Cross-validate: each component in layout.regions[].components[] MUST have a corresponding resource in sections[].resources[]
5. Write layout alongside mockup in uiWireframes[]

**RULE:** The layout is the source of truth for ralph-loop. The mockup is for human validation only.

### 3c. Identify Resources per Section

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

- List section → DataGrid, FilterBar, SearchInput, ExportButton, CreateButton
- Detail page (from list click) → BackButton, DetailHeader, StatusBadge, TabPanel, DetailCard, SmartForm (edit mode), SmartTable (relation tabs), Timeline (history tab)
- Create page (`/create` route) → SmartForm (full page), ValidationMessages, SubmitButton, BackButton
- Edit page (`/:id/edit` route) → SmartForm (full page, pre-filled), ValidationMessages, SubmitButton, BackButton
- Approve section → StatusTransitionPanel, CommentBox, ApproveRejectButtons
- Dashboard section → StatCard, RechartsChart (Bar/Line/Pie/Area), DashboardGrid, FilterBar

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

See [references/ui-dashboard-spec.md](../references/ui-dashboard-spec.md) for the complete dashboard capture process:
- Ask client for KPIs (name, visualization type, format, thresholds)
- Ask client for filters (date range, entity-based)
- Ask client for refresh mode (static/polling/SignalR)
- Store in `specification.dashboards[]` with full JSON template
- Generate standard ASCII mockup with KPI cards + chart placeholders

---

## SELF-VERIFICATION (MANDATORY before loading step-03c-compile)

Before proceeding to step-03c-compile.md, VERIFY:

1. **Wireframes displayed and validated** — ALL wireframes (list AND detail) were output as visible ASCII art in the conversation AND validated by the client via AskUserQuestion
2. **Wireframes exist for all sections** in `specification.uiWireframes[]` — INCLUDING a `section: "detail"` wireframe for every module that has a `list` section
2b. **Detail page companion check (BLOCKING)** — For EACH section with `code: "list"`, verify there is a matching wireframe with `section: "detail"` AND a section with `code: "detail"` + `navigation: "hidden"` + route containing `:id`. Missing detail page = FAIL.
3. **All wireframes have componentMapping** with smarter mapping rules
4. **All wireframes have layout** with regions and resourceRef references
5. **All resource references** in layout.regions[].components[].resourceRef exist in sections[].resources[]
6. **State machines defined** (if module has status fields) in `specification.lifeCycles[]`
7. **Form field completeness** — SmartForm fields[] covers ALL entity attributes except system/audit fields
8. **Navigation entries for all sections** — Every section (including dashboard) has a corresponding entry in `specification.navigation.entries[]`
9. **Wireframe structural compliance (BLOCKING)** — ALL wireframes have: `screen` (not just `name`), `section`, `mockupFormat`, `elements[]` (non-empty array of objects), `actions[]`, `componentMapping[]` (array of {wireframeElement, reactComponent}), `layout` (object with regions, NOT a string), `permissionsRequired[]`
   Quick check: `uiWireframes.every(wf => wf.screen && wf.section && wf.mockupFormat && Array.isArray(wf.elements) && wf.elements.length > 0 && typeof wf.layout === 'object' && wf.layout !== null)`
   IF any wireframe fails → FIX before proceeding. DO NOT load step-03c with degraded wireframes.

**IF any check fails → FIX before proceeding.** Do NOT load step-03c-compile with incomplete data.

---

### INTERMEDIATE WRITE: Persist Wireframes Immediately (MANDATORY)

> **WHY:** Wireframes exist only in conversation memory between step-03b and step-03d section 11.
> If the context is truncated (token limit, long conversation), wireframes are LOST forever.
> By writing them NOW, we guarantee persistence regardless of context management.

After SELF-VERIFICATION passes, persist wireframes to the module feature.json:

```
ba-writer.enrichSection({
  featureId: {module_feature_id},
  section: "specification.uiWireframes",
  data: {uiWireframes array from memory}
})
```

> **NOTE:** step-03d section 11 will do a FULL write of all specification data.
> This intermediate write ensures wireframes survive context truncation.
> step-03d will OVERWRITE this with the complete data — no conflict.

### POST-CHECK: Wireframe Persistence Verification (BLOCKING)

> **This check runs AFTER the intermediate write to verify wireframes are actually persisted.**
> It reads the REAL file on disk — not in-memory data the model "thinks" it wrote.

```bash
MODULE_JSON="{module_feature_json_path}"
node -e "
const fs = require('fs');
const data = JSON.parse(fs.readFileSync(process.argv[1], 'utf-8'));
const spec = data.specification || {};
const wf = spec.uiWireframes || spec.wireframes || [];
const sections = spec.sections || [];
console.log('WIREFRAMES: ' + wf.length);
console.log('SECTIONS: ' + sections.length);
if (wf.length === 0) { console.error('BLOCKING: 0 wireframes found in feature.json'); process.exit(1); }
if (wf.length < sections.length) { console.error('BLOCKING: ' + wf.length + ' wireframes < ' + sections.length + ' sections'); process.exit(1); }
const empty = wf.filter(w => !w.mockup && !w.ascii && !w.content);
if (empty.length > 0) { console.error('BLOCKING: ' + empty.length + ' wireframes have EMPTY mockup content'); process.exit(1); }
const badFields = wf.filter(w => !w.screen || w.title || w.ascii);
if (badFields.length > 0) { console.error('WARNING: ' + badFields.length + ' wireframes use forbidden field names (title/ascii) — auto-fix needed'); }
console.log('PASS: All ' + wf.length + ' wireframes present with content');
" "$MODULE_JSON"
```

IF this check FAILS:
- Re-read the wireframes from conversation context (they were displayed as ASCII art)
- Re-write them to feature.json using ba-writer with correct field names (`screen`, `mockup`, `mockupFormat`)
- Re-run the POST-CHECK until PASS

---

## NEXT STEP

Load: `steps/step-03c-compile.md`
