---
name: x-ipe-task-based-bug-fix
description: Diagnose and fix bugs in existing code. Use when something is broken, not working as expected, or producing errors. Triggers on requests like "fix bug", "something is broken", "not working".
---

# Task-Based Skill: Bug Fix

## Purpose

Systematically diagnose, fix, and verify bug resolutions by:
1. Understanding and reproducing the reported bug
2. Early conflict analysis against existing design/logic
3. Diagnosing root cause and defining fix scope (code + documentation)
4. Writing a failing test before implementing the minimal fix
5. Verifying the fix with no regressions

---

## Important Notes

BLOCKING: Learn `x-ipe-workflow-task-execution` skill before executing this skill.

**Note:** If Agent does not have skill capability, go to `.github/skills/` folder to learn skills. SKILL.md is the entry point.

**Bug Categories Reference:**

| Category | Symptoms | Typical Causes |
|----------|----------|----------------|
| Logic Error | Wrong output | Incorrect conditions |
| Null Reference | Crash/exception | Missing null checks |
| Race Condition | Intermittent failure | Async timing issues |
| Off-by-One | Wrong count | Loop/index errors |
| Resource Leak | Slowdown/crash | Missing cleanup |
| Integration | External fail | API changes |

---

## Input Parameters

```yaml
input:
  # Task attributes (from task board)
  task_id: "{TASK-XXX}"
  task_based_skill: "Bug Fix"

  # Execution context (passed by x-ipe-workflow-task-execution)
  execution_mode: "free-mode | workflow-mode"  # default: free-mode
  workflow:
    name: "N/A"  # workflow name, default: N/A

  # Task type attributes
  category: "standalone"
  next_task_based_skill: null
  require_human_review: yes

  # Required inputs
  auto_proceed: false
  bug_description: "{description of the bug}"
  expected_behavior: "{what should happen}"
  actual_behavior: "{what actually happens}"

  # Behavioral inputs
  human_approval: "notify"  # "notify" | "approval_required", set via --human-approval

  # Context (optional)
  reproduction_steps: "{steps to reproduce, if known}"
  environment_info: "{environment details, if relevant}"

  # Tech context (optional — auto-detected from affected files if not provided)
  program_type: "frontend | backend | fullstack | cli | library | skills | mcp | ..."  # non-exhaustive
  tech_stack: []  # e.g. ["Python/Flask", "JavaScript/Vanilla"]
```

### Input Initialization

```xml
<input_init>
  <!-- Standard fields (auto-populated by workflow) -->
  <field name="task_id" source="task-board-management (auto-generated)" />
  <field name="execution_mode" source="x-ipe-workflow-task-execution" />
  <field name="workflow.name" source="x-ipe-workflow-task-execution (from --workflow-mode:{name})" />
  <field name="category" derive="Read from this skill's Output Result category field" />

  <!-- Behavioral inputs -->
  <field name="human_approval">
    <steps>
      1. IF user message contains --human-approval:{value}: use {value}
      2. ELSE: default to "notify"
      3. Valid values: "notify", "approval_required"
      4. Controls ALL human approval gates across steps (conflicts, design decisions, etc.)
    </steps>
  </field>
</input_init>
```

---

## Definition of Ready

```xml
<definition_of_ready>
  <checkpoint required="true">
    <name>Bug description provided</name>
    <verification>Check that a clear description of the bug exists</verification>
  </checkpoint>
  <checkpoint required="true">
    <name>Expected vs actual behavior documented</name>
    <verification>Both expected and actual behavior are stated</verification>
  </checkpoint>
  <checkpoint required="recommended">
    <name>Steps to reproduce provided</name>
    <verification>Check if reproduction steps are available</verification>
  </checkpoint>
  <checkpoint required="recommended">
    <name>Environment info provided</name>
    <verification>Check if environment details are relevant and available</verification>
  </checkpoint>
</definition_of_ready>
```

---

## Execution Flow

| Step | Name | Action | Gate |
|------|------|--------|------|
| 1 | Understand | Read bug description, categorize severity | Bug understood |
| 2 | Reproduce | Follow steps to confirm bug occurs | Bug reproduced |
| 3 | Conflict Analysis | Check expected behavior against existing design/logic | Conflicts handled per human_approval |
| 4 | Diagnose | Trace root cause, check docs for design gaps | Root cause found |
| 5 | Define Fix Scope | Identify fix scope: code, feature spec, technical design | Fix scope defined |
| 6 | Design Fix | Identify fix options, choose minimal fix | Fix approach selected |
| 7 | Fix Related Docs | Update feature spec or technical design if in scope | Docs updated (if applicable) |
| 8 | Write Test | Create failing test that reproduces bug | Test fails |
| 9 | Implement | Write minimum code to fix bug | Test passes |
| 10 | Verify | Confirm bug fixed, all tests pass | DoD validated |

