Codex 写代码不听话?也许你该试试 Agents.md
AGENTS.md:给 Codex 看的项目说明书
很多人在真实项目里会发现一个现象:Codex 写代码是没问题,但它并不知道这个项目的具体规矩。用什么命令启动、跑什么测试、哪些目录是禁区、哪些操作必须先问一句……这些信息如果每次都靠手动敲进提示词里,不仅麻烦,还容易遗漏。
所以就有了 AGENTS.md。说白了,就是把这些规则固定下来,让 Codex 每次进项目时自动加载。它解决的核心问题是:
让 Agent 更懂你这个项目
坦白讲,很多人用了很久的 Codex,但一直没认真去看过 AGENTS.md 到底是个什么结构。今天就来把它彻底拆一遍。
简单来说,AGENTS.md 就是给 Agent 看的 README。
区别在哪?README.md 是给人看的——告诉你这个仓库是干什么的。而 AGENTS.md 是给 Codex 看的——让它在动代码之前,知道这个仓库有哪些工程约定。比如:
- 这个项目用什么命令启动
- 修改代码后要跑什么测试
- 哪些目录不能动
- 用什么包管理器
- 新增依赖要不要先确认
- 数据库、API、前端各自有什么约定
文件名建议写成 AGENTS.md,大小写要保持一致。写错成 Agent.md、Agents.md 或者 agents.md,某些场景下会导致加载不到。
全局 AGENTS.md
全局文件默认放在 ~/.codex/AGENTS.md。如果没有这个目录,手动创建一下就好:mkdir -p ~/.codex。
全局规则适合放你长期稳定的个人偏好,跟具体项目无关的那种。比如:
# ~/.codex/AGENTS.md
## Working agreements
- 默认用中文回复。
- 修改代码前先阅读相关文件。
- 优先使用项目现有风格。
- 不要擅自覆盖用户已有改动。
- 新增生产依赖前先确认。
- 如果无法运行验证命令,说明原因。
这些规则不依赖任何特定仓库,换到哪个项目都能成立。写完之后,可以用一条命令验证是否生效:
codex --ask-for-approval never "Summarize the current instructions."
如果输出里出现了你写进去的规则,就说明全局 AGENTS.md 被正确加载了。输出里如果还有一些英文规则,那也是正常的——因为这条命令总结的是“当前所有生效指令”,不只包含你的 AGENTS.md,还包括 Codex 自带的系统规则、当前工作目录、审批策略、沙箱权限等信息。
全局和项目级怎么分
AGENTS.md 可以放在不同层级,最常见的有三种:
~/.codex/AGENTS.md # 全局规则
repo/AGENTS.md # 项目规则
repo/apps/web/AGENTS.md # 子模块规则
它们不是互斥关系——不是说有了全局文件,项目文件就不生效了。实际上它们会一起加载。可以这么理解:
- :我希望 Codex 始终按照这些方式工作
全局规则
- :这个仓库具体怎么运作
项目规则
- :这个模块有什么特殊要求
子目录规则
判断标准也很简单:换一个项目仍然适用的,放全局;只在这个仓库成立的,放项目;只对某个子目录有意义的,放子目录。
举个例子。“新增生产依赖前先确认”这条规则,适合放全局,因为它不依赖项目类型。而“修改 Prisma schema 后运行 pnpm db:generate”这条,就适合放项目里。不是每个项目都用 Prisma,更不是每个项目都有 db:generate 这个脚本。
补充一句:Prisma 是 Node.js/TypeScript 生态里常见的数据库工具。它把数据库表结构、类型和查询代码连接起来,让你在代码里用类型安全的方式操作数据库。当你修改了 prisma/schema.prisma 文件(即数据库的表结构定义)后,项目通常需要重新生成数据库客户端代码。所以这条规则背后的意思是:不要只改了文件就结束,还要执行生成命令。
项目级 AGENTS.md
项目级文件一般放在仓库根目录,内容应该聚焦于这个项目的具体工程约定,比如安装命令、启动命令、测试命令、类型检查命令、lint 命令、目录结构、生成文件的边界、数据库变更要求、API 文档同步要求等。如果是生产项目,可以直接使用文末提供的模板,再按实际情况删改。
验证项目级 AGENTS.md
我按常理创建了一个测试项目,目录结构大致是这样:
agents-md-test/
AGENTS.md
apps/ web/
packages/ ui/ db/
services/ payments/
docs/ api/
src/ generated/
在项目根目录执行以下命令,可以验证文件是否被加载:
codex --ask-for-approval never "List the instruction sources you loaded and summarize the Project commands, Project structure, and Rules sections."
也可以测试某个子目录:
codex --cd services/payments --ask-for-approval never "List the instruction sources you loaded."
这里有个小窍门:验证 AGENTS.md 是否生效,不要只看它有没有说“加载了 AGENTS.md”。更好的方法是让它把文件里的独有规则总结出来。比如输出里出现了 pnpm dev、src/generated、pnpm db:generate、docs/api 这些项目特有的内容,才说明项目级规则确实被应用了。
子目录 AGENTS.md
除了项目根目录,子模块也能用 AGENTS.md 来做更细粒度的约束。比如在 monorepo 中,根目录放通用规则,services/payments/ 放支付服务的专属规则,services/search/ 放搜索服务的专属规则。
举个例子,支付服务的 AGENTS.md 可能会这样写:
# services/payments/AGENTS.md
## Payments Rules
- Do not change billing beha vior without updating payment tests.
- Do not log card numbers, tokens, or customer secrets.
- Run `pnpm test payments` after changing payment logic.
这种分层方式在 monorepo 里特别实用——一个仓库里可能同时有前端、后端、支付、搜索等多种模块,每个模块的风险点完全不同,统一的规则无法覆盖所有场景。
AGENTS.override.md 是什么
除了 AGENTS.md,还有一个特殊文件叫 AGENTS.override.md。它的优先级比同目录下的 AGENTS.md 更高,适合用在需要强覆盖的场景。
比如在 services/payments/ 目录下同时存在 AGENTS.md 和 AGENTS.override.md 时,Codex 会优先加载 AGENTS.override.md,而忽略同目录下的 AGENTS.md。
哪些场景会用上?比如某个子服务有特殊安全规则、某个目录禁止修改生成文件、某个模块必须使用特殊测试命令、或者想临时替换原来的行为。普通情况下,用 AGENTS.md 就够了。只有明确需要覆盖同目录文件时,才用 AGENTS.override.md。
自定义 fallback 文件名
有些团队可能已经建立了自己的项目说明文件,比如 TEAM_GUIDE.md 或 .agents.md。如果不想把文件名改成 AGENTS.md,可以通过 Codex 配置来设置 fallback 文件名。
编辑 ~/.codex/config.toml,加入以下内容:
project_doc_fallback_filenames = ["TEAM_GUIDE.md", ".agents.md"]
project_doc_max_bytes = 65536
配置生效后,Codex 在每个目录里会按这个顺序查找:AGENTS.override.md → AGENTS.md → TEAM_GUIDE.md → .agents.md。不在列表里的文件名会被忽略。比如 README.md 不会因为它存在,就自动变成 Codex 的指令文件。
project_doc_max_bytes 控制的是所有项目说明文件合并后的最大字节数。如果规则比较多,可以适当调大这个值。
使用 CODEX_HOME 切换配置目录
默认情况下,Codex 使用 ~/.codex 作为主目录,全局 AGENTS.md 自然也是 ~/.codex/AGENTS.md。但如果你想临时使用另一套配置,可以通过设置环境变量 CODEX_HOME 来实现:
CODEX_HOME=$(pwd)/.codex codex exec "List active instruction sources"
这条命令的意思是:本次执行不要使用默认的 ~/.codex,而是使用当前项目下的 $(pwd)/.codex。适合给项目自动化任务准备单独配置、区分个人配置和 CI 配置、或者临时测试不同的 AGENTS.md。如果发现规则加载不对,可以先检查一下 echo $CODEX_HOME——如果输出不是空的,说明 Codex 当前使用的不是默认目录。
可以直接抄的生产级 AGENTS.md
最后放一份更适合生产项目的 AGENTS.md 模板。这份模板偏工程纪律型,适合多人协作项目、monorepo、涉及数据库、API、CI 的项目。可以直接复制到项目根目录,再按实际情况删改。
# AGENTS.md
Working agreement for AI coding agents in this repository.
On conflict, follow: explicit user instructions > this file > existing code conventions > your defaults.
When the choice is risky or materially affects architecture, data, security, or public beha vior, stop and ask rather than guess.
## Orientation
Do this first, every session.
Before writing any code, build a working model of the repo from what is actually there:
- Read `README`, `CONTRIBUTING`, and any root-level `*.md` files for setup and norms.
- Detect the package manager from the lockfile:
- `pnpm-lock.yaml` -> `pnpm`
- `yarn.lock` -> `yarn`
- `package-lock.json` -> `npm`
- `uv.lock` or `poetry.lock` -> the matching Python tool
- Use the detected package manager. Never introduce a second package manager.
- Find the real commands in `package.json` scripts, `Makefile`, `Taskfile`, `justfile`, or CI config.
- Treat CI config (`.github/workflows`, `.gitlab-ci.yml`, etc.) as the source of truth for what passing means.
- Read the files you are about to change and their tests before editing.
- Do not assume a stack. Verify it from the repo.
## Core Principles
- Make the smallest change that solves the task.
- Do not do drive-by refactors, renames, or reformatting of untouched code.
- Keep unrelated changes out of the diff.
- Match the surrounding code: naming, structure, error handling, and test style.
- Consistency beats personal preference.
- Reuse existing helpers, components, and patterns before adding new ones.
- Do not add speculative abstractions, config, or error handling for cases that do not exist yet.
- Comments should explain non-obvious decisions. Do not comment what the code already says.
## Verification
Required before calling a task done:
- Use the project's defined commands. Prefer focused checks first, then broader checks.
- Run the narrow tests for the file, package, or feature you touched.
- Then run the broader gate that the project defines: lint, typecheck or compile, and tests.
- Mirror CI locally when practical.
- Do not invent unrelated verification commands just to ha ve something to run.
- Fix failures caused by your change.
- Add or update tests for beha vior changes.
- If you cannot run a command because of missing services, credentials, network, or time, say so explicitly.
- Never imply tests passed if you did not run them.
## Dependencies
- Do not add a production dependency without asking first.
- When requesting a dependency, explain why the existing tools are not enough.
- Dev-only tooling is lower risk, but still match what the repo already uses.
- Never edit generated files, vendored code, or lockfiles by hand.
- Regenerate generated files and lockfiles through the project's documented command.
## Git And PR
- Commit only when asked.
- If asked to commit and currently on the default branch, create a feature branch or ask before committing.
- Add files by name. Do not use `git add .` or `git add -A`.
- Use conventional commit subjects when committing, such as `feat:`, `fix:`, or `chore:`.
- Keep one logical change per commit.
- Never run `push --force`, `reset --hard`, `branch -D`, `clean -f`, or `--no-verify`.
- Do not amend, squash, or rebase already-pushed commits unless asked.
- Do not revert or overwrite changes you did not make.
## Security
- Never commit secrets, tokens, keys, or credentials.
- Treat `.env*` files as sensitive.
- Do not print secret values or write them to logs.
- Validate external input at trust boundaries.
- When changing access to user-visible data, check the authorization path.
- Do not log PII or customer data.
## Data And Migrations
- Treat schema changes and migrations as high risk.
- Do not create or modify production migrations unless the task explicitly asks for it.
- Flag destructive changes in your summary, including dropped columns, deleted rows, and irreversible backfills.
- Wait for confirmation before applying destructive data changes.
## When To Stop And Ask
Pause and ask before:
- Adding a production dependency or new framework.
- Adding a broad new abstraction.
- Touching production data, schema, or migrations.
- Making a breaking change to a public API or shared interface.
- Editing shared config, CI, or the build pipeline.
- Continuing when the task contradicts the code.
- Choosing between several valid approaches when there is no clear winner.
## Reporting Back
End each task with:
- What changed, by file.
- How it was verified, including commands run and results.
- What was not run, and why.
- Risks or follow-ups.
这份模板不绑定具体技术栈,所以比前面那种写死 pnpm、Prisma、docs/api 的模板更通用。它的核心思路是:让 Codex 先读项目、再判断命令、然后做最小修改,最后把验证结果和潜在风险说清楚。
如果你的项目已经有明确的技术栈,也可以在此基础上继续追加项目特有的规则,比如:
- After changing Prisma schema, run `pnpm db:generate`.
- API changes must update files under `docs/api`.
- Frontend changes must pass `pnpm test apps/web`.
也就是说,这份模板适合作为项目级 AGENTS.md 的底座,再叠加你项目自己的命令和边界,形成既通用又具体的约束体系。
总结
AGENTS.md 本质上就是给 Codex 看的项目说明书。全局文件放长期偏好,项目文件放工程规则,子目录文件放模块规则,AGENTS.override.md 用来覆盖同目录的普通规则。如果团队已有自己的说明文件,也可以通过配置 fallback 文件名来整合。
最关键的一点是:AGENTS.md 不要写空话。“请保持代码优雅”“请遵循最佳实践”这类表述,对 Codex 几乎没有约束力。真正有用的工程化约束,是那些能影响 Codex 具体行为、并且能被命令验证的规则。这才是这篇文章想传达的核心思路——让 Agent 真正“懂”你的项目,而不是在每一个任务里从头摸索。