---
name: business-analyse
description: Iterative multi-module business analysis with progressive context loading, JSON-first architecture, and interactive HTML deliverables.
argument-hint: "<feature description>"
---

<objective>
Execute business analysis workflows. This skill produces feature.json files progressively enriched at each step, published to docs/ for web app rendering.

**Three use cases:**
1. **New application** — full analysis workflow for a new business need (single or multi-application)
2. **Update** — delta changes on an existing application or module
3. **Multi-application project** — when a project spans multiple independent applications (e.g., HR Management + Employee Self-Service)

The skill auto-detects which use case applies by scanning existing features in `docs/{app}/` and `docs/business-analyse/`.

**Architecture highlights:**
- Conditional context loading: each step loads only the shared files it needs (~54% context reduction)
- 12 granular steps (1-2 responsibilities each, 200-500 lines) for maximum LLM attention quality
- Self-verification at every step transition, POST-CHECKs on critical outputs
- Templates and references extracted to separate files, loaded on demand
</objective>

<quick_start>

```bash
# New application analysis
/business-analyse Complete sales management system

# The skill auto-detects if an existing application matches
# and proposes "new" or "update" accordingly
/business-analyse Add export PDF to orders module
```

</quick_start>

<parameters>

| Flag | Description |
|------|-------------|
| (aucun) | Mode standard — analyse complete ou mise a jour |
| `-review` | Mode review — lit `ba-review.json`, cree une nouvelle version avec les corrections appliquees |

Step-00 handles detection automatically:
- **New vs Update**: scans `docs/` for existing applications
- **Single vs Multi-app**: multi-app detection in step-01, application identity confirmed in step-01b (always)
- **Single vs Multi-module**: determined during step-02 decomposition
- **Language**: detected from config or asked once
- **Review mode**: if `-review` flag, routes directly to step-06

</parameters>

<output_structure>
**All outputs saved to PROJECT directory:**

```
docs/
    business-analyse/v{X.Y}/
        feature.json              # PROJECT-level master (only if multi-app: applications, dependencies)
    {app}/
        index.json                # BA manifest (auto-updated at handoff, consumed by web app viewer)
        business-analyse/v{X.Y}/
            feature.json          # APPLICATION-level master (modules, dependencies, roles)
            ba-interactive.html   # Client-facing interactive review document (deployed at handoff)
        {app}/{module}/business-analyse/v{X.Y}/
            feature.json          # MODULE-level detail (entities, UC, FR, permissions, mockups)
```
> In standalone mode (single app), the project-level file is NOT created.

**Ralph Loop files (generated by step-05):**
```
.ralph/
├── prd-{moduleCode}.json  # Per-module task breakdown for /ralph-loop
└── progress.txt           # Links to BA documents
```

**Documentation integrated in SmartStack app:**
- Application view: `/docs/{app}` (module overview, dependency graph, roles)
- Module view: `/docs/{app}/{module}` (full specification, mockups)

**No intermediate markdown files - all state in feature.json**
</output_structure>

<navigation_hierarchy>
**SmartStack uses a 4-level navigation structure mapped to database tables:**

| Level | Entity | Table DB | Created in Step | Description |
|-------|--------|----------|-----------------|-------------|
| 1 | Application | `core.nav_Applications` | 00-01 | Top-level application (e.g., "HumanResources") |
| 2 | Module | `core.nav_Modules` | 02 | Functional module (e.g., "Employees", "TimeManagement") |
| 3 | **Section** | **`core.nav_Sections`** | **03a-03c** | **Page within module (e.g., "list", "detail", "dashboard")** |
| 4 | **Resource** | **`core.nav_Resources`** | **03b-03c** | **React component (SmartTable, SmartForm, Chart, KpiCard, etc.)** |

**Hierarchical relationship:**
- Application → Module → **Section** → **Resource**
- Each Section MUST have ≥1 Resource
- Each Section corresponds to 1 React page route
- Each Resource corresponds to 1 SmartStack UI component

**SeedData generation (step-03c):**

The `specification.seedDataCore` contains **9 mandatory arrays** for database seeding:

| Array | Table | Source | Description |
|-------|-------|--------|-------------|
| `navigationApplications` | `core.nav_Applications` | Manual (step-03c) | Application entry (Level 1) — created ONCE per application |
| `applicationRoles` | `core.auth_Roles` | Manual (step-03c) | Application-scoped roles (admin, manager, contributor, viewer) |
| `navigationModules` | `core.nav_Modules` | Manual (step-03c) | Module entry (Level 2) |
| **`navigationSections`** | **`core.nav_Sections`** | **Derived from `specification.sections[]`** | **Section entries (Level 3)** |
| **`navigationResources`** | **`core.nav_Resources`** | **Derived from `specification.sections[].resources[]`** | **Resource entries (Level 4)** |
| `navigationTranslations` | `core.nav_Translations` | Manual (i18n) | Multi-language labels |
| `permissions` | `core.Permissions` | Manual (step-03c) | Permission definitions ({path, action, description}) |
| `rolePermissions` | `core.RolePermissions` | Manual (step-03c) | Role-permission mappings |
| `permissionConstants` | `PermissionConstants.cs` | Manual (step-03c) | C# permission constants |

**Transform algorithm (step-03c section 8f-bis):**
- `navigationSections` = transform `specification.sections[]` → flatten to { code, label, icon, route, parentCode, permission, sort }
- `navigationResources` = transform `specification.sections[].resources[]` → flatten to { code, type, entity, parentCode, permission }

**Example:**
- Module: `Employees` (Level 2)
  - Section: `list` (Level 3) → contains resources:
    - Resource: `employees-grid` (SmartTable) (Level 4)
    - Resource: `status-filter` (FilterBar) (Level 4)
  - Section: `detail` (Level 3) → contains resources:
    - Resource: `employee-card` (DetailCard) (Level 4)
    - Resource: `contract-history` (SmartTable) (Level 4)

</navigation_hierarchy>

<resume_workflow>
**Update mode (auto-detected):**

When step-00 detects that the description matches an existing application:

1. Propose to user: "New application" or "Update {appName}"
2. If update: locate existing feature.json, create new version (v1.1, etc.)
3. Load existing feature context
4. Continue through steps 01-05 with delta focus
</resume_workflow>

<workflow>
**Step-00 routing (auto-detection):**

1. Read `{feature_description}`
2. Scan `docs/` for existing applications
3. If match found → ask user: "New application" or "Update {app}" ?
4. If no match → new application
5. Create master feature.json and proceed to step-01

**New application workflow (single or multi-app):**
- **Step 00:** Detection, scan existing, create master feature.json (draft)
- **Step 01:** Cadrage: context, stakeholders, scope, application roles (framed)
- **Step 01b:** Application identity (always): confirm code, route, icon, seed data (lightweight single-app / full decomposition multi-app)
- **Step 02:** Decomposition: modules, dependencies, client checkpoint (decomposed) — per application in multi-app mode
- **Step 03a:** Per-module data: sections, entities, business rules, questionnaires
- **Step 03b:** Per-module UI: state machines, wireframes, layouts, dashboards
- **Step 03c:** Per-module compile: actors, UCs, FRs, permissions, navigation, seed data, i18n
- **Step 03d:** Per-module validate: completeness checks, write feature.json, incremental HTML, loop
  - Loop: 03a → 03b → 03c → 03d → 03a (next module) until all specified (specified)
- **Step 04a:** Collect: module summaries, cross-module interactions (FK, events, shared data)
- **Step 04b:** Analyze: permission coherence, semantic validation, E2E flows, global risks
- **Step 04c:** Decide: final approval, write consolidation section, proceed to handoff (consolidated)
- **Step 05a:** Handoff: file mapping (7 categories), BR-to-code mapping, API summary, write to feature.json
- **Step 05b:** Deploy: prd.json, progress.txt, manifest, ba-interactive.html pre-populated (handed-off)
- **Step 05c:** Ralph Readiness Check: validation gate before /ralph-loop (optional but recommended)

**Update workflow (same phases, delta focus):**
- **Step 00:** Detection, locate existing feature, create version N+1
- **Step 01:** Cadrage delta: what changes, impact on existing
- **Step 02-05:** Same flow as new, with existing context loaded

**Review workflow (`-review` flag):**
- **Step 00:** Detection, scan for latest application, locate `ba-review.json`
- **Step 06:** Apply corrections, create new version, reverse-map data, regenerate all artifacts
</workflow>

<state_variables>
**Persist throughout all steps via feature.json:**

| Variable                | Type    | Description                                            |
| ----------------------- | ------- | ------------------------------------------------------ |
| `{feature_id}`          | string  | Unique identifier (e.g., `FEAT-001`)                   |
| `{feature_description}` | string  | What to analyze                                        |
| `{workflow_type}`       | string  | `"new"` or `"update"`                                  |
| `{version}`             | string  | SemVer (1.0, 1.1, 2.0, etc.)                           |
| `{application_name}`    | string  | Target application name                                |
| `{module_name}`         | string  | Target module name                                     |
| `{project_id}`          | string  | Project identifier (e.g., `PROJ-001`) — only in multi-app mode |
| `{workflow_mode}`       | string  | "project" (multi-app), "application" (single-app multi-module), or "module" (single) |
| `{analysisMode}`        | string  | Always "interactive" — analysis phase is always interactive with the user |
| `{docs_dir}`            | string  | `docs/{app}/{module}/business-analyse/v{X.Y}/` |

