---
name: business-analyse-quick
description: |
  Quick business analysis (Mini-BA) that produces a Mini-PRD for /apex delegate mode.
  Use this skill when:
  - User has a vague idea ("I want an HR app with employees and absences")
  - User doesn't know the exact entities, fields, or structure needed
  - User needs structured specifications before running /apex
  - Scope is small enough (≤ 6 entities) — for larger scope, use /business-analyse
  Produces .ralph/prd-{module}.json + 5 companion spec files.
model: opus
argument-hint: "<vague idea in natural language>"
---

<objective>
Transform a vague user prompt into a structured Mini-PRD (.ralph/prd-{module}.json) with 5 companion specification files, ready for `/apex -d` delegate mode. /business-analyse-quick is a rapid interactive design assistant — it guides the user through 3 phases (Cadrage → Specification → Generation) with 12-15 targeted questions.

**Key principles:**
- Interactive: 12-15 questions via AskUserQuestion (max 2 questions per call)
- Context-aware: scans codebase for existing apps, modules, entities
- Structured output: PRD v4.0 + entities/rules/usecases/permissions/screens JSON files
- Domain heuristics ACCELERATE inference — propose, then validate with user
- APEX compatibility: output is directly consumable by `/apex -d`
</objective>

<quick_start>

```bash
/business-analyse-quick une app RH avec employés et absences
/business-analyse-quick I want to manage customer orders and invoices
/business-analyse-quick gestion de projets avec tâches et jalons
/business-analyse-quick stock management with products and warehouses
```

</quick_start>

<anti_patterns>
- DO NOT skip user interaction — every major decision must be validated
- DO NOT call MCP tools — validation is /apex's job
- DO NOT generate actual source code — only specification JSON files
- DO NOT produce more than 6 entities without redirecting to /business-analyse
- DO NOT assume architecture without confirming with user
- DO NOT mix languages in JSON values — all content in `{conversation_language}` chosen in Step 2
- DO NOT use accented characters in entity names — PascalCase, valid C# identifiers only
- DO NOT generate ASCII-only French/German/Italian labels — "Employés" not "Employes", "Département" not "Departement", "Übersicht" not "Ubersicht", "attività" not "attivita". UTF-8 accents are MANDATORY in all i18n label values.
</anti_patterns>

<algorithm>

# ═══════════════════════════════════════════════════════
# PHASE 1: CADRAGE (Framing) — 3-4 questions
# ═══════════════════════════════════════════════════════

## Step 0: Banner + Load References

Display version banner:
```
═══════════════════════════════════════════════════════════
  SmartStack /business-analyse-quick — Mini-BA → Mini-PRD
  v{{SMARTSTACK_VERSION}}
═══════════════════════════════════════════════════════════
```

Read `references/domain-heuristics.md` — domain pattern table with entities, properties, sections, rules, and workflows for 15 common business domains.

## Step 1: Deep Codebase Scan (MANDATORY — silent)

> **This scan is BLOCKING.** You MUST know what already exists before proposing anything.

**1a. Application inventory:**
```
Glob("**/NavigationApplicationSeedData.cs")   → existing applications
Glob("*.sln")                                  → confirm SmartStack project
```
Read each NavigationApplicationSeedData file to extract: app code, app label, description.

**1b. Module inventory (per detected app):**
```
Glob("**/NavigationModuleSeedData.cs")         → existing modules per app
Glob("**/NavigationSectionSeedData.cs")        → existing sections per module
```
Read each file to extract: module code, module label, section codes.

**1c. Entity inventory:**
```
Glob("**/Domain/Entities/**/*.cs")             → existing entity names
```
Extract entity names from filenames (strip .cs). Group by app/module folder.

**1d. Existing BA documentation:**
```
Glob("docs/**/index.json")                     → previous BA work
Glob(".ralph/prd-*.json")                      → existing PRDs
```

Store all results as `{detected_apps}`, `{detected_modules}`, `{detected_entities}`, `{detected_prd}`.

## Step 2: First Contact (AskUserQuestion #1)

**AskUserQuestion** with 3 questions (max allowed per call):

- **Q1** (header: "Language"): "In which language should I communicate and write the specifications?"
  - Options: "Français" / "English" / "Italiano" / "Deutsch"
  - This sets `{conversation_language}` — ALL subsequent questions, displays, and JSON content values will use this language

- **Q2** (header: "Scope"): "Is this a new application or an update to an existing one?"
  - Options: "New application" / "Update to {app1}" / "Update to {app2}" (one option per detected app, max 3)
  - If no apps detected: only "New application" option

