Skip to main content
ClaudeWave
Skill85 estrellas del repoactualizado 3mo ago

bug-to-patch-generator

Generate code fixes and patches from bug reports, failing test cases, error messages, and stack traces. Use this skill when debugging code, fixing test failures, addressing GitHub issues, resolving runtime errors, or patching security vulnerabilities. Analyzes the bug context, identifies root causes, and generates precise code patches with explanations and validation steps.

Instalar en Claude Code
Copiar
git clone --depth 1 https://github.com/ArabelaTso/Skills-4-SE /tmp/bug-to-patch-generator && cp -r /tmp/bug-to-patch-generator/skills/bug-to-patch-generator ~/.claude/skills/bug-to-patch-generator
Después abre una sesión nueva de Claude Code; el skill carga automáticamente.

SKILL.md

# Bug-to-Patch Generator

Automatically generate code fixes from bug reports, failing tests, error messages, and stack traces. Analyzes bug context, identifies root causes, and produces verified patches.

## Core Capabilities

### 1. Bug Analysis

Understand bugs from multiple sources:
- **Failing test cases** - Analyze test failures and expected vs actual behavior
- **Error messages** - Parse exceptions, stack traces, and error logs
- **Bug reports** - Process issue descriptions, reproduction steps, and screenshots
- **Crash dumps** - Interpret segmentation faults, core dumps, and memory errors
- **Runtime errors** - Handle assertion failures, type errors, and logic bugs

### 2. Root Cause Identification

Determine the underlying issue:
- Trace error back to source
- Identify incorrect logic or assumptions
- Find missing validation or edge cases
- Detect off-by-one errors and boundary issues
- Recognize concurrency problems
- Spot resource leaks and memory issues

### 3. Patch Generation

Create targeted fixes:
- Minimal, focused changes
- Preserve existing functionality
- Follow code style and patterns
- Include safety checks where needed
- Add comments explaining the fix
- Suggest related improvements

### 4. Patch Validation

Ensure fix correctness:
- Verify fix addresses the bug
- Check for regression risks
- Suggest validation tests
- Recommend manual verification steps
- Consider edge cases and side effects

## Bug-to-Patch Workflow

### Step 1: Gather Bug Context

Collect all relevant information:

**From failing tests:**
```python
FAILED tests/test_calculator.py::test_divide - ZeroDivisionError: division by zero

def test_divide():
    result = divide(10, 0)
    assert result == None  # Expected to return None for division by zero
```

**From error messages:**
```
Traceback (most recent call last):
  File "app.py", line 42, in process_data
    result = data[index]
IndexError: list index out of range
```

**From bug reports:**
```
Title: App crashes when processing empty file
Steps to reproduce:
1. Upload empty CSV file
2. Click "Process"
3. App crashes with NoneType error

Expected: Error message shown to user
Actual: Application crashes
```

### Step 2: Analyze the Bug

Identify the root cause:

**Questions to answer:**
- What is the exact error?
- Where does it occur? (file, line, function)
- What are the preconditions?
- What input triggers it?
- What was expected vs what happened?
- Is it a logic error, validation issue, or edge case?

**Common bug patterns:**
- Missing null/None checks
- Off-by-one errors
- Incorrect boundary conditions
- Missing error handling
- Wrong operator or comparison
- Race conditions
- Resource leaks
- Type mismatches

### Step 3: Locate Relevant Code

Find the code that needs fixing:

```python
# Read the source file
def divide(a, b):
    return a / b  # Bug: No check for b == 0
```

**Context needed:**
- The buggy function/method
- Related functions it calls
- Caller functions
- Test cases
- Similar correct implementations

### Step 4: Generate the Patch

Create minimal, focused fix:

**Patch format:**
```python
# Before (buggy code)
def divide(a, b):
    return a / b

# After (fixed code)
def divide(a, b):
    if b == 0:
        return None  # or raise ValueError("Cannot divide by zero")
    return a / b
```

**Patch components:**
1. Clear before/after comparison
2. Explanation of the fix
3. Why this approach was chosen
4. Potential alternatives
5. Edge cases now handled

### Step 5: Validate the Fix

Ensure correctness:

**Validation steps:**
```python
# Test that should now pass
def test_divide_by_zero():
    assert divide(10, 0) is None

# Additional tests for edge cases
def test_divide_normal():
    assert divide(10, 2) == 5

def test_divide_negative():
    assert divide(-10, 2) == -5
```

**Verification checklist:**
- [ ] Original test now passes
- [ ] Existing tests still pass (no regression)
- [ ] Edge cases handled
- [ ] Error messages are clear
- [ ] Performance not degraded

