# Developer Workflow Error Handling

This guide defines all error scenarios specific to developer workflows and their recovery strategies.

## Error Classification

Errors are classified by severity and recoverability:

### 1. Blocker Errors (STOP)
Require orchestrator intervention, cannot continue:
- Missing critical files (story, context XML)
- Unclear/ambiguous requirements
- External dependencies unavailable
- Permission/authentication errors

**Action**: Return error report immediately

### 2. Test Failures (STOP)
Tests must pass 100%, cannot mark complete:
- Unit test failures
- Integration test failures
- E2E test failures
- Linting/TypeScript errors

**Action**: Return error report with test details

### 3. Validation Errors (RETRY)
Can be fixed within workflow execution:
- File format issues
- Minor syntax errors
- Missing imports

**Action**: Fix and continue (up to 2 retries)

### 4. Warning Issues (CONTINUE)
Non-blocking, log and continue:
- Performance warnings
- Code style suggestions
- Non-critical dependency updates

**Action**: Note in report, continue execution

---

## Error Scenarios: dev-story Workflow

### ES-001: Story Context XML Missing

**Trigger**: Story file loaded but context XML path invalid or file not found

**Symptoms**:
- Story file has "Context Reference" field but file doesn't exist
- Path is incorrect/outdated
- XML file not yet generated

**Impact**: BLOCKER - Cannot implement without architectural guidance

**Error Report**:
```markdown
**Status:** ❌ FAILED
**Failed At:** Loading Story Context XML
**Error:** Context XML not found at expected path

**Root Cause:**
Story Context XML referenced in story file (docs/stories/story-context-12.2.xml) does not exist. This file should be generated by SM agent via story-context workflow before dev-story execution.

**Recovery Options:**
1. Request orchestrator run story-context workflow for this story
2. Check if context XML exists at different path
3. Manual intervention: Create context XML manually
```

**Orchestrator Action**: Launch SM agent with story-context workflow

### ES-002: Test Failures (< 100% Passing)

**Trigger**: Test suite execution completes but not all tests passing

**Symptoms**:
- One or more tests fail
- Test pass rate < 100%
- Assertion failures, exceptions thrown

**Impact**: BLOCKER - Cannot mark story complete with failing tests

**Error Report**:
```markdown
**Status:** ❌ FAILED
**Failed At:** Test execution - validation suite
**Error:** 2 tests failing in phone.validator.spec.ts

**Test Results:**
- Unit Tests: 22/24 passing (92%)
- **FAILED TESTS:**
  - should validate phone with +55 country code: Expected true, received false
  - should handle phone without country code: TypeError: Cannot read property 'match' of undefined

**Root Cause:**
Phone validation regex doesn't account for optional + prefix in international format. Additionally, validation throws error on missing country code instead of handling gracefully.

**Recovery Options:**
1. Fix regex pattern to support optional + prefix: /^(\+)?(\d{2})?(\d{11})$/
2. Add null check before regex match
3. Re-run tests after fix
```

**Orchestrator Action**: Re-run dev-story after developer (or user) fixes issue

**Recovery Steps**:
1. Analyze test failure messages
2. Identify root cause in implementation
3. Fix implementation code
4. Re-run tests
5. If tests pass, continue workflow
6. If tests still fail after 2 fix attempts, return error report

### ES-003: Unclear Acceptance Criteria

**Trigger**: AC is ambiguous, missing details, or contradictory

**Symptoms**:
- AC doesn't specify expected behavior clearly
- Multiple interpretations possible
- Conflicts with other ACs or architecture

**Impact**: BLOCKER - Cannot implement without clarity

**Error Report**:
```markdown
**Status:** ❌ FAILED
**Failed At:** AC-002 analysis
**Error:** Acceptance criteria ambiguous - multiple valid interpretations

**Context:**
AC-002 states: "Phone validation must support Brazilian formats"
Ambiguity: Does this include landlines (10 digits) or only mobile (11 digits)? Should area code be validated against known codes?

**Root Cause:**
Acceptance criteria lacks specificity on:
1. Which Brazilian phone formats to support (landline vs mobile)
2. Whether to validate area codes against known list
3. How to handle edge cases (0800, special numbers)

**Recovery Options:**
1. Request correct-course workflow to clarify AC-002 requirements
2. Make assumption (document in code comments) and proceed
3. Manual intervention: Ask user for clarification

**Orchestrator Action Required:**
Launch correct-course workflow to update story AC-002 with specific format requirements
```

