以 Claude Code CLI 建立有邊界的自動化
用 claude -p、結構化輸出、turn 與成本上限、權限邊界及外部排程器建立安全自動化。
你會學到什麼
Claude Code 不必變成無限運作的 daemon 才能自動化。正式的基礎是 print mode:
claude -p "Review the current diff"
它接收 prompt、執行 agentic turn、輸出結果後結束。排程、重試與時間控制應由 CI、scheduler 或 wrapper 負責,讓每次執行都可觀察、可停止。
安全自動化的五個邊界
每個 job 都要定義:
- scope:repository 與允許目錄;
- authority:permission mode 與工具限制;
- time:最大 turns 與外層 process timeout;
- cost:最大預算;
- output:text、JSON、stream JSON 或 JSON Schema。
唯讀 review:
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。
結構化輸出
若結果要交給其他程式,使用 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。
不要把 --dangerously-skip-permissions 放進無人值守模板;它會移除重要安全邊界。
CI 原則
- 記錄或固定 Claude Code 版本;
- 使用乾淨且範圍明確的 checkout;
- 明確指定 permission mode;
- 限制 turns、budget 與外層 runtime;
- 程式消費者使用 structured output;
- 保存 stderr 與 exit status;
- 只重試已知安全的失敗;
- 不確定結果要升級處理,不能無限循環。
模型回答不能取代 test、lint、type check 與 deployment verifier;那些才是 authoritative gates。
下一課
Session 12 會加入 Git worktree 隔離,讓多個 Claude Code sessions 不共用同一個可寫 checkout。