Skip to content
6 changes: 5 additions & 1 deletion docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,11 @@ loading the delivery [commands](../src/loopzero/cli.py), which implement the con
head or an eligible review covering an ancestor, blocking findings
(unresolved threads a review publisher opened with a head-bound marker line),
target branch and required CI. The receipt must record a clean passing run
at that head with the current commands and check settings digest. A settings
at that head with the current commands and check settings digest. Ready and
merge validate the PR, head and hold before checking the local receipt.
An invalid receipt stops the command before it fetches remote readiness
evidence. Writes to advance readiness or merging recheck the receipt.
Status continues to collect all readiness diagnostics. A settings
change or an older receipt without the digest requires a fresh check. The
digest covers execution and stage reuse settings without recording raw
environment values. For local sandbox receipts it omits inherited `PATH`,
Expand Down
43 changes: 30 additions & 13 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,8 +179,8 @@ def _require_task_branch(config: Config, branch: str) -> None:
raise CliError(f"branch {branch!r} is the configured base; use a task branch")


def _require_pr(config: Config, branch: str, *, allow_merged: bool = False) -> github.PR:
pr = github.pr_for_branch(config.repo, branch)
def _require_pr(config: Config, branch: str, *, allow_merged: bool = False, list_only: bool = False) -> github.PR:
pr = github.pr_for_branch(config.repo, branch, list_only=list_only)
if pr is None:
raise CliError(f"no pull request for {branch}; run `loopzero pr` first")
if pr.state != "OPEN" and not (allow_merged and pr.state == "MERGED"):
Expand Down Expand Up @@ -304,12 +304,18 @@ def _review_cap_reason(config: Config, pr: github.PR, head: str, reviews: list[d
MERGEABILITY_PENDING = "GitHub is computing mergeability"


def _readiness_precheck(wt: Path, config: Config, pr: github.PR, head: str, diagnostics: bool) -> str | None:
return github.merge_hold(pr.number, pr.labels) or (
None if diagnostics else _check_report_problem(_load_report(wt), config, head)
)


def _readiness(
wt: Path, config: Config, pr: github.PR, head: str, reviews: list[dict] | None = None,
*, workflow_wait: bool = False, announce_receipt: bool = False,
*, workflow_wait: bool = False, announce_receipt: bool = False, diagnostics: bool = False,
) -> github.Readiness:
if hold := github.merge_hold(pr.number, pr.labels):
return github.Readiness(False, (hold,))
if problem := _readiness_precheck(wt, config, pr, head, diagnostics):
return github.Readiness(False, (problem,))
if reviews is None:
reviews = _pr_reviews(config.repo, pr.number)
publishers = config.review_publishers or (github.login(),)
Expand All @@ -333,12 +339,6 @@ def _readiness(
),
publishers=publishers,
)
report = _load_report(wt)
receipt_problem = _check_report_problem(report, config, head)
if receipt_problem:
result = github.Readiness(False, (*result.reasons, receipt_problem))
elif announce_receipt:
_print_receipt(wt, report, "accepted")
if config.merge_strategy == "mergify" and pr.state == "OPEN":
behind = github.behind_reason(pr, head if review else None)
reasons = result.reasons
Expand All @@ -356,6 +356,12 @@ def _readiness(
))
if pr.state == "OPEN" and pr.mergeable == "UNKNOWN":
result = dataclasses.replace(result, ready=False, reasons=(*result.reasons, MERGEABILITY_PENDING))
report = _load_report(wt)
receipt_problem = _check_report_problem(report, config, head)
if receipt_problem:
result = github.Readiness(False, (*result.reasons, receipt_problem))
elif announce_receipt:
_print_receipt(wt, report, "accepted")
return result


Expand Down Expand Up @@ -395,6 +401,11 @@ def _current_check_report(wt: Path, config: Config, head: str) -> CheckReport |
return None if _check_report_problem(report, config, head) else report


def _require_receipt(wt: Path, config: Config, head: str) -> None:
if problem := _check_report_problem(_load_report(wt), config, head):
raise CliError(problem)


