Claude Code & Context Engineering

Claude Code in CI: Headless Mode, Automated Code Review and Guardrails That Hold

15 November 2026 · Updated 28 November 2026 · 13 min read · by Yang Kai

Run Claude Code in CI properly, per Anthropic's official docs: headless mode flags, the official GitHub Action for automated review, cost caps, and a copyable workflow with a guardrail checklist.

Checklist inside: Example CI workflow plus guardrail checklist

Contents
  1. What you need before you start
  2. Headless mode: what changes when nobody is watching
  3. The official GitHub Action
  4. Workflow 1: automatic PR review with the official Action
  5. Workflow 2: headless CLI in any CI system
  6. Choosing triggers: every PR, labelled PRs, or on mention
  7. The three CI jobs actually worth running
  8. The guardrail checklist
  9. CI guardrail checklist
  10. Cost and failure honesty
  11. Common failures and their fixes
  12. Verdict

Claude Code can run in continuous integration with no human at the terminal — but CI removes the safety net interactive use relies on: you, reading each permission prompt before it runs.

So everything you normally approve by hand has to be decided in advance, in configuration. This guide walks through that advance work using Anthropic’s official documentation, checked November 2026: headless mode and its flags, the official GitHub Action, two copyable workflows, and the guardrails that keep an unattended agent advisory instead of dangerous.

Quick answer: run claude -p with a complete prompt, a restricted tool set, a turn cap and a budget cap — or skip the plumbing and use Anthropic’s official anthropics/claude-code-action@v1, which does the same thing inside GitHub Actions.

If your interactive setup is still loose, tighten it first with a deliberate permissions and sandboxing policy; CI is where a sloppy policy stops being an inconvenience and becomes an incident.

What you need before you start

Headless mode: what changes when nobody is watching

Add -p (long form --print) to any claude command and it runs non-interactively: one prompt in, the full agent loop runs once, the result prints to standard output, and the process exits with a status code your script can branch on.

There is no conversation, no follow-up question, no “did you mean…?” That constraint is a feature: it forces the prompt to be a complete brief — the task, the boundaries, the output format, the stopping condition. The discipline is identical to writing subagent briefs that get used, with added stakes: a vague brief in CI does not produce a confused question, it produces a confused pull request.

Headless mode also reads stdin, so it composes like a Unix filter — pipe a diff or a build log in, get an answer out.

The flags that matter in CI

Flag What it does
--output-format json Emits one JSON object with the result text, session ID and total_cost_usd — parse it with jq and track spend per run
--max-turns N Stops the run after N agentic turns instead of iterating until the job times out
--max-budget-usd N Stops the run when the client-side cost estimate reaches the amount; subagent spend counts toward it
--allowedTools Pre-approves exactly the tools the job needs, so nothing blocks waiting for approval
--permission-mode dontAsk Denies anything that would prompt, except what allow rules cover — the documented fit for locked-down CI
--bare Skips auto-discovery of hooks, skills, plugins, MCP servers, memory and CLAUDE.md; Anthropic recommends it for scripted calls

Two cautions come straight from the docs. First, without --bare, a headless run loads the hooks and MCP servers configured in the repository it runs against — in CI, that means whoever wrote the branch decides what executes, so know which mode you are in. Second, --bare ignores subscription sign-in entirely, so it always needs ANTHROPIC_API_KEY.

Note: --bare also skips CLAUDE.md. For a pure scripted question that is exactly right; for a rules review, where CLAUDE.md is the rulebook, leave bare mode off and control the environment through permissions instead.

The official GitHub Action

Anthropic ships an official action, anthropics/claude-code-action@v1, that runs Claude Code on a GitHub-hosted runner so you do not have to script the install yourself. The guided setup is /install-github-app inside Claude Code: it installs the Claude GitHub app, stores the secret, and opens a pull request containing the workflow.

The action has two modes:

Before a run starts, the action checks that the person who triggered it has write access to the repository, and it turns bots away unless they are listed in allowed_bots. Authentication accepts either anthropic_api_key (an API key from your secrets) or a Claude subscription OAuth token — the token route bills usage against your plan rather than per-token API rates.

CLI flags pass through the claude_args input, which is where your caps live in the Action route: claude_args: "--max-turns 10 --model claude-sonnet-5" is the documented pattern.

Watch out: the Claude GitHub app’s permissions are broad — read and write across contents, issues, pull requests, checks and workflows — because one app serves several Claude features. Grant it to repositories deliberately, not organisation-wide by default.

Workflow 1: automatic PR review with the official Action

This workflow reviews every opened or updated pull request against the rules in the repository’s CLAUDE.md and posts the result as a comment.

name: claude-review
on:
  pull_request:
    types: [opened, synchronize]
permissions:
  contents: read
  pull-requests: write   # comment only; no merge rights
  issues: write
jobs:
  review:
    runs-on: ubuntu-latest
    timeout-minutes: 15   # hard ceiling, not a hope
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
      - uses: anthropics/claude-code-action@v1
        with:
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
          prompt: |
            Review this pull request against the rules in
            CLAUDE.md. Report only: rule violations with file
            and line, and anything the definition of done
            missed. Do not edit files. If the diff is clean,
            say so in one line.
          claude_args: "--max-turns 10"

You should see the review appear as a PR comment within a few minutes of opening a pull request. If nothing appears, check the Actions log first — the usual causes are a missing secret or a trigger author without write access.

Workflow 2: headless CLI in any CI system

The raw route installs the CLI and calls it directly. It works in GitHub Actions, as below, and in any other CI that can run shell commands.

name: claude-review-cli
on:
  pull_request:
    types: [opened, synchronize]
permissions:
  contents: read
  pull-requests: write
