---
name: ba-loop
description: >
  Autonomous BA pipeline orchestrator. Chains phases 2-7 (actors → use cases →
  rules → RBAC → data model → screens) module by module in wave order, each
  phase running as a subagent with the create → audit → fix cycle. Reads
  ba-order.json for wave ordering. Run after /ba-create-ba-order (Phase 1.5).
allowed-tools: [Read, Write, Edit, Glob, Grep, Bash, Agent, AskUserQuestion]
argument-hint: '[APP1] [APP2] … [--from-phase N] [--module APP/MODULE]'
---

# ba-loop — Autonomous BA pipeline

You are the **BA pipeline orchestrator**. Your job is to chain the 6 BA
creation phases (actors → use cases → rules → RBAC → data model → screens)
**automatically**, using one **subagent per phase per module** to keep context
tight. Each subagent runs the cycle: **create → audit → fix → re-audit**.

You **never write BA content yourself** — you launch subagents and gate between
phases. Your responsibilities:

1. Read the BA tree and wave ordering
2. Launch subagents in the correct order
3. Read audit verdicts after each phase
4. Gate: 0 `err` → advance; `err > 0` after fix retry → stop and report
5. Report progress to the user between waves

## Prerequisites

Before invoking `/ba-loop`:
- `/ba-create-menu` (Phase 1) must be complete
- `/ba-create-ba-order` (Phase 1.5) should be complete (provides wave ordering)
- If no `ba-order.json` exists, discover modules from the tree and process in
  alphabetical order (flat, no waves)

## Arguments

| Arg | Effect |
|-----|--------|
| `APP1 APP2` | Scope to specific applications (default: all) |
| `--from-phase N` | Resume from phase N (2=actors, 3=UC, 4=rules, 5=RBAC, 6=data-model, 7=screens) |
| `--module APP/MODULE` | Process only one specific module |
| `--skip-existing` | Skip phases where audit already passes (0 err). Off by default — the default behavior is **enrichment** (re-analyze and add missing items even if the phase was already done) |

## Phase chain

```
Phase 2 : Actors       → app-scoped (one subagent per app)
Phase 3 : Use Cases    → section-scoped (one subagent per module, iterates sections)
Phase 4 : Business Rules → module-scoped (one subagent per module)
Phase 5 : RBAC         → module-scoped (one subagent per module)
Phase 6 : Data Model   → module-scoped (one subagent per module)
Phase 7 : Screens      → section-scoped (one subagent per module, iterates sections)
```

## Orchestration protocol

### Step 0 — Read state and plan

```
1. Glob .smartstack/ba/**/index.md → rebuild the menu tree
2. Read .smartstack/ba/_plan/ba-order.json (if exists) → wave ordering
3. Identify: which apps, which modules, which sections per module
4. Inventory existing content per phase:
   - Which acteur.md files exist and have real content (not placeholders)?
   - Which sections have use-case.md with actual UCs?
   - Which modules have règles-métier.md, rbac.md, entité.md, screen.md?
5. For each phase: mark as FRESH (placeholder/missing) or ENRICH (content exists)
6. Present the execution plan to the user (one-liner per module × phase,
   with FRESH/ENRICH status)
```

If `ba-order.json` exists, follow wave ordering. Otherwise, list all modules
alphabetically in a single wave.

**Default mode is ENRICH** — the subagent always re-analyzes, even when content
already exists. This catches:
- New sections added to the menu that have no UCs yet
- New actors added that need UC/RBAC coverage
- Upstream changes (renamed sections, updated contexts) that require
  downstream adjustments
- Missing business rules for newly discovered edge cases

Use `--skip-existing` to revert to skip-if-0-err behavior.

### Step 0.5 — Menu reconciliation preflight (BLOCKING)

**Rule**: en cas de modification du menu lors d'un rerun, **tu ne peux pas
skipper** — tu dois auditer si ce qui a été fait est correct et **corriger
si ce n'est pas le cas**. Even with `--skip-existing`, this preflight runs
unconditionally.

Before launching any Phase 2-7 subagent, invoke the reconciliation CLI in
dry-run mode to detect drift between the current menu tree and the codes
embedded in downstream docs:

```bash
npx --prefer-offline tsx skills/business-analyse/reconcile-menu/cli/reconcile-menu/index.ts \
  --spec '{"baRoot": ".smartstack/ba", "dryRun": true}'
```

Read the envelope:

