---
name: step-00-init
description: Parse flags, detect application, verify MCP, define hierarchy (4 levels), challenge the need
model: sonnet
next_step: steps/step-01-analyze.md
---

# Step 0: Initialize

**Before anything else**, display the version banner:

```
═══════════════════════════════════════════════════════════════
  SmartStack APEX — v{{SMARTSTACK_VERSION}}
═══════════════════════════════════════════════════════════════
```

## LOAD SHARED

Read `_shared.md` for SmartStack detection patterns and MCP tools reference.

---

## 1. Parse Flags

Extract flags from the raw input:

```
Input: "{raw_input}"

Flags to detect: -a, -x, -s, -e, -r, -pr, -d {path}, --foundation
Remaining text after flag removal = {task_description}
```

**Defaults:**

```yaml
auto_mode: false
examine_mode: false
save_mode: false
economy_mode: false
pr_mode: false
resume_mode: false
delegate_mode: false
delegate_prd_path: null
foundation_mode: false
```

**If `-d {path}` detected:** set `delegate_mode = true`, `delegate_prd_path = {path}`, force `auto_mode = true`, `economy_mode = true`.

**If `--foundation` detected:** set `foundation_mode = true`, force `auto_mode = true`. Foundation mode generates ONLY entities + EF configs + migration (domain + infrastructure layers). Skip application/api/frontend/tests.

---

## 1b. Delegate Mode Fast Path (if -d)

> **When `/ralph-loop` invokes `/apex -d {prd_path}`, all context is extracted from the PRD file.**
> Skip interactive sections (hierarchy definition, challenge questions).

```
IF delegate_mode:
  Read prd.json from {delegate_prd_path}

  Extract context:
    {app_name}          = prd.project.application       (e.g., "HumanResources")
    {module_code}       = prd.project.module            (e.g., "EmployeeManagement")
    {prd_path}          = {delegate_prd_path}
    {feature_path}      = prd.source.feature_json_path  (if exists)

  Extract sections from infrastructure tasks with _seedDataMeta:
    Find task where _seedDataMeta.coreSeedData.navigationSections exists
    {sections} = _seedDataMeta.coreSeedData.navigationSections[]
    → map to: { code, label, description, route, displayOrder, navigation }

  Extract entities from domain tasks:
    {entities} = prd.tasks.filter(t => t.category == 'domain').map(t => entity name from t.description)

  Extract code patterns from feature.json (if available):
    IF {feature_path} exists:
      Read feature.json → for each entity with codePattern defined:
        {code_patterns}[] += { entity, strategy, prefix, digits, includeTenantSlug, separator }
    ELSE:
      {code_patterns} = []  # will use heuristic fallback in analysis-methods.md

  Extract complexity:
    {module_complexity} = heuristic from task count:
      <= 10 tasks → "simple-crud"
      <= 20 tasks → "crud-rules"
      <= 30 tasks → "crud-workflow"
      > 30 tasks  → "complex"

  Set needs:
    {needs_seed_data}    = prd.tasks.some(t => t.category == 'seedData' || t.category == 'infrastructure')
    {needs_migration}    = prd.tasks.some(t => t._migrationMeta != null)
    {has_dependencies}   = prd.tasks.some(t => t.dependencies.length > 0) ? "references" : "none"
    {key_properties}     = [] (extracted during step-01 from feature.json if available)

  SKIP sections 2 (detect application), 4 (hierarchy), 5 (challenge questions)
  Jump to section 3 (MCP verify) → then section 6 (determine needs, already set) → section 9 (summary)
```

---

## 2. Detect SmartStack Application

Scan the project to identify the SmartStack hierarchy:

```
1. Glob("*.sln") → confirm .NET project
2. Glob("docs/business/**/*") → list existing BA artifacts
3. Glob(".ralph/prd-*.json") → list existing PRDs
4. Glob("src/pages/**/*.tsx") → confirm frontend exists
```

**From task description, infer:**
- `{app_name}`: application name
- `{module_code}`: target module
- `{sections}`: sections being added/modified

**From existing artifacts:**
- `{prd_path}`: `.ralph/prd-{module_code}.json` if exists
- `{feature_path}`: `docs/business/{app}/{module}/business-analyse/*/feature.json` if exists

If hierarchy cannot be inferred → load application question from `references/challenge-questions.md`.

---

## 3. Verify MCP Availability

```
Call: mcp__smartstack__validate_conventions (quick connectivity test)

IF success → MCP available, proceed normally
IF failure → warn user, continue in degraded mode (manual tools only)
```

---

## 4. Define Navigation Hierarchy (4 Levels)

> **Reference:** Load `references/challenge-questions.md` for hierarchy rules and challenge questions:
> - 4-level hierarchy structure (Application → Module → Section → Resource)
> - Challenge questions (4a: Application, 4b: Module, 4c: Sections, 5a: Entities, 5b: Dependencies, 5c: Code Generation)
> - Validation rules (sections MUST have at least one entry)
> - Storage format for each level
> - Delegate mode skip (if -d)

### 4d. Resources (Optional)

If the task or feature.json mentions specific resources (export, import, bulk actions):
```
For each section, check if resources are needed.
Resources are OPTIONAL — only define if explicitly mentioned or inferred.
```

### 4e. Hierarchy Summary

Display before proceeding:

```
{app_name} ({app_code}) → {module_code} → [{sections[].code}]
Routes: /{app-kebab}/{module-kebab}/{section-kebab}
```

---

## 5. Challenge the Need

> **Objective:** Even without a formal Business Analysis (`/business-analyse`), the need MUST be challenged to avoid obvious gaps. This is a rapid scope validation — 3-4 targeted questions to ensure the developer has thought through the fundamentals.

### 5a. Entity Scope & Relationships

Load and execute entity questions from `references/challenge-questions.md` section 5a.

### 5b. Dependencies & Key Properties

Load and execute dependency questions from `references/challenge-questions.md` section 5b.

### 5c. Code Generation Strategy

Load and execute code generation questions from `references/challenge-questions.md` section 5c.

**Skip if:**
- `delegate_mode` is true (PRD defines code patterns)
- `foundation_mode` is true (code strategy comes later)
- `feature.json` exists AND all entities in `{entities}` have `codePattern` defined

**If feature.json covers SOME but not all entities:**
→ Only ask for entities without `codePattern` in feature.json
→ Merge feature.json patterns + user answers into `{code_patterns}`

### 5d. Store Responses

```yaml
{entities}: string[]            # Main entities to manage
{module_complexity}: string     # "simple-crud" | "crud-rules" | "crud-workflow" | "complex"
{has_dependencies}: string      # "none" | "references" | "unknown"
{key_properties}: string[]      # Key business properties mentioned by user
{code_patterns}: object[]       # Per-entity code generation config (from 5c or feature.json)
```

These values are propagated to:
- **step-01 (Analyze):** Guide code exploration focus + code pattern detection (uses `{code_patterns}` as Priority 1)
- **step-02 (Plan):** Inform layer mapping (e.g., workflow → needs /workflow skill)
- **step-03 (Execute):** Entity scaffolding with correct properties, relationships, and code generation strategy

---

## 5e. Scope Complexity Guard

> **Root cause (test-apex-007):** `/apex` was invoked with 3 applications and 7 entities.
> The model's context window saturated, causing: incomplete migrations, lost conventions,
> missing pages, unregistered i18n, forgotten DI registrations.
>
> `/apex` is designed for **incremental** development (1 module at a time).
> Multi-module projects should use `/ralph-loop` which calls `/apex -d` per module.

### Scope Detection

```
entity_count = {entities}.length
section_count = {sections}.length
app_count = number of DISTINCT applications detected in {task_description}
           (heuristics: "application X et application Y", "module X, module Y, module Z"
            with different app names, "3 apps", etc.)

scope_score = entity_count + (section_count * 0.5) + (app_count * 3)
```

### Guard Rules

```
IF delegate_mode (-d flag):
  → SKIP guard (ralph-loop already handles scope per module)

ELSE IF app_count > 1:
  → Warning: "Multiple applications detected ({app_count} apps, {entity_count} entities).
     /apex handles 1 module at a time. For multi-module projects, use:
     - /ralph-loop (automated: reads PRD, generates all modules sequentially)
     - Multiple /apex calls (manual: one /apex per module)

     To proceed, split your request:
       /apex -e add HR employee management
       /apex -e add CRM client management
       /apex -e add Project management"

ELSE IF entity_count > 6:
  → BLOCKING: "Too many entities ({entity_count}) for a single /apex invocation.
     Context window saturation causes: incomplete migrations, lost conventions,
     missing pages, unregistered i18n, forgotten DI registrations.
     Maximum: 6 entities without delegate mode (-d).

     Solutions:
       /ralph-loop (automated multi-module orchestration)
       /apex -d {prd_path} (delegate mode, called per module by ralph-loop)
       Split manually: /apex add {first 3-4 entities} → then /apex add {remaining}"
  → STOP execution

ELSE IF scope_score > 8:
  → WARNING: "Large scope detected ({entity_count} entities, {section_count} sections).
     /apex works best with ≤ 4 entities per invocation.
     Consider splitting into smaller iterations."

  AskUserQuestion:
    header: "Scope"
    question: "Le périmètre est large ({entity_count} entités). Réduire le scope ou continuer ?"
    options:
      - label: "Continue anyway"
        description: "Proceed with full scope (higher risk of omissions)"
      - label: "Split into iterations"
        description: "Focus on the first module/app, then run /apex again for the rest"
      - label: "Use /ralph-loop"
        description: "Switch to /ralph-loop for automated multi-module orchestration"

  IF "Split" → ask user which module to focus on first, update {entities}/{sections}
  IF "/ralph-loop" → display command to run, STOP execution

ELSE:
  → PASS (scope is manageable)
```

### Recommended Scope per /apex Invocation

| Metric | Safe | Warning | Blocking |
|--------|------|---------|----------|
| Applications | 1 | 1 (large) | >1 |
| Entities | 1-4 | 5-6 | >6 without -d |
| Sections | 1-3 | 4-5 | >5 without -d |
| Sub-resources | 0-2 | 3-4 | >4 without -d |

---

## 6. Determine Needs

```
needs_seed_data   = {sections}.length > 0 OR task mentions navigation/permissions/roles/seed
needs_migration   = {entities}.length > 0 OR task mentions entity/field/table/column/migration
needs_workflow    = {module_complexity} == "crud-workflow" OR task mentions workflow/email/approval
needs_notification = {module_complexity} in ["crud-workflow","complex"] OR task mentions notification/alert
```

---

## 7. Resume Mode (if -r)

```
IF resume_mode:
  Read .claude/output/apex/ → find latest task directory (by timestamp)

  IF state.json exists:
    → Read state.json for precise layer-level resume:
      completed_layers, completed_entities, files_created, build_gates, commits
    → Resume step-03 at NEXT uncompleted layer (skip completed layers entirely)
    → Re-derive remaining state variables from existing files + git log

  ELSE IF 00-context.md exists:
    → Restore state from 00-context.md (step-00 output only)
    → Re-derive post-step-00 state from git history + existing files

  ELSE:
    → Full re-derive from git history + existing files (slowest path)
```

---

## 8. Save Mode Setup (if -s)

```
IF save_mode:
  Generate task_id → create .claude/output/apex/{task_id}/ → write 00-context.md
  (timestamp, state variables, flags, hierarchy, challenge responses)
```

---

## 9. Display Context Summary

```
APEX INIT COMPLETE — v{{SMARTSTACK_VERSION}}
Task: {task_description}
Hierarchy: {app_name} → {module_code} → {sections[].code}
Entities: {entities} | Complexity: {module_complexity} | Deps: {has_dependencies}
Code: {code_patterns summary — e.g., "Employee:sequential(emp), Contract:year-seq(ctr)" or "all manual" or "none"}
PRD: {prd_path||none} | Feature: {feature_path||none} | Flags: {active_flags}
MCP: {available|degraded} | Needs: migration/seed/workflow/notification = {yes|no}
NEXT STEP: step-01-analyze
```

---

## NEXT STEP

Load `steps/step-01-analyze.md`
