---
name: step-01-cadrage
description: Application/module framing - listen, reformulate, challenge, anticipate, bound scope
model: opus
next_step: steps/step-02-structure.md
---

> **Context files:** `_shared.md`
> **Reference (4d-bis):** `references/entity-architecture-decision.md` — Entity scoring, domain coherence, section patterns

# Step 1: Cadrage (Framing)

## MANDATORY EXECUTION RULES

- ALWAYS use ULTRATHINK mode for this step
- ALWAYS apply the Elicitation Techniques from `_shared.md`
- NEVER accept vague answers — probe deeper
- NEVER define entities or business rules here — that's per-module in step-03
- ALL questions via AskUserQuestion tool (NEVER as text dumps)
- ALL communication in `{language}` (from index.json metadata.language)
- **NEVER skip the reformulation phase** — it is the foundation of good analysis
- **NEVER auto-infer cadrage data without client validation** — every key decision is confirmed

## CONTEXT RECOVERY

Re-read session variables from `.business-analyse/config.json` (do NOT rely on LLM memory):
```javascript
const config = readJSON('.business-analyse/config.json').currentFeature;
const { id: feature_id, docsDir: docs_dir, projectSlug, application: application_name,
        applicationCode, workflowMode: workflow_mode, language, version } = config;
```

> **Path resolution (ba-006):** `docs_dir` points to `docs/{projectSlug}/v{version}`.
> Cadrage.json is written directly in `{docs_dir}/cadrage.json`.

## YOUR TASK

Frame the analysis scope at the **application level** through an interactive conversation with the client: understand the problem, stakeholders, scope, and define application-level roles. The analysis phase is ALWAYS interactive — the AI listens, reformulates, challenges, and validates with the user.

**Key difference from step-03:** This step does NOT define entities, business rules, or process flows. Those are per-module and handled in step-03.

---

## EXECUTION FLOW — 5 PHASES

```
Phase 1: ÉCOUTE           → Read brief + codebase pre-research + silent pre-analysis
Phase 2: REFORMULATION     → Rephrase the need back to the client for validation
Phase 3: APPROFONDISSEMENT → Challenge assumptions with targeted questionnaires
Phase 4: ANTICIPATION      → Suggest unexpressed needs from domain expertise
Phase 5: PÉRIMÈTRE         → Bound scope with roles, coverage matrix (sections + resources)
```

---

## PHASE 1: ÉCOUTE (Listen)

### 1. Read Current State

```
ba-reader.findFeature({feature_id})
→ Read metadata: application, language, workflow.mode, useCase
→ Read cadrage section (if resuming)
```

IF cadrage already completed (status = "framed"):
  Display: "Cadrage already completed. Loading next step."
  Load: steps/step-02-structure.md
  STOP

### 2. Codebase Pre-Research

> **Understand what already exists before engaging the client.**

**Phase 2a: MCP Tools (if available)**
```
IF mcp_available:
  Call: mcp__smartstack__analyze_extension_points
  → Discover existing modules, entities, services

  Call: mcp__smartstack__api_docs
  → Existing API documentation

  Call: mcp__smartstack__validate_conventions
  → Validate application/module naming

  Store findings in {codebase_context}
```

**Phase 2b: Parallel Codebase + Docs Agents**
```
Launch 4 agents in parallel:
  Agent 1: Search for existing domain entities (Glob: **/Domain/**/*.cs)
  Agent 2: Search for existing services/integrations (Grep: IService, IRepository)
  Agent 3: Search for existing page patterns (Glob: **/pages/**/*.tsx)
  Agent 4: Scan existing BA documentation (Glob: docs/*/v*/index.json, docs/**/business-analyse/**/index.json)
           → For each found file: read metadata.application, metadata.module, status, modules[].code
           → Also scan: docs/**/*.md (ERD, guides, specs)

Merge findings into {codebase_context}
```

**Phase 2c: Existing Documentation Context**

> **Load existing BAs and documentation BEFORE engaging the client.**
> This prevents re-specifying what already exists and surfaces integration constraints early.

```
IF Agent 4 found existing index.json files:
  For each file found:
    → Extract: application, modules[], entities[], status, version
    → Store as {existing_ba_context}: list of existing applications with their modules and key entities
  Display (silent — internal context only, not shown to client):
    "Found {count} existing BA(s): {app names} — {total modules} modules already specified"

IF docs/**/*.md files found:
  → Scan for ERD diagrams, API specs, architecture decisions
  → Store relevant findings in {codebase_context}
```

**Use in pre-analysis:**
- Cross-reference detected modules against `{existing_ba_context}` — flag modules that already exist
- Pre-identify integration points: new feature may depend on or extend existing modules
- NEVER re-specify what's already handed-off (status = "handed-off") — reference it instead

### 2d. Domain Research (WebSearch — MANDATORY — BLOCKING)

> → **Load** `references/domain-research-playbook.md` for search strategy, query templates, and extraction format.
> **MANDATORY — BLOCKING.** Web research is the #1 quality factor. An analysis without research is a 2/10.
> Do NOT rely on "built-in domain expertise" — real-world research catches what the LLM misses.

