Claude Code Headless Mode and GitHub Actions CI

📚 Exam guide v1.1 (exams from 7 Dec 2026)🔄 Checked against official sources: 24 Nov 2026⏱️ 7 min read🎯 D3 Claude Code Operation · D2 Configuration and SDLC Integration

👋 In plain words: In CI there is nobody to click “approve”, so Claude Code runs headless: one command in, one result out, with exactly the tools you allow. This lesson builds a pull-request test-review step that runs Claude Code headless, reads its JSON result in Python, and plugs into GitHub Actions, one step at a time.

Advertisement

Automated reviews, test-gap reports and failure triage on every pull request are where Claude Code pays off for QA teams. In this lesson you will run claude -p with JSON output, restrict tools and turns for a safe CI run, parse the result in a Python gate script that can fail the build, and wire it into GitHub Actions, both with the official claude-code-action and with a plain CLI step, keeping the API key in repository secrets.

📖 What You’ll Learn: You will be able to run Claude Code headless with controlled tools, turns and output format, parse its JSON result, gate a pipeline on it, and configure GitHub Actions securely.

🔑 Key terms

  • Headless (print) mode: claude -p "prompt": one prompt, no interactive interface, result on stdout.
  • –output-format: text (default), json (one result object) or stream-json (one JSON event per line).
  • –allowedTools / –disallowedTools: which tools may run without approval in this run.
  • –max-turns: a limit on agent turns for the run.
  • Repository secret: an encrypted CI variable, such as ANTHROPIC_API_KEY, never written in the workflow file.

🪜 Step 1: Prepare the input

A CI review usually starts from the pull request’s diff. Here a saved diff stands in for git diff origin/main...HEAD:

📄 pr.diff

--- a/tests/test_cart.py
+++ b/tests/test_cart.py
@@
+def test_add_item():
+    cart = Cart()
+    cart.add("SKU-1")
+    time.sleep(5)
+    assert cart

📄 CLAUDE.md

# Test review rules
- Flag time.sleep() in tests (use explicit waits).
- Flag assertions that cannot fail, such as `assert cart`.

🪜 Step 2: Run Claude Code headless with JSON output

⌨️ Terminal

claude -p "Review the test changes in pr.diff against CLAUDE.md" --output-format json --allowedTools Read --max-turns 3 --model claude-opus-5-5
  • --allowedTools Read lets the run read files and nothing else: no edits, no shell.
  • --max-turns 3 caps the agent loop.
  • --model pins the model so a default change cannot alter CI behaviour.
  • --output-format json returns a single JSON object with the result text plus metadata.
Advertisement

🪜 Step 3: Parse the result in a gate script

CI needs a pass/fail decision. This script runs the command, reads the JSON, prints a summary and exits non-zero when the review finds blocking issues:

📄 review_gate.py

import json
import subprocess
import sys

cmd = ["claude", "-p",
       "Review the test changes in pr.diff against CLAUDE.md. Start your answer with BLOCKING or OK.",
       "--output-format", "json", "--allowedTools", "Read", "--max-turns", "3", "--model", "claude-opus-5-5"]
proc = subprocess.run(cmd, capture_output=True, text=True, stdin=subprocess.DEVNULL, timeout=600)
data = json.loads(proc.stdout)

print("subtype   :", data["subtype"])
print("is_error  :", data["is_error"])
print("turns     :", data["num_turns"])
print("session id:", data["session_id"][:8] + "…")
print("review    :", data["result"])

if data["is_error"] or data["result"].startswith("BLOCKING"):
    sys.exit(1)  # fail the CI job

⌨️ Terminal

python review_gate.py

🖥️ Output (sample run)

subtype   : success
is_error  : False
turns     : 2
session id: b0f8404d…
review    : BLOCKING: tests/test_cart.py::test_add_item uses time.sleep(5) (replace with an explicit wait or remove it) and `assert cart` cannot fail; assert the item count instead.
  • The exit code 1 here is deliberate: it is how the script fails the pipeline.
  • total_cost_usd and usage are also in the JSON. Log them to track CI spend.
  • Asking for a fixed first word (BLOCKING/OK) makes the decision easy to parse. For richer data, ask for JSON in the result and validate it (Lesson 22).
⚠️ Watch out: A headless run never asks for permission. Anything not covered by --allowedTools (or settings) is simply denied, so a review that needs to run pytest must allow exactly that, for example --allowedTools "Read,Bash(pytest:*)". Never use bypassPermissions on a CI runner that has secrets.
Advertisement

🪜 Step 4: Use the official GitHub Action

Anthropic publishes anthropics/claude-code-action. Store your key as a repository secret (Settings → Secrets and variables → Actions → ANTHROPIC_API_KEY), then:

📄 .github/workflows/claude-test-review.yml

name: claude-test-review
on:
  pull_request:
    paths: ["tests/**"]
permissions:
  contents: read
  pull-requests: write
jobs:
  review:
    runs-on: ubuntu-latest
    timeout-minutes: 15
    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 the changed test files in this pull request against CLAUDE.md.
            Comment on flakiness risks, weak assertions and missing negative cases.
          claude_args: "--max-turns 5 --model claude-opus-5-5"
  • paths limits runs to pull requests that touch tests, which controls cost.
  • permissions gives the job only what it needs: read the code, write PR comments.
  • The action can also respond to @claude mentions in PR comments; running /install-github-app in Claude Code helps set up the GitHub app and secrets.

🪜 Step 5: Or call the CLI directly

If you need full control, install Claude Code in the job and run your own gate script:

📄 .github/workflows/claude-gate.yml

