Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,9 @@ 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.
reviews, finding threads, check statuses and merge state. On one host, PR body
writers with the same home directory share a repository-and-PR lock from the live
read through the update. Receipt publication retains its 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,
Expand Down
40 changes: 23 additions & 17 deletions scripts/ai-accounts/ai-accounts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ from __future__ import annotations

import argparse
import base64
import ctypes
import datetime as dt
import errno
from email.utils import parsedate_to_datetime
Expand Down Expand Up @@ -201,9 +202,20 @@ 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
def _rename_noreplace(source: Path, target: Path) -> None:
"""Publish a shared entry atomically, including directories."""
libc = ctypes.CDLL(None, use_errno=True)
renameat2 = getattr(libc, "renameat2", None)
if renameat2 is None:
raise OSError(errno.ENOSYS, "atomic no-replace promotion requires renameat2")
renameat2.argtypes = (ctypes.c_int, ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p, ctypes.c_uint)
at_fdcwd, rename_noreplace = -100, 1
if renameat2(at_fdcwd, os.fsencode(source), at_fdcwd, os.fsencode(target), rename_noreplace):
error = ctypes.get_errno()
raise OSError(error, os.strerror(error), source, None, target)


def _copy_across_devices(entry: Path, target: Path) -> None:
# 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:
Expand All @@ -214,16 +226,7 @@ def _copy_across_devices(entry: Path, target: Path) -> None:
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)
_rename_noreplace(staged, target)
if is_directory:
shutil.rmtree(entry)
else:
Expand All @@ -237,13 +240,16 @@ def _sync_codex_home(home: Path) -> None:
if shared(entry) and not entry.is_symlink() and not target.exists() \
and not target.is_symlink():
try:
os.rename(entry, target)
except FileNotFoundError:
pass
try:
_rename_noreplace(entry, target)
except OSError as exc:
if exc.errno != errno.EXDEV:
raise
_copy_across_devices(entry, target)
except OSError as exc:
if exc.errno != errno.EXDEV:
if exc.errno not in {errno.EEXIST, errno.ENOENT, errno.ENOSYS, errno.EINVAL,
errno.EOPNOTSUPP}:
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():
Expand Down
54 changes: 38 additions & 16 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import tempfile
import time
from collections.abc import Callable, Iterator
from contextlib import contextmanager
from functools import partial, wraps
from pathlib import Path

Expand Down Expand Up @@ -578,18 +579,41 @@ def _append_review(body: str, result: ReviewResult) -> str:
return (body[:match.start(1)] + line + "\n\n" + body[match.end():]).rstrip() + "\n"


@contextmanager
def _lock_pr_body(repo: str, number: int) -> Iterator[None]:
key = hashlib.sha256(f"{repo.casefold()}#{number}".encode()).hexdigest()
path = Path.home() / ".cache" / "loopzero" / "pr-bodies" / key
path.mkdir(mode=0o700, parents=True, exist_ok=True)
fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
try:
fcntl.flock(fd, fcntl.LOCK_EX)
yield
finally:
os.close(fd)


def _refresh_pr_review(repo: str, number: int, result: ReviewResult) -> None:
with _lock_pr_body(repo, number):
live = github.pr_view(repo, number)
github.update_body(repo, number, _append_review(live.body, result))


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 _lock_pr_body(config.repo, pr.number):
live = github.pr_view(config.repo, pr.number)
if live.state == "OPEN" and live.head_sha == head:
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)

Expand Down Expand Up @@ -716,7 +740,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 and pr.state == "OPEN":
with worktree.lock_local_state(wt):
with _lock_pr_body(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")
Expand Down Expand Up @@ -876,9 +900,7 @@ def cmd_review(args: argparse.Namespace, wt: Path, config: Config) -> int:
"inspect the cause and run `loopzero review --repost` to reconcile or explicitly retry"
) from exc
try:
with worktree.lock_local_state(wt):
live = github.pr_view(config.repo, pr.number)
github.update_body(config.repo, pr.number, _append_review(live.body, result))
_refresh_pr_review(config.repo, pr.number, 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)
return _review_verdict(result)
Expand Down Expand Up @@ -1851,18 +1873,18 @@ def _delete_tracking_ref(wt: Path, branch: str, expected_head: str) -> None:


