# Business Analysis - Shared Core

> **Ref:** Core shared functions loaded by ALL BA steps.
>
> **Conditional files (loaded per-step as needed):**
> - `_elicitation.md` — Interactive protocol, techniques 1-8, AskUserQuestion format, ULTRATHINK
> - `_architecture.md` — SmartStack 5 layers, entity base classes, DB conventions, SeedData Core
> - `_module-loop.md` — Module iteration protocol, state management, resume logic
> - `_suggestions.md` — Proactive suggestions, Context7 libraries

---

## JSON-First Architecture

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

### Project-Level (Multi-App Master) — Only if 2+ applications
**Path:** `docs/business-analyse/v{X.Y}/feature.json`
**Schema:** `docs/business-analyse/schemas/project-schema.json`
**$schema:** `"../schemas/project-schema.json"`

| Step | Section enriched | Status after |
|------|-----------------|--------------|
| 00-init | metadata | draft |
| 01-cadrage | cadrage (global problem, stakeholders, scope, roles) | framed |
| 01b-applications | applications[], applicationDependencyGraph | decomposed |
| 02-05 | applications[].status updated per iteration | specified → handed-off |

> **Backward compatibility:** If only 1 application is identified, the project level is NOT created. The application-level feature.json remains the master (current behavior).

### Application-Level (Master)
**Path:** `docs/{app}/business-analyse/v{X.Y}/feature.json`
**Schema:** `docs/{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 (or 01b) | 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/{app}/{module}/business-analyse/v{X.Y}/feature.json`
**Schema:** `docs/{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, createProjectFeature, enrichApplicationRegistry, advanceModuleLoop, advanceApplicationLoop)
- **ba-reader**: Reads feature.json (findFeature, findProjectFeature, readSection, answerQuestion, getSummaryForSkill, readApplicationContext, getCompletedModulesSummary, getCompletedApplicationsSummary)

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

### Workflow Modes

| Mode | Trigger | Master Level | Loop |
|------|---------|-------------|------|
| `"module"` | 1 module only | Application | No loop |
| `"application"` | 1 app, 2+ modules | Application | Module loop |
| `"project"` | 2+ applications | Project | Application loop → Module loop per app |

---

## 4-Level Navigation Hierarchy (SmartStack)

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

The BA aligns with the SmartStack navigation hierarchy:

```
Level 1: Application (Sales)
     Level 2: Module (Customers)
          Level 3: Section (list)              ← sidebar nav
               Level 4: Resource (customer-grid)
               Level 4: Resource (customer-filters)
          Level 3: Section (detail) [hidden]   ← reached by row click, route :id
               Level 4: Resource (customer-detail-header)
               Level 4: Resource (customer-detail-tabs)
               Level 4: Resource (customer-info-card)
               Level 4: Resource (customer-orders-grid)   ← relation tab
               Level 4: Resource (customer-history)        ← audit tab
     Level 2: Module (Orders)
          Level 3: Section (list)              ← sidebar nav
          Level 3: Section (detail) [hidden]   ← reached by row click
          Level 3: Section (approve)           ← sidebar nav (workflow)
