---
description: Start working on a bug fix - create branch and optionally link to Task Master
argument-hint: <bug-id> [--no-branch] [--task-master]
allowed-tools: Bash, Read, Edit, Write
---

# Start Bug Fix: $ARGUMENTS

## Phase 0: Parse Arguments

Extract from `$ARGUMENTS`:

- **bug-id**: Required bug ID to fix
- **--no-branch**: Skip git branch creation
- **--task-master**: Create Task Master task for this bug fix

**If no bug-id provided:**

- Error: "❌ Bug ID required. Usage: /bug:fix <bug-id>"
- Exit with status 1

## Phase 1: Read and Validate Bug

### 1.1 Check File Exists

````bash
test -f .bugs.local.md || { echo "⚠️  No bugs found."; exit 0; }
```text

### 1.2 Find and Validate Bug

Parse `.bugs.local.md` and locate bug by ID.

**If bug not found:**

```text
❌ Bug #[id] not found
Use /bug:list to see available bugs
```text

Exit with status 1

### 1.3 Check Bug Status

**If status = Closed:**

```text
⚠️  Bug #[ID] is already closed

To reopen: /bug:triage [ID]
```text

Prompt to continue anyway (y/N)

**If status = Resolved:**

```text
ℹ️  Bug #[ID] is marked as resolved

This may not need additional work.
```text

Prompt to continue (Y/n)

**If status = In Progress:**

```text
ℹ️  Bug #[ID] is already in progress

Existing fix branch may exist.
```text

Continue automatically

## Phase 2: Display Bug Context

Show bug details for reference:

```text
═══════════════════════════════════════════════════════════
🔧 Starting Fix: Bug #[ID]
═══════════════════════════════════════════════════════════

Summary:      [bug-summary]
Priority:     [priority]
Resolution:   [resolution]

Description:
[Bug description]

Repository Context:
  Project:    [project-type]
  Framework:  [framework]
  Current:    [current-branch]
═══════════════════════════════════════════════════════════
```text

## Phase 3: Git Branch Setup (unless --no-branch)

### 3.1 Check Git Repository

```bash
git rev-parse --git-dir 2>/dev/null
```text

**If not a git repo:**

```text
⚠️  Not a git repository. Skipping branch creation.
```text

Skip to Phase 4

### 3.2 Check Working Tree

```bash
git status --porcelain
```text

**If uncommitted changes exist:**

```text
⚠️  Uncommitted changes detected

Options:
  1. Commit changes first
  2. Stash changes: git stash
  3. Continue anyway (not recommended)

? How to proceed? (commit/stash/continue/cancel)
```text

Handle user choice:

- commit: Prompt for commit message, commit
- stash: Run `git stash push -m "WIP: before bug #[ID] fix"`
- continue: Proceed with warning
- cancel: Exit

### 3.3 Generate Branch Name

Create branch name from bug summary:

```bash
# Format: fix/bug-[ID]-[summary-slug]
# Example: fix/bug-1-auth-fails-safari

SLUG=$(echo "[summary]" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9]/-/g' | sed 's/--*/-/g' | sed 's/^-//' | sed 's/-$//' | cut -c1-50)
BRANCH="fix/bug-[ID]-${SLUG}"
```text

### 3.4 Check if Branch Exists

```bash
git show-ref --verify --quiet refs/heads/[BRANCH]
```text

**If branch exists:**

```text
ℹ️  Branch already exists: [BRANCH]

Options:
  1. Switch to existing branch
  2. Create new branch with different name
  3. Delete and recreate

? What to do? (switch/new/recreate/cancel)
```text

### 3.5 Create and Switch Branch

```bash
# Create and switch to new branch
git checkout -b [BRANCH]