def cmd_resolve(args: argparse.Namespace) -> int:
"""List open blocking findings, or reply to one with what changed and resolve its thread."""
encoding = getattr(sys.stdout, "encoding", None) or "utf-8"
wt, config = _context(args, pin_checks=True) # publishers come from the base, not the PR
pr = _require_pr(config, worktree.branch(wt))
if pr.base_ref != config.base_branch: # trusted publishers belong to the configured base
raise CliError(f"PR #{pr.number} targets {pr.base_ref}, configured base is {config.base_branch}")
publishers = config.review_publishers or (github.login(),)
if not args.finding:
for marker_id, _thread, f in github.open_findings(config.repo, pr.number, publishers):
print(f"{marker_id} {f.severity} {f.path or '-'}:{f.line or '-'} {f.title}")
print(f"{marker_id} {f.severity} {f.path or '-'}:{f.line or '-'} {f.title}".encode(encoding, "backslashreplace").decode(encoding))
return 0
finding = github.resolve_finding(config.repo, pr.number, args.finding, args.reply, publishers)
print(f"resolved {args.finding}: {finding.title}")
print(f"resolved {args.finding}: {finding.title}".encode(encoding, "backslashreplace").decode(encoding))
try:
with github.api_error_diagnostics():
remaining = github.open_blocking_findings(config.repo, pr.number, None, publishers)
Expand Down
5 changes: 0 additions & 5 deletions src/loopzero/worktree.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,11 +127,6 @@ def _local_state_directory(wt: Path, *, create: bool = False, lock: bool = False
os.close(fd)


def lock_local_state(wt: Path):
"""Serialize receipt publication and PR-body updates for this worktree."""
return _local_state_directory(wt, create=True, lock=True)


def _regular_state(wt: Path, fd: int, name: str) -> bool:
with suppress(FileNotFoundError):
if not stat.S_ISREG(os.stat(name, dir_fd=fd, follow_symlinks=False).st_mode):
Expand Down
25 changes: 25 additions & 0 deletions tests/test_ai_accounts.py
Original file line number Diff line number Diff line change
Expand Up @@ -632,3 +632,28 @@ def stage(src, dst, **kwargs):
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])


@pytest.mark.parametrize("unsupported", [None, "ENOSYS", "EINVAL"])
def test_sync_preserves_a_shared_directory_created_during_promotion(helper, monkeypatch, unsupported):
home = helper.codex_home("extra")
home.mkdir(parents=True)
helper.CODEX_MAIN.mkdir()
source = home / "sessions"
source.mkdir()
(source / "old").write_text("keep local")
(home / "notes").write_text("promote")
rename = helper._rename_noreplace

def create_destination(entry, target):
if entry == source:
target.mkdir()
if unsupported:
raise OSError(getattr(helper.errno, unsupported), "no-replace unsupported")
rename(entry, target)

monkeypatch.setattr(helper, "_rename_noreplace", create_destination)
helper.sync_codex_home(home)
assert (source / "old").read_text() == "keep local"
assert list((helper.CODEX_MAIN / "sessions").iterdir()) == []
assert (home / "notes").is_symlink() and (home / "notes").read_text() == "promote"
89 changes: 54 additions & 35 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,13 @@
import signal
import subprocess
import sys
from concurrent.futures import ThreadPoolExecutor
from contextlib import suppress
from dataclasses import asdict, replace
from email.utils import formatdate
from pathlib import Path
from select import select
from threading import Event, current_thread, main_thread
from types import SimpleNamespace
from unittest.mock import Mock
from urllib.parse import quote
Expand Down Expand Up @@ -506,20 +508,57 @@ def test_check_refresh_preserves_local_verdict(wt, gh, capsys, monkeypatch, push
monkeypatch.setattr(github, "update_body", Mock(side_effect=timeout))
code, out, err = run(capsys, "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
assert bool(err) == refresh_timeout
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")


def test_check_and_review_serialize_shared_pr_body(wt, tmp_path, capsys, monkeypatch):
git(wt, "push", "-q", "-u", "origin", "lz/t1")
other = tmp_path / "review"
git(wt, "clone", "-q", "-b", "lz/t1", git(wt, "remote", "get-url", "origin").strip(), str(other))
monkeypatch.chdir(other)
monkeypatch.setenv("HOME", str(tmp_path))
monkeypatch.setattr(cli, "_context", lambda *_, **__: (wt, config.load_trusted(wt)))
pr = github.pr_from_rest(rest_pr_json(pr_json(headRefOid=head_of(wt), body="# Human prose\n")))
monkeypatch.setattr(github, "pr_for_branch", lambda *_, **__: pr)
bodies, proceed, flock = [pr.body], Event(), cli.fcntl.flock
monkeypatch.setattr(github, "pr_view", lambda *_: replace(pr, body=bodies[-1]))

def acquire(fd, flags):
if current_thread() is not main_thread():
try:
return flock(fd, flags | cli.fcntl.LOCK_NB)
except BlockingIOError:
proceed.set()
return flock(fd, flags)

result = ReviewResult("claude", pr.head_sha, "primary", "approve", (), "")
with ThreadPoolExecutor(1) as pool:
def patch(repo, number, body):
if "## Review" not in body:
pending.append(pool.submit(cli._refresh_pr_review, repo, number, result))
assert proceed.wait(5)
bodies.append(body)
proceed.set()

pending = []
monkeypatch.setattr(cli.fcntl, "flock", acquire)
monkeypatch.setattr(github, "update_body", patch)
assert run(capsys, "check")[0] == 0
pending[0].result(timeout=5)
assert_contains(bodies[-1], "# Human prose", "## Validation", "Recorded for", "## Review", "approve")


@pytest.mark.parametrize("newline", ["\n", "\r\n"])
@pytest.mark.parametrize("command", ["check", "pr"])
def test_refresh_preserves_live_pr_evidence(
Expand Down Expand Up @@ -582,8 +621,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", [
Expand Down Expand Up @@ -611,25 +649,6 @@ 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):
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)])
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
final = json.loads(gh.calls[-1]["--input"])["body"]
assert all(text in final for text in ("Human evidence.", "Recorded for", "- primary, claude"))