**Execute Level 1 research from the playbook:**

```
IF workflow_mode = "project" (multi-app):
  For EACH candidateApplication in config.candidateApplications:
    1. WebSearch 1a: "{app_type} application modules features complete list"
    2. WebSearch 1b: "best {app_type} software features comparison"
    3. WebSearch 1c: "{app_type} data model entities relationships"
    → Store in {domain_research}.applications[{app_code}]

ELSE (single-app):
  1. WebSearch 1a: "{app_type} application modules features complete list"
  2. WebSearch 1b: "best {app_type} software features comparison"
  3. WebSearch 1c: "{app_type} data model entities relationships"
  → Store in {domain_research}

IF applicable domain (Billing, HR, Finance):
  Execute Level 3 regulatory research from playbook
  → Store in {domain_research}.regulatory[]
```

**FALLBACK (WebSearch unavailable):**
```
IF WebSearch tool is not available or fails:
  → Display WARNING: "WebSearch indisponible. Qualite d'analyse degradee (max 4/10)."
  → AskUserQuestion: "Continuer sans recherche web ? (Non recommande)"
  → IF user confirms: proceed with {domain_research}.source = "built-in-only"
    → Load references/module-completeness-challenge.md as fallback
  → IF user declines: STOP
```

### 2b. Silent Pre-Analysis (ULTRATHINK — no output to client)

> **The AI prepares the conversation before speaking. This is NOT output — it's internal reasoning.**
> **INCLUDES domain research findings from 2d above.**

Analyze `{feature_description}` AND `{domain_research}` silently:

1. **Identify problem type** from keywords (replace, automate, centralize, new tool)
2. **Extract explicit modules/features** mentioned in the description
3. **Detect shadow zones** — what is NOT said but should be:
   - Missing stakeholders (who else would use this?)
   - Missing sections (reports mentioned but no details?)
   - Implicit relationships (1:1, 1:N — why this cardinality?)
   - Missing non-functional needs (security, performance, compliance)
4. **Prepare challenge questions** — specific to this brief, not generic
5. **Pre-identify anticipated sections and resources** per detected module

6. **MODULE COMPLETENESS CROSS-CHECK** (CRITICAL — requires domain research from 2d):
   For EACH application:
     - Compare detected modules vs `{domain_research}.applications[app].standardModules`
     - For EACH **CORE** module absent → add to `shadow_zones` with `priority: "HIGH"`
     - For EACH **STANDARD** module absent → add to `shadow_zones` with `priority: "MEDIUM"`
   Example: User says "Facturation avec factures".
   Research reveals CORE modules: [Factures, Avoirs, Paiements].
   → `shadow_zones += [{topic: "Avoirs/Credit Notes", priority: "HIGH", why: "Module CORE manquant — legalement requis pour corriger une facture"}]`

7. **BUSINESS PROCESS MAPPING** (MANDATORY for multi-app):
   Before decomposing into modules, map the end-to-end business processes:
   - From `{domain_research}` and `{feature_description}`, identify cross-app processes:
     - "Cycle commercial: Prospect → Client → Opportunite → Devis → Facture → Paiement"
     - "Cycle RH: Embauche → Fiche employe → Absences → Documents"
     - "Cycle projet: Devis accepte → Projet → Affectation → Saisie heures → Validation → Facturation"
   - For EACH process step, check if a module covers it. Flag uncovered steps.
   Store in `{_preAnalysis.businessProcesses}`

Store in `{pre_analysis}` — Write pre_analysis to cadrage.json as a `_preAnalysis` field (transient — removed on cadrage completion). This ensures the data survives context compaction:
```yaml
_preAnalysis:
  problem_type: "new_tool|replace|automate|centralize"
  detected_modules: [{name, description, detected_sections}]
  shadow_zones: [{topic, why_it_matters, challenge_question, priority}]
  anticipated_suggestions: [{suggestion, justification, module}]
  domain_research:                          # from Phase 2d web search
    domain: "{detected domain}"
    applications:                           # Level 1 research per app
      {app_code}:
        standardModules: [{name, classification, description, standardSections}]
        competitiveInsights: [{product, keyFeatures}]
        dataModel: {entities, relationships, antiPatterns}
    regulatory: []                          # Level 3 if applicable
  businessProcesses:                        # from step 7 above
    - name: "Cycle commercial"
      apps: ["Crm", "Facturation"]
      steps: [{name, module, covered: true|false}]
```

---

## PHASE 2: REFORMULATION (Rephrase & Validate)

### 3. Reformulation du besoin (MANDATORY — NEVER SKIP)

> **Golden rule of requirements analysis: NEVER proceed without reformulating.**
> The analyst must prove they understood before digging deeper.
> This is what distinguishes a professional analysis from a superficial one.

**Process:**

1. From `{feature_description}` and `{pre_analysis}`, build a structured reformulation.

2. **Display as markdown** (direct text output, NOT inside AskUserQuestion):

