Code Review Inspector
by @michaelatamuk
Automated code review checking for bugs, security issues, best practices, performance problems, and code style
clawhub install code-review-inspectorπ About This Skill
name: code-review-inspector description: Automated code review checking for bugs, security issues, best practices, performance problems, and code style version: 1.0.2 metadata: openclaw: emoji: "π" requires: bins: - git os: ["macos", "linux", "windows"]
Code Review Assistant
Performs AI-assisted code reviews on your changes, helping identify bugs, security vulnerabilities, performance issues, best practice violations, and code style problems. Treats findings as suggestions to complement β not replace β human review and testing.
What This Skill Does
This skill analyzes your code changes and provides detailed feedback on:
Supports multiple languages and frameworks:
Why Use This Skill
Catches Bugs Early
Studies show bugs found in code review are 10-100Γ cheaper to fix than bugs found in production:
Improves Code Quality
Automated review catches issues humans miss:
Accelerates Team Reviews
Makes human code reviews more valuable:
Educational Value
Learn best practices as you code:
When to Use This Skill
Use this skill for comprehensive code review:
When NOT to Use This Skill
How It Works
Step-by-Step Process
1. Analyzes changed files: Reads git diff or specified files 2. Reads code structure: Identifies functions, classes, and logic flow from source text 3. Detects patterns: Identifies anti-patterns, bugs, security issues 4. Checks best practices: Validates against language/framework conventions 5. Evaluates performance: Finds inefficient algorithms, database queries 6. Reviews security: Scans for OWASP vulnerabilities, exposed credentials 7. Assesses style: Checks naming, organization, maintainability 8. Generates report: Prioritized list of issues with explanations and fixes
Review Categories
Critical Issues (Must fix before merge):
High Priority (Should fix):
Medium Priority (Consider fixing):
Low Priority (Nice to have):
Usage Examples
Example 1: React Component Review
Your code:
// src/components/UserProfile.tsx
import { useEffect, useState } from 'react';export function UserProfile({ userId }) {
const [user, setUser] = useState(null);
const [posts, setPosts] = useState([]);
useEffect(() => {
fetch(/api/users/${userId})
.then(res => res.json())
.then(setUser);
fetch(/api/users/${userId}/posts)
.then(res => res.json())
.then(setPosts);
}, [userId]);
return (
{user.name}
{posts.map(post => (
{post.title}
))}
);
}
Ask Claude:
"Review this React component for bugs and best practices"
Generated Review:
π΄ CRITICAL ISSUES
1. Null Pointer Exception (Line 14)
{user.name}
Problem: user is null initially, will crash on first renderFix:
{user && {user.name}
}
// Or use loading state:
{!user ? Loading...
: {user.name}
}
2. Missing Key Prop (Line 16)
{posts.map(post => {post.title})}
Problem: React requires key prop for list itemsFix:
{posts.map(post => {post.title})}
π‘ HIGH PRIORITY
3. Missing Error Handling (Lines 9-16) Problem: Fetch calls have no error handling
Fix:
useEffect(() => {
fetch(/api/users/${userId})
.then(res => {
if (!res.ok) throw new Error('Failed to fetch user');
return res.json();
})
.then(setUser)
.catch(err => {
console.error(err);
setError(err.message);
});
}, [userId]);
4. Performance Issue: Multiple API Calls (Lines 9-16) Problem: Two sequential API calls could be parallelized or combined
Fix:
// Option 1: Parallel requests
useEffect(() => {
Promise.all([
fetch(/api/users/${userId}).then(r => r.json()),
fetch(/api/users/${userId}/posts).then(r => r.json())
]).then(([user, posts]) => {
setUser(user);
setPosts(posts);
});
}, [userId]); // Option 2: Single endpoint
fetch(/api/users/${userId}?include=posts)
π MEDIUM PRIORITY
5. Missing TypeScript Types (Line 3)
export function UserProfile({ userId }) {
Problem: No type definitions for propsFix:
interface UserProfileProps {
userId: string;
} export function UserProfile({ userId }: UserProfileProps) {
6. Missing Loading State Problem: No visual feedback while loading
Recommendation: Add loading state for better UX
π΅ LOW PRIORITY
7. Component Could Use Custom Hook
Suggestion: Extract data fetching to useUserProfile hook for reusability
Summary: 7 issues found (2 critical, 2 high, 2 medium, 1 low) Recommendation: Fix critical issues before committing
Example 2: Security Review of API Endpoint
Your code:
// src/api/users.js
app.get('/api/search', (req, res) => {
const query = req.query.q;
const sql = SELECT * FROM users WHERE name LIKE '%${query}%'; db.query(sql, (err, results) => {
if (err) {
res.status(500).send(err.message);
} else {
res.json(results);
}
});
});
app.post('/api/users/:id/update', (req, res) => {
const userId = req.params.id;
const updates = req.body;
db.users.update(userId, updates);
res.json({ success: true });
});
Ask Claude:
"Review this API code for security vulnerabilities"
Generated Review:
π¨ CRITICAL SECURITY ISSUES
1. SQL Injection Vulnerability (Line 3-4) [CWE-89]
const sql = SELECT * FROM users WHERE name LIKE '%${query}%';
Severity: Critical (CVSS 9.8)
Problem: User input directly interpolated into SQL query
Attack Example: ?q=' OR '1'='1 returns all usersFix:
const sql = 'SELECT * FROM users WHERE name LIKE ?';
db.query(sql, [%${query}%], (err, results) => { ... });
2. Information Disclosure (Line 8)
res.status(500).send(err.message);
Problem: Exposes internal error messages to users
Risk: Database structure, paths, versions leakedFix:
if (err) {
console.error('Database error:', err);
res.status(500).json({ error: 'Internal server error' });
}
3. Missing Authentication (Both endpoints) Problem: No authentication middleware Risk: Anyone can access user data and modify records
Fix:
app.get('/api/search', authenticateUser, (req, res) => { ... });
app.post('/api/users/:id/update', authenticateUser, authorizeUser, ...);
4. Mass Assignment Vulnerability (Line 18)
const updates = req.body;
db.users.update(userId, updates);
Problem: User can update any field including role, isAdmin, etc.Fix:
const allowedFields = ['name', 'email', 'bio'];
const updates = pick(req.body, allowedFields);
// Or use explicit field extraction:
const updates = {
name: req.body.name,
email: req.body.email
};
π‘ HIGH PRIORITY SECURITY
5. Missing Input Validation Problem: No validation of request data Risk: Invalid data causes errors, potential exploits
Fix: Use validation library (Zod, Joi, express-validator)
6. Missing Rate Limiting Problem: No protection against brute force or DoS
Fix: Add rate limiting middleware
7. No HTTPS Enforcement Recommendation: Add middleware to redirect HTTP β HTTPS
Security Score: 2/10 (Critical vulnerabilities present) OWASP Issues Found: A1 (Injection), A2 (Broken Auth), A5 (Security Misconfiguration)
Example 3: Performance Review
Your code:
// src/services/analytics.ts
export async function generateUserReport(userId: string) {
const user = await db.users.findById(userId); const posts = await db.posts.findMany({
where: { authorId: userId }
});
const stats = [];
for (const post of posts) {
const likes = await db.likes.count({ postId: post.id });
const comments = await db.comments.count({ postId: post.id });
stats.push({
postId: post.id,
likes,
comments
});
}
return { user, posts, stats };
}
Ask Claude:
"Review this code for performance issues"
Generated Review:
π΄ CRITICAL PERFORMANCE ISSUES
1. N+1 Query Problem (Lines 10-17) Problem: Loop executes 2 database queries per post Impact: For 100 posts = 200 queries (should be 3 total) Performance: ~2-5 seconds instead of ~50ms
Fix:
// Fetch all stats in bulk
const postIds = posts.map(p => p.id); const [likeCounts, commentCounts] = await Promise.all([
db.likes.groupBy({
by: ['postId'],
where: { postId: { in: postIds } },
_count: true
}),
db.comments.groupBy({
by: ['postId'],
where: { postId: { in: postIds } },
_count: true
})
]);
const stats = posts.map(post => ({
postId: post.id,
likes: likeCounts.find(l => l.postId === post.id)?._count ?? 0,
comments: commentCounts.find(c => c.postId === post.id)?._count ?? 0
}));
2. Sequential Database Calls (Lines 2-7) Problem: User and posts fetched sequentially
Fix: Parallelize with Promise.all
const [user, posts] = await Promise.all([
db.users.findById(userId),
db.posts.findMany({ where: { authorId: userId } })
]);
π‘ HIGH PRIORITY
3. Missing Caching Problem: Report regenerated every time (expensive) Recommendation: Cache results with TTL
const cacheKey = user-report:${userId};
const cached = await cache.get(cacheKey);
if (cached) return cached; // ... generate report ...
await cache.set(cacheKey, report, { ttl: 300 }); // 5 min
return report;
4. Missing Pagination Problem: Loads ALL posts (could be thousands) Recommendation: Add pagination or limit
Performance Impact Analysis:
Example 4: Best Practices Review
Your code:
# services/order_processor.py
def process_order(order_id):
order = db.query("SELECT * FROM orders WHERE id = ?", [order_id])[0]
user = db.query("SELECT * FROM users WHERE id = ?", [order['user_id']])[0] if order['total'] > 0:
if user['balance'] >= order['total']:
user['balance'] = user['balance'] - order['total']
db.execute("UPDATE users SET balance = ? WHERE id = ?",
[user['balance'], user['id']])
order['status'] = 'completed'
db.execute("UPDATE orders SET status = ? WHERE id = ?",
['completed', order_id])
send_email(user['email'], "Order confirmed")
return True
else:
return False
return False
Ask Claude:
"Review this code for best practices and design patterns"
Generated Review:
π‘ HIGH PRIORITY
1. Missing Error Handling Problem: No try/except, will crash on database errors
Fix:
try:
order = db.query("SELECT * FROM orders WHERE id = ?", [order_id])[0]
except IndexError:
raise OrderNotFoundError(f"Order {order_id} not found")
except DatabaseError as e:
logger.error(f"Database error: {e}")
raise
2. No Transaction Management Problem: Balance deducted but order update could fail (data inconsistency)
Fix:
with db.transaction():
# Update balance
# Update order status
# Both succeed or both roll back
3. Magic Numbers and Strings
if order['total'] > 0: # What about zero?
order['status'] = 'completed' # Use enum
Fix:
class OrderStatus(Enum):
PENDING = 'pending'
COMPLETED = 'completed'
CANCELLED = 'cancelled' if order['total'] > Decimal('0'):
order['status'] = OrderStatus.COMPLETED.value
4. Missing Input Validation Problem: No validation of order_id type/format
Fix:
def process_order(order_id: str) -> bool:
if not order_id or not isinstance(order_id, str):
raise ValueError("Invalid order_id")
π MEDIUM PRIORITY
5. Tight Coupling Problem: Function does too many things (queries DB, sends email, updates multiple tables) Violation: Single Responsibility Principle
Refactor:
class OrderProcessor:
def __init__(self, db, email_service, payment_service):
self.db = db
self.email_service = email_service
self.payment_service = payment_service def process_order(self, order_id: str) -> bool:
order = self._get_order(order_id)
user = self._get_user(order.user_id)
if not self.payment_service.charge(user, order.total):
return False
self._complete_order(order)
self.email_service.send_confirmation(user, order)
return True
6. Using Dictionary Instead of Objects
Problem: order['status'] has no type safety
Fix: Use dataclasses or Pydantic models
7. No Logging Problem: No audit trail for order processing
Add: Structured logging for debugging and compliance
Design Pattern Recommendations:
Best Practice Score: 4/10 Key Improvements: Add transactions, error handling, use proper OOP design
Configuration
Specify Review Depth
"Quick review of critical issues only"
"Comprehensive review including style and documentation"
"Security-focused review for this authentication code"
"Performance review for this database query"
Customize Severity Levels
"Review code but only show critical and high priority issues"
"Include all issues including low priority suggestions"
Language-Specific Rules
"Review this React code following React best practices"
"Review this Python code following PEP 8 and Django conventions"
"Review this Go code following effective Go guidelines"
Best Practices
For Best Results
1. Provide context: Mention what the code does
"Review this authentication middleware for security issues"
2. Review small changes: Easier to review focused changes - Ideal: 50-200 lines of changes - Maximum: 400 lines for thorough review
3. Run before committing: Catch issues early
git add .
# Ask Claude to review staged changes
4. Act on critical issues: Fix security and bug issues immediately
5. Consider all feedback: Even low priority issues improve code quality
Review Workflow
1. Write code
2. Self-review (manual check)
3. Automated review (this skill)
4. Fix critical issues
5. Run tests
6. Commit
7. Create PR (human review)
Integration with Development Process
Pre-commit Hook:
#!/bin/bash
.git/hooks/pre-commit
Ask Claude to review staged changes
echo "Running automated code review..."If critical issues found, abort commit
CI/CD Integration:
# .github/workflows/code-review.yml
name: Automated Code Review
run: |
# Run review on PR changes
# Comment findings on PR
# Block merge if critical issues found
Troubleshooting
Issue: Too many false positives
Cause: Generic rules not fitting your codebase
Solution: Provide context
"Review this code, note: we intentionally use any types in this legacy module"
"Review for bugs only, skip style issues"
Issue: Missing issues you know exist
Cause: Complex logic requiring domain knowledge
Solution: Point to specific concerns
"Review this code, specifically check if the date calculation handles leap years"
"Look for potential race conditions in this concurrent code"
Issue: Review takes too long
Cause: Too many files or very large files
Solution: Review in chunks
"Review only the authentication logic in src/auth/"
"Quick security scan of API endpoints only"
Issue: Suggestions don't match team conventions
Cause: Generic best practices vs. team standards
Solution: Reference team guidelines
"Review following our team's style guide: [link or paste relevant rules]"
"We use X pattern for error handling, review with that in mind"
Advanced Usage
Security Audit Mode
"Perform a security audit focusing on:
SQL injection vulnerabilities
XSS attack vectors
Authentication and authorization flaws
Exposed secrets or credentials
CSRF protection
Input validation gaps"
Performance Profiling
"Review for performance issues:
Database query optimization
Memory leak potential
Algorithmic complexity
Caching opportunities
Bundle size impact (for frontend)"
Accessibility Review
"Review this React component for accessibility:
ARIA labels
Keyboard navigation
Screen reader compatibility
Color contrast
Focus management"
API Contract Review
"Review this API endpoint for:
Breaking changes vs v1
Backward compatibility
Versioning strategy
Deprecation notices needed"
Common Issues by Language
JavaScript/TypeScript
any abusePython
Go
Java
Rust
Related Resources
Real-World Impact
Case Study: Startup Series A
Before Automated Review:
After Automated Review:
ROI:
Case Study: Enterprise Team (50 developers)
Impact Over 6 Months:
Pro Tip: Use this skill as a learning tool. Read the explanations for every issue, even ones you disagree with. Over time, you'll internalize these patterns and write better code from the start!
License: MIT-0 (Public Domain)
βοΈ Configuration
Specify Review Depth
"Quick review of critical issues only"
"Comprehensive review including style and documentation"
"Security-focused review for this authentication code"
"Performance review for this database query"
Customize Severity Levels
"Review code but only show critical and high priority issues"
"Include all issues including low priority suggestions"
Language-Specific Rules
"Review this React code following React best practices"
"Review this Python code following PEP 8 and Django conventions"
"Review this Go code following effective Go guidelines"
π Tips & Best Practices
For Best Results
1. Provide context: Mention what the code does
"Review this authentication middleware for security issues"
2. Review small changes: Easier to review focused changes - Ideal: 50-200 lines of changes - Maximum: 400 lines for thorough review
3. Run before committing: Catch issues early
git add .
# Ask Claude to review staged changes
4. Act on critical issues: Fix security and bug issues immediately
5. Consider all feedback: Even low priority issues improve code quality
Review Workflow
1. Write code
2. Self-review (manual check)
3. Automated review (this skill)
4. Fix critical issues
5. Run tests
6. Commit
7. Create PR (human review)
Integration with Development Process
Pre-commit Hook:
#!/bin/bash
.git/hooks/pre-commit
Ask Claude to review staged changes
echo "Running automated code review..."If critical issues found, abort commit
CI/CD Integration:
# .github/workflows/code-review.yml
name: Automated Code Review
run: |
# Run review on PR changes
# Comment findings on PR
# Block merge if critical issues found