---
name: step-03a1-setup
description: Module setup, sections walkthrough, questionnaires, and cross-module references
model: opus
next_step: steps/step-03a2-analysis.md
---

> **Context files:** `_shared.md` | `_elicitation.md` | `_architecture.md` | `_module-loop.md`
> **Reference (5-bis):** `references/entity-architecture-decision.md` — Entity scoring, domain coherence, section patterns

# Step 3a1: Setup - Module Initialization

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

## MODE DETECTION

**Check your execution context before proceeding:**

**IF you are running as a TEAM AGENT** (you received a module-specifier prompt from `references/agent-module-prompt.md`):
  → You are in **AUTONOMOUS mode** (Propose & Review)
  → Do NOT use `AskUserQuestion` — you PROPOSE, the team lead handles user interaction
  → Replace ALL `AskUserQuestion` calls with **ULTRATHINK autonomous decisions**
  → Use the decomposition data + completed module summaries to make informed choices
  → After completing all steps (03a1 → 03a2 → 03b → 03c → 03d): send `PROPOSAL_READY` to team lead
  → See `references/agent-module-prompt.md` for autonomous decision rules
  → See `references/team-orchestration.md` § 3 for communication protocol

**IF you are running in the MAIN CONVERSATION** (classic inline mode):
  → Normal interactive mode — use `AskUserQuestion` as documented below
  → No `SendMessage` calls needed

**How to detect:** If your prompt contains `PROPOSE & REVIEW` or `team-lead` as recipient, you are a team agent.

---

## YOUR TASK

Specify one module's data model and business logic: walk through sections, define entities, business rules, and validate with client before proceeding to UI specification.

---

## 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-04a-collect.md, STOP

### 1b. Cache Warming for Module Loop (FIRST MODULE ONLY)

> **Performance Optimization:** Pre-load module specification references to reduce redundant reads across all modules.
> This step runs ONLY for the FIRST module (currentModuleIndex = 0), not repeated for subsequent modules.

```
IF currentModuleIndex === 0:
  // Pre-load module specification references (Bucket 3)
  const moduleRefs = [
    "~/.claude/skills/business-analyse/references/spec-auto-inference.md",
    "~/.claude/skills/business-analyse/references/ui-resource-cards.md",
    "~/.claude/skills/business-analyse/references/ui-dashboard-spec.md",
    "~/.claude/skills/business-analyse/references/cadrage-pre-analysis.md"
  ];

  for (const file of moduleRefs) {
    read(file);  // Pre-load into cache
  }

  Display: "✓ Cache warmed: module specification references (23KB, 4 files)"
  Display: "  Expected token savings: 75% reduction in reference reads across module loop"
  Display: "  Retention: until step-04 (after all modules specified)"
ELSE:
  // Subsequent modules use cached references (no re-load)
  Display: "✓ Using cached module references (from first module)"
```

**Rationale:**

- Module specification references are read 2-3× PER MODULE (5 modules = 10-15 reads without caching)
- Pre-loading once at start of module loop eliminates 75% of redundant reads
- Token savings: ~10,000 tokens for a 5-module application
- Cache retained until step-04 (when consolidation starts, references no longer needed)

See [references/cache-warming-strategy.md](../references/cache-warming-strategy.md) § Bucket 3 for details.

### 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/{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"
ba-writer.updateModuleStatus({feature_id}, {currentModule.code}, "in-progress")

### 2-ter. Derive Module Discovery Section (MANDATORY)

> **The module feature.json MUST have a `discovery` section.** In multi-module mode, derive it from the parent application's `cadrage`. In single-module mode, it should already exist from step-01.

```
ba-reader.readApplicationContext({feature_id})
→ Read cadrage: problem, asIs, toBe, trigger, stakeholders, risks, acceptanceCriteria

// Filter to this module's scope
moduleScope = cadrage.coverageMatrix.filter(cm => cm.module === currentModule.code)
moduleStakeholders = cadrage.stakeholders.filter(s => s.tasks relevant to this module)
moduleRisks = cadrage.risks.filter(r => r related to this module)

ba-writer.enrichSection({
  featureId: {module_feature_id},
  section: "discovery",
  data: {
    problem: cadrage.problem,
    asIs: cadrage.asIs,
    toBe: cadrage.toBe,
    trigger: cadrage.trigger,
    stakeholders: moduleStakeholders,
    scope: {
      mustHave: moduleScope.filter(s => s.category === "mustHave").map(s => s.item),
      shouldHave: moduleScope.filter(s => s.category === "shouldHave").map(s => s.item),
      couldHave: moduleScope.filter(s => s.category === "couldHave").map(s => s.item),
      outOfScope: []
    },
    risks: moduleRisks,
    acceptanceCriteria: cadrage.acceptanceCriteria.filter(ac => relevant to module),
    codebaseContext: cadrage.codebaseContext
  }
})
```

