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

**ULTRA THINK about existing code structure. Pay special attention to seed data files — they may exist but be INCOMPLETE (missing sections, permissions, or roles for the new scope). An existing file does NOT mean it's complete.**

**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/parallel-execution.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 `/business-analyse-develop -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 — ONLY entities from PRD tasks):
     For each entity_name in entities[]:
       - Glob("**/Domain/Entities/**/{entity_name}.cs") → exists? (create vs modify)
       - Glob("**/Infrastructure/Persistence/Configurations/**/{entity_name}Configuration.cs") → exists?
       - Glob("**/Application/Services/**/*{entity_name}*Service.cs") → exists?
       - Glob("**/Api/Controllers/**/*{entity_name}*Controller.cs") → exists?
     Module-level checks (once):
       - Glob("**/Infrastructure/Persistence/Seeding/Data/{module_code}/**/*SeedData*.cs") → existing seed data?
       - Glob("src/pages/**/{module_code}/**/*.tsx") → existing pages?
     Do NOT scan the full codebase — only verify files relevant to PRD tasks.
     Result: mark each PRD task as "create" (file missing) or "modify" (file exists).

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

  SKIP: Full Agent tool parallel 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: Parallel Agent Exploration

> **Protocol:** See `references/parallel-execution.md`

Launch 2-3 Explore agents in parallel (single message):

```
Agent(subagent_type='Explore', model='sonnet',
  prompt='Scan backend for module {module_code}: entities, EF configs, services,
   DTOs, validators, controllers in Domain/ + Infrastructure/ + Application/ + Api/')

Agent(subagent_type='Explore', model='sonnet',
  prompt='Scan frontend for module {module_code}: pages, components, hooks,
   i18n files, route definitions in src/pages/ + src/components/ + src/locales/')

Agent(subagent_type='Explore', model='sonnet',
  prompt='Read context artifacts for module {module_code}: .ralph/prd-{module_code}.json,
   docs/business/**/feature.json → extract sections, entities, rules, permissions, ACs')

# All 3 launched in a single message → agent principal aggregates results
```

---

## 3. Seed Data Inventory (CONTENT-AWARE)

> **CRITICAL:** Finding that a seed file EXISTS is not enough. You must READ it and compare its content against the target scope to determine if it needs MODIFICATION.

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

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

### 3b. Seed Data Content Analysis (if files exist)

For each existing seed file, READ IT and extract what's already covered:

```
NavigationModuleSeedData.cs:
  → Extract existing section codes (from GetSectionEntries or similar methods)
  → Extract existing resource codes (from GetResourceEntries or similar methods)
  → Compare against {sections} from step-00
  → Mark MISSING sections/resources → these need "modify" action

Permissions.cs:
  → Extract existing permission constants (Read, Create, Update, Delete per section)
  → Compare against {sections} from step-00
  → Mark sections WITHOUT permissions → these need "modify" action

PermissionsSeedData.cs:
  → Extract existing permission paths from HasData() entries
  → Mark missing paths → "modify"

RolesSeedData.cs:
  → Extract existing role-permission mappings
  → Mark missing mappings for new sections → "modify"

{App}SeedDataProvider.cs:
  → Check which seed methods are called (SeedNavigationAsync, SeedPermissionsAsync, etc.)
  → Check if new module/section seed classes are referenced → "modify" if missing
```

**Result:** For each seed file, set action to:
- `"skip"` — file exists AND covers ALL target sections/entities
- `"modify"` — file exists BUT is MISSING entries for new sections/entities
- `"create"` — file does not exist

> **Common mistake:** Marking seed files as "skip" just because the file exists. A `NavigationModuleSeedData.cs` that covers sections A and B MUST be marked "modify" if the task adds section C.

---

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