From 5c8d0e3a9cef984f390e6060fa8828512fd4d8dc Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 09:56:05 +0100 Subject: [PATCH 1/6] Refresh trusted publishers before local readiness Co-Authored-By: Codex --- docs/ARCHITECTURE.md | 7 ++++-- src/loopzero/cli.py | 7 ++++-- src/loopzero/config.py | 19 ++++++++++---- tests/test_cli.py | 57 +++++++++++++++++++++++++++++++++++++++--- 4 files changed, 78 insertions(+), 12 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 49620cba..a8878d44 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -45,8 +45,11 @@ 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 its current successful check receipt; hosted eligibility evaluates GitHub -review evidence using trusted base configuration. Losing local artifacts may -require rerunning checks or review, and never creates a hosted approval. +review evidence using trusted base configuration. Local readiness and merge fetch +the configured origin base once at startup before loading its publisher policy. +A receipt bound to the base may require a new check after that base advances. +Losing local artifacts may require rerunning checks or review, and never creates +a hosted approval. Saved runner artifacts also retain the repository, PR and actual request publisher before publication. A lost POST reply triggers a read-only reconciliation bounded by one 30-second transport deadline, with no read retries. Recovery regenerates diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index f1645fb8..d2c3aba3 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -125,6 +125,7 @@ def _repo_root(wt: Path) -> Path: def _load_config( args: argparse.Namespace, root: Path, *, pin_checks: bool = False, previous: Config | None = None, + refresh: bool = False, ) -> Config: path = args.config or root / "workflow.toml" if not pin_checks: @@ -132,7 +133,7 @@ def _load_config( if args.config: print("checks are unpinned because --config was provided") return config_mod.load(path) - config = config_mod.load_trusted(root, previous=previous) + config = config_mod.load_trusted(root, previous=previous, refresh=refresh) if args.command == "check": if not config.checks: raise config_mod.ConfigError( @@ -145,7 +146,9 @@ def _load_config( def _context(args: argparse.Namespace, *, pin_checks: bool = False) -> tuple[Path, Config]: wt = _toplevel() - return wt, _load_config(args, wt, pin_checks=pin_checks) + return wt, _load_config( + args, wt, pin_checks=pin_checks, refresh=args.command in {"ready", "merge"}, + ) def _is_ancestor(wt: Path, sha: str, head: str) -> bool: diff --git a/src/loopzero/config.py b/src/loopzero/config.py index 81388cfa..a6f72af2 100644 --- a/src/loopzero/config.py +++ b/src/loopzero/config.py @@ -108,12 +108,21 @@ def _has_replacement_refs(common_dir: Path) -> bool: return b" refs/replace/" in packed -def _remote_workflow(worktree: Path, branch: str, previous: Config | None) -> tuple[Config, str]: +def _remote_workflow(worktree: Path, branch: str, previous: Config | None, *, refresh: bool) -> tuple[Config, str]: source = f"origin/{branch}:workflow.toml" hint = "Fetch the trusted base workflow, or supply --config for bootstrap or an override." + ref = f"refs/remotes/origin/{branch}" + if refresh: + fetched = _proc.run( + ["git", "fetch", "--quiet", "--no-tags", "--no-recurse-submodules", + "--no-write-fetch-head", "origin", f"+refs/heads/{branch}:{ref}"], + cwd=worktree, env_allowlist=worktree_mod.GIT_ENV, timeout=60, + ) + if fetched.exit_code != 0: + raise ConfigError(f"could not refresh origin/{branch}. {hint}") directory_args = ["--path-format=absolute", "--git-common-dir"] if previous is not None else [] resolved = _proc.run( - ["git", "rev-parse", *directory_args, "--verify", f"refs/remotes/origin/{branch}^{{commit}}"], + ["git", "rev-parse", *directory_args, "--verify", f"{ref}^{{commit}}"], cwd=worktree, env_allowlist=worktree_mod.GIT_ENV, timeout=60, ) if resolved.exit_code != 0: @@ -140,7 +149,7 @@ def _remote_workflow(worktree: Path, branch: str, previous: Config | None) -> tu raise ConfigError(f"{source}: {exc}. {hint}") from None -def load_trusted(worktree: Path, *, previous: Config | None = None) -> Config: +def load_trusted(worktree: Path, *, previous: Config | None = None, refresh: bool = False) -> Config: """Select delivery policy using Git's origin default and its trusted workflow.""" prefix = "refs/remotes/origin/" default = _proc.run( @@ -154,10 +163,10 @@ def load_trusted(worktree: Path, *, previous: Config | None = None) -> Config: "or supply --config for bootstrap or an override." ) branch = ref.removeprefix(prefix) - policy, revision = _remote_workflow(worktree, branch, previous) + policy, revision = _remote_workflow(worktree, branch, previous, refresh=refresh) if policy.base_branch == branch: return replace(policy, trusted_base_revision=revision) - base, revision = _remote_workflow(worktree, policy.base_branch, previous) + base, revision = _remote_workflow(worktree, policy.base_branch, previous, refresh=refresh) if base.base_branch != policy.base_branch: raise ConfigError("trusted origin workflows disagree on repo.base; align them or supply --config") return replace(base, trusted_base_revision=revision) diff --git a/tests/test_cli.py b/tests/test_cli.py index 5c136d5d..a88db423 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -2192,7 +2192,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, 7, 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] @@ -2467,7 +2467,7 @@ def after_sleep(): @pytest.mark.parametrize("command", ["ready", "merge"]) @pytest.mark.parametrize("settled", ["CONFLICTING", "MERGEABLE", "UNKNOWN"]) -def test_wait_for_github_mergeability(wt, gh, capsys, monkeypatch, command, settled): +def test_wait_for_github_mergeability(wt, gh, capsys, monkeypatch, command, settled, git_calls): head = commit_mergify_configuration(wt) arm_approved_ready_pr(gh, head, wt, mergeable="UNKNOWN", isDraft=False) gh.respond_pr_view(pr_json(headRefOid=head, mergeable=settled, isDraft=False, @@ -2478,18 +2478,69 @@ def test_wait_for_github_mergeability(wt, gh, capsys, monkeypatch, command, sett monkeypatch.setattr(cli, "_wait_for_mergify", lambda *_: None) poll_clock(monkeypatch) + git_calls.clear() code, out, err = run(capsys, command, "--wait=1") + assert sum(call[0] == "fetch" for call in git_calls) == 1 if settled == "CONFLICTING": assert code == 1 and "has merge conflicts" in out + err elif settled == "UNKNOWN": - assert code == 3 and out.endswith(f"timed out waiting for GitHub to compute mergeability on {head[:12]}. Run `loopzero {command} --wait` to resume on this head.\n") + assert code == 3 and out.endswith(f"timed out waiting for GitHub to compute mergeability on {head[:12]}. Run `loopzero {command} --wait` to resume on this head.\n"), (code, out, err) else: assert code == (0 if command == "ready" else 3) assert requests == ([(REPO, 7, head, "main")] if command == "merge" and settled == "MERGEABLE" else []) +@pytest.mark.parametrize("publisher,expected", [ + ("retired-publisher", "pending"), ("replacement-publisher", "success"), +]) +def test_readiness_and_hosted_use_current_base_publishers(wt, gh, head, tmp_path, monkeypatch, capsys, + publisher, expected): + git(tmp_path, "clone", "-q", str(tmp_path / "origin.git"), "trusted") + trusted = tmp_path / "trusted" + workflow = trusted / "workflow.toml" + retired_workflow = (WORKFLOW.replace('required_ci = ["checks"]', + 'required_ci = ["checks", "Loop-zero Eligibility"]') + + 'review_publishers = ["retired-publisher"]\n') + workflow.write_text(retired_workflow) + git(trusted, "commit", "-qam", "trust old review publisher") + git(trusted, "push", "-q", "origin", "main") + git(wt, "fetch", "-q", "origin", "main") + stale = git(wt, "rev-parse", "origin/main") + + arm_approved_pr_with_check_result(gh, head, wt, "success", isDraft=False, review_login=publisher) + gh.respond(f"api repos/{REPO}/commits/{head}/statuses", + [{"context": "Loop-zero Eligibility", "state": "success"}]) + workflow.write_text(retired_workflow.replace("retired-publisher", "replacement-publisher")) + git(trusted, "commit", "-qam", "rotate review publisher") + git(trusted, "push", "-q", "origin", "main") + assert git(wt, "rev-parse", "origin/main") == stale + assert git(trusted, "rev-parse", "HEAD") != stale + + code, out, _ = run(capsys, "ready") + assert code == (0 if expected == "success" else 1) + assert (github.MISSING_REVIEW_REASON in out) == (expected == "pending") + if expected == "pending": + git(wt, "remote", "set-url", "origin", str(tmp_path / "unavailable.git")) + code, _, err = run(capsys, "ready") + assert code == 1 and "could not refresh origin/main" in err + explicit = tmp_path / "explicit.toml" + explicit.write_text(retired_workflow) + assert run(capsys, "--config", str(explicit), "ready")[0] == 0 + + event = trusted / "event.json" + event.write_text(json.dumps({"inputs": {"pr": "7"}})) + monkeypatch.chdir(trusted) + monkeypatch.setenv("GITHUB_REPOSITORY", REPO) + monkeypatch.setenv("GITHUB_EVENT_PATH", str(event)) + gh.respond(f"api repos/{REPO}/statuses/{head}", {}) + assert hosted.main() == 0 + payload = json.loads(gh.calls[-1]["--input"]) + assert gh.calls[-1]["argv"][1] == f"repos/{REPO}/statuses/{head}" + assert payload["state"] == expected + + @pytest.mark.parametrize("command,check,hold_at_admission", [ ("ready", "success", False), ("ready", "skipped", False), ("merge", "success", False), ("merge", "success", True), From 1e737f6470f5b55bc79a278d2ecd4e2e42607f5b Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:07:27 +0100 Subject: [PATCH 2/6] Exercise fetched remote state in readiness fixtures Co-Authored-By: Codex --- tests/test_cli.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/tests/test_cli.py b/tests/test_cli.py index a88db423..98ba15cd 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1445,13 +1445,16 @@ def test_review_runtime_paths_use_only_verified_base( def test_runtime_pinning_requires_trusted_workflow( wt: Path, gh: FakeGh, fake_bin: Path, capsys, command: str, missing: str, ) -> None: + origin = Path(git(wt, "remote", "get-url", "origin").strip()) if missing == "default": git(wt, "symbolic-ref", "--delete", "refs/remotes/origin/HEAD") elif missing == "remote": git(wt, "update-ref", "-d", "refs/remotes/origin/main") + git(origin, "update-ref", "-d", "refs/heads/main") else: - git(wt, "update-ref", "refs/remotes/origin/main", - git(wt, "rev-list", "--max-parents=0", "HEAD").strip()) + initial = git(wt, "rev-list", "--max-parents=0", "HEAD").strip() + git(wt, "update-ref", "refs/remotes/origin/main", initial) + git(origin, "update-ref", "refs/heads/main", initial) prepare_review(wt, gh, fake_bin) code, out, err = run(capsys, command) assert "reviewer paths" not in out + err @@ -2151,7 +2154,7 @@ def test_ready_after_reviewed_head( popen = subprocess.Popen def isolated_fetch(argv, **kwargs): - if "fetch" in argv: + if "fetch" in argv and f"https://github.com/{REPO}.git" in argv: if history == "missing history": raise cli.eligibility.candidate.CandidateError("history unavailable") argv = [wt.as_uri() if arg == f"https://github.com/{REPO}.git" else arg for arg in argv] @@ -3167,6 +3170,7 @@ def test_merged_bare_primary_cleans_only_clean_linked_worktree( repo: Path, gh: FakeGh, capsys, monkeypatch, state ) -> None: primary = repo.parent / "origin.git" + git(primary, "remote", "add", "origin", str(primary)) linked = repo.parent / "linked task" git(primary, "worktree", "add", "-q", "-b", "lz/bare", str(linked), "main") monkeypatch.chdir(linked) @@ -3696,7 +3700,7 @@ def test_commands_refuse_base_branch(wt: Path, gh: FakeGh, capsys, base) -> None git(wt, "checkout", "-q", "--ignore-other-worktrees", base) else: publish_workflow(wt, workflow.read_text()) - git(wt, "update-ref", f"refs/remotes/origin/{base}", "refs/remotes/origin/main") + git(wt, "push", "-q", "origin", f"origin/main:refs/heads/{base}") git(wt, "checkout", "-q", "-b", base) for command in ("pr", "review", "ready", "merge"): code, out, err = run(capsys, command) From 68705f1ec93f566cef7270a52b89f0a1ac8e4cff Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:15:27 +0100 Subject: [PATCH 3/6] Bound check failures and elapsed-time updates Architecture-Review: unchanged; the command data flow and delivery roles still apply. Co-Authored-By: Codex --- docs/ARCHITECTURE.md | 4 +-- src/loopzero/cli.py | 38 ++++++++++++++++--------- src/loopzero/sandbox.py | 7 +++-- tests/test_cli.py | 62 +++++++++++++++++++++++++++++++++++++++++ tests/test_sandbox.py | 5 ++-- 5 files changed, 96 insertions(+), 20 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 49620cba..5a9581c2 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -76,8 +76,8 @@ loading the delivery [commands](../src/loopzero/cli.py), which implement the con source sandbox. It inventories Git object stores only when alternates may be present. Its simple-command preflight catches missing local scripts, prepares recognized uv dependency groups offline in that sandbox and prints - progress before each command, metadata-only stage heartbeats every 30 seconds - (including silent children), and exit code/duration immediately after each stage. + progress before each command, a metadata-only heartbeat after 30 seconds and every + five minutes thereafter, and exit code/duration immediately after each stage. Heartbeats stop on completion or cancellation and never supply a verdict. Local stages drain merged child output and retain a bounded diagnostic tail. Trusted-base commands remain authoritative; diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index f1645fb8..bb4ef726 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -624,6 +624,20 @@ def cmd_start(args: argparse.Namespace) -> int: return 0 +def _check_failure_preview(tail: str, limit: int = 1536) -> str: + if len(tail.encode()) <= limit: + return tail + edge = limit // 8 + lines = (line.encode() for line in tail.splitlines()) + preview = b"\n".join( + line if len(line) <= 2 * edge else line[:edge] + b" [...] " + line[-edge:] + for line in lines + ) + if len(preview) > limit: + preview = b"[...]\n" + preview[6 - limit:] + return preview.decode(errors="ignore") + + def cmd_check(args: argparse.Namespace) -> int: wt, config = _context(args, pin_checks=True) if not config.checks: @@ -637,32 +651,30 @@ def cmd_check(args: argparse.Namespace) -> int: except sandbox.SandboxUnavailable as exc: print(f"sandbox unavailable: {exc}", file=sys.stderr) return 2 + shortened = False for result in report.results: if result.exit_code != 0: print(f"--- {result.command} (exit {result.exit_code}) ---", file=sys.stderr) tail = _proc.tail(result.tail) - print(tail, file=sys.stderr) + preview = _check_failure_preview(tail) + shortened |= preview != tail + print(preview, file=sys.stderr) if not config.network and (result.command.startswith("uv sync --offline --locked") or OFFLINE_FAILURE_RE.search(tail)): - env = { - **sandbox.SANDBOX_ENV, - **_proc.build_env(config.env_allowlist), - **dict(config.env), - } + env = sandbox.SANDBOX_ENV | _proc.build_env(config.env_allowlist) | dict(config.env) print( "\nThe sandbox has no network because `[checks] network = false`; " f"the effective UV_CACHE_DIR inside the sandbox is {env['UV_CACHE_DIR']}. " - "To prepare offline, run UV_CACHE_DIR= uv sync --group dev " - "(use the groups your checks require) on the host, or the same commands, so the cache " - "under `[checks] writable` is warm, or set `[checks] env` UV_CACHE_DIR to " - "that cache.", - file=sys.stderr, + "Run UV_CACHE_DIR= uv sync --group dev on the host " + "(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, ) - current_head = _save_report(wt, report) - if current_head is not None: + 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) return 1 + if shortened: + print(f"Full diagnostic tail: {CHECKS_FILE} (head {report.head})", file=sys.stderr) if report.ok and report.settings_sha256 is None: print("check stages passed but the receipt is unverified; rerun loopzero check from the task " "worktree with a stable, readable configured runner before running ready", file=sys.stderr) diff --git a/src/loopzero/sandbox.py b/src/loopzero/sandbox.py index 6f725e28..663784be 100644 --- a/src/loopzero/sandbox.py +++ b/src/loopzero/sandbox.py @@ -31,7 +31,8 @@ TIMEOUT_EXIT = 124 CHECK_SHELL = ("/bin/bash", "--posix", "-o", "pipefail", "-c") CHECK_TAIL_BYTES = 16 * 1024 -HEARTBEAT_INTERVAL = 30.0 +FIRST_HEARTBEAT_DELAY = 30.0 +HEARTBEAT_INTERVAL = 300.0 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. @@ -325,9 +326,11 @@ def _stage_status(status: Callable[[str], None] | None, ordinal: int, total: int started = time.monotonic() def heartbeat(): - while not stopped.wait(HEARTBEAT_INTERVAL): + delay = FIRST_HEARTBEAT_DELAY + while not stopped.wait(delay): status(f"stage {ordinal}/{total}: running " f"({time.monotonic() - started:.1f}s elapsed)") + delay = HEARTBEAT_INTERVAL reporter = threading.Thread(target=heartbeat, daemon=True) if status else None if reporter: diff --git a/tests/test_cli.py b/tests/test_cli.py index 5c136d5d..1a0e5abf 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -358,6 +358,68 @@ def expect_cli(capsys, exit_code, *argv, stdout=None, stderr=None, stdout_contai return out, err +# Transcript size regressions +@pytest.mark.parametrize("receipt", ["saved", "head moved", "write failed"]) +def test_check_bounds_large_failure_and_preserves_receipt(wt, head, capsys, monkeypatch, receipt): + tail = 'TEST_FAILURES={"detail":"' + "é" * 7500 + '","error":"Failed to fetch package"}\n' + tail += "migration failed: relation widgets already exists\nAssertionError: assert " + "x" * 1000 + monkeypatch.setattr(cli.sandbox, "run_checks", lambda *a, **k: CheckReport( + "a" * 40 if receipt == "head moved" else head, False, + (CheckResult("apply migrations", 7, 0.1, tail),), + )) + if receipt == "write failed": + monkeypatch.setattr(cli, "_save_report", Mock(side_effect=PermissionError("receipt write denied"))) + code, out, err = run(capsys, "check") + assert len((out + err).encode()) < 2500 + assert code == 1 and "apply migrations (exit 7)" in err + assert all(text in err for text in ("migration failed: relation widgets already exists", "AssertionError: assert", "[...]")) + assert "uv sync --group dev" in err + if receipt == "saved": + assert out.endswith("FAIL\n") and ".loopzero/checks.json" in err and head in err + assert json.loads((wt / ".loopzero/checks.json").read_text())["results"][0]["tail"] == tail + else: + assert ".loopzero/checks.json" not in err + assert ("current HEAD" if receipt == "head moved" else "receipt write denied") in err + + +def test_check_hour_long_stage_transcript(wt, head, gh, capsys, monkeypatch): + sandbox = cli.sandbox + clock = poll_clock(monkeypatch) + deadline = 0.0 + + def wait(seconds): + clock.now += seconds + return clock.now >= deadline + + monkeypatch.setattr(sandbox.threading, "Event", lambda: Mock(wait=wait)) + monkeypatch.setattr(sandbox.threading, "Thread", lambda *, target, daemon: Mock(start=target)) + + def run_checks(cfg, path, *, progress, status, checkpoint, workflow): + nonlocal deadline + results = [] + for ordinal in range(1, 25): + command = f"run tool {ordinal:02d}" + duration = 3600.0 if ordinal == 1 else 0.1 + deadline = clock.now + duration + progress(command) + with sandbox._stage_status(status, ordinal, 24): + pass + status(f"stage {ordinal}/24: exit 0 ({duration:.1f}s)") + results.append(CheckResult(command, 0, duration, "")) + return CheckReport(head, False, tuple(results), sandbox.settings_fingerprint(cfg, path)) + + monkeypatch.setattr(sandbox, "run_checks", run_checks) + code, out, err = run(capsys, "check") + assert len((out + err).encode()) < 2400 + assert (code, err, gh.calls) == (0, "", []) and out.endswith("PASS\n") + assert f"receipt produced: head={head}" in out and "stage 24/24: exit 0" in out + assert out.count("running: run tool") == 24 + assert [float(seconds) for seconds in re.findall(r"running \(([\d.]+)s elapsed\)", out)] == list( + range(30, 3600, 300) + ) + assert out.rindex("s elapsed)") < out.index("stage 1/24: exit 0 (3600.0s)") + + # --- start / check -------------------------------------------------------------------- diff --git a/tests/test_sandbox.py b/tests/test_sandbox.py index 674e4d8a..705d3f7c 100644 --- a/tests/test_sandbox.py +++ b/tests/test_sandbox.py @@ -542,7 +542,7 @@ def _pairs(argv: list[str], flag: str) -> list[tuple[str, str]]: @pytest.fixture def heartbeat_log(monkeypatch): - monkeypatch.setattr(sandbox, "HEARTBEAT_INTERVAL", 0.03) + monkeypatch.setattr(sandbox, "FIRST_HEARTBEAT_DELAY", 0.03) observed, events, reporters = Event(), [], set() def status(message): @@ -600,7 +600,6 @@ def run_stage(config, worktree, prefix, stage_command, timeout): def test_early_failure_reports_actual_exit_without_heartbeat(git_repo, bwrap_log, monkeypatch): - monkeypatch.setattr(sandbox, "HEARTBEAT_INTERVAL", 30.0) events = [] report = sandbox.run_checks( make_config(checks=("echo secret; exit 17", "echo never")), git_repo, @@ -685,7 +684,7 @@ def status(message): if mode == "blocked-heartbeat": threading.Event().wait() -sandbox.HEARTBEAT_INTERVAL = 0.03 +sandbox.FIRST_HEARTBEAT_DELAY = 0.03 repo = Path.cwd() command = "echo complete" if mode in {"dispatch", "removal"} else "exec sleep 30" report = sandbox.run_checks(make_config(checks=(command,)), repo, status=status) From b67aef410299f1f8dd27a60030a173fbbc79ac69 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:16:27 +0100 Subject: [PATCH 4/6] Keep regression proof within fifteen net test lines Co-Authored-By: Codex --- tests/test_cli.py | 82 ++++++++++++----------------------------------- 1 file changed, 21 insertions(+), 61 deletions(-) diff --git a/tests/test_cli.py b/tests/test_cli.py index 98ba15cd..805bfd86 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1448,13 +1448,11 @@ def test_runtime_pinning_requires_trusted_workflow( origin = Path(git(wt, "remote", "get-url", "origin").strip()) if missing == "default": git(wt, "symbolic-ref", "--delete", "refs/remotes/origin/HEAD") - elif missing == "remote": - git(wt, "update-ref", "-d", "refs/remotes/origin/main") - git(origin, "update-ref", "-d", "refs/heads/main") else: - initial = git(wt, "rev-list", "--max-parents=0", "HEAD").strip() - git(wt, "update-ref", "refs/remotes/origin/main", initial) - git(origin, "update-ref", "refs/heads/main", initial) + options = ("-d",) if missing == "remote" else () + revision = () if options else (git(wt, "rev-list", "--max-parents=0", "HEAD").strip(),) + for checkout, ref in ((wt, "refs/remotes/origin/main"), (origin, "refs/heads/main")): + git(checkout, "update-ref", *options, ref, *revision) prepare_review(wt, gh, fake_bin) code, out, err = run(capsys, command) assert "reviewer paths" not in out + err @@ -2470,7 +2468,7 @@ def after_sleep(): @pytest.mark.parametrize("command", ["ready", "merge"]) @pytest.mark.parametrize("settled", ["CONFLICTING", "MERGEABLE", "UNKNOWN"]) -def test_wait_for_github_mergeability(wt, gh, capsys, monkeypatch, command, settled, git_calls): +def test_wait_for_github_mergeability(wt, gh, capsys, monkeypatch, command, settled): head = commit_mergify_configuration(wt) arm_approved_ready_pr(gh, head, wt, mergeable="UNKNOWN", isDraft=False) gh.respond_pr_view(pr_json(headRefOid=head, mergeable=settled, isDraft=False, @@ -2481,69 +2479,18 @@ def test_wait_for_github_mergeability(wt, gh, capsys, monkeypatch, command, sett monkeypatch.setattr(cli, "_wait_for_mergify", lambda *_: None) poll_clock(monkeypatch) - git_calls.clear() code, out, err = run(capsys, command, "--wait=1") - assert sum(call[0] == "fetch" for call in git_calls) == 1 if settled == "CONFLICTING": assert code == 1 and "has merge conflicts" in out + err elif settled == "UNKNOWN": - assert code == 3 and out.endswith(f"timed out waiting for GitHub to compute mergeability on {head[:12]}. Run `loopzero {command} --wait` to resume on this head.\n"), (code, out, err) + assert code == 3 and out.endswith(f"timed out waiting for GitHub to compute mergeability on {head[:12]}. Run `loopzero {command} --wait` to resume on this head.\n") else: assert code == (0 if command == "ready" else 3) assert requests == ([(REPO, 7, head, "main")] if command == "merge" and settled == "MERGEABLE" else []) -@pytest.mark.parametrize("publisher,expected", [ - ("retired-publisher", "pending"), ("replacement-publisher", "success"), -]) -def test_readiness_and_hosted_use_current_base_publishers(wt, gh, head, tmp_path, monkeypatch, capsys, - publisher, expected): - git(tmp_path, "clone", "-q", str(tmp_path / "origin.git"), "trusted") - trusted = tmp_path / "trusted" - workflow = trusted / "workflow.toml" - retired_workflow = (WORKFLOW.replace('required_ci = ["checks"]', - 'required_ci = ["checks", "Loop-zero Eligibility"]') - + 'review_publishers = ["retired-publisher"]\n') - workflow.write_text(retired_workflow) - git(trusted, "commit", "-qam", "trust old review publisher") - git(trusted, "push", "-q", "origin", "main") - git(wt, "fetch", "-q", "origin", "main") - stale = git(wt, "rev-parse", "origin/main") - - arm_approved_pr_with_check_result(gh, head, wt, "success", isDraft=False, review_login=publisher) - gh.respond(f"api repos/{REPO}/commits/{head}/statuses", - [{"context": "Loop-zero Eligibility", "state": "success"}]) - workflow.write_text(retired_workflow.replace("retired-publisher", "replacement-publisher")) - git(trusted, "commit", "-qam", "rotate review publisher") - git(trusted, "push", "-q", "origin", "main") - assert git(wt, "rev-parse", "origin/main") == stale - assert git(trusted, "rev-parse", "HEAD") != stale - - code, out, _ = run(capsys, "ready") - assert code == (0 if expected == "success" else 1) - assert (github.MISSING_REVIEW_REASON in out) == (expected == "pending") - if expected == "pending": - git(wt, "remote", "set-url", "origin", str(tmp_path / "unavailable.git")) - code, _, err = run(capsys, "ready") - assert code == 1 and "could not refresh origin/main" in err - explicit = tmp_path / "explicit.toml" - explicit.write_text(retired_workflow) - assert run(capsys, "--config", str(explicit), "ready")[0] == 0 - - event = trusted / "event.json" - event.write_text(json.dumps({"inputs": {"pr": "7"}})) - monkeypatch.chdir(trusted) - monkeypatch.setenv("GITHUB_REPOSITORY", REPO) - monkeypatch.setenv("GITHUB_EVENT_PATH", str(event)) - gh.respond(f"api repos/{REPO}/statuses/{head}", {}) - assert hosted.main() == 0 - payload = json.loads(gh.calls[-1]["--input"]) - assert gh.calls[-1]["argv"][1] == f"repos/{REPO}/statuses/{head}" - assert payload["state"] == expected - - @pytest.mark.parametrize("command,check,hold_at_admission", [ ("ready", "success", False), ("ready", "skipped", False), ("merge", "success", False), ("merge", "success", True), @@ -4178,12 +4125,25 @@ def test_hosted_eligibility_uses_publisher_not_token(wt, gh, state, verdict, exp @pytest.mark.parametrize("publisher", ["stranger", "lz-bot"]) -def test_ready_pins_review_publishers_to_base(wt, gh, capsys, publisher, head): - (wt / "workflow.toml").write_text(WORKFLOW + f'\nreview_publishers = ["{publisher}"]\n') +def test_ready_pins_review_publishers_to_base(wt, repo, gh, capsys, monkeypatch, publisher, head): + policy = WORKFLOW.replace('required_ci = ["checks"]', 'required_ci = ["checks", "Loop-zero Eligibility"]') + publish_workflow(wt, policy + '\nreview_publishers = ["stranger"]\n') + commit_file(repo, "workflow.toml", policy + f'\nreview_publishers = ["{LOGIN}"]\n', "rotate publisher") + git(repo, "push", str(repo.parent / "origin.git"), "main") # preserve the retired local publisher + (wt / "workflow.toml").write_text(policy + f'\nreview_publishers = ["{publisher}"]\n') arm_approved_pr_with_check_result( gh, head, wt, "success", review_login=publisher, isDraft=False ) + gh.respond(f"api repos/{REPO}/commits/{head}/statuses", [{"context": "Loop-zero Eligibility", "state": "success"}]) assert run(capsys, "ready")[0] == (0 if publisher == LOGIN else 1) + event = repo / "event.json" + event.write_text(json.dumps({"inputs": {"pr": "7"}})) + monkeypatch.chdir(repo) + monkeypatch.setenv("GITHUB_REPOSITORY", REPO) + monkeypatch.setenv("GITHUB_EVENT_PATH", str(event)) + gh.respond(f"api repos/{REPO}/statuses/{head}", {}) + assert hosted.main() == 0 + assert json.loads(gh.calls[-1]["--input"])["state"] == ("success" if publisher == LOGIN else "pending") def test_mergify_confirmed_wait_reads_pr_once_per_steady_poll(wt, gh, monkeypatch): From 8534210211515bc33c81ae3c6ac0d2298c25f2ac Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:16:50 +0100 Subject: [PATCH 5/6] Place output regression tests next to their command coverage Co-Authored-By: Codex --- tests/test_cli.py | 122 +++++++++++++++++++++++----------------------- 1 file changed, 61 insertions(+), 61 deletions(-) diff --git a/tests/test_cli.py b/tests/test_cli.py index 1a0e5abf..8ac87bbe 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -359,67 +359,6 @@ def expect_cli(capsys, exit_code, *argv, stdout=None, stderr=None, stdout_contai # Transcript size regressions -@pytest.mark.parametrize("receipt", ["saved", "head moved", "write failed"]) -def test_check_bounds_large_failure_and_preserves_receipt(wt, head, capsys, monkeypatch, receipt): - tail = 'TEST_FAILURES={"detail":"' + "é" * 7500 + '","error":"Failed to fetch package"}\n' - tail += "migration failed: relation widgets already exists\nAssertionError: assert " + "x" * 1000 - monkeypatch.setattr(cli.sandbox, "run_checks", lambda *a, **k: CheckReport( - "a" * 40 if receipt == "head moved" else head, False, - (CheckResult("apply migrations", 7, 0.1, tail),), - )) - if receipt == "write failed": - monkeypatch.setattr(cli, "_save_report", Mock(side_effect=PermissionError("receipt write denied"))) - code, out, err = run(capsys, "check") - assert len((out + err).encode()) < 2500 - assert code == 1 and "apply migrations (exit 7)" in err - assert all(text in err for text in ("migration failed: relation widgets already exists", "AssertionError: assert", "[...]")) - assert "uv sync --group dev" in err - if receipt == "saved": - assert out.endswith("FAIL\n") and ".loopzero/checks.json" in err and head in err - assert json.loads((wt / ".loopzero/checks.json").read_text())["results"][0]["tail"] == tail - else: - assert ".loopzero/checks.json" not in err - assert ("current HEAD" if receipt == "head moved" else "receipt write denied") in err - - -def test_check_hour_long_stage_transcript(wt, head, gh, capsys, monkeypatch): - sandbox = cli.sandbox - clock = poll_clock(monkeypatch) - deadline = 0.0 - - def wait(seconds): - clock.now += seconds - return clock.now >= deadline - - monkeypatch.setattr(sandbox.threading, "Event", lambda: Mock(wait=wait)) - monkeypatch.setattr(sandbox.threading, "Thread", lambda *, target, daemon: Mock(start=target)) - - def run_checks(cfg, path, *, progress, status, checkpoint, workflow): - nonlocal deadline - results = [] - for ordinal in range(1, 25): - command = f"run tool {ordinal:02d}" - duration = 3600.0 if ordinal == 1 else 0.1 - deadline = clock.now + duration - progress(command) - with sandbox._stage_status(status, ordinal, 24): - pass - status(f"stage {ordinal}/24: exit 0 ({duration:.1f}s)") - results.append(CheckResult(command, 0, duration, "")) - return CheckReport(head, False, tuple(results), sandbox.settings_fingerprint(cfg, path)) - - monkeypatch.setattr(sandbox, "run_checks", run_checks) - code, out, err = run(capsys, "check") - assert len((out + err).encode()) < 2400 - assert (code, err, gh.calls) == (0, "", []) and out.endswith("PASS\n") - assert f"receipt produced: head={head}" in out and "stage 24/24: exit 0" in out - assert out.count("running: run tool") == 24 - assert [float(seconds) for seconds in re.findall(r"running \(([\d.]+)s elapsed\)", out)] == list( - range(30, 3600, 300) - ) - assert out.rindex("s elapsed)") < out.index("stage 1/24: exit 0 (3600.0s)") - - # --- start / check -------------------------------------------------------------------- @@ -646,6 +585,67 @@ def test_malformed_live_markers_do_not_mask_check_verdict( assert json.loads((wt / ".loopzero/checks.json").read_text())["results"][0]["exit_code"] == 0 +@pytest.mark.parametrize("receipt", ["saved", "head moved", "write failed"]) +def test_check_bounds_large_failure_and_preserves_receipt(wt, head, capsys, monkeypatch, receipt): + tail = 'TEST_FAILURES={"detail":"' + "é" * 7500 + '","error":"Failed to fetch package"}\n' + tail += "migration failed: relation widgets already exists\nAssertionError: assert " + "x" * 1000 + monkeypatch.setattr(cli.sandbox, "run_checks", lambda *a, **k: CheckReport( + "a" * 40 if receipt == "head moved" else head, False, + (CheckResult("apply migrations", 7, 0.1, tail),), + )) + if receipt == "write failed": + monkeypatch.setattr(cli, "_save_report", Mock(side_effect=PermissionError("receipt write denied"))) + code, out, err = run(capsys, "check") + assert len((out + err).encode()) < 2500 + assert code == 1 and "apply migrations (exit 7)" in err + assert all(text in err for text in ("migration failed: relation widgets already exists", "AssertionError: assert", "[...]")) + assert "uv sync --group dev" in err + if receipt == "saved": + assert out.endswith("FAIL\n") and ".loopzero/checks.json" in err and head in err + assert json.loads((wt / ".loopzero/checks.json").read_text())["results"][0]["tail"] == tail + else: + assert ".loopzero/checks.json" not in err + assert ("current HEAD" if receipt == "head moved" else "receipt write denied") in err + + +def test_check_hour_long_stage_transcript(wt, head, gh, capsys, monkeypatch): + sandbox = cli.sandbox + clock = poll_clock(monkeypatch) + deadline = 0.0 + + def wait(seconds): + clock.now += seconds + return clock.now >= deadline + + monkeypatch.setattr(sandbox.threading, "Event", lambda: Mock(wait=wait)) + monkeypatch.setattr(sandbox.threading, "Thread", lambda *, target, daemon: Mock(start=target)) + + def run_checks(cfg, path, *, progress, status, checkpoint, workflow): + nonlocal deadline + results = [] + for ordinal in range(1, 25): + command = f"run tool {ordinal:02d}" + duration = 3600.0 if ordinal == 1 else 0.1 + deadline = clock.now + duration + progress(command) + with sandbox._stage_status(status, ordinal, 24): + pass + status(f"stage {ordinal}/24: exit 0 ({duration:.1f}s)") + results.append(CheckResult(command, 0, duration, "")) + return CheckReport(head, False, tuple(results), sandbox.settings_fingerprint(cfg, path)) + + monkeypatch.setattr(sandbox, "run_checks", run_checks) + code, out, err = run(capsys, "check") + assert len((out + err).encode()) < 2400 + assert (code, err, gh.calls) == (0, "", []) and out.endswith("PASS\n") + assert f"receipt produced: head={head}" in out and "stage 24/24: exit 0" in out + assert out.count("running: run tool") == 24 + assert [float(seconds) for seconds in re.findall(r"running \(([\d.]+)s elapsed\)", out)] == list( + range(30, 3600, 300) + ) + assert out.rindex("s elapsed)") < out.index("stage 1/24: exit 0 (3600.0s)") + + @pytest.mark.parametrize("command,exit_code,tail", [ ("echo no; exit 3", 3, "no\n"), ("seq 1 50; exit 1", 1, "".join(f"{i}\n" for i in range(11, 51)))]) From 5d924132195d46b7abd156961597fed203f3a20e Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:17:19 +0100 Subject: [PATCH 6/6] Keep the shared test helper section unchanged Co-Authored-By: Codex --- tests/test_cli.py | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/test_cli.py b/tests/test_cli.py index 8ac87bbe..f51f214b 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -358,7 +358,6 @@ def expect_cli(capsys, exit_code, *argv, stdout=None, stderr=None, stdout_contai return out, err -# Transcript size regressions # --- start / check --------------------------------------------------------------------