---
name: step-05-handoff
description: Development handoff - file mapping, BR-to-code, API endpoints, prd.json, progress tracker
model: sonnet
next_step: null
---

# Step 5: Handoff

## MANDATORY EXECUTION RULES

- **ALWAYS** verify status = "consolidated" before proceeding
- **ALWAYS** ask user for implementation strategy preference (multi-module only)
- **ALWAYS** derive prd.json from feature.json (NEVER independently)
- **NEVER** invent entities/FRs/BRs not in feature.json
- **ALL** API routes from specification.apiEndpoints (exact copy)
- **Permission** paths from specification.permissionMatrix (full format)
- **ALWAYS** generate 5 CORE SeedData task entries per module

## YOUR TASK

Generate the development handoff package: file mapping, BR-to-code mapping, API endpoint summary, prd.json, and progress tracker. For multi-module applications, support both per-module and consolidated handoff approaches.

---

## EXECUTION SEQUENCE

### 1. Verify Consolidation Passed

Use ba-reader to locate the feature and verify consolidation status:

```
ba-reader.findFeature({feature_id})
→ Check status = "consolidated"
```

**IF** status ≠ "consolidated" → **STOP**. Return to step-04-consolidation.md.

Display validation summary:

```
✓ Consolidation: APPROVED
✓ Modules: {count} specified and validated
✓ Cross-module: interactions mapped
✓ Permissions: coherent
→ Proceeding to handoff...
```

Include:
- Number of modules
- Number of entities across all modules
- Number of use cases across all modules
- Number of business rules across all modules
- Cross-module interaction count

---

### 2. Implementation Strategy Choice (Multi-Module)

**IF** more than 1 module defined in feature.json:

Ask via AskUserQuestion:

```
question: "Quelle stratégie d'implémentation préférez-vous ?"
header: "Stratégie d'implémentation"
options:
  - label: "Module par module (Recommandé)"
    description: "Implémenter chaque module complètement avant de passer au suivant. Suit l'ordre topologique des dépendances."
  - label: "Couche par couche"
    description: "Implémenter toutes les entités, puis tous les services, puis tous les contrôleurs, etc. Plus de parallélisation possible mais plus complexe."
  - label: "Hybride"
    description: "Modules fondation en premier (couche par couche), puis modules dépendants (module par module)"
```

Store the chosen strategy in `handoff.implementationStrategy`.

**IF** only 1 module → default to "Module par module" (no choice needed).

---

### 3. Calculate Complexity

For each module in feature.json.modules[], calculate:

```json
{
  "complexity": "simple|medium|complex",
  "complexityDetails": {
    "entities": {count},
    "useCases": {count},
    "businessRules": {count},
    "calculated": "{level} (≤X entities, ≤Y UCs, ≤Z BRs)"
  }
}
```

| Criteria | Simple | Medium | Complex |
|----------|--------|--------|---------|
| Entities | ≤3 | ≤6 | >6 |
| Use Cases | ≤5 | ≤12 | >12 |
| Business Rules | ≤10 | ≤20 | >20 |

**Global complexity** = highest complexity across all modules.

Example:
- Module A: 4 entities, 6 use cases, 8 BRs → **simple**
- Module B: 8 entities, 15 use cases, 25 BRs → **complex**
- Overall: **complex**

---

### 4. Map Specification to Files

> **IMPORTANT:** Generate `handoff.filesToCreate` as structured object with 7 categories.
> Each file entry is `{path, type, linkedFRs, linkedUCs, module}`. NO free text.
> Read `.smartstack/config.json` to extract baseNamespace for project namespace.

**Order by topological dependency** (modules with no deps first, then dependents).

For **EACH module** in topological order:

#### 4.1 Domain Files

From `analysis.entities[]` of the module:

```json
"domain": [
  {
    "path": "src/Domain/Entities/{ModuleName}/{EntityName}.cs",
    "type": "Entity",
    "linkedFRs": ["FR-001", "FR-002"],
    "linkedUCs": ["UC-001"],
    "module": "{moduleCode}"
  }
]
```

Include:
- Value objects referenced by entities
- Enums used in domain
- Domain exceptions specific to module

#### 4.2 Application Files

From `analysis.useCases[]` of the module:

```json
"application": [
  {
    "path": "src/Application/Services/{ModuleName}/{ServiceName}Service.cs",
    "type": "Service",
    "linkedFRs": ["FR-001"],
    "linkedUCs": ["UC-001", "UC-002"],
    "module": "{moduleCode}"
  },
  {
    "path": "src/Application/DTOs/{ModuleName}/{DtoName}Dto.cs",
    "type": "Dto",
    "linkedUCs": ["UC-001"],
    "module": "{moduleCode}"
  },
  {
    "path": "src/Application/Validators/{ModuleName}/{ValidatorName}Validator.cs",
    "type": "Validator",
    "linkedFRs": ["FR-001"],
    "module": "{moduleCode}"
  }
]
```

Include:
- Service per use case cluster (or per domain entity if applicable)
- DTOs for API contracts
- Validators for FluentValidation
- Query handlers