**Orchestrator Action**: Launch SM agent with correct-course workflow

### ES-004: External Dependency Unavailable

**Trigger**: Required external service, API, or resource is unavailable

**Symptoms**:
- API returns 503/timeout
- Database connection fails
- External library not installed
- Network unavailable

**Impact**: BLOCKER or SKIP - Depends on criticality

**Error Report**:
```markdown
**Status:** ❌ FAILED
**Failed At:** Integration test - external API call
**Error:** Evolution API unavailable (connection timeout)

**Context:**
AC-003 requires integration with Evolution API for WhatsApp message sending. Integration test attempts to connect to Evolution API but times out after 30s.

**Root Cause:**
Evolution API service not running or network connectivity issue.

**Recovery Options:**
1. Start Evolution API service: pnpm docker:services
2. Skip integration tests temporarily (use --skip-integration flag)
3. Mock Evolution API for tests (refactor test to use mock)

**Orchestrator Action Required:**
Check if Evolution API service is running. If not, start services and re-run dev-story.
```

**Orchestrator Action**: Start required service or skip tests with user approval

### ES-005: TypeScript Type Errors

**Trigger**: Implementation introduces type errors

**Symptoms**:
- `pnpm typecheck` fails
- Type mismatches, missing properties
- "Cannot find name" errors

**Impact**: BLOCKER - Must fix before complete

**Error Report**:
```markdown
**Status:** ❌ FAILED
**Failed At:** TypeScript validation
**Error:** 3 type errors in patient.dto.ts

**Test Results:**
- TypeScript: ❌ 3 errors
  - patient.dto.ts:45:12 - Type 'string | undefined' is not assignable to type 'string'
  - patient.dto.ts:67:8 - Property 'validate' does not exist on type 'PhoneValidator'
  - patient.service.ts:102:15 - Argument of type 'string' is not assignable to parameter of type 'PhoneNumber'

**Root Cause:**
Phone field made optional in DTO but downstream code expects non-nullable. PhoneValidator interface not updated with validate method. Type alias PhoneNumber not defined.

**Recovery Options:**
1. Add null check in patient.service.ts before using phone field
2. Add validate method to PhoneValidator interface
3. Define PhoneNumber type alias or use string

**Orchestrator Action Required:**
Re-run dev-story after fixing type errors
```

**Orchestrator Action**: Re-run after fixes

**Recovery Steps**:
1. Run `pnpm typecheck` to identify errors
2. Fix type errors one by one
3. Re-run typecheck
4. Continue workflow when no errors

### ES-006: ESLint Violations

**Trigger**: Code style/quality violations detected

**Symptoms**:
- `pnpm lint` fails
- Unused variables, missing imports
- Style violations

**Impact**: BLOCKER (if CI enforces) or WARNING

**Error Report**:
```markdown
**Status:** ❌ FAILED
**Failed At:** Code quality validation
**Error:** 5 ESLint violations

**Quality Metrics:**
- ESLint: ❌ 5 errors
  - phone.validator.ts:12:7 - 'regex' is assigned a value but never used
  - phone.validator.ts:23:1 - Missing semicolon
  - patient.dto.ts:45:3 - Unexpected console.log statement
  - patient.service.ts:89:5 - Prefer nullish coalescing operator (??)
  - patient.service.ts:102:1 - More than 100 lines in function

**Root Cause:**
Development introduced code that violates project ESLint rules.

**Recovery Options:**
1. Run `pnpm lint:fix` to auto-fix violations
2. Manually fix violations that can't be auto-fixed
3. Re-run lint

**Orchestrator Action Required:**
Auto-fix: Run `pnpm lint:fix` and re-run dev-story
```

**Orchestrator Action**: Auto-fix or manual fix then re-run

**Recovery Steps**:
1. Run `pnpm lint:fix` to auto-fix
2. Manually fix remaining issues
3. Re-run `pnpm lint`
4. Continue when passing

### ES-007: Security Vulnerabilities Detected

**Trigger**: Security scan detects issues

