diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 2e93a996..3e5a69c5 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -116,6 +116,8 @@ loading the delivery [commands](../src/loopzero/cli.py), which implement the con that requested changes also requires resolved findings at the reviewed head. After its own draft-to-ready write, `ready --wait` revalidates through the same waiter and original deadline. + Each poll resolves the trusted workflow ref, reusing parsed policy when the + branch and immutable revision match the preceding observation. This is best-effort observation: an immediate green read may precede asynchronous CI scheduling, there is no unconditional delay, and merge admission checks readiness again. Missing-run diagnosis keeps its two-minute diff --git a/src/loopzero/candidate.py b/src/loopzero/candidate.py index 8edf4afc..aa314ef5 100644 --- a/src/loopzero/candidate.py +++ b/src/loopzero/candidate.py @@ -82,12 +82,7 @@ def _require(condition: bool, message: str, error: type[CandidateError] = Candid def _identity(actor: object) -> tuple[object, object, object, object]: if not isinstance(actor, dict): return (None, None, None, None) - return ( - actor.get("id"), - actor.get("login"), - actor.get("type"), - actor.get("html_url"), - ) + return actor.get("id"), actor.get("login"), actor.get("type"), actor.get("html_url") def _object(value: JsonValue, message: str) -> JsonObject: @@ -106,10 +101,7 @@ def visit(items: list[object]) -> None: _require(isinstance(item, dict), "Mergify status contains an invalid batch") batch_id = item.get("id") _require(isinstance(batch_id, str) and batch_id, "Mergify batch has no id") - _require( - batch_id not in indexed, - f"Mergify batch id is duplicated: {batch_id}", - ) + _require(batch_id not in indexed, f"Mergify batch id is duplicated: {batch_id}") indexed[batch_id] = item children = item.get("sub_batches") if children is not None: @@ -136,10 +128,8 @@ def _candidate_lineage(status: JsonObject, candidate_number: int) -> tuple[str, CandidateBatchError, ) candidate_id = matches[0]["id"] - pending = [candidate_id] - visited: set[str] = set() - source_numbers: list[int] = [] - missing: list[str] = [] + pending, visited = [candidate_id], set() + source_numbers, missing = [], [] while pending: batch_id = pending.pop() if batch_id in visited: @@ -170,10 +160,8 @@ def _candidate_lineage(status: JsonObject, candidate_number: int) -> tuple[str, ) pending.extend(parent_ids) _require(source_numbers, f"Mergify batch for PR #{candidate_number} has no sources") - _require( - len(source_numbers) == len(set(source_numbers)), - f"Mergify batch for PR #{candidate_number} repeats a source pull request", - ) + _require(len(source_numbers) == len(set(source_numbers)), + f"Mergify batch for PR #{candidate_number} repeats a source pull request") return candidate_id, sorted(source_numbers), sorted(missing) @@ -239,6 +227,11 @@ def _source_fingerprint(source: JsonObject) -> tuple[object, ...]: ) +def _lookup_source(github_get: GitHubGet, repo: str, number: int) -> JsonObject: + return _object(github_get(f"/repos/{repo}/pulls/{number}"), + f"GitHub source PR #{number} lookup returned an invalid payload") + + def _attest_source( source: JsonObject, *, @@ -247,10 +240,7 @@ def _attest_source( candidate_sha: str, github_get: GitHubGet, ) -> str: - _require( - source.get("number") == number, - f"GitHub returned the wrong source PR for #{number}", - ) + _require(source.get("number") == number, f"GitHub returned the wrong source PR for #{number}") _require( source.get("state") == "open", f"source PR #{number} is not open", @@ -280,12 +270,9 @@ def _attest_source( "GitHub compare returned an invalid payload", ) merge_base = comparison.get("merge_base_commit") - _require( - comparison.get("status") in {"ahead", "identical"} - and isinstance(merge_base, dict) - and merge_base.get("sha") == source_sha, - f"source PR #{number} head {source_sha} is not an ancestor of the candidate", - ) + _require(comparison.get("status") in {"ahead", "identical"} + and isinstance(merge_base, dict) and merge_base.get("sha") == source_sha, + f"source PR #{number} head {source_sha} is not an ancestor of the candidate") return source_sha @@ -374,14 +361,11 @@ def _verify_tree(repo: str, main: str, candidate: str, sources: list[str]) -> No cursor = candidate while cursor in graph and pending: parents = graph[cursor] - if cursor in pending: - pending.remove(cursor) - reverse_order.append(cursor) - if len(parents) > 1: - _require(len(parents) == 2, "ambiguous candidate integration topology") - if parents[1] in pending: - pending.remove(parents[1]) - reverse_order.append(parents[1]) + _require(len(parents) <= 2, "ambiguous candidate integration topology") + for source in (cursor, *parents[1:]): + if source in pending: + pending.remove(source) + reverse_order.append(source) cursor = parents[0] if parents else "" _require(not pending, "ambiguous source order in candidate topology") integrated = main @@ -435,26 +419,19 @@ def _attest_candidate_once( batch_wait: list[float], ) -> list[dict[str, object]]: """Return stable source evidence after every source passes `source_policy`.""" - repository = event.get("repository") - event_pr = event.get("pull_request") - _require(isinstance(repository, dict), "GitHub event repository is missing") - _require(isinstance(event_pr, dict), "GitHub event pull request is missing") + repository = _object(event.get("repository"), "GitHub event repository is missing") + event_pr = _object(event.get("pull_request"), "GitHub event pull request is missing") _require( event.get("action") in {"opened", "synchronize"}, "Candidate attestation requires its creation or head-update event", ) full_name = repository.get("full_name") - _require( - isinstance(full_name, str) and _REPOSITORY.fullmatch(full_name) is not None, - "GitHub event repository name is invalid", - ) - event_head = event_pr.get("head") - _require(isinstance(event_head, dict), "GitHub event candidate head is missing") + _require(isinstance(full_name, str) and _REPOSITORY.fullmatch(full_name) is not None, + "GitHub event repository name is invalid") + event_head = _object(event_pr.get("head"), "GitHub event candidate head is missing") event_ref = event_head.get("ref") - _require( - isinstance(event_ref, str) and event_ref.startswith(QUEUE_BRANCH_PREFIX), - "Mergify candidate has an unexpected head ref", - ) + _require(isinstance(event_ref, str) and event_ref.startswith(QUEUE_BRANCH_PREFIX), + "Mergify candidate has an unexpected head ref") owner, repo = full_name.split("/", 1) app = _object(github_get("/apps/mergify"), "GitHub App lookup is invalid") @@ -475,14 +452,10 @@ def _attest_candidate_once( expected_identity == (MERGIFY_BOT_ID, MERGIFY_BOT_LOGIN, "Bot", MERGIFY_APP_URL), "Could not resolve the Mergify GitHub App identity", ) - _require( - _identity(event_pr.get("user")) == expected_identity, - "Candidate author is not the verified Mergify GitHub App", - ) - _require( - _identity(event.get("sender")) == expected_identity, - "Candidate head event was not sent by the verified Mergify GitHub App", - ) + _require(_identity(event_pr.get("user")) == expected_identity, + "Candidate author is not the verified Mergify GitHub App") + _require(_identity(event.get("sender")) == expected_identity, + "Candidate head event was not sent by the verified Mergify GitHub App") candidate_number = event_pr.get("number") candidate_sha = event_head.get("sha") @@ -490,21 +463,15 @@ def _attest_candidate_once( isinstance(candidate_number, int) and candidate_number > 0, "Candidate PR number is invalid", ) - _require( - isinstance(candidate_sha, str) and _SHA.fullmatch(candidate_sha) is not None, - "Candidate head SHA is invalid", - ) + _require(isinstance(candidate_sha, str) and _SHA.fullmatch(candidate_sha) is not None, + "Candidate head SHA is invalid") candidate_path = f"/repos/{full_name}/pulls/{candidate_number}" - candidate_before = _object( - github_get(candidate_path), - "GitHub candidate lookup returned an invalid payload", - ) - _candidate_snapshot( - candidate_before, - event_pr=event_pr, - repository=repository, - expected_identity=expected_identity, - ) + def recheck_candidate(message: str = "GitHub candidate lookup returned an invalid payload") -> None: + candidate = _object(github_get(candidate_path), message) + _candidate_snapshot(candidate, event_pr=event_pr, repository=repository, + expected_identity=expected_identity) + + recheck_candidate() def live_lineage() -> tuple[str, list[int], list[str]]: delay = 2 @@ -512,19 +479,14 @@ def live_lineage() -> tuple[str, list[int], list[str]]: try: return _candidate_lineage(mergify_status(owner, repo, "main"), candidate_number) except CandidateBatchError: - def recheck_candidate() -> None: - current = _object(github_get(candidate_path), "Invalid candidate lookup") - _candidate_snapshot(current, event_pr=event_pr, repository=repository, - expected_identity=expected_identity) - - recheck_candidate() + recheck_candidate("Invalid candidate lookup") remaining = batch_deadline - _retry_clock() if remaining <= 0: raise started = _retry_clock() _retry_sleep(min(delay, remaining)) batch_wait[0] += _retry_clock() - started - recheck_candidate() + recheck_candidate("Invalid candidate lookup") if _retry_clock() >= batch_deadline: raise delay = min(delay * 2, 30) @@ -534,10 +496,7 @@ def recheck_candidate() -> None: main_before = github_get(main_path) if first_lineage[2] else None source_snapshots: dict[int, tuple[str, tuple[object, ...]]] = {} for number in first_lineage[1]: - source = _object( - github_get(f"/repos/{full_name}/pulls/{number}"), - f"GitHub source PR #{number} lookup returned an invalid payload", - ) + source = _lookup_source(github_get, full_name, number) source_sha = _attest_source( source, number=number, @@ -551,7 +510,7 @@ def recheck_candidate() -> None: except Exception as exc: current = None with contextlib.suppress(Exception): - current = github_get(f"/repos/{full_name}/pulls/{number}") + current = _lookup_source(github_get, full_name, number) if (isinstance(current, dict) and current.get("merged") is True and isinstance(current.get("head"), dict) and current["head"].get("sha") == source_sha): @@ -562,10 +521,7 @@ def recheck_candidate() -> None: try: main_ref = _object(main_before, "main ref unavailable") main_sha = _object(main_ref.get("object"), "main object unavailable").get("sha") - _require( - isinstance(main_sha, str) and _SHA.fullmatch(main_sha) is not None, - "invalid main head", - ) + _require(isinstance(main_sha, str) and _SHA.fullmatch(main_sha) is not None, "invalid main head") _verify_tree(full_name, main_sha, candidate_sha, [snapshot[0] for snapshot in source_snapshots.values()]) _require( @@ -586,21 +542,9 @@ def recheck_candidate() -> None: "Mergify candidate membership changed during attestation", CandidateRaceError, ) - candidate_after = _object( - github_get(candidate_path), - "GitHub candidate lookup returned an invalid payload", - ) - _candidate_snapshot( - candidate_after, - event_pr=event_pr, - repository=repository, - expected_identity=expected_identity, - ) + recheck_candidate() for number, (expected_sha, expected_fingerprint) in source_snapshots.items(): - current = _object( - github_get(f"/repos/{full_name}/pulls/{number}"), - f"GitHub source PR #{number} lookup returned an invalid payload", - ) + current = _lookup_source(github_get, full_name, number) current_head = current.get("head") _require( isinstance(current_head, dict) and current_head.get("sha") == expected_sha, diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 17aef1cb..e58359c3 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -107,14 +107,16 @@ def _repo_root(wt: Path) -> Path: return root -def _load_config(args: argparse.Namespace, root: Path, *, pin_checks: bool = False) -> Config: +def _load_config( + args: argparse.Namespace, root: Path, *, pin_checks: bool = False, previous: Config | None = None, +) -> Config: path = args.config or root / "workflow.toml" if not pin_checks: return config_mod.load(path) if args.config: print("checks are unpinned because --config was provided") return config_mod.load(path) - config = config_mod.load_trusted(root) + config = config_mod.load_trusted(root, previous=previous) if args.command == "check": if not config.checks: raise config_mod.ConfigError( @@ -1330,17 +1332,18 @@ def _print_check_wait_timeout(pr: github.PR) -> None: def _verify_wait_snapshot( args: argparse.Namespace | None, wt: Path, config: Config, head: str, current_head: str, -) -> None: + previous: Config | None = None, +) -> Config: if current_head != head: raise CliError(f"PR head changed while waiting: {head[:12]} to {current_head[:12]}") if args is None: - return - latest = _load_config(args, wt, pin_checks=True) + return config + latest = _load_config(args, wt, pin_checks=True, previous=previous or config) changed = "workflow settings" if latest == config: if (latest.trusted_base_revision == config.trusted_base_revision or not (config.check_runner or config.inputs)): - return + return latest changed = "check base" if _current_check_report(wt, latest, head) is None: raise CliError(f"{changed} changed while waiting; run loopzero check and retry") @@ -1358,13 +1361,14 @@ def _wait_for_checks( started = grace_started if started is None else started current = pr stale_notice = False + previous = config for _ in _poll_until(started, timeout, bounded=bounded): if initial is not None: readiness = initial initial = None else: current = github.pr_view(config.repo, pr.number) - _verify_wait_snapshot(args, wt, config, pr.head_sha, current.head_sha) + previous = _verify_wait_snapshot(args, wt, config, pr.head_sha, current.head_sha, previous) if allow_merged and current.state == "MERGED": return current, None, kicked readiness = _readiness(wt, config, current, pr.head_sha, workflow_wait=True) diff --git a/src/loopzero/config.py b/src/loopzero/config.py index cc1ca931..6563d33b 100644 --- a/src/loopzero/config.py +++ b/src/loopzero/config.py @@ -89,16 +89,39 @@ def base_revision(worktree: Path, base_branch: str) -> str: raise ConfigError(f"git rev-parse origin/{base_branch} failed: {message}") -def _remote_workflow(worktree: Path, branch: str) -> tuple[Config, str]: +def _has_replacement_refs(common_dir: Path) -> bool: + # A replacement can change what Git reads at a fixed object name. + for entry in ("refs/replace", "reftable"): + try: + (common_dir / entry).lstat() + except FileNotFoundError: + continue + except OSError: + return True + return True + try: + packed = (common_dir / "packed-refs").read_bytes() + except FileNotFoundError: + return False + except OSError: + return True + return b" refs/replace/" in packed + + +def _remote_workflow(worktree: Path, branch: str, previous: Config | None) -> tuple[Config, str]: source = f"origin/{branch}:workflow.toml" hint = "Fetch the trusted base workflow, or supply --config for bootstrap or an override." + directory_args = ["--path-format=absolute", "--git-common-dir"] if previous is not None else [] resolved = _proc.run( - ["git", "rev-parse", "--verify", f"refs/remotes/origin/{branch}^{{commit}}"], + ["git", "rev-parse", *directory_args, "--verify", f"refs/remotes/origin/{branch}^{{commit}}"], cwd=worktree, env_allowlist=worktree_mod.GIT_ENV, timeout=60, ) if resolved.exit_code != 0: raise ConfigError(f"{source} has no remote-tracking base commit. {hint}") - revision = resolved.stdout.strip() + common_dir, _, revision = resolved.stdout.rstrip("\n").rpartition("\n") + if (previous is not None and previous.base_branch == branch and previous.trusted_base_revision == revision + and common_dir and not _has_replacement_refs(Path(common_dir))): + return previous, revision shown = _proc.run( ["git", "show", f"{revision}:workflow.toml"], cwd=worktree, env_allowlist=worktree_mod.GIT_ENV, timeout=60, @@ -115,7 +138,7 @@ def _remote_workflow(worktree: Path, branch: str) -> tuple[Config, str]: raise ConfigError(f"{source}: {exc}. {hint}") from None -def load_trusted(worktree: Path) -> Config: +def load_trusted(worktree: Path, *, previous: Config | None = None) -> Config: """Select delivery policy using Git's origin default and its trusted workflow.""" prefix = "refs/remotes/origin/" default = _proc.run( @@ -129,10 +152,10 @@ def load_trusted(worktree: Path) -> Config: "or supply --config for bootstrap or an override." ) branch = ref.removeprefix(prefix) - policy, revision = _remote_workflow(worktree, branch) + policy, revision = _remote_workflow(worktree, branch, previous) if policy.base_branch == branch: return replace(policy, trusted_base_revision=revision) - base, revision = _remote_workflow(worktree, policy.base_branch) + base, revision = _remote_workflow(worktree, policy.base_branch, previous) 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/src/loopzero/runners.py b/src/loopzero/runners.py index 0e384789..29bd50fc 100644 --- a/src/loopzero/runners.py +++ b/src/loopzero/runners.py @@ -36,15 +36,10 @@ _CODEX_EFFORT_RE = re.compile(r"^[ \t]*reasoning effort[ \t]*:[ \t]*([^\r\n]+)$", re.IGNORECASE | re.MULTILINE) -_AUTH_PATTERNS = ( - re.compile(r"not logged in", re.IGNORECASE), - re.compile(r"please run /login", re.IGNORECASE), - re.compile(r"please (?:run )?`?codex login`?", re.IGNORECASE), - re.compile(r"invalid api key", re.IGNORECASE), - re.compile(r"authentication[_ ]error", re.IGNORECASE), - re.compile(r"OAuth access token has expired|Failed to authenticate|token expired", re.IGNORECASE), - re.compile(r"\b401\b.*unauthori[sz]ed|unauthori[sz]ed.*\b401\b", re.IGNORECASE), - re.compile(r"login required|not authenticated|missing credentials", re.IGNORECASE), +_AUTH_FAILURE = re.compile( + r"not logged in|please run /login|please (?:run )?`?codex login`?|invalid api key" + r"|authentication[_ ]error|OAuth access token has expired|Failed to authenticate|token expired|login required" + r"|\b401\b.*unauthori[sz]ed|unauthori[sz]ed.*\b401\b|not authenticated|missing credentials", re.IGNORECASE, ) REVIEW_SCHEMA: dict[str, object] = { @@ -104,16 +99,11 @@ class RunnerUsageLimit(RunnerBadOutput): r'reached your [\w .-]*limit|hit your (?:(?:usage|weekly|session) )?limit' r'|usage_limit_(?:reached|exceeded)|usageLimitExceeded', re.IGNORECASE, ) -_TOO_LONG_PATTERNS = ( - re.compile(r"prompt is too long", re.IGNORECASE), - re.compile(r"context_length_exceeded", re.IGNORECASE), - re.compile(r"maximum context length|input_too_large", re.IGNORECASE), # codex: >1 Mi chars +_TOO_LONG = re.compile( + r"prompt is too long|context_length_exceeded|maximum context length|input_too_large", re.IGNORECASE ) -# --------------------------------------------------------------------------- prompt - - def _review_policy(kind: str, *, split: bool) -> str: """Fixed native instructions; only the validated review scope varies.""" if kind not in ("primary", "delta"): @@ -177,29 +167,25 @@ def build_prompt(*, kind: str, head: str, task_text: str, diff: str, return header + "\n" + diff -# --------------------------------------------------------------------------- parsing - - def _tail(text: str) -> str: return text[-TAIL_CHARS:] def _looks_like_auth_failure(text: str) -> bool: - return any(p.search(text) for p in _AUTH_PATTERNS) + return _AUTH_FAILURE.search(text) is not None def _claude_envelope_auth_failure(envelope: object) -> bool: - if not isinstance(envelope, dict): - return False - return envelope.get("api_error_status") in (401, 403) or ( - envelope.get("terminal_reason") == "api_error" - and re.search(r"authenticate|OAuth|expired|401", str(envelope.get("result", "")), - re.IGNORECASE) is not None + return isinstance(envelope, dict) and ( + envelope.get("api_error_status") in (401, 403) + or (envelope.get("terminal_reason") == "api_error" + and re.search(r"authenticate|OAuth|expired|401", str(envelope.get("result", "")), + re.IGNORECASE) is not None) ) def _looks_too_long(text: str) -> bool: - return any(p.search(text) for p in _TOO_LONG_PATTERNS) + return _TOO_LONG.search(text) is not None def _subscription_exhausted(text: str, envelope: object = None) -> bool: @@ -327,18 +313,20 @@ def _review_config(family: str, binary: Path, ro_paths: tuple[str, ...]) -> Conf def _git_dir(cwd: Path, flag: str, env_allowlist: tuple[str, ...]) -> Path: - done = _proc.run(["git", "rev-parse", flag], cwd=cwd, env_allowlist=env_allowlist, timeout=30) + raw = _review_git(cwd, env_allowlist, f"rev-parse {flag}", "rev-parse", flag) + return (cwd / raw.strip()).resolve() + + +def _review_git(cwd: Path, allowlist: tuple[str, ...], label: str, *args: str) -> str: + done = _proc.run(["git", *args], cwd=cwd, env_allowlist=allowlist, timeout=30) if done.exit_code != 0: - raise RunnerBadOutput(f"git rev-parse {flag} exited {done.exit_code}", _tail(done.stderr)) - raw = Path(done.stdout.strip()) - return (raw if raw.is_absolute() else cwd / raw).resolve() + raise RunnerBadOutput(f"git {label} exited {done.exit_code}", _tail(done.stderr)) + return done.stdout def _git_dirs(cwd: Path, env_allowlist: tuple[str, ...]) -> tuple[Path, Path]: - done = _proc.run( - ["git", "rev-parse", "--path-format=absolute", "--git-common-dir", "--git-dir"], - cwd=cwd, env_allowlist=env_allowlist, timeout=30, - ) + argv = ["git", "rev-parse", "--path-format=absolute", "--git-common-dir", "--git-dir"] + done = _proc.run(argv, cwd=cwd, env_allowlist=env_allowlist, timeout=30) paths = done.stdout.removesuffix("\n").split("\n") if done.exit_code == 0 and len(paths) == 2: common_dir, git_dir = map(Path, paths) @@ -435,36 +423,37 @@ def _sandbox_prefix( def _auth_binds(family: str, home: Path) -> tuple[tuple[Path, Path], ...]: """Prepare mount points and return existing host auth paths to bind read-write.""" - binds: list[tuple[Path, Path]] = [] + sandbox_home = Path(sandbox.SANDBOX_HOME) if family == "claude": # Native environment auth needs no disk credentials or host refresh state. if any(os.environ.get(name) for name in CLAUDE_AUTH_ENV): return () - source_dir = Path(os.environ.get("CLAUDE_CONFIG_DIR") or Path.home() / ".claude").resolve() - if source_dir.is_dir(): - (home / ".claude").mkdir() - binds.append((source_dir, Path(sandbox.SANDBOX_HOME) / ".claude")) - state_file = (Path.home() / ".claude.json").resolve() - if state_file.is_file(): - (home / ".claude.json").touch() - binds.append((state_file, Path(sandbox.SANDBOX_HOME) / ".claude.json")) + state = Path(os.environ.get("CLAUDE_CONFIG_DIR") or Path.home() / ".claude") + mounts = ((state, ".claude", True), (Path.home() / ".claude.json", ".claude.json", False)) else: # Only auth.json: codex rewrites it in place on refresh, and the reviewer's # shell runs unsandboxed inside bwrap, so the rest of CODEX_HOME stays private. - auth_file = (Path(os.environ.get("CODEX_HOME") or Path.home() / ".codex") / "auth.json").resolve() - if auth_file.is_file(): - (home / ".codex").mkdir() - (home / ".codex" / "auth.json").touch() - binds.append((auth_file, Path(sandbox.SANDBOX_HOME) / ".codex" / "auth.json")) + state = Path(os.environ.get("CODEX_HOME") or Path.home() / ".codex") + mounts = ((state / "auth.json", ".codex/auth.json", False),) + binds = [] + for path, destination, directory in mounts: + source, target = path.resolve(), home / destination + if directory and source.is_dir(): + target.mkdir() + elif not directory and source.is_file(): + if target.parent != home: + target.parent.mkdir() + target.touch() + else: + continue + binds.append((source, sandbox_home / destination)) return tuple(binds) def _observe_codex_version(binary: Path, cwd: Path, env_allowlist: tuple[str, ...]) -> str: diagnostic = "codex: version probe failed" try: - done = _proc.run( - [str(binary), "--version"], cwd=cwd, env_allowlist=env_allowlist, timeout=30, - ) + done = _proc.run([str(binary), "--version"], cwd=cwd, env_allowlist=env_allowlist, timeout=30) except (_proc.ToolMissing, _proc.ProcTimeout, OSError) as exc: raise RunnerBadOutput(diagnostic) from exc if done.exit_code: @@ -477,12 +466,8 @@ def _codex_supports_ignore_user_config( ) -> bool: """Return whether this Codex version can avoid loading bound ``config.toml``.""" try: - done = _proc.run( - [str(binary), "exec", "--help"], - cwd=cwd, - env_allowlist=env_allowlist, - timeout=30, - ) + done = _proc.run([str(binary), "exec", "--help"], cwd=cwd, + env_allowlist=env_allowlist, timeout=30) except (_proc.ToolMissing, _proc.ProcTimeout, FileNotFoundError): return False return done.exit_code == 0 and "--ignore-user-config" in f"{done.stdout}\n{done.stderr}" @@ -583,6 +568,11 @@ def _setting(value: object) -> str | None: return value if isinstance(value, str) and re.fullmatch(r"[A-Za-z0-9_./:-]{1,128}", value) else None +def _settings(value: object) -> dict[str, str | None]: + fields = value if isinstance(value, dict) else {} + return {key: _setting(fields.get(key)) for key in ("model", "effort")} + + def review_settings(result: ReviewResult) -> list[dict[str, dict[str, str | None]]]: """Keep native claims, launch configuration and optional requests distinct.""" try: @@ -600,22 +590,16 @@ def review_settings(result: ReviewResult) -> list[dict[str, dict[str, str | None for index, envelope in enumerate(envelopes): envelope = envelope if isinstance(envelope, dict) else {} request = requested[index] if index < len(requested) else {} - request = request if isinstance(request, dict) else {} if result.family == "claude": usage = envelope.get("modelUsage") models = [key for key in usage if _setting(key)] if isinstance(usage, dict) else [] reported = {"model": ", ".join(models[:8]) or None, "effort": None} else: - evidence = envelope.get("reported_settings") - evidence = evidence if isinstance(evidence, dict) else {} - reported = {key: _setting(evidence.get(key)) for key in ("model", "effort")} - pinned = ( - (configured[index] if index < len(configured) else {}) - if result.family == "claude" else envelope.get("configured_settings", {}) - ) - pinned = pinned if isinstance(pinned, dict) else {} - settings.append({"configured": {key: _setting(pinned.get(key)) for key in ("model", "effort")}, - "requested": {key: _setting(request.get(key)) for key in ("model", "effort")}, + reported = _settings(envelope.get("reported_settings")) + pinned = envelope.get("configured_settings") + if result.family == "claude": + pinned = configured[index] if index < len(configured) else None + settings.append({"configured": _settings(pinned), "requested": _settings(request), "reported": reported}) return settings @@ -679,9 +663,7 @@ def _bounded_int(value, minimum=1): def _identifier(value, limit=128): - return ( - isinstance(value, str) and len(value) <= limit and re.fullmatch(r"[A-Za-z0-9_.:-]+", value) - ) + return isinstance(value, str) and len(value) <= limit and re.fullmatch(r"[A-Za-z0-9_.:-]+", value) def _hex(value, length): @@ -691,19 +673,8 @@ def _hex(value, length): def _valid_codex_evidence(value): """Strict closed schema, including exact context/order/offset bounds; no coercion.""" fields = { - "version", - "family", - "repo", - "pr", - "head", - "kind", - "publisher", - "receipt", - "raw_sha256", - "raw_bytes", - "complete", - "chunk_count", - "calls", + "version", "family", "repo", "pr", "head", "kind", "publisher", "receipt", + "raw_sha256", "raw_bytes", "complete", "chunk_count", "calls", } if not isinstance(value, dict) or set(value) != fields: return False @@ -731,22 +702,11 @@ def _valid_codex_evidence(value): return False sessions, ranges = set(), set() for index, call in enumerate(value["calls"], 1): - keys = { - "index", - "session", - "requested", - "reported", - "fatal", - "inspection", - "base", - "diff_sha256", - } if not isinstance(call, dict): return False - if "configured" in call: - keys.add("configured") - if call.get("inspection") == "verified": - keys |= {"head_event", "diff_event"} + settings_keys = ("requested", "reported", "configured") if "configured" in call else ("requested", "reported") + event_keys = ("head_event", "diff_event") if call.get("inspection") == "verified" else () + keys = {"index", "session", "fatal", "inspection", "base", "diff_sha256", *settings_keys, *event_keys} if ( set(call) != keys or not _bounded_int(call["index"]) @@ -761,26 +721,23 @@ def _valid_codex_evidence(value): return False sessions.add(call["session"]) ranges.add((call["base"], call["diff_sha256"])) - for label in ("requested", "reported", *(("configured",) if "configured" in call else ())): + for label in settings_keys: settings = call[label] if not isinstance(settings, dict) or set(settings) != {"model", "effort"}: return False for key, limit in (("model", 128), ("effort", 32)): if settings[key] is not None and not _identifier(settings[key], limit): return False - if call["inspection"] == "verified": - for label in ("head_event", "diff_event"): - event = call[label] - if ( - not isinstance(event, dict) - or set(event) != {"id", "start", "end"} - or not _identifier(event["id"]) - or not _bounded_int(event["start"], 0) - or not _bounded_int(event["end"]) - or not event["start"] < event["end"] <= value["raw_bytes"] - or (label == "head_event" and event["end"] - event["start"] != 40) - ): - return False + for label in event_keys: + event = call[label] + if ( + not isinstance(event, dict) or set(event) != {"id", "start", "end"} + or not _identifier(event["id"]) + or not (_bounded_int(event["start"], 0) and _bounded_int(event["end"])) + or not event["start"] < event["end"] <= value["raw_bytes"] + or (label == "head_event" and event["end"] - event["start"] != 40) + ): + return False return len(ranges) == 1 @@ -794,6 +751,10 @@ def valid_codex_evidence(value): def encode_codex_evidence(value): if not valid_codex_evidence(value): raise RunnerBadOutput("codex: invalid native evidence projection") + return _codex_header(value) + + +def _codex_header(value): encoded = json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode() header = CODEX_HEADER + base64.urlsafe_b64encode(encoded).decode().rstrip("=") + " -->" if len(header.encode()) > CODEX_HEADER_LIMIT: @@ -811,7 +772,7 @@ def decode_codex_evidence(header): token = match[1] data = base64.b64decode(token + "=" * (-len(token) % 4), altchars=b"-_", validate=True) value = _evidence_json(data) - if not valid_codex_evidence(value) or encode_codex_evidence(value) != header: + if not valid_codex_evidence(value) or _codex_header(value) != header: raise ValueError("noncanonical or invalid evidence") return value @@ -868,25 +829,22 @@ def _native_inspection(envelope, context): started, completed, found = {}, set(), {} for event in envelope["events"]: item = event.get("item") - if ( - not isinstance(item, dict) - or item.get("type") != "command_execution" - or not _identifier(item.get("id")) - ): + if not isinstance(item, dict) or item.get("type") != "command_execution" or not _identifier(item.get("id")): continue - if event.get("type") == "item.started": + event_type = event.get("type") + if event_type == "item.started": if item["id"] in started: return {} started[item["id"]] = item.get("command") continue - if event.get("type") == "item.completed": - if item["id"] in completed: - return {} - completed.add(item["id"]) + if event_type != "item.completed": + continue + if item["id"] in completed: + return {} + completed.add(item["id"]) output, command = item.get("aggregated_output"), item.get("command") if ( - event.get("type") != "item.completed" - or item.get("status") != "completed" + item.get("status") != "completed" or type(item.get("exit_code")) is not int or item["exit_code"] != 0 or not isinstance(output, str) @@ -900,20 +858,14 @@ def _native_inspection(envelope, context): if operation == ("head",): match = re.search(rb"(?m)^" + context["head"].encode() + rb"(?=\r?$)", data) if match: - found["head_event"] = { - "id": item["id"], - "start": match.start(), - "end": match.end(), - } + found["head_event"] = {"id": item["id"], "start": match.start(), "end": match.end()} elif operation == ("diff", context["base"], context["head"]): match = re.search(rb"(?m)^diff --git ", data) - if match: - start, end = match.start(), match.start() + context["diff_bytes"] - if ( - end <= len(data) - and hashlib.sha256(data[start:end]).hexdigest() == context["diff_sha256"] - ): - found["diff_event"] = {"id": item["id"], "start": start, "end": end} + if not match: + continue + start, end = match.start(), match.start() + context["diff_bytes"] + if end <= len(data) and hashlib.sha256(data[start:end]).hexdigest() == context["diff_sha256"]: + found["diff_event"] = {"id": item["id"], "start": start, "end": end} return found if set(found) == {"head_event", "diff_event"} else {} @@ -935,20 +887,8 @@ def _codex_evidence(result): context = envelope.get("review_context") if not isinstance(context, dict): raise RunnerBadOutput("codex: missing recorded review context") - binding = { - key: context.get(key) - for key in ( - "repo", - "pr", - "publisher", - "head", - "kind", - "base", - "diff_sha256", - "diff_bytes", - "cwd", - ) - } + shared_fields = ("repo", "pr", "publisher", "head", "kind", "base", "diff_sha256", "diff_bytes", "cwd") + binding = {key: context.get(key) for key in shared_fields} if common is None: common = binding if ( @@ -965,12 +905,8 @@ def _codex_evidence(result): or any( not _hex(context.get(key), 64) for key in ( - "fragment_sha256", - "prompt_sha256", - "policy_sha256", - "source_sha256", - "binary_sha256", - "argv_sha256", + "fragment_sha256", "prompt_sha256", "policy_sha256", + "source_sha256", "binary_sha256", "argv_sha256", ) ) ): @@ -1043,6 +979,7 @@ def _codex_evidence(result): "diff_sha256": context["diff_sha256"], } ) + raw_bytes = result.raw.encode("utf-8") value = { "version": 1, "family": "codex", @@ -1052,8 +989,8 @@ def _codex_evidence(result): "kind": result.kind, "publisher": common["publisher"], "receipt": f".loopzero/review-{result.head[:12]}-{result.kind}.json", - "raw_sha256": hashlib.sha256(result.raw.encode("utf-8")).hexdigest(), - "raw_bytes": len(result.raw.encode("utf-8")), + "raw_sha256": hashlib.sha256(raw_bytes).hexdigest(), + "raw_bytes": len(raw_bytes), "complete": True, "chunk_count": len(calls), "calls": calls, @@ -1162,9 +1099,6 @@ def _codex_provenance( return provenance, json.dumps(envelope, separators=(",", ":")) -# --------------------------------------------------------------------------- adapters - - def _review_claude( prompt: str, *, policy: str, cwd: Path, head: str, kind: str, timeout: int, ro_paths: tuple[str, ...], model: str | None, effort: str | None, @@ -1197,9 +1131,8 @@ def _review_claude( argv[0] = str(binary) configured = {"model": model or None, "effort": effort or None} # explicit --model/--effort above done = _run( - [*prefix, *argv], cwd=cwd, prompt=prompt, - env_allowlist=(*config.env_allowlist, *CLAUDE_AUTH_ENV), timeout=timeout, - family="claude", + [*prefix, *argv], cwd=cwd, prompt=prompt, timeout=timeout, family="claude", + env_allowlist=(*config.env_allowlist, *CLAUDE_AUTH_ENV), ) raw = done.stdout try: @@ -1409,18 +1342,15 @@ def merge_reviews(results: list[ReviewResult]) -> ReviewResult: "configured_settings": [call["configured"] for result in results for call in review_settings(result)], } if first.family == "claude": - provenance.update( - usage=[result.provenance["usage"] for result in results], - total_cost_usd=sum(float(result.provenance["total_cost_usd"]) for result in results), - duration_api_ms=sum(float(result.provenance["duration_api_ms"]) for result in results), - ) + provenance["usage"] = [result.provenance["usage"] for result in results] + for key in ("total_cost_usd", "duration_api_ms"): + provenance[key] = sum(float(result.provenance[key]) for result in results) else: provenance["token_usage"] = [result.provenance["token_usage"] for result in results] provenance["cli_versions"] = [result.provenance.get("cli_version") for result in results] - return ReviewResult( - family=first.family, - head=first.head, - kind=first.kind, + return replace( + first, + fallback="", verdict=verdict, findings=findings, raw=json.dumps(envelopes, separators=(",", ":")), @@ -1435,10 +1365,7 @@ def merge_reviews(results: list[ReviewResult]) -> ReviewResult: def split_diff(diff: str, budget: int) -> list[str]: """Group unified-diff file blocks below ``budget`` bytes.""" starts = [match.start() for match in re.finditer(r"(?m)^diff --git ", diff)] - blocks = [ - diff[starts[i] : starts[i + 1] if i + 1 < len(starts) else len(diff)] - for i in range(len(starts)) - ] if starts else [diff] + blocks = [diff[start:end] for start, end in zip(starts, [*starts[1:], len(diff)], strict=False)] or [diff] if len(diff.encode()) > budget: blocks = [_summarize_deleted(block) for block in blocks] pieces = [piece for block in blocks for piece in _split_bytes(block, budget)] @@ -1494,6 +1421,39 @@ def _split_bytes(text: str, budget: int) -> list[str]: return pieces +def _validated_payloads(family, envelopes, provenance, sessions): + if family not in ("claude", "codex") or [item.get("session_id") for item in envelopes] != sessions: + return None + usage_key = "usage" if family == "claude" else "token_usage" + usages = [item.get(usage_key) for item in envelopes] + if not all(isinstance(item, dict) for item in usages): + return None + if provenance.get(usage_key) != (usages[0] if len(usages) == 1 else usages): + return None + try: + if family == "claude" and _valid_claude_envelopes(envelopes, provenance): + return [_claude_payload(item) for item in envelopes] + if family == "codex" and all(item.get("type") == "codex_exec_result" + and not codex_fatal_startup(item) for item in envelopes): + return [_extract_json_object(str(item["final_message"])) for item in envelopes] + except (KeyError, ValueError): + return None + return None + + +def _valid_claude_envelopes(envelopes, provenance): + if not all(item.get("type") == "result" and item.get("subtype", "success") == "success" + and not item.get("is_error") for item in envelopes): + return False + for key in ("total_cost_usd", "duration_api_ms"): + amounts = [item.get(key) for item in envelopes] + if not all(isinstance(value, (int, float)) and not isinstance(value, bool) for value in amounts): + return False + if provenance.get(key) != sum(amounts): + return False + return True + + def validate_runner_result(result: ReviewResult) -> bool: """Return whether saved provenance agrees with the provider envelope(s).""" provenance = result.provenance @@ -1521,46 +1481,8 @@ def validate_runner_result(result: ReviewResult) -> bool: envelopes = decoded if isinstance(decoded, list) else [decoded] if len(envelopes) != result.chunk_count or not all(isinstance(item, dict) for item in envelopes): return False - if result.family == "claude": - envelope_sessions = [item.get("session_id") for item in envelopes] - usages = [item.get("usage") for item in envelopes] - costs = [item.get("total_cost_usd") for item in envelopes] - durations = [item.get("duration_api_ms") for item in envelopes] - expected_usage: object = usages[0] if len(usages) == 1 else usages - provenance_ok = ( - envelope_sessions == sessions - and all(item.get("type") == "result" for item in envelopes) - and all(item.get("subtype", "success") == "success" for item in envelopes) - and all(not item.get("is_error") for item in envelopes) - and all(isinstance(item, dict) for item in usages) - and all(isinstance(item, (int, float)) and not isinstance(item, bool) - for item in costs + durations) - and provenance.get("usage") == expected_usage - and provenance.get("total_cost_usd") == sum(costs) - and provenance.get("duration_api_ms") == sum(durations) - ) - try: - payloads = [_claude_payload(item) for item in envelopes] - except (json.JSONDecodeError, ValueError): - return False - elif result.family == "codex": - envelope_sessions = [item.get("session_id") for item in envelopes] - usages = [item.get("token_usage") for item in envelopes] - expected_usage = usages[0] if len(usages) == 1 else usages - provenance_ok = ( - envelope_sessions == sessions - and all(item.get("type") == "codex_exec_result" for item in envelopes) - and not any(codex_fatal_startup(item) for item in envelopes) - and all(isinstance(item, dict) for item in usages) - and provenance.get("token_usage") == expected_usage - ) - try: - payloads = [_extract_json_object(str(item["final_message"])) for item in envelopes] - except (KeyError, json.JSONDecodeError, ValueError): - return False - else: - return False - if not provenance_ok: + payloads = _validated_payloads(result.family, envelopes, provenance, sessions) + if payloads is None: return False try: parsed = [ @@ -1577,17 +1499,14 @@ def validate_runner_result(result: ReviewResult) -> bool: ) else "approve" if result.findings != findings or result.verdict != verdict: return False - if result.family == "codex": - try: + try: + if result.family == "codex": _codex_evidence(result) - except (RunnerBadOutput, ValueError, KeyError, TypeError, AttributeError): - return False + except (RunnerBadOutput, ValueError, KeyError, TypeError, AttributeError): + return False return True -# --------------------------------------------------------------------------- family - - def family_from_trailer(value: str) -> str | None: """Map a ``Co-Authored-By`` value to a reviewer family, if recognisable.""" lowered = value.lower() @@ -1605,12 +1524,6 @@ def author_families(cwd: Path, head: str, base: str) -> set[str]: use the PR merge-base, including for delta reviews of a narrower diff. """ revision = f"{base}..{head}" - done = _proc.run( - ["git", "log", "--format=%(trailers:key=Co-Authored-By,valueonly)", revision], - cwd=cwd, - env_allowlist=_ALLOWLIST, - timeout=30, - ) - if done.exit_code != 0: - raise RunnerBadOutput(f"git log {revision} exited {done.exit_code}", _tail(done.stderr)) - return {family for line in done.stdout.splitlines() if (family := family_from_trailer(line))} + trailers = _review_git(cwd, _ALLOWLIST, f"log {revision}", + "log", "--format=%(trailers:key=Co-Authored-By,valueonly)", revision) + return {family for line in trailers.splitlines() if (family := family_from_trailer(line))} diff --git a/src/loopzero/sandbox.py b/src/loopzero/sandbox.py index eaacf717..a127887c 100644 --- a/src/loopzero/sandbox.py +++ b/src/loopzero/sandbox.py @@ -497,17 +497,15 @@ def bwrap_argv( instead of cleared, so secrets never appear as ``--setenv`` arguments. ``writable_binds`` overlays specific paths inside the otherwise private HOME. """ - argv = [ - "bwrap", "--die-with-parent", "--new-session", "--unshare-all", - *(["--share-net"] if config.network else []), - "--cap-drop", "ALL", - ] + argv = ["bwrap", "--die-with-parent", "--new-session", "--unshare-all"] + if config.network: + argv.append("--share-net") + argv += ["--cap-drop", "ALL"] for path in SYSTEM_RO: if Path(path).exists(): argv += ["--ro-bind", path, path] argv += ["--dev", "/dev", "--proc", "/proc"] - for path in ("/tmp", "/run", "/var/run"): - argv += ["--tmpfs", path] + argv += ["--tmpfs", "/tmp", "--tmpfs", "/run", "--tmpfs", "/var/run"] # Restore resolv.conf (or its parent for masked symlinks) over the private tmpfs. if config.network: resolv_conf = Path("/etc/resolv.conf") @@ -518,12 +516,10 @@ def bwrap_argv( else: source, destination = resolved, resolv_conf argv += ["--ro-bind", str(source), str(destination)] - for path in config.sandbox_ro: - argv += ["--ro-bind-try", path, path] - for path in config.writable: - argv += ["--bind-try", path, path] - argv += ["--bind", str(home), SANDBOX_HOME] - for source, destination in writable_binds: + for flag, paths in (("--ro-bind-try", config.sandbox_ro), ("--bind-try", config.writable)): + for path in paths: + argv += [flag, path, path] + for source, destination in ((home, SANDBOX_HOME), *writable_binds): argv += ["--bind", str(source), str(destination)] # Read-only tree/Git binds follow tmpfs so paths under /tmp stay visible. binds = [worktree] diff --git a/src/loopzero/worktree.py b/src/loopzero/worktree.py index 008a7cde..7bf653e3 100644 --- a/src/loopzero/worktree.py +++ b/src/loopzero/worktree.py @@ -12,6 +12,7 @@ from loopzero._proc import run GIT_ENV = ("PATH", "HOME", "LANG", "LC_ALL", "TERM", "GIT_SSH_COMMAND", "SSH_AUTH_SOCK") +_ABSOLUTE_COMMON_DIR = ("rev-parse", "--path-format=absolute", "--git-common-dir") EXCLUDES = (".worktrees/", ".loopzero/") _BASE_LINE = re.compile(r"^Base:\s*([0-9a-fA-F]{7,40})\s*$", re.MULTILINE) _TASK_TEMPLATE = """# {title} @@ -56,7 +57,7 @@ def _git( preserve_whitespace: bool = False, preserve_newlines: bool = False, ) -> str: argv = ("git", *args) - done = run(list(argv), cwd=cwd, env_allowlist=GIT_ENV, timeout=timeout, + done = run(argv, cwd=cwd, env_allowlist=GIT_ENV, timeout=timeout, preserve_newlines=preserve_newlines) if done.exit_code != 0: raise GitError(argv, done.stderr or done.stdout) @@ -79,8 +80,8 @@ def branch_name(repo_root: Path, slug: str) -> str: def title_from_slug(slug: str) -> str: """`add-workflow_config-note` -> `Add workflow config note`.""" - words = re.sub(r"[-_]+", " ", slug).split() - return " ".join(words)[:1].upper() + " ".join(words)[1:] + title = " ".join(re.sub(r"[-_]+", " ", slug).split()) + return title[:1].upper() + title[1:] def worktree_dir(repo_root: Path, slug: str) -> Path: @@ -94,21 +95,18 @@ def task_file(wt: Path) -> Path: def _branch_exists(repo_root: Path, branch: str) -> bool: done = run( ["git", "rev-parse", "--verify", "--quiet", f"refs/heads/{branch}"], - cwd=repo_root, - env_allowlist=GIT_ENV, - timeout=30, + cwd=repo_root, env_allowlist=GIT_ENV, timeout=30, ) return done.exit_code == 0 def _ensure_excludes(repo_root: Path) -> None: - common = Path(_git(repo_root, "rev-parse", "--path-format=absolute", "--git-common-dir")) + common = Path(_git(repo_root, *_ABSOLUTE_COMMON_DIR)) exclude = common / "info" / "exclude" exclude.parent.mkdir(parents=True, exist_ok=True) exclude = exclude.resolve() existing = exclude.read_text() if exclude.exists() else "" - lines = set(existing.splitlines()) - missing = [e for e in EXCLUDES if e not in lines] + missing = [entry for entry in EXCLUDES if entry not in existing.splitlines()] if missing: sep = "" if not existing or existing.endswith("\n") else "\n" mode = stat.S_IMODE(exclude.stat().st_mode) if exclude.exists() else None @@ -174,8 +172,7 @@ def _resumable_head(repo_root: Path, wt: Path, expected_branch: str) -> str | No if (len(fields) != 3 or fields[2] != f"branch refs/heads/{expected_branch}" or not (wt / ".git").is_file()): return None - common_dir = ("rev-parse", "--path-format=absolute", "--git-common-dir") - if _git(wt, *common_dir) != _git(repo_root, *common_dir) or branch(wt) != expected_branch: + if _git(wt, *_ABSOLUTE_COMMON_DIR) != _git(repo_root, *_ABSOLUTE_COMMON_DIR) or branch(wt) != expected_branch: return None current_head = head(wt) if fields[1] != f"HEAD {current_head}" or is_dirty(wt): @@ -216,7 +213,7 @@ def head(wt: Path) -> str: def is_linked_checkout(wt: Path) -> bool: git_dir = _git(wt, "rev-parse", "--absolute-git-dir") - common_dir = _git(wt, "rev-parse", "--path-format=absolute", "--git-common-dir") + common_dir = _git(wt, *_ABSOLUTE_COMMON_DIR) return git_dir != common_dir diff --git a/tests/test_candidate.py b/tests/test_candidate.py index 1b228c55..c72eb281 100644 --- a/tests/test_candidate.py +++ b/tests/test_candidate.py @@ -105,21 +105,24 @@ def payloads(candidate_event: dict) -> dict[str, object]: def run_attestation( - *, candidate_event: dict | None = None, + *, status_reads: list[dict] | None = None, github_payloads: dict[str, object] | None = None, + github_get=None, + mergify_status=None, source_policy=lambda _number, _source: None, + run=attest_candidate, ): candidate_event = candidate_event or event() reads, values = ( cycle(status_reads or [status(), status()]), github_payloads or payloads(candidate_event), ) - return attest_candidate( + return run( candidate_event, - github_get=lambda path: deepcopy(values[path]), - mergify_status=lambda *_: deepcopy(next(reads)), + github_get=github_get or (lambda path: deepcopy(values[path])), + mergify_status=mergify_status or (lambda *_: deepcopy(next(reads))), source_policy=source_policy, ) @@ -187,10 +190,8 @@ def github_get(path: str): reads = iter([status(), status()]) with pytest.raises(CandidateError, match=diagnostic): - attest_candidate( - candidate_event, github_get=github_get, - mergify_status=lambda *_: deepcopy(next(reads)), source_policy=lambda *_: None, - ) + run_attestation(candidate_event, github_get=github_get, + mergify_status=lambda *_: deepcopy(next(reads))) def test_same_head_still_obeys_source_policy() -> None: @@ -286,8 +287,8 @@ def get(path): return deepcopy(values[path]) return {"object": {"sha": sha}} if (sha := next(reads)) else {} - return run(candidate_event, github_get=get, mergify_status=lambda *_: deepcopy(queue), - source_policy=policy) + return run_attestation(candidate_event, github_get=get, status_reads=[queue], + source_policy=policy, run=run) return attest, git, commit, base, parent, source, candidate_sha @@ -520,7 +521,8 @@ def verify_tree(repo, main_sha, candidate_sha, sources): monkeypatch.setattr(candidate, "_retry_sleep", sleeps.append) monkeypatch.setattr(candidate, "_verify_tree", verify_tree) - assert attest_candidate(candidate_event, github_get=get, mergify_status=lineage, source_policy=policy) == [{"number": 102, "head_sha": source}] + assert run_attestation(candidate_event, github_get=get, mergify_status=lineage, + source_policy=policy) == [{"number": 102, "head_sha": source}] assert seen == {"metadata": [101, 102, 102], "policy": [101, 102], "initial": [102]}[timing] assert candidate_reads == (4 if timing == "metadata" else 3) assert verified == [(main, head, [source])] and sleeps == [2] @@ -545,12 +547,7 @@ def policy(number, source): raise CandidateError("fresh policy rejects drift") with pytest.raises(CandidateError, match="fresh policy rejects drift"): - attest_candidate( - event(), - github_get=get, - mergify_status=lambda *_: status(), - source_policy=policy, - ) + run_attestation(github_get=get, source_policy=policy) assert snapshots == [ ("source 101", False), (value if field == "body" else "source 101", field == "draft"), @@ -598,12 +595,7 @@ def policy(*_): monkeypatch.setattr(candidate, "_retry_sleep", sleeps.append) with pytest.raises((CandidateError, LoopZeroError)) as caught: - attest_candidate( - event(), - github_get=get, - mergify_status=lambda *_: deepcopy(live), - source_policy=policy, - ) + run_attestation(github_get=get, status_reads=[live], source_policy=policy) assert not isinstance(caught.value, CandidateRaceError) and len(attempts) == 1 and sleeps == [] if failure == "policy": assert caught.value is expected and len(source_reads) == 2 @@ -632,12 +624,7 @@ def sleep(seconds): monkeypatch.setattr(candidate, "_retry_clock", lambda: clock[0]) monkeypatch.setattr(candidate, "_retry_sleep", sleep) with pytest.raises(CandidateRaceError, match="membership changed") as caught: - attest_candidate( - event(), - github_get=lambda _: None, - mergify_status=lambda *_: None, - source_policy=lambda *_: None, - ) + run_attestation(github_get=lambda _: None, status_reads=[None]) assert len(attempts) == attempt_count and caught.value is attempts[-1] assert sum(sleeps) <= 4 @@ -673,7 +660,8 @@ def read_status(*_): monkeypatch.setattr(candidate, "_retry_clock", lambda: clock[0]) monkeypatch.setattr(candidate, "_retry_sleep", sleep) def run(): - return attest_candidate(event(), github_get=lambda p: deepcopy(values[p]), mergify_status=read_status, source_policy=lambda n, _: seen.append(n)) + return run_attestation(github_payloads=values, mergify_status=read_status, + source_policy=lambda n, _: seen.append(n)) if stop in {"settled", "changed"}: assert run() == [{"number": 101, "head_sha": "1" * 40}, {"number": 102, "head_sha": "2" * 40}] assert seen == [101, 102] * (2 if stop == "changed" and second else 1) diff --git a/tests/test_cli.py b/tests/test_cli.py index e92db2c2..6eb6edd0 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -2392,14 +2392,14 @@ def test_skipped_required_check_activates_only_on_ready(wt, gh, capsys, head, dr assert all(c["argv"][:2] != ["pr", "ready"] for c in gh.calls) -def test_ready_wait_reports_initial_draft_blocker_once(wt, gh, capsys, monkeypatch, head): +def test_ready_wait_reports_initial_draft_blocker_once(wt, gh, capsys, monkeypatch, head, git_calls): arm_approved_pr_with_check_result(gh, head, wt, "skipped", isDraft=True) arm_check_progress(gh, head, "skipped", "skipped", "pending", "success") gh.respond("pr ready", "") - + git_calls.clear() monkeypatch.setattr(cli, "_sleep", lambda _: None) code, out, err = run(capsys, "ready", "--wait") - + assert sum(call[0] == "show" and call[-1].endswith(":workflow.toml") for call in git_calls) == 1 assert (code, err) == (0, "") assert out.count("receipt accepted:") == 1 assert without_accepted_receipt(out).splitlines() == [ diff --git a/tests/test_config.py b/tests/test_config.py index a877a3db..2ed48a21 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -102,14 +102,10 @@ def test_missing_file(tmp_path): config.load(tmp_path / "nope.toml") -def test_invalid_toml(tmp_path): - with pytest.raises(config.ConfigError, match="invalid TOML"): - config.load(write(tmp_path, "[repo\n")) - - @pytest.mark.parametrize( ("text", "message"), [ + ("[repo\n", "invalid TOML"), ("[checks]\ncommands = []\n", "missing required key repo.name"), ('[repo]\nname = "noslash"\n', 'must look like "owner/name"'), ('[repo]\nname = 3\n', "repo.name must be a str"), @@ -148,6 +144,13 @@ def test_invalid_toml(tmp_path): "checks.limits.memory_mb must be a positive int"), ('[repo]\nname = "o/n"\n[checks]\nlimits = { cpu = 1 }\n', "unknown key\\(s\\) in checks.limits: cpu"), + ('[repo]\nname = "o/n"\n[checks]\ncommands = ["echo ok"]\n' + '[checks.inputs]\n"echo okay" = ["."]\n', r'checks\.inputs\."echo okay".*exact'), + *[ + ('[repo]\nname = "o/n"\n[checks]\nrunner = ["runner"]\ncommands = ["true"]\n' + f"[checks.limits]\n{limit} = 1\n", rf"checks\.limits\.{limit}.*local") + for limit in ("file_mb", "memory_mb") + ], ], ) def test_invalid_content(tmp_path, text, message): @@ -160,17 +163,17 @@ def test_invalid_content(tmp_path, text, message): FORBIDDEN += ["/var/run/docker.sock", "/sys/fs", "/tmp/../run"] -@pytest.mark.parametrize("path", FORBIDDEN) -def test_ro_paths_reject_host_secrets(tmp_path, path): - text = f'[repo]\nname = "o/n"\n[checks]\nro_paths = ["{path}"]\n' - with pytest.raises(config.ConfigError, match="must not expose"): - config.load(write(tmp_path, text)) - - -@pytest.mark.parametrize("path", ["/home/me/.local/bin", "/opt/tool", "/tmp/x"]) -def test_ro_paths_accept_explicit_subpaths(tmp_path, path): - text = f'[repo]\nname = "o/n"\n[checks]\nro_paths = ["{path}"]\n' - assert config.load(write(tmp_path, text)).sandbox_ro == (path,) +@pytest.mark.parametrize("path,allowed", [ + *((path, False) for path in FORBIDDEN), + *((path, True) for path in ("/home/me/.local/bin", "/opt/tool", "/tmp/x")), +]) +def test_ro_path_boundary(tmp_path, path, allowed): + cfg = write(tmp_path, f'[repo]\nname = "o/n"\n[checks]\nro_paths = ["{path}"]\n') + if allowed: + assert config.load(cfg).sandbox_ro == (path,) + else: + with pytest.raises(config.ConfigError, match="must not expose"): + config.load(cfg) def test_check_inputs(tmp_path): @@ -180,24 +183,9 @@ def test_check_inputs(tmp_path): config.load(write(tmp_path, FULL + '\n[checks.inputs]\n"uv run pytest -q" = "src"\n')) -def test_check_inputs_reject_unmatched_command(tmp_path): - text = '[repo]\nname = "o/n"\n[checks]\ncommands = ["echo ok"]\n' - text += '[checks.inputs]\n"echo okay" = ["."]\n' - with pytest.raises(config.ConfigError, match=r'checks\.inputs\."echo okay".*exact'): - config.load(write(tmp_path, text)) - - @pytest.mark.parametrize("strategy", ["", 'merge = "squash"\n', 'merge = "queue"\n']) def test_mergify_queue_rejects_other_strategies(tmp_path, strategy): selected = "queue" if "queue" in strategy else "squash" text = '[repo]\nname = "o/n"\n[delivery]\n' + strategy + 'mergify_queue = "main"\n' with pytest.raises(config.ConfigError, match=rf"delivery\.mergify_queue.*delivery\.merge.*{selected}"): config.load(write(tmp_path, text)) - - -@pytest.mark.parametrize("limit", ["file_mb", "memory_mb"]) -def test_delegated_runner_rejects_local_limit_overrides(tmp_path, limit): - text = '[repo]\nname = "o/n"\n[checks]\nrunner = ["runner"]\ncommands = ["true"]\n' - text += f"[checks.limits]\n{limit} = 1\n" - with pytest.raises(config.ConfigError, match=rf"checks\.limits\.{limit}.*local"): - config.load(write(tmp_path, text)) diff --git a/tests/test_mergify.py b/tests/test_mergify.py index 518c6002..ff3b70e0 100644 --- a/tests/test_mergify.py +++ b/tests/test_mergify.py @@ -13,16 +13,8 @@ from loopzero import mergify -class Response(io.BytesIO): - def __enter__(self): - return self - - def __exit__(self, *_args): - self.close() - - -def response(payload: object) -> Response: - return Response(json.dumps(payload).encode()) +def response(payload: object) -> io.BytesIO: + return io.BytesIO(json.dumps(payload).encode()) def test_membership_uses_bearer_and_validates_queue(monkeypatch): @@ -86,7 +78,7 @@ def queue_api(monkeypatch): {"batches": [], "mode": "serial"} if suffix.startswith("/merge-queue/status") else {"configuration": [{"name": "main", "config": {"allow_inplace_checks": True}}]} )) - def github_config(text, *, default="main", changed=False): + def github_config(text, *, default="main", changed=False, file_overrides=None): reads = 0 def get(path): nonlocal reads @@ -95,7 +87,7 @@ def get(path): assert path == "repos/acme/widgets/contents/.mergify.yml?ref=refs%2Fheads%2Fmain" reads += 1 return {"type": "file", "encoding": "base64", "sha": str(reads if changed else 1)*40, - "content": base64.b64encode(text.encode()).decode()} + "content": base64.b64encode(text.encode()).decode(), **(file_overrides or {})} monkeypatch.setattr(mergify.github, "api_get", get) return github_config @@ -104,13 +96,7 @@ def get(path): ONE_CHECK = SAFE_CONFIG.replace("checks: 3", "checks: 1") # in place unless batches are explicit -@pytest.mark.parametrize("text", [SAFE_CONFIG, ONE_CHECK.replace("main}", "main, batch_size: 8}")]) -def test_configured_accepts_documented_speculation_despite_raw_inplace_default(queue_api, text): - queue_api(text) - assert mergify.configured("acme/widgets", "main", "main") - - -@pytest.mark.parametrize("text", [ +UNSAFE_CONFIGS = [ SAFE_CONFIG.replace("checks: 3", f"checks: {value}") for value in ["1", "0", "-1", "true", '"3"', "null"] ] + [ @@ -120,16 +106,22 @@ def test_configured_accepts_documented_speculation_despite_raw_inplace_default(q SAFE_CONFIG + "merge_queue: {max_parallel_checks: 1}\n", "[]", "!!python/object:object {}", "merge_queue: [", ] + [ONE_CHECK.replace("main}", r) for r in ["main, batch_size: 1}", "main, batch_size: true}", - 'main, batch_size: "8"}', "main, batch_size: null}", "main}, {name: o, batch_size: 8}"]]) -def test_configured_rejects_unsafe_or_ambiguous_canonical_config(queue_api, text): - queue_api(text) - assert not mergify.configured("acme/widgets", "main", "main") - - -@pytest.mark.parametrize("options", [{"default": "other"}, {"changed": True}]) -def test_configured_rejects_wrong_default_branch_or_config_change(queue_api, options): - queue_api(SAFE_CONFIG, **options) - assert not mergify.configured("acme/widgets", "main", "main") + 'main, batch_size: "8"}', "main, batch_size: null}", "main}, {name: o, batch_size: 8}"]] + + +@pytest.mark.parametrize("text,options,accepted", [ + (SAFE_CONFIG, {}, True), + (ONE_CHECK.replace("main}", "main, batch_size: 8}"), {}, True), + *((text, {}, False) for text in UNSAFE_CONFIGS), + (SAFE_CONFIG, {"default": "other"}, False), + (SAFE_CONFIG, {"changed": True}, False), + *((SAFE_CONFIG, {"file_overrides": {key: value}}, False) + for key, value in (("encoding", "none"), ("type", "symlink"), ("sha", None), + ("sha", "z" * 40), ("content", None), ("content", "!"))), +]) +def test_configured_validates_canonical_github_config(queue_api, text, options, accepted): + queue_api(text, **options) + assert mergify.configured("acme/widgets", "main", "main") == accepted def test_configured_still_requires_vendor_queue_identity(queue_api, monkeypatch): @@ -138,20 +130,6 @@ def test_configured_still_requires_vendor_queue_identity(queue_api, monkeypatch) assert not mergify.configured("acme/widgets", "main", "main") -@pytest.mark.parametrize("field,value", [("encoding", "none"), ("type", "symlink"), - ("sha", None), ("sha", "z"*40), ("content", None), ("content", "!")]) -def test_configured_rejects_malformed_github_file(queue_api, monkeypatch, field, value): - queue_api(SAFE_CONFIG) - original = mergify.github.api_get - def malformed(path): - data = original(path) - if "/contents/" in path: - data[field] = value - return data - monkeypatch.setattr(mergify.github, "api_get", malformed) - assert not mergify.configured("acme/widgets", "main", "main") - - def test_legacy_false_does_not_license_single_check_source_updates(queue_api, monkeypatch): queue_api(SAFE_CONFIG.replace("checks: 3", "checks: 1")) monkeypatch.setattr(mergify, "api_get", lambda _repo, suffix: ( diff --git a/tests/test_sandbox.py b/tests/test_sandbox.py index a21e2783..355fc0fb 100644 --- a/tests/test_sandbox.py +++ b/tests/test_sandbox.py @@ -15,6 +15,7 @@ from dataclasses import replace from pathlib import Path from select import select +from threading import Event, current_thread from unittest.mock import Mock import pytest @@ -512,15 +513,32 @@ def _pairs(argv: list[str], flag: str) -> list[tuple[str, str]]: return [(argv[i + 1], argv[i + 2]) for i, a in enumerate(argv) if a == flag] +@pytest.fixture +def heartbeat_log(monkeypatch): + monkeypatch.setattr(sandbox, "HEARTBEAT_INTERVAL", 0.03) + observed, events, reporters = Event(), [], set() + + def status(message): + events.append(message) + if ": running " in message: + reporters.add(current_thread()) + observed.set() + else: + assert reporters and all(not reporter.is_alive() for reporter in reporters) + + def wait(): + assert observed.wait(5), "no running heartbeat" + + return events, reporters, status, wait + + @pytest.mark.parametrize("exit_code", [0, 7]) def test_silent_stage_reports_live_metadata_then_completion( - git_repo, bwrap_log, monkeypatch, exit_code + git_repo, bwrap_log, monkeypatch, heartbeat_log, exit_code ): import re - import threading - monkeypatch.setattr(sandbox, "HEARTBEAT_INTERVAL", 0.03) - observed, events, reporters = threading.Event(), [], set() + events, _, status, wait_for_heartbeat = heartbeat_log monkeypatch.setenv("LZ_KEEP", "credential-value") command = f'echo "$LZ_KEEP"; echo private-stderr >&2; exit {exit_code}' cfg = make_config(checks=(command, "echo next")) @@ -528,17 +546,9 @@ def test_silent_stage_reports_live_metadata_then_completion( def run_stage(config, worktree, prefix, stage_command, timeout): if stage_command == command: - assert observed.wait(5), "no running heartbeat for first stage" + wait_for_heartbeat() return run_one(config, worktree, prefix, stage_command, timeout) - def status(event): - events.append(event) - if "running" in event: - reporters.add(threading.current_thread()) - observed.set() - else: - assert all(not reporter.is_alive() for reporter in reporters) - monkeypatch.setattr(sandbox, "_run_one", run_stage) report = sandbox.run_checks(cfg, git_repo, progress=events.append, status=status) assert report.results[0].exit_code == exit_code @@ -574,23 +584,8 @@ def test_early_failure_reports_actual_exit_without_heartbeat(git_repo, bwrap_log assert not report.ok -def test_timeout_stops_heartbeat_and_retains_failure_tail(git_repo, bwrap_log, monkeypatch): - import threading - - monkeypatch.setattr(sandbox, "HEARTBEAT_INTERVAL", 0.03) - observed, events, reporters = threading.Event(), [], [] - - def status(message): - events.append(message) - if message.startswith("stage 1/2: running"): - reporters.append(threading.current_thread()) - observed.set() - else: - assert reporters and all(not reporter.is_alive() for reporter in reporters) - - def wait_for_heartbeat(): - assert observed.wait(5), "no running heartbeat before timeout" - +def test_timeout_stops_heartbeat_and_retains_failure_tail(git_repo, bwrap_log, monkeypatch, heartbeat_log): + events, _, status, wait_for_heartbeat = heartbeat_log inject_check_timeout(monkeypatch, b"private\n", wait_for_heartbeat) report = sandbox.run_checks( make_config(checks=("echo private", "echo never")), git_repo, @@ -603,22 +598,14 @@ def wait_for_heartbeat(): assert report.results[0].tail == "private\n\n[loopzero] timed out after 0.2s" -def test_cancellation_stops_heartbeat_without_reporting_verdict(git_repo, bwrap_log, monkeypatch): - import threading - monkeypatch.setattr(sandbox, "HEARTBEAT_INTERVAL", 0.03) - observed, events, reporters = threading.Event(), [], [] - - def heartbeat(message): - events.append(message) - reporters.append(threading.current_thread()) - observed.set() - +def test_cancellation_stops_heartbeat_without_reporting_verdict(git_repo, bwrap_log, monkeypatch, heartbeat_log): + events, reporters, status, wait_for_heartbeat = heartbeat_log def cancel(*args): - assert observed.wait(5), "no running heartbeat before cancellation" + wait_for_heartbeat() raise KeyboardInterrupt monkeypatch.setattr(sandbox, "_run_one", cancel) with pytest.raises(KeyboardInterrupt): - sandbox.run_checks(make_config(), git_repo, status=heartbeat) + sandbox.run_checks(make_config(), git_repo, status=status) assert events and all("running" in event for event in events) assert all(not reporter.is_alive() for reporter in reporters) @@ -635,34 +622,28 @@ def test_sigterm_cleans_only_the_cancelled_checks_private_directories( from tests.test_sandbox import _save_report, make_config, sandbox mode = sys.argv[1] -if mode == "creation": - mkdtemp = tempfile.mkdtemp +def interrupt(): + print(mode, flush=True) + signal.raise_signal(signal.SIGTERM) - def create(*args, **kwargs): - path = mkdtemp(*args, **kwargs) - print("creation", flush=True) - signal.raise_signal(signal.SIGTERM) - return path +def interrupt_after(call): + def wrapped(*args, **kwargs): + result = call(*args, **kwargs) + interrupt() + return result + return wrapped - tempfile.mkdtemp = create - -if mode == "removal": +if mode == "creation": + tempfile.mkdtemp = interrupt_after(tempfile.mkdtemp) +elif mode == "removal": rmtree = shutil.rmtree - def remove(path, **kwargs): - print("removal", flush=True) - signal.raise_signal(signal.SIGTERM) + interrupt() rmtree(path, **kwargs) - shutil.rmtree = remove - -if mode == "dispatch": +elif mode == "dispatch": class Callbacks(deque): - def pop(self): - callback = super().pop() - print("dispatch", flush=True) - signal.raise_signal(signal.SIGTERM) - return callback + pop = interrupt_after(deque.pop) class Stack(ExitStack): def __init__(self): @@ -720,6 +701,25 @@ def fetched_base(git_repo): return head +@pytest.fixture +def cache_check(git_repo): + exclude = git_repo / ".git/info/exclude" + with exclude.open("a") as stream: + stream.write("\n.loopzero/\n") + + def cache(config, *, clean=False, verify_reuse=False): + report = sandbox.run_checks(config, git_repo) + assert report.ok + if clean: + assert not report.dirty + _save_report(git_repo, report) + if verify_reuse: + assert sandbox.run_checks(config, git_repo).results[0].reused_from == report.head + return report + + return cache + + @pytest.mark.parametrize('change', ['other', 'input', 'shared', 'command', 'network', 'environment', 'version', 'failed', 'boolean_exit_code', 'dirty_receipt', 'keyless', 'dirty_tree', 'legacy']) @@ -772,14 +772,11 @@ def test_declared_input_reuse(git_repo, bwrap_log, monkeypatch, fetched_base, ch @pytest.mark.parametrize("case", ["typo", "empty", "dirty", "no_base"]) -def test_unmatched_inputs_run_fresh(git_repo, bwrap_log, fetched_base, case): - (git_repo / ".git/info/exclude").write_text(".loopzero/\n") +def test_unmatched_inputs_run_fresh(git_repo, bwrap_log, fetched_base, case, cache_check): command = 'test "$(cat README.md)" = hello' paths = () if case == "empty" else ("ipnut.txt",) config = make_config(checks=(command,), inputs={command: paths}) - first = sandbox.run_checks(config, git_repo) - assert first.ok - _save_report(git_repo, first) + cache_check(config) (git_repo / "README.md").write_text("fail\n") if case != "dirty": git(git_repo, "commit", "-qam", "change actual input") @@ -808,16 +805,12 @@ def timed_out(*args): assert report.ok and report.dirty and report.results[0].command == command -def test_local_check_reuse_tracks_checkout_bytes(git_repo, bwrap_log, fetched_base): - (git_repo / ".git/info/exclude").write_text(".loopzero/\n") +def test_local_check_reuse_tracks_checkout_bytes(git_repo, bwrap_log, fetched_base, cache_check): path = git_repo / "README.md" command = "python3 -c 'from pathlib import Path; exit(13 in Path(\"README.md\").read_bytes())'" config = make_config(checks=(command,), inputs={command: ("README.md",)}) assert path.read_bytes() == b"hello\n" - report = sandbox.run_checks(config, git_repo) - assert report.ok and not report.dirty - _save_report(git_repo, report) - assert sandbox.run_checks(config, git_repo).results[0].reused_from == fetched_base + assert cache_check(config, clean=True, verify_reuse=True).head == fetched_base git(git_repo, "config", "core.autocrlf", "true") path.unlink() @@ -877,15 +870,12 @@ def test_reused_check_preserves_integration_shard_output(git_repo, bwrap_log, fe @pytest.mark.parametrize("error", [errno.E2BIG, errno.ENOENT]) -def test_cache_fingerprint_spawn_error(git_repo, bwrap_log, fetched_base, monkeypatch, error): +def test_cache_fingerprint_spawn_error(git_repo, bwrap_log, fetched_base, monkeypatch, error, cache_check): command = "echo stage ran" config = make_config(checks=(command,), inputs={command: ("README.md",)}) - (git_repo / ".git/info/exclude").write_text(".loopzero/\n") - original = sandbox.run_checks(config, git_repo) - assert original.ok and not original.dirty + original = cache_check(config, clean=True, verify_reuse=True) assert original.results[0].input_key - _save_report(git_repo, original) - assert sandbox.run_checks(config, git_repo).results[0].reused_from == fetched_base + assert original.head == fetched_base run = sandbox._proc.run @@ -912,12 +902,9 @@ def fail_fingerprint(argv, **kwargs): assert saved.get("input_key") is None and saved.get("reused_from") is None -def test_local_checks_run_fresh_without_a_base(git_repo, bwrap_log): - (git_repo / ".git/info/exclude").write_text(".loopzero/\n") +def test_local_checks_run_fresh_without_a_base(git_repo, bwrap_log, cache_check): config = make_config(inputs={"*": (".",)}) - first = sandbox.run_checks(config, git_repo) - assert first.ok - _save_report(git_repo, first) + cache_check(config) second = sandbox.run_checks(config, git_repo) assert second.ok @@ -984,7 +971,7 @@ def test_receipt_settings_distinguish_runner_paths(git_repo, monkeypatch, tmp_pa @pytest.mark.parametrize("change", ["target", "content"]) -def test_runner_upgrade_invalidates_pass(git_repo, fetched_base, tmp_path, change): +def test_runner_upgrade_invalidates_pass(git_repo, fetched_base, tmp_path, change, cache_check): def write_runner(path, exit_code): path.write_text( f"#!{sys.executable}\n" @@ -996,15 +983,12 @@ def write_runner(path, exit_code): ) path.chmod(0o755) - (git_repo / ".git/info/exclude").write_text(".loopzero/\n") runner = tmp_path / "runner" original = tmp_path / "runner-a" write_runner(original, 0) runner.symlink_to(original) config = make_config(check_runner=(str(runner),), inputs={"echo hello": (".",)}) - report = sandbox.run_checks(config, git_repo) - assert report.ok - _save_report(git_repo, report) + report = cache_check(config) assert _current_check_report(git_repo, config, report.head) assert sandbox.run_checks(config, git_repo).results[0].reused_from == report.head diff --git a/tests/test_stage_runner.py b/tests/test_stage_runner.py index 6fe18983..ddc88774 100644 --- a/tests/test_stage_runner.py +++ b/tests/test_stage_runner.py @@ -9,7 +9,7 @@ from loopzero.config import ConfigError, load from .conftest import git -from .test_sandbox import bwrap_log, make_config # noqa: F401 +from .test_sandbox import bwrap_log, fetched_base, make_config # noqa: F401 @pytest.mark.parametrize('base_ref,body,verdict,tails', [ @@ -82,14 +82,18 @@ def test_runner(git_repo, tmp_path, bwrap_log, body, verdict, tails, base_ref): assert receipt.keys() == {'head', 'dirty', 'results', 'settings_sha256'} +FALLBACK_RUNNER = (sys.executable, '-c', ( + 'import json,sys;r=json.load(sys.stdin);r.pop("env");' + 'r.update(exit_code=0,duration_s=0,not_started=True,tail="");print(json.dumps(r))' +)) + + @pytest.mark.parametrize('dirty', [True, False]) -def test_runner_unavailable(git_repo, monkeypatch, dirty): +def test_runner_unavailable(git_repo, monkeypatch, dirty, fetched_base): # noqa: F811 if dirty: (git_repo / 'dirty').write_text('x') - git(git_repo, 'update-ref', 'refs/remotes/origin/main', 'HEAD') monkeypatch.setattr(sandbox.shutil, 'which', lambda name: None) - prefix = (sys.executable, '-c', 'import json,sys;r=json.load(sys.stdin);r.pop("env");r.update(exit_code=0,duration_s=0,not_started=True,tail="");print(json.dumps(r))') - report = sandbox.run_checks(make_config(check_runner=prefix), git_repo) + report = sandbox.run_checks(make_config(check_runner=FALLBACK_RUNNER), git_repo) assert not report.ok and report.dirty is dirty assert ('bwrap binary missing' in report.results[0].tail) is not dirty @@ -144,8 +148,7 @@ def test_runner_preserves_executable_symlink(git_repo, tmp_path, monkeypatch, ba assert report.ok, report.results[0].tail -def test_runner_timeout(git_repo, monkeypatch): - git(git_repo, 'update-ref', 'refs/remotes/origin/main', 'HEAD') +def test_runner_timeout(git_repo, monkeypatch, fetched_base): # noqa: F811 original = sandbox._proc.run def run(argv, **kwargs): if argv[0] == sys.executable: @@ -160,21 +163,17 @@ def run(argv, **kwargs): @pytest.mark.parametrize('change', ['fallback', 'base']) -def test_runner_reuse_binds_execution_context(git_repo, bwrap_log, change): # noqa: F811 +def test_runner_reuse_binds_execution_context(git_repo, bwrap_log, fetched_base, change): # noqa: F811 from dataclasses import replace (git_repo / '.git/info/exclude').write_text('.loopzero/\n') - base = git(git_repo, 'rev-parse', 'HEAD').strip() - git(git_repo, 'update-ref', 'refs/remotes/origin/main', base) command = 'echo stage-ran; exit 7' if change == 'fallback' else 'echo one' cfg = make_config(checks=(command,), inputs={command: ('README.md',)}) - body = ('import json,sys;r=json.load(sys.stdin);r.pop("env");' - 'r.update(exit_code=0,duration_s=0,not_started=True,tail="");print(json.dumps(r))') - runner = (sys.executable, '-c', body) + runner = FALLBACK_RUNNER if change == 'fallback': passing = sandbox.run_checks(replace(cfg, checks=('echo seed',)), git_repo) result = replace(passing.results[0], command=command, - input_key=sandbox._input_key(cfg, git_repo, command, base)) + input_key=sandbox._input_key(cfg, git_repo, command, fetched_base)) _save_report(git_repo, replace(passing, results=(result,))) else: cfg = replace(cfg, check_runner=runner)