## Introduction

Le skill Business Analyse v6.0 est un workflow en 7 etapes qui transforme un besoin utilisateur en specification fonctionnelle complete avec support iteratif multi-module. La v6.0 ajoute un document HTML interactif pour la revue client et un pipeline d'extraction (`-x`) pour re-importer les modifications.

The Business Analyse v6.0 skill is a 7-step workflow that transforms a user need into a complete functional specification with iterative multi-module support. v6.0 adds an interactive HTML document for client review and an extraction pipeline (`-x`) to re-import modifications.

✓

##### Ameliorations recentes (v3.30-31)

##### Recent Improvements (v3.30-31)

- v3.31.0 - Correction deadlock agent team : agents pouvaient entrer en attente infinie lors de l'adhesion a des teams obsoletes
- v3.31.0 - Team agent deadlock fix: agents could enter infinite wait when joining stale teams
- v3.30.0 - Mode detection guards : agents team evitent les AskUserQuestion qui causaient des crashes en mode auto
- v3.30.0 - Mode detection guards: team agents avoid AskUserQuestion which would crash in auto mode
- Gestion robuste du cycle de vie des agents team avec protocole d'arret gracieux
- Robust team agent lifecycle management with graceful shutdown protocol

#### 7 Etapes du workflow

#### 7 Workflow Steps

1. Init - Detecte le mode (application vs module), cree feature.json initial
2. Cadrage - Analyse applicative : probleme, stakeholders, scope, roles (applicationRoles)
3. Decomposition - Decompose l'application en modules, dependances, graphe topologique
4. Specify (Per-Module) - Specification iterative de chaque module en ordre de dependance
5. Consolidation - Validation cross-module, coherence des permissions et entites partagees
6. Handoff - Mapping des fichiers par module, extraction programmatique prd.json via `ss derive-prd`, deploiement HTML interactif
7. Extract - Import depuis l'export JSON du HTML interactif (`-x`), mapping vers feature.json

#### Navigation hierarchique (4 niveaux)

#### Hierarchical Navigation (4 Levels)

    Application → Module → Section → Resource

    Exemple:
    - Application: "OrderManagement"
    - Module: "Checkout"
    - Section: "ShoppingCart" (page React)
    - Resource: "CartItem" (composant React)

⚠

##### Architecture multi-niveaux

##### Multi-level Architecture

Deux fichiers de schema : application-schema.json (master, cadrage et modules) et feature-schema.json (par module, specification).

Two schema files: application-schema.json (master, framing and modules) and feature-schema.json (per-module, specification).

📊

##### 2 Agents specialises

##### 2 Specialized Agents

ba-reader : lecture, recherche de features, validation des references croisees. ba-writer : creation, enrichissement, validation du schema, verification post-ecriture.

ba-reader: read, search features, validate cross-references. ba-writer: create, enrich, schema validation, post-write verification.

📊

##### prd.json programmatique

##### Programmatic prd.json

Le fichier `prd.json` n'est JAMAIS genere par l'LLM. Il est extrait programmatiquement par `ss derive-prd` a partir du feature.json final, garantissant coherence et tracabilite.

The `prd.json` file is NEVER generated by the LLM. It is extracted programmatically by `ss derive-prd` from the final feature.json, ensuring consistency and traceability.

## Architecture (Hierarchie 4-Niveaux) Architecture (4-Level Hierarchy)

La v6.0 utilise une hierarchie 4 niveaux (Application → Module → Section → Resource) pour naviguer les applications multi-modules. Deux fichiers JSON (master application + per-module) garantissent la tracabilite et la coherence cross-module.

v6.0 uses a 4-level hierarchy (Application → Module → Section → Resource) to navigate multi-module applications. Two JSON files (master application + per-module) ensure traceability and cross-module coherence.

#### Structure de repertoires

#### Directory Structure

    docs/business/{app}/business-analyse/
    ├── v1.0/
    │   ├── feature.json              ← MASTER (application-level)
    │   │                               includes: cadrage, moduleRegistry, dependencyGraph
    │   └── README.md                 ← Overview
    │
    ├── {module-name}/
    │   └── v1.0/
    │       ├── feature.json          ← PER-MODULE (feature-schema.json)
    │       │                           includes: specification, validation, handoff
    │       └── README.md

    └── .ralph/
        ├── prd.json                  ← Extracted programmatically
        ├── progress.txt              ← Tracker
        └── per-module/
            ├── checkout-handoff.json
            ├── payment-handoff.json
            └── ...

#### Deux schemas JSON

#### Two JSON Schemas

Fichier | Niveau Level | Contenu principal Main Content | Ecriture par Written by
--- | --- | --- | ---
`application-schema.json` | Master | cadrage, applicationRoles, moduleRegistry[], dependencyGraph framing, applicationRoles, moduleRegistry[], dependencyGraph | Step 01-02
`feature-schema.json` | Per-Module | specification, validation, handoff (entites, UC, BR, FR, wireframes) specification, validation, handoff (entities, UC, BR, FR, wireframes) | Step 03-05

#### Coverage Matrix (tracabilite)

#### Coverage Matrix (Traceability)

Chaque requirement original du cadrage doit etre trace a au moins 1 use case (UC), business rule (BR), ou functional requirement (FR).

Each original requirement from framing must be traced to at least 1 use case (UC), business rule (BR), or functional requirement (FR).

    "coverageMatrix": {
      "mustHave": [
        {
          "id": "REQ-001",
          "description": "Users can view their order history",
          "category": "core_feature",
          "tracedTo": ["UC-HIST-001", "FR-HIST-001"],
          "covered": true
        }
      ],
      "shouldHave": [...],
      "couldHave": [...]
    }

## Quick Start

`/business-analyse` SKILL

Lancez l'analyse metier complete avec le nouveau workflow 6 etapes.

Launch the complete business analysis with the new 6-step workflow.

    /business-analyse [description] [flags]

#### Exemples rapides

#### Quick Examples

    # Nouvelle application (workflow complet 6 etapes)
    /business-analyse Order management system

    # Question sur une application ou module
    /business-analyse -q FEAT-001 "What are the permission hierarchy?"

    # Refactoring (delta sur application existante)
    /business-analyse -r FEAT-001 "Add return management module"

    # Micro-feature (analyse minimale)
    /business-analyse -m Add a status field to orders

    # Extract depuis HTML interactif
    /business-analyse -x ./docs/business/MyApp/ba-export.json

## 5 Cas d'usage 5 Use Cases

Cas d'usage Use Case | Flag | Mode Mode | Parcours Flow
--- | --- | --- | ---
Nouvelle application New application | (aucun)(none) | application application | 00 → 01 → 02 → 03[*N modules] → 04 → 05
Question | `-q` | lecture seule read-only | ba-reader.findFeature() → ba-reader.readSection() → EXIT
Refactoring | `-r` | delta application delta application | 00 (delta) → 01 → 02 → 03[*N modules] → 04 → 05
Micro-feature | `-m` | module simple simple module | 00 (micro) → 01 (lite) → 02 (skip) → 03 (minimal) → 04 (auto) → 05
Extract | `-x` | import HTML interactif interactive HTML import | 00 → 06 (extract) → choix choice (01 | 05 | EXIT)

## Flags & Modes

Flag | Effet Effect | Par defaut Default
--- | --- | ---
`-q, --question` | Mode lecture seule (ba-reader) Read-only mode (ba-reader) | false
`-r, --refactor` | Creer version delta (v1.1) Create delta version (v1.1) | false
`-m, --micro` | Analyse minimale pour micro-feature Minimal analysis for micro-feature | false
`-x, --extract` | Importer depuis l'export JSON du HTML interactif Import from interactive HTML JSON export | false
`--economy-mode` | Haiku partout, moins de context Haiku everywhere, less context | false
`--mcp-available` | Valider avec SmartStack.mcp Validate with SmartStack.mcp | false

## Workflow (7 Etapes)

Le workflow v6.0 combine decouverte, decomposition, specification iterative et consolidation cross-module. Chaque etape enrichit progressivement le feature.json.

The v6.0 workflow combines discovery, decomposition, iterative specification and cross-module consolidation. Each step progressively enriches the feature.json.

### 00. Init

Detecte le mode d'execution (application vs module), cree le fichier feature.json initial avec metadata et configuration.

Detects execution mode (application vs module), creates initial feature.json with metadata and configuration.

#### Actions

- Lire config de projet + detecter contexte
- Read project config + detect context
- Mode application : creer master feature.json avec schema application-schema.json
- Application mode: create master feature.json with application-schema.json
- Mode module : creer feature.json single avec schema feature-schema.json
- Module mode: create single feature.json with feature-schema.json
- Initialiser metadata et premiere section
- Initialize metadata and first section

