详解.cursor/rules/.mdc文件的YAML frontmatter+条件匹配机制,通过项目级规则约束AI行为,提升代码质量。
你刚装好 Cursor,打开一个 TypeScript 文件,让 AI 修一个 bug。十秒后它给你抛出一个 type SomeType = any,还在那行报错的代码上面加了个 @ts-ignore。就在这一刻,大多数开发者意识到 AI 编程助手虽然强大,但缺乏纪律。
解法不是换一个更好的模型。是规则。
大多数 AI 编程助手的最佳实践可以归结为一个核心思想:在它开始敲代码之前,就告诉它什么叫"好"。Cursor 允许你在 .cursor/rules/ 目录下定义规则文件,这些文件会随项目上下文一起加载,告诉 AI 应该如何表现。Claude Code 有自己的规则系统,Windsurf 有规则目录,Copilot 读取 .github/copilot-instructions.md。学会正确配置 Cursor Rules,你的 AI 助手就会像一个细心的资深工程师,而不是一个冒失的实习生。
Cursor Rules 是以 .mdc 为扩展名的 Markdown 文件,存放在项目根目录的 .cursor/rules/ 中。每一个文件都是一组指令,AI 在开始工作前会读取它们。当某个规则的匹配条件与正在编辑的文件相符时,对应的指令就会被注入到模型的上下文窗口中。
一个 Cursor Rules 文件由两部分组成:两行 --- 之间用 YAML 编写的 frontmatter 块,以及包含实际指令的 Markdown 正文。
description(必填)。对规则约束内容的简短摘要。Cursor 在切换规则时会展示这个字段,所以要写得具体。
globs(可选)。规则适用的文件模式。不填 globs 的话,规则会对所有文件生效,这会浪费上下文额度并引发冲突。
alwaysApply(可选)。对于无论涉及哪些文件都应该加载的规则,设为 true。只在触达匹配文件时才触发的规则,保留 false。
---
description: Enforce strict TypeScript, no any, no ts-ignore
globs: **/*.{ts,tsx}
alwaysApply: false
---
# Strict TypeScript
## Context
This codebase runs with `strict: true`. Using `any` disables the type system
for that value and lets bugs through at runtime. Banned types are a team
decision, not a style preference.
## Requirements
- Give function parameters and return values explicit types.
- Use `unknown` instead of `any` when a value's shape is not known yet, then
narrow it with a type guard before using it.
- Model state with discriminated unions rather than long optional chaining
chains.
## Anti-Patterns
- ❌ `any` type annotations. Use `unknown` and narrow.
- ❌ `@ts-ignore` or `@ts-expect-error` to silence the compiler. Fix the type.
- ❌ `as any` casts to force a value through.
注意正文的结构:Context、Requirements、Anti-Patterns。这个模式就是让规则真正生效的核心,后面会再展开讲。
几个相关的标准做着类似的工作,但命名让所有人都困惑。
AGENTS.md 是一个跨工具标准:位于仓库根目录的一个 Markdown 文件,用来记录 AI 助手在这个仓库中应该如何工作。可以把它想象成一份为 AI 代理写的 README。它涵盖构建命令、项目约定、以及"不要碰 X"。因为是根目录的普通文件,任何遵循规范的工具都会读取它。
CLAUDE.md 是 Claude Code 的项目记忆文件。Claude Code 规则系统在启动时会读取它,以及它所引用的文件,并将其作为会话的长期上下文。老项目使用 CLAUDE/ 文件夹加子文件;现在推荐的做法是使用单一的根文件。
.cursor/rules 文件与这两者的一个关键区别在于:它们是有作用域的、条件触发的。AGENTS.md 和 CLAUDE.md 会完整地作为上下文被读取。Cursor Rules 只在文件的 globs 和设置与当前任务匹配时才会加载。这使得它们成为处理文件类型特定纪律约束的正确工具,而 AGENTS.md 则是处理仓库级 onboarding 信息的正确工具。
一个务实的配置方式是:把仓库事实(命令、架构、约定)放在 AGENTS.md 中,然后在上面叠加有作用域的规则,比如"TypeScript 文件里不许出现 any"或者"每个新 API 端点都需要输入校验"。这些工具在不同的文件名下正趋于收敛到同一个理念。
大多数规则文件失败的原因无非以下四个。
1. 规则太模糊。 "写干净的代码"不是规则,是愿望。AI 没有对"干净"的 operational definition,所以它会忽略这条指令。好的规则要命名具体的行为:"不许 any"、"每个函数都要有显式的返回类型"。
2. 缺少 Anti-Patterns。 告诉 AI 要做什么只是其中一半。模型在负样本上有很强的 pattern-match 能力。一个规则说"校验所有输入"但从不展示什么是无效的尝试,这样产生的校验就只是装饰性的。列出你绝不想看到的具体场景,并配上例子,AI 就不会再产出它们。
3. 没有 globs。 一条关于 API 端点的规则如果适用于所有文件,就会被不断加载,开始与其他规则冲突。把规则作用域限定在它所管理的文件上。一条测试规则应该放在 **/*.test.{ts,tsx} 上,而不是 **/*。
4. 没有人检查 AI 是否遵守了规则。 Cursor 允许你在聊天编辑器中切换规则,@-mention 某个规则或文件会强制将它拉入对话的上下文。如果一条规则对某个任务很重要,要显式地在聊天中提及它,而不是假设模型已经读完了全部十七条规则。然后验证:检查 diff 中是否有 any 和 @ts-ignore,如果 AI 没有遵守就退回去让它改。
还有一个上下文预算问题。每加载一条规则都要消耗 token。二十条模糊的规则会把真实的项目上下文挤出去,让 AI 表现得更差,而不是更好。宁可要几条精准的规则,也不要一堆理想化的规则。
这些可以直接放进 Cursor 的 .cursor/rules。这个结构可以迁移到任何读取 Markdown 规则的工具上。根据自己的技术栈调整 globs 即可。
---
description: No any, no ts-ignore in TypeScript files
globs: **/*.{ts,tsx}
alwaysApply: true
---
# Strict TypeScript
## Context
The project compiles with `strict: true`. Any, ts-ignore and unsafe casts are
banned because they disable compile-time checks and move failures to runtime.
## Requirements
- Write explicit types for parameters, return values, and exported variables.
- Reach for `unknown` when a value arrives from an untyped boundary, then
narrow it with a type guard.
- Handle `null` and `undefined` explicitly. Prefer early returns over `!`.
## Anti-Patterns
- ❌ `any`, `as any`, or `as unknown as SomeType`.
- ❌ `@ts-ignore` and `@ts-expect-error`.
- ❌ Non-null assertion `!` on values that can actually be null.
---
description: Test files must assert behavior, not cover lines
globs: "**/*.{test,spec}.{ts,tsx,js,jsx}"
alwaysApply: false
---
# Behavioral tests
## Context
Coverage percentages measure nothing if the assertions don't. A passing test
suite that never fails is a treadmill. Each test should demonstrate one
behavior.
## Requirements
- One behavior per test. Name it like `should reject expired tokens`.
- Assert on observable outcomes, not on how the code is wired internally.
- Follow arrange, act, assert, and keep the act section to one call.
## Anti-Patterns
- ❌ Tests with no assertions, or `expect(true).toBe(true)`.
- ❌ Mocking the system under test so heavily that the test proves nothing.
- ❌ Snapshot-only tests that would pass with obviously wrong output.
---
description: Validate input and avoid common security traps
globs: "**/*.{ts,tsx,js,jsx,py,go}"
alwaysApply: false
---
# Security guardrails
## Context
Every input is untrusted until proven otherwise. The cheapest vulnerability is
the one you never ship, so apply these checks to new code automatically.
## Requirements
- Validate and sanitize all input at the service boundary, before use.
- Use parameterized queries or an ORM for any database access. Never build SQL
by string concatenation.
- Escape output in HTML templates. Prefer the framework's built-in escaping.
- Redact secrets and tokens in logs. Never log request bodies wholesale.
## Anti-Patterns
- ❌ SQL assembled with template strings containing user input.
- ❌ Storing secrets in source code or config files that get committed.
- ❌ Trusting client-supplied values for authorization decisions.
以上示例是基础。一旦你理解了这个模式,就会想要为自己的技术栈配备更多规则:前端约定、后端 API 设计、数据库迁移、代码评审工作流,以及那些已经预置好规则的项目模板。
这就是 AgentForge 做的事情:它是一套 24 个有主见的、机器可读的规则文件,涵盖七个类别(通用、前端、后端、测试、AI 代理、DevOps、数据库)。每个文件都使用上述的 frontmatter 格式和 Context / Requirements / Anti-Patterns 结构,配有准确的 globs 和 alwaysApply 设置,确保规则只在相关时才加载。它带有一键安装脚本和项目模板,一次性购买 US$29(A$45),地址是 https://dedyclan.gumroad.com/l/agentforge。
不确定这个结构是否适合自己的工作流程?同一个页面提供了包含三个规则文件的免费样例包。把它们放进 .cursor/rules/,在下一个任务中感受差异。
Cursor Rules 文件是什么?
Cursor Rules 文件是放在 .cursor/rules/ 目录下的 .mdc 扩展名的 Markdown 文档。它包含 YAML frontmatter(description、globs、alwaysApply)和一组指令的 Markdown 正文。当正在操作的文件匹配规则的 globs,或者规则设置了 alwaysApply: true 时,Cursor 就会把正文注入到 AI 的上下文中。
怎么让 Cursor 遵守我的规则?
有三件事有帮助。第一,让规则具体化并配上明确的 Anti-Patterns,因为模糊的指令很容易被忽略。第二,在聊天编辑器中 @-mention 规则或文件,强制将其拉入对话上下文。第三,验证:检查 AI 的 diff 中是否有被禁止的模式(如 any 或 @ts-ignore),如果不符就退回去让它改到合规为止。
AGENTS.md 和 .cursor/rules 的区别是什么?
AGENTS.md 是位于仓库根目录的普通 Markdown 文件,任何遵循标准的 AI 代理工具都会将其作为上下文读取。它最适合仓库级的事实:构建命令、架构、约定。.cursor/rules 文件是有条件的、由 globs 限定的,这使得它们更适合细粒度的纪律约束,比如"TypeScript 文件中不许 any"。两者互为补充。