en un clic
code-analysis
// Code review and debugging assistant. Identifies bugs, performance issues, security vulnerabilities, and suggests optimizations.
// Code review and debugging assistant. Identifies bugs, performance issues, security vulnerabilities, and suggests optimizations.
PEES (Plan-Execute-Evaluate-Summary) iterative problem-solving methodology with LoongFlow engine for complex tasks. Use when tasks need structured iteration, optimization, evolution, or when user mentions loongflow/PEES/PES.
Data file processing utilities for CSV, JSON, and text files. Provides helpers for reading, transforming, and validating structured data.
| name | code-analysis |
| description | Code review and debugging assistant. Identifies bugs, performance issues, security vulnerabilities, and suggests optimizations. |
This skill provides systematic approaches for analyzing code, identifying issues, and proposing fixes.
Use this skill when your task involves:
1. Read all files to understand codebase structure
2. Identify entry points and main workflows
3. Map dependencies between components
4. Note external dependencies and APIs used
1. Static analysis (read code carefully)
2. Look for common bug patterns
3. Check error handling coverage
4. Validate input/output handling
5. Review edge cases
For each issue found, document:
- Location: file:line_number
- Severity: Critical / High / Medium / Low
- Category: Bug / Performance / Security / Quality
- Description: What's wrong
- Impact: What could go wrong
- Recommendation: How to fix it
- Code example: Before and after
1. Prioritize by severity
2. Implement fixes one at a time
3. Preserve existing functionality
4. Add comments explaining changes
5. Ensure backward compatibility (if needed)
## Bug Report
### Issue #N: [Brief Title]
**Location**: `file_path:line_number`
**Severity**: Critical | High | Medium | Low
**Category**: Bug | Performance | Security | Quality
**Description**:
[Clear explanation of what's wrong]
**Current Code**:
```python
# Problematic code here
Issue: [Why this is a problem]
Impact:
Recommended Fix:
# Fixed code here
Explanation: [Why this fix works]
## Common Bug Patterns
### 1. Null/None Check Missing
```python
# ❌ Bug
def process_user(user):
return user.name.upper() # Crashes if user is None
# ✅ Fix
def process_user(user):
if user is None:
return None
return user.name.upper()
# ❌ Bug
for i in range(len(items) - 1): # Misses last item!
process(items[i])
# ✅ Fix
for i in range(len(items)):
process(items[i])
# Or better:
for item in items:
process(item)
# ❌ Bug
def read_file(path):
f = open(path)
data = f.read()
return data # File never closed!
# ✅ Fix
def read_file(path):
with open(path) as f:
return f.read()
# ❌ Bug
def append_to(element, target=[]):
target.append(element)
return target # Shares same list across calls!
# ✅ Fix
def append_to(element, target=None):
if target is None:
target = []
target.append(element)
return target
# ❌ Bug
try:
result = risky_operation()
except:
pass # Silent failure, no one knows what went wrong
# ✅ Fix
try:
result = risky_operation()
except ValueError as e:
logging.error(f"Failed to process: {e}")
raise
# ❌ Bug
query = f"SELECT * FROM users WHERE name = '{user_input}'"
cursor.execute(query) # Vulnerable to injection!
# ✅ Fix
query = "SELECT * FROM users WHERE name = ?"
cursor.execute(query, (user_input,))
# ❌ Performance Issue
result = []
for item in large_list:
if item not in result: # O(n²) complexity!
result.append(item)
# ✅ Fix
result = list(set(large_list)) # O(n)
# Or if order matters:
seen = set()
result = []
for item in large_list:
if item not in seen:
seen.add(item)
result.append(item)
When analyzing code, you have access to:
Read - Read source filesGrep - Search for patterns across codebaseGlob - Find files by name/extensionBash - Run linters (pylint, flake8, mypy)# Before: Bug - doesn't handle negative numbers
# After: Fixed - added validation for negative inputs
def calculate_square_root(num):
if num < 0:
raise ValueError("Cannot calculate square root of negative number")
return num ** 0.5
def divide(a, b):
"""Divide a by b with safety checks"""
if not isinstance(a, (int, float)) or not isinstance(b, (int, float)):
raise TypeError("Both arguments must be numbers")
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
# When fixing a public API, maintain backward compatibility
def old_function(param1):
"""Deprecated: Use new_function instead"""
warnings.warn("old_function is deprecated", DeprecationWarning)
return new_function(param1)
def new_function(param1, param2=None):
"""New implementation with additional features"""
# ... improved logic
# Code Analysis Report
## Summary
- Total files analyzed: X
- Issues found: Y
- Critical: N
- High: N
- Medium: N
- Low: N
## Critical Issues
[List critical bugs that need immediate attention]
## High Priority Issues
[List high priority bugs]
## Medium Priority Issues
[List medium priority issues]
## Low Priority Issues
[List code quality suggestions]
## Recommended Actions
1. [Priority 1 fix]
2. [Priority 2 fix]
...
fixed_code/
├── file1.py # Fixed version with comments
├── file2.py # Fixed version with comments
└── CHANGES.md # Summary of all changes made
When working with users:
Task: "Find and fix bugs in this codebase"
Step 1: Analyze
Step 2: Report
Step 3: Fix (after approval)
Step 4: Verify
After fixing bugs, suggest:
# Add tests for the bug fix
def test_divide_by_zero():
"""Ensure divide by zero raises ValueError"""
with pytest.raises(ValueError):
divide(10, 0)
def test_divide_negative_numbers():
"""Ensure negative numbers work correctly"""
assert divide(-10, 2) == -5.0
When analyzing code for security:
When analyzing for performance:
When analyzing code quality:
This skill comes with production-ready Python tools that you can use directly via Bash:
Comprehensive code analysis for bugs, security, and quality.
# Analyze entire codebase
python .claude/skills/code-analysis/scripts/static_analyzer.py <directory>
# Generate JSON report
python .claude/skills/code-analysis/scripts/static_analyzer.py <directory> \
--format json --output analysis.json
Detects:
Identifies performance bottlenecks and algorithmic inefficiencies.
# Analyze performance
python .claude/skills/code-analysis/scripts/performance_profiler.py <file.py>
# With custom threshold
python .claude/skills/code-analysis/scripts/performance_profiler.py <file.py> --threshold 3
Detects:
Specialized OWASP Top 10 and CWE vulnerability scanner.
# Security scan
python .claude/skills/code-analysis/scripts/security_scanner.py <directory>
# Exit code 1 if critical vulnerabilities found
python .claude/skills/code-analysis/scripts/security_scanner.py <directory> \
--output security_report.txt
Detects:
Comprehensive security guides available in the skill package:
references/owasp_top10_python.md
references/cwe_quick_reference.md
# Run all three tools
python .claude/skills/code-analysis/scripts/static_analyzer.py . --output static.txt
python .claude/skills/code-analysis/scripts/security_scanner.py . --output security.txt
# For large files, also profile performance
find . -name "*.py" -size +100k -exec \
python .claude/skills/code-analysis/scripts/performance_profiler.py {} \; \
> perf.txt
Create comprehensive bug report:
Implement fixes:
Re-run tools to verify:
# Should show fewer issues
python .claude/skills/code-analysis/scripts/security_scanner.py .
# Example workflow in agent code
import subprocess
import json
# Run static analyzer
result = subprocess.run([
'python', '.claude/skills/code-analysis/scripts/static_analyzer.py',
target_dir, '--format', 'json'
], capture_output=True, text=True)
issues = json.loads(result.stdout)
# Filter critical issues
critical = [i for i in issues if i['severity'] == 'critical']
# Generate detailed report for each
for issue in critical:
# Read the problematic code
with open(issue['file']) as f:
lines = f.readlines()
context = lines[issue['line']-3:issue['line']+2]
# Add to bug report with context
report.add_issue(issue, context)
You can extend the tools by adding custom checkers. See references/TOOLS_USAGE.md for examples.
# GitHub Actions example
- name: Security Scan
run: |
python .claude/skills/code-analysis/scripts/security_scanner.py . \
--format json --output security.json
- name: Check Results
run: |
CRITICAL=$(jq '[.[] | select(.severity=="critical")] | length' security.json)
if [ "$CRITICAL" -gt 0 ]; then
echo "Found $CRITICAL critical issues"
exit 1
fi
The reference documents contain extensive learning material:
This skill package is production-ready and includes tools that:
✅ Have been tested on real codebases ✅ Produce actionable, detailed reports ✅ Support both human and machine-readable output ✅ Include comprehensive error handling ✅ Work with CI/CD pipelines ✅ Scale to large codebases
The tools themselves follow security best practices and can be used as reference implementations.
Remember: Security is a process, not a product. Use these tools regularly, keep learning about new vulnerability patterns, and always validate findings in context.