@pytest.mark.parametrize("command,exit_code", [("check", 0), ("pr", 1)])
def test_malformed_live_markers_do_not_mask_check_verdict(
wt: Path, gh: FakeGh, capsys, command: str, exit_code: int,
Expand All @@ -639,7 +658,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
Expand Down Expand Up @@ -1487,7 +1506,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 "
Expand Down Expand Up @@ -4061,25 +4080,25 @@ def finding_pr(wt, gh, head):

@pytest.mark.parametrize("outcome", ["refreshed", "remaining", "dispatch failed"])
def test_resolve_lists_then_replies_and_resolves_one_finding(finding_pr, gh: FakeGh, capsys, outcome) -> None:
listing = threads_json(finding_pr)
remaining = listing if outcome == "remaining" else threads_json()
gh.respond("api graphql", listing, listing, REPLY_ACCEPTED, THREAD_RESOLVED, remaining)
sys.stdout.reconfigure(encoding="ascii" if outcome == "refreshed" else "utf-8", errors="strict")
finding_pr["comments"]["nodes"][0]["body"] = finding_pr["comments"]["nodes"][0]["body"].replace("Off by one", "Łódź")
listing = threads_json({**finding_pr, "path": "src/Łódź.py"})
gh.respond("api graphql", listing, listing, REPLY_ACCEPTED, THREAD_RESOLVED,
listing if outcome == "remaining" else threads_json())
gh.respond("api -X", "", exit=int(outcome == "dispatch failed"), stderr="HTTP 403")

expect_cli(capsys, 0, "resolve", stderr="", stdout="0b9b59e7 important src/a.py:3 Off by one\n")
title = r"\u0141\xf3d\u017a" if outcome == "refreshed" else "Łódź"
expect_cli(capsys, 0, "resolve", stderr="", stdout=f"0b9b59e7 important src/{title}.py:3 {title}\n")
assert not any("eligibility.yml/dispatches" in " ".join(c["argv"]) for c in gh.calls)

code, out, err = run(capsys, "resolve", "0b9b59e7", "Fixed in abc1234: loop bound corrected.")
assert out.splitlines()[0] == "resolved 0b9b59e7: Off by one"
assert out.splitlines()[0] == f"resolved 0b9b59e7: {title}"
calls = [c["argv"] for c in gh.calls
if c["argv"][:2] == ["api", "graphql"] and "viewer {" not in c["argv"][3]][2:]
assert "addPullRequestReviewThreadReply" in calls[0][3] and "resolveReviewThread" in calls[1][3]
assert "body=Fixed in abc1234: loop bound corrected." in calls[0] and "thread=THREAD_1" in calls[1]
endpoint = f"repos/{REPO}/actions/workflows/eligibility.yml/dispatches"
dispatches = [c["argv"] for c in gh.calls if endpoint in c["argv"]]
if outcome == "remaining":
assert (code, err, dispatches) == (0, "", [])
assert len(out.splitlines()) == 1
assert (code, err, dispatches, len(out.splitlines())) == (0, "", [], 1)
else:
assert dispatches == [["api", "-X", "POST", endpoint, "-f", "ref=main", "-f", "inputs[pr]=7", "--include"]]
if outcome == "refreshed":
Expand Down
Loading