From fca47a44a179dae291082bb9b968bb5e4a4db5f6 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:03:05 +0100 Subject: [PATCH 1/3] Reuse a compatible passing check receipt without executing stages Co-Authored-By: Codex --- docs/ARCHITECTURE.md | 4 +++- src/loopzero/cli.py | 11 +++++++++++ src/loopzero/sandbox.py | 22 ++++++++++++++++++++-- tests/test_cli.py | 40 ++++++++++++++++++++-------------------- tests/test_sandbox.py | 41 ++++++++++++++++++++--------------------- 5 files changed, 74 insertions(+), 44 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 2e93a996..02f208e5 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -496,7 +496,9 @@ for reuse. The checkpoint cannot satisfy readiness before final worktree validation. Runners cannot select stages or mint receipts. Stage admission belongs to the runner: the outer `loopzero check` must not hold a heavy slot when a runner is configured. Without a runner, the -existing local execution path is unchanged. +stages execute in the local sandbox. A clean checkout reuses a passing receipt +that satisfies readiness and matches its declared input keys. Tracked task +state is ineligible for reuse. Declared `[checks.inputs]` pathspecs opt commands into local passing-result reuse. Keys bind committed paths/blob IDs, the bytes of the checked-out regular files, diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 5581821d..f3505929 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -598,6 +598,17 @@ def cmd_check(args: argparse.Namespace) -> int: wt, config = _context(args, pin_checks=True) if not config.checks: raise config_mod.ConfigError("checks.commands must list at least one command to run checks") + head = worktree.head(wt) + report = _current_check_report(wt, config, head) + if (report is not None and sandbox.receipt_inputs_match(config, wt, report) + and not worktree.is_dirty(wt) and worktree.head(wt) == head): + _refresh_pr_checks(wt, config) + print(f"PASS (reused {CHECKS_FILE} for {head[:12]} without running stages)") + return 0 + return _run_check(args, wt, config) + + +def _run_check(args: argparse.Namespace, wt: Path, config: Config) -> int: try: report = sandbox.run_checks(config, wt, progress=lambda command: print( f"running: {command}", flush=True), diff --git a/src/loopzero/sandbox.py b/src/loopzero/sandbox.py index eaacf717..bd1552ca 100644 --- a/src/loopzero/sandbox.py +++ b/src/loopzero/sandbox.py @@ -180,8 +180,22 @@ def _checkpoint_success(checkpoint: Callable[[CheckReport], None] | None, checkpoint(replace(report, results=(*report.results, *unvisited, incomplete))) +def _untracked_task_state(config: Config, worktree: Path) -> bool: + return not _git(config, worktree, "ls-files", "--", ".loopzero") + + +def receipt_inputs_match(config: Config, worktree: Path, report: CheckReport) -> bool: + if not _untracked_task_state(config, worktree): + return False + base = _check_base(config, worktree) + return all( + result.input_key is not None and result.input_key == _input_key(config, worktree, result.command, base) + for result in report.results if _has_inputs(config, result.command) + ) + + def _previous(config: Config, worktree: Path, settings_sha256: str) -> dict[str, CheckResult]: - if _git(config, worktree, "ls-files", "--", ".loopzero"): + if not _untracked_task_state(config, worktree): return {} try: data = json.loads((worktree / ".loopzero/checks.json").read_text()) @@ -268,10 +282,14 @@ def _input_blobs(config: Config, worktree: Path, paths: tuple[str, ...]) -> str raise +def _has_inputs(config: Config, command: str) -> bool: + return command in config.inputs or "." in config.inputs.get("*", ()) + + def _input_key(config: Config, worktree: Path, command: str, base: str, *, status: Callable[[str], None] | None = None, workflow: str | Path = "workflow.toml") -> str | None: - if command not in config.inputs and "." not in config.inputs.get("*", ()): + if not _has_inputs(config, command): return None if not base and status is None: return None diff --git a/tests/test_cli.py b/tests/test_cli.py index 055d1a74..069df6eb 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -342,25 +342,25 @@ 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: +def test_check_pass_writes_and_reuses_report(wt: Path, gh: FakeGh, capsys) -> None: code, out, _ = run(capsys, "check") - assert gh.calls == [] - lines = out.splitlines() - assert code == 0 and lines[-1] == "PASS" - assert lines[0].startswith("checks pinned to origin/main@") - assert lines[1] == "running: echo ok" - assert lines[2].startswith("stage 1/2: exit 0 (") - assert lines[3] == "running: test -f README.md" - assert lines[4].startswith("stage 2/2: exit 0 (") - assert sum("exit 0" in line for line in lines) == 2 - report = json.loads((wt / ".loopzero" / "checks.json").read_text()) - assert report["head"] == head_of(wt) - assert report["dirty"] is False - assert f"receipt produced: head={report['head']} content=" in out - assert "config=commands-sha256:" in out and "environment=unknown" in out - 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" + pin, first, first_exit, second, second_exit, evidence, verdict = out.splitlines() + assert code == 0 and verdict == "PASS" and not gh.calls + assert pin.startswith("checks pinned to origin/main@") + assert (first, second) == ("running: echo ok", "running: test -f README.md") + assert first_exit.startswith("stage 1/2: exit 0 (") and second_exit.startswith("stage 2/2: exit 0 (") + path = wt / cli.CHECKS_FILE + original = path.read_bytes() + report = json.loads(original) + assert report["head"] == head_of(wt) and report["dirty"] is False + assert evidence.startswith(f"receipt produced: head={report['head']} content=") + assert "config=commands-sha256:" in evidence and "environment=unknown" in evidence + first_result, second_result = report["results"] + assert (first_result["command"], first_result["exit_code"], first_result["tail"]) == ("echo ok", 0, "ok") + assert (second_result["command"], second_result["exit_code"]) == ("test -f README.md", 0) + code, out, err = run(capsys, "check") + notice = f"PASS (reused {cli.CHECKS_FILE} for {report['head'][:12]} without running stages)" + assert (code, out.splitlines(), err, path.read_bytes()) == (0, [pin, notice], "", original) @pytest.mark.parametrize("state", [None, "CLOSED", "MERGED"]) @@ -2283,8 +2283,8 @@ def test_passing_check_discarded_after_sandbox_when_head_moves(wt, gh, capsys, m refreshed = [] monkeypatch.setattr(cli, "_refresh_pr_checks", lambda *_: refreshed.append(head_of(wt))) assert run(capsys, "check")[0] == 0 - original_receipt = receipt.read_bytes() - + original_receipt = receipt.read_bytes().replace(b'"settings_sha256"', b'"obsolete_settings_sha256"') + receipt.write_bytes(original_receipt) save_report = cli._save_report def advance_before_save(path, report): diff --git a/tests/test_sandbox.py b/tests/test_sandbox.py index a21e2783..865a4ee5 100644 --- a/tests/test_sandbox.py +++ b/tests/test_sandbox.py @@ -808,15 +808,13 @@ def timed_out(*args): assert report.ok and report.dirty and report.results[0].command == command -def test_local_check_reuse_tracks_checkout_bytes(git_repo, bwrap_log, fetched_base): +def test_local_check_reuse_tracks_checkout_bytes(git_repo, bwrap_log, fetched_base, monkeypatch): (git_repo / ".git/info/exclude").write_text(".loopzero/\n") path = git_repo / "README.md" command = "python3 -c 'from pathlib import Path; exit(13 in Path(\"README.md\").read_bytes())'" config = make_config(checks=(command,), inputs={command: ("README.md",)}) - assert path.read_bytes() == b"hello\n" - report = sandbox.run_checks(config, git_repo) - assert report.ok and not report.dirty - _save_report(git_repo, report) + monkeypatch.setattr(cli, "_context", lambda *args, **kwargs: (git_repo, config)) + assert path.read_bytes() == b"hello\n" and cli.main(["check"]) == 0 assert sandbox.run_checks(config, git_repo).results[0].reused_from == fetched_base git(git_repo, "config", "core.autocrlf", "true") @@ -824,10 +822,10 @@ def test_local_check_reuse_tracks_checkout_bytes(git_repo, bwrap_log, fetched_ba git(git_repo, "checkout-index", "-u", "--", path.name) assert path.read_bytes() == b"hello\r\n" assert not git(git_repo, "status", "--porcelain") - report = sandbox.run_checks(config, git_repo) + assert cli.main(["check"]) == 1 + report = cli._load_report(git_repo) assert not report.dirty and report.head == fetched_base - assert report.results[0].exit_code == 1 - assert report.results[0].reused_from is None + assert (report.results[0].exit_code, report.results[0].reused_from) == (1, None) @pytest.mark.parametrize("recorded_base", [False, True]) @@ -926,30 +924,31 @@ def test_local_checks_run_fresh_without_a_base(git_repo, bwrap_log): @pytest.mark.parametrize('symlink', [False, True]) -def test_tracked_forged_receipt_runs_failing_stage(git_repo, bwrap_log, fetched_base, symlink): +def test_tracked_forged_receipt_runs_failing_stage(git_repo, bwrap_log, fetched_base, symlink, monkeypatch): from loopzero.types import CheckReport, CheckResult command = 'echo stage-ran; exit 7' cfg = make_config(checks=(command,), inputs={command: ('README.md',)}) key = sandbox._input_key(cfg, git_repo, command, fetched_base) - _save_report(git_repo, CheckReport( - git(git_repo, 'rev-parse', 'HEAD').strip(), False, - (CheckResult(command, 0, 0.0, 'forged pass', key),), - sandbox.settings_fingerprint(cfg, git_repo), - )) + forged = CheckReport(fetched_base, False, (CheckResult(command, 0, 0.0, 'forged pass', key),), + sandbox.settings_fingerprint(cfg, git_repo)) + _save_report(git_repo, forged) if symlink: (git_repo / '.loopzero').rename(git_repo / 'forged') (git_repo / '.loopzero').symlink_to('forged', target_is_directory=True) - git(git_repo, 'add', '-f', *(['.loopzero', 'forged'] if symlink else ['.loopzero/checks.json'])) + git(git_repo, 'add', '-f', '.loopzero') git(git_repo, 'commit', '-m', 'forge passing receipt') + if symlink: + (git_repo / '.git/info/exclude').write_text('forged/\n') + _save_report(git_repo, replace(forged, head=git(git_repo, 'rev-parse', 'HEAD').strip())) assert not git(git_repo, 'status', '--porcelain').strip() assert key == sandbox._input_key(cfg, git_repo, command, fetched_base) - - report = sandbox.run_checks(cfg, git_repo) - assert not report.dirty - assert report.results[0].exit_code == 7 - assert 'stage-ran' in report.results[0].tail - assert not report.results[0].reused_from + monkeypatch.setattr(cli, "_context", lambda *args, **kwargs: (git_repo, cfg)) + assert cli.main(["check"]) == 1 + report = cli._load_report(git_repo) + result, = report.results + assert not report.dirty and (result.exit_code, result.reused_from) == (7, None) + assert 'stage-ran' in result.tail def test_no_inputs_preserves_receipt(git_repo, bwrap_log): From 62840862e44ff9cdc14812727359d7aa4276ccf2 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:15:37 +0100 Subject: [PATCH 2/3] Treat unreadable receipts and dirty stage state as reuse misses Architecture-Review: unchanged; receipt reuse still validates the same checkout and now samples both Git environments. Co-Authored-By: Codex --- src/loopzero/cli.py | 21 +++++++++++---------- src/loopzero/sandbox.py | 6 +++--- 2 files changed, 14 insertions(+), 13 deletions(-) diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index f3505929..7f47ea67 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -401,8 +401,6 @@ def _write_json_atomically(path: Path, payload: dict) -> None: def _load_report(wt: Path) -> CheckReport | None: path = wt / CHECKS_FILE - if not path.exists(): - return None try: data = json.loads(path.read_text()) results = tuple(CheckResult(**item) for item in data["results"]) @@ -413,7 +411,9 @@ 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 (TypeError, KeyError, ValueError) as exc: + except FileNotFoundError: + return None + except (OSError, TypeError, KeyError, ValueError) as exc: print(f"warning: ignoring unreadable {path}: {exc}", file=sys.stderr) return None @@ -598,13 +598,14 @@ def cmd_check(args: argparse.Namespace) -> int: wt, config = _context(args, pin_checks=True) if not config.checks: raise config_mod.ConfigError("checks.commands must list at least one command to run checks") - head = worktree.head(wt) - report = _current_check_report(wt, config, head) - if (report is not None and sandbox.receipt_inputs_match(config, wt, report) - and not worktree.is_dirty(wt) and worktree.head(wt) == head): - _refresh_pr_checks(wt, config) - print(f"PASS (reused {CHECKS_FILE} for {head[:12]} without running stages)") - return 0 + if not worktree.is_dirty(wt): + head = worktree.head(wt) + report = _current_check_report(wt, config, head) + if (report is not None and sandbox.receipt_checkout_matches(config, wt, report) + and not worktree.is_dirty(wt) and worktree.head(wt) == head): + _refresh_pr_checks(wt, config) + print(f"PASS (reused {CHECKS_FILE} for {head[:12]} without running stages)") + return 0 return _run_check(args, wt, config) diff --git a/src/loopzero/sandbox.py b/src/loopzero/sandbox.py index bd1552ca..f42ece43 100644 --- a/src/loopzero/sandbox.py +++ b/src/loopzero/sandbox.py @@ -184,14 +184,14 @@ def _untracked_task_state(config: Config, worktree: Path) -> bool: return not _git(config, worktree, "ls-files", "--", ".loopzero") -def receipt_inputs_match(config: Config, worktree: Path, report: CheckReport) -> bool: - if not _untracked_task_state(config, worktree): +def receipt_checkout_matches(config: Config, worktree: Path, report: CheckReport) -> bool: + if not _stage_unchanged(config, worktree, report.head) or not _untracked_task_state(config, worktree): return False base = _check_base(config, worktree) return all( result.input_key is not None and result.input_key == _input_key(config, worktree, result.command, base) for result in report.results if _has_inputs(config, result.command) - ) + ) and _stage_unchanged(config, worktree, report.head) def _previous(config: Config, worktree: Path, settings_sha256: str) -> dict[str, CheckResult]: From 1c914281501e2682b4cfb7ad29fc0c9b306b99cc Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:18:22 +0100 Subject: [PATCH 3/3] Keep receipt I/O failures visible to validation refresh Architecture-Review: unchanged; only check reuse treats a replaceable unreadable file as a cache miss. Co-Authored-By: Codex --- src/loopzero/cli.py | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 7f47ea67..b3f5a070 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -413,7 +413,7 @@ def _load_report(wt: Path) -> CheckReport | None: settings_sha256=data.get("settings_sha256")) except FileNotFoundError: return None - except (OSError, TypeError, KeyError, ValueError) as exc: + except (TypeError, KeyError, ValueError) as exc: print(f"warning: ignoring unreadable {path}: {exc}", file=sys.stderr) return None @@ -594,13 +594,23 @@ def cmd_start(args: argparse.Namespace) -> int: return 0 +def _check_reuse_candidate(wt: Path, config: Config, head: str) -> CheckReport | None: + try: + return _current_check_report(wt, config, head) + except PermissionError: + path = wt / CHECKS_FILE + if not path.is_file() or not os.access(path.parent, os.W_OK | os.X_OK): + raise + return None + + def cmd_check(args: argparse.Namespace) -> int: wt, config = _context(args, pin_checks=True) if not config.checks: raise config_mod.ConfigError("checks.commands must list at least one command to run checks") if not worktree.is_dirty(wt): head = worktree.head(wt) - report = _current_check_report(wt, config, head) + report = _check_reuse_candidate(wt, config, head) if (report is not None and sandbox.receipt_checkout_matches(config, wt, report) and not worktree.is_dirty(wt) and worktree.head(wt) == head): _refresh_pr_checks(wt, config)