claude -p with output formats, schemas and caps
Drive claude -p from a script in each output format (text, json, stream-json), with --json-schema and both caps, then give the CI verdict: stop_reason first, then terminal_reason, then subtype, and with a schema, no structured_output means failure. It's the Interfaces topic's headless mode and output formats, wired the way a pipeline should use them.
- Python 3.9+
- standard library only
- offline: the recorded fixtures in
common/fixtures/
python3 core-4/headless_runner.py
┌──────────────────────────────────────────────────────┐
│ claude -p, headless · scenario explore · stream-json │
└──────────────────────────────────────────────────────┘
[1] The command (replay: this is what --real would run)
claude -p 'List the modules in tinyapp/ with one line on what each does. Read only: do not change files.' --output-format stream-json --verbose --max-turns 3 --max-budget-usd 0.1 --permission-mode dontAsk --tools Read,Grep,Glob --allowedTools Read,Grep,Glob --disallowedTools 'mcp__*' --strict-mcp-config --settings '{"disableAllHooks":true}' --no-session-persistence
[2] Consume it (stream-json)
claude -p "..." --output-format stream-json --verbose > run.jsonl
jq -c 'select(.type=="assistant") | .message.content[] | select(.type=="tool_use") | {name, input}' run.jsonl
tail -n 1 run.jsonl | jq '{stop_reason, terminal_reason, subtype, num_turns, total_cost_usd}' # the last line is the result
[init] model=claude-haiku-5-5 permissionMode=dontAsk tools=Glob,Grep,Read v2.1.303
[msg 01] text: I'll list the package modules first.
[msg 01] tool_use Glob {"pattern": "tinyapp/*.py"}
[result] ok 69 chars: tinyapp/cart.py tinyapp/__init__.py tinyapp/cli.p…
[msg 02] tool_use Read {"file_path": "/tmp/cc-lab-demo/tiny-app/tinyapp/pricing.py…
[msg 02] tool_use Read {"file_path": "/tmp/cc-lab-demo/tiny-app/tinyapp/cart.py"}
[result] ok 1184 chars: 1 """Money, tax and discount rules. All amounts a…
[result] ok 2108 chars: 1 """The cart model: line items, subtotal, discou…
[msg 03] tool_use Grep {"-n": true, "output_mode": "content", "path": "/tmp/cc-lab…
[result] ok 133 chars: 15:def parse_item(spec: str) -> tuple: 25:def rec…
[msg 04] text: tinyapp has four modules: - `pricing.py`: `money()` formatting, `tax_fo…
[result/success] stop_reason=end_turn terminal_reason=completed turns=4 cost=$0.001987
[3] Verdict
a CI step would exit: 0 (success)
[4] Summary from the result event (read num_turns and cost here, don't recompute them)
outcome: stop_reason=end_turn, terminal_reason=completed, subtype=success
turns: 4
model responses: 4 (6 assistant events)
tool calls: 4 {'Glob': 1, 'Grep': 1, 'Read': 2} errors=0
cost (estimate): $0.001987
duration: 7140 ms total, 6385 ms in the API
usage: {'input_tokens': 9, 'output_tokens': 444, 'cache_creation_input_tokens': 11614, 'cache_read_input_tokens': 31256}
- The exact command
--realwould run: the prompt right after-p,--verbose(the docs pair it with stream-json), both caps, an explicit mode and read-only tools. - The consuming side, as jq one-liners: tool calls from the
assistantlines, the verdict fields from the last line, which is theresult. - One model response, two events: each content block arrives as its own
assistantline with the samemessage.id. - The
resultline carries what the verdict needs: stop reason, terminal reason, turns and cost. - The verdict as an exit code. Add
--cito make the script itself exit with it. - Four responses, six events. Count responses by
message.id, and readnum_turnsand cost from the result rather than recomputing them.
Every recorded scenario through the same verdict:
┌──────────────────────────────────────────────────┐ │ All scenarios (replayed as --output-format json) │ └──────────────────────────────────────────────────┘ scenario fixture stop_reason terminal_reason subtype turns denials verdict why ────────────── ─────────────────── ─────────── ─────────────── ─────────────── ───── ─────── ─────── ──────────────────────────────────────────────────────────── explore explore_readonly end_turn completed success 4 0 PASS success error-recovery tool_error_recovery end_turn completed success 4 0 PASS success max-turns max_turns_stop tool_use max_turns error_max_turns 3 0 FAIL terminal_reason='max_turns' (subtype 'error_max_turns') denied permission_denied end_turn completed success 2 1 WARN success; 1 permission denial(s) (Bash): the task may be inc… structured structured_output tool_use completed success 4 0 PASS success with structured_output Read stop_reason, then terminal_reason, then subtype, and structured_output (not result) when you pass --json-schema.
- Stopped by
--max-turns:terminal_reason='max_turns'fails the step, and the result carries no answer. - The trap:
successwith a permission denial. The step passes, but the task may be incomplete, so surfacepermission_denials. - A schema run ends with
stop_reason: tool_useand still passes, because the answer is instructured_output.
--format json: the same run as one result object, with the jq lines to checkstop_reason,terminal_reason,subtypeandis_errorbefore using the answer.--format text: stdout is just the answer, and the script sees no cost or turn data; the exit status is all a text run gives you.--schema:structured_outputholds the parsed object, whileresultholds the same JSON as a string. Readstructured_output.--scenario denied: the progress lines show[denied] Bash (mode), and the verdict passes withwarning: 1 permission denial(s) (Bash).- Break it:
--scenario max-turns --ciexits 1, as a CI step would. - Break it:
--schema --scenario explore --ciexits 1 on a run that "succeeded":--json-schema was set and structured_output is missing. A script that read onlyresultwould have passed it.
Run it against your own Claude Code. It costs money, runs read-only in a temp copy of the sample repo, and is capped (--max-turns defaults to 3):
python3 core-4/headless_runner.py --real --schema --model haiku --max-budget-usd 0.05
The budget is checked against Claude Code's client-side estimate, and spend can pass the cap by up to one response, so leave headroom. A schema answer arrives through a tool call, so keep at least 2–3 turns. --max-turns 0, --max-budget-usd 0, anything over the ceilings, or no claude on PATH exits 2 before anything runs.
- Gate on
stop_reasonfirst (a refusal arrives assubtype: "success"), thenterminal_reason, thensubtype. - With
--json-schema, a success withoutstructured_outputis a failure. - A run that "succeeds" with denials did less than you asked: pre-approve what it needs, or fail on denials.
Plan or run N worktree sessions
Plan a fan-out of four parallel sessions, one git worktree each: check names, footprint overlaps, .gitignore, .worktreeinclude and the total budget, then print one claude -p --worktree command per task. With --execute it builds the worktrees in a temp git copy, applies a deterministic edit per task, merges in task order and cleans up. It's the Parallel Work topic's worktrees and multi-session hygiene, end to end.
- Python 3.9+
- standard library only
- git, for
--execute - offline:
core-4/samples/tasks.json
python3 core-4/worktree_fanout.py
┌────────────────────────────────────────┐ │ Worktree fan-out · 4 task(s) · dry run │ └────────────────────────────────────────┘ [1] Tasks (4) task worktree branch files it should touch name ────────────────────── ───────────────────────────────────────── ─────────────────────────────── ───────────────────────────────────────── ──── case-insensitive-codes .claude/worktrees/case-insensitive-codes/ worktree-case-insensitive-codes tinyapp/pricing.py, tests/test_pricing.py ok cli-json-output .claude/worktrees/cli-json-output/ worktree-cli-json-output tinyapp/cli.py ok cart-item-count .claude/worktrees/cart-item-count/ worktree-cart-item-count tinyapp/cart.py, tests/test_cart.py ok trim-codes .claude/worktrees/trim-codes/ worktree-trim-codes tinyapp/pricing.py, README.md ok [2] Footprint overlaps (split parallel tasks along file boundaries) warn case-insensitive-codes and trim-codes both touch tinyapp/pricing.py: merge one before starting the other, or narrow a footprint [3] Repository checks (common/samples/tiny-app) warn .gitignore: add `.claude/worktrees/` so worktree contents don't show as untracked files ok .worktreeinclude: no .env-style files at the root, so nothing to copy info git: not a git checkout here; --worktree needs a git repo with at least one commit info base: `claude --worktree` branches from origin's default branch by default (worktree.baseRef "fresh"); set "head" to carry unpushed commits. `git worktree add` uses your HEAD. [4] Budget per run: --max-turns 8, --max-budget-usd 0.25 (client-side estimate) worst case: 4 × $0.25 = $1.00 against your --max-total-usd $2.00 Spend can pass a cap by up to one response, so leave headroom (cli-reference, --max-budget-usd). [5] Commands (run each in its own terminal, or background them; plan mode keeps them from editing files) claude -p 'Make discount codes case-insensitive in apply_discount and add a test for a lower-case code.' --worktree case-insensitive-codes --permission-mode plan --tools Read,Grep,Glob --allowedTools Read,Grep,Glob --output-format json --max-turns 8 --max-budget-usd 0.25 > out/case-insensitive-codes.json claude -p 'Add a --json flag to the receipt CLI that prints the totals as JSON.' --worktree cli-json-output --permission-mode plan --tools Read,Grep,Glob --allowedTools Read,Grep,Glob --output-format json --max-turns 8 --max-budget-usd 0.25 > out/cli-json-output.json claude -p 'Add Cart.item_count() that returns the total quantity across lines, with a test.' --worktree cart-item-count --permission-mode plan --tools Read,Grep,Glob --allowedTools Read,Grep,Glob --output-format json --max-turns 8 --max-budget-usd 0.25 > out/cart-item-count.json claude -p 'Ignore surrounding whitespace in discount codes, and document the codes in the README.' --worktree trim-codes --permission-mode plan --tools Read,Grep,Glob --allowedTools Read,Grep,Glob --output-format json --max-turns 8 --max-budget-usd 0.25 > out/trim-codes.json Plan mode alone isn't a sandbox: with auto mode available, classifier-approved commands still run while it plans, so the commands also pin --tools and --allowedTools to Read,Grep,Glob. A plan-mode -p run can cost far more than a read-only one (about 15x in one recorded haiku run; LABS.md), so keep budget headroom. Switch to acceptEdits only for tasks you'll review; each run edits its own worktree. The same thing by hand (git creates the worktree, Claude runs inside it): git worktree add .claude/worktrees/case-insensitive-codes -b worktree-case-insensitive-codes (cd .claude/worktrees/case-insensitive-codes && claude -p 'Make discount codes case-insensitive in apply_discount and add a test for a lower-case code.' --permission-mode plan --tools Read,Grep,Glob --allowedTools Read,Grep,Glob --max-turns 8 --max-budget-usd 0.25) git worktree add .claude/worktrees/cli-json-output -b worktree-cli-json-output (cd .claude/worktrees/cli-json-output && claude -p 'Add a --json flag to the receipt CLI that prints the totals as JSON.' --permission-mode plan --tools Read,Grep,Glob --allowedTools Read,Grep,Glob --max-turns 8 --max-budget-usd 0.25) ... and 2 more [6] Cleanup (a -p run never removes its worktree) git worktree list git worktree remove .claude/worktrees/case-insensitive-codes # if git says it's locked: git worktree unlock .claude/worktrees/case-insensitive-codes git branch -d worktree-case-insensitive-codes worktree-cli-json-output worktree-cart-item-count worktree-trim-codes # after you've merged them Dry run: nothing was created. Add --execute to try it in a temp git copy.
- Each task gets
.claude/worktrees/<name>/on aworktree-<name>branch, the layoutclaude --worktree <name>uses. - The overlap check predicts a merge conflict before anything runs: split parallel tasks along file boundaries.
- A
--worktreesession branches from origin's default branch unlessworktree.baseRefis"head";git worktree adduses your HEAD. Unpushed commits aren't in the first kind. - One command per task, capped, in plan mode with read-only tools.
- Plan mode alone isn't a sandbox when auto mode is available, so the tools are pinned too. A plan-mode run can also cost far more than a read-only one.
- A
-prun never removes its worktree; the fan-out has to clean up itself.
With --execute the plan runs for real in a temp git copy (fixed author and date, so the hashes repeat):
… ┌─────────────────────────────────────────────────────────┐ │ Executing in a temp git copy of common/samples/tiny-app │ └─────────────────────────────────────────────────────────┘ [1] Create one worktree per task (what `claude --worktree <name>` does) git worktree add .claude/worktrees/case-insensitive-codes -b worktree-case-insensitive-codes git worktree add .claude/worktrees/cli-json-output -b worktree-cli-json-output git worktree add .claude/worktrees/cart-item-count -b worktree-cart-item-count git worktree add .claude/worktrees/trim-codes -b worktree-trim-codes <tmp>/tiny-app 34721b4 [main] <tmp>/tiny-app/.claude/worktrees/cart-item-count 34721b4 [worktree-cart-item-count] <tmp>/tiny-app/.claude/worktrees/case-insensitive-codes 34721b4 [worktree-case-insensitive-codes] <tmp>/tiny-app/.claude/worktrees/cli-json-output 34721b4 [worktree-cli-json-output] <tmp>/tiny-app/.claude/worktrees/trim-codes 34721b4 [worktree-trim-codes] … [3] Merge report: merge the branches into main in task order branch result conflicting files ─────────────────────────────── ──────── ────────────────────────────────────────────────────────────────────── worktree-case-insensitive-codes merged - worktree-cli-json-output merged - worktree-cart-item-count merged - worktree-trim-codes CONFLICT tinyapp/pricing.py (overlap with case-insensitive-codes was predicted) tests on main after the merges: 15 tests, OK [4] Cleanup: remove every worktree (a -p fan-out must do this itself) git worktree remove .claude/worktrees/case-insensitive-codes git worktree remove .claude/worktrees/cli-json-output git worktree remove .claude/worktrees/cart-item-count git worktree remove .claude/worktrees/trim-codes worktrees left: 0 …
- Five checkouts of one repository, all at the same commit, each on its own branch.
- The predicted conflict happens: the fourth branch conflicts in
tinyapp/pricing.py. - The other three merge and the tests pass on
main. - Every worktree removed: the step a headless fan-out can't skip.
-n 2 --json: the first two tasks only, so the overlap check printsnone: every task touches its own files; the plan is also written tocore-4/out/fanout-plan.json.- Break it:
--max-total-usd 0.5against four $0.25 runs: block [4] flagsover budgetand says what to lower. --tasks my-tasks.json --repo ~/code/appplans against your own repository, read-only.
Add one read-only claude -p per worktree to --execute. It costs money, at most N times the per-run cap, and runs in the temp copy:
python3 core-4/worktree_fanout.py --execute --real --model haiku --max-budget-usd 0.05
Each run is capped separately (--max-turns defaults to 8), the total is checked against --max-total-usd (default $2.00, at most $5), and each cap is checked against the client-side estimate, which can pass it by up to one response.
- Parallel sessions are cheap to start and expensive to merge. Predict the overlaps from footprints before you fan out, and decide the merge order up front.
- Know the base each worktree branches from, and remove every worktree a
-prun leaves behind.
Lint a claude-code-action workflow
Validate GitHub Actions workflows that run anthropics/claude-code-action against checks G001–G013: the v1 pin and removed beta inputs, unknown inputs, secrets, permissions, claude_args, PR-head checkouts under pull_request_target, who can trigger, full output in logs, and cost controls. A hardened kit to copy must pass. It's the Git and GitHub topic's GitHub Actions, as a pre-merge check.
- Python 3.9+
- standard library only
- offline: the kit in
core-4/kit/andcore-4/samples/workflows/bad-claude.yml
python3 core-4/gha_check.py
The action's input list is a snapshot of its action.yml from 2026-10-20, so no network is needed.
┌──────────────────────────────────────────────────────┐
│ claude-code-action workflow check · kit + bad sample │
└──────────────────────────────────────────────────────┘
[1] The kit (core-4/kit/.github/workflows), which must pass
core-4/kit/.github/workflows/claude-review.yml: 1 claude-code-action step(s), clean
core-4/kit/.github/workflows/claude.yml: 1 claude-code-action step(s), clean
[2] A deliberately broken workflow (core-4/samples/workflows/bad-claude.yml)
core-4/samples/workflows/bad-claude.yml: 1 claude-code-action step(s), 9 error(s), 8 warning(s)
check level where finding
───── ───── ─────────────────────── ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
G001 error jobs.claude.steps[1] anthropics/claude-code-action@beta: @beta is the pre-v1 interface; use @v1
G002 error jobs.claude.steps[1] `mode` was removed in v1; use nothing: the action detects interactive vs automation mode itself
G002 error jobs.claude.steps[1] `direct_prompt` was removed in v1; use prompt
G002 error jobs.claude.steps[1] `model` was removed in v1; use claude_args: --model
G002 error jobs.claude.steps[1] `max_turns` was removed in v1; use claude_args: --max-turns
G002 error jobs.claude.steps[1] `allowed_tools` was removed in v1; use claude_args: --allowedTools
G003 warn jobs.claude.steps[1] `sticky_comment` isn't an input of the action (did you mean use_sticky_comment?)
G004 error jobs.claude.steps[1] `anthropic_api_key` is a literal value; store it as a GitHub secret and pass ${{ secrets.NAME }}
G005 warn jobs.claude.permissions no permissions block: the token gets the repository default; grant only what the job needs
G008 error jobs.claude.steps[1] --dangerously-skip-permissions in claude_args: never skip permission checks on a runner that holds secrets and can push
G008 warn jobs.claude.steps[1] no --max-turns in claude_args: cap iterations per run
G008 warn jobs.claude.steps[1] --allowedTools grants all of Bash; list the commands the job needs, e.g. Bash(npm test *)
G009 error jobs.claude.steps[0] checks out the PR head into the workspace root before the action; check out the base ref, put the head in a subdirectory, pass --add-dir
G009 warn on pull_request_target/workflow_run run with the base repository's secrets; keep permissions minimal
G010 warn jobs.claude.steps[1] allowed_bots: '*' lets any bot trigger runs; on public repos external Apps may invoke the action with prompts they control
G011 warn jobs.claude.steps[1] show_full_output prints every message, including tool results that may hold secrets, to the (possibly public) run log
G012 warn jobs.claude no timeout-minutes: set a job timeout to stop runaway runs
G012 info jobs.claude no concurrency group: parallel runs on one PR can pile up
why: https://code.claude.com/docs/en/github-actions ; https://code.claude.com/docs/en/github-actions#manage-costs ; https://code.claude.com/docs/en/github-actions#protect-your-credentials ; https://code.claude.com/docs/en/github-actions#upgrade-from-beta ; https://code.claude.com/docs/en/permissions ; https://github.com/anthropics/claude-code-action/blob/main/action.yml ; https://github.com/anthropics/claude-code-action/blob/main/docs/migration-guide.md ; https://github.com/anthropics/claude-code-action/blob/main/docs/security.md
[3] Install the kit into your repo
mkdir -p <repo>/.github/workflows && cp core-4/kit/.github/workflows/claude.yml <repo>/.github/workflows/
# optional automatic PR review: also copy claude-review.yml
Then install the Claude GitHub App (https://github.com/apps/claude) and add the repository secret
ANTHROPIC_API_KEY (or CLAUDE_CODE_OAUTH_TOKEN from `claude setup-token`, and switch the input name).
Or run /install-github-app in Claude Code to do all three (github.com only).
Edit --allowedTools in claude_args to the commands your project needs before you commit it.
kit: 2 file(s) clean · bad sample: 9 error(s)
- The kit passes:
claude.ymlfor@claudementions andclaude-review.ymlfor automatic PR review. - A beta-era workflow:
@betaand five inputs that v1 removed, each with its v1 replacement. - An API key written into the file. Store it as a secret and pass
${{ secrets.NAME }}. - Never on a runner that holds secrets and can push.
- Under
pull_request_targetthe job has the base repository's secrets, and this one checks out untrusted PR code into the workspace root before the action runs. - No cost controls: no
--max-turnsand no jobtimeout-minutes.
--path core-4/kit/.github/workflows/claude.yml --strict: one file,clean, exit 0.- Break it:
--path core-4/samples/workflows/bad-claude.yml --strictexits 1 on its 9 errors. That's the CI form for your own workflow files. - Install the kit:
mkdir -p <repo>/.github/workflows && cp core-4/kit/.github/workflows/claude.yml <repo>/.github/workflows/, then edit--allowedToolsinclaude_argsto the commands your project needs before you commit it.
- A CI runner holds secrets and can push, so permissions, triggers and who can start a run matter more than the prompt.
- Cost controls belong in the workflow:
--max-turnsinclaude_args, a jobtimeout-minutes, and aconcurrencygroup.