---
name: step-02-plan
description: Create layer-by-layer execution plan with skill/MCP mapping per file
model: opus
prev_step: steps/step-01-analyze.md
next_step: steps/step-03-execute.md
---

# Step 2: Plan

**ULTRA THINK about the execution strategy. For each file: is it CREATE (new) or MODIFY (exists but needs additions for new sections/entities)? Seed data files are frequently marked "skip" by mistake when they should be "modify" — verify this explicitly.**

**Goal:** Create a precise, file-by-file plan. Each file mapped to a SKILL or MCP tool.

## LOAD CONDITIONALLY

Read `references/smartstack-layers.md` for layer execution rules, skill/MCP mapping, planning templates, and delegate mode fast path.
> **CONTEXT NOTE:** This file stays in context and is reused by step-03. Do NOT re-read it there.

---

## 0. Delegate Mode Fast Path (if delegate_mode)

> **When called via `/business-analyse-develop -d`, PRD tasks already define the scope. Map directly to layers.**

```
IF delegate_mode:
  Read PRD from {delegate_prd_path}

  Map each PRD task to a layer based on task.category:
    domain          → Layer 0
    infrastructure  → Layer 0
    seedData        → Layer 1
    application     → Layer 2
    api             → Layer 2
    frontend        → Layer 3
    test            → inline (Layer 2 backend tests, Layer 3 frontend tests)

  For each task:
    file_path    = task.files_changed.created[0] (primary file)
    action       = "create" (default for delegate mode)
    tool         = infer from category:
                   domain/infrastructure → MCP scaffold_extension
                   api → /controller skill or MCP scaffold_extension
                   seedData → MCP generate_permissions + ref core-seed-data.md
                   frontend → /ui-components skill + MCP scaffold_api_client + MCP scaffold_routes
                   test → MCP scaffold_tests
    acceptance_criteria = task.acceptance_criteria

  Use task._seedDataMeta, _frontendMeta, _migrationMeta for enriched context.

  SKIP: User checkpoint (section 6) — auto_mode implied
  Jump to section 5 (Estimated Commits) → NEXT STEP
```

---

## 1-3. Layer Mapping, Skill Assignment, Parallelization

> **Reference:** All planning procedures are now in `references/smartstack-layers.md` (already loaded above):
> - Layer assignment matrix (Domain/Infrastructure/Seed/Application/API/Frontend/DevData)
> - Entity definition template (tenantMode, codePattern, fkFields, ACs)
> - Skill/MCP assignment table (per file, per layer)
> - Layer 0/1/2/3/4 file lists with tools (see "Planning Template" section)
> - FK field guidance (EntityLookup + backend ?search= parameter)
> - Parallelization strategy (Agent tool within Layer 2/3 for multi-entity)
> - Delegate mode fast path (PRD task mapping to layers)

```
Layer 0: SEQUENTIAL (agent principal)
  → domain + infra + migration
  → dotnet build --no-restore (must pass)

Layer 1: SEQUENTIAL (agent principal)
  → seed data (navigation, permissions, roles)
  → dotnet build (must pass)

Layer 2: PARALLEL WITHIN LAYER (Agent tool if multi-entity)
  → services + controllers
  → dotnet build (must pass)
  → backend tests inline (scaffold + run + fix max 3)

Layer 3: PARALLEL WITHIN LAYER (Agent tool if multi-entity)
  → pages + i18n + documentation
  → compliance gate (must pass)
  → frontend tests inline (scaffold + run + fix max 3)

Layer 4: OPTIONAL (agent principal)
  → DevData seeder
```

If economy_mode: ALL layers sequential, agent principal only.

---

## 4. Dependency Validation

Verify the plan respects dependencies:

```
- Migration AFTER EF configs (always)
- Seed data AFTER migration (Layer 1 depends on Layer 0 build gate)
- Application services AFTER domain entities (always)
- Code generator service AFTER entity + EF config (needs DbSet for sequence query)
- CreateDto adjustments AFTER code pattern decision (remove Code property if auto-generated)
- Controllers AFTER application services (always)
- Backend tests AFTER services + controllers (inline in Layer 2)
- Frontend AFTER API controllers (API contract needed)
- Frontend tests AFTER pages created (inline in Layer 3)
- Build gate between EVERY layer (must pass): Layer 0 → 1 → 2 → 3 → 4
```

