Skip to content

matthewnyc2/Bug-Fixing-AI-Assistant

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

6 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Bug-Fixing-AI-Assistant πŸ€–πŸ”§

An intelligent AI-powered assistant that automatically scans codebases for bugs, generates fixes using Claude or GPT, validates changes with automated tests, and integrates fixes into your codebase via pull requests.

Python 3.7+ Tests License: MIT

Project Structure

Bug-Fixing-AI-Assistant/
β”œβ”€β”€ scanner/                 # Code scanning and bug detection
β”‚   β”œβ”€β”€ core/               # Core scanning functionality
β”‚   β”‚   β”œβ”€β”€ scanner.py      # Base scanner class
β”‚   β”‚   └── report.py       # Report generation
β”‚   └── detectors/          # Bug detection modules
β”‚       β”œβ”€β”€ pattern_detector.py    # Pattern-based bug detection
β”‚       └── security_detector.py   # Security vulnerability detection
β”œβ”€β”€ fixer/                  # Bug fixing and code generation
β”‚   β”œβ”€β”€ generators/         # Fix generation modules
β”‚   β”‚   β”œβ”€β”€ fix_generator.py      # Base fix generator
β”‚   β”‚   └── patch_generator.py    # Patch and diff generation
β”‚   └── validators/         # Fix validation modules
β”‚       β”œβ”€β”€ fix_validator.py      # Fix syntax validation
β”‚       └── test_runner.py        # Test execution
β”œβ”€β”€ pr-handler/             # Pull request management
β”‚   └── pr_creator.py       # PR creation and management
β”œβ”€β”€ examples/               # Example buggy and fixed code
β”‚   β”œβ”€β”€ buggy_code.py       # Intentionally buggy code samples
β”‚   β”œβ”€β”€ fixed_code.py       # Fixed versions of buggy code
β”‚   └── README.md           # Example documentation
└── tests/                  # Comprehensive test suite
    β”œβ”€β”€ test_scanner.py     # Scanner tests
    β”œβ”€β”€ test_detectors.py   # Detector tests
    β”œβ”€β”€ test_fixer.py       # Fixer tests
    β”œβ”€β”€ test_pr_handler.py  # PR handler tests
    └── README.md           # Test documentation

✨ Features

1. πŸ” Intelligent Code Scanning

  • Pattern Detection: Identifies common code anti-patterns
    • None comparison using == instead of is
    • Bare except clauses
    • Mutable default arguments
    • Wildcard imports
  • Security Analysis: Detects security vulnerabilities
    • Dangerous eval() and exec() usage
    • Unsafe deserialization (pickle)
    • Insecure module imports
  • Code Quality: Analyzes code quality issues
    • High cyclomatic complexity
    • Too many function arguments
    • Missing docstrings
    • Magic numbers
    • Functions with too many methods (God objects)

2. πŸ€– AI-Powered Fix Generation

  • Claude Integration: Uses Anthropic's Claude for intelligent fixes
  • OpenAI Integration: Supports GPT-4 and GPT-3.5-turbo
  • Context-Aware: Provides surrounding code context to AI
  • Confidence Scoring: AI rates fix confidence level
  • Fallback Support: Falls back to rule-based fixes when AI unavailable

3. ⚑ Automated Fix Application

  • Smart Application: Automatically applies fixes to files
  • Backup Creation: Creates backups before modifying files
  • Syntax Validation: Validates fixed code syntax before applying
  • Dry Run Mode: Preview changes without modifying files
  • Batch Processing: Apply multiple fixes at once

4. βœ… Validation & Testing

  • Python Syntax Validation: Ensures fixes don't introduce syntax errors
  • Test Execution: Runs pytest or unittest after fixing
  • Configurable: Control whether tests must pass
  • Fix Verification: Validates fixes before committing

5. πŸ”„ Pull Request Integration

  • Automated Branching: Creates feature branches automatically
  • Smart Commits: Generates descriptive commit messages
  • PR Descriptions: Creates detailed PR descriptions with fix summaries
  • Auto-Push: Optionally pushes to remote automatically
  • GitHub Integration: Works with gh CLI for PR creation

πŸš€ Quick Start

Installation

  1. Clone the repository:
git clone https://github.com/matthewnyc2/Bug-Fixing-AI-Assistant.git
cd Bug-Fixing-AI-Assistant
  1. Install dependencies (optional, for AI features):
# For Anthropic Claude
pip install anthropic

# For OpenAI GPT
pip install openai

# Or install all optional dependencies
pip install -e ".[full]"
  1. Set up your AI API key (optional):
# For Anthropic Claude
export ANTHROPIC_API_KEY=your-api-key-here

# For OpenAI GPT
export OPENAI_API_KEY=your-api-key-here

Command Line Usage

Basic Scanning (No AI)

# Scan current directory and show report
python main.py

# Scan a specific directory
python main.py /path/to/your/project

# Generate JSON report
python main.py --report json

AI-Powered Fixing

# Scan and generate AI fixes (dry run - no changes)
python main.py --ai --dry-run

# Scan, generate AI fixes, and apply them
python main.py --ai --apply

