AGENTS.md:让 Codex 真正理解你的项目
AGENTS.md 是 Codex 定制化体系的第一层基石。它以 Markdown 文件的形式,将项目级的持久指导嵌入版本控制,让 Codex 在每次会话开始前就理解你的仓库约定。本文基于官方 Customization 和 Prompting 文档,系统讲解 AGENTS.md 的编写策略、层级覆盖机制与工程协同实践。
一、AGENTS.md 的本质
1.1 定位:持久化的项目指导
Codex 的定制化体系由四层组成,各司其职:
| 层级 | 职责 |
|---|---|
| AGENTS.md | 塑造行为 — 告诉 Codex 在这个仓库里「每次都该遵守的规则」 |
| Skills | 打包流程 — 将可复用的工作流封装为独立技能 |
| MCP | 连接外部 — 让 Codex 访问本地工作区之外的系统(Linear、GitHub、Figma 等) |
| Subagents | 委派任务 — 将嘈杂或专业化的任务交给子代理 |
官方原话:「AGENTS.md gives Codex durable project guidance that travels with your repository and applies before the agent starts work. Keep it small.」
AGENTS.md 的核心价值在于 持久性 和 版本控制:
- 持久性:不像对话中的临时指令会随上下文窗口消失,AGENTS.md 的内容在每次会话开始时自动加载
- 版本控制:作为仓库中的普通文件,它随
git commit一起演进,团队成员共享同一套规则
1.2 与 Prompting 的关系
每次你向 Codex 发送提示词(Prompt),Codex 进入一个循环:调用模型 → 执行动作(读文件、编辑代码、调用工具)→ 直到任务完成。AGENTS.md 在这个循环 启动之前 就已经注入上下文,相当于为每次对话预设了一组「系统级指令」。
官方建议:Codex 在处理复杂任务时,效果与你提供的指令质量直接相关。将反复出现的约定写入 AGENTS.md,比每次在 Prompt 中重复更高效。
二、层级体系与覆盖机制
Codex 从多个位置加载 AGENTS.md,距离工作目录越近的文件优先级越高。
2.1 三级层级
| 层级 | 路径 | 用途 |
|---|---|---|
| 全局 | ~/.codex/AGENTS.md | 个人偏好:Review 风格、输出详细度、默认行为 |
| 仓库根 | $REPO_ROOT/AGENTS.md | 团队规则:构建命令、代码规范、测试策略 |
| 子目录 | $REPO_ROOT/services/auth/AGENTS.md | 模块级指导:该目录特有的约定和路由信息 |
2.2 覆盖规则
就近优先(Closest wins)
子目录 AGENTS.md → 覆盖 → 仓库根 AGENTS.md → 覆盖 → 全局 AGENTS.md这意味着:
- 全局文件 用来塑造 Codex 与你个人的沟通方式(输出语言、Review 详细度、个人习惯)
- 仓库文件 聚焦团队和代码库规则(所有开发者共享)
- 子目录文件 处理局部差异(例如前端模块和后端模块有不同的代码规范)
2.3 与 Skills 的层级对比
| 层级 | AGENTS.md | Skills |
|---|---|---|
| 全局 | ~/.codex/AGENTS.md | $HOME/.agents/skills |
| 仓库 | 仓库根或嵌套目录中的 AGENTS.md | .agents/skills 目录 |
三、应该写什么
官方明确推荐 AGENTS.md 适合承载的内容类型:
3.1 构建与测试命令
让 Codex 知道如何验证自己的输出。
## Build & Test
- Build: `./mvnw clean compile -pl refinex-system -am`
- Unit test: `./mvnw test -pl refinex-system`
- Integration test: `./mvnw verify -pl refinex-system -P integration`
- Full build: `./mvnw clean package -DskipTests`
- Lint: `./mvnw spotless:check`
- Format: `./mvnw spotless:apply`官方建议:「Codex produces higher-quality outputs when it can verify its work. Include steps to reproduce an issue, validate a feature, and run linting and pre-commit checks.」
3.2 代码规范
## Code Conventions
- Java 21, use records for DTOs, sealed interfaces for ADTs
- All public API methods must have Javadoc
- Use `@Slf4j` (Lombok), never `System.out.println`
- Exception handling: throw `BusinessException(ErrorCode)`, never raw exceptions
- REST controllers return `R<T>` wrapper; never return raw entities3.3 Review 期望
## Review Expectations
- Every PR must include unit tests for new logic
- Database schema changes require migration scripts in `db/migration/`
- API changes must update OpenAPI spec in `docs/api/`
- No `@SuppressWarnings` without a comment explaining why3.4 目录路由
当仓库结构复杂时,目录路由帮助 Codex 减少不必要的文件扫描。
## Directory Routing
- Gateway config & filters: `refinex-gateway/`
- Auth (Sa-Token + JWT): `refinex-auth/`
- System CRUD services: `refinex-system/`
- AI dialogue & RAG: `refinex-ai/`
- Media generation: `refinex-media/`
- Knowledge base & vector store: `refinex-knowledge/`
- Shared modules (core, redis, mybatis, log, security): `refinex-common/`
- Database migrations: `db/migration/`
- Deploy manifests: `deploy/`官方触发更新时机之一:「Too much reading — If it finds the right files but reads too many documents, add routing guidance (which directories/files to prioritize).」
四、不应该写什么
AGENTS.md 的核心原则是 Keep it small。以下内容应避免写入:
4.1 Linter / Formatter 已覆盖的规则
如果 spotless-maven-plugin 已经配置了代码格式化规则(缩进、import 排序、尾随空格),不要在 AGENTS.md 中重复这些规则。Codex 会运行你配置的检查工具,自动发现并修复格式问题。
在 AGENTS.md 中写「缩进使用 4 个空格,import 按字母排序」— 这些应由 .editorconfig 和 Spotless 处理。
4.2 过长的文档
AGENTS.md 的内容受 project_doc_max_bytes 限制(默认 32KB)。超出部分会被截断。更重要的是,过长的指导会稀释关键信息的权重。
4.3 频繁变化的信息
环境变量值、API 密钥、临时 workaround — 这些不属于 AGENTS.md。用 config.toml 的 [shell_environment_policy] 管理环境变量,用 Issue Tracker 跟踪临时方案。
4.4 通用知识
Codex 已经了解 Spring Boot、Maven、Git 等主流工具的用法。不要教它「什么是 Spring Bean」,而是告诉它「我们的项目用了哪些特殊约定」。
五、反馈循环:让 Codex 自动更新 AGENTS.md
官方将 AGENTS.md 定位为一个 活文档(Living Document),通过反馈循环持续演进。
5.1 何时触发更新
官方给出了五个明确的触发时机:
| 触发条件 | 处理方式 |
|---|---|
| 重复犯错 | 同一个错误出现两次以上 → 添加规则 |
| 过度阅读 | Codex 找对了文件但读了太多无关文档 → 添加目录路由 |
| 重复 PR 反馈 | 同样的 Review 意见出现两次以上 → 编码为规则 |
| GitHub PR 评论 | 在 PR 中 @codex add this to AGENTS.md → 委派云端任务自动更新 |
| 自动化漂移检查 | 设置定期 Automation,扫描指导空白并建议补充内容 |
5.2 实操方法
最直接的方式是在对话中纠正 Codex 后,追加一句:
Update AGENTS.md so this fix persists in future sessions.官方原话:「When the agent makes incorrect assumptions about your codebase, correct them in AGENTS.md and ask the agent to update AGENTS.md so the fix persists.」
Codex 会自动将修正写入 AGENTS.md,并在后续会话中继承这一修正。
5.3 GitHub 集成
在 PR 评论中使用 @codex 指令,可以将更新 AGENTS.md 的任务委派为云端任务:
@codex We always use constructor injection in this project. Add this to AGENTS.md.Codex 会创建一个云端线程,修改 AGENTS.md 并提交到当前分支。
六、与工程工具链的协同
官方明确建议:将 AGENTS.md 与基础设施工具配对使用,让规则既有「文档层面的指导」,又有「工具层面的强制执行」。
官方原话:「Pair AGENTS.md with infrastructure that enforces those rules: pre-commit hooks, linters, and type checkers catch issues before you see them, so the system gets smarter about preventing recurring mistakes.」
6.1 协同架构
┌─────────────────────────────────────────────────┐
│ AGENTS.md │
│ (意图层:告诉 Codex 该怎么做) │
└──────────────────────┬──────────────────────────┘
│
┌────────────┼────────────┐
▼ ▼ ▼
Pre-commit Linters Type Checkers
Hooks
(执行层:自动阻止违规提交)6.2 Pre-commit Hooks
AGENTS.md 中声明规则,pre-commit hooks 负责自动验证。Codex 在运行构建或测试时会触发这些 hooks,形成闭环。
## Pre-commit
项目使用 pre-commit hooks 自动执行以下检查:
- `spotless:check` — 代码格式
- `checkstyle` — 编码规范
- `mvn test` — 单元测试
Codex 在提交代码前应运行 `./mvnw spotless:apply` 确保格式正确。6.3 Linters
Linters 处理 可机器化检查 的规则(命名规范、import 排序、死代码检测)。AGENTS.md 处理 需要理解上下文 的规则(架构约定、设计模式选择、业务逻辑约束)。
| 适合 Linter / Formatter | 适合 AGENTS.md |
|---|---|
| 缩进风格、空格 vs Tab | DTO 必须使用 Java Record |
| Import 排序 | 异常必须抛出 BusinessException(ErrorCode) |
| 未使用的变量检测 | 每个 Service 必须有对应的接口 |
| 命名规范(camelCase) | 数据库操作统一使用 MyBatis-Plus,不写原生 SQL |
6.4 Type Checkers
类型检查器(Java 的编译器类型系统、TypeScript 的 tsc)能在编译阶段捕获类型错误。Codex 在 AGENTS.md 中被告知「运行 ./mvnw compile 验证类型正确性」后,会自动在编辑代码后执行编译检查。
七、实战:为 Spring Boot 微服务项目编写 AGENTS.md
以下是一个面向 Spring Boot + Spring Cloud Alibaba 微服务项目的完整 AGENTS.md 示例,综合运用前述所有原则。
7.1 仓库根 AGENTS.md
# Refinex-Cloud AGENTS.md
## Project Overview
Spring Boot 3.5 + Spring Cloud Alibaba 2025 microservice backend.
Java 21, Maven multi-module, Sa-Token (JWT mixin) for auth.
## Build & Test
- Full build: `./mvnw clean package -DskipTests`
- Single module: `./mvnw clean compile -pl refinex-system -am`
- Unit tests: `./mvnw test -pl <module>`
- Integration tests: `./mvnw verify -pl <module> -P integration`
- Lint check: `./mvnw spotless:check`
- Lint fix: `./mvnw spotless:apply`
- Always run `spotless:apply` before committing.
## Code Conventions
- Java 21: use records for DTOs, sealed interfaces for ADTs,
pattern matching for instanceof
- Logging: `@Slf4j` only, never `System.out.println`
- Exceptions: throw `BusinessException(ErrorCode)`, never raw exceptions
- REST controllers: return `R<T>`, never raw entities
- Dependency injection: constructor injection only, no `@Autowired` on fields
- Database: MyBatis-Plus for all CRUD, no raw SQL unless justified in comment
- Config: `@ConfigurationProperties` bind, no `@Value` for groups of related properties
## Review Expectations
- Every new feature includes unit tests
- DB schema changes require Flyway migration in `db/migration/`
- API changes must update OpenAPI spec in `docs/api/`
- No `@SuppressWarnings` without explanatory comment
- No `TODO` without linked issue number
## Directory Routing
- API Gateway (filters, rate limiting): `refinex-gateway/`
- Authentication (Sa-Token, JWT, OAuth2): `refinex-auth/`
- System management (RBAC, user, role, menu): `refinex-system/`
- AI dialogue, RAG, Agent orchestration: `refinex-ai/`
- Media generation (image, video, audio): `refinex-media/`
- Knowledge base, vector store: `refinex-knowledge/`
- Monitoring & alerting: `refinex-monitor/`
- Shared modules: `refinex-common/` (sub-modules: core, redis, mybatis, log, security, web)
- Database migrations: `db/migration/`
- Deploy manifests (Docker, K8s): `deploy/`
## Infrastructure Stack
- Registry & Config: Nacos 2.x
- Flow control: Sentinel
- Distributed TX: Seata (AT mode)
- Message queue: RocketMQ 5.x
- Cache: Redis 7 (Lettuce client)
- Vector DB: Milvus / PGVector
- Object storage: MinIO
- Observability: Prometheus + Grafana + Jaeger + ELK
## Git Workflow
- Branch naming: `feat/<issue-id>-<short-desc>`, `fix/<issue-id>-<short-desc>`
- Commit style: Conventional Commits (`feat:`, `fix:`, `docs:`, `refactor:`, `test:`, `chore:`)
- One logical change per commit7.2 子目录 AGENTS.md 示例
refinex-ai/AGENTS.md:
# refinex-ai AGENTS.md
## Module Specifics
This module handles AI dialogue, RAG pipeline, and Agent orchestration
using Spring AI.
## Key Conventions
- AI model calls go through `AiModelManager`, never call provider SDKs directly
- RAG pipeline: Document → Splitter → Embedding → VectorStore → Retriever → Prompt
- Conversation history stored in Redis with TTL, key pattern: `chat:{sessionId}`
- Streaming responses use SSE (`SseEmitter`), handle timeout and error callbacks
- All AI-generated content must be logged to `ai_audit_log` table for compliance
## Test
- Unit tests mock all external AI providers
- Integration tests use WireMock for provider API simulation
- `./mvnw test -pl refinex-ai`7.3 全局 AGENTS.md 示例
~/.codex/AGENTS.md:
# Unified Personal Agent Rules
- Reply to my questions in Chinese, unless the code context is in English
- Use Chinese for code comments
- Provide concise, data-driven explanations
- When reviewing code, prioritize: **security > correctness > performance > readability**
- Always show reasoning before the conclusion
- Prefer showing **diffs** over full file rewrites
- Prefer functional programming style
- Follow standard Git conventions for commands and write commit messages in Chinese八、最佳实践清单
- 从最小集开始:先写构建命令和目录路由,后续逐步补充
- 用反馈驱动增长:每次纠正 Codex,追加
Update AGENTS.md so this fix persists - 分层存放:个人偏好 → 全局,团队规则 → 仓库根,模块差异 → 子目录
- 与工具链配对:AGENTS.md 声明意图,pre-commit / linter / type checker 执行验证
- 控制体积:默认上限 32KB(
project_doc_max_bytes),超出即截断 - 定期维护:设置 Automation 定期检查 AGENTS.md 是否存在指导空白
- 版本控制:AGENTS.md 随代码一起 commit,Review 时也审查 AGENTS.md 的变更
九、AGENTS.md vs Skills vs MCP 选型决策树
需要 Codex 遵守的持久规则?
├─ 是 → AGENTS.md
└─ 否 → 是可复用的多步骤工作流?
├─ 是 → Skills
└─ 否 → 需要访问外部系统?
├─ 是 → MCP
└─ 否 → 直接在 Prompt 中说明官方推荐的构建顺序:
- AGENTS.md — 让 Codex 遵守仓库约定,配合 pre-commit hooks 和 linters 强制执行
- Skills — 封装重复性流程,避免「同一段对话反复出现」
- MCP — 当工作流需要外部系统时接入
- Subagents — 当你准备好将嘈杂或专业化任务委派给子代理时启用