```

**CRITICAL — Application identification (Level 1):**
The application is formally identified in step-01b (ALWAYS, even for single-app mode):
- Code: PascalCase (e.g., "HumanResources")
- Route: kebab-case (e.g., "/human-resources")
- Icon: Lucide icon name
- Sort order: position in navigation
This creates the `seedDataCore.navigationApplications` entry that links modules to their parent application.
The `seedDataCore.applicationRoles` entries are also built from `cadrage.applicationRoles`.

| BA Phase | Levels treated | What is defined |
|----------|---------------|-----------------|
| Cadrage (step-01) | Application | Problem, stakeholders, scope, application-level roles |
| Decomposition (step-02) | Modules | Module list, dependencies, processing order |
| Specification (step-03) | Module → Sections → Resources (levels 2-3-4) | 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 patterns
```
/{application}/{module}                         ← list section (= module route, NO /list suffix)
/{application}/{module}/:id                     ← detail page (= module route + /:id, NO /detail prefix)
/{application}/{module}/{section}               ← other sidebar sections (dashboard, approve, import, etc.)
```

**Detail page routing:**
- The detail page uses a parameterized route with `:id`
- It is NOT registered as a sidebar navigation entry (`navigation: "hidden"`)
- It is reached by clicking a row in the `list` section (action: `navigate:detail`)
- The back button navigates to `/{application}/{module}`
- Route MUST be registered in frontend routing (App.tsx) alongside the list route

> **ROUTE SPECIAL CASES (list and detail sections):**
> `list` and `detail` are view modes of the module, NOT functional sub-areas.
> - `list` route = module route (NO `/list` suffix) — React Router index route
> - `detail` route = module route + `/:id` (NO `/detail/` prefix) — React Router `:id` child
> - FORBIDDEN in navigation seed: `/module/list`, `/module/detail/:id`
> - Other sections (dashboard, approve, import) add `/{section-kebab}` normally

### Standard Sections per Module

> **RULE: Sections are functional zones, NOT CRUD operations.**
> `create` and `edit` are SEPARATE PAGES with their own URL routes (`/create` and `/:id/edit`).
> `detail` is a page with tabs accessible by clicking a row in `list` (not a standalone nav section).

| Section | Purpose | Typical Components |
|---------|---------|-------------------|
| `list` | **Main page**: entity grid + create button (navigates to `/create` page) + click to detail | DataGrid, FilterBar, Pagination, CreateButton |
| `detail` | **Reached from list** (hidden nav, route `:id`): tabbed view of entity details + edit button (navigates to `/:id/edit` page) | BackButton, DetailHeader, StatusBadge, TabPanel, DetailCard, SmartTable (relations), Timeline (history) |
| `dashboard` | Module overview/KPIs (if analytics needed) | Charts, StatCards, RecentActivity |
| `approve` | Approval workflow queue (if validation workflow) | ApprovalPanel, StatusTimeline |
| `import` | Bulk data import (if volume > 100) | FileUpload, MappingTable, Preview |
| `rapport` | Module-specific reporting | ReportBuilder, ExportPanel |
| `planning` | Calendar/planning view (if time-based data) | Calendar, GanttChart, TimelineView |

**What is NEVER a section:**

| NOT a sidebar section | What it really is |
|---------------|-------------------|
| `create` | Action button in `list` page → navigates to `/create` page with form |
| `edit` | Action in list/detail page → navigates to `/:id/edit` page with pre-filled form |
| `delete` | Action with inline confirmation in `list` or detail |
| `search` | FilterBar component integrated in the `list` section |

> **Note on `detail`:** The detail page IS a `specification.sections[]` entry (with `navigation: "hidden"`) so it gets a wireframe, resources, and route. But it is NOT shown in the sidebar — it is reached by clicking a row in `list`. Every module with a `list` section MUST have a companion `detail` section.

---

---

## Feature Directory Structure

```
docs/
  business-analyse/                       <- PROJECT level (only if multi-app)
      schemas/
          project-schema.json
      v1.0/
          feature.json                    <- PROJECT master ($schema: ../schemas/project-schema.json)
  {application}/
      business-analyse/
          schemas/                        <- JSON SCHEMAS (deployed by step-00)
              feature-schema.json
              application-schema.json
              project-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
```

> In standalone mode (single app), the project-level directory is NOT created.

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

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

---

## 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)

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

---

## Permission Path Format

| Level | Format | Example |
|-------|--------|---------|
| Module | `{app}.{module}.{action}` | `human-resources.employees.read` |
| Section | `{app}.{module}.{section}.{action}` | `human-resources.employees.departments.read` |

> **Rule:** Use module-level permissions for standard CRUD. Use section-level permissions only when a section requires distinct access control (e.g., dashboard, approve, import).
>
> **CRITICAL — All segments use kebab-case:** Multi-word codes MUST have hyphens. `human-resources`, NOT `humanresources`. Matches NavRoute convention. SmartStack.app ref: `support-client.my-tickets.read`

| 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/{app}/{module}/business-analyse/v{X.Y}/feature.json` |
| User Guide | `docs/{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: offer to create fresh feature.json
```

---

## 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 etre dans la langue configuree.

### Configuration

Le champ `language` dans `feature.json.metadata.language` definit la langue :

| Langue | Code | Defaut |
|--------|------|--------|
| Francais | `fr` | **Oui** |
| English | `en` | Non |
| Italiano | `it` | Non |
| Deutsch | `de` | Non |

### Portee

| Element | Adapte a la langue ? |
|---------|---------------------|
| Questions `AskUserQuestion` (labels, descriptions, options) | **OUI** — toujours dans `{language}` |
| Reformulations et resumes de categorie | **OUI** — toujours dans `{language}` |
| Relances et follow-ups (Elicitation Guide) | **OUI** — traduire les probes a la volee |
| Documents generes (discovery, analysis, specification, handoff) | **OUI** — rediges dans `{language}` |
| Reference technique interne (patterns, architecture) | NON — reste en langue du fichier |
| Noms de code (entites, permissions, paths) | NON — toujours en anglais (convention plateforme) |

### Regle

```
1. Lire {language} depuis feature.json.metadata.language (defaut: "fr")
2. Adapter TOUTE communication AskUserQuestion dans {language}
3. Les exemples de probes/relances dans les questionnaires sont en francais
   -> Si {language} != "fr", les traduire a la volee
4. Les documents generes sont rediges dans {language}
5. Le code, les noms d'entites et les paths restent TOUJOURS en anglais
6. Ne JAMAIS utiliser "SmartStack" dans les communications utilisateur
   -> Utiliser "la plateforme", "l'application" ou "le systeme" a la place
   -> SmartStack est le nom interne du framework, le projet client a son propre nom
```

---

## Config Template

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

---

## Support

Contact: **support@atlshub.ch**