```
## {language == "fr" ? "Voici ce que j'ai compris de votre besoin" : "Here is my understanding of your need"}

**Projet :** {projectSlug}
**Application :** {detected application name}
**Objectif :** {reformulation in 2-3 sentences of the global need — in the client's own words, not technical jargon}

**Modules identifiés :**
- **{Module 1}** : {functional description}
  - Section **list** : {entity}-grid, {entity}-filters + pages `/create` et `/:id/edit`
  - Page détail (onglets) : {Infos, {relation_tabs}...}
  - {IF dashboard needed:} Section **dashboard** : {kpi-cards, charts...}
- **{Module 2}** : {functional description}
  - Section **list** : {entity}-grid, {entity}-filters, {entity}-form
  - Page détail (onglets) : {Infos, ...}

**Points que j'ai notés :**
- {specific point 1 from the brief, quoted verbatim when possible}
- {specific point 2}

**Points qui me semblent ambigus ou non précisés :**
- {shadow zone 1 — what I don't know yet}
- {shadow zone 2}
```

3. Then ask via AskUserQuestion:
```
question: "{language == 'fr' ? 'Cette reformulation correspond-elle à votre besoin ?' : 'Does this reformulation match your need?'}"
header: "Validation"
options:
  - label: "{language == 'fr' ? 'Oui, c\'est correct' : 'Yes, correct'}"
    description: "{language == 'fr' ? 'La reformulation reflète bien mon besoin' : 'The reformulation accurately reflects my need'}"
  - label: "{language == 'fr' ? 'Partiellement' : 'Partially'}"
    description: "{language == 'fr' ? 'Certains points sont corrects mais d\'autres à ajuster' : 'Some points are correct but others need adjustment'}"
  - label: "{language == 'fr' ? 'Non, à revoir' : 'No, needs revision'}"
    description: "{language == 'fr' ? 'La reformulation ne correspond pas à mon besoin' : 'The reformulation does not match my need'}"
```

4. IF "Partially" or "No":
   - Ask for corrections via AskUserQuestion (open-ended "Other" option)
   - Re-reformulate and re-validate (loop until confirmed)

5. Once confirmed, update `{pre_analysis}` with any corrections.

---

### 3b. Challenge Against Industry Standards (MANDATORY — BEFORE scope lock)

> **Use domain research to challenge scope completeness BEFORE locking.**
> This is what distinguishes a 2/10 analysis from a 9/10 analysis.

1. From `{domain_research}.applications`, build a completeness comparison:

Display as markdown (direct text, NOT inside AskUserQuestion):

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

{language == "fr"
  ? "Pour chaque application, j'ai recherche ce que proposent les solutions du marche :"
  : "For each application, I researched what market solutions offer:"}

| Application | Vos modules | Modules standard industrie | Ecart |
|-------------|------------|---------------------------|-------|
| {app} | {user_modules} | {research_standard_modules} | {missing_CORE + missing_STANDARD} |

{language == "fr" ? "**Modules CORE manquants** (standard dans toute solution de ce type) :" : "**Missing CORE modules:**"}
{for each missing CORE module:}
- **{module_name}** : {description} — {why it matters for this project}

{language == "fr" ? "**Modules STANDARD manquants** (presents dans la majorite des solutions) :" : "**Missing STANDARD modules:**"}
{for each missing STANDARD module:}
- **{module_name}** : {description}
```

2. AskUserQuestion (multiSelect: true):
```
question: "{language == 'fr'
  ? 'Quels modules manquants souhaitez-vous ajouter ? Les modules CORE sont fortement recommandes.'
  : 'Which missing modules would you like to add? CORE modules are strongly recommended.'}"
header: "{language == 'fr' ? 'Completude des applications' : 'Application completeness'}"
multiSelect: true
options:
  - For each missing CORE module: label: "{name} (CORE — fortement recommande)", description: "{why}"
  - For each missing STANDARD module: label: "{name} (STANDARD — recommande)", description: "{why}"
  - label: "{language == 'fr' ? 'Aucun — perimetre initial' : 'None — keep initial scope'}"
    description: "{language == 'fr' ? 'Garder uniquement les modules initiaux' : 'Keep only initial modules'}"
