Integrate Claude Code into CI/CD pipelines
Learning objectives
Run a bounded noninteractive analysis, consume structured findings safely, and distinguish process completion from a valid review. Supply project context, compare repeat findings, and generate tests that add relevant coverage.
In the supplied terminology, CI expands to Continuous Integration and CLI to Command Line Interface. Those expansions identify the workflow and interface; they do not establish supported flag versions, authorization, actual process success or a completed review.
Design a noninteractive job
The supplied materials use -p, also written --print, for Claude Code's noninteractive mode. This enables a CI job to provide a prompt or input stream without opening the normal conversational interface. For example, this shell illustration supplies a build log:
claude -p "Explain the errors in this build log" < build.log > explanation.txt
The command illustrates input and output handling; it does not establish that the log was read or a run succeeded. The job must provision supported authentication, an explicit working directory, necessary configuration, a timeout, and effective permissions. Missing input should fail the intended analysis rather than silently becoming an analysis of nothing.
Noninteractive mode removes the normal conversational wait; it does not guarantee every tool or integration can run unattended. Avoid unsupported flag combinations, inspect startup failures, and prevent a tool-level approval from leaving the runner waiting indefinitely. Restrict credentials and side-effect capabilities according to the job's purpose. Tool pre-approval alone is not proof that all other tools are unavailable.
Check the process and the result
Capture the exit status, stdout, and stderr. A nonzero status is a failed invocation. A zero status is necessary for the ordinary success path but does not prove that the intended repository was reviewed, every input arrived, the findings are correct, or the output is safe to publish.
The materials describe configuration failures and runtime failures appearing in different output channels. Inspect both channels and the documented result envelope; do not rely on one string or the absence of stderr. Keep logs useful without exposing secrets. Cost fields, when available, are invocation estimates rather than a replacement for billing records. Count failed attempts and retries when measuring job consumption.
For stream output, process complete newline-delimited events and distinguish initialization, progress, and final results. An intermediate event cannot certify completion of the job. If a stream ends early, record an incomplete analysis rather than publishing a partial result as a complete review.
Parse a contract, then validate meaning
--output-format json gives a machine-readable response envelope in the described interface. --json-schema requests a specific structured payload; the materials place that payload in structured_output, distinct from ordinary result text. Check the actual supported schema and CLI interface in the deployed version. A parameter that accepts a schema string does not automatically accept a file:// reference; use its supported input form.
A schema can constrain fields and types. It cannot establish that a file exists, a line belongs to the current diff, or an alleged defect is real. Validate those properties after parsing. Do not depend on format annotations alone to enforce email or date semantics.
The supplied glossary serves as a terminology registry, anchor seed and audit dictionary; it is neither the factual primary knowledge base nor a final anchor registry. Candidate markers and preflight summaries do not establish approval. When a glossary generalization conflicts with the adopted Dxx domain material, follow that domain's factual conditions; for this workflow, D03's output/payload, format and semantic-evidence limits take precedence over broad JSON-syntax or casing guarantees.
This is an illustrative application-level result, not a complete CLI envelope:
{
"revision": "R8",
"review_status": "complete",
"findings": [
{
"id": "F1",
"file": "src/parser.py",
"line": 42,
"summary": "A null email is dereferenced before the missing-value check.",
"failure_scenario": "A record with email=null raises an exception before it can be skipped."
}
]
}
Before posting an inline comment, verify that R8 is still the reviewed head, the path and line are valid for that diff, the scenario is reproducible, and the finding has not already been reported. Reject an incomplete or mismatched result. Generating JSON and posting a comment are separate actions; the latter requires the configured authority and a valid target.
Supply shared project context
A CI checkout needs the same shared testing standards, fixtures, architecture notes, and review criteria that the workflow expects. Place broad conventions in the project's appropriate CLAUDE.md file and include its referenced resources in version control. Personal instructions on a developer's workstation do not transfer to a clean runner. The supplied glossary describes CLAUDE.md as persistent guidance for coding standards, architectural guidelines, and personal preferences across sessions, with personal preferences kept in the appropriate personal scope rather than imposed as shared project standards; persistence does not imply automatic inheritance by CI, actual loading, or compliance.
Confirm the active checkout, configuration sources, and loaded instructions. In an interactive diagnostic session, memory or context inspection can help establish what was loaded. Do not claim that adding a file forced every review to follow it. Specialized review services may have separate instruction files and configuration; treat them as distinct integrations rather than assuming every local command invokes a cloud review.
Separate writing from reviewing
A fresh review context can inspect the diff and surrounding code without inheriting the author's entire narrative. Provide the exact revision, acceptance criteria, relevant project instructions, and definition of an actionable finding. Ask for evidence and a concrete failure scenario.
In the supplied Context Isolation entry, a subagent's intermediate tool calls remain inside that worker, and only its final message returns to the parent. The parent must receive the findings, source locations and uncertainty needed for its next decision in that final return; it cannot assume unreturned intermediate evidence is available. This source-scoped context boundary is separate from checkout isolation and does not guarantee that the review was independent, accurate or complete.
Isolation can reduce a source of bias but does not guarantee a correct or independent audit. Verify candidate findings against the implementation. Inspect the actual review capability available in the environment; a slash-command-looking string in a scheduled or headless prompt is not proof that a special review service executed.
Re-review without duplicating comments
Retain prior findings with identifiers, locations, revision, and resolution status. On a new commit, compare each against the current code. Report new findings and still-unaddressed findings; suppress a duplicate only after confirming it represents the same issue. If a line moved, follow the relevant code rather than matching only the old line number.
For F1 above, suppose R9 moves the null check before the dereference. Rerun the reproducing null-input case. If it passes, record F1 as fixed with that evidence. If R9 merely renames the function while retaining the faulty order, keep F1 unresolved. A model-generated fixed label is not itself proof of repair. Inspect which deduplication or thread updates the actual integration performs automatically and which your job must manage.
Generate useful tests from existing evidence
Read the relevant existing tests and available fixtures before proposing new ones. Match their framework and assertion conventions, then identify behavior that lacks coverage. Adding another happy-path test is low value if the untested risk is null handling or a connection failure.
For a large suite, locate the relevant tests and their dependency paths, then read those artifacts. A path-specific instruction controls guidance loading; it does not automatically load test content or establish coverage. Preserve an honest account of what was examined.
Document valuable test criteria in shared instructions: observable behavior, important failures and boundaries, reusable fixtures, and the command that exercises the checks. Run the generated tests and confirm they execute the intended assertions. Do not change correct downstream behavior simply because an upstream failure produced several test failures.
Retain the exact source-scoped CLI branches
All exact flags, versions and service behavior in this section are attributed to the supplied snapshot. Its original anchor attachments were not supplied; no current CLI, SDK, hosted review or repository publication was tested.
The source describes resumable session persistence in print mode unless --no-session-persistence is explicitly selected. Choose persistence for the intended CI isolation/continuation contract; --continue is a separate context option. It rejects -p with --bg and with --cloud plus a new task description. Its different permitted branch uses an explicit existing cloud session ID to queue a follow-up and exit. Queue acceptance is not proof the remote task ran or completed.
The source formats are text (default plain response), json (one result envelope), and stream-json (one complete JSON event per line beginning with initialization). Without schema, ordinary response text is in result; with schema, the constrained payload is in structured_output, outside the root's session/usage metadata. A stream initialization or partial event is not final completion. The source example claude -p --output-format stream-json --verbose --forward-subagent-text "query" keeps forwarding with its required streaming format and verbose setting. It says --include-hook-events also requires stream-json. Do not transfer these flags to text/json without supported behavior.
Startup invalid flags/schema produce stderr diagnostics in the snapshot; described runtime authentication failures can appear in stdout as the result. Capture both streams and the status, then inspect the actual envelope/error state. The invalid-schema diagnostic is Error: --json-schema is not a valid JSON Schema. The source attributes explicit rejection and accepted-but-unenforced format annotations to v2.1.205+, and describes earlier clients silently ignoring invalid schemas or rejecting a format keyword. These are version-specific source claims, not guaranteed current behavior. Apply actual email/date validation if those values matter. Separately, the supplied Agent SDK material says an invalid JSON Schema makes the run fail at startup with an error identifying the specific schema problem. This is an attributed SDK behavior; no SDK test was executed here.
For authentication/access diagnostics or a review handoff, retain the non-secret workspace and runner/execution identity needed to match the intended checkout and revision. Only when the task needs account or credential access, retain the relevant non-secret identity or approved secret reference. Keep actual keys, tokens and passwords out of prompts, logs and handoff artifacts; use placeholders or approved references. Knowing a reference or sharing configuration does not itself authorize access or the sharing or use of credentials. If a necessary identity, approved reference or access authorization is missing or unverified, retain a blocked or incomplete state and seek the missing evidence or approval rather than silently switching accounts.
Unreadable stdin is described as warning on stderr and continuing with the command-line prompt. Before v2.1.211, Windows could reportedly crash or exit silently in this case. Prompt-only fallback does not satisfy an intended log/diff analysis. Verify the input really arrived; missing context keeps that analysis failed or incomplete even if a process continues.
The JSON total_cost_usd field and per-model breakdown are described as per-invocation USD estimates. They can differ from billing and do not prove savings or total project consumption. Include actual failed/retried invocations when measuring the intended job population.
A complete expected schema envelope
The source's ellipsis schema is incomplete. Its later full schema declares an object containing an array, even where surrounding prose calls the payload an array. Its file://schema.json samples also conflict with its schema-string description. This POSIX-shell illustration uses the stated string form, with complete JSON and required flags; it was not executed. For this exact fixture, changes.diff contains only the two added declarations below, with no other function declarations:
+def parse_count(value):
+ return value
+def classify_record(record):
+ return record
claude -p "Extract declared function names from the supplied diff; do not edit files." --output-format json --json-schema '{"type":"object","properties":{"functionNames":{"type":"array","items":{"type":"string"}}},"required":["functionNames"],"additionalProperties":false}' < changes.diff
Expected relevant envelope excerpt, omitting unrelated metadata deliberately:
{
"structured_output": {
"functionNames": ["parse_count", "classify_record"]
}
}
The consumer extracts envelope.structured_output.functionNames, checks it is an array of strings under the declared schema, and separately verifies each name against the actual reviewed diff. It is an object with an array member, not a top-level array. This does not validate private internal reasoning or factual completeness. For another shell, use its own safe quoting/process-argument API. Do not certify a file-URI mode from this source inconsistency. Source SDK outputFormat/output_format, Zod z.toJSONSchema(...,{target:"draft-7"}), Pydantic .model_json_schema() and jsonSchemaOutputFormat are separate interface-specific options requiring actual support.
The broad source --allowedTools "Bash,Edit" refactor sample illustrates preapproval, not a least-scope safe reviewer. Supplying an actual diff through stdin may avoid direct repository shell reads in a specific design, but it does not prove remaining tools cannot write. Keep the actual runner authority and effective policy.
Project and review-service context
The snapshot supports shared project guidance at root CLAUDE.md or .claude/CLAUDE.md. Include actual build/test commands, relevant architecture/workflows, available fixtures and concrete review criteria in version-controlled resources. A clean runner does not inherit a maintainer's personal home file. In a supported interactive diagnostic session, the source /context Memory files view reports loading for that session; do not invent its availability in every headless run or equate loading with compliance.
The source's review pipeline distinguishes general CLAUDE.md from higher-priority review-specific REVIEW.md. Its bundled local /code-review returns a fresh worker's findings, and /code-review ultra is a source-described deeper review surface. Hosted organizational review can be configured on PR open/push or manual request, with surrounding-code analysis and candidate verification/deduplication. These are separate configured mechanisms; ordinary headless review text does not prove one ran. In the supplied hosted review workflow, candidate findings are verified, then deduplicated and ranked by severity before inline posting. This describes the source workflow; no hosted review was executed here.
The snapshot says scheduled /code-review may arrive as plain text on Amazon Bedrock, Claude Platform on AWS, Google Cloud Agent Platform or Microsoft Foundry unless the host sets CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST; it also lists the apps gateway and privacy opt-outs DISABLE_TELEMETRY, DO_NOT_TRACK, CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC, or DISABLE_GROWTHBOOK. It says scheduled tasks never launch cloud ultra. skillOverrides can suppress automatic initiation while preserving manual availability, and v2.1.215–v2.1.222 reportedly prevented self-start in any configuration. Preserve these separate guards, actual privacy choices and missing-execution status; do not remove privacy controls as an assumed repair.
Worktree isolation concerns actual checkout bytes, not conversation history. Ensure the reviewer sees the intended diff rather than a stale independent checkout. The snapshot reports blocks on Edit/Write/NotebookEdit targeting the main checkout and Bash/PowerShell/Monitor whose cwd resolves there, extending to spawned descendants. These named checks do not establish that every external tool/path is sandboxed. Verify actual effective capabilities and the target revision.
Review history, races and reporting
In a custom rerun, supply actual prior identity/evidence/status and compare current behavior. In the source's hosted service, an actual subsequent review is described as deduplicating candidates, resolving repaired threads and updating its check with no issues detected when appropriate. A push or intended fix alone does not establish those outcomes. If a concurrent push makes a location stale, the described service withholds an inline comment while retaining findings in Check run Details and Files changed annotations. Reassess the current diff; do not publish against nonexistent coordinates. "No issues detected" describes the performed review, not absence of every possible bug.
The source ReportFindings interface is attributed to v2.1.196+. Its expected base report can be:
{
"count": 1,
"findings": [
{
"file": "src/parser.py",
"line": 42,
"summary": "Null email is dereferenced before its guard.",
"failure_scenario": "A null email raises before the skip/warning branch."
}
]
}
This expected report has count equal to array length. The snapshot requires each finding's file, summary and failure_scenario; line, short_summary and category are optional. Top-level level is optionally low/medium/high/xhigh/max. Optional verdict is CONFIRMED/PLAUSIBLE only when a real verify pass ran. Optional outcome belongs to post-fix re-reporting and is fixed/skipped/no_change_needed. Skipped is not repaired, disposition is not a verification verdict, and field presence cannot automatically deduplicate or prove resolution. No verification or repair was run for this example, so it includes neither verdict nor outcome. In that source interface, optional line is numeric; optional short_summary and category are strings. Their presence does not replace the required evidence or the stated verification/disposition guards.
The source manual review trigger is a top-level @claude review PR comment, whereas an inline reply does not start a new review. Fixing, pushing, requesting, actual review execution and returned results are separate states. Do not send a comment without the authorized repository workflow and rights; this article generated no comment or notification.
Concrete valuable-test criteria
In an invented parser project, assume the actual declared fixtures are fixtures/valid-email.json containing {"id":"R2","email":"[email protected]"} and fixtures/null-email.json containing {"id":"R1","email":null}, using pytest dictionary equality. Declare the test command python -m pytest tests/test_email_policy.py as an example project command, not an executed one. Expected complete decision objects are {"id":"R2","status":"ready","email":"[email protected]"} for the valid fixture and {"id":"R1","status":"skipped","warning":"missing_email"} for the null fixture. With source input {"id":"R3","email":""} or {"id":"R3","email":7}, expect {"id":"R3","status":"invalid","reason":"invalid_email_input"}; for {"id":"R1"}, expect the same skipped object as null. These are classification results, not successful storage writes. No live credentials are needed by these pure fixtures. A fixture not actually present in a real project is a gap, not an available resource.
Before adding tests, compare actual existing assertions for these behaviors. Another name for the same input/assertion is a duplicate; a genuinely uncovered null-dereference case adds value. For a suspected mean failure depending on add and divide, read the actual input/assertion and call path, repair only demonstrated upstream defects and rerun downstream/previously valid cases before declaring resolution. Do not weaken correct tests to hide failure.
If performance is a declared criterion, define workload, environment, metric, units, timing boundary and threshold before measurement. For example, a teaching workload of 1,000 in-memory records with a stated elapsed-millisecond threshold is a target only until measured under its declared environment. Do not invent a measured saving.
Path-scoped rules condition guidance loading; they do not select/read all relevant test content. The source's 10,000-character offload statement concerns a value/hook context and does not establish universal large-file behavior. A preview/path can require full-content retrieval for a coverage judgment. Preserve the exact examined versus missing bytes.
Specifically, the source uses paths frontmatter in .claude/rules/ to limit an instruction rule to matching file patterns. This is rule-loading scope, not automatic selection or actual reading of the corresponding test contents.
Finally, the source reports an anecdote of "Credentials generated successfully!" despite failed builds and other confidence-calibration concerns. These are unverified reports here, not reproduced universal defects. Actual credential validity, build/test output and applicable end-to-end checks determine checked completion. Strict written standards and model assurance cannot overwrite a failed or absent check.
A concrete review target and repair
For this separate teaching fixture, the caller supplies a string id but has no email guard. Missing/null email must skip with a warning; a nonempty string remains unchanged; other types and empty text are invalid. These are complete local functions, not code claimed to exist at the illustrative report's src/parser.py line 42:
def faulty_review_target(record):
record_id = record["id"]
email = record.get("email")
if email.lower() == "":
return {"id": record_id, "status": "invalid", "reason": "invalid_email_input"}
if email is None:
return {"id": record_id, "status": "skipped", "warning": "missing_email"}
return {"id": record_id, "status": "ready", "email": email}
def repaired_review_target(record):
record_id = record["id"]
email = record.get("email")
if email is None:
return {"id": record_id, "status": "skipped", "warning": "missing_email"}
if not isinstance(email, str) or email == "":
return {"id": record_id, "status": "invalid", "reason": "invalid_email_input"}
return {"id": record_id, "status": "ready", "email": email}
| Exact input | Faulty expected outcome | Repaired expected outcome |
|---|---|---|
| {"id":"R1","email":null} | AttributeError before skip | {"id":"R1","status":"skipped","warning":"missing_email"} |
| {"id":"R2","email":"[email protected]"} | {"id":"R2","status":"ready","email":"[email protected]"} | {"id":"R2","status":"ready","email":"[email protected]"} |
| {"id":"R3","email":7} | AttributeError before rejection | {"id":"R3","status":"invalid","reason":"invalid_email_input"} |
Under this exact unguarded caller contract, a null-before-check finding is actionable. If an actual caller excludes null, inspect that protection and the real requirement before making the same finding. An expected review of the faulty fixture should identify the demonstrated invalid dereference; an expected post-fix check should run the null and valid/invalid cases rather than infer fixed from a reordered line. The table is an expected comparison, not a recorded model review or hosted verification; actual publication still needs valid current-diff coordinates and authority.
A complete shared guidance teaching fixture
For an invented pure-Python email-policy repository, assume the module is src/email_policy.py, the pytest suite is tests/test_email_policy.py and the two JSON fixture files have exactly the contents declared earlier. Assume a prepared Python environment with pytest installed. This is a complete proposed root CLAUDE.md for that teaching repository; it is not a claim that these paths or commands exist in your checkout or that any command below ran:
# Shared email-policy project guidance
## Commands and standards
- Syntax/build check: python -m compileall -q src
- Behavior tests: python -m pytest tests/test_email_policy.py
- Use snake_case functions and pytest dictionary-equality assertions. Keep pure decisions free of network, credential and storage calls.
## Architecture and fixtures
- src/email_policy.py classifies caller-supplied records; the caller supplies a string id. A separate authorized persistence adapter handles storage and duplicate/conflict outcomes.
- fixtures/valid-email.json is {"id":"R2","email":"[email protected]"}; fixtures/null-email.json is {"id":"R1","email":null}. Read and verify available fixture bytes before relying on them.
- Valid nonempty strings yield ready with the same email. Missing/null yields skipped plus warning missing_email. Empty text and non-string email yield invalid plus reason invalid_email_input. These decisions do not claim stored records.
## Change and review workflow
1. Read the target classifier, actual caller, relevant tests and fixtures. Record missing artifacts and unresolved contracts before coding.
2. Preserve the accepted decisions above; make a bounded repair and add only genuinely uncovered behavior assertions.
3. Run the syntax and pytest commands in the actual prepared checkout. Retain exit status and observed failures; an unavailable dependency or command is pending evidence, never a pass.
4. Recheck null/missing, valid unchanged, empty and numeric inputs and unaffected cases. Fix supported upstream defects without weakening correct assertions.
5. Give a fresh reviewer the actual revision/diff, surrounding caller/implementation and these criteria. Require a concrete failure scenario and current location per finding; compare prior findings and rerun affected cases after repair.
6. Report actual inspected files, executed commands/results and remaining gaps. Do not publish comments, change permissions or invoke the persistence adapter without the applicable authorization.
This sample makes the source's objective version-controlled guidance concrete. A real team must replace the teaching assumptions with its actual available module layout, build/test commands and agreed behavior, commit the supported root CLAUDE.md or .claude/CLAUDE.md, and verify actual loading where that diagnostic is supported. A saved file, syntax check, requested review or expected outcome is not an observed behavioral pass or proof of compliance.
Summary
A dependable CI integration controls inputs, execution, and result validation separately. Supply shared context, verify structured findings against the current revision, track repeat issues by evidence, and add tests that cover demonstrated gaps. A completed invocation is one piece of evidence, not the entire release decision.
