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
4 changes: 2 additions & 2 deletions core/CONTRACT.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ own delivery state; `.loopzero/` holds task text and local receipts.
Merge rechecks readiness, uses the configured strategy, verifies the landed
SHA, and deletes the branch and worktree. If cleanup warns, the merge landed.
Follow the recovery step it names. A queue initially enqueues;
`--wait` shares a budget across source-check and landing waits. Cleanup follows
verified landing. Enqueueing without `--wait` returns 0 without cleanup.
`--wait` shares a budget across source-check and landing waits. Enqueueing
without `--wait` returns 0 without cleanup.

Merge is authorized by default under [merge authority](#merge-authority).

Expand Down
44 changes: 21 additions & 23 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,13 @@
import random
import re
import sys
import tempfile
import time
from collections.abc import Callable, Iterator
from contextlib import contextmanager
from contextlib import contextmanager, suppress
from datetime import UTC, datetime
from functools import partial, wraps
from pathlib import Path
from uuid import uuid4

from loopzero import _proc, eligibility, github, mergify, runners, sandbox, worktree
from loopzero import config as config_mod
Expand Down Expand Up @@ -369,20 +369,19 @@ def _print_receipt(wt: Path, report: CheckReport, action: str) -> None:


@contextmanager
def _lock_task_state(wt: Path) -> Iterator[None]:
def _lock_task_state(wt: Path) -> Iterator[int]:
directory = wt / ".loopzero"
directory.mkdir(parents=True, exist_ok=True)
fd = os.open(directory, os.O_RDONLY | os.O_DIRECTORY)
fd = os.open(directory, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
try:
fcntl.flock(fd, fcntl.LOCK_EX)
yield
yield fd
finally:
os.close(fd)


def _save_report(wt: Path, report: CheckReport) -> str | None:
"""Publish the receipt or return the current HEAD if the result is stale."""
path = wt / CHECKS_FILE
payload = {
"head": report.head,
"dirty": report.dirty,
Expand All @@ -392,27 +391,26 @@ def _save_report(wt: Path, report: CheckReport) -> str | None:
}
if report.settings_sha256 is not None:
payload["settings_sha256"] = report.settings_sha256
with _lock_task_state(wt):
with _lock_task_state(wt) as directory:
current_head = worktree.head(wt)
if report.head != current_head:
return current_head
_write_json_atomically(path, payload)
_write_json_atomically(directory, CHECKS_FILE.name, payload)
return None


def _write_json_atomically(path: Path, payload: dict) -> None:
with tempfile.NamedTemporaryFile(
mode="w", encoding="utf-8", dir=path.parent, prefix=f".{path.name}-", delete=False
) as stream:
temp = Path(stream.name)
try:
def _write_json_atomically(directory: int, name: str, payload: dict) -> None:
temp = f".{name}-{uuid4().hex}"
fd = os.open(temp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600, dir_fd=directory)
try:
with os.fdopen(fd, "w", encoding="utf-8") as stream:
stream.write(json.dumps(payload, indent=2) + "\n")
stream.flush()
os.fsync(stream.fileno())
stream.close()
os.replace(temp, path)
finally:
temp.unlink(missing_ok=True)
os.replace(temp, name, src_dir_fd=directory, dst_dir_fd=directory)
finally:
with suppress(FileNotFoundError):
os.unlink(temp, dir_fd=directory)


def _load_report(wt: Path) -> CheckReport | None:
Expand Down Expand Up @@ -1124,14 +1122,14 @@ def _review_file(wt: Path, head: str, kind: str) -> Path:

def _save_review(wt: Path, result: ReviewResult, publication: dict | None = None) -> None:
path = _review_file(wt, result.head, result.kind)
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
path.parent.chmod(0o700)
data = dataclasses.asdict(result)
if publication is not None:
data["publication"] = publication
if path.is_symlink():
raise OSError(f"refusing to replace symbolic link: {path}")
_write_json_atomically(path, data)
with _lock_task_state(wt) as directory:
os.fchmod(directory, 0o700)
if path.is_symlink():
raise OSError(f"refusing to replace symbolic link: {path}")
_write_json_atomically(directory, path.name, data)


def _load_review(wt: Path, head: str, kind: str) -> ReviewResult:
Expand Down
24 changes: 18 additions & 6 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -4735,23 +4735,35 @@ def test_wait_rechecks_closed_unmerged_pr(monkeypatch, final) -> None:
assert _closed_unmerged_wait(monkeypatch, reads, steps=1) == final


def test_checks_report_survives_failed_publication(tmp_path, monkeypatch):
@pytest.mark.parametrize("redirected", [False, True])
def test_checks_report_survives_failed_publication(tmp_path, monkeypatch, redirected):
path = tmp_path / cli.CHECKS_FILE
monkeypatch.setattr(cli.worktree, "head", lambda _: next(heads))
heads = iter(("a" * 40, "b" * 40))
cli._save_report(tmp_path, CheckReport("a" * 40, False, ()))

def interrupt(staged, dest):
assert Path(staged).parent == dest.parent
assert json.loads(Path(staged).read_text())["head"] == "b" * 40
assert json.loads(dest.read_text())["head"] == "a" * 40
def interrupt(staged, dest, *, src_dir_fd, dst_dir_fd):
assert src_dir_fd == dst_dir_fd and dest == path.name
assert json.loads(path.with_name(staged).read_text())["head"] == "b" * 40
assert json.loads(path.read_text())["head"] == "a" * 40
raise OSError("publication interrupted")

if redirected:
external = path.parent.rename(tmp_path / "external")
path.parent.symlink_to(external, target_is_directory=True)
monkeypatch.setattr(cli.os, "replace", interrupt)
with pytest.raises(OSError, match="publication interrupted"):
with pytest.raises(OSError, match="Not a directory" if redirected else "publication interrupted"):
cli._save_report(tmp_path, CheckReport("b" * 40, False, ()))
assert json.loads(path.read_text())["head"] == "a" * 40
assert list(path.parent.iterdir()) == [path]
if redirected:
external.chmod(0o755)
review = ReviewResult("claude", "a" * 40, "primary", "approve", (), "")
receipt = cli._review_file(tmp_path, review.head, review.kind)
receipt.write_text("user file")
with pytest.raises(OSError, match="Not a directory"):
cli._save_review(tmp_path, review)
assert receipt.read_text() == "user file" and external.stat().st_mode & 0o777 == 0o755


def test_already_merged_finishes_partial_cleanup(wt, repo, gh, capsys, monkeypatch, head):
Expand Down
Loading