From bfe43d35e72f7567295d6f705665b9c1e476d71f Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:12:09 +0100 Subject: [PATCH] Preserve trusted policy reuse in the source dedupe Architecture-Review: unchanged; the integration preserves immutable trusted policy reuse and shares only the Git invocation. Co-Authored-By: Codex --- src/loopzero/cli.py | 232 ++++++++++++------------------- src/loopzero/config.py | 91 +++++------- src/loopzero/eligibility.py | 24 ++-- src/loopzero/github.py | 269 ++++++++++++++---------------------- src/loopzero/mergify.py | 77 ++++++----- 5 files changed, 277 insertions(+), 416 deletions(-) diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index a0890dd2..3bbf8a81 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -36,7 +36,6 @@ RUNNER_FAILURES = (runners.RunnerMissing, runners.RunnerAuthFailed, runners.RunnerBadOutput) HANDLED = (LoopZeroError, worktree.WorktreeError, github.GhError, OSError, ValueError) UNEXPECTED = (KeyError, TypeError) -PAGE = 100 # --wait: poll interval, default timeout, and how long a required check may stay # missing before GitHub is assumed to have dropped the event for this head. # Each poll costs several GitHub API calls from a quota shared by every session. @@ -74,7 +73,7 @@ def review_marker(head: str, kind: str, source: str = "model") -> str: def _git(cwd: Path, *args: str, timeout: float = GIT_TIMEOUT) -> str: - done = _proc.run(["git", *args], cwd=cwd, env_allowlist=worktree.GIT_ENV, timeout=timeout) + done = config_mod.run_git(cwd, *args, timeout=timeout) if done.exit_code != 0: raise CliError(f"git {' '.join(args)} failed: {_proc.tail(done.stderr, 1)}") return done.stdout.strip() @@ -133,10 +132,7 @@ def _context(args: argparse.Namespace, *, pin_checks: bool = False) -> tuple[Pat def _is_ancestor(wt: Path, sha: str, head: str) -> bool: - done = _proc.run( - ["git", "merge-base", "--is-ancestor", sha, head], - cwd=wt, env_allowlist=worktree.GIT_ENV, timeout=GIT_TIMEOUT, - ) + done = config_mod.run_git(wt, "merge-base", "--is-ancestor", sha, head) if done.exit_code not in (0, 1): detail = _proc.tail(done.stderr or done.stdout, 1) raise CliError(f"git merge-base --is-ancestor failed (exit {done.exit_code}): " @@ -146,10 +142,7 @@ def _is_ancestor(wt: Path, sha: str, head: str) -> bool: def _primary_base(wt: Path, config: Config) -> str: base = config.trusted_base_revision or config_mod.base_revision(wt, config.base_branch) - done = _proc.run( - ["git", "merge-base", base, "HEAD"], - cwd=wt, env_allowlist=worktree.GIT_ENV, timeout=GIT_TIMEOUT, - ) + done = config_mod.run_git(wt, "merge-base", base, "HEAD") if done.exit_code == 0: return done.stdout.strip() if done.exit_code != 1: @@ -167,9 +160,7 @@ def _require_clean(wt: Path) -> None: def _require_task_branch(config: Config, branch: str) -> None: if branch == config.base_branch: - raise CliError( - f"branch {branch!r} is the configured base; use a task branch" - ) + 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: @@ -191,17 +182,7 @@ def _require_pushed(pr: github.PR, head: str) -> None: # --------------------------------------------------------------------------- review markers -def _rest_rows(endpoint: str, what: str) -> list[dict]: - """Every row of a REST list, oldest first, following pages until a short one.""" - rows: list[dict] = [] - for page in range(1, 101): - batch = github.api_get(f"{endpoint}?per_page={PAGE}&page={page}") - if not isinstance(batch, list) or not all(isinstance(row, dict) for row in batch): - raise CliError(f"invalid GitHub {what} response") - rows += batch - if len(batch) < PAGE: - return rows - raise CliError(f"GitHub {what} pagination limit exceeded") +_rest_rows = partial(github.rest_rows, error=CliError) def _pr_reviews(repo: str, number: int) -> list[dict]: @@ -290,10 +271,7 @@ def _readiness( report = _load_report(wt) receipt_problem = _check_report_problem(report, wt, config, head) if receipt_problem: - result = github.Readiness( - ready=False, - reasons=(*result.reasons, 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": @@ -355,34 +333,41 @@ def _print_receipt(wt: Path, report: CheckReport, action: str) -> None: @contextmanager -def _lock_task_state(wt: Path) -> Iterator[None]: - directory = wt / ".loopzero" - directory.mkdir(parents=True, exist_ok=True) +def _directory_lock(directory: Path | str, flags: int, *, busy: str = "") -> Iterator[None]: fd = os.open(directory, os.O_RDONLY | os.O_DIRECTORY) try: - fcntl.flock(fd, fcntl.LOCK_EX) + try: + fcntl.flock(fd, flags) + except BlockingIOError as exc: + if not busy: + raise + raise CliError(busy) from exc yield finally: os.close(fd) +@contextmanager +def _lock_task_state(wt: Path) -> Iterator[None]: + directory = wt / ".loopzero" + directory.mkdir(parents=True, exist_ok=True) + with _directory_lock(directory, fcntl.LOCK_EX): + yield + + def _save_report(wt: Path, report: CheckReport) -> str | None: """Publish the receipt or return the current HEAD if the result is stale.""" - path = wt / CHECKS_FILE - payload = { - "head": report.head, - "dirty": report.dirty, - "results": [{k: v for k, v in dataclasses.asdict(result).items() - if k not in {"input_key", "reused_from"} or v is not None} - for result in report.results], - } + results = [{k: v for k, v in dataclasses.asdict(result).items() + if k not in {"input_key", "reused_from"} or v is not None} + for result in report.results] + payload = {"head": report.head, "dirty": report.dirty, "results": results} if report.settings_sha256 is not None: payload["settings_sha256"] = report.settings_sha256 with _lock_task_state(wt): current_head = worktree.head(wt) if report.head != current_head: return current_head - _write_json_atomically(path, payload) + _write_json_atomically(wt / CHECKS_FILE, payload) return None @@ -506,12 +491,6 @@ def replace(match: re.Match[str]) -> str: return prefix + content.lstrip("\n") -def _update_pr_checks(wt: Path, head: str, config: Config, pr: github.PR) -> None: - 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) - - _REQUIRED_TASK_LINES = ("Context", "Problem", "Goal") @@ -546,24 +525,17 @@ def _append_review(body: str, result: ReviewResult) -> str: def _refresh_pr_checks(wt: Path, config: Config) -> None: - try: - with _lock_task_state(wt): - _refresh_existing_pr_checks(wt, config) - except OSError as exc: - print(f"note: could not refresh PR checks: {_one_line(exc)}", file=sys.stderr) - - -def _refresh_existing_pr_checks(wt: Path, config: Config) -> None: """Best-effort refresh only when local HEAD is the existing PR head.""" - argv = ["git", "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"] try: - upstream = _proc.run(argv, cwd=wt, env_allowlist=worktree.GIT_ENV, timeout=GIT_TIMEOUT) - 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 not None and pr.head_sha == head: - _update_pr_checks(wt, head, config, pr) + with _lock_task_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) except (github.GhError, _proc.ProcTimeout, OSError, ValueError, CliError) as exc: print(f"note: could not refresh PR checks: {_one_line(exc)}", file=sys.stderr) @@ -585,8 +557,7 @@ def _pr_title(wt: Path, branch: str) -> str: def cmd_start(args: argparse.Namespace) -> int: root = _toplevel() - argv = ["git", "symbolic-ref", "--quiet", "--short", "HEAD"] - current = _proc.run(argv, cwd=root, env_allowlist=worktree.GIT_ENV, timeout=GIT_TIMEOUT) + current = config_mod.run_git(root, "symbolic-ref", "--quiet", "--short", "HEAD") if current.stdout.strip().startswith("lz/") or ( current.exit_code == 1 and worktree.is_linked_checkout(root) ): @@ -610,41 +581,37 @@ def cmd_check(args: argparse.Namespace) -> int: print(f"sandbox unavailable: {exc}", file=sys.stderr) return 2 for result in report.results: - if result.exit_code != 0: - print(f"--- {result.command} (exit {result.exit_code}) ---", file=sys.stderr) - tail = _proc.tail(result.tail) - print(tail, file=sys.stderr) - if not config.network and (result.command.startswith("uv sync --offline --locked") - or OFFLINE_FAILURE_RE.search(tail)): - env = { - **sandbox.SANDBOX_ENV, - **_proc.build_env(config.env_allowlist), - **dict(config.env), - } - print( - "\nThe sandbox has no network because `[checks] network = false`; " - f"the effective UV_CACHE_DIR inside the sandbox is {env['UV_CACHE_DIR']}. " - "To prepare offline, run UV_CACHE_DIR= uv sync --group dev " - "(use the groups your checks require) on the host, or the same commands, so the cache " - "under `[checks] writable` is warm, or set `[checks] env` UV_CACHE_DIR to " - "that cache.", - file=sys.stderr, - ) + if result.exit_code == 0: + continue + tail = _proc.tail(result.tail) + print(f"--- {result.command} (exit {result.exit_code}) ---", tail, sep="\n", file=sys.stderr) + if config.network or not (result.command.startswith("uv sync --offline --locked") + or OFFLINE_FAILURE_RE.search(tail)): + continue + env = sandbox.SANDBOX_ENV | _proc.build_env(config.env_allowlist) | dict(config.env) + print( + "\nThe sandbox has no network because `[checks] network = false`; " + f"the effective UV_CACHE_DIR inside the sandbox is {env['UV_CACHE_DIR']}. " + "To prepare offline, run UV_CACHE_DIR= uv sync --group dev " + "(use the groups your checks require) on the host, or the same commands, so the cache " + "under `[checks] writable` is warm, or set `[checks] env` UV_CACHE_DIR to that cache.", + file=sys.stderr, + ) current_head = _save_report(wt, report) if current_head is not None: print(f"check result discarded: checked HEAD {report.head}, current HEAD {current_head}", file=sys.stderr) return 1 - if report.ok and report.settings_sha256 is None: + verified = not report.ok or report.settings_sha256 is not None + if not verified: print("check stages passed but the receipt is unverified; rerun loopzero check from the task " "worktree with a stable, readable configured runner before running ready", file=sys.stderr) - _refresh_pr_checks(wt, config) - return 1 - if report.ok and not report.dirty: + elif report.ok and not report.dirty: _print_receipt(wt, report, "produced") _refresh_pr_checks(wt, config) - print("PASS" if report.ok else "FAIL") - return 0 if report.ok else 1 + if verified: + print("PASS" if report.ok else "FAIL") + return 0 if report.ok and verified else 1 def cmd_pr(args: argparse.Namespace) -> int: @@ -667,8 +634,7 @@ def cmd_pr(args: argparse.Namespace) -> int: push = ["push", "-u", "origin"] if pr is not None and pr.state == "OPEN": # Only rewrite history this worktree has seen; an unknown remote head is someone else's. - known = _proc.run(["git", "cat-file", "-e", f"{pr.head_sha}^{{commit}}"], cwd=wt, - env_allowlist=worktree.GIT_ENV, timeout=GIT_TIMEOUT) + known = config_mod.run_git(wt, "cat-file", "-e", f"{pr.head_sha}^{{commit}}") if known.exit_code != 0: raise CliError( f"PR head {pr.head_sha[:12]} is not in this worktree; fetch and integrate it first" @@ -734,15 +700,9 @@ def _lock_review(run_review: Callable[[argparse.Namespace, Path, Config], int]): def locked(args: argparse.Namespace) -> int: wt, config = _context(args, pin_checks=True) git_dir = _git(wt, "rev-parse", "--absolute-git-dir") - fd = os.open(git_dir, os.O_RDONLY | os.O_DIRECTORY) - try: - try: - fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) - except BlockingIOError as exc: - raise CliError("review already running in this worktree") from exc + with _directory_lock(git_dir, fcntl.LOCK_EX | fcntl.LOCK_NB, + busy="review already running in this worktree"): return run_review(args, wt, config) - finally: - os.close(fd) return locked @@ -766,16 +726,12 @@ def cmd_review(args: argparse.Namespace, wt: Path, config: Config) -> int: login.casefold() for login in config.review_publishers }: raise CliError("current GitHub login is not a configured review publisher") - reviews = [] if args.repost else _pr_reviews(config.repo, pr.number) - if args.repost: - saved = [kind for kind in ("primary", "delta") if _review_file(wt, head, kind).exists()] - if len(saved) > 1: - raise CliError("multiple saved reviews for HEAD; publication is ambiguous") - if not saved: - reviews = _pr_reviews(config.repo, pr.number) - kind = saved[0] if saved else _decide_kind( - _pr_markers(reviews, head, config.review_publishers, repo=config.repo, number=pr.number), head - )[0] + saved = [kind for kind in ("primary", "delta") if _review_file(wt, head, kind).exists()] if args.repost else [] + if len(saved) > 1: + raise CliError("multiple saved reviews for HEAD; publication is ambiguous") + reviews = [] if saved else _pr_reviews(config.repo, pr.number) + if saved: + kind = saved[0] else: kind, reviewed = _decide_kind( _pr_markers(reviews, head, config.review_publishers, repo=config.repo, number=pr.number), head @@ -1049,7 +1005,6 @@ def select(family: str) -> Callable[..., ReviewResult]: try: try: result = selected[family](diff=diff) - break except runners.RunnerPromptTooLong: chunks = runners.split_diff(diff, config.review_chunk_bytes) print( @@ -1059,7 +1014,7 @@ def select(family: str) -> Callable[..., ReviewResult]: chunk_results = [selected[family](diff=chunk, chunk=(index, len(chunks))) for index, chunk in enumerate(chunks, 1)] result = runners.merge_reviews(chunk_results) - break + break except RUNNER_FAILURES as exc: reason, detail, fallback_reason = _review_failure(family, exc) failures.append(detail) @@ -1225,16 +1180,17 @@ def cmd_ready(args: argparse.Namespace) -> int: return 0 +def _required_check_reasons(names: tuple[str, ...], *states: str) -> dict[str, str]: + return {f"required check '{name}' {state}": name for name in names for state in states} + + def _draft_checks_waiting( config: Config, pr: github.PR, readiness: github.Readiness ) -> tuple[str, ...]: reasons = set(readiness.reasons) - {MERGEABILITY_PENDING} if not pr.is_draft or not reasons: return () - expected: dict[str, str] = {} - for name in config.required_ci: - expected[f"required check '{name}' missing on {pr.head_sha[:12]}"] = name - expected[f"required check '{name}' is skipped"] = name + expected = _required_check_reasons(config.required_ci, f"missing on {pr.head_sha[:12]}", "is skipped") if not reasons <= expected.keys(): return () blocked = {expected[reason] for reason in reasons} @@ -1249,9 +1205,8 @@ def _pending_checks( An explicit ready wait can observe a skipped result left over from draft CI. """ states = [f"missing on {pr.head_sha[:12]}", "is pending", *(["is skipped"] if allow_skipped else [])] - waitable = {f"required check '{n}' {state}" for n in config.required_ci for state in states} - waitable.update(readiness.waitable_failures) - waitable.add(MERGEABILITY_PENDING) + waitable = {*_required_check_reasons(config.required_ci, *states), + *readiness.waitable_failures, MERGEABILITY_PENDING} reasons = readiness.reasons return reasons if reasons and all(r in waitable for r in reasons) else () @@ -1301,10 +1256,11 @@ def _wait_with_deadline( allow_merged: bool = False, allow_skipped: bool = False, initial: github.Readiness | None = None, ) -> tuple[github.PR, github.Readiness | None, bool] | None: started = time.monotonic() if started is None else started + wait = partial(_wait_for_checks, wt, config, pr, timeout, kicked=kicked, started=started, + shown=shown, args=args, allow_merged=allow_merged, + allow_skipped=allow_skipped, initial=initial) if timeout == 0: - return _wait_for_checks(wt, config, pr, timeout, kicked=kicked, started=started, - shown=shown, args=args, allow_merged=allow_merged, - allow_skipped=allow_skipped, initial=initial) + return wait() deadline = started + timeout if time.monotonic() >= deadline: _print_check_wait_timeout(pr) @@ -1312,9 +1268,7 @@ def _wait_with_deadline( reported_timeout = False try: with github.bounded_reads(deadline, token=None, retry=True): - waited = _wait_for_checks(wt, config, pr, timeout, kicked=kicked, started=started, - shown=shown, args=args, bounded=True, allow_merged=allow_merged, - allow_skipped=allow_skipped, initial=initial) + waited = wait(bounded=True) reported_timeout = waited is None except github.ReadDeadline: if not reported_timeout: @@ -1324,10 +1278,8 @@ def _wait_with_deadline( def _print_check_wait_timeout(pr: github.PR) -> None: - if pr.mergeable == "UNKNOWN": - print(f"timed out waiting for GitHub to compute mergeability on {pr.head_sha[:12]}") - else: - print(f"timed out waiting for required checks on {pr.head_sha[:12]}") + what = "GitHub to compute mergeability" if pr.mergeable == "UNKNOWN" else "required checks" + print(f"timed out waiting for {what} on {pr.head_sha[:12]}") def _verify_wait_snapshot( @@ -1550,6 +1502,9 @@ def _wait_for_mergify( return None +_FOLLOW_QUEUE = "next: loopzero merge --wait follows the queue, verifies and cleans up" + + class _AdmissionDeadline(Exception): """The --wait budget expired before a new merge or queue request.""" @@ -1575,7 +1530,6 @@ def _merge_with_mergify( confirmed = state is not None if confirmed and not confirmed_marker: mergify.mark_confirmed(config.repo, pr.number, pr.head_sha, queue) - confirmed_marker = True if not confirmed and confirmed_marker: closed: list[github.GhError] = [] if sha := _mergify_departure(config, pr, queue, closed, confirmed=True): @@ -1585,14 +1539,10 @@ def _merge_with_mergify( if admit_by is not None and time.monotonic() > admit_by: raise _AdmissionDeadline mergify.request(config.repo, pr.number, pr.head_sha, queue) - requested = True if deadline is not None: return _wait_for_mergify(config, pr, max(0.0, deadline - time.monotonic()), confirmed) state_name = "confirmed in" if confirmed else "requested from" - print( - f"PR #{pr.number} {state_name} Mergify queue {queue}; " - "next: loopzero merge --wait follows the queue, verifies and cleans up" - ) + print(f"PR #{pr.number} {state_name} Mergify queue {queue}; {_FOLLOW_QUEUE}") return None @@ -1624,10 +1574,7 @@ def cmd_merge(args: argparse.Namespace) -> int: return 3 pr, readiness, _ = waited if readiness is None: - sha = github.merged_sha( - config.repo, pr.number, - expected_head=pr.head_sha, - ) + sha = github.merged_sha(config.repo, pr.number, expected_head=pr.head_sha) if sha is None: raise CliError(f"PR #{pr.number} reports MERGED but has no merge commit yet; rerun") print(f"PR #{pr.number} was already merged as {sha[:12]}; cleaning up") @@ -1653,10 +1600,7 @@ def cmd_merge(args: argparse.Namespace) -> int: print(f"timed out waiting for the merge queue to land PR #{pr.number}") return 3 if sha is None: - print( - f"PR #{pr.number} is queued for merge into {config.base_branch}; " - "next: loopzero merge --wait follows the queue, verifies and cleans up" - ) + print(f"PR #{pr.number} is queued for merge into {config.base_branch}; {_FOLLOW_QUEUE}") return 0 _cleanup_remote_refs(wt, config, branch, pr.head_sha) _cleanup(wt, pr) diff --git a/src/loopzero/config.py b/src/loopzero/config.py index 6563d33b..a5b2bd50 100644 --- a/src/loopzero/config.py +++ b/src/loopzero/config.py @@ -24,26 +24,14 @@ _SECTIONS: dict[str, dict[str, type]] = { "repo": {"name": str, "base": str}, "checks": { - "commands": list, - "runner": list, - "inputs": dict, - "required_ci": list, - "network": bool, - "env_allowlist": list, - "ro_paths": list, - "writable": list, - "scratch": list, - "env": dict, - "limits": dict, + "commands": list, "runner": list, "inputs": dict, "required_ci": list, "network": bool, + "env_allowlist": list, "ro_paths": list, "writable": list, "scratch": list, + "env": dict, "limits": dict, }, "delivery": { - "merge": str, - "mergify_queue": str, - "reviewers": list, - "review_publishers": list, - "reviewer_ro_paths": list, - "review_chunk_bytes": int, - "review": dict, + "merge": str, "mergify_queue": str, + "reviewers": list, "review_publishers": list, "reviewer_ro_paths": list, + "review_chunk_bytes": int, "review": dict, }, } @@ -75,12 +63,13 @@ def load(path: Path | str) -> Config: raise ConfigError(f"{path}: {exc}") from None +def run_git(worktree: Path, *args: str, timeout: float = 60) -> _proc.Completed: + return _proc.run(["git", *args], cwd=worktree, env_allowlist=worktree_mod.GIT_ENV, timeout=timeout) + + def base_revision(worktree: Path, base_branch: str) -> str: """Resolve the remote base, or the task's recorded base when the ref is absent.""" - done = _proc.run( - ["git", "rev-parse", "--verify", "--quiet", f"refs/remotes/origin/{base_branch}"], - cwd=worktree, env_allowlist=worktree_mod.GIT_ENV, timeout=60, - ) + done = run_git(worktree, "rev-parse", "--verify", "--quiet", f"refs/remotes/origin/{base_branch}") if done.exit_code == 0: return done.stdout.strip() if done.exit_code == 1: @@ -112,20 +101,15 @@ def _remote_workflow(worktree: Path, branch: str, previous: Config | None) -> tu source = f"origin/{branch}:workflow.toml" hint = "Fetch the trusted base workflow, or supply --config for bootstrap or an override." directory_args = ["--path-format=absolute", "--git-common-dir"] if previous is not None else [] - resolved = _proc.run( - ["git", "rev-parse", *directory_args, "--verify", f"refs/remotes/origin/{branch}^{{commit}}"], - cwd=worktree, env_allowlist=worktree_mod.GIT_ENV, timeout=60, - ) + resolved = run_git(worktree, "rev-parse", *directory_args, "--verify", + f"refs/remotes/origin/{branch}^{{commit}}") if resolved.exit_code != 0: raise ConfigError(f"{source} has no remote-tracking base commit. {hint}") common_dir, _, revision = resolved.stdout.rstrip("\n").rpartition("\n") if (previous is not None and previous.base_branch == branch and previous.trusted_base_revision == revision and common_dir and not _has_replacement_refs(Path(common_dir))): return previous, revision - shown = _proc.run( - ["git", "show", f"{revision}:workflow.toml"], - cwd=worktree, env_allowlist=worktree_mod.GIT_ENV, timeout=60, - ) + shown = run_git(worktree, "show", f"{revision}:workflow.toml") if shown.exit_code != 0: raise ConfigError(f"cannot read {source}. {hint}") try: @@ -141,10 +125,7 @@ def _remote_workflow(worktree: Path, branch: str, previous: Config | None) -> tu def load_trusted(worktree: Path, *, previous: Config | None = None) -> Config: """Select delivery policy using Git's origin default and its trusted workflow.""" prefix = "refs/remotes/origin/" - default = _proc.run( - ["git", "symbolic-ref", "--quiet", f"{prefix}HEAD"], - cwd=worktree, env_allowlist=worktree_mod.GIT_ENV, timeout=60, - ) + default = run_git(worktree, "symbolic-ref", "--quiet", f"{prefix}HEAD") ref = default.stdout.strip() if default.exit_code != 0 or not ref.startswith(prefix): raise ConfigError( @@ -203,20 +184,20 @@ def _build(data: dict[str, Any]) -> Config: raise ConfigError(f"unknown review family delivery.review.{family}") if not isinstance(table, dict): raise ConfigError(f"[delivery.review.{family}] must be a table") - _reject_unknown( - f"[delivery.review.{family}]", table, ("model", "effort", "allowed_efforts") - ) + label = f"delivery.review.{family}" + _reject_unknown(f"[{label}]", table, ("model", "effort", "allowed_efforts")) for key in ("model", "effort"): if key in table and (not isinstance(table[key], str) or not table[key]): - raise ConfigError(f"delivery.review.{family}.{key} must be a non-empty str") - if "allowed_efforts" in table and not isinstance(table["allowed_efforts"], list): - raise ConfigError(f"delivery.review.{family}.allowed_efforts must be a list") - allowed = _strings( - f"delivery.review.{family}.allowed_efforts", table.get("allowed_efforts", []) - ) - review[family] = ReviewConfig(table.get("model"), table.get("effort"), allowed) - - commands = _commands(checks.get("commands", [])) + raise ConfigError(f"{label}.{key} must be a non-empty str") + allowed = table.get("allowed_efforts", []) + if not isinstance(allowed, list): + raise ConfigError(f"{label}.allowed_efforts must be a list") + review[family] = ReviewConfig(table.get("model"), table.get("effort"), + _strings(f"{label}.allowed_efforts", allowed)) + + commands = _strings("checks.commands", checks.get("commands", [])) + if any(not command.strip() for command in commands): + raise ConfigError("checks.commands entries must each be a nonblank command") kwargs: dict[str, Any] = {} if "runner" in checks: runner = _strings("checks.runner", checks["runner"]) @@ -233,12 +214,11 @@ def _build(data: dict[str, Any]) -> Config: raise ConfigError(f"{label} must exactly match a checks.commands entry") inputs[key] = _strings(label, value) kwargs["inputs"] = inputs - if "env_allowlist" in checks: - kwargs["env_allowlist"] = _strings("checks.env_allowlist", checks["env_allowlist"]) - if "ro_paths" in checks: - kwargs["sandbox_ro"] = _host_paths("checks.ro_paths", checks["ro_paths"]) - if "writable" in checks: - kwargs["writable"] = _host_paths("checks.writable", checks["writable"]) + for key, field, read in (("env_allowlist", "env_allowlist", _strings), + ("ro_paths", "sandbox_ro", _host_paths), + ("writable", "writable", _host_paths)): + if key in checks: + kwargs[field] = read(f"checks.{key}", checks[key]) if "env" in checks: kwargs["env"] = _env_table(checks["env"]) if "scratch" in checks: @@ -295,13 +275,6 @@ def _reject_unknown(where: str, table: dict[str, Any], allowed: Any) -> None: raise ConfigError(f"unknown key(s) in {where}: {', '.join(unknown)}") -def _commands(value: list[Any]) -> tuple[str, ...]: - commands = _strings("checks.commands", value) - if any(not command.strip() for command in commands): - raise ConfigError("checks.commands entries must each be a nonblank command") - return commands - - def _strings(label: str, value: list[Any]) -> tuple[str, ...]: if not isinstance(value, list) or not all(isinstance(item, str) and item for item in value): raise ConfigError(f"{label} must be a list of non-empty strings") diff --git a/src/loopzero/eligibility.py b/src/loopzero/eligibility.py index 41de7f3c..a2611a0a 100644 --- a/src/loopzero/eligibility.py +++ b/src/loopzero/eligibility.py @@ -70,13 +70,17 @@ def review_projection(review: dict, head: str, repo: str, number: int): return True, None +def _trusted_marker(review: dict, trusted: set[str], head: str | None = None) -> bool: + return ((review.get("user") or {}).get("login", "").casefold() in trusted + and (head is None or review.get("commit_id") == head) + and "loopzero:review" in (review.get("body") or "")) + + 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) + latest = next((r for r in reversed(reviews) if _trusted_marker(r, trusted, head)), None) if latest is None or latest.get("state") not in {"APPROVED", "COMMENTED", "CHANGES_REQUESTED"}: return None body = latest.get("body") or "" @@ -129,8 +133,7 @@ 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 "")] + marked = [r for r in reviews if _trusted_marker(r, trusted)] 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] @@ -171,15 +174,8 @@ def evaluate(repo: str, number: int, head: str, base: str, 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 - while True: - batch = github.api_get(f"repos/{repo}/pulls/{number}/reviews?per_page=100&page={page}") - if not isinstance(batch, list): - raise LoopZeroError("invalid GitHub reviews response") - reviews.extend(batch) - if len(batch) < 100: - break - page += 1 + reviews = github.rest_rows(f"repos/{repo}/pulls/{number}/reviews", "reviews", + limit=None, validate_rows=False) 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) diff --git a/src/loopzero/github.py b/src/loopzero/github.py index 171efcb9..65a816c1 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -14,6 +14,7 @@ from contextvars import ContextVar from dataclasses import dataclass from datetime import UTC, datetime +from itertools import count from pathlib import Path from typing import Literal from urllib.parse import quote @@ -21,7 +22,7 @@ from loopzero import runners from loopzero._proc import ProcTimeout, ToolMissing, run from loopzero.runners import review_settings -from loopzero.types import BLOCKING, Finding, ReviewResult +from loopzero.types import BLOCKING, Finding, LoopZeroError, ReviewResult GH_ENV = ("PATH", "HOME", "LANG", "LC_ALL", "TERM", "GH_TOKEN", "GITHUB_TOKEN", "GH_HOST") APP_TOKEN_HELPER = Path.home() / ".config/loopzero/app-token" @@ -160,24 +161,17 @@ def api_error_diagnostics(): def _included_response(output: str) -> tuple[str | None, dict[str, str], str]: """Split one `gh api --include` response into status, headers and body.""" - head, separator, body = output.partition("\r\n\r\n") - line_separator = "\r\n" - if not separator: - head, separator, body = output.partition("\n\n") - line_separator = "\n" - if not separator: - return None, {}, output - lines = head.split(line_separator) - match = _HTTP_STATUS_RE.match(lines[0]) - if match is None: - return None, {}, output - status = match.group(1) - headers: dict[str, str] = {} - for line in lines[1:]: - name, separator, value = line.partition(":") - if separator: - headers[name.strip().casefold()] = value.strip() - return status, headers, body + for eol in ("\r\n", "\n"): + head, separator, body = output.partition(eol * 2) + if not separator: + continue + status, *lines = head.split(eol) + if not (match := _HTTP_STATUS_RE.match(status)): + break + headers = {name.strip().casefold(): value.strip() + for name, colon, value in (line.partition(":") for line in lines) if colon} + return match.group(1), headers, body + return None, {}, output def _api_method(args: tuple[str, ...]) -> str: @@ -229,23 +223,16 @@ def _api_error_detail(args: tuple[str, ...], stdout: str, stderr: str, status = match.group(1) if match else "unavailable" request_id = headers.get("x-github-request-id") or "unavailable" message = "" - try: + with suppress(ValueError, TypeError): 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): - message = "; ".join( - error["message"] for error in errors - if isinstance(error, dict) and isinstance(error.get("message"), str) - ) - if not message: - message = body.strip() or stderr.strip().removeprefix("gh:").strip() + if isinstance(payload, dict): + value = payload.get("message") + if isinstance(value, str): + message = value + elif isinstance(errors := payload.get("errors"), list): + message = "; ".join(item["message"] for item in errors + if isinstance(item, dict) and isinstance(item.get("message"), str)) + message = message or body.strip() or stderr.strip().removeprefix("gh:").strip() message = " ".join(_redact_tokens(message if message_tail is None else message_tail, token).split()) message = message[:400] or "no response message" return _redact_tokens( @@ -321,18 +308,18 @@ def _pr_list_error_guidance(args: tuple[str, ...], stderr: str, using_app: bool) def _gh(*args: str, cwd: Path | None = None, timeout: float = 120, token: str | None = None, retry_idempotent: bool = False) -> str: - diagnostic_api = _api_error_diagnostics.get() and args[:1] == ("api",) - rest_api = args[:1] == ("api",) and args[:2] != ("api", "graphql") - patch_error = args[:1] == ("api",) and _api_method(args) == "PATCH" - request_args = args - if (rest_api or diagnostic_api) and not {"--include", "-i"} & set(args): - request_args = (*args, "--include") - argv = ("gh", *request_args) + api = args[:1] == ("api",) + diagnostic_api = api and _api_error_diagnostics.get() + rest_api = api and args[:2] != ("api", "graphql") + explain = diagnostic_api or (api and _api_method(args) == "PATCH") + include = (rest_api or diagnostic_api) and not {"--include", "-i"} & set(args) + argv = ("gh", *args, *(("--include",) if include else ())) 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 = (None,) if scope and not scope[2] else (*RETRY_DELAYS, None) + rate_guidance = None for delay in delays: selected = _select_token(token, scope, read_only) # a retry backoff can outlive the app token try: @@ -357,21 +344,19 @@ def _gh(*args: str, cwd: Path | None = None, timeout: float = 120, tail = "\n".join(part for part in (done.stderr, body if rest_api else done.stdout) if part) if done.exit_code and ((rest_api and status == "429") or re.search(r"rate limit|HTTP 429", tail, re.IGNORECASE)): - guidance = (_redact_tokens(_rest_rate_limit(headers), selected) if rest_api - else _graphql_reset(args, tail, cwd, selected) + RATE_LIMIT_GUIDANCE) - if diagnostic_api or patch_error: - detail = _api_error_detail(args, done.stdout if diagnostic_api else "", done.stderr, selected, - message_tail=None if diagnostic_api else tail) - raise GhError(("GitHub API request",), detail, token=selected, guidance=guidance) - raise GhError(argv, tail, token=selected, guidance=guidance) + rate_guidance = (_redact_tokens(_rest_rate_limit(headers), selected) if rest_api + else _graphql_reset(args, tail, cwd, selected) + RATE_LIMIT_GUIDANCE) + break if done.exit_code == 0 or delay is None or not retryable or not _transient_error(tail, retry_idempotent): break _retry_sleep(_read_timeout(delay) if scope else delay) if done.exit_code != 0: - error_command = ("GitHub API request",) if diagnostic_api or patch_error else argv + error_command = ("GitHub API request",) if explain else argv error_tail = (_api_error_detail(args, done.stdout if diagnostic_api else "", done.stderr, selected, message_tail=None if diagnostic_api else tail) - if diagnostic_api or patch_error else tail) + if explain else tail) + if rate_guidance is not None: + raise GhError(error_command, error_tail, token=selected, guidance=rate_guidance) if "gh auth login" in tail or "not logged in" in tail.lower(): raise GhAuth(error_command, error_tail.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)) @@ -461,6 +446,19 @@ def _gh_json(*args: str, token: str | None = None) -> object: token=token or "") from None +def rest_rows(endpoint: str, what: str, *, error: type[LoopZeroError] = LoopZeroError, + limit: int | None = 100, validate_rows: bool = True) -> list[dict]: + rows: list[dict] = [] + for page in range(1, limit + 1) if limit is not None else count(1): + batch = api_get(f"{endpoint}?per_page={PAGE}&page={page}") + if not isinstance(batch, list) or (validate_rows and not all(isinstance(row, dict) for row in batch)): + raise error(f"invalid GitHub {what} response") + rows.extend(batch) + if len(batch) < PAGE: + return rows + raise error(f"GitHub {what} pagination limit exceeded") + + def _iter_paged(endpoint: str, key: str = "check_runs") -> Iterator[dict]: """Yield validated rows until the last page.""" page = 1 @@ -584,22 +582,27 @@ def _matches_branch(source: dict, repo: str, branch: str) -> bool: return source.get("ref") == branch and isinstance(name, str) and name.casefold() == repo.casefold() -def _branch_head(repo: str, branch: str) -> str | None: - endpoint = f"repos/{repo}/branches/{quote(branch, safe='')}" +def _ref_sha(endpoint: str, field: str) -> str | None: try: ref = api_get(endpoint) except GhError as exc: if re.search(r"\bHTTP 404\b", exc.tail): return None raise - commit = ref.get("commit") if isinstance(ref, dict) else None - sha = commit.get("sha") if isinstance(commit, dict) else None - if not isinstance(sha, str) or not re.fullmatch(r"[0-9a-f]{40}", sha): - raise GhError(("gh", "api", endpoint), "invalid remote branch SHA") - + obj = ref.get(field) if isinstance(ref, dict) else None + sha = obj.get("sha") if isinstance(obj, dict) else None + if field == "commit": + if not isinstance(sha, str) or not re.fullmatch(r"[0-9a-f]{40}", sha): + raise GhError(("gh", "api", endpoint), "invalid remote branch SHA") + elif not isinstance(sha, str) or not sha: + raise GhError(("gh", "api", endpoint), "missing remote ref SHA") return sha +def _branch_head(repo: str, branch: str) -> str | None: + return _ref_sha(f"repos/{repo}/branches/{quote(branch, safe='')}", "commit") + + def _commit_branch_prs(repo: str, branch: str) -> tuple[str, list[dict]]: sha = _branch_head(repo, branch) if sha is None: @@ -627,9 +630,10 @@ 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) - state_matches = pr.state == state or (state == "CLOSED" and pr.state == "MERGED") - if not state_matches or not _matches_branch(detail["head"], repo, branch): - raise GhError(("gh", "api", endpoint), "PR changed during branch lookup") + states = {"CLOSED", "MERGED"} if state == "CLOSED" else {state} + if pr.state not in states 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 @@ -695,10 +699,7 @@ def merged_pr_for_branch(repo: str, branch: str) -> PR | None: number = _closed_history_number(repo, branch, endpoint, row, seen) seen.add(number) if row["merged_at"] is not None: - pr, detail = _pr_detail(repo, number) - if pr.state != "MERGED" or not _matches_branch(detail["head"], repo, branch): - raise GhError(("gh", "api", endpoint), "PR changed during completion lookup") - return pr + 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() @@ -736,9 +737,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"" - ) + return f"" def _comment_body(f: Finding, head_sha: str, prefix: str = "") -> str: @@ -779,13 +778,8 @@ def _review_body(result: ReviewResult, unplaced: list[Finding], prefix: str = "" 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 += [ - ( - f"loopzero {result.kind} review by {result.family} on `{result.head}`, " - f"{settings}{duration}: " - f"**{result.verdict}** ({summary})" - ), - ] + 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: @@ -923,26 +917,10 @@ def review_payloads(repo: str, number: int, head_sha: str, result: ReviewResult, 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, + 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. - """ + """Publish with the verified login for token. GitHub only permits self-reviews as comments.""" 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))): @@ -1002,7 +980,7 @@ def open_findings(repo: str, number: int) -> list[tuple[str, str, Finding]]: """(marker id, thread id, finding) for every unresolved blocking thread, any head.""" return [ (MARKER_RE.search(node["comments"]["nodes"][0]["body"]).group("id") or node["id"], node["id"], f) - for node in _unresolved_threads(repo, number) + for node in _review_threads(repo, number) if (f := _parse_thread(node, None)) ] @@ -1101,26 +1079,22 @@ def open_blocking_findings( outdated thread is ignored unless its marker names that head. """ return [ - f for node in _unresolved_threads(repo, number) if (f := _parse_thread(node, current_head)) + f for node in _review_threads(repo, number) if (f := _parse_thread(node, current_head)) ] -def _unresolved_threads(repo: str, number: int) -> list[dict]: - return _review_threads(repo, number) +def _pr_graphql_args(query: str, repo: str, number: int) -> tuple[str, ...]: + owner, name = repo.split("/", 1) + return ("api", "graphql", "-f", f"query={query}", "-F", f"owner={owner}", + "-F", f"name={name}", "-F", f"number={number}") def _review_threads(repo: str, number: int, *, include_resolved: bool = False) -> list[dict]: - owner, name = repo.split("/", 1) + args = _pr_graphql_args(_THREADS_QUERY, repo, number) after: str | None = None found: list[dict] = [] while True: - args = [ - "api", "graphql", "-f", f"query={_THREADS_QUERY}", "-F", f"owner={owner}", - "-F", f"name={name}", "-F", f"number={number}", - ] - if after: - args += ["-F", f"after={after}"] - data = _gh_json(*args) + data = _gh_json(*args, *(("-F", f"after={after}") if after else ())) try: threads = data["data"]["repository"]["pullRequest"]["reviewThreads"] nodes = threads["nodes"] @@ -1133,46 +1107,37 @@ def _review_threads(repo: str, number: int, *, include_resolved: bool = False) - raise _not_found(number, exc) from exc +_PENDING_STATES = {"pending", "queued", "in_progress", "requested", "waiting", "expected"} +_NON_FAILURES = _PENDING_STATES | {"success"} + + def _check_signals( - repo: str, - head_sha: str, - review_at: str | None = None, - review_grace: bool = False, - required_ci: tuple[str, ...] = (), - stale_verdict_grace: bool = False, + repo: str, head_sha: str, review_at: str | None = None, review_grace: bool = False, + required_ci: tuple[str, ...] = (), stale_verdict_grace: bool = False, ) -> tuple[dict[str, str], tuple[str, ...], tuple[str, ...], bool]: - signals: dict[str, list[tuple[str, str | None]]] = {} latest_runs: dict[str, dict] = {} runs = _paged(f"repos/{repo}/commits/{head_sha}/check-runs") for cr in runs: previous = latest_runs.get(cr["name"]) if previous is None or _check_run_order(cr) > _check_run_order(previous): latest_runs[cr["name"]] = cr - for name, cr in latest_runs.items(): - signals[name] = [ - ( - cr.get("conclusion") or cr.get("status") or "unknown", - cr.get("completed_at") or cr.get("started_at"), - ) - ] + signals = { + name: [(run.get("conclusion") or run.get("status") or "unknown", + run.get("completed_at") or run.get("started_at"))] + for name, run in latest_runs.items() + } latest_status: dict[str, dict] = {} for status in _paged(f"repos/{repo}/commits/{head_sha}/statuses"): latest_status.setdefault(status["context"], status) for name, status in latest_status.items(): - signals.setdefault(name, []).append( - (status.get("state") or "unknown", status.get("created_at")) - ) - states = { - name: _aggregate_signal([state for state, _ in values]) - for name, values in signals.items() - } - pending = {"pending", "queued", "in_progress", "requested", "waiting", "expected"} + signals.setdefault(name, []).append((status.get("state") or "unknown", status.get("created_at"))) + states = {name: _aggregate_signal([state for state, _ in values]) for name, values in signals.items()} stale = tuple(name for name, values in signals.items() if review_at - and states[name] not in pending and states[name] != "success" + and states[name] not in _NON_FAILURES and all(at and at < review_at for state, at in values - if state != "success" and state not in pending) + if state not in _NON_FAILURES) and (review_grace or any(at and at >= review_at - for state, at in values if state in pending))) + for state, at in values if state in _PENDING_STATES))) stale_verdicts = tuple( name for name, values in signals.items() @@ -1187,10 +1152,10 @@ def _check_signals( workflows: list[dict] | None = None for name in required_ci: cr = latest_runs.get(name) - if (name in stale or cr is None or states.get(name) in pending | {"success"} + if (name in stale or cr is None or states.get(name) in _NON_FAILURES or cr.get("conclusion") not in {"failure", "cancelled", "timed_out"} or cr.get("status") != "completed" or not (cr.get("check_suite") or {}).get("id") - or any(state not in pending | {"success"} for state, _ in signals[name][1:])): + or any(state not in _NON_FAILURES for state, _ in signals[name][1:])): continue if workflows is None: workflows = _paged(f"repos/{repo}/actions/runs?head_sha={head_sha}", "workflow_runs") @@ -1263,9 +1228,7 @@ def _check_run_order(run: dict) -> tuple[int, str]: def _aggregate_signal(states: list[str]) -> str: if all(state == "success" for state in states): return "success" - pending = {"pending", "queued", "in_progress", "requested", "waiting", "expected"} - failures = [state for state in states if state != "success" and state not in pending] - return failures[0] if failures else "pending" + return next((state for state in states if state not in _NON_FAILURES), "pending") def behind_reason(pr: PR, reviewed_head: str | None) -> str: @@ -1360,27 +1323,23 @@ def merged_sha( 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": + state = view.get("state") + if view["merged"] and state == "closed": sha = view.get("merge_commit_sha") if isinstance(sha, str) and re.fullmatch(r"[0-9a-f]{40}", sha): return sha - elif not view["merged"] and view.get("state") == "open": + if not view["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. - if not view["merged"] and view.get("state") == "closed": - raise ClosedUnmerged(argv, "PR closed without a verified merge or invalid merge evidence") - raise GhError(argv, "PR closed without a verified merge or invalid merge evidence") + error = ClosedUnmerged if not view["merged"] and state == "closed" else GhError + raise error(argv, "PR closed without a verified merge or invalid merge evidence") def merge_pending(repo: str, number: int) -> bool: """True when GitHub holds the PR for merging: queued, or accepted as an auto-merge request that it moves into the queue shortly after (observed ~1 minute, #180).""" - owner, name = repo.split("/", 1) - argv = ( - "api", "graphql", "-f", f"query={_QUEUE_QUERY}", "-F", f"owner={owner}", - "-F", f"name={name}", "-F", f"number={number}", - ) + argv = _pr_graphql_args(_QUEUE_QUERY, repo, number) try: data = _gh_json(*argv) pr = data["data"]["repository"]["pullRequest"] @@ -1430,24 +1389,10 @@ def merge(repo: str, number: int, strategy: str, head_sha: str) -> str | None: raise MergeFailed(("gh", *argv), f"PR #{number} neither merged nor queued") -def _remote_branch_head(endpoint: str) -> str | None: - try: - current = api_get(endpoint) - except GhError as exc: - if re.search(r"\bHTTP 404\b", exc.tail): - return None - raise - obj = current.get("object") if isinstance(current, dict) else None - sha = obj.get("sha") if isinstance(obj, dict) else None - if not isinstance(sha, str) or not sha: - raise GhError(("gh", "api", endpoint), "missing remote ref SHA") - return sha - - def delete_remote_branch(repo: str, branch: str, expected_head: str) -> bool: """Return False if the remote ref moved, or True if deleted or absent.""" endpoint = f"repos/{repo}/git/ref/heads/{quote(branch, safe='/')}" - current = _remote_branch_head(endpoint) + current = _ref_sha(endpoint, "object") if current != expected_head: return current is None ref = f"refs/heads/{branch}" @@ -1463,7 +1408,7 @@ def delete_remote_branch(repo: str, branch: str, expected_head: str) -> bool: done = run(argv, cwd=scratch, env_allowlist=GH_ENV, extra_env=env, timeout=120) if done.exit_code == 0: return True - current = _remote_branch_head(endpoint) + current = _ref_sha(endpoint, "object") if current != expected_head: return current is None raise GhError(argv, done.stderr or done.stdout) diff --git a/src/loopzero/mergify.py b/src/loopzero/mergify.py index 61665b00..ba86c97b 100644 --- a/src/loopzero/mergify.py +++ b/src/loopzero/mergify.py @@ -76,17 +76,20 @@ def _open(request: urllib.request.Request): return urllib.request.build_opener(_NoRedirect).open(request, timeout=30) -def api_get(repo: str, suffix: str) -> 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") +def _request(repo: str, suffix: str, method: str | None = None) -> urllib.request.Request: owner, name = (quote(part, safe="") for part in repo.split("/", 1)) - endpoint = f"{API}/repos/{owner}/{name}{suffix}" - request = urllib.request.Request( - endpoint, + return urllib.request.Request( + f"{API}/repos/{owner}/{name}{suffix}", method=method, headers={"Accept": "application/json", "User-Agent": "loopzero", "Authorization": f"Bearer {_credential()}"}, ) + + +def api_get(repo: str, suffix: str) -> 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 = _request(repo, suffix) for delay in (2.0, 5.0, None): # reads retry server errors, throttling and dropped reads try: with _open(request) as response: @@ -203,13 +206,7 @@ def configured(repo: str, branch: str, queue: str) -> bool: def dequeue(repo: str, number: int) -> None: - owner, name = (quote(part, safe="") for part in repo.split("/", 1)) - endpoint = f"{API}/repos/{owner}/{name}/merge-queue/pull/{number}/dequeue" - request = urllib.request.Request( - endpoint, method="POST", - headers={"Accept": "application/json", "User-Agent": "loopzero", - "Authorization": f"Bearer {_credential()}"}, - ) + request = _request(repo, f"/merge-queue/pull/{number}/dequeue", "POST") try: with _open(request): return @@ -223,18 +220,26 @@ def _marker(kind: str, head: str, queue: str) -> str: return f"" +def _comment_login(comment: dict) -> object: + user = comment.get("user") + return user.get("login") if isinstance(user, dict) else None + + +def _comment_url(repo: str, number: int, comment_id: int) -> str: + return f"https://github.com/{repo}/pull/{number}#issuecomment-{comment_id}" + + +def _comments(repo: str, number: int) -> list[dict]: + return github._paged(f"repos/{repo}/issues/{number}/comments") + + 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(): - report_id = latest.get("id") - if type(report_id) is int and report_id > 0: - return report_id - return None + candidates = (comment for comment in comments if _comment_login(comment) == "mergify[bot]" + and str(comment.get("updated_at") or "") >= requested_at) + latest = max(candidates, key=lambda comment: str(comment.get("updated_at") or ""), default={}) + report_id = latest.get("id") + waiting = "### ⏳ Waiting for queue conditions" in str(latest.get("body") or "").splitlines() + return report_id if waiting and type(report_id) is int and report_id > 0 else None def _queue_command(body: str, queue: str) -> bool: @@ -265,7 +270,7 @@ def _departure_payload(body: str, queue: str) -> dict: def departure_report(repo: str, number: int, head: str, queue: str) -> Departure | None: """Use a bot report only when it identifies the latest command and current head.""" try: - comments = github._paged(f"repos/{repo}/issues/{number}/comments") + comments = _comments(repo, number) except github.GhError: return None comments = [item for item in comments if type(item.get("id")) is int and item["id"] > 0] @@ -274,8 +279,7 @@ def departure_report(repo: str, number: int, head: str, queue: str) -> Departure 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]"), + (item for item in comments if _comment_login(item) == "mergify[bot]"), key=lambda item: (str(item.get("updated_at") or ""), item["id"]), default={}, ) body = str(latest.get("body") or "") @@ -283,10 +287,10 @@ def departure_report(repo: str, number: int, head: str, queue: str) -> Departure if not command or not payload: return None - url = f"https://github.com/{repo}/pull/{number}#issuecomment-" + command_url = _comment_url(repo, number, command["id"]) entered = next((line for line in body.splitlines() 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]): + if f"]({command_url})" not in entered or not source or not head.startswith(source[1]): return None markers = [line for line in str(command.get("body") or "").splitlines() if line.startswith(f"