diff --git a/src/loopzero/github.py b/src/loopzero/github.py index 115c6179..af011c8a 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -168,24 +168,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]: @@ -796,9 +792,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": @@ -848,11 +843,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_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)