Skip to content
Closed
6 changes: 6 additions & 0 deletions SETUP.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
20 changes: 14 additions & 6 deletions scripts/ai-accounts/ai-accounts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
69 changes: 22 additions & 47 deletions src/loopzero/candidate.py
Original file line number Diff line number Diff line change
Expand Up @@ -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, ...]:
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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()

Expand Down Expand Up @@ -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()]
49 changes: 20 additions & 29 deletions src/loopzero/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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, *,
Expand All @@ -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 []
Expand All @@ -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

Expand All @@ -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:
Expand Down Expand Up @@ -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"]:
Expand Down Expand Up @@ -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,
)


Expand Down Expand Up @@ -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:
Expand Down
16 changes: 5 additions & 11 deletions src/loopzero/hosted.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import json
import os
import sys
from collections.abc import Callable
from contextlib import suppress
from pathlib import Path

Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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())
23 changes: 23 additions & 0 deletions tests/test_ai_accounts.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Loading
Loading