```

3. IF user adds modules → update `{pre_analysis}.detected_modules` and `candidateApplications`
4. IF user excludes CORE modules → document exclusion reason in `cadrage.globalScope.outOfScope`

---

## SCOPE LOCK (MANDATORY — after validated reformulation + competitive challenge)

> **The modules and applications identified in the validated reformulation are the LOCKED SCOPE.**

+==============================================================================+
|  SCOPE LOCK RULES — Applied from this point forward                          |
+==============================================================================+
|                                                                              |
|  1. The NUMBER of applications is LOCKED (confirmed in step-00 Step 3b).     |
|     Phase 4d-bis (Entity Sourcing) CANNOT create new applications.           |
|                                                                              |
|  2. Phase 4d-bis CAN recommend entities as `config_list` or                  |
|     `in_app_section` — but CANNOT recommend `new_module` or                  |
|     `new_application` without EXPLICIT AskUserQuestion confirmation.         |
|                                                                              |
|  3. Portal detection (4b-bis) creates ONE "Portal" module with sections,     |
|     NOT multiple MyX modules.                                                |
|                                                                              |
|  4. Any scope expansion beyond the reformulation = AskUserQuestion.          |
|     Silent scope expansion is FORBIDDEN.                                     |
|                                                                              |
+==============================================================================+

## PHASE 3: APPROFONDISSEMENT (Challenge & Deepen)

### 4. Targeted Questionnaires

> **Principle: Do NOT ask ALL questions from ALL questionnaires.**
> Select the RELEVANT questions based on the pre-analysis and detected shadow zones.
> Apply elicitation techniques from `_shared.md` after each batch.
> The goal is a CONVERSATION, not an interrogation.

#### 4a. Batch 1 — Contexte & Vision (from `questionnaire/01-context.md`)

> Load the full questionnaire reference for elicitation guides and alert signals.
> **Principe analyste expert :** Poser les questions necessaires pour une couverture metier complete.
> Proposer proactivement les modules et regles que le client n'a pas mentionnes.
> Challenger chaque zone d'ombre. L'auto-deduction est un COMPLEMENT, jamais un SUBSTITUT aux questions critiques.

**Questions a poser (1 batch via AskUserQuestion) :**
- Q1.1 (OBLIGATOIRE) : processus metier
- Q1.8 (OBLIGATOIRE) : vision cible
- Q1.4 (CONDITIONNEL) : frictions — poser UNIQUEMENT si `_preAnalysis.problem_type IN ("replace", "automate")`

```
IF _preAnalysis.problem_type IN ("new_tool", "centralize"):
  → Skip Q1.4
  → Auto-remplir: cadrage.asIs = "Aucun outil existant — nouveau système"
  → Ask Q1.1 + Q1.8 in 1 batch (2 questions)
ELSE:
  → Ask Q1.1 + Q1.4 + Q1.8 in 1 batch (3 questions)
```

**Aussi dans ce batch :** Detection utilisateurs externes (avancee depuis ex-4b-bis) :
- Ajouter la question : "Des utilisateurs externes (clients, fournisseurs, partenaires) accederont-ils au systeme ?"
- Cette reponse active `_portalDetected` DES LE DEBUT pour adapter les questions stakeholders en consequence.

Apply ULTRATHINK after the batch:
- If answer is vague → probe deeper using the elicitation guide from 01-context.md
- If answer is solution-oriented → apply Technique 1 (reformulate as need)
- If answer is superficial → apply Technique 2 (chain of whys)
- If answer is excellent → record and move on

#### 4b. Batch 2 — Utilisateurs & Acces (from `questionnaire/02-stakeholders-scope.md`)

> **5 questions obligatoires** couvrant profils, taches et niveaux d'acces.
> **Regle : 2 questions max par AskUserQuestion** — ne jamais submerger l'utilisateur.

**Batch 2a** (Q2.1 + Q2.5) : Profils et taches.
Ask via AskUserQuestion (2 questions).
- If only 1 user type mentioned → probe: "Who else interacts? Managers? Admins? External users?"
- If tasks are generic → ask for a concrete scenario: "Walk me through a typical day"

**Batch 2b** (Q2.9 + Q2.10) : Restrictions d'acces et droits de modification.
Ask via AskUserQuestion (2 questions).
- If "no restrictions" → probe: "Are there sensitive data (salary, contracts, personal info) that should be restricted to specific roles?"

**Batch 2c** (Q2.11) : Actions sensibles (suppression, validation, export).
Ask via AskUserQuestion (1 question).

Apply ULTRATHINK after EACH batch:
- If answer is vague → probe deeper using the elicitation guide
- If answer is solution-oriented → apply Technique 1 (reformulate as need)
- If answer is superficial → apply Technique 2 (chain of whys)
- If answer is excellent → record and move on

#### 4b-bis. Résolution Portail Client (ULTRATHINK — après batch 2)

> → **Load** `references/portal-classification.md` for external signal detection, classification rules, and portal mode resolution.

Execute portal classification following the reference. Store result in `_portalMode`.

#### 4c. Batch 3 — Perimetre & Limites (from `questionnaire/02-stakeholders-scope.md`)

> **Objectif :** Borner le perimetre — exclusions explicites + integrations/imports si pertinent.
> Les fonctionnalites IN-SCOPE sont couvertes par la reformulation (phase 2) et ne necessitent plus de question explicite.
> Le parcours utilisateur (ex-Q2.16-Q2.18) est desormais capture en step-03 lors de la specification des use cases.

**Questions a poser (1 batch via AskUserQuestion) :**
- Q2.15 (OBLIGATOIRE) : exclusions
- Q2.19 (CONDITIONNEL) : integrations — poser uniquement si le brief mentionne un systeme externe
- Q2.20 (CONDITIONNEL) : import donnees — poser uniquement si le brief mentionne migration/import

```
IF brief mentions external system OR integration:
  → Ask Q2.15 + Q2.19 + Q2.20 in 1 batch
ELIF brief mentions import OR migration:
  → Ask Q2.15 + Q2.20 in 1 batch
ELSE:
  → Ask Q2.15 only
  → Auto-remplir: cadrage.externalIntegrations = [], cadrage.dataImport = null
