code-review

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese
IRON LAW: Every finding MUST cite file, line range, and code evidence. No evidence = no finding.
铁律:每项发现都必须引用文件、行号范围和代码证据。没有证据 = 不构成发现。

Code Review — Risk-Priority with Proportional Verification

代码审查——风险优先与相称验证

Workflow

工作流

  • Step 1: Preflight ⚠️ REQUIRED
  • Step 2: Risk-Priority Audit (Passes A–F) ⚠️ REQUIRED
  • Step 3: Present Findings ⚠️ REQUIRED
  • Step 4: Fix Loop (conditional — scope set by Step 3)
  • Step 5: Pre-Publish Self-Check ⚠️ REQUIRED
  • Step 1: 预检 ⚠️ 必需
  • Step 2: 风险优先审计(Pass A–F)⚠️ 必需
  • Step 3: 报告发现 ⚠️ 必需
  • Step 4: 修复循环(条件执行——范围由 Step 3 确定)
  • Step 5: 发布前自检 ⚠️ 必需

1. Preflight — Establish Baseline ⚠️ REQUIRED

1. 预检——建立基线 ⚠️ 必需

For a PR URL, fetch platform diff and metadata (base/head refs, description, comments, CI status). Confirm the local review head corresponds to that PR before computing a local baseline.
Establish the requested review scope and freeze
baseline_commit
before reviewing:
  • For a branch or PR review, resolve the base branch and set
    baseline_commit
    to its merge base with the initial review head (
    git merge-base <base> HEAD
    ). Default
    base
    to
    main
    unless the user or PR metadata specifies another branch.
  • For an uncommitted-change review, set
    baseline_commit
    to the initial
    HEAD
    .
  • Record any user-specified path limits. Keep the baseline fixed throughout the fix loop, including when fixes are committed.
Collect in parallel, within that scope:
  • Branch state:
    git status --short --branch
  • Commits since baseline:
    git log --oneline --decorate --no-merges <baseline_commit>..HEAD
  • Tracked changes, including commits, staged changes, and unstaged changes:
    git diff --stat <baseline_commit>
    ,
    git diff --name-only <baseline_commit>
    , and
    git diff <baseline_commit>
  • Staging layers: when staged and unstaged edits coexist, also inspect
    git diff --cached <baseline_commit>
    and
    git diff
    so edits that cancel in the final working tree do not hide the staged state.
  • New files:
    git ls-files --others --exclude-standard
    ; read each in-scope file separately, since tracked diffs omit its content.
Explore related modules, usages, contracts, entry points, ownership boundaries, and critical paths.
对于 PR URL,获取平台 diff 和元数据(base/head 引用、描述、评论、CI 状态)。在计算本地基线前,确认本地 review head 与该 PR 对应。
确定请求的审查范围,并在审查前冻结
baseline_commit
:
  • 对于分支或 PR 审查,解析基础分支,并将
    baseline_commit
    设置为基础分支与初始 review head 的 merge base(
    git merge-base <base> HEAD
    )。除非用户或 PR 元数据指定了其他分支,否则默认使用
    main
    。
  • 对于未提交变更的审查,将
    baseline_commit
    设置为初始
    HEAD
    。
  • 记录用户指定的任何路径限制。在整个修复循环期间保持基线固定,包括修复已提交时。
在该范围内并行收集:
  • 分支状态:
    git status --short --branch
  • 自基线以来的提交:
    git log --oneline --decorate --no-merges <baseline_commit>..HEAD
  • 已跟踪的变更,包括提交、已暂存变更和未暂存变更:
    git diff --stat <baseline_commit>
    、
    git diff --name-only <baseline_commit>
    和
    git diff <baseline_commit>
  • 暂存层:当已暂存编辑与未暂存编辑同时存在时,还应检查
    git diff --cached <baseline_commit>
    和
    git diff
    ,避免最终工作区中相互抵消的编辑掩盖暂存状态。
  • 新文件:
    git ls-files --others --exclude-standard
    ;每个范围内文件都应单独读取,因为已跟踪的 diff 不包含其内容。
