From a3fbeb1f07a4415b672ce6fcf2960eef43416064 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:23:12 +0100 Subject: [PATCH 1/5] Explain how to resolve terminal required-check failures Architecture-Review: unchanged; Only refusal rendering changes, with the recorded readiness reasons left intact. Co-Authored-By: Codex --- src/loopzero/cli.py | 17 ++++++++++++++--- tests/test_cli.py | 18 +++++++++--------- 2 files changed, 23 insertions(+), 12 deletions(-) diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 48a64159..e7ee2dc6 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -1207,7 +1207,7 @@ def cmd_ready(args: argparse.Namespace) -> int: return 3 pr, readiness, kicked = waited assert readiness is not None - for reason in readiness.reasons: + for reason in _readiness_messages(pr, readiness): print(f"not ready: {reason}") if not readiness.ready: if args.wait is None and _pending_checks(config, pr, readiness): @@ -1248,6 +1248,17 @@ def _pending_checks( return reasons if reasons and all(r in waitable for r in reasons) else () +def _readiness_messages(pr: github.PR, readiness: github.Readiness) -> Iterator[str]: + for reason in readiness.reasons: + check, separator, conclusion = reason.rpartition("' is ") + if (separator and check.startswith("required check '") and conclusion not in {"pending", "skipped"} + and reason not in readiness.waitable_failures): + yield (f"{reason}. Inspect {pr.url}/checks. Fix reproducible failures before retrying. " + "Rerun the failed job only for a transient failure. Once green, run `loopzero ready --wait`.") + else: + yield reason + + def _merge_check_hint(config: Config, pr: github.PR, readiness: github.Readiness) -> str: if _pending_checks(config, pr, readiness): return "; next: loopzero merge --wait" @@ -1531,7 +1542,7 @@ def _merge_with_mergify( """Request Mergify after readiness verifies the source gates and queue configuration.""" if not readiness.ready: hint = _merge_check_hint(config, pr, readiness) - raise CliError("not ready to request Mergify: " + "; ".join(readiness.reasons) + hint) + raise CliError("not ready to request Mergify: " + "; ".join(_readiness_messages(pr, readiness)) + hint) queue = config.mergify_queue assert queue is not None requested, confirmed_marker = mergify.markers( @@ -1612,7 +1623,7 @@ def cmd_merge(args: argparse.Namespace) -> int: else: if not readiness.ready: hint = _merge_check_hint(config, pr, readiness) - raise CliError("not ready to merge: " + "; ".join(readiness.reasons) + hint) + raise CliError("not ready to merge: " + "; ".join(_readiness_messages(pr, readiness)) + hint) if admit_by is not None and time.monotonic() > admit_by: print(f"timed out before merging PR #{pr.number}") return 3 diff --git a/tests/test_cli.py b/tests/test_cli.py index c09d043c..de4bf011 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -49,6 +49,7 @@ REPO = "acme/widgets" URL = f"https://github.com/{REPO}/pull/7" +FAILED_CHECK_HINT = f". Inspect {URL}/checks. Fix reproducible failures before retrying. Rerun the failed job only for a transient failure. Once green, run `loopzero ready --wait`." MERGIFY_QUEUE_FIXTURE = json.loads((Path(__file__).with_name("fixtures") / "mergify-queue.json").read_text()) BRANCH_READ = branch_head_key().split() PR_LIST_READ = pr_list_key().split() @@ -2345,7 +2346,7 @@ def test_ready_not_ready_lists_reasons(wt: Path, gh: FakeGh, capsys, head) -> No assert code == 1 assert without_accepted_receipt(out).splitlines() == [ "not ready: no review recorded for the current head", - "not ready: required check 'checks' is failure", + f"not ready: required check 'checks' is failure{FAILED_CHECK_HINT}", ] assert all(c["argv"][:2] != ["pr", "ready"] for c in gh.calls) assert not any("actions/runs" in " ".join(c["argv"]) for c in gh.calls) @@ -2369,9 +2370,8 @@ def test_ready_uses_base_required_ci_when_worktree_empties_it( code, out, err = run(capsys, "ready") - out = without_accepted_receipt(out) assert (code, err) == (1, "") - assert out == "not ready: required check 'checks' is failure\n" + assert without_accepted_receipt(out) == f"not ready: required check 'checks' is failure{FAILED_CHECK_HINT}\n" def test_pending_required_check_names_the_wait(wt: Path, gh: FakeGh, capsys, head) -> None: @@ -2687,7 +2687,7 @@ def sleep(seconds): assert (code, err) == (expected, "") assert out.endswith({ - 0: f"ready: {URL}\n", 1: "not ready: required check 'checks' is failure\n", + 0: f"ready: {URL}\n", 1: f"not ready: required check 'checks' is failure{FAILED_CHECK_HINT}\n", 3: f"timed out waiting for required checks on {head[:12]}\n", }[expected]) @@ -2724,7 +2724,7 @@ def sleep(seconds: float) -> None: assert "timed out waiting for required checks" in out else: assert out.endswith(f"ready: {URL}\n" if expected == 0 else - "not ready: required check 'checks' is failure\n") + f"not ready: required check 'checks' is failure{FAILED_CHECK_HINT}\n") @pytest.mark.usefixtures("replay_gh") @@ -2772,7 +2772,7 @@ def advance(seconds): assert sleeps == ([30.0, 5.0, 5.0] if replacement == "pending" else [30.0, 5.0] if initial_pending else [30.0]) assert out.endswith(f"ready: {URL}\n" if expected == 0 else - "not ready: required check 'checks' is failure\n" if expected == 1 else + f"not ready: required check 'checks' is failure{FAILED_CHECK_HINT}\n" if expected == 1 else f"timed out waiting for required checks on {head[:12]}\n") assert sum(c["argv"][:2] == ["pr", "ready"] for c in gh.calls) == 1 @@ -2971,7 +2971,7 @@ def advance(seconds): ) assert (code, err, bool(sleeps)) == (expected, "", waited) assert out.endswith(f"ready: {URL}\n" if expected == 0 else - f"not ready: required check '{name}' is failure\n") + f"not ready: required check '{name}' is failure{FAILED_CHECK_HINT}\n") assert (f"waiting: required check '{name}' is failure" in out) == waited assert out.count("predates the review; awaiting refresh") == int( waited and (age < 0 or age >= 120) and not pending @@ -3256,14 +3256,14 @@ def test_ready_respects_latest_review_state(wt: Path, gh: FakeGh, capsys, state, def test_merge_refuses_when_not_ready(wt: Path, gh: FakeGh, capsys, head) -> None: arm_pr(gh, head, isDraft=False) gh.respond(reviews_key(), [rev(head, "primary")]) - arm_readiness(gh, head, wt, threads=( + arm_readiness(gh, head, wt, conclusion="failure", threads=( {"isResolved": False, "isOutdated": False, "path": "feature.py", "line": 1, "comments": {"nodes": [{"body": f"" "\n**critical: Bad**"}]}},)) code, out, err = run(capsys, "merge") out = without_accepted_receipt(out) assert code == 1 and out == "" - assert "not ready to merge: open critical finding at feature.py:1: Bad" in err + assert f"not ready to merge: open critical finding at feature.py:1: Bad; required check 'checks' is failure{FAILED_CHECK_HINT}" in err assert wt.exists() From 677c87b4c5592104dccf841e97124c3eccc5ebe1 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:25:09 +0100 Subject: [PATCH 2/5] Keep multi-blocker assertions compatible with the review-budget change Co-Authored-By: Codex --- tests/test_cli.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/test_cli.py b/tests/test_cli.py index afb1192c..a9e2c09d 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -2320,10 +2320,11 @@ def test_ready_not_ready_lists_reasons(wt: Path, gh: FakeGh, capsys, head) -> No "name": "checks", "status": "completed", "conclusion": "failure", "check_suite": {"id": 10}}]) code, out, _ = run(capsys, "ready") + out = out.replace(FAILED_CHECK_HINT, "") assert code == 1 assert without_accepted_receipt(out).splitlines() == [ "not ready: no review recorded for the current head", - f"not ready: required check 'checks' is failure{FAILED_CHECK_HINT}", + "not ready: required check 'checks' is failure", ] assert all(c["argv"][:2] != ["pr", "ready"] for c in gh.calls) assert not any("actions/runs" in " ".join(c["argv"]) for c in gh.calls) @@ -2342,8 +2343,7 @@ def test_ready_explains_trusted_policy_blocker(wt, gh, capsys, head, retargeted, code, out, err = run(capsys, "ready") - assert (code, err) == (1, "") - assert without_accepted_receipt(out) == f"not ready: {reason}\n" + assert (code, err, without_accepted_receipt(out)) == (1, "", f"not ready: {reason}\n") def test_pending_required_check_names_the_wait(wt: Path, gh: FakeGh, capsys, head) -> None: From e00eec6fc4b823fed911b0294beb590f60fc3659 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:26:09 +0100 Subject: [PATCH 3/5] Deduplicate review and check internals Architecture-Review: unchanged; existing subprocess, sandbox and candidate checks preserve their interfaces, trust boundaries and receipt formats. Co-Authored-By: Codex --- src/loopzero/candidate.py | 148 +++++---------- src/loopzero/runners.py | 383 +++++++++++++++----------------------- src/loopzero/sandbox.py | 22 +-- src/loopzero/worktree.py | 21 +-- 4 files changed, 212 insertions(+), 362 deletions(-) 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/runners.py b/src/loopzero/runners.py index 1fe9390a..2f0ea25c 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" + r"|\b401\b.*unauthori[sz]ed|login required|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: @@ -325,18 +311,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) @@ -433,36 +421,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: @@ -475,12 +464,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}" @@ -530,6 +515,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: @@ -547,22 +537,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 @@ -626,9 +610,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): @@ -638,19 +620,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 @@ -678,22 +649,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"]) @@ -708,26 +668,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 @@ -741,6 +698,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: @@ -758,7 +719,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 @@ -815,25 +776,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) @@ -847,20 +805,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 {} @@ -882,20 +834,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 ( @@ -912,12 +852,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", ) ) ): @@ -990,6 +926,7 @@ def _codex_evidence(result): "diff_sha256": context["diff_sha256"], } ) + raw_bytes = result.raw.encode("utf-8") value = { "version": 1, "family": "codex", @@ -999,8 +936,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, @@ -1109,9 +1046,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, @@ -1144,9 +1078,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: @@ -1351,18 +1284,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=(",", ":")), @@ -1377,10 +1307,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)] @@ -1436,6 +1363,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 @@ -1463,46 +1423,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 = [ @@ -1519,17 +1441,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() @@ -1547,12 +1466,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 7409f050..0aac5688 100644 --- a/src/loopzero/sandbox.py +++ b/src/loopzero/sandbox.py @@ -489,17 +489,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") @@ -510,12 +508,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 From 4c95f3b58b27379e449d7fcf5407823d2d756e22 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:30:26 +0100 Subject: [PATCH 4/5] Preserve both orderings of authentication errors Architecture-Review: unchanged; the original provider authentication diagnostics remain intact. Co-Authored-By: Codex --- src/loopzero/runners.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/loopzero/runners.py b/src/loopzero/runners.py index 2f0ea25c..a29dfa90 100644 --- a/src/loopzero/runners.py +++ b/src/loopzero/runners.py @@ -38,8 +38,8 @@ _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" - r"|\b401\b.*unauthori[sz]ed|login required|not authenticated|missing credentials", re.IGNORECASE, + 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] = { From f0085ec293c21045e996fe4aa63a368e30149e31 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:35:18 +0100 Subject: [PATCH 5/5] Reuse immutable trusted policy between source-wait observations Co-Authored-By: Codex --- docs/ARCHITECTURE.md | 2 ++ src/loopzero/cli.py | 18 +++++++++++------- src/loopzero/config.py | 35 +++++++++++++++++++++++++++++------ tests/test_cli.py | 6 +++--- 4 files changed, 45 insertions(+), 16 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index c474e6e7..277c4f48 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -114,6 +114,8 @@ The [CLI](../src/loopzero/cli.py) implements the contract's 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/cli.py b/src/loopzero/cli.py index 48a64159..642cc265 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -104,14 +104,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( @@ -1313,17 +1315,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") @@ -1341,13 +1344,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/tests/test_cli.py b/tests/test_cli.py index b5536583..da988397 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -2391,14 +2391,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() == [