jobs:
  review:
    runs-on: ubuntu-latest
    timeout-minutes: 15
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
      - name: Install Claude Code
        run: npm install -g @anthropic-ai/claude-code
      - name: Review against project rules
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
        run: |
          claude -p "Review this PR diff against the rules in
          CLAUDE.md. Report only rule violations with file and
          line. Do not edit files." \
          --output-format json \
          --max-turns 10 \
          --max-budget-usd 2.00 \
          --permission-mode dontAsk \
          > review.json
          jq -r '.result' review.json > review.md
      - name: Post review as comment
        run: gh pr comment ${{ github.event.pull_request.number }} --body-file review.md
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}

Pick the Action route when you live on GitHub and want the @claude mention workflow as well. Pick the CLI route when you need the same job in another CI system, or when you want the JSON cost field wired into your own reporting.

Choosing triggers: every PR, labelled PRs, or on mention

The trigger decides both cost and noise, and it is the setting teams adjust most after the first month.

Start permissive only if PR volume is low. Otherwise start with mentions, prove the reviews are worth reading, then widen the trigger.

The three CI jobs actually worth running

Automated review against your own rules. The agent reads the PR diff alongside your CLAUDE.md and flags violations of your conventions — the things generic linters cannot know: the forbidden pattern, the required file layout, the definition-of-done items. This is the highest-value CI job because it enforces project-specific knowledge at the moment it matters.

Fix-up jobs for mechanical failures. A lint failure, a formatting drift, a broken snapshot: bounded problems with a mechanical test for success. The agent proposes the fix as a commit or a follow-up PR; the test suite, not the agent, decides whether it worked.

Changelog and docs drafts. On merge or release, the agent drafts the changelog entry or the documentation diff from the actual commits. Low risk, genuinely tedious for humans, and easy to review — a good first CI job if you want to build trust gradually before allowing code changes.

What not to automate yet: autonomous feature implementation merged without human review, and anything that deploys. The agent proposes; humans and tests dispose.

The guardrail checklist

## CI guardrail checklist
[ ] Job permissions are minimal (read + comment; no merge, no deploy)
[ ] API key lives in the CI secret store, scoped, never logged
[ ] max-turns AND job timeout both set — either alone is not enough
[ ] A dollar cap (--max-budget-usd) on CLI-route jobs
[ ] Prompt states: task, boundaries, output format, stopping rule
[ ] Agent output lands as a comment/PR — never a direct merge
[ ] Tests, not the agent, judge any code the agent proposes
[ ] Bare mode chosen deliberately, knowing it skips CLAUDE.md and hooks
[ ] Cost visibility: usage checked weekly; a runaway job is a bug
[ ] CLAUDE.md in the repo is the single source of review rules

For team repositories, fold these jobs into the shared rules and review workflow your team already maintains rather than letting CI become a second, shadow policy. The hooks reference is worth a read before you rely on repo hooks in automation, since headless runs can execute them.

Cost and failure honesty

Unattended runs spend money unattended, so treat CI usage as a line item you review — the same habit optimising Claude Code costs day to day applies to interactive spend, and the cost ladder explains which plan or API route a CI job should draw from.

Per-run figures are deliberately not quoted here: they depend on your diff sizes, model choice and billing route, and a number from someone else’s repository would mislead yours. The JSON output’s total_cost_usd field exists precisely so you can measure your own first twenty runs, then decide whether the review job runs on every PR or only on labelled ones.

Failures deserve the same honesty. A headless agent will sometimes produce a confident, wrong review. That is tolerable precisely because the design keeps it advisory: it comments, humans decide, tests arbitrate. The moment an agent’s output can merge, deploy or delete without a human gate, the failure mode stops being a bad comment and starts being an outage — design so that day never arrives by accident.

Common failures and their fixes

Verdict

Start with the official Action in automation mode, reviewing pull requests against your CLAUDE.md, capped at 10 turns with a 15-minute timeout. It is the smallest setup that delivers the highest-value job, and every guardrail on the checklist is visible in that one file.

Graduate to fix-up jobs only after a few weeks of reviews you have read and mostly agreed with. Keep merges and deploys behind human gates permanently — that boundary is the whole design.

Current plan and feature details are maintained in the Claude Code tool profile, and the head-to-head context for why this tool earns CI trust is in Claude Code vs Codex compared.

FAQ

Can Claude Code run in GitHub Actions without a human present? Yes, two documented ways: the official anthropics/claude-code-action@v1, or the CLI in headless mode (claude -p) inside a workflow step. Both take a complete prompt, do the work, and finish without any interactive approval.

What should a Claude Code CI job never be allowed to do? Merge its own changes, deploy, or hold credentials broader than its single job. Keep it advisory or proposal-only, and let tests plus a human make the final call.

How do I stop a CI agent run from spending too much? Layer the caps: --max-turns on the invocation, --max-budget-usd on the CLI route, and a timeout on the job itself. Then read the total_cost_usd field in the JSON output weekly for the first month and narrow the trigger if costs surprise you.

What is the difference between the Action’s two modes? With no prompt input, the action is interactive: it responds to @claude mentions in issues and pull requests. With a prompt, it is automation: it runs on whatever event starts the workflow, such as a pull request opening or a schedule.

Does headless mode read my CLAUDE.md and hooks? By default, yes — a headless run loads the repository’s CLAUDE.md, hooks and MCP configuration. Adding --bare skips all of that auto-discovery; Anthropic recommends bare mode for scripted calls, but a rules review needs CLAUDE.md loaded, so choose per job.

Category: Claude Code & Context Engineering · Tags: #claude-code #automation #ai-agents #git

Next step: this article is part of Claude Code guides, which covers the full topic from first setup to advanced use.

Related guides