以 Claude Code CLI 建立有邊界的自動化
用 claude -p、結構化輸出、turn 與成本上限、權限邊界及外部排程器建立安全自動化。
你會學到什麼
Claude Code 不必變成無限運作的 daemon 才能自動化。正式的基礎是 print mode:
claude -p "Review the current diff"
它接收 prompt、完成任務、輸出結果後結束。排程、重試與時間控制應由 CI、scheduler 或 wrapper 負責,讓每次執行都可觀察、可停止。
安全自動化的五個邊界
每個 job 都要定義:
- scope:repository 與允許目錄;
- authority:permission mode 與工具限制;
- time:最大 turns 與外層 process timeout;
- cost:最大預算;
- output:text、JSON、stream JSON 或 JSON Schema。
唯讀 review job:
claude -p \
--permission-mode plan \
--max-turns 8 \
--max-budget-usd 1.50 \
"Review the current diff. Do not edit files. Return findings by severity."
在 Claude Code 中,-p 是 print mode;不能把這個語意套到其他 CLI。Codex 的 -p 是選擇 configuration profile。
請明確指定 permission mode。自 Claude Code 2.1.302 起,沒有設定模式的 -p 執行會以 Manual mode(設定值 default)啟動:讀取檔案與內建唯讀命令可以執行,其他需要核准的呼叫,除非有 allow rule、hook 或 permission-prompt tool 核准,否則一律拒絕。依 job 性質選擇模式:
| Job | 模式 | 不需提示即可執行的動作 |
|---|---|---|
| 唯讀分析或規劃 | --permission-mode plan | 讀取與探索;編輯一律封鎖 |
| 以明確 allowlist 鎖定的 CI | --permission-mode dontAsk 加上 --allowedTools | 讀取、唯讀命令與你的 allowlist;其餘全部拒絕 |
| 範圍明確的編輯 | --permission-mode acceptEdits | 檔案編輯與常見檔案系統命令;其他 shell 命令仍需 allow rule |
| 由分類器審查的自主執行 | --permission-mode auto | 經分類器模型核准的動作 |
結構化輸出
若結果要交給其他程式,使用 JSON:
claude -p \
--output-format json \
"Summarize the current git diff"
用 schema 約束最終結果:
claude -p \
--output-format json \
--json-schema '{
"type": "object",
"properties": {
"verdict": {"type": "string"},
"findings": {"type": "array", "items": {"type": "string"}}
},
"required": ["verdict", "findings"]
}' \
"Audit the current diff without changing files"
需要逐事件消費時使用 --output-format stream-json。只有 consumer 能處理 partial events 時才加 --include-partial-messages。
Session 延續
為需要後續延續的 job 命名:
claude -p --name nightly-review "Review the repository status"
指定 resume:
claude -p --resume nightly-review "Re-check only the unresolved findings"
延續最近一個符合條件的 session:
claude -p --continue "Run the affected tests and report the result"
不需要保存歷史的 stateless job,使用 --no-session-persistence。
把循環放在 Claude Code 外部
外部 scheduler 應決定何時執行與是否重試:
#!/usr/bin/env bash
set -euo pipefail
claude -p \
--permission-mode plan \
--max-turns 6 \
--max-budget-usd 1.00 \
--output-format json \
"Inspect the repository and report whether the documented verification command should run."
Wrapper 可設定 OS timeout、保存 exit status 與 logs、發送通知。每次 Claude Code 執行仍是一個有上限的 process。設定 timeout 時也要把背景工作算進去:-p 執行在輸出結果後,可能仍會保持開啟,等它啟動的背景命令或 subagent 完成。若 wrapper 以 SIGTERM 停止執行,Claude Code 會以 code 143 結束,且不會為未完成的回合記錄結果。
不要把 --dangerously-skip-permissions 放進無人值守模板;它會移除重要安全邊界,應該只用在另外審查過的環境。
當循環位於 Claude Code 內部
Claude Code 也內建了循環機制。每一種都會改變「由誰決定工作繼續」,因此要把它當成邊界的一部分:
| 命令 | 下一個回合何時開始 | 何時停止 | 適合 |
|---|---|---|---|
/goal <condition> | 上一個回合結束,且評估模型判斷條件尚未達成 | 評估模型判斷條件已達成或不可能、發生必須由你修正的錯誤,或你執行 /goal clear | 完成可驗證的最終狀態 |
/loop [interval] <prompt> | 開啟中的 session 經過指定間隔,或 Claude 自行選擇下一次喚醒 | 你取消它、Claude 結束自訂節奏的循環,或經過 7 天 | session 開著時進行輪詢 |
/schedule(雲端排程任務,研究預覽) | 排程、API 呼叫或 GitHub 事件觸發 | 你暫停或刪除該任務 | 在雲端基礎設施上無人值守執行 |
/goal 也能在 print mode 中使用:
claude -p --max-budget-usd 3.00 \
"/goal CHANGELOG.md has an entry for every PR merged this week"
這次執行會持續進行回合,直到評估模型滿意為止。評估模型只根據對話中出現的內容判斷,所以「or stop after 20 turns」這類條款只是軟性上限。Goal 不會改變 permission mode,authority 邊界依然適用;--max-budget-usd 與 wrapper 的 timeout 仍是 process 層級的停止機制。第 31 堂課會深入說明 /loop 與排程式自主執行。
CI 模式
可靠的 CI job 需要明確的輸入與不會修改檔案的 prompt:
git diff --exit-code -- . >/dev/null || true
claude -p \
--permission-mode dontAsk \
--max-turns 10 \
--output-format json \
--json-schema '{"type":"object","properties":{"pass":{"type":"boolean"},"reason":{"type":"string"}},"required":["pass","reason"]}' \
"Review the checked-out change against AGENTS.md. Do not modify files."
dontAsk 讓 review 可以讀取檔案並執行內建唯讀命令(例如唯讀形式的 git),任何原本會跳出提示的動作都會直接被拒絕,而不是等待回答。只為 job 真正需要的命令加入 --allowedTools 項目。
接著讓 CI 解讀結構化結果。流暢的文字回答不能當成 build 通過;test、lint、type check 與 deployment verifier 才是 authoritative gates。
操作檢查清單
- 記錄或固定 Claude Code 版本;
- 使用乾淨且範圍明確的 checkout;
- 明確指定 permission mode(自 Claude Code 2.1.302 起,
-p以 Manual mode 啟動); - job 必須忽略本機 hooks、plugins、MCP servers 與
CLAUDE.md時,加上--bare(在 Anthropic API 上,它只使用ANTHROPIC_API_KEY或透過--settings傳入的apiKeyHelper驗證); - 限制 turns、budget 與外層 runtime;
- 程式消費者使用 structured output;
- 保存 stderr 與 exit status;
- 只重試已知安全的失敗;
- 不確定結果要升級處理,不能無限循環。
下一課
Session 12 會加入 Git worktree 隔離,讓多個 Claude Code sessions 不共用同一個可寫 checkout。