Install
openclaw skills install code-review-inspectorAutomated code review checking for bugs, security issues, best practices, performance problems, and code style
openclaw skills install code-review-inspectorAutomatically performs comprehensive code reviews on your changes, identifying bugs, security vulnerabilities, performance issues, best practice violations, and code style problems before they reach production. Think of it as having a senior engineer review every line of code you write.
This skill analyzes your code changes and provides detailed feedback on:
Supports multiple languages and frameworks:
Studies show bugs found in code review are 10-100× cheaper to fix than bugs found in production:
Automated review catches issues humans miss:
Makes human code reviews more valuable:
Learn best practices as you code:
Use this skill for comprehensive code review:
Critical Issues (Must fix before merge):
High Priority (Should fix):
Medium Priority (Consider fixing):
Low Priority (Nice to have):
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 (
<div>
<h1>{user.name}</h1>
<div>
{posts.map(post => (
<div>{post.title}</div>
))}
</div>
</div>
);
}
Ask Claude:
"Review this React component for bugs and best practices"
Generated Review:
🔴 CRITICAL ISSUES
Null Pointer Exception (Line 14)
<h1>{user.name}</h1>
Problem: user is null initially, will crash on first render
Fix:
{user && <h1>{user.name}</h1>}
// Or use loading state:
{!user ? <p>Loading...</p> : <h1>{user.name}</h1>}
Missing Key Prop (Line 16)
{posts.map(post => <div>{post.title}</div>)}
Problem: React requires key prop for list items
Fix:
{posts.map(post => <div key={post.id}>{post.title}</div>)}
🟡 HIGH PRIORITY
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]);
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
Missing TypeScript Types (Line 3)
export function UserProfile({ userId }) {
Problem: No type definitions for props
Fix:
interface UserProfileProps {
userId: string;
}
export function UserProfile({ userId }: UserProfileProps) {
Missing Loading State Problem: No visual feedback while loading
Recommendation: Add loading state for better UX
🔵 LOW PRIORITY
useUserProfile hook for reusabilitySummary: 7 issues found (2 critical, 2 high, 2 medium, 1 low) Recommendation: Fix critical issues before committing
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
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 users
Fix:
const sql = 'SELECT * FROM users WHERE name LIKE ?';
db.query(sql, [`%${query}%`], (err, results) => { ... });
Information Disclosure (Line 8)
res.status(500).send(err.message);
Problem: Exposes internal error messages to users Risk: Database structure, paths, versions leaked
Fix:
if (err) {
console.error('Database error:', err);
res.status(500).json({ error: 'Internal server error' });
}
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, ...);
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
Missing Input Validation Problem: No validation of request data Risk: Invalid data causes errors, potential exploits
Fix: Use validation library (Zod, Joi, express-validator)
Missing Rate Limiting Problem: No protection against brute force or DoS
Fix: Add rate limiting middleware
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)
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
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
}));
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
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;
Missing Pagination Problem: Loads ALL posts (could be thousands) Recommendation: Add pagination or limit
Performance Impact Analysis:
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
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
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
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
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
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
Using Dictionary Instead of Objects
Problem: order['status'] has no type safety
Fix: Use dataclasses or Pydantic models
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
"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"
"Review code but only show critical and high priority issues"
"Include all issues including low priority suggestions"
"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"
Provide context: Mention what the code does
"Review this authentication middleware for security issues"
Review small changes: Easier to review focused changes
Run before committing: Catch issues early
git add .
# Ask Claude to review staged changes
Act on critical issues: Fix security and bug issues immediately
Consider all feedback: Even low priority issues improve code quality
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)
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
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"
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"
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"
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"
"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"
"Review for performance issues:
- Database query optimization
- Memory leak potential
- Algorithmic complexity
- Caching opportunities
- Bundle size impact (for frontend)"
"Review this React component for accessibility:
- ARIA labels
- Keyboard navigation
- Screen reader compatibility
- Color contrast
- Focus management"
"Review this API endpoint for:
- Breaking changes vs v1
- Backward compatibility
- Versioning strategy
- Deprecation notices needed"
any abuseBefore Automated Review:
After Automated Review:
ROI:
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)