def _print_receipt(wt: Path, report: CheckReport, action: str) -> None:
"""Best-effort transcript identity; never authority or environment attestation."""
try:
Expand Down Expand Up @@ -1189,7 +1200,7 @@ def _pr_readiness(
"""PR plus readiness; readiness is None only for an already merged PR (allow_merged)."""
head = worktree.head(wt)
_require_task_branch(config, branch)
pr = _require_pr(config, branch, allow_merged=allow_merged)
pr = _require_pr(config, branch, allow_merged=allow_merged, list_only=True)
_require_pushed(pr, head)
if pr.state == "MERGED":
return pr, None
Expand Down Expand Up @@ -1291,6 +1302,7 @@ def cmd_ready(args: argparse.Namespace) -> int:
kicked = bool(waiting)
started = time.monotonic()
if waiting:
_require_receipt(wt, config, pr.head_sha)
github.mark_ready(config.repo, pr.number)
if args.wait is None:
pending = f"; {MERGEABILITY_PENDING}" if pr.mergeable == "UNKNOWN" else ""
Expand All @@ -1310,6 +1322,7 @@ def cmd_ready(args: argparse.Namespace) -> int:
assert readiness is not None
_prequeue_size_budget(wt, config, pr, readiness)
if readiness.ready and pr.is_draft and not kicked:
_require_receipt(wt, config, pr.head_sha)
github.mark_ready(config.repo, pr.number)
if args.wait is not None:
waited = _wait_with_deadline(wt, config, pr, args.wait, kicked=True, started=started,
Expand Down Expand Up @@ -1500,6 +1513,7 @@ def _wait_for_checks(
return current, None, kicked
readiness = _readiness(wt, config, current, pr.head_sha, workflow_wait=True)
if not kicked and _draft_checks_waiting(config, current, readiness):
_require_receipt(wt, config, current.head_sha)
github.mark_ready(config.repo, pr.number)
print("marked ready; " + "; ".join(readiness.reasons))
return _wait_for_checks(wt, config, pr, timeout, kicked=True, started=started,
Expand Down Expand Up @@ -1702,6 +1716,7 @@ def _merge_with_mergify(
return sha
confirmed = state is not None
if confirmed and not confirmed_marker:
_require_receipt(wt, config, pr.head_sha)
mergify.mark_confirmed(config.repo, pr.number, pr.head_sha, queue)
if not confirmed and confirmed_marker:
closed: list[github.GhError] = []
Expand All @@ -1712,6 +1727,7 @@ def _merge_with_mergify(
_prequeue_size_budget(wt, config, pr, readiness, project=admit_by is None)
if admit_by is not None and time.monotonic() > admit_by:
raise _AdmissionDeadline
_require_receipt(wt, config, pr.head_sha)
mergify.request(config.repo, pr.number, pr.head_sha, queue)
if deadline is not None:
return _wait_for_mergify(config, pr, max(0.0, deadline - time.monotonic()), confirmed)
Expand Down Expand Up @@ -1769,6 +1785,7 @@ def cmd_merge(args: argparse.Namespace) -> int:
if admit_by is not None and time.monotonic() > admit_by:
print(f"timed out before merging PR #{pr.number}")
return 3
_require_receipt(wt, config, pr.head_sha)
sha = github.merge(config.repo, pr.number, config.merge_strategy, pr.head_sha)
if sha is None and args.wait is not None:
sha = _wait_for_merge(config, pr, max(0.0, deadline - time.monotonic()))
Expand Down Expand Up @@ -1862,7 +1879,7 @@ def cmd_status(args: argparse.Namespace) -> int:
print(f"review: {latest.kind} on {latest.head[:12]} ({latest.state.lower() or 'posted'})")
else:
print("review: none on this PR")
readiness = _readiness(wt, config, pr, head, reviews)
readiness = _readiness(wt, config, pr, head, reviews, diagnostics=True)
print(f"ready: {'yes' if readiness.ready else 'no'}")
for reason in readiness.reasons:
print(f" - {reason}")
Expand Down
19 changes: 9 additions & 10 deletions src/loopzero/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
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_ENV = (*GH_BASE_ENV, "GH_TOKEN", "GITHUB_TOKEN", "GH_CONFIG_DIR", "XDG_CONFIG_HOME")
APP_TOKEN_HELPER = Path.home() / ".config/loopzero/app-token"
_app_token_cache = ("", 0.0)
MISSING_REVIEW_REASON = "no review recorded for the current head"
Expand Down Expand Up @@ -666,13 +666,14 @@ def _confirm_branch_pr(repo: str, branch: str, endpoint: str, number: int, state
return pr


def pr_for_branch(repo: str, branch: str, *, open_only: bool = False) -> PR | None:
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."""
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"]))
return _confirm_branch_pr(repo, branch, endpoint, newest["number"], "OPEN")
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"]))
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]
Expand Down Expand Up @@ -763,9 +764,7 @@ def finding_id(head_sha: str, path: str | None, line: int | None, title: str) ->

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} -->"
)
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:
Expand Down
48 changes: 24 additions & 24 deletions src/loopzero/mergify.py
Original file line number Diff line number Diff line change
Expand Up @@ -285,17 +285,22 @@ def _marker(kind: str, head: str, queue: str) -> str:
return f"<!-- {kind} head={head} queue={queue} -->"


def _comments_by(comments: list[dict], login: str):
for comment in comments:
if isinstance(user := comment.get("user"), dict) and user.get("login") == login:
yield comment


def _updated_at(comment: dict) -> str:
return str(comment.get("updated_at") or "")


def _admission_report(comments: list[dict], requested_at: str) -> int | None:
vendor_comments = [
comment for comment in comments
if isinstance(user := comment.get("user"), dict) and user.get("login") == "mergify[bot]"
and str(comment.get("updated_at") or "") >= requested_at
]
latest = max(vendor_comments, key=lambda comment: str(comment.get("updated_at") or ""), default={})
if "### ⏳ Waiting for queue conditions" in str(latest.get("body") or "").splitlines():
latest = max(_comments_by(comments, "mergify[bot]"), key=_updated_at, default={})
if (_updated_at(latest) >= requested_at
and "### ⏳ Waiting for queue conditions" in str(latest.get("body") or "").splitlines()):
report_id = latest.get("id")
if type(report_id) is int and report_id > 0:
return report_id
return report_id if type(report_id) is int and report_id > 0 else None
return None


Expand Down Expand Up @@ -335,18 +340,15 @@ def departure_report(repo: str, number: int, head: str, queue: str) -> Departure
(item for item in comments if _queue_command(str(item.get("body") or ""), queue)),
key=lambda item: item["id"], default={},
)
latest = max(
(item for item in comments if isinstance(user := item.get("user"), dict)
and user.get("login") == "mergify[bot]"),
key=lambda item: (str(item.get("updated_at") or ""), item["id"]), default={},
)
latest = max(_comments_by(comments, "mergify[bot]"), key=lambda item: (_updated_at(item), item["id"]), default={})
body = str(latest.get("body") or "")
payload = _departure_payload(body, queue)
if not command or not payload:
return None

url = f"https://github.com/{repo}/pull/{number}#issuecomment-"
entered = next((line for line in body.splitlines() if line.startswith("- ✅ **Entered the queue** ")), "")
lines = body.splitlines()
entered = next((line for line in lines if line.startswith("- ✅ **Entered the queue** ")), "")
source = re.search(r"^- 🚫 \*\*Left the queue\*\* [^\n]+ · `([0-9a-f]{7,40})`$", body, re.M)
if f"]({url}{command['id']})" not in entered or not source or not head.startswith(source[1]):
return None
Expand All @@ -361,7 +363,7 @@ def departure_report(repo: str, number: int, head: str, queue: str) -> Departure
attribution = next((kind for prefix, kind in (
("**The failure is in this pull request.** It failed tested alone on top of ", "isolated"),
("**Not proven to be this pull request's failure.** It failed on top of the pull requests ahead of it, and was not tested alone.", "stacked"),
) if any(line.startswith(prefix) for line in body.splitlines())), "")
) if any(line.startswith(prefix) for line in lines)), "")
if isinstance(reason, dict) and reason.get("code") == "CONFLICT_WITH_BASE_BRANCH":
attribution = "base_conflict"
return Departure(f"{url}{latest['id']}", names, attribution)
Expand All @@ -371,14 +373,12 @@ def request_status(repo: str, number: int, head: str, queue: str) -> tuple[bool,
login, requested, confirmed = github.login(token=""), False, False
requested_at = ""
comments = github._paged(f"repos/{repo}/issues/{number}/comments")
for item in comments:
user = item.get("user")
if isinstance(user, dict) and user.get("login") == login:
lines = str(item.get("body") or "").splitlines()
requeue = _queue_command(str(item.get("body") or ""), queue)
if _marker(REQUEST, head, queue) in lines or (requeue and confirmed):
requested, requested_at = True, str(item.get("created_at") or "")
confirmed = _marker(CONFIRMED, head, queue) in lines or (confirmed and not requeue)
for item in _comments_by(comments, login):
body = str(item.get("body") or "")
lines, requeue = body.splitlines(), _queue_command(body, queue)
if _marker(REQUEST, head, queue) in lines or (requeue and confirmed):
requested, requested_at = True, str(item.get("created_at") or "")
confirmed = _marker(CONFIRMED, head, queue) in lines or (confirmed and not requeue)
report_id = _admission_report(comments, requested_at)
report = f"https://github.com/{repo}/pull/{number}#issuecomment-{report_id}" if report_id else None
return requested, confirmed, report
Expand Down
Loading
Loading