> **STRUCTURE CARD: discovery** — Same format as cadrage but module-scoped.
> Fields: `problem`, `asIs`, `toBe`, `trigger`, `stakeholders[]`, `scope{}`, `risks[]`, `acceptanceCriteria[]`, `codebaseContext`, `openQuestions[]`

### 2-bis. Coverage Verification (MANDATORY)

> **Before specifying any module, verify that the coverageMatrix from cadrage covers this module.**

```
ba-reader.readApplicationContext({feature_id})
→ Read cadrage.coverageMatrix[]
→ Filter entries where module = {currentModule.code}
→ Group by category: mustHave, shouldHave, couldHave
```

Display to client:
```
Module {currentModule}: Coverage from original brief

| # | Requirement | Category |
|---|-------------|----------|
| 1 | {item} | {category} |
| ... | ... | ... |

Total: {N} requirements mapped to this module
  - Must-have: {count}
  - Should-have: {count}
  - Could-have: {count}
```

**VALIDATION:** If mustHave count = 0 AND module is in must priority:
  → WARNING: "Module {currentModule} is must-priority but has no must-have requirements in coverageMatrix. Verify cadrage coverage."

**POST-SPECIFICATION CHECK (at end of module, before advancing):**
  For EACH mustHave item in coverageMatrix for this module:
    → Verify at least 1 UC exists that covers this requirement
    → If uncovered: BLOCK and ask client to either add a UC or reclassify the requirement

### 3. Section Walkthrough with Client

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

#### 3a. Identify Module Sections

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

> **RULE:** Sections = functional zones only. `list` is ALWAYS present (default).
> `create`/`edit` = separate pages with own URL routes (`/create` and `/:id/edit`). `detail` = tabbed page from list click.

| Module Type | Sections (functional zones) | Detail page tabs (from list click) |
|-------------|---------------------------|-----------------------------------|
| data-centric | list | Infos, {relations} |
| workflow | list, approve | Infos, {relations}, Historique |
| integration | list | Infos, Config, Logs, Sync |
| reporting | dashboard | — |
| full-module | list, dashboard, approve | Infos, {relations}, Historique |

**Section `list` is automatic and ALWAYS included.** Ask ONLY about additional functional sections:

Ask via AskUserQuestion:

```
question: "{language == 'fr'
  ? 'Le module {currentModule} aura une page liste (avec création et détail par onglets). Quelles sections fonctionnelles supplémentaires souhaitez-vous ?'
  : 'Module {currentModule} will have a list page (with create and tabbed detail). Which additional functional sections do you want?'}"
header: "Sections"
multiSelect: true
options:
  - label: "Dashboard"
    description: "{language == 'fr' ? 'Tableau de bord avec KPIs, graphiques et métriques clés' : 'Dashboard with KPIs, charts and key metrics'}"
  - label: "Validation/Approbation"
    description: "{language == 'fr' ? 'File d\'approbation avec workflow de changement de statut' : 'Approval queue with status change workflow'}"
  - label: "Import en masse"
    description: "{language == 'fr' ? 'Import CSV/Excel avec mapping et validation' : 'CSV/Excel import with mapping and validation'}"
  - label: "{language == 'fr' ? 'Aucune (liste seule)' : 'None (list only)'}"
    description: "{language == 'fr' ? 'Le module n\'a besoin que de la page liste avec détail' : 'Module only needs the list page with detail'}"
```

#### 3a-depth. Determine Specification Depth

> **Based on module complexity and type, determine how deeply to specify sections and resources.**
> **This avoids over-specifying simple modules and under-specifying complex ones.**

Read from application master:
```
ba-reader.readApplicationContext({feature_id})
→ module = modules.find(m => m.code === currentModule)
→ complexity = module.estimatedComplexity   // simple | medium | complex
→ featureType = module.featureType          // data-centric | workflow | integration | reporting | full-module
```

**Depth decision matrix:**

