Skip to content

Build a Commit Reviewer

Goal: Build a 20-line shell script that pipes a diff into claude-p, extracts structured review text and token usage from --output-format json, and distinguishes model errors from wrapper failures using exit codes.

Time: 10 minutes. You need claude, jq, and claude-p on $PATH.


The problem with piping to interactive claude

Section titled “The problem with piping to interactive claude”

Suppose you try to script interactive claude directly with a pipe:

Terminal window
echo "Review this diff" | claude

It fails immediately. Claude Code renders its UI with Ink, and Ink refuses to run when stdin is not a TTY. Even if you wrap it with script(1), Ink still emits terminal queries at boot and waits forever for replies—and you have no clean way to know when the assistant finished answering.

STAGE 1 · BOOT PTY + FIFO Open events.fifo first, spawn claude, reply to 5 DEC probes + modals. STAGE 2 · SUBMIT SessionStart Wait for quiescence, bracketed-paste prompt, verify UserPromptSubmit. STAGE 3 · RUN Tail & Wait Stream JSONL lines via pread() as flushed until Stop arrives on FIFO. STAGE 4 · EMIT Result + Reap Parse offset slice, emit text/json/result, kill child, remove temp dir.
Every one-shot invocation walks through four deterministic stages. No screen scraping is ever used to decide whether the assistant finished.

Instead of stuffing a multi-line diff into shell quotes (and risking ARG_MAX limits), feed the prompt on stdin. When claude-p sees no positional PROMPT and no --input-file, it reads stdin up to 16 MiB and trims trailing \r\n.

Run this in any repository:

Terminal window
{
printf 'Review the following diff for bugs. Reply in 3 bullet points max.\n\n'
git diff HEAD~1 2>/dev/null || printf '+ const x = 1 / 0;\n'
} | npx claude-p --disallowedTools Bash Edit Write

You should see a plain-text review printed to stdout and exit code 0. A text-only review needs no tools, so --disallowedTools denies shell and file writes instead of granting everything with --dangerously-skip-permissions. If Claude still asks for a permission, claude-p fails fast with exit 2 (PermissionPromptBlocked) rather than hanging.


Plain text is great for humans, awkward for scripts. Ask claude-p for the JSON result envelope instead, and combine it with --system-prompt to keep the review tight (--max-turns is print-mode-only, so claude-p rejects it):

Terminal window
REVIEW_JSON=$(
printf 'Spot any bug in this code:\n\nfunction div(a, b) { return a / b; }\n' \
| npx claude-p \
--output-format json \
--system-prompt "You are a terse code reviewer. No preamble."
)
printf '%s\n' "$REVIEW_JSON" | jq '{
subtype,
is_error,
duration_ms,
input_tokens: .usage.input_tokens,
output_tokens: .usage.output_tokens,
result
}'

Inspect the fields jq prints:

  • result: the final assistant text (exact same string text mode prints).
  • session_id: the Claude Code session UUID—save this if you want to --resume the review later.
  • duration_ms: wall-clock milliseconds from driver.run() entry until Stop fired.
  • usage: summed input_tokens, output_tokens, cache_read_input_tokens, and cache_creation_input_tokens across every assistant turn in the run.

Step 3: Try live streaming (and hit the guard rail on purpose)

Section titled “Step 3: Try live streaming (and hit the guard rail on purpose)”

What if a review runs tools and takes 20 seconds? You want to see progress as messages arrive. Try running stream-json by itself first:

Terminal window
npx claude-p --output-format stream-json "Reply with OK."
Error: --output-format=stream-json requires --verbose

Now add --verbose and watch each JSONL frame arrive:

Terminal window
npx claude-p \
--output-format stream-json \
--verbose \
"Reply with the single word OK." | jq -c '{type, subtype}'

Notice the last line is always {"type":"result","subtype":"success"}—the exact same result object you parsed in Step 2.


claude-p separates model errors from wrapper errors so your scripts never confuse a bad prompt or timeout with a normal assistant answer:

