moai-core-code-reviewer
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseEnterprise Systematic Code Review Orchestrator
企业级系统化代码审查编排工具
Skill Metadata
技能元数据
| Field | Value |
|---|---|
| Skill Name | moai-core-code-reviewer |
| Version | 4.0.0 Enterprise (2025-11-18) |
| Core Framework | TRUST 5 principles, Context7 integration |
| AI Integration | ✅ Context7 MCP, AI quality checks, pattern matching |
| Auto-load | When conducting code reviews or quality checks |
| Languages | 25+ (Python, JavaScript, Go, Rust, Java, etc.) |
| Lines of Content | 950+ with 15+ production examples |
| Progressive Disclosure | 3-level (framework, patterns, advanced) |
| 字段 | 取值 |
|---|---|
| 技能名称 | moai-core-code-reviewer |
| 版本 | 4.0.0 企业版 (2025-11-18) |
| 核心框架 | TRUST 5 原则, Context7 集成 |
| AI集成 | ✅ Context7 MCP, AI质量检查, 模式匹配 |
| 自动触发时机 | 执行代码审查或质量检查时 |
| 支持语言 | 25+ (Python、JavaScript、Go、Rust、Java等) |
| 内容行数 | 950+ 行,包含15+生产级示例 |
| 渐进式展示层级 | 3级 (框架、模式、高级用法) |
What It Does
功能介绍
Provides systematic guidance for enterprise-grade code review processes applying TRUST 5 principles, validating SOLID principles, identifying security issues, ensuring maintainability, and automating quality gates across all programming languages.
为企业级代码审查流程提供系统化指导,落地TRUST 5原则、验证SOLID原则、识别安全问题、保障可维护性,同时为所有编程语言提供自动化质量门禁能力。
The TRUST 5 Review Framework
TRUST 5 审查框架
T - Test First
T - 测试优先
Focus: Test coverage, quality, comprehensiveness
Key Questions:
- Are tests comprehensive? Do they cover happy path + edge cases?
- Test coverage ≥ 85%?
- Tests verify behavior, not just implementation?
- Edge cases handled: null, empty, boundary values?
- Async/concurrent scenarios tested?
Tools: pytest coverage, jest --coverage, go test -cover, cargo test
Examples:
python
undefined核心关注: 测试覆盖率、测试质量、覆盖全面性
核心检查问题:
- 测试是否全面?是否覆盖了正常流程+边界场景?
- 测试覆盖率 ≥ 85%?
- 测试校验的是行为逻辑,而非仅仅是实现细节?
- 边界场景是否处理:空值、空对象、边界数值?
- 异步/并发场景是否有测试覆盖?
配套工具: pytest coverage、jest --coverage、go test -cover、cargo test
示例:
python
undefined❌ Bad: Tests implementation, not behavior
❌ 错误示例:测试实现细节而非行为
def test_add():
assert add(2, 2) == 4
def test_add():
assert add(2, 2) == 4
✅ Good: Tests behavior with edge cases
✅ 正确示例:覆盖边界场景测试行为
def test_add_positive_numbers():
assert add(2, 2) == 4
assert add(-1, 1) == 0
assert add(0, 0) == 0
def test_add_boundary():
assert add(int.max, 1) == overflow_behavior()
undefineddef test_add_positive_numbers():
assert add(2, 2) == 4
assert add(-1, 1) == 0
assert add(0, 0) == 0
def test_add_boundary():
assert add(int.max, 1) == overflow_behavior()
undefinedR - Readable
R - 可读性
Focus: Code clarity, self-documentation, maintainability
Key Questions:
- Are function/variable names meaningful and clear?
- Can a new team member understand the intent?
- Comments explain WHY, not WHAT (code shows what)?
- Cyclomatic complexity reasonable (<10)?
- Functions single responsibility?
- Magic numbers extracted as constants?
Tools: linters, code formatters, readability checkers
Examples:
python
undefined核心关注: 代码清晰度、自说明性、可维护性
核心检查问题:
- 函数/变量命名是否表意清晰?
- 新团队成员能否快速理解代码意图?
- 注释解释的是「为什么这么做」而非「做了什么」(代码本身已经说明做了什么)?
- 圈复杂度是否合理(<10)?
- 函数是否遵循单一职责?
- 魔法数字是否被提取为常量?
配套工具: 静态检查工具、代码格式化工具、可读性检查工具
示例:
python
undefined❌ Bad: Unclear intent
❌ 错误示例:意图不清晰
def calc(x, y, z):
return x * (1 + y / 100) - z * 0.05
def calc(x, y, z):
return x * (1 + y / 100) - z * 0.05
✅ Good: Clear intent with constants
✅ 正确示例:使用常量、表意清晰
DISCOUNT_RATE = 0.05
TAX_RATE = 0.05
def calculate_final_price(base_price: float, tax_percent: float, discount: float) -> float:
"""Calculate final price after tax and discount.
Args:
base_price: Original product price
tax_percent: Tax percentage (0-100)
discount: Discount amount to subtract
"""
with_tax = base_price * (1 + tax_percent / 100)
return with_tax - (discount * DISCOUNT_RATE)undefinedDISCOUNT_RATE = 0.05
TAX_RATE = 0.05
def calculate_final_price(base_price: float, tax_percent: float, discount: float) -> float:
"""计算含税和折扣后的最终价格
参数:
base_price: 商品原价
tax_percent: 税率百分比(0-100)
discount: 抵扣的折扣金额
"""
with_tax = base_price * (1 + tax_percent / 100)
return with_tax - (discount * DISCOUNT_RATE)undefinedU - Unified
U - 统一性
Focus: Consistency, patterns, architectural cohesion
Key Questions:
- Does code follow team patterns and conventions?
- Consistent with codebase style?
- Uses established error handling patterns?
- Logging strategy aligned?
- Database access follows repository pattern?
- API design consistent with existing endpoints?
Tools: style guides, architectural patterns, linters
Examples:
python
undefined核心关注: 一致性、编码模式、架构内聚性
核心检查问题:
- 代码是否遵循团队统一的编码模式和规范?
- 与代码库整体风格是否一致?
- 是否使用了团队统一的错误处理模式?
- 日志策略是否对齐团队规范?
- 数据库访问是否遵循仓库模式?
- API设计是否与现有端点风格一致?
配套工具: 风格指南、架构模式规范、静态检查工具
示例:
python
undefined❌ Bad: Inconsistent error handling
❌ 错误示例:错误处理不一致
def get_user(user_id):
try:
return fetch_from_db(user_id)
except Exception as e:
return None # Inconsistent with rest of codebase
def get_user(user_id):
try:
return fetch_from_db(user_id)
except Exception as e:
return None # 和代码库其他部分的错误处理逻辑不一致
✅ Good: Consistent error handling
✅ 正确示例:统一的错误处理逻辑
def get_user(user_id: int) -> User:
"""Get user by ID.
Raises:
UserNotFoundError: If user doesn't exist
DatabaseError: If database connection fails
"""
try:
return self.user_repository.find_by_id(user_id)
except DatabaseConnectionError as e:
logger.error(f"Database error: {e}")
raise DatabaseError(str(e)) from e
except Exception as e:
logger.error(f"Unexpected error: {e}")
raiseundefineddef get_user(user_id: int) -> User:
"""根据用户ID获取用户信息
抛出异常:
UserNotFoundError: 用户不存在时抛出
DatabaseError: 数据库连接失败时抛出
"""
try:
return self.user_repository.find_by_id(user_id)
except DatabaseConnectionError as e:
logger.error(f"数据库错误: {e}")
raise DatabaseError(str(e)) from e
except Exception as e:
logger.error(f"非预期错误: {e}")
raiseundefinedS - Secured
S - 安全性
Focus: Security vulnerabilities, input validation, secret handling
Key Questions:
- Are inputs validated before use?
- No hardcoded credentials, API keys, or secrets?
- SQL injection prevention (parameterized queries)?
- XSS prevention (output escaping)?
- CSRF tokens used for state-changing operations?
- Authentication required for sensitive operations?
- Rate limiting on public endpoints?
- Dependency vulnerabilities scanned?
Tools: bandit, safety, npm audit, go vet, security scanners
Examples:
python
undefined核心关注: 安全漏洞、输入校验、密钥处理
核心检查问题:
- 输入使用前是否经过校验?
- 无硬编码的凭证、API密钥或其他敏感信息?
- 已预防SQL注入(使用参数化查询)?
- 已预防XSS攻击(输出做了转义)?
- 变更状态的操作是否使用了CSRF Token?
- 敏感操作是否要求身份认证?
- 公开端点是否配置了限流?
- 依赖包是否经过漏洞扫描?
配套工具: bandit、safety、npm audit、go vet、安全扫描工具
示例:
python
undefined❌ Bad: SQL injection vulnerability
❌ 错误示例:存在SQL注入漏洞
def get_user(user_id):
query = f"SELECT * FROM users WHERE id = {user_id}" # Vulnerable!
return db.execute(query)
def get_user(user_id):
query = f"SELECT * FROM users WHERE id = {user_id}" # 存在漏洞!
return db.execute(query)
✅ Good: Parameterized query
✅ 正确示例:使用参数化查询
def get_user(user_id: int) -> User:
query = "SELECT * FROM users WHERE id = ?"
return db.execute(query, [user_id])
undefineddef get_user(user_id: int) -> User:
query = "SELECT * FROM users WHERE id = ?"
return db.execute(query, [user_id])
undefinedT - Trackable
T - 可追溯性
Key Questions:
- Changelog entry added?
- Git history clear and atomic?
- Breaking changes documented?
- Migration guides for version updates?
Examples:
python
undefined核心检查问题:
- 是否添加了变更日志?
- Git提交记录是否清晰、原子化?
- 破坏性变更是否有说明文档?
- 版本升级是否提供了迁移指南?
示例:
python
undefined❌ Bad: No traceability
❌ 错误示例:无追溯信息
def calculate_discount(price, customer_type):
if customer_type == "vip":
return price * 0.8
return price
def calculate_discount(price, customer_type):
if customer_type == "vip":
return price * 0.8
return price
✅ Good: Full traceability
✅ 正确示例:完整的追溯信息
def calculate_discount(price: float, customer_type: str) -> float:
"""Calculate discount based on customer type.
Implements SPEC-042: VIP customers receive 20% discount
Linked to:
- SPEC-042: VIP pricing requirements
- TEST-042-001: VIP discount validation
- PR #1234: Feature implementation
"""
VIP_DISCOUNT_RATE = 0.20
if customer_type == "vip":
return price * (1 - VIP_DISCOUNT_RATE)
return price
---def calculate_discount(price: float, customer_type: str) -> float:
"""根据用户类型计算折扣
实现 SPEC-042 需求: VIP用户享受20%折扣
关联信息:
- SPEC-042: VIP定价需求
- TEST-042-001: VIP折扣校验用例
- PR #1234: 功能实现PR
"""
VIP_DISCOUNT_RATE = 0.20
if customer_type == "vip":
return price * (1 - VIP_DISCOUNT_RATE)
return price
---SOLID Principles Checklist
SOLID原则检查清单
| Principle | Focus | Review Question |
|---|---|---|
| Single Responsibility | One reason to change | Does this class/function do one thing? |
| Open/Closed | Open for extension, closed for modification | Can behavior be extended without modifying? |
| Liskov Substitution | Substitutable subtypes | Can derived classes replace base without breaking? |
| Interface Segregation | Minimal, specific interfaces | Are clients forced to depend on methods they don't use? |
| Dependency Inversion | Depend on abstractions, not concretions | Do high-level modules depend on low-level implementations? |
| 原则 | 核心关注 | 检查问题 |
|---|---|---|
| S单一职责 | 仅一个变更原因 | 当前类/函数是否只做一件事? |
| O开闭原则 | 对扩展开放,对修改关闭 | 是否可以在不修改现有代码的前提下扩展功能? |
| L里氏替换 | 子类可替换父类 | 派生类是否可以替换基类而不破坏功能? |
| I接口隔离 | 最小化、专用的接口 | 调用方是否被迫依赖他们不需要的方法? |
| D依赖倒置 | 依赖抽象而非具体实现 | 高层模块是否依赖底层模块的具体实现? |
Code Review Process (4-Step)
代码审查流程(4步)
Step 1: Automated Checks (5 min)
步骤1: 自动化检查(5分钟)
✓ Linting & formatting
✓ Security scanning (bandit, safety, npm audit)
✓ Dependency vulnerabilities
✓ Test coverage ≥85%
✓ Type checking (mypy, TypeScript, etc.)✓ 静态检查与格式化
✓ 安全扫描 (bandit、safety、npm audit)
✓ 依赖包漏洞检查
✓ 测试覆盖率 ≥85%
✓ 类型检查 (mypy、TypeScript等)Step 2: Architecture Review (15 min)
步骤2: 架构审查(15分钟)
✓ SOLID principles
✓ Design patterns appropriate?
✓ Consistency with codebase
✓ Scalability implications?
✓ Performance implications?✓ SOLID原则符合性
✓ 设计模式是否适用?
✓ 与代码库整体一致性
✓ 可扩展性影响?
✓ 性能影响?Step 3: Security Audit (10 min)
步骤3: 安全审计(10分钟)
✓ Input validation
✓ No hardcoded secrets
✓ Authentication/authorization correct?
✓ SQL injection prevention
✓ XSS prevention
✓ CSRF tokens present✓ 输入校验
✓ 无硬编码敏感信息
✓ 身份认证/授权逻辑正确?
✓ SQL注入预防
✓ XSS攻击预防
✓ 已配置CSRF TokenStep 4: Implementation Review (20 min)
步骤4: 实现审查(20分钟)
✓ TRUST 5 checklist
✓ Edge cases handled?
✓ Error messages helpful?
✓ Documentation complete?✓ TRUST 5检查清单
✓ 边界场景是否处理?
✓ 错误信息是否清晰有用?
✓ 文档是否完整?Review Depth Matrix
审查深度矩阵
| Change Type | Severity | Automation | Review Time | Focus Areas |
|---|---|---|---|---|
| Security fix | 🔴 Critical | Full scan | 30+ min | Vulnerabilities, test coverage, audit trail |
| Core architecture | 🔴 Critical | Partial | 45+ min | Design patterns, scalability, consistency |
| Feature (new) | 🟡 Major | Full scan | 30 min | Completeness, TRUST 5, documentation |
| Bug fix | 🟢 Minor | Partial | 15 min | Root cause, test coverage, regressions |
| Documentation | 🟢 Minor | Basic | 5 min | Accuracy, completeness, examples |
| Configuration | 🟡 Medium | Full | 10 min | Security, best practices, side effects |
| Refactoring | 🟢 Minor | Full | 15 min | Behavior preservation, performance |
| 变更类型 | 严重程度 | 自动化覆盖 | 审查耗时 | 关注重点 |
|---|---|---|---|---|
| 安全修复 | 🔴 critical | 全量扫描 | 30+ 分钟 | 漏洞、测试覆盖率、审计追踪 |
| 核心架构变更 | 🔴 critical | 部分覆盖 | 45+ 分钟 | 设计模式、可扩展性、一致性 |
| 新功能 | 🟡 重大 | 全量扫描 | 30 分钟 | 功能完整性、TRUST 5原则、文档 |
| Bug修复 | 🟢 minor | 部分覆盖 | 15 分钟 | 根因、测试覆盖率、回归风险 |
| 文档变更 | 🟢 minor | 基础检查 | 5 分钟 | 准确性、完整性、示例 |
| 配置变更 | 🟡 中等 | 全量检查 | 10 分钟 | 安全性、最佳实践、副作用 |
| 重构 | 🟢 minor | 全量检查 | 15 分钟 | 行为一致性、性能 |
Best Practices
最佳实践
DO
推荐做法
- Automate repetitive checks: Linting, coverage, formatting
- Focus human review on high-value areas: Architecture, security, design
- Be constructive: Review code, not people
- Explain WHY: Help reviewer understand the reasoning
- Request specific changes: Not vague "improve this"
- Provide examples: Show the better approach
- Flag trade-offs: Explain choices made
- Document decisions: Comment on why certain patterns chosen
- 自动化重复检查: 静态检查、覆盖率、格式化类工作全部自动化
- 人工审查聚焦高价值领域: 架构、安全、设计等维度
- 保持建设性: 审查代码而非针对个人
- 解释背后原因: 帮助提交人理解规则逻辑
- 提出明确的修改要求: 不要用模糊的「优化下这里」类表述
- 提供示例: 展示更优的实现方式
- 明确权衡取舍: 说明做出对应选择的原因
- 记录决策: 注释说明选择特定模式的原因
DON'T
禁止做法
- Nitpick style: Let linters handle formatting
- Reject without alternatives: Always suggest improvements
- Make personal comments: Focus on code quality
- Review when tired: Quality suffers
- Block on minor issues: Distinguish critical from nice-to-have
- Skip security review: Always check authentication, validation, secrets
- Ignore test coverage: Enforce ≥85% requirement
- 抠风格细节: 让静态检查工具处理格式化问题
- 无替代方案就直接驳回: 总是给出改进建议
- 发表人身攻击类评论: 聚焦代码质量本身
- 疲惫时做审查: 审查质量会大幅下降
- 因小问题阻塞流程: 区分严重问题和优化项
- 跳过安全审查: 始终检查身份认证、输入校验、敏感信息相关逻辑
- 忽略测试覆盖率: 严格执行≥85%的覆盖率要求
Integration with Context7
Context7集成能力
Live Security Scanning: Get latest vulnerability patterns from official databases
Best Practice Integration: Apply latest security recommendations from official docs
Version-Aware Checks: Context7 provides version-specific security guidance
Automated Fix Suggestions: Context7 patterns for common vulnerability fixes
Best Practice Integration: Apply latest security recommendations from official docs
Version-Aware Checks: Context7 provides version-specific security guidance
Automated Fix Suggestions: Context7 patterns for common vulnerability fixes
实时安全扫描: 从官方数据库获取最新的漏洞特征库
最佳实践集成: 应用官方文档发布的最新安全建议
版本感知检查: Context7提供对应版本的专属安全指导
自动修复建议: Context7内置常见漏洞的修复模式
最佳实践集成: 应用官方文档发布的最新安全建议
版本感知检查: Context7提供对应版本的专属安全指导
自动修复建议: Context7内置常见漏洞的修复模式
Related Skills
相关技能
- (Code patterns and best practices)
moai-core-practices - (Refactoring strategies)
moai-essentials-refactor
For detailed review checklists: reference.md
For real-world examples: examples.md
Last Updated: 2025-11-18
Status: Production Ready (Enterprise )
For real-world examples: examples.md
Last Updated: 2025-11-18
Status: Production Ready (Enterprise )
- (编码模式与最佳实践)
moai-core-practices - (重构策略)
moai-essentials-refactor
详细审查清单: reference.md
真实场景示例: examples.md
最后更新: 2025-11-18
状态: 生产可用(企业版)
真实场景示例: examples.md
最后更新: 2025-11-18
状态: 生产可用(企业版)