探索相关模块、使用方、契约、入口点、所有权边界和关键路径。

2. Risk-Priority Audit ⚠️ REQUIRED

2. 风险优先审计 ⚠️ 必需

Review every change in the established scope, including all branch/PR commits when applicable and in-scope uncommitted and new files. Execute passes in order.
审查既定范围内的每项变更,包括适用时所有分支/PR 提交,以及范围内的未提交变更和新文件。按顺序执行各个 Pass。

Pass A — Behavioral Regression & Compatibility

Pass A——行为回归与兼容性

  • Did any branch logic, default value, feature flag, or input/output contract change?
  • Are API parameters, defaults, and legacy-data handling backward-compatible?
  • Does naming/return-value semantics match the existing codebase? Flag "interface says X, implementation does Y" drift.
For every change impacting existing logic, state: original behavior → new behavior, impact scope, risk.
  • 是否有任何分支逻辑、默认值、feature flag 或输入/输出契约发生变化?
  • API 参数、默认值和旧数据处理是否向后兼容?
  • 命名和返回值语义是否与现有代码库一致?标记“接口声称为 X,实现却是 Y”这类偏移。
对于每项影响现有逻辑的变更,说明:原有行为 → 新行为、影响范围、风险。

Pass B — SOLID & Architecture

Pass B——SOLID 与架构

  • SRP: Does this module have exactly one reason to change?
  • OCP: Can a new variant be added without editing existing code?
  • LSP: Can any subclass substitute the parent without the caller knowing?
  • ISP: Do all implementers use all interface methods?
  • DIP: Is business logic tied to concrete I/O, storage, or hardcoded values?
  • Overly loose types (
    Any
    /
    any
    /
    dict
    /untyped) masking domain constraints?
Prefer incremental refactor plans over large rewrites. Load solid-checklist.md for deeper smell prompts.
  • SRP:该模块是否恰好只有一个变更原因?
  • OCP:能否在不修改现有代码的情况下添加新变体?
  • LSP:任何子类是否都能替代父类,而调用方无需感知?
  • ISP:所有实现者是否都使用了接口的全部方法?
  • DIP:业务逻辑是否绑定到具体 I/O、存储或硬编码值?
  • 过于宽松的类型(
    Any
    /
    any
    /
    dict
    /无类型)是否掩盖了领域约束?
相比大规模重写,优先采用渐进式重构计划。加载 solid-checklist.md,获取更深入的代码异味提示。

Pass C — Security & Reliability

Pass C——安全与可靠性

  • Can an unauthenticated or unauthorized user reach this code path? Could tenant A's data leak to tenant B?
  • What happens if two requests hit this code simultaneously? Could state change between check and act?
  • If this operation fails halfway, is data left consistent?
  • Unpinned deps, dependency confusion, known CVEs?
  • TLS verification disabled on HTTP clients (
    verify=False
    ,
    InsecureSkipVerify
    ,
    rejectUnauthorized: false
    )?
Call out both exploitability and impact. Load security-checklist.md for deeper threat-model analysis.
  • 未经身份验证或授权的用户能否到达此代码路径?租户 A 的数据是否可能泄漏给租户 B?
  • 如果两个请求同时命中此代码,会发生什么?状态是否可能在检查与执行之间发生变化?
  • 如果此操作中途失败,数据是否仍保持一致?
  • 依赖版本未锁定、dependency confusion 或已知 CVE?
  • HTTP 客户端是否禁用了 TLS 验证(
    verify=False
    、
    InsecureSkipVerify
    、
    rejectUnauthorized: false
    )?
必须同时指出可利用性和影响。加载 security-checklist.md,进行更深入的威胁模型分析。

Pass D — Performance & Stability

