From e24bd1d610978af825be6cf71fe21310c5d62b4d Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 14:56:19 +0100 Subject: [PATCH 1/3] Consolidate GitHub response parsing and Mergify retries Architecture-Review: unchanged; response validation, pagination bounds, retry budgets, and transport contracts remain intact. Co-Authored-By: Codex --- src/loopzero/github.py | 93 ++++++++++++++++------------------------- src/loopzero/mergify.py | 41 ++++++++---------- 2 files changed, 54 insertions(+), 80 deletions(-) diff --git a/src/loopzero/github.py b/src/loopzero/github.py index 3f535c3e..a1e55a87 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -16,7 +16,7 @@ from dataclasses import dataclass from datetime import UTC, datetime from email.utils import parsedate_to_datetime -from itertools import pairwise +from itertools import count, pairwise from pathlib import Path from typing import Literal from urllib.parse import quote @@ -176,18 +176,15 @@ def _included_response(output: str) -> tuple[str | None, dict[str, str], str]: """Split one `gh api --include` response into status, headers and body.""" for line_separator in ("\r\n", "\n"): head, separator, body = output.partition(line_separator * 2) - if separator: + if not separator: + continue + status_line, *header_lines = head.split(line_separator) + if not (match := _HTTP_STATUS_RE.match(status_line)): break - else: - return None, {}, output - lines = head.split(line_separator) - match = _HTTP_STATUS_RE.match(lines[0]) - if match is None: - return None, {}, output - headers = {name.strip().casefold(): value.strip() - for name, separator, value in (line.partition(":") for line in lines[1:]) - if separator} - return match.group(1), headers, body + headers = {name.strip().casefold(): value.strip() + for name, colon, value in (line.partition(":") for line in header_lines) if colon} + return match.group(1), headers, body + return None, {}, output def _api_methods(args: tuple[str, ...]) -> list[str]: @@ -202,14 +199,6 @@ def _api_method(args: tuple[str, ...]) -> str: return methods[0] if methods else "POST" if _API_BODY_FLAGS.intersection(args) else "GET" -def _api_path(args: tuple[str, ...]) -> str: - endpoint = args[1] if len(args) > 1 else "" - path = endpoint.split("?", 1)[0] - if "://" in path: - path = path.partition("://")[2].partition("/")[2] - return "/" + path.lstrip("/") - - def redact_credentials(value: str) -> str: value = re.sub(r"""(?i)(https?://)[^\s/?#'"<>`]+@""", r"\1[REDACTED]@", value) value = re.sub(r"""(?i)(\bauthorization(?:\\?['"])?[ \t]*:[ \t]*)(\\?['"])(?:(?!\2)(?:\\.|[^\\\r\n]))+\2""", @@ -242,28 +231,23 @@ def _api_error_detail(args: tuple[str, ...], response: tuple[str | None, dict[st status = match.group(1) if match else "unavailable" request_id = headers.get("x-github-request-id") or "unavailable" message = "" - try: - payload = json.loads(body) - except (TypeError, ValueError): - payload = None - if isinstance(payload, dict): - message_value = payload.get("message") - if isinstance(message_value, str): - message = message_value - else: - errors = payload.get("errors") - if isinstance(errors, list): + with suppress(TypeError, ValueError): + match json.loads(body): + case {"message": str(value)}: + message = value + case {"errors": list(errors)}: message = "; ".join( error["message"] for error in errors if isinstance(error, dict) and isinstance(error.get("message"), str) ) - if message_tail is not None: - message = message_tail - elif not message: - message = body.strip() or stderr.strip().removeprefix("gh:").strip() + message = (message_tail if message_tail is not None + else message or body.strip() or stderr.strip().removeprefix("gh:").strip()) message = " ".join(_redact_tokens(message, token).split())[:400] or "no response message" + path = (args[1] if len(args) > 1 else "").split("?", 1)[0] + if "://" in path: + path = path.partition("://")[2].partition("/")[2] return _redact_tokens( - f"method={_api_method(args)} endpoint={_api_path(args)} status={status} " + f"method={_api_method(args)} endpoint=/{path.lstrip('/')} status={status} " f"request_id={request_id} message={message}", token ) @@ -515,9 +499,8 @@ def record_full_page(endpoint: str, rows: list, seen: set[bytes]) -> None: def _iter_paged(endpoint: str, key: str = "check_runs") -> Iterator[dict]: """Yield validated rows until the last page.""" - page = 1 seen: set[bytes] = set() - while True: + for page in count(1): chunk = _gh_json("api", endpoint, "--method", "GET", "-F", f"per_page={PAGE}", "-F", f"page={page}") if isinstance(chunk, dict): @@ -529,7 +512,6 @@ def _iter_paged(endpoint: str, key: str = "check_runs") -> Iterator[dict]: yield from chunk if len(chunk) < PAGE: return - page += 1 def _paged(endpoint: str, key: str = "check_runs") -> list: @@ -557,11 +539,9 @@ def login(token: str | None = None) -> str: """Login of the identity used for GitHub reads and review publishing.""" data = _gh_json("api", "graphql", "-f", "query=query { viewer { login } }", token=token) content = data.get("data") if isinstance(data, dict) else None - viewer = content.get("viewer") if isinstance(content, dict) else None - name = viewer.get("login") if isinstance(viewer, dict) else None - if not name: - raise GhError(("gh", "api", "graphql"), "no login in viewer response") - return str(name) + if isinstance(content, dict) and isinstance(viewer := content.get("viewer"), dict) and (name := viewer.get("login")): + return str(name) + raise GhError(("gh", "api", "graphql"), "no login in viewer response") def _not_found(number: int, exc: Exception) -> GhError: @@ -684,8 +664,8 @@ def _commit_branch_prs(repo: str, branch: str) -> tuple[str, list[dict]]: def _confirm_branch_pr(repo: str, branch: str, endpoint: str, number: int, state: str) -> PR: pr, detail = _pr_detail(repo, number) - states = {"CLOSED", "MERGED"} if state == "CLOSED" else {state} - if pr.state not in states or not _matches_branch(detail["head"], repo, branch): + matches_state = pr.state == state or (state == "CLOSED" and pr.state == "MERGED") + if not matches_state or not _matches_branch(detail["head"], repo, branch): lookup = "completion" if state == "MERGED" else "branch" raise GhError(("gh", "api", endpoint), f"PR changed during {lookup} lookup") return pr @@ -695,9 +675,9 @@ def pr_for_branch(repo: str, branch: str, *, open_only: bool = False, list_only: """Return the open PR, falling back to the most recent closed PR unless open_only.""" if not list_only: endpoint, matches = _commit_branch_prs(repo, branch) - open_matches = [row for row in matches if row["state"] == "open"] - if open_matches: - newest = max(open_matches, key=lambda row: (row["created_at"], row["number"])) + newest = max((row for row in matches if row["state"] == "open"), + key=lambda row: (row["created_at"], row["number"]), default=None) + if newest is not None: return _confirm_branch_pr(repo, branch, endpoint, newest["number"], "OPEN") # A closed association cannot rule out an open PR or newer closed history. @@ -1405,20 +1385,20 @@ def merged_sha( """The verified merge commit, or None while open. Admission may check the hold label.""" argv = ("gh", "api", f"repos/{repo}/pulls/{number}") view = api_get(argv[2]) - if not isinstance(view, dict) or type(view.get("merged")) is not bool: + if not isinstance(view, dict) or type(merged := view.get("merged")) is not bool: raise GhError(argv, "invalid PR merge evidence") if expected_head and (not isinstance(view.get("head"), dict) or view["head"].get("sha") != expected_head): raise GhError(argv, "PR head changed before merge verification") - if view["merged"] and view.get("state") == "closed": - sha = view.get("merge_commit_sha") - if isinstance(sha, str) and re.fullmatch(r"[0-9a-f]{40}", sha): + state = view.get("state") + if merged and state == "closed": + if isinstance(sha := view.get("merge_commit_sha"), str) and re.fullmatch(r"[0-9a-f]{40}", sha): return sha - elif not view["merged"] and view.get("state") == "open": + elif not merged and state == "open": if check_hold and (hold := merge_hold(number, _pr_labels(view))): raise GhError(argv, hold) return None # An open PR's merge_commit_sha is only a test merge. - error = ClosedUnmerged if not view["merged"] and view.get("state") == "closed" else GhError + error = ClosedUnmerged if not merged and state == "closed" else GhError raise error(argv, "PR closed without a verified merge or invalid merge evidence") @@ -1427,8 +1407,7 @@ def merge_pending(repo: str, number: int) -> bool: request that it moves into the queue shortly after (observed ~1 minute, #180).""" args = _pull_query(repo, number, _QUEUE_QUERY) try: - data = _gh_json(*args) - pr = data["data"]["repository"]["pullRequest"] + pr = _gh_json(*args)["data"]["repository"]["pullRequest"] queued = pr["isInMergeQueue"] auto = pr.get("autoMergeRequest") if type(queued) is not bool or (auto is not None and not isinstance(auto, dict)): diff --git a/src/loopzero/mergify.py b/src/loopzero/mergify.py index cf5dd66b..709d5604 100644 --- a/src/loopzero/mergify.py +++ b/src/loopzero/mergify.py @@ -13,7 +13,7 @@ import time import urllib.error import urllib.request -from contextlib import ExitStack, contextmanager +from contextlib import ExitStack, contextmanager, suppress from dataclasses import dataclass from pathlib import Path from urllib.parse import quote @@ -117,20 +117,14 @@ def _wait_to_retry(delay: float, deadline: float | None) -> bool: return deadline is None or time.monotonic() < deadline -def _queue_read_failure(exc: Exception) -> tuple[str, bool]: - if isinstance(exc, (json.JSONDecodeError, UnicodeDecodeError)): - return "Mergify queue lookup returned no valid JSON", True - reason = exc.reason if isinstance(exc, urllib.error.URLError) else exc - return f"Mergify queue transport failed: {reason}", not isinstance(reason, ssl.SSLCertVerificationError) - - def api_get(repo: str, suffix: str, deadline: float | None = None) -> object | None: """GET one documented endpoint below this repository's fixed Mergify API path.""" if not suffix.startswith("/") or "://" in suffix or ".." in suffix: raise ValueError("Mergify API suffix must be a repository-relative absolute path") request = _api_request(repo, suffix) - for retry in (True, False): - delay = 2.0 + retry = True + while True: + wait = None try: with _open(request) as response: return json.load(response) @@ -138,16 +132,20 @@ def api_get(repo: str, suffix: str, deadline: float | None = None) -> object | N if exc.code == 404: return None wait = github.retry_after(exc.headers.get("Retry-After", "")) if exc.headers else None - delay = max(delay, wait or 0.0) detail = f"Mergify queue lookup failed with HTTP {exc.code}" + (f"; Retry-After: {wait:g}s" if wait is not None else "") transient = exc.code >= 500 or exc.code == 429 or (exc.code == 403 and wait is not None) - except (OSError, json.JSONDecodeError, UnicodeDecodeError, http.client.IncompleteRead) as exc: - detail, transient = _queue_read_failure(exc) + except (json.JSONDecodeError, UnicodeDecodeError): + detail, transient = "Mergify queue lookup returned no valid JSON", True + except (OSError, http.client.IncompleteRead) as exc: + reason = exc.reason if isinstance(exc, urllib.error.URLError) else exc + detail = f"Mergify queue transport failed: {reason}" + transient = not isinstance(reason, ssl.SSLCertVerificationError) if not retry or not transient: raise MergifyError(detail) - if not _wait_to_retry(delay, deadline): + if not _wait_to_retry(max(2.0, wait or 0.0), deadline): raise MergifyError(f"{detail}; retry delay exceeds the wait budget") - return None + retry = False + def _unmet_conditions(node: object) -> tuple[str, ...]: if not isinstance(node, dict) or node.get("match") is not False: @@ -241,8 +239,7 @@ def construct_mapping(self, node, deep=False): blob = github.api_get(path) try: if (blob["type"] != "file" or blob["encoding"] != "base64" - or not isinstance(blob["sha"], str) or len(blob["sha"]) != 40 - or any(char not in "0123456789abcdef" for char in blob["sha"]) + or not isinstance(blob["sha"], str) or not re.fullmatch(r"[0-9a-f]{40}", blob["sha"]) or not isinstance(blob["content"], str) or len(blob["content"]) > 90000): return False document = yaml.load(base64.b64decode("".join(blob["content"].split()), validate=True), @@ -334,13 +331,11 @@ class Departure: def _departure_payload(body: str, queue: str) -> dict: _, _, text = body.partition("-*- Mergify Payload -*-\n") - try: + with suppress(json.JSONDecodeError): payload = json.loads(text.partition("\n-*- Mergify Payload End -*-")[0]) - except json.JSONDecodeError: - return {} - if (isinstance(payload, dict) and payload.get("version") == 1 - and payload.get("state") == "dequeued" and payload.get("queue_rule_name") == queue): - return payload + if (isinstance(payload, dict) and payload.get("version") == 1 + and payload.get("state") == "dequeued" and payload.get("queue_rule_name") == queue): + return payload return {} From 0b76640dfdc47856671d4bc1233414cb2a501413 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:05:54 +0100 Subject: [PATCH 2/3] Reuse the PR lock for cross-checkout body updates Co-Authored-By: Codex --- docs/ARCHITECTURE.md | 8 +++--- src/loopzero/cli.py | 32 +++++++++++++---------- tests/test_cli.py | 61 ++++++++++++++++++++++++++++---------------- 3 files changed, 61 insertions(+), 40 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 4db76120..63071d10 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -33,10 +33,10 @@ local-receipt exceptions. Merge authority permits merging by default outside reserved classes. Git owns commits, branches and ancestry. GitHub owns the live PR narrative, -reviews, finding threads, check statuses and merge state. Within a task worktree, -PR body writers lock the state directory from the live read through the update. -Review publication rechecks the round while holding a same-host lock keyed by -repository and PR. The lock covers POST and lost-response read-back. +reviews, finding threads, check statuses and merge state. PR body writers hold +the same-host repository-and-PR lock from the live read through the update. +Review publication holds that lock for its round recheck, POST, read-back, and +body summary. Check coalescing and receipts retain the worktree-local lock. CI and branch protection provide the hosted enforcement. Readiness is a checklist over these sources, not a tamper-proof security boundary: repository writers can edit PR evidence, diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index cb219532..6d45fbf9 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -572,15 +572,20 @@ def _append_review(body: str, result: ReviewResult) -> str: def _refresh_pr_checks(wt: Path, config: Config) -> None: """Best-effort refresh only when local HEAD is the existing PR head.""" try: - with worktree.lock_local_state(wt): - upstream = config_mod.run_git(wt, "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}") - if upstream.exit_code == 0: - branch, head = worktree.branch(wt), worktree.head(wt) - pr = github.pr_for_branch(config.repo, branch, open_only=True) - if pr is not None and pr.head_sha == head: - body = _pr_body(wt, head, config, pr.body) - if body != (pr.body or "").replace("\r\n", "\n"): - github.update_body(config.repo, pr.number, body) + upstream = config_mod.run_git(wt, "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}") + if upstream.exit_code != 0: + return + branch, head = worktree.branch(wt), worktree.head(wt) + pr = github.pr_for_branch(config.repo, branch, open_only=True) + if pr is None or pr.head_sha != head: + return + with github.pr_lock(config.repo, pr.number): + live = github.pr_view(config.repo, pr.number) + if live.state != "OPEN" or live.head_sha != head: + return + body = _pr_body(wt, head, config, live.body) + if body != live.body.replace("\r\n", "\n"): + github.update_body(config.repo, pr.number, body) except (github.GhError, _proc.ProcTimeout, OSError, ValueError, CliError, worktree.WorktreeError) as exc: print(f"note: could not refresh PR checks: {_one_line(exc)}", file=sys.stderr) @@ -726,7 +731,7 @@ def cmd_pr(args: argparse.Namespace) -> int: _require_push_target(wt, config.repo) _git_push(wt, push, force_lease=force_lease) if pr is not None: - with worktree.lock_local_state(wt): + with github.pr_lock(config.repo, pr.number): live = github.pr_view(config.repo, pr.number) if live.state != "OPEN": raise CliError(f"PR #{pr.number} closed during publication") @@ -887,12 +892,11 @@ def cmd_review(args: argparse.Namespace, wt: Path, config: Config) -> int: f"{exc} | publication unconfirmed; review saved at {path}; " "inspect the cause and run `loopzero review --repost` to reconcile or explicitly retry" ) from exc - try: - with worktree.lock_local_state(wt): + try: live = github.pr_view(config.repo, pr.number) github.update_body(config.repo, pr.number, _append_review(live.body, result)) - except (github.GhError, _proc.ProcTimeout, OSError, ValueError) as exc: - print(f"note: could not append PR review summary: {_one_line(exc)}", file=sys.stderr) + except (github.GhError, _proc.ProcTimeout, OSError, ValueError) as exc: + print(f"note: could not append PR review summary: {_one_line(exc)}", file=sys.stderr) return _review_verdict(result) diff --git a/tests/test_cli.py b/tests/test_cli.py index f2654626..f1b8a3ad 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -17,7 +17,7 @@ from email.utils import formatdate from pathlib import Path from select import select -from threading import Event +from threading import Event, current_thread, main_thread from types import SimpleNamespace from unittest.mock import Mock from urllib.parse import quote @@ -519,8 +519,8 @@ def test_check_refresh_preserves_local_verdict(wt, gh, capsys, monkeypatch, tmp_ monkeypatch.setattr(github, "update_body", Mock(side_effect=timeout)) code, out, err = run(capsys, *options, "check") assert (code, out.splitlines()[-1]) == ((1, "FAIL") if stage_exit else (0, "PASS")) - assert [call["argv"][:2] for call in gh.calls] == LOOKUP_CALLS + ( - [["api", endpoint]] if pushed and not refresh_timeout else []) + extra = [["api", endpoint]] * (2 - refresh_timeout) if pushed else [] + assert [call["argv"][:2] for call in gh.calls] == LOOKUP_CALLS + extra report = json.loads((wt / ".loopzero/checks.json").read_text()) assert report["head"] == head_of(wt) and report["dirty"] is False assert report["results"][0]["exit_code"] == stage_exit @@ -532,7 +532,7 @@ def test_check_refresh_preserves_local_verdict(wt, gh, capsys, monkeypatch, tmp_ if refresh_timeout: assert f"note: could not refresh PR checks: PATCH {endpoint} timed out" in err if pushed and not refresh_timeout: - body = json.loads(gh.calls[len(LOOKUP_CALLS)]["--input"])["body"] + body = json.loads(gh.calls[-1]["--input"])["body"] assert body.count("## Validation") == 1 assert_contains(body, f"Recorded for `{head_of(wt)[:12]}`", "- `echo ok`: exit 0") @@ -599,8 +599,7 @@ def test_pr_body_is_unchanged_when_checks_are_unchanged(wt: Path, gh: FakeGh, ca before = len(gh.calls) assert run(capsys, command)[0] == 0 history = HISTORY_CALLS if command == "pr" else [] - refresh = [["api", f"repos/{REPO}/pulls/7"]] if command == "pr" else [] - assert [c["argv"][:2] for c in gh.calls[before:]] == history + LOOKUP_CALLS + refresh + assert [c["argv"][:2] for c in gh.calls[before:]] == history + LOOKUP_CALLS + LOOKUP_CALLS[-1:] @pytest.mark.parametrize("body", [ @@ -628,23 +627,41 @@ def test_check_refresh_replaces_previous_head_without_losing_evidence( assert text in updated -def test_delayed_check_preserves_review_summary(wt, gh, fake_bin, capsys, monkeypatch): +def test_delayed_check_preserves_review_summary(wt, gh, fake_bin, tmp_path, monkeypatch): head = prepare_review(wt, gh, fake_bin) - body = "# PR\n\n## Notes\nHuman evidence.\n" - gh.respond_pr_list([pr_json(headRefOid=head, body=body)]) + detail = f"api repos/{REPO}/pulls/7" + gh.respond(detail, rest_pr_json(pr_json(headRefOid=head, body="# PR\n\nHuman evidence.\n"))) git(wt, "push", "-q", "-u", "origin", "lz/t1") - refresh = cli._refresh_pr_checks - - def delay(path, config): - assert run(capsys, "review")[0] == 0 - live = json.loads(gh.calls[-1]["--input"])["body"] - gh.respond(f"api repos/{REPO}/pulls/7", rest_pr_json(pr_json(headRefOid=head, body=live))) - refresh(path, config) - - monkeypatch.setattr(cli, "_refresh_pr_checks", delay) - assert run(capsys, "check")[0] == 0 + check = tmp_path / "check" + git(wt, "clone", "-q", "-b", "lz/t1", git(wt, "remote", "get-url", "origin").strip(), str(check)) + context = cli._context + monkeypatch.setattr(cli, "_context", lambda args, **kw: (check, config.load_trusted(check)) + if args.command == "check" else context(args, **kw)) + proceed, flock, update = Event(), github.fcntl.flock, github.update_body + + def acquire(fd, op): + if current_thread() is not main_thread() and op == github.fcntl.LOCK_EX: + try: + return flock(fd, op | github.fcntl.LOCK_NB) + except BlockingIOError: + proceed.set() + return flock(fd, op) + + pending = [] + with ThreadPoolExecutor(1) as pool: + def patch(repo, number, body): + if "## Review" not in body: + pending.append(pool.submit(cli.main, ["review"])) + assert proceed.wait(10) + update(repo, number, body) + gh.respond(detail, rest_pr_json(pr_json(headRefOid=head, body=body))) + proceed.set() + + monkeypatch.setattr(github.fcntl, "flock", acquire) + monkeypatch.setattr(github, "update_body", patch) + assert cli.main(["check"]) == pending[0].result(timeout=10) == 0 final = json.loads(gh.calls[-1]["--input"])["body"] - assert all(text in final for text in ("Human evidence.", "Recorded for", "- primary, claude")) + assert_contains(final, "Human evidence.", "Recorded for", "- primary, claude") @pytest.mark.parametrize("command,exit_code", [("check", 0), ("pr", 1)]) @@ -656,7 +673,7 @@ def test_malformed_live_markers_do_not_mask_check_verdict( gh.respond_pr_list([pr_json(headRefOid=head_of(wt), body=body)]) out, _ = expect_cli(capsys, exit_code, command, stderr_contains=("malformed loopzero checks block",)) history = HISTORY_CALLS if command == "pr" else [] - assert [c["argv"][:2] for c in gh.calls] == history + LOOKUP_CALLS + assert [c["argv"][:2] for c in gh.calls] == history + LOOKUP_CALLS + (LOOKUP_CALLS[-1:] if command == "check" else []) if command == "check": assert out.endswith("PASS\n") assert json.loads((wt / ".loopzero/checks.json").read_text())["results"][0]["exit_code"] == 0 @@ -1490,7 +1507,7 @@ def test_review_primary_posts_marker(wt: Path, gh: FakeGh, fake_bin: Path, capsy expected_diff = git(wt, "diff", "--no-color", "origin/main", head).encode("utf-8") git_calls.clear() out, _ = expect_cli(capsys, 5, "review", stderr="") - assert_git_cost(git_calls, 18, 1) + assert_git_cost(git_calls, 17, 1) assert out.splitlines()[0].startswith("reviewer paths pinned to origin/main@") assert out.splitlines()[-1] + "\n" == ( f"primary review by claude on {head[:12]}: request_changes " From 054df43e53f6aa3ac307afdc3a8e2a3e6225ea32 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:06:17 +0100 Subject: [PATCH 3/3] Share workflow table validation Architecture-Review: unchanged; trusted workflow selection and configuration keys, defaults, validation order and diagnostics are preserved. Co-Authored-By: Codex --- src/loopzero/config.py | 78 ++++++++++++++++++------------------------ 1 file changed, 34 insertions(+), 44 deletions(-) diff --git a/src/loopzero/config.py b/src/loopzero/config.py index 6fd5279d..6216971b 100644 --- a/src/loopzero/config.py +++ b/src/loopzero/config.py @@ -34,6 +34,7 @@ "review_chunk_bytes": int, "review": dict, }, } +_REVIEW_SETTINGS = {"model": str, "effort": str, "allowed_efforts": list} class ConfigError(LoopZeroError): @@ -151,64 +152,44 @@ def load_trusted(worktree: Path, *, previous: Config | None = None, refresh: boo def _build(data: dict[str, Any]) -> Config: _reject_unknown("top level", data, _SECTIONS) - for section, keys in _SECTIONS.items(): - table = data.get(section, {}) - if not isinstance(table, dict): - raise ConfigError(f"[{section}] must be a table") - _reject_unknown(f"[{section}]", table, keys) - for key, kind in keys.items(): - if key in table and not isinstance(table[key], kind): - raise ConfigError(f"{section}.{key} must be a {kind.__name__}") - - repo = data.get("repo", {}) - checks = data.get("checks", {}) - delivery = data.get("delivery", {}) - - if "name" not in repo: + sections = { + section: _check_table(section, data.get(section, {}), schema) + for section, schema in _SECTIONS.items() + } + repo, checks, delivery = sections["repo"], sections["checks"], sections["delivery"] + + if (name := repo.get("name")) is None: raise ConfigError("missing required key repo.name (\"owner/name\")") - name = repo["name"] if name.count("/") != 1 or not all(name.split("/")): raise ConfigError(f'repo.name must look like "owner/name", got {name!r}') - base = repo.get("base", "main") - if not base: + if not (base := repo.get("base", "main")): raise ConfigError("repo.base must not be empty") merge, mergify_queue = _merge_settings(delivery) reviewers = _strings("delivery.reviewers", delivery.get("reviewers", list(REVIEWER_FAMILIES))) if not reviewers: raise ConfigError("delivery.reviewers must list at least one reviewer") - for reviewer in reviewers: - if reviewer not in REVIEWER_FAMILIES: - raise ConfigError( - f"delivery.reviewers entries must be in {REVIEWER_FAMILIES}, got {reviewer!r}" - ) - review_chunk_bytes = delivery.get("review_chunk_bytes", 200_000) + if unknown := next((family for family in reviewers if family not in REVIEWER_FAMILIES), None): + raise ConfigError(f"delivery.reviewers entries must be in {REVIEWER_FAMILIES}, got {unknown!r}") + review_chunk_bytes = delivery.get("review_chunk_bytes", Config.review_chunk_bytes) if isinstance(review_chunk_bytes, bool) or review_chunk_bytes < 4096: raise ConfigError("delivery.review_chunk_bytes must be an int >= 4096") review: dict[str, ReviewConfig] = {} for family, table in delivery.get("review", {}).items(): if family not in REVIEWER_FAMILIES: raise ConfigError(f"unknown review family delivery.review.{family}") - if not isinstance(table, dict): - raise ConfigError(f"[delivery.review.{family}] must be a table") 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"{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)) + table = _check_table(label, table, _REVIEW_SETTINGS, nonempty_strings=True) + review[family] = ReviewConfig( + table.get("model"), table.get("effort"), _strings(f"{label}.allowed_efforts", table.get("allowed_efforts", [])), + ) 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"]) - if not runner or any(not arg or "\0" in arg for arg in runner): + if not (runner := _strings("checks.runner", checks["runner"])) or any("\0" in arg for arg in runner): raise ConfigError("checks.runner must be a nonempty argv prefix") if "/" in runner[0] and not Path(runner[0]).is_absolute(): raise ConfigError("checks.runner executable paths must be absolute") @@ -236,10 +217,8 @@ def _build(data: dict[str, Any]) -> Config: if "runner" in checks and checks["limits"]: keys = ", ".join(f"checks.limits.{key}" for key in sorted(checks["limits"])) raise ConfigError(f"{keys} apply only to local checks and cannot be set with checks.runner") - reviewer_ro_paths = _host_paths( - "delivery.reviewer_ro_paths", delivery.get("reviewer_ro_paths", []) - ) return Config( + reviewer_ro_paths=_host_paths("delivery.reviewer_ro_paths", delivery.get("reviewer_ro_paths", [])), repo=name, base_branch=base, checks=commands, @@ -250,7 +229,6 @@ def _build(data: dict[str, Any]) -> Config: review_publishers=_strings("delivery.review_publishers", delivery.get("review_publishers", [])), review=review, - reviewer_ro_paths=reviewer_ro_paths, review_chunk_bytes=review_chunk_bytes, network=checks.get("network", False), inputs=inputs, env=env, **kwargs, @@ -258,8 +236,7 @@ def _build(data: dict[str, Any]) -> Config: def _merge_settings(delivery: dict[str, Any]) -> tuple[str, str | None]: - merge = delivery.get("merge", "squash") - if merge not in MERGE_STRATEGIES: + if (merge := delivery.get("merge", "squash")) not in MERGE_STRATEGIES: raise ConfigError(f"delivery.merge must be one of {MERGE_STRATEGIES}, got {merge!r}") mergify_queue = delivery.get("mergify_queue") if merge == "mergify": @@ -272,9 +249,22 @@ def _merge_settings(delivery: dict[str, Any]) -> tuple[str, str | None]: return merge, mergify_queue +def _check_table(label: str, table: Any, schema: dict[str, type], *, + nonempty_strings: bool = False) -> dict[str, Any]: + if not isinstance(table, dict): + raise ConfigError(f"[{label}] must be a table") + _reject_unknown(f"[{label}]", table, schema) + for key, kind in schema.items(): + if key in table: + nonempty = nonempty_strings and kind is str + if not isinstance(table[key], kind) or (nonempty and not table[key]): + expected = "non-empty str" if nonempty else kind.__name__ + raise ConfigError(f"{label}.{key} must be a {expected}") + return table + + def _reject_unknown(where: str, table: dict[str, Any], allowed: Any) -> None: - unknown = sorted(set(table) - set(allowed)) - if unknown: + if unknown := sorted(set(table) - set(allowed)): raise ConfigError(f"unknown key(s) in {where}: {', '.join(unknown)}")