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
6 changes: 4 additions & 2 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -450,8 +450,10 @@ 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 can reuse a
passing receipt that satisfies readiness on a clean checkout. An exclusion
pathspec in the check inputs disables whole-receipt reuse. 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
57 changes: 43 additions & 14 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -643,21 +643,29 @@ 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
EXCLUSION_PATHSPEC = re.compile(r"^:(?:[/!^]*[!^]|\((?:[^,)]*,)*exclude(?:[,)]))")

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: Respect escaped commas when detecting exclusion magic

Git accepts :(attr:foo=a\,exclude)README.md as a positive pathspec matching the attribute value a,exclude. The regex treats the escaped comma as a separator and exclude as a magic keyword, so every subsequent check reruns despite a clean checkout and a valid passing receipt. Parse long-form magic using Git’s escape rules and cover this positive case alongside the existing exclusion cases.



def _reusable_check_report(wt: Path, config: Config) -> CheckReport | None:
if any(EXCLUSION_PATHSPEC.match(path) for paths in config.inputs.values() for path in paths):
return 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):
return None
head = worktree.head(wt)
report = _current_check_report(wt, config, head)
if report is not None and not worktree.is_dirty(wt) and worktree.head(wt) == head:
_refresh_existing_pr_checks(wt, config)
return report
return None


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 +682,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
40 changes: 20 additions & 20 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -427,25 +427,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:
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"
@pytest.mark.parametrize("exclusion", ["", ":!README.md", ":^README.md", ":(glob,exclude)README.md"])
def test_check_pass_writes_and_reuses_report(wt, gh, capsys, monkeypatch, exclusion):
if exclusion:
publish_workflow(wt, WORKFLOW.replace("[delivery]", f'[checks.inputs]\n"*" = ["{exclusion}"]\n[delivery]'))
out, _ = expect_cli(capsys, 0, "check")
pin, first, first_exit, second, second_exit, evidence, verdict = out.splitlines()
assert not gh.calls and verdict == "PASS" 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 re.fullmatch(f"receipt produced: head={report['head']} content=.* config=commands-sha256:.* environment=unknown", evidence)
assert [(r["command"], r["exit_code"], r["tail"]) for r in report["results"]] == [("echo ok", 0, "ok"), ("test -f README.md", 0, "")]
monkeypatch.setattr(cli.sandbox, "run_checks", stages := Mock(wraps=cli.sandbox.run_checks))
out, _ = expect_cli(capsys, 0, "check")
assert stages.called is bool(exclusion)
if not exclusion:
assert out.endswith("PASS\n") and "receipt reused from .loopzero/checks.json" in out and path.read_bytes() == original


@pytest.mark.parametrize("state", [None, "CLOSED", "MERGED"])
Expand Down Expand Up @@ -2382,7 +2382,7 @@ 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):
Expand Down
Loading