Pass D——性能与稳定性

  • What if this runs with 10×/100× data? Are resources bounded and released?
  • N+1 queries? CPU-intensive work in a hot path that could be cached or batched?
  • On failure: enough context to debug? Secrets leaked in logs or error output?
  • What if this value is null, 0, or empty?
Load code-quality-checklist.md for detailed sub-checks.
  • 如果数据量达到 10 倍或 100 倍会怎样?资源是否有边界且能够正确释放?
  • 是否存在 N+1 查询?热路径中是否存在 CPU 密集型工作,而本可缓存或批处理?
  • 失败时:是否有足够的上下文用于调试?日志或错误输出中是否泄漏了密钥?
  • 如果该值为 null、0 或空值会怎样?
加载 code-quality-checklist.md,获取详细的子项检查。

Pass E — Removal Candidates

Pass E——可移除候选项

  • Identify unused, redundant, or feature-flagged-off code.
  • Distinguish safe delete now vs defer with plan.
Load removal-plan.md if candidates are found.
  • 识别未使用、冗余或已被 feature flag 关闭的代码。
  • 区分可立即安全删除与延期处理并制定计划。
如果发现候选项,请加载 removal-plan.md。

Pass F — Test Coverage & Language-Specific Checks

Pass F——测试覆盖与语言专项检查

  • Decide whether the changed observable contract has enough discriminating verification for its risk. Reuse existing tests and checks before adding new ones.
  • Missing tests count as regression risk only when the changed logic is materially unverified and the risk cannot be covered by a smaller existing, static, or manual check.
  • For a bug fix, add a focused regression test only when the current suite fails to catch the original failure and the case is stable and valuable to preserve. Do not add a duplicate when an existing discriminating test already fails on that same original failure before the fix, or when the change is documentation, configuration, wiring-only, or behavior-preserving refactoring.
  • Require integration-level coverage only when a cross-module contract or boundary is not meaningfully verified by focused checks. Do not duplicate unit and integration tests that prove the same observable outcome.
  • Assertion discriminability: verify fixtures and assertions can distinguish real behavior from bypass/no-op — including cases where filtered and unfiltered results would look the same under the data you used, or where one happy path cannot prove a branch ran. Strengthen with cardinality, identity or negative cases, or observable effects appropriate to the feature.
Language-specific gotchas (non-obvious items the general passes may miss):
LanguageCheckFlag whenPass
PythonNaive/aware
datetime
mixing
Naive and aware datetime objects compared, subtracted, or assigned to the same field without explicit conversionA
PythonORM lazy-load on detached instanceAn ORM relationship or deferred column is accessed after the session that loaded the object is closedD
PythonORM dialect portabilityQueries rely on engine-specific SQL or vendor-only functions, raw SQL fragments, or dialect-only types instead of APIs the ORM can translate for every backend the project supports. Confirm compilation or execution against each dialect/version in that supported setA, D
TS/React
useEffect
/
useMemo
/
useCallback
dependency issues
A reactive dependency is missing, redundant, or is an unstable reference (new object/array/function created each render)D
JS/NodeGlobal patches/polyfills without guardsA monkey-patch or polyfill executes unconditionally — no environment check, feature detection, or scope isolationA
  • 根据风险判断变更后的可观察契约是否已有足够的区分性验证。添加新测试前,优先复用现有测试和检查。
  • 仅当变更逻辑在实质上未经验证,且风险无法通过更小范围的现有、静态或手动检查覆盖时,缺少测试才构成回归风险。
  • 对于 bug 修复,仅当当前测试套件无法捕获原始故障,且该用例稳定且值得保留时,才添加聚焦的回归测试。若已有具备区分力的测试在修复前已因同一原始故障而失败,或变更仅涉及文档、配置、接线或保持行为不变的重构,则不要添加重复测试。
  • 仅当聚焦检查无法有效验证跨模块契约或边界时,才要求集成级覆盖。不要重复验证同一可观察结果的单元测试和集成测试。
  • 断言区分能力:验证 fixture 和断言能够区分真实行为与绕过或空操作,包括在所用数据下过滤与未过滤结果看起来相同的场景,以及单一正常路径无法证明某个分支实际执行的情况。通过基数、身份标识、反例或与功能相适应的可观察效果来加强验证。
