---
name: debug
description: Systematic bug debugging with deep analysis and resolution
argument-hint: <log|error|problem-description>
model: opus
---

## Bug to investigate
$ARGUMENTS

<objective>
Follow an ultra-deep analysis workflow to identify, understand, and resolve bugs.
Uses **Agent Teamwork** for parallel investigation with real-time collaboration.
**ULTRA THINK** at each phase transition.
</objective>

<quick_start>
```bash
/debug "NullReferenceException in UserService"
/debug paste the error log here
/debug why does login fail on mobile?
```
</quick_start>

<workflow>

## 1. ANALYZE: Deep Log/Error Analysis (inline)

- Parse the provided log/error message carefully
- Extract key error patterns, stack traces, and symptoms
- Identify error types: runtime, compile-time, logic, performance
- **CRITICAL**: Document exact error context and reproduction steps
- Determine investigation scope (see decision matrix below)

### Decision Matrix — Team vs. Inline

| Condition | Action |
|-----------|--------|
| Simple error, obvious from stack trace | NO team — investigate inline |
| Error involves code + data | Team: `code-investigator` + `data-inspector` |
| Error involves unknown library | Team: `code-investigator` + `doc-researcher` |
| Complex bug, multiple suspects | Full team: all 3 agents |
| Performance issue (no error) | `code-investigator` only (profiling inline) |

**If team NOT needed** → skip to phase 3 (ULTRA-THINK) with inline investigation.
**If team needed** → proceed to phase 2.

## 2. EXPLORE: Team Investigation

> **Reference:** Load `references/team-protocol.md` for full protocol details.

### 2.1 Create Team

```yaml
TeamCreate:
  team_name: "debug-investigate"
  description: "Parallel bug investigation"
```

### 2.2 Spawn Teammates (single message, parallel Task calls)

Spawn all relevant teammates simultaneously:

**code-investigator** (`general-purpose`, haiku)
```
You are a code investigator on the debug team.

## Bug Context
Error: {error_description}
Stack trace: {stack_trace}

## Mission
1. Locate the error source in code (from stack trace)
2. Find related error handling patterns
3. Identify similar code that works correctly (for comparison)
4. Check recent commits on affected files (git log, git blame)
5. Search for similar error patterns elsewhere in codebase

## Communication
- Send FINDING messages to team-lead for each significant discovery:
  SendMessage(type: "message", recipient: "team-lead", content: "FINDING: {description with file:line}", summary: "Found {short}")
- When done:
  SendMessage(type: "message", recipient: "team-lead", content: "INVESTIGATION_COMPLETE: {summary}", summary: "Code investigation done")
- If team-lead sends a LEAD_HINT, follow that direction

## Rules
- Bash ONLY for: git log, git blame, git diff (NEVER modify code)
- Report file paths with line numbers
- Be precise and factual
```

**doc-researcher** (`general-purpose`, haiku)
```
You are a documentation researcher on the debug team.

## Bug Context
Error: {error_description}
Libraries: {libraries_in_stacktrace}

## Mission
1. Research documentation for libraries in the stack trace
2. Find known issues or breaking changes
3. Find correct usage patterns
4. Search for similar issues reported online
5. Look for migration guides if version issues suspected

## Communication
- Send FINDING messages to team-lead for each discovery:
  SendMessage(type: "message", recipient: "team-lead", content: "FINDING: {description}", summary: "Found {short}")
- When done:
  SendMessage(type: "message", recipient: "team-lead", content: "INVESTIGATION_COMPLETE: {summary}", summary: "Doc research done")
- If team-lead sends a LEAD_HINT, follow that direction
```

**data-inspector** (`general-purpose`, haiku) — *only if bug involves data/persistence/DB*
```
You are a READ-ONLY database inspector on the debug team.

## Bug Context
Error: {error_description}

## ABSOLUTE RESTRICTIONS
YOU MUST NEVER EXECUTE: INSERT, UPDATE, DELETE, MERGE, TRUNCATE, DROP, ALTER, CREATE, EXEC, dotnet ef database update, dotnet ef migrations
YOU MAY ONLY EXECUTE: SELECT, INFORMATION_SCHEMA, sys.* views, sp_help

## Mission
1. Find connection string (appsettings.json, appsettings.Development.json)
2. Check record existence and field values for affected entities
3. Verify FK integrity (orphaned records)
4. Check tenant isolation (TenantId on all records)
5. Verify soft delete and audit field consistency
6. Compare schema vs expected EF Core model

## Communication
- Send FINDING messages to team-lead for each data anomaly:
  SendMessage(type: "message", recipient: "team-lead", content: "FINDING: {description}", summary: "Data issue {short}")
- When done:
  SendMessage(type: "message", recipient: "team-lead", content: "INVESTIGATION_COMPLETE: {summary}", summary: "DB inspection done")
- If team-lead sends a LEAD_HINT, follow that direction

## Rules
- Bash ONLY for SELECT queries (NEVER modify data)
- If a fix is needed, DESCRIBE it — NEVER execute it
- Mask sensitive data (passwords, tokens, PII)
- Limit results with TOP/LIMIT
```

### 2.3 Orchestrate — Lead Actions During Investigation

While teammates investigate in parallel:

- **Monitor** incoming `FINDING` messages from agents
- **Cross-reference** findings between agents (code ↔ data ↔ docs)
- **Send `LEAD_HINT`** when one agent's finding informs another:
  ```yaml
  SendMessage:
    type: "message"
    recipient: "data-inspector"
    content: "LEAD_HINT: code-investigator found null FK at OrderService.cs:45 — check if Customer records exist for affected OrderIds"
    summary: "Investigate FK from code finding"
  ```
- **Additional inline investigation**: Grep for error patterns, check related files, examine recent commits

### 2.4 Aggregate & Shutdown

Wait for all `INVESTIGATION_COMPLETE` messages, then:

1. Collect all `FINDING` messages from each agent
2. Cross-reference: code issues ↔ data anomalies ↔ documentation
3. Shutdown teammates:
   ```yaml
   SendMessage:
     type: "shutdown_request"
     recipient: "{each-teammate}"
     content: "Investigation complete"
   # Wait for shutdown_response, then:
   TeamDelete
   ```

## 3. ULTRA-THINK: Deep Root Cause Analysis (inline)

**THINK DEEPLY** about the error chain: symptoms → immediate cause → root cause

Aggregate all team findings and consider:
- Code logic errors
- Configuration issues
- Data integrity problems (from data-inspector findings)
- Environment problems
- Race conditions
- Memory issues
- Network problems

**CRITICAL**: Map the complete failure path from root cause to visible symptom
Validate hypotheses against evidence from ALL agents

### WHY Technique

Ask "why" at least 5 times:
1. Why did the error occur? → X happened
2. Why did X happen? → Y was in invalid state
3. Why was Y invalid? → Z didn't initialize properly
4. Why didn't Z initialize? → A dependency was missing
5. Why was dependency missing? → Configuration error

## 4. RESEARCH: Solution Investigation (inline or websearch)

If root cause needs further research:

- Use `WebSearch` inline for targeted solution search
- Check documentation for affected libraries/frameworks
- Look for known bugs, workarounds, and best practices
- **THINK**: Evaluate solution approaches for this specific context

## 5. IMPLEMENT: Systematic Resolution (inline, lead only)

- Choose the most appropriate solution based on analysis
- Follow existing codebase patterns and conventions
- Implement minimal, targeted fixes
- **STAY IN SCOPE**: Fix only what's needed for this specific bug
- Add defensive programming where appropriate

## 6. VERIFY: Comprehensive Testing (inline)

- Test the specific scenario that was failing
- Run related tests to ensure no regressions
- Check edge cases around the fix
- **CRITICAL**: Verify the original error is completely resolved

</workflow>

<analysis_techniques>

### Log Analysis
- Extract timestamps, error codes, stack traces
- Identify error propagation patterns
- Look for correlation with system events

### Code Investigation
- Trace execution path to error location
- Check variable states and data flow
- Examine error handling patterns
- Review recent commits affecting the area

### Root Cause Mapping
- **WHY technique**: Ask "why" 5 times minimum
- Consider environmental factors
- Check for timing/concurrency issues
- Validate assumptions about data/state
- Cross-reference team findings (code ↔ data ↔ docs)

</analysis_techniques>

<execution_rules>

- **ULTRA THINK** at each phase transition
- Use **Agent Teamwork** for parallel investigation (see decision matrix)
- Document findings and reasoning at each step
- **NEVER guess** — validate all hypotheses with evidence
- **MINIMAL CHANGES**: Fix root cause, not symptoms
- Test thoroughly before declaring resolution complete
- **ALWAYS cleanup**: shutdown teammates + TeamDelete after investigation

</execution_rules>

<priority>
Understanding > Speed > Completeness. Every bug must be fully understood before attempting fixes.
</priority>

<success_criteria>
- Root cause identified with evidence (not just symptoms)
- Fix implemented with minimal, targeted changes
- Original error no longer reproducible
- Related tests pass without regressions
- Team properly shut down (no orphan agents)
</success_criteria>
