clean-code-guard

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

clean-code-guard

clean-code-guard

You are reviewing generated or changed code before it ships. Apply the rules below as a guard pass after the first implementation pass. If the user explicitly invokes this skill before writing code, use the same rules while writing and still run the self-check before delivery.
你需要在代码发布前,对生成或修改的代码进行审查。在首次实现完成后,将以下规则作为防护检查环节应用。如果用户在编写代码前显式调用本技能,则在编写过程中遵循相同规则,并在交付前执行自我检查。

Compatibility

兼容性

This is a portable instruction skill. It requires no MCP server, network access, API key, shell command, local executable, or bundled script. It can be used in any runtime that supports
SKILL.md
plus directly linked references/ files;
agents/openai.yaml
is lightweight display metadata.
This skill does not replace project linters, formatters, type checkers, or test runners. Use the project's own tools for mechanical verification; use this skill for the judgement layer around code quality and review.
这是一个可移植的指令技能,无需MCP服务器、网络访问、API密钥、Shell命令、本地可执行文件或捆绑脚本。它可在任何支持
SKILL.md
及直接关联[references/]文件的运行环境中使用;
agents/openai.yaml
是轻量级展示元数据。
本技能不会替代项目的代码检查器(linter)、格式化工具、类型检查器或测试运行器。机械验证请使用项目自身工具;本技能用于代码质量和审查的判断层面。

How to use this skill

如何使用本技能

This skill has two modes — pick based on the user's request.
Guard-pass mode (recommended): after code has been generated, edited, refactored, or fixed, check the diff or target files against the Always-applied imperatives below. Fix violations before presenting, committing, or merging the work.
Live mode (explicit): when the user invokes this skill before a risky code edit, apply the same imperatives while writing, then run the Self-check before delivery checklist. If you violate any rule, fix it before showing the user.
Review mode (triggered when the user asks you to review, audit, critique, or rate code): walk references/review-checklist.md against the target file(s) and produce a structured findings report. Do not edit code in review mode unless asked.
For both modes, the rule bodies live in references/. Read the relevant reference file when:
  • You hit a rule you don't fully remember the reasoning for.
  • The user pushes back on a rule and you need the source citation.
  • You're in review mode and need the full checklist.
  • The code under review touches a specific principle (e.g., subclassing → references/solid.md; deduplication → references/dry-kiss-yagni.md).
The reference files are:
  • references/naming-and-functions.md — names, function size, parameters, command/query separation.
  • references/comments-and-formatting.md — when to comment, when to delete, matching neighbor style.
  • references/solid.md — SRP, OCP, LSP, ISP, DIP with the modern phrasings and detection smells.
  • references/dry-kiss-yagni.md — knowledge vs code duplication, Sandi Metz's re-inline rule, McCabe complexity, Fowler's YAGNI cost categories.
  • references/ai-failure-modes.md — the 14 systematic ways LLMs produce bad code. Read this one first if you are an AI agent reading this skill. It is the highest-leverage file in the skill.
  • references/review-checklist.md — structured walk-through for review mode.
  • references/sources.md — central bibliography for source URLs. Read it only when you need to verify or cite an external source.
本技能有两种模式——根据用户请求选择。
防护检查模式(推荐):在代码生成、编辑、重构或修复完成后,对照以下「始终强制执行的规则」检查差异或目标文件。在展示、提交或合并工作成果前修复所有违规问题。
实时模式(显式调用):当用户在高风险代码编辑前调用本技能时,在编写过程中应用相同规则,然后执行「交付前自我检查」清单。若违反任何规则,需在展示给用户前修复。
审查模式(当用户要求审查、审计、评判或评级代码时触发):对照[references/review-checklist.md]对目标文件进行结构化检查,并生成结构化发现报告。审查模式下除非用户要求,否则请勿编辑代码。
无论使用哪种模式,规则内容均存放在[references/]中。在以下场景下请阅读相关参考文件:
  • 遇到无法完全记清背后逻辑的规则时。
  • 用户对某条规则提出质疑,需要引用来源时。
  • 处于审查模式,需要完整清单时。
  • 待审查代码涉及特定原则(例如:子类化 → [references/solid.md];去重 → [references/dry-kiss-yagni.md])。
