From 36aac2b46a2206bc72d0657b6ed73dda4610904a Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:02:52 +0100 Subject: [PATCH 1/3] Redact credentials in reviewer authentication diagnostics Architecture-Review: unchanged; the runner keeps existing credential forwarding and authentication failure behavior and scrubs native diagnostic text. Co-Authored-By: Codex --- src/loopzero/runners.py | 16 +++++++++++++--- tests/test_cli.py | 15 +++++++++++++++ tests/test_runners.py | 6 ++++-- 3 files changed, 32 insertions(+), 5 deletions(-) diff --git a/src/loopzero/runners.py b/src/loopzero/runners.py index 3499b866..74ecd5e8 100644 --- a/src/loopzero/runners.py +++ b/src/loopzero/runners.py @@ -176,6 +176,16 @@ def _tail(text: str) -> str: return text[-TAIL_CHARS:] +def _auth_failure(family: str, diagnostic: str) -> RunnerAuthFailed: + names = CLAUDE_AUTH_ENV if family == "claude" else CODEX_AUTH_ENV + env = _proc.build_env(names) + values = {variant for value in env.values() if value for variant in (value, json.dumps(value)[1:-1])} + patterns = [*map(re.escape, sorted(values, key=len, reverse=True)), r"\bsk-[A-Za-z0-9_-]{8,}", + r"\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+"] + diagnostic = re.sub("|".join(patterns), "[REDACTED]", diagnostic) + return RunnerAuthFailed(f"{family}: CLI is not authenticated\n{_tail(diagnostic)}") + + def _looks_like_auth_failure(text: str) -> bool: return any(p.search(text) for p in _AUTH_PATTERNS) @@ -281,7 +291,7 @@ def _run( with contextlib.suppress(json.JSONDecodeError, ValueError): envelope = _extract_json_object(done.stdout) if _claude_envelope_auth_failure(envelope) or _looks_like_auth_failure(combined): - raise RunnerAuthFailed(f"{family}: CLI is not authenticated\n{_tail(combined)}") + raise _auth_failure(family, combined) if _subscription_exhausted(combined, envelope): raise RunnerUsageLimit(f"{family}: usage limit reached", _tail(combined)) if _looks_too_long(combined): @@ -1149,13 +1159,13 @@ def _review_claude( if not isinstance(envelope, dict): raise RunnerBadOutput("claude: result envelope is not an object", _tail(raw)) if _claude_envelope_auth_failure(envelope): - raise RunnerAuthFailed(f"claude: CLI is not authenticated\n{_tail(raw)}") + raise _auth_failure("claude", raw) if envelope.get("is_error") and _subscription_exhausted(raw, envelope): raise RunnerUsageLimit("claude: usage limit reached", _tail(raw)) if envelope.get("is_error") or envelope.get("subtype", "success") != "success": text = str(envelope.get("result", "")) if _looks_like_auth_failure(text): - raise RunnerAuthFailed(f"claude: CLI is not authenticated\n{_tail(text)}") + raise _auth_failure("claude", text) if _looks_too_long(text) or _looks_too_long(raw): raise RunnerPromptTooLong("claude: prompt is too long", _tail(raw)) raise RunnerBadOutput(f"claude: {envelope.get('subtype', 'error')}", _tail(raw)) diff --git a/tests/test_cli.py b/tests/test_cli.py index 3cd7131b..f5659007 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -2041,6 +2041,21 @@ def test_review_observes_new_codex_version_in_saved_receipt( assert result.provenance["cli_version"] == version +def test_review_redacts_native_authentication_diagnostics(wt, gh, fake_tool, capsys, monkeypatch, head): + arm_empty_primary_review_history(gh, head) + for family, env in (("claude", "ANTHROPIC_API_KEY"), ("codex", "OPENAI_API_KEY")): + monkeypatch.setenv(env, f"opaque-fake-{family}-credential") + fake_tool(family, "if [ \"$1\" = --version ]; then echo 'codex-cli 0.161.0'; exit 0; fi\n" + f'printf "Not logged in with %s (server echoed sk-FakeToken0123)\\n" "${env}" >&2\nexit 1\n') + code, _, err = run(capsys, "review") + assert code == 4 + assert err.count("Not logged in with [REDACTED] (server echoed [REDACTED])") == 2 + assert "opaque-fake-" not in err and "sk-FakeToken0123" not in err + for family, remedy in (("claude", "claude auth login"), ("codex", "codex login")): + assert f"{family}: CLI is not authenticated" in err + assert f"Fix: run `{remedy}`." in err + + @pytest.mark.parametrize("mixed_authors", [False, True]) def test_review_fails_with_three_line_errors_and_remedies_without_spending_budget( wt: Path, gh: FakeGh, capsys, monkeypatch, head, mixed_authors diff --git a/tests/test_runners.py b/tests/test_runners.py index 991d10ab..2c243368 100644 --- a/tests/test_runners.py +++ b/tests/test_runners.py @@ -690,7 +690,7 @@ def test_claude_bad_severity(fake_bin: Path, tmp_path: Path) -> None: CLAUDE_EXPIRED_OAUTH = { "is_error": True, "api_error_status": 401, "terminal_reason": "api_error", - "result": "Failed to authenticate. API Error: 401 OAuth access token has expired. Re-authenticate to continue.", + "result": "Failed to authenticate. API Error: 401 OAuth access token has expired. Re-authenticate to continue. Token sk-ant-FAKE0123.", } @@ -706,8 +706,10 @@ def test_claude_bad_severity(fake_bin: Path, tmp_path: Path) -> None: ]) def test_claude_auth_failure(fake_bin, tmp_path, output, exit_code, diagnostic): _fake_claude(fake_bin, output, exit_code=exit_code) - with pytest.raises(RunnerAuthFailed, match=diagnostic): + with pytest.raises(RunnerAuthFailed, match=diagnostic) as failure: _review("claude", tmp_path) + if output is CLAUDE_EXPIRED_OAUTH: + assert "Token [REDACTED]." in str(failure.value) @pytest.mark.parametrize("exit_code", [0, 1]) From d82dd4afa3df822d0ccaae9215d3ccfa59fcafb1 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:55:38 +0100 Subject: [PATCH 2/3] Merge origin/main and retain hosted test imports Architecture-Review: unchanged; merge recovery keeps the reviewed head checks and the conflict resolution only changes a test reference. Co-Authored-By: Codex --- src/loopzero/cli.py | 2 +- src/loopzero/github.py | 18 ++++++++++++------ tests/test_cli.py | 26 ++++++++++++++++++++++---- tests/test_github.py | 14 ++++++++++---- 4 files changed, 45 insertions(+), 15 deletions(-) diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 2077c223..f2b5f9d7 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -1411,7 +1411,7 @@ def _wait_for_merge(config: Config, pr: github.PR, timeout: float) -> str | None sha = _landed(config, pr, closed) if sha: return sha - if not github.merge_pending(config.repo, pr.number): + if not github.merge_pending(config.repo, pr.number, pr.head_sha): sha = _landed(config, pr, closed) if sha: return sha diff --git a/src/loopzero/github.py b/src/loopzero/github.py index c9a77a48..944c67ef 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -1322,7 +1322,7 @@ def mark_ready(repo: str, number: int) -> None: _QUEUE_QUERY = ( "query($owner:String!,$name:String!,$number:Int!){repository(owner:$owner,name:$name)" - "{pullRequest(number:$number){isInMergeQueue autoMergeRequest{enabledAt}}}}" + "{pullRequest(number:$number){headRefOid isInMergeQueue autoMergeRequest{enabledAt}}}}" ) @@ -1354,7 +1354,7 @@ def merged_sha( raise GhError(argv, "PR closed without a verified merge or invalid merge evidence") -def merge_pending(repo: str, number: int) -> bool: +def merge_pending(repo: str, number: int, head_sha: str) -> bool: """True when GitHub holds the PR for merging: queued, or accepted as an auto-merge request that it moves into the queue shortly after (observed ~1 minute, #180).""" owner, name = repo.split("/", 1) @@ -1373,6 +1373,8 @@ def merge_pending(repo: str, number: int) -> bool: raise MergeFailed(("gh", "api", "graphql"), f"GitHub queue lookup for PR #{number}: queue status could not be verified. " f"Check the PR's queue or merge state before retrying.\n{str(exc)[-300:]}") from exc + if pr.get("headRefOid") != head_sha: + raise MergeFailed(("gh", *argv), "PR head changed or unavailable during queue verification") return queued or bool(auto) @@ -1389,16 +1391,19 @@ def merge(repo: str, number: int, strategy: str, head_sha: str) -> str | None: argv = ( "pr", "merge", str(number), "--repo", repo, *method, "--match-head-commit", head_sha, ) + if strategy == "queue" and merge_pending(repo, number, head_sha): + return None + write_error = None try: _gh(*argv, timeout=300) - except GhError as exc: - raise MergeFailed(exc.command, exc.tail) from exc + except (GhError, ProcTimeout, OSError) as exc: + write_error = exc sha = merged_sha(repo, number, expected_head=head_sha) if sha: return sha queue_error = None try: - if merge_pending(repo, number): + if merge_pending(repo, number, head_sha): return None except MergeFailed as exc: queue_error = exc @@ -1408,7 +1413,8 @@ def merge(repo: str, number: int, strategy: str, head_sha: str) -> str | None: return sha if queue_error: raise queue_error - raise MergeFailed(("gh", *argv), f"PR #{number} neither merged nor queued") + detail = f": {write_error}" if write_error else "" + raise MergeFailed(("gh", *argv), f"PR #{number} neither merged nor queued{detail}") def _remote_branch_head(endpoint: str) -> str | None: diff --git a/tests/test_cli.py b/tests/test_cli.py index 6933ecd3..5a23ba1f 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -3223,6 +3223,19 @@ def test_merge_refuses_when_not_ready(wt: Path, gh: FakeGh, capsys, head) -> Non assert wt.exists() +def lose_native_merge_reply(monkeypatch): + original = github._gh + + def transport(*args, **kwargs): + result = original(*args, **kwargs) + if args[:2] == ("pr", "merge"): + raise github.ProcTimeout("lost native merge reply", "") + return result + + monkeypatch.setattr(github, "_gh", transport) + + +@pytest.mark.parametrize("lost_reply", [False, True]) @pytest.mark.parametrize("branch,changed", [ ("lz/t1", False), ("t3/archive-review-receipts", False), @@ -3231,13 +3244,15 @@ def test_merge_refuses_when_not_ready(wt: Path, gh: FakeGh, capsys, head) -> Non ("lz/t1", True), ]) def test_merge_prints_sha_and_cleans_up( - wt: Path, repo: Path, gh: FakeGh, capsys, changed, head, branch + wt: Path, repo: Path, gh: FakeGh, capsys, changed, head, branch, monkeypatch, lost_reply ) -> None: git(wt, "branch", "-m", branch) arm_approved_ready_pr(gh, head, wt, isDraft=False, branch=branch) gh.respond("pr merge", "") gh.append(f"api repos/{REPO}/pulls/7", merge_json(state='MERGED', head='f' * 40 if changed else head_of(wt), sha='c' * 40)) gh.respond("api -X", "") + if lost_reply: + lose_native_merge_reply(monkeypatch) code, out, err = run(capsys, "merge") out = without_accepted_receipt(out) if changed: @@ -3914,12 +3929,15 @@ def test_merge_of_externally_merged_pr_verifies_sha_and_cleans_up( assert all(c["argv"][:2] != ["pr", "merge"] for c in gh.calls) -def test_merge_queued_prints_and_keeps_worktree(wt: Path, gh: FakeGh, capsys, head) -> None: +@pytest.mark.parametrize("lost_reply", [False, True]) +def test_merge_queued_prints_and_keeps_worktree(wt, gh, capsys, head, monkeypatch, lost_reply): arm_approved_ready_pr(gh, head, wt, isDraft=False) gh.respond("pr merge", "") gh.append(f"api repos/{REPO}/pulls/7", merge_json(state='OPEN', head=head_of(wt), sha=None)) gh.respond("api graphql", threads_json(), - {"data": {"repository": {"pullRequest": {"isInMergeQueue": True}}}}) + {"data": {"repository": {"pullRequest": {"isInMergeQueue": True, "headRefOid": head}}}}) + if lost_reply: + lose_native_merge_reply(monkeypatch) code, out, err = run(capsys, "merge") assert (code, err) == (0, "") assert "queued for merge into main" in out and out.endswith( @@ -4045,7 +4063,7 @@ def test_merge_wait_preserves_reviewed_head_and_cleans_only_landed_work( merge_json(state="MERGED", head=head, sha="e" * 40) if landed else open_pr] gh.append(f"api repos/{REPO}/pulls/7", *snapshots) def queue(value: bool) -> dict: - return {"data": {"repository": {"pullRequest": {"isInMergeQueue": value}}}} + return {"data": {"repository": {"pullRequest": {"isInMergeQueue": value, "headRefOid": head}}}} ejected = outcome in {"ejected", "landed-on-ejection"} gh.respond("api graphql", threads_json(), queue(True), queue(not ejected)) gh.respond("api -X", "") diff --git a/tests/test_github.py b/tests/test_github.py index cbdc0588..2a8d08dd 100644 --- a/tests/test_github.py +++ b/tests/test_github.py @@ -1221,6 +1221,8 @@ def test_merge_success_verifies_rest_landing( def test_merge_command_failure(gh: FakeGh) -> None: gh.fail("pr merge", "head commit mismatch") + gh.respond(f"api repos/{REPO}/pulls/7", merge_json()) + gh.respond("api graphql", _queue_json(False)) with pytest.raises(github.MergeFailed) as info: github.merge(REPO, 7, "rebase", HEAD) assert "--rebase" in info.value.command and "mismatch" in info.value.tail @@ -1239,7 +1241,7 @@ def test_delete_remote_branch_checks_encoded_ref(gh: FakeGh, remote_head: str | def _queue_json(queued: bool) -> dict: - return {"data": {"repository": {"pullRequest": {"isInMergeQueue": queued}}}} + return {"data": {"repository": {"pullRequest": {"isInMergeQueue": queued, "headRefOid": HEAD}}}} @pytest.mark.parametrize("missing", [False, True]) @@ -1262,10 +1264,14 @@ def test_merge_queued_returns_none(gh: FakeGh, strategy, auto) -> None: accepted = _queue_json(not auto) if auto: accepted["data"]["repository"]["pullRequest"]["autoMergeRequest"] = {"enabledAt": "t"} - gh.respond("api graphql", accepted) + gh.respond("api graphql", *([_queue_json(False)] if strategy == "queue" else []), accepted) assert github.merge(REPO, 7, strategy, HEAD) is None - assert ("--squash" in gh.argv(0)) == (strategy == "squash") - assert "--queue" not in gh.argv(0) + if strategy == "queue": + assert github.merge(REPO, 7, strategy, HEAD) is None + writes = [c["argv"] for c in gh.calls if c["argv"][:2] == ["pr", "merge"]] + assert len(writes) == 1 + assert ("--squash" in writes[0]) == (strategy == "squash") + assert "--queue" not in writes[0] def test_merge_landed_between_reads_is_reported_merged(gh: FakeGh) -> None: From 8ece48107a7af613cffef0b1ac523af2b2f3164d Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:19:38 +0100 Subject: [PATCH 3/3] Share runner chunk packing and native file reads Architecture-Review: unchanged; chunk boundaries, native diagnostics, and no-follow snapshot restrictions are preserved. Co-Authored-By: Codex --- src/loopzero/runners.py | 174 +++++++++++++++++----------------------- 1 file changed, 72 insertions(+), 102 deletions(-) diff --git a/src/loopzero/runners.py b/src/loopzero/runners.py index a0bf539e..876b69d0 100644 --- a/src/loopzero/runners.py +++ b/src/loopzero/runners.py @@ -16,7 +16,9 @@ import shutil import stat import sys +from collections.abc import Callable, Iterable, Iterator from dataclasses import replace +from itertools import groupby from pathlib import Path from loopzero import _proc, sandbox @@ -43,16 +45,14 @@ ) REVIEW_SCHEMA: dict[str, object] = { - "type": "object", - "additionalProperties": False, + "type": "object", "additionalProperties": False, "required": ["verdict", "findings"], "properties": { "verdict": {"type": "string", "enum": ["approve", "request_changes"]}, "findings": { "type": "array", "items": { - "type": "object", - "additionalProperties": False, + "type": "object", "additionalProperties": False, "required": ["severity", "path", "line", "title", "body"], "properties": { "severity": {"type": "string", "enum": list(SEVERITIES)}, @@ -464,12 +464,13 @@ def _codex_repository_skill_overrides(cwd: Path) -> list[str]: f"{{path={json.dumps(path, ensure_ascii=False).replace(chr(127), '\\u007f')},enabled=false}}" for path in sorted(paths) ) - size = len(f"skills.config=[{entries}]".encode()) + override = f"skills.config=[{entries}]" + size = len(override.encode()) except (OSError, RuntimeError, UnicodeError) as exc: raise RunnerBadOutput(f"codex: cannot list repository skills to disable: {exc}") from exc if size > CODEX_SKILL_OVERRIDE_LIMIT: raise RunnerBadOutput(f"codex: {len(paths)} repository skills are too many to disable") - return ["-c", f"skills.config=[{entries}]"] if paths else [] + return ["-c", override] if paths else [] def _repository_skill_paths(cwd: Path) -> set[str]: @@ -489,16 +490,13 @@ def _repository_skill_paths(cwd: Path) -> set[str]: if not real.is_dir(): if path.name == "SKILL.md": paths.add(str(real)) - continue - if path in roots: + elif path in roots: pending.append(path / "skills") - continue - if real in seen: - continue - seen.add(real) - with os.scandir(real) as entries: - pending.extend(path / entry.name for entry in entries - if entry.is_symlink() or entry.is_dir() or entry.name == "SKILL.md") + elif real not in seen: + seen.add(real) + with os.scandir(real) as entries: + pending.extend(path / entry.name for entry in entries + if entry.is_symlink() or entry.is_dir() or entry.name == "SKILL.md") return paths @@ -536,9 +534,8 @@ def _settings(value: object) -> dict[str, str | None]: return {key: _setting(fields.get(key)) for key in ("model", "effort")} -def _read_envelopes(raw, loads=json.loads): - decoded = loads(raw) - return decoded if isinstance(decoded, list) else [decoded] +def _read_envelopes(raw: str, loads: Callable[[str], object] = json.loads) -> list[object]: + return decoded if isinstance(decoded := loads(raw), list) else [decoded] def review_settings(result: ReviewResult) -> list[dict[str, dict[str, str | None]]]: @@ -573,9 +570,7 @@ def codex_fatal_startup(envelope: object) -> bool: if not isinstance(envelope, dict) or envelope.get("type") != "codex_exec_result": return False events = envelope.get("events", ()) - if not isinstance(events, (list, tuple)): - return False - for event in events: + for event in events if isinstance(events, (list, tuple)) else (): if not isinstance(event, dict): continue item = event.get("item", {}) @@ -642,24 +637,19 @@ def _valid_codex_evidence(value): } if not isinstance(value, dict) or set(value) != fields: return False - if (type(value["version"]) is not int or value["version"] != 1 - or value["family"] != "codex" - or not isinstance(value["repo"], str) - or len(value["repo"]) > 256 + if ( + type(value["version"]) is not int or value["version"] != 1 or value["family"] != "codex" + or not isinstance(value["repo"], str) or len(value["repo"]) > 256 or not re.fullmatch(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", value["repo"]) - or not _bounded_int(value["pr"]) - or not _hex(value["head"], 40) + or not _bounded_int(value["pr"]) or not _hex(value["head"], 40) or value["kind"] not in {"primary", "delta"} - or not isinstance(value["publisher"], str) - or len(value["publisher"]) > 128 + or not isinstance(value["publisher"], str) or len(value["publisher"]) > 128 or not re.fullmatch(r"[A-Za-z0-9_.-]+(?:\[bot\])?", value["publisher"]) or value["receipt"] != f".loopzero/review-{value['head'][:12]}-{value['kind']}.json" - or not _hex(value["raw_sha256"], 64) - or not _bounded_int(value["raw_bytes"]) - or type(value["complete"]) is not bool - or not _bounded_int(value["chunk_count"]) - or not isinstance(value["calls"], list) - or len(value["calls"]) != value["chunk_count"]): + or not _hex(value["raw_sha256"], 64) or not _bounded_int(value["raw_bytes"]) + or type(value["complete"]) is not bool or not _bounded_int(value["chunk_count"]) + or not isinstance(value["calls"], list) or len(value["calls"]) != value["chunk_count"] + ): return False sessions, ranges = set(), set() for index, call in enumerate(value["calls"], 1): @@ -668,13 +658,13 @@ def _valid_codex_evidence(value): 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"]) or call["index"] != index - or not _identifier(call["session"]) - or call["session"] in sessions + if ( + set(call) != keys or not _bounded_int(call["index"]) or call["index"] != index + or not _identifier(call["session"]) or call["session"] in sessions or call["fatal"] not in {"present", "absent", "unknown"} or call["inspection"] not in {"verified", "unknown"} - or not _hex(call["base"], 40) - or not _hex(call["diff_sha256"], 64)): + or not _hex(call["base"], 40) or not _hex(call["diff_sha256"], 64) + ): return False sessions.add(call["session"]) ranges.add((call["base"], call["diff_sha256"])) @@ -960,10 +950,10 @@ def _codex_rollout_settings(home: Path, session_id: str) -> dict: paths = list((home / ".codex/sessions").glob(f"*/*/*/rollout-*-{session_id}.jsonl")) if len(paths) != 1 or not paths[0].resolve().is_relative_to(home.resolve()): return unknown - snapshot = _codex_final_file(paths[0], max_bytes=8 * 1024 * 1024) - if snapshot["status"] != "complete": + snapshot = _read_codex_file(paths[0], max_bytes=8 * 1024 * 1024) + if snapshot is None: return unknown - records = [json.loads(line) for line in base64.b64decode(snapshot["bytes_base64"]).decode("utf-8").splitlines()] + records = [json.loads(line) for line in snapshot.decode("utf-8").splitlines()] if any(not isinstance(record, dict) for record in records): return unknown metadata = [record.get("payload") for record in records if record.get("type") == "session_meta"] @@ -973,10 +963,8 @@ def _codex_rollout_settings(home: Path, session_id: str) -> dict: version = metadata[0].get("cli_version") if not isinstance(version, str) or not version.strip(): return unknown - 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 = [_settings(context) for context in contexts] + claims = [_settings(record.get("payload")) for record in records + if record.get("type") == "turn_context"] or [unknown] 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 @@ -1077,37 +1065,35 @@ def _review_claude( ) -def _codex_final_file(path: Path, *, max_bytes: int | None = None) -> dict: - """Bound a no-follow snapshot to the initial size of an owned regular file.""" +def _read_codex_file(path: Path, *, max_bytes: int | None = None) -> bytes | None: + """Read an owned regular file without following links. Missing files are empty.""" try: fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK) except FileNotFoundError: - return {"status": "absent"} - except OSError as exc: - return {"status": "unreadable", "error_type": type(exc).__name__} + return b"" + except OSError: + return None data = bytearray() - status, error = "complete", None try: before = os.fstat(fd) if not stat.S_ISREG(before.st_mode) or before.st_uid != os.getuid() or before.st_nlink != 1: - return {"status": "unreadable", "error_type": "NotOwnedRegularFile"} + return None if max_bytes is not None and before.st_size > max_bytes: - return {"status": "unreadable", "error_type": "FileTooLarge"} + return None while len(data) < before.st_size: block = os.read(fd, min(65536, before.st_size - len(data))) if not block: break data.extend(block) after = os.fstat(fd) - if (before.st_size, before.st_mtime_ns) != (after.st_size, after.st_mtime_ns) or len(data) != after.st_size: - status = "partial" - except (OSError, MemoryError) as exc: - status, error = "partial" if data else "unreadable", type(exc).__name__ + if ((before.st_size, before.st_mtime_ns) != (after.st_size, after.st_mtime_ns) + or len(data) != after.st_size): + return None + except (OSError, MemoryError): + return None finally: os.close(fd) - return {"status": status, "error_type": error, "byte_count": len(data), - "sha256": hashlib.sha256(data).hexdigest(), - "bytes_base64": base64.b64encode(data).decode("ascii")} + return bytes(data) def _review_codex( @@ -1149,10 +1135,9 @@ def _review_codex( env_allowlist=(*config.env_allowlist, *CODEX_AUTH_ENV), timeout=timeout, family="codex", ) - final = _codex_final_file(last_file) - if final["status"] not in ("complete", "absent"): + message_bytes = _read_codex_file(last_file) + if message_bytes is None: raise RunnerMalformedOutput("codex: final message file could not be read completely") - message_bytes = base64.b64decode(final.get("bytes_base64", "")) try: message = message_bytes.decode("utf-8") except UnicodeDecodeError as exc: @@ -1183,12 +1168,7 @@ def _review_codex( def review_with( family: str, - *, - cwd: Path, - head: str, - kind: str, - diff: str, - task_text: str, + *, cwd: Path, head: str, kind: str, diff: str, task_text: str, reviewer_ro_paths: tuple[str, ...] = (), timeout: int = 900, model: str | None = None, @@ -1264,17 +1244,17 @@ def split_diff(diff: str, budget: int) -> list[str]: 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)] - chunks: list[str] = [] - current = "" + return _pack_bytes((piece for block in blocks for piece in _split_bytes(block, budget)), budget) or [""] + + +def _pack_bytes(pieces: Iterable[str], budget: int) -> list[str]: + chunks, current = [], "" for piece in pieces: - candidate = current + piece - if current and len(candidate.encode()) > budget: + if current and len((current + piece).encode()) > budget: chunks.append(current) - current = piece - else: - current = candidate - if current or not chunks: + current = "" + current += piece + if current: chunks.append(current) return chunks @@ -1292,17 +1272,16 @@ def _summarize_deleted(block: str) -> str: return f"{header}\n{path}: deleted, {deleted} lines\n" -def _split_bytes(text: str, budget: int) -> list[str]: +def _split_bytes(text: str, budget: int) -> Iterator[str]: if len(text.encode()) <= budget: - return [text] - pieces: list[str] = [] - current = "" - for line in text.splitlines(keepends=True): - encoded = line.encode() - if len(encoded) > budget: - if current: - pieces.append(current) - current = "" + yield text + return + lines = ((line, line.encode()) for line in text.splitlines(keepends=True)) + for oversized, group in groupby(lines, key=lambda item: len(item[1]) > budget): + if not oversized: + yield from _pack_bytes((line for line, _ in group), budget) + continue + for _, encoded in group: start = 0 while start < len(encoded): cut = min(len(encoded), start + budget) @@ -1310,16 +1289,8 @@ def _split_bytes(text: str, budget: int) -> list[str]: cut -= 1 if cut <= start: raise ValueError("diff chunk budget cannot fit one UTF-8 character") - pieces.append(encoded[start:cut].decode()) + yield encoded[start:cut].decode() start = cut - elif current and len((current + line).encode()) > budget: - pieces.append(current) - current = line - else: - current += line - if current: - pieces.append(current) - return pieces def _validated_payloads(family, envelopes, provenance, sessions): @@ -1327,9 +1298,8 @@ def _validated_payloads(family, envelopes, provenance, 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): + if (not all(isinstance(item, dict) for item in usages) + or provenance.get(usage_key) != (usages[0] if len(usages) == 1 else usages)): return None try: if family == "claude" and _valid_claude_envelopes(envelopes, provenance):