语言专项陷阱(通用 Pass 可能遗漏的非显而易见项):
语言检查项标记条件Pass
Pythonnaive/aware
datetime
混用
naive 和 aware
datetime
对象进行比较、相减或赋给同一字段时未进行显式转换
A
Python分离实例上的 ORM 延迟加载加载对象的 session 关闭后,仍访问 ORM 关系或延迟加载列D
PythonORM 方言可移植性查询依赖特定引擎的 SQL 或厂商专有函数、原始 SQL 片段或方言专用类型,而不是使用 ORM 能够为项目支持的每个后端转换的 API。针对受支持集合中的各方言/版本确认编译或执行结果A, D
TS/React
useEffect
/
useMemo
/
useCallback
依赖问题
响应式依赖缺失、冗余,或引用不稳定(每次渲染都会创建新的对象/数组/函数)D
JS/Node无保护的全局补丁/polyfillmonkey-patch 或 polyfill 无条件执行——没有环境检查、特性检测或作用域隔离A

3. Present Findings ⚠️ REQUIRED

3. 报告发现 ⚠️ 必需

Report first — present findings before making any changes. Load output-template.md for document structure, severity levels, and evidence rules.
After presenting:
  • If the user's original request explicitly included fixing (e.g., "review and fix", "fix everything", "review then fix all issues"): automatically proceed to Fix Loop for all findings — no confirmation needed. Override the default only if the user explicitly scoped the fix (e.g., "fix High only"). Negative examples — these do NOT count as fix requests: "review this fix", "review my bugfix branch", "check if this fix is correct" — here "fix" describes existing work, not an instruction to apply fixes.
  • Otherwise: ask user how to proceed (fix all / fix High only / fix specific items / no changes). Do NOT implement changes until user confirms.
先报告——在进行任何更改之前呈现发现。
加载 output-template.md,获取文档结构、严重性级别和证据规则。
呈现发现后:
  • 如果用户的原始请求明确包含修复(例如“审查并修复”“修复所有问题”“审查后修复所有问题”),则自动进入修复循环并处理所有发现——无需确认。只有当用户明确限定了修复范围时,才覆盖默认行为(例如“仅修复 High”)。反例——以下内容不属于修复请求:“审查此修复”“审查我的 bugfix 分支”“检查此修复是否正确”——这里的“修复”描述的是现有工作,而不是应用修复的指令。
  • 否则,询问用户如何继续(修复全部/仅修复 High/修复指定项/不做修改)。在用户确认前,不要实施更改。

4. Fix Loop (conditional)

4. 修复循环(条件执行)

⛔ Enter only after Step 3 determines the fix scope. Fix only issues within that scope.
Each iteration:
  1. Run the smallest relevant verification to establish a pre-fix baseline.
  2. Apply the minimal fix (avoid introducing new behavior), adding or updating a targeted test only when the risk assessment above shows that it is needed to protect the changed contract.
  3. Re-run the same verification to confirm the fix.
  4. Adversarial re-review of the entire accumulated change against Step 1's frozen
    baseline_commit
    : re-read
    git diff <baseline_commit>
    and all in-scope new files, plus the separate staging-layer diffs from Step 1 when applicable. This includes the original changes and every fix, whether committed, staged, unstaged, or untracked. A commit-only diff such as
    <base>..HEAD
    omits uncommitted fixes; a working-tree-only diff omits the branch's commits. Keep the original scope and baseline instead of reviewing only the latest patch.
    The re-review must be adversarial: its default stance is that the fix introduced new problems. The reviewer must actively try to refute the fix's correctness before accepting it. Only flag issues that would cause observable failure in production or violate a documented contract — theoretical concerns that require multiple unlikely preconditions do not count as findings.
    Independent judgment: re-read the current full diff, project conventions, and affected callers on every re-review. Treat earlier findings and fix rationale as claims to verify against current code. Preserve iteration history for traceability.
    Apply Passes A, C, D, F (B and E remain part of the initial audit). For each modified region, try to construct a realistic failure scenario before accepting it. If an independent reviewer is available and delegation is authorized, provide project context and the full diff without leading it with the intended verdict or fix rationale. Otherwise perform the same evidence-driven review inline; do not claim that conversational context was erased.
  5. Expand scope only if the re-review (step 4) surfaces new issues within the agreed fix scope. If out-of-scope findings are discovered, record them in the Fix Loop Iterations table and report to user at the end of the Fix Loop.
