---
description: Orchestration automatique BA complete (ULTRATHINK + Ralph Loop)
argument-hint: "<description du besoin>"
model: opus
---

# Phase 0: Orchestration Automatique Business Analyse

> **Modele:** OPUS (orchestration complete, zero intervention)
> **Cout estime:** ~$15-50 (full flow avec Ralph Loop)
> **Prerequis:** Aucun - Point d'entree unique

---

## MISSION

```
+==============================================================================+
|  ORCHESTRATION COMPLETE: BESOIN → IMPLEMENTATION → DOCUMENTATION             |
+==============================================================================+
|                                                                              |
|  Cette commande orchestre AUTOMATIQUEMENT tout le workflow BA:               |
|                                                                              |
|  1. ANALYSE DU BESOIN (ce fichier)                                           |
|     → Contexte SmartStack (MCP verification)                                 |
|     → Application/Module existant ou nouveau                                 |
|     → Niveau de granularite (Muscles/Section/Resources)                      |
|                                                                              |
|  2. DISCOVERY + BRD + FRD (Phases 1-4)                                       |
|     → Ralph Loop si necessaire                                               |
|     → Validation automatique                                                 |
|                                                                              |
|  3. VALIDATION UTILISATEUR (Phase 5)                                         |
|     → Gate obligatoire                                                       |
|                                                                              |
|  4. HANDOFF + IMPLEMENTATION (Phases 6 + /implement)                         |
|     → Ralph Loop obligatoire                                                 |
|     → Skills SmartStack auto-executes                                        |
|                                                                              |
|  5. DOCUMENTATION HTML (Phase 7)                                             |
|     → Auto-generee apres implementation                                      |
|                                                                              |
+==============================================================================+
```

---

## STEP 0: VERIFICATION MCP SMARTSTACK (CRITIQUE)

```bash
# Verifier la presence du MCP SmartStack
MCP_CHECK=$(claude mcp list 2>/dev/null | grep -i "smartstack" || echo "")

if [ -z "$MCP_CHECK" ]; then
  echo ""
  echo "╔══════════════════════════════════════════════════════════════════════════════╗"
  echo "║                     ⚠️  ALERTE: MCP SMARTSTACK NON DETECTE                    ║"
  echo "╠══════════════════════════════════════════════════════════════════════════════╣"
  echo "║                                                                              ║"
  echo "║  Le MCP SmartStack n'est pas configure dans cette session.                   ║"
  echo "║                                                                              ║"
  echo "║  CONSEQUENCES:                                                               ║"
  echo "║  • Pas d'acces aux applications existantes                                   ║"
  echo "║  • Pas de validation des permissions                                         ║"
  echo "║  • Pas d'integration notifications/workflows/IA                              ║"
  echo "║                                                                              ║"
  echo "║  ACTIONS REQUISES:                                                           ║"
  echo "║  1. Verifier la configuration MCP: claude mcp list                           ║"
  echo "║  2. Ajouter SmartStack MCP si absent                                         ║"
  echo "║  3. Relancer /business-analyse                                               ║"
  echo "║                                                                              ║"
  echo "╚══════════════════════════════════════════════════════════════════════════════╝"
  echo ""
  # Ne pas bloquer mais alerter - continuer avec limitations
  MCP_AVAILABLE=false
else
  echo "✅ MCP SmartStack detecte: $MCP_CHECK"
  MCP_AVAILABLE=true
fi
```

---

## STEP 1: ANALYSE DU BESOIN UTILISATEUR

### 1.1 Collecter la description

```
BESOIN_UTILISATEUR = "$ARGUMENTS"

Si vide, utiliser AskUserQuestion:
```

```javascript
AskUserQuestion({
  questions: [{
    question: "Decrivez votre besoin en une phrase claire",
    header: "Besoin",
    options: [
      { label: "Nouvelle fonctionnalite", description: "Ajouter une capacite metier" },
      { label: "Amelioration existante", description: "Enrichir une feature existante" },
      { label: "Integration", description: "Connecter avec systeme externe" }
    ],
    multiSelect: false
  }]
})
```

### 1.2 Determiner le contexte SmartStack

**ULTRATHINK: Analyser le besoin pour determiner:**

| Question | Options | Impact |
|----------|---------|--------|
| Application existante? | Liste des apps business | Reutilisation patterns |
| Module existant? | Liste des modules de l'app | Coherence architecture |
| Nouveau module? | Nom propose | Structure a creer |