</state_variables>

<entry_point>

**FIRST ACTION:** Load `steps/step-00-init.md`

</entry_point>

<step_files>
**Progressive loading - only load current step:**

| Step | File                              | Model  | Purpose                                              |
| ---- | --------------------------------- | ------ | ---------------------------------------------------- |
| 00   | `steps/step-00-init.md`           | Sonnet | Auto-detect new/update, scan existing, create master feature.json |
| 01   | `steps/step-01-cadrage.md`        | Opus   | Framing: context, stakeholders, scope, application roles + multi-app detection |
| 01b  | `steps/step-01b-applications.md`  | Opus   | Application identity: confirm code, route, icon, seedData (lightweight single-app, full decomposition multi-app) |
| 02   | `steps/step-02-decomposition.md`  | Opus   | Module decomposition, dependency graph, client checkpoint (per application in multi-app) |
| 03a1 | `steps/step-03a1-setup.md`        | Opus   | Per-module: setup, sections, questionnaires, cross-refs |
| 03a2 | `steps/step-03a2-analysis.md`     | Opus   | Per-module: objectives, entities, BRs, process flow |
| 03b  | `steps/step-03b-ui.md`            | Opus   | Per-module: state machines, wireframes, layouts, dashboards |
| 03c  | `steps/step-03c-compile.md`       | Opus   | Per-module: actors, UCs, FRs, permissions, navigation, seedDataCore (9 arrays), i18n |
| 03d  | `steps/step-03d-validate.md`      | Sonnet | Per-module: validation, write, incremental HTML, loop decision |
| 04a  | `steps/step-04a-collect.md`       | Opus   | Collect module summaries & cross-module interactions |
| 04b  | `steps/step-04b-analyze.md`       | Opus   | Analyze permission coherence, semantic validation, E2E flows |
| 04c  | `steps/step-04c-decide.md`        | Opus   | Final approval, write consolidation, proceed to handoff |
| 05a  | `steps/step-05a-handoff.md`       | Sonnet | Handoff: file mapping (7 categories), BR-to-code mapping, API summary, write handoff |
| 05b  | `steps/step-05b-deploy.md`        | Sonnet | Deploy: prd.json, progress.txt, manifest, ba-interactive.html |
| 05c  | `steps/step-05c-ralph-readiness.md` | Opus | ULTRATHINK quality review + ralph readiness gate (MANDATORY) |
| 06   | `steps/step-06-review.md`         | Opus   | Apply review corrections, create new version, regenerate all artifacts |

</step_files>

<questionnaire_files>
**Progressive questionnaire loading (step-01 only):**

Load ONLY relevant categories based on feature type:

| Categorie | Fichier                               | Questions | Quand charger |
| --------- | ------------------------------------- | --------- | ------------- |
| 00b       | `questionnaire/00b-project.md`        | 5         | Si workflow_mode = "project" (multi-app) |
| 00        | `questionnaire/00-application.md`     | 18        | Si workflow_mode = "application" ou "project" |
| 01        | `questionnaire/01-context.md`         | 32        | Toujours      |
| 02        | `questionnaire/02-stakeholders.md`    | 33        | Toujours      |
| 03        | `questionnaire/03-scope.md`           | 32        | Toujours      |
| 04        | `questionnaire/04-data.md`            | 15        | Si module oriente donnees |
| 05        | `questionnaire/05-integrations.md`    | 14        | Si integrations |
| 06        | `questionnaire/06-security.md`        | 13        | Si securite mentionnee |
| 07        | `questionnaire/07-ui.md`              | 19        | Si module oriente interface |
| 08        | `questionnaire/08-performance.md`     | 8         | Si performance critique |
| 09        | `questionnaire/09-constraints.md`     | 6         | Si contraintes |
| 10        | `questionnaire/10-documentation.md`   | 7         | Si documentation requise |
| 11        | `questionnaire/11-data-lifecycle.md`  | 14        | Si lifecycle requis (retention, archivage, RGPD) |
| 12        | `questionnaire/12-migration.md`       | 14        | Si nouveau module (migration donnees existantes) |
| 13        | `questionnaire/13-cross-module.md`    | 14        | Si nouveau module OU references autres modules |
| 14        | `questionnaire/14-risk-assumptions.md`| 16        | Toujours      |
| 15        | `questionnaire/15-success-metrics.md` | 17        | Toujours      |

