|
| 1 | +"""Automatic code-review orchestration.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import hashlib |
| 6 | +import time |
| 7 | +import uuid |
| 8 | +from collections import Counter |
| 9 | +from dataclasses import replace |
| 10 | +from pathlib import Path |
| 11 | + |
| 12 | +from diff_parser import DiffParser |
| 13 | +from models import Finding |
| 14 | +from models import ReviewReport |
| 15 | +from redaction import redact_text |
| 16 | +from reporting import write_reports |
| 17 | +from rules import RuleEngine |
| 18 | +from sandbox import SandboxRunner |
| 19 | +from storage import SQLiteReviewStore |
| 20 | + |
| 21 | + |
| 22 | +class CodeReviewAgent: |
| 23 | + def __init__( |
| 24 | + self, |
| 25 | + root: str | Path, |
| 26 | + database: str | Path, |
| 27 | + policy: str | Path, |
| 28 | + dry_run: bool = False, |
| 29 | + ): |
| 30 | + self.root = Path(root) |
| 31 | + self.store = SQLiteReviewStore(database) |
| 32 | + self.runner = SandboxRunner(policy, self.root, dry_run=dry_run) |
| 33 | + self.rules = RuleEngine() |
| 34 | + self.confidence_threshold = float(self.runner.policy["confidence_threshold"]) |
| 35 | + |
| 36 | + def review_diff( |
| 37 | + self, |
| 38 | + diff: str, |
| 39 | + output_dir: str | Path, |
| 40 | + commands: list[list[str]] | None = None, |
| 41 | + ) -> ReviewReport: |
| 42 | + started = time.perf_counter() |
| 43 | + task_id = str(uuid.uuid4()) |
| 44 | + clean_diff, _ = redact_text(diff) |
| 45 | + # Rules inspect the in-memory source so secret detectors retain their |
| 46 | + # signal. Only redacted derivatives cross a logging/persistence boundary. |
| 47 | + lines = DiffParser.parse(diff) |
| 48 | + files = sorted({line.file for line in lines}) |
| 49 | + summary = { |
| 50 | + "sha256": hashlib.sha256(diff.encode("utf-8")).hexdigest(), |
| 51 | + "files": files, |
| 52 | + "added_lines": len(lines), |
| 53 | + "redacted": clean_diff != diff, |
| 54 | + } |
| 55 | + self.store.create_task(task_id, summary["sha256"], summary) |
| 56 | + exceptions: Counter[str] = Counter() |
| 57 | + sandbox_runs = [] |
| 58 | + try: |
| 59 | + raw_findings = [self._redact_finding(item) for item in self.rules.scan(lines)] |
| 60 | + findings = [item for item in raw_findings if item.confidence >= self.confidence_threshold] |
| 61 | + warnings = [item for item in raw_findings if item.confidence < self.confidence_threshold] |
| 62 | + for index, command in enumerate(commands or [["python", "-m", "compileall", "-q", "."]], 1): |
| 63 | + run = self.runner.run(command, index) |
| 64 | + sandbox_runs.append(run) |
| 65 | + if run.error_type: |
| 66 | + exceptions[run.error_type] += 1 |
| 67 | + filter_blocks = [ |
| 68 | + {"command": run.command, "decision": run.filter_decision, "reason": run.filter_reason} |
| 69 | + for run in sandbox_runs if run.status == "blocked" |
| 70 | + ] |
| 71 | + severity = Counter(item.severity for item in findings) |
| 72 | + conclusion = "changes_requested" if any( |
| 73 | + item.severity in ("critical", "high") for item in findings |
| 74 | + ) else "needs_human_review" if warnings or filter_blocks else "approve" |
| 75 | + status = "completed_with_errors" if exceptions else "completed" |
| 76 | + monitoring = { |
| 77 | + "total_duration_ms": (time.perf_counter() - started) * 1000, |
| 78 | + "sandbox_duration_ms": sum(run.duration_ms for run in sandbox_runs), |
| 79 | + "tool_call_count": len(sandbox_runs), |
| 80 | + "blocked_count": len(filter_blocks), |
| 81 | + "finding_count": len(findings), |
| 82 | + "warning_count": len(warnings), |
| 83 | + "severity_distribution": dict(severity), |
| 84 | + "exception_type_distribution": dict(exceptions), |
| 85 | + } |
| 86 | + report = ReviewReport( |
| 87 | + task_id=task_id, |
| 88 | + status=status, |
| 89 | + conclusion=conclusion, |
| 90 | + input_summary=summary, |
| 91 | + findings=findings, |
| 92 | + warnings=warnings, |
| 93 | + filter_blocks=filter_blocks, |
| 94 | + sandbox_runs=sandbox_runs, |
| 95 | + monitoring=monitoring, |
| 96 | + ) |
| 97 | + except Exception as exc: |
| 98 | + exceptions[type(exc).__name__] += 1 |
| 99 | + report = ReviewReport( |
| 100 | + task_id=task_id, |
| 101 | + status="failed", |
| 102 | + conclusion="needs_human_review", |
| 103 | + input_summary=summary, |
| 104 | + monitoring={ |
| 105 | + "total_duration_ms": (time.perf_counter() - started) * 1000, |
| 106 | + "sandbox_duration_ms": 0.0, |
| 107 | + "tool_call_count": 0, |
| 108 | + "blocked_count": 0, |
| 109 | + "finding_count": 0, |
| 110 | + "warning_count": 0, |
| 111 | + "severity_distribution": {}, |
| 112 | + "exception_type_distribution": dict(exceptions), |
| 113 | + }, |
| 114 | + ) |
| 115 | + self.store.save_report(report) |
| 116 | + write_reports(report, output_dir) |
| 117 | + return report |
| 118 | + |
| 119 | + def review_file(self, diff_file: str | Path, output_dir: str | Path) -> ReviewReport: |
| 120 | + diff = Path(diff_file).read_text(encoding="utf-8") |
| 121 | + return self.review_diff(diff, output_dir) |
| 122 | + |
| 123 | + def review_repo(self, repo_path: str | Path, output_dir: str | Path) -> ReviewReport: |
| 124 | + diff, _ = DiffParser.from_repo(repo_path) |
| 125 | + return self.review_diff(diff, output_dir) |
| 126 | + |
| 127 | + @staticmethod |
| 128 | + def _redact_finding(finding: Finding) -> Finding: |
| 129 | + evidence, _ = redact_text(finding.evidence) |
| 130 | + title, _ = redact_text(finding.title) |
| 131 | + recommendation, _ = redact_text(finding.recommendation) |
| 132 | + return replace(finding, evidence=evidence, title=title, recommendation=recommendation) |
0 commit comments