```javascript
AskUserQuestion({
  questions: [
    {
      question: "Dans quelle application SmartStack?",
      header: "Application",
      options: [
        { label: "CRM", description: "Gestion relation client" },
        { label: "Inventory", description: "Gestion des stocks" },
        { label: "HR", description: "Ressources humaines" },
        { label: "Nouvelle application", description: "Creer une nouvelle app business" }
      ],
      multiSelect: false
    }
  ]
})

// Si MCP_AVAILABLE, lister les applications existantes dynamiquement
// via appel MCP: smartstack.applications.list()
```

---

## STEP 2: DEFINIR LE NIVEAU DE GRANULARITE

### 2.1 Architecture SmartStack - 3 Niveaux

```
╔══════════════════════════════════════════════════════════════════════════════╗
║                    NIVEAUX DE GRANULARITE SMARTSTACK                          ║
╠══════════════════════════════════════════════════════════════════════════════╣
║                                                                              ║
║  NIVEAU 1: MUSCLES (Fonctionnalites majeures)                                ║
║  ├── Definition: Capacite metier complete et autonome                        ║
║  ├── Exemple: "Gestion des Contacts", "Gestion des Produits"                 ║
║  ├── Contient: Entites + CRUD + Regles metier + UI complete                  ║
║  └── Permission: business.{app}.{muscle}.*                                   ║
║                                                                              ║
║  NIVEAU 2: SECTIONS (Sous-fonctionnalites)                                   ║
║  ├── Definition: Partie d'un Muscle avec logique specifique                  ║
║  ├── Exemple: "Import Contacts", "Export Produits", "Historique"             ║
║  ├── Contient: Endpoints specifiques + UI partielle                          ║
║  └── Permission: business.{app}.{muscle}.{section}.*                         ║
║                                                                              ║
║  NIVEAU 3: RESOURCES (Elements atomiques)                                    ║
║  ├── Definition: Donnee ou action unitaire                                   ║
║  ├── Exemple: "Champ custom", "Action rapide", "Widget"                      ║
║  ├── Contient: 1 endpoint ou 1 composant                                     ║
║  └── Permission: herite du parent                                            ║
║                                                                              ║
╚══════════════════════════════════════════════════════════════════════════════╝
```

### 2.2 Questionnaire de granularite

```javascript
AskUserQuestion({
  questions: [{
    question: "Quel niveau de granularite pour ce besoin?",
    header: "Niveau",
    options: [
      { label: "Muscle (Recommande)", description: "Fonctionnalite complete avec entites, CRUD, UI" },
      { label: "Section", description: "Sous-fonctionnalite d'un Muscle existant" },
      { label: "Resource", description: "Element atomique (champ, action, widget)" }
    ],
    multiSelect: false
  }]
})
```

---

## STEP 3: DEFINIR LES OBJECTIFS

### 3.1 Objets a creer

```javascript
AskUserQuestion({
  questions: [{
    question: "Quels objets/entites sont necessaires?",
    header: "Entites",
    options: [
      { label: "Entite principale", description: "L'objet metier central (ex: Contact, Produit)" },
      { label: "Entites liees", description: "Objets dependants (ex: Adresse, Categorie)" },
      { label: "Lookup/Enum", description: "Listes de valeurs (ex: Status, Type)" }
    ],
    multiSelect: true
  }]
})
```

### 3.2 Permissions requises

```
PERMISSIONS A DEFINIR:
□ .read    - Lecture des donnees
□ .create  - Creation de nouvelles entrees
□ .update  - Modification des entrees
□ .delete  - Suppression des entrees
□ .export  - Export des donnees
□ .import  - Import des donnees
□ .admin   - Administration du module
```

### 3.3 Aspects legaux (RGPD, conformite)

```javascript
AskUserQuestion({
  questions: [{
    question: "Y a-t-il des contraintes legales/conformite?",
    header: "Legal",
    options: [
      { label: "RGPD", description: "Donnees personnelles, droit a l'oubli, consentement" },
      { label: "Audit Trail", description: "Tracabilite obligatoire des modifications" },
      { label: "Retention", description: "Duree de conservation des donnees" },
      { label: "Aucune", description: "Pas de contrainte specifique" }
    ],
    multiSelect: true
  }]
})
```

---

## STEP 4: INTEGRATIONS SMARTSTACK

### 4.1 Workflows