# Or switch to existing
git checkout [BRANCH]
```text

```text
✓ Created fix branch: [BRANCH]
```text

## Phase 4: Update Bug Status

### 4.1 Auto-Triage to "In Progress"

If bug status != "In Progress":

```text
? Update bug status to "In Progress"? (Y/n)
```text

If yes, update bug file:

- Status: → "In Progress"
- Resolution: → "Unresolved" (if not set)
- Updated: → [current-date]

Add triage note:

```markdown
**Triage Notes:**
- [YYYY-MM-DD]: Started fix work on branch [branch-name]
```text

## Phase 5: Task Master Integration (if --task-master or prompt)

### 5.1 Check Task Master Availability

```bash
# Check if Task Master MCP is available
mcp__task_master_ai__get_tasks --help 2>/dev/null
```text

**If not available:**

```text
ℹ️  Task Master not configured. Skipping task creation.
```text

Skip to Phase 6

### 5.2 Check Existing Task Reference

If bug already has Task Master reference:

```text
ℹ️  Bug #[ID] already linked to Task Master #[task-id]

? View task details? (Y/n)
```text

If yes:

```bash
mcp__task_master_ai__get_task --id=[task-id]
```text

Skip task creation

### 5.3 Create Task Master Task (if needed)

```text
? Create Task Master task for this bug fix? (Y/n)
```text

If yes:

```bash
# Create task with bug context
mcp__task_master_ai__add_task \
  --prompt="Fix Bug #[ID]: [summary]

Bug Details:
- Status: [status]
- Priority: [priority]
- Description: [description]

Fix branch: [branch-name]
"
```text

Get created task ID from response.

### 5.4 Link Task to Bug

Update bug's Task Reference column:

```markdown
| [Bug summary](#slug) | In Progress | [priority] | Unresolved | Task Master: #[task-id] |
```text

```text
✓ Created Task Master task #[task-id]
✓ Linked bug to task
```text

## Phase 6: Setup Development Environment

### 6.1 Provide Implementation Guidance

```text
═══════════════════════════════════════════════════════════
🎯 Fix Implementation Checklist
═══════════════════════════════════════════════════════════

[ ] Reproduce the bug locally
[ ] Identify root cause
[ ] Write failing test (if applicable)
[ ] Implement fix
[ ] Verify fix resolves original issue
[ ] Run test suite
[ ] Update documentation (if needed)
[ ] Commit changes
[ ] Update bug status

Branch:        [branch-name]
Bug File:      .bugs.local.md#bug-[ID]
[If Task Master:]
Task Master:   Task #[task-id]

TDD Approach (Recommended):
Follow test-driven development workflow for reliable bug fixes:
1. Write failing test that reproduces the bug (RED)
2. Implement minimal fix to pass the test (GREEN)
3. Refactor if needed while keeping tests passing (REFACTOR)

See: ~/.claude/guides/agents.tdd.md for TDD principles
See: ~/.claude/guides/agents.tdd.ts.md for TypeScript-specific patterns
═══════════════════════════════════════════════════════════
```text

### 6.2 Open Relevant Files

```bash
# Open bug file in editor
code .bugs.local.md

# If specific files mentioned in bug description, open them
# (Parse description for file paths)
```text

### 6.3 Suggest Next Steps

```text
Next Steps:
  1. Review bug details:     /bug:show [ID]
  2. Update progress:        /bug:triage [ID]
  3. When fixed:             /bug:close [ID]
  [If Task Master:]
  4. Update task:            mcp__task_master_ai__update_task --id=[task-id]
  5. Complete task:          mcp__task_master_ai__set_task_status --id=[task-id] --status=done

Quick Commands:
  • View bug:      /bug:show [ID]
  • List tests:    task test (if Taskfile exists)
  • Run tests:     bun test
  • Commit:        git commit -m "fix: resolve bug #[ID] - [summary]"
```text

## Error Handling

- **Bug not found**: Show available bugs
- **Git operations fail**: Continue without branch, note in output
- **Uncommitted changes**: Prompt for action, don't force
- **Task Master unavailable**: Skip gracefully with note
- **Branch creation fails**: Show error, suggest manual creation

## Exit Codes

- 0: Fix workflow started successfully
- 1: Bug not found or invalid ID
- 2: Git operation failed
- 3: User cancelled during prompts
````
