# Business Analysis - Shared Functions (v4 - Iterative Multi-Module Workflow)

> **Ref:** This file contains common functions for all BA phases.
> **Version:** 4.0 - Iterative multi-module workflow with 5-level navigation hierarchy

---

## Architecture Progressive

The BusinessAnalyse skill uses **progressive loading** to minimize context:

```
SKILL.md (entry point) → routes to use case
    ↓
steps/step-00-init.md (parse flags, create master feature.json via ba-writer)
    ↓
steps/step-01-cadrage.md (framing: context, stakeholders, scope, roles)
    ↓
steps/step-02-decomposition.md (module identification, dependency graph, CLIENT CHECKPOINT)
    ↓
steps/step-03-specify.md (ITERATIVE per module: sections, entities, BR, permissions, mockups)
    ↓                      ↻ loops back for each module in dependency order
steps/step-04-consolidation.md (cross-module validation, E2E flows, permissions coherence)
    ↓
steps/step-05-handoff.md (generates ralph prd.json per module)
```

**No digest files needed** — each step reads/writes `feature.json` directly via `ba-writer` and `ba-reader` agents.

**Benefit:** ~70% context reduction per phase

---

## JSON-First Architecture

All BA outputs are stored in **two levels** of feature.json, enriched progressively:

### Application-Level (Master)
**Path:** `docs/business/{app}/business-analyse/v{X.Y}/feature.json`
**Schema:** `docs/business/{app}/business-analyse/schemas/application-schema.json` (deployed to project by step-00)
**$schema:** `"../schemas/application-schema.json"` (relative in feature.json)

| Step | Section enriched | Status after |
|------|-----------------|--------------|
| 00-init | metadata | draft |
| 01-cadrage | cadrage (problem, stakeholders, scope, roles) | framed |
| 02-decomposition | modules, dependencyGraph | decomposed |
| 03-specify | modules[].status updated per iteration | specified |
| 04-consolidation | consolidation | consolidated |
| 05-handoff | (per-module handoff) | handed-off |

### Module-Level (Per Module)
**Path:** `docs/business/{app}/{module}/business-analyse/v{X.Y}/feature.json`
**Schema:** `docs/business/{app}/business-analyse/schemas/feature-schema.json` (deployed to project by step-00)
**$schema:** `"../../../business-analyse/schemas/feature-schema.json"` (relative in feature.json)

| Step | Section enriched | Status after |
|------|-----------------|--------------|
| 03-specify (init) | metadata, applicationContext | in-progress |
| 03-specify (sections) | specification.wireframes | in-progress |
| 03-specify (entities) | analysis.entities, analysis.businessRules | in-progress |
| 03-specify (spec) | specification (full) | specified |
| 03-specify (validate) | validation | validated |

**Agents:**
- **ba-writer**: Writes/updates feature.json (create, enrichSection, updateStatus, createVersion, createApplicationFeature, advanceModuleLoop)
- **ba-reader**: Reads feature.json (findFeature, readSection, answerQuestion, getSummaryForSkill, readApplicationContext, getCompletedModulesSummary)

**Schemas:** Deployed to project at `docs/business/{app}/business-analyse/schemas/` (9 files). Source: `schemas/` in skill directory. Every feature.json includes `$schema` relative reference.

---

## 5-Level Navigation Hierarchy (SmartStack)

> **This is the structuring principle of the entire BA workflow.**

The BA aligns with the SmartStack navigation hierarchy:

```
Level 1: Context (business)
  └── Level 2: Application (Sales)
       ├── Level 3: Module (Customers)
       │    ├── Level 4: Section (list)
       │    │    └── Level 5: Ressource (customer-card)
       │    ├── Level 4: Section (detail)
       │    │    └── Level 5: Ressource (customer-form)
       │    └── Level 4: Section (create)
       └── Level 3: Module (Orders)
            ├── Level 4: Section (list)
            ├── Level 4: Section (detail)
            ├── Level 4: Section (create)
            └── Level 4: Section (approve)
```

| BA Phase | Levels treated | What is defined |
|----------|---------------|-----------------|
| Cadrage (step-01) | Context + Application | Problem, stakeholders, scope, application-level roles |
| Decomposition (step-02) | Modules | Module list, dependencies, processing order |
| Specification (step-03) | Module → Sections → Resources | Entities, BR, UC, permissions, ASCII/SVG mockups per section |
| Consolidation (step-04) | Cross-module | Interactions, permission coherence, E2E flows |
| Handoff (step-05) | All levels | Implementation mapping, prd.json |

