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: 4 additions & 1 deletion docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,10 @@ and branch protection remains essential.

Local `.loopzero/task.md` is working handoff context, rendered into the PR.
The CLI also writes a head-bound checks receipt and saved review output in
`.loopzero/` for local readiness and reposting. They do not form a second authoritative delivery history; new Codex native audit
`.loopzero/` for local readiness and reposting. The CLI rejects tracked state
and symbolic links. Receipt reads and writes use a directory descriptor for
the worktree's state directory. These files do not form a second authoritative
delivery history; new Codex native audit
receipts have the restricted retention requirement described below. Local readiness requires
its current successful check receipt; hosted eligibility evaluates GitHub
review evidence using trusted base configuration. Local readiness and merge fetch
Expand Down
103 changes: 33 additions & 70 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,16 @@
import hashlib
import json
import os
import shlex
import random
import re
import shlex
import sys
import tempfile
import time
from collections.abc import Callable, Iterator
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 @@ -389,18 +387,6 @@ def _print_receipt(wt: Path, report: CheckReport, action: str) -> None:
return


@contextmanager
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 | os.O_NOFOLLOW)
try:
fcntl.flock(fd, fcntl.LOCK_EX)
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."""
payload = {
Expand All @@ -412,34 +398,15 @@ 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) as directory:
current_head = worktree.head(wt)
if report.head != current_head:
return current_head
_write_json_atomically(directory, CHECKS_FILE.name, payload)
return None


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())
os.replace(temp, name, src_dir_fd=directory, dst_dir_fd=directory)
finally:
with suppress(FileNotFoundError):
os.unlink(temp, dir_fd=directory)
return worktree.write_local_state(
wt, CHECKS_FILE.name, json.dumps(payload, indent=2) + "\n", expected_head=report.head,
)


def _load_report(wt: Path) -> CheckReport | None:
path = wt / CHECKS_FILE
if not path.exists():
return None
try:
data = json.loads(path.read_text())
data = json.loads(worktree.read_local_state(wt, path.name))
results = tuple(CheckResult(**item) for item in data["results"])
if any(not is_check_exit_code(result.exit_code) for result in results):
raise TypeError("exit_code must be an integer")
Expand All @@ -448,6 +415,8 @@ def _load_report(wt: Path) -> CheckReport | None:
raise TypeError("dirty must be a bool")
return CheckReport(head=str(data["head"]), dirty=dirty, results=results,
settings_sha256=data.get("settings_sha256"))
except FileNotFoundError:
return None
except (TypeError, KeyError, ValueError) as exc:
print(f"warning: ignoring unreadable {path}: {exc}", file=sys.stderr)
return None
Expand Down Expand Up @@ -580,7 +549,7 @@ def _append_review(body: str, result: ReviewResult) -> str:

def _refresh_pr_checks(wt: Path, config: Config) -> None:
try:
with _lock_task_state(wt):
with worktree.lock_local_state(wt):
_refresh_existing_pr_checks(wt, config)
except OSError as exc:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Best-effort lock/refresh paths no longer absorb directory-level rejections

Before this change, _lock_task_state failures were plain OSErrors, which _refresh_pr_checks (line 504) and the PR review-summary append in cmd_review (line 820) catch and print as notes. _local_state_directory now raises WorktreeError for tracked or symlinked state, and WorktreeError is not an OSError. _refresh_existing_pr_checks (line 519) can also receive WorktreeError from _load_report/task_text. The up-front checks make this reachable only if the state is swapped during the command. Even so, in cmd_review the review has already been posted at that point, so the command ends with an error instead of the review's verdict exit code. Smallest fix: add worktree.WorktreeError to the except tuples at lines 504, 519 and 820 so these steps stay best-effort.

print(f"note: could not refresh PR checks: {_one_line(exc)}", file=sys.stderr)
Expand Down Expand Up @@ -645,6 +614,7 @@ def _check_failure_preview(tail: str, limit: int = 1536) -> str:

def cmd_check(args: argparse.Namespace) -> int:
wt, config = _context(args, pin_checks=True)
worktree.local_state_files(wt, CHECKS_FILE.name)
if not config.checks:
raise config_mod.ConfigError("checks.commands must list at least one command to run checks")
try:
Expand Down Expand Up @@ -729,7 +699,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 _lock_task_state(wt):
with worktree.lock_local_state(wt):
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 @@ -805,6 +775,10 @@ def cmd_review(args: argparse.Namespace, wt: Path, config: Config) -> int:
runtime_source = f"reviewer paths pinned to origin/{config.base_branch}@{config.trusted_base_revision}"
branch, head = worktree.branch(wt), worktree.head(wt)
_require_task_branch(config, branch)
kinds = ("primary", "delta")
_, *saved_files = worktree.local_state_files(
wt, "task.md", *(_review_file(wt, head, kind).name for kind in kinds)
)
_require_clean(wt)
pr = _require_review_pr(config, branch, repost=args.repost)
_require_pushed(pr, head)
Expand All @@ -818,7 +792,7 @@ def cmd_review(args: argparse.Namespace, wt: Path, config: Config) -> int:
raise CliError("current GitHub login is not a configured review publisher")
reviews = [] if args.repost else _pr_reviews(config.repo, pr.number)
if args.repost:
saved = [kind for kind in ("primary", "delta") if _review_file(wt, head, kind).exists()]
saved = [kind for kind, exists in zip(kinds, saved_files, strict=True) if exists]
if len(saved) > 1:
raise CliError("multiple saved reviews for HEAD; publication is ambiguous")
if not saved:
Expand All @@ -832,9 +806,8 @@ def cmd_review(args: argparse.Namespace, wt: Path, config: Config) -> int:
)
publication_context = {"repo": config.repo, "number": pr.number, "publisher": publisher}
if args.repost:
result = _load_review(wt, head, kind)
result, publication = _load_review(wt, head, kind)
candidates, excluded = _repost_reviewer_families(wt, config, head, result)
publication = json.loads(_review_file(wt, head, kind).read_text()).get("publication")
if publication is not None:
if (not isinstance(publication, dict) or publication.get("repo") != config.repo
or publication.get("number") != pr.number
Expand Down Expand Up @@ -904,7 +877,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 _lock_task_state(wt):
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))
except (github.GhError, _proc.ProcTimeout, OSError, ValueError) as exc:
Expand Down Expand Up @@ -958,7 +931,7 @@ def _has_recoverable_review(
if not _review_file(wt, head, kind).exists() or _review_file(wt, head, other_kind).exists():
return False
try:
result = _load_review(wt, head, kind, publication=publication)
result, _ = _load_review(wt, head, kind, publication=publication)
candidates, excluded = _repost_reviewer_families(wt, config, head, result)
if result.fallback and not _published_fallback(result.fallback, candidates, excluded):
return False
Expand Down Expand Up @@ -1160,10 +1133,9 @@ def _save_review_failure_output(wt: Path, head: str, kind: str, errors: dict[str
return ""
path = wt / ".loopzero" / f"reviewer-output-{head[:12]}-{kind}.json"
try:
with _lock_task_state(wt) as directory:
_write_json_atomically(directory, path.name, fragments)
except OSError as exc:
return f"\nCould not save reviewer output: {exc.strerror or exc}"
worktree.write_local_state(wt, path.name, json.dumps(fragments, indent=2) + "\n", private=True)
except (OSError, worktree.WorktreeError) as exc:
return f"\nCould not save reviewer output: {_one_line(exc)}"
return f"\nReviewer output: {path.relative_to(wt)}"


Expand Down Expand Up @@ -1201,31 +1173,20 @@ 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)
data = dataclasses.asdict(result)
if publication is not None:
data["publication"] = publication
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)
data = dataclasses.asdict(result) | ({"publication": publication} if publication is not None else {})
worktree.write_local_state(wt, path.name, json.dumps(data, indent=2) + "\n", private=True)


def _load_review(
wt: Path, head: str, kind: str, *, publication: dict | None = None,
) -> ReviewResult:
) -> tuple[ReviewResult, object]:
path = _review_file(wt, head, kind)
if not path.exists():
raise CliError(f"no saved {kind} review for {head[:12]} at {path}; run without --repost")
try:
data = json.loads(path.read_text())
except (ValueError, OSError) as exc:
raise CliError(f"{path} is not runner-produced: invalid saved review") from exc
if not isinstance(data, dict):
raise CliError(f"{path} is not runner-produced: invalid saved review")
if data.get("head") != head:
raise CliError(f"{path} holds a review of {str(data.get('head'))[:12]}, not HEAD {head[:12]}")
try:
data = json.loads(worktree.read_local_state(wt, path.name))
if not isinstance(data, dict):
raise ValueError("review receipt must be an object")
if data.get("head") != head:
raise CliError(f"{path} holds a review of {str(data.get('head'))[:12]}, not HEAD {head[:12]}")
saved_publication = data.pop("publication", None)
if data.get("kind") != kind or (publication is not None and saved_publication != publication):
raise ValueError("saved review kind or publication mismatch")
Expand All @@ -1236,11 +1197,13 @@ def _load_review(
if data.pop(field, default) != default:
raise ValueError("retired paired review")
result = ReviewResult(**{**data, "findings": findings})
except (KeyError, TypeError, ValueError) as exc:
except FileNotFoundError:
raise CliError(f"no saved {kind} review for {head[:12]} at {path}; run without --repost") from None
except (KeyError, OSError, TypeError, ValueError) as exc:
raise CliError(f"{path} is not runner-produced: invalid saved review") from exc
if not runners.validate_runner_result(result):
raise CliError(f"{path} is not runner-produced: provenance/envelope mismatch")
return result
return result, saved_publication


def _pr_readiness(
Expand Down
12 changes: 5 additions & 7 deletions src/loopzero/sandbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
from . import __version__, _proc
from . import config as config_mod
from .types import CheckReport, CheckResult, Config, LoopZeroError, is_check_exit_code
from .worktree import WorktreeError
from .worktree import WorktreeError, read_local_state

GIT_TIMEOUT = 60.0
DEFAULT_TIMEOUT = 3600.0
Expand Down Expand Up @@ -100,7 +100,7 @@ def run_checks(config: Config, worktree: Path, *, timeout: float = DEFAULT_TIMEO
"Runner requires a clean worktree"),))
base = _check_base(config, worktree)
settings_sha256 = settings_fingerprint(config, worktree, base=base)
previous = _previous(config, worktree, settings_sha256) if config.inputs and base and settings_sha256 and not dirty else {}
previous = _previous(worktree, settings_sha256) if config.inputs and base and settings_sha256 and not dirty else {}
common_dir = _git_dir(config, worktree, "--git-common-dir")
git_dir = _git_dir(config, worktree, "--git-dir")

Expand Down Expand Up @@ -184,11 +184,9 @@ def _checkpoint_success(checkpoint: Callable[[CheckReport], None] | None,
checkpoint(replace(report, results=(*report.results, *unvisited, incomplete)))


def _previous(config: Config, worktree: Path, settings_sha256: str) -> dict[str, CheckResult]:
if _git(config, worktree, "ls-files", "--", ".loopzero"):
return {}
def _previous(worktree: Path, settings_sha256: str) -> dict[str, CheckResult]:
try:
data = json.loads((worktree / ".loopzero/checks.json").read_text())
data = json.loads(read_local_state(worktree, "checks.json"))
if (data["dirty"] is not False or not isinstance(data["head"], str)
or data.get("settings_sha256") != settings_sha256):
return {}
Expand All @@ -204,7 +202,7 @@ def _previous(config: Config, worktree: Path, settings_sha256: str) -> dict[str,
source if isinstance(source, str) else data["head"],
)
return previous
except (OSError, ValueError, KeyError, TypeError, AttributeError):
except (OSError, WorktreeError, ValueError, KeyError, TypeError, AttributeError):
return {}


Expand Down
Loading
Loading