#### 4.3 Infrastructure Files

From `analysis.entities[]` of the module:

```json
"infrastructure": [
  {
    "path": "src/Infrastructure/Repositories/{ModuleName}/{EntityName}Repository.cs",
    "type": "Repository",
    "linkedFRs": ["FR-001"],
    "module": "{moduleCode}"
  },
  {
    "path": "src/Infrastructure/Persistence/{ModuleName}DbContext.cs",
    "type": "DbContext",
    "linkedFRs": ["FR-001", "FR-002"],
    "module": "{moduleCode}"
  }
]
```

Include:
- Repository per entity
- DbContext configuration (if module-specific)
- Unit of Work pattern if applicable
- Specifications if complex queries

#### 4.4 API Files

From `specification.apiEndpoints[]` of the module:

```json
"api": [
  {
    "path": "src/API/Controllers/{ModuleName}Controller.cs",
    "type": "ApiController",
    "linkedUCs": ["UC-001", "UC-002"],
    "linkedFRs": ["FR-001"],
    "module": "{moduleCode}"
  }
]
```

Include:
- One controller per domain aggregate root (or logical grouping)
- Include all HTTP methods (GET, POST, PUT, DELETE, PATCH)
- Error handling and validation responses

#### 4.5 Frontend Files

From `specification.uiWireframes[]`, `specification.dashboards[]` and `analysis.useCases[]` of the module:

> **WIREFRAME TRACEABILITY RULE:** Every frontend file (Page, DashboardPage, Component) MUST include `linkedWireframes[]` referencing the wireframe `screen` identifiers from `specification.uiWireframes[]`. This ensures the BA mockups validated by the client are respected during implementation.

```json
"frontend": [
  {
    "path": "src/pages/{ModuleName}/{PageName}Page.tsx",
    "type": "Page",
    "linkedUCs": ["UC-001", "UC-002"],
    "linkedWireframes": ["{module}-list"],
    "module": "{moduleCode}",
    "wireframeAcceptanceCriteria": "Layout MUST match wireframe '{module}-list': elements [{elements}], actions [{actions}]. See specification.uiWireframes[] for exact mockup."
  },
  {
    "path": "src/pages/{ModuleName}/{PageName}DetailPage.tsx",
    "type": "Page",
    "linkedUCs": ["UC-003"],
    "linkedWireframes": ["{module}-detail"],
    "module": "{moduleCode}",
    "wireframeAcceptanceCriteria": "Layout MUST match wireframe '{module}-detail': elements [{elements}], actions [{actions}]. See specification.uiWireframes[] for exact mockup."
  },
  {
    "path": "src/pages/{ModuleName}/{DashboardName}DashboardPage.tsx",
    "type": "DashboardPage",
    "linkedUCs": ["UC-060"],
    "linkedWireframes": ["{module}-dashboard"],
    "module": "{moduleCode}",
    "dashboardRef": "{module}-dashboard",
    "instructions": "Use Recharts library. See specification.dashboards[] for KPI definitions, chart types, filters, and data sources.",
    "wireframeAcceptanceCriteria": "Layout MUST match wireframe '{module}-dashboard': KPI card positions, chart placement, filter bar location. See specification.uiWireframes[] AND specification.dashboards[] for exact mockup and KPI specs."
  },
  {
    "path": "src/components/{ModuleName}/{ComponentName}.tsx",
    "type": "Component",
    "linkedUCs": ["UC-001"],
    "linkedWireframes": ["{module}-{section}"],
    "module": "{moduleCode}"
  },
  {
    "path": "src/hooks/use{ModuleName}{Hook}.ts",
    "type": "Hook",
    "linkedUCs": ["UC-001", "UC-002"],
    "module": "{moduleCode}"
  }
]
```

**Wireframe Acceptance Criteria (ALL frontend pages):**
> **MANDATORY** for every Page and DashboardPage task. These criteria ensure the BA mockups are respected.
- Layout structure matches the validated ASCII/SVG wireframe from `specification.uiWireframes[]`
- All `elements` listed in the wireframe are present in the generated component
- All `actions` listed in the wireframe are implemented with correct permissions
- Component mapping follows the wireframe-to-component table (see step-03 section 3b-bis)
- If wireframe shows a DataGrid → implement with `SmartTable` or `EntityCard` grid
- If wireframe shows FilterBar → implement with `SmartFilter`
- If wireframe shows ActionButton → wrap in `RequirePermission`

**Dashboard pages (type: DashboardPage):**
- Generated from `specification.dashboards[]` entries
- `dashboardRef` links to the dashboard code in specification.dashboards[]
- `linkedWireframes` links to the dashboard wireframe in specification.uiWireframes[]
- `instructions` MUST reference chart types, KPI definitions, and data sources
- Acceptance criteria for DashboardPage tasks MUST include:
  - Chart library (Recharts) installed in package.json
  - Chart types matching specification.dashboards[].kpis[].visualization
  - KPI cards for kpi-card type visualizations
  - Filters functional (dateRange, select, etc.)
  - CSS variables used (no hardcoded colors) - see ui-components/patterns/dashboard-chart.md
  - Responsive layout (1-col mobile, 2-col tablet, 3-col desktop)
  - **KPI card positions match wireframe layout** (e.g., 4 cards in a row if wireframe shows 4)
  - **Chart placement matches wireframe** (e.g., 2-column grid if wireframe shows side-by-side)

