Repository navigation
1776 lines (1694 loc) · 108 KB
/
Copy pathlabel-pr-review-state.yml
File metadata and controls
1776 lines (1694 loc) · 108 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: Label PR review state
on:
schedule:
- cron: "0 * * * *" # hourly fallback
push:
branches: [main]
workflow_dispatch:
inputs:
pull_request_number:
description: Pull request number to reconcile
required: true
type: number
stale_dry_run:
description: Set to false to let the stale clock write labels, comments, and closes
required: false
type: string
default: "true"
# This workflow only reads PR metadata and never checks out or executes PR code.
# pull_request_target gives fork PRs a token that can update labels and comments.
pull_request_target:
types:
[
opened,
reopened,
ready_for_review,
converted_to_draft,
synchronize,
review_requested,
review_request_removed,
labeled,
unlabeled,
]
pull_request_review:
types: [submitted, dismissed]
# Fork review events have a read-only token. CodeRabbit's status-comment update
# provides a trusted base-repository event that can reconcile those PRs promptly.
issue_comment:
types: [created, edited]
# Fork pull_request_review runs get a read-only token and skip their label
# writes (issue #2046). The privileged follow-up for those runs lives in
# label-pr-review-state-fork-review-followup.yml: GitHub rejects a workflow
# that lists itself in workflow_run.workflows (issue #2086).
workflow_run:
workflows: ["Code QA Roo Code", "E2E Tests (Mocked)", "Webview Visual Regression", "CodeQL Advanced"]
types: [completed]
permissions:
# This privileged workflow only reads PR/check metadata and writes issue labels,
# comments, and commit statuses. All unspecified permissions, including contents,
# are none; no fork code or configuration is checked out or executed.
pull-requests: write
issues: write
checks: read
statuses: write
# Concurrency is keyed at two levels (issue #1707):
#
# Workflow level (below): keeps bursts of activity on unrelated PRs from
# starving whole runs. GitHub keeps only the newest pending run per group even
# with cancel-in-progress: false, so keying per PR makes that freshest-state-
# wins within one PR. Issue/PR numbers share one GitHub sequence, so
# issue-comment runs can never collide with a different PR's group.
# workflow_run events key by the triggering run's id instead of a PR number: a
# single run can reconcile several associated PRs (and fork runs backfill
# none), so a PR-number key would let an unrelated event for the first PR
# supersede reconciliation of the rest. Fork pull_request_review runs are
# read-only (see isReadOnlyRun in the reconcile script) and write nothing, so
# they take a unique per-run group rather than a PR-keyed group whose
# newest-pending-wins could supersede a queued mutating run for that PR.
# Sweep triggers (hourly schedule, pushes to main) share one group, and
# anything unresolved falls back to a unique per-run group.
#
# Job level (on the reconcile job): every mutating shard keys per PR in one
# shared group namespace, so direct-event shards, sweep-resolved shards, and
# workflow_run-resolved shards for the same PR serialize against each other
# instead of racing non-atomic label, status, and comment writes. Only the
# reconcile job mutates PR state, so no workflow-level key can bypass that
# per-PR serialization.
concurrency:
group: >-
label-pr-review-state-${{
((github.event_name == 'pull_request_review' &&
github.event.pull_request.head.repo.full_name != github.event.pull_request.base.repo.full_name) && github.run_id) ||
github.event.pull_request.number ||
github.event.issue.number ||
github.event.inputs.pull_request_number ||
github.event.workflow_run.id ||
((github.event_name == 'schedule' || github.event_name == 'push') && 'sweep') ||
github.run_id
}}
cancel-in-progress: false
jobs:
resolve:
name: Zoo Code / resolve PRs to reconcile
if: >-
github.event_name != 'issue_comment' ||
(github.event.issue.pull_request && github.event.comment.user.login == 'coderabbitai[bot]')
runs-on: ubuntu-latest
outputs:
pr_numbers: ${{ steps.resolve.outputs.pr_numbers }}
env:
# Mirrors the workflow-level concurrency group so the run's queueing
# identity is visible in the logs (kept in sync by the workflow tests).
CONCURRENCY_GROUP: >-
label-pr-review-state-${{
((github.event_name == 'pull_request_review' &&
github.event.pull_request.head.repo.full_name != github.event.pull_request.base.repo.full_name) && github.run_id) ||
github.event.pull_request.number ||
github.event.issue.number ||
github.event.inputs.pull_request_number ||
github.event.workflow_run.id ||
((github.event_name == 'schedule' || github.event_name == 'push') && 'sweep') ||
github.run_id
}}
steps:
- name: Resolve target PR numbers
id: resolve
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8
with:
retries: 3
script: |
const { owner, repo } = context.repo;
// A queue-superseded run leaves no other trace in the logs.
core.info(`Concurrency group: ${process.env.CONCURRENCY_GROUP}`);
if (context.eventName === 'issue_comment' &&
(!context.payload.issue?.pull_request ||
context.payload.comment?.user?.login?.toLowerCase() !== 'coderabbitai[bot]')) {
core.info('Ignoring untrusted issue comment event');
core.setOutput('pr_numbers', '[]');
return;
}
// Resolve which PRs this event targets. Single-PR events carry the
// number in the payload; sweep triggers (hourly schedule, pushes to
// main) list every open PR; workflow_run events use the run's
// associated PRs, with a fork-safe backfill by exact head owner,
// branch, and SHA when GitHub left pull_requests empty. The
// workflows listed in workflow_run trigger on pull_request, whose
// head_repository is the real fork, so the owner-and-branch query
// is safe here. The follow-up workflow's copy of this backfill
// matches by head branch, SHA, and base repository instead: its
// pull_request_review runs report the base repository as
// head_repository (issue #2133).
let prNumbers = [];
if (context.payload.pull_request?.number) {
prNumbers = [context.payload.pull_request.number];
} else if (context.eventName === 'issue_comment') {
prNumbers = [context.payload.issue.number];
} else if (context.eventName === 'workflow_dispatch') {
prNumbers = [Number(context.payload.inputs.pull_request_number)];
} else if (context.payload.workflow_run?.pull_requests?.length > 0) {
prNumbers = context.payload.workflow_run.pull_requests.map(pr => pr.number);
} else if (context.eventName === 'workflow_run') {
const run = context.payload.workflow_run;
const headOwner = run.head_repository?.owner?.login;
if (headOwner && run.head_branch && run.head_sha) {
const candidates = await github.paginate(github.rest.pulls.list, {
owner,
repo,
state: 'open',
head: `${headOwner}:${run.head_branch}`,
per_page: 100,
});
const baseRepository = `${owner}/${repo}`.toLowerCase();
prNumbers = candidates
.filter(pr =>
pr.head?.sha === run.head_sha &&
pr.base?.repo?.full_name?.toLowerCase() === baseRepository
)
.map(pr => pr.number);
core.info(
`Resolved workflow_run ${run.id ?? '(unknown)'} to ` +
`${prNumbers.length} PR(s) by exact head owner, branch, and SHA`
);
}
} else {
const openPrs = await github.paginate(github.rest.pulls.list, {
owner, repo, state: 'open', per_page: 100,
});
// GitHub rejects matrices over 256 jobs, so the sweep pages the
// sorted open-PR list: consecutive runs rotate through
// fixed-size windows by run number, covering every open PR on a
// bounded cadence without ever exceeding the limit.
const allNumbers = openPrs.map(pr => pr.number).sort((a, b) => a - b);
const sweepPageSize = 200;
const pageCount = Math.max(1, Math.ceil(allNumbers.length / sweepPageSize));
const page = context.runNumber % pageCount;
prNumbers = allNumbers.slice(page * sweepPageSize, (page + 1) * sweepPageSize);
if (allNumbers.length > sweepPageSize) {
core.info(
`Sweep page ${page + 1}/${pageCount}: reconciling ` +
`${prNumbers.length} of ${allNumbers.length} open PRs`
);
}
}
core.info(
`Reconciliation targets: ` +
`${prNumbers.length > 0 ? prNumbers.join(', ') : '(none)'}`
);
core.setOutput('pr_numbers', JSON.stringify(prNumbers));
reconcile:
name: Zoo Code / reconcile PR review state
needs: resolve
if: >-
(github.event_name != 'issue_comment' ||
(github.event.issue.pull_request && github.event.comment.user.login == 'coderabbitai[bot]')) &&
needs.resolve.outputs.pr_numbers != '[]'
strategy:
fail-fast: false
matrix:
pr_number: ${{ fromJSON(needs.resolve.outputs.pr_numbers) }}
# One mutating shard per PR, serialized per PR across every trigger path:
# direct-event shards, sweep-resolved shards, and workflow_run-resolved
# shards all share this group namespace, so their non-atomic writes can
# never interleave. cancel-in-progress stays false — within one PR,
# newest-pending-wins is exactly freshest-state-wins. The run_id fallback
# only applies to the skipped empty-resolution case so empty runs never
# contend. The `-reconcile-` infix keeps job-level groups in their own
# namespace: concurrency groups are one repo-wide namespace across
# workflow and job levels, so a shard group equal to the workflow-level
# group its own run holds (e.g. label-pr-review-state-<pr> for direct
# triggers, or a workflow_run.id that numerically matches a PR number)
# fails the job at startup. Read-only fork pull_request_review shards
# write nothing, so they take a run-scoped `-ro-<run_id>` group instead of
# the PR-keyed group: the non-numeric `-ro-` infix keeps them from ever
# colliding with (or superseding) a mutating shard for the same PR.
concurrency:
group: >-
label-pr-review-state-reconcile-${{
((github.event_name == 'pull_request_review' &&
github.event.pull_request.head.repo.full_name != github.event.pull_request.base.repo.full_name) && 'ro-') || ''
}}${{
((github.event_name == 'pull_request_review' &&
github.event.pull_request.head.repo.full_name != github.event.pull_request.base.repo.full_name) && github.run_id) ||
matrix.pr_number ||
github.run_id
}}
cancel-in-progress: false
runs-on: ubuntu-latest
env:
PR_NUMBER: ${{ matrix.pr_number }}
# Mirrors this job's concurrency group so a superseded shard's queueing
# identity is visible in the logs (kept in sync by the workflow tests).
CONCURRENCY_GROUP: >-
label-pr-review-state-reconcile-${{
((github.event_name == 'pull_request_review' &&
github.event.pull_request.head.repo.full_name != github.event.pull_request.base.repo.full_name) && 'ro-') || ''
}}${{
((github.event_name == 'pull_request_review' &&
github.event.pull_request.head.repo.full_name != github.event.pull_request.base.repo.full_name) && github.run_id) ||
matrix.pr_number ||
github.run_id
}}
steps:
- name: Reconcile PR review state labels
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8
with:
retries: 3
script: |
const { owner, repo } = context.repo;
// A queue-superseded shard leaves no other trace in the logs.
core.info(`Concurrency group: ${process.env.CONCURRENCY_GROUP}`);
// Turn labels reconcile exclusively among themselves: exactly one
// can be true. has-conflicts is deliberately NOT in this group
// (issue #2089) — whether the branch has conflicts is an
// independent fact that can coexist with any turn. It is managed
// only by reconcileConflictFlag below: set on a known dirty read,
// removed on a known read that is not dirty, untouched while
// mergeability is unknown.
const stateLabels = [
'awaiting-author',
'awaiting-coderabbit',
'awaiting-ready',
'awaiting-maintainer',
'awaiting-review', // Legacy label removed during reconciliation.
];
const labelDefinitions = [
{
name: 'awaiting-coderabbit',
color: '5319e7',
description: 'Waiting for automated review of the latest commit',
},
{
name: 'awaiting-ready',
color: '1d76db',
description: 'Automated review complete; waiting for the draft to be marked ready',
},
{
name: 'awaiting-maintainer',
color: '0e8a16',
description: 'Waiting for fresh human maintainer or CODEOWNER approval',
},
{
name: 'coderabbit-review-active',
color: '5319e7',
description: 'Required CI passed; CodeRabbit review is active',
},
{
name: 'community-approved',
color: 'c2e0c6',
description: 'Fresh community approval on the current head; maintainer review still required',
},
];
const guideMarker = '<!-- zoo-code-pr-review-process -->';
const codeRabbitLabelMarkerPrefix = '<!-- coderabbit-review-label:';
const codeRabbitLogin = 'coderabbitai[bot]';
const codeRabbitLogins = new Set([codeRabbitLogin, 'coderabbitai']);
const codeRabbitActiveLabel = 'coderabbit-review-active';
const codeRabbitEligibleBotLogins = new Set(['zoomote[bot]']);
// Advisory priority signal only — kept outside stateLabels so it never
// replaces or blocks the review-state queue labels.
const communityApprovedLabel = 'community-approved';
const reviewGateName = 'Zoo Code / PR review gate';
const reconciliationCheckName = 'Zoo Code / reconcile PR review state';
const workflowRunUrl = `${context.serverUrl}/${owner}/${repo}/actions/runs/${context.runId}`;
if (context.eventName === 'issue_comment' &&
(!context.payload.issue?.pull_request ||
context.payload.comment?.user?.login?.toLowerCase() !== codeRabbitLogin)) {
core.info('Ignoring untrusted issue comment event');
return;
}
// The resolve job fans out one shard per target PR; this job
// reconciles exactly this matrix shard's PR. The single-PR GET
// endpoint returns mergeable fields that list endpoints omit.
const { data: shardPr } = await github.rest.pulls.get({
owner,
repo,
pull_number: Number(process.env.PR_NUMBER),
});
const prs = shardPr.state === 'open' ? [shardPr] : [];
// pull_request_review runs originating from forks can still receive a read-only
// token. pull_request_target, schedule, and workflow_dispatch runs execute in the
// base repository context and can safely mutate metadata without trusting PR code.
// See: https://docs.github.com/en/actions/concepts/security/github_token
const isReadOnlyRun = context.eventName === 'pull_request_review' &&
Boolean(context.payload.pull_request) &&
context.payload.pull_request.head?.repo?.full_name !==
context.payload.pull_request.base?.repo?.full_name;
function isForkPR(pr) {
return pr.head?.repo?.full_name && pr.head.repo.full_name !== pr.base?.repo?.full_name;
}
if (!isReadOnlyRun) {
// One paginated list keeps the per-shard API budget flat no matter
// how many labels are managed; per-label getLabel calls would
// multiply across a full sweep against the Actions token pool.
const repoLabels = await github.paginate(github.rest.issues.listLabelsForRepo, {
owner, repo, per_page: 100,
});
const existingLabelNames = new Set(repoLabels.map(label => label.name));
for (const label of labelDefinitions) {
if (existingLabelNames.has(label.name)) continue;
try {
await github.rest.issues.createLabel({ owner, repo, ...label });
} catch (createError) {
// Concurrent shards for other PRs can win the creation race.
// Tolerate only the duplicate-label payload; any other 422
// must fail the shard.
const isDuplicateRace = createError.status === 422 &&
(createError.response?.data?.errors ?? []).some(
error => error.code === 'already_exists' && error.field === 'name'
);
if (!isDuplicateRace) throw createError;
}
}
}
// Strips stateLabels (turn labels) from a PR, optionally keeping
// one desired label. Callers skip this entirely while mergeability
// is unknown (see the hoisted check below), so no keep-list is
// needed. has-conflicts lives outside this group: it is the
// independent conflict flag managed by reconcileConflictFlag, so
// turn-label reconciliation — including the outer failure cleanup
// — never strips or sets it.
// Stale-clock labels are owned by the stale step below and are never
// touched here: stripping one on a transient CI or mergeability flap
// would erase a live warning and restart its close grace (issue #2076).
// Only skipped when this run's own token is read-only (see isReadOnlyRun) —
// schedule/workflow_dispatch runs reconcile fork PRs normally.
async function reconcileLabels(pr, desiredLabel) {
if (isReadOnlyRun && isForkPR(pr)) {
core.info(`PR #${pr.number}: fork PR on a read-only run — skipping label mutation`);
return;
}
const currentLabels = new Set(pr.labels.map(l => l.name));
const labelErrors = [];
if (desiredLabel && !currentLabels.has(desiredLabel)) {
try {
await github.rest.issues.addLabels({
owner, repo, issue_number: pr.number, labels: [desiredLabel],
});
currentLabels.add(desiredLabel);
pr.labels.push({ name: desiredLabel });
} catch (err) {
const error = new Error(`Could not add desired label: ${err.message}`);
error.preserveStateLabels = true;
throw error;
}
}
for (const label of stateLabels) {
if (label !== desiredLabel && currentLabels.has(label)) {
try {
await github.rest.issues.removeLabel({
owner, repo, issue_number: pr.number, name: label,
});
currentLabels.delete(label);
pr.labels = pr.labels.filter(current => current.name !== label);
} catch (err) {
if (err.status === 404) {
currentLabels.delete(label);
pr.labels = pr.labels.filter(current => current.name !== label);
} else {
labelErrors.push(err);
}
}
}
}
if (labelErrors.length > 0) {
throw new Error(`Could not reconcile labels: ${labelErrors.map(err => err.message).join('; ')}`);
}
}
// Reconciles the independent has-conflicts flag (issue #2089).
// `present` is a mergeability fact, so callers pass a known read
// only: true for a known dirty read, false for a known read that
// is not dirty. While mergeability is unknown no caller runs, so
// the flag freezes together with the turn labels. A conflicted PR
// must never sit in the maintainer queue, so every conflict
// branch pairs this call with reconcileLabels(pr, 'awaiting-author').
async function reconcileConflictFlag(pr, present) {
if (isReadOnlyRun && isForkPR(pr)) {
core.info(`PR #${pr.number}: fork PR on a read-only run — skipping label mutation`);
return;
}
const hasLabel = pr.labels.some(label => label.name === 'has-conflicts');
if (present === hasLabel) return;
try {
if (present) {
await github.rest.issues.addLabels({
owner, repo, issue_number: pr.number, labels: ['has-conflicts'],
});
if (!pr.labels.some(label => label.name === 'has-conflicts')) {
pr.labels.push({ name: 'has-conflicts' });
}
} else {
await github.rest.issues.removeLabel({
owner, repo, issue_number: pr.number, name: 'has-conflicts',
});
pr.labels = pr.labels.filter(label => label.name !== 'has-conflicts');
}
} catch (err) {
if (err.status === 404 && !present) {
pr.labels = pr.labels.filter(label => label.name !== 'has-conflicts');
return;
}
// The flag already decided this run's label state, so a
// failed flag write must fail closed: mark the wrapper
// error so the outer cleanup keeps the current state
// labels exactly like the unknown-mergeability freeze
// instead of stripping them.
const error = new Error(`Could not reconcile has-conflicts label: ${err.message}`);
error.preserveStateLabels = true;
throw error;
}
}
async function findReviewGuide(pr) {
const comments = await github.paginate(github.rest.issues.listComments, {
owner, repo, issue_number: pr.number, per_page: 100,
});
return comments.find(comment =>
comment.user?.login === 'github-actions[bot]' && comment.body?.includes(guideMarker)
);
}
async function setCodeRabbitReviewActive(pr, enabled, recycle = false) {
if (isReadOnlyRun && isForkPR(pr)) return;
const hasLabel = pr.labels.some(label => label.name === codeRabbitActiveLabel);
if (enabled && hasLabel && recycle) {
try {
await github.rest.issues.removeLabel({
owner, repo, issue_number: pr.number, name: codeRabbitActiveLabel,
});
} catch (error) {
if (error.status !== 404) throw error;
}
pr.labels = pr.labels.filter(label => label.name !== codeRabbitActiveLabel);
}
if (enabled && (!hasLabel || recycle)) {
let addError = null;
for (let attempt = 1; attempt <= 2; attempt++) {
try {
await github.rest.issues.addLabels({
owner, repo, issue_number: pr.number, labels: [codeRabbitActiveLabel],
});
if (!pr.labels.some(label => label.name === codeRabbitActiveLabel)) {
pr.labels.push({ name: codeRabbitActiveLabel });
}
delete pr.codeRabbitActivationUncertain;
return;
} catch (error) {
addError = error;
if (attempt === 1) {
core.warning(`PR #${pr.number}: retrying CodeRabbit activation label: ${error.message}`);
}
}
}
pr.codeRabbitActivationUncertain = true;
try {
const { data: issue } = await github.rest.issues.get({
owner, repo, issue_number: pr.number,
});
pr.labels = issue.labels.map(label =>
typeof label === 'string' ? { name: label } : label
);
if (pr.labels.some(label => label.name === codeRabbitActiveLabel)) {
delete pr.codeRabbitActivationUncertain;
return;
}
} catch (verificationError) {
core.warning(
`PR #${pr.number}: could not verify CodeRabbit activation label: ${verificationError.message}`
);
}
throw addError;
} else if (!enabled && (hasLabel || pr.codeRabbitActivationUncertain)) {
try {
await github.rest.issues.removeLabel({
owner, repo, issue_number: pr.number, name: codeRabbitActiveLabel,
});
} catch (error) {
if (error.status !== 404) throw error;
}
pr.labels = pr.labels.filter(label => label.name !== codeRabbitActiveLabel);
delete pr.codeRabbitActivationUncertain;
}
}
// Reconciles the advisory community-approved label. The label means
// "fresh community code approval for the current head; maintainer
// review still required" — it is a priority signal only and never
// grants merge authority. Every reconciliation branch routes through
// this one helper with a single decision:
// 'add' — stable head, maintainer queue, qualifying fresh approval
// 'remove' — known non-maintainer phase, known head change, or
// invalidated approval (known invalidation beats uncertainty)
// 'preserve' — unknown mergeability, or a permission lookup that
// fails only in the community check, with no known
// invalidation. A lookup failure that also blocks
// maintainer classification fails the PR and removes
// the label through the outer catch instead.
// A failed community label update is advisory: it must not clear the
// queue label or fail the review gate, so errors are logged, not thrown.
async function reconcileCommunityApproval(pr, decision) {
if (isReadOnlyRun && isForkPR(pr)) return;
if (decision === 'preserve') return;
const hasLabel = pr.labels.some(label => label.name === communityApprovedLabel);
try {
if (decision === 'add' && !hasLabel) {
await github.rest.issues.addLabels({
owner, repo, issue_number: pr.number, labels: [communityApprovedLabel],
});
pr.labels.push({ name: communityApprovedLabel });
} else if (decision === 'remove' && hasLabel) {
await github.rest.issues.removeLabel({
owner, repo, issue_number: pr.number, name: communityApprovedLabel,
});
pr.labels = pr.labels.filter(label => label.name !== communityApprovedLabel);
}
} catch (error) {
if (decision === 'remove' && error.status === 404) {
pr.labels = pr.labels.filter(label => label.name !== communityApprovedLabel);
return;
}
core.warning(
`PR #${pr.number}: could not ${decision} ${communityApprovedLabel}: ${error.message}`
);
}
}
function codeRabbitLabelHead(comment) {
const markerPattern = new RegExp(`${codeRabbitLabelMarkerPrefix}([a-f0-9]{40}) -->`);
const match = comment?.body?.match(markerPattern);
return match?.[1] ?? null;
}
// Collaborator permissions are repository-level, so memoize them for
// the whole run: a maintainer's current-head CHANGES_REQUESTED reaches
// both review loops, and scheduled sweeps reconcile every open PR.
const permissionCache = new Map();
async function permissionFor(username) {
const key = username.toLowerCase();
if (permissionCache.has(key)) return permissionCache.get(key);
try {
const result = await github.rest.repos.getCollaboratorPermissionLevel({
owner, repo, username,
});
permissionCache.set(key, result.data.permission);
return result.data.permission;
} catch (error) {
if (error.status === 404) {
permissionCache.set(key, 'none');
return 'none';
}
throw error;
}
}
function phaseMessage(phase) {
const messages = {
draft: 'Mark the PR ready. Required CI must pass before CodeRabbit starts.',
conflict: 'Resolve the merge conflicts. The review sequence resumes after the branch is mergeable.',
'ci-pending': 'Wait for required CI checks; awaiting-maintainer requires CI and automated review completion.',
'ci-failed': 'Fix the failing required CI checks; awaiting-maintainer requires CI and automated review completion.',
'mergeability-pending': 'Wait for GitHub to finish calculating mergeability.',
'configuration-error': 'Repository rules must not require this advisory workflow\'s own gate or reconciliation job.',
'coderabbit-changes': 'Address automated review findings and push fixes.',
coderabbit: 'Required CI passed. Waiting for automated review of the latest commit.',
'draft-approved': 'Automated review complete for the latest commit. Mark the draft ready.',
'maintainer-changes': 'Address maintainer or CODEOWNER feedback, push an update, then re-request review from the blocking maintainer.',
maintainer: 'Awaiting fresh human maintainer or CODEOWNER approval.',
approved: 'The required review sequence passed. Remaining merge requirements apply.',
};
return messages[phase];
}
async function updateReviewGate(pr, phase, passed, required = false) {
if (isReadOnlyRun && isForkPR(pr)) return;
const state = passed ? 'success' : 'pending';
const description = phaseMessage(phase);
let latestGateStatus = null;
let lookupSucceeded = false;
try {
const { data: combinedStatus } = await github.rest.repos.getCombinedStatusForRef({
owner, repo, ref: pr.head.sha,
});
lookupSucceeded = true;
latestGateStatus = combinedStatus.statuses
.filter(status => status.context === reviewGateName)
.sort((a, b) => b.id - a.id)[0];
} catch (error) {
core.warning(`PR #${pr.number}: could not inspect ${reviewGateName}: ${error.message}`);
}
if (!lookupSucceeded && passed) return;
if (latestGateStatus?.state === state &&
latestGateStatus.description === description) {
return;
}
const mustInvalidateSuccess = !passed &&
(!lookupSucceeded || latestGateStatus?.state === 'success');
try {
await github.rest.repos.createCommitStatus({
owner,
repo,
sha: pr.head.sha,
state,
context: reviewGateName,
description,
target_url: workflowRunUrl,
});
} catch (error) {
if (required || mustInvalidateSuccess) throw error;
core.warning(`PR #${pr.number}: could not publish ${reviewGateName}: ${error.message}`);
}
}
function reviewGuideBody(pr, phase, activationPending = false) {
const automatedAuthor = pr.user?.type === 'Bot';
const authorNote = automatedAuthor
? 'This PR was opened by an automated account. A human maintainer must verify the change intent, provenance, and validation before merging.'
: 'Thanks for contributing. This comment tracks the review sequence and the next action.';
const labelMarker = phase === 'coderabbit'
? `\n${codeRabbitLabelMarkerPrefix}${pr.head.sha}${activationPending ? ':pending' : ''} -->`
: '';
const phaseHelp = phase === 'coderabbit-changes'
? '\n\nAfter fixes are pushed and required CI passes, automated review restarts.'
: phase === 'coderabbit'
? '\n\nIf automated review does not start, a maintainer must restart it.'
: phase === 'maintainer' && !automatedAuthor
? '\n\nAutomated review is complete for the latest commit but does not replace human approval.'
: '';
return `${guideMarker}\n### Review status\n\n${authorNote}\n\n` +
`**Current step:** ${phaseMessage(phase)}${phaseHelp}\n\n` +
'Review-state labels are managed by this workflow; do not edit them manually. ' +
'`community-approved` is managed the same way — do not add or remove it manually. ' +
'It signals a fresh community code approval for the current head as an advisory ' +
'priority only; maintainer review is still required.' +
labelMarker;
}
async function updateReviewGuide(pr, phase, existingGuide = null, activationPending = false) {
if (isReadOnlyRun && isForkPR(pr)) {
core.info(`PR #${pr.number}: fork PR on a read-only run — skipping guide update`);
return;
}
const body = reviewGuideBody(pr, phase, activationPending);
const existing = existingGuide ?? await findReviewGuide(pr);
if (!existing) {
const { data: created } = await github.rest.issues.createComment({
owner, repo, issue_number: pr.number, body,
});
return created;
} else if (existing.body !== body) {
await github.rest.issues.updateComment({
owner, repo, comment_id: existing.id, body,
});
return { ...existing, body };
}
return existing;
}
// Fetch required status check names from the branch ruleset.
// Uses the public /rules/branches endpoint — no admin token needed.
// Fails closed if the endpoint is unavailable.
let requiredChecks = null;
try {
const rules = await github.paginate(
'GET /repos/{owner}/{repo}/rules/branches/{branch}',
{ owner, repo, branch: 'main', per_page: 100 },
);
const statusRules = rules.filter(rule => rule.type === 'required_status_checks');
requiredChecks = [];
if (statusRules.length > 0) {
const uniqueChecks = new Map();
for (const rule of statusRules) {
for (const check of rule.parameters.required_status_checks) {
const integrationId = check.integration_id ?? null;
uniqueChecks.set(`${check.context}:${integrationId ?? 'any'}`, {
context: check.context,
integrationId,
});
}
}
requiredChecks = [...uniqueChecks.values()];
core.info(
`Required checks: ${requiredChecks.map(check =>
`${check.context}${check.integrationId ? `@${check.integrationId}` : ''}`
).join(', ')}`
);
}
} catch (err) {
core.warning(`Could not fetch branch rules; review gate remains pending: ${err.message}`);
}
const failures = [];
for (const pr of prs) {
let failurePhase = 'ci-pending';
try {
// The matrix job reports one check per shard named
// "<reconciliationCheckName> (<pr_number>)", so catch both the
// bare name and any matrix-suffixed variant.
const selfReferentialRequirements = (requiredChecks ?? []).filter(check =>
check.context === reviewGateName ||
check.context === reconciliationCheckName ||
check.context.startsWith(`${reconciliationCheckName} (`)
);
if (selfReferentialRequirements.length > 0) {
failurePhase = 'configuration-error';
const contexts = selfReferentialRequirements.map(check => check.context).join(', ');
core.warning(
`PR #${pr.number}: unsupported self-referential required check configuration: ${contexts}`
);
await updateReviewGate(pr, 'configuration-error', false, true);
const existingGuide = await findReviewGuide(pr);
await setCodeRabbitReviewActive(pr, false);
await reconcileLabels(pr, null);
await reconcileCommunityApproval(pr, 'remove');
await updateReviewGuide(pr, 'configuration-error', existingGuide);
continue;
}
let existingGuide = await findReviewGuide(pr);
// `mergeable`/`mergeable_state` are only returned by the single-PR
// GET endpoint and are computed asynchronously by GitHub — this
// shard's own pulls.get above provides them, but even that can
// return `null`/"unknown" while the merge check is still running.
// Treat "unknown" as not-yet-computed rather than as conflicting,
// and give GitHub a bounded chance to finish computing it: retry
// the read up to 3 times with a short wait between reads before
// applying the unknown handling below (issue #2089). The wait is
// env-overridable so the test suite can retry without real waits.
const mergeabilityRetryDelayMs = Number(process.env.MERGEABILITY_RETRY_DELAY_MS ?? 5000);
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
let prDetail = pr;
for (
let attempt = 1;
attempt <= 3 &&
(prDetail.mergeable === null || prDetail.mergeable_state === 'unknown');
attempt++
) {
await sleep(mergeabilityRetryDelayMs);
core.info(`PR #${pr.number}: mergeability unknown — retrying read (${attempt}/3)`);
try {
const { data: retryDetail } = await github.rest.pulls.get({
owner, repo, pull_number: pr.number,
});
prDetail = retryDetail;
} catch (error) {
// The loop condition guarantees mergeability was still
// unknown when this retry started. A failed retry (for
// example HTTP 503) adds no new mergeability answer, so
// the outer cleanup must keep the current state labels
// exactly like the still-unknown path below (issue
// #2089). Gate invalidation and failure reporting still
// happen in the outer catch.
error.preserveStateLabels = true;
throw error;
}
}
if (prDetail.mergeable === false && prDetail.mergeable_state === 'dirty') {
core.info(
`PR #${pr.number}: has merge conflicts — ` +
'labeling has-conflicts and awaiting-author'
);
await updateReviewGate(pr, 'conflict', false);
await setCodeRabbitReviewActive(pr, false);
// Conflicts are an independent flag, and a conflicted PR
// always owes the author action (issue #2089): set the
// flag and force the awaiting-author turn label — never
// has-conflicts alone, and never a maintainer-queue label.
await reconcileConflictFlag(pr, true);
await reconcileLabels(pr, 'awaiting-author');
await reconcileCommunityApproval(pr, 'remove');
await updateReviewGuide(pr, 'conflict', existingGuide);
continue;
}
// Unknown mergeability is handled once here, ahead of every
// branch that reconciles labels (issues #2045 and #2089). If the
// reads above still report `mergeable: null` /
// `mergeable_state: "unknown"`, GitHub has not finished computing
// the answer, so it says nothing about conflicts and nothing about
// whose turn it is. This run then changes NO state label for the
// PR: every state-label reconcile below is skipped, and the
// has-conflicts flag freezes with the turn labels. Acting on
// unknown previously let the normal reconcile swap labels (for
// example has-conflicts to awaiting-author and back on the next
// run's `dirty` read), which flapped labels on unchanged PRs.
// Known-dirty never reaches here (the conflict check above
// handles it first); a known read that is not dirty removes
// the flag in the branches below. The awaiting-maintainer
// branch below still refetches mergeability before the
// maintainer handoff, because a push between this fetch and
// labeling can change the answer; a known read there
// re-enables the final reconcile.
let mergeabilityUnknown =
prDetail.mergeable === null || prDetail.mergeable_state === 'unknown';
if (mergeabilityUnknown) {
core.info(
`PR #${pr.number}: mergeability still unknown after retries — ` +
'leaving state labels unchanged this run'
);
}
// Check CI status for required checks on the PR's head commit only.
// Scoping to required checks avoids advisory checks (e.g. codecov/patch)
// incorrectly blocking label assignment on otherwise-ready PRs.
const checkRuns = await github.paginate(github.rest.checks.listForRef, {
owner, repo, ref: pr.head.sha, per_page: 100,
});
const needsLegacyStatuses = requiredChecks?.some(
check => check.integrationId === null
);
const commitStatuses = needsLegacyStatuses
? await github.paginate(github.rest.repos.listCommitStatusesForRef, {
owner, repo, ref: pr.head.sha, per_page: 100,
})
: [];
// listForRef returns every check run ever recorded on the ref, including
// stale superseded ones (e.g. a failed run later re-run green). Branch
// protection and the PR UI only consider the latest run per check name, so
// reduce to that before evaluating — otherwise a single stale failure makes
// ciFailed true forever and state labels never come back. See issue #884.
//
// Unlike listReviews (which documents oldest-first order), listForRef's
// ordering is unspecified, so we pick the latest by run.id — GitHub assigns
// monotonically increasing IDs, and id is never null (a freshly re-queued
// run can have started_at: null, which would lose a string comparison
// against an older completed run's timestamp).
const latestByName = new Map();
const latestByNameAndApp = new Map();
for (const run of checkRuns) {
const prev = latestByName.get(run.name);
if (!prev || run.id > prev.id) {
latestByName.set(run.name, run);
}
const appKey = `${run.name}:${run.app?.id ?? 'none'}`;
const previousAppRun = latestByNameAndApp.get(appKey);
if (!previousAppRun || run.id > previousAppRun.id) {
latestByNameAndApp.set(appKey, run);
}
}
const latestStatusByContext = new Map();
for (const status of commitStatuses) {
const previous = latestStatusByContext.get(status.context);
if (!previous || status.id > previous.id) {
latestStatusByContext.set(status.context, status);
}
}
// Evaluate every required rule exactly as GitHub reports it. Workflow
// ownership cannot be inferred from the shared GitHub Actions app ID.
const requiredSpecs = requiredChecks ?? [];
const requiredResults = requiredSpecs.map(check => {
const run = check.integrationId === null
? latestByName.get(check.context)
: latestByNameAndApp.get(`${check.context}:${check.integrationId}`);
const status = check.integrationId === null
? latestStatusByContext.get(check.context)
: null;
return { check, run, status };
});
const relevantRuns = requiredResults.map(result => result.run).filter(Boolean);
const relevantStatuses = requiredResults.map(result => result.status).filter(Boolean);
const missingRequiredChecks = requiredResults
.filter(result => !result.run && !result.status)
.map(result =>
`${result.check.context}${result.check.integrationId ? `@${result.check.integrationId}` : ''}`
);
core.debug(
`PR #${pr.number}: ${relevantRuns.length} check run(s), ` +
`${relevantStatuses.length} commit status(es), ` +
`missing=[${missingRequiredChecks.join(', ')}]`
);
for (const run of relevantRuns) {
core.debug(` check: "${run.name}" status=${run.status} conclusion=${run.conclusion}`);
}
const ciFailed = relevantRuns.some(
run => run.status === 'completed' &&
run.conclusion !== 'success' &&
run.conclusion !== 'skipped' &&
run.conclusion !== 'neutral',
) || relevantStatuses.some(
status => status.state === 'failure' || status.state === 'error'
);
const ciPending = !ciFailed && (
requiredChecks === null || missingRequiredChecks.length > 0 || relevantRuns.some(
run => run.status !== 'completed',
) || relevantStatuses.some(
status => status.state === 'pending'
)
);
// While CI is running or has failed, remove state labels and move on.
// CI failure is its own signal; the label would add noise, not clarity.
// Exception (issues #2025 and #2089): while GitHub is still
// computing mergeability, a missing required check can simply
// mean a conflicting PR got no merge-ref CI run — not that its
// conflicts went away. Unknown mergeability changes no state
// label in this run, so this branch keeps every existing state
// label (the has-conflicts flag included) instead of stripping
// them; a later run with a known read reconciles them. On a
// known read the branch got here only because the PR is not
// dirty (the conflict check handles dirty first), so the
// conflict flag is removed along with the turn labels.
if (ciPending || ciFailed) {
core.info(
`PR #${pr.number}: CI ${ciPending ? 'pending' : 'failed'} — ` +
(mergeabilityUnknown
? 'mergeability unknown; leaving state labels unchanged'
: 'stripping state labels')
);
await updateReviewGate(pr, ciPending ? 'ci-pending' : 'ci-failed', false);
await setCodeRabbitReviewActive(pr, false);
if (!mergeabilityUnknown) {
await reconcileConflictFlag(pr, false);
await reconcileLabels(pr, null);
}
await reconcileCommunityApproval(pr, 'remove');
await updateReviewGuide(
pr,
ciPending ? 'ci-pending' : 'ci-failed',