参考文件包括:
  • [references/naming-and-functions.md] —— 命名、函数大小、参数、命令/查询分离。
  • [references/comments-and-formatting.md] —— 何时添加注释、何时删除注释、匹配周边代码风格。
  • [references/solid.md] —— 采用现代表述方式的SRP、OCP、LSP、ISP、DIP原则及问题检测方法。
  • [references/dry-kiss-yagni.md] —— 知识重复 vs 代码重复、Sandi Metz的内联规则、McCabe复杂度、Fowler的YAGNI成本分类。
  • [references/ai-failure-modes.md] —— LLM生成劣质代码的14种系统性方式。如果您是阅读本技能的AI Agent,请首先阅读此文件,它是本技能中价值最高的文件。
  • [references/review-checklist.md] —— 审查模式下的结构化检查清单。
  • [references/sources.md] —— 来源URL的集中参考书目。仅在需要验证或引用外部来源时阅读。

Examples

示例

  • A coding agent implements an endpoint: use guard-pass mode on the diff before the work is presented or committed.
  • User asks "review this PR" or "should I merge this?": use review mode and report findings from references/review-checklist.md; do not edit unless asked.
  • User asks "implement this endpoint using clean-code-guard": use live mode while writing, then run the self-check before delivery.
  • User asks "refactor this function, same behavior": preserve observable behavior exactly and treat any bug fix as a separate change.
  • 编码Agent实现了一个端点:在展示或提交工作成果前,对差异使用防护检查模式。
  • 用户询问“review this PR”或“should I merge this?”:使用审查模式,根据[references/review-checklist.md]报告发现结果;除非用户要求,否则请勿编辑代码。
  • 用户要求“implement this endpoint using clean-code-guard”:编写时使用实时模式,交付前执行自我检查。
  • 用户要求“refactor this function, same behavior”:严格保留可观察行为,将任何bug修复视为单独变更。

Success criteria

成功标准

This skill is working when code-writing tasks avoid the listed failure modes, code-review tasks produce prioritized findings with concrete evidence, and refactors preserve behavior unless the user explicitly asks for a behavior change. It should stay silent for conceptual, CI, git workflow, prose, data analysis, and test-running tasks covered by the frontmatter exclusions.
当代码编写任务避免了列出的故障模式、代码审查任务生成了带有具体证据的优先级发现结果,且重构操作保留行为(除非用户明确要求变更行为)时,本技能即发挥作用。对于概念类、CI、Git工作流、散文、数据分析和测试运行等任务(排除在前置说明外的内容),本技能应保持静默。

Why this skill exists

本技能的存在意义