**Standard pages (type: Page):**
- Pages for major use cases
- Components for reusable UI elements
- Custom hooks for business logic
- Forms for data entry
- List/Detail views
- **ALL pages MUST reference their wireframe via `linkedWireframes`**

#### 4.6 SeedData Files

**OBLIGATORY:** 5 CORE SeedData entries per module + business seed data:

```json
"seedData": [
  {
    "path": "src/Infrastructure/Persistence/Seeding/Data/{ModuleName}/NavigationModuleSeedData.cs",
    "type": "SeedData",
    "category": "core",
    "source": "specification.seedDataCore.navigationModules",
    "module": "{moduleCode}"
  },
  {
    "path": "src/Infrastructure/Persistence/Seeding/Data/{ModuleName}/PermissionsSeedData.cs",
    "type": "SeedData",
    "category": "core",
    "source": "specification.seedDataCore.permissions",
    "module": "{moduleCode}"
  },
  {
    "path": "src/Infrastructure/Persistence/Seeding/Data/{ModuleName}/RolesSeedData.cs",
    "type": "SeedData",
    "category": "core",
    "source": "specification.seedDataCore.roles",
    "module": "{moduleCode}"
  },
  {
    "path": "src/Infrastructure/Persistence/Seeding/Data/{ModuleName}/TenantSeedData.cs",
    "type": "SeedData",
    "category": "core",
    "source": "specification.seedDataCore.tenants",
    "module": "{moduleCode}"
  },
  {
    "path": "src/Infrastructure/Persistence/Seeding/Data/{ModuleName}/UserSeedData.cs",
    "type": "SeedData",
    "category": "core",
    "source": "specification.seedDataCore.users",
    "module": "{moduleCode}"
  },
  {
    "path": "src/Infrastructure/Persistence/Seeding/Data/{ModuleName}/{Entity}SeedData.cs",
    "type": "SeedData",
    "category": "business",
    "source": "specification.seedDataBusiness.{module}",
    "module": "{moduleCode}"
  }
]
```

**For client projects (ExtensionsDbContext), add these MANDATORY infrastructure files:**

```json
"seedData": [
  // ... 5 core + business entries above ...
  {
    "path": "src/Infrastructure/Persistence/Seeding/{AppPascalName}SeedDataProvider.cs",
    "type": "IClientSeedDataProvider",
    "category": "infrastructure",
    "description": "Runtime provider that injects core seed data (navigation, permissions, roles) into Core schema",
    "source": "specification.seedDataCore",
    "module": "{moduleCode}"
  },
  {
    "path": "src/Infrastructure/Persistence/Seeding/DevDataSeeder.cs",
    "type": "DevDataSeeder",
    "category": "infrastructure",
    "description": "Seeds development/demo data for domain entities at startup",
    "module": "{moduleCode}"
  },
  {
    "path": "src/Infrastructure/Persistence/Seeding/Data/SeedConstants.cs",
    "type": "SeedConstants",
    "category": "infrastructure",
    "description": "Shared constants for deterministic seed data",
    "module": "{moduleCode}"
  }
]
```

**Path convention:** All seed data files MUST be under `Persistence/Seeding/Data/` (matching SmartStack.app architecture).
NEVER use `Data/SeedData/` or `Infrastructure/Data/SeedData/`.

**IClientSeedDataProvider (MANDATORY for client projects):** This provider injects core seed data
(navigation, permissions, roles) into the Core schema at runtime. Generated at
`src/Infrastructure/Persistence/Seeding/{AppPascalName}SeedDataProvider.cs`.
See `/application` skill step-03b-provider for the full pattern.
Without this provider, the 5 core SeedData files are DEAD CODE and will have no effect.

Core categories (ALWAYS 5):
1. NavigationModuleSeedData (navigation items for module)
2. PermissionsSeedData (RBAC permissions)
3. RolesSeedData (roles using permissions)
4. TenantSeedData (test tenants)
5. UserSeedData (test users)

Business categories (from specification.seedDataBusiness):
- Domain-specific reference data
- Test data fixtures
- Lookup tables (statuses, categories, etc.)

#### 4.7 Test Files

```json
"tests": [
  {
    "path": "src/Tests/Unit/Domain/{ModuleName}/{Entity}Tests.cs",
    "type": "UnitTests",
    "linkedFRs": ["FR-001"],
    "module": "{moduleCode}"
  },
  {
    "path": "src/Tests/Unit/Application/{ModuleName}/{ServiceName}ServiceTests.cs",
    "type": "UnitTests",
    "linkedFRs": ["FR-001"],
    "linkedUCs": ["UC-001"],
    "module": "{moduleCode}"
  },
  {
    "path": "src/Tests/Integration/{ModuleName}/{ApiControllerName}ControllerTests.cs",
    "type": "IntegrationTests",
    "linkedUCs": ["UC-001"],
    "module": "{moduleCode}"
  },
  {
    "path": "src/Tests/Security/{ModuleName}/{ModuleName}SecurityTests.cs",
    "type": "SecurityTests",
    "linkedFRs": ["FR-001"],
    "module": "{moduleCode}"
  }
]
```

