diff --git a/scripts/ai-accounts/ai-accounts b/scripts/ai-accounts/ai-accounts index 5c4c901d..cdc7a1fd 100755 --- a/scripts/ai-accounts/ai-accounts +++ b/scripts/ai-accounts/ai-accounts @@ -47,6 +47,7 @@ from __future__ import annotations import argparse import base64 import datetime as dt +import errno from email.utils import parsedate_to_datetime import fcntl import hashlib @@ -200,6 +201,35 @@ def sync_codex_home(home: Path, *, create: bool = False) -> None: _sync_codex_home(home) +def _copy_across_devices(entry: Path, target: Path) -> None: + import ctypes + + # The private staging directory is also excluded from future mirroring + # by shared() if the process is interrupted before cleanup. + with tempfile.TemporaryDirectory(dir=target.parent, prefix=".codex-sync-", suffix=".lock") as directory: + staged = Path(directory) / entry.name + is_directory = entry.is_dir() + if is_directory: + shutil.copytree(entry, staged, symlinks=True) + else: + shutil.copy2(entry, staged, follow_symlinks=False) + + # Linux/WSL renameat2 with RENAME_NOREPLACE publishes the complete + # entry in one operation without replacing a competing destination. + rename = getattr(ctypes.CDLL(None, use_errno=True), "renameat2", None) + if rename is None: + raise OSError(errno.ENOSYS, "Atomic cross-device publication is unavailable", target) + if rename(-100, os.fsencode(staged), -100, os.fsencode(target), 1): + error = ctypes.get_errno() + if error == errno.EEXIST: + return + raise OSError(error, os.strerror(error), target) + if is_directory: + shutil.rmtree(entry) + else: + entry.unlink() + + def _sync_codex_home(home: Path) -> None: """Mirror shared Codex files while holding the home lock.""" for entry in home.iterdir(): @@ -210,6 +240,10 @@ def _sync_codex_home(home: Path) -> None: os.rename(entry, target) except FileNotFoundError: pass + except OSError as exc: + if exc.errno != errno.EXDEV: + raise + _copy_across_devices(entry, target) for src in CODEX_MAIN.iterdir(): dst = home / src.name if shared(src) and not dst.exists() and not dst.is_symlink(): diff --git a/src/loopzero/candidate.py b/src/loopzero/candidate.py index 351bc8f6..27eff315 100644 --- a/src/loopzero/candidate.py +++ b/src/loopzero/candidate.py @@ -86,30 +86,26 @@ def _identity(actor: object) -> tuple[object, object, object, object]: return actor.get("id"), actor.get("login"), actor.get("type"), actor.get("html_url") -def _object(value: JsonValue, message: str) -> JsonObject: +def _object(value: object, message: str) -> JsonObject: _require(isinstance(value, dict), message) return value def flatten_batches(status: object) -> dict[str, JsonObject]: - _require(isinstance(status, dict), "Mergify status is not an object") - batches = status.get("batches") + batches = _object(status, "Mergify status is not an object").get("batches") _require(isinstance(batches, list), "Mergify status has no batches list") indexed: dict[str, JsonObject] = {} def visit(items: list[object]) -> None: for item in items: - _require(isinstance(item, dict), "Mergify status contains an invalid batch") + item = _object(item, "Mergify status contains an invalid batch") batch_id = item.get("id") _require(isinstance(batch_id, str) and batch_id, "Mergify batch has no id") _require(batch_id not in indexed, f"Mergify batch id is duplicated: {batch_id}") indexed[batch_id] = item children = item.get("sub_batches") if children is not None: - _require( - isinstance(children, list), - f"Mergify batch {batch_id} has invalid sub_batches", - ) + _require(isinstance(children, list), f"Mergify batch {batch_id} has invalid sub_batches") visit(children) visit(batches) @@ -118,17 +114,11 @@ def visit(items: list[object]) -> None: def _candidate_lineage(status: JsonObject, candidate_number: int) -> tuple[str, list[int], list[str]]: indexed = flatten_batches(status) - matches = [ - batch - for batch in indexed.values() - if batch.get("queue_pull_request_number") == candidate_number - ] - _require( - len(matches) == 1, - f"PR #{candidate_number} is not exactly one live Mergify batch", - CandidateBatchError, - ) - candidate_id = matches[0]["id"] + matches = [batch_id for batch_id, batch in indexed.items() + if batch.get("queue_pull_request_number") == candidate_number] + _require(len(matches) == 1, f"PR #{candidate_number} is not exactly one live Mergify batch", + CandidateBatchError) + candidate_id = matches[0] pending, visited = [candidate_id], set() source_numbers, missing = [], [] while pending: @@ -141,10 +131,7 @@ def _candidate_lineage(status: JsonObject, candidate_number: int) -> tuple[str, missing.append(batch_id) continue pull_requests = batch.get("pull_requests") - _require( - isinstance(pull_requests, list), - f"Mergify batch {batch_id} has no pull_requests list", - ) + _require(isinstance(pull_requests, list), f"Mergify batch {batch_id} has no pull_requests list") for pull_request in pull_requests: _require( isinstance(pull_request, dict) @@ -154,11 +141,9 @@ def _candidate_lineage(status: JsonObject, candidate_number: int) -> tuple[str, ) source_numbers.append(pull_request["number"]) parent_ids = batch.get("parent_ids", []) - _require( - isinstance(parent_ids, list) - and all(isinstance(parent_id, str) and parent_id for parent_id in parent_ids), - f"Mergify batch {batch_id} has invalid parent_ids", - ) + _require(isinstance(parent_ids, list) + and all(isinstance(parent, str) and parent for parent in parent_ids), + f"Mergify batch {batch_id} has invalid parent_ids") pending.extend(parent_ids) _require(source_numbers, f"Mergify batch for PR #{candidate_number} has no sources") _require(len(source_numbers) == len(set(source_numbers)), @@ -196,7 +181,8 @@ def _candidate_snapshot( def _source_fingerprint(source: JsonObject) -> tuple[object, ...]: head = source.get("head") base = source.get("base") - base_repo = base.get("repo") if isinstance(base, dict) else None + base = base if isinstance(base, dict) else {} + base_repo = base.get("repo") labels = source.get("labels", []) if not isinstance(labels, list) or any(not isinstance(label, dict) or not isinstance(label.get("name"), str) for label in labels): raise CandidateError("invalid source PR labels") @@ -209,9 +195,8 @@ def _source_fingerprint(source: JsonObject) -> tuple[object, ...]: source.get("draft"), source.get("body"), head.get("sha") if isinstance(head, dict) else None, - base.get("ref") if isinstance(base, dict) else None, - base_repo.get("id") if isinstance(base_repo, dict) else None, - base_repo.get("full_name") if isinstance(base_repo, dict) else None, + base.get("ref"), + *_repo_identity(base_repo if isinstance(base_repo, dict) else {}), ) @@ -438,10 +423,8 @@ def _attest_candidate_once( """Return stable source evidence after every source passes `source_policy`.""" repository = _object(event.get("repository"), "GitHub event repository is missing") event_pr = _object(event.get("pull_request"), "GitHub event pull request is missing") - _require( - event.get("action") in {"opened", "synchronize"}, - "Candidate attestation requires its creation or head-update event", - ) + _require(event.get("action") in {"opened", "synchronize"}, + "Candidate attestation requires its creation or head-update event") full_name = repository.get("full_name") _require(isinstance(full_name, str) and _REPOSITORY.fullmatch(full_name) is not None, "GitHub event repository name is invalid") @@ -453,22 +436,12 @@ def _attest_candidate_once( app = _object(github_get("/apps/mergify"), "GitHub App lookup is invalid") app_owner = app.get("owner") - _require( - app.get("id") == MERGIFY_APP_ID - and app.get("slug") == "mergify" - and isinstance(app_owner, dict) - and app_owner.get("login") == MERGIFY_APP_OWNER, - "Could not resolve the official Mergify GitHub App", - ) - expected_actor = _object( - github_get("/users/mergify%5Bbot%5D"), - "GitHub bot lookup is invalid", - ) - expected_identity = _identity(expected_actor) - _require( - expected_identity == (MERGIFY_BOT_ID, MERGIFY_BOT_LOGIN, "Bot", MERGIFY_APP_URL), - "Could not resolve the Mergify GitHub App identity", - ) + _require(app.get("id") == MERGIFY_APP_ID and app.get("slug") == "mergify" + and isinstance(app_owner, dict) and app_owner.get("login") == MERGIFY_APP_OWNER, + "Could not resolve the official Mergify GitHub App") + expected_identity = _identity(_object(github_get("/users/mergify%5Bbot%5D"), "GitHub bot lookup is invalid")) + _require(expected_identity == (MERGIFY_BOT_ID, MERGIFY_BOT_LOGIN, "Bot", MERGIFY_APP_URL), + "Could not resolve the Mergify GitHub App identity") _require(_identity(event_pr.get("user")) == expected_identity, "Candidate author is not the verified Mergify GitHub App") _require(_identity(event.get("sender")) == expected_identity, @@ -476,10 +449,7 @@ def _attest_candidate_once( candidate_number = event_pr.get("number") candidate_sha = event_head.get("sha") - _require( - isinstance(candidate_number, int) and candidate_number > 0, - "Candidate PR number is invalid", - ) + _require(isinstance(candidate_number, int) and candidate_number > 0, "Candidate PR number is invalid") _require(isinstance(candidate_sha, str) and _SHA.fullmatch(candidate_sha) is not None, "Candidate head SHA is invalid") candidate_path = f"/repos/{full_name}/pulls/{candidate_number}" diff --git a/src/loopzero/hosted.py b/src/loopzero/hosted.py index ece412a4..3eea9ddf 100644 --- a/src/loopzero/hosted.py +++ b/src/loopzero/hosted.py @@ -28,9 +28,9 @@ def event_number(event: dict) -> int: value = prs[0].get("number") else: value = event.get("inputs", {}).get("pr", "") - if isinstance(value, bool) or not str(value).isdigit() or int(value) < 1: - raise LoopZeroError("refresh requires a positive PR number") - return int(value) + if not isinstance(value, bool) and str(value).isdigit() and (number := int(value)) > 0: + return number + raise LoopZeroError("refresh requires a positive PR number") def main() -> int: @@ -122,11 +122,10 @@ def _landed_before_publication(repo: str, number: int, head: str, snapshot: gith current = github.pr_view(repo, number) if current.head_sha != head: raise LoopZeroError("head changed before publication; refresh eligibility") - if snapshot is not None: - if current.state == "MERGED": - return True - if eligibility.source_fingerprint(current) != eligibility.source_fingerprint(snapshot): - raise LoopZeroError("source metadata changed before publication; refresh eligibility") + if snapshot is None or current.state == "MERGED": + return snapshot is not None + if eligibility.source_fingerprint(current) != eligibility.source_fingerprint(snapshot): + raise LoopZeroError("source metadata changed before publication; refresh eligibility") return False diff --git a/tests/test_ai_accounts.py b/tests/test_ai_accounts.py index c161c052..cba117bd 100644 --- a/tests/test_ai_accounts.py +++ b/tests/test_ai_accounts.py @@ -2,6 +2,7 @@ import importlib.machinery import importlib.util import json +import tempfile from concurrent.futures import ThreadPoolExecutor from io import BytesIO from pathlib import Path @@ -593,3 +594,27 @@ def test_account_lock_preserves_existing_file_and_rejects_symlink(helper): with pytest.raises(OSError), helper._locked(".codex-sync.lock"): pytest.fail("redirected lock opened") assert lock.read_text() == "preserve" + + +@pytest.mark.parametrize("outcome", ["published", "copy failed"]) +def test_account_env_moves_shared_entry_across_devices(helper, monkeypatch, outcome): + if not Path("/dev/shm").is_dir() or Path("/dev/shm").stat().st_dev == helper.STATE.stat().st_dev: + pytest.skip("requires two filesystems") + entry = helper.codex_home("extra") / "session-index.jsonl" + helper.write_private(entry, "original") + helper.write_private(entry.with_name("auth.json"), "{}") + copy = helper.shutil.copy2 + with tempfile.TemporaryDirectory(dir="/dev/shm") as main: + monkeypatch.setattr(helper, "CODEX_MAIN", Path(main)) + def stage(src, dst, **kwargs): + copy(src, dst, **kwargs) + if outcome == "copy failed": + raise OSError("copy interrupted") + monkeypatch.setattr(helper.shutil, "copy2", stage) + if outcome == "copy failed": + with pytest.raises(OSError, match="copy interrupted"): + helper.account_env("codex", "extra") + else: + helper.account_env("codex", "extra") + assert entry.read_text() == "original" and entry.is_symlink() == (outcome == "published") + assert list(Path(main).iterdir()) == ([] if outcome == "copy failed" else [Path(main) / entry.name])