### Route pattern
```
/business/{application}/{module}/{section}
```

### Standard Sections per Module
| Section | Purpose | Typical Components |
|---------|---------|-------------------|
| `list` | Main entity list with filters | DataGrid, FilterBar, Pagination |
| `detail` | Entity detail view | DetailCard, TabPanel, StatusBadge |
| `create` | Create new entity | Form, Validation, SubmitButton |
| `edit` | Edit existing entity | Form (pre-filled), Validation |
| `approve` | Approval workflow | ApprovalPanel, StatusTimeline |
| `dashboard` | Module overview/KPIs | Charts, StatCards, RecentActivity |
| `import` | Bulk data import | FileUpload, MappingTable, Preview |
| `export` | Data export | FormatSelector, FilterOptions |

---

## Module Loop Protocol

> **Step-03 iterates over modules.** State is persisted in the master feature.json.

### State Management

```json
{
  "metadata": {
    "workflow": {
      "mode": "application",
      "moduleOrder": ["Customers", "Products", "Orders", "Invoices"],
      "currentModuleIndex": 2,
      "completedModules": ["Customers", "Products"],
      "currentModule": "Orders"
    }
  }
}
```

### Loop Logic (end of each step-03 iteration)

```
1. Mark current module as "validated" in master feature.json
2. Add to completedModules[]
3. IF currentModuleIndex + 1 < moduleOrder.length:
     currentModuleIndex++
     currentModule = moduleOrder[currentModuleIndex]
     Write master feature.json
     Display: "Module {name} complete. Next: {next_name} ({N}/{total})"
     RE-LOAD: steps/step-03-specify.md
4. ELSE:
     master.status = "specified"
     Load: steps/step-04-consolidation.md
```

### Context Management During Loop

To prevent context explosion as modules accumulate:
- **Current module:** Load full module feature.json
- **Completed modules:** Only load compact summary via `ba-reader.getCompletedModulesSummary()` (max 100 lines)
- **Master feature.json:** Only read workflow state + application roles

### Resume After Interruption

```
1. ba-reader.findApplicationFeature() → locate master feature.json
2. Read metadata.workflow.currentModuleIndex
3. IF currentModule has a feature.json with status != "validated":
     Resume step-03-specify for that module
4. ELSE:
     Start step-03-specify for next module
```

---

## Use Case Routing

| Flag | Use Case | Workflow |
|------|----------|---------|
| (none) | Single module | step-00 → step-01 → step-02 (trivial) → step-03 (1 iteration) → step-04 (auto) → step-05 |
| `-app` | Application (multi-module) | step-00 → step-01 → step-02 → step-03 (N iterations) → step-04 → step-05 |
| `-q FEAT-ID "question"` | Question | ba-reader.answerQuestion → EXIT |
| `-r FEAT-ID "change"` | Refactoring | ba-writer.createVersion → step-01 (delta) → step-02 → step-03 → step-04 → step-05 |
| `-m` | Micro-feature | step-00 (minimal) → step-05 (simplified) |

---

## Business Context Validation

```
validate_business_context(context):
  IF context IN ['platform', 'personal', 'system'] THEN
    ERROR "BA restricted to 'business' context. Contact: support@atlshub.ch"
    RETURN false
  END IF
  RETURN true
```

**CRITICAL:** BusinessAnalyze works ONLY for the `business` context.

---

## Architecture SmartStack (Référence BA)

> **Objectif :** Fournir le contexte architectural au BA pour des questions pertinentes et des recommandations alignées.

### 5 Couches (Clean Architecture)

| Couche | Projet | Contenu | Impact BA |
|--------|--------|---------|-----------|
| **Domain** | `SmartStack.Domain` | Entités, enums, interfaces | Entités identifiées en discovery |
| **Application** | `SmartStack.Application` | CQRS (Commands/Queries), validations, DTOs | Use cases de la spécification |
| **Infrastructure** | `SmartStack.Infrastructure` | EF Core, services externes, jobs | Intégrations et contraintes techniques |
| **API** | `SmartStack.API` | Controllers REST, permissions | Endpoints et sécurité |
| **Web** | `smartstack-web` | React 19, pages, composants | UI/UX et navigation |

