Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 8 additions & 7 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -450,8 +450,9 @@ index, README and AGENTS guidance without network access. The repository's
CI enforce it against the event's base SHA. Push-to-main CI runs `--links-only`, because squash merging
can drop authored trailers and landed history cannot re-establish the pre-merge
acknowledgement; that mode still rejects broken local links and anchors.
`loopzero check` pins checks to trusted base configuration, so run a new or
changed gate directly until its configuration lands on the base.
`loopzero check` pins checks to trusted base configuration and reuses a passing
receipt when readiness validation, the clean checkout and declared inputs still
match. Run a new or changed gate directly until its configuration lands on the base.

The checker watches source-owned contracts, skill routing, the example and actual
workflow, hosted workflow files, itself, and selected CLI/configuration interfaces;
Expand Down Expand Up @@ -527,16 +528,16 @@ existing local execution path is unchanged.
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,
command, version, sandbox configuration and the resolved base SHA. A stage runs
fresh when a matched path cannot be identified as a readable regular file.
fresh when a declared pattern has no matches or a matched file cannot be hashed.
The receipt fingerprint also binds the base SHA when reuse
is configured, so advancing the base invalidates a pass at the same task head.
With explicit `--config`, reuse can fall back to the recorded task base if the
remote ref is absent. Without either base, local stages run fresh.
The `"*"` entry adds shared inputs to listed commands. Unlisted commands reuse only
when `"*"` includes `"."` (the whole tree); a partial or empty `"*"` leaves them unkeyed.
The `"*"` entry adds shared inputs to listed commands. For unlisted commands it
supplies a key only when `"*"` includes `"."` (the whole tree).
Consumers own complete input declarations.
Reuse only successful keyed stages from this worktree's clean receipt or
checkpoint. Dirty trees run fresh. A tracked receipt is never eligible for reuse.
For individual stage reuse, use only successful keyed results from this worktree's
clean receipt or checkpoint. Dirty trees run fresh. A tracked receipt is ineligible.
Receipts that use saved stage results bind the current head and check settings.
For delegated checks, both the receipt and the stage key bind the runner's launch
path, resolved executable path and executable bytes. Unavailable runner identity
Expand Down
53 changes: 39 additions & 14 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -629,6 +629,22 @@ def cmd_start(args: argparse.Namespace) -> int:
return 0


def _reusable_check_report(wt: Path, config: Config) -> CheckReport | None:
with suppress(OSError, sandbox.SandboxUnavailable, _proc.ProcTimeout, worktree.WorktreeError):
if not (wt / CHECKS_FILE).is_file():
return None
with _lock_task_state(wt):
if worktree.is_dirty(wt) or not sandbox.has_untracked_task_state(config, wt):
return None
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_existing_pr_checks(wt, config)
return report
return None


def _check_failure_preview(tail: str, limit: int = 1536) -> str:
if len(tail.encode()) <= limit:
return tail
Expand All @@ -643,21 +659,9 @@ def _check_failure_preview(tail: str, limit: int = 1536) -> str:
return preview.decode(errors="ignore")


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")
try:
report = sandbox.run_checks(config, wt, progress=lambda command: print(
f"running: {command}", flush=True),
status=lambda message: print(message, flush=True),
checkpoint=lambda partial: _save_report(wt, partial),
workflow=args.config or f"origin/{config.base_branch}:workflow.toml")
except sandbox.SandboxUnavailable as exc:
print(f"sandbox unavailable: {exc}", file=sys.stderr)
return 2
def _print_check_failures(config: Config, results: tuple[CheckResult, ...]) -> bool:
shortened = False
for result in report.results:
for result in results:
if result.exit_code != 0:
print(f"--- {result.command} (exit {result.exit_code}) ---", file=sys.stderr)
tail = _proc.tail(result.tail)
Expand All @@ -674,6 +678,27 @@ def cmd_check(args: argparse.Namespace) -> int:
"(use the required groups) so the cache under `[checks] writable` is warm, "
"or set `[checks] env` UV_CACHE_DIR to a warm cache.", file=sys.stderr,
)
return shortened


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 (receipt := _reusable_check_report(wt, config)) is not None:
_print_receipt(wt, receipt, f"reused from {CHECKS_FILE}")
print("PASS")
return 0
try:
report = sandbox.run_checks(config, wt, progress=lambda command: print(
f"running: {command}", flush=True),
status=lambda message: print(message, flush=True),
checkpoint=lambda partial: _save_report(wt, partial),
workflow=args.config or f"origin/{config.base_branch}:workflow.toml")
except sandbox.SandboxUnavailable as exc:
print(f"sandbox unavailable: {exc}", file=sys.stderr)
return 2
shortened = _print_check_failures(config, report.results)
if (current_head := _save_report(wt, report)) is not None:
print(f"check result discarded: checked HEAD {report.head}, current HEAD {current_head}",
file=sys.stderr)
Expand Down
42 changes: 38 additions & 4 deletions src/loopzero/sandbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
CHECK_TAIL_BYTES = 16 * 1024
FIRST_HEARTBEAT_DELAY = 30.0
HEARTBEAT_INTERVAL = 300.0
EXCLUSION_PATHSPEC = re.compile(r"^:(?:[/!^]*[!^]|\((?:[^,)]*,)*exclude(?:[,)]))")
SANDBOX_HOME = "/tmp/home"
# Only these system directories are exposed read-only by default; home tool paths
# require explicit `[checks] ro_paths`. Host homes, sockets and processes stay hidden.
Expand Down Expand Up @@ -184,8 +185,22 @@ def _checkpoint_success(checkpoint: Callable[[CheckReport], None] | None,
checkpoint(replace(report, results=(*report.results, *unvisited, incomplete)))


def has_untracked_task_state(config: Config, worktree: Path) -> bool:
return not _git(config, worktree, "ls-files", "--", ".loopzero")


def receipt_checkout_matches(config: Config, worktree: Path, report: CheckReport) -> bool:
if not _stage_unchanged(config, worktree, report.head):
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 result.command in config.inputs or "*" in config.inputs

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

important: Allow same-head receipt reuse with partial wildcard inputs

With inputs = {"*": ("README.md",)}, this filter requires an input key for every command, but _has_inputs prevents _input_key from producing one for any unlisted command. A second check therefore reruns stages even when HEAD, settings, and README.md are unchanged. Record and validate a head-bound key for these commands so the complete receipt can be reused while cross-head stage reuse stays disabled. Cover the unchanged second run alongside the existing checkout-byte change case.

) and _stage_unchanged(config, worktree, report.head)


def _previous(config: Config, worktree: Path, settings_sha256: str) -> dict[str, CheckResult]:
if _git(config, worktree, "ls-files", "--", ".loopzero"):
if not has_untracked_task_state(config, worktree):
return {}
try:
data = json.loads((worktree / ".loopzero/checks.json").read_text())
Expand Down Expand Up @@ -275,22 +290,41 @@ 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 _pathspec_matches(config: Config, worktree: Path, path: str) -> bool:
blobs = _input_blobs(config, worktree, (path,))
if EXCLUSION_PATHSPEC.match(path):
# Git applies an exclusion-only pathspec to the whole tree.
whole = _input_blobs(config, worktree, (".",))
return blobs is not None and whole is not None and blobs != whole
return bool(blobs)


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
entries = {key: config.inputs[key] for key in (command, "*") if key in config.inputs}
paths = tuple(path for group in entries.values() for path in group)
try:
blobs = _input_blobs(config, worktree, tuple(path for paths in entries.values() for path in paths))
blobs = _input_blobs(config, worktree, paths)
if blobs and not all(
_pathspec_matches(config, worktree, path)
for path in paths if len(paths) > 1 or EXCLUSION_PATHSPEC.match(path)
):
blobs = ""
except (SandboxUnavailable, _proc.ProcTimeout, OSError, ValueError):
if not base:
return None
raise
if blobs == "" and status:
status(f"{workflow}: checks.inputs for {command!r} matches no files in HEAD. "
status(f"{workflow}: checks.inputs for {command!r} is empty or has a pathspec that matches no files in HEAD. "
f"Correct these entries: {entries!r}. Running the check fresh.")
if not blobs or not base:
return None
Expand Down
51 changes: 31 additions & 20 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -427,25 +427,37 @@ 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:
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)]
@pytest.mark.parametrize("move_head", [False, True])

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

important: Meet the net-zero test-line requirement

The repository’s size check reports 13,786 test lines against 13,774 at base. The diff adds 11 net lines in tests/test_cli.py and one in tests/test_sandbox.py. Consolidate 12 lines of test setup or assertions while preserving coverage to meet the explicit net-zero requirement.

def test_check_pass_writes_and_reuses_report(wt, gh, capsys, monkeypatch, move_head):
out, _ = expect_cli(capsys, 0, "check")
pin, first, first_exit, second, second_exit, receipt, verdict = out.splitlines()
assert verdict == "PASS" and not gh.calls and 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 / ".loopzero/checks.json"
report = json.loads(original := path.read_bytes())
assert report["head"] == head_of(wt) and report["dirty"] is False
assert receipt.startswith(f"receipt produced: head={report['head']} content=") and "environment=unknown" in receipt
assert "config=commands-sha256:" in receipt
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"
reused = receipt.replace("receipt produced", "receipt reused from .loopzero/checks.json", 1)
with monkeypatch.context() as patch:
patch.setattr(cli.sandbox, "run_checks", Mock(side_effect=AssertionError("stages ran")))
expect_cli(capsys, 0, "check", stdout=f"{pin}\n{reused}\nPASS\n", stderr="")
assert path.read_bytes() == original

def change_checkout(*args, lock=cli._lock_task_state):
if move_head:
git(wt, "commit", "-qm", "advance HEAD", "--allow-empty")
return True
(wt / "README.md").write_text("edited while waiting\n")
return lock(*args)

target, hook = (cli.sandbox, "receipt_checkout_matches") if move_head else (cli, "_lock_task_state")
monkeypatch.setattr(target, hook, change_checkout)
expect_cli(capsys, 0, "check", stdout_contains=("running: echo ok",))
assert (updated := json.loads(path.read_bytes()))["head"] == head_of(wt) and updated["dirty"] is not move_head


@pytest.mark.parametrize("state", [None, "CLOSED", "MERGED"])
Expand Down Expand Up @@ -2382,9 +2394,8 @@ def test_late_check_preserves_receipt_when_head_moves(wt, gh, capsys, monkeypatc
monkeypatch.setattr(cli, "_refresh_pr_checks", lambda *_: refreshed.append(head_of(wt)))
if phase != "stage":
expect_cli(capsys, 0, "check")
saved_receipt = receipt.read_bytes()
receipt.write_bytes(saved_receipt := receipt.read_bytes().replace(b'"settings_sha256"', b'"obsolete_settings_sha256"'))
run_stage, run_checks, save_report = cli.sandbox._run_one, cli.sandbox.run_checks, cli._save_report

def advance_head(*, rerun=True):
nonlocal saved_receipt
git(wt, "commit", "--allow-empty", "-qm", "advance HEAD")
Expand Down
Loading
Loading