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.
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
```typescript
```
Problem: user is null initially, will crash on first render
Fix:
```typescript
{user &&
// Or use loading state:
{!user ?
Loading...
:```
```typescript
{posts.map(post =>
```
Problem: React requires key prop for list items
Fix:
```typescript
{posts.map(post =>
```
🟡 HIGH PRIORITY
Problem: Fetch calls have no error handling
Fix:
```typescript
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]);
```
Problem: Two sequential API calls could be parallelized or combined
Fix:
```typescript
// 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
```typescript
export function UserProfile({ userId }) {
```
Problem: No type definitions for props
Fix:
```typescript
interface UserProfileProps {
userId: string;
}
export function UserProfile({ userId }: UserProfileProps) {
```
Problem: No visual feedback while loading
Recommendation: Add loading state for better UX
🔵 LOW PRIORITY
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
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
```javascript
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:
```javascript
const sql = 'SELECT * FROM users WHERE name LIKE ?';
db.query(sql, [%${query}%], (err, results) => { ... });
```
```javascript
res.status(500).send(err.message);
```
Problem: Exposes internal error messages to users
Risk: Database structure, paths, versions leaked
Fix:
```javascript
if (err) {
console.error('Database error:', err);
res.status(500).json({ error: 'Internal server error' });
}
```
Problem: No authentication middleware
Risk: Anyone can access user data and modify records
Fix:
```javascript
app.get('/api/search', authenticateUser, (req, res) => { ... });
app.post('/api/users/:id/update', authenticateUser, authorizeUser, ...);
```
```javascript
const updates = req.body;
db.users.update(userId, updates);
```
Problem: User can update any field including role, isAdmin, etc.
Fix:
```javascript
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
Problem: No validation of request data
Risk: Invalid data causes errors, potential exploits
Fix: Use validation library (Zod, Joi, express-validator)
Problem: No protection against brute force or DoS
Fix: Add rate limiting middleware
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
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:
```typescript
// 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
}));
```
Problem: User and posts fetched sequentially
Fix: Parallelize with Promise.all
```typescript
const [user, posts] = await Promise.all([
db.users.findById(userId),
db.posts.findMany({ where: { authorId: userId } })
]);
```
🟡 HIGH PRIORITY
Problem: Report regenerated every time (expensive)
Recommendation: Cache results with TTL
```typescript
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;
```
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
Problem: No try/except, will crash on database errors
Fix:
```python
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
```
Problem: Balance deducted but order update could fail (data inconsistency)
Fix:
```python
with db.transaction():
# Update balance
# Update order status
# Both succeed or both roll back
```
```python
if order['total'] > 0: # What about zero?
order['status'] = 'completed' # Use enum
```
Fix:
```python
class OrderStatus(Enum):
PENDING = 'pending'
COMPLETED = 'completed'
CANCELLED = 'cancelled'
if order['total'] > Decimal('0'):
order['status'] = OrderStatus.COMPLETED.value
```
Problem: No validation of order_id type/format
Fix:
```python
def process_order(order_id: str) -> bool:
if not order_id or not isinstance(order_id, str):
raise ValueError("Invalid order_id")
```
🟠 MEDIUM PRIORITY
Problem: Function does too many things (queries DB, sends email, updates multiple tables)
Violation: Single Responsibility Principle
Refactor:
```python
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
```
Problem: order['status'] has no type safety
Fix: Use dataclasses or Pydantic models
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"
```
"Review this authentication middleware for security issues"
```
```bash
git add .
# Ask Claude to review staged changes
```
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)
共 1 个版本