```

After the batch:
- If no exclusions → probe: "What should this system explicitly NOT do?"

> **Error Path Challenge :** Deplace vers step-03 — les scenarios d'erreur sont captures par module
> lors de la specification des use cases (alternativeScenarios, errorScenarios).
> En step-01, les erreurs globales sont couvertes par les suggestions (phase 4 — Anticipation).

#### 4d. Challenge Implicit Assumptions (CRITICAL)

> **Load reference material from `_shared.md` for domain-specific patterns and elicitation techniques.**

Apply elicitation techniques to challenge what the client considers "obvious".
This is what separates a deep analysis from a shallow one.

For EACH specific point from the brief, prepare a targeted challenge question:
1. Identify the assumption (what the client stated as fact)
2. Formulate a "what if the opposite?" question
3. Use techniques from the reference (Scenario, Absence Test, Impact Escalation)

Ask challenge questions via AskUserQuestion (1-2 batches of max 4).

#### 4d-bis. Entity Sourcing Pattern (MANDATORY for detected dependencies)

> **When the analysis detects a referenced entity/concept (e.g., "Projets" referenced by activities, "Clients" referenced by orders), ALWAYS analyze and recommend BEFORE asking the client.**
> This pattern detects potential new modules not mentioned in the original brief.
> **Reference:** Load [references/entity-architecture-decision.md](../references/entity-architecture-decision.md) for scoring grid, decision tree, and section patterns.

For EACH referenced entity/concept detected during phases 2-4 that is NOT already covered by an identified module:

> → **Load** `references/entity-sourcing-presentation.md` for the 4-phase entity sourcing flow:
> PHASE 1 (ULTRATHINK analysis), PHASE 2 (display to client), PHASE 3 (AskUserQuestion), PHASE 4 (process answer).

Execute ALL 4 phases from the reference for EACH referenced entity detected.

#### 4e. Conditional Deep-Dives

Based on brief analysis, load additional materials if relevant:

| Condition | Questionnaire |
|-----------|---------------|
| Security or compliance mentioned | `questionnaire/03-data-ui.md` (security section) |
| External system integration | `questionnaire/05-cross-module.md` (integration section) |
| Performance requirements | Additional probing on non-functional needs |
| Technical constraints | Additional probing on platform constraints |

---

## PHASE 4: ANTICIPATION (Suggest Unexpressed Needs)

### 4f. Detection des besoins structurants (MANDATORY — BEFORE suggestions)

> **Auto-deduire les besoins structurants depuis le domain research et confirmer en 1 seule question.**
> Ces choix impactent la structure du systeme et doivent etre captures AVANT la specification.

**ULTRATHINK — Detection des besoins structurants :**

```
1. HISTORIQUE DES MODIFICATIONS
   → Analyse: {domain_research} — le domaine necessite-t-il de tracer qui a modifie quoi et quand ?
   → Default: OUI pour les entites principales, NON pour les tables de reference
   → Exemples: Employes (OUI), AbsenceType (NON)

2. DONNEES HIERARCHIQUES (parent-enfant)
   → Analyse: existe-t-il des structures arborescentes ? (departements → sous-departements, categories → sous-categories)
   → Default: NON sauf si explicitement detecte

3. SUPPRESSION RECUPERABLE
   → Analyse: les donnees supprimees doivent-elles pouvoir etre restaurees ?
   → Default: OUI pour les entites metier, NON pour les tables de liaison

4. CYCLE DE VIE (etats et transitions)
   → Analyse: quelles entites passent par des etats successifs ?
   → Lister: [{entity, states: ["Brouillon", "Actif", ...], transitions: ["Brouillon→Actif", ...]}]
```

**Presenter en 1 AskUserQuestion :**

```
question: "{language == 'fr'
  ? 'Voici les besoins structurants que j\'ai déduits pour votre domaine. Confirmez-vous ?'
  : 'Here are the structural needs I deduced for your domain. Do you confirm?'}"
header: "{language == 'fr' ? 'Besoins structurants' : 'Structural needs'}"

Display as markdown BEFORE the question:
  | Besoin | Détection | Données concernées |
  |--------|----------|--------------------|
  | Historique des modifications | {OUI/NON} | {liste entites} |
  | Données hiérarchiques | {OUI/NON} | {liste entites si OUI} |
  | Suppression récupérable | {OUI/NON} | {liste entites} |
  | Cycle de vie | {OUI/NON} | {entite: [etats]} |

options:
  - label: "{language == 'fr' ? 'Oui, c\'est correct' : 'Yes, correct'}"
  - label: "{language == 'fr' ? 'À ajuster' : 'Needs adjustment'}"
    description: "{language == 'fr' ? 'Certains points sont à modifier' : 'Some points need modification'}"
