---
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)
   - the OTHER apps' .smartstack/ba/*/acteur.md (reuse candidates — actors are
     project-scoped: never re-create an existing actor under a new code; reuse
     its code and add a Périmètre line instead)
   - .smartstack/sources/index.json + the source.md whose scopes/tags cover {APP}
     (client sources, if the registry exists — cite SRC-NNN §n on supported items
     and PRESERVE every existing **Sources** line; never raw/, never the whole corpus)

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
     (internal | external | system), description, scope (which
     modules/sections), origin
   - Follow the format from /ba-create-actors: anchor comment + ### headings
   - Write ONLY acteur.md files (this app's, or another app's ONLY to add a
     Périmètre line to a reused actor — same code, never a redefinition)
   - Write the COMPLETE file to .smartstack/ba/{APP}/acteur.md
     (Write overwrites — include ALL actors: existing + new)

3. AUDIT your work — through the DETERMINISTIC engine, never by eye:
   npx --prefer-offline tsx skills/business-analyse/audit-run/cli/audit-ba/index.ts \
     --spec '{"baRoot":".smartstack/ba","dimensions":["actors"]}'
   The engine evaluates ACT-001/002/006 (authoritative texts in
   /ba-audit-actors) and writes .smartstack/ba/_audit/actors.md itself.
   Exit 3 = parsing suspect: the acteur.md you wrote has a form the parser
   rejects — fix the FORM, never hand-write a verdict around it.
   Author against the rules while writing: ≥1 actor project-wide; the SAME
   actor reused across apps keeps ONE code (a duplicate = same label under
   different codes, or one code with divergent definitions); every actor
   typed internal | external | system.

4. FIX if needed:
   - If the engine found errors (err > 0), fix the acteur.md and re-run it
   - 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`, `.smartstack/sources/index.json` + in-scope `source.md`
**Subagent writes**: `use-case.md` at each section (authoritative), audit verdict at module
**Audit rules**: UC-001 through UC-022 (UC-023 — cross-app similarity — is
app/project-scope only and never runs in the loop)

**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)
   - .smartstack/sources/index.json + the source.md whose scopes/tags cover {APP}/{MODULE}
     (client sources, if the registry exists — cite SRC-NNN §n on supported items
     and PRESERVE every existing **Sources** line; never raw/, never the whole corpus)

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, acceptance criteria
     (AC-NN — the test contract, required for user-goal UCs)
   - Write ONLY under .smartstack/ba/{APP}/{MODULE}/ — never another app or
     module; a similar UC elsewhere is mentioned in the report, never edited
   - Write the COMPLETE file (existing + new UCs) to each section's use-case.md

3. AUDIT — through the DETERMINISTIC engine, never by re-reading your output:
   npx --prefer-offline tsx skills/business-analyse/audit-run/cli/audit-ba/index.ts \
     --spec '{"baRoot":".smartstack/ba","scope":{"app":"{APP}","module":"{MODULE}"},"dimensions":["use-cases"]}'
   It evaluates UC-001..022 (authoritative texts in /ba-audit-use-cases) and
   writes the verdict itself. Exit 3 = parsing suspect: the use-case.md you
   wrote has a form the parser rejects — fix the FORM. Arbitrate your
   report.judgmentNeeded[] entries (UC-007/011/015) from their excerpts and
   re-run with "judgments". AUTHOR against the rules while writing:
   ≥1 UC per section · non-empty main flow (≥3 imperative steps) ·
   ≥1 precondition/postcondition · ≥1 alternative OR exception flow ·
   no vague/placeholder steps · actor refs resolve · no intra-module
   redundancy · AC contract (sequential AC-NN, one testable assertion each,
   entity refs resolve) · scheduled UCs declare their idempotence AC ·
   one AC per EXC-N flow.

4. FIX if err > 0, then re-run the engine. 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`, `.smartstack/sources/index.json` + in-scope `source.md`
**Subagent writes**: `règles-métier.md` at module level
**Audit rules**: BR-001 through BR-011 (BR-005 retired; BR-012 — cross-app
similarity — is app/project-scope only and never runs in the loop)

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

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