```javascript
AskUserQuestion({
  questions: [{
    question: "Quels workflows automatiques sont necessaires?",
    header: "Workflows",
    options: [
      { label: "Email automatique", description: "Envoi d'emails sur evenements" },
      { label: "Rappels/SLA", description: "Notifications avec delais" },
      { label: "Approbation", description: "Circuit de validation" },
      { label: "Aucun", description: "Pas de workflow" }
    ],
    multiSelect: true
  }]
})
```

### 4.2 Notifications

```javascript
AskUserQuestion({
  questions: [{
    question: "Quelles notifications en temps reel?",
    header: "Notifs",
    options: [
      { label: "Creation", description: "Notifier quand nouvel element cree" },
      { label: "Modification", description: "Notifier sur changements" },
      { label: "Assignation", description: "Notifier le nouvel assigne" },
      { label: "Aucune", description: "Pas de notification" }
    ],
    multiSelect: true
  }]
})
```

### 4.3 Intelligence Artificielle

```javascript
AskUserQuestion({
  questions: [{
    question: "Utilisation de l'IA SmartStack?",
    header: "IA",
    options: [
      { label: "Generation texte", description: "Suggestions, descriptions auto" },
      { label: "Classification", description: "Categorisation automatique" },
      { label: "Extraction", description: "Parsing de documents" },
      { label: "Aucune", description: "Pas d'IA" }
    ],
    multiSelect: true
  }]
})
```

---

## STEP 5: GENERER LE CONTEXTE COMPLET

### 5.1 Creer le fichier de contexte

```bash
FEATURE_ID="FEAT-$(date +%Y%m%d-%H%M%S)"
APP_NAME="{application}"
MODULE_NAME="{module}"
FEATURE_DIR=".business-analyse/business/${APP_NAME}/modules/${MODULE_NAME}/features/${FEATURE_ID}"

mkdir -p "$FEATURE_DIR"
mkdir -p "$FEATURE_DIR/.ralph"
```

### 5.2 Generer context.json

```json
{
  "feature_id": "{FEATURE_ID}",
  "created_at": "{timestamp}",
  "mcp_available": "{true/false}",

  "smartstack_context": {
    "application": "{APP_NAME}",
    "module": "{MODULE_NAME}",
    "granularity": "{muscle/section/resource}",
    "is_new_app": "{true/false}",
    "is_new_module": "{true/false}"
  },

  "requirements": {
    "description": "{BESOIN_UTILISATEUR}",
    "entities": ["{liste}"],
    "permissions": ["{liste}"],
    "legal_constraints": ["{liste}"]
  },

  "integrations": {
    "workflows": {
      "required": "{true/false}",
      "types": ["{liste}"]
    },
    "notifications": {
      "required": "{true/false}",
      "events": ["{liste}"]
    },
    "ai": {
      "required": "{true/false}",
      "use_cases": ["{liste}"]
    }
  },

  "ralph_config": {
    "discovery_max_iterations": 15,
    "handoff_max_iterations": 10,
    "implement_max_iterations": 25,
    "completion_promise": "FEATURE_COMPLETE"
  }
}
```

---

## STEP 6: CREER LES FICHIERS RALPH LOOP

### 6.1 prd.json pour Discovery

```json
{
  "feature_id": "{FEATURE_ID}",
  "phase": "discovery",
  "created_at": "{timestamp}",
  "userStories": [
    { "id": "1", "title": "Contexte et objectifs", "passes": false },
    { "id": "2", "title": "Parties prenantes", "passes": false },
    { "id": "3", "title": "Processus metier actuels", "passes": false },
    { "id": "4", "title": "Besoins fonctionnels", "passes": false },
    { "id": "5", "title": "Besoins non-fonctionnels", "passes": false },
    { "id": "6", "title": "Contraintes techniques", "passes": false },
    { "id": "7", "title": "Integrations SmartStack", "passes": false },
    { "id": "8", "title": "Aspects legaux/conformite", "passes": false },
    { "id": "9", "title": "Criteres de succes", "passes": false }
  ]
}
```

### 6.2 progress.txt initial

```markdown
# Progress - {FEATURE_ID}

## Initialisation
- Feature: {description}
- Application: {APP_NAME}
- Module: {MODULE_NAME}
- Date: {timestamp}
- MCP SmartStack: {disponible/non disponible}

## Contexte SmartStack
- Granularite: {muscle/section/resource}
- Application existante: {oui/non}
- Module existant: {oui/non}

## Integrations requises
- Workflows: {oui/non} - Types: {liste}
- Notifications: {oui/non} - Events: {liste}
- IA: {oui/non} - Use cases: {liste}

## Legal/Conformite
- Contraintes: {liste}

---

## Iterations Discovery

### Iteration 1 - {timestamp}
[A remplir par Claude lors de la premiere iteration]
```

---

## STEP 7: DEFINIR LES CRITERES DE VALIDATION RALPH

### 7.1 Criteres pour COMPLETE

```markdown
## CRITERES DE VALIDATION RALPH LOOP

Pour signaler <promise>FEATURE_COMPLETE</promise>, TOUS ces criteres doivent etre vrais:

### Phase Discovery
□ Toutes les 9 sections de prd.json ont "passes": true
□ Aucune question en suspens
□ Contexte SmartStack clairement defini

### Phase Handoff
□ Toutes les 11 sections generees
□ Aucun placeholder {TBD} restant
□ Permissions completement definies
□ Integrations SmartStack specifiees

### Phase Implementation
□ 18 taches completees dans prd.json
□ Backend build OK
□ Frontend build OK
□ Tests passent
□ Migrations EF Core creees
□ Skills SmartStack executes (si requis)

### Phase Documentation
□ DocumentationPage.tsx genere
□ i18n 4 langues complete (FR, EN, IT, DE)
□ Routes ajoutees
```

---

## STEP 8: GENERER LE PROMPT RALPH LOOP

### 8.1 Prompt pour Discovery

```markdown
## PROMPT RALPH LOOP - DISCOVERY

/ralph-loop "
Tu es un Business Analyst senior expert SmartStack.

CONTEXTE:
- Feature: {FEATURE_ID}
- Application: {APP_NAME}
- Module: {MODULE_NAME}
- Description: {BESOIN_UTILISATEUR}

FICHIERS:
- prd.json: Liste des sections a completer
- progress.txt: Memoire des iterations

PROCESSUS PAR ITERATION:
1. Lire prd.json → Trouver section 'passes': false
2. Lire progress.txt → Comprendre le contexte
3. Completer UNE section avec questions ULTRATHINK
4. Mettre a jour 1-discovery.md
5. Marquer section 'passes': true dans prd.json
6. Ajouter resume a progress.txt

SIGNAL DE FIN:
Quand TOUTES les sections sont 'passes': true:
<promise>DISCOVERY_COMPLETE</promise>
" --completion-promise "DISCOVERY_COMPLETE" --max-iterations 15
```

### 8.2 Prompt pour Implementation complete

```markdown
## PROMPT RALPH LOOP - IMPLEMENTATION COMPLETE

/ralph-loop "
Tu es un Developpeur Senior expert SmartStack.

FEATURE: {FEATURE_ID}
HANDOFF: .business-analyse/.../4-development-handoff.md

PROCESSUS PAR ITERATION:
1. Lire prd.json → Prochaine tache 'passes': false
2. Lire progress.txt → Contexte et decisions
3. Implementer UNE tache (backend/frontend/test/integration)
4. git commit avec message conventionnel
5. Marquer 'passes': true dans prd.json
6. Documenter dans progress.txt

SKILLS SMARTSTACK A EXECUTER (si requis dans handoff section 9):
- /notification add {config} - Notifications temps reel
- /workflow create {config} - Workflows automatiques
- /ai-prompt create {config} - Prompts IA

SIGNAL DE FIN:
Quand TOUTES les 18+ taches sont 'passes': true:
<promise>FEATURE_COMPLETE</promise>
" --completion-promise "FEATURE_COMPLETE" --max-iterations 25
```

---

## STEP 9: LANCEMENT AUTOMATIQUE

### 9.1 Workflow complet