# Full workflow: scan, fix, test, and create PR
python main.py --ai --apply --run-tests --create-pr

Using Configuration File

# Copy example config
cp config.example.yaml config.yaml

# Edit config.yaml with your preferences
# Then run with config
python main.py --config config.yaml --ai --apply

Python API Usage

Simple Scanning

from main import BugFixingAssistant

# Create assistant
assistant = BugFixingAssistant()

# Scan directory
issues = assistant.scan_directory('.')

# Print issues
for issue in issues:
    print(f"{issue['type']} at {issue['file']}:{issue['line']}")

AI-Powered Fixing

from main import BugFixingAssistant
from config import Config

# Create config with AI enabled
config = Config()
config.set('ai.provider', 'anthropic')
config.set('ai.model', 'claude-sonnet-4-5-20250929')

# Create assistant
assistant = BugFixingAssistant(config)

# Scan and fix
issues = assistant.scan_directory('.')
fixes = assistant.generate_fixes(use_ai=True)

# Apply fixes (with backup)
results = assistant.apply_fixes()

# Show what was fixed
for result in results:
    if result['success']:
        print(f"βœ“ Fixed {result['file']}")
        print(result['diff'])

Create Pull Request

from main import BugFixingAssistant

assistant = BugFixingAssistant()
issues = assistant.scan_directory('.')
fixes = assistant.generate_fixes()
assistant.apply_fixes()

# Create PR with fixes
pr_result = assistant.create_pr(fixes)
print(pr_result['pr_description'])

Running Tests

Run all tests:

python -m unittest discover tests -v

Run specific test suite:

python -m unittest tests.test_scanner -v
python -m unittest tests.test_detectors -v
python -m unittest tests.test_fixer -v
python -m unittest tests.test_pr_handler -v

Examples

The examples/ directory contains sample files demonstrating the assistant's capabilities:

  • buggy_code.py: Contains intentional bugs for testing
  • fixed_code.py: Shows corrected versions of the bugs
  • README.md: Detailed explanation of each bug and fix

Test the scanner on examples:

python -c "
from scanner.detectors.pattern_detector import detect_patterns
from scanner.detectors.security_detector import detect_security_issues
from pathlib import Path

file_path = Path('examples/buggy_code.py')
with open(file_path) as f:
    content = f.read()

issues = detect_patterns(file_path, content) + detect_security_issues(file_path, content)
print(f'Found {len(issues)} issues')
"

Development

Project Requirements

  • Python 3.7+
  • No external dependencies for core functionality
  • Uses Python standard library only

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Run tests to ensure everything works
  5. Submit a pull request

Architecture

Scanner Module

The scanner module is responsible for analyzing code and detecting potential issues. It uses Python's ast module for syntax tree analysis.

Fixer Module

The fixer module generates suggested fixes for detected issues. It includes validators to ensure fixes don't introduce new problems.

PR Handler Module

The PR handler automates the process of creating pull requests with fixes, including branch management and commit operations.

πŸ“‹ Supported Issue Types

Issue Type Severity Auto-Fix AI-Fix
Pattern Issues
None comparison (== instead of is) Warning βœ… Yes βœ… Yes
Bare except clause Warning βœ… Yes βœ… Yes
Mutable default argument Warning ❌ No βœ… Yes
Wildcard import Info ❌ No βœ… Yes
Security Issues
Dangerous eval() usage Critical ❌ No βœ… Yes
Dangerous exec() usage Critical ❌ No βœ… Yes
Unsafe pickle deserialization High ❌ No βœ… Yes
Insecure module import Info ❌ No βœ… Yes
Quality Issues
High cyclomatic complexity Warning ❌ No βœ… Yes
Too many function arguments Info ❌ No βœ… Yes
Missing docstrings Info ❌ No βœ… Yes
Magic numbers Info ❌ No βœ… Yes
Too many methods (God object) Warning ❌ No βœ… Yes
Assert in production code Info ❌ No βœ… Yes

Legend:

  • βœ… Yes = Fully automated fix available
  • ❌ No = Requires manual intervention or AI
  • AI-Fix = Can be fixed using AI (Claude/GPT)

🎯 Roadmap & Future Enhancements

Completed βœ…

  • Automated fix application
  • AI-powered bug detection and fixing
  • Code quality metrics and complexity analysis
  • Comprehensive test suite
  • Configuration file support
  • Pull request automation

Planned 🚧

  • Support for more programming languages (JavaScript, TypeScript, Java, Go)
  • Integration with CI/CD pipelines (GitHub Actions, GitLab CI)
  • Web dashboard for visualization
  • Custom rule definitions and plugins
  • Performance optimization analysis
  • Dead code detection
  • Dependency vulnerability scanning
  • Integration with issue trackers (Jira, Linear)
  • Multi-file refactoring support
  • Incremental scanning (only changed files)

License

This project is open source. See LICENSE file for details.

Contact

For questions or suggestions, please open an issue on GitHub.

About

An AI assistant dedicated to scanning codebases for bugs, generating fixes autonomously, validating changes with automated tests, and integrating fixes into the codebase via pull requests.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages