Repository navigation
Expand file tree
/
Copy patheligibility.py
More file actions
272 lines (238 loc) · 13.2 KB
/
Copy patheligibility.py
File metadata and controls
272 lines (238 loc) · 13.2 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
"""Source-head review evidence shared by local readiness and trusted hosted callers.
Run the module only from trusted base code/config; it never checks out a PR.
Hosted callers must serialize refreshes per PR and invalidate before review edits.
"""
from __future__ import annotations
import argparse
import json
import re
import sys
from collections.abc import Callable
from pathlib import Path
from time import sleep
from loopzero import candidate, config, github, runners
from loopzero.types import LoopZeroError
REVIEW_MARKER_RE = runners.REVIEW_MARKER_RE
CONTEXT = "Loop-zero Eligibility"
def leading_marker(body: str) -> re.Match[str] | None:
"""The review marker opening the publisher's leading machine block; prose never counts."""
block, span = runners.leading_review_block(body if isinstance(body, str) else "")
if not block or len(REVIEW_MARKER_RE.findall(span)) != 1:
return None
return REVIEW_MARKER_RE.fullmatch(block[0])
def review_envelopes(body: str) -> tuple[str, list[dict]]:
"""Decode only the publisher's raw-output block, not quoted findings/prose."""
if not isinstance(body, str):
return "", []
match = re.search(r"<details><summary>Raw reviewer output</summary>\s*```\s*\n(.*?)\n```", body, re.DOTALL)
if not match:
return "", []
raw = match[1].strip()
try:
value = json.loads(raw)
except (ValueError, TypeError):
return raw, []
envelopes = value if isinstance(value, list) else [value]
return raw, envelopes if all(isinstance(item, dict) for item in envelopes) else []
def review_projection(review: dict, head: str, repo: str, number: int):
"""Only the anchored leading machine block; model prose/fences are never searched."""
body = review.get("body") or ""
block, span = runners.leading_review_block(body)
positions = [i for i, line in enumerate(block) if line.lstrip().startswith("<!-- loopzero:codex-evidence")]
# Retired pair markers must never fall back to ordinary review evidence.
if any("source=pair" in marker[0] for marker in REVIEW_MARKER_RE.finditer(span)):
return True, None
if not positions:
return False, None
try:
if (positions != [1] or len(span.encode("utf-8")) > runners.CODEX_HEADER_LIMIT
or (len(block) > 2 and (len(block) != 3 or not re.fullmatch(
r"<!-- loopzero:adjudication v=1 replaces=[0-9]+(?:,[0-9]+)* target=" + head + r" -->", block[2])))):
return True, None
marker = REVIEW_MARKER_RE.fullmatch(block[0])
evidence = runners.decode_codex_evidence(block[1])
if (not marker or marker[1] != head or marker[2] != evidence["kind"]
or evidence["repo"] != repo or evidence["pr"] != number
or evidence["head"] != head or evidence["publisher"] != (review.get("user") or {}).get("login")
or review.get("commit_id") != head or not evidence["complete"]):
return True, None
return True, evidence
except (ValueError, TypeError, KeyError):
return True, None
def eligible_review(reviews: list[dict], head: str, publishers: tuple[str, ...], *,
repo: str = "", number: int = 0) -> dict | None:
"""Latest trusted evidence on this exact head; revocation cannot revive older evidence."""
trusted = {login.casefold() for login in publishers}
latest = next((r for r in reversed(reviews)
if (r.get("user") or {}).get("login", "").casefold() in trusted
and r.get("commit_id") == head and "loopzero:review" in (r.get("body") or "")), None)
if latest is None or latest.get("state") not in {"APPROVED", "COMMENTED", "CHANGES_REQUESTED"}:
return None
body = latest.get("body") or ""
marker = leading_marker(body)
if not marker or marker.group(1) != head or not re.fullmatch(r"[0-9a-f]{40}", head):
return None
verdict = latest.get("state") in {"APPROVED", "CHANGES_REQUESTED"} or any(
f"**{value}**" in body for value in ("approve", "request_changes")
)
present, evidence = review_projection(latest, head, repo, number)
if present and (evidence is None or any(call["fatal"] != "absent" for call in evidence["calls"])):
return None
_, envelopes = review_envelopes(body)
if not present and any(runners.codex_fatal_startup(item) for item in envelopes):
return None
return latest if verdict else None
def _verified_merge(git: Callable[..., str], merge: str, first: str, second: str,
base: str, *, clean: bool) -> bool:
git("merge-base", "--is-ancestor", second, base)
merge_bases = git("merge-base", "--all", first, second).splitlines()
# A shallow root outside the known merge bases could hide another base.
if git("rev-list", "--max-parents=0", first, second, "--not", *merge_bases):
return False
return not clean or git("merge-tree", "--write-tree", first, second) == git("rev-parse", f"{merge}^{{tree}}")
def _verified_base_chain(git: Callable[..., str], reviewed: str, head: str, base: str, *,
clean: bool, conflict_only: bool) -> bool:
cursor, conflict = head, False
row_lengths = {3} if clean or conflict_only else {2, 3}
for row in git("rev-list", "--first-parent", "--parents", f"{reviewed}..{head}").splitlines():
commits = row.split()
if len(commits) not in row_lengths or commits[0] != cursor:
return False
cursor = commits[1]
if len(commits) == 2:
continue
if not _verified_merge(git, *commits, base, clean=clean):
return False
if conflict_only and not conflict:
conflict = git("merge-tree", "--write-tree", *commits[1:], merge_conflict_status=True) == "1"
return cursor == reviewed and (conflict or not conflict_only)
def base_merge_material(
repo: str, number: int, reviewed: str, head: str, base_branch: str, *, clean: bool, conflict_only: bool = False,
) -> bytes | None:
"""Return a verified delta patch, or empty bytes for proven clean inheritance."""
try:
pr = github.api_get(f"repos/{repo}/pulls/{number}")
base = pr["base"]["sha"]
if (pr["head"]["sha"] != head or pr["base"]["ref"] != base_branch
or not re.fullmatch(r"[0-9a-f]{40}", base)):
return None
with candidate.fetched_git(repo, [reviewed, head, base]) as git:
if not _verified_base_chain(git, reviewed, head, base, clean=clean, conflict_only=conflict_only):
return None
if clean:
return b""
patch = git("log", "--first-parent", "--reverse", "--remerge-diff", "-p", "--format=",
"--no-color", "--no-ext-diff", "--no-textconv", "--text",
"--ignore-submodules=none", "--submodule=short",
f"{reviewed}..{head}", preserve_newlines=True)
return patch.encode("utf-8", errors="surrogateescape")
except github.GhUnavailable:
raise
except (candidate.CandidateError, github.GhError, KeyError, OSError, TypeError, ValueError):
return None
def _summary_verdict(body: str, kind: str) -> str:
# Read the publisher's summary before model prose can quote either verdict.
_, machine_block = runners.leading_review_block(body)
summary, _, rest = body[len(machine_block):].lstrip().partition("\n")
if summary.startswith(("Reposted from runner session: ", "Reposted from runner sessions: ")):
summary = rest.partition("\n")[0]
return summary.partition(": **")[2] if summary.startswith(f"loopzero {kind} review by ") else ""
def approved_delta(reviews: list[dict], head: str, publishers: tuple[str, ...], *, repo: str, number: int) -> bool:
review = eligible_review(reviews, head, publishers, repo=repo, number=number)
return bool(review and review["state"] in {"APPROVED", "COMMENTED"}
and _summary_verdict(review["body"], "delta").startswith("approve** ("))
def readiness_review(reviews: list[dict], head: str, publishers: tuple[str, ...], *,
repo: str, number: int, base_branch: str) -> dict | None:
"""An eligible review at the current head or an ancestor that covers it."""
trusted = {login.casefold() for login in publishers}
marked = [r for r in reviews if (r.get("user") or {}).get("login", "").casefold() in trusted
and "loopzero:review" in (r.get("body") or "")]
if not marked or any(r.get("commit_id") == head for r in marked):
return eligible_review(marked, head, publishers, repo=repo, number=number)
latest = marked[-1]
marker = leading_marker(latest["body"])
if not marker or marker[2] not in {"primary", "delta"}:
return None
reviewed = marker[1]
if eligible_review(marked, reviewed, publishers, repo=repo, number=number) is not latest:
return None
if marker[2] == "primary":
verdict = _summary_verdict(latest["body"], "primary")
state = latest.get("state")
if verdict.startswith("request_changes** (") and state in {"CHANGES_REQUESTED", "COMMENTED"}:
if github.open_blocking_findings(repo, number, reviewed, publishers):
return None
elif not (verdict.startswith("approve** (") and state in {"APPROVED", "COMMENTED"}):
return None
if base_merge_material(repo, number, reviewed, head, base_branch, clean=True) is None:
return None
return latest
def source_fingerprint(pr: github.PR) -> tuple[object, ...]:
return (pr.number, pr.head_sha, pr.base_ref, pr.state, pr.mergeable == "CONFLICTING",
github.merge_hold(pr.number, pr.labels))
def source_snapshot(repo: str, number: int, head: str, pr: github.PR | None = None) -> github.PR:
pr = pr if pr is not None else github.pr_view(repo, number)
for delay in (2, 4, 8):
if pr.head_sha != head or github.mergeability_blocker(pr) != github.MERGEABILITY_PENDING:
break
sleep(delay)
pr = github.pr_view(repo, number)
return pr
def evaluate(repo: str, number: int, head: str, base: str,
publishers: tuple[str, ...], *, snapshot: github.PR | None = None) -> github.Readiness:
"""Evaluate live review evidence. Callers supplying a snapshot own the final source check."""
if not publishers or not re.fullmatch(r"[0-9a-f]{40}", head):
raise LoopZeroError("eligibility requires trusted publishers and a full source SHA")
pr = snapshot if snapshot is not None else source_snapshot(repo, number, head)
if pr.number != number or pr.head_sha != head:
return github.Readiness(False, ("source head changed; refresh eligibility",))
if hold := github.merge_hold(pr.number, pr.labels):
return github.Readiness(False, (hold,))
reviews, page = [], 1
seen: set[bytes] = set()
endpoint = f"repos/{repo}/pulls/{number}/reviews"
while True:
batch = github.api_get(f"{endpoint}?per_page={github.PAGE}&page={page}")
if not isinstance(batch, list):
raise LoopZeroError("invalid GitHub reviews response")
if len(batch) >= github.PAGE:
github.record_full_page(endpoint, batch, seen)
reviews.extend(batch)
if len(batch) < github.PAGE:
break
page += 1
review = readiness_review(reviews, head, publishers, repo=repo, number=number, base_branch=base)
result = github.readiness(repo, pr, base, (), head if review else None, allow_behind=True,
ancestor_review=review is not None and review["commit_id"] != head,
publishers=publishers)
current = github.pr_view(repo, number) if snapshot is None else pr
if snapshot is None and source_fingerprint(current) != source_fingerprint(pr):
return github.Readiness(False, ("source changed during eligibility refresh",))
if snapshot is None and result.ready and (blocker := github.mergeability_blocker(current)):
return github.Readiness(False, (blocker,))
return result
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--config", type=Path, required=True, help="trusted base workflow.toml")
parser.add_argument("--pr", type=int, required=True)
parser.add_argument("--head", required=True)
parser.add_argument("--publish", action="store_true")
args = parser.parse_args(argv)
try:
cfg = config.load(args.config)
except config.ConfigError as exc:
print(exc, file=sys.stderr)
return 1
if not cfg.review_publishers or args.pr <= 0 or not re.fullmatch(r"[0-9a-f]{40}", args.head):
raise LoopZeroError("configure delivery.review_publishers and specify PR/full source SHA")
def publish(state: str, description: str) -> None:
github.commit_status(cfg.repo, args.head, CONTEXT, state, description[:140])
if args.publish:
publish("pending", "Refreshing source review evidence")
result = evaluate(cfg.repo, args.pr, args.head, cfg.base_branch, cfg.review_publishers)
if args.publish:
publish("success" if result.ready else "failure", "; ".join(result.reasons) or "Reviewed source head")
print("eligible" if result.ready else "; ".join(result.reasons))
return 0 if result.ready else 1
if __name__ == "__main__":
raise SystemExit(main())