---
name: step-01-apply
description: Apply review corrections from ba-review.json, create new version, regenerate all artifacts
model: opus
---

> **Context files:** `references/review-data-mapping.md`

# Step 01: Apply Review Corrections

Apply corrections exported from the interactive HTML review (`ba-review.json`) to create a new version of the business analysis with all downstream artifacts regenerated.

## Prerequisites

- `workflow_type = "review"` (set by step-00)
- `review_json_path` points to a valid `ba-review.json` file
- `application_name` and `docs_dir` are set

## Flow

1. Read and validate ba-review.json
2. Read existing master index.json and version directory
3. Create new version
4. Apply cadrage corrections (reverse mapping)
5. Apply module corrections
6. Apply consolidation corrections
7. Preserve review comments
8. Regenerate HTML
9. Update manifest
10. Display completion summary

---

## Step 1: Read and Validate ba-review.json

```
1. Read file at {review_json_path}
2. Parse JSON
3. Validate required structure:
   - _reviewMeta: { sourceVersion, sourceApplicationId, exportedAt }
   - metadata: { applicationId, version }
   - cadrage: { ... }
   - modules: [ ... ]
   - moduleSpecifications: { ... }
4. If validation fails → display error with missing fields, STOP
5. Display: "Review file valid: {_reviewMeta.changeSummary}"
```

**Store:**
```yaml
review_data: parsed ba-review.json object
source_version: _reviewMeta.sourceVersion
change_summary: _reviewMeta.changeSummary
```

## Step 2: Read Existing Master Index.json

```
1. Locate master index.json from docs_dir (ba-006: docs/{projectSlug}/v{X.Y}/index.json, legacy: docs/{app}/business-analyse/v{X.Y}/index.json)
2. Read and parse
3. Verify metadata.applicationId matches _reviewMeta.sourceApplicationId
4. Store as existing_master_index
5. Read all thematic files referenced in index.json (cadrage.json, entities.json, rules.json, etc.)
```

## Step 3: Create New Version

Determine version bump based on changes:

```
IF change_summary.modulesAdded.length > 0 OR change_summary.modulesRemoved.length > 0:
  version_type = "major"  (v1.0 → v2.0)
ELSE:
  version_type = "minor"  (v1.0 → v1.1)

Call ba-writer.createVersion(existing_master.id, "Review corrections applied from v{source_version}")
```

**Store:**
```yaml
new_version: string (e.g., "1.1" or "2.0")
new_docs_dir: path to new version directory
new_version_dir: path to new version directory (contains index.json + thematic files)
```

## Step 4: Apply Cadrage Corrections

> **Reference:** `references/review-data-mapping.md` for exact field mapping

Read the new version's cadrage.json and apply reverse mapping from review data:

```
1. Scope mapping (review → cadrage.json):
   - cadrage.scope.inscope[] → cadrage.globalScope.inScope[]
   - cadrage.scope.outofscope[] → cadrage.globalScope.outOfScope[]
   (Extract name from {name, description} objects)

2. Stakeholders mapping:
   - For each review stakeholder:
     - role → role (preserved)
     - function → function
     - tasks → tasks
     - access → involvement (reverse: admin→decision-maker, manager→consulted, contributor→end-user, viewer→informed)
     - frequency → frequency (reverse: daily→Quotidien, weekly→Hebdomadaire, monthly→Mensuel, occasional→Occasionnel)
     - frustrations → painPoints (split by newline)

3. Problem/Vision mapping:
   - cadrage.problem.description → cadrage.problem
   - cadrage.problem.trigger → cadrage.trigger
   - cadrage.vision.changes → cadrage.toBe
   - cadrage.current.tools → cadrage.asIs

4. Risks mapping:
   - For each review risk → cadrage.risks[] (direct mapping, generate RISK-NNN IDs if missing)

5. Acceptance criteria:
   - cadrage.success.definition → cadrage.acceptanceCriteria[] (split by newline, generate AC-NNN IDs)

Update cadrage.json with corrected data and update its hash in index.json
```

## Step 5: Apply Module Corrections

```
FOR EACH moduleCode in review_data.moduleSpecifications:
  1. Check if module exists in current index.json.modules[]
     - If NEW module (in change_summary.modulesAdded):
       a. Add to index.json.modules[] with metadata from review
       b. Create module directory and entities.json, rules.json, usecases.json, etc. via ba-writer
     - If REMOVED module (in change_summary.modulesRemoved):
       a. Mark module status as "removed" in index.json (do NOT delete files)
     - If EXISTING module:
       a. Update module's thematic files

  2. Reverse-map module specification data:
     - review.useCases[] → usecases.json.useCases[]
       (name→name, actor→primaryActor, steps→mainScenario (split by \n), alternative→alternativeScenarios)
     - review.businessRules[] → rules.json.businessRules[]
       (name→name, category→category, statement→statement, example→examples[])
     - review.entities[] → entities.json.entities[]
       (name→name, description→description, attributes→attributes, relationships→relationships)
     - review.permissions[] → permissions.json.permissionMatrix
       (reverse "Role|Action" format → {permissions[], roleAssignments[]})

  3. Update each module's thematic files via ba-writer.enrichSection()
  4. Update hashes in index.json for modified files
```