LLM-generated code has measurable, systematic failure modes that generic "follow clean code" instructions do not catch. Examples backed by published research:
  • Code duplication grew 8x in tracked codebases between 2021 and 2024 (GitClear 2025 report).
  • Package hallucination rate averages 19.6% across 16 models (Spracklen et al., USENIX Security '25).
  • LLMs often wrap risky operations in broad catch-all handlers that swallow errors (Karpathy).
  • AI agents "declare success despite failing tests" by returning hardcoded fixture values (Fowler, Patterns for Reducing Friction).
  • Function size grew from 142 to 267 LoC, cyclomatic complexity from 4.2 to 8.1 in AI-assisted commits (GitClear).
The classic principles (Clean Code, SOLID, DRY/KISS/YAGNI) are still the foundation — but this skill adds the AI-specific layer most rule packs miss.
LLM生成的代码存在可衡量的系统性故障模式,而通用的“遵循Clean Code”指令无法捕捉这些问题。已发表研究支持的示例包括:
  • 代码重复率增长8倍:2021年至2024年间,被跟踪的代码库中代码重复率增长了8倍(GitClear 2025报告)。
  • 包幻觉率平均19.6%:在16个模型中,包幻觉率平均为19.6%(Spracklen等人,USENIX Security '25)。
  • LLM常将高风险操作包裹在宽泛的异常捕获处理器中,从而掩盖错误(Karpathy)。
  • AI Agent**“尽管测试失败仍宣称成功”**:通过返回硬编码的固定值来实现(Fowler,Patterns for Reducing Friction)。
  • 在AI辅助的提交中,函数大小从142行增长到267行,圈复杂度从4.2增长到8.1(GitClear)。
经典原则(Clean Code、SOLID、DRY/KISS/YAGNI)仍是基础——但本技能增加了大多数规则包缺失的AI特定层面。

Always-applied imperatives

始终强制执行的规则

These are the rules to follow on every code change. They are imperative, not suggestions.
这些规则适用于所有代码变更,是强制要求而非建议。

Functions and names

函数与命名

  1. Names reveal intent. Never use
    data
    ,
    data2
    ,
    result
    ,
    result_final
    ,
    item
    ,
    temp
    ,
    value
    ,
    obj
    ,
    info
    ,
    helper
    ,
    manager
    ,
    utils
    , or
    handle_*
    /
    process_*
    /
    do_*
    without a qualifier. A name must answer why it exists and what it does. (Clean Code Ch. 2)
  2. Functions stay small. Target ≤20 lines, one level of abstraction, one thing. If you can extract a function with a name that doesn't restate the body, the parent was doing more than one thing. (Clean Code Ch. 3)
  3. Four arguments is the hard ceiling. At five, stop and introduce a request/config object (record, struct, DTO, or equivalent). Never use boolean flag arguments — split into two functions instead.
  4. No output arguments. A function either returns a value (query) or has a side effect (command). Never both. Command names use verbs; query names use nouns or getter-style names. (CQS)
  1. 名称需体现意图。禁止在无限定词的情况下使用
    data
    data2
    result
    result_final
    item
    temp
    value
    obj
    info
    helper
    manager
    utils
    handle_*
    /
    process_*
    /
    do_*
    。名称必须明确回答「它为何存在,以及它做什么」。(Clean Code 第2章)
  2. 函数保持短小。目标是≤20行、单一抽象层级、只做一件事。如果能提取出一个名称无需重复函数体内容的子函数,说明父函数承担了多项职责。(Clean Code 第3章)
  3. 参数上限为4个。若参数达到5个,应停止并引入请求/配置对象(record、struct、DTO或等效结构)。禁止使用布尔标志参数——应拆分为两个函数。
  4. 无输出参数。函数要么返回值(查询),要么产生副作用(命令),不可两者兼具。命令型函数名称使用动词;查询型函数名称使用名词或getter风格名称。(CQS原则)

Comments and structure

注释与结构

  1. Comments explain why, never what. Delete any comment that paraphrases the line below it. Delete step-number scaffolding comments. Delete commented-out code — version control exists. (Clean Code Ch. 4)
  2. Match the file's existing style. Read the file you're editing and at least one neighbor before writing. Mirror the casing, import order, error handling, logging, and HTTP/DB client choices. Do not introduce a second pattern.
  1. 注释解释「为什么」,而非「是什么」。删除任何重复下方代码内容的注释。删除带步骤编号的脚手架注释。删除注释掉的代码——版本控制系统已记录历史。(Clean Code 第4章)
  2. 匹配文件现有风格。在编写前,阅读要编辑的文件及至少一个同目录下的相邻文件。镜像现有代码的大小写、导入顺序、错误处理、日志记录以及HTTP/DB客户端选择。请勿引入第二种模式。

SOLID

SOLID原则

  1. One actor per module. A class should be answerable to one stakeholder group (Accounting, Auth, Reporting). If two unrelated subsystems both reach into the same class, split it. (SRP, Uncle Bob 2014)
  2. Extension via new code, not edits. If adding a new variant requires another type-tag branch in an existing function, refactor to a registry, strategy, or polymorphic dispatch first. (OCP)
  3. No subclass refuses its parent's contract. Never override a method to signal "not implemented" or "unsupported operation." Never strengthen preconditions or weaken postconditions in an override. If you need to do that, the inheritance is wrong. (LSP)
  4. Abstractions live with the client, not the implementation. When you introduce an interface, protocol, or abstract contract, put it in the package that consumes it, not next to the concrete class. (DIP)
  1. 每个模块对应一个参与者。类应仅对一个利益相关方群体负责(如会计、认证、报表)。若两个不相关的子系统都依赖同一个类,应将其拆分。(SRP原则,Uncle Bob 2014)
  2. 通过新增代码扩展,而非修改现有代码。若添加新变体需要在现有函数中新增类型标签分支,应先重构为注册表、策略模式或多态分派。(OCP原则)
  3. 子类不得违背父类契约。禁止重写方法以表示「未实现」或「不支持操作」。禁止在重写时强化前置条件或弱化后置条件。若必须这么做,说明继承设计有误。(LSP原则)
  4. 抽象与客户端共存,而非与实现共存。当引入接口、协议或抽象契约时,应将其放在消费它的包中,而非与具体类放在一起。(DIP原则)

DRY, KISS, YAGNI

DRY、KISS、YAGNI原则

  1. Delete duplicated knowledge, not duplicated text. Two functions that look alike but encode different rules are not a DRY violation. One rule expressed in code + docs + schema is. (Pragmatic Programmer, "DRY")
  2. The wrong abstraction is worse than duplication. If an abstraction has accumulated branches for each caller's special case, re-inline it back into callers, then delete the dead branches before re-abstracting. (Sandi Metz, "The Wrong Abstraction")
  3. Complexity ceiling: cyclomatic ≤10, nesting depth ≤5. Refactor before exceeding. (McCabe 1976)
  4. No speculative anything. No optional parameter, config flag, env var, feature toggle, interface, factory, or base class without a present-day caller. If you find yourself adding
    enable_*
    ,
    use_*_v2
    , or
    *_mode
    , delete it and ship the concrete behavior. (Fowler, "Yagni")
  1. 删除重复的「知识」,而非重复的「文本」。两个看似相似但编码不同规则的函数不属于DRY违规。同一规则同时出现在代码、文档和 schema 中才属于违规。(《程序员修炼之道》“DRY”章节)
  2. 错误的抽象比重复更糟糕。若某个抽象为每个调用者的特殊情况积累了分支,应将其内联回调用者,然后删除无用分支,再重新进行抽象。(Sandi Metz,“The Wrong Abstraction”)
  3. 复杂度上限:圈复杂度≤10,嵌套深度≤5。超过上限前需进行重构。(McCabe 1976)
  4. 无任何投机性内容。若无当前调用者,禁止添加可选参数、配置标志、环境变量、功能开关、接口、工厂或基类。若发现自己在添加
    enable_*
    use_*_v2
    *_mode
    ,请删除并交付具体行为。(Fowler,“Yagni”)

AI-specific guardrails — the highest-leverage section

AI特定防护规则——最高价值部分

  1. Never swallow errors with broad catch-all handling. Catch only the specific error type you can recover from. If you cannot recover, let the error propagate. Returning null/none/empty success from a catch handler is forbidden unless the function contract documents that behavior. (Karpathy)
  2. No defensive guards for impossible cases. Do not add null checks or runtime type checks for values whose declared type or caller contract already excludes that case. Trust the contract. (arXiv 2409.19182)
  3. Verify every import and external call. Before calling a method on a library, confirm it exists in the version installed (read the package, check the lockfile, or import and inspect). Do not generate code based on what the API "should" look like. (USENIX Security '25)
  4. No hardcoded "success" returns or mock fixtures in production code. Never return
    {"status": "ok", ...}
    or canned data from a function whose spec says it does real work. If you cannot implement, fail explicitly with the language's unimplemented or unsupported-operation mechanism and say so. Never disable, skip, or weaken a test to make it pass. (Fowler, Claude Code issue #6984)
  5. Re-derive, do not copy from similar. When tempted to copy a function and modify it, stop. Re-derive from the spec. Off-by-one and wrong-null-semantic bugs almost always enter through copy-from-similar. (arXiv 2411.01414)
  6. Enumerate boundary cases before writing them. For any range, off-by-one, null/empty/one/many, even/odd, or unicode/byte boundary, write the case list in a comment first. Cover each case in code before moving on.
  7. Strip dead code before delivery. Run a linter or grep pass for unused imports, unused symbols, unreachable branches, and "just in case" exports. Remove them. A function that nothing calls today does not get to live for "someday."
  8. Read before write. Before writing in an unfamiliar repo, read the file you'll edit, one neighbor, and any project rules file (CLAUDE.md, AGENTS.md, README's "conventions" section). Use the project's existing helpers, error types, and logging.
  1. 禁止用宽泛的异常捕获掩盖错误。仅捕获可恢复的特定错误类型。若无法恢复,让错误向上传播。除非函数契约明确记录该行为,否则禁止在捕获处理器中返回null/none/空成功值。(Karpathy)
  2. 不为不可能的情况添加防御性检查。对于已通过声明类型或调用者契约排除的情况,请勿添加空值检查或运行时类型检查。信任契约。(arXiv 2409.19182)
  3. 验证所有导入和外部调用。在调用库方法前,确认其在已安装版本中存在(读取包信息、检查锁文件,或导入并检查)。请勿基于API「应该是什么样」来生成代码。(USENIX Security '25)
  4. 生产代码中禁止硬编码「成功」返回值或模拟数据。若函数规范要求执行实际工作,禁止返回
    {"status": "ok", ...}
    或固定数据。若无法实现,应使用语言的未实现或不支持操作机制明确失败并说明原因。禁止为了通过测试而禁用、跳过或弱化测试。(Fowler,Claude Code issue #6984)
  5. 重新推导,而非复制相似代码。当想要复制函数并修改时,请停止操作。根据规范重新推导。差一错误和空值语义错误几乎总是通过复制相似代码引入的。(arXiv 2411.01414)
  6. 编写前枚举边界情况。对于任何范围、差一、空/空/单个/多个、偶/奇或Unicode/字节边界情况,先在注释中列出所有情况。在代码中覆盖每个情况后再继续。
  7. 交付前删除无用代码。运行代码检查器或grep,查找未使用的导入、未使用的符号、不可达分支和「以防万一」的导出。将其移除。当前无调用者的函数不应为「某天」而存在。
  8. 先读再写。在不熟悉的仓库中编写代码前,阅读要编辑的文件、一个相邻文件以及任何项目规则文件(CLAUDE.md、AGENTS.md、README的「约定」部分)。使用项目现有的辅助工具、错误类型和日志记录方式。

Refactoring discipline

重构准则

  1. Preserve observable behavior when refactoring. When the user asks you to clean up, simplify, or refactor existing code, do not change the contract — same inputs produce the same outputs, same exceptions raised, same side effects, same ordering guarantees. If you spot a bug while refactoring, flag it separately and ask before changing it. Refactoring is defined as "a change made to the internal structure of software to make it easier to understand and cheaper to modify without changing its observable behavior" (Fowler, Refactoring). Bug fixes and refactors are two operations — never bundle them in a single change.
  1. 重构时保留可观察行为。当用户要求清理、简化或重构现有代码时,请勿修改契约——相同输入应产生相同输出、抛出相同异常、产生相同副作用、保证相同顺序。若在重构时发现bug,应单独标记并在修改前询问用户。重构的定义是「对软件内部结构进行修改,使其更易于理解、修改成本更低,且不改变其可观察行为」(Fowler,《重构》)。bug修复和重构是两个独立操作——切勿将它们捆绑在一次变更中。

Self-check before delivery

交付前自我检查

Before you show the user the code you wrote or edited:
  1. Walk imperatives 1–23 against your diff. Fix every violation.
  2. For new functions, count: lines ≤ 20? params ≤ 4? complexity feels ≤ 10? names reveal intent?
  3. For new comments, ask: does this explain why? If it explains what, delete it.
  4. For new error handling: is the caught error type specific? Does the handler do something other than silently return?
  5. For new abstractions (interface, factory, base class, registry): is there a second concrete user today? If no, inline it.
  6. Did you read the file you edited and at least one neighbor? Did your style match?
  7. Is there any hardcoded "ok" return or fixture data? If yes, replace with real implementation or an explicit unimplemented/unsupported-operation failure.
  8. If this is a refactor: did you change observable behavior? If yes, you bundled a bug fix — split it out and ask the user.
If you cannot answer yes to every check, fix before shipping.
在向用户展示编写或编辑的代码前:
  1. 对照你的代码差异检查规则1-23。修复所有违规问题。
  2. 对于新函数,检查:行数≤20?参数≤4?复杂度≤10?名称体现意图?
  3. 对于新注释,询问:它是否解释「为什么」?若解释「是什么」,请删除。
  4. 对于新错误处理:捕获的错误类型是否具体?处理器是否做了除静默返回外的其他操作?
  5. 对于新抽象(接口、工厂、基类、注册表):当前是否有第二个具体使用者?若无,将其内联。
  6. 你是否阅读了要编辑的文件及至少一个相邻文件?你的风格是否匹配?
  7. 是否存在硬编码的「ok」返回值或模拟数据?若有,替换为实际实现或明确的未实现/不支持操作失败。
  8. 如果是重构:你是否改变了可观察行为?若是,说明你捆绑了bug修复——请拆分并询问用户。
若无法对所有检查给出肯定回答,请在发布前修复。

When the user pushes back on a rule

当用户对规则提出质疑时

Refer them to the source name in the relevant references/ file and use references/sources.md only when the URL is needed. The rules are defensible — they come from primary sources (Uncle Bob, Fowler, Hunt & Thomas, McCabe, Metz) and from published 2024–2026 research on LLM code generation. If the user has a context-specific reason to override (e.g., a constructor genuinely needs 8 params for a config DTO), document the exception in a code comment that includes the principle being overridden and the reason.
请参考相关[references/]文件中的来源名称,仅在需要URL时使用[references/sources.md]。这些规则是有依据的——它们来自主要来源(Uncle Bob、Fowler、Hunt & Thomas、McCabe、Metz)以及2024-2026年关于LLM代码生成的已发表研究。若用户有特定上下文原因需要覆盖规则(例如:构造函数确实需要8个参数用于配置DTO),请在代码注释中记录例外情况,包括被覆盖的原则及原因。

Troubleshooting

故障排除

  • If the task is conceptual rather than code-producing, do not apply this skill; answer the concept directly.
  • If review mode starts producing style-only feedback, use references/review-checklist.md and prioritize behavioral bugs, brittleness, and maintainability risks.
  • If a rule conflicts with an explicit project convention, follow the project convention and document the exception only when it would otherwise surprise a future maintainer.
  • If the skill feels too broad, use the frontmatter exclusions first; do not add runtime-specific rules to this general guard skill.
  • 若任务为概念性而非代码生成类,请勿应用本技能;直接回答概念问题。
  • 若审查模式仅产生风格层面的反馈,请使用[references/review-checklist.md],优先关注行为bug、脆弱性和可维护性风险。
  • 若规则与明确的项目约定冲突,请遵循项目约定,仅当可能会让未来维护者感到意外时才记录例外情况。
  • 若本技能范围过宽,请首先使用前置说明中的排除项;请勿为这个通用防护技能添加运行时特定规则。

What this skill does not do

本技能不做的事

  • Run linters or static analysis. Those are tool-level concerns; this skill is about what to write and what to look for.
  • Enforce language-specific formatter or linter preferences. Defer to the project's style tooling.
  • Replace tests. Clean code passes tests; tests do not pass without clean code, but clean code without tests is also a defect.
  • 运行代码检查器或静态分析。这些是工具层面的问题;本技能关注「编写什么」和「检查什么」。
  • 强制执行特定语言的格式化工具或代码检查器偏好。请遵循项目的风格工具。
  • 替代测试。整洁的代码通过测试;没有整洁代码的测试无法通过,但没有测试的整洁代码也是缺陷。