BLOCKING: When human_approval == "approval_required", any step requiring human decision MUST stop and wait for confirmation.
BLOCKING: Step 7 must complete before Step 8 if fix scope includes documentation changes.
BLOCKING: Step 8 to 9 is blocked until test is written and FAILS.
BLOCKING: Step 9 to 10 is blocked until the new test PASSES.
BLOCKING: If fix changes key interfaces, update technical design FIRST.

---

## Execution Procedure

```xml
<procedure name="bug-fix">
  <!-- CRITICAL: Both DoR/DoD check elements below are MANDATORY -->
  <execute_dor_checks_before_starting/>
  <schedule_dod_checks_with_sub_agent_before_starting/>

  <step_1>
    <name>Understand the Bug</name>
    <action>
      1. Read bug description carefully
      2. Clarify if unclear: What was expected? What actually happened? When did it start?
      3. Categorize severity:
         - Critical: System down or data loss
         - High: Feature broken
         - Medium: Partial functionality
         - Low: Minor issue
    </action>
    <output>Bug understood with severity classification</output>
  </step_1>

  <step_2>
    <name>Reproduce the Bug</name>
    <action>
      1. IF reproduction steps provided: follow them exactly, confirm bug occurs
         ELSE: analyze symptoms, create hypothesis, design test case, attempt to reproduce
      2. Document exact steps, environment conditions, and error messages
    </action>
    <output>Documented reproduction steps with confirmed bug occurrence</output>
  </step_2>

  <step_3>
    <name>Conflict Analysis</name>
    <action>
      1. Spawn sub-agent (Conflict Detector) to check the user's expected_behavior against existing logic:
         - Read existing feature specifications and technical design docs for the affected area
         - Read affected code and its callers/dependents
         - Identify design conflicts: expected behavior contradicts documented intentional design
         - Identify logic conflicts: expected behavior contradicts existing code logic that may be intentional
         - Output: list of conflicts with description and affected locations (empty if none)
      2. IF no conflicts found: proceed to Step 4
      3. IF conflicts found: spawn sub-agent (Conflict Validator) to classify each conflict:
         - "expected": user's request aligns with original design intent (code diverged from design)
         - "unexpected": user's expected behavior contradicts intentional design decisions
         - Output: classified conflict list with suggested resolution for each
      4. Handle conflicts based on human_approval:
         - IF human_approval == "notify":
           Record all conflicts and suggested resolutions in task summary, proceed to Step 4
         - IF human_approval == "approval_required":
           Present conflicts and suggested resolutions to user, STOP and wait for human approval
           - IF user approves: proceed to Step 4
           - IF user rejects/clarifies: update understanding and re-run conflict analysis
    </action>
    <constraints>
      - BLOCKING: If human_approval == "approval_required" and conflicts exist, do NOT proceed without human approval
      - CRITICAL: Conflict Detector must examine actual codebase AND design docs, not just code in isolation
      - CRITICAL: Conflict Validator must compare against documented design intent, not just current code behavior
    </constraints>
    <output>Conflict analysis result with resolution per human_approval mode</output>
  </step_3>

  <step_4>
    <name>Diagnose Root Cause</name>
    <action>
      1. Read related code starting from error location, trace backwards
      2. Check recent changes via git log
      3. If feature-related bug, read both:
         - Feature specification at x-ipe-docs/requirements/FEATURE-XXX/specification.md
         - Technical design at x-ipe-docs/requirements/FEATURE-XXX/technical-design.md
      4. Identify root cause: what lines, why it occurs, what triggers it
      5. Assess if root cause reveals gaps in documentation:
         - Missing functional requirement in feature specification?
         - Missing non-functional requirement in technical design?
      6. Document: root cause, affected files, risk assessment, design impact, doc gaps found
    </action>
    <constraints>
      - CRITICAL: Distinguish design flaw vs implementation error vs missing requirement
    </constraints>
    <output>Root cause analysis with affected files, risk assessment, and documentation gap assessment</output>
  </step_4>

  <step_5>
    <name>Define Fix Scope</name>
    <action>
      1. Based on root cause analysis, identify the complete fix scope:
         - Code-level fixes: source files that need changes
         - Feature specification gaps: functional requirements missing or incomplete
         - Technical design gaps: non-functional requirements, architecture decisions, or contracts missing
      2. Classify each scope item:
         - "code": fix in source code
         - "feature-spec": add/update functional requirement in specification.md
         - "technical-design": add/update non-functional requirement or design decision in technical-design.md
      3. Document fix scope as ordered list with rationale for each item
    </action>
    <constraints>
      - CRITICAL: Fix scope MUST NOT be limited to code changes — include documentation gaps identified in Step 4
      - CRITICAL: Each scope item must trace back to the root cause
    </constraints>
    <output>Classified fix scope covering code, feature spec, and technical design as needed</output>
  </step_5>

  <step_6>
    <name>Design Fix</name>
    <action>
      1. Identify fix options (Option A, Option B, etc.) covering all items in fix scope
      2. Evaluate each: code impact, regression risk, complexity, design compatibility
      3. Choose minimal fix: smallest change, lowest risk, most maintainable
      4. IF fix requires changes to key components or interfaces:
         - IF human_approval == "notify": log the design impact in task summary, proceed
         - IF human_approval == "approval_required": present design impact to user, STOP and wait for approval
         - UPDATE technical-design.md FIRST, add entry to Design Change Log
    </action>
    <constraints>
      - BLOCKING: Do NOT make incompatible changes to key components without updating design first
      - BLOCKING: If human_approval == "approval_required" and fix changes key interfaces, do NOT proceed without human approval
      - CRITICAL: Fix design must address ALL items in fix scope, not just code changes
    </constraints>
    <output>Selected fix approach covering all fix scope items</output>
  </step_6>

  <step_7>
    <name>Fix Related Docs</name>
    <action>
      1. IF fix scope contains NO "feature-spec" or "technical-design" items: SKIP this step
      2. IF fix scope contains "feature-spec" items:
         - Open x-ipe-docs/requirements/FEATURE-XXX/specification.md
         - Add missing functional requirements identified in fix scope
         - Ensure new requirements are consistent with existing ones
      3. IF fix scope contains "technical-design" items:
         - Open x-ipe-docs/requirements/FEATURE-XXX/technical-design.md
         - Add missing non-functional requirements, architecture decisions, or component contracts
         - Add entry to Design Change Log documenting the addition
      4. Document all doc changes made for traceability
    </action>
    <constraints>
      - CRITICAL: Only modify docs for items explicitly in fix scope — do not scope-creep
      - CRITICAL: Doc changes must be consistent with existing content
    </constraints>
    <output>Updated documentation files (if applicable), or "skipped" if no doc items in scope</output>
  </step_7>

  <step_8>
    <name>Write Failing Test</name>
    <action>
      1. Determine test type from program_type/tech_stack and affected file:
         - Backend bug (Python/server code) → pytest test
         - Frontend bug (JS/CSS file) → JS test using Vitest/Jest + jsdom (NOT string matching in pytest)
         - Fullstack bug → test both layers: pytest for backend, Vitest for frontend
         - If program_type not provided, auto-detect from affected file extensions
         - CRITICAL: For JS logic bugs, use a proper JS test runner. If not configured, set it up.
      2. Locate existing test file in tests/ folder for the affected component
      3. If no test file exists, create one following project test conventions
      4. Write test case that reproduces the bug with descriptive name
      5. Run the test and confirm it FAILS
    </action>
    <constraints>
      - BLOCKING: Test MUST fail before proceeding to Step 9
      - BLOCKING: Do NOT write fix code before test fails
      - CRITICAL: If test passes, revise it - test does not capture the bug
      - CRITICAL: For frontend bugs, ensure test covers the JS/CSS behavior, not just backend
    </constraints>
    <output>Failing test that reproduces the bug</output>
  </step_8>

  <step_9>
    <name>Implement Fix</name>
    <action>
      1. Implement the minimal fix: only change what is necessary, follow code style
      2. Run the new test: it MUST now pass
      3. Run ALL existing tests: all must pass, no regressions allowed
    </action>
    <constraints>
      - BLOCKING: New test must pass after fix
      - BLOCKING: All existing tests must pass
    </constraints>
    <output>Minimal code fix with all tests passing</output>
  </step_9>

  <step_10>
    <name>Verify Fix</name>
    <action>
      1. Follow original reproduction steps, confirm bug is fixed
      2. Run full test suite, perform manual smoke test
      3. Document: what was changed, why it fixes the bug, any side effects
    </action>
    <success_criteria>
      - Bug can no longer be reproduced
      - Full test suite passes
      - Fix is documented
    </success_criteria>
    <output>Verified fix with documentation</output>
  </step_10>

</procedure>
```

---

## Output Result

```yaml
task_completion_output:
  category: "standalone"
  status: completed | blocked
  next_task_based_skill: null
  require_human_review: yes
  auto_proceed: "{from input auto_proceed}"
  execution_mode: "{from input}"
  workflow:
    name: "{from input}"
  task_output_links:
    - "{path to fixed source file}"
    - "{path to test file}"
    - "{path to updated spec/design docs, if applicable}"
  # Dynamic attributes
  bug_severity: "Critical | High | Medium | Low"
  root_cause: "{brief description of root cause}"
  fix_scope: []  # classified list: [{type: "code|feature-spec|technical-design", description: "..."}]
  conflicts_found: []  # list of conflicts identified, empty if none
  docs_updated: []  # list of doc files updated, empty if none
```

---

## Definition of Done

CRITICAL: Use a sub-agent to validate DoD checkpoints independently.

```xml
<definition_of_done>
  <checkpoint required="true">
    <name>Bug can no longer be reproduced</name>
    <verification>Follow original reproduction steps and confirm bug does not occur</verification>
  </checkpoint>
  <checkpoint required="true">
    <name>Conflict analysis completed</name>
    <verification>Confirm conflicts were checked and handled per human_approval mode</verification>
  </checkpoint>
  <checkpoint required="true">
    <name>Fix scope defined</name>
    <verification>Confirm fix scope covers code and any documentation gaps identified during diagnosis</verification>
  </checkpoint>
  <checkpoint required="true">
    <name>Related docs updated if in scope</name>
    <verification>If fix scope includes feature-spec or technical-design items, confirm docs were updated</verification>
  </checkpoint>
  <checkpoint required="true">
    <name>Failing test written before fix</name>
    <verification>Confirm test was committed before fix code, and test fails without fix</verification>
  </checkpoint>
  <checkpoint required="true">
    <name>Test passes after fix</name>
    <verification>Run the bug-specific test and confirm it passes</verification>
  </checkpoint>
  <checkpoint required="true">
    <name>All existing tests pass</name>
    <verification>Run full test suite and confirm zero failures</verification>
  </checkpoint>
  <checkpoint required="true">
    <name>Fix documented</name>
    <verification>Check that root cause, fix scope, fix description, doc changes, and any side effects are documented</verification>
  </checkpoint>
</definition_of_done>
```