Test files:
- Unit tests for domain entities and value objects
- Unit tests for services and validators
- Integration tests for API endpoints
- Security tests for authorization and tenant isolation
- E2E tests for critical user flows

---

### 5. Map Business Rules to Code

Derive from `analysis.businessRules[]` of **EACH module**.

Generate complete mapping for each BR:

```json
{
  "brToCodeMapping": [
    {
      "ruleId": "BR-VAL-001",
      "title": "Order total must equal sum of item prices",
      "module": "{moduleCode}",
      "severity": "critical",
      "implementationPoints": [
        {
          "layer": "Domain",
          "component": "Order.cs",
          "method": "CalculateTotal()",
          "implementation": "Validate sum equals sum of OrderItems.Price"
        },
        {
          "layer": "Application",
          "component": "CreateOrderService.cs",
          "method": "Handle()",
          "implementation": "Calculate total before persisting"
        },
        {
          "layer": "API",
          "component": "OrdersController.cs",
          "method": "CreateOrder()",
          "implementation": "Return validation error if total mismatch"
        },
        {
          "layer": "Frontend",
          "component": "OrderForm.tsx",
          "method": "calculateTotal()",
          "implementation": "Real-time calculation on item change"
        }
      ]
    },
    {
      "ruleId": "BR-SEC-002",
      "title": "User can only view orders from their tenant",
      "module": "{moduleCode}",
      "severity": "critical",
      "implementationPoints": [
        {
          "layer": "Domain",
          "component": "Order.cs",
          "method": "Validate()",
          "implementation": "Check TenantId matches user context"
        },
        {
          "layer": "Infrastructure",
          "component": "OrderRepository.cs",
          "method": "GetUserOrders()",
          "implementation": "Filter by TenantId in WHERE clause"
        },
        {
          "layer": "API",
          "component": "OrdersController.cs",
          "method": "GetOrders()",
          "implementation": "Enforce permission check + tenant filter"
        }
      ]
    }
  ]
}
```

For each BR include:
- **ruleId**: Reference to analysis.businessRules[].id
- **title**: The rule statement
- **module**: Which module it belongs to
- **severity**: "critical", "high", "medium", "low"
- **implementationPoints**: Array of {layer, component, method, implementation}

Layers: Domain, Application, Infrastructure, API, Frontend

---

### 6. API Endpoint Summary

> **ABSOLUTE RULE:** Copy **EXACTLY** from `specification.apiEndpoints[]`. **NEVER** reinvent routes.

Generate summary with full details:

```json
{
  "apiEndpointSummary": [
    {
      "operation": "ListOrders",
      "method": "GET",
      "route": "/api/business/orders",
      "linkedUC": "UC-001",
      "linkedFR": "FR-001",
      "permissions": ["business.orders.read"],
      "requestSchema": { "type": "query", "params": ["pageNumber", "pageSize", "status"] },
      "responseSchema": { "type": "PaginatedOrderDto[]" },
      "errorCodes": [401, 403, 400, 500],
      "module": "{moduleCode}"
    },
    {
      "operation": "CreateOrder",
      "method": "POST",
      "route": "/api/business/orders",
      "linkedUC": "UC-002",
      "linkedFR": "FR-002",
      "permissions": ["business.orders.create"],
      "requestSchema": { "type": "body", "schema": "CreateOrderDto" },
      "responseSchema": { "type": "OrderDto" },
      "errorCodes": [400, 401, 403, 422, 500],
      "module": "{moduleCode}"
    }
  ]
}
```

For each endpoint:
- **operation**: Use case name or operation name
- **method**: HTTP method (GET, POST, PUT, DELETE, PATCH)
- **route**: Full API path from specification
- **linkedUC**: Use case ID(s) this endpoint implements
- **linkedFR**: Feature requirement ID(s)
- **permissions**: Array of exact permission paths
- **requestSchema**: Input contract (query params or body)
- **responseSchema**: Output contract
- **errorCodes**: Expected HTTP error codes
- **module**: Which module

Total endpoints = count of specification.apiEndpoints[] across all modules.

---

### 7. Generate prd.json (PROGRAMMATIC)

> **RULE:** prd.json is extracted by CLI code, **NEVER** generated by LLM.
> The `ss derive-prd` command performs a deterministic data transformation from feature.json.

**For each module:**

```
Execute: ss derive-prd --feature {moduleFeaturePath} --output .ralph/prd-{moduleCode}.json
```

**For consolidated view (multi-module, optional):**

```
Execute: ss derive-prd --application {masterFeaturePath}
→ Generates .ralph/prd-{moduleCode}.json for each module
```

**Verification:** After execution, read the generated prd.json and display summary:

```
prd.json generated for module {moduleCode}:
  - Use cases: {count}
  - Functional requirements: {count}
  - Business rules: {count}
  - API endpoints: {count}
  - Sections: {count}
  - Files to create: {count}
  - BR-to-code mappings: {count}
```

**Key guarantees:**
- Source MUST reference feature.json path (traceability)
- All data is EXACT COPY from feature.json (no transformation, no invention)
- prd.json version: "2.0.0"
- source.type: "ba-handoff-programmatic"

---

### 8. Initialize Progress Tracker

Generate `.ralph/progress.txt` as main task tracker:

```
═════════════════════════════════════════════════════════════════
  SMARTSTACK RALPH LOOP - PROGRESS TRACKER
  Project: {project_name} | Application: {app_name}
  Modules: {count} ({moduleOrder.join(', ')})
  Strategy: {implementation_strategy}
  Created: {timestamp}
  Status: HANDED-OFF
═════════════════════════════════════════════════════════════════

{For each module in topological order:}
[MODULE: {module_name}] ({complexity})
  Status: NOT STARTED
  Dependencies: {list of module dependencies or "FOUNDATION"}

  [DOMAIN] Entity & Value Object Definitions
    □ Define {Entity1} entity with properties and validation
    □ Define {Entity2} entity with relationships
    □ Define {ValueObject1} value object
    □ Define domain exceptions
    □ Total: X tasks

  [SEEDDATA-CORE] Core Configuration (MANDATORY)
    □ NavigationModuleConfiguration - Module navigation structure
    □ PermissionsConfiguration - RBAC permissions setup
    □ RolesConfiguration - Predefined roles
    □ TenantConfiguration - Test tenants
    □ UserConfiguration - Test users
    Total: 5 CORE tasks

  [SEEDDATA] Business Reference Data
    □ Seed {Entity1} reference data
    □ Seed {Entity2} lookup values
    □ Total: Y business seed tasks

  [APPLICATION] Services & Business Logic
    □ Create {ServiceName}Service for {UC1}
    □ Create {DtoName}Dto for API contracts
    □ Create {ValidatorName}Validator for input validation
    □ Implement query handlers
    Total: Z tasks

  [INFRASTRUCTURE] Repositories & Persistence
    □ Create {Entity1}Repository with CRUD + custom queries
    □ Create {Entity2}Repository
    □ Configure DbContext for module
    □ Setup specifications for complex queries
    □ Create IClientSeedDataProvider (client projects ONLY - injects core seeds at runtime)
    □ Create DevDataSeeder + SeedConstants (if first module)
    Total: A tasks

  [API] REST Endpoints & Controllers
    □ Create {ModuleNameController} GET endpoints (List, GetById)
    □ Create {ModuleNameController} POST endpoint (Create)
    □ Create {ModuleNameController} PUT endpoint (Update)
    □ Create {ModuleNameController} DELETE endpoint (Delete)
    □ Implement error handling and validation responses
    Total: B tasks

  [FRONTEND] UI Components & Pages (wireframe-driven)
    □ Create {ModuleName}Page for listing [wireframe: {module}-list]
    □ Create {ModuleName}DetailPage for viewing [wireframe: {module}-detail]
    □ Create {ModuleName}Form component for creation/edit [wireframe: {module}-create]
    □ Create custom hook use{ModuleName}
    □ Implement pagination, filtering, sorting
    □ Validate all pages match their wireframe layout
    □ ⚠️ Routes MUST be INSIDE Layout wrapper (AdminLayout/BusinessLayout/UserLayout)
    Total: C tasks

  [I18N] Internationalization Keys
    □ Define i18n keys for {Module} UI labels
    □ Setup translations for locales: fr, en, it, de
    Total: D keys

  [TESTS] Unit & Integration Tests
    □ Unit tests for {Entity} domain logic
    □ Unit tests for {ServiceName}Service
    □ Integration tests for {ModuleNameController}
    □ Security tests for authorization & tenant isolation
    □ E2E tests for critical user flows
    Total: E unit + F integration + G security = H tests

  [QA] Quality Assurance
    □ Code review against SmartStack conventions
    □ Test coverage minimum 80%
    □ Security scan for OWASP vulnerabilities
    □ Performance testing under load
    Total: 4 QA tasks

  Module Total: X + 5 + Y + Z + A + B + C + D + H + 4 = {module_total} tasks
  Estimated Effort: {simple/medium/complex} - {1-3/3-8/8-15} days

{If multi-module:}
[CROSS-MODULE] Integration Tasks
  Status: NOT STARTED
  Dependencies: All modules COMPLETED

  □ Verify cross-module entity relationships
  □ Test cross-module API dependencies
  □ Validate permission matrix across modules
  □ E2E flow tests spanning multiple modules
  □ Cross-module data consistency checks
  □ Integration test suite for module interactions
  Total: 6 CROSS-MODULE tasks

═════════════════════════════════════════════════════════════════
SUMMARY
═════════════════════════════════════════════════════════════════
Total Modules:         {count}
Total Tasks:           {total_count}
  - CORE SeedData:     {count} × 5 = {total_core}
  - Business Tasks:    {total_biz}
  - Development:       {total_dev}
  - Tests:             {total_tests}
  - QA:                {total_qa}
  - Cross-Module:      {cross_module_count or 0}

Strategy:              {strategy}
Module Order:          {topological order with dependencies noted}

Complexity Distribution:
  Simple:   {count} modules ({estimate} days each)
  Medium:   {count} modules ({estimate} days each)
  Complex:  {count} modules ({estimate} days each)

Total Effort Estimate:  {total_days} days ({total_hours} hours)
Per Developer (2):      {total_days / 2} days
Parallel Potential:     {strategy_efficiency_percent}%

═════════════════════════════════════════════════════════════════
LEGEND
═════════════════════════════════════════════════════════════════
□ = Task not started
✓ = Task completed
⚠ = Task in progress
✗ = Task failed / blocked

COLORS:
[DOMAIN]      = Domain Model & Business Logic
[SEEDDATA-CORE] = MANDATORY core configuration (5 entries)
[SEEDDATA]    = Business reference & lookup data
[APPLICATION] = Services, DTOs, Validators
[INFRASTRUCTURE] = Repositories, DbContext, ORM
[API]         = REST controllers & endpoints
[FRONTEND]    = React pages, components, hooks
[I18N]        = Internationalization
[TESTS]       = Unit, Integration, Security, E2E
[QA]          = Code quality, coverage, security
[CROSS-MODULE] = Multi-module integration (if applicable)

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

**Progress Tracker Rules:**
- One section per module, in topological order (dependencies first)
- CORE SeedData ALWAYS 5 entries (mandatory)
- Business SeedData varies by module
- Hierarchical task structure (module → layer → tasks)
- Each task is independent, assignable checkbox
- Effort estimate per module (simple/medium/complex)
- Summary with totals across all modules
- Identified dependencies for parallel execution
- Cross-module tasks only if multi-module

---

### 9. Write Handoff to Feature.json

> **BLOCKING RULE: The handoff MUST be written in EACH module feature.json.**
> A handoff at master level alone is INSUFFICIENT. Ralph-loop consumes module-level handoffs.
> An empty module handoff (`"handoff": {}`) is a CRITICAL BUG that blocks all downstream generation.

#### 9a. Module Handoff Loop (MANDATORY)

> **STRUCTURE CARD: handoff** — Field names are EXACT. Include ALL fields below.
> ```json
> {
>   "complexity": "simple|medium|complex",
>   "filesToCreate": {
>     "domain": [{"path": "...", "type": "Entity|ValueObject|Enum", "linkedFRs": [], "linkedUCs": [], "module": "..."}],
>     "application": [{"path": "...", "type": "Service|Dto|Validator", "linkedFRs": [], "linkedUCs": [], "module": "..."}],
>     "infrastructure": [{"path": "...", "type": "Repository|DbContext", "linkedFRs": [], "module": "..."}],
>     "api": [{"path": "...", "type": "ApiController", "linkedUCs": [], "linkedFRs": [], "module": "..."}],
>     "frontend": [{"path": "...", "type": "Page|Component|Hook|DashboardPage", "linkedUCs": [], "linkedWireframes": [], "module": "..."}],
>     "seedData": [{"path": "...", "type": "HasData", "category": "core|business", "source": "...", "module": "..."}],
>     "tests": [{"path": "...", "type": "UnitTests|IntegrationTests|SecurityTests", "linkedFRs": [], "linkedUCs": [], "module": "..."}]
>   },
>   "brToCodeMapping": [{"ruleId": "BR-...", "files": ["path1", "path2"], "implementation": "description"}],
>   "apiEndpointSummary": [{"method": "GET|POST|PUT|DELETE", "path": "/api/...", "permission": "business.{app}.{module}.{action}", "linkedUC": "UC-..."}],
>   "prdFile": ".ralph/prd-{module}.json",
>   "totalFiles": 0,
>   "totalTasks": 0,
>   "handedOffAt": "{ISO timestamp}"
> }
> ```
> **MANDATORY fields:** ALL of the above. `filesToCreate` MUST have all 7 categories (even if empty arrays).
> **FORBIDDEN:** `handoff: {}` (empty object is a CRITICAL BUG). Missing `brToCodeMapping` or `apiEndpointSummary`.

**For i = 0; i < modules.length; i++:**

```
1. moduleCode = modules[i].code
2. moduleFeatureId = modules[i].featureJsonPath or find via ba-reader.findFeature()
3. Read the module feature.json via ba-reader.findFeature(moduleFeatureId)
4. Build the handoff payload for THIS module:
   - complexity (from step 3 calculation)
   - filesToCreate (full 7-category structure from step 4, filtered for this module)
   - brToCodeMapping (from step 5, filtered for this module)
   - apiEndpointSummary (from step 6, filtered for this module)
   - prdFile path
   - totalFiles count
   - totalTasks count
   - handedOffAt timestamp

