Repository navigation
Expand file tree
/
Copy pathgithub.py
More file actions
1558 lines (1327 loc) · 71 KB
/
Copy pathgithub.py
File metadata and controls
1558 lines (1327 loc) · 71 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
"""GitHub operations through the `gh` CLI: pull requests, reviews, checks, merge."""
from __future__ import annotations
import fcntl
import hashlib
import json
import os
import re
import shlex
import tempfile
import time
from collections.abc import Iterator
from contextlib import contextmanager, suppress
from contextvars import ContextVar
from dataclasses import dataclass
from datetime import UTC, datetime
from email.utils import parsedate_to_datetime
from itertools import count, pairwise
from pathlib import Path
from typing import Literal
from urllib.parse import quote
from loopzero import runners
from loopzero._proc import ProcTimeout, ToolMissing, run
from loopzero.runners import review_settings
from loopzero.types import BLOCKING, Finding, ReviewResult
GH_BASE_ENV = ("PATH", "HOME", "LANG", "LC_ALL", "TERM", "GH_HOST")
GH_ENV = (*GH_BASE_ENV, "GH_TOKEN", "GITHUB_TOKEN", "GH_CONFIG_DIR", "XDG_CONFIG_HOME")
APP_TOKEN_HELPER = Path.home() / ".config/loopzero/app-token"
PR_LOCK_DIR = Path.home() / ".cache/loopzero/pr-locks"
_app_token_cache = ("", 0.0)
MISSING_REVIEW_REASON = "no review recorded for the current head"
MERGEABILITY_PENDING = "GitHub is computing mergeability"
MARKER_RE = re.compile(
r"<!-- loopzero:finding v=1 severity=(?P<severity>\w+) "
r"head=(?P<head>[0-9a-f]{40}) id=(?P<id>[0-9a-f]{8}) -->"
)
PAGE = 100
PR_FILE_LIMIT = 3_000
PR_APP_INSTALLATION_HINT = "Check that the GitHub App installation includes this repository."
RATE_LIMIT_GUIDANCE = "\nRate limited: retry after GitHub's reset or Retry-After; No automatic retry."
CHECK_SUITE_LIMIT = 1_000
GH_AUTH_REMEDY = "Run `gh auth login --scopes repo` (required token scope: repo)."
_HUNK_RE = re.compile(r"^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@", re.MULTILINE)
_ANCHOR_NOTE = "No file location given by the reviewer; anchored here.\n\n"
_MOVED_NOTE = "Reviewer location {where} is not in the diff; anchored here.\n\n"
_SELF_REVIEW = re.compile(r"(approve|request changes on) your own pull request", re.IGNORECASE)
_THREADS_QUERY = """
query($owner: String!, $name: String!, $number: Int!, $after: String) {
repository(owner: $owner, name: $name) {
pullRequest(number: $number) {
reviewThreads(first: 100, after: $after) {
pageInfo { hasNextPage endCursor }
nodes {
id isResolved isOutdated path line
comments(first: 1) {
nodes { body author { __typename login } } pageInfo { hasNextPage endCursor }
}
}
}
}
}
}
"""
class GhError(Exception):
def __init__(self, command: tuple[str, ...], tail: str, *,
token: str = "", guidance: str = "", confirmed_rate_limit: bool = False) -> None:
self.command = tuple(_redact_tokens(arg, token) for arg in command)
self.tail = _redact_tokens(tail, token) + guidance
self.confirmed_rate_limit = confirmed_rate_limit
command_text = _redact_tokens(" ".join(command), token)
super().__init__(f"{command_text} failed: {self.tail.strip()[-600:]}")
class GhUnavailable(GhError):
"""GitHub could not supply a result because of a transient fault or limit."""
class ReadDeadline(GhUnavailable):
"""A shared GitHub read deadline elapsed."""
class StatusLimitReached(GhError):
"""GitHub has no status slots left for this commit and context."""
class GhMissing(GhError):
"""The `gh` executable is not on PATH."""
class GhAuth(GhError):
"""`gh` is not authenticated."""
class MergeFailed(GhError):
"""Merge did not complete or could not be verified."""
@dataclass(frozen=True)
class PR:
number: int
url: str
head_sha: str
base_ref: str
is_draft: bool
state: str # "OPEN" | "CLOSED" | "MERGED"
mergeable: str # "MERGEABLE" | "CONFLICTING" | "UNKNOWN"
author: str = "" # login of the PR author
merge_state: str = "UNKNOWN" # GitHub mergeStateStatus, e.g. "BEHIND" | "CLEAN"
body: str = ""
labels: tuple[str, ...] = ()
@dataclass(frozen=True)
class Readiness:
ready: bool
reasons: tuple[str, ...]
waitable_failures: tuple[str, ...] = ()
stale_verdicts: tuple[str, ...] = ()
has_pending_checks: bool = False
TRANSIENT_RE = re.compile(r"HTTP 5\d\d|timed out|TLS handshake timeout|i/o timeout|"
r"connection reset|no server is currently|error connecting to api\.github\.com|"
r"unexpected end of JSON input|Something went wrong while executing your query", re.IGNORECASE)
RETRY_DELAY = 5.0
_retry_sleep = time.sleep
_read_scope: ContextVar[tuple[float, str | None, bool] | None] = ContextVar("github_reads", default=None)
_api_error_diagnostics: ContextVar[bool] = ContextVar("github_api_error_diagnostics", default=False)
_HTTP_STATUS_RE = re.compile(r"^HTTP/\S+\s+(\d{3})(?:\s+(.*))?$", re.IGNORECASE)
_READINESS_TIMESTAMP = re.compile(r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.([0-9]+))?"
r"(?:Z|[+-](?:[01][0-9]|2[0-3]):[0-5][0-9])")
_HTTP_DATE = re.compile(r"[A-Za-z]{3}, [0-9]{2} [A-Za-z]{3} [0-9]{4} [0-9]{2}:[0-9]{2}:[0-9]{2} GMT")
_CREDENTIAL_TOKEN_RE = re.compile(
r"\b(?:github_pat_[A-Za-z0-9_]+\b|gh[pousr]_[A-Za-z0-9_]{10,}\b|sk-[A-Za-z0-9_-]{8,})"
)
@contextmanager
def bounded_reads(deadline: float, token: str | None = "", *, retry: bool = False):
"""Share a monotonic budget across reads, including any retries."""
previous = _read_scope.get()
deadline = min(previous[0], deadline) if previous else deadline
scope = _read_scope.set((deadline, token, retry))
try:
yield
_read_timeout(0)
finally:
_read_scope.reset(scope)
def _read_timeout(limit: float, *, scoped: bool = True) -> float:
scope = _read_scope.get() if scoped else None
if scope is None:
return limit
remaining = scope[0] - time.monotonic()
if remaining <= 0:
raise ReadDeadline(("gh",), "GitHub read deadline exceeded")
return min(limit, remaining)
@contextmanager
def api_error_diagnostics():
"""Include response headers and safe error details for a trusted API validation."""
scope = _api_error_diagnostics.set(True)
try:
yield
finally:
_api_error_diagnostics.reset(scope)
def _included_response(output: str) -> tuple[str | None, dict[str, str], str]:
"""Split one `gh api --include` response into status, headers and body."""
for line_separator in ("\r\n", "\n"):
head, separator, body = output.partition(line_separator * 2)
if not separator:
continue
status_line, *header_lines = head.split(line_separator)
if not (match := _HTTP_STATUS_RE.match(status_line)):
break
headers = {name.strip().casefold(): value.strip()
for name, colon, value in (line.partition(":") for line in header_lines) if colon}
return match.group(1), headers, body
return None, {}, output
def _api_methods(args: tuple[str, ...]) -> list[str]:
return [method.upper() for flag, method in pairwise(args) if flag in ("--method", "-X")]
_API_BODY_FLAGS = {"-f", "-F", "--field", "--raw-field", "--input"}
def _api_method(args: tuple[str, ...]) -> str:
methods = _api_methods(args)
return methods[0] if methods else "POST" if _API_BODY_FLAGS.intersection(args) else "GET"
def redact_credentials(value: str) -> str:
value = re.sub(r"""(?i)(https?://)[^\s/?#'"<>`]+@""", r"\1[REDACTED]@", value)
value = re.sub(r"""(?i)(\bauthorization(?:\\?['"])?[ \t]*:[ \t]*)(\\?['"])(?:(?!\2)(?:\\.|[^\\\r\n]))+\2""",
r"\1\2[REDACTED]\2", value)
return re.sub(r"""(?i)((?P<quote>['"])?\bauthorization[ \t]*:[ \t]*)"""
r"""(?(quote)(?:\\.|(?!(?P=quote))[^\\\r\n])+|(?:[a-z][\w-]*[ \t]+)?(?:\\.|[^\\\s'"`])+)""",
r"\1[REDACTED]", value)
def _redact_tokens(value: str, token: str = "") -> str:
for secret in (token, os.environ.get("GH_TOKEN", ""),
os.environ.get("GITHUB_TOKEN", "")):
if secret:
value = value.replace(secret, "[REDACTED]")
value = re.sub(r"(?i)\b(authorization)\s*[:=]\s*"
r"(?:(?:basic|bearer|token)\s+)?[^\s,;]+", r"\1=[REDACTED]", value)
value = re.sub(r"(?i)\bBearer\s+[^\s,;]+", "Bearer [REDACTED]", value)
value = _CREDENTIAL_TOKEN_RE.sub("[REDACTED]", value)
value = re.sub(r"(?i)\b(access_token|auth_token|token)\s*[:=]\s*"
r"[^\s,;]+", r"\1=[REDACTED]", value)
value = re.sub(r"(?i)(https?://[^?\s]+)\?[^\s]+", r"\1?[REDACTED]", value)
return re.sub(r"(?<!\S)(/[^?\s]+)\?[^\s]+", r"\1?[REDACTED]", value)
def _api_error_detail(args: tuple[str, ...], response: tuple[str | None, dict[str, str], str],
stderr: str, token: str, *, message_tail: str | None = None) -> str:
status, headers, body = response
if status is None:
match = re.search(r"\bHTTP(?:/\S+)?\s+(\d{3})\b", stderr, re.IGNORECASE)
status = match.group(1) if match else "unavailable"
request_id = headers.get("x-github-request-id") or "unavailable"
message = ""
with suppress(TypeError, ValueError):
match json.loads(body):
case {"message": str(value)}:
message = value
case {"errors": list(errors)}:
message = "; ".join(
error["message"] for error in errors
if isinstance(error, dict) and isinstance(error.get("message"), str)
)
message = (message_tail if message_tail is not None
else message or body.strip() or stderr.strip().removeprefix("gh:").strip())
message = " ".join(_redact_tokens(message, token).split())[:400] or "no response message"
path = (args[1] if len(args) > 1 else "").split("?", 1)[0]
if "://" in path:
path = path.partition("://")[2].partition("/")[2]
return _redact_tokens(
f"method={_api_method(args)} endpoint=/{path.lstrip('/')} status={status} "
f"request_id={request_id} message={message}", token
)
def _read_only(args: tuple[str, ...]) -> bool:
"""Only reads are retried: a repeated write could post or change state twice."""
if args[:2] == ("api", "graphql"):
return not any("mutation" in arg for arg in args)
if args[:1] != ("api",):
return False
methods = _api_methods(args)
return all(method == "GET" for method in methods) if methods else not _API_BODY_FLAGS.intersection(args)
def _app_token_clock() -> float | None:
"""Read elapsed time including suspend, when the OS provides it."""
if (clock := getattr(time, "CLOCK_BOOTTIME", None)) is not None:
with suppress(OSError):
return time.clock_gettime(clock)
return None
def _cached_app_token() -> str:
token, minted = _app_token_cache
now = _app_token_clock() if token else None
return token if now is not None and 0 <= now - minted < 3000 else ""
@contextmanager
def pr_lock(repo: str, number: int) -> Iterator[None]:
"""Serialize a GitHub write across local checkouts for this PR."""
key = hashlib.sha256(f"{repo.casefold()}#{number}".encode()).hexdigest()
PR_LOCK_DIR.mkdir(mode=0o700, parents=True, exist_ok=True)
with (PR_LOCK_DIR / key).open("a") as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
yield
def app_token() -> str:
global _app_token_cache
if token := _cached_app_token():
return token
if not APP_TOKEN_HELPER.is_file() or not os.access(APP_TOKEN_HELPER, os.X_OK):
return ""
minted = _app_token_clock() # before minting so a suspend mid-call ages the token
try:
result = run([str(APP_TOKEN_HELPER)], cwd=Path("/"), env_allowlist=GH_BASE_ENV, timeout=_read_timeout(10))
except (ToolMissing, ProcTimeout, ReadDeadline, OSError):
return ""
if result.exit_code or not result.stdout.strip():
return ""
token = result.stdout.strip()
if minted is None:
return token # no suspend-aware clock, so use this token only for this call
_app_token_cache = (token, minted)
return _cached_app_token()
def _select_token(token: str | None, scope: tuple[float, str | None, bool] | None, read_only: bool) -> str:
selected = token if token is not None else (scope[1] if scope else None)
return selected if selected is not None else (app_token() if read_only else "")
def _transient_error(tail: str, retry_idempotent: bool, status: str | None = None) -> bool:
return (status or "").startswith("5") or bool(TRANSIENT_RE.search(tail)) or (
retry_idempotent and "something went wrong while executing your query" in tail.lower()
)
def _rate_limited(status: str | None, headers: dict[str, str], tail: str) -> bool:
return (status == "429"
or (status == "403" and (headers.get("x-ratelimit-remaining") == "0" or "retry-after" in headers))
or bool(re.search(r"rate limit|HTTP 429", tail, re.IGNORECASE)))
def _retry_pause(delay: float | None, limit: float, *, scoped: bool = True) -> bool:
if delay is None or delay >= _read_timeout(limit, scoped=scoped):
return False
_retry_sleep(delay)
return True
def retry_after(value: str) -> float | None:
try:
if re.fullmatch(r"[0-9]{1,18}", value):
return float(value)
date = parsedate_to_datetime(value)
return max(0.0, date.timestamp() - time.time()) if date.tzinfo is not None else None
except (OverflowError, OSError, ValueError):
return None
def _rate_limit_delay(headers: dict[str, str], delay: float | None) -> float | None:
if delay is None or headers.get("x-ratelimit-remaining") == "0":
return None
wait = retry_after(headers.get("retry-after", ""))
return None if wait is None else max(delay, wait)
def _pr_list_error_guidance(args: tuple[str, ...], stderr: str, using_app: bool) -> str:
if (using_app and len(args) > 1 and args[0] == "api"
and re.fullmatch(r"repos/[^/]+/[^/]+/pulls\?.+", args[1])
and "(HTTP 404)" in stderr):
return f"\n{PR_APP_INSTALLATION_HINT}"
return ""
def _gh(*args: str, cwd: Path | None = None, timeout: float = 120,
token: str | None = None, retry_idempotent: bool = False, dates: list[str] | None = None) -> str:
dates = [] if dates is None else dates
api = args[:1] == ("api",)
diagnostic_api = api and _api_error_diagnostics.get()
rest_api = api and args[:2] != ("api", "graphql")
patch_error = api and _api_method(args) == "PATCH"
command = ("gh", *args)
argv = (*command, "--include") if api and not {"--include", "-i"} & set(args) else command
cwd = cwd or Path("/")
read_only = _read_only(args)
retryable = read_only or retry_idempotent
scope = _read_scope.get() if read_only else None
delays = (RETRY_DELAY, None) if retryable and (not scope or scope[2]) else (None,)
for delay in delays:
selected = _select_token(token, scope, read_only) # a retry backoff can outlive the app token
try:
done = run(list(argv), cwd=cwd, env_allowlist=GH_ENV,
extra_env={"GH_TOKEN": selected} if selected else None,
timeout=_read_timeout(timeout, scoped=read_only), encoding="utf-8")
except ToolMissing as exc:
raise GhMissing(argv, str(exc), token=selected,
guidance=f"\nInstall GitHub CLI, then {GH_AUTH_REMEDY}") from exc
except ProcTimeout as exc:
_read_timeout(timeout, scoped=bool(scope and scope[2]))
if not _retry_pause(delay, timeout, scoped=read_only):
raise ProcTimeout(
_redact_tokens(str(exc), selected), _redact_tokens(exc.stdout, selected),
stderr=_redact_tokens(exc.stderr, selected), duration_s=exc.duration_s,
) from None
continue
response = _included_response(done.stdout) if api else (None, {}, done.stdout)
status, headers, body = response
tail = "\n".join(part for part in (done.stderr, body) if part)
if done.exit_code == 0:
dates[:] = [headers.get("date", "")]
return body
rate_limited = _rate_limited(status, headers, tail)
transient = rate_limited or _transient_error(tail, retry_idempotent, status)
pause = _rate_limit_delay(headers, delay) if rate_limited else delay
if not transient or not _retry_pause(pause, timeout, scoped=read_only):
break
error_command, detail = (command if rate_limited else argv), tail
if diagnostic_api or patch_error:
error_command = ("GitHub API request",)
detail = _api_error_detail(args, response if diagnostic_api else (None, {}, ""),
done.stderr, selected, message_tail=None if diagnostic_api else tail)
if rate_limited:
guidance = (_redact_tokens(_rest_rate_limit(headers), selected) if rest_api or headers
else _graphql_reset(args, tail, cwd, selected) + RATE_LIMIT_GUIDANCE)
else:
if "gh auth login" in tail or "not logged in" in tail.lower():
raise GhAuth(error_command, detail.rstrip(), token=selected, guidance=f"\n{GH_AUTH_REMEDY}")
guidance = _pr_list_error_guidance(args, done.stderr, bool(read_only and selected and token is None))
error = GhUnavailable if transient else GhError
raise error(error_command, detail, token=selected, guidance=guidance,
confirmed_rate_limit=rate_limited and status in {"403", "429"})
def _rest_rate_limit(headers: dict[str, str]) -> str:
resource = headers.get("x-ratelimit-resource", "")
remaining_value = headers.get("x-ratelimit-remaining", "")
remaining = int(remaining_value) if re.fullmatch(r"[0-9]{1,18}", remaining_value) else None
retry_after = headers.get("retry-after", "")
retry_seconds = re.fullmatch(r"[0-9]{1,18}", retry_after)
retry_date = _HTTP_DATE.fullmatch(retry_after)
reset = ""
try:
if epoch := headers.get("x-ratelimit-reset"):
reset = datetime.fromtimestamp(int(epoch), UTC).isoformat()
except (OverflowError, OSError, ValueError):
pass
evidence = {
"X-RateLimit-Resource": resource if re.fullmatch(r"[a-zA-Z][a-zA-Z0-9_-]{0,63}", resource) else None,
"X-RateLimit-Remaining": remaining, "X-RateLimit-Reset": reset or None,
"Retry-After": retry_after if retry_seconds or retry_date else None,
}
guidance = RATE_LIMIT_GUIDANCE
if remaining == 0:
guidance = f"\nRate limited: hourly quota exhausted: retry after {reset or 'the quota resets'}; No automatic retry."
elif remaining is not None or retry_seconds or retry_date:
delay = f"{retry_after} s" if retry_seconds else retry_after if retry_date else "~60 s"
guidance = f"\nRate limited: short-window limit: retry after {delay}; No automatic retry."
return "".join(f"\n{name}: {value}" for name, value in evidence.items() if value is not None) + guidance
def _graphql_reset(args: tuple[str, ...], tail: str, cwd: Path, token: str = "") -> str:
"""Best-effort reset evidence for a primary GraphQL limit, never a preflight."""
if re.search(r"secondary|HTTP 429", tail, re.IGNORECASE):
return ""
graphql = args[:2] == ("api", "graphql") or (
args[:1] == ("pr",) and "graphql" in tail.casefold())
if not graphql or not re.search(r"rate limit (?:already )?exceeded", tail, re.IGNORECASE):
return ""
resource = re.search(r"(?im)^x-ratelimit-resource:\s*(\S+)", tail)
remaining = re.search(r"(?im)^x-ratelimit-remaining:\s*(\d+)", tail)
reset = re.search(r"(?im)^x-ratelimit-reset:\s*(\d+)", tail)
if resource and resource[1].casefold() == "graphql" and remaining and remaining[1] == "0" and reset:
try:
stamp = datetime.fromtimestamp(int(reset[1]), UTC)
if stamp.timestamp() > time.time():
return f"\nGraphQL quota resets at {stamp.isoformat()} (response header)."
except (OverflowError, OSError, ValueError):
pass
try:
query = "query { rateLimit { remaining resetAt } }"
result = run(["gh", "api", "graphql", "-f", f"query={query}"], cwd=cwd,
env_allowlist=GH_ENV, extra_env={"GH_TOKEN": token} if token else None,
timeout=_read_timeout(10))
if result.exit_code:
return ""
data = json.loads(result.stdout)
if not isinstance(data, dict) or data.get("errors"):
return ""
limit = data["data"]["rateLimit"]
if not isinstance(limit, dict) or not isinstance(limit.get("resetAt"), str):
return ""
stamp = datetime.fromisoformat(limit["resetAt"])
if (type(limit["remaining"]) is int and limit["remaining"] == 0
and stamp.tzinfo is not None and stamp.timestamp() > time.time()):
return f"\nGraphQL quota resets at {stamp.isoformat()} (diagnostic query)."
except (ToolMissing, ProcTimeout, ReadDeadline, KeyError, TypeError, ValueError, OverflowError, OSError):
pass
return ""
def _gh_json(*args: str, token: str | None = None, **kwargs) -> object:
out = _gh(*args, token=token, **kwargs)
try:
return json.loads(out) if out.strip() else None
except json.JSONDecodeError as exc:
raise GhError(("gh", *args), f"invalid JSON from gh at line {exc.lineno}, column {exc.colno}",
token=token or "") from None
def record_full_page(endpoint: str, rows: list, seen: set[bytes]) -> None:
digest = hashlib.sha256(json.dumps(rows, sort_keys=True).encode()).digest()
if digest in seen:
raise GhError(("gh", "api", endpoint), "GitHub repeated a full page")
seen.add(digest)
def _iter_paged(endpoint: str, key: str = "check_runs") -> Iterator[dict]:
"""Yield validated rows until the last page."""
seen: set[bytes] = set()
for page in count(1):
chunk = _gh_json("api", endpoint, "--method", "GET", "-F", f"per_page={PAGE}",
"-F", f"page={page}")
if isinstance(chunk, dict):
chunk = chunk.get(key)
if not isinstance(chunk, list) or not all(isinstance(row, dict) for row in chunk):
raise GhError(("gh", "api", endpoint), "invalid paginated response")
if len(chunk) >= PAGE:
record_full_page(endpoint, chunk, seen)
yield from chunk
if len(chunk) < PAGE:
return
def _paged(endpoint: str, key: str = "check_runs") -> list:
return list(_iter_paged(endpoint, key))
def api_get(endpoint: str, **kwargs) -> object:
"""`gh api <endpoint>` parsed as JSON (None on an empty body)."""
return _gh_json("api", endpoint, **kwargs)
def response_date(value: str) -> datetime | None:
if _HTTP_DATE.fullmatch(value):
with suppress(OverflowError, ValueError):
return parsedate_to_datetime(value)
return None
def auth_token() -> str:
"""Token of the authenticated `gh` host, for Git transports that cannot call gh."""
return _gh("auth", "token", "--hostname", "github.com").strip()
def login(token: str | None = None) -> str:
"""Login of the identity used for GitHub reads and review publishing."""
data = _gh_json("api", "graphql", "-f", "query=query { viewer { login } }", token=token)
content = data.get("data") if isinstance(data, dict) else None
if isinstance(content, dict) and isinstance(viewer := content.get("viewer"), dict) and (name := viewer.get("login")):
return str(name)
raise GhError(("gh", "api", "graphql"), "no login in viewer response")
def _not_found(number: int, exc: Exception) -> GhError:
return GhError(("gh", "api"), f"PR #{number} not found or not accessible ({exc!r})")
def _api(endpoint: str, payload: dict, method: str = "POST",
token: str | None = None, *, timeout: float = 120) -> object:
with tempfile.NamedTemporaryFile(
mode="w", suffix=".loopzero", encoding="utf-8", delete_on_close=False
) as handle:
handle.write(json.dumps(payload))
handle.close()
return _gh_json("api", endpoint, "--method", method, "--input", handle.name, token=token, timeout=timeout)
def merge_hold(number: int, labels: tuple[str, ...]) -> str | None:
if "hold" in labels:
return f"PR #{number} has a merge-authority hold; ask the decisions owner to release it"
return None
def _pr_labels(data: dict) -> tuple[str, ...]:
return tuple(label["name"] for label in data.get("labels", []))
def pr_from_rest(data: object) -> PR:
"""Normalize one REST pull detail without treating absent merge evidence as clean."""
try:
if not isinstance(data, dict):
raise TypeError("PR detail is not an object")
number = data["number"]
head, base = data["head"], data["base"]
url, head_sha, base_ref = data["html_url"], head["sha"], base["ref"]
state, merged, draft = data["state"], data["merged"], data["draft"]
mergeable = data["mergeable"]
merge_state = data["mergeable_state"]
if (type(number) is not int or number < 1 or state not in {"open", "closed"}
or type(merged) is not bool or type(draft) is not bool
or (mergeable is not None and type(mergeable) is not bool)
or (merge_state is not None and not isinstance(merge_state, str))
or (merged and state != "closed")
or not isinstance(url, str) or not url.startswith("https://")
or not isinstance(base_ref, str) or not base_ref
or not isinstance(head_sha, str)
or not re.fullmatch(r"[0-9a-f]{40}", head_sha)):
raise ValueError("invalid PR state, mergeability, or head")
return PR(
number=number, url=url, head_sha=head_sha, base_ref=base_ref, is_draft=draft,
state="MERGED" if merged else state.upper(),
mergeable="UNKNOWN" if mergeable is None else
("MERGEABLE" if mergeable else "CONFLICTING"),
merge_state=merge_state.upper() if merge_state else "UNKNOWN",
author=str((data.get("user") or {}).get("login") or ""),
body=str(data.get("body") or ""), labels=_pr_labels(data),
)
except (AttributeError, KeyError, TypeError, ValueError) as exc:
number = data.get("number", "?") if isinstance(data, dict) else "?"
raise _not_found(number, exc) from exc
def _pr_detail(repo: str, number: int) -> tuple[PR, dict]:
endpoint = f"repos/{repo}/pulls/{number}"
data = api_get(endpoint)
pr = pr_from_rest(data)
if pr.number != number:
raise GhError(("gh", "api", endpoint), f"PR detail number {pr.number} differs from requested {number}")
return pr, data
def _matches_branch(source: dict, repo: str, branch: str) -> bool:
source_repo = source.get("repo")
name = source_repo.get("full_name") if isinstance(source_repo, dict) else None
return source.get("ref") == branch and isinstance(name, str) and name.casefold() == repo.casefold()
def _branch_sha(endpoint: str, field: str, invalid: str, *, full_sha: bool = False) -> str | None:
try:
ref = api_get(endpoint)
except GhError as exc:
if re.search(r"\bHTTP 404\b", exc.tail):
return None
raise
ref_data = ref.get(field) if isinstance(ref, dict) else None
sha = ref_data.get("sha") if isinstance(ref_data, dict) else None
if not isinstance(sha, str) or not sha or (full_sha and not re.fullmatch(r"[0-9a-f]{40}", sha)):
raise GhError(("gh", "api", endpoint), invalid)
return sha
def _branch_head(repo: str, branch: str) -> str | None:
endpoint = f"repos/{repo}/branches/{quote(branch, safe='')}"
return _branch_sha(endpoint, "commit", "invalid remote branch SHA", full_sha=True)
def _commit_branch_prs(repo: str, branch: str) -> tuple[str, list[dict]]:
sha = _branch_head(repo, branch)
if sha is None:
return "", []
matches: list[dict] = []
for page in range(1, 101):
endpoint = f"repos/{repo}/commits/{sha}/pulls?per_page={PAGE}&page={page}"
rows = api_get(endpoint)
if not isinstance(rows, list) or len(rows) > PAGE:
raise GhError(("gh", "api", endpoint), "invalid commit PR page")
for row in rows:
if not isinstance(row, dict) or not isinstance(row.get("head"), dict):
raise GhError(("gh", "api", endpoint), "invalid commit PR head")
if _matches_branch(row["head"], repo, branch):
if (row.get("state") not in ("open", "closed")
or type(row.get("number")) is not int or row["number"] < 1
or not isinstance(row.get("created_at"), str)):
raise GhError(("gh", "api", endpoint), "invalid commit PR")
matches.append(row)
if len(rows) < PAGE:
return endpoint, matches
raise GhError(("gh", "api", endpoint), "commit PRs exceed 100 pages")
def _confirm_branch_pr(repo: str, branch: str, endpoint: str, number: int, state: str) -> PR:
pr, detail = _pr_detail(repo, number)
matches_state = pr.state == state or (state == "CLOSED" and pr.state == "MERGED")
if not matches_state or not _matches_branch(detail["head"], repo, branch):
lookup = "completion" if state == "MERGED" else "branch"
raise GhError(("gh", "api", endpoint), f"PR changed during {lookup} lookup")
return pr
def pr_for_branch(repo: str, branch: str, *, open_only: bool = False, list_only: bool = False) -> PR | None:
"""Return the open PR, falling back to the most recent closed PR unless open_only."""
if not list_only:
endpoint, matches = _commit_branch_prs(repo, branch)
newest = max((row for row in matches if row["state"] == "open"),
key=lambda row: (row["created_at"], row["number"]), default=None)
if newest is not None:
return _confirm_branch_pr(repo, branch, endpoint, newest["number"], "OPEN")
# A closed association cannot rule out an open PR or newer closed history.
owner = repo.split("/", 1)[0]
head = quote(f"{owner}:{branch}", safe="")
for state in (("open",) if open_only else ("open", "closed")):
endpoint = (f"repos/{repo}/pulls?state={state}&head={head}"
"&sort=created&direction=desc&per_page=1")
rows = api_get(endpoint)
if not isinstance(rows, list):
raise GhError(("gh", "api", endpoint), "invalid PR list response")
if rows:
number = rows[0].get("number") if isinstance(rows[0], dict) else None
if type(number) is not int or number < 1:
raise GhError(("gh", "api", endpoint), "invalid PR number in list")
return _confirm_branch_pr(repo, branch, endpoint, number, state.upper())
return None
def _closed_history_number(repo: str, branch: str, endpoint: str, row: dict,
seen: set[int]) -> int:
try:
number, merged_at = row["number"], row["merged_at"]
source = row["head"]
if (type(number) is not int or number < 1 or number in seen
or row["state"] != "closed" or not isinstance(source, dict)
or not _matches_branch(source, repo, branch)):
raise ValueError("invalid or repeated closed PR")
if merged_at is not None and (
not isinstance(merged_at, str) or datetime.fromisoformat(merged_at).tzinfo is None
):
raise ValueError("invalid merged_at")
except (KeyError, TypeError, ValueError) as exc:
raise GhError(("gh", "api", endpoint), "invalid or repeated closed PR history") from exc
return number
def merged_pr_for_branch(repo: str, branch: str) -> PR | None:
"""Prove completion, or read the complete closed history before publication."""
head = quote(f"{repo.split('/', 1)[0]}:{branch}", safe="")
commit_endpoint, matches = _commit_branch_prs(repo, branch)
seen: set[int] = set()
for page in range(101):
if page == 0:
endpoint = commit_endpoint
rows = [row for row in matches if row["state"] == "closed"]
else:
endpoint = (f"repos/{repo}/pulls?state=closed&head={head}"
f"&sort=created&direction=desc&per_page={PAGE}&page={page}")
rows = api_get(endpoint)
if not isinstance(rows, list) or (page and len(rows) > PAGE):
raise GhError(("gh", "api", endpoint), "invalid closed PR history page")
for row in rows:
number = _closed_history_number(repo, branch, endpoint, row, seen)
seen.add(number)
if row["merged_at"] is not None:
return _confirm_branch_pr(repo, branch, endpoint, number, "MERGED")
if page == 0:
# A prior merge may belong to a different commit of this branch.
seen.clear()
elif len(rows) < PAGE:
return None
raise GhError(("gh", "api", endpoint), "closed PR history exceeds 100-page publication limit")
def pr_view(repo: str, number: int) -> PR:
return _pr_detail(repo, number)[0]
def create_draft_pr(repo: str, branch: str, base: str, title: str, body: str) -> PR:
detail = _api(
f"repos/{repo}/pulls", {"head": branch, "base": base, "title": title,
"body": body, "draft": True})
pr = pr_from_rest(detail)
if (pr.state != "OPEN" or not pr.is_draft or pr.base_ref != base
or not _matches_branch(detail["head"], repo, branch)):
raise GhError(("gh", "api", f"repos/{repo}/pulls"), "created PR differs from request")
return pr
def update_body(repo: str, number: int, body: str) -> None:
_api(f"repos/{repo}/pulls/{number}", {"body": body}, method="PATCH", token=app_token())
def finding_id(head_sha: str, path: str | None, line: int | None, title: str) -> str:
raw = f"{head_sha}{path or ''}{line if line is not None else ''}{title}"
return hashlib.sha256(raw.encode()).hexdigest()[:8]
def finding_marker(severity: str, head_sha: str, finding: Finding) -> str:
stable_id = finding_id(head_sha, finding.path, finding.line, finding.title)
return f"<!-- loopzero:finding v=1 severity={severity} head={head_sha} id={stable_id} -->"
def _comment_body(f: Finding, head_sha: str, prefix: str = "") -> str:
text = prefix + _CREDENTIAL_TOKEN_RE.sub("[REDACTED]", f"**{f.severity}: {f.title}**\n\n{f.body}").rstrip()
if f.severity in BLOCKING:
return f"{finding_marker(f.severity, head_sha, f)}\n{text}"
return text
ReviewSettingsLayout = Literal["current", "requested-reported", "summary"]
def _review_body(result: ReviewResult, unplaced: list[Finding], prefix: str = "", *,
settings_layout: ReviewSettingsLayout = "current", legacy_display: bool = False,
publication: tuple[str, int] | None = None) -> str:
evidence = None
if result.family == "codex":
evidence = (runners.codex_evidence(result) if result.provenance
else runners._codex_evidence(result))
if evidence is not None:
if legacy_display or (publication and (evidence["repo"], evidence["pr"]) != publication):
raise runners.RunnerBadOutput("codex: publication context mismatch")
first, separator, rest = prefix.partition("\n")
marker = runners.REVIEW_MARKER_RE.fullmatch(first)
header = runners.encode_codex_evidence(evidence)
if not marker or marker[1] != result.head or marker[2] != result.kind:
raise runners.RunnerBadOutput("codex: invalid/oversized leading machine block")
prefix = first + "\n" + header + (separator + rest if separator else "")
_, span = runners.leading_review_block(prefix)
if len(span.encode("utf-8")) > runners.CODEX_HEADER_LIMIT:
raise runners.RunnerBadOutput("codex: oversized leading machine block; HOLD")
severities = [f.severity for f in result.findings]
summary = ", ".join(f"{severities.count(s)} {s}" for s in ("critical", "important", "suggestion"))
duration = "unknown" if result.duration_s is None else f"{result.duration_s:.1f}s"
settings = ""
if settings_layout == "summary":
effort = f" (effort {result.effort})" if result.effort else ""
settings = f"model {result.model or 'unknown'}{effort}, "
lines = [prefix.rstrip("\n")] if prefix else []
lines.append(
f"loopzero {result.kind} review by {result.family} on `{result.head}`, "
f"{settings}{duration}: **{result.verdict}** ({summary})"
)
if result.fallback:
lines.append(f"\nSame-family fallback: {result.fallback}. Cross-family review is preferred.")
if result.chunk_count > 1:
lines.append(f"\nReviewed in {result.chunk_count} chunks with the same model family.")
if settings_layout != "summary":
lines.extend(_review_settings_lines(result, include_configured=settings_layout == "current"))
if unplaced:
lines.append("\nFindings without a file location:\n")
lines += [_CREDENTIAL_TOKEN_RE.sub("[REDACTED]", f"- **{f.severity}**: {f.title} — {f.body}".rstrip(" —")) for f in unplaced]
return "\n".join(lines) + _review_transcript(result, legacy_display)
def _review_settings_lines(result: ReviewResult, *, include_configured: bool) -> list[str]:
claims = "launch configuration and CLI claims" if include_configured else "CLI claims"
lines = [f"\nSettings per native call ({claims}, not backend attestation):"]
for index, call in enumerate(review_settings(result), 1):
request, reported = call["requested"], call["reported"]
if result.family == "codex":
request, reported = ({key: value if runners._identifier(value, 128 if key == "model" else 32) else None
for key, value in settings.items()} for settings in (request, reported))
fields = [("requested", request), ("CLI-reported", reported)]
if include_configured:
fields.append(("configured", call["configured"]))
settings = "; ".join(f"{label} model {value['model'] or 'unknown'} "
f"(effort {value['effort'] or 'unknown'})" for label, value in fields)
lines.append(f"- Call {index}: {settings}")
return lines
def _review_transcript(result: ReviewResult, legacy_display: bool) -> str:
if result.family == "claude" and not legacy_display:
return "\n\nNative Claude output is retained in the restricted local review receipt."
raw = result.raw
if result.family == "codex" and not legacy_display:
raw = ("Native Codex transcript retained in the restricted local review receipt; "
"public evidence is publisher-derived, not backend attestation. "
"Exact raw SHA256: " + hashlib.sha256(result.raw.encode()).hexdigest())
encoded = raw.encode("utf-8")
if len(encoded) > 30_000:
tail = encoded[-30_000:].decode("utf-8", errors="ignore")
raw = ("[Transcript truncated; showing the last at most 30,000 UTF-8 bytes. "
"Full output remains in the saved local review artifact.]\n" + tail)
return f"\n\n<details><summary>Raw reviewer output</summary>\n\n```\n{raw}\n```\n</details>"
def _right_lines(patch: str) -> tuple[set[int], int | None]:
"""Right-side (new file) line numbers present in `patch`, and the first added line."""
lines: set[int] = set()
first_added: int | None = None
current = None
for raw in patch.removesuffix("\n").split("\n"):
hunk = _HUNK_RE.match(raw)
if hunk:
current = int(hunk.group(1))
continue
if current is None or raw.startswith(("-", "\\")):
continue
lines.add(current)
if raw.startswith("+") and first_added is None:
first_added = current
current += 1
return lines, first_added
def _diff_map(repo: str, number: int, head_sha: str,
findings: tuple[Finding, ...]) -> tuple[dict[str, set[int]], dict | None]:
blocking = tuple(f for f in findings if f.severity in BLOCKING)
remaining = {f.path for f in findings if f.path and (f.line or f.severity in BLOCKING)}
commentable: dict[str, set[int]] = {}
anchor: dict | None = None
endpoint = f"repos/{repo}/pulls/{number}/files"
rows = _iter_paged(endpoint) if remaining or blocking else ()
count = 0
for entry in rows:
count += 1
path = entry["filename"]
lines, first_added = _right_lines(entry.get("patch") or "")
commentable[path] = lines
if lines and anchor is None:
line = first_added if first_added is not None else min(lines)
anchor = {"path": path, "line": line, "side": "RIGHT"}
remaining.discard(path)
if not remaining and (not blocking or anchor is not None):
return commentable, anchor
missing = next((f.path for f in blocking if f.path in remaining), None)
if missing is not None and count >= PR_FILE_LIMIT:
pr, detail = _pr_detail(repo, number)
request = ("gh", "api", endpoint)
if pr.head_sha != head_sha:
raise GhError(request, f"PR #{number} head moved from {head_sha[:12]} to {pr.head_sha[:12]}; rerun review")
if detail.get("changed_files") != len(commentable):
raise GhError(request, f"cannot place finding on PR #{number} at {missing!r}: "
f"GitHub's {PR_FILE_LIMIT:,}-file limit prevents verifying the complete file list")
return commentable, anchor
def review_payload(repo: str, number: int, head_sha: str, result: ReviewResult,
body_prefix: str) -> dict:
"""Regenerate the publication content from the runner result and current PR diff."""
return review_payloads(repo, number, head_sha, result, [(body_prefix, "current", False)])[0]
def review_payloads(repo: str, number: int, head_sha: str, result: ReviewResult,
formats: list[tuple[str, ReviewSettingsLayout, bool]]) -> list[dict]:
"""Place findings once for all exact body formats used in read-back."""
commentable, anchor = _diff_map(repo, number, head_sha, result.findings)
comments: list[dict] = []
loose: list[Finding] = []
for f in result.findings:
if f.path and f.line and f.line in commentable.get(f.path, ()):
comments.append({"path": f.path, "line": f.line, "side": "RIGHT",
"body": _comment_body(f, head_sha)})
elif f.severity not in BLOCKING:
loose.append(f)
elif anchor is None:
raise GhError(("gh", "api", f"repos/{repo}/pulls/{number}/files"),
f"cannot anchor '{f.title}': PR has no diff hunks")
else:
note = _MOVED_NOTE.format(where=f"{f.path}:{f.line}") if f.path else _ANCHOR_NOTE
comments.append({**anchor, "body": _comment_body(f, head_sha, prefix=note)})
return [{
"commit_id": head_sha,
"body": _review_body(result, loose, body_prefix, settings_layout=settings_layout,
legacy_display=legacy_display, publication=(repo, number)),
"comments": comments,
} for body_prefix, settings_layout, legacy_display in formats]
def post_review(
repo: str,
number: int,
head_sha: str,
result: ReviewResult,
body_prefix: str = "",
pr: PR | None = None,
token: str | None = None,
*,
publisher: str | None = None,
) -> None:
"""Post `result` as a PR review on `head_sha`, one inline comment per finding.
`body_prefix`, when given, becomes the first line of the review body. When the
token user authored the PR (`pr` is fetched if not given) the review is posted
as a COMMENT, since GitHub rejects self-approval and self-request-changes.
Findings whose location is missing or outside the diff are anchored on the first
changed file with a hunk, so every blocking finding creates a review thread.
A supplied publisher is the login already checked for the supplied token.
"""
author = (pr or pr_view(repo, number)).author
token = app_token() if token is None else token # "" means the operator identity
if token or (author and author == (publisher or login(token=token))):
event = "COMMENT"
else:
event = "APPROVE" if result.verdict == "approve" else "REQUEST_CHANGES"
payload = {**review_payload(repo, number, head_sha, result, body_prefix), "event": event}
endpoint = f"repos/{repo}/pulls/{number}/reviews"
try:
_api(endpoint, payload, token=token)
except GhError as exc:
if event == "COMMENT" or not _SELF_REVIEW.search(exc.tail):
raise
_api(endpoint, {**payload, "event": "COMMENT"}, token=token)
def _title_of(text: str) -> str:
lines = [ln for ln in text.strip().splitlines() if ln.strip()]
title_line = next((ln for ln in lines if ln.startswith("**")), lines[0] if lines else "")
return re.sub(r"^\*\*\w+:\s*|\*\*$", "", title_line).strip()
def _thread_marker(node: dict, publishers: tuple[str, ...]) -> re.Match[str] | None:
"""The v=1 marker opening a thread's first comment, if a review publisher wrote it."""
comments = node.get("comments", {}).get("nodes") or []
if not comments:
return None
author = comments[0].get("author") or {}
login = str(author.get("login") or "")
# GraphQL names an App's bot account without REST's "[bot]" suffix.
if author.get("__typename") == "Bot":
login += "[bot]"
if not login or login.casefold() not in {p.casefold() for p in publishers}:
return None