**Symptoms**:
- Dependency vulnerabilities
- Hardcoded secrets
- PII in logs
- SQL injection risk
- XSS vulnerability

**Impact**: BLOCKER - Must fix before complete

**Error Report**:
```markdown
**Status:** ❌ FAILED
**Failed At:** Security validation
**Error:** 2 security issues detected

**Quality Metrics:**
- Security: ❌ 2 issues
  - HIGH: Hardcoded API key in patient.service.ts:45
  - MEDIUM: PII (patient phone) logged in console.log

**Root Cause:**
Implementation includes API key directly in code instead of environment variable. Patient phone number logged for debugging.

**Recovery Options:**
1. Move API key to environment variable (EVOLUTION_API_KEY)
2. Remove console.log or sanitize to remove PII
3. Re-run security scan

**Orchestrator Action Required:**
Re-run dev-story after removing hardcoded secrets and PII logs
```

**Orchestrator Action**: Re-run after security fixes

**Critical Rule**: NEVER ignore security issues

### ES-008: Performance Issues Detected

**Trigger**: Implementation causes performance degradation

**Symptoms**:
- Tests timeout
- Slow response times
- Memory leaks
- CPU spikes

**Impact**: WARNING or BLOCKER (if critical)

**Error Report**:
```markdown
**Status:** ⚠️ WARNING
**Failed At:** Performance validation
**Error:** Slow query detected in phone validation

**Quality Metrics:**
- Performance: ⚠️ 1 warning
  - Phone validation taking 2.3s (threshold: 1s)

**Root Cause:**
Regex validation loops through multiple patterns sequentially. Inefficient algorithm.

**Recovery Options:**
1. Optimize regex to single pattern with alternation
2. Add caching for validated phones
3. If not critical path, note as tech debt and continue

**Orchestrator Action Required:**
Note performance issue in tech debt. Continue if non-critical, fix if blocking user experience.
```

**Orchestrator Action**: Continue with note or fix if critical

---

## Error Scenarios: story-done Workflow

### ES-101: Definition of Done Not Met

**Trigger**: Story marked "In Review" but doesn't meet DoD criteria

**Symptoms**:
- Tasks not all checked off
- ACs not all satisfied
- Tests not 100% passing
- TypeScript/ESLint errors

**Impact**: BLOCKER - Cannot advance to DONE

**Error Report**:
```markdown
**Status:** ❌ FAILED
**Failed At:** Definition of Done validation
**Error:** Story does not meet DoD criteria

**DoD Checklist:**
- ✅ All ACs implemented and verified
- ❌ All tasks completed (2 tasks unchecked)
- ✅ Tests passing 100%
- ❌ Code follows Story Context patterns (1 anti-pattern used)
- ✅ No console.log or PII in logs
- ✅ TypeScript errors resolved
- ✅ ESLint passing

**Root Cause:**
Story file shows 2 tasks in Dev Agent Record not checked off. Code review identified use of anti-pattern (direct database access instead of repository pattern) specified in Story Context XML.

**Recovery Options:**
1. Complete remaining 2 tasks
2. Refactor database access to use repository pattern
3. Re-run story-done after fixes

**Orchestrator Action Required:**
Re-run dev-story to complete remaining tasks and fix anti-pattern usage
```

**Orchestrator Action**: Re-run dev-story or manual completion

### ES-102: State Transition Invalid

**Trigger**: Workflow status doesn't allow transition

**Symptoms**:
- Story not in expected state
- Queue advancement fails
- Workflow-status.md corrupt

**Impact**: BLOCKER - State machine violation

**Error Report**:
```markdown
**Status:** ❌ FAILED
**Failed At:** State transition validation
**Error:** Cannot transition story from TODO to DONE (must be IN PROGRESS)

**Current State:**
- BACKLOG: 8 stories
- TODO: 12.2
- IN PROGRESS: empty
- DONE: 5 stories

**Root Cause:**
Story 12.2 is in TODO queue but story-done workflow expects IN PROGRESS. State machine violation.

**Recovery Options:**
1. Run story-ready workflow to move 12.2 to IN PROGRESS
2. Check if workflow-status.md is out of sync with reality
3. Manual intervention: Fix workflow-status.md state

**Orchestrator Action Required:**
Verify workflow-status.md accuracy. Run story-ready before story-done.
```

**Orchestrator Action**: Fix state, run prerequisite workflows

---

## Error Scenarios: review-story Workflow

### ES-201: Clean Context Not Achieved

**Trigger**: Review agent has implementation context from prior session

**Symptoms**:
- Review references implementation decisions not in code
- Review biased by implementation approach

**Impact**: WARNING - Review quality degraded

**Error Report**:
```markdown
**Status:** ⚠️ WARNING
**Failed At:** Context initialization
**Error:** Review may be biased by implementation context

**Root Cause:**
Review-story workflow should start with clean context but prior agent memory may influence review.

**Recovery Options:**
1. Explicitly clear context before review
2. Launch review-story in fresh agent session
3. Note potential bias in review report

**Orchestrator Action Required:**
Restart review-story in fresh agent for unbiased review
```

**Orchestrator Action**: Restart in fresh session

---

## Error Recovery Strategies

### Strategy 1: Automatic Retry (Limited)

For transient errors (network, service unavailable):
1. Wait 5 seconds
2. Retry operation
3. Max 2 retries
4. If still failing, return error report

### Strategy 2: Fix and Continue (Within Workflow)

For fixable errors (type errors, lint violations):
1. Identify root cause
2. Apply fix
3. Re-validate
4. Continue workflow if fix successful
5. If fix unsuccessful after 2 attempts, return error report

### Strategy 3: Request Orchestrator Help (Blockers)

For blockers requiring external intervention:
1. Document blocker clearly
2. Provide recovery options
3. Return error report immediately
4. Wait for orchestrator to resolve

### Strategy 4: Skip and Note (Non-Critical)

For non-blocking issues:
1. Log warning in report notes
2. Continue execution
3. Add to tech debt
4. Complete workflow with note

---

## Error Prevention Best Practices

### Pre-Execution Validation

Before starting workflow:
1. Verify all input files exist
2. Check Story Context XML loads correctly
3. Validate workflow-status.md parse-able
4. Confirm environment ready (services running)

### During Execution Monitoring

During workflow execution:
1. Run tests after EVERY significant change
2. Run typecheck periodically
3. Check for console.log before commits
4. Validate file paths before writes

### Post-Execution Validation

Before marking complete:
1. Re-run full test suite
2. Run `pnpm ci:quality` for full validation
3. Verify all tasks checked off
4. Confirm DoD met

---

## Error Reporting Standards

All error reports must include:

1. **Clear error classification**: BLOCKER, WARNING, RETRY
2. **Specific failure point**: Which AC, which step, which file
3. **Root cause analysis**: Why it failed (technical)
4. **Recovery options**: Minimum 2 concrete options
5. **Orchestrator recommendation**: Specific next action

**Never**:
- Return generic "error occurred" messages
- Skip root cause analysis
- Provide vague recovery options
- Continue execution after blocker
- Hide test failures

---

## Integration with Orchestrator

Orchestrator uses error reports to:
1. **Decide retry strategy**: Automatic vs manual
2. **Launch helper workflows**: correct-course, story-context
3. **Alert user**: For manual intervention
4. **Log for retrospective**: Pattern identification

Quality error reports enable automated recovery in 60%+ of cases.

---

## Error Taxonomy Reference

| Error Code | Category | Severity | Auto-Recoverable |
|------------|----------|----------|------------------|
| ES-001 | Context Missing | BLOCKER | No - Request SM |
| ES-002 | Test Failure | BLOCKER | Partial - Fix & Retry |
| ES-003 | Unclear AC | BLOCKER | No - Request SM |
| ES-004 | External Dependency | BLOCKER | Partial - Start Service |
| ES-005 | TypeScript | BLOCKER | Yes - Fix & Retry |
| ES-006 | ESLint | BLOCKER | Yes - Auto-fix |
| ES-007 | Security | BLOCKER | No - Manual Fix |
| ES-008 | Performance | WARNING | Yes - Optimize or Note |
| ES-101 | DoD Not Met | BLOCKER | Partial - Complete Tasks |
| ES-102 | Invalid Transition | BLOCKER | No - Fix State |
| ES-201 | Context Bias | WARNING | Yes - Restart Fresh |

Use error codes in reports for consistent handling.
