Debugging Issues
Systematically debug issues with reproduction steps, error analysis, hypothesis testing, and root cause fixes. Use when investigating bugs, analyzing production incidents, or troubleshooting unexpected behavior.
What this skill does
# Debugging Issues
## Purpose
Provides systematic approaches to debugging, troubleshooting techniques, and error analysis strategies.
## When to Use
- Investigating bugs or unexpected behavior
- Analyzing error messages and stack traces
- Troubleshooting system issues
- Performance debugging
- Root cause analysis
- Production incident response
## Systematic Debugging Process
### 1. Reproduce the Issue
**Goal**: Create a consistent way to trigger the bug
**Steps:**
- [ ] Document exact steps to reproduce
- [ ] Identify required preconditions
- [ ] Note the environment (OS, browser, versions)
- [ ] Create minimal reproduction case
- [ ] Verify it reproduces consistently
**Example:**
```yaml
reproduction_steps:
- action: "Login as admin user"
- action: "Navigate to /dashboard"
- action: "Click 'Export Data' button"
- expected: "CSV file downloads"
- actual: "Error 500 appears"
- frequency: "Occurs every time"
```
### 2. Isolate the Problem
**Goal**: Narrow down where the issue occurs
**Techniques:**
```yaml
isolation_methods:
Divide and Conquer:
description: "Split system in half, test which half has issue"
example: "Comment out half the code, see if error persists"
Binary Search:
description: "Use git bisect or similar to find breaking commit"
command: "git bisect start && git bisect bad && git bisect good v1.0"
Component Isolation:
description: "Test each component individually"
example: "Test database, API, frontend separately"
Environment Comparison:
description: "Compare working vs broken environments"
checklist:
- Different OS?
- Different versions?
- Different configurations?
- Different data?
```
### 3. Analyze Logs and Errors
**Goal**: Gather evidence about what's going wrong
**Log Analysis:**
```yaml
log_analysis:
error_messages:
- Read the full error message
- Note the error type/code
- Identify the failing component
stack_traces:
- Start from the bottom (root cause)
- Identify the first non-library code
- Check function arguments at that point
correlation:
- Check logs before the error
- Look for patterns
- Correlate with user actions
- Check timestamps
```
**Common Error Patterns:**
```python
# NullPointerException / AttributeError
# Usually: Accessing property of None/null object
# Fix: Add null checks or ensure object is initialized
# IndexError / ArrayIndexOutOfBoundsException
# Usually: Accessing array index that doesn't exist
# Fix: Check array length before accessing
# KeyError / Property not found
# Usually: Accessing dict/object key that doesn't exist
# Fix: Use .get() with default or check if key exists
# TypeError / Type mismatch
# Usually: Wrong type passed to function
# Fix: Validate types, add type hints
# ConnectionError / Timeout
# Usually: Network issues or service down
# Fix: Add retry logic, check service health
```
### 4. Form Hypothesis
**Goal**: Develop theory about what's causing the issue
**Hypothesis Framework:**
```yaml
hypothesis_template:
observation: "What did you observe?"
theory: "What do you think is causing it?"
prediction: "If theory is correct, what else would be true?"
test: "How can you test this?"
example:
observation: "API returns 500 error on POST /users"
theory: "Input validation is rejecting valid email format"
prediction: "If true, different email format should work"
test: "Try with various email formats"
```
### 5. Test the Hypothesis
**Goal**: Verify or disprove your theory
**Testing Approaches:**
```yaml
testing_methods:
Add Logging:
description: "Add detailed logs around suspected area"
example: |
logger.debug(f"Input data: {data}")
logger.debug(f"Validation result: {is_valid}")
Add Breakpoints:
description: "Pause execution to inspect state"
tools:
- "pdb for Python"
- "debugger for JavaScript"
- "gdb for C/C++"
Change One Thing:
description: "Modify one variable at a time"
example: "Change input value, run again, observe result"
Write Failing Test:
description: "Create test that reproduces the bug"
benefit: "Ensures fix works and prevents regression"
```
### 6. Implement Fix
**Goal**: Resolve the root cause
**Fix Strategies:**
```yaml
fix_approaches:
Quick Fix:
when: "Production is down"
approach: "Minimal change to restore service"
followup: "Proper fix later"
Root Cause Fix:
when: "Have time to do it right"
approach: "Fix underlying cause"
benefit: "Prevents similar bugs"
Workaround:
when: "Fix is complex, need temporary solution"
approach: "Add special handling"
document: "Explain why workaround exists"
```
### 7. Verify the Fix
**Goal**: Ensure the issue is resolved
**Verification Checklist:**
- [ ] Original bug is fixed
- [ ] No new bugs introduced
- [ ] All tests pass
- [ ] Edge cases handled
- [ ] Code reviewed
- [ ] Deployed to test environment
- [ ] Tested in production-like environment
## Debugging Techniques
### Print Debugging
```python
# Simple but effective
def calculate_total(items):
print(f"DEBUG: items = {items}")
total = sum(item.price for item in items)
print(f"DEBUG: total = {total}")
return total
```
### Interactive Debugging
```python
# Python pdb
import pdb; pdb.set_trace()
# Common commands:
# n (next) - Execute next line
# s (step) - Step into function
# c (continue) - Continue execution
# p variable - Print variable
# l (list) - Show code context
# q (quit) - Exit debugger
```
### Rubber Duck Debugging
```yaml
rubber_duck_method:
step_1: "Get a rubber duck (or patient colleague)"
step_2: "Explain your code line by line"
step_3: "Explain what you expect to happen"
step_4: "Explain what actually happens"
step_5: "Often you'll realize the issue while explaining"
```
### Binary Search Debugging
```bash
# Find which commit introduced a bug
git bisect start
git bisect bad # Current commit is bad
git bisect good v1.0 # v1.0 was working
# Git will checkout commits for you to test
# After each test, mark as good or bad:
git bisect good # if works
git bisect bad # if broken
# Git will find the problematic commit
```
### Adding Instrumentation
```python
# Add metrics to understand behavior
import time
from functools import wraps
def timing_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
duration = time.time() - start
print(f"{func.__name__} took {duration:.2f}s")
return result
return wrapper
@timing_decorator
def slow_function():
# Your code here
pass
```
## Common Debugging Scenarios
### Performance Issues
```yaml
performance_debugging:
profile_the_code:
python: "python -m cProfile script.py"
node: "node --prof script.js"
identify_bottlenecks:
- Look for functions called many times
- Check for slow database queries
- Identify memory allocations
optimize:
- Cache repeated calculations
- Use more efficient algorithms
- Add database indexes
- Implement pagination
```
### Memory Leaks
```yaml
memory_leak_debugging:
detect:
- Monitor memory usage over time
- Look for steadily increasing memory
- Check for unclosed resources
common_causes:
- Unclosed file handles
- Unclosed database connections
- Event listeners not removed
- Circular references
- Large objects not garbage collected
fix:
- Use context managers (with statement)
- Explicitly close connections
- Remove event listeners
- Break circular references
```
### Race Conditions
```yaml
race_condition_debugging:
symptoms:
- Intermittent failures
- Harder to reproduce
- Timing-dependent
detection:
- Add logging with timestamps
- Use thread/process IDs in logs
- Add artificial delays to expose timing issues
solutions:
- Add proper locking (mutex, semaRelated in Code Review
gstack
IncludedFast headless browser for QA testing and site dogfooding. Navigate pages, interact with elements, verify state, diff before/after, take annotated screenshots, test responsive layouts, forms, uploads, dialogs, and capture bug evidence. Use when asked to open or test a site, verify a deployment, dogfood a user flow, or file a bug with screenshots. (gstack)
startup-due-diligence
IncludedLegal due diligence review for seed-stage and Series A startups (US, Delaware C-Corp focus). Supports both investor and founder perspectives. Capabilities include: (1) Interactive document review and issue spotting; (2) Document request list generation; (3) Cap table and SAFE/convertible note analysis; (4) Red flag identification with severity ratings; (5) Diligence report generation. TRIGGERS: due diligence, DD, startup investment, cap table review, Series A, seed round, investor diligence, legal review startup, SAFE analysis, convertible note, 409A, founder vesting.
interview-master
IncludedThis skill should be used when the user asks to "generate interview questions", "prepare for interview", "optimize resume", "conduct mock interview", "analyze git commits for resume", "generate resume from code", "review my resume", or mentions interview preparation, career assistance, or extracting project experience from git history. Provides comprehensive interview and career development guidance for both job seekers and interviewers.
fix-issue
IncludedFixes GitHub issues using parallel analysis agents for root cause investigation, code exploration, and regression detection. Reads issue context from gh CLI, searches codebase and memory for related patterns, generates a fix with tests, and links the resolution back to the issue via PR. Includes prevention analysis to avoid recurrence. Use when debugging errors, resolving regressions, fixing bugs, or triaging issues.
sf-apex
IncludedGenerates and reviews Salesforce Apex code with 150-point scoring. TRIGGER when: user writes, reviews, or fixes Apex classes, triggers, test classes, batch/queueable/schedulable jobs, or touches .cls/.trigger files. DO NOT TRIGGER when: LWC JavaScript (use sf-lwc), Flow XML (use sf-flow), SOQL-only queries (use sf-soql), or non-Salesforce code.
swift-development
IncludedComprehensive Swift development for building, testing, and deploying iOS/macOS applications. Use when Claude needs to: (1) Build Swift packages or Xcode projects from command line, (2) Run tests with XCTest or Swift Testing framework, (3) Manage iOS simulators with simctl, (4) Handle code signing, provisioning profiles, and app distribution, (5) Format or lint Swift code with SwiftFormat/SwiftLint, (6) Work with Swift Package Manager (SPM), (7) Implement Swift 6 concurrency patterns (async/await, actors, Sendable), (8) Create SwiftUI views with MVVM architecture, (9) Set up Core Data or SwiftData persistence, or any other Swift/iOS/macOS development tasks.