是什么
Claude Code 使用的核心约束是上下文窗口——它填满得很快,性能随填充程度下降。所有最佳实践都围绕这一约束展开:如何给 Claude 可验证的目标、如何管理上下文、如何扩展到并行会话。
核心机制
给 Claude 验证手段(最高杠杆操作):
- 提供测试用例:「实现 validateEmail,测试用例:user@example.com → true,invalid → false,运行测试后告诉我结果」
- 提供截图:粘贴设计稿,让 Claude 对比实现结果
- 提供预期输出:明确描述「修复后」应该是什么样
探索-计划-实施三阶段:
- Plan 模式探索:
read /src/auth and understand how we handle sessions - 生成计划:
I want to add Google OAuth. What files need to change? Create a plan. - 切换到实施模式执行计划
具体化提示词:
| 模糊 | 具体 |
|---|---|
fix the bug | users report login fails after session timeout. check src/auth/, especially token refresh. write a failing test first, then fix it |
add tests for foo.py | write a test for foo.py covering the edge case where the user is logged out. avoid mocks. |
add a calendar widget | look at HotDogWidget.php as example, follow the pattern to implement a calendar widget that lets user select month and paginate |
上下文管理策略:
/clear在不相关任务之间重置上下文/compact focus on the API changes手动压缩并指定保留重点- 用 Subagent 隔离研究任务:「use subagents to investigate how our auth system handles token refresh」
Esc+Esc或/rewind回滚到之前的检查点
扩展到并行:
- Worktrees:独立 git 检出,多个 Claude 会话不冲突
- Writer/Reviewer 模式:一个会话实现,另一个会话审查(新鲜上下文,无偏见)
- Fan-out 脚本:
for file in $(cat files.txt); do claude -p "migrate $file" --allowedTools "Edit,Bash(git commit *)"; done
关键细节
- CLAUDE.md 超过 200 行后 Claude 开始忽略部分规则
- 同一问题纠正两次后,用
/clear开新会话比继续纠正更有效 claude -p "prompt" --output-format json用于脚本集成claude -p "prompt" --output-format stream-json用于实时处理--allowedTools限制批量操作的工具权限,避免意外操作
关联
- how-claude-code-works — agentic loop 和上下文管理原理
- context-window — 上下文窗口可视化和压缩机制
- memory — CLAUDE.md 编写技巧
- common-workflows — 具体工作流模板
- permission-modes — Auto 模式用于无人值守执行
实践要点
- 最高杠杆:给 Claude 可验证的目标(测试、截图、预期输出)
- 上下文是主要约束:频繁清理,用 Subagent 隔离大量读取
- CLAUDE.md 要精简:每行问「删掉这行 Claude 会犯错吗?」,不会就删
- 避免「厨房水槽会话」:一个会话只做一件事,不相关任务开新会话
- 纠正两次还不对时,停下来重新写更好的提示词,而不是继续纠正
- 让 Claude 先采访你(
Interview me using the AskUserQuestion tool),再写规格文档,然后开新会话执行