```bash
echo "╔══════════════════════════════════════════════════════════════════════════════╗"
echo "║              LANCEMENT WORKFLOW BA AUTOMATISE                                ║"
echo "╠══════════════════════════════════════════════════════════════════════════════╣"
echo "║                                                                              ║"
echo "║  Feature: ${FEATURE_ID}                                                      ║"
echo "║  Application: ${APP_NAME}                                                    ║"
echo "║  Module: ${MODULE_NAME}                                                      ║"
echo "║                                                                              ║"
echo "║  PHASES A EXECUTER:                                                          ║"
echo "║  1. Discovery (Ralph Loop: 15 iterations max)                                ║"
echo "║  2. Analysis (BRD generation)                                                ║"
echo "║  3. Specification (FRD generation)                                           ║"
echo "║  4. Validation (Gate utilisateur)                                            ║"
echo "║  5. Handoff (Ralph Loop: 10 iterations max)                                  ║"
echo "║  6. Implementation (Ralph Loop: 25 iterations max)                           ║"
echo "║  7. Documentation HTML                                                       ║"
echo "║                                                                              ║"
echo "╚══════════════════════════════════════════════════════════════════════════════╝"

# Lancer Phase 1: Init
/business-analyse:1-init ${APP_NAME} ${MODULE_NAME}

# Lancer Phase 2: Discovery avec Ralph Loop
/ralph-loop "/business-analyse:2-discover ${FEATURE_ID}" \
  --completion-promise "DISCOVERY_COMPLETE" \
  --max-iterations 15

# Phases 3-4: Analysis et Specification (sequentielles)
/business-analyse:3-analyse ${FEATURE_ID}
/business-analyse:4-specify ${FEATURE_ID}

# Phase 5: Validation (GATE OBLIGATOIRE - attend l'utilisateur)
/business-analyse:5-validate ${FEATURE_ID}

# SI APPROVED:
# Phase 6: Handoff avec Ralph Loop
/ralph-loop "/business-analyse:6-handoff ${FEATURE_ID}" \
  --completion-promise "HANDOFF_COMPLETE" \
  --max-iterations 10

# Phase 7: Implementation avec Ralph Loop
/ralph-loop "/implement ${FEATURE_ID}" \
  --completion-promise "FEATURE_COMPLETE" \
  --max-iterations 25

# Phase 8: Documentation HTML
/business-analyse:7-doc-html ${FEATURE_ID}

echo ""
echo "╔══════════════════════════════════════════════════════════════════════════════╗"
echo "║                    ✅ FEATURE COMPLETE                                        ║"
echo "╠══════════════════════════════════════════════════════════════════════════════╣"
echo "║                                                                              ║"
echo "║  Feature: ${FEATURE_ID}                                                      ║"
echo "║  Backend: Implemente                                                         ║"
echo "║  Frontend: Implemente                                                        ║"
echo "║  Tests: Passes                                                               ║"
echo "║  Documentation: Generee                                                      ║"
echo "║  Integrations SmartStack: Configurees                                        ║"
echo "║                                                                              ║"
echo "║  PROCHAINES ETAPES:                                                          ║"
echo "║  1. Revue de code                                                            ║"
echo "║  2. /gitflow:7-pull-request                                                  ║"
echo "║  3. Deploy staging                                                           ║"
echo "║                                                                              ║"
echo "╚══════════════════════════════════════════════════════════════════════════════╝"
```

---

## RESUME AUTOMATISATION

| Phase | Commande | Ralph Loop | Validation |
|-------|----------|------------|------------|
| 0 | `/business-analyse` | Non | MCP Check |
| 1 | Auto: 1-init | Non | Structure |
| 2 | Auto: 2-discover | Oui (15 iter) | prd.json 9/9 |
| 3 | Auto: 3-analyse | Non | BRD complet |
| 4 | Auto: 4-specify | Non | FRD complet |
| 5 | GATE: 5-validate | Non | UTILISATEUR |
| 6 | Auto: 6-handoff | Oui (10 iter) | prd.json 11/11 |
| 7 | Auto: /implement | Oui (25 iter) | prd.json 18/18 |
| 8 | Auto: 7-doc-html | Non | React + i18n |

---

## FICHIERS CREES PAR CETTE ORCHESTRATION

```
.business-analyse/
└── business/{app}/modules/{module}/features/{FEAT-XXX}/
    ├── context.json              ← Contexte SmartStack
    ├── .ralph/
    │   ├── discovery/
    │   │   ├── prd.json          ← Tracking Discovery
    │   │   └── progress.txt      ← Memoire Discovery
    │   ├── handoff/
    │   │   ├── prd.json          ← Tracking Handoff
    │   │   └── progress.txt      ← Memoire Handoff
    │   └── implement/
    │       ├── prd.json          ← Tracking Implementation
    │       └── progress.txt      ← Memoire Implementation
    ├── 1-discovery.md
    ├── 2-business-requirements.md
    ├── 3-functional-specification.md
    ├── 4-development-handoff.md
    ├── validation.json
    └── ralph-prompts/
        ├── discovery-prompt.md   ← Prompt Ralph Discovery
        ├── handoff-prompt.md     ← Prompt Ralph Handoff
        └── implement-prompt.md   ← Prompt Ralph Implementation
```
