diff --git a/src/loopzero/candidate.py b/src/loopzero/candidate.py index e1beb361..38a68c8a 100644 --- a/src/loopzero/candidate.py +++ b/src/loopzero/candidate.py @@ -165,51 +165,30 @@ def _candidate_lineage(status: JsonObject, candidate_number: int) -> tuple[str, return candidate_id, sorted(source_numbers), sorted(missing) +def _repo_identity(repo: JsonObject) -> tuple[object, object]: + return repo.get("id"), repo.get("full_name") + + def _candidate_snapshot( - candidate: JsonObject, - *, - event_pr: JsonObject, - repository: JsonObject, + candidate: JsonObject, number: int, event_head: JsonObject, repository: JsonObject, expected_identity: tuple[object, object, object, object], ) -> None: - _require( - candidate.get("number") == event_pr.get("number"), - "GitHub returned the wrong candidate PR", - ) - _require(candidate.get("state") != "closed", "Mergify candidate PR is superseded (closed)") - _require(candidate.get("state") == "open", "Mergify candidate PR is not open") + _require(candidate.get("number") == number, "GitHub returned the wrong candidate PR") + state = candidate.get("state") + state_error = "Mergify candidate PR is superseded (closed)" if state == "closed" else "Mergify candidate PR is not open" + _require(state == "open", state_error) _require(candidate.get("draft") is True, "Mergify candidate PR must be a draft") - _require( - _identity(candidate.get("user")) == expected_identity, - "Candidate author is not the verified Mergify GitHub App", - ) - head = candidate.get("head") - event_head = event_pr.get("head") - base = candidate.get("base") - _require( - isinstance(head, dict) and isinstance(event_head, dict) and isinstance(base, dict), - "Candidate refs are missing", - ) - _require( - head.get("sha") == event_head.get("sha"), - "Candidate head changed after the workflow event", - ) - _require( - head.get("ref") == event_head.get("ref") - and isinstance(head.get("ref"), str) - and head["ref"].startswith(QUEUE_BRANCH_PREFIX), - "Mergify candidate has an unexpected head ref", - ) - _require( - base.get("ref") == "main", - "Mergify candidate must target the real main branch", - ) - expected_repo = (repository.get("id"), repository.get("full_name")) + _require(_identity(candidate.get("user")) == expected_identity, + "Candidate author is not the verified Mergify GitHub App") + head, base = candidate.get("head"), candidate.get("base") + _require(isinstance(head, dict) and isinstance(base, dict), "Candidate refs are missing") + _require(head.get("sha") == event_head.get("sha"), "Candidate head changed after the workflow event") + _require(head.get("ref") == event_head.get("ref"), "Mergify candidate has an unexpected head ref") + _require(base.get("ref") == "main", "Mergify candidate must target the real main branch") + expected_repo = _repo_identity(repository) for label, repo in (("head", head.get("repo")), ("base", base.get("repo"))): - _require( - isinstance(repo, dict) and (repo.get("id"), repo.get("full_name")) == expected_repo, - f"Mergify candidate {label} repository does not match this repository", - ) + _require(isinstance(repo, dict) and _repo_identity(repo) == expected_repo, + f"Mergify candidate {label} repository does not match this repository") def _source_fingerprint(source: JsonObject) -> tuple[object, ...]: @@ -263,8 +242,7 @@ def _attest_source( _require( base.get("ref") == "main" and isinstance(base_repo, dict) - and (base_repo.get("id"), base_repo.get("full_name")) - == (repository.get("id"), repository.get("full_name")), + and _repo_identity(base_repo) == _repo_identity(repository), f"source PR #{number} does not target this repository's main branch", ) source_sha = head.get("sha") @@ -503,8 +481,7 @@ def _attest_candidate_once( candidate_path = f"/repos/{full_name}/pulls/{candidate_number}" def recheck_candidate(message: str = "GitHub candidate lookup returned an invalid payload") -> None: candidate = _object(github_get(candidate_path), message) - _candidate_snapshot(candidate, event_pr=event_pr, repository=repository, - expected_identity=expected_identity) + _candidate_snapshot(candidate, candidate_number, event_head, repository, expected_identity) recheck_candidate() @@ -590,6 +567,4 @@ def live_lineage() -> tuple[str, list[int], list[str]]: f"source PR #{number} metadata changed during attestation", CandidateRaceError, ) - return [ - {"number": number, "head_sha": source_snapshots[number][0]} for number in first_lineage[1] - ] + return [{"number": number, "head_sha": sha} for number, (sha, _) in source_snapshots.items()] diff --git a/src/loopzero/config.py b/src/loopzero/config.py index baca4af6..97db3d8f 100644 --- a/src/loopzero/config.py +++ b/src/loopzero/config.py @@ -90,12 +90,11 @@ def _has_replacement_refs(common_dir: Path) -> bool: return True return True try: - packed = (common_dir / "packed-refs").read_bytes() + return b" refs/replace/" in (common_dir / "packed-refs").read_bytes() except FileNotFoundError: return False except OSError: return True - return b" refs/replace/" in packed def _remote_workflow(worktree: Path, branch: str, previous: Config | None, *, @@ -104,11 +103,8 @@ def _remote_workflow(worktree: Path, branch: str, previous: Config | None, *, hint = "Fetch the trusted base workflow, or supply --config for bootstrap or an override." ref = f"refs/remotes/origin/{branch}" if refresh: - fetched = _proc.run( - ["git", "fetch", "--quiet", "--no-tags", "--no-recurse-submodules", - "--no-write-fetch-head", "origin", f"+refs/heads/{branch}:{ref}"], - cwd=worktree, env_allowlist=worktree_mod.GIT_ENV, timeout=read_timeout(60), - ) + fetched = run_git(worktree, "fetch", "--quiet", "--no-tags", "--no-recurse-submodules", + "--no-write-fetch-head", "origin", f"+refs/heads/{branch}:{ref}", timeout=read_timeout(60)) if fetched.exit_code != 0: raise ConfigError(f"could not refresh origin/{branch}. {hint}") directory_args = ["--path-format=absolute", "--git-common-dir"] if previous is not None else [] @@ -129,13 +125,12 @@ def _remote_workflow(worktree: Path, branch: str, previous: Config | None, *, if shown.exit_code != 0: raise ConfigError(f"cannot read {source}. {hint}") try: - data = tomllib.loads(shown.stdout.encode("utf-8", errors="surrogateescape").decode("utf-8")) + text = shown.stdout.encode("utf-8", errors="surrogateescape").decode("utf-8") + return _build(tomllib.loads(text)), revision except UnicodeDecodeError as exc: raise ConfigError(f"{source}: {exc}") from exc except tomllib.TOMLDecodeError as exc: raise ConfigError(f"{source}: invalid TOML: {exc}. {hint}") from None - try: - return _build(data), revision except ConfigError as exc: raise ConfigError(f"{source}: {exc}. {hint}") from None @@ -153,12 +148,12 @@ def load_trusted(worktree: Path, *, previous: Config | None = None, refresh: boo ) branch = ref.removeprefix(prefix) policy, revision = _remote_workflow(worktree, branch, previous, refresh=refresh, read_timeout=read_timeout) - if policy.base_branch == branch: - return replace(policy, trusted_base_revision=revision) - base, revision = _remote_workflow(worktree, policy.base_branch, previous, refresh=refresh, read_timeout=read_timeout) - if base.base_branch != policy.base_branch: - raise ConfigError("trusted origin workflows disagree on repo.base; align them or supply --config") - return replace(base, trusted_base_revision=revision) + if policy.base_branch != branch: + branch = policy.base_branch + policy, revision = _remote_workflow(worktree, branch, previous, refresh=refresh, read_timeout=read_timeout) + if policy.base_branch != branch: + raise ConfigError("trusted origin workflows disagree on repo.base; align them or supply --config") + return replace(policy, trusted_base_revision=revision) def _build(data: dict[str, Any]) -> Config: @@ -225,21 +220,18 @@ def _build(data: dict[str, Any]) -> Config: if "/" in runner[0] and not Path(runner[0]).is_absolute(): raise ConfigError("checks.runner executable paths must be absolute") kwargs["check_runner"] = runner - if "inputs" in checks: - inputs = {} - for key, value in checks["inputs"].items(): - label = f'checks.inputs."{key}"' - if key != "*" and key not in commands: - raise ConfigError(f"{label} must exactly match a checks.commands entry") - inputs[key] = _strings(label, value) - kwargs["inputs"] = inputs + inputs = {} + for key, value in checks.get("inputs", {}).items(): + label = f'checks.inputs."{key}"' + if key != "*" and key not in commands: + raise ConfigError(f"{label} must exactly match a checks.commands entry") + inputs[key] = _strings(label, value) 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"]) + env = _env_table(checks.get("env", {})) if "scratch" in checks: kwargs["scratch"] = _strings("checks.scratch", checks["scratch"]) for entry in kwargs["scratch"]: @@ -268,7 +260,7 @@ def _build(data: dict[str, Any]) -> Config: reviewer_ro_paths=reviewer_ro_paths, review_chunk_bytes=review_chunk_bytes, network=checks.get("network", False), - **kwargs, + inputs=inputs, env=env, **kwargs, ) @@ -326,8 +318,7 @@ def _env_table(table: dict[str, Any]) -> tuple[tuple[str, str], ...]: def _limits(table: dict[str, Any]) -> ResourceLimits: defaults = ResourceLimits() - allowed = tuple(defaults.__dict__) - _reject_unknown("checks.limits", table, allowed) + _reject_unknown("checks.limits", table, defaults.__dict__) values = defaults.__dict__ | table for name, value in values.items(): if isinstance(value, bool) or not isinstance(value, int) or value <= 0: diff --git a/src/loopzero/hosted.py b/src/loopzero/hosted.py index 24046c22..8a9fdd12 100644 --- a/src/loopzero/hosted.py +++ b/src/loopzero/hosted.py @@ -4,7 +4,6 @@ import json import os import sys -from collections.abc import Callable from contextlib import suppress from pathlib import Path @@ -71,10 +70,9 @@ def _run(cfg: Config) -> int: head = pr["head"]["sha"] candidate = (pr["head"]["ref"].startswith("mergify/merge-queue/") or pr["user"]["login"] == "mergify[bot]") - if not candidate and pr.get("merged") is True: + active = _candidate_event(event, head) if candidate else pr.get("merged") is not True + if not active: return 0 # A landed source needs no new verdict; a late refresh must not turn it red. - if candidate and not _candidate_event(event, head): - return 0 def publish(state: str, message: str) -> None: github.commit_status(cfg.repo, head, eligibility.CONTEXT, state, message[:140]) publish("pending", "Refreshing live source review evidence") @@ -110,7 +108,9 @@ def policy(source_number: int, source: dict) -> None: print(f"Eligibility pending: evidence unavailable ({exc})", file=sys.stderr) return 0 except Exception as exc: - _mark_refresh_failed(publish, exc) + if not isinstance(exc, github.StatusLimitReached): + with suppress(Exception): + publish("failure", "Eligibility refresh failed; inspect workflow logs") raise _publish_verdict(cfg.repo, head, state, message[:140]) print(message) @@ -142,11 +142,5 @@ def _publish_verdict(repo: str, head: str, state: str, description: str) -> None raise LoopZeroError(f"Could not confirm eligibility status publication: {exc}") from exc -def _mark_refresh_failed(publish: Callable[[str, str], None], exc: Exception) -> None: - if not isinstance(exc, github.StatusLimitReached): - with suppress(Exception): - publish("failure", "Eligibility refresh failed; inspect workflow logs") - - if __name__ == "__main__": raise SystemExit(main())