diff --git a/SETUP.md b/SETUP.md index be726773..4747e04d 100644 --- a/SETUP.md +++ b/SETUP.md @@ -509,6 +509,12 @@ the consumer CI pin that supplies `loopzero.hosted` or `loopzero.eligibility` eligibility workflow for the existing PR, or run the command below with its unchanged source SHA. The refreshed reader can use the approval already on GitHub. +For inherited review coverage, advance both source and candidate workflow pins to +a revision containing [23219dd3 (#1081)](https://github.com/feder-positronics/loop-zero/commit/23219dd39e641549164c346e137f4e09718115f6). +The updated reader accepts an ancestor approval only across verified clean merges +from the configured base. After deploying both pins, refresh eligibility for open +sources judged by the older reader so their statuses reflect the updated policy. + From a trusted base checkout, run: ```sh diff --git a/scripts/ai-accounts/ai-accounts b/scripts/ai-accounts/ai-accounts index bf9d96d1..5c4c901d 100755 --- a/scripts/ai-accounts/ai-accounts +++ b/scripts/ai-accounts/ai-accounts @@ -56,8 +56,10 @@ import os import re import shutil import signal +import stat import subprocess import sys +import tempfile import threading import time import urllib.error @@ -115,11 +117,14 @@ def notify(msg: str) -> None: def write_private(path: Path, text: str) -> None: path.parent.mkdir(parents=True, exist_ok=True, mode=0o700) - tmp = path.with_name(f"{path.name}.{os.getpid()}.{threading.get_ident()}.tmp") - fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) - with os.fdopen(fd, "w", encoding="utf-8") as fh: - fh.write(text) - os.replace(tmp, path) + fd, staged = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent) + try: + with os.fdopen(fd, "w", encoding="utf-8") as fh: + fh.write(text) + os.replace(staged, path) + except BaseException: + Path(staged).unlink(missing_ok=True) + raise # ----------------------------------------------------------------- accounts @@ -171,7 +176,10 @@ class AccountLockTimeout(TimeoutError): @contextmanager def _locked(name: str): - with (STATE / name).open("a") as lock: + fd = os.open(STATE / name, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW | os.O_NONBLOCK, 0o600) + with os.fdopen(fd, "rb") as lock: + if not stat.S_ISREG(os.fstat(lock.fileno()).st_mode): + raise ValueError(f"{name} is not a regular lock file") deadline = time.monotonic() + 60 while (remaining := deadline - time.monotonic()) > 0: try: 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()) diff --git a/tests/test_ai_accounts.py b/tests/test_ai_accounts.py index 82041ff8..c161c052 100644 --- a/tests/test_ai_accounts.py +++ b/tests/test_ai_accounts.py @@ -570,3 +570,26 @@ def open_(*args, **kwargs): monkeypatch.setattr(helper.urllib.request, "urlopen", open_) with pytest.raises(TimeoutError, match="provider HTTP request timed out"): helper._http(request, timeout=1) + + +@pytest.mark.parametrize("symlink", [False, True]) +def test_account_staging_preserves_colliding_path(helper, tmp_path, symlink): + path = helper.STATE / "status.json" + staged = path.with_name(f"{path.name}.{helper.os.getpid()}.{helper.threading.get_ident()}.tmp") + target = tmp_path / "unrelated" if symlink else staged + target.write_text("preserve") + if symlink: + staged.symlink_to(target) + helper.write_private(path, "{}") + assert path.read_text() == "{}" and target.read_text() == "preserve" + + +def test_account_lock_preserves_existing_file_and_rejects_symlink(helper): + lock = helper.STATE / ".lock" + lock.write_text("preserve") + with helper._locked(lock.name): + assert lock.read_text() == "preserve" + (helper.STATE / ".codex-sync.lock").symlink_to(lock) + with pytest.raises(OSError), helper._locked(".codex-sync.lock"): + pytest.fail("redirected lock opened") + assert lock.read_text() == "preserve" diff --git a/tests/test_hosted.py b/tests/test_hosted.py index 26e83553..08e1dfd0 100644 --- a/tests/test_hosted.py +++ b/tests/test_hosted.py @@ -3,6 +3,7 @@ import subprocess import sys from contextlib import nullcontext +from functools import partial from pathlib import Path from types import SimpleNamespace @@ -11,6 +12,7 @@ from loopzero import github, hosted from loopzero.candidate import CandidateError, CandidateRaceError from tests import test_github as fixtures +from tests.conftest import git from tests.test_candidate import event as candidate_event from tests.test_candidate import payloads as candidate_payloads from tests.test_candidate import status as candidate_status @@ -108,6 +110,58 @@ def test_source_publication_is_bound_to_live_review(publisher, case, blocker, st assert status != "pending" or statuses[-1]["description"] == "Awaiting trusted review of current source head" +@pytest.mark.parametrize("candidate", [False, True]) +@pytest.mark.parametrize("change", ["exact", "ordinary", "clean merge"]) +def test_hosted_review_coverage_after_source_head_changes( + publisher, git_repo, monkeypatch, candidate, change, +): + git(git_repo, "switch", "-qc", "source") + git(git_repo, "commit", "-qm", "reviewed source", "--allow-empty") + reviewed = git(git_repo, "rev-parse", "HEAD").strip() + git(git_repo, "switch", "-q", "main") + git(git_repo, "commit", "-qm", "base advance", "--allow-empty") + base = git(git_repo, "rev-parse", "HEAD").strip() + git(git_repo, "switch", "-q", "source") + if change == "ordinary": + git(git_repo, "commit", "-qm", "unreviewed source", "--allow-empty") + elif change == "clean merge": + git(git_repo, "merge", "-q", "--no-edit", "main") + head = git(git_repo, "rev-parse", "HEAD").strip() + source = fixtures.rest_pr_json(pr_json(headRefOid=head)) + source["base"]["sha"] = base + publisher.respond(f"api repos/{REPO}/pulls/7", source) + publisher.respond(f"api repos/{REPO}/pulls/7/reviews?per_page=100&page=1", [{ + "state": "COMMENTED", "commit_id": reviewed, "user": {"login": "trusted-publisher"}, + "body": f"\n" + "loopzero primary review by claude: **approve** (0 critical, 0 important, 0 suggestion)", + }]) + publisher.respond(f"api repos/{REPO}/compare/{reviewed}...{head}", {"status": "ahead"}) + monkeypatch.setattr(hosted.candidate_mod, "fetched_git", + lambda *_: nullcontext(partial(git, git_repo))) + + target = head + if candidate: + target = HEAD + Path("event.json").write_text(json.dumps({ + "action": "opened", "pull_request": {"number": 9, "head": {"sha": target}}, + })) + publisher.respond(f"api repos/{REPO}/pulls/9", fixtures.rest_pr_json( + pr_json(number=9, headRefOid=target), branch="mergify/merge-queue/main", + )) + monkeypatch.setattr(hosted.candidate_mod, "attest_candidate", + lambda _event, *, source_policy, **_: source_policy(7, source)) + publisher.respond(f"api repos/{REPO}/statuses/{target}", {}) + + if change == "ordinary" and candidate: + with pytest.raises(hosted.LoopZeroError, match="no review recorded"): + hosted.main() + else: + assert hosted.main() == 0 + states = [json.loads(call["--input"])["state"] for call in publisher.calls if "--input" in call] + assert states == ["pending", ("failure" if candidate else "pending") + if change == "ordinary" else "success"] + + def test_merged_source_refresh_publishes_nothing(publisher): body = json.dumps({"head": {"sha": HEAD, "ref": "lz/task"}, "user": {"login": "author"}, "merged": True, "title": "before\u2028after"}, ensure_ascii=False)