```

Store confirmed patterns in `cadrage.smartStackPatterns`:
```json
{
  "auditTrail": { "enabled": true, "entities": ["Employee", "Invoice"] },
  "hierarchy": { "enabled": false, "entities": [] },
  "softDelete": { "enabled": true, "entities": ["Employee", "Client", "Invoice"] },
  "workflowStates": [
    { "entity": "Invoice", "states": ["Draft", "Sent", "Paid", "Overdue"], "transitions": [...] }
  ]
}
```

### 4g. Evolution et risques de donnees (MANDATORY)

> **Anticiper les changements futurs et les risques de qualite de donnees.**

Ask via AskUserQuestion (2 questions max) :

```
question: "{language == 'fr'
  ? 'Qu\'est-ce qui risque de changer dans votre activité dans les 6 prochains mois ? Dans 1 an ? (nouveaux utilisateurs, réglementations, croissance des volumes...)'
  : 'What is likely to change in your business in the next 6 months? 1 year? (new users, regulations, volume growth...)'}"
header: "{language == 'fr' ? 'Évolution prévisible' : 'Expected evolution'}"
```

Then ask:
```
question: "{language == 'fr'
  ? 'Que se passe-t-il si une donnée est saisie incorrectement ou manquante ? Quels sont les risques métier ?'
  : 'What happens if data is entered incorrectly or is missing? What are the business risks?'}"
header: "{language == 'fr' ? 'Risques de données' : 'Data risks'}"
```

Store answers in `cadrage.anticipatedEvolution` and `cadrage.dataRisks`.

### 5. Proactive Suggestions

> **An expert analyst doesn't just capture what is said.**
> They anticipate what the client hasn't thought to ask for.

**Process:**

1. Load pattern guidance from `_shared.md`
2. Match suggestion patterns against the project context (domain, modules, features)
3. Add implicit needs for this type of system that weren't mentioned

4. **Display as markdown** (direct text, NOT inside AskUserQuestion):

```
## {language == "fr" ? "Besoins complémentaires que je vous suggère" : "Complementary needs I suggest"}

{language == "fr"
  ? "D'après mon analyse de votre besoin, voici des aspects que vous n'avez peut-être pas mentionnés mais qui sont souvent nécessaires pour ce type d'application :"
  : "Based on my analysis of your need, here are aspects you may not have mentioned but that are often necessary for this type of application:"}

| # | Suggestion | Justification | Module concerné |
|---|-----------|---------------|-----------------|
| 1 | {suggestion} | {why it's relevant for THIS project} | {module} |
| 2 | {suggestion} | {why} | {module} |
| 3 | {suggestion} | {why} | {module} |
| ... | ... | ... | ... |
```

5. Then ask via AskUserQuestion (multiSelect: true):
```
question: "{language == 'fr' ? 'Quelles suggestions souhaitez-vous inclure dans le périmètre ?' : 'Which suggestions would you like to include in scope?'}"
header: "Suggestions"
multiSelect: true
options:
  - label: "{suggestion 1 short name}"
    description: "{justification in 1 sentence}"
  - label: "{suggestion 2 short name}"
    description: "{justification in 1 sentence}"
  - label: "{suggestion 3 short name}"
    description: "{justification in 1 sentence}"
  - label: "{language == 'fr' ? 'Aucune' : 'None'}"
    description: "{language == 'fr' ? 'Je n\'ai pas besoin de ces suggestions' : 'I don\'t need any of these suggestions'}"
```

6. Accepted suggestions enrich `coverageMatrix` and `globalScope`.

---

## PHASE 4b: BUSINESS PROCESS MAPPING (MANDATORY for multi-app)

> **Map the end-to-end business processes BEFORE bounding scope.**
> Business processes reveal cross-app dependencies and missing modules.
> A process step without a covering module = a GAP in the application.

1. From `{domain_research}` and cadrage answers, identify the main business processes:

Display as markdown:
```
### {language == "fr" ? "Processus metier identifies" : "Identified business processes"}

| # | Processus | Applications concernees | Flux |
|---|-----------|----------------------|------|
| 1 | {process_name} | {app1} → {app2} | {step1} → {step2} → ... → {stepN} |
```

2. For EACH process, check that every step has a corresponding module:

```
For each step in process:
  IF no module covers this step:
    FLAG as gap: "{process_name} step '{step_name}' has no covering module"

Display flagged gaps:
  "�� Etapes non couvertes :"
  - {process} : "{step}" — pas de module correspondant
```

3. AskUserQuestion:
```
question: "{language == 'fr'
  ? 'Voici les processus metier identifies. Des etapes ne sont pas couvertes par vos modules. Souhaitez-vous les couvrir ?'
  : 'Here are the identified business processes. Some steps are not covered by your modules. Would you like to cover them?'}"
header: "{language == 'fr' ? 'Processus metier' : 'Business processes'}"
options:
  - label: "{language == 'fr' ? 'Oui, ajouter les modules manquants' : 'Yes, add missing modules'}"
  - label: "{language == 'fr' ? 'Exclure ces etapes du perimetre' : 'Exclude these steps from scope'}"
  - label: "{language == 'fr' ? 'Revoir les processus' : 'Review the processes'}"
```

4. Store confirmed processes in `cadrage._preAnalysis.businessProcesses`

---

## PHASE 5: PERIMETRE (Bound Scope)

### 6. Application Roles Definition

> **Define roles at the APPLICATION level, not per-module.**

Propose the standard 4-tier roles:

```
Application Roles for {application_name}:

| Role | Level | Default Permissions |
|------|-------|-------------------|
| {App} Admin | admin | {app}.* (wildcard) |
| {App} Manager | manager | read, create, update, assign |
| {App} Contributor | contributor | read, create, update |
| {App} Viewer | viewer | read only |
```

Ask via AskUserQuestion:
```
question: "{language == 'fr' ? 'Ces 4 rôles conviennent-ils pour votre application ?' : 'Do these 4 roles suit your application?'}"
header: "Rôles"
options:
  - label: "{language == 'fr' ? 'Oui, parfait' : 'Yes, perfect'}"
    description: "{language == 'fr' ? 'Utiliser les 4 rôles standards tels quels' : 'Use the 4 standard roles as-is'}"
  - label: "{language == 'fr' ? 'Renommer' : 'Rename'}"
    description: "{language == 'fr' ? 'Garder 4 niveaux mais personnaliser les noms' : 'Keep 4 levels but customize names'}"
  - label: "{language == 'fr' ? 'Personnaliser' : 'Customize'}"
    description: "{language == 'fr' ? 'Modifier le nombre ou les permissions des rôles' : 'Modify number or permissions of roles'}"
```

### 6b. Identifiant court de l'application (MANDATORY)

> **Chaque application metier a besoin d'un identifiant court** (2-5 lettres) pour distinguer ses donnees
> dans le systeme. Cet identifiant sera utilise en interne pour le nommage.

**Process:**

1. Derive a suggested prefix from the application name:
   - Use the most recognizable abbreviation (2-5 lowercase letters + `_`)
   - Examples: HumanResources → `rh_`, SalesManagement → `sales_`, Finance → `fi_`, CRM → `crm_`

2. **Display as markdown** (direct text output):

```
{language == "fr"
  ? "### Identifiant de l'application\n\nPour distinguer les données de votre application dans le système, un identifiant court est nécessaire.\n\nIdentifiant suggéré : **`{suggested_prefix}`**"
  : "### Application identifier\n\nTo distinguish your application's data in the system, a short identifier is needed.\n\nSuggested identifier: **`{suggested_prefix}`**"}
```

3. Ask via AskUserQuestion:
```
question: "{language == 'fr' ? 'Cet identifiant court vous convient-il ?' : 'Does this short identifier work for you?'}"
header: "{language == 'fr' ? 'Identifiant' : 'Identifier'}"
options:
  - label: "{language == 'fr' ? 'Oui, parfait' : 'Yes, perfect'}"
    description: "{language == 'fr' ? 'Utiliser l\'identifiant suggéré' : 'Use the suggested identifier'}"
  - label: "{language == 'fr' ? 'Personnaliser' : 'Customize'}"
    description: "{language == 'fr' ? 'Choisir un autre identifiant (2-5 lettres)' : 'Choose a different identifier (2-5 letters)'}"
```

4. IF "Customize" → ask for custom prefix via AskUserQuestion (open-ended "Other" option)

5. **Validate the prefix:**
   - Format: `^[a-z]{2,5}_$` (2-5 lowercase letters followed by underscore)
   - Must NOT collide with platform prefixes: `auth_`, `nav_`, `usr_`, `ai_`, `cfg_`, `wkf_`, `support_`, `entra_`, `ref_`, `loc_`, `lic_`, `tenant_`
   - If collision detected → ask the user to choose another prefix

6. Store in `metadata.tablePrefix`

### 7. Coverage Matrix with Sections & Resources (MANDATORY)

**ENRICHMENT:** The coverage matrix now includes anticipated sections (Level 4) and resources (Level 5).
This gives downstream steps (step-02, step-03) a concrete starting point.

BEFORE transitioning to step-02:

1. Re-read the original prompt/brief in its entirety
2. Re-read ALL answers collected during phases 2-4
3. For EACH distinct feature/requirement identified:
   - Create an entry in `cadrage.coverageMatrix[]`
   - Assign it to inScope or outOfScope
   - Assign the module that will cover it (or null if cross-cutting)
   - List anticipated sections (Level 4) — ONLY functional sections
   - List anticipated resources (Level 5) for each section
   - List detail page tabs — for entities accessible via click from `list`

   **SI `_portalMode === "dual"` :**
   - Chaque entrée `coverageMatrix` reçoit `audience: "internal" | "external" | "shared"`
   - Règles de dérivation :
     - Items mentionnés uniquement par stakeholders internes → `"internal"`
     - Items mentionnés uniquement par stakeholders externes → `"external"`
     - Items mentionnés par les deux ou cross-cutting → `"shared"`
   - Afficher colonne "Audience" dans le tableau de la matrice

4. **RECONCILIATION CHECK (MANDATORY — BLOCKING):**

   > **Every explicitly requested item MUST appear in the coverage matrix.**
   > This check prevents silent omissions — if the user asked for 5 modules, all 5 must be tracked.

   ```
   // Extract all explicit requests from the original prompt
   requestedItems = extract_explicit_items({feature_description})
   // Include: modules mentioned by name, features listed, applications named

   // Verify each requested item has a coverage matrix entry
   uncoveredItems = requestedItems.filter(item =>
     !coverageMatrix.some(entry => fuzzyMatch(entry.feature, item))
   )

   IF uncoveredItems.length > 0:
     BLOCKING: "The following requested items have no coverage matrix entry:
       {uncoveredItems.map(i => '- ' + i).join('\n')}
     Add them to the coverage matrix before proceeding."

   ELSE:
     Display: "✓ Coverage reconciliation: all {requestedItems.length} requested items mapped"
   ```

5. **OUTPUT the matrix as text** (do NOT put it inside AskUserQuestion — it won't render)

6. **THEN** (after the table is displayed) ask via AskUserQuestion for confirmation

7. Iterate until the client confirms

### 7b. Validation de completude (MANDATORY — apres confirmation de la matrice)

> **Jouer l'avocat du diable avant de clore le cadrage.**

Ask via AskUserQuestion (1 question avec options) :
```
question: "{language == 'fr'
  ? 'Avant de passer à la phase suivante, quelques vérifications :'
  : 'Before moving to the next phase, a few checks:'}"
