From 70ecea9ab56b8b75fb208fcef7c9aa06b7bf65f9 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:05:24 +0100 Subject: [PATCH] Keep local receipts in the task worktree Architecture-Review: unchanged; The guide already assigns local receipts to the task worktree and describes atomic local evidence. Co-Authored-By: Codex --- src/loopzero/cli.py | 44 +++++++++++++++++++++----------------------- tests/test_cli.py | 24 ++++++++++++++++++------ 2 files changed, 39 insertions(+), 29 deletions(-) diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 5581821d..766a714d 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -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 @@ -353,20 +353,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, @@ -376,27 +375,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: @@ -1108,14 +1106,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: diff --git a/tests/test_cli.py b/tests/test_cli.py index 055d1a74..5840e7ba 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -4694,23 +4694,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):