"""Constrained, auditable syntax review of one Python source file.""" import argparse import ast from datetime import datetime, timezone import difflib import hashlib import json import os from pathlib import Path import re import signal import subprocess import sys import tempfile import time SHA_RE = re.compile(r"[0-9a-f]{40}|[0-9a-f]{64}", re.ASCII) MAX_BACKEND_BYTES = 1_000_000 TIMEOUT_SECONDS = 120 def _timestamp(): return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z") def backend(source): override = os.environ.get("REVIEWER_BACKEND_COMMAND") if not override: from .llama_adapter import propose return propose(source) command = json.loads(override) if not isinstance(command, list) or not command or not all(type(x) is str and x for x in command): raise ValueError("backend command must be a nonempty JSON string array") with tempfile.TemporaryFile(mode="w+b") as stdout, tempfile.TemporaryFile(mode="w+b") as stderr: process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=stdout, stderr=stderr, start_new_session=True) try: process.communicate(json.dumps({"source": source}).encode(), timeout=TIMEOUT_SECONDS) except subprocess.TimeoutExpired as exc: os.killpg(process.pid, signal.SIGKILL) process.communicate() raise TimeoutError(f"backend exceeded {TIMEOUT_SECONDS} seconds") from exc if stdout.tell() > MAX_BACKEND_BYTES or stderr.tell() > MAX_BACKEND_BYTES: raise ValueError("backend output exceeded size limit") stdout.seek(0) if process.returncode: raise RuntimeError(f"backend exit {process.returncode}") return json.loads(stdout.read().decode("utf-8")) def review(input_path, source_commit, out_dir, propose=backend): output = Path(out_dir) output.mkdir(parents=True, exist_ok=False) started = _timestamp() started_clock = time.monotonic() metadata = dict(source_commit=source_commit, model_id=None, status="error", summary="", diff="", input_tokens=None, output_tokens=None, schema_version=1, mode="fixture" if os.environ.get("REVIEWER_BACKEND_COMMAND") else "live", started_at=started, finished_at=None, elapsed_seconds=None) code = 3 try: if type(source_commit) is not str or SHA_RE.fullmatch(source_commit) is None: raise ValueError("full lowercase source commit SHA required") original = Path(input_path).read_bytes() source = original.decode("utf-8") metadata["input_sha256"] = hashlib.sha256(original).hexdigest() try: ast.parse(source) except SyntaxError: response = propose(source) if not isinstance(response, dict): raise ValueError("backend response must be a JSON object") model_id = response.get("model_id") if type(model_id) is not str or not model_id.strip(): raise ValueError("backend model_id required") metadata["model_id"] = model_id for key in ("input_tokens", "output_tokens"): count = response.get(key) if count is not None and (type(count) is not int or count < 0): raise ValueError(f"{key} must be a nonnegative integer or null") metadata[key] = count if "model_revision" in response: metadata["model_revision"] = response["model_revision"] raw = response.get("raw_response") if raw is not None: if type(raw) is not str or len(raw.encode("utf-8")) > MAX_BACKEND_BYTES: raise ValueError("raw_response must be bounded text") (output / "raw_response.txt").write_text(raw, encoding="utf-8") metadata["raw_response_file"] = "raw_response.txt" runtime_response = response.get("runtime_response") if runtime_response is not None: encoded = json.dumps(runtime_response, indent=2).encode("utf-8") if len(encoded) > MAX_BACKEND_BYTES: raise ValueError("runtime_response exceeded size limit") (output / "runtime_response.json").write_bytes(encoded + b"\n") metadata["runtime_response_file"] = "runtime_response.json" candidate = response.get("candidate") if type(candidate) is not str: raise ValueError("backend candidate must be text") expected = {"print(\"hello\"": "print(\"hello\")", "print(\"hello\"\n": "print(\"hello\")\n"} if source not in expected or candidate != expected[source]: metadata.update(status="rejected", summary="Proposal exceeds the permitted closing-parenthesis repair") code = 2 else: ast.parse(candidate) metadata.update(status="corrected", summary="Added the missing closing parenthesis", diff="".join(difflib.unified_diff(source.splitlines(keepends=True), candidate.splitlines(keepends=True), fromfile="original.py", tofile="reviewed.py"))) code = 0 else: candidate = source metadata.update(status="unchanged", summary="Input parses; inference bypassed", mode="bypass") code = 0 if code == 0: (output / "reviewed.py").write_bytes(original if metadata["status"] == "unchanged" else candidate.encode("utf-8")) except Exception as exc: (output / "reviewed.py").unlink(missing_ok=True) metadata.update(status="error", summary=f"{type(exc).__name__}: review could not complete", diff="", diagnostic=f"{type(exc).__name__}: {str(exc)[:240]}") code = 3 metadata["finished_at"] = _timestamp() metadata["elapsed_seconds"] = round(time.monotonic() - started_clock, 6) (output / "review.json").write_text(json.dumps(metadata, indent=2) + "\n", encoding="utf-8") return code def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--input", required=True) parser.add_argument("--source-commit", required=True) parser.add_argument("--out-dir", required=True) args = parser.parse_args(argv) try: return review(args.input, args.source_commit, args.out_dir) except OSError as exc: print(f"review output unavailable: {type(exc).__name__}", file=sys.stderr) return 3 if __name__ == "__main__": raise SystemExit(main())