From 0b6b62cf1b9247b11ccbd9d25f666255963a047b Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:04:35 +0100 Subject: [PATCH 1/3] Deduplicate CLI readiness and command plumbing Architecture-Review: unchanged; command entry points, trusted configuration, review locking, and readiness policy retain their existing boundaries. Co-Authored-By: Codex --- src/loopzero/cli.py | 136 +++++++++++++++++++------------------------- 1 file changed, 58 insertions(+), 78 deletions(-) diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index cb219532..8b4c87bc 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -21,7 +21,7 @@ import tempfile import time from collections.abc import Callable, Iterator -from contextlib import suppress +from contextlib import ExitStack, suppress from functools import partial, wraps from pathlib import Path @@ -137,11 +137,9 @@ def _load_config( return config -def _context(args: argparse.Namespace, *, pin_checks: bool = False) -> tuple[Path, Config]: +def _context(args: argparse.Namespace, *, pin_checks: bool = True) -> tuple[Path, Config]: wt = _toplevel() - return wt, _load_config( - args, wt, pin_checks=pin_checks, refresh=args.command in {"ready", "merge"}, - ) + return wt, _load_config(args, wt, pin_checks=pin_checks, refresh=args.command in {"ready", "merge"}) def _is_ancestor(wt: Path, sha: str, head: str) -> bool: @@ -269,13 +267,10 @@ def _conflict_delta_base(config: Config, pr: github.PR, head: str, reviews: list if len({primary, reviewed, head}) != 3: return None publishers = publishers or (github.login(),) - if not eligibility.approved_delta(reviews, reviewed, publishers, repo=config.repo, number=pr.number): - return None - if eligibility.base_merge_material( - config.repo, pr.number, reviewed, head, config.base_branch, clean=False, conflict_only=True, - ) is None: - return None - if github.open_blocking_findings(config.repo, pr.number, None, publishers): + if (not eligibility.approved_delta(reviews, reviewed, publishers, repo=config.repo, number=pr.number) + or eligibility.base_merge_material( + config.repo, pr.number, reviewed, head, config.base_branch, clean=False, conflict_only=True, + ) is None or github.open_blocking_findings(config.repo, pr.number, None, publishers)): return None return reviewed @@ -288,31 +283,17 @@ def _select_review_round(config: Config, pr: github.PR, head: str, reviews: list return _decide_kind(markers, head) -def _review_cap_reason(config: Config, pr: github.PR, head: str, reviews: list[dict], - markers: list[Marker], publishers: tuple[str, ...]) -> str: - if _conflict_delta_base(config, pr, head, reviews, markers, publishers): - return f"Run `loopzero review` for the available conflict-resolution delta on {head[:12]}." - return ( - f"The review budget is exhausted and {head[:12]} has no eligible review. " - "Open a replacement PR for changes that need review. Another `loopzero review` on this PR will be refused." - ) - - MERGEABILITY_PENDING = github.MERGEABILITY_PENDING -def _readiness_precheck(wt: Path, config: Config, pr: github.PR, head: str, diagnostics: bool) -> str | None: - return github.merge_hold(pr.number, pr.labels) or ( - None if diagnostics else _check_report_problem(_load_report(wt), config, head) - ) - - def _readiness( wt: Path, config: Config, pr: github.PR, head: str, reviews: list[dict] | None = None, *, workflow_wait: bool = False, announce_receipt: bool = False, diagnostics: bool = False, mergify_deadline: float | None = None, ) -> github.Readiness: - if problem := _readiness_precheck(wt, config, pr, head, diagnostics): + if problem := github.merge_hold(pr.number, pr.labels) or ( + None if diagnostics else _check_report_problem(_load_report(wt), config, head) + ): return github.Readiness(False, (problem,)) dates: list[str] = [] reviews = (_pr_reviews(config.repo, pr.number, **({"dates": dates} if workflow_wait else {})) @@ -351,15 +332,21 @@ def _readiness( if github.MISSING_REVIEW_REASON in result.reasons: markers = _pr_markers(reviews, head, publishers, repo=config.repo, number=pr.number) if _review_cap_spent(markers) and all(marker.head != head for marker in markers): - exhausted = _review_cap_reason(config, pr, head, reviews, markers, publishers) + if _conflict_delta_base(config, pr, head, reviews, markers, publishers): + exhausted = f"Run `loopzero review` for the available conflict-resolution delta on {head[:12]}." + else: + exhausted = ( + f"The review budget is exhausted and {head[:12]} has no eligible review. " + "Open a replacement PR for changes that need review. Another `loopzero review` on this PR will be refused." + ) result = dataclasses.replace(result, reasons=tuple( exhausted if reason == github.MISSING_REVIEW_REASON else reason for reason in result.reasons )) report = _load_report(wt) receipt_problem = _check_report_problem(report, config, head) if receipt_problem: - result = github.Readiness(False, (*result.reasons, receipt_problem)) - elif announce_receipt: + return github.Readiness(False, (*result.reasons, receipt_problem)) + if announce_receipt: _print_receipt(wt, report, "accepted") return result @@ -462,13 +449,11 @@ def _validation_section(wt: Path, head: str, config: Config) -> str: loaded = _load_report(wt) if loaded is None: return "(no `loopzero check` run recorded)" - recorded, results = loaded.head, loaded.results - lines = [f"Recorded for `{recorded[:12]}`" + ("" if recorded == head else " (not current head)")] + heading = f"Recorded for `{loaded.head[:12]}`" + ("" if loaded.head == head else " (not current head)") if _check_report_problem(loaded, config, head, require_pass=False): - lines[0] += " (unverified, run `loopzero check`)" - lines += [f"- `{github.redact_credentials(r.command)}`: exit {r.exit_code}" - for r in results] or ["- (no check commands configured)"] - return "\n".join(lines) + heading += " (unverified, run `loopzero check`)" + results = [f"- `{github.redact_credentials(r.command)}`: exit {r.exit_code}" for r in loaded.results] + return "\n".join([heading, *(results or ["- (no check commands configured)"])]) _CHECKS_START = "" @@ -624,7 +609,7 @@ def _check_failure_preview(tail: str, limit: int = 1536) -> str: def cmd_check(args: argparse.Namespace) -> int: - wt, config = _context(args, pin_checks=True) + wt, config = _context(args) worktree.local_state_files(wt, CHECKS_FILE.name) if not config.checks: raise config_mod.ConfigError("checks.commands must list at least one command to run checks") @@ -692,7 +677,7 @@ def _finish_check(wt: Path, config: Config, report: CheckReport, locked_fd: int) def cmd_pr(args: argparse.Namespace) -> int: - wt, config = _context(args, pin_checks=True) + wt, config = _context(args) branch, head = worktree.branch(wt), worktree.head(wt) _require_task_branch(config, branch) _require_clean(wt) @@ -779,18 +764,16 @@ def _require_review_pr(config: Config, branch: str, *, repost: bool) -> github.P def _lock_review(run_review: Callable[[argparse.Namespace, Path, Config], int]): @wraps(run_review) def locked(args: argparse.Namespace) -> int: - wt, config = _context(args, pin_checks=True) + wt, config = _context(args) git_dir = _git(wt, "rev-parse", "--absolute-git-dir", paths=True) - fd = os.open(git_dir, os.O_RDONLY | os.O_DIRECTORY) - try: + with ExitStack() as cleanup: + fd = os.open(git_dir, os.O_RDONLY | os.O_DIRECTORY) + cleanup.callback(os.close, fd) try: fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) except BlockingIOError as exc: raise CliError("review already running in this worktree") from exc return run_review(args, wt, config) - finally: - os.close(fd) - return locked @@ -1321,8 +1304,13 @@ def _warn_queue_size( print(f"warning: projected size budget after {predecessors}:\n{result.stdout.rstrip()}") +def _mark_ready(wt: Path, config: Config, number: int, head: str) -> None: + _require_receipt(wt, config, head) + github.mark_ready(config.repo, number) + + def cmd_ready(args: argparse.Namespace) -> int: - wt, config = _context(args, pin_checks=True) + wt, config = _context(args) read_started = time.monotonic() pr, readiness = _pr_readiness(wt, config, worktree.branch(wt), workflow_wait=args.wait is not None) assert readiness is not None @@ -1332,8 +1320,7 @@ def cmd_ready(args: argparse.Namespace) -> int: wait = partial(_wait_with_deadline, wt, config, timeout=args.wait, started=started, args=args, allow_skipped=True, initial_read_time=started - read_started) if waiting: - _require_receipt(wt, config, pr.head_sha) - github.mark_ready(config.repo, pr.number) + _mark_ready(wt, config, pr.number, pr.head_sha) if args.wait is None: pending = f"; {MERGEABILITY_PENDING}" if pr.mergeable == "UNKNOWN" else "" print(f"marked ready; waiting for required checks: {', '.join(waiting)}{pending}; {NEXT_WAIT}") @@ -1342,20 +1329,17 @@ def cmd_ready(args: argparse.Namespace) -> int: if args.wait is not None and ( waiting or _pending_checks(config, pr, readiness, allow_skipped=not pr.is_draft) ): - waited = wait(pr, kicked=kicked, shown=readiness.reasons if kicked else (), - initial=None if kicked else readiness) - if waited is None: + if (waited := wait(pr, kicked=kicked, shown=readiness.reasons if kicked else (), + initial=None if kicked else readiness)) is None: return 3 pr, readiness, kicked = waited _prequeue_size_budget(wt, config, pr, readiness) if readiness.ready and pr.is_draft and not kicked: - _require_receipt(wt, config, pr.head_sha) - github.mark_ready(config.repo, pr.number) + _mark_ready(wt, config, pr.number, pr.head_sha) if args.wait is not None: - waited = wait(pr, kicked=True) - if waited is None: + if (waited := wait(pr, kicked=True)) is None: return 3 - pr, readiness, kicked = waited + pr, readiness, _ = waited for reason in _readiness_messages(pr, readiness): print(f"not ready: {reason}") if not readiness.ready: @@ -1460,27 +1444,25 @@ def _wait_with_deadline( if timeout == 0: return wait() deadline = started + timeout - if time.monotonic() >= deadline: - _print_check_wait_timeout(pr, args) - return None reported_timeout = False try: - with github.bounded_reads(deadline, token=None, retry=True): - waited = wait(bounded=True, initial_read_time=initial_read_time) - reported_timeout = waited is None + if time.monotonic() < deadline: + with github.bounded_reads(deadline, token=None, retry=True): + waited = wait(bounded=True, initial_read_time=initial_read_time) + reported_timeout = waited is None + return waited except (github.ReadDeadline, _proc.ProcTimeout) as exc: if isinstance(exc, _proc.ProcTimeout) and time.monotonic() < deadline: raise - if not reported_timeout: - _print_check_wait_timeout(pr, args) - return None - return waited + if not reported_timeout: + _print_check_wait_timeout(pr, args) + return None -def _print_check_wait_timeout(pr: github.PR, args: argparse.Namespace | None) -> None: +def _print_check_wait_timeout(pr: github.PR, args: argparse.Namespace) -> None: waiting_for = "GitHub to compute mergeability" if pr.mergeable == "UNKNOWN" else "required checks" - command = ["loopzero", args.command if args else "ready", "--wait"] - if args and args.config: + command = ["loopzero", args.command, "--wait"] + if args.config: command.insert(1, f"--config={args.config}") print( f"timed out waiting for {waiting_for} on {pr.head_sha[:12]}. " @@ -1488,12 +1470,12 @@ def _print_check_wait_timeout(pr: github.PR, args: argparse.Namespace | None) -> ) def _verify_wait_snapshot( - args: argparse.Namespace | None, wt: Path, config: Config, head: str, current_head: str, + args: argparse.Namespace, wt: Path, config: Config, head: str, current_head: str, previous: Config, ) -> Config: if current_head != head: raise CliError(f"PR head changed while waiting: {head[:12]} to {current_head[:12]}") - latest = config if args is None else _load_config(args, wt, pin_checks=True, previous=previous, refresh=True) + latest = _load_config(args, wt, pin_checks=True, previous=previous, refresh=True) if latest == config: return latest retry = "retry with the current settings" if _current_check_report(wt, latest, head) else "run loopzero check and retry" @@ -1512,14 +1494,13 @@ def by_check(reasons: tuple[str, ...]) -> dict[str, str]: def _wait_for_checks( wt: Path, config: Config, pr: github.PR, timeout: float, *, kicked: bool, - started: float | None = None, shown: tuple[str, ...] = (), - args: argparse.Namespace | None = None, bounded: bool = False, allow_merged: bool = False, + started: float, args: argparse.Namespace, shown: tuple[str, ...] = (), + bounded: bool = False, allow_merged: bool = False, allow_skipped: bool = False, initial: github.Readiness | None = None, initial_read_time: float = 0.0, ) -> tuple[github.PR, github.Readiness | None, bool] | None: """Poll the same head until it settles, omitting readiness for an allowed merge.""" grace_started = time.monotonic() - started = grace_started if started is None else started current = pr stale_notice = False previous = config @@ -1535,8 +1516,7 @@ def _wait_for_checks( readiness = _readiness(wt, config, current, pr.head_sha, workflow_wait=True, mergify_deadline=started + timeout) if not kicked and _draft_checks_waiting(config, current, readiness): - _require_receipt(wt, config, current.head_sha) - github.mark_ready(config.repo, pr.number) + _mark_ready(wt, config, pr.number, current.head_sha) print("marked ready; " + "; ".join(readiness.reasons)) return _wait_for_checks(wt, config, pr, timeout, kicked=True, started=started, shown=readiness.reasons, args=args, bounded=bounded, @@ -1771,7 +1751,7 @@ def _merge_with_mergify( def cmd_merge(args: argparse.Namespace) -> int: if args.cancel and args.wait is not None: raise CliError("merge --cancel cannot be combined with --wait") - wt, config = _context(args, pin_checks=True) + wt, config = _context(args) branch = worktree.branch(wt) if args.cancel: if config.merge_strategy != "mergify": 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)}")