header: "{language == 'fr' ? 'Complétude du périmètre' : 'Scope completeness'}"
```

Display as markdown BEFORE the question:
```
{language == "fr"
  ? "### Vérifications finales\n\n1. **Remplacement** — Ce système remplace-t-il complètement l'outil ou processus actuel ? Ou cohabitera-t-il avec l'existant ?\n2. **Tâches manuelles** — Reste-t-il des tâches aujourd'hui faites sur Excel, papier ou email qui ne sont pas couvertes ?\n3. **Utilisateurs rares** — Y a-t-il des utilisateurs occasionnels ou des cas d'usage peu fréquents mais réels qui ne sont pas couverts ?"
  : "### Final checks\n\n1. **Replacement** — Does this system fully replace the current tool or process? Or will it coexist?\n2. **Manual tasks** — Are there tasks currently done in Excel, on paper, or by email that are not covered?\n3. **Edge users** — Are there occasional users or infrequent but real use cases that are not covered?"}
```

```
options:
  - label: "{language == 'fr' ? 'Tout est couvert' : 'Everything is covered'}"
  - label: "{language == 'fr' ? 'Il manque des éléments' : 'Some elements are missing'}"
    description: "{language == 'fr' ? 'Préciser les manques' : 'Specify what is missing'}"
```

IF "Il manque des éléments" → iterate: collect missing items, update coverageMatrix and globalScope.

---

## WRITE & SUMMARY

### 8. Write Cadrage to Feature.json

Use ba-writer with granular JSON approach. Write to `cadrage.json` section:

```
ba-writer.enrichSection({
  featureId: {feature_id},
  section: "cadrage",
  subsection: "cadrage.json",
  data: {
    metadata: {
      tablePrefix: "{from Phase 5, section 6b — validated prefix, e.g., rh_}",
      portalMode: "{_portalMode || 'internal-only'}"
    },
    problem: {from Phase 3, section 4a — Q1.1 answer or refined problem},
    asIs: {from Phase 3, section 4a — Q1.4 answer},
    toBe: {from Phase 3, section 4a — Q1.8 answer},
    stakeholders: [
      // Shape: {name, role, type: "internal"|"external",
      //         audience: "internal"|"external"|"shared" (if portalMode="dual"),
      //         tasks: [], involvement?: "daily"|"weekly"|"monthly",
      //         frequency?: string, painPoints?: []}
      // 'involvement', 'frequency', 'painPoints' are OPTIONAL — include when known
      {from Phase 3, section 4b}
    ],
    globalScope: {
      inScope: [
        // Shape: {feature, priority: "must"|"should"|"could", module, app?}
        {from Phase 3, section 4c + Phase 4 accepted suggestions + coverage matrix}
      ],
      outOfScope: [
        // Shape: {feature, reason}
        {from Phase 3, section 4c — Q2.15 exclusions}
      ]
    },
    applicationRoles: [{from Phase 5, section 6}],
    smartStackPatterns: {from Phase 4, section 4f — confirmed patterns},
    anticipatedEvolution: "{from Phase 4, section 4g — changes in 6mo/1yr}",
    dataRisks: "{from Phase 4, section 4g — business risks if data is incorrect/missing}",
    coverageMatrix: [{from Phase 5, section 7 — with anticipatedSections and anticipatedResources}],
    codebaseContext: "{string summary of codebase findings}"
  }
})

ba-writer.updateStatus({feature_id}, "framed")
```

### 9. Display Summary

```
## Cadrage Complete - {feature_id}

| Aspect | Count |
|--------|-------|
| Stakeholders | {count} |
| In-scope items | {count} |
| Application roles | {count} |
| Suggestions accepted | {count} |
| Anticipated sections | {total across all modules} |

### Application Roles
{table of roles with permission levels}

### Coverage Highlights
{top 3-5 must-have items with their anticipated sections}

### Next Step
→ Module structure analysis (step-02-structure.md)
```

---

## NEXT STEP

Load: `./step-02-structure.md`

> step-02 handles module structure analysis and entity/section definition.