5. Write via ba-writer:
   ba-writer.enrichModuleHandoff({
     moduleFeatureId: {moduleFeatureId},
     handoffData: {
       complexity: "{simple|medium|complex}",
       filesToCreate: {...},
       brToCodeMapping: [...],
       apiEndpointSummary: [...],
       prdFile: ".ralph/prd-{moduleCode}.json",
       totalFiles: {count},
       totalTasks: {count},
       handedOffAt: "{ISO timestamp}"
     }
   })

6. VERIFICATION (MANDATORY - done automatically by enrichModuleHandoff):
   - handoff !== {}
   - handoff.filesToCreate has 7 categories
   - handoff.brToCodeMapping.length > 0
   IF verification fails → STOP, report error, do NOT continue

7. Display progress:
   "✓ Handoff module {i+1}/{N} : {moduleCode} ({fileCount} fichiers, {brCount} BRs mappées)"
```

#### 9b. Master Handoff (after ALL modules written successfully)

```
ba-writer.enrichSection({
  featureId: {feature_id},
  section: "handoff",
  data: {
    status: "handed-off",
    complexity: "{simple|medium|complex}",
    implementationStrategy: "{strategy}",
    moduleCount: {count},
    moduleOrder: [...],
    totalFilesToCreate: {sum across all modules},
    totalTasks: {sum across all modules},
    prdStructure: "per-module | consolidated",
    prdFiles: [
      { module: "{module1}", path: ".ralph/prd-{module1}.json" },
      { module: "{module2}", path: ".ralph/prd-{module2}.json" }
    ],
    progressTrackerPath: ".ralph/progress.txt",
    handedOffAt: "{ISO timestamp}"
  }
})
```

#### 9c. Final Verification (BLOCKING)

```
count = 0
FOR each module in modules[]:
  Read module feature.json
  IF module.handoff !== {} AND module.status === "handed-off":
    count++

IF count < modules.length:
  → BLOCKING ERROR: {modules.length - count} modules missing handoff
  → List the missing modules by name
  → DO NOT proceed to step 10
  → Return to 9a for missing modules only

IF count === modules.length:
  ba-writer.updateStatus({feature_id}, "handed-off")
  Display: "✓ Handoff complet: {count}/{modules.length} modules avec handoff valide"
```

Status journey: analyze → consolidate → **handed-off**

---

### 10. User Choice: Next Agent

Present development options after successful handoff:

```
═══════════════════════════════════════════════════════════════
  ✓ HANDOFF COMPLETE - {application_name}
═══════════════════════════════════════════════════════════════

Modules:   {count} ({names})
Strategy:  {strategy}
Files:     {total files across all modules}
Tasks:     {total tasks} ({core_count} CORE + {biz_count} business + {dev_count} development)
Complexity: {complexity}
Effort:    {total_days} days ({total_hours} hours)

Generated Artifacts:
  ✓ feature.json (master + per-module) - enhanced with handoff section
  ✓ .ralph/prd.json or .ralph/prd-{module}.json - derived from feature.json
  ✓ .ralph/progress.txt - comprehensive task tracker
  ✓ Implementation strategy selected: {strategy}

Next: Choose development approach
═══════════════════════════════════════════════════════════════
```

Ask via AskUserQuestion:

```
question: "Quelle approche de développement souhaitez-vous utiliser ?"
header: "Approche de développement"
options:
  - label: "Feature Full (Recommandé)"
    description: "Génération parallèle rapide (code + tests). Couverture 70-80%. ~{hours/3} heures."
  - label: "Ralph Loop"
    description: "Développement task-driven séquentiel. Couverture 95-100%. ~{hours} heures."
  - label: "Terminer le BA"
    description: "Finir l'analyse, développement manuel par l'équipe."
