---
name: step-01-analyze
description: Explore existing code to understand what exists — do NOT plan yet
model: opus
prev_step: steps/step-00-init.md
next_step: steps/step-02-plan.md
---

# Step 1: Analyze

**Goal:** Understand what EXISTS in the codebase. Pure exploration, NO planning.

## LOAD CONDITIONALLY

- **ALWAYS** read `references/smartstack-api.md` — BaseEntity API, entity/config/controller patterns
  > **CONTEXT NOTE:** This file stays in context and is reused by step-03. Do NOT re-read it there.
- If NOT `{economy_mode}`: read `references/agent-teams-protocol.md`

---

## 0. Fresh Project Detection (Early Exit)

```
IF .smartstack/init-state.json exists:
  Read it → check if project was recently initialized
  Glob("src/**/Entities/**/*.cs") → count entity files

  IF entity count == 0 AND no PRD AND no feature.json:
    → SKIP full code exploration (sections 2-3)
    → Declare: "Fresh project — all elements need to be CREATED"
    → Jump directly to section 4 (Gap Analysis) with all items marked "create"
```

This saves ~2 minutes of Glob searches on an empty project.

---

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

> **When called via `/ralph-loop -d`, PRD tasks provide pre-computed scope. Reduce exploration to verification only.**

```
IF delegate_mode:
  Read PRD from {delegate_prd_path} (already loaded in step-00)

  1. Extract entity list from domain tasks:
     entities[] = prd.tasks.filter(category == 'domain').map(entity name from description)

  2. Extract FK relationships from frontend tasks with _frontendMeta:
     fkFields[] = _frontendMeta.fkFields[] (e.g., ["DepartmentId→Department", "CompanyId→Company"])

  3. Determine tenant modes per entity:
     IF feature.json exists at {feature_path}:
       Read entity definitions → extract tenantMode per entity
     ELSE:
       Default all entities to tenantMode: "strict"

  4. Read feature.json for wireframes/componentMapping if {feature_path} exists:
     → enriches frontend generation in step-03

  5. Perform LIGHTWEIGHT code exploration (verification only):
     - Glob("**/Domain/Entities/**/{module_code}/**/*.cs") → what already exists?
     - Glob("**/Infrastructure/Persistence/Seeding/Data/**/*SeedData*.cs") → existing seed data?
     - Glob("src/pages/**/{module_code}/**/*.tsx") → existing pages?
     → Only to determine create vs modify vs skip (NOT deep analysis)

  6. Gap Analysis: Mark all PRD tasks as "create" unless existing code found

  SKIP: Full Agent Teams exploration (section 2), challenge question follow-up
  Jump to section 5 (Gap Analysis summary) → section 7 (Analysis Summary)
```

---

## 1. Context Sources

Read available context (in order of priority):

| Source | Action |
|--------|--------|
| PRD (`{prd_path}`) | Extract: filesToCreate, brToCodeMapping, permissionMatrix, acceptance criteria |
| Feature.json (`{feature_path}`) | Extract: module structure, business rules, entity definitions, permissions |
| Task description only | Rely on task description and code exploration |

---

## 2. Code Exploration

### If economy_mode: Direct Tools

```
Backend:
- Glob("**/Domain/Entities/**/{module_code}/**/*.cs")
- Glob("**/Infrastructure/Persistence/Configurations/**/{module_code}/**/*.cs")
- Glob("**/Application/Services/**/{module_code}/**/*.cs")
- Glob("**/Api/Controllers/**/*{module_code}*Controller.cs")
- Glob("**/Infrastructure/Persistence/Seeding/Data/{module_code}/**/*.cs")

Frontend:
- Glob("src/pages/**/{module_code}/**/*.tsx")
- Glob("src/components/**/{module_code}/**/*.tsx")

MCP:
- mcp__smartstack__api_docs → existing API surface
- mcp__smartstack__analyze_extension_points → React extension points
```

### If NOT economy_mode: Agent Teams

> **Protocol:** See `references/agent-teams-protocol.md`

```
TeamCreate("apex-analyze", description: "Scan SmartStack project for existing code")

Spawn 3 teammates (subagent_type: "Explore", model: "sonnet"):

1. scan-backend:
   "Scan backend for module {module_code}: entities, EF configs, services,
    DTOs, validators, controllers in Domain/ + Infrastructure/ + Application/ + Api/"

2. scan-frontend:
   "Scan frontend for module {module_code}: pages, components, hooks,
    i18n files, route definitions in src/pages/ + src/components/ + src/locales/"

3. scan-context:
   "Read context artifacts for module {module_code}: .ralph/prd-{module_code}.json,
    docs/business/**/feature.json → extract sections, entities, rules, permissions, ACs"

Wait for all 3 → aggregate results → shutdown → TeamDelete("apex-analyze")
```

---

## 3. Seed Data Inventory

```
Glob("**/Seeding/Data/{module_code}/*SeedData.cs")
Glob("**/Seeding/*SeedDataProvider.cs")
```

Identify: NavigationModuleSeedData, PermissionsSeedData, RolesSeedData, SeedConstants, IClientSeedDataProvider (+ DI registration).

---

## 4-7. Analysis Methods & Validation

> **Reference:** Load `references/analysis-methods.md` for detailed analysis procedures:
> - FK field detection (frontend EntityLookup + backend search support)
> - Tenant mode decision (strict/optional/scoped/none)
> - Code pattern detection (auto-generated strategies)
> - Gap analysis (exists/missing/modify classification)
> - Scope re-check (entity count validation)
> - Analysis validation checkpoint (user confirmation)
> - Analysis summary output format

---

## 8. Save Output (if save_mode)

Write to `{output_dir}/01-analyze.md` with analysis results.

---

## NEXT STEP

Load `steps/step-02-plan.md`
