Skip to content
Merged
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
6 changes: 4 additions & 2 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +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
receipts have the restricted retention requirement described below. Local readiness requires
`.loopzero/` for local readiness and reposting. The CLI rejects tracked state
and symlinks and uses the worktree's state directory descriptor for receipt I/O.
GitHub retains authoritative delivery history. The retention rule for Codex
native audit receipts is 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
the configured origin base once at startup before loading its publisher policy.
Expand Down
105 changes: 34 additions & 71 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 @@ -374,18 +372,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 @@ -397,34 +383,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 @@ -433,6 +400,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 @@ -560,7 +529,7 @@ def _append_review(body: str, result: ReviewResult) -> str:
def _refresh_pr_checks(wt: Path, config: Config) -> None:
"""Best-effort refresh only when local HEAD is the existing PR head."""
try:
with _lock_task_state(wt):
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)
Expand All @@ -569,7 +538,7 @@ def _refresh_pr_checks(wt: Path, config: Config) -> None:
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)
except (github.GhError, _proc.ProcTimeout, OSError, ValueError, CliError) as exc:
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 @@ -616,6 +585,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 @@ -701,7 +671,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 @@ -777,6 +747,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 @@ -788,7 +762,7 @@ def cmd_review(args: argparse.Namespace, wt: Path, config: Config) -> int:
login.casefold() for login in config.review_publishers
}:
raise CliError("current GitHub login is not a configured review publisher")
saved = [kind for kind in ("primary", "delta") if _review_file(wt, head, kind).exists()] if args.repost else []
saved = [kind for kind, exists in zip(kinds, saved_files, strict=True) if exists] if args.repost else []
if len(saved) > 1:
raise CliError("multiple saved reviews for HEAD; publication is ambiguous")
reviews = [] if saved else _pr_reviews(config.repo, pr.number)
Expand All @@ -800,9 +774,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 @@ -872,7 +845,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 @@ -926,7 +899,7 @@ def _has_recoverable_review(
if not _review_file(wt, head, kind).exists() or _review_file(wt, head, other_kind).exists():

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: _has_recoverable_review still checks for saved reviews with Path.exists()

cmd_review now gets saved_files from worktree.local_state_files, which checks for regular files without following symbolic links. _has_recoverable_review still uses _review_file(...).exists() for both kinds. That check follows symbolic links, and the second implementation can drift from the one in local_state_files.

The current behavior is safe because local_state_files already rejected symbolic links and _load_review reads through read_local_state. Still, a shared helper should be the only source of this check. Smallest fix: pass the saved_files existence flags (or a kind-to-exists dict) into _has_recoverable_review and remove its own .exists() calls.

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 @@ -1127,10 +1100,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 @@ -1168,31 +1140,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 @@ -1203,11 +1164,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 @@ -176,11 +176,9 @@ def run_checks(config: Config, worktree: Path, *, timeout: float = DEFAULT_TIMEO
INCOMPLETE_CHECK_COMMAND = "<checks 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 @@ -196,7 +194,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