### Hiérarchie de Navigation

```
Context (business) → Application (Sales) → Module (Orders) → Section (list/detail)
```

Route pattern : `/business/{application}/{module}/{section}`

### Classes de Base des Entités

| Classe | Interface | Champs auto-inclus | Quand utiliser |
|--------|-----------|---------------------|----------------|
| `BaseEntity` | - | `Id` (Guid), `TenantId`, `CreatedAt`, `UpdatedAt` | **Défaut pour toute entité métier** |
| `BaseEntity` | `IAuditableEntity` | + `CreatedBy`, `UpdatedBy` | Entité avec audit complet |
| `SystemEntity` | - | `Id` (Guid), `CreatedAt` (pas de TenantId) | Entités système (navigation, permissions) |
| `BaseEntity` | `ISoftDeletable` | + `IsDeleted`, `DeletedBy`, `DeletedAt` | Entité avec suppression logique |
| `HierarchicalEntity` | - | + `ParentId`, `Level`, `Path` | Arborescences (catégories, menus) |

> **IMPORTANT :** Ne JAMAIS proposer `CreatedBy`, `UpdatedBy`, `IsDeleted`, `TenantId` comme champs explicites — ils sont AUTOMATIQUES via la classe de base ou l'interface.

### Services d'Intégration Disponibles

| Service | Interface | Quand le proposer |
|---------|-----------|-------------------|
| Notifications in-app | `INotificationService` | Alertes, événements, rappels |
| Workflow automatisé | `IWorkflowService` | Emails transactionnels, webhooks, actions chaînées |
| Complétion IA | `IAICompletionService` | Suggestions, classification, génération contenu |
| SignalR temps réel | `IHubContext<BusinessHub>` | Mises à jour en temps réel |
| Jobs planifiés | Hangfire `IBackgroundJobClient` | Traitements différés, purges, imports |

### Conventions Base de Données

| Aspect | Convention | Exemple |
|--------|------------|---------|
| Schema | `core` (socle SmartStack) vs `extensions` (entités client/métier) | `core.auth_Roles`, `extensions.bik_FreeBickes` |
| Tables | `{prefix}_{EntityPlural}` (préfixe domaine + PascalCase pluriel) | `auth_Users`, `nav_Applications`, `supp_Tickets` |
| Préfixes domaine | `auth_` (auth), `nav_` (navigation), `cfg_` (config), `ref_` (références), `wkf_` (workflows), `ai_` (IA), `loc_` (i18n), `lic_` (licences), `tenant_` (tenants), `support_` (support) | Pour un nouveau module métier : choisir un préfixe court (3-5 chars) |
| FK | `{Entity}Id` (ex: `ClientId`, `OrderId`) | |
| Index | `IX_{Table}_{Column}` | `IX_bik_FreeBickes_TenantId_Code` |
| Migration | 1 migration par feature, nommée via MCP (`suggest_migration`) | `extensions_v1.0.0_001_AddFreeBicke` |

### Conventions de Dossiers (Clean Architecture)

| Couche | Pattern de dossiers | Exemple (module FreeBicke dans business > operations) |
|--------|--------------------|---------------------------------------------------------|
| **Domain** | `{Project}.Domain/Business/{Application}/{Module}/` | `Domain/Business/Operations/FreeBicke/FreeBicke.cs` |
| **Application/DTOs** | `{Project}.Application/Business/{Application}/{Module}/DTOs/` | `Application/Business/Operations/FreeBicke/DTOs/FreeBickeDto.cs` |
| **Application/Interfaces** | `{Project}.Application/Common/Interfaces/` | `Application/Common/Interfaces/IFreeBickeService.cs` |
| **Infrastructure/Config** | `{Project}.Infrastructure/Persistence/Configurations/{Module}/` | `Configurations/FreeBicke/FreeBickeConfiguration.cs` |
| **Infrastructure/Services** | `{Project}.Infrastructure/Services/{Module}/` | `Services/FreeBicke/FreeBickeService.cs` |
| **Infrastructure/SeedData** | `{Project}.Infrastructure/Persistence/Seeding/Data/{Module}/` | `Seeding/Data/FreeBicke/FreeBickeSeedData.cs` |
| **API/Controllers** | `{Project}.Api/Controllers/Business/{Application}/` | `Controllers/Business/Operations/FreeBickeController.cs` |
| **Frontend/Pages** | `web/src/pages/business/{application}/{module}/` | `pages/business/operations/freebicke/page.tsx` |
| **Frontend/i18n** | `web/src/i18n/locales/{lang}/{module}.json` | `locales/fr/freebicke.json` |