```

**Recommendations by complexity:**
- **Simple:** Feature Full (1-3 days) or Ralph Loop (2-4 days)
- **Medium:** Ralph Loop recommended (5-10 days), Feature Full possible (3-6 days)
- **Complex:** Ralph Loop strongly recommended (10-20 days), Feature Full (8-12 days)

---

## MODE SUPPORT

### Standard Mode

Full handoff with all implementation details:
- All 7 file categories
- Complete BR-to-code mapping
- Full API endpoint summary
- Detailed prd.json
- Comprehensive progress tracker

### Micro Mode (use_case = micro)

Simplified handoff with minimal scope:
- Only essential CRUD entity + controller
- 3 core SeedData entries (omit some optional ones)
- Basic prd.json with simplified sections
- Lightweight progress.txt
- Auto-suggest Feature Full for rapid development

### Delta Mode (use_case = refactoring)

Focused handoff for changes:
- Only affected modules listed
- Reuse existing implementation patterns
- Highlight what changed vs baseline
- Update only affected prd.json sections
- Progress tracker shows only delta tasks

---

## OUTPUT

> **FORBIDDEN:** Do NOT generate separate JSON files (specification.json, analysis.json, etc.).
> **ONLY:** feature.json is the mandatory JSON deliverable.
> **PLUS:** prd.json and progress.txt are additional working files.

This step enriches **feature.json** (master + per-module) with:
- **handoff** section: complexity, implementationStrategy, moduleOrder, filesToCreate (7 categories), brToCodeMapping, apiEndpointSummary, prdFiles
- **status:** "handed-off"

Also generates two working files:
- **.ralph/prd.json** (or .ralph/prd-{module}.json per module structure)
  - Derived entirely from feature.json
  - Single source of truth for development team
  - Includes all entities, use cases, business rules, API endpoints
  - Task breakdown and implementation sequence

- **.ralph/progress.txt**
  - Main development task tracker
  - Hierarchical structure (module → layer → tasks)
  - Checkboxes for progress tracking
  - Effort estimates per module
  - Cross-module integration tasks (if multi-module)

Next agent selection via user question:
1. **Feature Full** - Parallel rapid code generation (70-80% coverage)
2. **Ralph Loop** - Sequential task-driven development (95-100% coverage)
3. **End BA** - Manual development by team

---

## EXAMPLES & TEMPLATES

### Example: Simple Single Module (Orders)

**Feature:** Order Management
**Module:** Orders (1 entity, 2 use cases, 3 BRs)

**Output:**
- feature.json with handoff section
- .ralph/prd.json (single consolidated file)
- .ralph/progress.txt (~150 lines, 20-30 tasks)

Strategy: Module by module (only 1 module)

### Example: Medium Multi-Module (E-Commerce)

**Feature:** E-Commerce Platform
**Modules:** Customers (4 entities), Products (6 entities), Orders (8 entities), Invoices (3 entities)

**Dependencies:**
- Customers: Foundation (no deps)
- Products: Foundation (no deps)
- Orders: Depends on Customers + Products
- Invoices: Depends on Orders

**Output:**
- feature.json (master + 4 module features) with handoff sections
- User chooses: per-module prd (.ralph/prd-customers.json, .ralph/prd-products.json, etc.) or consolidated (.ralph/prd.json)
- .ralph/progress.txt (~400 lines, 100+ tasks)
- Module order: Customers, Products → Orders → Invoices (topological)

Strategy options: Module by module (recommended), Layer by layer, Hybrid

### Example: Complex Multi-Module (ERP)

**Feature:** Enterprise Resource Planning
**Modules:** Accounting, Sales, Purchasing, Inventory, HR, Finance (20+ entities total, 50+ use cases, 100+ BRs)

**Output:**
- feature.json (master + 6 module features) with handoff sections
- Per-module prd.json (recommended for complexity management)
- .ralph/progress.txt (~800+ lines, 200+ tasks)

Complexity: Complex (highest across all modules)
Strategy: Hybrid recommended (Foundation modules layer-by-layer, then dependent modules module-by-module)

---

## VALIDATION CHECKLIST

Before presenting handoff to user:

- [ ] Status verified: "consolidated"
- [ ] Implementation strategy selected or defaulted
- [ ] Complexity calculated for each module and overall
- [ ] filesToCreate: 7 categories complete, no free text
- [ ] **WIREFRAME TRACEABILITY:** Every frontend Page/DashboardPage has `linkedWireframes[]` referencing specification.uiWireframes[].screen
- [ ] **WIREFRAME ACCEPTANCE:** Every frontend Page/DashboardPage has `wireframeAcceptanceCriteria` describing expected layout
- [ ] brToCodeMapping: All business rules from analysis.businessRules[] mapped
- [ ] apiEndpointSummary: Exact copy from specification.apiEndpoints[]
- [ ] prd.json: Derived from feature.json, not independently generated
- [ ] prd.json: Includes all UCs, FRs, BRs, entities, API endpoints from source
- [ ] progress.txt: Hierarchical, all modules in topological order, 5 CORE SeedData per module
- [ ] progress.txt: Frontend tasks reference wireframe identifiers [wireframe: {screen}]
- [ ] Module order: Follows topological dependency graph
- [ ] feature.json updated: handoff section + status "handed-off"
- [ ] All paths use project namespace from .smartstack/config.json
- [ ] No invented requirements (everything traced to feature.json)
- [ ] User ready for next agent selection

---

## TROUBLESHOOTING

| Issue | Resolution |
|-------|-----------|
| Status ≠ "consolidated" | Stop. Return to step-04-consolidation.md. |
| No specification section | Cannot generate handoff without specification. Return to step-02-specify.md. |
| Missing apiEndpoints | Copy exact routes from specification.apiEndpoints[] (absolute rule). |
| BR not in analysis | Do not invent. Update feature.json analysis section. |
| Circular dependencies | Reorder modules or break circular dependency. Notify user. |
| prd.json too large | Use per-module structure instead of consolidated (multi-module). |
| Progress.txt tasks unclear | Ensure each task is atomic and independently assignable. |
| Module complexity unclear | Recalculate using entity count, UC count, BR count against thresholds. |

---

END OF STEP 5: HANDOFF
