CLI コントロールサーフェス:Print Mode、JSON、Sessions
Print mode、構造化出力、turn 上限、権限モード、再開可能 session を使い、Claude Code を境界付き CLI process として運用する。
学ぶこと
Claude Code は対話型 TUI だけではありません。リリース済み CLI は、一回の 境界付きタスク、machine-readable 出力、JSON Schema、agent turn 上限、 permission mode、保存 session の再開を提供します。
この記事は Claude Code 2.1.226 の command contract に基づきます。重要な
automation では claude --version と最新 CLI reference を再確認してください。
Print Mode から始める
-p は --print の短縮形です。Claude は非対話で実行し、結果を出力して
終了します。
claude -p "Summarize the changed files and report which tests ran."
別 CLI の -p を転用しないでください。Codex の -p は configuration
profile、Grok Build の -p は single-turn prompt です。
出力契約を選ぶ
人が読むなら text、一つの構造化結果なら JSON、incremental events が必要なら stream JSON を使います。
claude -p --output-format text "Explain the failing test."
claude -p --output-format json "Return the repository status."
claude -p --output-format stream-json --include-partial-messages \
"Report progress while reviewing this repository."
出力は untrusted data です。parse と shape validation を行い、shell command 生成から分離してください。
JSON Schema を要求する
--json-schema は print-mode 出力を制約します。shell の分割や展開を防ぐため、
schema 全体を quote します。
claude -p \
--json-schema '{"type":"object","properties":{"summary":{"type":"string"},"tests":{"type":"array","items":{"type":"string"}}},"required":["summary","tests"],"additionalProperties":false}' \
"Review the current diff and return the requested fields."
Schema は形を検証しますが、真実性は保証しません。呼び出し側が files、tests、 external state を検証します。
Authority と作業量を制限する
Turn 上限と permission mode は別々の control です。
claude -p \
--max-turns 6 \
--permission-mode plan \
"Map the implementation path and risks without editing."
--max-turns は agent loop を制限し、--permission-mode は tool authority を
決めます。どちらも OS sandbox、repository isolation、destructive command
review の代わりにはなりません。
Session を明示的に続ける
再現性が必要なら session ID を指定します。
claude -p --resume SESSION_ID \
"Continue from the saved context and re-check the current worktree first."
--continue は current directory の最新 conversation を選び、便利ですが曖昧です。
claude -p --continue "Continue only if the repository state still matches."
保存 context は古い可能性があります。再開ごとに instructions、permissions、 branch、diff、test state を確認してください。
Production Checklist
- Claude Code version を固定して記録する。
-pは Claude print mode としてのみ解釈する。- Output format を選び、machine-readable output を検証する。
- Downstream が fields に依存するなら JSON Schema を使う。
- Turns を制限し、意図した permission mode を選ぶ。
- Session 再開後に worktree を再検証する。
- Model output を直接 shell へ埋め込まない。
次へ
Session 14 では、この境界付き CLI workflow を MCP server に接続し、server trust と tool authority を明示的に保ちます。