### 01. Cadrage

Analyse applicative au niveau master : probleme, stakeholders, scope, roles, risques. Definit les `applicationRoles` (admin, manager, contributor, viewer).

Application-level framing: problem, stakeholders, scope, roles, risks. Defines `applicationRoles` (admin, manager, contributor, viewer).

#### Actions

- AskUserQuestion (max 4 par batch) pour decouvrir besoin metier
- AskUserQuestion (max 4 per batch) to discover business need
- Definir 4-tier applicationRoles : admin, manager, contributor, viewer
- Define 4-tier applicationRoles: admin, manager, contributor, viewer
- Suggestions proactives depuis catalog
- Proactive suggestions from catalog
- Analyse des risques (securite, performance, complexite)
- Risk analysis (security, performance, complexity)
- Creer COVERAGE MATRIX (obligatoire) : trace chaque requirement a une UC/BR/FR
- Create COVERAGE MATRIX (mandatory): trace each requirement to a UC/BR/FR

⚠

##### Coverage Matrix obligatoire

##### Coverage Matrix Mandatory

Chaque requirement doit avoir at least une trace cross-reference. La matrice est validee a l'etape 04 (Consolidation).

Each requirement must have at least one trace cross-reference. Matrix is validated in step 04 (Consolidation).

### 02. Decomposition

Decompose l'application en modules interdependants. Construit le graphe de dependances avec tri topologique. Assigne priorite et complexite.

Decomposes application into interdependent modules. Builds dependency graph with topological sort. Assigns priority and complexity.

#### Actions

- Splitter l'application en modules logiques
- Split application into logical modules
- Determiner dependances inter-modules
- Determine inter-module dependencies
- Construire dependencyGraph (tri topologique obligatoire)
- Build dependencyGraph (topological sort mandatory)
- Assigner priorite (must/should/could) et complexite estimee
- Assign priority (must/should/could) and estimated complexity
- Ecrire moduleRegistry dans master feature.json
- Write moduleRegistry in master feature.json

    "dependencyGraph": {
      "modules": ["Checkout", "Payment", "Inventory", "Shipping"],
      "edges": [
        { "from": "Checkout", "to": "Payment", "type": "requires" },
        { "from": "Checkout", "to": "Inventory", "type": "requires" }
      ],
      "topologicalOrder": ["Inventory", "Checkout", "Payment", "Shipping"],
      "priorities": {
        "Inventory": "must",
        "Checkout": "must",
        "Payment": "must",
        "Shipping": "should"
      }
    }

### 03. Specify (Per-Module Loop)

Specification iterative de chaque module dans l'ordre topologique. Pour chaque module : sections, entites, regles metier, UC, FR, permissions, wireframes.

Iterative specification of each module in topological order. For each module: sections, entities, business rules, UC, FR, permissions, wireframes.

#### Actions par module

#### Actions per module

- Sections & Resources (Niveaux 4-5) : Section = page React, Resource = composant
- Sections & Resources (Levels 4-5): Section = React page, Resource = component
- Entites : tables metier, FK, indexes
- Entities: business tables, FK, indexes
- Regles metier (BR) : format id BR-{CATEGORY}-{PREFIX}-{NNN}
- Business Rules (BR): format id BR-{CATEGORY}-{PREFIX}-{NNN}
- Cas d'usage (UC) : format id UC-{PREFIX}-{NNN}
- Use Cases (UC): format id UC-{PREFIX}-{NNN}
- Exigences fonctionnelles (FR) : format id FR-{PREFIX}-{NNN}
- Functional Requirements (FR): format id FR-{PREFIX}-{NNN}
- Wireframes structurels : ASCII mockup + JSON layout
- Structural Wireframes: ASCII mockup + JSON layout

#### Verification de couverture

#### Coverage Verification

Chaque requirement "mustHave" de la coverageMatrix doit avoir at least 1 UC qui la reference.

Each "mustHave" requirement in coverageMatrix must have at least 1 UC that references it.

### 04. Consolidation

Validation cross-module (10 verifications semantiques). Coherence des permissions, entites partagees, mappage UC-FR.

Cross-module validation (10 semantic checks). Permission coherence, shared entities, UC-FR mapping.

