---
name: step-02-execute
description: Execute ONE task with dependency checks and rich tracking
next_step: steps/step-03-commit.md
---

# Step 2: Execute Task

## YOUR TASK:

Execute exactly ONE task from prd.json. Do NOT batch multiple tasks.

**ULTRA THINK about the implementation.**

---

## EXECUTION RULES:

1. **ONE TASK ONLY** - Execute only `{current_task_description}`
2. **ATOMIC CHANGES** - Changes should be complete and working
3. **USE MCP** - Validate with SmartStack MCP as needed
4. **DOCUMENT** - Track what you're doing
5. **CHECK DEPENDENCIES** - Verify all dependencies are met before starting
6. **TRACK FILES** - Record every file created or modified

---

## EXECUTION SEQUENCE:

### 1. Verify Dependencies

**BEFORE starting, check all dependencies are satisfied:**

```javascript
const prd = readJSON('.ralph/prd.json');
const task = prd.tasks.find(t => t.id === {current_task_id});

for (const depId of task.dependencies) {
  const dep = prd.tasks.find(t => t.id === depId);
  if (!dep || dep.status !== 'completed') {
    echo `❌ BLOCKED: Task ${task.id} depends on task ${depId} (status: ${dep?.status || 'missing'})`;
    task.status = 'blocked';
    task.error = `Dependency task ${depId} not completed (${dep?.status})`;
    writeJSON('.ralph/prd.json', prd);
    STOP - return to step-01 to find next eligible task
  }
}
```

### 2. Mark Task as In-Progress

**Update prd.json immediately:**

```javascript
task.status = 'in_progress';
task.started_at = new Date().toISOString();
prd.updated_at = task.started_at;
writeJSON('.ralph/prd.json', prd);
```

### 3. Understand the Task

**ULTRA THINK:**

- What exactly needs to be done?
- What files need to be created/modified?
- What are the acceptance criteria? → `{current_task_criteria}`
- What patterns should be followed?
- What category is this? → `{current_task_category}`

**Category-specific guidance:**

| Category | MCP Tools | Patterns |
|----------|-----------|----------|
| `domain` | `validate_conventions` | Entity base class, IHasData, audit fields |
| `application` | `validate_conventions`, `scaffold_extension` | CQRS, MediatR, FluentValidation |
| `infrastructure` | `check_migrations`, `suggest_migration` | EF Core config, HasData seeding, IClientSeedDataProvider, SqlObjects |
| `api` | `scaffold_routes`, `validate_security` | Controller conventions, authorization, context-based folder hierarchy |
| `frontend` | `validate_frontend_routes`, `scaffold_frontend_extension` | React patterns, hooks, Layout wrapper |
| `i18n` | - | 4-language JSON structure |
| `test` | `scaffold_tests`, `analyze_test_coverage` | xUnit, test naming conventions |
| `validation` | `validate_conventions` | Build, test, lint checks |

**Infrastructure task guidance (MANDATORY directory conventions):**

When executing `infrastructure` category tasks, follow these rules strictly:

1. **Seed data files** MUST go under `Infrastructure/Persistence/Seeding/Data/{Module}/`
   - NEVER use `Infrastructure/Data/SeedData/` or `Data/SeedData/`
   - Each module gets 5 core files: NavigationModuleSeedData.cs, PermissionsSeedData.cs, RolesSeedData.cs, TenantSeedData.cs, UserSeedData.cs

2. **IClientSeedDataProvider** (client projects with `extensions` DbContext):
   - Generate at `Infrastructure/Persistence/Seeding/{AppPascalName}SeedDataProvider.cs`
   - Register in DI: `services.AddScoped<IClientSeedDataProvider, {AppPascalName}SeedDataProvider>()`
   - Must implement: SeedNavigationAsync, SeedPermissionsAsync, SeedRolePermissionsAsync
   - See `/application` skill step-03b-provider for the full pattern

3. **DevDataSeeder** for domain entity seed data:
   - Located at `Infrastructure/Persistence/Seeding/DevDataSeeder.cs`
   - Implements `IDevDataSeeder`, registered in DI

4. **Migrations** MUST all be in `Infrastructure/Persistence/Migrations/`
   - NEVER create subdirectories under Migrations/
   - Always use `-o Persistence/Migrations` flag with `dotnet ef migrations add`

5. **SQL Objects** go under `Infrastructure/Persistence/SqlObjects/`
   - `Functions/` for TVFs and scalar functions (.sql files)
   - Use `SqlObjectHelper.cs` for embedded resource loading
   - Use `CREATE OR ALTER` in SQL files for idempotency

**Frontend task guidance (MANDATORY Layout wrapper):**

When executing `frontend` category tasks, follow these rules strictly:

1. **Routes MUST be inside Layout wrapper** (CRITICAL - violating this breaks the entire UI shell)
   - All routes MUST be nested inside the appropriate context Layout component
   - `platform.*` → `<Route path="/platform" element={<AdminLayout />}>` children
   - `business.*` → `<Route path="/business" element={<BusinessLayout />}>` children
   - `personal.*` → `<Route path="/personal/myspace" element={<UserLayout />}>` children
   - **If routes are placed OUTSIDE the layout wrapper: header, sidebar, and AvatarMenu will NOT render**
   - NEVER create flat routes at the top level of `<Routes>`

2. **Nested routes, NOT flat routes**
   - Use `<Route path="application"><Route path="module" element={...} /></Route>` pattern
   - NEVER use `<Route path="/context/application/module" element={...} />` (flat)
   - Use `<Route index element={<Navigate to="default" replace />} />` for default redirects

3. **Tenant-prefixed routes** - If `/t/:slug/` block exists, add routes there too

4. **See `/application` skill templates-frontend.md** for full template patterns

**API/Controller task guidance (MANDATORY folder hierarchy):**

When executing `api` category tasks, follow these rules strictly:

1. **Controllers MUST be organized by context and application folders:**
   - Path: `Api/Controllers/{ContextShort}/{Application}/{EntityName}Controller.cs`
   - If no application sub-level: `Api/Controllers/{ContextShort}/{EntityName}Controller.cs`

2. **Context-to-folder mapping (from navRoute):**

   | NavRoute Prefix | Controller Folder |
   |-----------------|-------------------|
   | `platform.administration` | `Admin` |
   | `platform.support` | `Support` |
   | `business.*` | `Business` |
   | `personal.*` | `User` |

3. **Sub-folders for applications/modules with multiple controllers:**
   - `Admin/Tenants/` for tenant-related controllers
   - `Admin/AI/` for AI-related controllers
   - `Admin/Communications/` for communication controllers

4. **Reference:** SmartStack.app `Api/Controllers/` for the canonical structure

### 4. Explore Context (if needed)

**Use subagents sparingly:**

```
If exploration needed:
  - Use explore-codebase agent for file discovery
  - Use explore-docs agent for library docs
  - Use Context7 MCP for documentation
```

**Prefer direct tool usage:**
- Glob for file patterns
- Grep for code search
- Read for file contents

### 5. Execute Implementation

**Implement the task:**

- Create/modify files as needed
- Follow existing patterns in codebase
- Use SmartStack conventions
- Add appropriate logging
- Handle errors properly

**Track every file operation:**

```
{files_created}  = []   // Accumulate as you create files
{files_modified} = []   // Accumulate as you modify files
```

**Use TodoWrite to track sub-steps:**

```
If task has multiple parts:
  1. Create TodoWrite entries for each part
  2. Mark in_progress as you work
  3. Mark completed when done
```

### 6. Validate with MCP

**After implementation, validate based on category:**

```
# Always run general validation
mcp__smartstack__validate_conventions:
  checks: ["all"]

# Category-specific validation
if category == "infrastructure":
  mcp__smartstack__check_migrations

if category == "api":
  mcp__smartstack__validate_security

if category == "frontend":
  mcp__smartstack__validate_frontend_routes

if category == "test":
  mcp__smartstack__analyze_test_coverage
```

**Record validation result:**
```
{validation_result} = "passed" | "failed: {reason}"
```

**If validation fails:**
- Fix the issues
- Re-validate
- Do NOT proceed until valid
- If cannot fix: set `{validation_result} = "failed: {reason}"`

### 7. Check Acceptance Criteria

**Verify against `{current_task_criteria}`:**

```
ULTRA THINK: Does the implementation satisfy the acceptance criteria?

Criteria: {current_task_criteria}

✅ Met / ❌ Not met (explain why)
```

**If criteria NOT met:**
- Continue working until met
- If impossible to meet: document in `{task_error}`

### 8. Run Quick Tests

**If applicable:**

```bash
# For backend changes (domain, application, infrastructure, api)
dotnet build --no-restore 2>&1

# For frontend changes
npm run lint && npm run typecheck

# For test category
dotnet test --filter "FullyQualifiedName~{relevant_test}"
```

**If tests fail:**
- Fix the failing tests
- Re-run until passing
- Document what was fixed

### 9. Update Task State in prd.json

**Persist tracking data BEFORE committing:**

```javascript
const prd = readJSON('.ralph/prd.json');
const task = prd.tasks.find(t => t.id === {current_task_id});

task.files_changed = {
  created: {files_created},
  modified: {files_modified}
};
task.validation = {validation_result};

// If task failed
if ({task_failed}) {
  task.status = 'failed';
  task.error = '{failure_reason}';
  task.completed_at = new Date().toISOString();
}

prd.updated_at = new Date().toISOString();
writeJSON('.ralph/prd.json', prd);
```

**Note: `task.status` stays `"in_progress"` until step-03 confirms the commit. Only `"failed"` is set here if the task cannot be completed.**

---

## IMPORTANT CONSTRAINTS:

### What TO DO:
- Implement exactly what the task describes
- Follow existing patterns
- Validate changes with MCP
- Track all file operations
- Check acceptance criteria
- Write minimal, clean code

### What NOT TO DO:
- Don't implement other tasks
- Don't refactor unrelated code
- Don't add "nice to have" features
- Don't skip validation
- Don't forget to track files

---

## OUTPUT FORMAT:

```
Task Executed:

| Action | Details |
|--------|---------|
| Task | [{current_task_id}] {current_task_description} |
| Category | {current_task_category} |
| Files Created | {files_created} |
| Files Modified | {files_modified} |
| Validation | {validation_result} |
| Acceptance | ✅ Criteria met |
| Tests | ✅ Passed |

-> Committing changes...
```

---

## ERROR HANDLING:

**If task cannot be completed:**

1. Document the blocker in `task.error`
2. Set `task.status = "failed"` in prd.json
3. Update progress.txt with learnings
4. Proceed to step-03 to save progress (commit what was done)
5. step-04 will handle blocked downstream tasks

**If build fails:**

1. Analyze error messages
2. Fix the issues
3. Re-build until success
4. Then proceed

**If validation fails:**

1. Fix validation issues
2. Re-validate until clean
3. If unfixable: document in `task.error`, set `task.validation = "failed: {reason}"`

---

## NEXT STEP:

After task executed and validated, proceed to `./step-03-commit.md`
