メインコンテンツへスキップ
モジュール 2:マルチエージェント 5 / 6
中級 S11 Claude Code CLI Print Mode 自動化 安全

Claude Code CLI による境界付き自動化

claude -p、構造化出力、turn とコスト上限、権限境界、外部オーケストレーションで安全な自動化を構築します。

2026年3月20日 14分
確認済み カリキュラム確認日: 2026年7月31日

学ぶこと

Claude Code を無制限の daemon にしなくても自動化できます。正式な基盤は print mode です。

claude -p "Review the current diff"

Prompt を受け取り、agentic turn を実行し、結果を出力して終了します。スケジュール、再試行、時間制限は CI、scheduler、wrapper が所有します。

安全な自動化の五つの境界

各 job で次を定義します。

  1. scope — repository と許可ディレクトリ
  2. authority — permission mode とツール制限
  3. time — 最大 turns と外側の process timeout
  4. cost — 最大予算
  5. 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"

イベント単位の consumer には --output-format stream-json を使います。Partial events を処理できる場合だけ --include-partial-messages を追加します。

Session の継続

後から対象にする job には名前を付けます。

claude -p --name nightly-review "Review the repository status"
claude -p --resume nightly-review "Re-check only the unresolved findings"
claude -p --continue "Run the affected tests and report the result"

履歴を残さない 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 version を固定または記録する
  • clean で scoped な checkout を使う
  • permission mode を明示する
  • turns、budget、外側 runtime を制限する
  • プログラム向けには structured output を使う
  • stderr と exit status を保存する
  • 安全と分かる失敗だけを再試行する
  • 曖昧な結果を無限ループせず人に上げる

Model の返答は test、lint、type check、deployment verifier の代わりではありません。

次のセッション

Session 12 では Git worktree isolation を追加し、複数 Claude Code sessions が同じ書き込み checkout を共有しないようにします。