| `data.renames` | `data.deletions` | Action |
|----------------|------------------|--------|
| empty | empty | Tree consistent — proceed to Step 1 silently |
| any | any | **Hand off to `/ba-reconcile-menu`** (skill, not orchestrator) — it shows the diff via AskUserQuestion, applies, then returns control here |

When `/ba-reconcile-menu` returns:
- If the user validated and applied → re-run the dry-run scan once to confirm
  `renames + deletions = 0`. If still non-empty, surface the residual and halt.
- If the user picked "Skipper" → emit a `warn` in the loop's report and continue
  (downstream audits — SEC-007 and UC-019 — will block the GO gate anyway).

**Never skip Step 0.5 with `--skip-existing`** — that flag controls whether
to re-create existing 0-err content, not whether to reconcile a modified
menu. The two concerns are orthogonal.

### Step 1 — Phase 2: Actors (per app)

Actors are **app-scoped**. Launch one subagent per application.

**Subagent prompt template** (substitute `{APP}`, `{APP_CONTEXT}`, `{MODULES}`):

```
You are a senior business analyst. Your task:

1. READ these files:
   - .smartstack/ba/{APP}/index.md (app context)
   - .smartstack/ba/{APP}/*/index.md (all module contexts)
   - .smartstack/ba/{APP}/acteur.md (existing actors, if any)

2. ENRICH actors for the {APP} application:
   - If acteur.md is a placeholder or missing → create from scratch
   - If acteur.md already has actors → READ THEM CAREFULLY, then:
     a. Check every module has ≥1 actor covering it (ACT-006)
     b. Check if new modules/sections were added that need new actors
     c. Check if existing actor scopes need updating (new sections)
     d. PRESERVE every existing actor (keep its code, label, fields)
     e. ADD new actors with the next available code sequence
     f. UPDATE scope lines of existing actors if needed
   - For each actor: code (BA-{NNN}-AC-{NNN}), label, type (Humain/Système/Externe),
     description, scope (which modules/sections), origin
   - Follow the format from /ba-create-actors: anchor comment + ### headings
   - Write the COMPLETE file to .smartstack/ba/{APP}/acteur.md
     (Write overwrites — include ALL actors: existing + new)

3. AUDIT your work:
   - Apply rules ACT-001 through ACT-006:
     ACT-001: Every app must have ≥1 actor
     ACT-002: No duplicate actor names (case-insensitive) across the project
     ACT-003: Every actor must have a type (Humain/Système/Externe)
     ACT-004: Every actor must have a non-empty description
     ACT-005: Actor codes must follow BA-{NNN}-AC-{NNN} format
     ACT-006: Every module should be covered by ≥1 actor scope
   - Write the verdict to .smartstack/ba/_audit/actors.md

4. FIX if needed:
   - If your audit found errors (err > 0), fix the acteur.md and re-audit
   - Max 2 fix cycles

Report: N existing actors kept, N new actors added, audit result (N err, N warn, N ok).
```

### Step 2 — Phases 3-7: Per module, in wave order

For each wave (1, 2, 3…), for each module in that wave, run phases 3 through 7
**sequentially** (each in its own subagent). Between phases, verify the
previous phase's audit is clean (0 err).

#### Phase 3: Use Cases (subagent per module)

**Subagent reads**: app `acteur.md`, module + all sections `index.md`
**Subagent writes**: `use-case.md` at each section (authoritative), audit verdict at module
**Audit rules**: UC-001 through UC-018

**Subagent prompt template** (substitute `{APP}`, `{MODULE}`, `{SECTIONS}`):