Continue without a fixed iteration cap until relevant verification passes and the latest full-diff re-review finds no remaining in-scope issues. If a missing prerequisite, a required decision outside the authorized scope, or repeated attempts without new evidence or improvement prevents further progress, stop and report the unresolved findings, verification status, and concrete blocker. Iteration count alone is not a reason to stop or request renewed authorization.
Iteration tracking: Record each iteration's findings and fixes. The final report must include a per-iteration summary (iteration number, issue addressed, fix applied, verification result, re-review outcome) so the user can trace the fix history (see output-template.md § Fix Loop Iterations).
Test strategy (adapt per project):
  • Run the smallest existing check that exercises the changed contract, then broaden only when the change crosses a boundary or the focused check reveals a relevant dependency.
  • Python: run the target test or existing focused check first, then the related directory only when warranted by the change.
  • Frontend: run the affected component/page check first, then related suites only when the change crosses their contract.
  • API changes: verify the changed request/response or error contract with existing coverage; add one discriminating case only when that contract is otherwise unverified.
  • Do not create tests solely to increase coverage, mirror implementation branches, or make a report look complete. A test that cannot fail for a plausible regression is not useful. Record why no new test was needed when existing checks or the low-risk scope are sufficient.
  • Missing prerequisites (command not found, deps missing): state "unverified" with impact scope; provide reproducible commands; never fake results.
⛔ 仅在 Step 3 确定修复范围后进入。只修复该范围内的问题。
每次迭代:
  1. 运行最小相关验证,以建立修复前基线。
  2. 实施最小修复(避免引入新行为),仅当上述风险评估表明需要保护变更后的契约时,才添加或更新针对性测试。
  3. 重新运行相同验证,以确认修复有效。
  4. 对全部累计变更相对于 Step 1 冻结的
    baseline_commit
    进行对抗性复审:重新读取
    git diff <baseline_commit>
    和范围内所有新文件,并在适用时读取 Step 1 中单独的暂存层 diff。这包括原始变更和每项修复,无论其已提交、已暂存、未暂存或未跟踪。仅显示提交的 diff(如
    <base>..HEAD
    )会遗漏未提交的修复;仅显示工作区的 diff 会遗漏分支提交。保持原始范围和基线,而不是只审查最新补丁。
    复审必须具有对抗性:默认立场是假设修复引入了新问题。审查者必须主动尝试推翻修复的正确性,然后才能接受修复。仅标记那些会在生产环境中造成可观察故障或违反已记录契约的问题——需要多个不太可能的前置条件才能成立的理论隐患不构成发现。
    独立判断:每次复审时,重新阅读当前完整 diff、项目约定和受影响的调用方。将之前的发现和修复理由视为需要根据当前代码验证的主张。保留迭代历史以供追溯。
    执行 Pass A、C、D、F(B 和 E 仍属于初始审计的一部分)。对于每个修改区域,尝试构建现实中的故障场景,然后才能接受修复。如果有独立审查者且已授权委派,应提供项目上下文和完整 diff,但不要以预期结论或修复理由引导审查者。否则,应在当前流程中执行同样的证据驱动审查;不要声称对话上下文已被清除。
  5. 仅当复审(步骤 4)发现约定修复范围内的新问题时,才扩展范围。如果发现范围外问题,将其记录在修复循环迭代表中,并在修复循环结束时报告给用户。
