비대화형 모드
헤드리스 CI 실행을 위한 -p / --print 플래그를 다룹니다
비대화형 모드은(는) CoddyKit의 무료 Claude Architect 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Claude Architect 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Claude Architect 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Why Headless Mode Exists
Claude Code defaults to an interactive terminal session: it prompts you, waits for input, and streams a conversation. That model is perfect at your desk and useless inside a pipeline.
A CI/CD runner has no human to confirm a plan, approve an edit, or answer a follow-up question. It needs a single command that runs, produces output, and exits with a status code.
That is exactly what -p / --print delivers: non-interactive (headless) execution. It is the foundational flag for running Claude Code in CI.
The --print Flag
You invoke headless mode by passing your prompt to -p (the short form of --print). Claude runs the agentic loop to completion and prints the final result to stdout, then the process exits.
There is no REPL, no waiting on input, no confirmation prompts. One command in, one result out — the contract a pipeline step needs.
# Interactive (default) — opens a session, waits for you
claude
# Non-interactive (headless) — runs and exits, prints to stdout
claude -p "Review the staged diff and list any blocking issues"A Real CI Step
In practice -p becomes one step in a job. The runner checks out the code, then calls Claude with a precise instruction. Because the process exits when the loop reaches end_turn, the pipeline moves on naturally.
Keep the prompt scoped and explicit — there is no human to clarify ambiguity mid-run, so the instruction must stand on its own.
# .github/workflows/review.yml (excerpt)
- name: Claude review
run: |
claude -p "Review the diff in this PR. Flag only changes that
introduce a bug, a security issue, or break a public API."
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}Parseable Output: --output-format json
Plain text is fine for a human reading logs, but a pipeline usually needs to act on the result — post a comment, set a check status, gate a merge.
Add --output-format json so Claude emits a structured, machine-readable result instead of free prose. Your next step can then parse fields deterministically with jq or a script.
claude -p "List blocking issues in the staged diff" \
--output-format json | jq '.result'Enforcing a Schema
JSON alone still lets the model choose its shape. For reliable automation, pair --output-format json with a schema so every run returns the same fields. This eliminates syntax surprises and lets you require exactly the keys your pipeline consumes.
Reuse the same structured-output discipline as the API: mark a field required only if it is always present — never force a field that may legitimately be absent, or the model will fabricate it.
{
"type": "object",
"properties": {
"verdict": { "type": "string", "enum": ["pass", "fail"] },
"issues": {
"type": "array",
"items": {
"type": "object",
"properties": {
"file": { "type": "string" },
"severity": { "type": "string", "enum": ["blocking", "warning"] },
"detail": { "type": "string" }
},
"required": ["file", "severity", "detail"]
}
}
},
"required": ["verdict", "issues"]
}Review in an Isolated Session
A subtle but exam-critical point: when Claude both generates code and then reviews it in the same session, the review is biased — the author retains its own reasoning and won't challenge itself.
In CI, run the review in a fresh, isolated session, separate from any generation context. An independent instance is far more likely to catch real defects. This mirrors the general rule: independent review beats same-session self-review.
# Generation and review are SEPARATE invocations / sessions
claude -p "Implement the change described in TASK.md"
# Fresh, unbiased reviewer — no generation history
claude -p "Review the resulting diff for correctness and security only" \
--output-format jsonMinimize False Positives
A CI reviewer that cries wolf gets ignored. The goal is precision: surface real blockers, stay quiet otherwise.
The lever is the prompt, not vague pleading. Explicit criteria beat fuzzy asks: "flag a comment only when it contradicts the code" outperforms "be more precise." A few targeted few-shot examples (2-4) of true vs. false positives further calibrate the model on your edge cases.
claude -p "Review the diff. Report an issue ONLY if it (a) causes
incorrect behavior, (b) is a security risk, or (c) breaks a public
contract. Do NOT comment on style, naming, or formatting.
Example (flag): off-by-one in loop bound -> array overrun
Example (ignore): a variable could be renamed for clarity" \
--output-format jsonScope Tools with Least Privilege
A headless run executes without human approval, so unrestricted tool access is risky. Grant only what the job needs.
For a read-only review you typically want Read, Grep, and Glob — not Write, Edit, or arbitrary Bash. This is the same least-privilege principle you apply to agent tool sets: scope tools to the role, and keep the set small for reliable selection.
claude -p "Review the diff and report blocking issues" \
--output-format json \
--allowedTools "Read,Grep,Glob"Stop on the Loop, Not on a Status Line
Even headless, the agentic loop is unchanged: request -> inspect stop_reason -> if tool_use, run tools and continue -> repeat until end_turn. The process exits when the model reaches end_turn.
Do not wrap Claude in a script that greps the output for words like "done" or "finished" to decide completion. Termination is driven by the stop reason. Any iteration cap you set is a safety net, never the primary stop mechanism.
Re-Runs: Report Only What's New
CI re-runs constantly — every push retriggers the job. If the reviewer re-reports the same five issues each time, the signal drowns in noise.
On a re-run, feed the prior results back in and instruct Claude to report only new or still-unfixed issues. This keeps each comment actionable and respects that developers have already seen the earlier findings.
claude -p "Here are the issues from the previous run:
$(cat prev_review.json)
Review the current diff. Report ONLY issues that are new or remain
unfixed. Omit anything already resolved." \
--output-format json > review.jsonHeadless vs. the Batch API
Don't confuse non-interactive CLI execution with the Message Batches API. They solve different problems.
- -p / --print: synchronous, blocking, returns now — correct for a pre-merge gate where the pipeline waits on the verdict.
- Batch API: 50% cheaper, up to a 24h window, no latency SLA, and no multi-turn tool calling — correct for non-blocking overnight audits, never for a time-sensitive blocking check.
A pre-merge review must block, so use -p; reach for Batch only for offline, non-urgent jobs.
Quick Check: Wiring Up a CI Reviewer
You're adding Claude Code as a pre-merge review step in your pipeline. The job must run with no human present, return a result the next step can parse to set the check status, and avoid biased self-review of generated code. Which approach is correct?
Recap: Headless Claude Code
Key takeaways for non-interactive mode:
- -p / --print is the required flag for headless CI execution — runs the loop to completion, prints to stdout, exits.
- --output-format json (ideally with a schema) makes results parseable so the pipeline can act on them; require only always-present fields.
- Run review in an isolated, fresh session — independent review beats biased same-session self-review.
- Drive precision with explicit criteria and few-shot examples to minimize false positives.
- Apply least-privilege tools for unattended runs; on re-runs report only new/unfixed issues.
- Termination follows the stop reason, never text parsing; iteration caps are only a safety net.
- Use
-pfor blocking pre-merge gates; reserve the Batch API for non-blocking, non-urgent jobs.
자주 묻는 질문
“비대화형 모드” 강의는 무료인가요?
네 — “비대화형 모드” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Claude Architect 강의 전체를 잠금 해제할 수 있습니다. Claude Architect 강의에는 총 4개의 강의가 포함되어 있습니다.
“비대화형 모드”에서 뭘 배우나요?
헤드리스 CI 실행을 위한 -p / --print 플래그를 다룹니다 브라우저에서 직접 실행하는 실습 코드로 Claude Architect을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Claude Architect을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Claude Architect은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“비대화형 모드” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Claude Architect 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Claude Architect 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.