> **IMPORTANT :** Chaque module a son **propre sous-dossier** dans chaque couche. Ne JAMAIS mettre tous les fichiers à la racine d'une couche.

### SeedData Core (Obligatoire pour chaque feature)

> **Chaque nouvelle feature nécessite des SeedData dans 5 fichiers core** pour être fonctionnelle (navigation visible, permissions actives, rôles assignés).

| # | Fichier | Contenu | Mécanisme |
|---|---------|---------|-----------|
| 1 | `NavigationModuleConfiguration.cs` | Entrée module dans `nav_Modules` (HasData) | EF Core Migration |
| 2 | `NavigationTranslationConfiguration.cs` | Traductions du module (4 langues × chaque entité nav) | EF Core Migration |
| 3 | `PermissionConfiguration.cs` | Permissions CRUD + wildcards dans `nav_Permissions` (HasData) | EF Core Migration |
| 4 | `Permissions.cs` (Application layer) | Constantes compile-time pour `[RequirePermission]` | Code |
| 5 | `RolePermissionConfiguration.cs` | Associations rôle-permission dans `auth_RolePermissions` (HasData) | EF Core Migration |

**Rôles par défaut pour chaque application (4 niveaux) :**

| Rôle | Permissions | Description |
|------|-------------|-------------|
| **{App} Admin** | `{context}.{app}.*` (wildcard) | Accès complet à l'application |
| **{App} Manager** | `read`, `create`, `update`, `assign` | Gestion complète sans suppression |
| **{App} Contributor** | `read`, `create`, `update` | Contribution active |
| **{App} Viewer** | `read` uniquement | Consultation seule |

> **CRITIQUE :** Si les SeedData ne sont pas créés, le module sera invisible dans la navigation et les permissions retourneront 403.

### Contraintes Non-Négociables

| Contrainte | Détail |
|------------|--------|
| **Multi-tenant** | `TenantId` sur toute entité métier, isolation automatique |
| **RBAC** | Permissions `business.{app}.{module}.{action}`, HasData pattern |
| **CQRS** | Commands (write) et Queries (read) séparés via MediatR |
| **Validation** | FluentValidation pour toute commande |
| **i18n** | 4 langues obligatoires (fr, en, it, de) |
| **Soft Delete** | Pas de DELETE physique sauf purge RGPD planifiée |

### Outils MCP Pertinents pour le BA

| Phase BA | Outil MCP | Usage |
|----------|-----------|-------|
| Pre-research (01) | `analyze_extension_points` | Découvrir modules/entités existants |
| Pre-research (01) | `api_docs` | Consulter la documentation API existante |
| Analyse (02) | `validate_conventions` | Vérifier les noms d'entités proposés |
| Spécification (03) | `generate_permissions` | Générer la matrice de permissions |
| Handoff (05) | `scaffold_extension` | Préparer le scaffolding |

---

## Feature Directory Structure

```
docs/
├── business/
│   └── {application}/
│       ├── business-analyse/
│       │   ├── schemas/                  ← JSON SCHEMAS (deployed by step-00)
│       │   │   ├── feature-schema.json
│       │   │   ├── application-schema.json
│       │   │   ├── sections/
│       │   │   │   ├── analysis-schema.json
│       │   │   │   ├── discovery-schema.json
│       │   │   │   ├── handoff-schema.json
│       │   │   │   ├── metadata-schema.json
│       │   │   │   ├── specification-schema.json
│       │   │   │   └── validation-schema.json
│       │   │   └── shared/
│       │   │       └── common-defs.json
│       │   └── v1.0/
│       │       └── feature.json          ← APPLICATION master ($schema: ../schemas/application-schema.json)
│       ├── {module1}/
│       │   └── business-analyse/
│       │       └── v1.0/
│       │           └── feature.json      ← MODULE detail ($schema: ../../../business-analyse/schemas/feature-schema.json)
│       └── {module2}/
│           └── business-analyse/
│               └── v1.0/
│                   └── feature.json      ← MODULE detail
```

**Ralph Loop Integration (generated by step-05):**

