From f1b3b86977f9c42b7ee2e33b1ac88e0162e81793 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:48:34 +0100 Subject: [PATCH 1/4] Confine local task state to the worktree Co-Authored-By: Codex --- docs/ARCHITECTURE.md | 5 +- src/loopzero/cli.py | 69 ++++++------------- src/loopzero/sandbox.py | 4 +- src/loopzero/worktree.py | 124 ++++++++++++++++++++++++++-------- tests/test_cli.py | 100 +++++++++++++++++++++++---- tests/test_codex_transport.py | 20 +++--- tests/test_review_runtime.py | 6 +- 7 files changed, 219 insertions(+), 109 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index ddbcc678..f199c717 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -40,7 +40,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. Losing local artifacts may diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index b05a23dd..006d04a7 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -9,16 +9,14 @@ import importlib.metadata import io import json -import math import os +import math import shlex import random import re import sys -import tempfile import time from collections.abc import Callable, Iterator -from contextlib import contextmanager from datetime import UTC, datetime from functools import partial, wraps from pathlib import Path @@ -365,21 +363,8 @@ def _print_receipt(wt: Path, report: CheckReport, action: str) -> None: return -@contextmanager -def _lock_task_state(wt: Path) -> Iterator[None]: - directory = wt / ".loopzero" - directory.mkdir(parents=True, exist_ok=True) - fd = os.open(directory, os.O_RDONLY | os.O_DIRECTORY) - try: - fcntl.flock(fd, fcntl.LOCK_EX) - yield - 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, @@ -389,35 +374,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): - current_head = worktree.head(wt) - if report.head != current_head: - return current_head - _write_json_atomically(path, 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: - 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) + 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") @@ -426,6 +391,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 @@ -600,6 +567,7 @@ def cmd_start(args: argparse.Namespace) -> int: 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: @@ -739,6 +707,10 @@ def locked(args: argparse.Namespace) -> int: def cmd_review(args: argparse.Namespace, wt: Path, config: Config) -> int: 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) @@ -754,7 +726,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: @@ -784,7 +756,7 @@ def cmd_review(args: argparse.Namespace, wt: Path, config: Config) -> int: f"saved reviewer family {result.family} contributed to this PR lineage; " "run without --repost to obtain an independent review" ) - publication = json.loads(_review_file(wt, head, kind).read_text()).get("publication") + publication = json.loads(worktree.read_local_state(wt, _review_file(wt, head, kind).name)).get("publication") if publication is not None: if (not isinstance(publication, dict) or publication.get("repo") != config.repo or publication.get("number") != pr.number @@ -1090,22 +1062,18 @@ 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) + worktree.write_local_state(wt, path.name, json.dumps(data, indent=2) + "\n", private=True) def _load_review(wt: Path, head: str, kind: str) -> ReviewResult: 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()) + data = json.loads(worktree.read_local_state(wt, path.name)) + except FileNotFoundError: + raise CliError(f"no saved {kind} review for {head[:12]} at {path}; run without --repost") from None except (json.JSONDecodeError, OSError) as exc: raise CliError(f"{path} is not runner-produced: invalid saved review") from exc if not isinstance(data, dict): @@ -1136,6 +1104,7 @@ def _pr_readiness( """PR plus readiness; readiness is None only for an already merged PR (allow_merged).""" branch, head = worktree.branch(wt), worktree.head(wt) _require_task_branch(config, branch) + worktree.local_state_files(wt, CHECKS_FILE.name) pr = _require_pr(config, branch, allow_merged=allow_merged) _require_pushed(pr, head) if pr.state == "MERGED": diff --git a/src/loopzero/sandbox.py b/src/loopzero/sandbox.py index 868a83cb..12ccb55f 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 @@ -211,7 +211,7 @@ def _previous(config: Config, worktree: Path, settings_sha256: str) -> dict: if _git(config, worktree, "ls-files", "--", ".loopzero"): return {} 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 {} diff --git a/src/loopzero/worktree.py b/src/loopzero/worktree.py index f4a82f3a..4fa9ea28 100644 --- a/src/loopzero/worktree.py +++ b/src/loopzero/worktree.py @@ -3,9 +3,11 @@ from __future__ import annotations import errno +import fcntl +import os import re import stat -import tempfile +from contextlib import contextmanager, suppress from pathlib import Path from uuid import uuid4 @@ -85,6 +87,84 @@ def task_file(wt: Path) -> Path: return Path(wt) / ".loopzero" / "task.md" +@contextmanager +def _local_state_directory(wt: Path, *, create: 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: + yield fd + finally: + os.close(fd) + + +def _regular_state(wt: Path, fd: int, name: str) -> bool: + try: + mode = os.stat(name, dir_fd=fd, follow_symlinks=False).st_mode + except FileNotFoundError: + return False + if not stat.S_ISREG(mode): + raise WorktreeError(f"local state file is not regular or is a symbolic link: {wt / '.loopzero' / name}") + return True + + +def local_state_files(wt: Path, *names: str) -> tuple[bool, ...]: + """Validate the state directory and report which requested files exist.""" + try: + with _local_state_directory(wt) as fd: + return tuple(_regular_state(wt, fd, name) for name in names) + except FileNotFoundError: + return (False,) * len(names) + + +def read_local_state(wt: Path, name: str) -> str: + with _local_state_directory(wt) as fd: + if not _regular_state(wt, fd, name): + raise FileNotFoundError(wt / ".loopzero" / name) + file_fd = os.open(name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=fd) + with os.fdopen(file_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) as fd: + if expected_head is not None: + fcntl.flock(fd, fcntl.LOCK_EX) + current_head = head(wt) + if current_head != 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}"], @@ -178,30 +258,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: @@ -223,13 +290,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.name) + except FileNotFoundError: raise WorktreeError( f"missing {task}. 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() + ) from None def base_sha(wt: Path) -> str: diff --git a/tests/test_cli.py b/tests/test_cli.py index 356ca373..0e823dc8 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -120,12 +120,13 @@ 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(_source, dest, *, src_dir_fd, dst_dir_fd, follow_symlinks): + assert dest == task.name and src_dir_fd == dst_dir_fd and not follow_symlinks 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 @@ -523,6 +524,75 @@ def test_invalid_workflow_utf8_names_file(wt, capsys, explicit_config): assert "Traceback" not in err +@pytest.mark.parametrize("command", ["check", "review", "repost", "ready"]) +def test_commands_refuse_external_local_state( + wt, gh, fake_bin, capsys, tmp_path, command, +): + if command == "ready": + arm_approved_ready_pr(gh, head_of(wt), wt) + else: + prepare_review(wt, gh, fake_bin) + exclude = Path(git(wt, "rev-parse", "--path-format=absolute", "--git-path", "info/exclude").strip()) + with exclude.open("a") as stream: + stream.write("\n.loopzero\n") + external = tmp_path / "external-state" + state = wt / ".loopzero" + state.rename(external) + state.symlink_to(external, target_is_directory=True) + original = {file.name: file.read_bytes() for file in external.iterdir()} + external.chmod(0o755) + + argv = ["review", "--repost"] if command == "repost" else [command] + code, _, err = run(capsys, *argv) + + assert external.stat().st_mode & 0o777 == 0o755 + assert {file.name: file.read_bytes() for file in external.iterdir()} == original + assert code == 1 and "symbolic link" in err + + +@pytest.mark.parametrize("command,artifact", [ + ("check", "checks.json"), ("review", "task.md"), + ("review", "review-{head}-primary.json"), ("repost", "review-{head}-primary.json"), + ("ready", "checks.json"), +]) +def test_commands_refuse_linked_local_artifacts( + wt, gh, fake_bin, capsys, tmp_path, command, artifact, +): + if command == "ready": + arm_approved_ready_pr(gh, head_of(wt), wt) + else: + prepare_review(wt, gh, fake_bin) + state = wt / ".loopzero" + path = state / artifact.format(head=head_of(wt)[:12]) + sentinel = tmp_path / "sentinel" + sentinel.write_bytes(path.read_bytes() if path.exists() else b"external data") + original = sentinel.read_bytes() + path.unlink(missing_ok=True) + path.symlink_to(sentinel) + state.chmod(0o755) + + argv = ["review", "--repost"] if command == "repost" else [command] + code, _, err = run(capsys, *argv) + + assert sentinel.read_bytes() == original and path.is_symlink() + assert state.stat().st_mode & 0o777 == 0o755 + assert code == 1 and "symbolic link" in err + + +def test_check_rejects_tracked_local_state(wt, gh, capsys): + task = wt / ".loopzero/task.md" + original = task.read_bytes() + git(wt, "add", "-f", str(task)) + git(wt, "commit", "-qm", "track task state") + + code, _, err = run(capsys, "check") + + assert task.read_bytes() == original + assert not (wt / ".loopzero/checks.json").exists() + assert code == 1 and "repository-tracked local state" in err + assert not gh.calls + + 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"')) code, out, err = run(capsys, "check") @@ -1076,7 +1146,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).strip().encode("utf-8") git_calls.clear() code, out, err = run(capsys, "review") - assert_git_cost(git_calls, 16, 2) + assert_git_cost(git_calls, 19, 2) 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" == ( @@ -1994,7 +2064,7 @@ 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, 6, 1) + assert_git_cost(git_calls, 8, 1) 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] @@ -3294,7 +3364,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, 6, 1) + assert_git_cost(git_calls, 7, 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 @@ -4298,21 +4368,21 @@ def test_wait_raises_when_closed_unmerged_persists(monkeypatch) -> None: _closed_unmerged_wait(monkeypatch, ["closed", "closed"], steps=1) -def test_checks_report_survives_failed_publication(tmp_path, monkeypatch): - path = tmp_path / cli.CHECKS_FILE +def test_checks_report_survives_failed_publication(git_repo, monkeypatch): + 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): - 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 dest == path.name and src_dir_fd == dst_dir_fd + assert json.loads((path.parent / staged).read_text())["head"] == "b" * 40 + assert json.loads(path.read_text())["head"] == "a" * 40 raise OSError("publication interrupted") - monkeypatch.setattr(cli.os, "replace", interrupt) + monkeypatch.setattr(cli.worktree.os, "replace", interrupt) with pytest.raises(OSError, match="publication interrupted"): - cli._save_report(tmp_path, CheckReport("b" * 40, False, ())) + cli._save_report(git_repo, CheckReport("b" * 40, False, ())) assert json.loads(path.read_text())["head"] == "a" * 40 assert list(path.parent.iterdir()) == [path] diff --git a/tests/test_codex_transport.py b/tests/test_codex_transport.py index de241158..2542eb76 100644 --- a/tests/test_codex_transport.py +++ b/tests/test_codex_transport.py @@ -100,7 +100,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) @@ -125,10 +125,10 @@ def test_large_real_native_private_public_saved_and_exact_bytes(native, tmp_path assert eligibility.eligible_review( [row(result)], result.head, ("bot",), repo="acme/widgets", number=7 ) - 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 @@ -473,7 +473,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") @@ -484,8 +484,8 @@ def test_legacy_toolfree_remains_unknown_without_projection(tmp_path): assert eligibility.eligible_review( [row(legacy)], legacy.head, ("bot",), repo="acme/widgets", number=7 ) - 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").raw == legacy.raw @pytest.mark.parametrize("change", [ @@ -521,7 +521,7 @@ def test_leading_block_is_anchored_and_schema_complete(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) @@ -531,8 +531,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 34c14060..aff95fc4 100644 --- a/tests/test_review_runtime.py +++ b/tests/test_review_runtime.py @@ -50,12 +50,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]) From 2a20919f9d9612b123c231ad6aeeebc5598ea0d8 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:11:16 +0100 Subject: [PATCH 2/4] Reuse guarded reads and report serialization Architecture-Review: unchanged; Descriptor-relative access and guarded check publication remain the authority for local state. Co-Authored-By: Codex --- src/loopzero/cli.py | 18 ++++++------------ src/loopzero/sandbox.py | 8 +++----- src/loopzero/worktree.py | 26 +++++++++----------------- tests/test_cli.py | 2 +- 4 files changed, 19 insertions(+), 35 deletions(-) diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 7ff343f3..372a481a 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -9,11 +9,11 @@ import importlib.metadata import io import json -import os import math -import shlex +import os import random import re +import shlex import sys import time from collections.abc import Callable, Iterator @@ -372,15 +372,10 @@ def _print_receipt(wt: Path, report: CheckReport, action: str) -> None: def _save_report(wt: Path, report: CheckReport) -> str | None: """Publish the receipt or return the current HEAD if the result is stale.""" - payload = { - "head": report.head, - "dirty": report.dirty, - "results": [{k: v for k, v in dataclasses.asdict(result).items() - if k not in {"input_key", "reused_from"} or v is not None} - for result in report.results], - } - if report.settings_sha256 is not None: - payload["settings_sha256"] = report.settings_sha256 + payload = {key: value for key, value in dataclasses.asdict(report).items() if value is not None} + payload["results"] = [ + {key: value for key, value in result.items() if value is not None} for result in payload["results"] + ] return worktree.write_local_state( wt, CHECKS_FILE.name, json.dumps(payload, indent=2) + "\n", expected_head=report.head, ) @@ -1117,7 +1112,6 @@ def _pr_readiness( """PR plus readiness; readiness is None only for an already merged PR (allow_merged).""" branch, head = worktree.branch(wt), worktree.head(wt) _require_task_branch(config, branch) - worktree.local_state_files(wt, CHECKS_FILE.name) pr = _require_pr(config, branch, allow_merged=allow_merged) _require_pushed(pr, head) if pr.state == "MERGED": diff --git a/src/loopzero/sandbox.py b/src/loopzero/sandbox.py index 4dcc4922..d8b9de29 100644 --- a/src/loopzero/sandbox.py +++ b/src/loopzero/sandbox.py @@ -149,7 +149,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") @@ -229,9 +229,7 @@ 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(read_local_state(worktree, "checks.json")) if (data["dirty"] is not False or not isinstance(data["head"], str) @@ -249,7 +247,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 933c37c0..b378fcb8 100644 --- a/src/loopzero/worktree.py +++ b/src/loopzero/worktree.py @@ -106,28 +106,21 @@ def _local_state_directory(wt: Path, *, create: bool = False): def _regular_state(wt: Path, fd: int, name: str) -> bool: - try: - mode = os.stat(name, dir_fd=fd, follow_symlinks=False).st_mode - except FileNotFoundError: - return False - if not stat.S_ISREG(mode): - raise WorktreeError(f"local state file is not regular or is a symbolic link: {wt / '.loopzero' / name}") - return True + 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, ...]: - """Validate the state directory and report which requested files exist.""" - try: - with _local_state_directory(wt) as fd: - return tuple(_regular_state(wt, fd, name) for name in names) - except FileNotFoundError: - return (False,) * len(names) + 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: - if not _regular_state(wt, fd, name): - raise FileNotFoundError(wt / ".loopzero" / name) file_fd = os.open(name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=fd) with os.fdopen(file_fd, encoding="utf-8") as stream: if not stat.S_ISREG(os.fstat(stream.fileno()).st_mode): @@ -142,8 +135,7 @@ def write_local_state( with _local_state_directory(wt, create=True) as fd: if expected_head is not None: fcntl.flock(fd, fcntl.LOCK_EX) - current_head = head(wt) - if current_head != expected_head: + if (current_head := head(wt)) != expected_head: return current_head _regular_state(wt, fd, name) if private: diff --git a/tests/test_cli.py b/tests/test_cli.py index 6c84015a..63e396c8 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -2183,7 +2183,7 @@ 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, 7, 1) 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] From 6cb497747def833d5fa47325de77770d606b7f8e Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:28:42 +0100 Subject: [PATCH 3/4] Serialize local state receipts without redundant paths Architecture-Review: unchanged; Local state still uses the same guarded directory and receipt format. Co-Authored-By: Codex --- src/loopzero/cli.py | 12 ++++-------- src/loopzero/worktree.py | 19 +++++++++---------- 2 files changed, 13 insertions(+), 18 deletions(-) diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 7bbd06cc..2c49bf99 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -339,14 +339,10 @@ def _print_receipt(wt: Path, report: CheckReport, action: str) -> None: def _save_report(wt: Path, report: CheckReport) -> str | None: - """Publish the receipt or return the current HEAD if the result is stale.""" - payload = {key: value for key, value in dataclasses.asdict(report).items() if value is not None} - payload["results"] = [ - {key: value for key, value in result.items() if value is not None} for result in payload["results"] - ] - return worktree.write_local_state( - wt, CHECKS_FILE.name, json.dumps(payload, indent=2) + "\n", expected_head=report.head, - ) + payload = dataclasses.asdict( + report, dict_factory=lambda fields: {key: value for key, value in fields if value is not None}) + text = json.dumps(payload, indent=2) + "\n" + return worktree.write_local_state(wt, CHECKS_FILE.name, text, expected_head=report.head) def _load_report(wt: Path) -> CheckReport | None: diff --git a/src/loopzero/worktree.py b/src/loopzero/worktree.py index b378fcb8..65ec3076 100644 --- a/src/loopzero/worktree.py +++ b/src/loopzero/worktree.py @@ -120,12 +120,12 @@ def local_state_files(wt: Path, *names: str) -> tuple[bool, ...]: def read_local_state(wt: Path, name: str) -> str: - with _local_state_directory(wt) as fd: - file_fd = os.open(name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=fd) - with os.fdopen(file_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() + 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( @@ -198,7 +198,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}") @@ -281,12 +281,11 @@ def branch(wt: Path) -> str: def task_text(wt: Path) -> str: - task = task_file(wt) try: - return read_local_state(wt, task.name) + 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" ) from None From 2c8f4408a58f07d58e82609273e7238d6cd5138f Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:46:08 +0100 Subject: [PATCH 4/4] Read saved review and publication metadata together Architecture-Review: unchanged; Repost now validates one private receipt snapshot for both review and publication. Co-Authored-By: Codex --- src/loopzero/cli.py | 34 +++++++++++++--------------------- tests/test_cli.py | 4 ++-- tests/test_codex_transport.py | 6 +++--- 3 files changed, 18 insertions(+), 26 deletions(-) diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 2c49bf99..5e333642 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -321,9 +321,7 @@ def _check_report_matches(report: CheckReport, wt: Path, config: Config, head: s def _current_check_report(wt: Path, config: Config, head: str) -> CheckReport | None: report = _load_report(wt) - if report is not None and report.ok and _check_report_matches(report, wt, config, head): - return report - return None + return report if report and report.ok and _check_report_matches(report, wt, config, head) else None def _print_receipt(wt: Path, report: CheckReport, action: str) -> None: @@ -714,7 +712,7 @@ def cmd_review(args: argparse.Namespace, wt: Path, config: Config) -> int: if args.repost: authors = runners.author_families(wt, head, _primary_base(wt, config)) excluded = [family for family in config.reviewers if family in authors] - result = _load_review(wt, head, kind) + result, publication = _load_review(wt, head, kind) if result.fallback and result.family not in excluded: raise CliError( f"saved review claims a same-family fallback, but {result.family} is not a configured " @@ -729,7 +727,6 @@ def cmd_review(args: argparse.Namespace, wt: Path, config: Config) -> int: f"saved reviewer family {result.family} contributed to this PR lineage; " "run without --repost to obtain an independent review" ) - publication = json.loads(worktree.read_local_state(wt, _review_file(wt, head, kind).name)).get("publication") if publication is not None: if (not isinstance(publication, dict) or publication.get("repo") != config.repo or publication.get("number") != pr.number @@ -1038,26 +1035,19 @@ 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 + 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) -> ReviewResult: +def _load_review(wt: Path, head: str, kind: str) -> tuple[ReviewResult, object]: path = _review_file(wt, head, kind) try: data = json.loads(worktree.read_local_state(wt, path.name)) - except FileNotFoundError: - raise CliError(f"no saved {kind} review for {head[:12]} at {path}; run without --repost") from None - except (json.JSONDecodeError, 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.pop("publication", None) + 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]}") + publication = data.pop("publication", None) if data.get("kind") != kind: raise ValueError("saved review kind mismatch") findings = tuple(Finding(**f) for f in data["findings"]) @@ -1067,11 +1057,13 @@ def _load_review(wt: Path, head: str, kind: str) -> ReviewResult: 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, publication def _pr_readiness( diff --git a/tests/test_cli.py b/tests/test_cli.py index def6f8a2..299f2e62 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1733,7 +1733,7 @@ def test_review_with_every_supported_family_authoring_uses_disclosed_fallback( reason = "every configured family contributed (claude, codex)" assert f"same-family fallback: {reason}" in err assert f"Same-family fallback: {reason}. Cross-family review is preferred." in posted_review(gh)["body"] - assert cli._load_review(wt, head, "primary").fallback == reason + assert cli._load_review(wt, head, "primary")[0].fallback == reason @pytest.mark.parametrize("family,configured,note,code,diagnostic,no_post", [ @@ -2049,7 +2049,7 @@ def test_review_observes_new_codex_version_in_saved_receipt( code, out, err = run(capsys, "review") assert code == 0 and "review by codex" in out 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 diff --git a/tests/test_codex_transport.py b/tests/test_codex_transport.py index 2542eb76..01123a5c 100644 --- a/tests/test_codex_transport.py +++ b/tests/test_codex_transport.py @@ -128,7 +128,7 @@ def test_large_real_native_private_public_saved_and_exact_bytes(native, git_repo 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(git_repo, 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 @@ -485,7 +485,7 @@ def test_legacy_toolfree_remains_unknown_without_projection(git_repo): [row(legacy)], legacy.head, ("bot",), repo="acme/widgets", number=7 ) cli._save_review(git_repo, legacy) - assert cli._load_review(git_repo, legacy.head, "primary").raw == legacy.raw + assert cli._load_review(git_repo, legacy.head, "primary")[0].raw == legacy.raw @pytest.mark.parametrize("change", [ @@ -532,7 +532,7 @@ def test_utf8_raw_is_hashed_exactly_and_local_replay_regenerates(native, git_rep assert value["raw_sha256"] == hashlib.sha256(changed.raw.encode()).hexdigest() assert value["raw_sha256"] != runners.codex_evidence(result)["raw_sha256"] cli._save_review(git_repo, changed) - loaded = cli._load_review(git_repo, changed.head, changed.kind) + loaded, _ = cli._load_review(git_repo, changed.head, changed.kind) assert loaded.raw == changed.raw and body(loaded) == body(changed)