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..a29dfa90 100644 --- a/src/loopzero/runners.py +++ b/src/loopzero/runners.py @@ -36,15 +36,10 @@ _CODEX_EFFORT_RE = re.compile(r"^[ \t]*reasoning effort[ \t]*:[ \t]*([^\r\n]+)$", re.IGNORECASE | re.MULTILINE) -_AUTH_PATTERNS = ( - re.compile(r"not logged in", re.IGNORECASE), - re.compile(r"please run /login", re.IGNORECASE), - re.compile(r"please (?:run )?`?codex login`?", re.IGNORECASE), - re.compile(r"invalid api key", re.IGNORECASE), - re.compile(r"authentication[_ ]error", re.IGNORECASE), - re.compile(r"OAuth access token has expired|Failed to authenticate|token expired", re.IGNORECASE), - re.compile(r"\b401\b.*unauthori[sz]ed|unauthori[sz]ed.*\b401\b", re.IGNORECASE), - re.compile(r"login required|not authenticated|missing credentials", re.IGNORECASE), +_AUTH_FAILURE = re.compile( + r"not logged in|please run /login|please (?:run )?`?codex login`?|invalid api key" + r"|authentication[_ ]error|OAuth access token has expired|Failed to authenticate|token expired|login required" + r"|\b401\b.*unauthori[sz]ed|unauthori[sz]ed.*\b401\b|not authenticated|missing credentials", re.IGNORECASE, ) REVIEW_SCHEMA: dict[str, object] = { @@ -104,16 +99,11 @@ class RunnerUsageLimit(RunnerBadOutput): r'reached your [\w .-]*limit|hit your (?:(?:usage|weekly|session) )?limit' r'|usage_limit_(?:reached|exceeded)|usageLimitExceeded', re.IGNORECASE, ) -_TOO_LONG_PATTERNS = ( - re.compile(r"prompt is too long", re.IGNORECASE), - re.compile(r"context_length_exceeded", re.IGNORECASE), - re.compile(r"maximum context length|input_too_large", re.IGNORECASE), # codex: >1 Mi chars +_TOO_LONG = re.compile( + r"prompt is too long|context_length_exceeded|maximum context length|input_too_large", re.IGNORECASE ) -# --------------------------------------------------------------------------- prompt - - def _review_policy(kind: str, *, split: bool) -> str: """Fixed native instructions; only the validated review scope varies.""" if kind not in ("primary", "delta"): @@ -177,29 +167,25 @@ def build_prompt(*, kind: str, head: str, task_text: str, diff: str, return header + "\n" + diff -# --------------------------------------------------------------------------- parsing - - def _tail(text: str) -> str: return text[-TAIL_CHARS:] def _looks_like_auth_failure(text: str) -> bool: - return any(p.search(text) for p in _AUTH_PATTERNS) + return _AUTH_FAILURE.search(text) is not None def _claude_envelope_auth_failure(envelope: object) -> bool: - if not isinstance(envelope, dict): - return False - return envelope.get("api_error_status") in (401, 403) or ( - envelope.get("terminal_reason") == "api_error" - and re.search(r"authenticate|OAuth|expired|401", str(envelope.get("result", "")), - re.IGNORECASE) is not None + return isinstance(envelope, dict) and ( + envelope.get("api_error_status") in (401, 403) + or (envelope.get("terminal_reason") == "api_error" + and re.search(r"authenticate|OAuth|expired|401", str(envelope.get("result", "")), + re.IGNORECASE) is not None) ) def _looks_too_long(text: str) -> bool: - return any(p.search(text) for p in _TOO_LONG_PATTERNS) + return _TOO_LONG.search(text) is not None def _subscription_exhausted(text: str, envelope: object = None) -> bool: @@ -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