name: claude-gate
on: [pull_request]
jobs:
  gate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with: {fetch-depth: 0}
      - uses: actions/setup-node@v4
        with: {node-version: "22"}
      - run: npm install -g @anthropic-ai/claude-code
      - run: git diff origin/${{ github.base_ref }}...HEAD > pr.diff
      - run: python review_gate.py
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}

🪜 Step 6: Make CI runs safe and predictable

  1. Pin the model and the action/CLI version.
  2. Restrict tools to the minimum; prefer read-only for reviews.
  3. Limit turns and job time; log cost per run.
  4. Protect secrets: keys only in CI secrets; for pull requests from forks, remember that secrets are not available by default, and do not weaken that.
  5. Treat PR content as untrusted: a malicious pull request can contain instructions aimed at the reviewer. Keep the CI agent read-only and let humans make merge decisions.
  6. Version the configuration: CLAUDE.md, .claude/settings.json and the workflow files go through code review.
🎯 Exam focus: CI scenarios test: headless flags (-p, --output-format json, --allowedTools, --max-turns, --model), where the key lives (secrets, never the workflow file), and least privilege (read-only reviews, no bypass mode). A run that “hangs waiting for approval” in CI means a needed tool was not allowed; the fix is to allow exactly that tool, not to bypass permissions.

🌍 Real-world example: Ravi’s PR gate

Ravi’s team added the review gate to pull requests that touch tests/. In the first month it flagged 41 time.sleep() calls and 12 assertions that could never fail. The job is read-only, pinned to one model, limited to 5 turns, and costs a few cents per pull request, which the team tracks from total_cost_usd in the logs.

Advertisement

🧪 Practice Questions

Question 1. A CI job runs claude -p to fix lint errors, but it ends without making changes; the JSON shows permission denials for Edit. What is the correct fix?

  • A. Use bypassPermissions on the shared CI runner
  • B. Allow exactly the tools the task needs, for example –allowedTools “Read,Edit”
  • C. Remove –max-turns
  • D. Switch to interactive mode
Show answer

Answer: B. Headless runs deny tools that are not allowed. Allow the minimum set instead of disabling checks.

Question 2. Where should the Anthropic API key for a GitHub Actions workflow live?

  • A. In the workflow YAML
  • B. In CLAUDE.md
  • C. In an encrypted repository or organisation secret referenced as ${{ secrets.ANTHROPIC_API_KEY }}
  • D. In the pull request description
Show answer

Answer: C. Secrets keep the key out of the repository and logs.

Question 3. Which two flags make a headless Claude Code run more predictable in CI? (Choose 2.)

  • A. –model with a pinned model ID
  • B. –dangerously-skip-everything
  • C. –max-turns with a small limit
  • D. –verbose only
Show answer

Answer: A and C. A pinned model avoids silent behaviour changes, and a turn limit bounds runtime and cost.

Question 4. A pull request from an outside contributor contains a comment instructing the review bot to approve and merge. What design keeps this safe?

  • A. The CI agent is read-only and humans decide merges
  • B. The bot has merge permissions but a strong system prompt
  • C. Secrets are exposed to forks so the bot can run
  • D. The bot ignores all comments
Show answer

Answer: A. PR content is untrusted. Without write or merge permissions, injected instructions cannot cause harm.

📝 Assignment

  1. Task 1: Run claude -p with --output-format json on one of your repositories and print result, num_turns and total_cost_usd.
    ✅ Done when: your script prints all three.
  2. Task 2: Add the claude-test-review.yml workflow to a test repository with your key in secrets.
    ✅ Done when: a pull request that touches tests/ gets a review comment.
  3. Stretch: Make the gate script ask for JSON findings (file, line, issue, severity), validate them with Pydantic, and fail only on severity high.
    ✅ Done when: a low-severity finding passes and a high-severity one fails the job.
Advertisement

❓ Frequently Asked Questions

🤔 How do I run Claude Code in CI?

Use headless mode: claude -p "…" with --output-format json, the minimum --allowedTools, --max-turns and a pinned --model, and provide the API key from CI secrets. Or use anthropics/claude-code-action.

🤔 What does –output-format json return?

A single JSON object with the result text and metadata such as subtype, is_error, num_turns, session_id, total_cost_usd and usage.

🤔 How do I stop Claude Code in CI from changing files?

Allow only read tools (for example --allowedTools Read), and add deny rules or hooks for anything sensitive.

🤔 Can Claude Code respond to comments on GitHub pull requests?

Yes. With the GitHub app and claude-code-action, it can respond to @claude mentions in issues and pull requests.

🏁 Summary

  • claude -p runs one prompt headless; --output-format json gives a parseable result.
  • Control runs with --allowedTools, --max-turns and --model; never bypass permissions on CI.
  • A small Python gate script turns the result into a pass/fail exit code.
  • Use anthropics/claude-code-action@v1 or a plain CLI step, with the key in secrets.
  • Treat PR content as untrusted: keep CI agents read-only and humans in charge of merges.
📝 Test yourself: D3 Claude Code practice test (20 random questions, 20 minutes), or browse all CCDV-F mock tests (3 full 70-question exams and 8 domain practice tests, with explanations).

Next, continue with Claude Model Versioning: Pinning, Tiers and Release Planning.

🎬 Prefer video? Watch QA, automation and AI testing tutorials on the SQA Tools YouTube channel.

Independent study material by SQA Tools. Not affiliated with, endorsed by or sponsored by Anthropic. Claude is a trademark of Anthropic. Practice questions are original, not real exam content. Code outputs marked “sample run” come from running the exact code against a local stand-in for the Claude API, so real replies, IDs and token counts will differ. Exam facts checked against Anthropic’s official CCDV-F exam guide v1.1 on 24 Nov 2026.