-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreviews.py
More file actions
926 lines (825 loc) · 37.5 KB
/
Copy pathreviews.py
File metadata and controls
926 lines (825 loc) · 37.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
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
"""Review lifecycle and review-freshness helpers."""
from __future__ import annotations
from datetime import datetime, timezone
from typing import Any, Iterable
from urllib.parse import quote
from .config import (
MANDATORY_TRIAGE_APPROVER_LABEL,
MANDATORY_TRIAGE_ESCALATION_TEMPLATE,
MANDATORY_TRIAGE_SATISFIED_TEMPLATE,
STATUS_AWAITING_CONTRIBUTOR_RESPONSE_LABEL,
STATUS_AWAITING_REVIEWER_RESPONSE_LABEL,
STATUS_AWAITING_WRITE_APPROVAL_LABEL,
STATUS_LABELS,
)
def _now_iso() -> str:
return datetime.now(timezone.utc).isoformat()
def parse_github_timestamp(value: str | None) -> datetime | None:
if not isinstance(value, str) or not value:
return None
try:
return datetime.fromisoformat(value.replace("Z", "+00:00"))
except ValueError:
return None
def get_latest_review_by_reviewer(bot, reviews: list[dict], reviewer: str) -> dict | None:
latest_review = None
latest_key = (datetime.min.replace(tzinfo=timezone.utc), "")
for review in reviews:
author = review.get("user", {}).get("login")
if not isinstance(author, str) or author.lower() != reviewer.lower():
continue
submitted_at = bot.parse_github_timestamp(review.get("submitted_at"))
if submitted_at is None:
continue
review_id = str(review.get("id", ""))
review_key = (submitted_at, review_id)
if review_key >= latest_key:
latest_key = review_key
latest_review = review
return latest_review
def get_latest_valid_current_reviewer_review_for_cycle(
bot,
issue_number: int,
review_data: dict,
*,
reviews: list[dict] | None = None,
) -> dict | None:
current_reviewer = review_data.get("current_reviewer")
if not isinstance(current_reviewer, str) or not current_reviewer.strip():
return None
boundary = get_current_cycle_boundary(bot, review_data)
if boundary is None:
return None
if reviews is None:
reviews = bot.get_pull_request_reviews(issue_number)
if reviews is None:
return None
latest_review = None
latest_key = (datetime.min.replace(tzinfo=timezone.utc), "")
for review in reviews:
if not isinstance(review, dict):
continue
author = review.get("user", {}).get("login")
if not isinstance(author, str) or author.lower() != current_reviewer.lower():
continue
state = str(review.get("state", "")).upper()
if state not in {"APPROVED", "COMMENTED", "CHANGES_REQUESTED"}:
continue
submitted_at = parse_github_timestamp(review.get("submitted_at"))
if submitted_at is None or submitted_at < boundary:
continue
commit_id = review.get("commit_id")
if not isinstance(commit_id, str) or not commit_id.strip():
continue
review_id = str(review.get("id", ""))
review_key = (submitted_at, review_id)
if review_key >= latest_key:
latest_key = review_key
latest_review = review
return latest_review
def build_reviewer_review_record_from_live_review(review: dict, *, actor: str | None = None) -> dict | None:
if not isinstance(review, dict):
return None
review_id = review.get("id")
submitted_at = review.get("submitted_at")
commit_id = review.get("commit_id")
author = actor if isinstance(actor, str) and actor.strip() else review.get("user", {}).get("login")
if not isinstance(review_id, int) or not isinstance(submitted_at, str) or not isinstance(commit_id, str):
return None
if not isinstance(author, str) or not author.strip():
return None
return {
"semantic_key": f"pull_request_review:{review_id}",
"timestamp": submitted_at,
"actor": author,
"reviewed_head_sha": commit_id,
"source_precedence": 1,
"payload": {},
}
def accept_reviewer_review_from_live_review(review_data: dict, review: dict, *, actor: str | None = None) -> bool:
record = build_reviewer_review_record_from_live_review(review, actor=actor)
if record is None:
return False
return accept_channel_event(
review_data,
"reviewer_review",
semantic_key=record["semantic_key"],
timestamp=record["timestamp"],
actor=record["actor"],
reviewed_head_sha=record["reviewed_head_sha"],
source_precedence=record["source_precedence"],
payload=record["payload"],
)
def repair_missing_reviewer_review_state(bot, issue_number: int, review_data: dict, *, reviews: list[dict] | None = None) -> bool:
reviewer_review = review_data.get("reviewer_review", {}).get("accepted")
if isinstance(reviewer_review, dict):
return False
live_review = get_latest_valid_current_reviewer_review_for_cycle(bot, issue_number, review_data, reviews=reviews)
if live_review is None:
return False
submitted_at = live_review.get("submitted_at")
changed = accept_reviewer_review_from_live_review(review_data, live_review, actor=review_data.get("current_reviewer"))
if isinstance(submitted_at, str):
record_reviewer_activity(review_data, submitted_at)
return changed
def find_triage_approval_after(bot, reviews: list[dict], since: datetime | None) -> tuple[str, datetime] | None:
permission_cache: dict[str, bool] = {}
approvals: list[tuple[datetime, str, str]] = []
for review in reviews:
state = str(review.get("state", "")).upper()
if state != "APPROVED":
continue
author = review.get("user", {}).get("login")
if not isinstance(author, str) or not author:
continue
submitted_at = bot.parse_github_timestamp(review.get("submitted_at"))
if submitted_at is None:
continue
if since is not None and submitted_at <= since:
continue
approvals.append((submitted_at, str(review.get("id", "")), author))
approvals.sort(key=lambda item: (item[0], item[1]))
for submitted_at, _, author in approvals:
cache_key = author.lower()
if cache_key not in permission_cache:
permission_cache[cache_key] = bot.is_triage_or_higher(author)
if permission_cache[cache_key]:
return author, submitted_at
return None
def _ensure_channel_map(review_entry: dict, name: str) -> dict:
value = review_entry.get(name)
if not isinstance(value, dict):
value = {"accepted": None, "seen_keys": []}
review_entry[name] = value
if not isinstance(value.get("seen_keys"), list):
value["seen_keys"] = []
return value
def _ensure_dict(review_entry: dict, name: str) -> dict:
value = review_entry.get(name)
if not isinstance(value, dict):
value = {}
review_entry[name] = value
return value
def ensure_review_entry(state: dict, issue_number: int, create: bool = False) -> dict | None:
issue_key = str(issue_number)
if "active_reviews" not in state or not isinstance(state.get("active_reviews"), dict):
state["active_reviews"] = {}
review_entry = state["active_reviews"].get(issue_key)
if review_entry is None:
if not create:
return None
review_entry = {}
state["active_reviews"][issue_key] = review_entry
elif isinstance(review_entry, list):
review_entry = {"skipped": review_entry}
state["active_reviews"][issue_key] = review_entry
if not isinstance(review_entry, dict):
return None
defaults: dict[str, Any] = {
"skipped": [],
"current_reviewer": None,
"cycle_started_at": None,
"active_cycle_started_at": None,
"assigned_at": None,
"active_head_sha": None,
"last_reviewer_activity": None,
"transition_warning_sent": None,
"transition_notice_sent_at": None,
"assignment_method": None,
"review_completed_at": None,
"review_completed_by": None,
"review_completion_source": None,
"mandatory_approver_required": False,
"mandatory_approver_label_applied_at": None,
"mandatory_approver_pinged_at": None,
"mandatory_approver_satisfied_by": None,
"mandatory_approver_satisfied_at": None,
"repair_needed": None,
"overdue_anchor": None,
}
for field, default in defaults.items():
if field not in review_entry:
review_entry[field] = default
if not isinstance(review_entry.get("skipped"), list):
review_entry["skipped"] = []
for channel in (
"reviewer_comment",
"reviewer_review",
"contributor_comment",
"contributor_revision",
"review_dismissal",
):
_ensure_channel_map(review_entry, channel)
for mapping in (
"deferred_gaps",
"observer_discovery_watermarks",
"pending_privileged_commands",
"current_cycle_completion",
"current_cycle_write_approval",
):
_ensure_dict(review_entry, mapping)
reconciled_source_events = review_entry.get("reconciled_source_events")
if not isinstance(reconciled_source_events, list):
review_entry["reconciled_source_events"] = []
return review_entry
def _reset_cycle_state(review_data: dict) -> None:
for channel in (
"reviewer_comment",
"reviewer_review",
"contributor_comment",
"contributor_revision",
"review_dismissal",
):
review_data[channel] = {"accepted": None, "seen_keys": []}
review_data["current_cycle_completion"] = {}
review_data["current_cycle_write_approval"] = {}
review_data["overdue_anchor"] = None
if isinstance(review_data.get("pending_privileged_commands"), dict):
review_data["pending_privileged_commands"] = {}
def clear_transition_timers(review_data: dict) -> None:
review_data["transition_warning_sent"] = None
review_data["transition_notice_sent_at"] = None
def record_reviewer_activity(review_data: dict, timestamp: str) -> None:
current = parse_github_timestamp(review_data.get("last_reviewer_activity"))
candidate = parse_github_timestamp(timestamp)
if current is None or candidate is None or candidate >= current:
review_data["last_reviewer_activity"] = timestamp
clear_transition_timers(review_data)
def record_transition_notice_sent(review_data: dict, timestamp: str) -> None:
review_data["transition_notice_sent_at"] = timestamp
def set_current_reviewer(
state: dict,
issue_number: int,
reviewer: str,
assignment_method: str = "round-robin",
) -> None:
now = _now_iso()
review_data = ensure_review_entry(state, issue_number, create=True)
if review_data is None:
return
review_data["current_reviewer"] = reviewer
review_data["cycle_started_at"] = now
review_data["active_cycle_started_at"] = now
review_data["assigned_at"] = now
record_reviewer_activity(review_data, now)
review_data["assignment_method"] = assignment_method
review_data["review_completed_at"] = None
review_data["review_completed_by"] = None
review_data["review_completion_source"] = None
review_data["mandatory_approver_required"] = False
review_data["mandatory_approver_label_applied_at"] = None
review_data["mandatory_approver_pinged_at"] = None
review_data["mandatory_approver_satisfied_by"] = None
review_data["mandatory_approver_satisfied_at"] = None
review_data["active_head_sha"] = None
_reset_cycle_state(review_data)
def _semantic_key_seen(review_data: dict, channel_name: str, semantic_key: str) -> bool:
channel = _ensure_channel_map(review_data, channel_name)
return semantic_key in channel["seen_keys"]
def _compare_records(left: dict | None, right: dict | None) -> int:
if right is None:
return 1
if left is None:
return -1
left_time = parse_github_timestamp(left.get("timestamp")) or datetime.min.replace(tzinfo=timezone.utc)
right_time = parse_github_timestamp(right.get("timestamp")) or datetime.min.replace(tzinfo=timezone.utc)
left_rank = int(left.get("source_precedence", 0))
right_rank = int(right.get("source_precedence", 0))
left_key = str(left.get("semantic_key", ""))
right_key = str(right.get("semantic_key", ""))
left_tuple = (left_time, left_rank, left_key)
right_tuple = (right_time, right_rank, right_key)
if left_tuple > right_tuple:
return 1
if left_tuple < right_tuple:
return -1
return 0
def accept_channel_event(
review_data: dict,
channel_name: str,
*,
semantic_key: str,
timestamp: str,
actor: str | None = None,
reviewed_head_sha: str | None = None,
source_precedence: int = 0,
payload: dict | None = None,
dismissal_only: bool = False,
) -> bool:
channel = _ensure_channel_map(review_data, channel_name)
if semantic_key in channel["seen_keys"]:
return False
channel["seen_keys"].append(semantic_key)
if dismissal_only:
channel["accepted"] = channel.get("accepted") or {
"semantic_key": semantic_key,
"timestamp": timestamp,
}
return True
candidate = {
"semantic_key": semantic_key,
"timestamp": timestamp,
"actor": actor,
"reviewed_head_sha": reviewed_head_sha,
"source_precedence": source_precedence,
"payload": payload or {},
}
current = channel.get("accepted")
if _compare_records(candidate, current) >= 0:
channel["accepted"] = candidate
return True
def update_reviewer_activity(state: dict, issue_number: int, reviewer: str) -> bool:
review_data = ensure_review_entry(state, issue_number)
if review_data is None:
return False
current_reviewer = review_data.get("current_reviewer")
if not isinstance(current_reviewer, str) or current_reviewer.lower() != reviewer.lower():
return False
record_reviewer_activity(review_data, _now_iso())
return True
def mark_review_complete(state: dict, issue_number: int, reviewer: str | None, source: str) -> bool:
review_data = ensure_review_entry(state, issue_number, create=True)
if review_data is None:
return False
now = _now_iso()
review_data["review_completed_at"] = now
review_data["review_completed_by"] = reviewer or None
review_data["review_completion_source"] = source
record_reviewer_activity(review_data, now)
review_data["current_cycle_completion"] = {
"completed": True,
"completed_at": now,
"source": source,
"reviewer": reviewer,
}
return True
def is_triage_or_higher(bot, username: str) -> bool:
return bot.check_user_permission(username, "triage")
def trigger_mandatory_approver_escalation(bot, state: dict, issue_number: int) -> bool:
review_data = ensure_review_entry(state, issue_number, create=True)
if review_data is None:
return False
now = _now_iso()
state_changed = False
if not review_data.get("mandatory_approver_required"):
review_data["mandatory_approver_required"] = True
review_data["mandatory_approver_satisfied_by"] = None
review_data["mandatory_approver_satisfied_at"] = None
state_changed = True
if bot.ensure_label_exists(MANDATORY_TRIAGE_APPROVER_LABEL):
try:
if bot.add_label_with_status(issue_number, MANDATORY_TRIAGE_APPROVER_LABEL):
if review_data.get("mandatory_approver_label_applied_at") is None:
review_data["mandatory_approver_label_applied_at"] = now
state_changed = True
except RuntimeError as exc:
print(f"WARNING: Unable to apply escalation label on #{issue_number}: {exc}", file=bot.sys.stderr)
if review_data.get("mandatory_approver_pinged_at") is None:
if bot.post_comment(issue_number, MANDATORY_TRIAGE_ESCALATION_TEMPLATE):
review_data["mandatory_approver_pinged_at"] = now
state_changed = True
return state_changed
def satisfy_mandatory_approver_requirement(bot, state: dict, issue_number: int, approver: str) -> bool:
review_data = ensure_review_entry(state, issue_number, create=True)
if review_data is None or not review_data.get("mandatory_approver_required"):
return False
if review_data.get("mandatory_approver_satisfied_at"):
return False
now = _now_iso()
review_data["mandatory_approver_required"] = False
review_data["mandatory_approver_satisfied_by"] = approver
review_data["mandatory_approver_satisfied_at"] = now
try:
bot.remove_label_with_status(issue_number, MANDATORY_TRIAGE_APPROVER_LABEL)
except RuntimeError as exc:
print(f"WARNING: Unable to remove escalation label on #{issue_number}: {exc}", file=bot.sys.stderr)
bot.post_comment(issue_number, MANDATORY_TRIAGE_SATISFIED_TEMPLATE.format(approver=approver))
return True
def get_pull_request_reviews(bot, issue_number: int) -> list[dict] | None:
reviews: list[dict] = []
page = 1
while True:
result = bot.github_api("GET", f"pulls/{issue_number}/reviews?per_page=100&page={page}")
if result is None:
return None
if not isinstance(result, list):
return reviews
page_reviews = [review for review in result if isinstance(review, dict)]
reviews.extend(page_reviews)
if len(result) < 100:
return reviews
page += 1
def collapse_latest_reviews_by_login(reviews: list[dict]) -> dict[str, dict]:
latest_by_login: dict[str, tuple[datetime, str, dict]] = {}
for review in reviews:
author = review.get("user", {}).get("login")
if not isinstance(author, str) or not author.strip():
continue
submitted_at = parse_github_timestamp(review.get("submitted_at"))
if submitted_at is None:
continue
review_id = str(review.get("id", ""))
key = author.lower()
review_key = (submitted_at, review_id)
current = latest_by_login.get(key)
if current is None or review_key >= (current[0], current[1]):
latest_by_login[key] = (submitted_at, review_id, review)
return {login: item[2] for login, item in latest_by_login.items()}
def get_current_cycle_boundary(bot, review_data: dict) -> datetime | None:
for field in ("active_cycle_started_at", "cycle_started_at", "assigned_at"):
boundary = bot.parse_iso8601_timestamp(review_data.get(field))
if boundary is not None:
return boundary
return None
def rebuild_pr_approval_state(
bot,
issue_number: int,
review_data: dict,
*,
pull_request: dict | None = None,
reviews: list[dict] | None = None,
) -> tuple[dict | None, dict | None]:
boundary = get_current_cycle_boundary(bot, review_data)
if boundary is None:
return None, None
if pull_request is None:
pull_request = bot.github_api("GET", f"pulls/{issue_number}")
if not isinstance(pull_request, dict):
return None, None
head = pull_request.get("head")
current_head = head.get("sha") if isinstance(head, dict) else None
if not isinstance(current_head, str) or not current_head.strip():
return None, None
if reviews is None:
reviews = bot.get_pull_request_reviews(issue_number)
if reviews is None:
return None, None
survivors: dict[str, dict] = {}
for review in reviews:
if not isinstance(review, dict):
continue
state = str(review.get("state", "")).upper()
if state == "DISMISSED":
continue
submitted_at = parse_github_timestamp(review.get("submitted_at"))
if submitted_at is None or submitted_at < boundary:
continue
commit_id = review.get("commit_id")
if not isinstance(commit_id, str) or not commit_id.strip():
continue
if commit_id.strip() != current_head:
continue
author = review.get("user", {}).get("login")
if not isinstance(author, str) or not author.strip():
continue
review_id = str(review.get("id", ""))
key = author.lower()
candidate_key = (submitted_at, review_id)
current = survivors.get(key)
if current is None:
survivors[key] = review
continue
current_key = (
parse_github_timestamp(current.get("submitted_at")) or datetime.min.replace(tzinfo=timezone.utc),
str(current.get("id", "")),
)
if candidate_key >= current_key:
survivors[key] = review
approvals = [review for review in survivors.values() if str(review.get("state", "")).upper() == "APPROVED"]
completion = {
"completed": bool(approvals),
"current_head_sha": current_head,
"qualifying_review_ids": [review.get("id") for review in approvals],
}
permission_cache: dict[str, bool] = {}
has_write_approval = False
write_approvers: list[str] = []
for review in approvals:
author = review.get("user", {}).get("login")
if not isinstance(author, str) or not author.strip():
continue
cache_key = author.lower()
if cache_key not in permission_cache:
permission_cache[cache_key] = bot.check_user_permission(author, "push")
if permission_cache[cache_key]:
has_write_approval = True
write_approvers.append(author)
write_approval = {
"has_write_approval": has_write_approval,
"write_approvers": write_approvers,
"current_head_sha": current_head,
}
review_data["active_head_sha"] = current_head
review_data["current_cycle_completion"] = completion
review_data["current_cycle_write_approval"] = write_approval
if completion["completed"]:
review_data["review_completed_at"] = _now_iso()
review_data["review_completed_by"] = None
review_data["review_completion_source"] = "live_review_rebuild"
else:
review_data["review_completed_at"] = None
review_data["review_completed_by"] = None
review_data["review_completion_source"] = None
return completion, write_approval
def pr_has_current_write_approval(
bot,
issue_number: int,
review_data: dict,
permission_cache: dict[str, bool] | None = None,
reviews: list[dict] | None = None,
) -> bool | None:
del permission_cache
completion, write_approval = rebuild_pr_approval_state(bot, issue_number, review_data, reviews=reviews)
if completion is None or write_approval is None:
return None
return bool(write_approval.get("has_write_approval"))
def _record_timestamp(record: dict | None) -> datetime | None:
if not isinstance(record, dict):
return None
return parse_github_timestamp(record.get("timestamp"))
def _compare_cross_channel_conversation(contributor: dict | None, reviewer: dict | None) -> int:
contributor_time = _record_timestamp(contributor) or datetime.min.replace(tzinfo=timezone.utc)
reviewer_time = _record_timestamp(reviewer) or datetime.min.replace(tzinfo=timezone.utc)
contributor_key = str((contributor or {}).get("semantic_key", ""))
reviewer_key = str((reviewer or {}).get("semantic_key", ""))
if (contributor_time, contributor_key) == (reviewer_time, reviewer_key):
return 0
if contributor_time > reviewer_time:
return 1
if contributor_time < reviewer_time:
return -1
if contributor_key >= reviewer_key:
return 1
return -1
def _initial_reviewer_anchor(review_data: dict) -> str | None:
for field in ("active_cycle_started_at", "cycle_started_at", "assigned_at"):
value = review_data.get(field)
if isinstance(value, str) and value:
return value
return None
def _contributor_revision_handoff_record(review_data: dict, current_head: str | None, reviewer_review: dict | None) -> dict | None:
contributor_revision = review_data.get("contributor_revision", {}).get("accepted")
if not isinstance(contributor_revision, dict):
return None
revision_head = contributor_revision.get("reviewed_head_sha")
if not isinstance(revision_head, str) or not isinstance(current_head, str):
return None
if revision_head != current_head:
return None
reviewer_head = reviewer_review.get("reviewed_head_sha") if isinstance(reviewer_review, dict) else None
if isinstance(reviewer_head, str) and reviewer_head == current_head:
return None
return contributor_revision
def compute_reviewer_response_state(
bot,
issue_number: int,
review_data: dict,
*,
issue_snapshot: dict | None = None,
pull_request: dict | None = None,
reviews: list[dict] | None = None,
) -> dict[str, object]:
if issue_snapshot is None:
issue_snapshot = bot.get_issue_or_pr_snapshot(issue_number)
if not isinstance(issue_snapshot, dict):
return {"state": "projection_failed", "reason": "issue_snapshot_unavailable"}
is_pr = isinstance(issue_snapshot.get("pull_request"), dict)
current_reviewer = review_data.get("current_reviewer")
if not isinstance(current_reviewer, str) or not current_reviewer.strip():
return {"state": "untracked", "reason": "no_current_reviewer"}
reviewer_comment = review_data.get("reviewer_comment", {}).get("accepted")
reviewer_review = review_data.get("reviewer_review", {}).get("accepted")
contributor_comment = review_data.get("contributor_comment", {}).get("accepted")
if not reviewer_comment and not reviewer_review and is_pr:
live_review = get_latest_valid_current_reviewer_review_for_cycle(bot, issue_number, review_data, reviews=reviews)
if live_review is not None:
reviewer_review = build_reviewer_review_record_from_live_review(live_review, actor=current_reviewer)
if not reviewer_comment and not reviewer_review:
return {
"state": "awaiting_reviewer_response",
"reason": "no_reviewer_activity",
"anchor_timestamp": _initial_reviewer_anchor(review_data),
"reviewer_comment": reviewer_comment,
"reviewer_review": reviewer_review,
"contributor_comment": contributor_comment,
"contributor_handoff": None,
}
latest_reviewer_response = reviewer_comment
if _compare_records(reviewer_review, latest_reviewer_response) > 0:
latest_reviewer_response = reviewer_review
if not is_pr:
completion = review_data.get("current_cycle_completion")
if not isinstance(completion, dict) or not completion.get("completed"):
if review_data.get("review_completed_at"):
return {"state": "done", "reason": None}
return {
"state": "awaiting_contributor_response",
"reason": "completion_missing",
"anchor_timestamp": latest_reviewer_response.get("timestamp") if isinstance(latest_reviewer_response, dict) else None,
}
return {"state": "done", "reason": None}
if pull_request is None:
pull_request = bot.github_api("GET", f"pulls/{issue_number}")
if not isinstance(pull_request, dict):
return {"state": "projection_failed", "reason": "pull_request_unavailable"}
head = pull_request.get("head")
current_head = head.get("sha") if isinstance(head, dict) else None
if not isinstance(current_head, str) or not current_head.strip():
return {"state": "projection_failed", "reason": "pull_request_head_unavailable"}
review_data["active_head_sha"] = current_head
contributor_handoff = contributor_comment
contributor_revision = _contributor_revision_handoff_record(review_data, current_head, reviewer_review if isinstance(reviewer_review, dict) else None)
if _compare_records(contributor_revision, contributor_handoff) > 0:
contributor_handoff = contributor_revision
latest_review_head = reviewer_review.get("reviewed_head_sha") if isinstance(reviewer_review, dict) else None
if not isinstance(latest_review_head, str) or latest_review_head != current_head:
return {
"state": "awaiting_reviewer_response",
"reason": "review_head_stale",
"anchor_timestamp": contributor_handoff.get("timestamp") if isinstance(contributor_handoff, dict) else _initial_reviewer_anchor(review_data),
"current_head_sha": current_head,
"reviewer_comment": reviewer_comment,
"reviewer_review": reviewer_review,
"contributor_comment": contributor_comment,
"contributor_handoff": contributor_handoff,
}
if _compare_cross_channel_conversation(contributor_handoff, latest_reviewer_response) > 0:
reason = "contributor_comment_newer"
if isinstance(contributor_handoff, dict) and str(contributor_handoff.get("semantic_key", "")).startswith("pull_request_"):
reason = "contributor_revision_newer"
return {
"state": "awaiting_reviewer_response",
"reason": reason,
"anchor_timestamp": contributor_handoff.get("timestamp") if isinstance(contributor_handoff, dict) else None,
"current_head_sha": current_head,
"reviewer_comment": reviewer_comment,
"reviewer_review": reviewer_review,
"contributor_comment": contributor_comment,
"contributor_handoff": contributor_handoff,
}
completion, write_approval = rebuild_pr_approval_state(bot, issue_number, review_data, pull_request=pull_request, reviews=reviews)
if completion is None or write_approval is None:
return {"state": "projection_failed", "reason": "live_review_state_unknown"}
if not completion.get("completed"):
return {
"state": "awaiting_contributor_response",
"reason": "completion_missing",
"anchor_timestamp": latest_reviewer_response.get("timestamp") if isinstance(latest_reviewer_response, dict) else None,
"current_head_sha": current_head,
"reviewer_comment": reviewer_comment,
"reviewer_review": reviewer_review,
"contributor_comment": contributor_comment,
"contributor_handoff": contributor_handoff,
}
if not write_approval.get("has_write_approval"):
return {
"state": "awaiting_write_approval",
"reason": "write_approval_missing",
"anchor_timestamp": latest_reviewer_response.get("timestamp") if isinstance(latest_reviewer_response, dict) else None,
"current_head_sha": current_head,
"reviewer_comment": reviewer_comment,
"reviewer_review": reviewer_review,
"contributor_comment": contributor_comment,
"contributor_handoff": contributor_handoff,
}
return {
"state": "done",
"reason": "write_approval_present",
"anchor_timestamp": latest_reviewer_response.get("timestamp") if isinstance(latest_reviewer_response, dict) else None,
"current_head_sha": current_head,
"reviewer_comment": reviewer_comment,
"reviewer_review": reviewer_review,
"contributor_comment": contributor_comment,
"contributor_handoff": contributor_handoff,
}
def project_status_labels_for_item(
bot,
issue_number: int,
state: dict,
*,
issue_snapshot: dict | None = None,
) -> tuple[set[str] | None, dict[str, str | None]]:
if issue_snapshot is None:
issue_snapshot = bot.get_issue_or_pr_snapshot(issue_number)
if not isinstance(issue_snapshot, dict):
return None, {"state": "projection_failed", "reason": "issue_snapshot_unavailable"}
if str(issue_snapshot.get("state", "")).lower() == "closed":
return set(), {"state": "closed", "reason": None}
review_data = bot.ensure_review_entry(state, issue_number)
if review_data is None:
return set(), {"state": "untracked", "reason": "no_review_entry"}
current_reviewer = review_data.get("current_reviewer")
if not isinstance(current_reviewer, str) or not current_reviewer.strip():
return set(), {"state": "untracked", "reason": "no_current_reviewer"}
response_state = compute_reviewer_response_state(bot, issue_number, review_data, issue_snapshot=issue_snapshot)
state_name = response_state.get("state")
reason = response_state.get("reason")
if state_name == "projection_failed":
return None, {"state": str(state_name), "reason": str(reason)}
if state_name == "awaiting_reviewer_response":
return ({STATUS_AWAITING_REVIEWER_RESPONSE_LABEL}, {"state": str(state_name), "reason": str(reason)})
if state_name == "awaiting_contributor_response":
return ({STATUS_AWAITING_CONTRIBUTOR_RESPONSE_LABEL}, {"state": str(state_name), "reason": str(reason)})
if state_name == "awaiting_write_approval":
return ({STATUS_AWAITING_WRITE_APPROVAL_LABEL}, {"state": str(state_name), "reason": str(reason)})
return set(), {"state": str(state_name), "reason": None if reason is None else str(reason)}
def sync_status_labels(bot, issue_number: int, desired_labels: set[str], actual_labels: Iterable[str]) -> bool:
actual_status_labels = {label for label in actual_labels if label in STATUS_LABELS}
to_add = desired_labels - actual_status_labels
to_remove = actual_status_labels - desired_labels
if not to_add and not to_remove:
return False
for label in STATUS_LABELS:
if not bot.ensure_label_exists(label):
raise RuntimeError(f"Unable to ensure reviewer-bot status label exists: {label}")
changed = False
for label in sorted(to_remove):
if not bot.remove_label_with_status(issue_number, label):
raise RuntimeError(f"Unable to remove reviewer-bot status label '{label}' from #{issue_number}")
changed = True
for label in sorted(to_add):
if not bot.add_label_with_status(issue_number, label):
raise RuntimeError(f"Unable to add reviewer-bot status label '{label}' to #{issue_number}")
changed = True
return changed
def sync_status_labels_for_items(bot, state: dict, issue_numbers: Iterable[int]) -> bool:
changed = False
for issue_number in sorted({n for n in issue_numbers if isinstance(n, int) and n > 0}):
issue_snapshot = bot.get_issue_or_pr_snapshot(issue_number)
desired_labels, metadata = bot.project_status_labels_for_item(issue_number, state, issue_snapshot=issue_snapshot)
if desired_labels is None:
reason = metadata.get("reason") if isinstance(metadata, dict) else "unknown"
raise RuntimeError(f"Failed to derive reviewer-bot status labels for #{issue_number}: {reason}")
if not isinstance(issue_snapshot, dict):
raise RuntimeError(f"Failed to refresh issue/PR snapshot for #{issue_number}")
labels = issue_snapshot.get("labels", [])
actual_labels = set()
if isinstance(labels, list):
for label in labels:
if isinstance(label, dict):
name = label.get("name")
if isinstance(name, str):
actual_labels.add(name)
if bot.sync_status_labels(issue_number, desired_labels, actual_labels):
changed = True
return changed
def list_open_items_with_status_labels(bot) -> list[int]:
numbers: set[int] = set()
for label in sorted(STATUS_LABELS):
page = 1
encoded_label = quote(label, safe="")
while True:
result = bot.github_api("GET", f"issues?state=open&labels={encoded_label}&per_page=100&page={page}")
if result is None:
raise RuntimeError(f"Failed to list open items for status label '{label}'")
if not isinstance(result, list):
break
for item in result:
if isinstance(item, dict):
number = item.get("number")
if isinstance(number, int):
numbers.add(number)
if len(result) < 100:
break
page += 1
return sorted(numbers)
def list_open_tracked_review_items(state: dict) -> list[int]:
numbers: set[int] = set()
active_reviews = state.get("active_reviews")
if not isinstance(active_reviews, dict):
return []
for issue_key, review_data in active_reviews.items():
if not isinstance(review_data, dict):
continue
current_reviewer = review_data.get("current_reviewer")
if not isinstance(current_reviewer, str) or not current_reviewer.strip():
continue
try:
issue_number = int(issue_key)
except (TypeError, ValueError):
continue
if issue_number > 0:
numbers.add(issue_number)
return sorted(numbers)
def handle_pr_approved_review(bot, state: dict, issue_number: int, review_author: str, completion_source: str) -> bool:
review_data = ensure_review_entry(state, issue_number)
if review_data is None:
return False
current_reviewer = review_data.get("current_reviewer")
author_is_designated = isinstance(current_reviewer, str) and current_reviewer.lower() == review_author.lower()
author_is_triage = is_triage_or_higher(bot, review_author)
state_changed = False
if author_is_designated:
if mark_review_complete(state, issue_number, review_author, completion_source):
state_changed = True
if author_is_triage:
if satisfy_mandatory_approver_requirement(bot, state, issue_number, review_author):
state_changed = True
return state_changed
if trigger_mandatory_approver_escalation(bot, state, issue_number):
state_changed = True
return state_changed
if review_data.get("mandatory_approver_required") and author_is_triage:
if satisfy_mandatory_approver_requirement(bot, state, issue_number, review_author):
state_changed = True
return state_changed