| Complexity | featureType | Depth | Behavior |
|---|---|---|---|
| simple | data-centric | **convention** | Auto-generate sections + resources from entities. Quick client validation. |
| simple | reporting | **convention** | Standard dashboard template. Quick validation. |
| simple | * | **convention** | Standard sections for featureType. Quick validation. |
| medium | data-centric | **override** | Auto-generate then ask client which sections to customize. |
| medium | workflow | **full** | State machine required → always full. |
| medium | * | **override** | Auto-generate then ask client to customize. |
| complex | * | **full** | Full specification: state machine, typed columns, conditional actions. |
| * | workflow | **full** | Always full for workflow modules (state machine is mandatory). |

Display to client:
```
"Module {currentModule}: complexité {complexity}, type {featureType} → profondeur: {depth}"
```

**IF depth = convention:**
  - Execute 3a-infer (auto-inference) → generates sections + resources
  - Execute 3b (wireframes) for each section
  - Skip 3a-bis detailed walkthrough → present auto-generated spec for quick validation
  - Ask client: "La spécification auto-générée convient-elle, ou souhaitez-vous personnaliser certaines sections ?"
    - If client says OK → proceed to step 4 (questionnaires)
    - If client wants changes → switch to **override** for specified sections

**IF depth = override:**
  - Execute 3a-infer (auto-inference) → generates base sections + resources
  - Ask client: "Quelles sections souhaitez-vous personnaliser ?"
  - For selected sections → execute full 3a-bis + 3b + 3b-ter
  - For other sections → keep auto-generated spec

**IF depth = full:**
  - Execute standard flow: 3a-bis → 3b → 3b-bis → 3b-ter → 3c → 3d (as currently defined below)
  - PLUS: 3a-state (state machine definition) for entities with status fields

#### 3a-infer. Auto-Infer Resources from Entities (Convention/Override)

> **For convention and override depths, auto-generate resource details from entity definitions.**
> **The goal: produce a complete spec without manual input, that the client only validates.**

**Prerequisites:** Entity attributes must be defined (from step 6) OR anticipated from decomposition.

See [references/spec-auto-inference.md](../references/spec-auto-inference.md) for complete inference rules:
- Entity attribute → SmartTable column mapping (9 type rules)
- Entity attribute → SmartForm field mapping (8 type rules)
- Auto-generated sections per featureType (5 types)
- Component generation rules (list section, create/edit form pages with own routes, detail page with tabs, dashboard section)
- Status/lifecycle enhancement rules

Write auto-generated sections to `specification.sections[]` via ba-writer.enrichSection()

### 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}"
```

#### 5-bis. Unresolved Entity Dependencies (New Module Detection)

> **When an entity reference is detected that does NOT belong to any completed or planned module, apply the SAME intelligent Entity Sourcing Pattern as step-01-cadrage (section 4d-bis).**
> **Reference:** Load [references/entity-architecture-decision.md](../references/entity-architecture-decision.md) for scoring grid, decision tree, and section patterns.

For each entity referenced by {currentModule} that is NOT covered by any existing/planned module:

##### A. ULTRATHINK: Silent Analysis (NO output to client)

> **Same intelligence as cadrage 4d-bis. Score the entity, assess domain coherence, recommend.**

```
ULTRATHINK — Entity Architecture Analysis for {entity_name} (discovered during specification of {currentModule}):

1. DOMAIN COHERENCE
   - Application domain: {app_description}
   - Entity fit: CORE | SUPPORT | PERIPHERAL
   - Justification: {1 sentence}

2. ENTITY SCORING (5 criteria, 0-3 each — from scoring grid in reference)
   - Lifecycle:  {score}/3
   - Actors:     {score}/3
   - Relations:  {score}/3
   - Volume:     {score}/3
   - Autonomy:   {score}/3
   - TOTAL:      {total}/15 → {classification}

3. PRE-CLASSIFICATION CHECK (from entity patterns in reference, section 10 of suggestion-catalog)
   - Match? → {yes: which pattern | no: use scoring}

4. RECOMMENDATION
   - Option: {in_this_module | new_module | external_system | config_list}
   - Confidence: HIGH | MEDIUM | LOW
   - Reasoning: {1-2 sentences}

5. IF recommendation = new_module → PRE-BUILD ARCHITECTURE
   - Module code: {PascalCase}
   - Section `list` + detail page tabs
   - Additional sections (ONLY functional zones)
   - Impact on dependency graph
```

##### B. Present Analysis & Recommendation

**BEFORE AskUserQuestion, display as markdown:**

```
### {language == "fr" ? "Analyse" : "Analysis"} : {entity_plural}

{language == "fr"
  ? "Pendant la spécification de **{currentModule}**, j'ai détecté une référence aux **{entity_plural}** qui ne font partie d'aucun module existant."
  : "During specification of **{currentModule}**, I detected a reference to **{entity_plural}** not covered by any existing module."}

{language == "fr" ? "**Mon analyse :**" : "**My analysis:**"}
- {language == "fr" ? "Cohérence domaine" : "Domain coherence"} : **{CORE|SUPPORT|PERIPHERAL}** — {justification}
- {language == "fr" ? "Score de complexité" : "Complexity score"} : **{score}/15** ({classification})
- **{language == "fr" ? "Recommandation" : "Recommendation"}** : **{recommended_option}** — {reasoning}
```

**IF recommendation = new_module AND confidence >= MEDIUM, ALSO display the architecture proposal** (same format as cadrage 4d-bis Phase 2: Application/Module table + Sections table + Detail tabs table + Impact).

##### C. Ask with Recommended Option First

```
question: "{language == 'fr'
  ? 'Comment souhaitez-vous gérer les {entity_plural} ?'
  : 'How do you want to manage {entity_plural}?'}"
header: "{entity_name}"
options:
  (ORDER: recommended option FIRST with "(Recommandé)"/"(Recommended)", then remaining 3)

  IF recommendation = new_module:
  - label: "{language == 'fr' ? 'Nouveau module dédié (Recommandé)' : 'New dedicated module (Recommended)'}"
    description: "{language == 'fr'
      ? 'Module {ModuleCode} avec page liste, détail par onglets, permissions dédiées'
      : '{ModuleCode} module with list page, tabbed detail, dedicated permissions'}"
  - label: "{language == 'fr' ? 'Dans ce module' : 'In this module'}"
    description: "{language == 'fr'
      ? 'Onglet dans la page détail de {currentModule}'
      : 'Tab in {currentModule} detail page'}"
  - label: "{language == 'fr' ? 'Système externe' : 'External system'}"
    description: "..."
  - label: "{language == 'fr' ? 'Liste de référence' : 'Reference list'}"
    description: "..."

  IF recommendation = config_list:
  - label: "{language == 'fr' ? 'Liste de référence (Recommandé)' : 'Reference list (Recommended)'}"
    description: "{language == 'fr'
      ? 'Table de lookup configurable par l\'admin'
      : 'Admin-configurable lookup table'}"
  - (3 remaining options in logical order)

  IF recommendation = in_this_module:
  - label: "{language == 'fr' ? 'Dans ce module (Recommandé)' : 'In this module (Recommended)'}"
    description: "{language == 'fr'
      ? 'Onglet dans la page détail de {currentModule}'
      : 'Tab in {currentModule} detail page'}"
  - (3 remaining options)

  IF confidence = LOW:
  (all 4 options in neutral order, NO "(Recommandé)" tag)
```

##### D. Process Answer

| Choice | Action |
|--------|--------|
| **Dans ce module** | Entity becomes a sub-entity of {currentModule}. Add as a **tab in the detail page**. Add to this module's `analysis.entities[]`. |
| **Nouveau module dédié** | Add new module to master `modules[]` via ba-writer with proposed architecture (sections, detail tabs, dependencies). The `list` section is ALWAYS the main section. Additional sections ONLY for functional zones. |
| **Système externe** | Flag for integration. Add to `coverageMatrix` as integration. |
| **Liste de référence** | Lookup table, admin-managed. No module, no section. |

**IF "Nouveau module dédié" is selected:**
1. Add new module to master `modules[]` via ba-writer (status: "pending", sortOrder: after current module)
2. Update dependency graph: current module depends on the new module
3. **Display:**
   ```
   "{language == 'fr'
     ? '⚠ Nouveau module {ModuleCode} ajouté au graphe de dépendances. Il sera spécifié après {currentModule}.'
     : '⚠ New module {ModuleCode} added to dependency graph. It will be specified after {currentModule}.'}"
   ```
4. Update `metadata.workflow.moduleOrder` to include the new module (inserted after its dependents)

---

## NEXT STEP

Load: `./step-03a2-analysis.md`
