code-review
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinesecode-review
代码评审
Description: Automated code quality analysis, static analysis, security scanning, and best practices enforcement
Category: Code Quality Assurance
Complexity: High (multi-tool integration + analysis)
描述: 自动化代码质量分析、静态分析、安全扫描与最佳实践强制执行
类别: 代码质量保障
复杂度: 高(多工具集成+分析)
Purpose
目标
Perform comprehensive code review to ensure quality, security, maintainability, and compliance with architectural decisions (ADRs) and specifications (SPEC). Identifies issues before code reaches production.
执行全面的代码评审,确保代码的质量、安全性、可维护性,同时符合架构决策记录(ADRs)与规格说明(SPEC)。在代码进入生产环境前识别问题。
Capabilities
核心能力
1. Static Analysis
1. 静态分析
- Linting: pylint, ruff, flake8 integration
- Type checking: mypy, pyright for type safety
- Code style: PEP 8 compliance, formatting issues
- Complexity metrics: cyclomatic complexity, cognitive complexity
- Code smells: duplicate code, long methods, god classes
- 代码检查: 集成pylint、ruff、flake8
- 类型检查: 使用mypy、pyright保障类型安全
- 代码风格: 遵循PEP 8规范,检测格式问题
- 复杂度指标: 圈复杂度、认知复杂度
- 代码异味: 重复代码、过长方法、上帝类
2. Security Vulnerability Scanning
2. 安全漏洞扫描
- Dependency vulnerabilities: bandit, safety checks
- Security anti-patterns: SQL injection, XSS, CSRF risks
- Secret detection: hardcoded credentials, API keys
- OWASP Top 10: Common security vulnerabilities
- CWE mapping: Common Weakness Enumeration references
- 依赖项漏洞: bandit、safety检查
- 安全反模式: SQL注入、XSS、CSRF风险
- 敏感信息检测: 硬编码凭证、API密钥
- OWASP Top 10: 常见安全漏洞检测
- CWE映射: 关联通用弱点枚举(CWE)参考
3. Best Practices Enforcement
3. 最佳实践强制执行
- Design patterns: Proper pattern usage
- SOLID principles: Violation detection
- DRY principle: Code duplication analysis
- Error handling: Exception management review
- Resource management: Memory leaks, file handle leaks
- 设计模式: 规范模式使用
- SOLID原则: 检测违反情况
- DRY原则: 代码重复分析
- 错误处理: 异常管理评审
- 资源管理: 内存泄漏、文件句柄泄漏检测
4. Code Coverage Analysis
4. 代码覆盖率分析
- Line coverage: Percentage of executed lines
- Branch coverage: Conditional path coverage
- Function coverage: Tested vs untested functions
- Gap identification: Uncovered critical paths
- 行覆盖率: 已执行代码行占比
- 分支覆盖率: 条件路径覆盖情况
- 函数覆盖率: 已测试与未测试函数对比
- 缺口识别: 未覆盖的关键路径
5. Architectural Compliance
5. 架构合规性
- ADR validation: Code aligns with architecture decisions
- SPEC compliance: Implementation matches specifications
- Dependency rules: No circular dependencies, proper layering
- API contract adherence: Matches CTR definitions
- ADR验证: 代码与架构决策对齐
- SPEC合规性: 实现与规格说明匹配
- 依赖规则: 无循环依赖、分层合理
- API契约遵循: 符合CTR定义
6. Performance Analysis
6. 性能分析
- Inefficient algorithms: O(n²) where O(n) possible
- Memory usage: Excessive allocations
- Database queries: N+1 query problems
- Caching opportunities: Repeated expensive operations
- 低效算法: 可优化为O(n)的O(n²)实现
- 内存使用: 过度内存分配检测
- 数据库查询: N+1查询问题识别
- 缓存优化: 重复高开销操作的缓存建议
7. Documentation Quality
7. 文档质量
- Docstring coverage: Missing or inadequate documentation
- Comment quality: Outdated or misleading comments
- API documentation: Public method documentation
- Type hints: Missing type annotations
- 文档字符串覆盖率: 缺失或不充分的文档检测
- 注释质量: 过时或误导性注释识别
- API文档: 公共方法文档检查
- 类型提示: 缺失类型注解检测
8. Automated Fix Suggestions
8. 自动修复建议
- Auto-fixable issues: Formatting, imports, simple refactorings
- Refactoring recommendations: Extract method, simplify conditions
- Performance optimizations: Suggest faster alternatives
- Security patches: Fix common vulnerabilities
- 可自动修复问题: 格式调整、导入优化、简单重构
- 重构建议: 提取方法、简化条件判断
- 性能优化: 提供更高效的替代方案
- 安全补丁: 常见漏洞修复建议
Code Review Workflow
代码评审工作流
mermaid
graph TD
A[Code Submission] --> B[Static Analysis]
B --> C{Linting Pass?}
C -->|Fail| D[Report Linting Issues]
C -->|Pass| E[Type Checking]
E --> F{Type Safety?}
F -->|Fail| G[Report Type Errors]
F -->|Pass| H[Security Scan]
H --> I{Security Issues?}
I -->|Critical| J[Block Merge]
I -->|Warning| K[Flag for Review]
I -->|Pass| L[Complexity Analysis]
L --> M{Complexity High?}
M -->|Yes| N[Suggest Refactoring]
M -->|No| O[Coverage Analysis]
O --> P{Coverage < 90%?}
P -->|Yes| Q[Request More Tests]
P -->|No| R[ADR Compliance]
R --> S{ADR Violations?}
S -->|Yes| T[Report Violations]
S -->|No| U[SPEC Compliance]
U --> V{SPEC Mismatch?}
V -->|Yes| W[Report Mismatches]
V -->|No| X[Generate Review Report]
D --> X
G --> X
J --> X
K --> X
N --> X
Q --> X
T --> X
W --> X
X --> Y[Review Complete]mermaid
graph TD
A[代码提交] --> B[静态分析]
B --> C{代码检查通过?}
C -->|不通过| D[报告代码检查问题]
C -->|通过| E[类型检查]
E --> F{类型安全?}
F -->|不通过| G[报告类型错误]
F -->|通过| H[安全扫描]
H --> I{存在安全问题?}
I -->|严重| J[阻止合并]
I -->|警告| K[标记需评审]
I -->|通过| L[复杂度分析]
L --> M{复杂度过高?}
M -->|是| N[建议重构]
M -->|否| O[覆盖率分析]
O --> P{覆盖率<90%?}
P -->|是| Q[要求补充测试]
P -->|否| R[ADR合规性检查]
R --> S{违反ADR?}
S -->|是| T[报告违规情况]
S -->|否| U[SPEC合规性检查]
U --> V[SPEC不匹配?]
V -->|是| W[报告不匹配问题]
V -->|否| X[生成评审报告]
D --> X
G --> X
J --> X
K --> X
N --> X
Q --> X
T --> X
W --> X
X --> Y[评审完成]Usage Instructions
使用说明
Review Single File
评审单个文件
bash
code-review analyze --file src/auth/service.pyOutput:
=== Code Review Report: src/auth/service.py ===
Issues Found: 8
[CRITICAL] Security Issue (Line 45)
- SQL Injection vulnerability in user_login()
- Direct string concatenation in SQL query
- CWE-89: SQL Injection
→ Fix: Use parameterized queries
[ERROR] Type Safety (Line 78)
- Missing return type annotation for validate_token()
- mypy: Function return type cannot be inferred
→ Fix: Add return type hint -> bool
[WARNING] Complexity (Line 112-156)
- Cyclomatic complexity: 12 (threshold: 10)
- Method authenticate_user() too complex
→ Suggestion: Extract validation logic to separate methods
[WARNING] Code Duplication (Lines 201-215, 234-248)
- 15 lines duplicated with 95% similarity
→ Suggestion: Extract common logic to validate_password_strength()
[INFO] Documentation (Line 89)
- Missing docstring for public method reset_password()
→ Suggestion: Add docstring with parameter and return descriptions
[INFO] Performance (Line 167)
- N+1 query detected in get_user_permissions()
→ Suggestion: Use JOIN or prefetch related data
Coverage: 87% (Below 90% threshold)
- Uncovered lines: 45-47, 89-91, 134-136
→ Action: Add tests for error handling paths
ADR Compliance: 1 violation
- ADR-003 requires JWT tokens, code uses session cookies
→ Action: Update implementation to use JWT
Total Score: 72/100 (Acceptable with improvements)bash
code-review analyze --file src/auth/service.py输出:
=== 代码评审报告: src/auth/service.py ===
发现问题: 8个
[严重] 安全问题(第45行)
- user_login()存在SQL注入漏洞
- SQL查询中直接拼接字符串
- CWE-89: SQL注入
→ 修复建议: 使用参数化查询
[错误] 类型安全(第78行)
- validate_token()缺失返回类型注解
- mypy: 无法推断函数返回类型
→ 修复建议: 添加返回类型提示 -> bool
[警告] 复杂度(第112-156行)
- 圈复杂度: 12(阈值:10)
- authenticate_user()方法过于复杂
→ 建议: 将验证逻辑提取到独立方法
[警告] 代码重复(第201-215行、234-248行)
- 15行代码重复,相似度95%
→ 建议: 将通用逻辑提取为validate_password_strength()
[信息] 文档(第89行)
- 公共方法reset_password()缺失文档字符串
→ 建议: 添加包含参数与返回值说明的文档字符串
[信息] 性能(第167行)
- get_user_permissions()中检测到N+1查询问题
→ 建议: 使用JOIN或预加载关联数据
覆盖率: 87%(低于90%阈值)
- 未覆盖行: 45-47、89-91、134-136
→ 操作: 为错误处理路径添加测试
ADR合规性: 1项违规
- ADR-003要求使用JWT令牌,代码使用会话Cookie
→ 操作: 更新实现以使用JWT
总分: 72/100(需改进后可接受)Review Entire Module
评审整个模块
bash
code-review analyze --module src/authbash
code-review analyze --module src/authReview Changed Files (Git)
评审Git变更文件
bash
code-review analyze --diff HEAD~1..HEADbash
code-review analyze --diff HEAD~1..HEADReview with Auto-fix
带自动修复的评审
bash
code-review analyze --file src/auth/service.py --auto-fixbash
code-review analyze --file src/auth/service.py --auto-fixAnalysis Categories
分析类别
1. Security Analysis
1. 安全分析
Tools: bandit, safety, semgrep
Checks:
- SQL injection vulnerabilities
- XSS attack vectors
- CSRF token validation
- Hardcoded secrets
- Insecure randomness
- Path traversal risks
- Command injection
- Insecure deserialization
- Weak cryptography
Severity Levels:
- CRITICAL: Immediate security risk (block merge)
- HIGH: Serious vulnerability (requires fix)
- MEDIUM: Potential security issue (review required)
- LOW: Security best practice violation
Example:
python
undefined工具: bandit, safety, semgrep
检查项:
- SQL注入漏洞
- XSS攻击向量
- CSRF令牌验证
- 硬编码敏感信息
- 不安全的随机数生成
- 路径遍历风险
- 命令注入
- 不安全的反序列化
- 弱加密实现
严重等级:
- 严重: 直接安全风险(阻止合并)
- 高: 严重漏洞(需修复)
- 中: 潜在安全问题(需评审)
- 低: 违反安全最佳实践
示例:
python
undefinedCRITICAL: SQL Injection
严重: SQL注入
query = f"SELECT * FROM users WHERE username = '{username}'" # ❌
query = f"SELECT * FROM users WHERE username = '{username}'" # ❌错误示例
FIX
修复方案
query = "SELECT * FROM users WHERE username = %s"
cursor.execute(query, (username,)) # ✓
query = "SELECT * FROM users WHERE username = %s"
cursor.execute(query, (username,)) # ✓正确示例
CRITICAL: Hardcoded Secret
严重: 硬编码敏感信息
API_KEY = "sk-1234567890abcdef" # ❌
API_KEY = "sk-1234567890abcdef" # ❌错误示例
FIX
修复方案
API_KEY = os.environ.get('API_KEY') # ✓
---API_KEY = os.environ.get('API_KEY') # ✓正确示例
---2. Code Quality Analysis
2. 代码质量分析
Tools: pylint, ruff, radon
Checks:
- PEP 8 compliance
- Cyclomatic complexity
- Maintainability index
- Code duplication
- Dead code
- Unused imports/variables
- Magic numbers
- Long functions/classes
Complexity Thresholds:
- A (1-5): Simple, easy to maintain
- B (6-10): Moderate complexity
- C (11-20): High complexity (refactor recommended)
- D (21-50): Very high complexity (refactor required)
- F (>50): Extreme complexity (immediate refactor)
Example:
python
undefined工具: pylint, ruff, radon
检查项:
- PEP 8规范遵循
- 圈复杂度
- 可维护性指数
- 代码重复
- 死代码
- 未使用的导入/变量
- 魔法值
- 过长函数/类
复杂度阈值:
- A(1-5): 简单,易于维护
- B(6-10): 中等复杂度
- C(11-20): 高复杂度(建议重构)
- D(21-50): 极高复杂度(需重构)
- F(>50): 极端复杂度(立即重构)
示例:
python
undefinedComplexity: 12 (High)
复杂度:12(高)
def process_order(order): # ❌
if order.status == 'pending':
if order.payment_verified:
if order.items_available:
if order.shipping_valid:
# ... nested logic
pass
def process_order(order): # ❌错误示例
if order.status == 'pending':
if order.payment_verified:
if order.items_available:
if order.shipping_valid:
# ...嵌套逻辑
pass
FIX: Complexity: 4 (Simple)
修复方案: 复杂度:4(简单)
def process_order(order): # ✓
if not can_process_order(order):
return False
return execute_order_processing(order)def can_process_order(order):
return (order.status == 'pending' and
order.payment_verified and
order.items_available and
order.shipping_valid)
---def process_order(order): # ✓正确示例
if not can_process_order(order):
return False
return execute_order_processing(order)def can_process_order(order):
return (order.status == 'pending' and
order.payment_verified and
order.items_available and
order.shipping_valid)
---3. Type Safety Analysis
3. 类型安全分析
Tools: mypy, pyright
Checks:
- Missing type hints
- Type incompatibilities
- Invalid type casting
- Optional value handling
- Generic type usage
- Protocol compliance
Example:
python
undefined工具: mypy, pyright
检查项:
- 缺失类型提示
- 类型不兼容
- 无效类型转换
- 可选值处理
- 泛型类型使用
- 协议遵循
示例:
python
undefinedType error: Missing return type
类型错误: 缺失返回类型
def calculate_total(items): # ❌
return sum(item.price for item in items)
def calculate_total(items): # ❌错误示例
return sum(item.price for item in items)
FIX
修复方案
def calculate_total(items: list[Item]) -> Decimal: # ✓
return sum(item.price for item in items)
def calculate_total(items: list[Item]) -> Decimal: # ✓正确示例
return sum(item.price for item in items)
Type error: None not handled
类型错误: 未处理None值
def get_user(user_id: int) -> User: # ❌
return database.query(User).get(user_id) # May return None
def get_user(user_id: int) -> User: # ❌错误示例
return database.query(User).get(user_id) # 可能返回None
FIX
修复方案
def get_user(user_id: int) -> User | None: # ✓
return database.query(User).get(user_id)
---def get_user(user_id: int) -> User | None: # ✓正确示例
return database.query(User).get(user_id)
---4. Performance Analysis
4. 性能分析
Checks:
- Inefficient algorithms
- Memory leaks
- N+1 query problems
- Unnecessary loops
- Missing caching
- Blocking I/O operations
- Large memory allocations
Example:
python
undefined检查项:
- 低效算法
- 内存泄漏
- N+1查询问题
- 不必要的循环
- 缺失缓存
- 阻塞式I/O操作
- 大量内存分配
示例:
python
undefinedPerformance issue: N+1 queries
性能问题: N+1查询
def get_users_with_permissions(): # ❌
users = User.query.all()
for user in users:
user.permissions = Permission.query.filter_by(user_id=user.id).all()
return users
def get_users_with_permissions(): # ❌错误示例
users = User.query.all()
for user in users:
user.permissions = Permission.query.filter_by(user_id=user.id).all()
return users
FIX: Single query with JOIN
修复方案: 单查询JOIN
def get_users_with_permissions(): # ✓
return User.query.options(
joinedload(User.permissions)
).all()
def get_users_with_permissions(): # ✓正确示例
return User.query.options(
joinedload(User.permissions)
).all()
Performance issue: Inefficient algorithm O(n²)
性能问题: 低效算法O(n²)
def find_duplicates(items): # ❌
duplicates = []
for i, item1 in enumerate(items):
for item2 in items[i+1:]:
if item1 == item2:
duplicates.append(item1)
return duplicates
def find_duplicates(items): # ❌错误示例
duplicates = []
for i, item1 in enumerate(items):
for item2 in items[i+1:]:
if item1 == item2:
duplicates.append(item1)
return duplicates
FIX: O(n) with set
修复方案: O(n)时间复杂度(使用集合)
def find_duplicates(items): # ✓
seen = set()
duplicates = set()
for item in items:
if item in seen:
duplicates.add(item)
seen.add(item)
return list(duplicates)
---def find_duplicates(items): # ✓正确示例
seen = set()
duplicates = set()
for item in items:
if item in seen:
duplicates.add(item)
seen.add(item)
return list(duplicates)
---5. Best Practices Analysis
5. 最佳实践分析
Checks:
- SOLID principles
- DRY (Don't Repeat Yourself)
- KISS (Keep It Simple)
- YAGNI (You Aren't Gonna Need It)
- Error handling patterns
- Resource management
- Logging practices
Example:
python
undefined检查项:
- SOLID原则
- DRY(避免重复)
- KISS(保持简单)
- YAGNI(无需过度设计)
- 错误处理模式
- 资源管理
- 日志实践
示例:
python
undefinedViolation: Single Responsibility Principle
违反: 单一职责原则
class UserManager: # ❌
def create_user(self, data):
# Validates data
# Saves to database
# Sends email
# Logs action
pass
class UserManager: # ❌错误示例
def create_user(self, data):
# 验证数据
# 保存到数据库
# 发送邮件
# 记录操作
pass
FIX: Separate responsibilities
修复方案: 拆分职责
class UserValidator: # ✓
def validate(self, data): pass
class UserRepository:
def save(self, user): pass
class EmailService:
def send_welcome_email(self, user): pass
class AuditLogger:
def log_user_creation(self, user): pass
---class UserValidator: # ✓正确示例
def validate(self, data): pass
class UserRepository:
def save(self, user): pass
class EmailService:
def send_welcome_email(self, user): pass
class AuditLogger:
def log_user_creation(self, user): pass
---6. Documentation Analysis
6. 文档分析
Checks:
- Missing docstrings
- Incomplete docstrings
- Outdated comments
- Type hint documentation
- API documentation
- Example usage
Example:
python
undefined检查项:
- 缺失文档字符串
- 不完整的文档字符串
- 过时注释
- 类型提示文档
- API文档
- 示例用法
示例:
python
undefinedPoor documentation
文档质量差
def process(data): # ❌
# Process the data
return result
def process(data): # ❌错误示例
# 处理数据
return result
Good documentation
优质文档
def process_user_registration( # ✓
user_data: dict[str, Any]
) -> User:
"""
Process new user registration with validation and persistence.
Args:
user_data: Dictionary containing user registration information
Required keys: username, email, password
Optional keys: full_name, phone_number
Returns:
User: Newly created user instance with assigned ID
Raises:
ValidationError: If user_data fails validation
DatabaseError: If user cannot be persisted
DuplicateUserError: If username or email already exists
Example:
>>> user = process_user_registration({
... 'username': 'johndoe',
... 'email': 'john@example.com',
... 'password': 'SecureP@ss123'
... })
>>> user.id
12345
"""
validated_data = UserValidator.validate(user_data)
user = User.create(validated_data)
return UserRepository.save(user)
---def process_user_registration( # ✓正确示例
user_data: dict[str, Any]
) -> User:
"""
处理新用户注册,包含验证与持久化逻辑。
参数:
user_data: 包含用户注册信息的字典
必填键: username, email, password
可选键: full_name, phone_number
返回:
User: 新创建的用户实例,已分配ID
抛出:
ValidationError: 若user_data验证失败
DatabaseError: 若用户无法持久化
DuplicateUserError: 若用户名或邮箱已存在
示例:
>>> user = process_user_registration({
... 'username': 'johndoe',
... 'email': 'john@example.com',
... 'password': 'SecureP@ss123'
... })
>>> user.id
12345
"""
validated_data = UserValidator.validate(user_data)
user = User.create(validated_data)
return UserRepository.save(user)
---7. ADR Compliance Analysis
7. ADR合规性分析
Checks:
- Architecture decision adherence
- Technology stack compliance
- Design pattern usage
- API design standards
- Data flow patterns
Example:
python
undefined检查项:
- 架构决策遵循
- 技术栈合规性
- 设计模式使用
- API设计标准
- 数据流模式
示例:
python
undefinedADR-003: All authentication must use JWT tokens
ADR-003: 所有认证必须使用JWT令牌
Violation
违反规范
@app.route('/login', methods=['POST']) # ❌
def login():
# ... authentication logic
session['user_id'] = user.id # Using sessions, not JWT
return jsonify({'success': True})
@app.route('/login', methods=['POST']) # ❌错误示例
def login():
# ...认证逻辑
session['user_id'] = user.id # 使用会话而非JWT
return jsonify({'success': True})
Compliant
符合规范
@app.route('/login', methods=['POST']) # ✓
def login():
# ... authentication logic
token = jwt.encode(
{'user_id': user.id, 'exp': datetime.utcnow() + timedelta(hours=1)},
SECRET_KEY,
algorithm='HS256'
)
return jsonify({'token': token})
---@app.route('/login', methods=['POST']) # ✓正确示例
def login():
# ...认证逻辑
token = jwt.encode(
{'user_id': user.id, 'exp': datetime.utcnow() + timedelta(hours=1)},
SECRET_KEY,
algorithm='HS256'
)
return jsonify({'token': token})
---8. SPEC Compliance Analysis
8. SPEC合规性分析
Checks:
- Implementation matches specifications
- API signatures correct
- Data structures match schemas
- Business logic correct
- Error handling as specified
Example:
python
undefined检查项:
- 实现与规格说明一致
- API签名正确
- 数据结构与Schema匹配
- 业务逻辑正确
- 错误处理符合要求
示例:
python
undefinedSPEC-AUTH-V1: Password validation requirements
SPEC-AUTH-V1: 密码验证要求
SPEC violation: Missing uppercase requirement
违反规范: 缺少大写字母要求
def validate_password(password: str) -> bool: # ❌
return (
len(password) >= 8 and
any(c.islower() for c in password) and
any(c.isdigit() for c in password)
)
def validate_password(password: str) -> bool: # ❌错误示例
return (
len(password) >= 8 and
any(c.islower() for c in password) and
any(c.isdigit() for c in password)
)
SPEC compliant
符合规范
def validate_password(password: str) -> bool: # ✓
return (
8 <= len(password) <= 20 and
any(c.isupper() for c in password) and # Missing requirement
any(c.islower() for c in password) and
any(c.isdigit() for c in password) and
any(c in '!@#$%^&*' for c in password)
)
---def validate_password(password: str) -> bool: # ✓正确示例
return (
8 <= len(password) <= 20 and
any(c.isupper() for c in password) and # 补充缺失的要求
any(c.islower() for c in password) and
any(c.isdigit() for c in password) and
any(c in '!@#$%^&*' for c in password)
)
---Review Score Calculation
评审分数计算
python
score = (
security_score * 0.30 + # 30% weight
quality_score * 0.25 + # 25% weight
type_safety_score * 0.15 + # 15% weight
coverage_score * 0.15 + # 15% weight
documentation_score * 0.10 + # 10% weight
performance_score * 0.05 # 5% weight
)python
score = (
security_score * 0.30 + # 权重30%
quality_score * 0.25 + # 权重25%
type_safety_score * 0.15 + # 权重15%
coverage_score * 0.15 + # 权重15%
documentation_score * 0.10 + # 权重10%
performance_score * 0.05 # 权重5%
)Score categories
分数等级
90-100: Excellent (merge approved)
80-89: Good (minor improvements recommended)
70-79: Acceptable (improvements required)
60-69: Needs work (significant issues)
<60: Poor (major rework needed)
---90-100: 优秀(批准合并)
80-89: 良好(建议小幅改进)
70-79: 可接受(需改进)
60-69: 待优化(存在显著问题)
<60: 不合格(需大幅重构)
---Tool Access
工具权限
Required tools:
- : Read source code files
Read - : Execute analysis tools (pylint, mypy, bandit)
Bash - : Search for patterns and violations
Grep - : Find code files
Glob
Required libraries:
- pylint
- ruff
- mypy / pyright
- bandit
- safety
- radon
- coverage
- semgrep
所需工具:
- : 读取源代码文件
Read - : 执行分析工具(pylint、mypy、bandit)
Bash - : 搜索模式与违规情况
Grep - : 查找代码文件
Glob
所需库:
- pylint
- ruff
- mypy / pyright
- bandit
- safety
- radon
- coverage
- semgrep
Integration Points
集成点
With test-automation
与自动化测试集成
- Verify test coverage meets thresholds
- Identify untested code paths
- Validate test quality
- 验证测试覆盖率是否达到阈值
- 识别未测试的代码路径
- 验证测试质量
With doc-validator
与文档验证工具集成
- Check code documentation quality
- Validate traceability references in code
- Ensure code comments follow standards
- 检查代码文档质量
- 验证代码中的可追溯性引用
- 确保代码注释遵循规范
With security-audit
与安全审计工具集成
- Share security vulnerability findings
- Coordinate security fixes
- Track security metrics
- 共享安全漏洞发现结果
- 协调安全修复工作
- 跟踪安全指标
With refactor-flow
与重构工作流集成
- Identify refactoring opportunities
- Provide complexity metrics
- Suggest code improvements
- 识别重构机会
- 提供复杂度指标
- 建议代码改进方案
Auto-fix Capabilities
自动修复能力
Safe Auto-fixes (Applied Automatically)
安全自动修复(自动应用)
- Import sorting
- Code formatting (black, autopep8)
- Trailing whitespace removal
- Missing blank lines
- Unused imports removal
- Simple type hint additions
- 导入排序
- 代码格式化(black、autopep8)
- 移除尾随空格
- 补充缺失空行
- 移除未使用的导入
- 简单类型提示补充
Suggested Fixes (Requires Approval)
建议修复(需审批)
- Extract method refactorings
- Complexity reduction
- Performance optimizations
- Security vulnerability patches
- Documentation additions
- 提取方法重构
- 复杂度降低
- 性能优化
- 安全漏洞补丁
- 文档补充
CI/CD Integration
CI/CD集成
yaml
undefinedyaml
undefined.github/workflows/code-review.yml
.github/workflows/code-review.yml
name: Automated Code Review
on: [pull_request]
jobs:
code-review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Run code review
run: |
code-review analyze --diff origin/main..HEAD
- name: Check quality gate
run: |
if [ $CODE_REVIEW_SCORE -lt 70 ]; then
echo "Code quality below threshold"
exit 1
fi
---name: 自动化代码评审
on: [pull_request]
jobs:
code-review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: 执行代码评审
run: |
code-review analyze --diff origin/main..HEAD
- name: 检查质量门禁
run: |
if [ $CODE_REVIEW_SCORE -lt 70 ]; then
echo "代码质量低于阈值"
exit 1
fi
---Best Practices
最佳实践
- Review early and often: Don't wait until PR stage
- Fix critical issues immediately: Security and correctness first
- Track metrics over time: Monitor code quality trends
- Automate in CI/CD: Prevent poor code from merging
- Prioritize issues: Focus on high-impact problems
- Provide context: Explain why issues matter
- Suggest solutions: Don't just identify problems
- Balance strictness: Don't block progress over minor style issues
- 尽早且频繁评审: 不要等到拉取请求(PR)阶段
- 立即修复严重问题: 优先处理安全与正确性问题
- 持续跟踪指标: 监控代码质量趋势
- CI/CD自动化: 阻止低质量代码合并
- 问题优先级排序: 聚焦高影响问题
- 提供上下文: 解释问题的影响
- 给出解决方案: 不仅识别问题,还要提供修复建议
- 平衡严格性: 不要因微小风格问题阻碍进度
Limitations
局限性
- Cannot understand business logic intent
- May produce false positives (requires human review)
- Cannot detect all security vulnerabilities
- Performance analysis limited to obvious patterns
- ADR/SPEC compliance requires manual rule definition
- Tool installation and configuration required
- 无法理解业务逻辑意图
- 可能产生误报(需人工评审)
- 无法检测所有安全漏洞
- 性能分析仅能识别明显模式
- ADR/SPEC合规性需要手动定义规则
- 需要安装与配置相关工具
Future Enhancements
未来改进方向
- AI-powered code understanding and suggestions
- Learning from historical code reviews
- Custom rule engine for project-specific standards
- Visual code quality dashboards
- Automated dependency updates
- Predictive bug detection
- Code smell trend analysis
- 基于AI的代码理解与建议
- 从历史评审中学习优化
- 项目特定标准的自定义规则引擎
- 可视化代码质量仪表盘
- 自动化依赖项更新
- 预测性缺陷检测
- 代码异味趋势分析
Success Criteria
成功标准
- Zero critical security vulnerabilities
- Code quality score ≥80/100
- Type safety: 100% type hints on public APIs
- Coverage ≥90%
- Complexity: No functions with complexity >10
- Zero ADR violations
- Zero SPEC mismatches
- 无严重安全漏洞
- 代码质量评分≥80/100
- 类型安全: 公共API实现100%类型提示覆盖
- 覆盖率≥90%
- 复杂度: 无函数复杂度超过10
- 无ADR违规
- 无SPEC不匹配
Notes
注意事项
- Review reports saved to
reports/code-review/ - Historical metrics tracked in
metrics/code-quality.json - Auto-fixes require approval unless configured otherwise
- Security issues always block merge
- Can be customized per project with config
.code-review.yml
- 评审报告保存至
reports/code-review/ - 历史指标记录在
metrics/code-quality.json - 自动修复需审批,除非另行配置
- 安全问题始终阻止合并
- 可通过配置文件按项目自定义规则
.code-review.yml