```
.ralph/
├── prd.json          # Task breakdown derived from handoff (for /ralph-loop -r)
├── progress.txt      # Links back to BA feature documents
├── logs/
└── reports/
```

**Integrated Documentation (SmartStack app):**
- Application view: `/docs/business/{app}` → reads master feature.json
- Module view: `/docs/business/{app}/{module}` → reads module feature.json

---

## Feature ID Generation

```
generate_feature_id():
  last_id = read_config(".business-analyse/config.json", "lastFeatureId") OR 0
  new_id = last_id + 1
  update_config(".business-analyse/config.json", "lastFeatureId", new_id)
  RETURN format("FEAT-%03d", new_id)
```

---

## Models by Phase (Step)

| Step | Model | Reason |
|------|-------|--------|
| 00-init | Haiku | Quick structure setup |
| 01-cadrage | **Opus** | ULTRATHINK framing |
| 02-decomposition | Sonnet | Module identification + dependency analysis |
| 03-specify | **Opus** | ULTRATHINK per-module specification |
| 04-consolidation | Sonnet | Cross-module validation |
| 05-handoff | **Opus** | Zero-ambiguity prompt |

---

## Interactive Elicitation Protocol

> **RULE: ALL questions MUST be asked interactively using `AskUserQuestion`.**
> **NEVER dump a list of questions as text. ALWAYS use the tool.**

### Protocol

1. **Group questions by theme** — max 4 questions per `AskUserQuestion` call (tool limit)
2. **Propose predefined options** — for questions with predictable answers, provide 2-4 options
3. **The user can always choose "Other"** — the tool adds this automatically for free-text answers
4. **Process answers immediately** — apply ULTRATHINK + follow-ups before moving to next group
5. **Adapt next questions** — based on previous answers, skip irrelevant questions

### Batching Strategy

| Category | Questions | Batches |
|----------|-----------|---------|
| 01-context | Q1.1-Q1.4 | 1 call |
| 02-stakeholders | Q2.1-Q2.8 | 2 calls |
| 03-scope | Q3.1-Q3.8 | 2 calls |
| 04-data | Q4.1-Q4.8 | 2 calls |
| 05-integrations | Q5.1-Q5.8 | 2 calls |
| 06-security | Q6.1-Q6.8 | 2 calls |
| 07-ui | Q7.1-Q7.8 | 2 calls |
| 08-performance | Q8.1-Q8.4 | 1 call |
| 09-constraints | Q9.1-Q9.4 | 1 call |
| 10-documentation | Q10.1-Q10.4 | 1 call |
| 11-data-lifecycle | Q11.1-Q11.8 | 2 calls |
| 12-migration | Q12.1-Q12.8 | 2 calls |
| 13-cross-module | Q13.1-Q13.8 | 2 calls |

### AskUserQuestion Format

> **⚠️ FORMATTING CRITICAL: `AskUserQuestion` does NOT support markdown or line breaks.**
> Le champ `question` est rendu en texte brut (plain text). Il n'y a pas de retour à la ligne,
> pas de gras, pas de puces. Une question simple reste lisible meme longue. Mais du contenu
> structuré (listes, résumés multi-points, tableaux) devient un mur de texte illisible.

| Field | Rule |
|-------|------|
| `question` | **1 question ou 1 phrase.** Jamais de liste, résumé multi-points ou contenu structuré. |
| `header` | 1-2 mots (max 12 chars) |
| `label` (option) | Court et clair (~20 chars) |
| `description` (option) | 1 phrase explicative (~60 chars) |

> **Pour afficher du contenu structuré** (résumés, listes, tableaux, synthèses) :
> **TOUJOURS** utiliser du **texte direct** (output text) AVANT l'appel `AskUserQuestion`.
> Le texte direct supporte le markdown et sera correctement formaté avec titres, puces, gras, etc.
>
> **Exemple — Validation de synthèse :**
> 1. Afficher le résumé structuré en markdown (texte direct)
> 2. Puis poser une question courte : "Cette synthèse est-elle correcte ?"

```
AskUserQuestion({
  questions: [
    {
      question: "Quel problème métier ce module doit-il résoudre ?",
      header: "Problème",       // max 12 chars
      options: [
        { label: "Processus manuel", description: "Automatiser un processus existant fait manuellement" },
        { label: "Données dispersées", description: "Centraliser des données éparpillées dans plusieurs outils" },
        { label: "Manque visibilité", description: "Obtenir des indicateurs et du suivi inexistants aujourd'hui" },
        { label: "Conformité", description: "Répondre à une obligation réglementaire ou de sécurité" }
      ],
      multiSelect: false
    },
    // ... up to 4 questions per call
  ]
})
```

### After Each Batch

1. **Evaluate answer quality** (see Answer Quality Indicators)
2. **If insufficient** → follow-up AskUserQuestion with targeted probes from the Elicitation Guide
3. **If solution-oriented** → reframe using Technique 1 before proceeding
4. **If sufficient/excellent** → record and move to next batch
5. **Summarize** what was understood before moving to the next category

---

## Elicitation Techniques

> **Loaded by:** step-01-analyse (Opus ULTRATHINK)
> **Purpose:** Guide HOW to question, not just WHAT to ask.

### Technique 1: Solution → Problem Reframing

If the user describes a **solution** (button, field, screen, API), reframe as a **need**:

| User says | BA agent asks |
|-----------|---------------|
| "I need a Role dropdown on the User form" | "What problem are you trying to solve with different user access levels?" |
| "We need an export button" | "What do you do with the exported data? Who needs it and why?" |
| "Add a status field" | "What lifecycle does this entity go through? What triggers each transition?" |

### Technique 2: 5 Whys (Root Cause)

When the need seems superficial, chain up to 5 "Why?":

```
User: "We need to track user activity"
→ Why? "To know who modified what"
→ Why? "Because we had data integrity issues"
→ Why? "Because multiple people edit the same records"
→ ROOT CAUSE: Concurrent editing conflict → Need audit trail + optimistic locking
```

### Technique 3: Concrete Scenario Extraction

Never accept abstract descriptions. Always ask for **a real day-in-the-life scenario**:

```
"Walk me through a typical day: you arrive at the office,
 you open the application — what is the FIRST thing you need to do?
 Then what? What information do you look at? What decisions do you make?"
```

### Technique 4: Absence Test

Validate necessity by asking what happens WITHOUT:

```
"If this feature did NOT exist, what would you do instead?
 How much time/money does the current workaround cost?"
```

### Technique 5: Completeness Probing

For every list answer, challenge completeness:

| Answer type | Probe |
|-------------|-------|
| "There are 3 user types" | "Are there external actors? Auditors? System admins? Automated processes?" |
| "The main flow is A→B→C" | "What if the user cancels at step B? What if step C fails? What if they go back to A?" |
| "Required fields: name, email" | "What uniqueness constraints? What format? What happens on duplicate?" |

### Answer Quality Indicators

| Quality | Signal | Action |
|---------|--------|--------|
| **Insufficient** | < 1 sentence, "I don't know", vague adjective | Apply technique 1-5, ask for concrete example |
| **Solution-oriented** | Contains UI/tech terms (button, field, API, database) | Apply technique 1 (reframe to problem) |
| **Sufficient** | Contains WHO, WHAT, WHY, concrete example | Proceed, note confidence level |
| **Excellent** | Includes edge cases, constraints, measurable criteria | Proceed, mark as "Confirmed" |

---

## ULTRATHINK

Behavioral mode for critical phases (01, 02, 04):

```
ULTRATHINK MODE:
- Consider ALL edge cases
- Challenge EVERY assumption
- Anticipate UNEXPRESSED needs
- Validate completeness before output
- Apply Elicitation Techniques (see above)

DO NOT:
- Accept vague answers
- Skip question categories
- Assume stakeholder thought of everything
- Accept solutions without understanding the problem first
```

**DO NOT invoke** as a skill/tool - it is a thinking mode.

---

## Proactive Suggestions

After scope definition in step-01, the skill suggests complementary modules/sections:

1. Analyze feature type and scope from questionnaire answers
2. Load `patterns/suggestion-catalog.md`
3. Match against catalog patterns
4. Present suggestions via AskUserQuestion (accept/reject per suggestion)
5. Store in feature.json.suggestions[]

Accepted suggestions become candidates for future /business-analyse runs.

---

## Context7 (Step 04)

```
Prompt pattern:
"use context7 with /facebook/react and /i18next/react-i18next
 to generate {component} following SmartStack patterns"
```

Libraries:
- `/facebook/react` - React 19 patterns
- `/i18next/react-i18next` - Internationalization
- `/remix-run/react-router` - React Router v7
- `/lucide-icons/lucide-react` - Icons