MANDATORY: After completing this skill, return to `x-ipe-workflow-task-execution` to continue the task execution flow.

---

## Patterns & Anti-Patterns

### Pattern: Test-First Bug Fix

**When:** Bug is clearly reproducible
**Then:**
```
1. Write test that reproduces bug
2. Verify test fails
3. Fix code
4. Verify test passes
5. Verify no regressions
```

### Pattern: Conflict-Aware Fix

**When:** Expected behavior may contradict existing design decisions
**Then:**
```
1. Check expected behavior against existing design/logic
2. Classify conflicts (expected vs unexpected)
3. Handle per human_approval mode (notify or approval_required)
4. Only then proceed to diagnosis and fix
```

### Pattern: Full-Scope Fix

**When:** Root cause reveals missing requirements in documentation
**Then:**
```
1. Diagnose root cause
2. Define fix scope (code + docs)
3. Update feature spec (missing functional requirements)
4. Update technical design (missing non-functional requirements)
5. Write test and implement code fix
```

### Pattern: Binary Search Diagnosis

**When:** Bug source is unclear
**Then:**
```
1. Find last known working state (git bisect)
2. Find first broken state
3. Narrow down to specific commit
4. Analyze changes in that commit
```

### Pattern: Defensive Fix

**When:** Root cause is external or unclear
**Then:**
```
1. Add input validation
2. Add null checks
3. Add error handling
4. Log diagnostic info
5. Document workaround
```

### Anti-Patterns

| Anti-Pattern | Why Bad | Do Instead |
|--------------|---------|------------|
| Fix without understanding | May fix symptom not cause | Diagnose root cause |
| Large refactor as fix | High regression risk | Minimal targeted fix |
| Skip test for bug | Bug may recur | Always add test |
| Skip conflict analysis | May break existing behavior silently | Always check for conflicts before diagnosing |
| Code-only fix for doc gap | Missing requirement will cause future bugs | Include doc updates in fix scope |
| Fix multiple bugs at once | Hard to verify | One bug per fix |

---

## Examples

See [references/examples.md](references/examples.md) for concrete execution examples.
