Headless Mode 與 CI/CD 整合
Claude Code 的無頭模式:不開互動式對話,像一個 CLI 工具接受指令直接跑——適合 CI/CD pipeline、定時排程、自動化腳本。
核心 flag:-p
claude -p "幫我跑全部測試並摘要結果"| flag | 用途 |
|---|---|
-p "<prompt>" | 一次性 prompt |
--no-interactive | 完全靜默模式 |
--output-format json | 結構化輸出 |
--allowed-tools <list> | 限制可用工具 |
為什麼要 Headless?
互動式 Claude Code:
- 需要終端機 + 人盯著
- 等使用者輸入 → 不能放 cron / GitHub Actions
Headless:
- ✅ 放進
.github/workflows/*.yml - ✅ 放進 cron job / launchd
- ✅ 接管 deploy script
經典場景
1. PR 自動 review
# .github/workflows/claude-review.yml
on: pull_request
jobs:
review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: |
claude -p "Review this PR diff focus on:
1. SQL injection risk
2. Test coverage gap
3. Naming consistency
${{ github.event.pull_request.diff_url }}"→ 每 PR 自動 review,commenter = Claude bot。
2. 每日健檢
# crontab
0 9 * * * cd ~/ExamSystem && claude -p "跑單元測試 + lint,異常寄 email" >> /var/log/pam.log3. 部署前驗證
# deploy.sh
claude -p "確認 CLAUDE.md 中所有檢查項都過 OR 列出未過項" --output-format json | jq .ok跟 Scheduled Tasks 的差異
| Headless Claude Code | Scheduled Tasks(Cowork) | |
|---|---|---|
| 環境 | CLI / CI server | 桌機 Cowork |
| 適用 | 開發者、DevOps | 一般使用者 |
| 觸發 | cron / GitHub Actions | Cowork 內建 scheduler |
跟 Hooks 的差異
| Hooks | Headless Mode | |
|---|---|---|
| 觸發 | Claude Code 內部事件 | 外部排程 |
| 目的 | 改變對話行為 | 跑完即離 |
限制 / 注意
- 權限收斂:Headless 跑時要嚴格
--allowed-tools列白名單 - 無人決策:Claude 卡住時只會錯誤退出,不會等你(需用 Channels 補通知)
- token 成本:定時跑會持續消耗 quota
對 Vincent 工作場景
Use Case 1:PR 自動 review
on: pull_request
- run: claude -p "Review focus on: 等第計算邏輯 + 出勤公式"→ 你 review 前,Claude 先跑一輪基本檢查。
Use Case 2:每週健檢
# Mac launchd 每週一 09:00
claude -p "
1. 跑 ExamSystem.Tests
2. 跑前端 npm test
3. lint Python scripts
4. 異常用 [[Channels]] 推 Telegram
"Use Case 3:dependabot 替代品
# 每月跑一次
claude -p "
讀 ExamSystem.csproj + package.json
查每個依賴最新版本 + breaking changes
寫一份建議升級報告到 ~/Reports/dep-$(date).md
"Use Case 4:CI build
- run: claude -p "
讀 build error log
定位失敗原因
若是測試失敗,列出測試名與失敗原因
" --output-format json跟 Plugin 的搭配
claude -p "@plugin:karpathy-wiki-pattern wiki-lint"→ Headless 跑 plugin 提供的 skill。可以把整個團隊的 SOP 用 plugin 封裝 + headless 跑。
相關概念
強連結(原文明確提及)
- Scheduled Tasks — Cowork 對應自動化
- Channels — Headless 結果通知
- Hooks — 互動模式的事件機制
- Remote Control — 半人工的延伸方案
← 回到 wiki