- **Q3** (header: "Description"): "Describe what you want to build in 1-2 sentences"
  - Options are illustrative examples from user's prompt domain — user will likely use "Other" for free text

**Language rule:** From this point on, ALL text output (questions, tables, summaries) and ALL JSON string values (descriptions, rule statements, use case steps, screen labels) MUST be in `{conversation_language}`. The i18n `labels` fields always contain all 4 languages regardless.

**If UPDATE selected** → AskUserQuestion #2 (1 question):
- Display detected modules for the selected app
- **Q4** (header: "Module"): "Which module?"
  - Options: "New module for {app}" / "{existing_module_1}" / "{existing_module_2}" (from Step 1b)

## Step 3: Domain Research + Deep Inference (ULTRATHINK)

> **ULTRATHINK is MANDATORY here. Do NOT skip or rush this step.**
> This is where the quality of the entire analysis is determined.

### 3a. Web Research (MANDATORY if domain is not trivial CRUD)

**Perform 1-3 WebSearch calls** to understand the domain:
- Search for best practices in the user's domain (e.g., "HR management system features", "project management app architecture")
- Search for industry standards or regulations if applicable (e.g., "leave management legal requirements {country}")
- Search for common workflows in the domain

**Skip WebSearch ONLY if:**
- The domain is a textbook CRUD with no business logic (simple reference table)
- The heuristics table already covers the domain exhaustively

### 3b. Collision Detection (MANDATORY)

Cross-reference inferred entities with `{detected_entities}` from Step 1c:
```
For each inferred entity:
  IF entity name already exists in codebase:
    → Flag as COLLISION — this entity already exists
    → Decision: reuse existing entity (FK to it) OR rename new entity
```

Cross-reference inferred module with `{detected_modules}` from Step 1b:
```
IF module code already exists for the selected app:
  → Flag as COLLISION — redirect user to update flow
```

### 3c. Full Architecture Inference (ULTRATHINK)

From user description + domain heuristics + web research + existing codebase:

**CRITICAL — Module Splitting Rule:**
> One module = one functional domain. If the user mentions multiple business concepts
> that have distinct lifecycles, actors, or workflows, they MUST be separate modules.
>
> Examples:
> - "employees and absences" → 2 modules: `employees` + `absence-management`
> - "orders and invoicing" → 2 modules: `orders` + `invoicing`
> - "projects with tasks and milestones" → 1 module: `projects` (tasks/milestones are sub-entities of project)
>
> **Test:** Can concept A exist without concept B? If yes → separate modules.
> "An absence REQUIRES an employee but an employee does NOT require absences" → 2 modules.

1. **Application:** PascalCase name, determine if new or existing
2. **Modules (PLURAL):** For EACH distinct functional domain:
   - `code` (kebab-case), PascalCase name, description
   - Which entities belong to this module
   - Inter-module dependencies (e.g., absence-management depends on employees)
3. **Sections per module:** for EACH section infer:
   - `code` (kebab-case)
   - `sectionType`: primary | functional | embedded
   - `permissionMode`: crud | custom | read-only | inherit
   - `labels` in 4 languages (fr, en, it, de)
   - `icon` suggestion
   - Which entities are displayed in this section
   - **NEVER create sections for detail/create/edit** — these are implicit APEX pages (routes /:id, /create, /:id/edit under the primary section). Only create primary (list/CRUD), functional (approve, calendar), and embedded (dashboard, kpi) sections.
4. **Resources** per section: for EACH section infer:
   - `code` (kebab-case, e.g., "employees-grid")
   - `type`: SmartTable | SmartForm | DetailCard | KpiPanel | Timeline | Chart | Calendar
   - Which entity it displays
   - Key columns (for SmartTable) or fields (for SmartForm)
