---
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

**ULTRA THINK about whether this is a NEW module (create from scratch) or an UPDATE to an existing module (add sections/resources/entities to existing code). This distinction drives every downstream decision — especially seed data, permissions, and roles.**

**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 input: `-a, -x, -s, -e, -r, -pr, -d {path}, --foundation`

| Flag | Sets | Force |
|------|------|-------|
| `-a` | auto_mode | — |
| `-x` | examine_mode | — |
| `-s` | save_mode | — |
| `-e` | economy_mode | — |
| `-r` | resume_mode | — |
| `-pr` | pr_mode | — |
| `-d {path}` | delegate_mode, delegate_prd_path | auto_mode, economy_mode |
| `--foundation` | foundation_mode | auto_mode |

**Special behaviors:** `-d {path}` enables delegate mode (extract context from PRD). `--foundation` generates ONLY entities + EF configs + migration (domain + infrastructure layers only).

---

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

When `-d {prd_path}` is used, extract all context from PRD file and skip sections 2, 4, 5:

**Extract from prd.json:**
- `{app_name}` = prd.project.application
- `{module_code}` = prd.project.module
- `{sections}` = infrastructure tasks → _seedDataMeta.coreSeedData.navigationSections (map to code/label/description/route/displayOrder/navigation)
- `{entities}` = domain tasks → extract entity names from descriptions
- `{code_patterns}` = feature.json entity patterns (or [] for heuristic fallback)
- `{module_complexity}` = heuristic from task count (≤10→"simple-crud", ≤20→"crud-rules", ≤30→"crud-workflow", >30→"complex")
- `{needs_seed_data}` = any seedData/infrastructure tasks exist
- `{needs_migration}` = any tasks with _migrationMeta
- `{has_dependencies}` = prd.tasks.some(t => t.dependencies.length > 0) ? "references" : "none"

**Fallback extraction (if prd.project is absent — e.g. PRD v3.0.0 with metadata format):**
- `{app_name}` = prd.metadata?.applicationCode || prd.project?.application
- `{module_code}` = prd.metadata?.moduleCode || prd.project?.module
- `{entities}` = prd.implementation?.filesToCreate?.domain?.filter(f => f.type === 'Entity').map(f => extractEntityName(f.path)) || domain tasks fallback
- `{sections}` = prd.implementation?.filesToCreate?.seedData?.filter(f => f.path.includes('NavigationSectionSeedData')).length > 0 ? extractSectionsFromSeedDataPaths(prd) : []
- `{needs_seed_data}` = (prd.implementation?.filesToCreate?.seedData?.length || 0) > 0
- `{needs_migration}` = (prd.implementation?.filesToCreate?.infrastructure?.length || 0) > 0

**Specification Files Loading (if prd.specificationFiles present):**

```javascript
if (prd.specificationFiles) {
  const specsDir = path.dirname(delegate_prd_path); // .ralph/
  const specFiles = prd.specificationFiles;

  // Store loading plan for layer-specific consumption
  specification_loading_plan = {
    layer0_domain:   [specFiles.entities],
    layer1_seed:     [specFiles.entities, specFiles.permissions],
    layer2_backend:  [specFiles.rules, specFiles.usecases],
    layer3_frontend: [specFiles.screens, specFiles.usecases]
  };

  // Verify all companion files exist
  for (const [layer, files] of Object.entries(specification_loading_plan)) {
    for (const file of files) {
      const filePath = path.join(specsDir, file);
      if (!fileExists(filePath)) {
        console.warn(`WARNING: Companion file missing for ${layer}: ${filePath}`);
      }
    }
  }
}
```

Each layer step (step-03a through step-03d) will load its companion files at the start. This provides full BA specifications (entity attributes, BR formulas, UC steps, screen columns) without loading the entire spec corpus.

**PRD Quality Gate (delegate mode — BLOCKING):**

> Validate that PRD file paths are valid C# identifiers BEFORE starting execution.
> Invalid entity names (French with spaces/apostrophes/accents) cause CS1001 build errors
> that waste 3+ retry iterations before being correctly classified.