## Step 6: Apply Consolidation Corrections

```
IF review_data.consolidation exists:
  1. Reverse-map interactions:
     - consolidation.interactions[] → consolidation.json.crossModuleInteractions[]
       (from→fromModule, to→toModule, description→description)

  2. Reverse-map E2E flows:
     - consolidation.e2eFlows[] → consolidation.json.e2eFlows[]
       (name→name, steps→steps, actors preserved)

  3. Update consolidation.json and update hash in index.json
```

## Step 7: Preserve Review Comments

Store all review feedback in a new review.json file:

```
review_section = {
  appliedAt: new Date().toISOString(),
  sourceVersion: source_version,
  comments: review_data.comments || [],          // inline structured comments
  specComments: review_data.specComments || {},   // textarea comments per spec item
  wireframeComments: review_data.wireframeComments || {},  // wireframe feedback
  changeSummary: change_summary
}

Create review.json with review_section and update hash in index.json
```

> `review.json` is an AUDIT artifact — it preserves the review trail for traceability. No downstream skill consumes it.

## Step 8: Determine Correction Routing

Analyze the corrections applied to determine which phase needs re-execution:

```
analysis_changes = false
ui_changes = false

FOR EACH module in corrected_modules:
  IF entities, rules, usecases, or permissions were modified:
    analysis_changes = true
  IF screens, wireframes, or navigation were modified:
    ui_changes = true

IF analysis_changes AND ui_changes:
  route = "both"
ELSE IF analysis_changes:
  route = "analysis"
ELSE IF ui_changes:
  route = "ui"
ELSE:
  route = "html-only"
```

## Step 9: Regenerate Interactive HTML

Delegate HTML generation to `/business-analyse-html` skill:

```
1. Load skill: /business-analyse-html with feature_id
2. The skill handles: collect → build → render → verify
3. Output: {new_version_dir}/ba-interactive.html
```

## Step 10: Update Project Index

```
1. Read {docs_dir}/index.json (project master index)
2. Update version, lastModified, status
3. Write {docs_dir}/index.json
4. Legacy: if docs/index.json global manifest exists, also update it
```

## Step 10b: Update Status

```javascript
ba-writer.updateStatus({feature_id}, "reviewed")
```

## Step 11: Display Completion Summary

```
=====================================================================
  REVIEW CORRECTIONS APPLIED SUCCESSFULLY
=====================================================================

| Field                | Value                                |
|----------------------|--------------------------------------|
| Application          | {application_name}                   |
| Previous version     | v{source_version}                    |
| New version          | v{new_version}                       |
| Version type         | {major/minor}                        |

Changes applied:
| Change               | Count                                |
|----------------------|--------------------------------------|
| Cadrage modified     | {yes/no}                             |
| Modules added        | {count} ({list})                     |
| Modules removed      | {count} ({list})                     |
| Modules modified     | {count} ({list})                     |
| Comments preserved   | {count}                              |

Artifacts regenerated:
| Artifact             | Path                                 |
|----------------------|--------------------------------------|
| Master index.json    | {new_version_dir}/index.json         |
| ba-interactive.html  | {new_version_dir}/ba-interactive.html|
| Thematic files       | {new_version_dir}/*.json             |
| Manifest             | docs/index.json                      |

NEXT STEPS (based on correction routing: {route}):
```

Display next steps based on `route`:

```
IF route == "analysis":
  "1. Run /business-analyse step-03 for modules: {corrected_module_list}"
  "2. Then run /business-analyse-design to update UI specs"
  "3. Then run /business-analyse-html to regenerate documentation"

IF route == "ui":
  "1. Run /business-analyse-design for modules: {corrected_module_list}"
  "2. Then run /business-analyse-html to regenerate documentation"

IF route == "both":
  "1. Run /business-analyse step-03 for modules: {analysis_corrected_modules}"
  "2. Then run /business-analyse-design for modules: {ui_corrected_modules}"
  "3. Then run /business-analyse-html to regenerate documentation"

IF route == "html-only":
  "HTML has been regenerated. Review the updated document."
  "If satisfied, run /business-analyse-handoff to generate PRD files."

IF no corrections (client approves):
  "No corrections needed. Run /business-analyse-handoff to generate PRD files."
  "Then run /business-analyse-develop to start development."
```

```
=====================================================================
```

## Error Handling

| Error | Action |
|-------|--------|
| ba-review.json malformed | Display structure errors, STOP |
| Source version mismatch | Warn but continue (corrections may still apply) |
| Module not found for update | Skip module, warn user |
| HTML generation fails | Warn but continue (can be re-run manually) |
| Manifest update fails | Warn but continue |
