---
name: step-03a2-analysis
description: Analysis section - objectives, entities, business rules, process flow
model: opus
next_step: steps/step-03b-ui.md
---

> **Context files:** `_shared.md` | `_elicitation.md` | `_architecture.md` | `_module-loop.md`
> **Reference (check 7):** `references/entity-architecture-decision.md` — Entity scoring for unresolved relationship targets

# Step 3a2: Analysis - Entities & Business Logic

## MANDATORY EXECUTION RULES

- ALWAYS use ULTRATHINK mode
- This step follows step-03a1-setup.md (module already initialized)
- **ID NAMING RULE:** All IDs MUST include module prefix (BR-{CAT}-{PREFIX}-{NNN}, OBJ-{PREFIX}-{NNN}, etc.)
- **SCHEMA CONFORMITY RULE:** ALL data MUST fit within feature-schema.json structure

## MODE DETECTION (inherited from step-03a1)

> **CRITICAL: Re-check your execution mode before proceeding.**

**IF you are running as a TEAM AGENT** (your prompt contains `PROPOSE & REVIEW` or `team-lead` as recipient):
  → **NEVER** use `AskUserQuestion` — replace ALL user interactions with ULTRATHINK autonomous decisions
  → You are in autonomous mode — make all choices based on decomposition data + SmartStack conventions
  → Do NOT present options to the user — you PROPOSE to the team lead via SendMessage, not to the user

**IF you are running in the MAIN CONVERSATION** (classic inline mode):
  → Normal interactive mode — use `AskUserQuestion` as documented below

## YOUR TASK

Define the module's analysis section: objectives, entities (with attributes and relationships), business rules, process flow, and data lifecycle.

---

## EXECUTION SEQUENCE

### 6. Analysis Section

#### 6a. Objectives

Define measurable business objectives for this module:

> **STRUCTURE CARD: analysis.objectives[]**
> ```json
> { "id": "OBJ-{PREFIX}-001", "objective": "Reduce order processing time", "metric": "Average time to fulfillment", "target": "< 4 hours" }
> ```

#### 6b. Entity Definition

Define entities for this module (business attributes, not technical):

> **STRUCTURE CARD: analysis.entities[]** — Field names are EXACT. Do NOT deviate.
> ```json
> {
>   "name": "PascalCase",
>   "description": "1-2 sentences describing the entity purpose",
>   "attributes": [
>     {
>       "name": "attributeName",
>       "description": "What this attribute represents",
>       "required": true,
>       "unique": false,
>       "validation": "Format: XXX-NNNNN, max 100 chars, etc."
>     }
>   ],
>   "relationships": [
>     { "target": "OtherEntity", "type": "1:1|1:N|N:1|N:M", "description": "description" }
>   ]
> }
> ```
> **FORBIDDEN fields in attributes:** Do NOT use `type`, `values`, `rules`.
> Use `description` to explain what the attribute is, `validation` for format/constraint rules, `unique` as boolean.
>
> **FORBIDDEN FORMAT — DO NOT USE (technical/database schema):**
> ```json
> {
>   "name": "Project",
>   "tableName": "rh_projects",
>   "primaryKey": "id",
>   "fields": [
>     { "name": "code", "type": "UUID", "required": true }
>   ]
> }
> ```
> **Why forbidden:** `tableName`, `primaryKey` are technical fields that do NOT belong in analysis. `fields[]` is NOT recognized by the build pipeline — only `attributes[]` is. `type` with SQL types (UUID, string, timestamp) belongs in implementation, not analysis. Using this format causes **empty entity data in the HTML documentation** and **broken PRD extraction**.
> The canonical format uses `attributes[]` (not `fields[]`), `relationships[]` (not FK inside fields), and NO technical fields (tableName, primaryKey).

#### 6b-bis. Code Pattern Definition

For EACH entity defined above, determine the code generation strategy.

> **STRUCTURE CARD: analysis.entities[].codePattern**
> ```json
> {
>   "strategy": "sequential|timestamp-daily|timestamp-minute|year-sequential|uuid-short|manual",
>   "prefix": "emp",
>   "includeTenantSlug": true,
>   "separator": "-",
>   "estimatedVolume": 1000,
>   "digits": 5,
>   "example": "acme-emp-00001"
> }
> ```

**Strategy selection heuristic** (use as default when user does not specify):

| Entity type / name pattern | Default strategy | Example |
|---------------------------|-----------------|---------|
| Invoice, Order, Receipt, Bill, Delivery | `timestamp-daily` | `acme-inv-20260215-001` |
| Ticket, Request, Incident, Support, Alert | `timestamp-minute` | `acme-ticket-202602151430-001` |
| Contract, Agreement, Policy, License | `year-sequential` | `acme-ctr-2026-00001` |
| Reference, Category, Tag, Type, Status | `uuid-short` | `acme-ref-a1b2c3d4` |
| Employee, Customer, Partner, Project, Product | `sequential` | `acme-emp-00001` |
| User says "manual" or "user-provided" | `manual` | (user types the code) |

**Digits calculation (x10 rule):**
- Use Q4.4 (estimated volume) as input
- Apply: `digits = max(4, ceil(log10(volume * 10)))`
- If no volume estimate: default to 5 digits (capacity: 99,999)

**Interactive question (if NOT team agent):**

```yaml
questions:
  - header: "Code Pattern"
    question: "For entity {entityName}, how should the Code be generated?"
    options:
      - label: "Auto-sequential (Recommended)"
        description: "{tenant}-{prefix}-00001 — simple sequential numbering"
      - label: "Date-based (daily)"
        description: "{tenant}-{prefix}-20260215-001 — includes creation date"
      - label: "Year-sequential"
        description: "{tenant}-{prefix}-2026-00001 — yearly numbering"
      - label: "Manual entry"
        description: "User provides the code — no auto-generation"
    multiSelect: false
```

