Repository navigation
492 lines (444 loc) · 21.5 KB
/
Copy pathclaude-review.yml
File metadata and controls
492 lines (444 loc) · 21.5 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
# Concord — reusable Claude code review for member mods.
#
# Maintains a single sticky review comment on non-draft PRs: each push edits
# the same comment in place (anchored by a hidden marker) so the PR shows only
# the latest review, headed by the commit it reviewed.
#
# Triggered AFTER CI, not on the PR event. The caller stub fires on
# `workflow_run` when the mod's CI workflow completes, so the review always runs
# with CI's verdict already known — no polling, no race. The review reasons
# statically; CI (build / unit tests / gametest) is the only thing that runs the
# code, so its conclusion grounds the Correctness category. Because the trigger
# is `workflow_run`, the GITHUB_TOKEN has write scope even for fork PRs, so the
# sticky comment posts on forks too.
#
# This reusable workflow takes the CI run's head SHA, conclusion, and run id as
# inputs and resolves the associated open PR itself (skipping push builds and
# drafts). Migration: a legacy stub still triggering on pull_request keeps
# working — the gate falls back to the PR event's head SHA and the review runs
# with Correctness marked CI-unverified until the stub is migrated to the
# workflow_run form below. Prompt/criteria resolution order (first match wins):
# 1. explicit `prompt-file` / `criteria-file` workflow inputs (paths in
# the calling repo) — set these in the stub to use custom locations
# 2. the calling repo's .ai/prompts/code-reviewer.md / .ai/review-criteria.yml
# (whole-file override; delete them to fall back to the suite defaults)
# 3. the suite defaults in this repo's .ai/
# AGENTS.md always comes from the calling repo. Caller stub:
#
# name: Claude Code Review
# on:
# workflow_run:
# # Must match the `name:` of the mod's CI workflow exactly.
# workflows: ["CI"]
# types: [completed]
# concurrency:
# group: claude-review-${{ github.event.workflow_run.head_branch }}
# cancel-in-progress: true
# permissions:
# contents: read
# pull-requests: write
# issues: read
# actions: read # read the triggering CI run's per-job results
# jobs:
# review:
# uses: rfizzle/concord/.github/workflows/claude-review.yml@stable
# with:
# head-sha: ${{ github.event.workflow_run.head_sha }}
# ci-conclusion: ${{ github.event.workflow_run.conclusion }}
# ci-run-id: ${{ github.event.workflow_run.id }}
# secrets: inherit
#
# The hub files this workflow checks out load from the `concord-ref` input
# (default stable). The canary stub calls @master and passes
# `concord-ref: master`, so the workflow and the hub files it loads come from
# the same ref.
name: Claude Code Review
on:
workflow_call:
inputs:
concord-ref:
description: "concord ref to load the prompt defaults from (stable by default; the canary stub passes master)"
type: string
default: stable
head-sha:
description: >-
the CI run's head commit SHA (github.event.workflow_run.head_sha).
Empty = legacy pull_request-triggered stub: the gate falls back to the
PR event's head SHA and Correctness runs in CI-unverified mode.
type: string
default: ""
ci-conclusion:
description: "the CI run's conclusion (success / failure / cancelled / …)"
type: string
default: ""
ci-run-id:
description: "the CI run's id, used to fetch per-job pass/fail for the prompt"
type: string
default: ""
prompt-file:
description: "path (in the calling repo) to a custom reviewer prompt; empty = auto-resolve"
type: string
default: ""
criteria-file:
description: "path (in the calling repo) to custom review criteria; empty = auto-resolve"
type: string
default: ""
model:
type: string
default: claude-opus-5-5
max-budget-usd:
type: string
default: "8.00"
max-turns:
type: string
default: "100"
secrets:
CLAUDE_CODE_OAUTH_TOKEN:
required: true
jobs:
# Resolve the open, non-draft PR for the CI run's head commit. A push build
# (no PR) or a draft PR short-circuits the review without spending a turn.
gate:
runs-on: ubuntu-latest
outputs:
proceed: ${{ steps.pr.outputs.proceed }}
pr: ${{ steps.pr.outputs.pr }}
base: ${{ steps.pr.outputs.base }}
sha: ${{ steps.pr.outputs.sha }}
steps:
- name: Resolve PR for head SHA
id: pr
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
REPO="${{ github.repository }}"
SHA="${{ inputs.head-sha }}"
if [ -z "$SHA" ]; then
# Legacy stub still triggering on pull_request: take the SHA from
# the caller's event so the migration is non-breaking.
SHA="${{ github.event.pull_request.head.sha }}"
fi
if [ -z "$SHA" ]; then
echo "::warning::no head-sha input and no pull_request event; nothing to review"
echo "proceed=false" >> "$GITHUB_OUTPUT"; exit 0
fi
# PRs containing this commit. For a PR head the base repo can resolve
# it via refs/pull/N/head, so this works for fork PRs too. Take the
# first open one. Tab-separated so bodies/titles can't split fields.
INFO="$(gh api "repos/$REPO/commits/$SHA/pulls" \
--jq '[.[] | select(.state=="open")][0] | "\(.number)\t\(.draft)\t\(.base.ref)\t\(.head.ref)"' \
2>/dev/null || true)"
PR="$(printf '%s' "$INFO" | cut -f1)"
DRAFT="$(printf '%s' "$INFO" | cut -f2)"
BASE="$(printf '%s' "$INFO" | cut -f3)"
HEAD_REF="$(printf '%s' "$INFO" | cut -f4)"
if [ -z "$PR" ] || [ "$PR" = "null" ]; then
echo "No open PR for $SHA (likely a push build); skipping review."
echo "proceed=false" >> "$GITHUB_OUTPUT"; exit 0
fi
if [ "$DRAFT" = "true" ]; then
echo "PR #$PR is a draft; skipping review."
echo "proceed=false" >> "$GITHUB_OUTPUT"; exit 0
fi
if [ "$HEAD_REF" = "concord-sync" ]; then
echo "PR #$PR is a concord-sync bot PR (hub-reviewed); skipping review."
echo "proceed=false" >> "$GITHUB_OUTPUT"; exit 0
fi
echo "Reviewing PR #$PR (base $BASE) at $SHA"
{ echo "proceed=true"; echo "pr=$PR"; echo "base=$BASE"; echo "sha=$SHA"; } >> "$GITHUB_OUTPUT"
review:
needs: gate
if: needs.gate.outputs.proceed == 'true'
runs-on: ubuntu-latest
# Reads the code and history, reads issue/PR comments, and maintains the
# sticky review comment. No write beyond pull-requests — cap it here.
permissions:
contents: read
pull-requests: write
issues: read
actions: read # per-job pass/fail from the triggering CI run
steps:
# workflow_run checks out the default branch by default — pin to the PR
# head commit so the reviewer reads the code under review.
- name: Checkout PR head
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: ${{ needs.gate.outputs.sha }}
fetch-depth: 0
- name: Checkout concord (prompt defaults)
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
repository: rfizzle/concord
ref: ${{ inputs.concord-ref }}
path: .concord
- name: Install Claude Code
run: |
# Fetch the installer to disk rather than piping the network stream
# straight into bash: this captures the exact bytes (a truncated/MITM'd
# response can't partially execute) and logs their digest for audit.
curl -fsSL https://claude.ai/install.sh -o /tmp/claude-install.sh
echo "claude install.sh sha256: $(sha256sum /tmp/claude-install.sh | cut -d' ' -f1)"
bash /tmp/claude-install.sh
# CI has already finished (this workflow is triggered by its completion),
# so its result is authoritative — no polling, no race. Render the overall
# conclusion plus per-job pass/fail for the reviewer to ground Correctness.
- name: Summarize CI results
run: |
REPO="${{ github.repository }}"
CI_CONCLUSION="${{ inputs.ci-conclusion }}"
CI_RUN_ID="${{ inputs.ci-run-id }}"
OUT=/tmp/ci-status.txt
case "$CI_CONCLUSION" in
success) HEAD="CI PASSED on this commit." ;;
failure|timed_out|startup_failure)
HEAD="CI FAILED on this commit (conclusion: ${CI_CONCLUSION}). Name the failing step and test; see the prompt for how to grade it." ;;
cancelled|skipped|"")
HEAD="CI did not complete cleanly (conclusion: ${CI_CONCLUSION:-unknown}). Correctness is UNVERIFIED by CI — do not score it ✓ on reading alone." ;;
*) HEAD="CI conclusion: ${CI_CONCLUSION}." ;;
esac
{
echo "$HEAD"
echo
echo "CI jobs (conclusion|name):"
if [ -n "$CI_RUN_ID" ]; then
gh api "repos/$REPO/actions/runs/$CI_RUN_ID/jobs" --paginate \
--jq '.jobs[] | " \(.conclusion // .status)|\(.name)", (.steps[]? | select(.conclusion=="failure") | " failed step: \(.name)")' 2>/dev/null \
|| echo " (per-job details unavailable)"
else
echo " (no ci-run-id provided)"
fi
# Failure excerpt: the lines that identify the failing step and
# test, so the reviewer names them instead of guessing a cause.
case "$CI_CONCLUSION" in
failure|timed_out|startup_failure)
if [ -n "$CI_RUN_ID" ]; then
echo
echo "CI failure log excerpt (filtered, max 40 lines):"
if LOG="$(gh run view "$CI_RUN_ID" --repo "$REPO" --log-failed 2>/dev/null)" && [ -n "$LOG" ]; then
printf '%s\n' "$LOG" \
| grep -E 'FAILED|AssertException|required tests failed|Caused by|error:' \
| cut -c1-300 | head -n 40 || true
else
echo " (failed-step log unavailable; name the failing step from the job list only, do not infer a cause)"
fi
fi
;;
esac
} > "$OUT"
echo "--- CI status for reviewer ---"
cat "$OUT"
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Build review prompt
run: |
PR=${{ needs.gate.outputs.pr }}
BASE_REF="${{ needs.gate.outputs.base }}"
# Resolution: explicit input > repo-local .ai/ file > concord default.
# An explicit input that points at a missing file is a config error.
if [ -n "${{ inputs.prompt-file }}" ]; then
PROMPT_FILE="${{ inputs.prompt-file }}"
[ -f "$PROMPT_FILE" ] || { echo "::error::prompt-file '$PROMPT_FILE' not found"; exit 1; }
else
PROMPT_FILE=.ai/prompts/code-reviewer.md
[ -f "$PROMPT_FILE" ] || PROMPT_FILE=.concord/.ai/prompts/code-reviewer.md
fi
if [ -n "${{ inputs.criteria-file }}" ]; then
CRITERIA_FILE="${{ inputs.criteria-file }}"
[ -f "$CRITERIA_FILE" ] || { echo "::error::criteria-file '$CRITERIA_FILE' not found"; exit 1; }
else
CRITERIA_FILE=.ai/review-criteria.yml
[ -f "$CRITERIA_FILE" ] || CRITERIA_FILE=.concord/.ai/review-criteria.yml
fi
echo "Using prompt: $PROMPT_FILE"
echo "Using criteria: $CRITERIA_FILE"
DIFF="$(gh pr diff "$PR" --repo ${{ github.repository }})"
# Cap the inlined diff so one huge file (a deleted log, generated
# assets) can't blow the model's context window — "Prompt is too
# long" fails the call before a single turn. The reviewer has the
# full checkout and git history; tell it what was cut so it can
# read the rest itself.
MAX_DIFF_BYTES=400000
DIFF_BYTES=${#DIFF}
if [ "$DIFF_BYTES" -gt "$MAX_DIFF_BYTES" ]; then
echo "Diff is ${DIFF_BYTES} bytes; truncating inlined copy to ${MAX_DIFF_BYTES}"
DIFF="$(printf '%s' "$DIFF" | head -c "$MAX_DIFF_BYTES")
[INLINED DIFF TRUNCATED at ${MAX_DIFF_BYTES} of ${DIFF_BYTES} bytes.
The working directory contains the full PR checkout with history;
run 'git diff origin/${BASE_REF}...HEAD --stat'
for the full file list and diff any remaining file directly.]"
fi
PR_TITLE="$(gh pr view "$PR" --repo ${{ github.repository }} --json title --jq .title)"
PR_BODY="$(gh pr view "$PR" --repo ${{ github.repository }} --json body --jq .body)"
# The sticky review comment from the previous push, so the reviewer
# doesn't re-raise findings the latest push already addressed.
PREV_REVIEW="$(gh pr view "$PR" --repo ${{ github.repository }} \
--json comments \
--jq '[.comments[] | select(.body | startswith("<!-- concord-code-review -->"))] | last | .body // ""')"
# Issue(s) this PR closes — their bodies carry the implementation spec
# the change was built from. closingIssuesReferences captures both
# closing keywords (Closes #N) and issues linked via the PR sidebar.
# Reviewing against the spec catches drift the PR description misses.
OWNER="${GITHUB_REPOSITORY%/*}"
REPO="${GITHUB_REPOSITORY#*/}"
LINKED_ISSUES="$(gh api graphql \
-f query='query($owner:String!,$repo:String!,$pr:Int!){repository(owner:$owner,name:$repo){pullRequest(number:$pr){closingIssuesReferences(first:10){nodes{number title body}}}}}' \
-F owner="$OWNER" -F repo="$REPO" -F pr="$PR" \
--jq '.data.repository.pullRequest.closingIssuesReferences.nodes[] | "Issue #\(.number): \(.title)\n\n\(.body)\n"' 2>/dev/null)" || LINKED_ISSUES=""
# Quick signal in the log: did we resolve a linked issue (whose body
# carries the spec), or is the reviewer running on the PR alone?
if [ -n "$LINKED_ISSUES" ]; then
echo "Linked issue(s) resolved into review context: ${#LINKED_ISSUES} chars"
else
echo "::warning::No linked issue resolved — reviewing against the PR description only. Link the source issue with 'Closes #<n>' to feed the spec."
fi
PROMPT="$(cat "$PROMPT_FILE")
---
Project conventions (from AGENTS.md):
$(cat AGENTS.md 2>/dev/null || echo '(no AGENTS.md in this repository)')
---
Categories to score (from review-criteria.yml):
$(cat "$CRITERIA_FILE")
---
HEAD commit: ${{ needs.gate.outputs.sha }}
PR title: ${PR_TITLE}
PR description:
${PR_BODY}
---
Linked issue(s) this PR closes — the implementation spec and intent
the change was built from. Review the diff against this, not just the
PR description; flag where the implementation drifts from the spec:
${LINKED_ISSUES:-(none referenced)}
---
CI results for the head commit — the build, unit tests, and gametests
that actually ran the code. Use this to ground the Correctness verdict:
a failing check is a 🔴 must-fix unless it is a provably unrelated
test (see the prompt); do not score Correctness ✓ while CI is failing
or unverified. Name the failing step and test from the lists below.
$(cat /tmp/ci-status.txt 2>/dev/null || echo '(CI status unavailable)')
---
Previous review (if any) — do not repeat findings this push has
already addressed; only carry forward items that are genuinely still
open:
${PREV_REVIEW:-(none)}
---
The full repository is checked out in the current working directory.
(The .concord/ subdirectory is the suite standards repo, checked out
for reference — it is not part of this PR.)
Read any file you need (Read/Grep) to verify a finding before
including it.
Diff:
${DIFF}"
echo "$PROMPT" > /tmp/review-prompt.txt
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# Surface the exact prompt sent to the model — download from the run's
# Artifacts to confirm the linked issue body, diff, and AGENTS.md are
# present. The prompt holds no secrets (the token is passed via env).
- name: Upload review prompt
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: review-prompt
path: /tmp/review-prompt.txt
if-no-files-found: warn
- name: Run review
run: |
ATTEMPT=0
MAX_ATTEMPTS=3
# Accumulated across attempts so the reported figure is the whole
# job's spend, not just the winning attempt.
TOTAL_COST=0
TOTAL_TURNS=0
# Report dollar spend to the Actions run summary (and the log).
report_cost() {
echo "💲 Code review: \$${TOTAL_COST} over ${TOTAL_TURNS} turn(s) in ${ATTEMPT} attempt(s) on ${{ inputs.model }}"
if [ -n "$GITHUB_STEP_SUMMARY" ]; then
{
echo "### 💲 Code review cost"
echo ""
echo "| Model | Cost (USD) | Turns | Attempts |"
echo "|---|---|---|---|"
echo "| ${{ inputs.model }} | \$${TOTAL_COST} | ${TOTAL_TURNS} | ${ATTEMPT} |"
} >> "$GITHUB_STEP_SUMMARY"
fi
}
while [ $ATTEMPT -lt $MAX_ATTEMPTS ]; do
ATTEMPT=$((ATTEMPT + 1))
echo "Review attempt ${ATTEMPT}/${MAX_ATTEMPTS}"
RESULT="$(~/.local/bin/claude -p \
--output-format json \
--model ${{ inputs.model }} \
--max-turns ${{ inputs.max-turns }} \
--max-budget-usd ${{ inputs.max-budget-usd }} \
< /tmp/review-prompt.txt 2>/tmp/review-stderr.txt)" || true
COST="$(echo "$RESULT" | jq -r '.total_cost_usd // 0' 2>/dev/null)" || COST=0
TURNS="$(echo "$RESULT" | jq -r '.num_turns // 0' 2>/dev/null)" || TURNS=0
TOTAL_COST="$(awk "BEGIN{printf \"%.4f\", ${TOTAL_COST:-0} + ${COST:-0}}")"
TOTAL_TURNS=$((TOTAL_TURNS + ${TURNS:-0}))
COMMENT="$(echo "$RESULT" | jq -r '.result // empty' 2>/dev/null)" || true
if [ -n "$COMMENT" ] && echo "$COMMENT" | grep -q "## Code Review"; then
echo "Review produced successfully on attempt ${ATTEMPT}"
echo "$COMMENT" > /tmp/review-comment.md
report_cost
break
fi
echo "Attempt ${ATTEMPT} did not produce valid output"
echo "--- claude stderr (tail) ---"
tail -c 2000 /tmp/review-stderr.txt || true
echo "--- raw result (head) ---"
echo "$RESULT" | head -c 2000
echo "---"
if [ $ATTEMPT -eq $MAX_ATTEMPTS ]; then
report_cost
echo "::error::All ${MAX_ATTEMPTS} review attempts failed to produce valid output"
exit 1
fi
done
env:
CLAUDE_CODE_OAUTH_TOKEN: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
- name: Post review comment
run: |
if [ ! -s /tmp/review-comment.md ]; then
echo "No review comment to post"
exit 0
fi
# Trim any model preamble before the "## Code Review" header.
sed -n '/^## Code Review/,$p' /tmp/review-comment.md > /tmp/review-trimmed.md
[ -s /tmp/review-trimmed.md ] || cp /tmp/review-comment.md /tmp/review-trimmed.md
# Hidden marker anchors the sticky comment: the body must start with
# it so the find-and-edit lookup (and next run's PREV_REVIEW) match.
MARKER="<!-- concord-code-review -->"
SHA="${{ needs.gate.outputs.sha }}"
{
echo "$MARKER"
echo "_Reviewed at \`${SHA:0:7}\` · $(date -u '+%Y-%m-%d %H:%M UTC')_"
echo
cat /tmp/review-trimmed.md
} > /tmp/review-body.md
PR=${{ needs.gate.outputs.pr }}
REPO=${{ github.repository }}
# Edit the existing sticky comment in place if one exists, else create
# it. --paginate applies --jq per page, so emit one id per match and
# take the last rather than relying on jq's `last` across pages.
COMMENT_ID="$(gh api "repos/$REPO/issues/$PR/comments" --paginate \
--jq ".[] | select(.body | startswith(\"$MARKER\")) | .id" | tail -n1)"
# GitHub's API occasionally returns transient 401s — retry with backoff.
for i in 1 2 3; do
if [ -n "$COMMENT_ID" ]; then
if gh api -X PATCH "repos/$REPO/issues/comments/$COMMENT_ID" \
-F body=@/tmp/review-body.md >/dev/null; then
echo "Updated sticky review comment $COMMENT_ID"
exit 0
fi
else
if gh pr comment "$PR" --repo "$REPO" --body-file /tmp/review-body.md; then
echo "Created sticky review comment"
exit 0
fi
fi
echo "Post attempt $i failed; retrying in $((i * 10))s"
sleep $((i * 10))
done
echo "::error::Failed to post review comment after 3 attempts"
exit 1
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}