1. READ:
   - .smartstack/ba/{APP}/acteur.md (actors — for access rules)
   - .smartstack/ba/{APP}/{MODULE}/index.md (module context)
   - .smartstack/ba/{APP}/{MODULE}/*/index.md (all section contexts)
   - ALL use-case.md files of the module's sections (rule sources)
   - .smartstack/ba/{APP}/{MODULE}/entité.md if present (fields → invariants)
   - .smartstack/ba/{APP}/{MODULE}/règles-métier.md (existing rules, if any)
   - .smartstack/sources/index.json + the source.md whose scopes/tags cover {APP}/{MODULE}
     (client sources, if the registry exists — cite SRC-NNN §n on supported items
     and PRESERVE every existing **Sources** line; never raw/, never the whole corpus)

2. ENRICH business rules for module {APP}/{MODULE}:
   - If règles-métier.md is a placeholder or missing → create from scratch
   - If it already has rules → PRESERVE every existing rule (code, all
     fields), ADD missing ones with the next available BR-NNN, never renumber
   - Each rule: BR-NNN code, Type, Sévérité, Portée, Condition (QUAND…ALORS),
     Expression, Code d'erreur ({module}.{entity}.{cas}), ≥1 valid + ≥1
     invalid example, linked UCs — format from /ba-create-business-rules
   - Write ONLY under .smartstack/ba/{APP}/{MODULE}/ — never another app or
     module; a similar rule elsewhere is mentioned in the report, never edited
   - Write the COMPLETE file to .smartstack/ba/{APP}/{MODULE}/règles-métier.md

3. AUDIT — through the DETERMINISTIC engine, never by re-reading your output:
   npx --prefer-offline tsx skills/business-analyse/audit-run/cli/audit-ba/index.ts \
     --spec '{"baRoot":".smartstack/ba","scope":{"app":"{APP}","module":"{MODULE}"},"dimensions":["rules"]}'
   It evaluates BR-001..011 (authoritative texts in /ba-audit-rules) and
   writes the verdict itself. Exit 3 = parsing suspect: fix the FORM of the
   règles-métier.md you wrote. AUTHOR against the rules while writing:
   ≥1 rule · every rule with ≥1 valid + ≥1 invalid complete example (the
   invalid side cites the expected error code) · no conflicts/redundancy ·
   every rule linked to ≥1 UC and every UC covered by ≥1 rule · edge cases
   per ruleType · numbering rules fully specified (socle tokens, scope,
   reset, gapless) · error codes {module}.{entity}.{cas}.

4. FIX if err > 0, then re-run the engine. Max 2 fix cycles.

Report: N existing rules kept, N new rules added, audit result.
```

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

**Subagent reads**: `acteur.md`, `use-case.md` files, `règles-métier.md`, `.smartstack/sources/index.json` + in-scope `source.md` (cite `SRC-NNN §n`, preserve existing `**Sources**` lines)
**Subagent writes**: `rbac.md` at module level
**Audit rules**: RBAC-001 through RBAC-010, as defined in /ba-audit-rbac
(RBAC-008 — derived-lookup freshness — only becomes meaningful after phase 6;
before it, the audit marks it deferred)

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

**Subagent reads**: `use-case.md` files, `règles-métier.md`, `rbac.md`, `index.md` — client sources are NOT an entity source (the closed set holds; a concept a document reveals goes through a UC/BR upstream)
**Subagent writes**: `entité.md` at module level
**Audit rules**: DM-001 through DM-020, as defined in /ba-audit-data-model

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)
- Run the MANDATORY post-step after the `entité.md` Write + audit:
  `derive-lookup-grants` in `"mode":"derive"` (create-rbac companion CLI) so
  the module's rbac.md machine block follows the FKs — RBAC-008 re-checks it

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

**Subagent reads**: `entité.md`, `rbac.md`, `use-case.md` files, section `index.md`, `.smartstack/sources/index.json` + in-scope `source.md` (cite `SRC-NNN §n`, preserve existing `**Sources**` lines)
**Subagent writes**: `screen.md` at each section (authoritative)
**Audit rules**: SCR-001 through SCR-025, as defined in /ba-audit-screens

### Step 3 — Cross-dimension audit

After all modules complete phases 2-7, run the deterministic engine ONCE for
the whole project (`dimensions:["cross-dimension","cross-ref-code"]` — one
invocation, NOT one subagent per module) — it verifies coherence **across**
the six documents (data model fields ↔ business rules ↔ use cases ↔ screens ↔
RBAC) and writes every module's verdict. A subagent is needed only to
arbitrate the remaining `judgmentNeeded[]` items (XD-008).

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

**Write boundary.** Write ONLY under the module you were launched for —
`.smartstack/ba/{APP}/{MODULE}/` (Phase 2: only `acteur.md` files + the
project verdict `.smartstack/ba/_audit/actors.md`). Anything the phase would
need to change OUTSIDE that subtree (a similar UC/rule/screen in another
application, a stale reference elsewhere) is reported in the summary as a
warning or blocker — never written.

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 — through the DETERMINISTIC engine, never by eye

**Do NOT apply the audit rules by re-reading the docs you just wrote** — that
per-agent rule replay is exactly the 394M-token incident shape. Run the
shared engine scoped to your module + dimension; it evaluates the mechanical
rules, writes the verdict file at the standard location AND fails closed on
parsing drift:

```bash
npx --prefer-offline tsx skills/business-analyse/audit-run/cli/audit-ba/index.ts \
  --spec '{"baRoot":".smartstack/ba","scope":{"app":"<APP>","module":"<MODULE>"},"dimensions":["<dim>"]}'
```

Read the envelope: `report.counts` gives err/warn/ok; exit 3 (« parsing
suspect ») means the doc you wrote has a FORM the parsers reject —
`report.parseControl.perDoc` names the doc and counter; fix the FORM (it is
your own output), never hand-write a verdict around it. Arbitrate your
dimension's `report.judgmentNeeded[]` entries from their excerpts and re-run
with `"judgments":"<path>"` — the CLI finalizes the verdict itself.

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

If the engine found errors:
1. Read `report.findings[]` → identify each `err`
2. Edit the authoritative file to fix each error
3. Re-run the engine (it rewrites 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 let a subagent write outside its module subtree** — every prompt
  carries the `{APP}/{MODULE}` write boundary; cross-app similarities are
  reported, never fixed in place
- **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
