1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
|
# Integrates Claude Code as an AI assistant for reviewing pull requests.
# Mention @claude in any PR comment to request a review. Claude authenticates
# via AWS Bedrock using OIDC — no long-lived API keys required.
#
# Architecture: The workflow is split into three jobs for least-privilege:
# 1. "setup" — posts/updates a "reviewing…" tracking comment (write permissions)
# 2. "review" — runs Claude with read-only permissions, produces structured JSON
# 3. "post" — reads the JSON and posts comments to the PR (write permissions)
name: Claude Review
on:
pull_request_target:
types: [opened, synchronize, reopened, labeled]
# Strangely enough you have to use issue_comment to react to regular comments on PRs.
# See https://docs.github.com/en/actions/reference/workflows-and-actions/events-that-trigger-workflows#pull_request_comment-use-issue_comment.
issue_comment:
types: [created]
pull_request_review_comment:
types: [created]
pull_request_review:
types: [submitted]
concurrency:
group: claude-review-${{ github.event.pull_request.number || github.event.issue.number }}
jobs:
setup:
runs-on: ubuntu-latest
env:
PR_NUMBER: ${{ github.event.pull_request.number || github.event.issue.number }}
if: |
github.repository_owner == 'systemd' &&
((github.event_name == 'pull_request_target' &&
(github.event.action == 'labeled' && github.event.label.name == 'claude-review' && github.event.sender.login != 'github-actions[bot]' ||
github.event.action != 'labeled' && contains(github.event.pull_request.labels.*.name, 'claude-review') ||
github.event.action == 'opened' &&
contains(fromJSON('["MEMBER","OWNER","COLLABORATOR"]'), github.event.pull_request.author_association) &&
github.event.pull_request.user.login != 'YHNdnzj')) ||
(github.event_name == 'issue_comment' &&
github.event.issue.pull_request &&
contains(github.event.comment.body, '@claude review') &&
contains(fromJSON('["MEMBER","OWNER","COLLABORATOR"]'), github.event.comment.author_association)) ||
(github.event_name == 'pull_request_review_comment' &&
contains(github.event.comment.body, '@claude review') &&
contains(fromJSON('["MEMBER","OWNER","COLLABORATOR"]'), github.event.comment.author_association)) ||
(github.event_name == 'pull_request_review' &&
contains(github.event.review.body, '@claude review') &&
contains(fromJSON('["MEMBER","OWNER","COLLABORATOR"]'), github.event.review.author_association)))
permissions:
contents: read
pull-requests: write
outputs:
pr_number: ${{ steps.pr.outputs.number }}
head_sha: ${{ steps.pr.outputs.head_sha }}
comment_id: ${{ steps.tracking.outputs.comment_id }}
steps:
- name: Auto-add claude-review label for trusted contributors
if: github.event_name == 'pull_request_target' && github.event.action == 'opened'
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: gh pr edit --repo "${{ github.repository }}" "$PR_NUMBER" --add-label claude-review
- name: Resolve PR metadata
id: pr
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
echo "number=$PR_NUMBER" >> "$GITHUB_OUTPUT"
gh pr view --repo "${{ github.repository }}" "$PR_NUMBER" --json headRefOid --jq '.headRefOid' | \
xargs -I{} echo "head_sha={}" >> "$GITHUB_OUTPUT"
- name: Create or update tracking comment
id: tracking
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd
with:
script: |
const owner = context.repo.owner;
const repo = context.repo.repo;
const prNumber = parseInt(process.env.PR_NUMBER, 10);
const runUrl = `${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}/actions/runs/${process.env.GITHUB_RUN_ID}`;
const MARKER = "<!-- claude-pr-review -->";
const issueComments = await github.paginate(
github.rest.issues.listComments,
{ owner, repo, issue_number: prNumber, per_page: 100 },
);
const existing = issueComments.find((c) => c.body && c.body.includes(MARKER));
let commentId;
if (existing) {
console.log(`Updating existing tracking comment ${existing.id}.`);
/* Prepend a re-reviewing banner but keep the previous review visible. */
const prevBody = existing.body.replace(/\n\n\[Workflow run\]\([^)]*\)$/, "");
await github.rest.issues.updateComment({
owner,
repo,
comment_id: existing.id,
body: `> **Claude is re-reviewing this PR…** ([workflow run](${runUrl}))\n\n${prevBody}`,
});
commentId = existing.id;
} else {
console.log("Creating new tracking comment.");
const {data: created} = await github.rest.issues.createComment({
owner,
repo,
issue_number: prNumber,
body: `Claude is reviewing this PR… ([workflow run](${runUrl}))\n\n${MARKER}`,
});
commentId = created.id;
}
core.setOutput("comment_id", commentId);
review:
runs-on: ubuntu-latest
needs: setup
permissions:
contents: read
pull-requests: read # Fetch PR comments and reviews
issues: read # Fetch issue comments
id-token: write # Authenticate with AWS via OIDC
outputs:
structured_output: ${{ steps.claude.outputs.structured_output }}
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd
- name: Configure AWS credentials
uses: aws-actions/configure-aws-credentials@8df5847569e6427dd6c4fb1cf565c83acfa8afa7
with:
role-to-assume: arn:aws:iam::${{ secrets.AWS_ACCOUNT_ID }}:role/${{ secrets.AWS_ROLE_NAME }}
role-session-name: GitHubActions-Claude-${{ github.run_id }}
aws-region: us-east-1
- name: Run Claude Code
id: claude
uses: anthropics/claude-code-action@26ec041249acb0a944c0a47b6c0c13f05dbc5b44
env:
REVIEW_SCHEMA: >-
{
"type": "object",
"required": ["comments", "summary"],
"properties": {
"summary": {
"type": "string",
"description": "A markdown summary of the review to post as a top-level tracking comment"
},
"comments": {
"type": "array",
"items": {
"type": "object",
"required": ["file", "severity", "body", "commit"],
"properties": {
"file": {
"type": "string",
"description": "Path to the file relative to the repo root"
},
"line": {
"type": "integer",
"description": "Line number in the diff (new file side) to attach the comment to"
},
"severity": {
"type": "string",
"enum": ["must-fix", "suggestion", "nit"]
},
"body": {
"type": "string",
"description": "The review comment body in markdown"
},
"commit": {
"type": "string",
"description": "The SHA of the PR commit that introduced the code being commented on"
}
}
}
},
"resolve": {
"type": "array",
"items": {
"type": "integer"
},
"description": "REST API IDs of existing review comments whose threads should be resolved because the issue was addressed or the author left a disagreeing reply"
}
}
}
with:
use_bedrock: "true"
# We still have to pass GITHUB_TOKEN here because claude-code-action
# requires it, but we restrict Claude's tools to read-only operations
# so it cannot post comments or modify the PR.
github_token: ${{ secrets.GITHUB_TOKEN }}
track_progress: false
show_full_output: "true"
claude_args: |
--model us.anthropic.claude-opus-4-6-v1
--max-turns 100
--allowedTools "
Read,LS,Grep,Glob,Task,TaskStop,
Bash(cat *),Bash(test *),Bash(printf *),Bash(jq *),Bash(head *),Bash(tail *),
Bash(git *),Bash(grep *),Bash(find *),Bash(ls *),Bash(wc *),
Bash(gh api *),
Bash(diff *),Bash(sed *),Bash(awk *),Bash(sort *),Bash(uniq *),
"
--json-schema '${{ env.REVIEW_SCHEMA }}'
prompt: |
REPO: ${{ github.repository }}
PR NUMBER: ${{ needs.setup.outputs.pr_number }}
HEAD SHA: ${{ needs.setup.outputs.head_sha }}
You are a code reviewer for the ${{ github.repository }} project. Review this pull request and
produce a structured JSON result containing your review. Do NOT attempt
to post comments yourself — just return the JSON. You are in the upstream repo
without the patch applied. Do not apply it.
## Phase 1: Gather context
Use `gh api` to fetch all PR data. The base path for all endpoints is
`repos/${{ github.repository }}/pulls/${{ needs.setup.outputs.pr_number }}`.
**IMPORTANT: All data fetching in this phase MUST complete before moving to
Phase 2. Do NOT use `run_in_background` for any commands in this phase. Wait
for all results before proceeding.**
Fetch the following in parallel:
- `gh api repos/${{ github.repository }}/pulls/${{ needs.setup.outputs.pr_number }}`
— PR title, body, and metadata
- `gh api repos/${{ github.repository }}/pulls/${{ needs.setup.outputs.pr_number }}/reviews --paginate`
— PR reviews
- `gh api repos/${{ github.repository }}/pulls/${{ needs.setup.outputs.pr_number }}/commits --paginate --jq '.[].sha'`
— list of commit SHAs
- `gh api repos/${{ github.repository }}/issues/${{ needs.setup.outputs.pr_number }}/comments --paginate`
— issue comments (look for the tracking comment containing `<!-- claude-pr-review -->`;
if one exists, use it as the basis for your `summary` in Phase 3)
- `gh api repos/${{ github.repository }}/pulls/${{ needs.setup.outputs.pr_number }}/comments --paginate`
— inline review comments including each comment's numeric `id`, `path`,
`line`, `body`, `user.login`, and `in_reply_to_id`; you will need the
`id` fields in Phase 3 to populate the `resolve` array
## Phase 2: Per-commit review with subagents
Review each commit in the PR individually, in order (oldest first). For each
commit, fetch its diff using `gh api repos/{owner}/{repo}/commits/{sha}
-H 'Accept: application/vnd.github.diff'` via Bash, then launch a subagent
to review that commit's changes.
Each commit review subagent receives:
- The PR title and description (for overall context)
- The diffs of all preceding commits in the PR (for context on what was already changed)
- The commit message and SHA of the commit being reviewed
- The commit diff (from `gh api`)
Each commit review subagent reviews:
- Code quality, style, and best practices
- Potential bugs, issues, incorrect logic
- Security implications
- CLAUDE.md compliance
Each commit review subagent must return a JSON array of issues:
`[{"file": "path", "line": <number> (optional), "severity": "must-fix|suggestion|nit", "body": "...", "commit": "<sha>"}]`
The `commit` field MUST be set to the SHA of the commit being reviewed.
Each commit review subagent MUST only return comments about changes in the commit it is
reviewing — do NOT comment on code from preceding commits, even if it was
provided for context. If a preceding commit has an issue, it will be caught
by the subagent reviewing that commit.
`line` should be a line number from the NEW side of the diff **that appears inside
a diff hunk** (i.e. a line that is shown in the patch output). GitHub's review
comment API rejects lines outside the diff context, so never reference lines
that are not visible in the patch. If you cannot determine a valid diff line,
omit `line` — the comment will still appear in the tracking comment summary.
Each commit review subagent MUST verify its findings before returning them:
- For style/convention claims, check at least 3 existing examples in the codebase to confirm
the pattern actually exists before flagging a violation.
- For "use X instead of Y" suggestions, confirm X actually exists and works for this case.
- If unsure, don't include the issue.
Launch commit review subagents for all commits in parallel (e.g. if
reviewing a 7-commit PR, launch all 7 commit review subagents at once).
## Phase 3: Collect, deduplicate, and summarize
After ALL commit review subagents complete:
1. Collect all issues. Merge duplicates (same file, lines within 3 of each other, same problem).
2. Drop low-confidence findings.
3. Check the existing inline review comments fetched in Phase 1. Do NOT include a
comment if one already exists on the same file and line about the same problem.
Also check for author replies that dismiss or reject a previous comment — do NOT
re-raise an issue the PR author has already responded to disagreeing with.
Populate the `resolve` array with the REST API `id` (integer) of existing
review comments whose threads should be resolved. A thread should be resolved if:
- The issue it raised has been addressed in the current PR (i.e. your review
no longer flags it), OR
- The PR author (or another reviewer) left a reply disagreeing with or
dismissing the comment.
Only include the `id` of the **first** comment in each thread (the one that
started the conversation). Do NOT resolve threads for issues that are still
present and unaddressed.
4. Do NOT prefix `body` with a severity tag — the severity is already
captured in the `severity` field and will be added automatically when
posting inline comments.
5. Write a `summary` field in markdown for a top-level tracking comment.
**If no existing tracking comment was found (first run):**
Use this format:
```
## Claude review of PR #<number> (<HEAD SHA>)
<!-- claude-pr-review -->
### Must fix
- [ ] **short title** — `file:line` — brief explanation
### Suggestions
- [ ] **short title** — `file:line` — brief explanation
### Nits
- [ ] **short title** — `file:line` — brief explanation
```
Omit empty sections. Each checkbox item must correspond to an entry in `comments`.
If there are no issues at all, write a short message saying the PR looks good.
**If an existing tracking comment was found (subsequent run):**
Use the existing comment as the starting point. Preserve the order and wording
of all existing items. Then apply these updates:
- Update the HEAD SHA in the header line.
- For each existing item, re-check whether the issue is still present in the
current diff. If it has been fixed, mark it checked: `- [x]`.
- If the PR author replied dismissing an item, mark it:
`- [x] ~~short title~~ (dismissed)`.
- Preserve checkbox state that was already set by previous runs or by hand.
- Append any NEW issues found in this run that aren't already listed,
in the appropriate severity section, after the existing items.
- Do NOT reorder, reword, or remove existing items.
## Error tracking
Throughout all phases, track any errors that prevented you from doing
your job fully: permission denials (403, "Resource not accessible by
integration"), tools that were not available, rate limits, or any other
failures that degraded the review quality. If there were any, append a
`### Errors` section to the summary listing each failed tool/action and
the error message, so maintainers can fix the workflow configuration.
## CRITICAL: Return structured JSON output
Before returning structured output, cancel ALL running background tasks
using the TaskStop tool. A background task completing after you return
structured output will trigger a new conversation turn that overwrites your
result and causes the workflow to fail.
Your FINAL action must be to return a JSON object matching the following
JSON schema — do NOT end with a text summary or narrative. The `--json-schema`
flag is set, so your last response must be the structured JSON result, not a
text message.
```json
${{ env.REVIEW_SCHEMA }}
```
Do NOT attempt to post comments or use any MCP tools to modify the PR.
post:
runs-on: ubuntu-latest
needs: [setup, review]
if: always() && needs.setup.result == 'success'
permissions:
pull-requests: write
steps:
- name: Post review comments
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd
env:
STRUCTURED_OUTPUT: ${{ needs.review.outputs.structured_output }}
REVIEW_RESULT: ${{ needs.review.result }}
PR_NUMBER: ${{ needs.setup.outputs.pr_number }}
HEAD_SHA: ${{ needs.setup.outputs.head_sha }}
COMMENT_ID: ${{ needs.setup.outputs.comment_id }}
with:
script: |
const owner = context.repo.owner;
const repo = context.repo.repo;
const prNumber = parseInt(process.env.PR_NUMBER, 10);
const headSha = process.env.HEAD_SHA;
const commentId = parseInt(process.env.COMMENT_ID, 10);
const runUrl = `${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}/actions/runs/${process.env.GITHUB_RUN_ID}`;
const MARKER = "<!-- claude-pr-review -->";
/* If the review job failed or was cancelled, update the tracking
* comment to reflect that and bail out. */
if (process.env.REVIEW_RESULT !== "success") {
const verb = process.env.REVIEW_RESULT === "cancelled" ? "was cancelled" : "failed";
await github.rest.issues.updateComment({
owner,
repo,
comment_id: commentId,
body: `Claude review ${verb} — see [workflow run](${runUrl}) for details.\n\n${MARKER}`,
});
core.setFailed("Review job did not succeed.");
return;
}
/* Parse Claude's structured output. */
const raw = process.env.STRUCTURED_OUTPUT;
console.log("Structured output from Claude:");
console.log(raw || "(empty)");
let comments = [];
let resolveIds = [];
let summary = "";
if (raw) {
try {
const review = JSON.parse(raw);
if (Array.isArray(review.comments))
comments = review.comments;
if (Array.isArray(review.resolve))
resolveIds = review.resolve;
if (typeof review.summary === "string")
summary = review.summary;
} catch (e) {
core.warning(`Failed to parse structured output: ${e.message}`);
}
}
console.log(`Claude produced ${comments.length} review comment(s).`);
/* Post each inline comment individually. Deduplication against existing
* comments is handled by Claude in the prompt, so we just post whatever
* it returns. Using individual comments (rather than a review) means
* re-runs only add new comments instead of creating a whole new review. */
const inlineComments = comments.filter((c) => c.line);
const skipped = comments.length - inlineComments.length;
if (skipped > 0)
console.log(`Skipping ${skipped} file-level comment(s) (no line number).`);
let posted = 0;
for (const c of inlineComments) {
console.log(` Posting comment on ${c.file}:${c.line}`);
try {
await github.rest.pulls.createReviewComment({
owner,
repo,
pull_number: prNumber,
commit_id: c.commit,
path: c.file,
line: c.line,
body: `Claude: **${c.severity}**: ${c.body}`,
});
posted++;
} catch (e) {
/* GitHub rejects comments on lines outside the diff context. Log
* and continue — the tracking comment still contains all findings. */
console.log(` Warning: failed to post comment on ${c.file}:${c.line}: ${e.message}`);
}
}
if (posted > 0)
console.log(`Posted ${posted}/${inlineComments.length} inline comment(s).`);
else if (inlineComments.length > 0)
console.log(`Could not post any of ${inlineComments.length} inline comment(s) — see warnings above.`);
else
console.log("No inline comments to post.");
/* Resolve review threads that Claude identified as addressed or dismissed. */
if (resolveIds.length > 0) {
const resolveSet = new Set(resolveIds);
/* Fetch all review threads and map first-comment database IDs to thread IDs. */
let threads = [];
try {
let threadCursor = null;
do {
const threadQuery = `
query($owner: String!, $repo: String!, $number: Int!, $cursor: String) {
repository(owner: $owner, name: $repo) {
pullRequest(number: $number) {
reviewThreads(first: 100, after: $cursor) {
pageInfo { hasNextPage endCursor }
nodes {
id
isResolved
comments(first: 1) {
nodes {
databaseId
}
}
}
}
}
}
}
`;
const threadResult = await github.graphql(threadQuery, { owner, repo, number: prNumber, cursor: threadCursor });
const page = threadResult.repository.pullRequest.reviewThreads;
threads.push(...page.nodes);
threadCursor = page.pageInfo.hasNextPage ? page.pageInfo.endCursor : null;
} while (threadCursor);
} catch (e) {
console.log(`Warning: failed to fetch review threads, skipping resolution: ${e.message}`);
threads = [];
}
let resolved = 0;
let alreadyResolved = 0;
const matchedIds = new Set();
for (const thread of threads) {
const firstCommentId = thread.comments.nodes[0]?.databaseId;
if (!firstCommentId || !resolveSet.has(firstCommentId)) continue;
matchedIds.add(firstCommentId);
if (thread.isResolved) {
alreadyResolved++;
continue;
}
try {
await github.graphql(`
mutation($threadId: ID!) {
resolveReviewThread(input: { threadId: $threadId }) {
thread { id }
}
}
`, { threadId: thread.id });
resolved++;
console.log(` Resolved thread for comment ${firstCommentId}`);
} catch (e) {
console.log(` Warning: failed to resolve thread for comment ${firstCommentId}: ${e.message}`);
}
}
const requested = resolveSet.size;
const unmatched = [...resolveSet].filter(id => !matchedIds.has(id));
if (resolved > 0)
console.log(`Resolved ${resolved}/${requested} review thread(s)${alreadyResolved > 0 ? ` (${alreadyResolved} already resolved)` : ""}.`);
else if (alreadyResolved === requested)
console.log(`All ${requested} review thread(s) were already resolved.`);
else if (alreadyResolved > 0)
console.log(`${alreadyResolved}/${requested} review thread(s) were already resolved; could not resolve the rest — see warnings above.`);
else if (threads.length > 0)
console.log(`Could not resolve any of ${requested} review thread(s) — see warnings above.`);
if (unmatched.length > 0)
console.log(` ${unmatched.length} comment ID(s) not found in any thread: ${unmatched.join(", ")}`);
} else {
console.log("No review threads to resolve.");
}
/* Update the tracking comment with Claude's summary. */
if (!summary)
summary = "Claude review: no issues found :tada:\n\n" + MARKER;
else if (!summary.includes(MARKER))
summary += "\n\n" + MARKER;
summary += `\n\n[Workflow run](${runUrl})`;
await github.rest.issues.updateComment({
owner,
repo,
comment_id: commentId,
body: summary,
});
console.log("Tracking comment updated successfully.");
if (inlineComments.length > 0 && posted === 0)
core.setFailed(`Could not post any of ${inlineComments.length} inline comment(s) — see warnings above.`);
else if (posted < inlineComments.length)
core.warning(`${inlineComments.length - posted}/${inlineComments.length} inline comment(s) could not be posted.`);
|