```
You are a senior business analyst. Your task:

1. READ:
   - .smartstack/ba/{APP}/acteur.md (actors — source of valid actor codes)
   - .smartstack/ba/{APP}/{MODULE}/index.md (module context)
   - .smartstack/ba/{APP}/{MODULE}/*/index.md (all section contexts)
   - ALL existing use-case.md files in sections (may have real content)

2. ENRICH use cases for EVERY section of module {APP}/{MODULE}:
   Sections to cover: {SECTIONS}
   For each section:
   - If use-case.md is a placeholder → create from scratch
   - If use-case.md already has UCs → READ THEM, then:
     a. PRESERVE every existing UC (keep its code, all flows, all fields)
     b. Check: does the section context mention capabilities not covered by any UC?
     c. Check: are there new actors (from acteur.md) that need their own UCs?
     d. Check: are existing UC actor references still valid?
     e. ADD missing UCs with the next available code sequence
     f. UPDATE existing UCs only if actor refs are stale or flows reference
        removed sections
   - Write Cockburn-style UCs: code UC-{APP}-{MODULE}-{SECTION}-NNN
   - Each UC: level, primary actor, preconditions, main flow (≥3 steps),
     alternative flows, exception flows, postconditions, linked BRs
   - Write the COMPLETE file (existing + new UCs) to each section's use-case.md

3. AUDIT — apply rules UC-001..018:
   UC-001: Every section must have ≥1 UC
   UC-002: UC code format UC-{APP}-{MOD}-{SEC}-NNN
   UC-003: Primary actor must reference a valid BA-NNN-AC-NNN from acteur.md
   UC-004: Main flow must have ≥3 numbered steps
   UC-005: At least one alternative flow per UC
   UC-006: Preconditions must be testable (not vague)
   UC-007: Postconditions must state observable outcomes
   UC-008: No duplicate UC titles within a module
   UC-009: Level must be user-goal or subfunction
   UC-010: No CRUD-style titles (Create X, Edit Y, Delete Z)
   UC-011: Steps must use active voice with named actors
   UC-012: Every UC should link to ≥1 BR (even placeholder)
   Write verdict to .smartstack/ba/{APP}/{MODULE}/_audit/use-case.md

4. FIX if err > 0, then re-audit. Max 2 fix cycles.

Report: N existing UCs kept, N new UCs added, N sections covered, audit result.
```

#### Phase 4: Business Rules (subagent per module)

**Subagent reads**: module `use-case.md` files, `acteur.md`, `index.md`
**Subagent writes**: `règles-métier.md` at module level
**Audit rules**: BR-001 through BR-010

**Subagent prompt** — same pattern: read UCs + section contexts → generate
structured rules with valid/invalid examples → write → audit BR-001..010 → fix.

#### Phase 5: RBAC (subagent per module)

**Subagent reads**: `acteur.md`, `use-case.md` files, `règles-métier.md`
**Subagent writes**: `rbac.md` at module level
**Audit rules**: RBAC-001 through RBAC-005

#### Phase 6: Data Model (subagent per module)

**Subagent reads**: `use-case.md` files, `règles-métier.md`, `rbac.md`, `index.md`
**Subagent writes**: `entité.md` at module level
**Audit rules**: DM-001 through DM-017

This is the most complex phase. The subagent must:
- Deduce entities from UCs and business rules
- Define attributes (name, type, constraints), relationships (FK), indexes
- Use SmartStack conventions (PascalCase entities, snake_case tables, Guid PKs)
- Mark cross-module FKs as `FK cross-module vers APP/MODULE.Entity`
- Classify each entity (agrégat racine, composant, lookup, technical)

#### Phase 7: Screens (subagent per module)

**Subagent reads**: `entité.md`, `rbac.md`, `use-case.md` files, section `index.md`
**Subagent writes**: `screen.md` at each section (authoritative)
**Audit rules**: SCR-001 through SCR-013

### Step 3 — Cross-dimension audit

After all modules complete phases 2-7, launch one subagent per module for the
cross-dimension audit (`/ba-audit-cross-dimension`). This verifies coherence
**across** the six documents (data model fields ↔ business rules ↔ use cases ↔
screens ↔ RBAC).

### Step 4 — Pre-dev readiness

Run `/ba-audit-pre-dev` to aggregate all dimension verdicts into a single
GO/NO-GO report at `.smartstack/ba/_audit/pre-dev.md`.

### Step 5 — Report to user

Present a summary table:

```
| Module | Actors | UCs | Rules | RBAC | Data Model | Screens | Cross-dim | Ready |
|--------|--------|-----|-------|------|------------|---------|-----------|-------|
| APP/REF | ✅ 0e | ✅ 0e | ✅ 0e | ✅ 0e | ✅ 0e | ✅ 0e | ✅ 0e | GO |
| APP/CLI | ✅ 0e | ⚠️ 1w | ✅ 0e | ✅ 0e | ❌ 2e | ✅ 0e | — | NO-GO |
```

For modules that are GO → suggest `/ba-create-prd`.
For modules that are NO-GO → list the blocking errors and the fix skill.

## Subagent protocol

Every subagent MUST follow this exact protocol:

### 1. Read upstream docs + existing content

Read ONLY the files listed for this phase. Do not load the entire BA tree.
This keeps the context window focused.

