By Abhijith N M · Reviewed 24 October 2026 · Editorial standards
A team added a pull-request reviewer to its pipeline. The job ran claude -p 'review this diff' and grepped the text for the phrase no issues found. For two weeks it passed every pull request, including one that deleted an authentication check.
The run had failed. The model replied that it could read only part of the diff, so the phrase never appeared. The grep matched nothing, the script treated an empty match as approval, and the gate failed open.
Two bugs made that possible. The script parsed prose, and it treated an unknown outcome as a pass. A headless run gives you the tools to fix both.
Plain text. The default output format is text, so the script has to parse a sentence written for a person. That is the failure this lesson removes.
-p turns a session into a command-p, or --print, runs one non-interactive session, prints the result and exits. The exit code is 0 on success and non-zero when the run fails, so a pipeline can branch on it before parsing anything.
| Flag | What it does | Why a pipeline needs it |
|---|---|---|
-p or --print | Runs without the terminal interface | Nothing waits for a person |
--output-format json | One JSON object with the result, session id, cost and usage | A field you can parse, not a sentence |
--output-format stream-json | One JSON object per line, as the run happens | Progress and partial text |
--json-schema | Constrains the answer to a JSON Schema | A shape your code can validate |
--allowedTools | Pre-approves the named tools | The run does not stop on a prompt |
--permission-mode | Sets the baseline for the whole run | dontAsk denies anything that would prompt |
--bare | Skips discovery of hooks, skills, MCP servers and memory | A fast run that cannot inherit a repository hook |
Branch on the exit code before you parse anything. A non-zero exit means the run failed, and the JSON body can still carry a message that explains why. Log the whole object, then fail the job.
Two flags make a pipeline run predictable. --append-system-prompt adds an instruction without replacing Claude Code's own prompt, so a review job can say what to look for and keep the normal tool behaviour. --allowedTools pre-approves the tools the job needs, so the run does not stall on a prompt it cannot answer.
A session id comes back in the JSON. Pass it to --resume to continue that exact conversation, or use --continue for the most recent one. That is how a job adds a second review pass without sending the diff again.
--json-schema works with --output-format json. The answer arrives in structured_output, and the metadata sits beside it. A schema keyword such as format is treated as a note, not as a check.
claude -p "Review the diff on stdin. List only blocking findings." \
--output-format json \
--json-schema '{
"type": "object",
"properties": {
"blocking": {"type": "boolean"},
"findings": {
"type": "array",
"items": {
"type": "object",
"properties": {
"file": {"type": "string"},
"line": {"type": "integer"},
"reason": {"type": "string"}
},
"required": ["file", "line", "reason"]
}
}
},
"required": ["blocking", "findings"]
}' < diff.txtThe schema is the contract between the agent and your pipeline. Keep it small, mark the fields your code depends on as required, and use closed sets where the answer is a decision rather than prose.
Pass the diff on stdin, as the example does. Piped input has a cap, and it is generous for a diff. For a large input, write it to a file and name the path in the prompt instead of piping it.
A run can end without a valid answer. The model may decline, the schema may not be satisfied, or the process may fail. A missing structured_output is a possible outcome, not a defect.
import json
# What one `claude -p ... --output-format json` run printed, trimmed to the
# fields a gate reads. The answer lives in structured_output.
STDOUT = '''{
"type": "result",
"is_error": false,
"session_id": "9f3c1a",
"structured_output": {
"blocking": true,
"findings": [
{"file": "src/auth.py", "line": 88, "reason": "Drops the token expiry check"},
{"file": "src/session.py", "line": 12, "reason": "Reads the token without validating it"}
]
}
}'''
def gate(stdout: str) -> tuple[str, list[str]]:
try:
payload = json.loads(stdout)
except json.JSONDecodeError:
return "fail", ["the run did not print JSON"]
if payload.get("is_error"):
return "fail", ["the run reported an error"]
review = payload.get("structured_output")
if not isinstance(review, dict):
return "fail", ["no structured_output, so nothing was reviewed"]
if review.get("blocking"):
return "fail", [
f"{item['file']}:{item['line']} {item['reason']}"
for item in review["findings"]
]
return "pass", []
verdict, reasons = gate(STDOUT)
print(verdict, len(reasons))The gate fails closed on three states: no JSON, a reported error, and a missing structured_output. Only a well-formed review with blocking: false passes. That is the difference between a parser and a guard.
Use --output-format stream-json when a person is watching the run or when you need partial text. Add --verbose and --include-partial-messages to receive token deltas.
claude -p "Write the migration notes for this release" \
--output-format stream-json --verbose --include-partial-messages \
| jq -rj 'select(.type == "stream_event" and .event.delta.type? == "text_delta") | .event.delta.text'Every line is a complete JSON object, so parse line by line and never buffer the whole stream into one json.loads. Do not assume the last line is the answer either: a message from a background task can arrive after the result and start another turn. Keep the last object whose type is result.
A headless run is a real session, with a transcript on disk. The id comes back in the JSON, and --resume continues that conversation by id. --continue picks the most recent one for the directory.
Inside the terminal, /clear starts a fresh context and /compact shrinks the current one. Resuming replays the transcript, so a resumed run pays for the history it reloads.
Treat the session id as state your pipeline owns. Write it to the job's output, pass it to the second stage, and never guess which conversation is current.
claude -p command that returns JSON against a schema you define.structured_output from the payload and confirm your script fails.jq, so you can see where the result sits in the stream.--bare and note which hooks, skills and servers stopped loading.Key takeaways
-p runs one non-interactive session, and the exit code tells you whether it succeeded.
--output-format json gives fields; --json-schema gives a shape in structured_output.
Treat a missing structured_output as a failure, never as an empty success.
stream-json prints one event per line; match on type and expect messages after the result.
--resume and --continue reuse a session by id; /clear and /compact manage the context you reload.
A -p run inherits the repository's hooks and servers, so use --bare when it should not.
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.
Don't lose this lesson
Create a free account to save your progress, keep your streak, and work toward a shareable certificate.