# Bug Fix Workflow

This skill orchestrates a systematic bug fixing process, from reproduction to validation.

## Workflow Overview

```
┌──────────────┐
│  Reproduce   │ → Understand & reproduce the bug
└──────────────┘
       ↓
┌──────────────┐
│   Diagnose   │ → Find root cause
└──────────────┘
       ↓
┌──────────────┐
│     Fix      │ → Implement fix
└──────────────┘
       ↓
┌──────────────┐
│     Test     │ → Add regression test
└──────────────┘
       ↓
┌──────────────┐
│   Validate   │ → Verify fix doesn't break anything
└──────────────┘
       ↓
    ✅ Done
```

## Step-by-Step Process

### Pre-Flight: Understand the Bug

**Gather information**:
- Bug description
- Steps to reproduce
- Expected vs actual behavior
- Error messages/stack traces
- Affected users/severity

**Tools**:
```typescript
mcp__crafted-context__get_context_summary()
mcp__crafted-context__search_in_context({
  query: "error-related-term",
  type: "both"
})
```

---

### Step 1: Reproduce

**Goal**: Confirm the bug and understand its scope

**Tasks**:
1. **Create minimal reproduction**
   - Write a test that FAILS (demonstrates the bug)
   - Or manually reproduce in browser/app

2. **Understand the scope**
   - Is it a frontend bug? Backend? Both?
   - Which layer is affected? (Router/Service/Domain)
   - Are there related bugs?

**For Web Projects**:
```typescript
mcp__chrome-devtools__navigate_page({ url: "..." })
mcp__chrome-devtools__take_snapshot()
mcp__chrome-devtools__list_console_messages()
```

**For API Bugs**:
```typescript
// Write failing test
describe('Bug: User cannot update email', () => {
  it('should allow user to update email', async () => {
    const result = await userService.updateEmail(userId, newEmail);
    expect(result.isSuccess).toBe(true); // Currently fails
  });
});
```

**Output**: Confirmed reproduction + scope understanding

---

### Step 2: Diagnose

**Goal**: Find the root cause

**Techniques**:

1. **Read relevant code**
   ```typescript
   mcp__crafted-context__search_in_context({
     query: "updateEmail",
     type: "content"
   })
   ```

2. **Check logs/errors**
   ```typescript
   mcp__chrome-devtools__list_console_messages()
   mcp__github__search_issues({ q: "updateEmail error" })
   ```

3. **Trace the flow**
   - Frontend → API → Service → Repository → Database
   - Or Domain → Use-case → Infrastructure

4. **Check recent changes**
   ```bash
   git log --oneline --all --graph -- path/to/file.ts
   git blame path/to/file.ts
   ```

**Tools**:
```typescript
mcp__filesystem__read_file()
mcp__github__get_file_contents()
```

**Common root causes**:
- Missing validation
- Type mismatch
- Race condition
- Missing error handling
- Wrong business logic
- Database constraint violation

**Output**: Root cause identified

---

### Step 3: Fix

**Goal**: Implement the fix following level-appropriate rules

**Level-Specific Guidelines**:

**For RAPID level**:
- Fix directly in router (if < 100 lines)
- Basic error handling
- Quick and working solution

**For BALANCED level**:
- Fix in appropriate layer (Service/Repository)
- Maintain function size (< 50 lines)
- Follow 3-layer architecture
- Add proper error handling

**For CRAFTED level**:
- Fix in domain layer if business logic
- Maintain function size (< 20 lines)
- Use Result pattern (no exceptions)
- Update domain entities/value objects
- Ensure ZERO external deps in domain

**Apply Clean Code**:
- NO inline comments (refactor instead)
- Self-documenting code
- Extract functions if needed
- Proper error messages

**Validation**:
```typescript
mcp__rules-validator__validate_code({
  code: fixedCode,
  filePath: "...",
  level: detectedLevel
})

mcp__architecture-guard__check_dependencies({
  filePath: "...",
  level: detectedLevel
})
```

**Output**: Fix implemented

---

### Step 4: Test (Regression Test)

**Goal**: Ensure bug doesn't come back

**Test Strategy by Level**:

**For RAPID level**:
- Add basic test for the bug
- Ensure fix doesn't break auth/payment flows

**For BALANCED level**:
- Add unit test for the fixed code
- Add integration test if needed
- Ensure 70% coverage maintained

**For CRAFTED level**:
- Add comprehensive domain test
- Ensure 100% coverage maintained
- Add contract test if API changed

**Write Regression Test**:
```typescript
describe('Bug Fix: User email update', () => {
  it('should allow user to update email to valid address', async () => {
    const result = await userService.updateEmail(userId, 'new@email.com');

    expect(result.isSuccess).toBe(true);
    expect(result.value.email).toBe('new@email.com');
  });

  it('should reject invalid email format', async () => {
    const result = await userService.updateEmail(userId, 'invalid-email');

    expect(result.isFailure).toBe(true);
    expect(result.error).toContain('Invalid email format');
  });
});
```

**Run Tests**:
```typescript
mcp__vitest__run_tests()
mcp__vitest__check_coverage({ threshold: 70 }) // or 100 for Crafted
```

**Output**: Regression test passes ✅

---

### Step 5: Validate

**Goal**: Ensure fix doesn't break anything else

**Validation Checklist**:

1. **Run ALL tests**
   ```bash
   pnpm test
   ```

2. **Check types**
   ```typescript
   mcp__typescript__check_types()
   ```

3. **Validate architecture** (Balanced/Crafted)
   ```typescript
   mcp__architecture-guard__check_layer_boundaries()
   ```

4. **Manual testing**
   - Test the fixed functionality
   - Test related functionalities
   - Test edge cases

5. **Check for side effects**
   - Did the fix affect other features?
   - Are there any new errors?

**Tools**:
```typescript
mcp__vitest__run_tests()
mcp__typescript__check_types()
mcp__architecture-guard__check_layer_boundaries()
```

**On failure**: Return to Step 3 with more context

**On success**: Bug fixed! 🎉

---

## Example Usage

### User Report
> "Users can't update their email address. They get a 'Validation failed' error."

### Execution

```bash
# 1. Reproduce
# Write failing test
it('should update user email', async () => {
  const result = await userService.updateEmail('user-123', 'new@email.com');
  expect(result.isSuccess).toBe(true); // FAILS
});

# Run test to confirm it fails
pnpm test user.service.test.ts

# 2. Diagnose
# Read the updateEmail code
mcp__crafted-context__search_in_context({
  query: "updateEmail",
  type: "content"
})

# Found issue: Email validation is too strict, rejects valid emails with + sign

# 3. Fix
# Update Email value object validation
export class Email {
  private static readonly REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

  static create(email: string): Result<Email> {
    // Previous: Rejected emails with +
    // Fixed: Allow + in email addresses
    if (!Email.REGEX.test(email)) {
      return Result.fail('Invalid email format');
    }
    return Result.ok(new Email(email));
  }
}

# 4. Test
# Add regression test
it('should accept email with plus sign', async () => {
  const result = await userService.updateEmail('user-123', 'user+test@email.com');
  expect(result.isSuccess).toBe(true);
});

# Run tests
pnpm test user.service.test.ts
# ✅ All tests pass

# 5. Validate
pnpm test          # All tests pass ✅
pnpm typecheck     # No errors ✅
pnpm test:e2e      # E2E tests pass ✅

# Bug fixed! 🎉
```

---

## Bug Severity Levels

### P0: Critical (Production Down)
- **Response time**: Immediate
- **Fix quality**: Can be Rapid-style for quick hotfix
- **Follow-up**: Create proper fix later (technical debt ticket)

### P1: High (Feature Broken)
- **Response time**: Within 24h
- **Fix quality**: Follow project level rules
- **Testing**: Full regression suite

### P2: Medium (Degraded Experience)
- **Response time**: Within 1 week
- **Fix quality**: Follow project level rules
- **Testing**: Comprehensive tests + coverage

### P3: Low (Minor Issue)
- **Response time**: Within 1 month
- **Fix quality**: Follow project level rules
- **Testing**: Full TDD approach (Crafted level)

---

## Creating ADRs for Bug Fixes (Balanced/Crafted)

For significant bugs, create an ADR:

```markdown
# ADR-XXX: Fix Email Validation Regex

## Status
Accepted

## Context
Users reported inability to update emails with + sign (user+test@email.com).
Email validation regex was too restrictive.

## Decision
Update Email value object regex to accept + sign and other valid characters.

## Consequences
- Positive: Users can use email aliases
- Positive: RFC 5322 compliant
- Negative: None

## Bug Root Cause
Previous regex: /^[a-zA-Z0-9@.]+$/
New regex: /^[^\s@]+@[^\s@]+\.[^\s@]+$/

## Prevention
Add test cases for edge cases in Email value object tests.
```

---

## Commands

```bash
# Invoke this skill
/bugfix

# Or use slash command
/bugfix "Users can't update email"
```

---

## Tips

1. **Reproduce first** - Don't skip this step
2. **Write regression test** - Prevent bug from coming back
3. **Check root cause** - Fix the cause, not the symptom
4. **Validate thoroughly** - Ensure no side effects
5. **Document if needed** - ADR for complex bugs

---

## Common Pitfalls

❌ **Don't**:
- Fix symptoms instead of root cause
- Skip writing regression test
- Break other features
- Add inline comments instead of refactoring

✅ **Do**:
- Reproduce and understand first
- Write failing test
- Fix properly according to level
- Validate no side effects
- Create ADR for complex bugs
