Claude Code `/goal` 命令:生产级自主执行完全指南
Claude Code /goal 命令:生产级自主执行完全指南
这是 Claude Code v2.1.139(2026 年 5 月)最重要的更新——
/goal命令。你设定一个可验证的完成条件,AI 自己跑到底,不需要你说"继续"。这篇文章从原理到语法到生产级实战,精确到每一个参数和决策点,是你用好/goal的唯一文档。
一、/goal 解决了什么问题
老方法的问题
没有 /goal 的开发流程:
你: "实现 Task 1"
AI: [写完代码] "完成了,要开始 Task 2 吗?"
你: "开始 Task 2"
AI: [写完代码] "完成了,要开始 Task 3 吗?"
你: "开始 Task 3"
...(重复 27 次)
问题:
- 你必须守在电脑前,每个 Task 完成后手动推进
- 离开 30 分钟 = AI 空闲 30 分钟
- 一个 27 Task 的项目,你可能需要交互 50+ 次
/goal 的做法
有 /goal 的开发流程:
你: /goal 实现 specs/tasks.md 中的所有 27 个 Task
until 每个 Task [x] 且 pytest --tb=short 全部通过 且 ruff check 零错误
without 修改 specs/ 目录下的文件
or stop after 30 turns
AI: [开始执行 Task 1 → Task 2 → Task 3 → ...]
每轮结束后评估模型自动检查完成条件
未完成 → 自动继续
已完成 → 归还控制权
你: 可以去做别的事,30 分钟后回来看结果
核心区别:你不再是 AI 的"发令员",你变成了 AI 的"验收人"。
二、内部原理:两个模型的分工
这是 /goal 区别于其他"循环脚本"方案的本质设计。
两模型架构
┌─────────────────────────────────────────────────────────┐
│ /goal 执行循环 │
├─────────────────────────────────────────────────────────┤
│ │
│ 主模型(Worker) 评估模型(Evaluator) │
│ ┌──────────────────┐ ┌──────────────────┐ │
│ │ 通常是 Sonnet │ │ 默认 Haiku │ │
│ │ 有全部工具权限: │ │ 只有读权限: │ │
│ │ Read/Write/Edit │ │ 只能读会话记录 │ │
│ │ Bash/Grep/Glob │ │ 不能执行命令 │ │
│ │ Task/TodoWrite │ │ 不能改文件 │ │
│ └──────┬───────────┘ └──────┬───────────┘ │
│ │ 执行任务 │ 判断完成 │
│ ▼ ▼ │
│ 写代码、跑测试、修 Bug 只看 transcript │
│ │ "Goal met?" │
│ ▼ │ │
│ 每轮结束 ──────────────────────→ YES/NO │
│ │ │
│ NO → 告诉主模型原因 │
│ 主模型修正 → 下一轮 │
│ YES → 清除 Goal → 完成 │
└─────────────────────────────────────────────────────────┘
关键设计:
- 主模型和评估模型是独立的——主模型无法"说服"评估模型自己已经完成
- 评估模型只看会话记录(transcript)——不能自己打开文件验证,只能检查主模型在对话中展示的证据
- 评估模型默认用 Haiku——足够判断 yes/no,消耗极低
这意味着什么——你的完成条件必须能在 transcript 中被验证
✅ 能被评估模型验证:
"npm test 退出码 = 0" → 主模型跑测试时,退出码会显示在 transcript 中
"ruff check 零错误" → lint 输出会显示在 transcript 中
"tasks.md 中所有 Task 标 [x]" → 主模型用 Read 工具读取 tasks.md 时,内容在 transcript 中
❌ 不能被评估模型验证:
"代码质量很好" → 主观判断,评估模型无法验证
"性能应该优化了" → 没有可观测的输出
"UI 看起来不错" → 评估模型看不到浏览器渲染
三、完整命令参考
基本命令
/goal <condition> # 设定 Goal 并立即开始执行
/goal # 查看当前 Goal 状态
/goal clear # 取消 Goal(别名: stop, off, reset, none, cancel)
条件语法:三要素公式
/goal [what to do] until [measurable end state] without [constraints] or stop after [N turns]
| 要素 | 必需? | 作用 |
|---|---|---|
| what to do | 强烈建议 | 告诉主模型具体做什么 |
| until | 必需 | 评估模型判断完成的标准 |
| without | 可选但推荐 | 防止 AI 越界破坏 |
| or stop after N turns | 强烈建议 | 成本安全阀 |
条件支持最多 4,000 字符,复杂任务可以用结构化格式。
结构化条件格式(用于复杂任务)
/goal
Objective: 将 src/auth/ 模块从 JavaScript 迁移到 TypeScript strict mode
Success criteria:
- tsc --noEmit 退出码 = 0
- 所有测试通过: npm test -- --testPathPattern=auth 退出码 = 0
- src/auth/ 下无 .js 文件
- 无 any 类型(grep -r ": any" src/auth/ 返回空)
Constraints:
- 不修改 src/models/ 下的任何文件
- 不改变 API 接口签名(参数和返回值不变)
- 不引入新的 npm 依赖
Stop after 25 turns.
四、实战示例库——按场景复制使用
场景 1: 修复失败的测试
/goal fix every failing test
until npm test exits 0
without modifying any file outside /src/services/
or stop after 15 turns
场景 2: 执行 Spec-Kit 生成的 tasks.md
/goal implement all tasks in specs/001-user-points/tasks.md
until every task is marked [x] AND
pytest tests/ -x -q exits 0 AND
ruff check src/ exits 0
without modifying specs/ directory
or stop after 30 turns
场景 3: 代码迁移
/goal
Objective: 将 src/legacy/ 下的所有 API 调用从 requests 库迁移到 httpx
Success criteria:
- grep -r "import requests" src/legacy/ 返回空
- grep -r "requests\." src/legacy/ 返回空
- pytest tests/ -k "legacy" 全部通过
- 所有 API 调用的 timeout 参数都已设置(httpx 强制要求)
Without modifying tests/ directory.
Stop after 20 turns.
场景 4: 大文件拆分
/goal split src/utils/helpers.py (currently 847 lines) into modules
under src/utils/helpers/ each < 200 lines
until all modules < 200 lines AND
pytest tests/test_helpers.py exits 0 AND
ruff check src/utils/helpers/ exits 0
without changing any public function signatures
or stop after 10 turns
场景 5: 安全审计修复
/goal find and fix all instances of hardcoded credentials in the codebase
until grep -rE "(password|secret|token|api_key)\s*=\s*['\"]" src/ --include="*.py" returns empty AND
all tests still pass AND
.env.example is updated with any new required variables
without modifying .env or any config/ directory that contains legitimate config files
or stop after 12 turns
场景 6: 依赖清理
/goal remove all unused dependencies from package.json
until npm ls exits 0 AND
no import of removed packages exists in src/ AND
npm test exits 0
without removing devDependencies that are used by build scripts
or stop after 10 turns
场景 7: Issue 批量处理
/goal
Objective: 处理所有标记为 "good first issue" 的 bug
Success criteria:
- gh issue list --label "good first issue" --state open 返回空
- 每个修复有对应的测试
- pytest 全部通过
Constraints:
- 每个 issue 单独一个 commit
- commit message 包含 "Fixes #<issue-number>"
Stop after 40 turns.
场景 8: CI/CD 自动修复
# 在 CI 中以非交互模式运行
claude -p "/goal fix the CI build failure
until npm run build exits 0 AND npm test exits 0
without changing the build configuration in .github/
or stop after 8 turns"
五、生产级实践:写好完成条件的 7 条铁律
铁律 1: 完成条件必须产生可观测的输出
评估模型只看 transcript。你的条件必须对应到某个工具调用的输出。
✅ "pytest tests/ -q 退出码 0" → 主模型跑 pytest 时,stdout 和 exit code 在 transcript 中
❌ "所有函数都有正确的类型标注" → 除非主模型显式用 grep 检查并展示结果
修正方法:把隐含标准变成显式检查。
# 不好
/goal add type annotations to all functions
# 好
/goal add type annotations to all functions in src/
until ruff check src/ --select ANN 退出码 0 AND
mypy src/ --strict 退出码 0
or stop after 15 turns
铁律 2: 用 “without” 明确边界
AI 在自主执行时会"创造性地解决问题"——这可能是好也可能是坏。用 without 画红线。
# 保护核心模块
without modifying src/models/ src/middleware/auth.py
# 防止依赖膨胀
without adding new dependencies to package.json
# 保护配置
without modifying .env .env.example docker-compose.yml
# 限定作用域
without modifying any file that already has passing tests
铁律 3: 总是加 turn 上限
一个 run-away goal 可以在几小时内烧掉数十美元。or stop after N turns 是最低成本的保险。
Turn 数怎么定:
小任务(1-5 个文件改动) → stop after 10 turns
中等任务(5-15 个文件) → stop after 20 turns
大任务(15+ 个文件) → stop after 40 turns
铁律 4: 完成条件要分层验证
单靠一个条件可能被"形式化通过"。例如 pytest exits 0——AI 可能写了空测试。
# 单层验证(弱)
/goal fix tests until pytest exits 0
# 分层验证(强)
/goal fix tests until
pytest exits 0 AND
pytest --cov=src/services --cov-report=term --cov-fail-under=80 exits 0 AND
no test file uses pytest.skip() as a workaround
铁律 5: 条件中引用具体文件路径
不让 AI 猜范围——明确告诉它改哪些文件、不改哪些文件。
# 模糊范围
/goal add error handling to the API
# 明确范围
/goal add error handling to every route handler in src/routes/*.py
until grep -r "except:" src/routes/ 返回空 AND
grep -r "HTTPException" src/routes/ 覆盖每个文件
铁律 6: 编写可调试的完成条件
如果 /goal 提前停止(评估模型说"完成了"但实际上没完成),你需要能从 transcript 中判断是哪个条件被误判。
# 不可调试——条件混在一起,不知道哪个通过了、哪个没通过
/goal implement feature X until everything works
# 可调试——每个条件独立,能从 transcript 中看到每项的验证结果
/goal implement feature X until ALL of:
1. "python -c 'from app import FeatureX; assert FeatureX.is_working()' exits 0" 显示在 transcript
2. "pytest tests/test_feature_x.py -v" exits 0
3. "ruff check src/feature_x.py" exits 0
铁律 7: 让 AI 先写 Goal,你审阅
有时你描述任务比写 Goal 条件更擅长。让 AI 帮你写:
👤: 我需要把 src/legacy_payment/ 模块的信用卡处理逻辑从 Stripe v1 API 迁移到 v2 API。
帮我生成一个 /goal 命令,要有清晰的完成条件和约束。
🤖: /goal
Objective: Migrate src/legacy_payment/ from Stripe v1 to v2 API
Success criteria:
- grep -r "stripe\.v1" src/legacy_payment/ returns empty
- pytest tests/test_payment.py -v exits 0
- A manual diff review confirms no business logic changes outside API call syntax
Constraints:
- Do not modify tests/test_payment.py (existing tests must pass as-is)
- Do not change the public interface of payment_service.py
Stop after 15 turns.
👤: 第三个条件评估模型验证不了,改成 check_stripe_migration.py 脚本验证。
加上 without modifying src/routes/payment_routes.py。
六、/goal 与其他 Claude Code 特性配合
6.1 /plan → /goal:最佳搭档
第 1 步: /plan 实现用户积分过期提醒功能。约束: 用现有的 APScheduler,不引入新依赖。
→ AI 分析现有代码 → 提出方案:
1. 新增 Notification 模型
2. 在 expire_points() 中加通知逻辑
3. 新增 GET /api/notifications 接口
→ 你审阅确认
第 2 步: /goal 按上述方案实现,until pytest tests/ -k "points" -v exits 0
without modifying src/models/points.py src/cli/main.py
or stop after 12 turns
→ AI 在 Plan 的约束下自主执行
6.2 Spec-Kit + /goal
# 用 Spec-Kit 生成 Spec/Plan/Tasks 后,用 /goal 执行
/speckit.specify → specs/001-feature/spec.md (需求)
/speckit.plan → specs/001-feature/plan.md (方案)
/speckit.tasks → specs/001-feature/tasks.md (任务)
/goal execute all tasks in specs/001-feature/tasks.md
until every task checkbox is [x] AND
the check script specs/001-feature/verify.sh exits 0
without modifying specs/ directory
or stop after 30 turns
6.3 Stop Hook + /goal:双重保险
Stop Hook 和 /goal 可以叠加——Goal 管"什么时候算完成",Stop Hook 管"每次停止前的最后检查"。
// .claude/hooks.json —— Stop Hook 在 /goal 每轮结束时额外检查
{
"Stop": [
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "cd \"$CLAUDE_PROJECT_DIR\" && python -m pytest tests/unit/ -x -q 2>&1 || (echo '[HOOK] Tests failed, continue working.' && exit 1)"
}
]
}
]
}
效果:即使评估模型误判了,Stop Hook 的测试失败也会阻止 AI 停止。
6.4 /goal + Scratchpad:进度追踪
/goal
Objective: ... (your conditions)
While working, maintain a PROGRESS.md file with:
- Completed tasks
- Current task
- Blockers encountered
- Decisions made and why
Until ... AND PROGRESS.md shows all tasks complete
好处:
- 你随时可以
cat PROGRESS.md看进度(不用解析 transcript) - 如果中途
/goal clear,下一个 Goal 可以从 PROGRESS.md 续接 - 评估模型可以检查 PROGRESS.md 辅助判断完成状态
七、成本控制与风险管理
7.1 成本估算
单轮平均消耗: ~15K-25K tokens(含主模型 + 工具调用结果)
评估模型每轮: ~2K-5K tokens(Haiku,极低成本)
场景估算:
10 轮小任务: ~$2-5(Sonnet) 或 ~$0.50(Haiku)
30 轮中等任务: ~$8-15(Sonnet)或 ~$1.50(Haiku)
50 轮大任务: ~$15-30(Sonnet)或 ~$3(Haiku)
7.2 成本控制策略
# 策略 1: Turn 上限(最直接)
/goal ... or stop after 15 turns
# 策略 2: 分段执行(每段独立验证)
/goal implement Phase 1 (T001-T004) until ... or stop after 10 turns
# 审阅 Phase 1
/goal implement Phase 2 (T005-T008) until ... or stop after 10 turns
# 策略 3: 用 --model 选择成本更低的模型
claude --model haiku -p "/goal fix all ruff errors until ruff check exits 0 or stop after 5 turns"
# 简单格式化任务不需要 Opus,Haiku 足够
# 策略 4: 在非交互模式(-p)中运行
claude -p "/goal ... or stop after 20 turns"
# Ctrl+C 即可中断
7.3 失控预警信号
🔴 需要立刻 /goal clear 的信号:
→ 连续 3 轮没有文件改动(失速)
→ 同一错误被修复了 3 次仍失败(打转)
→ AI 开始修改你没授权的文件(越界)
→ 评估模型连续 2 轮说 "condition met" 但你明显看到没完成(评估异常)
→ Token 消耗超过预期预算的 2 倍
🟡 需要注意但不必停止:
→ 每轮都改同一个文件(可能在反复重构)
→ Turn 数超过预期的 1.5 倍
→ Transcript 中 AI 出现 "let me try another approach" 多次
八、常见失败模式与解决
失败模式 1: 评估模型误判"已完成"
症状: /goal 在 Task 只完成了 60% 时就停止了
评估模型说 "condition met",但明显还有未完成的 Task
根因: 完成条件的可验证性不够——评估模型在 transcript 中找到了
满足条件的"关键词"但实际未完成
解决:
1. 把单一条件拆成多个 AND 条件
2. 加一个"验证脚本"作为最终检查
/goal ... until ALL of:
1. pytest tests/ -q exits 0
2. python scripts/verify_all_tasks.py exits 0 ← 自定义验证脚本
3. tasks.md 中每个 Task 标记 [x]
失败模式 2: AI 在无关方向上反复尝试
症状: 主模型遇到一个问题 → 尝试方案 A(失败)→ 方案 B(失败)
→ 方案 C(失败)→ 仍不放弃,尝试方案 D
根因: 没有限制"同一个问题的重试次数"
解决: 在条件中加上探索约束
/goal ... until ...
when a single error persists after 2 fix attempts,
document it in BLOCKERS.md and move to the next task
失败模式 3: 上下文退化导致后期质量下降
症状: 前 5 轮代码质量好,第 10+ 轮开始忽略约束、犯低级错误
根因: 长对话上下文被早期轮次的历史占满
解决:
→ 分段 goal(每段 8-12 轮)
→ 每段完成后 /goal clear → 检查 → 新 /goal 继续
→ 或让 AI 每 5 轮生成 checkpoint summary
失败模式 4: AI "创造性绕过"约束
症状: 你设了 "without modifying tests/",但 AI 在 tests/ 外面
新建了 test2/ 目录然后在那里面改
根因: 约束条件不够精确,AI 找了字面解释的漏洞
解决: 约束条件写全路径,覆盖变体
without modifying any test file, creating new test directories,
or changing test configuration in pyproject.toml or conftest.py
九、完整实战:用 /goal 从零完成一个功能
以第 15 篇的"用户积分系统"为例,展示 /goal 的完整生产级用法。
Step 1: 前期准备(Spec-Kit 生成 Spec)
# 在 Claude Code 中
/speckit.specify → 生成 specs/001-user-points/spec.md
/speckit.plan → 生成 specs/001-user-points/plan.md
/speckit.tasks → 生成 specs/001-user-points/tasks.md
审阅通过后,创建验证脚本 specs/001-user-points/verify.sh:
#!/bin/bash
# verify.sh —— 积分系统验证脚本
set -e
echo "=== Verifying User Points System ==="
# 1. 数据库迁移
echo "[1/5] Running migrations..."
alembic upgrade head
# 2. 单元测试
echo "[2/5] Running unit tests..."
python -m pytest tests/unit/test_points.py -v -q
# 3. 集成测试
echo "[3/5] Running integration tests..."
python -m pytest tests/integration/test_points_e2e.py -v -q
# 4. Lint
echo "[4/5] Running ruff check..."
python -m ruff check src/ --quiet
# 5. 类型检查
echo "[5/5] Running mypy..."
python -m mypy src/ --ignore-missing-imports
echo "=== All checks passed ==="
Step 2: 设定 Goal
/goal
Objective: 实现 specs/001-user-points/tasks.md 中的所有 16 个 Task(用户积分系统)
Success criteria (ALL must be met):
1. 每个 Task 在 tasks.md 中标记为 [x]
2. bash specs/001-user-points/verify.sh exits 0
3. git diff --stat 不包含 specs/ 目录下的任何文件
Constraints:
- 不修改 src/models/ 下非 points 相关的模型文件
- 不修改 src/routes/ 下非 points 相关的路由文件
- 不引入 requirements.txt 中未列出的第三方依赖
- 所有错误信息用中文注释,标识符用英文
- 数据库操作必须用 async/await
While working:
- 每完成一个 Phase 更新 specs/001-user-points/progress.md
- 遇到无法自动解决的阻塞标记在 BLOCKERS.md 中并继续下一个 Task
- 同一个错误重试不超过 2 次
Stop after 35 turns.
Step 3: 监控执行
在另一个终端窗口中:
# 实时查看进度
watch -n 5 'cat specs/001-user-points/progress.md 2>/dev/null || echo "Not started yet"'
# 查看 Git 变更
watch -n 5 'git diff --stat'
# 查看 Goal 执行日志(如果在 Claude Code 外部循环中)
tail -f logs/goal_execution.log
Step 4: Turn 上限到达后的处理
# Goal 在 35 轮后自动停止
/goal # 查看当前状态
# 输出: ◎ /goal active | round 35/35 | 187K tokens | elapsed 48min
# Condition: "All 16 tasks [x] AND verify.sh exits 0"
# Last eval: ❌ 14/16 tasks done, 2 tasks remaining (T015, T016)
# 还有 2 个 Task 未完成,设定新的 Goal 继续
/goal complete remaining tasks T015 and T016 from specs/001-user-points/tasks.md
until both marked [x] AND verify.sh exits 0
or stop after 10 turns
Step 5: 完成后验证
# Goal 完成后的最终检查
/goal
# 输出: ○ No active goal (上一 Goal 已完成: 16/16 tasks, 32 turns, 156K tokens, 1h12min)
# 手动最终验证
bash specs/001-user-points/verify.sh
git diff --stat # 确认只有预期的文件被修改
git diff HEAD~1 # 审阅最后一个 Phase 的改动
pytest tests/ -v --cov # 最终覆盖率检查
十、/goal 决策速查
什么时候用 /goal
✅ 适合 /goal:
- 可量化完成条件的任务(test 通过、lint 零错误、文件 count)
- 多步骤重复性工作(迁移、重构、批量修复)
- 有 Spec/Tasks 文档的标准化开发
- 需要长时间运行但你不想守在电脑前
- CI/CD 中的自动修复流程
❌ 不适合 /goal:
- 主观性任务("让 UI 更好看"、"优化代码质量")
- 单文件简单改动(/goal 的评估开销不值得)
- 需要频繁人类判断的探索性开发
- 评估模型无法验证的任务(研究、设计、文档审阅)
- 需要跨多个 repository 的工作
一句话总结
将 /goal 用于:
/plan → 确定方向 → /goal → 自主执行 → 回来验收
将普通对话用于:
探索 → 理解 → 设计 → 决策 → 单步实现
总结
-
/goal的核心机制:主模型(Worker)执行 + 评估模型(Evaluator/Haiku)判断完成,两模型独立,防止"自己判自己"。 -
三要素公式:
/goal [做什么] until [可验证完成标准] without [约束边界] or stop after [N turns]。 -
写完成条件的核心原则:条件必须能在 transcript 中被观察到——评估模型不跑命令、不读文件,只看对话记录。
-
7 条铁律:可观测输出、画清边界、加 turn 上限、分层验证、引用具体路径、可调试、让 AI 先写你审阅。
-
最佳拍档:
/plan对齐方向 →/goal自主执行。Spec-Kit 生成文档后 →/goal执行。 -
成本控制:turn 上限是底线,分段 goal 是常规操作,简单任务用 Haiku 模型。
-
失败模式:评估误判(加验证脚本)、方向打转(加重试上限)、上下文退化(分段 goal)、约束绕过(写全路径)。
延伸阅读
更多推荐



所有评论(0)