持续执行,不设固定迭代次数上限,直到相关验证通过,且最新的完整 diff 复审未发现剩余的范围内问题。如果缺少必要前置条件、需要作出授权范围之外的决策,或反复尝试后没有新证据或改进,从而无法继续推进,则停止并报告未解决的发现、验证状态和具体阻塞因素。不得仅以迭代次数作为停止或请求重新授权的理由。
迭代跟踪:记录每次迭代的发现和修复。最终报告必须包含逐次迭代摘要(迭代编号、已处理问题、已应用修复、验证结果、复审结论),以便用户追踪修复历史(参见 output-template.md § 修复循环迭代)。
测试策略(根据项目调整):
  • 运行能够验证变更后契约的最小现有检查;仅当变更跨越边界或聚焦检查揭示了相关依赖时,才扩大检查范围。
  • Python:先运行目标测试或现有聚焦检查,仅当变更确有需要时再运行相关目录。
  • 前端:先运行受影响的组件或页面检查,仅当变更跨越其契约时再运行相关测试套件。
  • API 变更:使用现有覆盖验证变更后的请求/响应或错误契约;仅当该契约未经验证时,添加一个具备区分力的用例。
  • 不要仅为提高覆盖率、镜像实现分支或让报告显得完整而创建测试。无法因合理回归而失败的测试没有价值。当现有检查或低风险范围已经足够时,记录无需新增测试的原因。
  • 缺少必要前置条件(找不到命令、缺少依赖):将其标记为“unverified”(未验证),并说明影响范围;提供可复现的命令;绝不可伪造结果。

5. Pre-Publish Self-Check ⚠️ REQUIRED

5. 发布前自检 ⚠️ 必需

Run the self-check in output-template.md § Pre-Publish Self-Check before finalizing.
最终定稿前,运行 output-template.md § 发布前自检中的自检流程。

Constraints & Anti-Patterns

约束与反模式

Never:
  • Dismiss implicit behavior changes from default-value modifications.
  • Label an unverified item as "passed."
  • Bypass critical checks to make tests pass (removing auth, swallowing exceptions, downgrading security).
  • Commit or push without explicit user request.
  • Make fixes before presenting findings.
Avoid:
  • Listing style/naming issues before security and correctness.
  • Reporting "no issues found" without listing what was checked.
  • Copy-pasting code without explaining what is wrong.
  • Treating all findings as equal severity.
  • Guessing at behavior instead of reading actual code and diff.
绝不:
  • 忽视默认值修改带来的隐式行为变化。
  • 将未验证项标为“passed”。
  • 为使测试通过而绕过关键检查(移除身份验证、吞掉异常、降低安全级别)。
  • 未经用户明确要求便提交或推送。
  • 在呈现发现之前实施修复。
避免:
  • 在安全与正确性问题之前列出样式或命名问题。
  • 未列出已检查内容便报告“未发现问题”。
  • 粘贴代码却不解释问题所在。
  • 将所有发现视为相同严重性。
  • 根据猜测而非实际代码和 diff 判断行为。

Resources

资源

Load on demand — only when a finding needs deeper analysis.
FileWhen to load
solid-checklist.mdPass B finding needs smell prompts or refactor heuristics
security-checklist.mdPass C finding needs threat-model detail
code-quality-checklist.mdPass D finding needs stability/performance sub-checks
removal-plan.mdPass E found removal candidates
output-template.mdStep 3 & 5 — document structure, evidence rules, self-check
按需加载——仅当某项发现需要更深入的分析时加载。
文件何时加载
solid-checklist.mdPass B 发现需要代码异味提示或重构启发式方法时
security-checklist.mdPass C 发现需要威胁模型细节时
code-quality-checklist.mdPass D 需要稳定性或性能子项检查时
removal-plan.mdPass E 发现可移除候选项时
output-template.mdStep 3 和 Step 5——文档结构、证据规则、自检