#### 10 Verifications semantiques

#### 10 Semantic Checks

1. Permission orphans : roles utilises mais non definis dans applicationRoles
2. Permission orphans: roles used but not defined in applicationRoles
3. UC-FR links : chaque UC doit avoir at least 1 FR
4. UC-FR links: each UC must have at least 1 FR
5. Entity-endpoint mapping : chaque entite doit avoir CRUD endpoints
6. Entity-endpoint mapping: each entity must have CRUD endpoints
7. BR consistency : chaque BR doit etre test dans un UC
8. BR consistency: each BR must be tested in a UC
9. Cross-module entity refs : shared entities coherentes
10. Cross-module entity refs: shared entities coherent
11. Permission hierarchy : no conflicts ou contraintes
12. Permission hierarchy: no conflicts or constraints
13. E2E flows : workflows complets tracables
14. E2E flows: complete workflows traceable
15. Coverage matrix completion : toutes requirements couverts
16. Coverage matrix completion: all requirements covered
17. ID uniqueness : pas de collisions dans modules
18. ID uniqueness: no collisions across modules
19. Schema validation : JSON Schema 2020-12 compliance
20. Schema validation: JSON Schema 2020-12 compliance

### 05. Handoff

Handoff final par module avec mapping de fichiers (7 categories). Extraction programmatique du prd.json via `ss derive-prd`.

Final per-module handoff with file mapping (7 categories). Programmatic extraction of prd.json via `ss derive-prd`.

#### Actions

Categorie Category | Fichiers Files
--- | ---
Domain | entities/, aggregates/, valueObjects/
Application | services/, handlers/, DTOs/
Infrastructure | repositories/, context/, migrations/
API | controllers/, endpoints/, auth/
Frontend | pages/, components/, hooks/
SeedData | Seeding/Data/{module}/
Tests | Tests/{module}/, Unit/, Integration/

#### prd.json (extraction programmatique)

#### prd.json (Programmatic Extraction)