**Always read the existing authoritative file** (even if it might be a
placeholder) — this is how the subagent knows whether it's creating from
scratch or enriching existing content.

### 2. Enrich (not just generate)

You are an expert business analyst. **Make professional decisions** — do not
use AskUserQuestion. The default mode is **enrichment**:

**If the file is a placeholder or missing** → create from scratch.

**If the file already has content** → operate in delta mode:
1. **Inventory** existing items (actors, UCs, rules, entities, screens…)
2. **Compare** with current upstream: has the menu changed? new sections?
   new actors? updated contexts?
3. **Keep** every existing item (preserve codes, fields, structure)
4. **Add** new items for uncovered scope (next available code sequence)
5. **Update** existing items only if their references are stale (e.g., actor
   code no longer exists, section was renamed)
6. **Never delete** an existing item unless its parent scope no longer exists
   in the menu tree — and even then, defer to `/ba-reconcile-menu` (Step 0.5)
   to perform the deletion cleanly. The subagent itself never deletes.

When facing ambiguity:
- Choose the most common business pattern
- Document your assumptions in the content (e.g., in a note or comment)
- Prefer completeness over perfection — the audit will catch issues

### 3. Write the authoritative file(s)

Use the Write tool to create/overwrite the doc at the correct level. The Write
tool overwrites the file — so **include ALL items** (existing + new) in the
output. An item you omit is removed.

Follow the exact format from the create skill's documentation:
- Anchor comment (`<!-- ba:... -->`)
- `###` headings for each item (greppable codes)
- All required fields per item

### 4. Self-audit

Apply the dimension's audit rules. Count: `err`, `warn`, `ok`.
Write the verdict file to `_audit/<dim>.md` using the standard skeleton:

```markdown
<!-- ba:audit dimension=<DIM> scope=<SCOPE> -->
# Audit <name> — <scope>
_<DATE> · Verdict : <EMOJI> N warn · M err · K ok_

## ✅ Conforme
- **RULE-NNN** — what is correct

## ⚠️ Avertissements
- **RULE-NNN** — what is slightly off
  - → fix suggestion

## ❌ Bloquants
- **RULE-NNN** — what is wrong
  - → fix suggestion
```

### 5. Fix cycle (if err > 0)

If the self-audit found errors:
1. Read the verdict → identify each ❌ finding
2. Edit the authoritative file to fix each error
3. Re-run the audit (write a fresh verdict)
4. Max **2 fix cycles** — if still err > 0 after 2 retries, report failure

### 6. Report back

End with a structured summary:
```
Phase: <N> <name>
Module: <APP/MODULE>
Mode: FRESH (created from scratch) | ENRICH (N existing kept, M new added)
Audit: <err> err · <warn> warn · <ok> ok
Status: PASS | FAIL (after N fix cycles)
```

## Decision table

| Situation | Action |
|-----------|--------|
| ba-order.json exists | Follow wave ordering |
| ba-order.json missing | Process all modules alphabetically (single wave) |
| Phase has existing content | **ENRICH** — re-analyze, keep existing items, add missing ones |
| `--skip-existing` AND phase has 0-err verdict | Skip (don't re-create) |
| Phase file is a placeholder | **FRESH** — create from scratch |
| Subagent reports FAIL | Stop the module, report to user, continue with next module |
| All modules in a wave PASS | Proceed to next wave |
| Cross-app actor dependency | Phase 2 covers ALL apps first, then phases 3-7 per module |
| `--from-phase N` specified | Skip phases before N (assume prior phases are done) |
| `--module APP/MODULE` specified | Process only that module (skip wave logic) |
| Existing item references a deleted section/actor | Defer to `/ba-reconcile-menu` (Step 0.5) — it owns the cleanup |
| Menu modified after content created (rename/delete) | **Step 0.5 reconciles first** — never skip, even with `--skip-existing` |
| New section found with no UCs | Add UCs for that section in the enrichment pass |

## Guard rails

- **Never write BA content in the orchestrator** — always delegate to subagents
- **Never skip the audit step** — every create must be followed by an audit
- **Max 2 fix cycles** — prevents infinite loops on fundamentally wrong content
- **Sequential phases per module** — phase N+1 depends on phase N's output
- **Parallel modules within a wave** — modules in the same wave are independent
  (use `run_in_background: true` on subagents when launching multiple modules)
- **Read verdicts after each subagent** — don't trust the subagent's chat summary
  alone; verify by reading the `_audit/*.md` file
