-
Notifications
You must be signed in to change notification settings - Fork 0
1893 lines (1678 loc) · 90.6 KB
/
Copy pathpull-request.yml
File metadata and controls
1893 lines (1678 loc) · 90.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
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
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
name: Pull Request
on:
workflow_call:
inputs:
internal_app:
description: "Set true for internal apps where low-risk changes do not require approval"
type: boolean
required: false
default: false
claude_model:
description: "Claude model used for automated PR review"
type: string
required: false
default: claude-opus-5
claude_extra_prompt:
description: "Optional repository-specific Claude review instructions"
type: string
required: false
default: ""
claude_allowed_bots:
description: "Comma-separated bot actors allowed to trigger automated Claude PR review"
type: string
required: false
default: "github-actions,github-actions[bot]"
context_repositories:
description: "Newline-separated GitHub repositories to clone as read-only review context"
type: string
required: false
default: |
simpleanalytics/admin
simpleanalytics/assistant
simpleanalytics/boardroom
simpleanalytics/chat
simpleanalytics/common
simpleanalytics/compare-node-versions-action
simpleanalytics/dashboard
simpleanalytics/docs
simpleanalytics/dropzone
simpleanalytics/elasticsearch-api
simpleanalytics/embed
simpleanalytics/extension
simpleanalytics/github-actions
simpleanalytics/google-tag-manager
simpleanalytics/infrastructure
simpleanalytics/intranet
simpleanalytics/main
simpleanalytics/marketing-site
simpleanalytics/news-alerts
simpleanalytics/notify
simpleanalytics/online
simpleanalytics/playground.simpleanalytics.com
simpleanalytics/queue
simpleanalytics/recall
simpleanalytics/screenshot-grabber
simpleanalytics/scripts
simpleanalytics/status
simpleanalytics/strapi
simpleanalytics/support-reminder
simpleanalytics/wordpress-plugin
context_clone_concurrency:
description: "Maximum number of context repositories to clone in parallel"
type: number
required: false
default: 8
secrets:
ANTHROPIC_API_KEY:
required: true
SA_PAT_ADRIAAN_READ_REPOS:
required: false
jobs:
claude-review:
runs-on: ubuntu-latest
if: ${{ !github.event.pull_request.draft && github.event_name == 'pull_request' && contains(fromJson('["opened", "reopened", "synchronize"]'), github.event.action) }}
concurrency:
group: claude-pr-review-${{ github.repository }}-${{ github.event.pull_request.number }}
cancel-in-progress: false
permissions:
contents: read
pull-requests: write
issues: write
actions: read
steps:
- name: Ensure SDLC labels
uses: actions/github-script@v9
with:
script: |
const labels = [
{
name: 'change: needs review',
color: 'b60205',
description: 'Changes affecting security, data protection, or system stability.',
},
{
name: 'change: routine',
color: 'fbca04',
description: 'Changes to internal tools or low-risk changes (e.g., design updates or content modifications)',
},
];
for (const label of labels) {
try {
await github.rest.issues.getLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
});
await github.rest.issues.updateLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
new_name: label.name,
color: label.color,
description: label.description,
});
} catch (error) {
if (error.status !== 404) throw error;
await github.rest.issues.createLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
color: label.color,
description: label.description,
});
}
}
- name: Checkout pull request branch
uses: actions/checkout@v7
with:
repository: ${{ github.event.pull_request.head.repo.full_name }}
ref: ${{ github.event.pull_request.head.ref }}
fetch-depth: 0
- name: Fetch base branch
env:
BASE_REF: ${{ github.event.pull_request.base.ref }}
run: |
git remote add base "https://github.com/${{ github.repository }}.git" 2>/dev/null || git remote set-url base "https://github.com/${{ github.repository }}.git"
git fetch --no-tags --prune --depth=200 base "$BASE_REF"
- name: Index current pull request patches
id: current_patches
env:
BASE_SHA: ${{ github.event.pull_request.base.sha }}
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
run: |
merge_base="$(git merge-base "$BASE_SHA" "$HEAD_SHA")"
patch_index="$RUNNER_TEMP/current-pr-patches.tsv"
: > "$patch_index"
while read -r commit_sha; do
parent_sha="$(git rev-parse "$commit_sha^" 2>/dev/null || true)"
[[ -n "$parent_sha" ]] || continue
patch_id="$(
git diff --binary "$parent_sha" "$commit_sha" |
git patch-id --stable |
awk 'NR == 1 { print $1 }'
)"
if [[ "$patch_id" =~ ^[a-f0-9]{40}$ ]]; then
printf '%s\t%s\n' "$patch_id" "$commit_sha" >> "$patch_index"
fi
done < <(git rev-list --reverse "$merge_base..$HEAD_SHA" | tail -n 500)
patches_json="$(jq -Rn '[inputs | split("\t") | {patch_id: .[0], commit_sha: .[1]}]' < "$patch_index")"
{
echo "merge_base=$merge_base"
echo "patches_json<<EOF"
echo "$patches_json"
echo "EOF"
} >> "$GITHUB_OUTPUT"
- name: Find previous Claude review checkpoint
id: previous_review
uses: actions/github-script@v9
with:
script: |
const owner = context.repo.owner;
const repo = context.repo.repo;
const nameWithOwner = `${owner}/${repo}`;
const issueNumber = context.payload.pull_request.number;
const trustedBotLogins = new Set(['github-actions[bot]']);
const markerPattern = /<!--\s*simpleanalytics-claude-pr-review-checkpoint\s+([\s\S]*?)\s*-->/g;
const comments = await github.paginate(github.rest.issues.listComments, {
owner,
repo,
issue_number: issueNumber,
per_page: 100,
});
const checkpoints = [];
const fallbackClaudeComments = [];
for (const comment of comments) {
if (!trustedBotLogins.has(comment.user?.login)) continue;
const body = comment.body || '';
let match;
markerPattern.lastIndex = 0;
while ((match = markerPattern.exec(body)) !== null) {
try {
const checkpoint = JSON.parse(match[1].trim());
if (
[1, 2].includes(checkpoint.version) &&
checkpoint.repository === nameWithOwner &&
Number(checkpoint.pull_request) === Number(issueNumber) &&
/^[a-f0-9]{40}$/i.test(checkpoint.head_sha || '')
) {
checkpoints.push({
headSha: checkpoint.head_sha,
reviewedAt: checkpoint.reviewed_at || comment.updated_at || comment.created_at,
commentId: comment.id,
});
}
} catch (error) {
core.warning(`Ignoring invalid Claude review checkpoint in comment ${comment.id}: ${error.message}`);
}
}
if (/\bclaude\b/i.test(body)) {
fallbackClaudeComments.push({
reviewedAt: comment.updated_at || comment.created_at,
commentId: comment.id,
});
}
}
checkpoints.sort((left, right) => new Date(right.reviewedAt) - new Date(left.reviewedAt));
fallbackClaudeComments.sort((left, right) => new Date(right.reviewedAt) - new Date(left.reviewedAt));
const checkpoint = checkpoints[0];
if (checkpoint) {
core.setOutput('head_sha', checkpoint.headSha);
core.setOutput('reviewed_at', checkpoint.reviewedAt);
core.setOutput('source', `checkpoint-comment-${checkpoint.commentId}`);
core.info(`Found previous Claude review checkpoint ${checkpoint.headSha} from ${checkpoint.reviewedAt}.`);
return;
}
const fallback = fallbackClaudeComments[0];
if (fallback) {
core.setOutput('head_sha', '');
core.setOutput('reviewed_at', fallback.reviewedAt);
core.setOutput('source', `claude-comment-${fallback.commentId}`);
core.info(`No checkpoint marker found. Falling back to latest trusted Claude bot comment from ${fallback.reviewedAt}.`);
return;
}
core.setOutput('head_sha', '');
core.setOutput('reviewed_at', '');
core.setOutput('source', '');
core.info('No previous Claude review checkpoint found.');
- name: Find reviewed patches in related pull requests
id: related_reviews
uses: actions/github-script@v9
env:
CURRENT_PATCHES_JSON: ${{ steps.current_patches.outputs.patches_json }}
CURRENT_PR_NUMBER: ${{ github.event.pull_request.number }}
LOOKUP_TIMEOUT_MS: 30000
with:
script: |
const owner = context.repo.owner;
const repo = context.repo.repo;
const nameWithOwner = `${owner}/${repo}`;
const currentPrNumber = Number(process.env.CURRENT_PR_NUMBER);
const timeoutMs = Number(process.env.LOOKUP_TIMEOUT_MS || 30000);
const trustedBotLogins = new Set(['github-actions', 'github-actions[bot]']);
const markerPattern = /<!--\s*simpleanalytics-claude-pr-review-checkpoint\s+([\s\S]*?)\s*-->/g;
const shaPattern = /^[a-f0-9]{40}$/i;
function emptyResult(status, message) {
core.setOutput('reviewed_commit_shas', '[]');
core.setOutput('source_pull_requests', '[]');
core.setOutput('legacy_checkpoints', '[]');
core.setOutput('matched_patch_count', '0');
core.setOutput('lookup_status', status);
core.setOutput('lookup_message', message || '');
if (status === 'failed') {
core.warning(message, { title: 'Cross-PR review deduplication' });
} else if (message) {
core.info(message);
}
}
let currentPatches;
try {
currentPatches = JSON.parse(process.env.CURRENT_PATCHES_JSON || '[]');
} catch (error) {
emptyResult('failed', `Could not parse the current patch index: ${error.message}`);
return;
}
const currentPatchCommits = new Map();
for (const entry of currentPatches) {
if (!shaPattern.test(entry.patch_id || '') || !shaPattern.test(entry.commit_sha || '')) continue;
const patchId = entry.patch_id.toLowerCase();
const commits = currentPatchCommits.get(patchId) || [];
commits.push(entry.commit_sha.toLowerCase());
currentPatchCommits.set(patchId, commits);
}
if (!currentPatchCommits.size) {
emptyResult('no-patches', 'The current pull request has no patch IDs to compare.');
return;
}
const query = `
query RelatedReviewCheckpoints($owner: String!, $repo: String!) {
repository(owner: $owner, name: $repo) {
openPullRequests: pullRequests(
states: OPEN
first: 50
orderBy: { field: UPDATED_AT, direction: DESC }
) {
nodes {
number
firstComments: comments(first: 20) {
nodes { id author { login } body updatedAt }
}
lastComments: comments(last: 20) {
nodes { id author { login } body updatedAt }
}
}
}
mergedPullRequests: pullRequests(
states: MERGED
first: 20
orderBy: { field: UPDATED_AT, direction: DESC }
) {
nodes {
number
mergedAt
firstComments: comments(first: 20) {
nodes { id author { login } body updatedAt }
}
lastComments: comments(last: 20) {
nodes { id author { login } body updatedAt }
}
}
}
}
}
`;
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
let result;
try {
const response = await github.request('POST /graphql', {
query,
variables: { owner, repo },
request: { signal: controller.signal },
});
if (response.data.errors?.length) {
throw new Error(response.data.errors.map((error) => error.message).join('; '));
}
result = response.data.data;
} catch (error) {
emptyResult('failed', `Cross-PR checkpoint lookup failed; reviewing normally: ${error.message}`);
return;
} finally {
clearTimeout(timeoutId);
}
const mergedCutoff = Date.now() - (14 * 24 * 60 * 60 * 1000);
const candidates = [
...(result.repository.openPullRequests.nodes || []),
...(result.repository.mergedPullRequests.nodes || []).filter(
(pullRequest) => Date.parse(pullRequest.mergedAt || 0) >= mergedCutoff,
),
].filter((pullRequest) => Number(pullRequest.number) !== currentPrNumber);
const reviewedCommitShas = new Set();
const sourcePullRequests = new Set();
const legacyCheckpoints = [];
for (const pullRequest of candidates) {
const commentsById = new Map();
for (const comment of [
...(pullRequest.firstComments?.nodes || []),
...(pullRequest.lastComments?.nodes || []),
]) {
commentsById.set(comment.id, comment);
}
const checkpoints = [];
for (const comment of commentsById.values()) {
if (!trustedBotLogins.has(comment.author?.login)) continue;
markerPattern.lastIndex = 0;
let match;
while ((match = markerPattern.exec(comment.body || '')) !== null) {
try {
const checkpoint = JSON.parse(match[1].trim());
if (
[1, 2].includes(checkpoint.version) &&
checkpoint.repository === nameWithOwner &&
Number(checkpoint.pull_request) === Number(pullRequest.number) &&
shaPattern.test(checkpoint.base_sha || '') &&
shaPattern.test(checkpoint.head_sha || '')
) {
checkpoints.push(checkpoint);
}
} catch (error) {
core.warning(`Ignoring invalid cross-PR checkpoint in comment ${comment.id}: ${error.message}`);
}
}
}
checkpoints.sort(
(left, right) => Date.parse(right.reviewed_at || 0) - Date.parse(left.reviewed_at || 0),
);
const checkpoint = checkpoints[0];
if (!checkpoint) continue;
if (checkpoint.version === 1) {
legacyCheckpoints.push({
base_sha: checkpoint.base_sha.toLowerCase(),
head_sha: checkpoint.head_sha.toLowerCase(),
pull_request: Number(pullRequest.number),
});
continue;
}
if (!Array.isArray(checkpoint.reviewed_patch_ids)) continue;
for (const patchId of checkpoint.reviewed_patch_ids) {
const commitShas = currentPatchCommits.get(String(patchId).toLowerCase()) || [];
for (const commitSha of commitShas) {
reviewedCommitShas.add(commitSha);
sourcePullRequests.add(Number(pullRequest.number));
}
}
}
core.setOutput('reviewed_commit_shas', JSON.stringify([...reviewedCommitShas]));
core.setOutput('source_pull_requests', JSON.stringify([...sourcePullRequests].sort((a, b) => a - b)));
core.setOutput('legacy_checkpoints', JSON.stringify(legacyCheckpoints));
core.setOutput('matched_patch_count', String(reviewedCommitShas.size));
const lookupMessage = (
reviewedCommitShas.size
? `Matched ${reviewedCommitShas.size} reviewed patches from PRs ${[...sourcePullRequests].join(', ')}.`
: 'No matching version-2 patch fingerprints were found in related pull requests.'
);
core.setOutput('lookup_status', reviewedCommitShas.size ? 'matched' : 'no-match');
core.setOutput('lookup_message', lookupMessage);
core.info(lookupMessage);
- name: Resolve review scope
id: review_scope
env:
BASE_SHA: ${{ github.event.pull_request.base.sha }}
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
LAST_REVIEWED_SHA: ${{ steps.previous_review.outputs.head_sha }}
LAST_REVIEWED_AT: ${{ steps.previous_review.outputs.reviewed_at }}
LAST_REVIEW_SOURCE: ${{ steps.previous_review.outputs.source }}
CURRENT_MERGE_BASE: ${{ steps.current_patches.outputs.merge_base }}
RELATED_REVIEWED_SHAS_JSON: ${{ steps.related_reviews.outputs.reviewed_commit_shas }}
RELATED_REVIEW_SOURCE_PRS: ${{ steps.related_reviews.outputs.source_pull_requests }}
RELATED_LEGACY_CHECKPOINTS: ${{ steps.related_reviews.outputs.legacy_checkpoints }}
RELATED_LOOKUP_STATUS: ${{ steps.related_reviews.outputs.lookup_status }}
RELATED_LOOKUP_MESSAGE: ${{ steps.related_reviews.outputs.lookup_message }}
run: |
full_pr_range="$BASE_SHA...$HEAD_SHA"
mode="full-pr"
diff_range="$full_pr_range"
scope_start_sha="$CURRENT_MERGE_BASE"
scope_description="Review the full pull request diff: $full_pr_range."
last_review_note="No previous trusted Claude review checkpoint was found."
if [[ -n "$LAST_REVIEWED_SHA" ]]; then
if git cat-file -e "$LAST_REVIEWED_SHA^{commit}" 2>/dev/null && git merge-base --is-ancestor "$LAST_REVIEWED_SHA" "$HEAD_SHA"; then
mode="since-last-claude-review"
diff_range="$LAST_REVIEWED_SHA..$HEAD_SHA"
scope_start_sha="$LAST_REVIEWED_SHA"
scope_description="Review current PR changes not checked since Claude last reviewed commit $LAST_REVIEWED_SHA. Use $full_pr_range as the current full PR diff and ignore base-only branch update changes."
last_review_note="Last trusted Claude checkpoint: $LAST_REVIEWED_SHA from $LAST_REVIEW_SOURCE."
else
echo "::warning::Previous Claude checkpoint $LAST_REVIEWED_SHA is not available on the current PR branch. Reviewing the full PR diff instead."
last_review_note="Previous trusted Claude checkpoint $LAST_REVIEWED_SHA from $LAST_REVIEW_SOURCE is not available on this branch, so the workflow fell back to the full PR diff."
fi
elif [[ -n "$LAST_REVIEWED_AT" ]]; then
checkpoint_sha="$(git rev-list -n 1 --before="$LAST_REVIEWED_AT" "$HEAD_SHA" 2>/dev/null || true)"
if [[ -n "$checkpoint_sha" ]] && git merge-base --is-ancestor "$checkpoint_sha" "$HEAD_SHA"; then
mode="since-last-claude-comment"
diff_range="$checkpoint_sha..$HEAD_SHA"
scope_start_sha="$checkpoint_sha"
scope_description="Review current PR changes not checked since the latest trusted Claude bot comment at $LAST_REVIEWED_AT. Use $full_pr_range as the current full PR diff and ignore base-only branch update changes."
last_review_note="No checkpoint marker existed. Approximated the last reviewed commit as $checkpoint_sha from trusted Claude bot comment time $LAST_REVIEWED_AT."
else
echo "::warning::Could not map the latest trusted Claude bot comment at $LAST_REVIEWED_AT to a commit. Reviewing the full PR diff instead."
last_review_note="A trusted Claude bot comment existed at $LAST_REVIEWED_AT, but it could not be mapped to a commit, so the workflow fell back to the full PR diff."
fi
fi
related_reviewed_index="$RUNNER_TEMP/related-reviewed-shas.txt"
: > "$related_reviewed_index"
jq -r '.[] | select(test("^[a-f0-9]{40}$"))' <<< "${RELATED_REVIEWED_SHAS_JSON:-[]}" >> "$related_reviewed_index"
source_pr_index="$RUNNER_TEMP/related-review-source-prs.txt"
: > "$source_pr_index"
jq -r '.[]' <<< "${RELATED_REVIEW_SOURCE_PRS:-[]}" >> "$source_pr_index"
while IFS=$'\t' read -r legacy_base legacy_head legacy_pr; do
if
[[ "$legacy_base" =~ ^[a-f0-9]{40}$ ]] &&
[[ "$legacy_head" =~ ^[a-f0-9]{40}$ ]] &&
[[ "$legacy_pr" =~ ^[0-9]+$ ]] &&
git cat-file -e "$legacy_base^{commit}" 2>/dev/null &&
git cat-file -e "$legacy_head^{commit}" 2>/dev/null &&
git merge-base --is-ancestor "$legacy_base" "$scope_start_sha" &&
git merge-base --is-ancestor "$scope_start_sha" "$legacy_head" &&
git merge-base --is-ancestor "$legacy_head" "$HEAD_SHA"
then
git rev-list "$scope_start_sha..$legacy_head" >> "$related_reviewed_index"
echo "$legacy_pr" >> "$source_pr_index"
fi
done < <(
jq -r '.[] | [.base_sha, .head_sha, (.pull_request | tostring)] | @tsv' <<< "${RELATED_LEGACY_CHECKPOINTS:-[]}"
)
source_prs="$(
sort -nu "$source_pr_index" |
jq -Rrsc 'split("\n") | map(select(length > 0) | tonumber) | unique | map("#" + tostring) | join(", ")'
)"
sort -u -o "$related_reviewed_index" "$related_reviewed_index"
reviewed_commits=()
unreviewed_commits=()
while read -r commit_sha; do
if grep -Fxq "$commit_sha" "$related_reviewed_index"; then
reviewed_commits+=("$commit_sha")
else
unreviewed_commits+=("$commit_sha")
fi
done < <(git rev-list --reverse "$scope_start_sha..$HEAD_SHA")
reviewed_commit_shas="${reviewed_commits[*]}"
unreviewed_commit_shas="${unreviewed_commits[*]}"
if (( ${#reviewed_commits[@]} > 0 )); then
mode="cross-pr-deduplicated"
scope_description="Review only these unreviewed commits: ${unreviewed_commit_shas:-none}. Treat commits already reviewed in ${source_prs:-related pull requests} as context only and do not repeat their findings."
last_review_note="$last_review_note Cross-PR reviewed commits: $reviewed_commit_shas from ${source_prs:-related pull requests}."
echo "::notice title=Cross-PR review deduplication::Skipped ${#reviewed_commits[@]} already-reviewed commit(s) from ${source_prs:-related pull requests}; ${#unreviewed_commits[@]} commit(s) remain for review."
fi
{
echo "### Cross-PR review deduplication"
if (( ${#reviewed_commits[@]} > 0 )); then
echo "- Result: skipped ${#reviewed_commits[@]} already-reviewed commit(s); ${#unreviewed_commits[@]} remain for review."
echo "- Source PRs: ${source_prs:-unknown}"
echo "- Skipped commits: $reviewed_commit_shas"
echo "- Remaining commits: ${unreviewed_commit_shas:-none}"
elif [[ "$RELATED_LOOKUP_STATUS" == "failed" ]]; then
echo "- Result: lookup failed; retained the normal review scope."
echo "- Details: ${RELATED_LOOKUP_MESSAGE:-unknown failure}"
elif [[ "$RELATED_LOOKUP_STATUS" == "no-patches" ]]; then
echo "- Result: the current PR has no patch fingerprints to compare."
else
echo "- Result: no previously reviewed patches apply to the active review scope."
fi
} >> "$GITHUB_STEP_SUMMARY"
{
echo "mode=$mode"
echo "diff_range=$diff_range"
echo "full_pr_diff_range=$full_pr_range"
echo "reviewed_commit_shas=$reviewed_commit_shas"
echo "unreviewed_commit_shas=$unreviewed_commit_shas"
echo "related_review_source_prs=$source_prs"
echo "scope_description<<EOF"
echo "$scope_description"
echo "EOF"
echo "last_review_note<<EOF"
echo "$last_review_note"
echo "EOF"
} >> "$GITHUB_OUTPUT"
- name: Checkout Simple Analytics context
id: checkout_context
env:
CONTEXT_REPOSITORIES: ${{ inputs.context_repositories }}
CONTEXT_CLONE_CONCURRENCY: ${{ inputs.context_clone_concurrency }}
CURRENT_REPOSITORY: ${{ github.repository }}
READ_TOKEN: ${{ secrets.SA_PAT_ADRIAAN_READ_REPOS }}
run: |
context_dir="$RUNNER_TEMP/simpleanalytics-context"
echo "context_dir=$context_dir" >> "$GITHUB_OUTPUT"
mkdir -p "$context_dir"
status_dir="$RUNNER_TEMP/simpleanalytics-context-status"
rm -rf "$status_dir"
mkdir -p "$status_dir"
if [[ -z "$READ_TOKEN" ]]; then
message="SA_PAT_ADRIAAN_READ_REPOS is not set. Continuing with current-repo context only. Add this repo or org secret from 1Password by searching for SA_PAT_ADRIAAN_READ_REPOS."
echo "::warning::$message"
{
echo "### Cross-repo context"
echo "$message"
} >> "$GITHUB_STEP_SUMMARY"
exit 0
fi
export GIT_TERMINAL_PROMPT=0
askpass="$RUNNER_TEMP/simpleanalytics-git-askpass.sh"
cat > "$askpass" <<'EOF'
#!/usr/bin/env bash
case "$1" in
*Username*) echo "x-access-token" ;;
*Password*) echo "$READ_TOKEN" ;;
*) echo "" ;;
esac
EOF
chmod 700 "$askpass"
export GIT_ASKPASS="$askpass"
github_api_status() {
local url="$1"
local output="$2"
curl --retry 2 --retry-delay 1 --connect-timeout 5 --max-time 20 --silent --show-error \
--output "$output" \
--write-out "%{http_code}" \
--header "Authorization: Bearer $READ_TOKEN" \
--header "Accept: application/vnd.github+json" \
--header "X-GitHub-Api-Version: 2022-11-28" \
"$url" || true
}
token_status="$(github_api_status "https://api.github.com/user" "$status_dir/token-user.json")"
if [[ "$token_status" != "200" ]]; then
message="SA_PAT_ADRIAAN_READ_REPOS is set, but GitHub rejected it or it is not authorized for API access (HTTP ${token_status:-000}). Continuing with current-repo context only. Update the secret from 1Password, authorize it for the Simple Analytics organization if SSO is required, and grant read access to repository contents."
echo "::warning::$message"
{
echo "### Cross-repo context"
echo "$message"
} >> "$GITHUB_STEP_SUMMARY"
exit 0
fi
clone_concurrency="$CONTEXT_CLONE_CONCURRENCY"
if ! [[ "$clone_concurrency" =~ ^[0-9]+$ ]] || [[ "$clone_concurrency" -lt 1 ]]; then
clone_concurrency=8
fi
diagnose_repo_access() {
local repo="$1"
local safe_name="$2"
local repo_status contents_status
repo_status="$(github_api_status "https://api.github.com/repos/$repo" "$status_dir/$safe_name.repo.json")"
case "$repo_status" in
200)
contents_status="$(github_api_status "https://api.github.com/repos/$repo/contents" "$status_dir/$safe_name.contents.json")"
if [[ "$contents_status" == "200" ]]; then
echo "SA_PAT_ADRIAAN_READ_REPOS can read this repo via the API, but git clone failed. Confirm the token is authorized for SSO and that checkout credentials are not overriding the read token."
else
echo "SA_PAT_ADRIAAN_READ_REPOS can see this repo, but cannot read repository contents via the API (HTTP ${contents_status:-000}). For a fine-grained PAT, add this repository and grant Contents: Read."
fi
;;
401)
echo "SA_PAT_ADRIAAN_READ_REPOS was rejected by GitHub (HTTP 401). Update the secret from 1Password; the token is likely expired, revoked, or invalid."
;;
403)
echo "SA_PAT_ADRIAAN_READ_REPOS is forbidden from this repo (HTTP 403). Authorize the token for the Simple Analytics organization if SSO is required, add this repository to the token, and grant Contents: Read."
;;
404)
echo "SA_PAT_ADRIAAN_READ_REPOS cannot see this repo (HTTP 404). Add this repository to the token's selected repositories, grant Contents: Read, or verify the repo name still exists."
;;
*)
echo "Could not verify SA_PAT_ADRIAAN_READ_REPOS access for this repo via the GitHub API (HTTP ${repo_status:-000}). Check token validity, organization SSO authorization, and network/API availability."
;;
esac
}
clone_repo() {
local repo="$1"
local safe_name="${repo//\//__}"
local owner="${repo%%/*}"
local name="${repo#*/}"
local target="$context_dir/$owner/$name"
local log_file="$status_dir/$safe_name.log"
local diagnosis
mkdir -p "$(dirname "$target")"
if (
cd "$RUNNER_TEMP"
git -c "http.https://github.com/.extraheader=" -c credential.helper= clone --depth=1 --filter=blob:none "https://github.com/$repo.git" "$target"
) >"$log_file" 2>&1; then
echo "$repo" > "$status_dir/$safe_name.ok"
printf 'Cloned %s\n' "$repo"
else
diagnosis="$(diagnose_repo_access "$repo" "$safe_name")"
printf '%s\t%s\n' "$repo" "$diagnosis" > "$status_dir/$safe_name.fail"
cat "$log_file"
echo "::warning::Could not clone $repo for Claude context. Continuing without it. $diagnosis"
rm -rf "$target"
fi
}
while IFS= read -r raw_repo; do
repo="${raw_repo%%#*}"
repo="$(printf '%s' "$repo" | xargs)"
if [[ -z "$repo" || "$repo" == "$CURRENT_REPOSITORY" ]]; then
continue
fi
clone_repo "$repo" &
while [[ "$(jobs -rp | wc -l | xargs)" -ge "$clone_concurrency" ]]; do
wait -n || true
done
done <<< "$CONTEXT_REPOSITORIES"
wait || true
cloned="$(find "$status_dir" -name '*.ok' -type f | wc -l | xargs)"
failed="$(find "$status_dir" -name '*.fail' -type f | wc -l | xargs)"
{
echo "### Cross-repo context"
echo "Cloned $cloned repositories into \`$context_dir\` with concurrency $clone_concurrency."
if [[ "$failed" != "0" ]]; then
echo ""
echo "$failed repositories could not be cloned. The review continued without them."
echo ""
find "$status_dir" -name '*.fail' -type f | sort | while IFS=$'\t' read -r repo diagnosis; do
echo "- \`$repo\`: $diagnosis"
done
fi
} >> "$GITHUB_STEP_SUMMARY"
- name: Capture existing linked issue
id: existing_issue
uses: actions/github-script@v9
with:
script: |
const owner = context.repo.owner;
const repo = context.repo.repo;
const nameWithOwner = `${owner}/${repo}`;
const prNumber = context.payload.pull_request.number;
const refs = [];
function addBodyRefs(body) {
const pattern = /\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\s+((?:[\w.-]+\/[\w.-]+)?#\d+)/gi;
let match;
while ((match = pattern.exec(body || '')) !== null) {
refs.push(match[1]);
}
}
const { data: pullRequest } = await github.rest.pulls.get({
owner,
repo,
pull_number: prNumber,
});
addBodyRefs(pullRequest.body || '');
try {
const result = await github.graphql(`
query($owner: String!, $repo: String!, $number: Int!) {
repository(owner: $owner, name: $repo) {
pullRequest(number: $number) {
closingIssuesReferences(first: 20) {
nodes {
number
repository {
nameWithOwner
}
}
}
}
}
}
`, { owner, repo, number: prNumber });
for (const issue of result.repository.pullRequest.closingIssuesReferences.nodes) {
refs.push(issue.repository.nameWithOwner === nameWithOwner
? `#${issue.number}`
: `${issue.repository.nameWithOwner}#${issue.number}`);
}
} catch (error) {
core.warning(`Could not capture closingIssuesReferences via GraphQL: ${error.message}`);
}
const issueRef = refs.find(Boolean) || '';
core.setOutput('ref', issueRef);
core.info(issueRef
? `Captured existing linked issue ${issueRef}.`
: 'No existing linked issue was found.');
- name: Classify PR description provenance
id: description_provenance
uses: actions/github-script@v9
with:
script: |
const owner = context.repo.owner;
const repo = context.repo.repo;
const prNumber = context.payload.pull_request.number;
const capturedAt = new Date().toISOString();
const workflowLogins = new Set(['github-actions', 'github-actions[bot]']);
const knownAutomatedLogins = new Set([
'claude',
'claude[bot]',
'github-actions',
'github-actions[bot]',
'simple-analytics-ai',
'simple-analytics-ai[bot]',
]);
function normalizedLogin(login) {
return String(login || '').trim().toLowerCase();
}
function loginLooksAutomated(login) {
const normalized = normalizedLogin(login);
if (!normalized) return false;
if (knownAutomatedLogins.has(normalized)) return true;
return /(?:^|[-_])(ai|bot|chatgpt|claude|codex|openai)(?:$|[-_\[])/i.test(normalized);
}
function actorIsAutomated(actor) {
const type = actor?.type || actor?.__typename || '';
return type === 'Bot' || type === 'App' || loginLooksAutomated(actor?.login);
}
function actorIsHuman(actor) {
const type = actor?.type || actor?.__typename || '';
return type === 'User' && !loginLooksAutomated(actor?.login);
}
function identityTextLooksAutomated(...values) {
const text = values.filter(Boolean).join(' ');
return /\b(?:chatgpt|claude|codex|openai)\b|codex@simpleanalytics\.invalid|@anthropic\.com/i.test(text);
}
function bodyLooksAutomated(body) {
return [
/(?:generated|written|created)\s+(?:with|by)\s+(?:an?\s+)?(?:ai|chatgpt|claude|codex|openai)\b/i,
/co-authored-by:\s*(?:chatgpt|claude|codex|openai)\b/i,
/<!--\s*(?:ai|chatgpt|claude|codex|openai)[^>]*(?:generated|written|created)/i,
].some((pattern) => pattern.test(body || ''));
}
function commitLooksAutomated(commit) {
return (
actorIsAutomated(commit.author) ||
actorIsAutomated(commit.committer) ||
identityTextLooksAutomated(
commit.commit?.author?.name,
commit.commit?.author?.email,
commit.commit?.committer?.name,
commit.commit?.committer?.email,
commit.commit?.message
)
);
}
const { data: pullRequest } = await github.rest.pulls.get({
owner,
repo,
pull_number: prNumber,
});
const body = pullRequest.body || '';
const edits = [];
try {
const result = await github.graphql(`
query($owner: String!, $repo: String!, $number: Int!) {
repository(owner: $owner, name: $repo) {
pullRequest(number: $number) {
userContentEdits(first: 100) {
nodes {
editedAt
editor {
__typename
login
}
}
}
}
}
}
`, { owner, repo, number: prNumber });
edits.push(...(result.repository.pullRequest.userContentEdits.nodes || []));
} catch (error) {
core.warning(`Could not inspect PR description edit history: ${error.message}`);
}
edits.sort((left, right) => new Date(right.editedAt) - new Date(left.editedAt));
const commits = await github.paginate(github.rest.pulls.listCommits, {
owner,
repo,
pull_number: prNumber,
per_page: 100,
});
const automatedCommits = commits.filter(commitLooksAutomated);
const humanEdit = edits.find((edit) => actorIsHuman(edit.editor));
const latestNonWorkflowEdit = edits.find((edit) =>
edit.editor && !workflowLogins.has(normalizedLogin(edit.editor.login))
);
const pullRequestAuthor = pullRequest.user;
const automatedBranch = /^(?:ai|bot|chatgpt|claude|codex)[\/-]/i.test(pullRequest.head?.ref || '');
const explicitBodySignal = bodyLooksAutomated(body);
const workflowBodySignal = body.includes('<!-- simpleanalytics:changes-start -->');
let kind = 'human';
let reason = 'No reliable automation signal was found; preserving the description as human-authored.';
if (humanEdit) {
reason = `A human (${humanEdit.editor.login}) edited the description; human content takes precedence over every automation signal.`;
} else if (latestNonWorkflowEdit && actorIsAutomated(latestNonWorkflowEdit.editor)) {
kind = 'automated';
reason = `The latest substantive description editor is automated (${latestNonWorkflowEdit.editor.login}).`;
} else if (explicitBodySignal) {
kind = 'automated';
reason = 'The description contains an explicit AI-generation marker.';
} else if (actorIsHuman(pullRequestAuthor)) {
reason = `The pull request author is human (${pullRequestAuthor.login}) and no direct description signal indicates automation.`;
} else if (actorIsAutomated(pullRequestAuthor)) {
kind = 'automated';
reason = `The pull request author is automated (${pullRequestAuthor.login}).`;
} else if (commits.length > 0 && automatedCommits.length === commits.length) {
kind = 'automated';
reason = 'Every pull request commit has an automated author, committer, or AI attribution.';
} else if (automatedBranch && automatedCommits.length > 0) {
kind = 'automated';
reason = 'The agent branch name and commit attribution both indicate automation.';
} else if (workflowBodySignal && automatedCommits.length > 0) {
kind = 'automated';
reason = 'The workflow-managed description marker and commit attribution both indicate automation.';
}
core.setOutput('kind', kind);
core.setOutput('reason', reason);
core.setOutput('body_base64', Buffer.from(body, 'utf8').toString('base64'));
core.setOutput('captured_at', capturedAt);
core.info(`Classified the existing PR description as ${kind}: ${reason}`);
- name: Run Claude PR review
id: claude
uses: anthropics/claude-code-action@v1
env:
GH_TOKEN: ${{ github.token }}
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
github_token: ${{ github.token }}
track_progress: false
use_sticky_comment: false
include_fix_links: true
allowed_bots: ${{ inputs.claude_allowed_bots }}
additional_permissions: |
actions: read
prompt: |
REPO: ${{ github.repository }}
PR NUMBER: ${{ github.event.pull_request.number }}
PR URL: ${{ github.event.pull_request.html_url }}
INTERNAL APP: ${{ inputs.internal_app }}
REVIEW MODE: ${{ steps.review_scope.outputs.mode }}
REVIEW RANGE: ${{ steps.review_scope.outputs.diff_range }}
FULL PR RANGE: ${{ steps.review_scope.outputs.full_pr_diff_range }}
REVIEW SCOPE: ${{ steps.review_scope.outputs.scope_description }}
LAST REVIEW: ${{ steps.review_scope.outputs.last_review_note }}
CROSS-PR REVIEWED COMMITS: ${{ steps.review_scope.outputs.reviewed_commit_shas }}
UNREVIEWED COMMITS: ${{ steps.review_scope.outputs.unreviewed_commit_shas }}
RELATED REVIEWED PRS: ${{ steps.review_scope.outputs.related_review_source_prs }}
CROSS-REPO CONTEXT DIR: ${{ steps.checkout_context.outputs.context_dir }}
EXISTING LINKED ISSUE: ${{ steps.existing_issue.outputs.ref }}
PR DESCRIPTION PROVENANCE: ${{ steps.description_provenance.outputs.kind }}
PR DESCRIPTION PROVENANCE REASON: ${{ steps.description_provenance.outputs.reason }}
Review this pull request for security vulnerabilities, privacy risks, correctness bugs, data loss, runtime/deployment failures, and high-confidence regressions.
Scope rules:
- For full-pr mode, review the full PR diff.
- For since-last-claude-review and since-last-claude-comment mode, focus findings on current PR changes that were not checked after the last trusted Claude review checkpoint.
- For cross-pr-deduplicated mode, review only UNREVIEWED COMMITS with `git show`. Treat CROSS-PR REVIEWED COMMITS as context only; do not report code or documentation findings solely from those commits unless an unreviewed commit materially changes their behavior.
- If cross-pr-deduplicated mode has no UNREVIEWED COMMITS, do not post code or documentation findings; only apply and briefly explain the SDLC label.
- REVIEW RANGE may include base branch update commits. Use FULL PR RANGE as the current pull request diff and do not report base-only branch update changes.
- Do not report issues that already existed before the last trusted Claude review checkpoint unless they are critical, exploitable, or made materially worse by the new commits.
- For SDLC label classification, consider the full pull request, not only the incremental range.
- Use local git commands such as `git diff ${{ steps.review_scope.outputs.diff_range }}` and `git diff ${{ steps.review_scope.outputs.full_pr_diff_range }}` when helpful.
- You may inspect read-only cross-repo context under `${{ steps.checkout_context.outputs.context_dir }}`. Do not edit files there.