mcpField
C
code-reviewing

code-reviewing

github.com/melodic-software测试与质量2836 次安装今天更新
代码仓库

关于 code-reviewing

code-reviewing 是一项清单驱动的代码审查技能,依据工程、安全和项目规范检查代码变更。它提供多种审查配置,并在分析前收集技术背景。

主要功能

  1. 01快速、全面、安全和性能审查配置
  2. 02代码分析前查询技术资料
  3. 03加载项目专属审查配置
  4. 04深入审查时分析 Git 历史
  5. 05区分新增与既有问题
  6. 06识别生成文件

适用场景

  1. 01提交前审查暂存的变更
  2. 02检查拉取请求中的安全问题
  3. 03进行针对性的性能审查
  4. 04区分本次新增问题与既有问题

MCP 相关

该技能要求在代码分析前查询 MCP 服务,以了解当前技术实践。文档列出 microsoft-learn、perplexity、context7 和 ref 等按技术选用的服务。

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/melodic-software/claude-code-plugins --skill code-reviewing

安装后在 Claude Code 中输入/code-reviewing确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

references/
checklist.md
fix-workflow.md
references/clean-code/
code-smells.md
naming-functions.md
refactoring-patterns.md
references/tier-0/
research-phase.md
references/tier-1/
breaking-changes.md
git-history-context.md
reference-integrity.md
references/tier-2/
ai-ml-checks.md
backend-checks.md
config-checks.md
database-checks.md
frontend-checks.md
infrastructure-checks.md
mobile-checks.md
references/tier-3/
api-patterns.md
concurrency-patterns.md
privacy-patterns.md
security-patterns.md
references/tier-4/
anti-duplication-rules.md
claude-code-components.md
claude-md-core.md
documentation-rules.md
memory-rules.md
path-rules.md
pattern-compliance.md
platform-rules.md
repo-config.md
skill-rules.md

详细介绍

代码审查

基于 Google Engineering、OWASP 和现代开发标准中的行业最佳实践,提供系统化的代码审查技能。通过结构化、清单驱动的分析,发现随意审查容易遗漏的问题。

核心原则(Google): 即使代码并不完美,只要能改善整体代码健康度,就应批准。追求持续改进,而非尽善尽美。但绝不要批准会降低代码健康度的代码。

何时使用此技能

自动激活条件:

  • 完成重要的实现任务后
  • 提交更改前
  • 审查 PR 或暂存文件时

显式激活条件:

  • 用户要求“审查”“检查”“审计”或“检视”代码
  • 用户提到“代码审查”“PR 审查”或“看看这段代码”
  • 用户询问代码质量或是否符合标准

交互式审查范围界定

如果用户未指定审查深度和风险等级,请使用 AskUserQuestion 确定:

# Question 1: Review Depth (MCP: Google Engineering code review, OWASP)
question: "What type of code review is needed?"
header: "Review Type"
options:
  - label: "Quick Review (Recommended)"
    description: "Surface issues, style, obvious bugs (~15 min, ~3.5K tokens)"
  - label: "Thorough Review"
    description: "Multi-pass: logic, design, tests (~45 min, ~14K tokens)"
  - label: "Security Review"
    description: "Threat-focused: auth, validation, crypto (~30 min)"
  - label: "Architecture Review"
    description: "Design patterns, dependencies, coupling (~60 min)"

# Question 2: Risk Profile (MCP: CLI best practices - scope selection)
question: "What is the risk profile of this change?"
header: "Risk"
options:
  - label: "Low Risk (Recommended)"
    description: "Isolated fix, well-tested area, no user impact"
  - label: "Medium Risk"
    description: "Feature change, moderate scope, reversible"
  - label: "High Risk"
    description: "Critical path, security-sensitive, wide impact"
  - label: "Unknown"
    description: "I'm not sure - analyze and recommend"

根据这些回答选择合适的审查配置(快速、深入、安全、严格、性能)。

审查工作流

Code Review Progress:
- [ ] Step 0: RESEARCH PHASE (MANDATORY - Run MCP queries for technology stack)
- [ ] Step 0b: LOAD REPO CONFIG (Check .claude/code-review.md, fallback to CLAUDE.md)
- [ ] Step 0e: Git History Analysis (coupling, hot spots, author context - thorough/strict only)
- [ ] Step 1: Count files to review (accurate file counting)
- [ ] Step 1b: Detect generated content (scan for markers, identify generators)
- [ ] Step 2: Identify scope (files to review, excluding generated files)
- [ ] Step 3: Load context (repo standards + MCP research results + repo config)
- [ ] Step 4: Run Universal Checks (Layer 1) - informed by MCP research
- [ ] Step 5: Run Repo-Specific Checks (Layer 2, applying repo config rules)
- [ ] Step 5b: Run Claude Code Validation (Tier 4b, if CC files detected)
- [ ] Step 6: Report ALL findings with severity, rule source, and MCP validation status
- [ ] Step 7: Propose specific fixes with rationale and MCP-backed recommendations
步骤 0:调研阶段(必须执行)

重要:此步骤必须在任何代码分析之前执行,不可跳过。

审查代码前,先查询 MCP 服务,了解当前模式和最佳实践。这可以避免基于过时的训练数据提出判断。

加载参考资料: references/tier-0/research-phase.md

快速参考:

  1. 检测技术栈(根据文件扩展名、导入语句和清单文件)
  2. 查询 MCP 服务(根据检测到的技术并行查询):
    • Microsoft 技术(.NET、Azure、C#)→ microsoft-learn + perplexity(始终进行双重验证)
    • npm/PyPI 包 → context7 + ref
    • 安全模式 → perplexity(OWASP)
    • 版本相关判断 → perplexity(始终验证)
  3. 建立当前事实依据(保存经过验证的模式,供分析时使用)

核心规则:

  • 先调研,再分析——在提出判断前了解当前最佳实践
  • 必须使用 Perplexity——训练数据已过时;始终进行交叉验证
  • Microsoft 技术必须双重验证——microsoft-learn 可能过时,始终与 perplexity 配合使用
  • 每项发现都需要来源——未经权威验证的发现一律不予报告

高风险技术(必须额外使用 Perplexity 验证):

  • .NET 10、.NET Aspire、Azure AI Foundry、HybridCache、Microsoft.Extensions.AI
步骤 0b:加载仓库配置

加载特定于仓库的规则,以定制审查。

加载参考资料: references/tier-4/repo-config.md

配置优先级链:

1. .claude/code-review.md (PRIMARY)
   ├── Found: Parse config, apply rules, STOP
   └── Not found: Continue to fallback

1.5. .claude/rules/*.md (NATIVE - auto-loaded by Claude Code runtime)
     Always in context, supplements other config, path-scoped support

2. CLAUDE.md + @imports (FALLBACK)
   ├── Found: Read CLAUDE.md + follow @imports
   │   └── Extract rules from ## Critical Rules, ## Conventions sections
   └── Not found: Continue to fallback

3. No config found
   ├── Interactive mode: Use AskUserQuestion
   │   └── "No review configuration found. Review with default rules?"
   └── Non-interactive: Apply default rules only

加载内容:

来源解析内容
.claude/code-review.md技术栈、排除规则、严重性覆盖项、自定义检查
.claude/rules/*.md由运行时自动注入;视为附加审查规则
CLAUDE.md + @imports## Critical Rules、## Conventions、## Code Review 部分中的文本

配置对审查的影响:

配置部分对审查的影响
技术栈覆盖自动检测结果,提高 MCP 查询准确性
排除规则完全跳过这些规则(不生成任何发现)
严重性覆盖项更改特定规则的默认严重性
自定义检查添加项目专属检查(文件模式、内容规则)

快速参考:

# Check if config exists
ls .claude/code-review.md 2>/dev/null || echo "No config, will use CLAUDE.md fallback"

# Preview what config will be loaded (via review command)
/code-quality:review --show-rules

Agent 适用性:

所有加载 code-reviewing 技能的 Agent 都必须执行步骤 0b。这包括 code-reviewer、quality-reviewer 和 security-reviewer。每个 Agent 都必须独立加载并在自身职责范围内应用仓库配置。

安全排除提示:

如果仓库配置排除了与安全相关的规则,Agent 必须发出一条提示: “ADVISORY: Security rule '{rule}' excluded by repo config. Ensure intentional.” 此提示仅供参考——不属于审查发现,也不会阻止流程。

步骤 0e:Git 历史分析

触发条件: thorough 或 strict 配置(security/performance 配置下部分触发)

加载参考文档: references/tier-1/git-history-context.md

提取 Git 历史背景,为审查优先级提供依据并发现耦合问题:

  1. 读取配置 - 检查 .claude/code-review.md 中的历史分析设置
  2. 耦合分析 - 查找经常一起变更的文件
  3. 热点检测 - 识别高变更频率的文件(可配置阈值,默认:3 个月内变更 10 次以上)
  4. 作者背景 - 提取所有权模式(仅限 strict 配置)
  5. 近期模式 - 检测 Bug 修复、安全或重构历史

快速参考命令:

# Coupling analysis - files that change together
git log --name-only --pretty=format: -- <files> | sort | uniq -c | sort -rn | head -20

# Hot spot detection - change frequency
git log --since="3 months ago" --name-only --pretty=format: | sort | uniq -c | sort -rn | head -20

# Author context - ownership
git shortlog -sn -- <files>

# Recent patterns - commit messages
git log --oneline -10 -- <files>

配置行为:

配置分析深度
quick完全跳过
security部分(仅分析与安全相关的提交)
thorough耦合 + 热点 + 近期模式
strict完整分析,包括作者背景
performance部分(仅分析与性能相关的历史)
步骤 1:统计文件数(准确统计文件)

审查前,统计文件数以确保报告准确:

审查范围统计命令
已暂存的变更git diff --staged --name-only | wc -l
PR 变更git diff --name-only main...HEAD | wc -l
指定路径使用 Glob 工具并统计结果

重要事项:

  • 准确记录此数量,并在 Files Reviewed 输出中报告
  • 审查统计时排除二进制文件(图像、编译后的资源)
  • 审查统计时排除已删除的文件(无需审查)
  • 对于重命名文件:计为 1 个文件(新名称)

大型变更集警告:

  • 50 个以上文件:考虑分批审查或使用共识模式
  • 100 个以上文件:强烈建议拆分为更小的批次
步骤 1b:检测生成内容

扫描变更文件中的生成标记,以识别由脚本/工具创建的文件。审查生成器(事实来源),而非生成的输出。

检测标记(扫描前 20 行和后 10 行):

文件类型标记
MarkdownGenerated: YYYY-MM-DD、``
JSON根级 "timestamp" 或 "generator" 字段
脚本Auto-generated from、DO NOT EDIT、Generated by
代码// <auto-generated>、@generated、*.g.cs、*.generated.ts

工作流:

  1. 扫描变更文件中的标记
  2. 如果找到标记:提取生成器名称,搜索对应脚本,并将其加入审查范围
  3. 将生成文件标记为跳过或轻量审查
  4. 如果变更的只有生成文件,则发出警告(可能表示生成内容未及时更新)

边缘情况:

  • 生成器也有变更 → 仅审查生成器,跳过生成文件
  • 只有生成文件有变更 → 警告:生成内容可能未及时更新或被手动编辑
  • 未找到生成器 → 仍然审查生成文件
  • 对安全敏感的生成文件 → 仍然审查(凭据、配置)

加载 references/tier-5/generated-content-detection.md,了解完整的检测模式和算法。

步骤 2:确定范围
  • 明确请求:用户指定的文件或变更
  • 已暂存的变更:git diff --staged 或 git status
  • 近期工作:当前会话中修改的文件
  • PR 范围:拉取请求中的所有文件
步骤 3:加载背景信息

检查是否有针对仓库的标准。若有,则加载以进行第 2 层检查。

审查配置

指定 --profile <name> 时,会将层级加载限制为对应配置的子集。这样可以针对特定关注点进行重点审查。

可用配置:

配置加载的层级描述使用场景
security0, 1.3, 3-securityOWASP、密钥、身份验证、加密合并前快速安全扫描
quick1.1-1.6, 1.12设计、逻辑、基础风格提交前快速检查
thorough所有层级 + 1.30-1.32完整分析 + 参考/模式检查PR 审查(默认)
strict所有 thorough 层级 + 深度模式全面分析 + 架构模式检查库发布、重大更改
performance0, 1.5, 2-backend, 3-concurrencyN+1、复杂度、内存、并发性能审计

配置层级映射:

security:
  - Tier 0: Research Phase (ALWAYS - detect auth/crypto libraries)
  - Tier 1.3: Security (OWASP-Based)
  - Tier 3: security-patterns.md (when auth/crypto patterns detected)
  - Skip: Design, readability, testing, documentation

quick:
  - Tier 1.1: Design and Architecture (basic structure)
  - Tier 1.2: Functionality and Logic (obvious errors)
  - Tier 1.3: Security (CRITICAL only - hardcoded secrets)
  - Tier 1.4: Concurrency (obvious race conditions)
  - Tier 1.5: Performance (N+1, obvious inefficiencies)
  - Tier 1.6: Complexity (extreme violations)
  - Tier 1.12: Style (consistency)
  - Skip: Tier 0 MCP research, Tier 2+, Clean Code deep-dives

thorough:
  - ALL tiers loaded based on file types/patterns
  - Complete analysis (default behavior)
  - Section 1.30: Reference Integrity (always when renames/deletions detected)
  - Section 1.31: Breaking Changes (always for public API changes)
  - Section 1.32: Pattern Compliance (basic pattern checks)
  - Sections 1.33-1.36: Git History Context (coupling, hot spots, recent patterns)

strict:
  - ALL 'thorough' checks
  - Section 1.32 Pattern Compliance (full analysis):
    - Architectural pattern deviation (CQRS, mediator, repository)
    - DI registration consistency
    - File organization enforcement
  - Section 1.35: Author Context (ownership patterns, bus factor)
  - Import/export hygiene (module boundaries, barrel pollution)
  - Test correlation (orphaned tests detection)
  - Dependency safety (migration verification)

performance:
  - Tier 0: Research Phase (performance best practices via MCP)
  - Tier 1.5: Performance and Efficiency
  - Tier 2: backend-checks.md (database, API performance)
  - Tier 3: concurrency-patterns.md (async, threading)
  - Skip: Style, documentation, clean code deep-dives

各配置的令牌节省量:

配置预计令牌数相较 strict 节省
security~5,50060%+
quick~3,50075%+
thorough~14,00015%
strict~17,0000%(基准)
performance~6,00065%+
基线模式(差异分析)

指定 --baseline <branch> 时,会将每项发现归类为 NEW 或 PRE-EXISTING。

重要原因: 这是阻碍代码审查工具推广的头号因素。背负技术债的团队在 PR 仅引入 3 个新问题时,却会被 100 多项发现淹没,最终放弃使用该工具。

基线模式工作流:

  1. 根据 git diff 构建归因映射:

    git diff <baseline>...HEAD  # Three-dot for symmetric comparison
    
  2. 解析 diff,识别每个文件中更改的行范围

  3. 针对每项发现:检查 file:line 是否位于更改范围内

  4. 标记发现:NEW(新增/修改的行)或 PRE-EXISTING(未更改)

  5. 分开输出:突出显示新问题,折叠显示既有问题

发现归因规则:

行状态归因输出部分
新增(diff 中的 +)NEW“引入的新问题”
已修改(hunk 中发生更改)NEW“引入的新问题”
上下文(hunk 中未更改)PRE-EXISTING“既有问题”(折叠)
不在任何 hunk 中PRE-EXISTING“既有问题”(折叠)
已删除(diff 中的 -)SKIP不审查(已不存在)

基线输出格式:

## Review Summary (Baseline Mode)

**Baseline**: `main`
**New Issues (this changeset)**: 2 CRITICAL, 1 MAJOR ← FOCUS HERE
**Pre-existing Issues**: 47 (collapsed)
**Assessment**: Based on NEW issues only

## New Issues Introduced
[Detailed findings with Attribution: NEW]

<details>
<summary>Pre-existing Issues (47)</summary>
[Condensed findings]
</details>

质量门禁(CI/CD):

  • --fail-on-new-critical:只要出现任何新的 CRITICAL,退出码即为 1
  • --fail-on-new-major:只要出现任何新的 MAJOR,退出码即为 1
  • 既有问题不会导致构建失败

边界情况:

  • 基线不存在 → 报错并提供有效分支建议
  • 文件重命名 → 根据内容更改进行归因
  • 合并提交 → 使用三点 diff 进行正确比较
复杂度阈值

评估代码复杂度时,请使用以下具体阈值:

指标警告错误测量方式
圈复杂度> 10> 20统计决策点(if、while、for、case、&&、||、?)
认知复杂度> 15> 30SonarQube 指标(嵌套会增加权重)
函数行数> 30> 50统计非空、非注释行
嵌套深度> 3> 5统计嵌套的大括号/缩进层级
参数数量> 4> 7统计函数/方法参数
文件行数> 300> 500统计文件总行数

超出阈值时:

  • 警告 → MINOR 严重级别的发现
  • 错误 → MAJOR 严重级别的发现

建议的修复模板:

### Complexity Threshold Exceeded

**File**: `src/services/order.ts:processOrder()`
**Severity**: MAJOR
**Metric**: Cyclomatic Complexity = 23 (threshold: 15, error: 20)

**Problem**: Function has 23 independent paths through the code.

**Impact**: Difficult to test (need 23+ test cases), hard to maintain, high bug risk.

**Fix**: Extract methods for logical branches. Consider:
- Extract validation logic → `validateOrder()`
- Extract pricing logic → `calculatePrice()`
- Extract notification logic → `notifyCustomer()`
渐进式加载(令牌优化)

此技能采用分层渐进式披露来优化令牌用量。仅加载与正在审查的文件相关的内容。

**第 0 层(强制 — 始终最先加载):**研究阶段(约 2,000 个令牌)

  • 始终在分析前加载:references/tier-0/research-phase.md
  • 包含:技术检测矩阵、MCP 查询模板、“构建真实上下文”工作流
  • 目的:在提出任何结论前,查询 MCP 服务以了解当前模式
  • 此层级不可跳过——仅当代码完全属于内部代码且没有外部依赖时才可跳过

Tier 1(始终应用): 本文件中的通用检查(约 4,500 个 token)

**Tier 2(由文件类型触发):**根据文件扩展名加载

文件加载参考资料
.tsx、.jsx、.vue、.sveltereferences/tier-2/frontend-checks.md
.py、.java、.cs、.go、.rbreferences/tier-2/backend-checks.md
.swift、.kt、.dartreferences/tier-2/mobile-checks.md
.sql、migrations/*references/tier-2/database-checks.md
.yaml、.json、.env、.tomlreferences/tier-2/config-checks.md
Dockerfile、.tf、k8s/references/tier-2/infrastructure-checks.md
.ipynb、model/、ml/references/tier-2/ai-ml-checks.md

**Tier 3(由内容模式触发):**代码包含特定模式时加载

模式关键词加载参考资料
auth、crypto、password、secret、token、jwtreferences/tier-3/security-patterns.md
async、await、thread、lock、mutex、concurrentreferences/tier-3/concurrency-patterns.md
route、endpoint、@app、@Get、@Post、api/references/tier-3/api-patterns.md
PII、email、user、customer、gdpr、consentreferences/tier-3/privacy-patterns.md

**整洁代码深入指南:**加载以获取详细指导

**Tier 4(仓库专属):**存在仓库配置或 CLAUDE.md 时加载

上下文加载参考资料
存在 .claude/code-review.mdreferences/tier-4/repo-config.md
存在 CLAUDE.md(始终)references/tier-4/claude-md-core.md
*.md 文件references/tier-4/documentation-rules.md
重复内容指标references/tier-4/anti-duplication-rules.md
检测到路径模式references/tier-4/path-rules.md
*-{platform}.md 文件references/tier-4/platform-rules.md
.claude/skills/**references/tier-4/skill-rules.md
.claude/memory/**references/tier-4/memory-rules.md
.claude/temp/**references/tier-4/temp-file-rules.md
Profile 为 thorough/strictreferences/tier-4/pattern-compliance.md

Tier 4b(Claude Code 组件): 检测到 CC 文件时,委派给专门的审查员

文件模式组件类型审查员 Agent
.claude/agents/**/*.md、agents/*.mdAgentclaude-ecosystem:agent-auditor
.claude/skills/**、skills/*/SKILL.mdSkillclaude-ecosystem:skill-auditor
.claude/hooks/**、hooks.jsonHookclaude-ecosystem:hook-auditor
.claude/skills/**Skillclaude-ecosystem:skill-auditor
CLAUDE.md、.claude/memory/**Memoryclaude-ecosystem:memory-component-auditor
output-styles/*.md输出样式claude-ecosystem:output-style-auditor
.mcp.json、mcp.jsonMCP 配置claude-ecosystem:mcp-auditor
settings.json、.claude/settings.json设置claude-ecosystem:settings-auditor
plugin.json、.claude-plugin/**插件claude-ecosystem:plugin-component-auditor
状态栏脚本状态栏claude-ecosystem:statusline-auditor

加载参考资料以获取完整的检测和委派模式:references/tier-4/claude-code-components.md

注意:Tier 4b 需要安装 claude-ecosystem 插件。若未安装,请记录警告并跳过 CC 专属验证(继续进行标准审查)。

审查员 Agent 验证: Agent 名称可能会随插件版本更新而变化。如果委派失败,请运行 /claude-ecosystem:list skills 以验证当前的审查员 Agent 名称。上表列出的是截至本文件最近一次更新时已知的 Agent。

Tier 5(生成内容与 MCP 验证详情): 根据变更集特征加载

触发条件加载参考资料
大型变更集(50 个以上文件)references/tier-5/generated-content-detection.md
找到生成标记references/tier-5/generated-content-detection.md
需要高级 MCP 查询模式references/tier-5/mcp-validation.md
技术栈复杂references/tier-5/mcp-validation.md
安全模式需要 OWASP 验证references/tier-5/mcp-validation.md

注意: 主要的 MCP 验证在**Tier 0(研究阶段)**进行,且为必需步骤。Tier 5 的 mcp-validation.md 为复杂场景提供额外的查询模板和高级模式。

Token 预算估算:

场景令牌数
Tier 0 研究阶段(强制)~2,000(始终包含)
简单 Python 文件~8,500(Tier 0 + Hub + 后端)
React 组件~8,000(Tier 0 + Hub + 前端)
身份验证服务~10,000(Tier 0 + Hub + 后端 + 安全)
全栈 PR~11,500(Tier 0 + Hub + 前端 + 后端 + API)
文档文件(CLAUDE.md 仓库)~8,500(Tier 0 + Hub + 核心规则 + 文档规则)
Skill 修改~8,000(Tier 0 + Hub + 核心规则 + Skill 规则)
Memory 文件更新~7,500(Tier 0 + Hub + 核心规则 + Memory 规则)
使用高级 MCP 模式+~1,200 个令牌(Tier 5 mcp-validation.md)
委派 CC 审计员+~1,500 个令牌(Tier 4b 参考资料 + 启动审计员的开销)
检测生成内容+~1,200 个令牌(Tier 5 generated-content-detection.md)
包含 Git 历史上下文(全面/严格)+~1,500 个令牌(Tier 1 git-history-context.md)

**注意:**由于强制执行 Tier 0 研究阶段,令牌预算增加了约 2,000 个。此权衡通过 MCP 验证显著提升了审查准确性。

第 1 层:通用代码审查清单

这些检查适用于任何代码库、任何语言。

1.1 设计与架构
  • 整体设计合理 - 组件之间的交互合乎逻辑
  • 适合放在此代码库中 - 放在某个库或其他模块中并不更合适
  • 集成良好 - 符合现有系统架构
  • 现在正是进行此更改的时机 - 并非操之过急,也不是在解决错误的问题
  • 没有过度设计 - 解决当前问题,而非臆测未来需求(YAGNI)

SOLID 原则:

  • 单一职责(SRP) - 每个类/函数只有一个需要更改的理由
  • 开闭原则(OCP) - 对扩展开放,对修改关闭(不会针对不同类型反复使用 if/else)
  • 里氏替换原则(LSP) - 派生类可以替换基类(无需显式类型转换)
  • 接口隔离原则(ISP) - 客户端只依赖自己使用的方法
  • 依赖倒置原则(DIP) - 依赖抽象,而非具体实现
1.2 功能与逻辑
  • 实现预期功能 - 实现所需的功能
  • 对用户有益 - 既对最终用户有益,也对使用此代码的开发者有益
  • 处理边缘情况 - 边界条件、空输入、null 值
  • 错误处理健壮 - 妥善处理故障,并提供可执行的消息
  • 没有逻辑错误 - 差一错误、运算符错误、条件错误
1.3 安全性(基于 OWASP)
  • 输入验证 - 在服务端验证所有输入(使用允许列表,而非拒绝列表)
  • 输出编码 - 使用符合上下文的编码(HTML、JS、SQL、URL)
  • 没有注入漏洞 - SQL 注入、命令注入、XSS、路径遍历
  • 身份验证正确 - 通过 POST 登录、安全地处理会话,并在适当时使用 MFA
  • 强制执行授权 - 基于角色的访问控制,遵循最小权限原则
  • 机密未硬编码 - 代码中没有 API 密钥、密码或令牌
  • 机密未写入日志 - 日志、错误消息和 URL 中没有敏感数据
  • 使用现代密码学 - 密码使用 bcrypt/Argon2,加密使用 AES-GCM,不使用 MD5/SHA1
  • 依赖项安全 - 第三方库中没有已知漏洞
1.4 并发与线程安全
  • 保护共享状态 - 使用适当的锁、互斥锁或原子操作保护共享数据
  • 没有竞态条件 - 分析并发访问模式
  • 锁的获取顺序一致 - 按相同顺序获取锁,以防止死锁
  • 没有循环依赖 - 不同锁保护的资源之间没有循环依赖
  • 异步模式正确 - 正确使用 await,并传播异常
  • 线程安全的集合 - 在需要时使用并发集合
  • 没有死锁风险 - 使用超时机制,持有锁时不进行无限期等待
1.5 性能与效率
  • 没有不必要的操作 - 算法高效,不做冗余工作
  • 数据结构恰当 - 根据访问模式选择合适的数据结构
  • 没有 N+1 查询 - 优化数据库查询
  • 内存使用高效 - 没有内存泄漏,缓存使用恰当
  • I/O 已优化 - 对 I/O 密集型操作使用异步,适当进行批处理
  • 异步代码中没有阻塞操作 - 同步操作不会阻塞异步上下文
1.6 复杂度与可读性
  • 没有不必要的复杂度 - 可以快速理解
  • 函数/类大小适当 - 职责单一,不会过长
  • 没有过深的嵌套 - 缩进最多 3-4 层
  • 命名清晰 - 名称能充分表达用途,又不会过长
  • 注释说明原因 - 而不是说明做什么(代码应能自我说明)
  • 没有代码重复 - 遵循 DRY 原则
1.7 测试
  • 包含测试 - 根据变更编写适当的单元/集成测试
  • 测试正确 - 确实测试了其声称要测试的内容
  • 测试有用 - 代码出错时测试会失败
  • 测试边界情况 - 测试边界条件和错误场景
  • 测试易于维护 - 不过于复杂,断言清晰
  • 没有不稳定的测试 - 结果确定,不依赖时序

测试异味检测:

检查测试代码中常见的测试异味,这些异味会降低测试质量和可维护性:

异味检测方式严重性重要原因
空测试不包含断言的测试方法严重造成虚假的信心——测试总是通过
贪婪测试单个测试中有 > 5 个断言警告测试失败时,难以确定哪项行为出错
神秘客人未使用模拟对象,却访问外部文件/网络重大不稳定、运行缓慢、依赖环境
断言轮盘赌多个断言都没有描述性消息轻微难以确定哪个断言失败
测试中休眠Thread.Sleep、await Task.Delay、setTimeout重大速度慢、不稳定,还会掩盖时序错误
无效测试永远不会失败的测试(总是通过)警告通常没有测试任何有意义的内容
注释掉的测试已禁用的测试用例([Ignore]、skip、xtest)警告技术债务,可能掩盖实际问题
测试代码重复多个测试中存在相同的设置/清理代码轻微增加维护负担;使用 fixture

示例发现:

### Test Smell: Eager Test

**File**: `tests/UserService.test.ts:45`
**Severity**: WARNING
**Confidence**: MEDIUM

**Problem**: Test "should handle user operations" has 12 assertions testing multiple behaviors.

**Impact**: When this test fails, you won't know which behavior broke without debugging.

**Suggested Fix**:
```typescript
// Before (Eager Test - 12 assertions, multiple behaviors)
test('should handle user operations', () => {
  const user = createUser();
  expect(user.name).toBe('John');
  expect(user.email).toContain('@');
  // ... 10 more assertions about different behaviors
});

// After (Focused Tests - one behavior each)
test('should create user with valid name', () => {
  const user = createUser();
  expect(user.name).toBe('John');
});

test('should validate email format', () => {
  const user = createUser();
  expect(user.email).toContain('@');
});

```markdown
### Test Smell: Sleep in Test

**File**: `tests/api.test.ts:78`
**Severity**: MAJOR
**Confidence**: HIGH

**Problem**: Test uses `await new Promise(r => setTimeout(r, 2000))` to wait for async operation.

**Impact**: Test is slow (2 seconds), flaky (timing varies), and hides real async handling bugs.

**Suggested Fix**:
```typescript
// Before (Sleep - slow and flaky)
await new Promise(r => setTimeout(r, 2000));
expect(result).toBeDefined();

// After (Proper async handling)
await waitFor(() => expect(result).toBeDefined());
// Or
await expect(asyncOperation()).resolves.toBeDefined();

### 1.8 Error Handling and Logging

- [ ] **Errors caught appropriately** - Right level of granularity
- [ ] **Error messages actionable** - Clear what went wrong and how to fix
- [ ] **Logging present** - For debugging and troubleshooting
- [ ] **No sensitive data in logs** - PII, passwords, keys excluded
- [ ] **Graceful degradation** - Partial failures don't crash entire system

### 1.9 Documentation

- [ ] **Code documented** - Public APIs, complex logic explained
- [ ] **README updated** - If behavior/setup changes
- [ ] **API docs updated** - If endpoints change
- [ ] **Inline comments where needed** - For non-obvious decisions

### 1.10 Cross-Platform Compatibility

- [ ] **No hardcoded platform paths**:
  - `/mnt/c/Users/...` (WSL)
  - `/c/Users/...` (Git Bash)
  - `C:\Users\...` (Windows)
  - `/home/username/...` (Linux)
  - `/Users/username/...` (macOS)
- [ ] **Portable tool detection** - `command -v tool` not path hunting
- [ ] **Platform fallbacks** - Graceful handling when features unavailable
- [ ] **Scripts self-locate** - Use `Path(__file__).resolve()`, `$PSScriptRoot`, `${BASH_SOURCE[0]}`

### 1.11 Anti-Duplication

- [ ] **No duplicate content** - Same info in ONE place only
- [ ] **No identical files** - `diff` similar files to verify
- [ ] **Single source of truth** - Link instead of copy-paste
- [ ] **Config files distinct** - Each serves different purpose

### 1.12 Style and Consistency

- [ ] **Follows style guide** - Language/project conventions
- [ ] **Consistent with codebase** - Matches existing patterns
- [ ] **No style changes mixed with logic** - Separate formatting PRs

### 1.13 Accessibility (WCAG 2.1 AA)

- [ ] **Alt text present** - All images have descriptive alt text; decorative images use `alt=""`
- [ ] **Color contrast sufficient** - 4.5:1 for text, 3:1 for UI components
- [ ] **Keyboard navigable** - All interactive elements via Tab/Enter/Space; no keyboard traps
- [ ] **Focus visible** - Clear focus indicators on all interactive elements
- [ ] **Semantic HTML** - Proper heading hierarchy; buttons not divs; links not spans
- [ ] **ARIA correct** - Used only when semantic HTML insufficient; no conflicting roles

### 1.14 Internationalization (i18n)

- [ ] **No hardcoded strings** - All user-facing text externalized to resource files
- [ ] **Locale-aware formatting** - Dates, numbers, currency use locale APIs
- [ ] **RTL consideration** - Logical CSS properties where applicable
- [ ] **No string concatenation** - Use parameterized messages, not `"Hello " + name`
- [ ] **Pluralization handled** - Proper plural rules, not `count + " items"`

### 1.15 Observability

- [ ] **Structured logging** - JSON format with trace IDs, timestamps, context
- [ ] **Metrics present** - Latency, error rates, throughput for critical paths
- [ ] **Trace context propagated** - Distributed tracing across service boundaries
- [ ] **Health checks implemented** - Liveness/readiness probes with dependency checks
- [ ] **SLOs defined** - Measurable service level objectives for key operations

### 1.16 Data Privacy (GDPR/CCPA)

- [ ] **PII identified and protected** - Personal data encrypted, access controlled
- [ ] **Data retention enforced** - Clear policies, automated cleanup
- [ ] **Right to deletion** - Complete erasure across all systems possible
- [ ] **Consent tracked** - Explicit opt-in with audit trail
- [ ] **No PII in logs** - Redaction or hashing of personal identifiers

### 1.17 API Design

- [ ] **Versioning strategy** - Clear version in URL, header, or media type
- [ ] **Backward compatible** - New fields nullable, no removed fields
- [ ] **Deprecation documented** - Sunset dates, migration paths
- [ ] **Consistent naming** - Follows REST/GraphQL conventions
- [ ] **Error responses standardized** - Consistent error format across endpoints

### 1.18 Dependency Management

- [ ] **No known vulnerabilities** - CVE scanning in CI/CD
- [ ] **License compliance** - No GPL conflicts with proprietary code
- [ ] **Version pinned** - Lockfiles present and up-to-date
- [ ] **Transitive deps reviewed** - Indirect dependencies also secure
- [ ] **SBOM available** - Software Bill of Materials for audits

### 1.19 Database Patterns

- [ ] **N+1 queries avoided** - Eager loading or batch queries used
- [ ] **Indexes present** - For foreign keys, join columns, query patterns
- [ ] **Migrations backward compatible** - Incremental changes, no data loss
- [ ] **Schema properly normalized** - Or denormalized with clear rationale
- [ ] **Query optimization** - Explain plans reviewed for complex queries

### 1.20 Configuration Management

- [ ] **Secrets in vault** - Never hardcoded, use env vars or secrets manager
- [ ] **Feature flags used** - For gradual rollouts, A/B testing
- [ ] **12-factor compliant** - Config via environment, not files
- [ ] **Validation at startup** - Fail fast on missing/invalid config
- [ ] **Environment parity** - Same config structure across dev/staging/prod

### 1.21 Cloud/Infrastructure (12-Factor)

- [ ] **Stateless processes** - No local session storage, use external stores
- [ ] **Port binding** - Self-contained, exports HTTP via port
- [ ] **Disposability** - Fast startup, graceful SIGTERM shutdown
- [ ] **Dev/prod parity** - Minimal gap between environments
- [ ] **Container best practices** - Multi-stage builds, non-root user, resource limits
- [ ] **IaC used** - Terraform/CloudFormation for reproducibility

### 1.22 Frontend Patterns

- [ ] **Component design** - Small, reusable, composition over inheritance
- [ ] **State management** - Appropriate tool (local, context, Zustand, Redux)
- [ ] **Bundle size** - Code splitting, lazy loading, < 500KB main bundle
- [ ] **Memoization** - Strategic use of memo/useMemo/useCallback
- [ ] **Web Vitals** - LCP < 2.5s, FID < 100ms, CLS < 0.1

### 1.23 Mobile Patterns

- [ ] **Battery efficient** - WorkManager/JobScheduler, batched operations
- [ ] **Offline-first** - Local caching with sync, offline queue
- [ ] **Responsive layout** - Flexible dimensions (dp/sp), rotation handling
- [ ] **Memory efficient** - Image downsampling, lifecycle awareness
- [ ] **Network efficient** - Request batching, compression, exponential backoff

### 1.24 AI/ML Code Patterns

- [ ] **Model versioning** - MLflow/DVC for models and data
- [ ] **Reproducibility** - Random seeds, pinned dependencies, exact environments
- [ ] **Bias detection** - Fairness metrics across demographics
- [ ] **Data pipeline validated** - Schema validation, statistical tests
- [ ] **Model monitoring** - Drift detection for data and performance

### 1.25 Clean Code: Names (Robert C. Martin)

- [ ] **Intention-revealing names** - Name tells you why it exists, what it does, how it's used
- [ ] **No misleading names** - `accountList` should actually be a list; avoid false clues
- [ ] **Meaningful distinctions** - Not `data1`, `data2`, `dataInfo`, `theData`
- [ ] **Pronounceable names** - Can discuss code verbally without spelling variables
- [ ] **Searchable names** - Single-letter names only for small local scope
- [ ] **No encodings** - No Hungarian notation, no type prefixes (strName, intCount)
- [ ] **No mental mapping** - Reader shouldn't translate names to concepts they know
- [ ] **Class names are nouns** - Customer, Account, Parser (not verbs)
- [ ] **Method names are verbs** - postPayment, deletePage, save (not nouns)

### 1.26 Clean Code: Functions (Robert C. Martin)

- [ ] **Small** - 5-20 lines ideal; rarely exceed 30 lines
- [ ] **Do one thing** - Single level of abstraction; one reason to change
- [ ] **One abstraction level** - Don't mix getHtml() with .append("\n")
- [ ] **Descriptive names** - Long descriptive name better than short enigmatic one
- [ ] **Few arguments** - Zero ideal, one/two good, three questionable, never more than four
- [ ] **No flag arguments** - Split function into two instead of passing boolean
- [ ] **No side effects** - Don't modify unexpected state; function does what name says only
- [ ] **Command/Query separation** - Either do something OR answer something, never both
- [ ] **Prefer exceptions to error codes** - Don't return -1 or null for errors
- [ ] **Extract try/catch blocks** - Bodies of try/catch should be one-line function calls

### 1.27 Clean Code: Comments (Robert C. Martin)

- [ ] **Code explains itself first** - If you need a comment, try rewriting the code
- [ ] **Comments explain WHY** - Not what (code shows what) or how (code shows how)
- [ ] **Legal comments acceptable** - Copyright, license headers
- [ ] **Informative comments acceptable** - Regex explanation, return value meaning
- [ ] **TODO comments have tickets** - `// TODO: TICKET-123 - refactor after API v2`
- [ ] **No redundant comments** - `// Constructor` above a constructor is noise
- [ ] **No commented-out code** - Delete it; version control remembers
- [ ] **No closing brace comments** - `} // end if` means function is too long
- [ ] **No attribution comments** - `// Added by Bob` - use version control blame
- [ ] **No journal comments** - Change logs belong in VCS, not code

### 1.28 Clean Code: Conditionals (Pragmatic Programmer)

- [ ] **Positive conditions** - `if (isValid)` not `if (!isInvalid)`
- [ ] **No double negatives** - `if (!notFound)` should be `if (found)`
- [ ] **Guard clauses** - Early return for edge cases; avoid deep nesting
- [ ] **Explanatory variables** - Extract complex conditions to named booleans
- [ ] **Encapsulate conditionals** - `if (shouldBeDeleted(timer))` not `if (timer.hasExpired() && !timer.isRecurrent())`
- [ ] **Avoid negative conditionals** - `if (buffer.shouldCompact())` not `if (!buffer.shouldNotCompact())`
- [ ] **Polymorphism over switch** - Type-based switches often indicate missing polymorphism
- [ ] **No null checks everywhere** - Use Null Object pattern or Optional types

### 1.29 Code Smells Quick Reference

| Smell | Detection | Impact | Fix |
| --- | --- | --- | --- |
| **Long Method** | > 30 lines | Maintainability | Extract methods |
| **Long Parameter List** | > 4 parameters | Usability | Introduce parameter object |
| **Deep Nesting** | > 3-4 indent levels | Readability | Guard clauses, extract method |
| **Magic Numbers** | Hardcoded values | Maintainability | Named constants |
| **God Class** | Class does too much | Testability, coupling | Extract classes by responsibility |
| **Feature Envy** | Method uses other class's data | Coupling | Move method to data class |
| **Duplicate Code** | Same logic repeated | DRY violation | Extract to shared function |
| **Dead Code** | Unused code | Clutter, confusion | Delete it |
| **Primitive Obsession** | Overuse of primitives | Type safety | Value objects |
| **Shotgun Surgery** | One change touches many files | Fragility | Consolidate related code |
| **Divergent Change** | One class changed for many reasons | SRP violation | Split by reason for change |
| **Data Clumps** | Same data appears together | Missing abstraction | Create class for data group |
| **Comments** | Explaining bad code | Readability | Rewrite the code |
| **Speculative Generality** | Code for "future needs" | Complexity | Delete unused abstractions |

### 1.30 Reference Integrity (Rename/Cleanup Validation)

**Triggered by:** Git diff shows renames (R) or deletions (D)

When files, functions, classes, or variables are renamed or deleted, verify all references are updated.

- [ ] **Imports updated** - No broken imports referencing old paths/names
- [ ] **Documentation links valid** - No stale markdown links to renamed/deleted files
- [ ] **Config references current** - No orphaned references in tsconfig, package.json, etc.
- [ ] **String literals checked** - Hardcoded references to old names (low confidence, profile-gated)

**Detection:**

```bash
# Detect renames and deletions from git diff
git diff --name-status HEAD~1 | grep -E '^[RD]'

严重性:

检查项严重性始终启用
重命名后导入失效严重是
过时的文档链接重大是
孤立的配置引用重大是
硬编码字符串引用轻微配置文件(thorough+)

加载参考: 检测到重命名/删除时,加载 references/tier-1/reference-integrity.md。

1.31 破坏性变更检测

触发条件: 公共 API 表面发生变更

检测可能会破坏公共 API 外部使用者的变更。

  • 没有移除公共成员 - 删除公共方法/类前先弃用
  • 签名保持不变 - 参数类型/数量不变
  • 返回类型兼容 - 更改返回类型时提供迁移路径
  • 记录行为变更 - 通过注释标记语义变更

检测:

# Identify removed public members
git diff HEAD~1 | grep "^-.*public\s"

严重性:

检查项严重性始终启用
移除公共 API严重是
签名变更严重是
返回类型变更重大是
行为变更(手动)重大标记

加载参考: 公共 API 发生变更时,加载 references/tier-1/breaking-changes.md。

1.32 模式合规性

触发条件: thorough 或 strict 配置

验证新增代码是否符合代码库中既有的模式。

  • 错误处理保持一致 - 符合代码库的模式(Result、异常等)
  • 遵循命名约定 - 类、方法和变量的命名符合既有风格
  • 遵循架构模式 - 保持 CQRS、repository 等模式
  • 文件组织符合预期 - 新文件位于项目结构规定的位置

加载参考: references/tier-4/pattern-compliance.md,了解模式检测和比较。

1.33 缺少协同变更文件(Git 历史)

触发条件: thorough 或 strict 配置

检测经常一起变更、但未纳入审查范围的文件。

  • 已分析协同变更模式 - 识别协同变更率 >60% 的文件
  • 已标记缺少的关联文件 - 关联文件未纳入审查范围
  • 已验证测试耦合关系 - 源代码变更包含相关测试文件

严重性: 主要(缺少协同变更率 >60% 的文件可能表示变更不完整)

加载参考: references/tier-1/git-history-context.md

1.34 正在审查的热点文件(Git 历史)

触发条件: thorough 或 strict 配置

识别需要额外审查的高频变更文件。

  • 已分析变更频率 - 标记在配置的时间范围内变更 10 次以上的文件
  • 已分类提交模式 - 识别错误修复、功能开发和重构
  • 已进行额外审查 - 提高热点文件的审查优先级

严重性: 警告(高频变更的文件可能存在设计问题或代码脆弱)

加载参考: references/tier-1/git-history-context.md

1.35 单一所有者文件(Git 历史)

触发条件: 仅 strict 配置

识别所有权高度集中的文件(单人依赖风险)。

  • 已分析所有权 - 识别主要作者(提交占比 >90%)
  • 已注明单人依赖风险 - 标记单一所有者文件,以促进知识共享
  • 新作者变更 - 新作者修改既有文件时发出标记

严重性: 信息(用于提醒,不会阻止审查)

加载参考: references/tier-1/git-history-context.md

1.36 近期错误修复区域(Git 历史)

触发条件: thorough 或 strict 配置

识别近期有错误修复记录、可能较脆弱的区域。

  • 已分析错误修复历史 - 查找近期提交中包含 fix/bug/patch 关键词的记录
  • 已标记脆弱区域 - 在配置的时间范围内有 3 次以上错误修复
  • 加强边界情况审查 - 更仔细地检查错误处理路径

严重性: 警告(近期修复过的区域可能需要格外谨慎)

加载参考: references/tier-1/git-history-context.md

第 2 层:仓库专属检查

仅适用于存在 CLAUDE.md 或仓库规范的情况。

2.1 模式合规性
  • 遵循现有模式 - 与仓库中的其他文件相似
  • 命名约定一致 - 符合既有命名规范
  • 文件结构正确 - 位于正确位置,布局符合要求
2.2 CLAUDE.md 反模式(如适用)
  • 不混合操作系统内容 - 每个文件仅面向一个平台
  • 主题文件夹中不包含 README.md - 仅在根目录中
  • 不使用带编号的文件名 - 使用 git-setup.md,而非 01-git-setup.md
  • 标题与文件名一致 - 文件名与 # Header 相匹配

第 3 层:仓库规则(CLAUDE.md 合规性)

仅适用于根目录中包含 CLAUDE.md 的仓库。 根据正在审查的文件类型加载第 4 层参考资料。

3.1 检测和启用
  1. 检查仓库根目录中是否存在 CLAUDE.md
  2. 检查是否存在 .claude/memory/ 目录
  3. 如果两者均存在,则执行第 3 层检查
  4. 每次审查都加载 tier-4/claude-md-core.md
3.2 快速参考清单
  • 不使用绝对路径 - 使用相对于根目录的路径或占位符(<repo-root>、<skill-name>)
  • 标题与文件名匹配 - git-setup-windows.md -> # Git Setup Windows
  • 不混用平台内容 - 每个文件只服务于一个平台
  • 主题文件夹中不放 README - 仅在根目录和中心目录级别放置
  • 不使用带编号的文件 - 使用 git-setup.md,而不是 01-git-setup.md
  • 临时文件放在 .claude/temp/ - 不放在其他位置,并使用正确的命名约定
  • 单一事实来源 - 使用链接,不要重复内容
  • UTF-8 编码 - 仅使用 ASCII 标点(不使用弯引号)
  • 官方来源 - 文档须有官方文档作为依据,并注明最后验证日期
3.3 文档文件(*.md)

加载 tier-4/documentation-rules.md,了解:

  • 官方文档链接 - 所有安装指南都必须提供
  • 版本信息 - 记录当前版本和最低版本
  • 安装步骤 - 按依赖顺序排列
  • 验证步骤 - 附上预期输出
  • 最后验证日期 - 必须存在且为近期日期
3.4 平台专用文件(*-{platform}.md)

加载 tier-4/platform-rules.md,了解:

  • 平台隔离 - 不混入不同操作系统的内容
  • 后缀正确 - -windows、-macos、-linux、-wsl
  • WSL 重定向模式 - 在适当情况下重定向至 Linux
  • 中心目录完整性 - 同步更新所有平台中心目录
3.5 防止重复

检测到重复内容迹象时,加载 tier-4/anti-duplication-rules.md:

  • 不重复内容 - 每条信息只放在一个位置
  • 仅在 Last Verified 中记录版本 - 所有其他文件都链接至此处
  • 中心目录链接至分支文档 - 中心目录与参考文档之间不重复内容
  • 每项任务仅一份报告 - 合并多份报告
3.6 路径约定

检测到路径模式时,加载 tier-4/path-rules.md:

  • 不使用绝对路径 - 禁止使用特定平台的绝对路径
  • 相对于根目录的路径 - 从仓库根目录开始,而非当前目录
  • 通用占位符 - 使用 <repo-root>、<skill-name>,而非明确路径
  • 脚本自定位 - Path(__file__).resolve()、$PSScriptRoot
3.7 技能文件(.claude/skills/**)

加载 tier-4/skill-rules.md,了解:

  • SKILL.md 结构 - 包含必需章节
  • YAML 前置元数据 - name、description、allowed-tools
  • 渐进式披露 - 分层加载参考资料
  • 技能封装 - 不向外部暴露内部路径
3.8 记忆文件(.claude/memory/**)

加载 tier-4/memory-rules.md,了解:

  • 导入语法 - @.claude/memory/file.md
  • 记录令牌预算 - 注明大致令牌数量
  • 上下文指南 - 说明何时加载(始终加载或视上下文而定)
  • 最后更新日期 - 必须存在且准确
3.9 临时文件(.claude/temp/**)

加载 tier-4/temp-file-rules.md,了解:

  • 位置正确 - 仅允许放在 .claude/temp/
  • 命名约定 - YYYY-MM-DD_HHmmss-{agent-type}-{topic}.md
  • 扁平结构 - 不使用子目录
  • UTC 时间戳 - 使用 ISO 8601 格式

严重程度分类

严重(必须修复)
  • 安全漏洞(注入、绕过身份验证、机密信息泄露)
  • 可能导致数据丢失或损坏
  • 生产代码中存在竞态条件
  • 功能失效
  • 硬编码的机密信息或凭据
警告(应该修复)
  • 性能问题
  • 缺少错误处理
  • 测试覆盖不足
  • 代码重复
  • 硬编码的平台路径
  • 命名不佳
建议(可考虑)
  • 风格改进(加上“Nit:”前缀)
  • 替代方案
  • 文档改进
  • 重构机会

报告格式

## Code Review Findings

### Configuration Summary

**Config Source**: `.claude/code-review.md` | CLAUDE.md + @imports (fallback) | Defaults only
**Tech Stack**: .NET 10, ASP.NET Core 10 (config override) | React 19 (auto-detected)
**Rules Excluded**: [count] ([list if any])
**Severity Overrides**: [count] ([rule: old→new if any])
**Custom Checks**: [count] ([list if any])

### Technology Research Summary (from Step 0)

| Category | Technology | Version | MCP Source | Detection |
| --- | --- | --- | --- | --- |
| Runtime | .NET | 10 | perplexity | config override |
| Framework | ASP.NET Core | 10 | microsoft-learn + perplexity | config override |
| Frontend | React | 19 | context7 | package.json |

### Critical Issues (Must Fix)
1. **[Issue Title]**
   - **Location**: file:line
   - **Problem**: What's wrong and why it matters
   - **Confidence**: HIGH | MEDIUM | LOW
   - **Fix**: Specific code change
   - **Suggested Fix** (when Confidence is HIGH):
     ```language
     // Before (problematic)
     [original code]

     // After (fixed)
     [corrected code]
     ```
   - **Rule Source**: Tier 1 (Universal) - 1.3 Security | Tier 4 (repo-config.md) - Custom Check
   - **Validated**: Yes - [Source] [mcp-server-name]

### Warnings (Should Fix)
1. **[Issue Title]**
   - **Location**: file:line
   - **Problem**: What's wrong
   - **Confidence**: HIGH | MEDIUM | LOW
   - **Fix**: Specific change
   - **Suggested Fix** (when Confidence is HIGH):
     ```language
     // Before
     [original code]

     // After
     [corrected code]
     ```
   - **Rule Source**: Tier 1 (Universal) - 1.5 Performance | CLAUDE.md - Critical Rules
   - **Validated**: Yes/No - [Source if validated]

### Suggestions (Nit)
1. [Suggestion with rationale]
   - **Confidence**: LOW (stylistic)
   - **Rule Source**: Tier 1 (Universal) - 1.12 Style

### MCP Validation Summary

**Sources Consulted**: [count]
**Findings Validated**: [validated/total]
**Corrections Applied**: [count] (findings corrected based on MCP research)

| Finding | Source | Status |
| --- | --- | --- |
| [Finding] | [mcp-server] | Confirmed/Corrected/Outdated |
规则来源值

规则来源字段表示触发该发现的规则:

来源类型格式示例
通用检查Tier 1 (Universal) - {section}Tier 1 (Universal) - 1.3 Security
文件类型检查Tier 2 ({type}) - {section}Tier 2 (Backend) - API Design
内容触发Tier 3 ({pattern}) - {section}Tier 3 (Security) - OWASP Auth
仓库配置Tier 4 (repo-config.md) - {section}Tier 4 (repo-config.md) - Custom Check: PowerShell Naming
CLAUDE.mdCLAUDE.md - {section}CLAUDE.md - Critical Rules
自定义检查Custom Check: {name}Custom Check: No Console.WriteLine

验证状态选项:

  • 是 - [Source] [mcp-server]:已根据权威来源验证发现
  • 否(内部模式):无需外部参考(仓库特定约定)
  • 否(MCP 不可用):MCP 服务不可用;建议手动验证
置信度级别

置信度字段表示对该发现的确定程度:

级别标准建议修复?
高精确模式匹配 + MCP 验证是 - 生成可操作的修复代码
中语义分析,可识别的反模式可选 - 如果模式明确,则提供代码片段
低启发式/风格方面,可能是误报否 - 仅描述问题

置信度分配逻辑:

1. Pattern match detected?
   ├── YES + MCP validates pattern → HIGH
   ├── YES + No MCP validation → MEDIUM
   └── NO → Continue to heuristics

2. Anti-pattern recognized?
   ├── YES + Clear remediation path → MEDIUM
   └── YES + Ambiguous remediation → LOW

3. Stylistic/subjective concern?
   └── Always → LOW

不同置信度级别的示例:

发现置信度原因
通过字符串拼接导致 SQL 注入高精确模式,OWASP 记录了修复方法
缺少 null 检查中可识别的模式,修复取决于上下文
方法过长(35 行)低启发式判断,在具体上下文中可能可以接受
变量命名建议低风格偏好
建议修复指南

在以下情况中包含建议修复:

  1. 置信度为高 - 模式匹配 + MCP 验证
  2. 修复具有确定性 - 只有一种正确的修复方式
  3. MCP 提供代码模式 - 根据权威来源进行修复

建议修复格式:

**Suggested Fix**:
```csharp
// Before (vulnerable)
var query = "SELECT * FROM Users WHERE Id = " + userId;

// After (parameterized - OWASP recommendation)
var query = "SELECT * FROM Users WHERE Id = @userId";
cmd.Parameters.AddWithValue("@userId", userId);

**Omit Suggested Fix when:**

1. **Confidence is LOW** - May be false positive
2. **Multiple valid approaches** - User should choose
3. **Context-dependent** - Requires understanding broader system
4. **MCP unavailable** - Cannot validate the fix pattern

## Anti-Patterns (What NOT to Do)

- **"Looks good overall"** - Never without systematic checklist review
- **Benefit of the doubt** - If questionable, it IS a finding
- **Summarizing** - Critically analyze against checklist
- **Missing security issues** - Always check OWASP basics
- **Ignoring concurrency** - Think through race conditions
- **Skipping similar files** - Always diff files with similar purposes
- **Vague fixes** - "Fix this" vs "Replace lines X-Y with..."
- **Partial table verification** - Never verify only SOME items from a reference table; if you cite a table, verify ALL items with Glob or git status
- **Concluding files missing without Glob** - When uncertain if files exist, use `Glob pattern="path/**/*.md"` to verify rather than assuming based on what you haven't read

## Behavioral Rules

1. **Be skeptical, not charitable** - Assume problems until verified clean
2. **Every line matters** - Review ALL code assigned, understand it
3. **Think like an attacker** - What could go wrong? How could this be exploited?
4. **Think like a user** - Both end-user and developer-user
5. **Context matters** - View changes in context of whole file/system
6. **Report everything** - Every issue, with appropriate severity
7. **Propose specific fixes** - Concrete code, not vague suggestions
8. **Acknowledge good things** - Compliment well-done code

## Quick Reference Card

```text
ALWAYS CHECK:
[ ] Security: inputs validated, outputs encoded, no secrets
[ ] Concurrency: shared state protected, no race conditions
[ ] Design: SOLID principles, appropriate complexity
[ ] Tests: present, correct, useful
[ ] Platform: no hardcoded paths, portable detection
[ ] Duplicates: diff similar files
[ ] Accessibility: alt text, contrast, keyboard nav, semantic HTML
[ ] i18n: no hardcoded strings, locale-aware formatting
[ ] Observability: structured logs, metrics, traces, health checks
[ ] Privacy: PII protected, no PII in logs, consent tracked

CLEAN CODE (Robert C. Martin):
[ ] Names: intention-revealing, pronounceable, searchable, no encodings
[ ] Functions: small (5-20 lines), do one thing, few args (0-2), no side effects
[ ] Comments: explain WHY not WHAT, no commented-out code, no redundancy
[ ] Conditionals: positive conditions, guard clauses, no double negatives

DOMAIN-SPECIFIC (when applicable):
[ ] API: versioning, backward compat, error format
[ ] Database: N+1 avoided, indexes, migrations safe
[ ] Config: secrets in vault, feature flags, 12-factor
[ ] Frontend: component design, bundle size, web vitals
[ ] Mobile: battery/memory/network efficient, offline-first
[ ] AI/ML: model versioning, reproducibility, bias detection

CODE SMELLS (watch for):
- Long methods (> 30 lines)
- Long parameter lists (> 4 params)
- Deep nesting (> 3-4 levels)
- God classes (too many responsibilities)
- Feature envy (method uses other class's data)
- Primitive obsession (should use value objects)
- Shotgun surgery (one change touches many files)

RED FLAGS:
- Long if/else chains (OCP violation)
- Explicit type casting (LSP violation)
- new keyword overuse (DIP violation)
- String concatenation in queries (injection)
- Shared state without locks (race condition)
- Catch-all exception handlers (error hiding)
- Magic numbers/strings (maintainability)
- Platform-specific paths (portability)
- Missing alt text on images (accessibility)
- Hardcoded user-facing strings (i18n)
- console.log instead of structured logging (observability)
- PII in log statements (privacy violation)

参考资料

版本历史

  • v9.0.0 (2025-12-31):重大更新:增强验证覆盖 - 新增 6 项验证能力:(1) 引用完整性(第 1.30 节)——在重命名或删除后验证导入、文档链接和配置;(2) 破坏性变更检测(第 1.31 节)——检测公共 API 移除和签名变更;(3) 模式合规性(第 1.32 节)——验证错误处理、命名和架构的一致性;(4) 导入/导出规范——检查未使用的导入、循环依赖和模块边界;(5) 测试影响关联——检查代码变更是否未同步更新测试;(6) 依赖更新安全性——检查主版本升级和破坏性变更。新增用于库发布的 strict 配置。令牌预算已更新:thorough 约 14K,strict 约 17K。
  • v8.0.0 (2025-12-29):重大更新:研究优先的 MCP 验证 - 新增强制执行的第 0 步(研究阶段),在任何代码分析之前运行;在渐进式加载中新增第 0 层(始终最先加载);MCP 验证现已全面且必需,不再是有条件执行;所有发现都必须包含验证状态;在报告格式中新增技术研究摘要和 MCP 验证摘要;Microsoft 技术始终必须使用 perplexity(双重验证);为换取准确性,令牌预算增加约 2,000 个令牌
  • v7.0.0 (2025-12-29):新增生成内容检测(第 1b 步);通过基于内容的标记检测由脚本/工具创建的文件;将审查转向生成器脚本(事实来源);减少大型变更集中的审查噪声;新增第 5 层参考,用于检测模式和算法
  • v6.0.0 (2025-12-29):新增准确的文件计数工作流(第 1 步);新增第 4b 层 Claude Code 组件检测,并委派给 claude-ecosystem 审核器;文件计数可确保大型变更集的 已审查文件 报告准确
  • v5.0.0 (2025-12-24):新增第 5 层 MCP 验证阶段,使用 MCP 服务(perplexity、context7、ref、microsoft-learn、firecrawl)根据当前最佳实践验证发现;包括技术检测、交叉验证和引用支持
  • v4.0.0 (2025-11-28):新增第 3 层(仓库规则),包含第 4 层 CLAUDE.md 专项检查;新增 8 个参考文件,涉及文档、反重复、路径、平台、技能、记忆和临时文件;扩展渐进式加载,以支持特定于仓库的验证
  • v3.0.0 (2025-11-28):新增整洁代码原则(第 1.25 至 1.29 节):命名、函数、注释、条件语句、代码异味,内容来自 Robert C. Martin 和《程序员修炼之道》;更新快速参考卡,新增整洁代码和代码异味章节
  • v2.1.0 (2025-11-28):新增 12 个现代跨领域章节(第 1.13 至 1.24 节):无障碍、国际化、本地化、可观测性、数据隐私、API 设计、依赖管理、数据库模式、配置管理、云/基础设施、前端模式、移动端模式、AI/ML 代码模式
  • v2.0.0 (2025-11-27):重大扩展,新增 SOLID、OWASP、并发和 Google 实践
  • v1.0.0 (2025-11-27):首次发布

评论

支持 Markdown