```javascript
// Extract all file paths from PRD
const filesToCreate = prd.$version === '4.0.0' ? prd.expectedFiles : prd.implementation?.filesToCreate;
if (filesToCreate) {
  const invalidPaths = [];
  for (const [category, files] of Object.entries(filesToCreate)) {
    for (const file of (files || [])) {
      const filePath = file.path || file;
      // Extract filename (without extension) from path
      const fileName = filePath.split('/').pop().replace(/\.(cs|tsx|ts|json)$/, '');
      // Check for illegal characters in C# identifiers
      if (/[\s'àâäéèêëïîôùûüçÀÂÄÉÈÊËÏÎÔÙÛÜÇ]/.test(fileName)) {
        invalidPaths.push({ category, path: filePath, fileName });
      }
    }
  }

  if (invalidPaths.length > 0) {
    console.error('BLOCKING — PRD QUALITY ERROR (not a code error):');
    console.error('The following file paths contain illegal C# identifier characters:');
    for (const p of invalidPaths) {
      console.error(`  ${p.category}: ${p.path} (invalid name: "${p.fileName}")`);
    }
    console.error('');
    console.error('FIX: Re-run /business-analyse-handoff which now includes entity name canonicalization.');
    console.error('     Or manually fix entity names in the PRD (strip accents, remove spaces/apostrophes, PascalCase).');
    console.error('');
    console.error('This is a PRD quality error (Category G), NOT a code generation error.');
    console.error('Do NOT attempt to generate code from this PRD — it will fail with CS1001.');
    STOP; // Do not proceed with invalid PRD
  }
}
```

**Jump to:** section 3 (MCP verify) → section 6 (determine needs) → section 9 (summary)

---

## 1c. Prompt Precision Guard

> **APEX executes, it does not explore.** If the prompt is too vague, redirect to `/business-analyse`.

**Score the prompt — count how many of these are present or inferable:**

| Element | Example | Weight |
|---------|---------|--------|
| Module name/code | "employees", "absence management" | 1 |
| At least 1 entity name | "Employee", "Absence" | 1 |
| At least 1 property/field | "FirstName, StartDate, Status" | 1 |
| Target application | "HR module", "HumanResources" | 0.5 |
| Section hint | "list", "dashboard", "approval" | 0.5 |

```
precision_score = sum of weights for elements found in task description

IF precision_score < 2:
  DISPLAY:
  ╔══════════════════════════════════════════════════════════════╗
  ║  ⚠ Prompt too vague for /apex                              ║
  ║                                                             ║
  ║  /apex needs precise features to execute in one shot.       ║
  ║  Your request looks more like a discovery/design task.      ║
  ║                                                             ║
  ║  Suggestions:                                               ║
  ║  1. Use /sketch to quickly design your module (~2 min)      ║
  ║  2. Use /business-analyse for full analysis (40+ questions) ║
  ║  3. Rewrite your prompt with entities and fields, e.g.:     ║
  ║     /apex add employees section with Employee entity        ║
  ║     (FirstName, LastName, Email) to HumanResources module   ║
  ╚══════════════════════════════════════════════════════════════╝
  → STOP — do NOT proceed to section 2
```

---

## 2. Detect SmartStack Application

Scan project: Glob("*.sln"), Glob("docs/business/**/*"), Glob(".ralph/prd-*.json"), Glob("src/pages/**/*.tsx")

**Infer from task description:** {app_name}, {module_code}, {sections}
**From 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

Reference `references/challenge-questions.md` for 4-level structure (Application → Module → Section → Resource), validation rules, and challenge questions 4a-4c.

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

**Resources:** OPTIONAL — only define if explicitly mentioned or inferred from task/feature.json (export, import, bulk actions).

### 4f. Naming Derivation Rules (DETERMINISTIC)

All naming variants are derived from {app_name}, {module_code}, {sections}. Do NOT invent names.

| Source | Derivation | Example |
|--------|-----------|---------|
| {app_name} | kebab: lowercase, hyphen-separated | `human-resources` |
| {app_name} | PascalCase | `HumanResources` |
| {module_code} | already kebab | `employee-management` |
| {module_code} | PascalCase: remove hyphens, capitalize | `EmployeeManagement` |
| {sections[].code} | already kebab | `employees` |
| {sections[].code} | PascalCase | `Employees` |
| NavRoute | `{app_name_kebab}.{module_code}.{section_code}` (dots) | `human-resources.employee-management.employees` |
| API route | resolved dynamically by [NavRoute] from DB | N/A |
| Permission | `{app_name_kebab}.{module_code}.{section_code}.{action}` | `human-resources.employee-management.employees.read` |

Call `mcp__smartstack__validate_conventions` after computing derivations. Fix any errors BEFORE step-01.

---

## 5. Collect Technical Parameters

Rapid technical parameter collection — load and execute questions from `references/challenge-questions.md`:
- **5a:** Entity scope & relationships
- **5b:** Dependency auto-detection (NO question — agent scans codebase and infers from {entities})
- **5b-bis:** Key properties (question kept — user may have specific field requirements)
- **5c:** Code generation strategy

**Skip 5c if:**
- `delegate_mode = true` (PRD defines patterns)
- `foundation_mode = true` (code strategy later)
- `feature.json` exists AND all entities have `codePattern` defined

**If feature.json covers SOME entities:** Only ask for entities without `codePattern`, merge responses.

**Store responses:**
```
{entities}, {module_complexity}, {has_dependencies}, {key_properties}, {code_patterns}
```
Propagated to: step-01 (code focus), step-02 (layer mapping), step-03 (scaffolding)

---

## 5e. Scope Complexity Guard

**Design:** `/apex` handles 1 module at a time. Use `/business-analyse-develop` for multi-module projects.

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

**Rules:**
- `delegate_mode (-d)` → SKIP guard (business-analyse-develop handles scope per module)
- `app_count > 1` → Warning: use `/business-analyse-develop` or split requests
- `entity_count > 6` → BLOCKING: max 6 entities. Solutions: `/business-analyse-develop`, `/apex -d`, or split manually
- `scope_score > 8` → WARNING: ask user to split or use `/business-analyse-develop`

**Recommended Scope:**
| Metric | Safe | Warning | Blocking |
|--------|------|---------|----------|
| Applications | 1 | 1 | >1 |
| Entities | 1-4 | 5-6 | >6 without -d |
| Sections | 1-3 | 4-5 | >5 without -d |

---

## 6. Determine Needs

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

---

## 7. Resume Mode (if -r)

Read latest task directory in `.claude/output/apex/`:
- **If state.json exists:** resume step-03 at next uncompleted layer (skip completed)
  - **Delegate context recovery:** If `state.delegate_mode === true`:
    1. Restore `{delegate_prd_path}` from `state.delegate_prd_path`
    2. Restore `{app_name}`, `{module_code}`, `{sections}`, `{entities}` from state
    3. Re-read PRD at `{delegate_prd_path}` to rebuild `{specification_loading_plan}`:
       ```javascript
       const prd = readJSON(state.delegate_prd_path);
       if (prd.specificationFiles) {
         const sf = prd.specificationFiles;
         specification_loading_plan = {
           layer0_domain:   [sf.entities],
           layer1_seed:     [sf.entities, sf.permissions],
           layer2_backend:  [sf.rules, sf.usecases],
           layer3_frontend: [sf.screens, sf.usecases]
         };
       }
       ```
    4. Set `{delegate_mode} = true` — companion spec loading will work in remaining layers
- **Else if 00-context.md exists:** restore step-00 state, re-derive post-step-00 from git + files
- **Else:** full re-derive from git history + files

---

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

Generate task_id → create `.claude/output/apex/{task_id}/` → write `00-context.md` with timestamp, state, flags, hierarchy, 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} | PRD: {prd_path||none} | Feature: {feature_path||none}
Flags: {active_flags} | MCP: {available|degraded} | Needs: {migration/seed/workflow/notification}
Specs: {specification_loading_plan ? 'companion files available (layer-specific loading)' : 'none'}
NEXT STEP: step-01-analyze
```