---

## Permission Path Format

**Format:** `business.{application}.{module}.{action}`

| Action | Permission | Usage |
|--------|------------|-------|
| Read | `.read` | GET endpoints |
| Create | `.create` | POST endpoints |
| Update | `.update` | PUT endpoints |
| Delete | `.delete` | DELETE endpoints |
| Export | `.export` | Export data |
| Import | `.import` | Import data |
| Admin | `.admin` | Administrative |

---

## i18n (4 required languages)

| Language | File | Code |
|----------|------|------|
| French | `fr/docs-{app}-{module}.json` | fr |
| English | `en/docs-{app}-{module}.json` | en |
| Italian | `it/docs-{app}-{module}.json` | it |
| German | `de/docs-{app}-{module}.json` | de |

---

## Output Paths

| Type | Path |
|------|------|
| BA Feature | `docs/business/{app}/{module}/business-analyse/v{X.Y}/feature.json` |
| User Guide | `docs/business/{app}/{module}/user-guide/v{X.Y}/guide.json` |
| i18n | `web/smartstack-web/src/i18n/locales/{lang}/` |

---

## State Persistence

State is persisted in `feature.json.metadata` and `feature.json.metadata.steps`. Each step reads/writes via `ba-writer` and `ba-reader` agents.

```json
{
  "metadata": {
    "featureId": "FEAT-001",
    "status": "analysed",
    "steps": {
      "00-init": { "completed": "2025-02-01T10:00:00Z" },
      "01-analyse": { "completed": "2025-02-01T11:30:00Z" },
      "02-specify": { "inProgress": true }
    }
  }
}
```

---

## Resume Workflow

```
resume_workflow(feat_id):
  1. ba-reader.findFeature(feat_id) → latest feature.json
  2. Read feature.json.metadata.steps → find last completed step
  3. Load next step file
  4. If not found in docs/: fallback to .business-analyse/ (legacy)
```

---

## Standard Summary (End of Step)

```
{STEP_NAME} - {feature_id}
├── Status: {status in feature.json}
├── Section enriched: {discovery|analysis|specification|validation|handoff}
├── feature.json: {path}
└── Next: {next step name}
```

---

## Configuration Langue de Communication

> **Objectif :** La langue de communication avec le client est configurable.
> Toute interaction via `AskUserQuestion` (questions, options, reformulations, relances)
> doit être dans la langue configurée.

### Configuration

Le champ `language` dans `feature.json.metadata.language` définit la langue :

| Langue | Code | Défaut |
|--------|------|--------|
| Français | `fr` | **Oui** |
| English | `en` | Non |
| Italiano | `it` | Non |
| Deutsch | `de` | Non |

### Portée

| Élément | Adapté à la langue ? |
|---------|---------------------|
| Questions `AskUserQuestion` (labels, descriptions, options) | **OUI** — toujours dans `{language}` |
| Reformulations et résumés de catégorie | **OUI** — toujours dans `{language}` |
| Relances et follow-ups (Elicitation Guide) | **OUI** — traduire les probes à la volée |
| Documents générés (discovery, analysis, specification, handoff) | **OUI** — rédigés dans `{language}` |
| Référence technique interne (patterns, architecture) | NON — reste en langue du fichier |
| Noms de code (entités, permissions, paths) | NON — toujours en anglais (convention plateforme) |

### Règle

```
1. Lire {language} depuis feature.json.metadata.language (défaut: "fr")
2. Adapter TOUTE communication AskUserQuestion dans {language}
3. Les exemples de probes/relances dans les questionnaires sont en français
   → Si {language} ≠ "fr", les traduire à la volée
4. Les documents générés sont rédigés dans {language}
5. Le code, les noms d'entités et les paths restent TOUJOURS en anglais
6. Ne JAMAIS utiliser "SmartStack" dans les communications utilisateur
   → Utiliser "la plateforme", "l'application" ou "le système" à la place
   → SmartStack est le nom interne du framework, le projet client a son propre nom
```

---

## Config Template

```json
{
  "project": "{Name}",
  "lastFeatureId": 0,
  "context": "business",
  "language": "fr",
  "standards": ["BABOK-v3", "IEEE-830"],
  "contact": "support@atlshub.ch"
}
```

---

## Support

Contact: **support@atlshub.ch**