**Total noyau (toujours chargés) : 130 questions** (contexte, acteurs, périmètre, risques, métriques)
**Total avec application : 148 questions** (+ identité application si mode multi-module)
**Total conditionnel : 124 questions** (data, intégrations, sécurité, UI, performance, contraintes, doc, lifecycle, migration, cross-module)
**Total maximum possible : 272 questions** (noyau + application + tous conditionnels chargés)

</questionnaire_files>

<template_files>
**Progressive template loading:**

| Template | File                                | Used in step |
| -------- | ----------------------------------- | ------------ |
| schema   | `schemas/feature-schema.json`       | All steps    |
| spec     | `templates/tpl-frd.md`              | 02           |
| handoff  | `templates/tpl-handoff.md`          | 05a          |
| suggestions | `patterns/suggestion-catalog.md` | 01           |
| interactive | `html/ba-interactive.html`        | 03d (incremental), 05b (final deploy)  |
| mapping    | `references/html-data-mapping.md`  | 03d, 05b (FEATURE_DATA + EMBEDDED_ARTIFACTS mapping) |

</template_files>

<execution_rules>

- **Load one step at a time** - Only load the current step file
- **Load shared files conditionally** - Each step loads only the _shared files it needs (see step headers)
- **Reference files on demand** - Templates and mappings in references/ and templates/ are loaded only when needed
- **ULTRATHINK** for steps 01, 02, 03a-03c, 04 (critical thinking)
- **State persisted in feature.json** (NOT markdown files)
- **Use ba-writer agent** for all JSON writes
- **Use ba-reader agent** for all JSON reads
- **Follow next_step directive** at end of each step
- **Use parallel agents** for codebase exploration
- **Team mode** (2+ modules): After step-02, load `references/team-orchestration.md` and follow team protocol
- **Inline mode** (1 module): Classic sequential execution, no team
- **Project mode** (2+ applications): Application loop wraps module loop — see `_module-loop.md`
</execution_rules>

<team_mode>
**Automatic team activation for multi-module applications:**

| Condition | Mode |
|-----------|------|
| 1 module | Inline (classic, no team) |
| 2+ modules | Team mode (Propose & Review) |

**Team mode workflow (Parallel Propose & Review):**
1. Steps 00-02 execute inline in the main conversation (interactive with user)
2. After step-02 decomposition: clean up old team data (§1a), then `TeamCreate({ team_name: "ba-{appName}" })` — **CRITICAL: capture the RETURNED team name** (may differ from requested)
3. For each dependency layer: pre-analyze cross-module touchpoints, then spawn autonomous agents **IN PARALLEL** (all modules in the same layer run simultaneously). Team lead pre-injects coordination notes into each agent's prompt, handles runtime cross-module queries between agents, then presents cross-module interaction analysis + individual module reviews to user.
4. Between layers: shutdown all layer agents, rebuild completedModulesSummary, spawn next layer
5. After all modules specified: spawn consolidation agent (steps 04a + 04b), present report for user approval (04c)
6. After consolidation approved: spawn handoff agent (steps 05a + 05b + 05c)
7. `TeamDelete()` cleanup

**Why team mode:**
- Each module agent gets a **fresh context window** (zero accumulation)
- The team lead stays lightweight (< 30% context even with 10+ modules)
- Module agents work **autonomously** (no AskUserQuestion — they PROPOSE, user REVIEWS)
- **Parallel execution**: modules in the same dependency layer run simultaneously (~50-66% wall-clock reduction)
- **Cross-module coordination**: team lead pre-injects known touchpoints + relays runtime queries between parallel agents
- Error recovery: if an agent crashes, other agents in the layer continue; crashed module retried independently

**Reference:** `references/team-orchestration.md` (loaded by step-02 after decomposition)
**Agent prompt template:** `references/agent-module-prompt.md`
</team_mode>

<success_criteria>

- Master feature.json created and enriched progressively through all steps
- Module decomposition validated by client (step-02 checkpoint)
- Each module specified iteratively with client validation
- ASCII/SVG mockups proposed for each module's sections
- Cross-module consolidation passed (step-04)
- Development handoff ready for `/ralph-loop`
- Ralph Loop prd.json generated (per module or consolidated)
- All outputs renderable by SmartStack app viewer at `/docs/{app}/`
</success_criteria>
