# Business Analysis — Shared Conventions

## Fundamental Analysis Rules

1. **NEVER skip web research.** Domain research is MANDATORY and BLOCKING.
   An analysis without research is a 2/10 regardless of structural quality.

2. **NEVER accept a thin application.** Every application MUST be challenged
   against industry standard module counts (see `references/module-completeness-challenge.md`).
   A 1-module billing application is ALWAYS wrong — challenge it.

3. **ALWAYS propose domain-specific business rules.** Generic CRUD rules
   (date validation, required fields) are the MINIMUM baseline. Domain rules
   (half-day absences, team capacity, carry-over limits, credit note linking,
   sequential invoice numbering) are what make an analysis valuable.
   **Target: >= 2 domain-specific rules per business module (`domainSpecific: true`).**
   Post-check C19 enforces this as a WARNING.

4. **ALWAYS propose contextual views.** A workflow module without filtered
   views (open-requests, rejected, history, my-{entity}) is incomplete.

5. **ALWAYS process application by application.** Research each app's domain
   before decomposing into modules. Challenge module completeness per app.

6. **ACT AS AN EXPERT ANALYST, NOT A NOTE-TAKER.** Challenge, propose,
   question. If the user says "billing with invoices", your job is to say
   "standard billing also includes credit notes, payment tracking, and
   dunning. Would you like to add these?" The user came to you for expertise.

7. **NEVER compress or batch module processing in step-03.** Each module MUST be
   processed sequentially in the main context. Sub-agents do NOT have access to the
   JSON schema and WILL produce inconsistent formats. If there are 15+ modules, the
   correct approach is to maintain sequential processing, NOT to "accelerate" by
   batching. The ba-012 audit proved that batching reduced schema conformity from
   95% to 35% — the rework cost exceeded any time saved.

8. **ALL generated JSON content values MUST be in `{language}`** (from metadata or config).
   This applies to ALL text values written to JSON files:
   - Entity `description`, attribute `description`, relationship `description`
   - Business rule `name`, `statement`, `examples[].input`, `examples[].expected`
   - Use case `name`, `mainScenario[]` steps, `alternativeScenarios[].steps[]`, `errorScenarios[].steps[]`, `preconditions[]`, `postconditions[]`
   - Permission `description`, role `description`
   - Lifecycle state `displayName`
   - Section and resource labels

   **Mixed-language content across modules is a BLOCKING quality defect.**
   If `language == "fr"` : write "Créer une absence", NOT "Create an absence".
   If `language == "en"` : write "Create an absence", NOT "Créer une absence".
   Technical identifiers (entity names, field names, enum values, IDs) remain in English/PascalCase.

9. **BR `examples[]` are TEST DATA, not documentation.** Each example must be a
   concrete test case with the `{scenario, given, when, then}` format:
   - `given`: object with `Entity.field: concreteValue` pairs (initial state)
   - `when`: string action (`"create"`, `"submit"`, `"calculate_remaining"`)
   - `then`: object with expected outcome (`{result: "success"|"error", Entity.field: value}`)

   These examples directly feed:
   - Gherkin `Examples:` tables (step-03, F-ter)
   - `brToCodeMapping` in handoff
   - Automated unit/integration tests in `/business-analyse-develop`

   A rule without test-ready examples = a test gap in development.
   Prose examples like `"code déjà existant"` are INSUFFICIENT — use concrete values.

---

## JSON-First Architecture

Feature data is stored as granular JSON files, NOT markdown. Each module has an `index.json` referencing thematic files.

### File structure

```
docs/
  {projet-slug}/                     ← Project (kebab-case, 100% autonomous)
    v{X.Y}/
      index.json                     ← Project master index
      cadrage.json                   ← Project-level framing
      consolidation.json             ← Cross-module validation
      navigation.json                ← Navigation tree
      validation.json                ← Validation results
      ba-interactive.html            ← Generated HTML deliverable
      {app-kebab}/                   ← Application (kebab-case)
        index.json                   ← Application index
        {module-kebab}/              ← Module (kebab-case)
          index.json                 ← Module index
          entities.json              ← Entities, attributes, relations
          rules.json                 ← Business rules
          usecases.json              ← Use cases
          permissions.json           ← Permissions matrix
          screens.json               ← Interface specs (sections, resources, mockups)
          handoff.json               ← File mapping, API specs
```

### Index.json structure

```json
{
  "metadata": {
    "featureId": "FEAT-001",
    "moduleCode": "Employees",
    "applicationCode": "HumanResources",
    "version": "1.0",
    "status": "specified",
    "createdAt": "...",
    "lastModified": "..."
  },
  "files": {
    "entities": { "path": "entities.json", "hash": "abc123", "lastModified": "..." },
    "rules": { "path": "rules.json", "hash": "def456", "lastModified": "..." },
    ...
  },
  "summary": {
    "entityCount": 3,
    "ruleCount": 5,
    "useCaseCount": 8,
    "permissionCount": 22,
    "screenCount": 4,
    "dependencies": ["Absences"]
  }
}
```

### Partial loading

Steps load only the files they need:
- **ba-reader** reads `index.json` to discover files, then loads only the requested file
- **ba-writer** writes to specific files (e.g., `entities.json`) and updates the hash in `index.json`

## Workflow Modes

| Mode | Trigger | Description |
|------|---------|-------------|
| `new` | No existing index.json | Full analysis from scratch |
| `update` | Existing index.json found | Delta analysis (add modules, update specs) |

### Workflow detection

```
1. Check for existing docs/*/v*/index.json → mode = "update"
2. Otherwise → mode = "new"
```

> **Legacy detection:** Also check `docs/business-analyse/v*/index.json` and `docs/*/business-analyse/v*/index.json` for backward compatibility with pre-ba-006 projects.

> **Note:** Review mode (`ba-review.json`) is handled by the `/business-analyse-review` skill.

## Navigation Hierarchy

Maps to SmartStack DB tables:

| Level | DB Table | Example |
|-------|----------|---------|
| Application | nav_Applications | HumanResources |
| Module | nav_Modules | Employees |
| Section | nav_Sections | list, detail |
| Resource | nav_Resources | employees-grid, employee-form |

### Naming conventions

- **Project directory**: kebab-case slug (e.g., `projet-rh`, `commande-repas`)
- **Application directory**: kebab-case (e.g., `human-resources`) — derived from PascalCase code via `toKebabCase()`
- **Module directory**: kebab-case (e.g., `employees`) — derived from PascalCase code via `toKebabCase()`
- **Application code** (in JSON): PascalCase (e.g., `HumanResources`)
- **Module code** (in JSON): PascalCase (e.g., `Employees`)
- **Section code**: kebab-case (e.g., `list`, `detail`, `dashboard`)
- **Resource code**: kebab-case (e.g., `employees-grid`, `employee-form`)

### Directory name conversion

```javascript
function toKebabCase(code) {
  return code
    .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
    .replace(/([A-Z]+)([A-Z][a-z])/g, '$1-$2')
    .toLowerCase();
}
```

### Project detection and selection

Projects are discovered by glob — no central registry:

```
1. Glob: docs/*/v*/index.json
2. If 0 projects → ERROR "No project found. Run /business-analyse first."
3. If 1 project → auto-select
4. If N projects → AskUserQuestion "Which project?"
   Options: [{label: "{slug} (v{X.Y})", description: "{appCount} apps, {moduleCount} modules, status: {status}"}, ...]
5. Store selection in .business-analyse/config.json
```

### Path resolution helpers

```javascript
function resolveProjectDir(projectSlug, version) {
  return `docs/${projectSlug}/v${version}`;
}

function resolveAppDir(projectDir, appCode) {
  return `${projectDir}/${toKebabCase(appCode)}`;
}

function resolveModuleDir(projectDir, appCode, moduleCode) {
  return `${projectDir}/${toKebabCase(appCode)}/${toKebabCase(moduleCode)}`;
}
```

## Permission Paths

Format: `{ApplicationCode}.{ModuleCode}.{Action}`

Actions: `Read`, `Create`, `Update`, `Delete`, `Export`, `Validate`

Example: `HumanResources.Employees.Read`

For section-level: `{ApplicationCode}.{ModuleCode}.{SectionCode}.{Action}`

## Agents

### ba-writer

Writes granular JSON files. Key operations:
- `create(scope, data)` — Create index.json + initial files in `docs/{projectSlug}/v{X.Y}/`
- `enrichSection(fileType, data)` — Write to specific file (entities.json, rules.json, etc.)
- `updateIndex(summary)` — Update index.json metadata and summary
- `createVersion(type)` — Create new version (major/minor)
- `applyReview(reviewData)` — Apply ba-review.json corrections

All paths follow the pattern: `docs/{projectSlug}/v{X.Y}/{appKebab}/{moduleKebab}/`

### ba-reader

Reads via index.json. Key operations:
- `findFeature(featureId)` — Locate feature by ID
- `readSection(moduleCode, fileType)` — Read specific file via index
- `getModuleStatus()` — Status table of all modules
- `getCompletedModulesSummary()` — Compact summaries for context loading
- `getSummaryForSkill(skill)` — Context for other skills (business-analyse-develop, etc.)

## Status Progression

```
draft → framed → decomposed → specified → consolidated → designed → reviewed → handed-off
```

| Status | Set by | Meaning |
|--------|--------|---------|
| draft | Step 00 | Feature created, no content |
| framed | Step 01 | Application-level framing complete (scope, stakeholders, roles) |
| decomposed | Step 02 | Module hierarchy identified (App > Module > Section > Resource) |
| specified | Step 03 | Module fully specified (entities, UCs, BRs, permissions, screens) |
| consolidated | Step 04 | Cross-module validation and consolidation passed |
| designed | Step 05 | UI/UX design and navigation complete |
| reviewed | `/business-analyse-review` | Client review applied |
| handed-off | `/business-analyse-handoff` | PRD files generated, ready for development |

## Handoff & PRD Generation

Handoff data and PRD files are generated by the `/business-analyse-handoff` skill. The workflow is:

```
/business-analyse (steps 00-04) → /business-analyse-html → /business-analyse-review (if needed) → /business-analyse-handoff → /business-analyse-develop
```

## HTML Generation

For HTML generation, use the `/business-analyse-html` skill after step-04 consolidation. For client review corrections, use `/business-analyse-review`.

## Resume Protocol

State is tracked in `index.json` metadata:
- `metadata.status` — Current status
- `metadata.lastModified` — Last modification timestamp

The step system checks metadata to determine where to resume.