5. **Entities:** name (PascalCase, valid C#), key attributes, types, nullable, FK
6. **FK relationships:** between new entities AND to existing entities (User, Organisation, detected entities). Cross-module FK are critical (e.g., Absence.EmployeeId → Employee in another module)
7. **Business rules:** from heuristics `typicalRules` + web research + domain knowledge
8. **Complexity deduction per module:**
    - `simple-crud` if ≤ 2 entities with no workflow/status transitions
    - `crud-rules` if validations, computed fields, or status fields present
    - `crud-workflow` if approval flows, notifications, or email mentioned
    - `complex` if > 4 entities with specific business logic
9. **Workflow detection:** from heuristics `workflow` field + user description
10. **Role derivation** (MANDATORY — at least 2 roles):
   a. Start with Admin role: `"{App} Admin"` — level: admin, wildcard access
   b. Check domain heuristics for `typicalRoles` — if available, adopt them as starting point
   c. If workflow detected (approval, validation) → add a manager-level role (e.g., `"{App} Manager"`)
   d. If multiple distinct actor types identified (e.g., employee vs HR staff) → derive per-actor roles
   e. If no domain signals → default to 3-role set: Admin + Contributor + Viewer
   f. Apply the 4-level hierarchy as ceiling: admin > manager > contributor > viewer
      (only include levels that match the domain — not every domain needs all 4)
   g. Each role: name (string), level (admin|manager|contributor|viewer), description (string)
11. **Person Extension Pattern:** if an entity has FirstName + LastName + Email attributes
12. **i18n labels** in 4 languages for all hierarchy levels

### 3d. Architecture Challenge (ULTRATHINK — self-review)

Before presenting to the user, CHALLENGE your own architecture:

- [ ] **Module split correct?** Separate lifecycles = separate modules. Never cram unrelated domains into 1 module.
- [ ] **Cross-module dependencies declared?** If module B references entities from module A, this FK must be explicit.
- [ ] **Missing sections?** Does a module need a dashboard? An approval queue? Import/export? Calendar?
- [ ] **No detail/create/edit sections?** These are implicit APEX pages (routes under primary section), NOT sections. Only create primary (list), functional (approve, calendar), and embedded (dashboard) sections.
- [ ] **Entity completeness?** Are there implicit entities? (e.g., if "absences" → do we need AbsenceType? AbsenceBalance?)
- [ ] **FK to existing entities?** Does an entity need User (CreatedBy, AssignedTo)? Organisation? Another app's entity?
- [ ] **Collisions resolved?** Every collision from 3b must have a decision (reuse vs rename)
- [ ] **Workflow states?** If workflow detected, are states defined as an enum entity?
- [ ] **Resource appropriateness?** Is SmartTable the right choice or should it be a Kanban board? Timeline? Calendar?
- [ ] **Roles derived?** At least Admin + 1 operational role. Roles match detected actors/workflow. Checked domain heuristics `typicalRoles`.
- [ ] **Permission paths predictable?** Each section with `permissionMode: crud` will generate 4+ permission paths (`{App}.{Module}.Read/Create/Update/Delete`). Each section with `permissionMode: custom` needs explicit paths.

**Scope Guard per module:** If any single module has > 6 entities:
```
Module {module} has too many entities (> 6). Split it further or use /business-analyse.
```

**Total Scope Guard:** If total entities across all modules > 10:
```
This scope is too large for /business-analyse-quick (> 10 entities total).
Use /business-analyse for a full analysis with stakeholder interviews and design phase.
```
→ STOP

## Step 4: Propose Full Architecture (AskUserQuestion #3)

Display the COMPLETE architecture as a **tree** (NOT a table — tables are unreadable for hierarchical data).

```markdown
### Proposed Architecture

**Application:** {app_name} ({new/existing})
**Complexity:** {complexity_per_module}

#### Navigation Tree

{AppCode} — {label_fr}
├── {module-1-code} — {label_fr} ({complexity})
│   ├── [P] {section-code} — {label_fr} ← {Entity1}, {Entity2}
│   │   ├── {entities}-grid (SmartTable)
│   │   └── {entity}-form (SmartForm)
│   │   └── (implicit: detail /:id, create /create, edit /:id/edit)
│   ├── [F] approve — {label_fr} ← {Entity1}
│   │   └── approve-queue (SmartTable)
│   └── [E] dashboard — {label_fr}
│       └── kpi-panel (KpiPanel)
│
├── {module-2-code} — {label_fr} ({complexity})
│   ├── [P] {section-code} — {label_fr} ← {Entity3}
│   │   ├── {entities}-grid (SmartTable)
│   │   └── {entity}-form (SmartForm)
│   │   └── (implicit: detail /:id, create /create, edit /:id/edit)
│   └── [F] calendar — {label_fr} ← {Entity3}
│       └── {entity}-calendar (Calendar)

Legend: [P]=primary (crud)  [F]=functional  [E]=embedded
Note: detail/create/edit pages are IMPLICIT routes under [P] sections — NOT separate sections

#### Cross-Module Dependencies
- {module-2} → {module-1}: {Entity3}.{FK} → {Entity1}

#### Entities

| Entity | Module | Key Attributes | FK → | Collision? |
|--------|--------|---------------|------|------------|
| {Entity1} | {module-1} | {attr1}:{type}, {attr2}:{type} | → {Target} | None |
| {Entity3} | {module-2} | {attr1}:{type}, {attr2}:{type} | → {Entity1} (cross-module) | None |

#### Workflow
- **{Entity}** ({module}): {state1} → {state2} → {state3} / {state4}

#### Roles & Permissions Preview

| Role | Level | Typical Access |
|------|-------|----------------|
| {App} Admin | admin | Full module access (wildcard `{App}.*`) |
| {Role2} | manager | Read + Create + Update + Approve |
| {Role3} | contributor | Read + Create |
| {Role4} | viewer | Read only |

> Roles derived from: {source — domain heuristics / workflow actors / default hierarchy}.
> Permission paths will follow: `{ApplicationPascalCase}.{ModulePascalCase}.{Action}`

#### Findings from research
- {key_insight_1_from_web_research}
- {key_insight_2_from_web_research}
```

Then **AskUserQuestion** with 1 question:
- **Q5** (header: "Architecture"): "Is this architecture correct?"
  - Options: "Yes, proceed to specification" / "No, let me correct" / "I want to add context"

If "No" or "Add context" → collect correction, re-run Step 3c-3d inference, re-display. Loop max 2 times.

# ═══════════════════════════════════════════════════════
# PHASE 2: SPECIFICATION (8-10 questions)
# ═══════════════════════════════════════════════════════

## Step 5: Entity Specification (AskUserQuestion #4)

Display proposed entities as a detailed table:

```markdown
### Proposed Entities

| Entity | Key Attributes | Relationships | Code Pattern |
|--------|---------------|---------------|--------------|
| Employee | FirstName:string, LastName:string, Email:string, HireDate:DateTime | → Department (FK) | emp-{tenant}-00001 |
| Department | Name:string, Code:string | → Department? (self-ref) | dep-{tenant}-00001 |
```

Then **AskUserQuestion**:
- **Q5** (header: "Entities"): "Here are the entities I propose. What would you like to change?"
  - Options: "Accept all as proposed" / "Modify entities" / "Add more entities"

**If "Modify" or "Add"** → AskUserQuestion #5:
- **Q6** (header: "Details"): "Describe the changes you want (add/remove entities, change properties, add relationships)"
  - User provides corrections via free text (Other)
  - Re-infer with corrections applied, re-display table for confirmation

## Step 6: Dependencies + Person Extension Pattern (silent scan + 0-1 question)

Scan existing codebase for entity conflicts:
```
Glob("**/Domain/Entities/**/*.cs")   → existing entity names
```

**Check for:**
- Name conflicts with existing entities → warn user
- FK dependencies on User entity (auth_Users)
- FK dependencies on Organisation entity
- Person Extension Pattern candidates: entities with FirstName + LastName + Email attributes

**If Person Extension Pattern detected** → AskUserQuestion #6:
- **Q7** (header: "Person Pattern"): "Entity {X} has personal attributes (name, email). SmartStack links these to auth_Users via the Person Extension Pattern. Should I apply it?"
  - Options: "Yes, link to User" / "No, keep standalone" / "Explain the pattern"
  - If "Explain": display brief explanation, then re-ask Yes/No

If PEP applied: add `personRoleConfig` to entity, change UserId type to `string` (ASP.NET Identity convention).

## Step 7: Business Rules + Cross-Cutting Needs (AskUserQuestion #7)

**AskUserQuestion** with 1 multiSelect question:
- **Q8** (header: "Needs", multiSelect: true): "Does this module need any of the following?"
  - "Status transitions / approval workflow" — e.g., Draft → Submitted → Approved
  - "Automated notifications (email, in-app)" — triggered by status changes or events
  - "Calculated / computed fields" — e.g., TotalAmount = sum of lines
  - "Date constraints (start < end, deadlines)" — temporal validation rules
  - "Uniqueness constraints beyond Code" — e.g., unique email, unique serial number
  - "AI-powered features (generation, classification, recommendation)"

**If "Status transitions" selected** → AskUserQuestion #8:
- **Q9** (header: "Workflow"): "Describe the workflow for {main entity}"
  - Options: "{suggested workflow from heuristics}" / "Linear: Draft → Submitted → Approved/Rejected" / "Multi-step with delegation" / "Custom (describe)"

**If "AI-powered features" selected** → AskUserQuestion #9:
- **Q10** (header: "AI Feature"): "What type of AI integration?"
  - Options: "Content generation (text, summaries)" / "Classification (categorize, tag)" / "Recommendations (suggest, predict)" / "Custom (describe)"

After collecting all answers, compile business rules:
1. Start with `typicalRules` from domain heuristics
2. Add rules from selected needs (workflow transitions, date constraints, uniqueness, calculations)
3. Add any user-specified custom rules

## Step 8: Sections + Navigation (AskUserQuestion #10)

Display proposed sections:

```markdown
### Proposed Sections

| Section | Type | Pages | Permission |
|---------|------|-------|------------|
| list | primary | List + implicit Detail/Create/Edit | CRUD |
| dashboard | embedded | KPIs, Charts | read-only |
| approve | functional | Approval queue | custom |

> **Note:** detail/create/edit pages are implicit routes under the primary section
> (/:id, /create, /:id/edit). Do NOT create separate sections for them.
```

Then **AskUserQuestion**:
- **Q11** (header: "Sections", multiSelect: true): "Here are the planned sections. Select any you want to add or remove:"
  - List current sections as selected by default
  - Offer additional options: "Add dashboard section" / "Add import/export section" / "Add calendar view" / "Remove {section}" (for each optional section)

## Step 9: Challenge + Final Validation (AskUserQuestion #11)

**ULTRATHINK: Final review checklist:**
- [ ] All entities have at least one FK or are standalone with justification
- [ ] No orphan entities (entity without a section)
- [ ] Entity-section mapping is clear (which entity belongs to which section)
- [ ] Business rules reference valid entity names
- [ ] Workflow states are consistent with status enum values
- [ ] **Roles defined:** at least Admin + 1 operational role (from Step 3c item 10)
- [ ] **Permission paths cover all CRUD sections:** each module has at minimum Read, Create, Update, Delete paths
- [ ] **Permission path format:** `{ApplicationPascalCase}.{ModulePascalCase}.{Action}` (3-segment) — PascalCase, no hyphens, no spaces
- [ ] **Role-permission matrix complete:** every role in matrix exists in roles[], every path in matrix exists in permissionPaths
- [ ] i18n labels provided in 4 languages

Display full specification summary as markdown, including any issues found.

Then **AskUserQuestion**:
- **Q12** (header: "Final"): "The specification is ready. Any last changes?"
  - Options: "Generate the PRD" / "I want to change something" / "Start over"

If "change something" → collect changes, apply, re-display summary. Loop max 1 time.
If "Start over" → restart from Step 2.

# ═══════════════════════════════════════════════════════
# PHASE 3: GENERATION (0 questions, 1 final choice)
# ═══════════════════════════════════════════════════════

## Step 10: Entity Name Quality Gate (BLOCKING)

Before generating any files, validate all entity names:
```
For each entity name:
  - Must be PascalCase
  - Must be a valid C# identifier (no spaces, accents, apostrophes)
  - Must not contain: àâäéèêëïîôùûüçÀÂÄÉÈÊËÏÎÔÙÛÜÇ or spaces or apostrophes

If any invalid name found → fix automatically (strip accents, PascalCase) and warn user.
```

## Step 11: Compute PRD v4.0 (one per module)

Read `references/prd-schema.md` for the exact JSON structure.

**Repeat for EACH module** identified in Step 3c. Each module gets its own PRD + 5 companion files.

Build the PRD object with these computed values:

**project:**
- `application` = {app_name} (PascalCase)
- `module` = {module_code} (kebab-case)

**expectedFiles:** Generate file paths using deterministic templates from prd-schema.md.
For EACH entity in this module, generate paths in: domain, infrastructure, application (service + 3 DTOs + validator), api (controller).
For the module, generate paths in: seedData (4 files: NavModule, NavSection, Permissions, Roles), frontend (4 pages per entity: List, Detail, Create, Edit + i18n × 4 langs), tests.

**Route convention:** The `route` field in screens.json follows a UNIFORM rule for ALL sections: `route` = `/{app-kebab}/{module-kebab}/{section-code}`. For a `list` section: `/{app-kebab}/{module-kebab}/list`. `navigate('create')` (relative) correctly resolves to `/{module}/create` in React Router v6.

**specificationFiles:** Relative paths to companion files:
```json
{
  "entities": "prd-{module}.entities.json",
  "permissions": "prd-{module}.permissions.json",
  "rules": "prd-{module}.rules.json",
  "usecases": "prd-{module}.usecases.json",
  "screens": "prd-{module}.screens.json"
}
```

**tasks:** Generate one task per major work item, with dependencies:
- Task per entity (domain layer, no dependencies)
- Task for EF configs (depends on entity tasks)
- Task for seed data (depends on entity tasks)
- Task per service (depends on entity tasks)
- Task per controller (depends on service tasks)
- Task per frontend page set (4 pages per entity: List, Detail, Create, Edit — depends on controller tasks)
- Task for tests (depends on all above)

**Cross-module dependencies:** If module B has entities with FK to module A, the PRD for module B must list module A as a dependency. APEX will process them in topological order.

## Step 12: Generate Companion Specification Files

Generate 5 JSON files following the schemas in `references/prd-schema.md`:

### entities.json
For each entity collected in Phase 2:
- `name`: PascalCase entity name
- `description`: one-line description
- `personRoleConfig`: only if Person Extension Pattern applied
- `attributes`: all collected properties with name, type, required, unique, searchable flags
- `relationships`: all FK relationships with target, type (ManyToOne/OneToMany/etc.), description
- `codePattern`: strategy (default: sequential), prefix (first 3 letters), digits (5), separator ("-"), includeTenantSlug (true)
- `estimatedVolume`: inferred from domain (low: 50/1000, medium: 200/5000, high: 1000/25000)

### rules.json
For each business rule collected in Steps 7-9:
- `id`: BR-{CAT}-{MODULE_SHORT}-{NNN} format
- `name`, `category`, `statement`, `severity`, `priority`
- `entities`: list of affected entity names
- `examples`: at least 1 input/expected pair per rule
- `formula` for calculation rules, `conditions`+`consequences` for workflow rules

### usecases.json
Generate standard CRUD use cases per entity + custom use cases from workflow:
- CRUD: Create, Read (list), Read (detail), Update, Delete per entity
- Custom: one UC per workflow transition, one UC per functional section
- Each UC: id, name, sectionCode, primaryActor, permission, preconditions, mainScenario (3-5 steps), postconditions, businessRules refs

### permissions.json — Deterministic Generation

> **This section generates a complete, cross-validated permissions file.**
> Roles were derived in Step 3c item 10 and confirmed by the user in Step 4.

**A. Roles**

Include the roles derived in Step 3c. AT MINIMUM:
1. `"{App} Admin"` — level: admin, description: "Full access to {module} module"
2. One operational role from domain analysis (Manager, Contributor, etc.)

Optional: additional roles from workflow actors or domain heuristics `typicalRoles`.

Format per role:
```json
{ "role": "{Name}", "level": "{admin|manager|contributor|viewer}", "description": "..." }
```

**B. Permission Paths**

For EACH module, compute paths deterministically:

```
base = "{ApplicationPascalCase}.{ModulePascalCase}"
```

Where `{ApplicationPascalCase}` is the app name in PascalCase (e.g., `HumanResources`) and `{ModulePascalCase}` is the module code converted from kebab-case to PascalCase (e.g., `absence-management` → `AbsenceManagement`).

**Standard paths (ALWAYS generate for each module):**
- `{base}.Read`
- `{base}.Create`
- `{base}.Update`
- `{base}.Delete`

**Conditional paths (add if applicable):**
- If export needed (user selected or heuristic suggests) → `{base}.Export`
- If import needed → `{base}.Import`
- If approval workflow detected → `{base}.Approve`
- If admin section exists → `{base}.Admin`

**Section-specific paths (4-segment, only if section has `permissionMode: "custom"`):**
- `{base}.{SectionPascalCase}.{Action}`
- Example: `HumanResources.AbsenceManagement.Approve.Read`

**IMPORTANT:** Permission paths are per MODULE, not per entity. A module with 3 entities (e.g., Absence, AbsenceType, AbsenceBalance) gets ONE set of paths like `HumanResources.AbsenceManagement.Read`, not three separate sets.

**C. Matrix (roleAssignments)**

Map each role to its permission paths using the hierarchy:

| Role level | Gets these permissions |
|------------|----------------------|
| admin | `["{base}.*"]` (wildcard — covers all current and future paths) |
| manager | All Read + Create + Update + Approve paths (explicit list) |
| contributor | Read + Create paths only (explicit list) |
| viewer | Read paths only (explicit list) |
| custom | Specific permission list derived from workflow analysis |

**D. Cross-Validation (BLOCKING — do NOT generate file if any check fails)**

Before writing permissions.json, verify:
1. Every `permission` field referenced in usecases.json exists in `permissionPaths`
2. Every section in screens.json with `permissionMode` not equal to `"inherit"` has a corresponding permission in `permissionPaths`
3. Every role name in `matrix.roleAssignments` exists in the `roles[]` array
4. `permissionPaths.length >= 4` (at minimum: Read, Create, Update, Delete)
5. No duplicate permission paths

If any check fails, fix the data (add missing paths, add missing roles) before generating the file.

### screens.json
Generate from sections collected in Step 8:
- **NEVER include sections with code "detail", "create", "edit", or "*-detail"** — these are implicit APEX routes, not sections
- For each section: code, sectionType, permissionMode, labels (4 langs), route, permission
- For primary sections: SmartTable resource with columns from entity attributes, default actions
- For functional sections: appropriate resource type (SmartForm for approval, etc.)
- For embedded sections: KpiPanel, Chart, or other widget resources
- Column format deduction: string→text, DateTime→date, decimal→number, bool→boolean, enum→badge
- **Route validation:** Verify every section has `route` equal to `"/{app-kebab}/{module-kebab}/{section-code}"` — including `list` sections (route ends with `/list`)

### I18n Label Quality Gate (BLOCKING — run before writing ANY companion file)

Before writing screens.json, entities.json, and usecases.json, verify ALL text labels have correct UTF-8 accents.

**Primary rule:** Write proper French/German/Italian with accents. You are an LLM that knows these languages — write them correctly.

**Safety net — common ASCII-stripping corrections:**

| ASCII (WRONG) | Accented (CORRECT) | Language |
|---|---|---|
| Employes | Employés | FR |
| Employe | Employé | FR |
| Departement | Département | FR |
| Departements | Départements | FR |
| Prenom | Prénom | FR |
| Numero | Numéro | FR |
| Societe | Société | FR |
| Categorie | Catégorie | FR |
| Categories | Catégories | FR |
| Securite | Sécurité | FR |
| Conge | Congé | FR |
| Conges | Congés | FR |
| Generalites | Généralités | FR |
| Resume | Résumé | FR |
| Echeance | Échéance | FR |
| Activite | Activité | FR |
| Salarie | Salarié | FR |
| Creee | Créée | FR |
| Cree | Créé | FR |
| Modifiee | Modifiée | FR |
| Modifie | Modifié | FR |
| Taux occupation | Taux d'occupation | FR |
| Detail employe | Détail employé | FR |
| Departement parent | Département parent | FR |
| Soldes de conges | Soldes de congés | FR |
| Demi-journee | Demi-journée | FR |
| Ubersicht | Übersicht | DE |
| Beschaftigungsgrad | Beschäftigungsgrad | DE |
| Uberabteilung | Überabteilung | DE |
| attivita | attività | IT |

**Scan all label objects** in sections[].labels, resources[].columns[].label, and any description fields. If any value matches the ASCII column above, replace it with the accented version.

**This gate is BLOCKING:** do NOT write the file if any French label lacks expected accents.

## Step 13: Write Files

Write 6 files per module to `.ralph/` directory:

```
For EACH module:
  .ralph/prd-{module}.json                    — PRD manifest
  .ralph/prd-{module}.entities.json           — Entity specifications
  .ralph/prd-{module}.rules.json              — Business rules
  .ralph/prd-{module}.usecases.json           — Use cases
  .ralph/prd-{module}.screens.json            — Screen specifications
  .ralph/prd-{module}.permissions.json        — Permission matrix
```

Also generate a queue file for multi-module execution:
```
.ralph/modules-queue.json
```
```json
{
  "application": "{app_name}",
  "modules": [
    { "code": "{module-1}", "prd": "prd-{module-1}.json", "dependsOn": [] },
    { "code": "{module-2}", "prd": "prd-{module-2}.json", "dependsOn": ["{module-1}"] }
  ]
}
```

Ensure `.ralph/` directory exists before writing.

## Step 14: Display Summary + Handoff

Display the generation summary:

```
═══════════════════════════════════════════════════════════════
  /business-analyse-quick — Mini-PRD Generated
═══════════════════════════════════════════════════════════════

  Application:  {app_name}
  Modules:      {module_count}

  {module-1-code} ({complexity})
    Entities:   {count} ({entity_names})
    Sections:   {count} ({section_names})
    Rules:      {count} | Use Cases: {count}
    Roles:      {count} ({role_names}) | Permissions: {path_count} paths

  {module-2-code} ({complexity})  → depends on {module-1-code}
    Entities:   {count} ({entity_names})
    Sections:   {count} ({section_names})
    Rules:      {count} | Use Cases: {count}
    Roles:      {count} ({role_names}) | Permissions: {path_count} paths

  Total files:  {total_expected} expected across 8 categories

  Artifacts written:
    .ralph/modules-queue.json                  — Execution order
    .ralph/prd-{module-1}.json + 5 specs       — Module 1
    .ralph/prd-{module-2}.json + 5 specs       — Module 2

═══════════════════════════════════════════════════════════════
```

Then **AskUserQuestion** (final choice):
- **Q-final** (header: "Next step"): "What would you like to do?"
  - Options:
    - "Run /apex -d for all modules (sequential, respecting dependencies)"
    - "Run /apex -d for {module-1} only (start with first module)"
    - "Edit specifications manually"
    - "Cancel"

</algorithm>

<handoff>

Based on user selection:

```
IF user selects "Run /apex -d for all modules":
  → Execute Ralph-Loop (see below)

IF user selects "Run /apex -d for {module-1} only":
  → Execute Ralph-Loop for single module (see below)

IF user selects "Edit specifications manually":
  → Display the list of generated files in .ralph/
  → Display: "Edit the JSON files, then run:
              /apex -d .ralph/prd-{module}.json (per module)"
  → STOP

IF user selects "Cancel":
  → Display: "Cancelled. Your specifications remain in .ralph/ for later use."
  → STOP
```

## Ralph-Loop — Module Execution with PRD Compliance

> **EXECUTION GUARANTEE:** Once the user selects "Run /apex -d", execute ALL selected modules
> without stopping for confirmation between modules. The loop runs autonomously.

### Algorithm

```javascript
const queue = readJSON('.ralph/modules-queue.json');
const results = [];

// If user selected single module, filter queue to that module only
const modulesToRun = singleModule
  ? queue.modules.filter(m => m.code === singleModule)
  : queue.modules;

for (const module of modulesToRun) {
  // 1. Dependency check
  if (module.dependsOn?.length > 0) {
    const unmetDeps = module.dependsOn.filter(dep =>
      !results.find(r => r.code === dep && r.status !== 'skipped')
    );
    if (unmetDeps.length > 0) {
      results.push({
        code: module.code,
        status: 'skipped',
        reason: `Unmet dependencies: ${unmetDeps.join(', ')}`
      });
      continue;
    }
  }

  // 2. Execute /apex -d for this module
  //    /apex now includes PRD Compliance Gate (step-04 section 6d)
  //    which validates columns, actions, permissions, i18n against companion specs
  Skill("apex", args: `-d .ralph/${module.prd}`);

  // 3. Verify completion status
  const prd = readJSON(`.ralph/${module.prd}`);
  const allTasksDone = prd.tasks?.every(t => t.status === 'completed') ?? false;

  results.push({
    code: module.code,
    status: allTasksDone ? 'completed' : 'completed-with-warnings',
    taskCount: prd.tasks?.length || 0,
    completedTasks: prd.tasks?.filter(t => t.status === 'completed').length || 0
  });
}
```

### Ralph-Loop Report

After all modules are processed, display the execution report:

```
═══════════════════════════════════════════════════════════════
  Ralph-Loop — Execution Report
═══════════════════════════════════════════════════════════════

  Application:  {app_name}
  Modules:      {modulesToRun.length} executed

  Module              Status                Tasks
  ─────────────────────────────────────────────────────────────
  {module-1}          COMPLETED             {n}/{n} tasks done
  {module-2}          COMPLETED             {n}/{n} tasks done
  {module-3}          SKIPPED               Unmet dep: {dep}

═══════════════════════════════════════════════════════════════

  PRD Compliance: Validated by /apex step-04 section 6d
    PC-1 (columns)     PASS
    PC-2 (actions)     PASS
    PC-3 (i18n)        PASS
    PC-4 (permissions) PASS

═══════════════════════════════════════════════════════════════
```

> **Note:** The retry mechanism for PRD compliance issues is handled INTERNALLY by `/apex`
> (step-04 returns to step-03d for fixes). The ralph-loop does NOT re-invoke `/apex` for
> individual compliance failures — it trusts `/apex`'s internal correction loop.

</handoff>
