forked from docker/cagent-action
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaction.yml
More file actions
902 lines (813 loc) · 36 KB
/
action.yml
File metadata and controls
902 lines (813 loc) · 36 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
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
name: "PR Review with docker-agent"
description: "AI-powered pull request review with automatic learning from feedback"
author: "Docker"
inputs:
pr-number:
description: "Pull request number to review (auto-detected from github.event if not provided)"
required: false
default: ""
comment-id:
description: "Comment ID for reactions (auto-detected from github.event if not provided)"
required: false
default: ""
additional-prompt:
description: "Additional instructions appended to the review (e.g., language-specific patterns, project conventions)"
required: false
default: ""
anthropic-api-key:
description: "Anthropic API key"
required: false
openai-api-key:
description: "OpenAI API key"
required: false
google-api-key:
description: "Google API key for Gemini models"
required: false
aws-bearer-token-bedrock:
description: "AWS Bearer token for Bedrock models"
required: false
xai-api-key:
description: "xAI API key for Grok models"
required: false
nebius-api-key:
description: "Nebius API key"
required: false
mistral-api-key:
description: "Mistral API key"
required: false
github-token:
description: "GitHub token for API access (overridden if github-app-id is provided)"
required: false
github-app-id:
description: "GitHub App ID for custom app identity (comments/reviews will appear as the app)"
required: false
github-app-private-key:
description: "GitHub App private key (required if github-app-id is provided)"
required: false
model:
description: "Model to use for reviews (e.g., anthropic/claude-sonnet-4-5, openai/gpt-4o)"
required: false
default: ""
add-prompt-files:
description: "Comma-separated list of files to append to the prompt (e.g., 'AGENTS.md,CLAUDE.md')"
required: false
default: ""
trusted-bot-app-id:
description: "GitHub App ID of a trusted bot that can bypass comment-based auth checks"
required: false
default: ""
org-membership-token:
description: "PAT with read:org scope for org membership authorization checks"
required: false
default: ""
auth-org:
description: "GitHub organization to check membership against"
required: false
default: ""
skip-auth:
description: "Skip the built-in authorization check (caller already verified auth)"
required: false
default: "false"
outputs:
exit-code:
description: "Exit code from the review"
value: ${{ steps.run-review.outputs.exit-code }}
review-url:
description: "URL to the posted review"
value: ${{ steps.post-summary.outputs.review-url }}
runs:
using: "composite"
steps:
# ========================================
# SETUP
# ========================================
- name: Resolve PR number and comment ID
id: resolve-context
shell: bash
run: |
# Resolve PR number: input > pull_request event > issue event
PR_NUMBER="${{ inputs.pr-number }}"
if [ -z "$PR_NUMBER" ]; then
PR_NUMBER="${{ github.event.pull_request.number }}"
fi
if [ -z "$PR_NUMBER" ]; then
PR_NUMBER="${{ github.event.issue.number }}"
fi
if [ -z "$PR_NUMBER" ]; then
echo "❌ Could not determine PR number. Provide pr-number input or trigger from a PR event."
exit 1
fi
echo "pr-number=$PR_NUMBER" >> $GITHUB_OUTPUT
echo "✅ Resolved PR number: $PR_NUMBER"
# Resolve comment ID: input > comment event (optional, for reactions)
COMMENT_ID="${{ inputs.comment-id }}"
if [ -z "$COMMENT_ID" ]; then
COMMENT_ID="${{ github.event.comment.id }}"
fi
echo "comment-id=$COMMENT_ID" >> $GITHUB_OUTPUT
if [ -n "$COMMENT_ID" ]; then
echo "✅ Resolved comment ID: $COMMENT_ID"
else
echo "ℹ️ No comment ID - reactions will be skipped"
fi
# Generate GitHub App token if credentials are provided
# This allows comments/reviews to appear as the custom app instead of github-actions[bot]
- name: Generate GitHub App token
id: app-token
if: inputs.github-app-id != ''
uses: tibdex/github-app-token@3beb63f4bd073e61482598c45c71c1019b59b73a # v2
with:
app_id: ${{ inputs.github-app-id }}
private_key: ${{ inputs.github-app-private-key }}
# Resolve which token to use: app token > explicit github-token > default github.token
- name: Resolve GitHub token
id: resolve-token
shell: bash
run: |
if [ -n "$APP_TOKEN" ]; then
echo "✅ Using GitHub App token"
echo "token=$APP_TOKEN" >> $GITHUB_OUTPUT
elif [ -n "$EXPLICIT_TOKEN" ]; then
echo "✅ Using provided github-token"
echo "token=$EXPLICIT_TOKEN" >> $GITHUB_OUTPUT
else
echo "ℹ️ Using default github.token"
echo "token=$DEFAULT_TOKEN" >> $GITHUB_OUTPUT
fi
env:
APP_TOKEN: ${{ steps.app-token.outputs.token }}
EXPLICIT_TOKEN: ${{ inputs.github-token }}
DEFAULT_TOKEN: ${{ github.token }}
# Concurrent review guard: best-effort lock using GitHub Actions cache.
# There is a narrow race window where two runs starting within seconds
# can both pass the check before either saves its lock. This is accepted
# because reviews are idempotent (duplicate reviews are harmless) and
# the window is small enough that it rarely occurs in practice.
- name: Check for concurrent review
id: review-lock
uses: actions/cache/restore@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0
with:
path: .cache/review-lock
# Exact key will never match (saves include run_id), so this always
# falls through to restore-keys prefix match — finding the most recent lock
key: pr-review-lock-${{ github.repository }}-${{ steps.resolve-context.outputs.pr-number }}-exact
restore-keys: |
pr-review-lock-${{ github.repository }}-${{ steps.resolve-context.outputs.pr-number }}-
- name: Evaluate review lock
id: lock-check
shell: bash
run: |
# cache-hit is only true on exact key match; prefix matches via restore-keys
# set cache-matched-key but leave cache-hit as false
if [ -n "${{ steps.review-lock.outputs.cache-matched-key }}" ]; then
LOCK_TIME=$(cat .cache/review-lock/timestamp 2>/dev/null || echo "0")
NOW=$(date +%s)
AGE=$(( NOW - LOCK_TIME ))
if [ "$AGE" -lt 2500 ]; then # ~42 min TTL (slightly longer than the 40-min review timeout)
echo "⏭️ Review already in progress (started ${AGE}s ago) — skipping"
echo "skip=true" >> $GITHUB_OUTPUT
echo "skip-reason=concurrent" >> $GITHUB_OUTPUT
echo "lock-age=${AGE}" >> $GITHUB_OUTPUT
exit 0
fi
echo "🔓 Stale lock (${AGE}s old) — proceeding"
fi
echo "skip=false" >> $GITHUB_OUTPUT
- name: Acquire review lock
if: steps.lock-check.outputs.skip != 'true'
shell: bash
run: |
mkdir -p .cache/review-lock
date +%s > .cache/review-lock/timestamp
- name: Save review lock
if: steps.lock-check.outputs.skip != 'true'
uses: actions/cache/save@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0
with:
path: .cache/review-lock
# Use run_id in save key so each run can save (cache keys are immutable)
# The restore step uses the fixed key with no run_id, so it matches via prefix
key: pr-review-lock-${{ github.repository }}-${{ steps.resolve-context.outputs.pr-number }}-${{ github.run_id }}
- name: Add eyes reaction
if: steps.resolve-context.outputs.comment-id != '' && steps.lock-check.outputs.skip != 'true'
shell: bash
env:
GH_TOKEN: ${{ steps.resolve-token.outputs.token }}
run: |
gh api repos/${{ github.repository }}/issues/comments/${{ steps.resolve-context.outputs.comment-id }}/reactions \
-X POST -f content='eyes' || true
- name: Get PR information
if: steps.lock-check.outputs.skip != 'true'
id: pr-info
shell: bash
env:
GH_TOKEN: ${{ steps.resolve-token.outputs.token }}
PR_NUMBER: ${{ steps.resolve-context.outputs.pr-number }}
REPO: ${{ github.repository }}
READ_TOKEN: ${{ github.token }}
run: |
PR_URL="https://github.com/${REPO}/pull/${PR_NUMBER}"
gh pr view "$PR_URL" --json files -q '.files[].path' > changed_files.txt
gh pr view "$PR_URL" --json title,body,author,baseRefName,headRefName > pr_metadata.json
echo "files_count=$(wc -l < changed_files.txt | tr -d ' ')" >> $GITHUB_OUTPUT
# Pre-fetch diff for the agent so it doesn't need to call gh pr diff itself.
# Uses github.token (has contents:read) instead of the App token (used for posting reviews).
# Uses the full PR URL instead of just the number — gh can't resolve a bare number
# from a detached HEAD (refs/pull/N/head).
if GH_TOKEN="$READ_TOKEN" gh pr diff "$PR_URL" > pr.diff 2>pr_diff_stderr.txt; then
echo "✅ Pre-fetched PR diff via gh pr diff ($(wc -l < pr.diff | tr -d ' ') lines)"
rm -f pr_diff_stderr.txt
else
echo "::warning::gh pr diff failed: $(cat pr_diff_stderr.txt 2>/dev/null)"
rm -f pr.diff pr_diff_stderr.txt
# Fallback: git diff with merge-base (repo is checked out with full history)
MERGE_BASE=$(git merge-base origin/main HEAD 2>/dev/null || git merge-base origin/master HEAD 2>/dev/null || echo "")
if [ -n "$MERGE_BASE" ]; then
if git diff "$MERGE_BASE"...HEAD > pr.diff; then
echo "✅ Pre-fetched PR diff via git diff ($(wc -l < pr.diff | tr -d ' ') lines)"
else
echo "::warning::git diff failed — agent will fetch diff itself"
rm -f pr.diff
fi
else
echo "::warning::Could not determine merge base — agent will fetch diff itself"
fi
fi
- name: Split diff into chunks
if: hashFiles('pr.diff') != ''
id: chunk-diff
shell: bash
run: |
set -euo pipefail
# Clean up stale chunk files from previous runs
rm -f /tmp/drafter_chunk_*.diff
TOTAL_LINES=$(wc -l < pr.diff | tr -d ' ')
echo "📄 Diff is $TOTAL_LINES lines"
if [ "$TOTAL_LINES" -le 1500 ]; then
# Small diff — single chunk
cp pr.diff /tmp/drafter_chunk_1.diff
echo "chunk_count=1" >> $GITHUB_OUTPUT
# Build manifest: list all files in the diff
FILES=$(grep '^diff --git' pr.diff | sed 's|diff --git a/.* b/||' | jq -R . | jq -s '.')
echo "chunk_manifest=$(jq -nc --argjson f "$FILES" '{"1": $f}')" >> $GITHUB_OUTPUT
echo "✅ Single chunk ($TOTAL_LINES lines)"
else
# Large diff — split at file boundaries, targeting ~1000 lines per chunk
CHUNK=1
CHUNK_LINES=0
CURRENT_FILE=""
CURRENT_DIR=""
MANIFEST="{}"
CHUNK_FILES="[]"
# Create first chunk file
> /tmp/drafter_chunk_1.diff
while IFS= read -r line; do
if [[ "$line" == "diff --git"* ]]; then
FILE=$(echo "$line" | sed 's|diff --git a/.* b/||')
DIR=$(dirname "$FILE")
# Start new chunk if:
# - over soft limit (1000 lines) and directory changed, OR
# - over hard limit (2000 lines) regardless of directory
if ([ "$CHUNK_LINES" -gt 1000 ] && [ "$DIR" != "$CURRENT_DIR" ]) || [ "$CHUNK_LINES" -gt 2000 ]; then
# Save current chunk's file list to manifest
MANIFEST=$(echo "$MANIFEST" | jq --argjson files "$CHUNK_FILES" --arg k "$CHUNK" '.[$k] = $files')
CHUNK=$((CHUNK + 1))
CHUNK_LINES=0
CHUNK_FILES="[]"
> /tmp/drafter_chunk_${CHUNK}.diff
fi
CURRENT_FILE="$FILE"
CURRENT_DIR="$DIR"
CHUNK_FILES=$(echo "$CHUNK_FILES" | jq --arg f "$FILE" '. += [$f]')
fi
echo "$line" >> /tmp/drafter_chunk_${CHUNK}.diff
CHUNK_LINES=$((CHUNK_LINES + 1))
done < pr.diff
# Save final chunk's file list
MANIFEST=$(echo "$MANIFEST" | jq --argjson files "$CHUNK_FILES" --arg k "$CHUNK" '.[$k] = $files')
echo "chunk_count=$CHUNK" >> $GITHUB_OUTPUT
echo "chunk_manifest=$(echo "$MANIFEST" | jq -c .)" >> $GITHUB_OUTPUT
echo "✅ Split into $CHUNK chunks (target ~1000 lines each)"
for i in $(seq 1 $CHUNK); do
LINES=$(wc -l < /tmp/drafter_chunk_${i}.diff | tr -d ' ')
FILES_IN_CHUNK=$(echo "$MANIFEST" | jq -r --arg k "$i" '.[$k] | length')
echo " Chunk $i: $LINES lines, $FILES_IN_CHUNK files"
done
fi
- name: Score file risk
if: hashFiles('pr.diff') != ''
shell: bash
run: |
# Extract per-file diff stats (added lines, hunk count)
awk '
/^diff --git/ {
if (file != "") print file, added, hunks
file = $0; sub(/.*b\//, "", file)
added = 0; hunks = 0
}
/^@@/ { hunks++ }
/^\+[^+]/ { added++ }
END { if (file != "") print file, added, hunks }
' pr.diff > /tmp/file_diff_stats.txt
# Build final scores
jq -n '{}' > /tmp/file_risk_scores.json
while read -r file added hunks; do
SCORE=0
# Security-sensitive paths: +2
if echo "$file" | grep -qiE 'auth|security|crypto|session|secret|token|password|credential'; then
SCORE=$((SCORE + 2))
fi
# Large change (>100 added lines): +2
if [ "$added" -gt 100 ]; then
SCORE=$((SCORE + 2))
fi
# Many hunks (>3): +1
if [ "$hunks" -gt 3 ]; then
SCORE=$((SCORE + 1))
fi
# Test/doc/config files: score = 0
if echo "$file" | grep -qiE '_test\.go$|\.test\.[tj]sx?$|\.spec\.[tj]sx?$|test_.*\.py$|\.md$|\.ya?ml$|\.json$|\.toml$'; then
SCORE=0
fi
# Error handling patterns in diff for this file: +1
ERROR_LINES=$(awk -v f="$file" '
/^diff --git/ { cur=$0; sub(/.*b\//, "", cur) }
cur == f && /^\+[^+]/ && /catch|rescue|except|recover|error|panic/ { count++ }
END { print count+0 }
' pr.diff)
if [ "$ERROR_LINES" -gt 0 ]; then
SCORE=$((SCORE + 1))
fi
if jq --arg f "$file" --argjson s "$SCORE" '.[$f] = $s' /tmp/file_risk_scores.json > /tmp/file_risk_scores.tmp; then
mv /tmp/file_risk_scores.tmp /tmp/file_risk_scores.json
else
echo "⚠️ Failed to score $file, skipping"
rm -f /tmp/file_risk_scores.tmp
fi
done < /tmp/file_diff_stats.txt
rm -f /tmp/file_diff_stats.txt
echo "✅ File risk scores: $(jq -c . /tmp/file_risk_scores.json)"
- name: Generate file history
if: hashFiles('changed_files.txt') != ''
shell: bash
run: |
> /tmp/file_history.txt
while IFS= read -r file; do
# Skip new files (no git history)
HISTORY=$(git log --oneline -5 -- "$file" 2>/dev/null || true)
if [ -n "$HISTORY" ]; then
echo "## $file" >> /tmp/file_history.txt
echo "$HISTORY" >> /tmp/file_history.txt
echo "" >> /tmp/file_history.txt
fi
done < changed_files.txt
ENTRIES=$(grep -c '^## ' /tmp/file_history.txt 2>/dev/null || echo "0")
echo "✅ Generated history for $ENTRIES file(s)"
- name: Resolve stale review threads
if: steps.lock-check.outputs.skip != 'true'
continue-on-error: true
shell: bash
env:
GH_TOKEN: ${{ steps.resolve-token.outputs.token }}
PR_NUMBER: ${{ steps.resolve-context.outputs.pr-number }}
REPO: ${{ github.repository }}
run: |
echo "🔍 Checking for stale bot review threads to resolve..."
# A. Parse diff → file:line set
# Tracks current file from "diff --git" headers, line numbers from @@ hunks,
# and emits "file:line" for each added (+) line.
if [ ! -f pr.diff ]; then
echo "ℹ️ No pr.diff found — skipping stale thread resolution"
exit 0
fi
DIFF_LINES_FILE=$(mktemp)
trap "rm -f '$DIFF_LINES_FILE'" EXIT
awk '
/^\+\+\+ b\// {
# Extract file path from "+++ b/foo" (unambiguous, unlike diff --git header)
file = substr($0, 7)
}
/^@@ / {
# Parse new file line number from "@@ -X,Y +Z,W @@"
match($0, /\+([0-9]+)/, arr)
line = arr[1]
next
}
/^\+[^+]/ || /^\+$/ {
# Added line (but not the +++ header)
if (file != "" && line > 0) {
print file ":" line
}
line++
}
/^ / { line++ }
/^-/ { next }
' pr.diff | sort -u > $DIFF_LINES_FILE
DIFF_LINE_COUNT=$(wc -l < $DIFF_LINES_FILE | tr -d ' ')
echo "📄 Found $DIFF_LINE_COUNT unique file:line pairs in diff"
# B. Fetch all review threads via GraphQL (paginated)
OWNER="${REPO%%/*}"
REPO_NAME="${REPO##*/}"
QUERY='
query($owner: String!, $repo: String!, $pr: Int!, $cursor: String) {
repository(owner: $owner, name: $repo) {
pullRequest(number: $pr) {
reviewThreads(first: 100, after: $cursor) {
pageInfo { hasNextPage endCursor }
nodes {
id
isResolved
path
line
comments(first: 5) {
nodes { body }
}
}
}
}
}
}'
ALL_THREADS="[]"
CURSOR=""
PAGE=0
FETCH_OK=true
while true; do
PAGE=$((PAGE + 1))
GQL_ARGS=(-f query="$QUERY" -f owner="$OWNER" -f repo="$REPO_NAME" -F pr="$PR_NUMBER")
if [ -n "$CURSOR" ]; then
GQL_ARGS+=(-f cursor="$CURSOR")
fi
RESULT=$(gh api graphql "${GQL_ARGS[@]}" 2>&1) || {
echo "::warning::GraphQL query failed (page $PAGE): $RESULT"
FETCH_OK=false
break
}
# Check for GraphQL errors in response (HTTP 200 can still contain errors)
if echo "$RESULT" | jq -e '.errors' > /dev/null 2>&1; then
echo "::warning::GraphQL returned errors: $(echo "$RESULT" | jq -c '.errors')"
FETCH_OK=false
break
fi
THREADS=$(echo "$RESULT" | jq '.data.repository.pullRequest.reviewThreads.nodes // []') || {
echo "::warning::Failed to parse threads on page $PAGE"
FETCH_OK=false
break
}
ALL_THREADS=$(echo "$ALL_THREADS" "$THREADS" | jq -s '.[0] + .[1]') || {
echo "::warning::Failed to merge threads on page $PAGE"
FETCH_OK=false
break
}
HAS_NEXT=$(echo "$RESULT" | jq -r '.data.repository.pullRequest.reviewThreads.pageInfo.hasNextPage')
if [ "$HAS_NEXT" != "true" ]; then
break
fi
CURSOR=$(echo "$RESULT" | jq -r '.data.repository.pullRequest.reviewThreads.pageInfo.endCursor')
done
if [ "$FETCH_OK" != "true" ]; then
echo "::warning::Thread fetch incomplete — skipping resolution to avoid acting on partial data"
exit 0
fi
TOTAL_THREADS=$(echo "$ALL_THREADS" | jq 'length')
echo "📋 Fetched $TOTAL_THREADS review threads (across $PAGE page(s))"
# C. Filter to unresolved bot threads (containing <!-- cagent-review --> marker)
BOT_THREADS=$(echo "$ALL_THREADS" | jq '[
.[] | select(
.isResolved == false and
(.comments.nodes | any(.body | contains("<!-- cagent-review -->")))
)
]')
BOT_COUNT=$(echo "$BOT_THREADS" | jq 'length')
if [ -z "$BOT_COUNT" ] || ! [[ "$BOT_COUNT" =~ ^[0-9]+$ ]]; then
echo "::warning::Failed to count bot threads"
exit 0
fi
echo "🤖 Found $BOT_COUNT unresolved bot review thread(s)"
if [ "$BOT_COUNT" -eq 0 ]; then
echo "✅ No stale bot threads to resolve"
exit 0
fi
# D. Resolve stale threads (file:line no longer in diff)
RESOLVED=0
KEPT=0
for i in $(seq 0 $((BOT_COUNT - 1))); do
THREAD_ID=$(echo "$BOT_THREADS" | jq -r ".[$i].id")
THREAD_PATH=$(echo "$BOT_THREADS" | jq -r ".[$i].path")
THREAD_LINE=$(echo "$BOT_THREADS" | jq -r ".[$i].line")
# Skip threads with null path (file-level or unknown context)
if [ "$THREAD_PATH" = "null" ] || [ -z "$THREAD_PATH" ]; then
echo " ⏭️ Keeping open: thread $THREAD_ID (no file path)"
KEPT=$((KEPT + 1))
continue
fi
# Null line means GitHub marked the comment "outdated" — the code changed
# since the comment was posted and the position is no longer valid.
# These are stale by definition and should be resolved.
SHOULD_RESOLVE=false
if [ "$THREAD_LINE" = "null" ] || [ -z "$THREAD_LINE" ]; then
echo " 🔄 Outdated: $THREAD_PATH (position invalidated by push)"
SHOULD_RESOLVE=true
elif grep -qFx "${THREAD_PATH}:${THREAD_LINE}" "$DIFF_LINES_FILE"; then
echo " ⏭️ Keeping open: ${THREAD_PATH}:${THREAD_LINE} (still in diff)"
KEPT=$((KEPT + 1))
else
echo " 🔄 Stale: ${THREAD_PATH}:${THREAD_LINE} (no longer in diff)"
SHOULD_RESOLVE=true
fi
if [ "$SHOULD_RESOLVE" = "true" ]; then
MUTATION_RESULT=$(gh api graphql -f query='
mutation($threadId: ID!) {
resolveReviewThread(input: { threadId: $threadId }) {
thread { id isResolved }
}
}
' -f threadId="$THREAD_ID" 2>&1) || {
echo " ⚠️ Failed to resolve thread $THREAD_ID (API error)"
continue
}
if echo "$MUTATION_RESULT" | jq -e '.errors' > /dev/null 2>&1; then
echo " ⚠️ Failed to resolve thread $THREAD_ID: $(echo "$MUTATION_RESULT" | jq -c '.errors')"
continue
fi
echo " ✅ Resolved thread $THREAD_ID"
RESOLVED=$((RESOLVED + 1))
fi
done
echo ""
echo "📋 Summary: Resolved $RESOLVED thread(s), kept $KEPT thread(s) open"
- name: Ensure cache directory exists
if: steps.lock-check.outputs.skip != 'true'
shell: bash
run: mkdir -p "${{ github.workspace }}/.cache"
- name: Restore reviewer memory
if: steps.lock-check.outputs.skip != 'true'
id: restore-memory
uses: actions/cache/restore@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0
with:
path: ${{ github.workspace }}/.cache/pr-review-memory.db
key: pr-review-memory-${{ github.repository }}-${{ github.job }}-${{ github.run_id }}
restore-keys: |
pr-review-memory-${{ github.repository }}-${{ github.job }}-
pr-review-memory-${{ github.repository }}-
# ========================================
# PROCESS PENDING FEEDBACK
# Downloads feedback artifacts left by capture-feedback jobs
# and processes them into memory before the review runs.
# ========================================
- name: Collect pending feedback
if: steps.lock-check.outputs.skip != 'true'
id: pending-feedback
continue-on-error: true
shell: bash
env:
GH_TOKEN: ${{ steps.resolve-token.outputs.token }}
run: |
ARTIFACTS=$(gh api "repos/${{ github.repository }}/actions/artifacts?name=pr-review-feedback" \
--jq '.artifacts[].id' 2>/dev/null || echo "")
if [ -z "$ARTIFACTS" ]; then
echo "has_feedback=false" >> $GITHUB_OUTPUT
echo "ℹ️ No pending feedback to process"
exit 0
fi
mkdir -p pending_feedback
COMBINED=""
COUNT=0
for AID in $ARTIFACTS; do
# Download artifact zip
gh api "repos/${{ github.repository }}/actions/artifacts/$AID/zip" > "feedback_$AID.zip" 2>/dev/null || continue
unzip -o "feedback_$AID.zip" -d "pending_feedback/" 2>/dev/null || continue
if [ -f pending_feedback/feedback.json ]; then
FB_PATH=$(jq -r '.path // "unknown"' pending_feedback/feedback.json)
FB_LINE=$(jq -r '.line // "?"' pending_feedback/feedback.json)
FB_BODY=$(jq -r '.body // ""' pending_feedback/feedback.json)
COMBINED+="- **File:** ${FB_PATH} (line ${FB_LINE})"$'\n'
COMBINED+=" **Feedback:** ${FB_BODY}"$'\n\n'
((COUNT++)) || true
fi
rm -f pending_feedback/feedback.json
# Delete processed artifact
gh api "repos/${{ github.repository }}/actions/artifacts/$AID" -X DELETE 2>/dev/null || true
done
if [ "$COUNT" -gt 0 ]; then
echo "has_feedback=true" >> $GITHUB_OUTPUT
{
echo "prompt<<FEEDBACK_EOF"
echo "$COMBINED"
echo "FEEDBACK_EOF"
} >> $GITHUB_OUTPUT
echo "✅ Found $COUNT pending feedback item(s) to process"
else
echo "has_feedback=false" >> $GITHUB_OUTPUT
fi
- name: Process pending feedback
if: steps.lock-check.outputs.skip != 'true' && steps.pending-feedback.outputs.has_feedback == 'true'
continue-on-error: true
uses: docker/cagent-action@dba0ca51938c78afb363625363c50582243218d6 # v1.3.1
with:
agent: ${{ github.action_path }}/agents/pr-review-feedback.yaml
prompt: |
Developers left feedback on previous review comments. Learn from each item:
${{ steps.pending-feedback.outputs.prompt }}
For each item:
1. If they're correcting a false positive, add a memory to avoid this mistake
2. If they're asking for clarification, note what was unclear
3. If they're agreeing and adding context, store the additional insight
Use add_memory to record what you learned from each feedback item.
anthropic-api-key: ${{ inputs.anthropic-api-key }}
openai-api-key: ${{ inputs.openai-api-key }}
google-api-key: ${{ inputs.google-api-key }}
aws-bearer-token-bedrock: ${{ inputs.aws-bearer-token-bedrock }}
xai-api-key: ${{ inputs.xai-api-key }}
nebius-api-key: ${{ inputs.nebius-api-key }}
mistral-api-key: ${{ inputs.mistral-api-key }}
github-token: ${{ steps.resolve-token.outputs.token }}
trusted-bot-app-id: ${{ inputs.trusted-bot-app-id }}
extra-args: ${{ inputs.model && format('--model={0}', inputs.model) || '' }}
skip-summary: "true"
org-membership-token: ${{ inputs.org-membership-token }}
auth-org: ${{ inputs.auth-org }}
skip-auth: ${{ inputs.skip-auth }}
# ========================================
# BUILD REVIEW CONTEXT
# ========================================
- name: Build review context
if: steps.lock-check.outputs.skip != 'true'
id: context
shell: bash
env:
PR_NUMBER: ${{ steps.resolve-context.outputs.pr-number }}
EXTRA_PROMPT: ${{ inputs.additional-prompt }}
REPO: ${{ github.repository }}
run: |
title=$(jq -r '.title' pr_metadata.json)
author=$(jq -r '.author.login' pr_metadata.json)
body=$(jq -r '.body // "No description provided."' pr_metadata.json)
base=$(jq -r '.baseRefName' pr_metadata.json)
head=$(jq -r '.headRefName' pr_metadata.json)
files_count=$(wc -l < changed_files.txt | tr -d ' ')
# Build review context (using echo to avoid YAML heredoc parsing issues)
{
echo "# Pull Request Review Request"
echo ""
echo "## PR Information"
echo "- **URL**: https://github.com/${REPO}/pull/${PR_NUMBER}"
echo "- **Title**: $title"
echo "- **Author**: $author"
echo "- **Branch**: $head → $base"
echo "- **Files Changed**: $files_count"
echo ""
echo "## PR Description"
echo "$body"
echo ""
echo "## Changed Files"
echo ""
cat changed_files.txt
echo ""
echo "---"
echo ""
echo "## Instructions"
echo ""
echo "Execute the review pipeline:"
echo ""
echo "1. **Gather**: Read the pre-fetched \`pr.diff\` file. If missing, run \`gh pr diff https://github.com/${REPO}/pull/${PR_NUMBER}\` (use the full URL, not just the number)"
echo '2. **Draft**: Delegate to `drafter` agent to generate bug hypotheses'
echo '3. **Verify**: For each hypothesis, delegate to `verifier` agent'
echo '4. **Post**: Aggregate findings and post review via `gh api`'
echo ""
echo "Only report CONFIRMED and LIKELY findings. Always post as COMMENT (never APPROVE or REQUEST_CHANGES)."
} > review_context.md
# Append extra prompt if provided
if [ -n "$EXTRA_PROMPT" ]; then
{
echo ""
echo "## Additional Guidelines"
echo ""
echo "$EXTRA_PROMPT"
} >> review_context.md
fi
# Save prompt to output for the action
{
echo "review_prompt<<PROMPT_EOF"
cat review_context.md
echo "PROMPT_EOF"
} >> $GITHUB_OUTPUT
# ========================================
# RUN REVIEW using root cagent-action
# ========================================
- name: Run PR Review
if: steps.lock-check.outputs.skip != 'true'
id: run-review
uses: docker/cagent-action@dba0ca51938c78afb363625363c50582243218d6 # v1.3.1
with:
agent: ${{ github.action_path }}/agents/pr-review.yaml
prompt: ${{ steps.context.outputs.review_prompt }}
timeout: "2400" # 40 min — allows time for large diffs and retries
anthropic-api-key: ${{ inputs.anthropic-api-key }}
openai-api-key: ${{ inputs.openai-api-key }}
google-api-key: ${{ inputs.google-api-key }}
aws-bearer-token-bedrock: ${{ inputs.aws-bearer-token-bedrock }}
xai-api-key: ${{ inputs.xai-api-key }}
nebius-api-key: ${{ inputs.nebius-api-key }}
mistral-api-key: ${{ inputs.mistral-api-key }}
github-token: ${{ steps.resolve-token.outputs.token }}
trusted-bot-app-id: ${{ inputs.trusted-bot-app-id }}
extra-args: ${{ inputs.model && format('--model={0}', inputs.model) || '' }}
add-prompt-files: ${{ inputs.add-prompt-files }}
max-retries: "1" # One retry handles transient API failures (e.g. Anthropic 400s) without risking duplicate reviews from full pipeline restarts
skip-summary: "true"
org-membership-token: ${{ inputs.org-membership-token }}
auth-org: ${{ inputs.auth-org }}
skip-auth: ${{ inputs.skip-auth }}
- name: Release review lock
if: always() && steps.lock-check.outputs.skip != 'true'
continue-on-error: true # Release failures are safe — stale locks expire via TTL (2500s)
shell: bash
env:
GH_TOKEN: ${{ steps.resolve-token.outputs.token }}
REPO: ${{ github.repository }}
PR_NUMBER: ${{ steps.resolve-context.outputs.pr-number }}
run: |
# Delete all cache entries matching this PR's lock prefix
gh api --paginate "repos/$REPO/actions/caches?key=pr-review-lock-${REPO}-${PR_NUMBER}-" \
--jq '.actions_caches[].id' 2>/dev/null | while read -r CACHE_ID; do
gh api "repos/$REPO/actions/caches/$CACHE_ID" -X DELETE 2>/dev/null || true
done
echo "🔓 Released review lock for PR #$PR_NUMBER"
- name: Save reviewer memory
if: always() && steps.lock-check.outputs.skip != 'true'
continue-on-error: true # Don't fail if memory file doesn't exist (first run)
uses: actions/cache/save@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0
with:
path: ${{ github.workspace }}/.cache/pr-review-memory.db
key: pr-review-memory-${{ github.repository }}-${{ github.job }}-${{ github.run_id }}
# ========================================
# POST-REVIEW: Clean summary & reactions
# ========================================
- name: Post clean summary
id: post-summary
if: always()
shell: bash
env:
GH_TOKEN: ${{ steps.resolve-token.outputs.token }}
PR_NUMBER: ${{ steps.resolve-context.outputs.pr-number }}
REPOSITORY: ${{ github.repository }}
EXIT_CODE: ${{ steps.run-review.outputs.exit-code }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
VERBOSE_LOG_FILE: ${{ steps.run-review.outputs.verbose-log-file }}
SKIP_REASON: ${{ steps.lock-check.outputs.skip-reason }}
LOCK_AGE: ${{ steps.lock-check.outputs.lock-age }}
run: |
REVIEW_URL="https://github.com/$REPOSITORY/pull/$PR_NUMBER"
echo "review-url=$REVIEW_URL" >> $GITHUB_OUTPUT
if [ "$SKIP_REASON" = "concurrent" ]; then
STATUS="⏭️ **Review skipped** — another review is already in progress"
gh api "repos/$REPOSITORY/issues/$PR_NUMBER/comments" \
-f body="⏭️ **Review skipped** — another review for this PR is already in progress (started ${LOCK_AGE}s ago). Only one review runs at a time to avoid duplicate comments. The in-progress review will post its results when complete." \
2>&1 || {
echo "::warning::Failed to post skip comment to PR"
STATUS="${STATUS} (⚠️ failed to notify on PR)"
}
elif [ -z "$EXIT_CODE" ]; then
STATUS="⏭️ **Review skipped** — agent did not run"
elif [ "$EXIT_CODE" != "0" ]; then
# Check if agent actually posted a review despite the error exit code.
# This happens when a sub-agent fails (e.g., API overload) but the root
# agent recovers and posts the review itself.
if [ -n "$VERBOSE_LOG_FILE" ] && grep -qE 'pullrequestreview-[0-9]+' "$VERBOSE_LOG_FILE" 2>/dev/null; then
echo "::warning::Agent exited $EXIT_CODE but a review was posted — treating as partial success"
STATUS="⚠️ **Review completed with warnings** (exit code: $EXIT_CODE)"
else
STATUS="❌ **Review failed** (exit code: $EXIT_CODE)"
if ! gh api "repos/$REPOSITORY/issues/$PR_NUMBER/comments" \
-f body="❌ **PR Review Failed** — The review agent encountered an error and could not complete the review. [View logs]($RUN_URL)." \
2>&1; then
echo "::warning::Failed to post fallback comment to PR"
fi
fi
else
STATUS="✅ **Review completed**"
fi
# Override the default summary with a cleaner one for PR reviews
{
echo ""
echo "---"
echo ""
echo "## PR Review Summary"
echo ""
echo "$STATUS"
echo ""
echo "📝 [View Pull Request #$PR_NUMBER]($REVIEW_URL)"
} >> $GITHUB_STEP_SUMMARY
- name: Add completion reaction
if: steps.resolve-context.outputs.comment-id != '' && always() && steps.lock-check.outputs.skip != 'true'
shell: bash
env:
GH_TOKEN: ${{ steps.resolve-token.outputs.token }}
EXIT_CODE: ${{ steps.run-review.outputs.exit-code }}
run: |
if [ "$EXIT_CODE" != "0" ]; then
gh api "repos/${{ github.repository }}/issues/comments/${{ steps.resolve-context.outputs.comment-id }}/reactions" \
-X POST -f content='confused' || true
else
gh api "repos/${{ github.repository }}/issues/comments/${{ steps.resolve-context.outputs.comment-id }}/reactions" \
-X POST -f content='+1' || true
fi