Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,10 @@ local-receipt exceptions. Merge authority permits merging by default outside
reserved classes.

Git owns commits, branches and ancestry. GitHub owns the live PR narrative,
reviews, finding threads, check statuses and merge state. Within a task worktree,
PR body writers lock the state directory from the live read through the update.
Review publication rechecks the round while holding a same-host lock keyed by
repository and PR. The lock covers POST and lost-response read-back.
reviews, finding threads, check statuses and merge state. PR body writers hold
the same-host repository-and-PR lock from the live read through the update.
Review publication holds that lock for its round recheck, POST, read-back, and
body summary. Check coalescing and receipts retain the worktree-local lock.
CI and branch protection
provide the hosted enforcement. Readiness is a checklist over these sources,
not a tamper-proof security boundary: repository writers can edit PR evidence,
Expand Down
32 changes: 18 additions & 14 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -572,15 +572,20 @@ def _append_review(body: str, result: ReviewResult) -> str:
def _refresh_pr_checks(wt: Path, config: Config) -> None:
"""Best-effort refresh only when local HEAD is the existing PR head."""
try:
with worktree.lock_local_state(wt):
upstream = config_mod.run_git(wt, "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}")
if upstream.exit_code == 0:
branch, head = worktree.branch(wt), worktree.head(wt)
pr = github.pr_for_branch(config.repo, branch, open_only=True)
if pr is not None and pr.head_sha == head:
body = _pr_body(wt, head, config, pr.body)
if body != (pr.body or "").replace("\r\n", "\n"):
github.update_body(config.repo, pr.number, body)
upstream = config_mod.run_git(wt, "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}")
if upstream.exit_code != 0:
return
branch, head = worktree.branch(wt), worktree.head(wt)
pr = github.pr_for_branch(config.repo, branch, open_only=True)
if pr is None or pr.head_sha != head:
return
with github.pr_lock(config.repo, pr.number):
live = github.pr_view(config.repo, pr.number)
if live.state != "OPEN" or live.head_sha != head:
return
body = _pr_body(wt, head, config, live.body)
if body != live.body.replace("\r\n", "\n"):
github.update_body(config.repo, pr.number, body)
except (github.GhError, _proc.ProcTimeout, OSError, ValueError, CliError, worktree.WorktreeError) as exc:
print(f"note: could not refresh PR checks: {_one_line(exc)}", file=sys.stderr)

Expand Down Expand Up @@ -727,7 +732,7 @@ def cmd_pr(args: argparse.Namespace) -> int:
_require_push_target(wt, config.repo)
_git_push(wt, push, force_lease=force_lease)
if pr is not None:
with worktree.lock_local_state(wt):
with github.pr_lock(config.repo, pr.number):
live = github.pr_view(config.repo, pr.number)
if live.state != "OPEN":
raise CliError(f"PR #{pr.number} closed during publication")
Expand Down Expand Up @@ -888,12 +893,11 @@ def cmd_review(args: argparse.Namespace, wt: Path, config: Config) -> int:
f"{exc} | publication unconfirmed; review saved at {path}; "
"inspect the cause and run `loopzero review --repost` to reconcile or explicitly retry"
) from exc
try:
with worktree.lock_local_state(wt):
try:
live = github.pr_view(config.repo, pr.number)
github.update_body(config.repo, pr.number, _append_review(live.body, result))
except (github.GhError, _proc.ProcTimeout, OSError, ValueError) as exc:
print(f"note: could not append PR review summary: {_one_line(exc)}", file=sys.stderr)
except (github.GhError, _proc.ProcTimeout, OSError, ValueError) as exc:
print(f"note: could not append PR review summary: {_one_line(exc)}", file=sys.stderr)
return _review_verdict(result)


Expand Down
93 changes: 36 additions & 57 deletions src/loopzero/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
from dataclasses import dataclass
from datetime import UTC, datetime
from email.utils import parsedate_to_datetime
from itertools import pairwise
from itertools import count, pairwise
from pathlib import Path
from typing import Literal
from urllib.parse import quote
Expand Down Expand Up @@ -176,18 +176,15 @@ 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 separator:
if not separator:
continue
status_line, *header_lines = head.split(line_separator)
if not (match := _HTTP_STATUS_RE.match(status_line)):
break
else:
return None, {}, output
lines = head.split(line_separator)
match = _HTTP_STATUS_RE.match(lines[0])
if match is None:
return None, {}, output
headers = {name.strip().casefold(): value.strip()
for name, separator, value in (line.partition(":") for line in lines[1:])
if separator}
return match.group(1), headers, body
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]:
Expand All @@ -202,14 +199,6 @@ def _api_method(args: tuple[str, ...]) -> str:
return methods[0] if methods else "POST" if _API_BODY_FLAGS.intersection(args) else "GET"