Le fichier `.ralph/prd.json` est genere par `ss derive-prd feature.json` (NOT par l'LLM). Il contient le resume technique pour implementation.

The `.ralph/prd.json` file is generated by `ss derive-prd feature.json` (NOT by LLM). It contains technical summary for implementation.

    {
      "application": "OrderManagement",
      "version": "1.0",
      "modules": [
        {
          "name": "Checkout",
          "priority": "must",
          "entities": ["Order", "OrderLine", "Customer"],
          "useCases": ["UC-CHK-001", "UC-CHK-002"],
          "apiEndpoints": [
            "POST /api/orders",
            "GET /api/orders/{id}",
            "PUT /api/orders/{id}/confirm"
          ],
          "permissions": ["viewer", "contributor"]
        }
      ]
    }

#### Document HTML interactif

#### Interactive HTML Document

A l'etape de handoff, un document HTML interactif (`ba-interactive.html`) est deploye dans le repertoire du projet. Ce document permet au client de consulter, modifier et enrichir l'analyse metier directement dans son navigateur, sans serveur. Les modifications peuvent etre re-importees via `/business-analyse -x <json-path>`.

At the handoff step, an interactive HTML document (`ba-interactive.html`) is deployed to the project directory. This document allows the client to review, edit and enrich the business analysis directly in their browser, without a server. Modifications can be re-imported via `/business-analyse -x <json-path>`.

⚠ Important : Source de verite Important: Source of Truth

Le HTML interactif est un livrable genere, pas une source de donnees. La source de verite est constituee par les fichiers JSON (`index.json`, `cadrage.json`, `entities.json`, etc.). Toute modification faite directement dans le HTML sera ecrasee a la prochaine regeneration via `/business-analyse-html`.

The interactive HTML is a generated deliverable, not a data source. The source of truth is the JSON files (`index.json`, `cadrage.json`, `entities.json`, etc.). Any modification made directly in the HTML will be overwritten on the next regeneration via `/business-analyse-html`.

Pour conserver vos modifications :
1. Exporter le JSON depuis le HTML (bouton d'export)
2. Re-importer avec `/business-analyse -x <json-path>` (met a jour les fichiers JSON sources)
3. Regenerer le HTML avec `/business-analyse-html`

To preserve your modifications:
1. Export JSON from the HTML (export button)
2. Re-import with `/business-analyse -x <json-path>` (updates source JSON files)
3. Regenerate the HTML with `/business-analyse-html`

#### Verification post-handoff

#### Post-Handoff Verification

- Valider ba-reader.readApplicationContext() = tous modules presents
- Validate ba-reader.readApplicationContext() = all modules present
- Verifier ba-writer.enrichModuleHandoff() completude
- Verify ba-writer.enrichModuleHandoff() completeness
- Extraction prd.json via `ss derive-prd`
- Extract prd.json via `ss derive-prd`
- Generer progress.txt tracker
- Generate progress.txt tracker
- Deployer ba-interactive.html avec placeholders remplaces
- Deploy ba-interactive.html with placeholders replaced

### 06. Extract

Importe les donnees depuis l'export JSON du document HTML interactif (`ba-interactive.html`) et les transforme en feature.json. Cette etape est declenchee par le flag `-x`.

Imports data from the interactive HTML document's JSON export (`ba-interactive.html`) and transforms it into feature.json. This step is triggered by the `-x` flag.

#### Principe

#### Principle

- Zero perte d'information : chaque champ du JSON exporte est mappe vers feature.json
- Zero information loss: every field from the exported JSON is mapped to feature.json
- Mapping deterministe : cadrage, modules, specifications, consolidation
- Deterministic mapping: cadrage, modules, specifications, consolidation
- Post-extraction : choix entre enrichir (step-01), handoff (step-05), ou terminer
- Post-extraction: choice between enrichment (step-01), handoff (step-05), or terminate

    /business-analyse -x ./docs/business/MyApp/ba-export.json

## Skills complementaires Companion Skills

Deux skills independants completent le workflow de business analyse pour la gestion du document HTML interactif.

Two independent skills complement the business analysis workflow for managing the interactive HTML document.

### `/business-analyse-html`

Genere (ou regenere) le document HTML interactif a partir des fichiers JSON d'analyse. Ce skill lit les sources JSON (`index.json`, `cadrage.json`, fichiers modules) et produit un fichier `ba-interactive.html` autonome.

Generates (or regenerates) the interactive HTML document from the analysis JSON files. This skill reads the JSON sources (`index.json`, `cadrage.json`, module files) and produces a standalone `ba-interactive.html` file.

    /business-analyse-html FEAT-001
    /business-analyse-html FEAT-001 --force

Flag | Effet Effect
--- | ---
`--force` | Regenerer meme si le HTML existe deja Regenerate even if HTML already exists

#### Etapes internes Internal Steps

Step | Role Role
--- | ---
01 | Lire les sources JSON (index, cadrage, modules, consolidation)Read JSON sources (index, cadrage, modules, consolidation)
02 | Construire FEATURE_DATA + EMBEDDED_ARTIFACTS Build FEATURE_DATA + EMBEDDED_ARTIFACTS
03 | Injecter dans le template ba-interactive.html Inject into ba-interactive.html template
04 | Verification (taille > 100KB, sections, coherence)Verification (size > 100KB, sections, coherence)

⚠ Regeneration = ecrasement Regeneration = overwrite

`/business-analyse-html` ecrase le HTML existant. Si vous avez fait des modifications dans le HTML interactif, exportez d'abord le JSON puis re-importez avec `/business-analyse -x` avant de regenerer.

`/business-analyse-html` overwrites the existing HTML. If you made modifications in the interactive HTML, first export the JSON then re-import with `/business-analyse -x` before regenerating.

### `/ba-review`

Applique les corrections client exportees depuis le HTML interactif et regenere le document. Ce skill attend un fichier `ba-review.json` contenant les modifications structurees.

Applies client corrections exported from the interactive HTML and regenerates the document. This skill expects a `ba-review.json` file containing structured modifications.

    /ba-review

#### Workflow Workflow

1. Lire `ba-review.json` (exporte depuis le HTML interactif)
2. Read `ba-review.json` (exported from interactive HTML)
3. Lire le master `index.json` existant
4. Read the existing master `index.json`
5. Creer une nouvelle version
6. Create a new version
7. Appliquer les corrections (cadrage, modules, consolidation)
8. Apply corrections (cadrage, modules, consolidation)
9. Regenerer le HTML via `/business-analyse-html`
10. Regenerate HTML via `/business-analyse-html`

#### Routage des corrections Correction Routing

Type de modification Modification Type | Action declenchee Triggered Action
--- | ---
Entites / regles / UC / permissions Entities / rules / UC / permissions | Re-execution `/business-analyse` step-03 Re-run `/business-analyse` step-03
Ecrans / wireframes / navigation Screens / wireframes / navigation | Re-execution `/ba-design-ui` Re-run `/ba-design-ui`
Les deux Both | Re-specification complete Full re-specification
Cadrage uniquement Cadrage only | Regeneration HTML uniquement HTML regeneration only
Client approuve Client approves | `/derive-prd`

### Cycle de vie complet Complete Lifecycle

    # 1. Analyse initiale (genere les JSON + HTML)
    /business-analyse My Application Description

    # 2. Client consulte le HTML, fait des modifications, exporte le JSON

    # 3a. Re-import des modifications client dans les JSON sources
    /business-analyse -x ./docs/business/MyApp/ba-export.json

    # 3b. OU appliquer des corrections structurees
    /ba-review

    # 4. Regenerer le HTML apres modifications des JSON
    /business-analyse-html FEAT-001# 1. Initial analysis (generates JSON + HTML)
    /business-analyse My Application Description

    # 2. Client reviews the HTML, makes modifications, exports JSON

    # 3a. Re-import client modifications into source JSONs
    /business-analyse -x ./docs/business/MyApp/ba-export.json

    # 3b. OR apply structured corrections
    /ba-review

    # 4. Regenerate HTML after JSON modifications
    /business-analyse-html FEAT-001

## Schemas

Deux schemas JSON Schema 2020-12 : application-schema.json (master) et feature-schema.json (per-module).

Two JSON Schema 2020-12 files: application-schema.json (master) and feature-schema.json (per-module).

#### `application-schema.json` (Master Level)

- Metadata : titre, contexte, version
- Metadata: title, context, version
- Cadrage : problem, stakeholders, scope, applicationRoles, risks
- Framing: problem, stakeholders, scope, applicationRoles, risks
- moduleRegistry[] : list des modules avec dependencies
- moduleRegistry[]: list of modules with dependencies
- dependencyGraph : edges, topologicalOrder, priorities
- dependencyGraph: edges, topologicalOrder, priorities
- coverageMatrix : mustHave/shouldHave/couldHave requirements
- coverageMatrix: mustHave/shouldHave/couldHave requirements

#### `feature-schema.json` (Per-Module Level)

- Metadata : module, version, featureType
- Metadata: module, version, featureType
- Sections & Resources : 4-level navigation
- Sections & Resources: 4-level navigation
- Entities : domaine, attributs, constraints
- Entities: domain, attributes, constraints
- Business Rules (BR-{CAT}-{PREFIX}-{NNN}) : validations metier
- Business Rules (BR-{CAT}-{PREFIX}-{NNN}): business validations
- Use Cases (UC-{PREFIX}-{NNN}) : workflows, actors, flows
- Use Cases (UC-{PREFIX}-{NNN}): workflows, actors, flows
- Functional Requirements (FR-{PREFIX}-{NNN}) : exigences techniques
- Functional Requirements (FR-{PREFIX}-{NNN}): technical requirements
- Wireframes : ASCII + JSON layout
- Wireframes: ASCII + JSON layout
- Permissions : roles et access control
- Permissions: roles and access control
- Handoff : mapping de fichiers, API endpoints, tests
- Handoff: file mapping, API endpoints, tests

#### Module-Prefixed IDs

Chaque ID inclut le prefixe du module pour eviter les collisions cross-module.

Each ID includes module prefix to avoid cross-module collisions.

    UC-{PREFIX}-{NNN}     # UseCase
    BR-{CAT}-{PREFIX}-{NNN}  # BusinessRule
    FR-{PREFIX}-{NNN}     # FunctionalRequirement

    Exemple (module "checkout"):
    UC-CHK-001     # Add item to cart
    BR-VAL-CHK-001  # Order total must be positive
    FR-CHK-001     # Shopping cart API

## Agents (ba-reader / ba-writer)

#### `ba-reader`

Agent de lecture specialise dans la decouverte et validation. Toutes operations sont read-only et deterministes.

Read-only agent specialized in discovery and validation. All operations are read-only and deterministic.

- `findFeature(featureId)` - Localiser feature par ID
- `readSection(moduleId, sectionPath)` - Lire section specifique
- `readApplicationContext()` - Charger contexte complet application
- `listAllModuleIds()` - Lister tous modules (ID collision detection)
- `answerQuestion(question)` - Repondre a question sur feature

#### `ba-writer`

Agent d'ecriture avec validation schema obligatoire et verification post-ecriture.

Write agent with mandatory schema validation and post-write verification.

- `create(spec)` - Creer nouveau feature.json (validate schema)
- `createApplicationFeature(appSpec)` - Creer master application feature
- `enrichSection(moduleId, sectionPath, content)` - Enrichir section existante
- `enrichModuleHandoff(moduleId, handoffData)` - Enrichir handoff (verify completeness)
- `updateStatus(featureId, newStatus)` - Mettre a jour statut step
- `enrichModuleRegistry(moduleRegistry)` - Enrichir registry modules
- `advanceModuleLoop(nextModuleId)` - Avancer au prochain module

#### Resilience des agents team

#### Team Agent Resilience

Les agents team de Business Analyse (cadrage, decomposition, specify, consolidation) beneficient d'une gestion robuste du cycle de vie avec trois mecanismes de resilience clefs :

Business Analyse team agents (framing, decomposition, specify, consolidation) benefit from robust lifecycle management with three key resilience mechanisms:

Mecanisme | Mechanism | Comportement | Behavior
--- | --- | --- | ---
Detection de mode Mode Detection | Agents team detectent automatiquement si execution en auto-mode (flags `-a`, `-m`, etc.) | Team agents automatically detect if running in auto-mode (flags `-a`, `-m`, etc.) | Evite les appels a AskUserQuestion qui causeraient crash ou deadlock | Avoids AskUserQuestion calls which would cause crash or deadlock
Prevention des team obsoletes Stale Team Prevention | Agents verifient la "freshness" de la team avant adhesion pour eviter deadlock | Agents verify team freshness before joining to avoid deadlock | Detecte teams devenues obsoletes (timeouts) et refuse l'adhesion | Detects stale teams (timeouts) and refuses to join
Protocole d'arret gracieux Graceful Shutdown Protocol | 3 tentatives avant force-termination des agents dans la team | 3 attempts before force-termination of agents in team | Timeout configurable (default 30s), logs detailles des tentatives | Configurable timeout (default 30s), detailed logs of attempts

ℹ

##### Logs et diagnostics

##### Logs and Diagnostics

Tous les evenements de lifecycle (join, leave, timeout, mode detection) sont loges avec timestamps pour faciliter le diagnostique en cas d'issue. Les mode detection guards emettent des warning clairs au demarrage.

All lifecycle events (join, leave, timeout, mode detection) are logged with timestamps for easy diagnosis in case of issues. Mode detection guards emit clear warnings at startup.

⚠

##### Validation schema OBLIGATOIRE

##### Schema Validation MANDATORY

Chaque write doit passer par JSON Schema 2020-12 validation AVANT persistance. Les erreurs sont rejetes avec messages clairs.

Each write must pass JSON Schema 2020-12 validation BEFORE persistence. Errors are rejected with clear messages.

## IDs & References croisees IDs & Cross-References

#### Patterns de nommage

#### Naming Patterns

    Module Prefix Format:
    - 3-4 characters (e.g., CHK, PAY, INV)
    - Derived from module name
    - Stored in moduleRegistry

    ID Formats:
    UC-{PREFIX}-{NNN}      # Use Case (sequential)
    BR-{CAT}-{PREFIX}-{NNN}  # Business Rule with category
    FR-{PREFIX}-{NNN}      # Functional Requirement

    Example:
    Module: "Checkout"
      Prefix: "CHK"
      UC-CHK-001: Add item to cart
      BR-VAL-CHK-001: Order total validation
      FR-CHK-001: Cart API endpoint

#### Detection des collisions

#### Collision Detection

L'agent `ba-reader.listAllModuleIds()` detecte les collisions cross-module et rapporte les IDs dupliques.

The `ba-reader.listAllModuleIds()` agent detects cross-module collisions and reports duplicate IDs.

#### Regles de validation des references croisees

#### Cross-Reference Validation Rules

- Chaque UC doit referencer at least 1 FR
- Each UC must reference at least 1 FR
- Chaque BR doit etre teste dans at least 1 UC
- Each BR must be tested in at least 1 UC
- Chaque requirement (mustHave) doit etre couverte par coverage matrix
- Each requirement (mustHave) must be covered by coverage matrix
- Les references croisees (xref) doivent utiliser module prefix correct
- Cross-references (xref) must use correct module prefix

## Sorties Output

#### Structure des fichiers generes

#### Generated Files Structure

    docs/business/{app}/business-analyse/
    ├── v1.0/
    │   ├── feature.json              ← Master application spec
    │   ├── ba-interactive.html       ← Interactive client review document
    │   └── README.md                 ← Overview
    ├── checkout/v1.0/
    │   ├── feature.json              ← Module spec
    │   └── README.md
    ├── payment/v1.0/
    │   ├── feature.json
    │   └── README.md
    └── shipping/v1.0/
        ├── feature.json
        └── README.md

    .ralph/
    ├── prd.json                      ← Extracted (programmatic)
    ├── progress.txt                  ← Tracking
    └── per-module/
        ├── checkout-handoff.json
        ├── payment-handoff.json
        └── shipping-handoff.json

#### Master `feature.json`

    {
      "id": "APP-ORDERS-001",
      "version": "1.0.0",
      "application": "OrderManagement",
      "status": "handed-off",
      "metadata": {
        "context": "ecommerce",
        "title": "Order Management System",
        "createdAt": "2026-02-04",
        "language": "fr"
      },
      "cadrage": {
        "problem": "...",
        "stakeholders": [...],
        "scope": {...},
        "applicationRoles": ["admin", "manager", "contributor", "viewer"]
      },
      "coverageMatrix": {...},
      "moduleRegistry": [...],
      "dependencyGraph": {...},
      "changelog": [...]
    }

#### Per-Module `feature.json`

    {
      "id": "FEAT-CHK-001",
      "module": "Checkout",
      "version": "1.0.0",
      "status": "handed-off",
      "metadata": {...},
      "specification": {
        "sections": [...],
        "entities": [...],
        "businessRules": [...],
        "useCases": [...],
        "requirements": [...]
      },
      "validation": {...},
      "handoff": {
        "fileMapping": {...},
        "apiEndpoints": [...],
        "wireframes": [...],
        "testPlan": {...}
      }
    }

#### `prd.json` (Programmatic)

Genere par `ss derive-prd feature.json`, contient resume technique pour implementation.

Generated by `ss derive-prd feature.json`, contains technical summary for implementation.

    {
      "application": "OrderManagement",
      "version": "1.0.0",
      "generatedAt": "2026-02-04",
      "modules": [
        {
          "name": "Checkout",
          "priority": "must",
          "complexity": "high",
          "entities": ["Order", "OrderLine", "Customer"],
          "apiEndpoints": [
            { "method": "POST", "path": "/api/orders", "auth": "contributor" }
          ],
          "permissions": ["viewer", "contributor"],
          "dependencies": ["Inventory"]
        }
      ]
    }

#### `progress.txt`

Tracker textuel de progression, genere a chaque etape.

Text progress tracker, generated at each step.

    # Business Analyse Progress - OrderManagement v1.0

    [✓] Step 00 - Init (completed 2026-02-04 10:00)
    [✓] Step 01 - Cadrage (completed 2026-02-04 10:15)
        - 4 applicationRoles defined
        - 5 mustHave requirements in coverage matrix

    [✓] Step 02 - Decomposition (completed 2026-02-04 10:30)
        - 3 modules identified: Checkout, Payment, Shipping
        - Topological order: [Inventory, Checkout, Payment, Shipping]

    [→] Step 03 - Specify (in progress)
        - Current module: Checkout (1/4)
        - Entities: 3/5 done
        - Use Cases: 2/8 done

    [ ] Step 04 - Consolidation (pending)
    [ ] Step 05 - Handoff (pending)

## Versioning

Les versions suivent SemVer. Les workflows complets incrementent MAJOR ou MINOR. Les deltas (refactoring) incrementent PATCH.

Versions follow SemVer. Complete workflows increment MAJOR or MINOR. Deltas (refactoring) increment PATCH.

Scenario Scenario | Version Version | Flag
--- | --- | ---
Nouvelle application | New application | 1.0.0 | -
Ajout module majeur | Add major module | 2.0.0 | -
Refactoring delta | Refactoring delta | 1.1.0 | -r
Micro-feature | Micro-feature | 1.0.1 | -m

Developpe par Developed by AtlasHub • support@atlashub.ch • MIT License