---
name: step-00-init
description: Parse flags, detect context, verify MCP, define hierarchy (5 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}
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
```

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

---

## 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:
    {context_code}      = prd.project.context          (e.g., "business")
    {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 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 context), 4 (hierarchy), 5 (challenge questions)
  Jump to section 3 (MCP verify) → then section 6 (determine needs, already set) → section 9 (summary)
```

---

## 2. Detect SmartStack Context

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:**
- `{context_code}`: business (default), platform, personal
- `{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 context detection 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 (5 Levels)

> **BLOCKING RULE:** SmartStack uses a 5-level navigation hierarchy:
> **Context → Application → Module → Section → Resource**
>
> **Every module MUST have at least one section.** A module without sections produces an incomplete navigation tree, broken seed data, and missing frontend routes.

### 4a. Validate Application Level

Load and execute application question from `references/challenge-questions.md` section 4a.

### 4b. Validate Module Level

Load and execute module question from `references/challenge-questions.md` section 4b.

### 4c. Define Sections (MANDATORY — at least one)

Load and execute section questions from `references/challenge-questions.md` section 4c (includes validation and storage format).

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

```
{context_code} → {app_name} ({app_code}) → {module_code} → [{sections[].code}]
Routes: /{context_code}/{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. 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
```

These values are propagated to:
- **step-01 (Analyze):** Guide code exploration focus
- **step-02 (Plan):** Inform layer mapping (e.g., workflow → needs /workflow skill)
- **step-03 (Execute):** Entity scaffolding with correct properties and relationships

---

## 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 → restore state from 00-context.md → SKIP to next step
```

---

## 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}
Context: {context_code} → {app_name} → {module_code} → {sections[].code}
Entities: {entities} | Complexity: {module_complexity} | Deps: {has_dependencies}
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`