### 4b. Module Code Collision Guard (BLOCKING)

```
IF appCode == moduleCode:
  BLOCK — module_code identique à app_code cause des segments doublés (e.g. /hr/hr).
  Suggestion : "{appCode}-core", "{appCode}-management"
  ASK user pour un module_code différent.
```

---

## 5. Estimated Commits

```
feat({module}): [domain+infra] {description}
feat({module}): [seed] navigation, permissions, roles
feat({module}): [app+api] {description}
test({module}): backend unit and integration tests
feat({module}): [frontend] pages, routes, i18n, documentation
test({module}): frontend form tests
feat({module}): [devdata] test data for development  # if applicable
```

**Maximum 7 commits per module.**

---

## 6. User Checkpoint (if NOT auto_mode)

Present the plan and ask for validation:

```yaml
questions:
  - header: "Plan"
    question: "Does this execution plan look correct?"
    options:
      - label: "Approve and execute (Recommended)"
        description: "Proceed with the plan as described"
      - label: "Modify plan"
        description: "I want to adjust some items"
      - label: "Cancel"
        description: "Abort the workflow"
    multiSelect: false
```

If "Modify plan": ask what to change, update plan, re-present.
If "Cancel": abort workflow.

---

## 7. Save Output (if save_mode)

Write to `{output_dir}/02-plan.md` with the complete plan.

---

## 8. Create Task List

> **Visibility:** TaskCreate generates the grouped progress UI with checkboxes.
> This makes APEX execution trackable and predictable for the user.

After plan is finalized (auto_mode or user approved):

### Task Creation Rules

1. Create ONE task per layer (Layer 0-4)
2. For multi-entity layers (2, 3): create ONE sub-task per entity within the layer
3. Add build/test gate tasks after each layer
4. Set dependencies via `addBlockedBy` to enforce layer ordering

### Metadata Schema

> **All APEX tasks use this metadata schema for context recovery after compression:**

```typescript
// Schema for ALL APEX tasks
{
  layer?: number,           // 0-4, absent for meta/examine/finding tasks
  apex_step?: string,       // "02-plan", "03-execute", etc (meta task only)
  entities?: string[],      // entities concerned
  tools?: string[],         // MCP tools/skills used
  build_gate?: "pending" | "pass" | "fail",
  files_created?: string[], // updated via TaskUpdate after creation
  module?: string,          // module code (meta task only)
  app?: string,             // app name (meta task only)
  flags?: object            // APEX flags (meta task only)
}
```

### Task Template