Exit code What failed How your script should react
0 Nothing (is_error: false) Parse stdout and continue.
1 Assistant returned is_error: true Surface .result to the caller; do not retry blindly.
2 Bad or rejected flags (including print-only --max-turns), empty prompt, PermissionPromptBlocked, PromptNotAccepted, PromptTruncated, TranscriptUnavailable, InvalidExtraSettings, InvalidCwd, UnexpectedStartupDialog, or spawn error Read stderr (or rerun with --debug; stderr omits screen contents unless --debug or CLAUDE_P_DEBUG_SCREEN=1).
124 Timed out (SessionStartTimeout, StopTimeout, or TranscriptStalled) Raise --timeout or --transcript-idle-timeout, or retry with a smaller prompt.
128 + sig Interrupted: 130 for SIGINT, 143 for SIGTERM, 129 for SIGHUP. The native binary sets this code after cleaning up; a duplicate signal within 2 s is ignored so cleanup finishes. Stop cleanly.

Step 5: Put it together in review-commit.sh

Section titled “Step 5: Put it together in review-commit.sh”

Save this script and mark it executable (chmod +x review-commit.sh):

#!/usr/bin/env bash
set -euo pipefail
DIFF="$(git diff HEAD~1)"
if [ -z "$DIFF" ]; then
echo "No diff against HEAD~1." >&2
exit 0
fi
TMP_PROMPT="$(mktemp)"
trap 'rm -f "$TMP_PROMPT"' EXIT
{
printf 'Review this diff. List concrete bugs or edge cases only.\n\n'
printf '%s\n' "$DIFF"
} > "$TMP_PROMPT"
set +e
OUT="$(npx claude-p \
--output-format json \
--input-file "$TMP_PROMPT" \
--timeout 120 \
--disallowedTools Bash Edit Write)"
CODE=$?
set -e
case "$CODE" in
0)
printf '%s\n' "$OUT" | jq -r '.result'
printf '\n[session=%s tokens=%s/%s ms=%s]\n' \
"$(printf '%s\n' "$OUT" | jq -r '.session_id')" \
"$(printf '%s\n' "$OUT" | jq -r '.usage.input_tokens')" \
"$(printf '%s\n' "$OUT" | jq -r '.usage.output_tokens')" \
"$(printf '%s\n' "$OUT" | jq -r '.duration_ms')" >&2
;;
1)
echo "Model reported an error:" >&2
printf '%s\n' "$OUT" | jq -r '.result' >&2
exit 1
;;
*)
echo "claude-p wrapper failed (exit $CODE). Re-run with --debug." >&2
exit "$CODE"
;;
esac

Notice we used --input-file "$TMP_PROMPT" instead of passing $DIFF as a CLI argument—that avoids shell quoting hazards and kernel ARG_MAX caps on large diffs.


Sharpen your pencil: predict the exit code

What happens when you run these three commands? Predict the exit code before expanding the answer.

  1. npx claude-p —output-format stream-json “Reply OK.”
  2. npx claude-p —bare “Reply OK.”
  3. npx claude-p —timeout 1 “Write a 5,000-word essay.”
Check your answer
  1. Exit 2 (StreamJsonRequiresVerbose): one-shot stream-json requires —verbose.
  2. Exit 2 (UnsupportedFlag): Claude Code 2.1 skips —settings hooks under —bare and —safe-mode, so claude-p rejects both up front.
  3. Exit 124 (SessionStartTimeout or StopTimeout): every one-shot timeout maps to 124, matching GNU timeout(1).

Q: Why doesn’t claude-p just pass my prompt as a CLI argument to claude "hello"? A: Passing a prompt on argv bypasses SessionStart, leaves you exposed to shell quoting and ARG_MAX limits on large diffs, and can race with Claude Code 2.1 startup modals (trust / bypass-permissions). Waiting for SessionStart and pasting through the PTY lets claude-p dismiss modals first and verify exact delivery via UserPromptSubmit.

Q: Does claude-p edit my ~/.claude/settings.json to install hooks? A: No. Every run passes inline --settings '<json>' on the child argv and places hook.sh and events.fifo inside $TMPDIR/claude-p-<pid>-<rand>/, which is removed when the process exits.

Q: Can I still attach my own hooks if --settings is reserved? A: Yes. Pass --extra-hook 'PreToolUse=my-check.sh' (repeatable) or --setting-json '{"cleanupPeriodDays":7}'. claude-p merges them into the generated --settings while keeping its own relay hooks at index 0.