---
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 |
| `api` | `scaffold_routes`, `validate_security` | Controller conventions, authorization |
| `frontend` | `validate_frontend_routes`, `scaffold_frontend_extension` | React patterns, hooks |
| `i18n` | - | 4-language JSON structure |
| `test` | `scaffold_tests`, `analyze_test_coverage` | xUnit, test naming conventions |
| `validation` | `validate_conventions` | Build, test, lint checks |

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