```
# APEX Progress Tracker (recovery anchor)
TaskCreate(subject: "APEX Progress",
  description: "Module: {module_code}, App: {app_name}, Entities: {entities list}. Current: step-02 (Plan)",
  activeForm: "Planning execution",
  metadata: {
    apex_step: "02-plan",
    module: "{module_code}",
    app: "{app_name}",
    entities: ["{entity1}", "{entity2}"],
    flags: { auto: {auto_mode}, economy: {economy_mode}, examine: {examine_mode} }
  })

# Layer 0 — Domain + Infrastructure
TaskCreate(subject: "Layer 0: Domain + Infrastructure",
  description: "Entities: {entity1} ({tenantMode}), {entity2} ({tenantMode}).
Files: Domain/Entities/*.cs, Infrastructure/Persistence/Configs/*.cs, Migration.
Tools: MCP scaffold_extension (type: entity). EF config: manual per smartstack-api.md. MCP suggest_migration.
Gate: dotnet build --no-restore. ACs: {relevant ACs}.",
  activeForm: "Creating domain entities",
  metadata: { layer: 0, entities: [...], tools: ["scaffold_extension", "suggest_migration"], build_gate: "pending", files_created: [] })

# Layer 1 — Seed Data
TaskCreate(subject: "Layer 1: Seed Data",
  description: "Navigation, permissions, roles, provider for {module_code}.
Files: Seeding/Data/{Module}/*.cs, {App}SeedDataProvider.cs.
Tools: MCP generate_permissions. Ref: core-seed-data.md.
Gate: dotnet build. ACs: {relevant ACs}.",
  activeForm: "Generating seed data",
  metadata: { layer: 1, entities: [...], tools: ["generate_permissions"], build_gate: "pending", files_created: [] })
TaskUpdate(taskId: layer1_id, addBlockedBy: [layer0_id])

# Layer 2 — Backend (1 task per entity if multi-entity, 1 task if single)
IF multi-entity:
  FOR EACH entity:
    TaskCreate(subject: "Layer 2: {Entity} backend",
      description: "Service + DTO + Controller + Validator for {Entity}.
Files: Application/Services/{Entity}Service.cs, Application/DTOs/{Entity}*.cs, Api/Controllers/{Entity}Controller.cs.
Tools: MCP scaffold_extension, /controller skill. Gate: dotnet build.
ACs: {relevant ACs for this entity}.",
      activeForm: "Building {Entity} backend",
      metadata: { layer: 2, entities: ["{Entity}"], tools: ["scaffold_extension", "controller"], build_gate: "pending", files_created: [] })
    TaskUpdate(taskId: entity_task_id, addBlockedBy: [layer1_id])

# Layer 2 Tests
TaskCreate(subject: "Layer 2: Backend tests",
  description: "Unit + integration tests for all entities.
Tools: MCP scaffold_tests (unit + integration). Gate: dotnet test.",
  activeForm: "Running backend tests",
  metadata: { layer: 2, tools: ["scaffold_tests"], build_gate: "pending" })

# Layer 3 — Frontend (1 task per entity if multi-entity)
IF multi-entity:
  FOR EACH entity:
    TaskCreate(subject: "Layer 3: {Entity} frontend",
      description: "API client, pages (List/Detail/Create/Edit), i18n (4 langs), routes for {Entity}.
Files: src/pages/{App}/{Module}/{Entity}*.tsx, src/i18n/locales/*/{module}.json.
Tools: MCP scaffold_api_client, MCP scaffold_routes, /ui-components skill.
Gate: npm run typecheck + 5 compliance gates. ACs: {relevant ACs}.",
      activeForm: "Building {Entity} frontend",
      metadata: { layer: 3, entities: ["{Entity}"], tools: ["scaffold_api_client", "scaffold_routes", "ui-components"], build_gate: "pending", files_created: [] })
    TaskUpdate(taskId: entity_task_id, addBlockedBy: [layer2_tests_id])

# Layer 3 Tests + Compliance
TaskCreate(subject: "Layer 3: Frontend tests + compliance",
  description: "Form tests (Create/Edit .test.tsx), typecheck, 5 compliance gates.
Tools: Vitest + React Testing Library. Gate: npm run test + typecheck.",
  activeForm: "Running frontend tests",
  metadata: { layer: 3, tools: ["vitest"], build_gate: "pending" })

# Layer 4 (if applicable)
IF NOT foundation_mode AND devdata needed:
  TaskCreate(subject: "Layer 4: DevData",
    description: "Development test data seeder.
Files: Infrastructure/Persistence/Seeding/DevData/{Module}DevDataSeeder.cs.
Gate: dotnet build.",
    activeForm: "Creating dev data",
    metadata: { layer: 4, tools: [], build_gate: "pending", files_created: [] })

# Post-execution
TaskCreate(subject: "eXamine: Validation + POST-CHECKs",
  description: "MCP validate_conventions, build, POST-CHECKs (see post-checks.md), acceptance criteria.
Tools: MCP validate_conventions, validate_security, validate_frontend_routes.",
  activeForm: "Validating conventions",
  metadata: { tools: ["validate_conventions", "validate_security", "validate_frontend_routes"] })
```

### Economy Mode

IF economy_mode: Create the SAME tasks (for visibility), but no parallel agents — agent principal executes sequentially.

### Delegate Mode

IF delegate_mode: Create tasks from PRD task list, mapped to layers.

---

## NEXT STEP

Load `steps/step-03-execute.md`
