diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 9e1bc6d8..1c4f145e 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -122,7 +122,11 @@ loading the delivery [commands](../src/loopzero/cli.py), which implement the con head or an eligible review covering an ancestor, blocking findings (unresolved threads a review publisher opened with a head-bound marker line), target branch and required CI. The receipt must record a clean passing run - at that head with the current commands and check settings digest. A settings + at that head with the current commands and check settings digest. Ready and + merge validate the PR, head and hold before checking the local receipt. + An invalid receipt stops the command before it fetches remote readiness + evidence. Writes to advance readiness or merging recheck the receipt. + Status continues to collect all readiness diagnostics. A settings change or an older receipt without the digest requires a fresh check. The digest covers execution and stage reuse settings without recording raw environment values. For local sandbox receipts it omits inherited `PATH`, diff --git a/src/loopzero/_proc.py b/src/loopzero/_proc.py index 1d70e76f..a7db463d 100644 --- a/src/loopzero/_proc.py +++ b/src/loopzero/_proc.py @@ -188,22 +188,15 @@ def run( stdin = input.encode(raw_encoding) if preserve_newlines and input is not None else input try: with subprocess.Popen( - argv, - cwd=str(cwd), - env=build_env(env_allowlist, extra_env), - stdin=subprocess.PIPE if input is not None else subprocess.DEVNULL, - stdout=subprocess.PIPE, + argv, cwd=str(cwd), env=build_env(env_allowlist, extra_env), + stdin=subprocess.PIPE if input is not None else subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT if merge_output else subprocess.PIPE, - encoding=None if preserve_newlines else encoding, - errors=None if preserve_newlines else "replace", - pass_fds=pass_fds, - start_new_session=os.name == "posix", + encoding=None if preserve_newlines else encoding, errors=None if preserve_newlines else "replace", + pass_fds=pass_fds, start_new_session=os.name == "posix", ) as proc: try: - if tail_chars is None: - stdout, stderr = proc.communicate(stdin, timeout=timeout) - else: - stdout, stderr = _read_output_tail(proc, tail_chars, timeout), "" + stdout, stderr = (proc.communicate(stdin, timeout=timeout) if tail_chars is None + else (_read_output_tail(proc, tail_chars, timeout), "")) except BaseException: if os.name == "posix": with suppress(ProcessLookupError): @@ -221,19 +214,10 @@ def run( out = exc.stdout.decode(errors="replace") if isinstance(exc.stdout, bytes) else (exc.stdout or "") err = exc.stderr.decode(errors="replace") if isinstance(exc.stderr, bytes) else exc.stderr elapsed = time.monotonic() - started - raise ProcTimeout( - f"{' '.join(argv)}: timed out after {timeout:g}s\n{tail(out)}", - out, - stderr=err or "", - duration_s=elapsed, - ) from exc + message = f"{' '.join(argv)}: timed out after {timeout:g}s\n{tail(out)}" + raise ProcTimeout(message, out, stderr=err or "", duration_s=elapsed) from exc if isinstance(stdout, bytes): stdout = stdout.decode(raw_encoding, errors="surrogateescape") if isinstance(stderr, bytes): stderr = stderr.decode(raw_encoding, errors="replace") - return Completed( - exit_code=proc.returncode, - stdout=stdout or "", - stderr=stderr or "", - duration_s=time.monotonic() - started, - ) + return Completed(proc.returncode, stdout or "", stderr or "", time.monotonic() - started) diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index e9136315..3ac7a1c5 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -179,8 +179,8 @@ def _require_task_branch(config: Config, branch: str) -> None: raise CliError(f"branch {branch!r} is the configured base; use a task branch") -def _require_pr(config: Config, branch: str, *, allow_merged: bool = False) -> github.PR: - pr = github.pr_for_branch(config.repo, branch) +def _require_pr(config: Config, branch: str, *, allow_merged: bool = False, list_only: bool = False) -> github.PR: + pr = github.pr_for_branch(config.repo, branch, list_only=list_only) if pr is None: raise CliError(f"no pull request for {branch}; run `loopzero pr` first") if pr.state != "OPEN" and not (allow_merged and pr.state == "MERGED"): @@ -304,12 +304,18 @@ def _review_cap_reason(config: Config, pr: github.PR, head: str, reviews: list[d MERGEABILITY_PENDING = "GitHub is computing mergeability" +def _readiness_precheck(wt: Path, config: Config, pr: github.PR, head: str, diagnostics: bool) -> str | None: + return github.merge_hold(pr.number, pr.labels) or ( + None if diagnostics else _check_report_problem(_load_report(wt), config, head) + ) + + def _readiness( wt: Path, config: Config, pr: github.PR, head: str, reviews: list[dict] | None = None, - *, workflow_wait: bool = False, announce_receipt: bool = False, + *, workflow_wait: bool = False, announce_receipt: bool = False, diagnostics: bool = False, ) -> github.Readiness: - if hold := github.merge_hold(pr.number, pr.labels): - return github.Readiness(False, (hold,)) + if problem := _readiness_precheck(wt, config, pr, head, diagnostics): + return github.Readiness(False, (problem,)) if reviews is None: reviews = _pr_reviews(config.repo, pr.number) publishers = config.review_publishers or (github.login(),) @@ -333,12 +339,6 @@ def _readiness( ), publishers=publishers, ) - report = _load_report(wt) - receipt_problem = _check_report_problem(report, config, head) - if receipt_problem: - result = github.Readiness(False, (*result.reasons, receipt_problem)) - elif announce_receipt: - _print_receipt(wt, report, "accepted") if config.merge_strategy == "mergify" and pr.state == "OPEN": behind = github.behind_reason(pr, head if review else None) reasons = result.reasons @@ -356,6 +356,12 @@ def _readiness( )) if pr.state == "OPEN" and pr.mergeable == "UNKNOWN": result = dataclasses.replace(result, ready=False, reasons=(*result.reasons, MERGEABILITY_PENDING)) + report = _load_report(wt) + receipt_problem = _check_report_problem(report, config, head) + if receipt_problem: + result = github.Readiness(False, (*result.reasons, receipt_problem)) + elif announce_receipt: + _print_receipt(wt, report, "accepted") return result @@ -395,6 +401,11 @@ def _current_check_report(wt: Path, config: Config, head: str) -> CheckReport | return None if _check_report_problem(report, config, head) else report +def _require_receipt(wt: Path, config: Config, head: str) -> None: + if problem := _check_report_problem(_load_report(wt), config, head): + raise CliError(problem) + + def _print_receipt(wt: Path, report: CheckReport, action: str) -> None: """Best-effort transcript identity; never authority or environment attestation.""" try: @@ -409,13 +420,12 @@ 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], - } + 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 + ] + payload = {"head": report.head, "dirty": report.dirty, "results": results} if report.settings_sha256 is not None: payload["settings_sha256"] = report.settings_sha256 return worktree.write_local_state( @@ -550,15 +560,13 @@ def _require_pr_details(wt: Path) -> None: def _append_review(body: str, result: ReviewResult) -> str: """Append one compact review record under Review, replacing its placeholder.""" line = f"- {result.kind}, {result.family}, {result.head[:12]}, {result.verdict}" - pattern = re.compile(r"(^## Review\n)(.*?)(?=^## |\Z)", re.DOTALL | re.MULTILINE) - match = pattern.search(body) + match = re.search(r"^## Review\n(.*?)(?=^## |\Z)", body, re.DOTALL | re.MULTILINE) if not match: return f"{body.rstrip()}\n\n## Review\n{line}\n" - existing = match.group(2).rstrip() - if existing.startswith("(filled by `loopzero review`)"): - existing = "" - replacement = match.group(1) + (f"{existing}\n" if existing else "") + line + "\n\n" - return pattern.sub(lambda _: replacement, body, count=1).rstrip() + "\n" + existing = match[1].rstrip() + if existing and not existing.startswith("(filled by `loopzero review`)"): + line = f"{existing}\n{line}" + return (body[:match.start(1)] + line + "\n\n" + body[match.end():]).rstrip() + "\n" def _refresh_pr_checks(wt: Path, config: Config) -> None: @@ -589,9 +597,6 @@ def _pr_title(wt: Path, branch: str) -> str: return next((t for t in headings if t and t.lower() not in _SECTIONS), branch) -# --------------------------------------------------------------------------- commands - - def cmd_start(args: argparse.Namespace) -> int: root = _toplevel() current = config_mod.run_git(root, "symbolic-ref", "--quiet", "--short", "HEAD") @@ -623,15 +628,11 @@ def cmd_check(args: argparse.Namespace) -> int: 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: - report = sandbox.run_checks(config, wt, progress=lambda command: print( - f"running: {github.redact_credentials(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 + report = sandbox.run_checks( + config, wt, progress=lambda command: print(f"running: {github.redact_credentials(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", + ) shortened = False for result in report.results: if result.exit_code != 0: @@ -657,16 +658,16 @@ def cmd_check(args: argparse.Namespace) -> int: 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: + verified = not report.ok or report.settings_sha256 is not None + if not verified: 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) - _refresh_pr_checks(wt, config) - return 1 - if report.ok and not report.dirty: + elif report.ok and not report.dirty: _print_receipt(wt, report, "produced") _refresh_pr_checks(wt, config) - print("PASS" if report.ok else "FAIL") - return 0 if report.ok else 1 + if verified: + print("PASS" if report.ok else "FAIL") + return 0 if report.ok and verified else 1 def cmd_pr(args: argparse.Namespace) -> int: @@ -688,8 +689,7 @@ def cmd_pr(args: argparse.Namespace) -> int: force_lease = False push = ["push", "-u", "origin"] if pr is not None and pr.state == "OPEN": - known = _proc.run(["git", "cat-file", "-e", f"{pr.head_sha}^{{commit}}"], cwd=wt, - env_allowlist=worktree.GIT_ENV, timeout=GIT_TIMEOUT) + known = config_mod.run_git(wt, "cat-file", "-e", f"{pr.head_sha}^{{commit}}") if known.exit_code != 0: raise CliError( f"PR head {pr.head_sha[:12]} is not in this worktree; fetch and integrate it first" @@ -776,10 +776,10 @@ def locked(args: argparse.Namespace) -> int: @_lock_review def cmd_review(args: argparse.Namespace, wt: Path, config: Config) -> int: - if args.config: - runtime_source = "reviewer paths are unpinned because --config was provided" - else: - runtime_source = f"reviewer paths pinned to origin/{config.base_branch}@{config.trusted_base_revision}" + runtime_source = ( + "reviewer paths are unpinned because --config was provided" if args.config + else f"reviewer paths pinned to origin/{config.base_branch}@{config.trusted_base_revision}" + ) branch, head = worktree.branch(wt), worktree.head(wt) _require_task_branch(config, branch) kinds = ("primary", "delta") @@ -801,10 +801,7 @@ def cmd_review(args: argparse.Namespace, wt: Path, config: Config) -> int: if len(saved) > 1: raise CliError("multiple saved reviews for HEAD; publication is ambiguous") reviews = [] if saved else _pr_reviews(config.repo, pr.number) - if saved: - kind = saved[0] - else: - kind, reviewed = _select_review_round(config, pr, head, reviews) + kind, reviewed = (saved[0], None) if saved else _select_review_round(config, pr, head, reviews) publication_context = {"repo": config.repo, "number": pr.number, "publisher": publisher} if args.repost: result, publication = _load_review(wt, head, kind) @@ -833,28 +830,21 @@ def cmd_review(args: argparse.Namespace, wt: Path, config: Config) -> int: wt, config, head, kind, publication_context, ): raise CliError(f"saved {kind} review for {head[:12]}; run `loopzero review --repost`") - try: - result = _run_review(wt, config, head, kind, reviewed, args.model, args.effort, - runtime_source=runtime_source, publication=(config.repo, pr.number, publisher)) - except sandbox.SandboxUnavailable as exc: - print(f"sandbox unavailable: {exc}", file=sys.stderr) - return 2 + result = _run_review(wt, config, head, kind, reviewed, args.model, args.effort, + runtime_source=runtime_source, publication=(config.repo, pr.number, publisher)) final_head, final_dirty = worktree.head(wt), worktree.is_dirty(wt) if final_head != head or final_dirty: raise CliError( f"worktree changed during review: HEAD before {head}, HEAD after {final_head}; " f"dirty before False, dirty after {final_dirty}" ) - prefix = review_marker(head, kind, "model") try: - evidence = runners.codex_evidence(result) + if not _matches_publication(result, publication_context): + raise CliError("native publication context changed; HOLD") except runners.RunnerBadOutput: _save_review(wt, result) raise - if evidence is not None and (evidence["repo"], evidence["pr"], evidence["publisher"]) != (config.repo, pr.number, publisher): - raise CliError("native publication context changed; HOLD") - if args.repost: - prefix = _repost_prefix(result) + prefix = _repost_prefix(result) if args.repost else review_marker(head, kind, "model") _save_review(wt, result, publication_context) token = _refresh_publisher_token(token, publisher) try: @@ -905,22 +895,28 @@ def _repost_reviewer_families( wt: Path, config: Config, head: str, result: ReviewResult, ) -> tuple[list[str], list[str]]: authors = runners.author_families(wt, head, _primary_base(wt, config)) + candidates = [family for family in config.reviewers if family not in authors] excluded = [family for family in config.reviewers if family in authors] 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 " "reviewer family that contributed to this PR lineage; run without --repost" ) - if not result.fallback and not any(family not in authors for family in config.reviewers): - raise IndependentReviewerUnavailable( - _independence_message(authors, excluded, []) - ) + if not result.fallback and not candidates: + raise IndependentReviewerUnavailable(_independence_message(authors, excluded, [])) if result.family in authors and not result.fallback: raise IndependentReviewerUnavailable( f"saved reviewer family {result.family} contributed to this PR lineage; " "run without --repost to obtain an independent review" ) - return [family for family in config.reviewers if family not in authors], excluded + return candidates, excluded + + +def _matches_publication(result: ReviewResult, publication: dict) -> bool: + evidence = runners.codex_evidence(result) + return evidence is None or (evidence["repo"], evidence["pr"], evidence["publisher"]) == ( + publication["repo"], publication["number"], publication["publisher"] + ) def _has_recoverable_review( @@ -934,12 +930,9 @@ def _has_recoverable_review( candidates, excluded = _repost_reviewer_families(wt, config, head, result) if result.fallback and not _published_fallback(result.fallback, candidates, excluded): return False - evidence = runners.codex_evidence(result) + return _matches_publication(result, publication) except (CliError, runners.RunnerBadOutput): return False - return evidence is None or (evidence["repo"], evidence["pr"], evidence["publisher"]) == ( - publication["repo"], publication["number"], publication["publisher"], - ) def _repost_prefix(result: ReviewResult) -> str: @@ -1104,10 +1097,7 @@ def select(family: str) -> Callable[..., ReviewResult]: result = selected[family](diff=diff) except runners.RunnerPromptTooLong: chunks = runners.split_diff(diff, config.review_chunk_bytes) - print( - f"reviewer {family} rejected the full diff; reviewing {len(chunks)} chunks", - file=sys.stderr, - ) + print(f"reviewer {family} rejected the full diff; reviewing {len(chunks)} chunks", file=sys.stderr) chunk_results = [selected[family](diff=chunk, chunk=(index, len(chunks))) for index, chunk in enumerate(chunks, 1)] result = runners.merge_reviews(chunk_results) @@ -1210,7 +1200,7 @@ def _pr_readiness( """PR plus readiness; readiness is None only for an already merged PR (allow_merged).""" head = worktree.head(wt) _require_task_branch(config, branch) - pr = _require_pr(config, branch, allow_merged=allow_merged) + pr = _require_pr(config, branch, allow_merged=allow_merged, list_only=True) _require_pushed(pr, head) if pr.state == "MERGED": return pr, None @@ -1312,6 +1302,7 @@ def cmd_ready(args: argparse.Namespace) -> int: kicked = bool(waiting) started = time.monotonic() if waiting: + _require_receipt(wt, config, pr.head_sha) github.mark_ready(config.repo, pr.number) if args.wait is None: pending = f"; {MERGEABILITY_PENDING}" if pr.mergeable == "UNKNOWN" else "" @@ -1331,6 +1322,7 @@ def cmd_ready(args: argparse.Namespace) -> int: assert readiness is not None _prequeue_size_budget(wt, config, pr, readiness) if readiness.ready and pr.is_draft and not kicked: + _require_receipt(wt, config, pr.head_sha) github.mark_ready(config.repo, pr.number) if args.wait is not None: waited = _wait_with_deadline(wt, config, pr, args.wait, kicked=True, started=started, @@ -1521,6 +1513,7 @@ def _wait_for_checks( return current, None, kicked readiness = _readiness(wt, config, current, pr.head_sha, workflow_wait=True) if not kicked and _draft_checks_waiting(config, current, readiness): + _require_receipt(wt, config, current.head_sha) github.mark_ready(config.repo, pr.number) print("marked ready; " + "; ".join(readiness.reasons)) return _wait_for_checks(wt, config, pr, timeout, kicked=True, started=started, @@ -1577,16 +1570,13 @@ def _wait_for_merge(config: Config, pr: github.PR, timeout: float) -> str | None closed: list[github.GhError] = [] print(f"PR #{pr.number} is queued for merge into {config.base_branch}; waiting") for _ in _poll_until(started, timeout): - sha = _landed(config, pr, closed) - if sha: + if sha := _landed(config, pr, closed): return sha if not github.merge_pending(config.repo, pr.number): - sha = _landed(config, pr, closed) - if sha: + if sha := _landed(config, pr, closed): return sha - if closed: - continue - raise CliError(f"PR #{pr.number} left the merge queue unmerged") + if not closed: + raise CliError(f"PR #{pr.number} left the merge queue unmerged") if closed: raise closed[0] return None @@ -1726,6 +1716,7 @@ def _merge_with_mergify( return sha confirmed = state is not None if confirmed and not confirmed_marker: + _require_receipt(wt, config, pr.head_sha) mergify.mark_confirmed(config.repo, pr.number, pr.head_sha, queue) if not confirmed and confirmed_marker: closed: list[github.GhError] = [] @@ -1736,6 +1727,7 @@ def _merge_with_mergify( _prequeue_size_budget(wt, config, pr, readiness, project=admit_by is None) if admit_by is not None and time.monotonic() > admit_by: raise _AdmissionDeadline + _require_receipt(wt, config, pr.head_sha) mergify.request(config.repo, pr.number, pr.head_sha, queue) if deadline is not None: return _wait_for_mergify(config, pr, max(0.0, deadline - time.monotonic()), confirmed) @@ -1793,6 +1785,7 @@ def cmd_merge(args: argparse.Namespace) -> int: if admit_by is not None and time.monotonic() > admit_by: print(f"timed out before merging PR #{pr.number}") return 3 + _require_receipt(wt, config, pr.head_sha) sha = github.merge(config.repo, pr.number, config.merge_strategy, pr.head_sha) if sha is None and args.wait is not None: sha = _wait_for_merge(config, pr, max(0.0, deadline - time.monotonic())) @@ -1886,7 +1879,7 @@ def cmd_status(args: argparse.Namespace) -> int: print(f"review: {latest.kind} on {latest.head[:12]} ({latest.state.lower() or 'posted'})") else: print("review: none on this PR") - readiness = _readiness(wt, config, pr, head, reviews) + readiness = _readiness(wt, config, pr, head, reviews, diagnostics=True) print(f"ready: {'yes' if readiness.ready else 'no'}") for reason in readiness.reasons: print(f" - {reason}") @@ -1913,9 +1906,6 @@ def _print_mergify_status(config: Config, pr: github.PR, readiness: github.Readi print(f" Mergify report: {report}") -# --------------------------------------------------------------------------- entry point - - def main(argv: list[str] | None = None) -> int: return _run(parse_args(build_parser(), argv)) @@ -1928,6 +1918,9 @@ def _run(args: argparse.Namespace) -> int: print(f"loopzero {args.command}: {exc}", file=sys.stderr) return 4 except HANDLED as exc: + if isinstance(exc, sandbox.SandboxUnavailable) and args.command in {"check", "review"}: + print(f"sandbox unavailable: {exc}", file=sys.stderr) + return 2 message = str(exc) if isinstance(exc, ReviewersUnavailable) else _one_line(exc) print(f"loopzero {args.command}: {message}", file=sys.stderr) return 1 diff --git a/src/loopzero/github.py b/src/loopzero/github.py index 42299f88..9fa4eff6 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -666,13 +666,14 @@ def _confirm_branch_pr(repo: str, branch: str, endpoint: str, number: int, state return pr -def pr_for_branch(repo: str, branch: str, *, open_only: bool = False) -> PR | None: +def pr_for_branch(repo: str, branch: str, *, open_only: bool = False, list_only: bool = False) -> PR | None: """Return the open PR, falling back to the most recent closed PR unless open_only.""" - endpoint, matches = _commit_branch_prs(repo, branch) - open_matches = [row for row in matches if row["state"] == "open"] - if open_matches: - newest = max(open_matches, key=lambda row: (row["created_at"], row["number"])) - return _confirm_branch_pr(repo, branch, endpoint, newest["number"], "OPEN") + if not list_only: + endpoint, matches = _commit_branch_prs(repo, branch) + open_matches = [row for row in matches if row["state"] == "open"] + if open_matches: + newest = max(open_matches, key=lambda row: (row["created_at"], row["number"])) + return _confirm_branch_pr(repo, branch, endpoint, newest["number"], "OPEN") # A closed association cannot rule out an open PR or newer closed history. owner = repo.split("/", 1)[0] diff --git a/src/loopzero/sandbox.py b/src/loopzero/sandbox.py index 962e62a9..d2f65d4c 100644 --- a/src/loopzero/sandbox.py +++ b/src/loopzero/sandbox.py @@ -82,11 +82,7 @@ def run_checks(config: Config, worktree: Path, *, timeout: float = DEFAULT_TIMEO status: Callable[[str], None] | None = None, checkpoint: Callable[[CheckReport], None] | None = None, workflow: str | Path = "workflow.toml", _resolved: bool = False) -> CheckReport: - """Run checks, stopping at the first failure; status emits only stage metadata. - - progress receives each command before launch, as before. Optional status receives - heartbeats from a reporting thread and completion from the calling thread. - """ + """Run until a check fails, reporting commands via progress and stage metadata via status.""" worktree = worktree.resolve() if not config.check_runner and shutil.which("bwrap") is None: raise SandboxUnavailable( @@ -147,11 +143,8 @@ def run_checks(config: Config, worktree: Path, *, timeout: float = DEFAULT_TIMEO if checkpoint is not None and result.input_key and result.exit_code == 0: # The receipt stays nonpassing until final validation. incomplete = CheckResult(INCOMPLETE_CHECK_COMMAND, 1, 0.0, "") - unvisited = ( - previous[stage] for stage in commands[ordinal:] if stage in previous - ) - checkpoint(CheckReport(head, dirty, (*results, *unvisited, incomplete), - settings_sha256)) + unvisited = (previous[stage] for stage in commands[ordinal:] if stage in previous) + checkpoint(CheckReport(head, dirty, (*results, *unvisited, incomplete), settings_sha256)) if status: status(f"stage {ordinal}/{len(commands)}: exit {result.exit_code} " f"({result.duration_s:.1f}s)") @@ -189,10 +182,8 @@ def _previous(worktree: Path, settings_sha256: str) -> dict[str, CheckResult]: if (isinstance(command, str) and isinstance(key, str) and key and is_check_exit_code(code) and code == 0 and isinstance(tail, str)): source = result.get("reused_from") - previous[command] = CheckResult( - command, 0, 0.0, _check_tail(tail), key, - source if isinstance(source, str) else data["head"], - ) + reused_from = source if isinstance(source, str) else data["head"] + previous[command] = CheckResult(command, 0, 0.0, _check_tail(tail), key, reused_from) return previous except (OSError, WorktreeError, ValueError, KeyError, TypeError, AttributeError): return {} @@ -247,8 +238,7 @@ def settings_fingerprint(config: Config) -> str | None: host_env = {"PATH", "LANG", "LC_ALL", "TERM", "HEAVY_SLOT_GRANTED_CORES"} for name in host_env - dict(config.env).keys(): settings["environment"].pop(name, None) - payload = [settings, config.inputs] - return hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest() + return hashlib.sha256(json.dumps([settings, config.inputs], sort_keys=True).encode()).hexdigest() def _input_blobs(config: Config, worktree: Path, paths: tuple[str, ...]) -> str | None: diff --git a/tests/test_cli.py b/tests/test_cli.py index db219611..e790e384 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -2405,7 +2405,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, 9, 1) + assert_git_cost(git_calls, 11, 1) # Receipt ownership is checked before gates, after them and before marking ready. assert ["ls-files", "-z", "--", ".loopzero"] in git_calls 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] @@ -3060,54 +3060,52 @@ def test_ready_draft_with_open_blocking_finding_does_not_mark_ready( assert all(c["argv"][:2] != ["pr", "ready"] for c in gh.calls) -@pytest.mark.parametrize("draft,condition,reason", [ - (False, "missing", "run loopzero check at this head"), - *((False, condition, "check receipt") for condition in ("wrong-head", "failed", "dirty")), - (False, "wrong-commands", "check receipt's plan differs from the trusted workflow."), - (False, "legacy", "check receipt is missing its settings fingerprint."), - (False, "incompatible", "check receipt has an incompatible settings fingerprint."), - (False, "matching", None), - (True, "stale", "check receipt is for aaaaaaaaaaaa."), - (True, "red", "check receipt records a failed stage."), - (True, "dirty", "check receipt was recorded in a dirty worktree."), - (True, "commands", "check receipt's plan differs from the trusted workflow."), - *((True, condition, "check receipt is incomplete.") for condition in ("empty", "checkpoint")), +@pytest.mark.parametrize("command", ["ready", "merge"]) +@pytest.mark.parametrize("condition,reason", [ + *((case, "run loopzero check at this head") for case in ("missing", "during-gates", "transient")), + ("head", "check receipt is for aaaaaaaaaaaa."), + ("failed", "check receipt records a failed stage."), ("dirty", "check receipt was recorded in a dirty worktree."), + ("plan", "check receipt's plan differs from the trusted workflow."), + ("legacy", "check receipt is missing its settings fingerprint."), + ("incompatible", "check receipt has an incompatible settings fingerprint."), + ("empty", "check receipt is incomplete."), ("checkpoint", "check receipt is incomplete."), ]) -def test_ready_requires_clean_successful_local_report_at_head(wt, gh, capsys, condition, head, draft, reason): - arm_approved_pr_with_check_result(gh, head, wt, "success", isDraft=draft, readiness={ - "local_exit": int(condition == "failed"), "dirty": condition == "dirty", - }) +def test_delivery_requires_current_receipt(wt, gh, capsys, head, monkeypatch, command, condition, reason): + head = commit_mergify_configuration(wt) if command == "merge" else head + monkeypatch.setattr(mergify, "configured", lambda *_: condition == "during-gates" or pytest.fail("remote gate read")) + arm_approved_pr_with_check_result(gh, head, wt, "success", isDraft=command == "ready") + gh.respond(" ".join(BRANCH_READ), {"object": {"sha": head}}) path = wt / ".loopzero/checks.json" - if condition == "missing": + report = json.loads(path.read_text()) + if condition == "during-gates": + readiness = github.readiness + + def replace_receipt(*args, **kwargs): + path.unlink() + return readiness(*args, **kwargs) + + monkeypatch.setattr(github, "readiness", replace_receipt) + elif condition in {"missing", "transient"}: path.unlink() - elif condition not in {"failed", "dirty", "matching"}: - report = json.loads(path.read_text()) - if condition in {"wrong-head", "stale"}: - report["head"] = ("a" if draft else "0") * 40 - elif condition == "wrong-commands": - report["results"].pop() - elif condition == "commands": - report["results"][0]["command"] = "changed" - elif condition == "empty": - report["results"] = [] - elif condition == "checkpoint": - report["results"][1:] = [asdict(CheckResult("", 1, 0.0, ""))] - elif condition == "red": - report["results"][0]["exit_code"] = 1 - elif condition == "legacy": - del report["settings_sha256"] - else: - report["settings_sha256"] = "0" * 64 + if condition == "transient": + monkeypatch.setattr(github, "_retry_sleep", lambda _: None) + gh.respond(pr_list_key(), {"stdout": "", "exit_code": 1, "stderr": "HTTP 503"}, [{"number": 7}]) + else: + results = report["results"] + report.update({ + "head": {"head": "a" * 40}, "dirty": {"dirty": True}, + "failed": {"results": [dict(results[0], exit_code=1), *results[1:]]}, + "plan": {"results": results[:-1]}, "empty": {"results": []}, + "legacy": {"settings_sha256": None}, "incompatible": {"settings_sha256": "0" * 64}, + "checkpoint": {"results": [results[0], asdict(CheckResult("", 1, 0, ""))]}, + }[condition]) path.write_text(json.dumps(report)) - - out, _ = expect_cli(capsys, int(reason is not None), "ready") - if reason: - assert f"not ready: {reason}" in out - if draft: - assert "receipt accepted:" not in out - if condition in {"legacy", "incompatible"}: - assert ("Run loopzero check in this worktree at this head with the same current CLI and effective " - "settings as ready, using a local coordinator for delegated stages." in out) + out, err = expect_cli(capsys, 1, command, *(["--wait"] if command == "merge" or condition == "during-gates" else [])) + assert reason in out + err and "receipt accepted:" not in out + assert all(github._read_only(tuple(c["argv"])) for c in gh.calls) + if condition != "during-gates": + expected = [PR_LIST_READ, *LOOKUP_CALLS[1:]] if condition == "transient" else LOOKUP_CALLS[1:] + assert [c["argv"][:2] for c in gh.calls] == expected @pytest.fixture @@ -3118,8 +3116,8 @@ def check_environment(wt, gh, head, tmp_path): return path, policy, ("--config", str(path)) -@pytest.mark.parametrize("case", ["explicit", "ready", "merge", "inherited", "fixed"]) -def test_ready_checks_effective_receipt_environment(gh, capsys, head, monkeypatch, case, check_environment): +@pytest.mark.parametrize("case", ["explicit", "ready", "merge", "fresh", "inherited", "fixed"]) +def test_ready_checks_effective_receipt_environment(wt, gh, capsys, head, monkeypatch, case, check_environment): config_path, config, args = check_environment inherited = case in {"inherited", "fixed"} if inherited: @@ -3135,26 +3133,28 @@ def test_ready_checks_effective_receipt_environment(gh, capsys, head, monkeypatc monkeypatch.setenv("CHECK_POLICY", "new") else: new_config = config.replace('CHECK_POLICY = "old"', 'CHECK_POLICY = "new"') - if case in {"ready", "merge"}: - arm_check_runs(gh, head, [{"name": "checks", "status": "in_progress"}]) + if case in {"ready", "merge", "fresh"}: + arm_check_progress(gh, head, "pending") + command = "merge" if case == "fresh" else case def change_policy(_seconds): - assert config_path.read_text() == config config_path.write_text(new_config) + if case == "fresh": + cfg = cli._load_config(SimpleNamespace(config=config_path, command=command), wt, pin_checks=True) + cli._save_report(wt, cli.dataclasses.replace(cli._load_report(wt), + settings_sha256=cli.sandbox.settings_fingerprint(cfg))) monkeypatch.setattr(cli, "_sleep", change_policy) - expect_cli(capsys, 1, *args, case, "--wait", - stderr_contains=("workflow settings changed while waiting; run loopzero check",)) - arm_check_runs(gh, head, [{"name": "checks", "status": "completed", "conclusion": "success"}]) + hint = "retry with the current settings" if case == "fresh" else "run loopzero check" + expect_cli(capsys, 1, *args, command, "--wait", stderr_contains=(f"workflow settings changed while waiting; {hint}",)) + arm_check_progress(gh, head, "success") else: config_path.write_text(new_config) - if case == "fixed": - expect_cli(capsys, 0, *args, "ready") - else: - expect_cli(capsys, 1, *args, "ready", - stdout_contains=("not ready: check receipt has an incompatible settings fingerprint.",)) - if not inherited: - expect_cli(capsys, 1, *args, "check") + passing = case in {"fixed", "fresh"} + out, _ = expect_cli(capsys, int(not passing), *args, "ready") + assert passing or "not ready: check receipt has an incompatible settings fingerprint." in out + if not (passing or inherited): + expect_cli(capsys, 1, *args, "check") def test_check_refuses_unverified_receipt_after_runner_retarget(wt, gh, capsys, head, tmp_path): @@ -3480,7 +3480,7 @@ def membership(*_): code, out, err = run(capsys, "merge", *(["--wait=1"] if wait else [])) calls = [c["argv"][:2] for c in gh.calls] - assert calls.count(LOOKUP_CALLS[0]) == 1 + assert calls.count(LOOKUP_CALLS[0]) == 0 assert calls.count(detail.split()) == 2 if outcome == "merged": assert (code, err) == (0, "") and out.splitlines()[-1] == merged_sha