-
Notifications
You must be signed in to change notification settings - Fork 441
701 lines (616 loc) Β· 32.6 KB
/
Copy pathclaude-review.yml
File metadata and controls
701 lines (616 loc) Β· 32.6 KB
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
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
# 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" β fetches PR context, posts/updates 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' &&
github.event.pull_request.base.ref == 'main' &&
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.context.outputs.pr_number }}
comment_id: ${{ steps.context.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: Fetch PR context and create tracking comment
id: context
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3
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 -->";
/* Fetch all PR data in parallel. */
const [pr, reviews, issueComments, reviewComments] = await Promise.all([
github.rest.pulls.get({ owner, repo, pull_number: prNumber }),
github.paginate(github.rest.pulls.listReviews, { owner, repo, pull_number: prNumber, per_page: 100 }),
github.paginate(github.rest.issues.listComments, { owner, repo, issue_number: prNumber, per_page: 100 }),
github.paginate(github.rest.pulls.listReviewComments, { owner, repo, pull_number: prNumber, per_page: 100 }),
]);
/* Find or create tracking comment. */
const existing = issueComments.find((c) => c.body && c.body.includes(MARKER));
let commentId;
let trackingCommentBody = null;
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;
trackingCommentBody = prevBody;
} 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;
}
/* Build context JSON for Claude. */
const prContext = {
pr: pr.data,
reviews,
issue_comments: issueComments,
tracking_comment: trackingCommentBody,
review_comments: reviewComments,
};
core.setOutput("pr_number", prNumber);
core.setOutput("comment_id", commentId);
const fs = require("fs");
fs.writeFileSync("pr-context.json", JSON.stringify(prContext));
# archive: false makes upload-artifact use the file's basename
# (pr-context.json) as the artifact name, ignoring the name input.
- name: Upload PR context
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
with:
path: pr-context.json
archive: false
retention-days: 7
review:
runs-on: ubuntu-latest
needs: setup
timeout-minutes: 60
permissions:
contents: read
id-token: write # Authenticate with AWS via OIDC
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd
with:
# Need full history for git worktree add to work on all PR commits.
fetch-depth: 0
persist-credentials: false
- name: Download PR context
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c
with:
name: pr-context.json
- name: Prettify PR context
run: |
jq . pr-context.json > pr-context-pretty.json
mv pr-context-pretty.json pr-context.json
- name: Prepare PR worktrees
env:
PR_NUMBER: ${{ needs.setup.outputs.pr_number }}
run: |
git fetch origin "pull/${PR_NUMBER}/head"
# Chronological commit order, oldest first. The worktree dirs are
# SHA-named, so listing them doesn't preserve order β reviewers read
# this manifest to review commits in the order they were authored.
git log --reverse --format=%H HEAD..FETCH_HEAD > commit-order.txt
while read -r sha; do
git worktree add "worktrees/$sha" "$sha"
git -C "worktrees/$sha" diff HEAD~..HEAD > "worktrees/$sha/commit.patch"
git -C "worktrees/$sha" log -1 --format='%B' HEAD > "worktrees/$sha/commit-message.txt"
done < commit-order.txt
- name: Install sandbox dependencies
run: |
sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0
sudo apt-get update && sudo apt-get install -y bubblewrap socat
- name: Configure AWS credentials
uses: aws-actions/configure-aws-credentials@acca2b1b2070338fb9fd1ca27ecee81d687e58e5
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: Install Claude Code
run: curl -fsSL https://claude.ai/install.sh | bash
- name: Run Claude Code
env:
CLAUDE_CODE_DISABLE_BACKGROUND_TASKS: "1"
CLAUDE_CODE_USE_BEDROCK: "1"
# Pin the `opus` alias (used by the review subagents) to 4.8 so they
# don't silently resolve to an older model the Bedrock alias points at.
ANTHROPIC_DEFAULT_OPUS_MODEL: us.anthropic.claude-opus-4-8
run: |
mkdir -p ~/.claude
cat > ~/.claude/settings.json << 'SETTINGS'
{
"permissions": {
"allow": [
"Bash",
"Read",
"Edit(/${{ github.workspace }}/**)",
"Write(/${{ github.workspace }}/**)",
"Grep",
"Glob",
"Agent",
"Task",
"TaskOutput",
"ToolSearch"
]
},
"sandbox": {
"enabled": true,
"autoAllowBashIfSandboxed": true,
"allowUnsandboxedCommands": false,
"filesystem": {
"allowWrite": ["/tmp", "/var/tmp", "${{ github.workspace }}"]
}
}
}
SETTINGS
cat > review-schema.json << 'SCHEMA'
{
"type": "object",
"required": ["summary", "comments"],
"properties": {
"summary": { "type": "string" },
"comments": {
"type": "array",
"items": {
"type": "object",
"required": ["path", "line", "severity", "body", "commit"],
"properties": {
"path": { "type": "string" },
"line": { "type": "integer" },
"side": { "enum": ["LEFT", "RIGHT"] },
"start_line": { "type": "integer" },
"start_side": { "enum": ["LEFT", "RIGHT"] },
"severity": { "enum": ["must-fix", "suggestion", "nit"] },
"body": { "type": "string" },
"commit": { "type": "string" }
}
}
},
"resolve": { "type": "array", "items": { "type": "integer" } }
}
}
SCHEMA
cat > /tmp/review-prompt.txt << 'PROMPT'
You are a code reviewer for the ${{ github.repository }} project.
Review this pull request. All required context has been
pre-fetched into local files.
## Phase 1: Review the PR through multiple lenses
First, read `review-schema.json` and `commit-order.txt` in the repository
root. `commit-order.txt` lists the commit SHAs in chronological order,
oldest first β this is the order in which commits must be reviewed. Each
worktree at `worktrees/<sha>/` contains the full source tree checked out at
that commit, plus `commit.patch` (the diff) and `commit-message.txt` (the
commit message).
mkosi is a Python tool for building operating system images. You will
review the PR through a set of lenses. Every review uses these four base
lenses:
1. Correctness & error handling β logic errors, edge cases, wrong
conditionals, off-by-one, incorrect None/Optional handling, exceptions
that are swallowed or caught too broadly, mishandled error paths, and
wrong handling of subprocess exit codes, stdout/stderr, or return values.
2. Resource lifetimes & cleanup β file descriptors, open files,
subprocesses, mounts and bind mounts, loop devices, and temporary
files/directories. Check that resources are released on every path
(including error paths), that `with`/context managers and `ExitStack`
are used correctly, and that nothing is leaked between operations.
3. Security & robustness β handling of untrusted input (config, downloaded
packages, image contents), path and symlink handling (path traversal,
TOCTOU, sandbox/chroot escapes), command injection when building
subprocess argument lists or using a shell, privilege boundaries
(running as root, user namespaces, capabilities, sandbox setup), and
resource exhaustion.
4. API design, style & maintainability β consistency with existing mkosi
idioms and `docs/CODING_STYLE.md`, naming, type hints, error propagation
via exceptions, coercing Path-like objects with `os.fspath`, dead code,
and needless complexity.
### Add PR-specific lenses
Before spawning, briefly inspect what this PR actually changes so you can
add domain-specific lenses. Read each worktree's `commit-message.txt` and
skim the changed file paths and hunk headers in each `commit.patch`, in
chronological order β just enough to understand which subsystems and
problem domains are touched. Do
NOT perform the review yourself or read the full source; that is the
subagents' job.
Based on that, add 1 to 3 EXTRA lenses targeting the specific concerns of
this PR. Each extra lens needs a short name and a one-sentence description
of what it must check. For example:
- a PR changing sandboxing, namespaces, or mount logic (e.g.
`mkosi/sandbox.py`, `mkosi/mounts.py`) β a "sandbox isolation & mount
safety" lens (namespace and uid/gid mapping setup, bind-mount ordering,
chroot correctness, unmount/cleanup, privilege drops).
- a PR changing a distribution or package manager backend (e.g.
`mkosi/distribution/`) β a "package manager integration" lens (correct
invocation, repository and GPG key handling, cache locking,
reproducibility).
- a PR changing config parsing (e.g. `mkosi/config.py`) β a "config
compatibility" lens (setting semantics, defaults, backward
compatibility, and keeping `mkosi/resources/man/` docs in sync).
- a PR touching boot, initrd, or systemd-repart integration β a
"boot & image layout" lens.
Only add extra lenses genuinely warranted by the diff β for a small or
generic change the four base lenses may be enough, in which case add none.
### Spawn the reviewers
Then spawn exactly one review subagent per lens (the base lenses plus any
extra lenses you derived), all in a single message so they run
concurrently. Each subagent reviews EVERY commit (every worktree
directory), but only through the perspective of its assigned lens.
Each subagent must be spawned with `model: "opus"`.
Each subagent prompt must include:
- The name and full description of its assigned lens, with an instruction
to report ONLY findings that fall under that lens and to ignore issues
belonging to the other lenses β those are covered by other reviewers.
- Instructions to read `pr-context.json` in the repository root for additional
context.
- The contents of `review-schema.json` (paste it into each prompt so the
agent doesn't have to read it separately).
- The list of every worktree path in chronological order (oldest commit
first, matching `commit-order.txt`), with an instruction to review the
commits in that order and read each one's `commit-message.txt` and
`commit.patch`.
- Instructions that each finding's `commit` field must be the SHA of the
worktree the finding belongs to, and that every `line` and `start_line`
value must be verified against the hunk ranges in that commit's
`commit.patch` before returning.
- Instructions to return ONLY a raw JSON array of findings. No markdown,
no explanation, no code fences β just the JSON array. If there are no
findings, return `[]`.
- Instructions that `severity` is a separate structured field β do NOT
repeat it inside `body` (no "must-fix:", "**suggestion**:", etc.
prefix). The posting step adds the severity label itself, so
including it in `body` produces duplicates.
## Phase 2: Collect, deduplicate, and summarize
After all reviews are done, read `pr-context.json` from the repository root.
It contains PR metadata from the GitHub API. Rules for its `review_comments`
field:
- Only look at your own comments (user.login == "github-actions[bot]" and
body starts with "Claude: "). Ignore all other comments.
- Items checked off in the `tracking_comment` (`- [x]`) are resolved.
- You will need the `id` fields of your own unresolved comments to
populate the `resolve` array.
- If `tracking_comment` is non-null, use it as the basis for your summary.
Trust the subagent findings β do NOT re-verify them by running your own
bash, grep, sed, or awk commands against the source code. Phase 2 should
only read `pr-context.json` and then produce the structured output.
Then:
1. Collect all issues. Merge duplicates across agents (same file, same
problem, lines within 3 of each other). Because the lenses overlap,
the same issue is often reported by more than one lens β collapse
these into a single comment, keeping the clearest wording.
2. Drop any issue whose suggestion is to add a code comment, docstring,
or documentation (e.g. "add a comment explainingβ¦", "missing
docstring", "document this function", "would benefit from a
comment"). mkosi style is to write no comments unless the WHY is
non-obvious, so these are noise β drop them from `comments` and from
the `summary`.
3. Drop issues that already have a review comment on the same file about
the same problem, or where the PR author replied disagreeing.
4. Populate the `resolve` array with the `id` of your own review comment
threads (user.login == "github-actions[bot]", body starts with
"Claude: ") that should be resolved β either because the issue was
fixed or because the author dismissed it. Use the first comment `id`
in each thread. Do not resolve threads from human reviewers.
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** β `path:line` β brief explanation
### Suggestions
- [ ] **short title** β `path:line` β brief explanation
### Nits
- [ ] **short title** β `path: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
If any errors prevented you from doing your job fully (tools that were
not available, git commands that failed, etc.), append a `### Errors`
section to the summary listing each failed action and the error message.
## Output formatting
Do NOT escape characters in `body` or `summary`. Write plain markdown β no
backslash escaping of `!` or other characters. In particular, HTML comments
like `<!-- ... -->` must be written verbatim, never as `<\!-- ... -->`.
## Review result
Produce your review result with a single `StructuredOutput` call that
contains all of these fields together:
- `summary`: The markdown summary for the tracking comment.
- `comments`: Array of review comments (same schema as the reviewer output above).
- `resolve`: REST API IDs of review comment threads to resolve.
`comments` and `resolve` are required β include them in the same call even
when they are empty (`[]`). Never emit a call with `summary` alone; a call
missing `comments` is rejected and wastes a full retry. Build `comments`
first, then write `summary` from it, then emit everything in one call.
Keep `summary` concise: each checkbox is a short title, `path:line`, and a
one-line explanation β the detailed reasoning belongs in the matching
`comments` entry, not the summary. Do not restate full findings prose in
the summary.
PROMPT
claude \
--model us.anthropic.claude-opus-4-8 \
--effort xhigh \
--max-turns 200 \
--setting-sources user \
--output-format stream-json \
--json-schema "$(cat review-schema.json)" \
--verbose \
-p "$(cat /tmp/review-prompt.txt)" \
| tee claude.json
jq '.structured_output | select(. != null)' claude.json > review-result.json
- name: Upload review result
if: always()
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a
with:
path: review-result.json
if-no-files-found: ignore
archive: false
retention-days: 7
post:
runs-on: ubuntu-latest
needs: [setup, review]
if: always() && needs.setup.result == 'success'
permissions:
pull-requests: write
steps:
- name: Download review result
if: needs.review.result == 'success'
continue-on-error: true
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c
with:
name: review-result.json
- name: Post review comments
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3
env:
REVIEW_RESULT: ${{ needs.review.result }}
PR_NUMBER: ${{ needs.setup.outputs.pr_number }}
COMMENT_ID: ${{ needs.setup.outputs.comment_id }}
with:
script: |
const fs = require("fs");
const owner = context.repo.owner;
const repo = context.repo.repo;
const prNumber = parseInt(process.env.PR_NUMBER, 10);
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 review result from the downloaded artifact. */
let raw = "";
try {
raw = fs.readFileSync("review-result.json", "utf8");
} catch (e) {
console.log(`Failed to read review-result.json: ${e.message}`);
}
console.log("Review result 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.path && c.line);
const skipped = comments.length - inlineComments.length;
if (skipped > 0)
console.log(`Skipping ${skipped} comment(s) missing path or line number.`);
let posted = 0;
for (const c of inlineComments) {
console.log(` Posting comment on ${c.path}:${c.line}`);
try {
await github.rest.pulls.createReviewComment({
owner,
repo,
pull_number: prNumber,
commit_id: c.commit,
path: c.path,
line: c.line,
...(c.side != null && { side: c.side }),
...(c.start_line != null && { start_line: c.start_line }),
...(c.start_side != null && { start_side: c.start_side }),
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.path}:${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.`);