If team agent: use heuristic defaults autonomously.

**Reference:** See `apex/references/code-generation.md` for full ICodeGenerator<T> implementation details, DI registration patterns, and backend service integration.

#### 6c. Process Flow

Define the main business process flow for this module (not lifecycle — that's in 8j):

> **STRUCTURE CARD: analysis.processFlow**
> ```json
> {
>   "entryPoints": ["User navigates to module", "System event triggers action"],
>   "mainFlow": [
>     { "step": 1, "actor": "Manager", "action": "Opens the list", "system": "Displays filtered records" },
>     { "step": 2, "actor": "Manager", "action": "Creates a record", "system": "Validates BR-VAL-{PREFIX}-001" },
>     { "step": 3, "actor": "System", "action": "Saves record", "system": "Sends notification" }
>   ],
>   "decisionPoints": [
>     { "condition": "Is amount > threshold?", "ifTrue": "Route to approver", "ifFalse": "Auto-approve", "rule": "BR-WF-{PREFIX}-001" }
>   ],
>   "alternativeFlows": ["Bulk import via CSV", "Automatic sync from SFTP"]
> }
> ```
> **FORBIDDEN:** Do NOT put lifecycle/state machine data here. Use `specification.lifeCycles[]` for that.

#### 6d. Data Lifecycle (MANDATORY — ALL modules)

> **CRITICAL:** This section is MANDATORY for EVERY module, even simple ones without GDPR requirements.
> Missing `analysis.dataLifecycle` causes BLOCKING errors in step-03d validation and consolidation structural checks.

Define data retention and lifecycle policies:

> **STRUCTURE CARD: analysis.dataLifecycle**
> ```json
> {
>   "retentionPeriod": "7 years",
>   "archiveStrategy": "Move to cold storage after 2 years",
>   "gdprCompliance": "PII anonymized on request, data export available",
>   "states": [
>     { "name": "active", "transitions": ["archived", "deleted"] },
>     { "name": "archived", "transitions": ["active"] },
>     { "name": "deleted", "transitions": [] }
>   ]
> }
> ```
>
> **Standard defaults** (use for modules without specific GDPR/retention requirements):
> ```json
> {
>   "retentionPeriod": "Standard (as per company policy)",
>   "archiveStrategy": "Soft-delete with audit trail",
>   "gdprCompliance": "N/A — no PII or standard audit trail only",
>   "states": [
>     { "name": "active", "transitions": ["archived"] },
>     { "name": "archived", "transitions": ["active"] }
>   ]
> }
> ```

### 7. Business Rules Extraction

Extract business rules specific to this module:

> **STRUCTURE CARD: analysis.businessRules[]** — Field names are EXACT. Do NOT deviate.
> ```json
> {
>   "id": "BR-VAL-{PREFIX}-001",
>   "name": "Short rule name",
>   "category": "validation|calculation|workflow|security|data",
>   "statement": "IF {condition} THEN {consequence} ELSE {alternative}",
>   "priority": "must|should|could",
>   "conditions": ["Condition 1", "Condition 2"],
>   "examples": [{ "input": "Order total $5000, budget $2000", "expected": "Order rejected" }],
>   "testability": "Via unit test with mock data / integration test"
> }
> ```
> **MANDATORY fields:** `id`, `name`, `category`, `statement`, `priority`
> **FORBIDDEN fields:** Do NOT use `rule`, `condition` (singular), `action`. Use `name` + `statement` (IF/THEN/ELSE format) + `conditions` (array).
> **ID PATTERN:** `BR-{CAT}-{PREFIX}-{NNN}` where CAT = VAL|CALC|WF|SEC|DATA, PREFIX = module initials (2-4 chars)
> **category values:** lowercase only: `validation`, `calculation`, `workflow`, `security`, `data`

---

## SELF-VERIFICATION (MANDATORY before loading step-03b-ui)

Before proceeding to step-03b-ui.md, VERIFY:

1. **Module feature.json exists** at expected path (`docs/business/{app}/{module}/business-analyse/v{X.Y}/feature.json`)
2. **Module feature.json has analysis section** with `entities[]` (at least 1) and `businessRules[]` (at least 1)
3. **Entity schema compliance (BLOCKING)** — EVERY entity has `attributes[]` (NOT `fields[]`) and `relationships[]` arrays.
   Quick check: `analysis.entities.every(e => Array.isArray(e.attributes) && e.attributes.length >= 1)`
   IF any entity has `fields[]` instead of `attributes[]` → STRUCTURAL ERROR, fix before proceeding.
   IF any entity has `tableName` or `primaryKey` → STRUCTURAL ERROR, these are technical fields that do not belong in analysis.
4. **Module status in master** = "in-progress" (set by section 2 above)
5. **Master modules[].featureJsonPath** for this module ≠ null (set by ba-writer.create)
6. **Sections identified** with clear roles and entities assigned
7. **Unresolved relationship targets (BLOCKING)** — For EACH entity's `relationships[].target`:
   - Check if the target entity exists in THIS module's `entities[]`
   - OR in a completed/planned module's `entities[]`
   - OR is a known config list / external system reference
   - **IF unresolved:** Apply the Entity Sourcing Pattern from step-03a1 section 5-bis
     (ULTRATHINK scoring + domain coherence + recommendation + AskUserQuestion)
   - This catches entities discovered DURING analysis that weren't identified in setup

**IF any check fails → FIX before proceeding.** Do NOT load step-03b-ui with incomplete data.

---

## NEXT STEP

Load: `steps/step-03b-ui.md`