## Bug Fix Patterns

### Pattern 1: Missing Null/None Check

**Bug report:**
```
AttributeError: 'NoneType' object has no attribute 'upper'
```

**Buggy code:**
```python
def format_name(name):
    return name.upper()
```

**Root cause:** No validation for None input

**Patch:**
```python
def format_name(name):
    if name is None:
        return ""  # or raise ValueError("Name cannot be None")
    return name.upper()
```

**Explanation:**
- Added None check before accessing string method
- Returns empty string for None (or could raise exception)
- Prevents AttributeError

**Alternative approaches:**
```python
# Option 1: Raise exception
def format_name(name):
    if name is None:
        raise ValueError("Name cannot be None")
    return name.upper()

# Option 2: Use default parameter
def format_name(name=None):
    return (name or "").upper()

# Option 3: Type hint and early return
def format_name(name: str | None) -> str:
    if not name:
        return ""
    return name.upper()
```

### Pattern 2: Off-by-One Error

**Bug report:**
```
IndexError: list index out of range
```

**Failing test:**
```python
def test_get_last_element():
    arr = [1, 2, 3]
    assert get_element(arr, 3) == 3  # Want last element
```

**Buggy code:**
```python
def get_element(arr, index):
    return arr[index]  # index 3 is out of bounds for length 3
```

**Root cause:** Confusion between length and index (0-based)

**Patch:**
```python
def get_element(arr, index):
    if index < 0 or index >= len(arr):
        raise IndexError(f"Index {index} out of range for array of length {len(arr)}")
    return arr[index]
```

**Explanation:**
- Added bounds checking
- Clear error message
- Handles negative indices too

**Better alternative:**
```python
def get_element(arr, index):
    """Get element at index. Supports negative indexing."""
    try:
        return arr[index]
    except IndexError:
        raise IndexError(f"Index {index} out of range for array of length {len(arr)}")
```

### Pa
abstract-domain-explorerSkill

Applies abstract interpretation using different abstract domains (intervals, octagons, polyhedra, sign, congruence) to statically analyze program variables and infer invariants, value ranges, and relationships. Use when analyzing program properties, inferring loop invariants, detecting potential errors, or understanding variable relationships through static analysis.

abstract-invariant-generatorSkill

Uses abstract interpretation to automatically infer loop invariants, function preconditions, and postconditions for formal verification. Generates invariants that capture program behavior and support correctness proofs in Dafny, Isabelle, Coq, and other verification systems. Use when adding formal specifications to code, generating verification conditions, inferring contracts for functions, or discovering loop invariants for proofs.

abstract-state-analyzerSkill

Performs abstract interpretation over source code to infer possible program states, variable ranges, and data properties without executing the program. Reports potential runtime errors including out-of-bounds accesses, null dereferences, type inconsistencies, division by zero, and integer overflows. Use when analyzing code for potential runtime errors, performing static analysis, checking safety properties, or verifying program behavior without execution.

abstract-trace-summarizerSkill

Performs abstract interpretation to produce summarized execution traces and high-level program behavior representations. Highlights key control flow paths, variable relationships, loop invariants, function summaries, and potential runtime states using abstract domains (intervals, signs, nullness, etc.). Use when analyzing program behavior, understanding execution paths, computing loop invariants, tracking variable ranges, detecting potential runtime errors, or generating program summaries without concrete execution.

acsl-annotation-assistantSkill

Create ACSL (ANSI/ISO C Specification Language) formal annotations for C/C++ programs. Use this skill when working with formal verification, adding function contracts (requires/ensures), loop invariants, assertions, memory safety annotations, or any ACSL specifications. Supports Frama-C verification and generates comprehensive formal specifications for C/C++ code.

agent-browserSkill

CLI-based browser automation with persistent page state using ref-based element interaction. Use when users ask to navigate websites, interact with web pages, fill forms, take screenshots, test web applications, or extract information from web pages.

ambiguity-detectorSkill

Detects and analyzes ambiguous language in software requirements and user stories. Use when reviewing requirements documents, user stories, specifications, or any software requirement text to identify vague quantifiers, unclear scope, undefined terms, missing edge cases, subjective language, and incomplete specifications. Provides detailed analysis with clarifying questions and suggested improvements.

api-design-assistantSkill

Design and review APIs with suggestions for endpoints, parameters, return types, and best practices. Use when designing new APIs from requirements, reviewing existing API designs, generating API documentation, or getting implementation guidance. Supports REST APIs with focus on endpoint structure, request/response schemas, authentication, pagination, filtering, versioning, and OpenAPI specifications. Triggers when users ask to design, review, document, or improve APIs.