diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index efb9567c..cf72b1df 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -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. diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 1775f8c0..efeb78dc 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -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 @@ -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 = { @@ -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") @@ -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 @@ -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) @@ -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) @@ -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: @@ -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") @@ -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) @@ -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) @@ -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 @@ -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: @@ -926,7 +899,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 @@ -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)}" @@ -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") @@ -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( diff --git a/src/loopzero/sandbox.py b/src/loopzero/sandbox.py index a2ab44de..fdd06721 100644 --- a/src/loopzero/sandbox.py +++ b/src/loopzero/sandbox.py @@ -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 @@ -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") @@ -176,11 +176,9 @@ def run_checks(config: Config, worktree: Path, *, timeout: float = DEFAULT_TIMEO INCOMPLETE_CHECK_COMMAND = "" -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 {} @@ -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 {} diff --git a/src/loopzero/worktree.py b/src/loopzero/worktree.py index fe421d6d..8916bc2a 100644 --- a/src/loopzero/worktree.py +++ b/src/loopzero/worktree.py @@ -6,12 +6,13 @@ import fcntl import os import re +import stat import subprocess -import tempfile from collections.abc import Iterator from contextlib import contextmanager, suppress from pathlib import Path from select import select +from uuid import uuid4 from loopzero._proc import build_env, run, run_git_paths @@ -96,6 +97,81 @@ def task_file(wt: Path) -> Path: return Path(wt) / ".loopzero" / "task.md" +@contextmanager +def _local_state_directory(wt: Path, *, create: bool = False, lock: bool = False): + path = wt / ".loopzero" + if _git(wt, "ls-files", "-z", "--", ".loopzero"): + raise WorktreeError(f"refusing repository-tracked local state: {path}") + if create: + with suppress(FileExistsError): + path.mkdir(mode=0o700) + try: + fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + except NotADirectoryError as exc: + raise WorktreeError(f"local state directory is not a directory or is a symbolic link: {path}") from exc + try: + if lock: + fcntl.flock(fd, fcntl.LOCK_EX) + yield fd + finally: + 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): + raise WorktreeError(f"local state file is not regular or is a symbolic link: {wt / '.loopzero' / name}") + return True + return False + + +def local_state_files(wt: Path, *names: str) -> tuple[bool, ...]: + with suppress(FileNotFoundError), _local_state_directory(wt) as fd: + return tuple(_regular_state(wt, fd, name) for name in names) + return (False,) * len(names) + + +def read_local_state(wt: Path, name: str) -> str: + with _local_state_directory(wt) as fd, os.fdopen( + os.open(name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=fd), encoding="utf-8" + ) as stream: + if not stat.S_ISREG(os.fstat(stream.fileno()).st_mode): + raise WorktreeError(f"local state file is not regular: {wt / '.loopzero' / name}") + return stream.read() + + +def write_local_state( + wt: Path, name: str, text: str, *, private: bool = False, exclusive: bool = False, + expected_head: str | None = None, +) -> str | None: + with _local_state_directory(wt, create=True, lock=private or expected_head is not None) as fd: + if expected_head is not None and (current_head := head(wt)) != expected_head: + return current_head + _regular_state(wt, fd, name) + if private: + os.fchmod(fd, 0o700) + temp = f".{name}-{uuid4().hex}" + file_fd = os.open(temp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600, dir_fd=fd) + try: + with os.fdopen(file_fd, "w", encoding="utf-8") as stream: + stream.write(text) + stream.flush() + os.fsync(stream.fileno()) + if exclusive: + os.link(temp, name, src_dir_fd=fd, dst_dir_fd=fd, follow_symlinks=False) + else: + os.replace(temp, name, src_dir_fd=fd, dst_dir_fd=fd) + finally: + with suppress(FileNotFoundError): + os.unlink(temp, dir_fd=fd) + return None + + def _branch_exists(repo_root: Path, branch: str) -> bool: done = run( ["git", "rev-parse", "--verify", "--quiet", f"refs/heads/{branch}"], @@ -135,7 +211,7 @@ def start(repo_root: Path, slug: str, base_branch: str) -> Path: task = task_file(wt) existing = wt.exists() refusal = f"worktree directory already exists: {wt}" - if wt.is_symlink() or task.exists() or task.is_symlink() or task.parent.is_symlink(): + if wt.is_symlink() or task.parent.is_symlink() or task.is_symlink() or task.exists(): raise WorktreeError(refusal) if not existing and _branch_exists(repo_root, branch): raise WorktreeError(f"branch already exists: {branch}") @@ -189,30 +265,17 @@ def _resumable_head(repo_root: Path, wt: Path, expected_branch: str) -> str | No def _initialize_task(task: Path, text: str) -> None: - if task.parent.is_symlink(): - raise WorktreeError(f"task directory is a symbolic link: {task.parent}") - task.parent.mkdir(parents=True, exist_ok=True) - with tempfile.NamedTemporaryFile( - mode="w", encoding="utf-8", dir=task.parent, prefix=".task.md-", delete=False - ) as stream: - temp = Path(stream.name) - try: - stream.write(text) - stream.close() - # Publish the complete file without replacing an existing handoff. - try: - task.hardlink_to(temp) - except FileExistsError as exc: - raise WorktreeError(f"task file already exists: {task}") from exc - except OSError as exc: - if exc.errno not in (errno.EOPNOTSUPP, errno.ENOTSUP, errno.ENOSYS, errno.EPERM): - raise - raise WorktreeError( - f"cannot publish task file {task} ({exc.strerror}): hard links are required; " - "run loopzero start from a checkout on a filesystem that supports hard links" - ) from exc - finally: - temp.unlink(missing_ok=True) + try: + write_local_state(task.parent.parent, task.name, text, exclusive=True) + except FileExistsError as exc: + raise WorktreeError(f"task file already exists: {task}") from exc + except OSError as exc: + if exc.errno not in (errno.EOPNOTSUPP, errno.ENOTSUP, errno.ENOSYS, errno.EPERM): + raise + raise WorktreeError( + f"cannot publish task file {task} ({exc.strerror}): hard links are required; " + "run loopzero start from a checkout on a filesystem that supports hard links" + ) from exc def head(wt: Path) -> str: @@ -233,14 +296,14 @@ def branch(wt: Path) -> str: def task_text(wt: Path) -> str: - task = task_file(wt) - if not task.exists(): + try: + return read_local_state(wt, "task.md") + except FileNotFoundError: raise WorktreeError( - f"missing {task}. Run `loopzero start ` for a new task worktree, " + f"missing {task_file(wt)}. Run `loopzero start ` for a new task worktree, " "or recreate the file using the handoff template at " "https://github.com/feder-positronics/loop-zero/blob/main/core/HANDOFF.md" - ) - return task.read_text(encoding="utf-8") + ) from None def base_sha(wt: Path) -> str: diff --git a/tests/test_cli.py b/tests/test_cli.py index 8b73e600..239019c8 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -147,12 +147,12 @@ def test_start_reports_handoff_publication_failure(repo, monkeypatch, capsys, li monkeypatch.chdir(repo) task = repo / ".worktrees" / "t1" / ".loopzero" / "task.md" - def fail_link(path, source): + def fail_link(*_args, **_kwargs): if link_error == errno.EEXIST: - path.write_text("existing handoff") + task.write_text("existing handoff") raise OSError(link_error, "link failed") - monkeypatch.setattr(Path, "hardlink_to", fail_link) + monkeypatch.setattr(cli.worktree.os, "link", fail_link) assert cli.main(["start", "t1"]) == 1 error = capsys.readouterr().err assert str(task) in error @@ -427,11 +427,17 @@ def test_start_without_config(git_repo: Path, monkeypatch, capsys) -> None: assert code == 1 and "workflow.toml" in err and err.count("\n") == 1 -def test_check_pass_writes_report(wt: Path, gh: FakeGh, capsys) -> None: +@pytest.mark.parametrize("dirty", [False, True]) +def test_check_pass_writes_report(wt: Path, gh: FakeGh, capsys, dirty) -> None: + if dirty: + (wt / "README.md").write_text("uncommitted content") code, out, _ = run(capsys, "check") assert gh.calls == [] lines = out.splitlines() assert code == 0 and lines[-1] == "PASS" + if dirty: + assert "receipt produced:" not in out + return assert lines[0].startswith("checks pinned to origin/main@") assert lines[1] == "running: echo ok" assert lines[2].startswith("stage 1/2: exit 0 (") @@ -446,6 +452,9 @@ def test_check_pass_writes_report(wt: Path, gh: FakeGh, capsys) -> None: assert [(r["command"], r["exit_code"]) for r in report["results"]] == [ ("echo ok", 0), ("test -f README.md", 0)] assert report["results"][0]["tail"] == "ok" + cli._load_report(wt) + cli._validation_section(wt, report["head"], config.load(wt / "workflow.toml")) + assert "receipt " not in capsys.readouterr().out @pytest.mark.parametrize("state", [None, "CLOSED", "MERGED"]) @@ -835,6 +844,39 @@ def test_invalid_workflow_utf8_names_file(wt, capsys, trusted): assert "Traceback" not in err +@pytest.mark.parametrize("command,state_file", [ + ("check", None), ("review", None), ("repost", None), ("ready", None), + ("check", "checks.json"), ("review", "task.md"), ("ready", "checks.json"), ("check", "tracked"), + ("review", "review-{head}-primary.json"), ("repost", "review-{head}-primary.json"), +]) +def test_commands_refuse_linked_local_state(wt, gh, capsys, tmp_path, command, state_file, head): + if command == "ready": + arm_approved_ready_pr(gh, head, wt) + state, sentinel = wt / ".loopzero", tmp_path / "external" + tracked = state_file == "tracked" + if tracked: + sentinel = state / "task.md" + git(wt, "add", "-f", str(sentinel)) + else: + target = state / state_file.format(head=head[:12]) if state_file else state + if state_file and not target.exists(): + target.write_text("local state") + target.rename(sentinel) + target.symlink_to(sentinel, target_is_directory=state_file is None) + directory = state if state_file else sentinel + directory.chmod(0o755) + + def snapshot(): + return {f.name: f.read_bytes() for f in (directory.iterdir() if not state_file else (sentinel,))} + + original = snapshot() + args = ("review", "--repost") if command == "repost" else (command,) + diagnostic = "repository-tracked local state" if tracked else "symbolic link" + expect_cli(capsys, 1, *args, stderr_contains=(diagnostic,)) + assert snapshot() == original and (tracked or target.is_symlink()) + assert directory.stat().st_mode & 0o777 == 0o755 + + def test_check_uses_base_commands_when_worktree_weakens_them(wt: Path, capsys) -> None: (wt / "workflow.toml").write_text(WORKFLOW.replace('"echo ok", "test -f README.md"', '"true"')) out, _ = expect_cli(capsys, 0, "check", stderr="") @@ -935,16 +977,11 @@ def test_check_rejects_invalid_base_workflow(wt, repo, capsys, workflow, error): out, _ = expect_cli(capsys, 1, "check", stderr_contains=(f"origin/main:workflow.toml: {error}",)) assert "PASS" not in out if workflow is None else out == "" assert not (wt / ".loopzero" / "checks.json").exists() - - -def test_readiness_rejects_existing_empty_check_receipt(wt: Path, repo: Path) -> None: - advance_checks(repo, []) - args = SimpleNamespace(config=None, command="ready") - config = cli._load_config(args, wt, pin_checks=True) - head = head_of(wt) - cli._save_report(wt, CheckReport(head, False, (), cli.sandbox.settings_fingerprint(config, wt))) - - assert cli._current_check_report(wt, config, head) is None + if workflow is None: + cfg = cli._load_config(SimpleNamespace(config=None, command="ready"), wt, pin_checks=True) + head = head_of(wt) + cli._save_report(wt, CheckReport(head, False, (), cli.sandbox.settings_fingerprint(cfg, wt))) + assert cli._current_check_report(wt, cfg, head) is None # --- pr ------------------------------------------------------------------------------------ @@ -1439,7 +1476,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() code, out, err = run(capsys, "review") - assert_git_cost(git_calls, 14, 1) + assert_git_cost(git_calls, 18, 1) assert (code, err) == (5, "") # request_changes: the exit code is the verdict assert out.splitlines()[0].startswith("reviewer paths pinned to origin/main@") assert out.splitlines()[-1] + "\n" == ( @@ -1719,46 +1756,29 @@ def interrupt_encoding(value, *args, **kwargs): assert not saved.exists() -def test_repost_refuses_retired_paired_review( - wt: Path, gh: FakeGh, fake_bin: Path, capsys -) -> None: - head = prepare_review(wt, gh, fake_bin) - code, _, err = run(capsys, "review") - assert (code, err) == (0, "") - saved = wt / ".loopzero" / f"review-{head[:12]}-primary.json" - data = json.loads(saved.read_text()) - data["members"] = [{"family": "claude"}] - saved.write_text(json.dumps(data)) - (fake_bin / "claude.stdin").unlink() - _fake_codex(fake_bin, json.dumps(APPROVE)) +@pytest.mark.parametrize("saved_state", ["missing", "stale", "hand-written", "retired"]) +def test_repost_refuses_invalid_saved_review(wt, gh, fake_bin, capsys, saved_state, head): + saved = cli._review_file(wt, head, "primary") + if saved_state == "retired": + prepare_review(wt, gh, fake_bin) + expect_cli(capsys, 0, "review", stderr="") + saved.write_text(json.dumps(json.loads(saved.read_text()) | {"members": [{"family": "claude"}]})) + (fake_bin / "claude.stdin").unlink() + _fake_codex(fake_bin, json.dumps(APPROVE)) + else: + arm_empty_primary_review_history(gh, head) + if saved_state != "missing": + saved.write_text(json.dumps({ + "family": "claude", "head": "0" * 40 if saved_state == "stale" else head, + "kind": "primary", "verdict": "approve", "findings": [], + "raw": "" if saved_state == "stale" else json.dumps(_claude_envelope(APPROVE)), + })) prior_calls = len(gh.calls) - - _, err = expect_cli(capsys, 1, "review", "--repost") - assert "invalid saved review" in err - assert not (fake_bin / "claude.stdin").exists() - assert not (fake_bin / "codex.stdin").exists() - assert not any( - call["argv"][:2] == post_key().split() for call in gh.calls[prior_calls:] - ) - - -@pytest.mark.parametrize("saved_state", ["missing", "stale", "hand-written"]) -def test_repost_refuses_missing_stale_or_hand_written_review( - wt: Path, gh: FakeGh, capsys, saved_state: str, head -) -> None: - arm_empty_primary_review_history(gh, head) - if saved_state != "missing": - saved = wt / ".loopzero" / f"review-{head[:12]}-primary.json" - saved.write_text(json.dumps({ - "family": "claude", "head": "0" * 40 if saved_state == "stale" else head, - "kind": "primary", "verdict": "approve", "findings": [], - "raw": "" if saved_state == "stale" else json.dumps(_claude_envelope(APPROVE)), - })) - code, out, err = run(capsys, "review", "--repost") expected = {"missing": "no saved primary review", "stale": f"not HEAD {head[:12]}", - "hand-written": "not runner-produced"} - assert code == 1 and out == "" and expected[saved_state] in err - assert all(c["argv"][1] != post_key().split(" ")[1] for c in gh.calls) + "hand-written": "not runner-produced", "retired": "invalid saved review"} + expect_cli(capsys, 1, "review", "--repost", stdout="", stderr_contains=(expected[saved_state],)) + assert all(not (fake_bin / f"{family}.stdin").exists() for family in ("claude", "codex")) + assert all(call["argv"][:2] != post_key().split() for call in gh.calls[prior_calls:]) @pytest.mark.parametrize("chunk_auth", [False, True]) @@ -2166,7 +2186,7 @@ def test_review_observes_new_codex_version_in_saved_receipt( _fake_codex(fake_bin, json.dumps(APPROVE), version=version) _, err = expect_cli(capsys, 0, "review", stdout_contains=("review by codex",)) assert "reviewer codex unavailable:" not in err - result = cli._load_review(wt, git(wt, "rev-parse", "HEAD").strip(), "primary") + result, _ = cli._load_review(wt, git(wt, "rev-parse", "HEAD").strip(), "primary") assert result.provenance["cli_version"] == version @@ -2181,9 +2201,9 @@ def malformed(family, *, head, kind, **kwargs): monkeypatch.setattr(cli.runners, "review_with", malformed) if not save: - def fail(*args): + def fail(*args, **kwargs): raise PermissionError("diagnostic write denied") - monkeypatch.setattr(cli, "_write_json_atomically", fail) + monkeypatch.setattr(cli.worktree, "write_local_state", fail) code, out, err = run(capsys, "review") size = len((out + err).encode()) assert size < 650, size @@ -2367,7 +2387,8 @@ def test_ready_marks_draft_ready(wt: Path, gh: FakeGh, capsys, head, branch, git gh.respond("pr ready", "") git_calls.clear() code, out, err = run(capsys, "ready") - assert_git_cost(git_calls, 8, 1) + assert_git_cost(git_calls, 9, 1) + assert ["ls-files", "-z", "--", ".loopzero"] in git_calls assert (code, err) == (0, "") and out.endswith(f"ready: {URL}\n") assert ["pr", "ready", "7", "--repo", REPO] in [c["argv"] for c in gh.calls] @@ -3108,33 +3129,43 @@ def check_environment(wt, gh, head, tmp_path): return path, policy, ("--config", str(path)) -@pytest.mark.parametrize("wait_for", [None, "ready", "merge"]) -def test_ready_requires_receipt_from_current_check_environment(gh, capsys, head, monkeypatch, wait_for, check_environment): +@pytest.mark.parametrize("case", ["explicit", "ready", "merge", "inherited", "fixed"]) +def test_ready_checks_effective_receipt_environment(gh, capsys, head, monkeypatch, case, check_environment): config_path, config, args = check_environment - config = config.replace("[checks]", '[checks]\nenv = { CHECK_POLICY = "old" }') + inherited = case in {"inherited", "fixed"} + if inherited: + config = config.replace("[checks]", '[checks]\nenv_allowlist = ["PATH", "CHECK_POLICY"]') + monkeypatch.setenv("CHECK_POLICY", "old") + if case != "inherited": + config = config.replace("[checks]", '[checks]\nenv = { CHECK_POLICY = "old" }') config_path.write_text(config) + expect_cli(capsys, 0, *args, "check") + expect_cli(capsys, 0, *args, "ready") - assert run(capsys, *args, "check")[0] == 0 - assert run(capsys, *args, "ready")[0] == 0 - - new_config = config.replace('CHECK_POLICY = "old"', 'CHECK_POLICY = "new"') - if wait_for: - arm_check_runs(gh, head, [{"name": "checks", "status": "in_progress"}]) - - def change_policy(_seconds): - assert config_path.read_text() == config + if inherited: + monkeypatch.setenv("CHECK_POLICY", "new") + else: + new_config = config.replace('CHECK_POLICY = "old"', 'CHECK_POLICY = "new"') + if case in {"ready", "merge"}: + arm_check_runs(gh, head, [{"name": "checks", "status": "in_progress"}]) + + def change_policy(_seconds): + assert config_path.read_text() == config + config_path.write_text(new_config) + + monkeypatch.setattr(cli, "_sleep", change_policy) + expect_cli(capsys, 1, *args, case, "--wait", + stderr_contains=("workflow settings changed while waiting; run loopzero check",)) + arm_check_runs(gh, head, [{"name": "checks", "status": "completed", "conclusion": "success"}]) + else: config_path.write_text(new_config) - - monkeypatch.setattr(cli, "_sleep", change_policy) - code, _, err = run(capsys, *args, wait_for, "--wait") - assert code == 1 and "workflow settings changed while waiting; run loopzero check" in err - arm_check_runs(gh, head, [ - {"name": "checks", "status": "completed", "conclusion": "success"}]) + if case == "fixed": + expect_cli(capsys, 0, *args, "ready") else: - config_path.write_text(new_config) - out, _ = expect_cli(capsys, 1, *args, "ready") - assert "not ready: check receipt has an incompatible settings fingerprint." in out - assert run(capsys, *args, "check")[0] == 1 + expect_cli(capsys, 1, *args, "ready", + stdout_contains=("not ready: check receipt has an incompatible settings fingerprint.",)) + if not inherited: + expect_cli(capsys, 1, *args, "check") def test_check_refuses_unverified_receipt_after_runner_retarget(wt, gh, capsys, head, tmp_path): @@ -3189,24 +3220,6 @@ def test_wait_snapshot_handles_trusted_base_advance(wt, repo, base_sensitive): cli._verify_wait_snapshot(args, wt, config, head, head) -@pytest.mark.parametrize("fixed", [False, True]) -def test_ready_matches_effective_inherited_check_environment(capsys, monkeypatch, fixed, check_environment): - config_path, config, args = check_environment - config = config.replace("[checks]", '[checks]\nenv_allowlist = ["PATH", "CHECK_POLICY"]') - if fixed: - config = config.replace("[checks]", '[checks]\nenv = { CHECK_POLICY = "old" }') - config_path.write_text(config) - - monkeypatch.setenv("CHECK_POLICY", "old") - assert run(capsys, *args, "check")[0] == 0 - monkeypatch.setenv("CHECK_POLICY", "new") - code, out, _ = run(capsys, *args, "ready") - if fixed: - assert code == 0 - else: - assert code == 1 and "not ready: check receipt has an incompatible settings fingerprint." in out - - @pytest.mark.parametrize("worker", ["legacy", "different-environment", "matching"]) def test_ready_checks_transferred_whole_job_receipt(wt, gh, capsys, head, tmp_path, monkeypatch, worker): policy = WORKFLOW.replace( @@ -3722,7 +3735,7 @@ def test_status_full(wt: Path, gh: FakeGh, capsys, git_calls) -> None: (wt / "scratch").write_text("x") git_calls.clear() code, out, _ = run(capsys, "status") - assert_git_cost(git_calls, 7, 1) + assert_git_cost(git_calls, 8, 1) assert code == 0 and "dirty: yes" in out assert f"pr: #7 {URL} (draft, OPEN)" in out assert f"review: primary on {head[:12]} (approved)" in out @@ -4628,7 +4641,7 @@ def test_review_discloses_fallback_for_all_contributing_families(wt, gh, fake_bi assert not (fake_bin / "codex.stdin").exists() assert f"Same-family fallback: {reason}. Cross-family review is preferred." in posted_review(gh)["body"] kind = "delta" if lineage == "delta" else "primary" - assert cli._load_review(wt, head, kind).fallback == reason + assert cli._load_review(wt, head, kind)[0].fallback == reason def test_repost_rejects_saved_contributor_review( @@ -4705,20 +4718,6 @@ def test_load_report_requires_integer_exit_code(wt, head, capsys, exit_code, ok) assert report.head == head -def test_passive_receipt_load_is_silent(wt, gh, capsys, head): - arm_approved_ready_pr(gh, head, wt) - cli._load_report(wt) - cli._validation_section(wt, head, cli.config_mod.load(wt / "workflow.toml")) - assert "receipt " not in capsys.readouterr().out - - -def test_dirty_check_does_not_claim_committed_receipt(wt, capsys): - (wt / "README.md").write_text("uncommitted content") - code, out, _ = run(capsys, "check") - assert code == 0 and out.endswith("PASS\n") - assert "receipt produced:" not in out - - @pytest.mark.parametrize("case", ["dirty", "unpushed", "after-head-read"]) def test_cleanup_preserves_local_work(wt, case, capsys, monkeypatch): pr = SimpleNamespace(head_sha=cli.worktree.head(wt)) @@ -4769,11 +4768,11 @@ def test_wait_rechecks_closed_unmerged_pr(monkeypatch, final) -> None: @pytest.mark.parametrize("redirected", [False, True]) -def test_checks_report_survives_failed_publication(tmp_path, monkeypatch, redirected): - path = tmp_path / cli.CHECKS_FILE +def test_checks_report_survives_failed_publication(git_repo, tmp_path, monkeypatch, redirected): + path = git_repo / 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, ())) + cli._save_report(git_repo, CheckReport("a" * 40, False, ())) def interrupt(staged, dest, *, src_dir_fd, dst_dir_fd): assert src_dir_fd == dst_dir_fd and dest == path.name @@ -4785,17 +4784,18 @@ def interrupt(staged, dest, *, src_dir_fd, dst_dir_fd): 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="Not a directory" if redirected else "publication interrupted"): - cli._save_report(tmp_path, CheckReport("b" * 40, False, ())) + error = cli.worktree.WorktreeError if redirected else OSError + with pytest.raises(error, match="symbolic link" if redirected else "publication interrupted"): + cli._save_report(git_repo, 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 = cli._review_file(git_repo, review.head, review.kind) receipt.write_text("user file") - with pytest.raises(OSError, match="Not a directory"): - cli._save_review(tmp_path, review) + with pytest.raises(cli.worktree.WorktreeError, match="symbolic link"): + cli._save_review(git_repo, review) assert receipt.read_text() == "user file" and external.stat().st_mode & 0o777 == 0o755 diff --git a/tests/test_codex_transport.py b/tests/test_codex_transport.py index bdb73fc5..152eb537 100644 --- a/tests/test_codex_transport.py +++ b/tests/test_codex_transport.py @@ -124,7 +124,7 @@ def packed(value): return packed_json(json.dumps(value, sort_keys=True, separators=(",", ":"))) -def test_large_real_native_private_public_saved_and_exact_bytes(native, tmp_path): +def test_large_real_native_private_public_saved_and_exact_bytes(native, git_repo): result = native[0]() assert len(result.raw.encode()) > 30000 evidence = runners.codex_evidence(result) @@ -147,10 +147,10 @@ def test_large_real_native_private_public_saved_and_exact_bytes(native, tmp_path parsed = projection(result) assert parsed == (True, evidence) assert eligible(row(result)) - cli._save_review(tmp_path, result) - path = tmp_path / evidence["receipt"] + cli._save_review(git_repo, result) + path = git_repo / evidence["receipt"] assert path.stat().st_mode & 0o777 == 0o600 and path.parent.stat().st_mode & 0o777 == 0o700 - loaded = cli._load_review(tmp_path, result.head, "primary") + loaded, _ = cli._load_review(git_repo, result.head, "primary") assert loaded.raw == result.raw and body(loaded) == rendered assert json.loads(path.read_text())["raw"] == result.raw @@ -477,7 +477,7 @@ def test_strict_projection_types_and_bounds(native, field, value): runners.decode_codex_evidence(packed(evidence)) -def test_legacy_toolfree_remains_unknown_without_projection(tmp_path): +def test_legacy_toolfree_remains_unknown_without_projection(git_repo): legacy = test_runners._native_codex_result("a" * 40) raw = json.loads(legacy.raw) raw.pop("review_context") @@ -486,8 +486,8 @@ def test_legacy_toolfree_remains_unknown_without_projection(tmp_path): rendered = body(legacy) assert runners.CODEX_HEADER not in rendered assert eligible(row(legacy)) - cli._save_review(tmp_path, legacy) - assert cli._load_review(tmp_path, legacy.head, "primary").raw == legacy.raw + cli._save_review(git_repo, legacy) + assert cli._load_review(git_repo, legacy.head, "primary")[0].raw == legacy.raw @pytest.mark.parametrize("change", [ @@ -519,7 +519,7 @@ def test_leading_block_is_anchored_and_schema_complete(published_native, change) assert present is (change != "fence") -def test_utf8_raw_is_hashed_exactly_and_local_replay_regenerates(native, tmp_path): +def test_utf8_raw_is_hashed_exactly_and_local_replay_regenerates(native, git_repo): result = native[0]() changed = dataclasses.replace( result, raw=json.dumps(json.loads(result.raw), ensure_ascii=False, indent=1) @@ -529,8 +529,8 @@ def test_utf8_raw_is_hashed_exactly_and_local_replay_regenerates(native, tmp_pat assert value["raw_bytes"] == len(changed.raw.encode()) assert value["raw_sha256"] == hashlib.sha256(changed.raw.encode()).hexdigest() assert value["raw_sha256"] != runners.codex_evidence(result)["raw_sha256"] - cli._save_review(tmp_path, changed) - loaded = cli._load_review(tmp_path, changed.head, changed.kind) + cli._save_review(git_repo, changed) + loaded, _ = cli._load_review(git_repo, changed.head, changed.kind) assert loaded.raw == changed.raw and body(loaded) == body(changed) diff --git a/tests/test_review_runtime.py b/tests/test_review_runtime.py index 0b038c1f..133f5c68 100644 --- a/tests/test_review_runtime.py +++ b/tests/test_review_runtime.py @@ -52,12 +52,12 @@ def result(row): @pytest.mark.parametrize("row", RECEIPTS, ids=lambda r: str(r["id"])) -def test_legacy_startup_failure_refuses_saved_result_and_multichunk(row, tmp_path): +def test_legacy_startup_failure_refuses_saved_result_and_multichunk(row, git_repo): bad = result(row) assert not runners.validate_runner_result(bad) - cli._save_review(tmp_path, bad) + cli._save_review(git_repo, bad) with pytest.raises(cli.CliError, match="provenance/envelope mismatch"): - cli._load_review(tmp_path, bad.head, bad.kind) + cli._load_review(git_repo, bad.head, bad.kind) clean = dataclasses.replace(bad, raw=json.dumps(envelope(row) | {"events": []})) with pytest.raises(runners.RunnerBadOutput, match="Code Mode"): runners.merge_reviews([clean, bad])