diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index e6012622..3a17a4ff 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -37,7 +37,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. @@ -151,10 +150,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}): " @@ -164,10 +160,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: @@ -185,9 +178,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: @@ -213,11 +204,11 @@ 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}") + batch = github.api_get(f"{endpoint}?per_page={github.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: + if len(batch) < github.PAGE: return rows raise CliError(f"GitHub {what} pagination limit exceeded") @@ -309,10 +300,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": @@ -536,12 +524,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") @@ -576,24 +558,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) @@ -615,8 +590,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) ): @@ -814,16 +788,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 @@ -1128,7 +1098,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( @@ -1138,7 +1107,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) errors[family] = detail, exc.tail if isinstance(exc, runners.RunnerMalformedOutput) else "" @@ -1384,16 +1353,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} @@ -1408,9 +1378,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 () @@ -1460,10 +1429,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, args) @@ -1471,9 +1441,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: @@ -1722,6 +1690,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.""" @@ -1747,7 +1718,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): @@ -1758,14 +1728,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 @@ -1797,10 +1763,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") @@ -1826,10 +1789,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 2db069b3..edf87338 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: @@ -152,10 +141,7 @@ def _remote_workflow(worktree: Path, branch: str, previous: Config | None, *, re def load_trusted(worktree: Path, *, previous: Config | None = None, refresh: bool = False) -> 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( @@ -214,20 +200,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"]) @@ -244,12 +230,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: @@ -306,13 +291,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/github.py b/src/loopzero/github.py index e40611b9..e27216f2 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -15,6 +15,7 @@ from dataclasses import dataclass from datetime import UTC, datetime from email.utils import parsedate_to_datetime +from itertools import pairwise from pathlib import Path from typing import Literal from urllib.parse import quote @@ -186,13 +187,16 @@ def _included_response(output: str) -> tuple[str | None, dict[str, str], str]: return status, headers, body +def _api_methods(args: tuple[str, ...]) -> list[str]: + return [method.upper() for flag, method in pairwise(args) if flag in ("--method", "-X")] + + +_API_BODY_FLAGS = {"-f", "-F", "--field", "--raw-field", "--input"} + + def _api_method(args: tuple[str, ...]) -> str: - for index, arg in enumerate(args[:-1]): - if arg in ("--method", "-X"): - return args[index + 1].upper() - if {"-f", "-F", "--field", "--raw-field", "--input"} & set(args): - return "POST" - return "GET" + methods = _api_methods(args) + return methods[0] if methods else "POST" if _API_BODY_FLAGS.intersection(args) else "GET" def _api_path(args: tuple[str, ...]) -> str: @@ -227,9 +231,9 @@ def _redact_tokens(value: str, token: str = "") -> str: return re.sub(r"(? str: - status, headers, body = _included_response(stdout) +def _api_error_detail(args: tuple[str, ...], response: tuple[str | None, dict[str, str], str], + stderr: str, token: str, *, message_tail: str | None = None) -> str: + status, headers, body = response if status is None: match = re.search(r"\bHTTP(?:/\S+)?\s+(\d{3})\b", stderr, re.IGNORECASE) status = match.group(1) if match else "unavailable" @@ -250,10 +254,11 @@ def _api_error_detail(args: tuple[str, ...], stdout: str, stderr: str, error["message"] for error in errors if isinstance(error, dict) and isinstance(error.get("message"), str) ) - if not message: + if message_tail is not None: + message = message_tail + elif not message: message = 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" + message = " ".join(_redact_tokens(message, token).split())[:400] or "no response message" return _redact_tokens( f"method={_api_method(args)} endpoint={_api_path(args)} status={status} " f"request_id={request_id} message={message}", token @@ -264,12 +269,10 @@ def _read_only(args: tuple[str, ...]) -> bool: """Only reads are retried: a repeated write could post or change state twice.""" if args[:2] == ("api", "graphql"): return not any("mutation" in arg for arg in args) - if args[:1] == ("api",): - methods = [args[i + 1] for i, arg in enumerate(args[:-1]) if arg in ("-X", "--method")] - if methods: - return all(method.upper() == "GET" for method in methods) - return not {"-f", "-F", "--field", "--raw-field", "--input"} & set(args) - return False + if args[:1] != ("api",): + return False + methods = _api_methods(args) + return all(method == "GET" for method in methods) if methods else not _API_BODY_FLAGS.intersection(args) def _app_token_clock() -> float | None: @@ -317,10 +320,6 @@ def _transient_error(tail: str, retry_idempotent: bool, status: str | None = Non ) -def _request_error(transient: bool) -> type[GhError]: - return GhUnavailable if transient else GhError - - def _rate_limited(status: str | None, headers: dict[str, str], tail: str) -> bool: return (status == "429" or (status == "403" and (headers.get("x-ratelimit-remaining") == "0" or "retry-after" in headers)) @@ -355,14 +354,12 @@ 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 api = args[:1] == ("api",) - if api and not {"--include", "-i"} & set(args): - request_args = (*args, "--include") - argv = ("gh", *request_args) + diagnostic_api = api and _api_error_diagnostics.get() + rest_api = api and args[:2] != ("api", "graphql") + patch_error = api and _api_method(args) == "PATCH" + command = ("gh", *args) + argv = (*command, "--include") if api and not {"--include", "-i"} & set(args) else command cwd = cwd or Path("/") read_only = _read_only(args) retryable = read_only or retry_idempotent @@ -385,32 +382,31 @@ def _gh(*args: str, cwd: Path | None = None, timeout: float = 120, stderr=_redact_tokens(exc.stderr, selected), duration_s=exc.duration_s, ) from None continue - status, headers, body = (_included_response(done.stdout) if api - else (None, {}, done.stdout)) + response = _included_response(done.stdout) if api else (None, {}, done.stdout) + status, headers, body = response tail = "\n".join(part for part in (done.stderr, body) if part) - if done.exit_code and _rate_limited(status, headers, tail): - if _retry_pause(_rate_limit_delay(headers, delay), timeout, scoped=read_only): - continue - guidance = (_redact_tokens(_rest_rate_limit(headers), selected) if rest_api or headers - 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 GhUnavailable(("GitHub API request",), detail, token=selected, guidance=guidance) - raise GhUnavailable(("gh", *args), tail, token=selected, guidance=guidance) - transient = _transient_error(tail, retry_idempotent, status) - if done.exit_code == 0 or not transient or not _retry_pause(delay, timeout, scoped=read_only): + if done.exit_code == 0: + return body + rate_limited = _rate_limited(status, headers, tail) + transient = rate_limited or _transient_error(tail, retry_idempotent, status) + pause = _rate_limit_delay(headers, delay) if rate_limited else delay + if not transient or not _retry_pause(pause, timeout, scoped=read_only): break - if done.exit_code != 0: - error_command = ("GitHub API request",) if diagnostic_api or patch_error 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) + + error_command, detail = (command if rate_limited else argv), tail + if diagnostic_api or patch_error: + error_command = ("GitHub API request",) + detail = _api_error_detail(args, response if diagnostic_api else (None, {}, ""), + done.stderr, selected, message_tail=None if diagnostic_api else tail) + if rate_limited: + guidance = (_redact_tokens(_rest_rate_limit(headers), selected) if rest_api or headers + else _graphql_reset(args, tail, cwd, selected) + RATE_LIMIT_GUIDANCE) + else: if "gh auth login" in tail or "not logged in" in tail.lower(): - raise GhAuth(error_command, error_tail.rstrip(), token=selected, guidance=f"\n{GH_AUTH_REMEDY}") + raise GhAuth(error_command, detail.rstrip(), token=selected, guidance=f"\n{GH_AUTH_REMEDY}") guidance = _pr_list_error_guidance(args, done.stderr, bool(read_only and selected and token is None)) - raise _request_error(transient)(error_command, error_tail, token=selected, guidance=guidance) - return body + error = GhUnavailable if transient else GhError + raise error(error_command, detail, token=selected, guidance=guidance) def _rest_rate_limit(headers: dict[str, str]) -> str: @@ -428,22 +424,18 @@ def _rest_rate_limit(headers: dict[str, str]) -> str: reset = datetime.fromtimestamp(int(epoch), UTC).isoformat() except (OverflowError, OSError, ValueError): pass - evidence = [] - if re.fullmatch(r"[a-zA-Z][a-zA-Z0-9_-]{0,63}", resource): - evidence.append(f"X-RateLimit-Resource: {resource}") - if remaining is not None: - evidence.append(f"X-RateLimit-Remaining: {remaining}") - if reset: - evidence.append(f"X-RateLimit-Reset: {reset}") - if retry_seconds or retry_date: - evidence.append(f"Retry-After: {retry_after}") + evidence = { + "X-RateLimit-Resource": resource if re.fullmatch(r"[a-zA-Z][a-zA-Z0-9_-]{0,63}", resource) else None, + "X-RateLimit-Remaining": remaining, "X-RateLimit-Reset": reset or None, + "Retry-After": retry_after if retry_seconds or retry_date else None, + } guidance = RATE_LIMIT_GUIDANCE if remaining == 0: guidance = f"\nRate limited: hourly quota exhausted: retry after {reset or 'the quota resets'}; No automatic retry." elif remaining is not None or retry_seconds or retry_date: delay = f"{retry_after} s" if retry_seconds else retry_after if retry_date else "~60 s" guidance = f"\nRate limited: short-window limit: retry after {delay}; No automatic retry." - return "".join(f"\n{line}" for line in evidence) + guidance + return "".join(f"\n{name}: {value}" for name, value in evidence.items() if value is not None) + guidance def _graphql_reset(args: tuple[str, ...], tail: str, cwd: Path, token: str = "") -> str: @@ -608,11 +600,11 @@ def pr_from_rest(data: object) -> PR: def _pr_detail(repo: str, number: int) -> tuple[PR, dict]: - data = api_get(f"repos/{repo}/pulls/{number}") + endpoint = f"repos/{repo}/pulls/{number}" + data = api_get(endpoint) pr = pr_from_rest(data) if pr.number != number: - raise GhError(("gh", "api", f"repos/{repo}/pulls/{number}"), - f"PR detail number {pr.number} differs from requested {number}") + raise GhError(("gh", "api", endpoint), f"PR detail number {pr.number} differs from requested {number}") return pr, data @@ -622,22 +614,25 @@ 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 _branch_sha(endpoint: str, field: str, invalid: str, *, full_sha: bool = False) -> str | None: try: ref = api_get(endpoint) except GhError as exc: if re.search(r"\bHTTP 404\b", exc.tail): return None raise - 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") - + ref_data = ref.get(field) if isinstance(ref, dict) else None + sha = ref_data.get("sha") if isinstance(ref_data, dict) else None + if not isinstance(sha, str) or not sha or (full_sha and not re.fullmatch(r"[0-9a-f]{40}", sha)): + raise GhError(("gh", "api", endpoint), invalid) return sha +def _branch_head(repo: str, branch: str) -> str | None: + endpoint = f"repos/{repo}/branches/{quote(branch, safe='')}" + return _branch_sha(endpoint, "commit", "invalid remote branch SHA", full_sha=True) + + def _commit_branch_prs(repo: str, branch: str) -> tuple[str, list[dict]]: sha = _branch_head(repo, branch) if sha is None: @@ -665,9 +660,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 @@ -733,10 +729,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() @@ -754,11 +747,8 @@ def create_draft_pr(repo: str, branch: str, base: str, title: str, body: str) -> f"repos/{repo}/pulls", {"head": branch, "base": base, "title": title, "body": body, "draft": True}) pr = pr_from_rest(detail) - source_repo = detail["head"].get("repo") or {} if (pr.state != "OPEN" or not pr.is_draft or pr.base_ref != base - or detail["head"].get("ref") != branch - or not isinstance(source_repo, dict) - or str(source_repo.get("full_name") or "").casefold() != repo.casefold()): + or not _matches_branch(detail["head"], repo, branch)): raise GhError(("gh", "api", f"repos/{repo}/pulls"), "created PR differs from request") return pr @@ -892,24 +882,14 @@ def _right_lines(patch: str) -> tuple[set[int], int | None]: return lines, first_added -def _require_complete_file_list(repo: str, number: int, head_sha: str, count: int, missing: str) -> None: - pr, detail = _pr_detail(repo, number) - request = ("gh", "api", f"repos/{repo}/pulls/{number}/files") - if pr.head_sha != head_sha: - raise GhError(request, f"PR #{number} head moved from {head_sha[:12]} to {pr.head_sha[:12]}; rerun review") - if detail.get("changed_files") != count: - raise GhError(request, - f"cannot place finding on PR #{number} at {missing!r}: " - f"GitHub's {PR_FILE_LIMIT:,}-file limit prevents verifying the complete file list") - - def _diff_map(repo: str, number: int, head_sha: str, findings: tuple[Finding, ...]) -> tuple[dict[str, set[int]], dict | None]: blocking = tuple(f for f in findings if f.severity in BLOCKING) remaining = {f.path for f in findings if f.path and (f.line or f.severity in BLOCKING)} commentable: dict[str, set[int]] = {} anchor: dict | None = None - rows = _iter_paged(f"repos/{repo}/pulls/{number}/files") if remaining or blocking else () + endpoint = f"repos/{repo}/pulls/{number}/files" + rows = _iter_paged(endpoint) if remaining or blocking else () count = 0 for entry in rows: count += 1 @@ -924,7 +904,13 @@ def _diff_map(repo: str, number: int, head_sha: str, return commentable, anchor missing = next((f.path for f in blocking if f.path in remaining), None) if missing is not None and count >= PR_FILE_LIMIT: - _require_complete_file_list(repo, number, head_sha, len(commentable), missing) + pr, detail = _pr_detail(repo, number) + request = ("gh", "api", endpoint) + if pr.head_sha != head_sha: + raise GhError(request, f"PR #{number} head moved from {head_sha[:12]} to {pr.head_sha[:12]}; rerun review") + if detail.get("changed_files") != len(commentable): + raise GhError(request, f"cannot place finding on PR #{number} at {missing!r}: " + f"GitHub's {PR_FILE_LIMIT:,}-file limit prevents verifying the complete file list") return commentable, anchor @@ -1020,7 +1006,7 @@ def _thread_marker(node: dict, publishers: tuple[str, ...]) -> re.Match[str] | N def _parse_thread(node: dict, current_head: str | None, - publishers: tuple[str, ...]) -> Finding | None: + publishers: tuple[str, ...]) -> tuple[str, Finding] | None: match = _thread_marker(node, publishers) if not match or match.group("severity") not in BLOCKING: return None @@ -1029,9 +1015,9 @@ def _parse_thread(node: dict, current_head: str | None, if current_head is not None and marker_head != current_head and node.get("isOutdated"): return None severity = match.group("severity") - rest = body[match.end():].lstrip() - return Finding(severity=severity, path=node.get("path"), line=node.get("line"), - title=_title_of(rest), body=rest.strip()) + rest = body[match.end():].strip() + return match.group("id"), Finding(severity=severity, path=node.get("path"), line=node.get("line"), + title=_title_of(rest), body=rest) _REPLY_MUTATION = ( @@ -1047,9 +1033,9 @@ def open_findings(repo: str, number: int, publishers: tuple[str, ...]) -> list[tuple[str, str, Finding]]: """(marker id, thread id, finding) for every unresolved blocking thread, any head.""" return [ - (_thread_marker(node, publishers).group("id"), node["id"], f) - for node in _unresolved_threads(repo, number) - if (f := _parse_thread(node, None, publishers)) + (parsed[0], node["id"], parsed[1]) + for node in _review_threads(repo, number) + if (parsed := _parse_thread(node, None, publishers)) ] @@ -1098,12 +1084,11 @@ def resolve_finding(repo: str, number: int, finding_id: str, reply: str, """Reply to a blocking finding, or resume an identical resolution.""" threads = _review_threads(repo, number, include_resolved=True) for node in sorted(threads, key=lambda node: bool(node.get("isResolved"))): - finding = _parse_thread(node, None, publishers) - if finding is None: + parsed = _parse_thread(node, None, publishers) + if parsed is None or parsed[0] != finding_id: continue thread_id = node["id"] - if _thread_marker(node, publishers).group("id") != finding_id: - continue + _, finding = parsed confirmed = _has_thread_reply(node, reply) if node.get("isResolved"): if confirmed: @@ -1158,40 +1143,41 @@ def open_blocking_findings( unless its marker names that head. """ return [ - f for node in _unresolved_threads(repo, number) - if (f := _parse_thread(node, current_head, publishers)) + parsed[1] for node in _review_threads(repo, number) + if (parsed := _parse_thread(node, current_head, publishers)) ] -def _unresolved_threads(repo: str, number: int) -> list[dict]: - return _review_threads(repo, number) +def _pull_query(repo: str, number: int, query: str) -> 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) - after: str | None = None + args = _pull_query(repo, number, _THREADS_QUERY) seen: set[str] = set() found: list[dict] = [] + cursor: tuple[str, ...] = () 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, *cursor) try: threads = data["data"]["repository"]["pullRequest"]["reviewThreads"] - nodes = threads["nodes"] page = threads["pageInfo"] - found += [node for node in nodes if include_resolved or not node.get("isResolved")] + found.extend(node for node in threads["nodes"] if include_resolved or not node.get("isResolved")) if not page["hasNextPage"]: return found - after = _next_thread_cursor(page, seen) + cursor = ("-F", f"after={_next_thread_cursor(page, seen)}") except (KeyError, TypeError) as exc: raise _not_found(number, exc) from exc +_ACTIVE_WORKFLOWS = {"queued", "in_progress", "waiting", "pending", "requested"} +_PENDING_CHECKS = _ACTIVE_WORKFLOWS | {"expected"} +_NONFAILING_CHECKS = _PENDING_CHECKS | {"success"} +_FAILED_VERDICTS = {"failure", "error", "cancelled", "timed_out"} + + def _check_signals( repo: str, head_sha: str, @@ -1200,72 +1186,53 @@ def _check_signals( 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: [(cr.get("conclusion") or cr.get("status") or "unknown", + cr.get("completed_at") or cr.get("started_at"))] + for name, cr 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")) - ) + 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"} stale = tuple(name for name, values in signals.items() if review_at - and states[name] not in pending and states[name] != "success" - and all(at and at < review_at for state, at in values - if state != "success" and state not in pending) - and (review_grace or any(at and at >= review_at - for state, at in values if state in pending))) - stale_verdicts = tuple( - name - for name, values in signals.items() - if review_at - and stale_verdict_grace - and name not in stale - and states[name] in {"failure", "error", "cancelled", "timed_out"} - and all(at and at < review_at for state, at in values if state != "success") - ) - stale = (*stale, *stale_verdicts) + and states[name] not in _NONFAILING_CHECKS + and all(at and at < review_at for state, at in values if state not in _NONFAILING_CHECKS) + and (review_grace or any(at and at >= review_at for state, at in values if state in _PENDING_CHECKS))) + stale_verdicts = tuple(name for name, values in signals.items() if review_at and stale_verdict_grace + and name not in stale and states[name] in _FAILED_VERDICTS + and all(at and at < review_at for state, at in values if state != "success")) + stale += stale_verdicts superseded: list[str] = [] 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 _NONFAILING_CHECKS 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 _NONFAILING_CHECKS for state, _ in signals[name][1:])): continue if workflows is None: workflows = _paged(f"repos/{repo}/actions/runs?head_sha={head_sha}", "workflow_runs") if _has_active_replacement(repo, cr, workflows, head_sha): superseded.append(name) capped = _check_suites_at_limit(runs) - _discard_unverified_successes(states, latest_status.keys() - latest_runs.keys(), capped) - return states, (*stale, *superseded), stale_verdicts, capped - - -def _discard_unverified_successes(states: dict[str, str], status_only: set[str], capped: bool) -> None: # A status-only success may hide a failed run outside the returned suites. - if capped: - for name in status_only: - if states[name] == "success": - del states[name] + verified = { + name: state for name, state in states.items() if state != "success" or name in latest_runs + } if capped else states + return verified, (*stale, *superseded), stale_verdicts, capped def _check_suites_at_limit(runs: list[dict]) -> bool: @@ -1298,7 +1265,7 @@ def find_producer(runs: list[dict]) -> dict | None: for workflow in workflows: if (workflow.get("head_sha") != head_sha or workflow.get("workflow_id") != producer["workflow_id"] - or workflow.get("status") not in {"queued", "in_progress", "waiting", "pending", "requested"}): + or workflow.get("status") not in _ACTIVE_WORKFLOWS): continue if workflow.get("id") == producer.get("id"): if (workflow.get("run_attempt", 1) > 1 and check.get("completed_at") @@ -1322,9 +1289,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 _NONFAILING_CHECKS), "pending") def behind_reason(pr: PR, reviewed_head: str | None) -> str: @@ -1372,25 +1337,20 @@ def readiness( repo, pr.head_sha, review_at, review_grace, required_ci if workflow_wait else (), workflow_wait and stale_verdict_grace, ) if required_ci else ({}, (), (), False)) + failures = { + name: f"required check '{name}' is {checks[name]}" for name in required_ci + if name in checks and checks[name] != "success" + } for name in required_ci: - conclusion = checks.get(name) - if conclusion is None: + if name not in checks: reasons.append(_missing_check_reason(name, pr.head_sha, capped)) - elif conclusion != "success": - reasons.append(f"required check '{name}' is {conclusion}") + elif name in failures: + reasons.append(failures[name]) return Readiness( ready=not reasons, reasons=tuple(reasons), - waitable_failures=tuple( - f"required check '{name}' is {checks[name]}" - for name in required_ci - if name in stale - or ( - workflow_wait - and review_grace - and checks.get(name) in {"failure", "error", "cancelled", "timed_out"} - ) - ), + waitable_failures=tuple(failures[name] for name in required_ci if name in stale + or (workflow_wait and review_grace and checks.get(name) in _FAILED_VERDICTS)), stale_verdicts=tuple(name for name in required_ci if name in stale_verdicts), has_pending_checks="pending" in checks.values(), ) @@ -1429,21 +1389,16 @@ def merged_sha( 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 view.get("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}", - ) + args = _pull_query(repo, number, _QUEUE_QUERY) try: - data = _gh_json(*argv) + data = _gh_json(*args) pr = data["data"]["repository"]["pullRequest"] queued = pr["isInMergeQueue"] auto = pr.get("autoMergeRequest") @@ -1492,17 +1447,7 @@ def merge(repo: str, number: int, strategy: str, head_sha: str) -> str | None: 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 + return _branch_sha(endpoint, "object", "missing remote ref SHA") def delete_remote_branch(repo: str, branch: str, expected_head: str) -> bool: @@ -1522,12 +1467,12 @@ def delete_remote_branch(repo: str, branch: str, expected_head: str) -> bool: if done.exit_code != 0: raise GhError(init, done.stderr or done.stdout) 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) - if current != expected_head: + if done.exit_code: + current = _remote_branch_head(endpoint) + if current == expected_head: + raise GhError(argv, done.stderr or done.stdout) return current is None - raise GhError(argv, done.stderr or done.stdout) + return True def commit_status(repo: str, head: str, context: str, state: str, description: str) -> None: