diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 2ae035b3..8304086f 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -1706,16 +1706,30 @@ class _AdmissionDeadline(Exception): """The --wait budget expired before a new merge or queue request.""" +def _follow_blocked_mergify( + config: Config, pr: github.PR, readiness: github.Readiness, queue: str, deadline: float | None, +) -> str | None: + hint = _merge_check_hint(config, pr, readiness) + try: + confirmed = (deadline is not None and pr.base_ref == config.base_branch + and mergify.membership(config.repo, pr.number, queue) is not None) + except mergify.MergifyError as exc: + confirmed = False + hint += f"; Mergify membership unverified: {exc}" + if confirmed: + return _wait_for_mergify(config, pr, max(0.0, deadline - time.monotonic()), True) + raise CliError("not ready to request Mergify: " + "; ".join(_readiness_messages(pr, readiness)) + hint) + + def _merge_with_mergify( wt: Path, config: Config, pr: github.PR, readiness: github.Readiness, deadline: float | None, admit_by: float | None = None, ) -> str | None: - """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_messages(pr, readiness)) + hint) + """Request admission after readiness, or observe a live queue entry without writing.""" queue = config.mergify_queue assert queue is not None + if not readiness.ready: + return _follow_blocked_mergify(config, pr, readiness, queue, deadline) requested, confirmed_marker = mergify.markers( config.repo, pr.number, pr.head_sha, queue ) diff --git a/src/loopzero/github.py b/src/loopzero/github.py index ba49032d..a8d56ccb 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -171,24 +171,20 @@ def api_error_diagnostics(): def _included_response(output: str) -> tuple[str | None, dict[str, str], str]: """Split one `gh api --include` response into status, headers and body.""" - head, separator, body = output.partition("\r\n\r\n") - line_separator = "\r\n" - if not separator: - head, separator, body = output.partition("\n\n") - line_separator = "\n" - if not separator: + for line_separator in ("\r\n", "\n"): + head, separator, body = output.partition(line_separator * 2) + if separator: + break + else: return None, {}, output lines = head.split(line_separator) match = _HTTP_STATUS_RE.match(lines[0]) if match is None: return None, {}, output - status = match.group(1) - headers: dict[str, str] = {} - for line in lines[1:]: - name, separator, value = line.partition(":") - if separator: - headers[name.strip().casefold()] = value.strip() - return status, headers, body + headers = {name.strip().casefold(): value.strip() + for name, separator, value in (line.partition(":") for line in lines[1:]) + if separator} + return match.group(1), headers, body def _api_methods(args: tuple[str, ...]) -> list[str]: @@ -806,9 +802,8 @@ def _review_body(result: ReviewResult, unplaced: list[Finding], prefix: str = "" _, span = runners.leading_review_block(prefix) if len(span.encode("utf-8")) > runners.CODEX_HEADER_LIMIT: raise runners.RunnerBadOutput("codex: oversized leading machine block; HOLD") - counts = {s: sum(1 for f in result.findings if f.severity == s) for s in - ("critical", "important", "suggestion")} - summary = ", ".join(f"{n} {s}" for s, n in counts.items()) + severities = [f.severity for f in result.findings] + summary = ", ".join(f"{severities.count(s)} {s}" for s in ("critical", "important", "suggestion")) duration = "unknown" if result.duration_s is None else f"{result.duration_s:.1f}s" settings = "" if settings_layout == "summary": @@ -858,11 +853,9 @@ def _review_transcript(result: ReviewResult, legacy_display: bool) -> str: "Exact raw SHA256: " + hashlib.sha256(result.raw.encode()).hexdigest()) encoded = raw.encode("utf-8") if len(encoded) > 30_000: - raw = encoded[-30_000:].decode("utf-8", errors="ignore") - raw = ( - "[Transcript truncated; showing the last at most 30,000 UTF-8 bytes. " - "Full output remains in the saved local review artifact.]\n" + raw - ) + tail = encoded[-30_000:].decode("utf-8", errors="ignore") + raw = ("[Transcript truncated; showing the last at most 30,000 UTF-8 bytes. " + "Full output remains in the saved local review artifact.]\n" + tail) return f"\n\n
Raw reviewer output\n\n```\n{raw}\n```\n
" diff --git a/src/loopzero/runners.py b/src/loopzero/runners.py index 8a22d2fb..04b8e803 100644 --- a/src/loopzero/runners.py +++ b/src/loopzero/runners.py @@ -934,33 +934,23 @@ def _codex_evidence(result): raise RunnerBadOutput("codex: configured settings/context mismatch") settings["configured"] = configured inspection = _native_inspection(envelope, context) - calls.append( - { - "index": index, - "session": session, - **settings, - "fatal": "present" if codex_fatal_startup(envelope) else "absent", - "inspection": "verified" if inspection else "unknown", - **inspection, - "base": context["base"], - "diff_sha256": context["diff_sha256"], - } - ) + calls.append({ + "index": index, "session": session, **settings, + "fatal": "present" if codex_fatal_startup(envelope) else "absent", + "inspection": "verified" if inspection else "unknown", + **inspection, + "base": context["base"], "diff_sha256": context["diff_sha256"], + }) raw_bytes = result.raw.encode("utf-8") value = { - "version": 1, - "family": "codex", - "repo": common["repo"], - "pr": common["pr"], - "head": result.head, - "kind": result.kind, + "version": 1, "family": "codex", + "repo": common["repo"], "pr": common["pr"], + "head": result.head, "kind": result.kind, "publisher": common["publisher"], "receipt": f".loopzero/review-{result.head[:12]}-{result.kind}.json", "raw_sha256": hashlib.sha256(raw_bytes).hexdigest(), - "raw_bytes": len(raw_bytes), - "complete": True, - "chunk_count": len(calls), - "calls": calls, + "raw_bytes": len(raw_bytes), "complete": True, + "chunk_count": len(calls), "calls": calls, } if not valid_codex_evidence(value): raise RunnerBadOutput("codex: invalid full native evidence") @@ -974,6 +964,7 @@ def codex_evidence(result): raise RunnerBadOutput("codex: invalid complete native result") return _codex_evidence(result) + def _codex_rollout_settings(home: Path, session_id: str) -> dict: """Read only unambiguous native settings for this private session.""" unknown = {"model": None, "effort": None} @@ -999,7 +990,7 @@ def _codex_rollout_settings(home: Path, session_id: str) -> dict: contexts = [record.get("payload") for record in records if record.get("type") == "turn_context"] if not contexts or any(not isinstance(context, dict) for context in contexts): return unknown - claims = [{key: _setting(context.get(key)) for key in unknown} for context in contexts] + claims = [_settings(context) for context in contexts] return claims[0] if all(claims[0].values()) and all(claim == claims[0] for claim in claims) else unknown except (OSError, ValueError, TypeError): return unknown @@ -1020,10 +1011,8 @@ def _codex_provenance( ), None, ) - usage = next( - (event["usage"] for event in reversed(events) if isinstance(event.get("usage"), dict)), - None, - ) + usage = next((event["usage"] for event in reversed(events) + if isinstance(event.get("usage"), dict)), None) session_match = re.search( r"(?:session|thread)(?:\s+id)?\s*[:=]\s*([A-Za-z0-9_-]{6,})", stderr, re.IGNORECASE, @@ -1033,11 +1022,8 @@ def _codex_provenance( re.IGNORECASE, ) session_id = session_id or (session_match.group(1) if session_match else None) - usage = usage or ( - {"total_tokens": int(tokens_match.group(1).replace(",", ""))} - if tokens_match - else None - ) + usage = usage or ({"total_tokens": int(tokens_match.group(1).replace(",", ""))} + if tokens_match else None) if not session_id or not isinstance(usage, dict): raise RunnerBadOutput( "codex: execution output lacks session/token provenance", _tail(stdout + stderr) @@ -1263,6 +1249,12 @@ def review_with( ) +def _review_outcome(results: list[ReviewResult]) -> tuple[tuple[Finding, ...], str]: + findings = tuple(finding for result in results for finding in result.findings) + verdict = "request_changes" if any(r.verdict == "request_changes" for r in results) else "approve" + return findings, verdict + + def merge_reviews(results: list[ReviewResult]) -> ReviewResult: """Merge same-family chunk reviews while retaining every provider envelope/session.""" if not results: @@ -1270,8 +1262,7 @@ def merge_reviews(results: list[ReviewResult]) -> ReviewResult: first = results[0] if any((r.family, r.head, r.kind) != (first.family, first.head, first.kind) for r in results): raise ValueError("chunk reviews do not describe the same review") - findings = tuple(finding for result in results for finding in result.findings) - verdict = "request_changes" if any(r.verdict == "request_changes" for r in results) else "approve" + findings, verdict = _review_outcome(results) envelopes = [json.loads(result.raw) for result in results] if any(codex_fatal_startup(envelope) for envelope in envelopes): raise RunnerBadOutput("codex: fatal Code Mode startup failure") @@ -1292,10 +1283,7 @@ def merge_reviews(results: list[ReviewResult]) -> ReviewResult: provenance["token_usage"] = [result.provenance["token_usage"] for result in results] provenance["cli_versions"] = [result.provenance.get("cli_version") for result in results] return replace( - first, - fallback="", - verdict=verdict, - findings=findings, + first, fallback="", verdict=verdict, findings=findings, raw=json.dumps(envelopes, separators=(",", ":")), model=", ".join(dict.fromkeys(r.model for r in results if r.model)) or None, effort=", ".join(dict.fromkeys(r.effort for r in results if r.effort)) or None, @@ -1434,18 +1422,12 @@ def validate_runner_result(result: ReviewResult) -> bool: return False try: parsed = [ - parse_review( - payload, family=result.family, head=result.head, kind=result.kind, raw=result.raw - ) + parse_review(payload, family=result.family, head=result.head, kind=result.kind, raw=result.raw) for payload in payloads ] except RunnerBadOutput: return False - findings = tuple(finding for item in parsed for finding in item.findings) - verdict = "request_changes" if any( - item.verdict == "request_changes" for item in parsed - ) else "approve" - if result.findings != findings or result.verdict != verdict: + if (result.findings, result.verdict) != _review_outcome(parsed): return False try: if result.family == "codex": diff --git a/tests/test_cli.py b/tests/test_cli.py index aab7989a..ab708699 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -4381,6 +4381,9 @@ def membership(*_): ("head_changed", 1.0), ("timeout", 0.9), ("timeout", 1.0), + ("incompatible_landed", 1.0), + ("incompatible_absent", 1.0), + ("incompatible_unverified", 1.0), ("api_error", 1.0), ("unsafe_config", 1.0), ("config_error", 1.0), @@ -4397,9 +4400,12 @@ def test_mergify_wait_outcomes_preserve_unmerged_work(wt, repo, gh, capsys, monk gh, head, wt, "success", isDraft=False, state="MERGED" if outcome.startswith("already_") else "OPEN", ) + if outcome.startswith("incompatible_"): + receipt = wt / ".loopzero/checks.json" + receipt.write_text(json.dumps({**json.loads(receipt.read_text()), "settings_sha256": "0" * 64})) gh.respond("api -X", "") landed = outcome in { - "merged", "worktree_removed", "merged_head_changed", "already_merged", "already_merged_changed", + "merged", "incompatible_landed", "worktree_removed", "merged_head_changed", "already_merged", "already_merged_changed", } snapshots = [] if not outcome.startswith("already_"): @@ -4430,6 +4436,10 @@ def configured(*_): reads = [] def membership(*_): reads.append(True) + if outcome == "incompatible_absent": + return None + if outcome == "incompatible_unverified": + raise mergify.MergifyError("HTTP 503") if outcome in {"unsafe_pending", "requested_head_changed"} and len(reads) == 1: return None if len(reads) > 1: @@ -4459,7 +4469,11 @@ def remove_worktree_then_poll(*args, **kwargs): assert sum(c["argv"][:2] == PR_LIST_READ for c in gh.calls) == 1 assert sum(c["argv"][:2] == ["api", "graphql"] for c in gh.calls) == 2 assert requests == ([(REPO, 7, head, "main")] if outcome == "requested_head_changed" else []) - if outcome in {"merged", "already_merged", "worktree_removed"}: + if outcome.startswith("incompatible_"): + assert reads == [True] * (2 if landed else 1) + if not landed: + assert "incompatible settings fingerprint" in err + if outcome in {"merged", "incompatible_landed", "already_merged", "worktree_removed"}: assert code == 0 and "e" * 40 in out and not wt.exists(), err if outcome == "worktree_removed": assert "warning: merged but worktree cleanup failed" in err @@ -4470,6 +4484,7 @@ def remove_worktree_then_poll(*args, **kwargs): assert err.index('"Left the queue" comment') < err.index("post `@mergifyio queue`") message = {"ejected": "post `@mergifyio queue` as the whole PR comment (same login), then rerun `loopzero merge --wait`", "head_changed": "head changed", "timeout": "timed out", "api_error": "HTTP 503", + "incompatible_absent": "incompatible settings fingerprint", "incompatible_unverified": "HTTP 503", "unsafe_config": "unsafe or unavailable", "unsafe_pending": "unsafe or unavailable", "config_error": "HTTP 503", "requested_head_changed": "head changed", "merged_head_changed": "head changed", "already_merged_changed": "head changed", "ejection_head_changed": "head changed"}[outcome] assert message in out + err diff --git a/tests/test_github.py b/tests/test_github.py index d92af20d..8310de8e 100644 --- a/tests/test_github.py +++ b/tests/test_github.py @@ -433,6 +433,14 @@ def test_post_review_payload(gh: FakeGh, raw: str, prefix: str, family: str) -> assert all("subject_type" not in c for c in comments) +def test_legacy_transcript_truncates_on_utf8_boundary(): + tail = "x" * 29_999 + result = ReviewResult("claude", HEAD, "primary", "approve", (), "🧪" + tail) + output = github._review_transcript(result, legacy_display=True) + assert "Transcript truncated" in output + assert output.endswith(f"\n{tail}\n```\n") + + @pytest.mark.parametrize("metadata", ["new", "legacy", "malformed"]) def test_publication_qualifies_each_call_from_native_evidence(gh, metadata): arm_review(gh)