def _api_path(args: tuple[str, ...]) -> str:
endpoint = args[1] if len(args) > 1 else ""
path = endpoint.split("?", 1)[0]
if "://" in path:
path = path.partition("://")[2].partition("/")[2]
return "/" + path.lstrip("/")


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""",
Expand Down Expand Up @@ -242,28 +231,23 @@ def _api_error_detail(args: tuple[str, ...], response: tuple[str | None, dict[st
status = match.group(1) if match else "unavailable"
request_id = headers.get("x-github-request-id") or "unavailable"
message = ""
try:
payload = json.loads(body)
except (TypeError, ValueError):
payload = None
if isinstance(payload, dict):
message_value = payload.get("message")
if isinstance(message_value, str):
message = message_value
else:
errors = payload.get("errors")
if isinstance(errors, list):
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)
)
if message_tail is not None:
message = message_tail
elif not message:
message = body.strip() or stderr.strip().removeprefix("gh:").strip()
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={_api_path(args)} status={status} "
f"method={_api_method(args)} endpoint=/{path.lstrip('/')} status={status} "
f"request_id={request_id} message={message}", token
)

Expand Down Expand Up @@ -515,9 +499,8 @@ def record_full_page(endpoint: str, rows: list, seen: set[bytes]) -> None:

def _iter_paged(endpoint: str, key: str = "check_runs") -> Iterator[dict]:
"""Yield validated rows until the last page."""
page = 1
seen: set[bytes] = set()
while True:
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):
Expand All @@ -529,7 +512,6 @@ def _iter_paged(endpoint: str, key: str = "check_runs") -> Iterator[dict]:
yield from chunk
if len(chunk) < PAGE:
return
page += 1


def _paged(endpoint: str, key: str = "check_runs") -> list:
Expand Down Expand Up @@ -557,11 +539,9 @@ 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
viewer = content.get("viewer") if isinstance(content, dict) else None
name = viewer.get("login") if isinstance(viewer, dict) else None
if not name:
raise GhError(("gh", "api", "graphql"), "no login in viewer response")
return str(name)
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:
Expand Down Expand Up @@ -684,8 +664,8 @@ def _commit_branch_prs(repo: str, branch: str) -> tuple[str, list[dict]]:

def _confirm_branch_pr(repo: str, branch: str, endpoint: str, number: int, state: str) -> PR:
pr, detail = _pr_detail(repo, number)
states = {"CLOSED", "MERGED"} if state == "CLOSED" else {state}
if pr.state not in states or not _matches_branch(detail["head"], repo, branch):
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
Expand All @@ -695,9 +675,9 @@ def pr_for_branch(repo: str, branch: str, *, open_only: bool = False, list_only:
"""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)
open_matches = [row for row in matches if row["state"] == "open"]
if open_matches:
newest = max(open_matches, key=lambda row: (row["created_at"], row["number"]))
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.
Expand Down Expand Up @@ -1437,20 +1417,20 @@ def merged_sha(
"""The verified merge commit, or None while open. Admission may check the hold label."""
argv = ("gh", "api", f"repos/{repo}/pulls/{number}")
view = api_get(argv[2])
if not isinstance(view, dict) or type(view.get("merged")) is not bool:
if not isinstance(view, dict) or type(merged := view.get("merged")) is not bool:
raise GhError(argv, "invalid PR merge evidence")
if expected_head and (not isinstance(view.get("head"), dict)
or view["head"].get("sha") != expected_head):
raise GhError(argv, "PR head changed before merge verification")
if view["merged"] and view.get("state") == "closed":
sha = view.get("merge_commit_sha")
if isinstance(sha, str) and re.fullmatch(r"[0-9a-f]{40}", sha):
state = view.get("state")
if merged and state == "closed":
if isinstance(sha := view.get("merge_commit_sha"), str) and re.fullmatch(r"[0-9a-f]{40}", sha):
return sha
elif not view["merged"] and view.get("state") == "open":
elif not merged and state == "open":
if check_hold and (hold := merge_hold(number, _pr_labels(view))):
raise GhError(argv, hold)
return None # An open PR's merge_commit_sha is only a test merge.
error = ClosedUnmerged if not view["merged"] and view.get("state") == "closed" else GhError
error = ClosedUnmerged if not merged and state == "closed" else GhError
raise error(argv, "PR closed without a verified merge or invalid merge evidence")


Expand All @@ -1459,8 +1439,7 @@ def merge_pending(repo: str, number: int) -> bool:
request that it moves into the queue shortly after (observed ~1 minute, #180)."""
args = _pull_query(repo, number, _QUEUE_QUERY)
try:
data = _gh_json(*args)
pr = data["data"]["repository"]["pullRequest"]
pr = _gh_json(*args)["data"]["repository"]["pullRequest"]
queued = pr["isInMergeQueue"]
auto = pr.get("autoMergeRequest")
if type(queued) is not bool or (auto is not None and not isinstance(auto, dict)):
Expand Down
41 changes: 18 additions & 23 deletions src/loopzero/mergify.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
import time
import urllib.error
import urllib.request
from contextlib import ExitStack, contextmanager
from contextlib import ExitStack, contextmanager, suppress
from dataclasses import dataclass
from pathlib import Path
from urllib.parse import quote
Expand Down Expand Up @@ -117,37 +117,35 @@ def _wait_to_retry(delay: float, deadline: float | None) -> bool:
return deadline is None or time.monotonic() < deadline


def _queue_read_failure(exc: Exception) -> tuple[str, bool]:
if isinstance(exc, (json.JSONDecodeError, UnicodeDecodeError)):
return "Mergify queue lookup returned no valid JSON", True
reason = exc.reason if isinstance(exc, urllib.error.URLError) else exc
return f"Mergify queue transport failed: {reason}", not isinstance(reason, ssl.SSLCertVerificationError)


def api_get(repo: str, suffix: str, deadline: float | None = None) -> object | None:
"""GET one documented endpoint below this repository's fixed Mergify API path."""
if not suffix.startswith("/") or "://" in suffix or ".." in suffix:
raise ValueError("Mergify API suffix must be a repository-relative absolute path")
request = _api_request(repo, suffix)
for retry in (True, False):
delay = 2.0
retry = True
while True:
wait = None
try:
with _open(request) as response:
return json.load(response)
except urllib.error.HTTPError as exc:
if exc.code == 404:
return None
wait = github.retry_after(exc.headers.get("Retry-After", "")) if exc.headers else None
delay = max(delay, wait or 0.0)
detail = f"Mergify queue lookup failed with HTTP {exc.code}" + (f"; Retry-After: {wait:g}s" if wait is not None else "")
transient = exc.code >= 500 or exc.code == 429 or (exc.code == 403 and wait is not None)
except (OSError, json.JSONDecodeError, UnicodeDecodeError, http.client.IncompleteRead) as exc:
detail, transient = _queue_read_failure(exc)
except (json.JSONDecodeError, UnicodeDecodeError):
detail, transient = "Mergify queue lookup returned no valid JSON", True
except (OSError, http.client.IncompleteRead) as exc:
reason = exc.reason if isinstance(exc, urllib.error.URLError) else exc
detail = f"Mergify queue transport failed: {reason}"
transient = not isinstance(reason, ssl.SSLCertVerificationError)
if not retry or not transient:
raise MergifyError(detail)
if not _wait_to_retry(delay, deadline):
if not _wait_to_retry(max(2.0, wait or 0.0), deadline):
raise MergifyError(f"{detail}; retry delay exceeds the wait budget")
return None
retry = False


def _unmet_conditions(node: object) -> tuple[str, ...]:
if not isinstance(node, dict) or node.get("match") is not False:
Expand Down Expand Up @@ -241,8 +239,7 @@ def construct_mapping(self, node, deep=False):
blob = github.api_get(path)
try:
if (blob["type"] != "file" or blob["encoding"] != "base64"
or not isinstance(blob["sha"], str) or len(blob["sha"]) != 40
or any(char not in "0123456789abcdef" for char in blob["sha"])
or not isinstance(blob["sha"], str) or not re.fullmatch(r"[0-9a-f]{40}", blob["sha"])
or not isinstance(blob["content"], str) or len(blob["content"]) > 90000):
return False
document = yaml.load(base64.b64decode("".join(blob["content"].split()), validate=True),
Expand Down Expand Up @@ -334,13 +331,11 @@ class Departure:

def _departure_payload(body: str, queue: str) -> dict:
_, _, text = body.partition("-*- Mergify Payload -*-\n")
try:
with suppress(json.JSONDecodeError):
payload = json.loads(text.partition("\n-*- Mergify Payload End -*-")[0])
except json.JSONDecodeError:
return {}
if (isinstance(payload, dict) and payload.get("version") == 1
and payload.get("state") == "dequeued" and payload.get("queue_rule_name") == queue):
return payload
if (isinstance(payload, dict) and payload.get("version") == 1
and payload.get("state") == "dequeued" and payload.get("queue_rule_name") == queue):
return payload
return {}


Expand Down
Loading
Loading