Development
上下文工程
优化代理上下文设置。适用于启动新会话、代理输出质量下降、在任务间切换或配置规则文件时。
在正确的时间为代理提供正确的信息。上下文是影响代理输出质量的最大杠杆。
┌─────────────────────────────────────┐
│ 1. 规则文件(CLAUDE.md 等) │ ← 始终加载,项目级
├─────────────────────────────────────┤
│ 2. 规范/架构文档 │ ← 按功能/会话加载
├─────────────────────────────────────┤
│ 3. 相关源文件 │ ← 按任务加载
├─────────────────────────────────────┤
│ 4. 错误输出/测试结果 │ ← 按迭代加载
├─────────────────────────────────────┤
│ 5. 对话历史 │ ← 累积、压缩
└─────────────────────────────────────┘
创建一个跨会话持久化的规则文件:
# Project: [Name]
## Tech Stack
- React 18, TypeScript 5, Vite, Tailwind CSS 4
- Node.js 22, Express, PostgreSQL, Prisma
## Commands
- Build: `npm run build`
- Test: `npm test`
- Lint: `npm run lint --fix`
- Dev: `npm run dev`
## Code Conventions
- Functional components with hooks
- Named exports (no default exports)
- Colocate tests next to source
- Use `cn()` utility for conditional classNames
## Boundaries
- Never commit .env files or secrets
- Never add dependencies without checking bundle size
- Ask before modifying database schema
- Always run tests before committing
开始功能开发时,加载相关的规范章节,不要加载整个规范。
编辑文件前先阅读。实现模式前先找到已有示例。
当测试失败时,将具体错误反馈给代理:
有效方式: "测试失败:TypeError: Cannot read property 'id' of undefined at UserService.ts:42"
低效方式: 粘贴整个 500 行的测试输出。
在会话开始时,提供代理所需的所有信息:
PROJECT CONTEXT:
- We're building [X] using [tech stack]
- The relevant spec section is: [spec excerpt]
- Key constraints: [list]
- Files involved: [list with brief descriptions]
- Known gotchas: [list]
只包含与当前任务相关的内容:
TASK: Add email validation to the registration endpoint
RELEVANT FILES:
- src/routes/auth.ts (the endpoint to modify)
- src/lib/validation.ts (existing validation utilities)
- tests/routes/auth.test.ts (existing tests to extend)
PATTERN TO FOLLOW:
- See how phone validation works in src/lib/validation.ts:45-60
CONSTRAINT:
- Must use the existing ValidationError class
CONFUSION:
The spec calls for REST endpoints, but the existing codebase uses GraphQL
for user queries (src/graphql/user.ts).
Options:
A) Follow the spec — add REST endpoint
B) Follow existing patterns — use GraphQL
C) Ask — this seems like an intentional decision
→ Which approach should I take?
| 反模式 | 问题 | 修复方式 | |--------|------|----------| | 上下文不足 | 代理自行发明 API,忽略约定 | 加载规则文件 + 相关源文件 | | 上下文过载 | 代理在 >5,000 行后失去焦点 | 只包含与任务相关的上下文 | | 上下文过时 | 代理引用过时的模式 | 上下文偏移时开始新会话 | | 缺少示例 | 代理发明新风格 | 包含一个模式示例 | | 隐式知识 | 代理不知道项目规则 | 将规则写入规则文件 |
设置上下文后: