Spaces:
Running
Running
soumyadeep maji commited on
Commit Β·
47d2384
0
Parent(s):
Initial commit: OpenCodeReview with Gradio web UI
Browse files- .dockerignore +35 -0
- .gitignore +5 -0
- Dockerfile +92 -0
- app.py +436 -0
- auth.py +353 -0
- config.py +206 -0
- docker-compose.yml +50 -0
- docker-entrypoint.sh +22 -0
- eval_data/eval_results.json +16 -0
- eval_data/evaluate.py +481 -0
- eval_data/fetcher.py +287 -0
- eval_data/prs.jsonl +1 -0
- github_client.py +135 -0
- graph.py +98 -0
- main.py +270 -0
- nodes/__init__.py +23 -0
- nodes/aggregator.py +283 -0
- nodes/correctness_reviewer.py +195 -0
- nodes/executor.py +294 -0
- nodes/human_approval.py +91 -0
- nodes/ingestion.py +231 -0
- nodes/passthrough.py +24 -0
- nodes/post_results.py +153 -0
- nodes/retrieval.py +455 -0
- nodes/security_reviewer.py +152 -0
- nodes/test_coverage_reviewer.py +156 -0
- nodes__init__.py +0 -0
- requirements.txt +10 -0
- state.py +84 -0
.dockerignore
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# --- Python ---
|
| 2 |
+
__pycache__/
|
| 3 |
+
*.pyc
|
| 4 |
+
*.pyo
|
| 5 |
+
*.pyd
|
| 6 |
+
.venv/
|
| 7 |
+
venv/
|
| 8 |
+
|
| 9 |
+
# --- Git ---
|
| 10 |
+
.git/
|
| 11 |
+
.gitignore
|
| 12 |
+
|
| 13 |
+
# --- IDE ---
|
| 14 |
+
.idea/
|
| 15 |
+
.vscode/
|
| 16 |
+
*.swp
|
| 17 |
+
*.swo
|
| 18 |
+
|
| 19 |
+
# --- OS ---
|
| 20 |
+
.DS_Store
|
| 21 |
+
Thumbs.db
|
| 22 |
+
|
| 23 |
+
# --- Project data ---
|
| 24 |
+
*.db
|
| 25 |
+
eval_data/prs.jsonl
|
| 26 |
+
eval_data/eval_results.json
|
| 27 |
+
|
| 28 |
+
# --- Docker ---
|
| 29 |
+
Dockerfile
|
| 30 |
+
docker-compose.yml
|
| 31 |
+
.dockerignore
|
| 32 |
+
|
| 33 |
+
# --- Env ---
|
| 34 |
+
.env
|
| 35 |
+
.env.*
|
.gitignore
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.db
|
| 2 |
+
__pycache__/
|
| 3 |
+
*.pyc
|
| 4 |
+
.env
|
| 5 |
+
.venv/
|
Dockerfile
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# =============================================================================
|
| 2 |
+
# OpenCodeReview β Dockerfile
|
| 3 |
+
# =============================================================================
|
| 4 |
+
# Multi-stage build:
|
| 5 |
+
# 1. builder β installs all Python dependencies
|
| 6 |
+
# 2. runtime β minimal image with just the app + deps
|
| 7 |
+
#
|
| 8 |
+
# Usage
|
| 9 |
+
# -----
|
| 10 |
+
# docker build -t opencodereview .
|
| 11 |
+
# docker run --rm opencodereview review --smoke
|
| 12 |
+
# docker run --rm -e GROQ_API_KEY=gsk_... -e GITHUB_TOKEN=ghp_... \
|
| 13 |
+
# opencodereview review --repo org/repo --pr 42
|
| 14 |
+
#
|
| 15 |
+
# To include sentence-transformers (needed for vector-store retrieval):
|
| 16 |
+
# docker build --target runtime-full -t opencodereview:full .
|
| 17 |
+
#
|
| 18 |
+
# Environment variables
|
| 19 |
+
# ---------------------
|
| 20 |
+
# GROQ_API_KEY Required for AI reviewers (correctness, security, etc.)
|
| 21 |
+
# GITHUB_TOKEN Required for fetching PRs and posting comments
|
| 22 |
+
# =============================================================================
|
| 23 |
+
|
| 24 |
+
# -- Stage 1: Builder (core + optional deps, except heavy ML) -----------------
|
| 25 |
+
FROM python:3.12-slim AS builder
|
| 26 |
+
|
| 27 |
+
ENV PYTHONDONTWRITEBYTECODE=1 \
|
| 28 |
+
PYTHONUNBUFFERED=1
|
| 29 |
+
|
| 30 |
+
WORKDIR /build
|
| 31 |
+
|
| 32 |
+
# Install system build deps needed by chromadb
|
| 33 |
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 34 |
+
gcc \
|
| 35 |
+
g++ \
|
| 36 |
+
build-essential \
|
| 37 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 38 |
+
|
| 39 |
+
# Core dependencies
|
| 40 |
+
COPY requirements.txt .
|
| 41 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 42 |
+
|
| 43 |
+
# Optional dependencies (chromadb for vector store, langchain-groq for LLM)
|
| 44 |
+
RUN pip install --no-cache-dir \
|
| 45 |
+
chromadb \
|
| 46 |
+
langchain-groq
|
| 47 |
+
|
| 48 |
+
# -- Stage 2: Runtime (default) -----------------------------------------------
|
| 49 |
+
FROM python:3.12-slim AS runtime
|
| 50 |
+
|
| 51 |
+
ENV PYTHONDONTWRITEBYTECODE=1 \
|
| 52 |
+
PYTHONUNBUFFERED=1
|
| 53 |
+
|
| 54 |
+
WORKDIR /app
|
| 55 |
+
|
| 56 |
+
# chromadb/onnx needs libgomp at runtime
|
| 57 |
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 58 |
+
libgomp1 \
|
| 59 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 60 |
+
|
| 61 |
+
# Copy Python packages from builder
|
| 62 |
+
COPY --from=builder /usr/local/lib/python3.12/site-packages /usr/local/lib/python3.12/site-packages
|
| 63 |
+
COPY --from=builder /usr/local/bin /usr/local/bin
|
| 64 |
+
|
| 65 |
+
# Copy application code
|
| 66 |
+
COPY . .
|
| 67 |
+
COPY docker-entrypoint.sh /docker-entrypoint.sh
|
| 68 |
+
|
| 69 |
+
# Non-root user
|
| 70 |
+
RUN useradd -m -u 1000 appuser && chown -R appuser:appuser /app \
|
| 71 |
+
&& chmod +x /docker-entrypoint.sh \
|
| 72 |
+
&& mkdir -p /tmp/opencodereview_vectors \
|
| 73 |
+
&& chown -R appuser:appuser /tmp/opencodereview_vectors
|
| 74 |
+
|
| 75 |
+
# The entrypoint runs as root to fix volume permissions, then drops to appuser.
|
| 76 |
+
# Default: run the Gradio web UI on port 7860 (HF Spaces expects this).
|
| 77 |
+
# Override CMD for CLI usage:
|
| 78 |
+
# docker run --rm opencodereview python -m main review --smoke
|
| 79 |
+
ENTRYPOINT ["/docker-entrypoint.sh"]
|
| 80 |
+
CMD ["python", "app.py"]
|
| 81 |
+
|
| 82 |
+
# -- Stage 3: Full runtime (includes sentence-transformers for embeddings) -----
|
| 83 |
+
# Build with: docker build --target runtime-full -t opencodereview:full .
|
| 84 |
+
FROM runtime AS runtime-full
|
| 85 |
+
|
| 86 |
+
USER root
|
| 87 |
+
RUN pip install --no-cache-dir sentence-transformers
|
| 88 |
+
# Note: No USER appuser here β ENTRYPOINT (inherited from runtime) handles privilege dropping
|
| 89 |
+
|
| 90 |
+
# Note: sentence-transformers pulls in PyTorch (~800 MB), making the image
|
| 91 |
+
# significantly larger. Only use this target when you need the retrieval node
|
| 92 |
+
# to build vector indexes from scratch.
|
app.py
ADDED
|
@@ -0,0 +1,436 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""OpenCodeReview β Gradio Web UI for Hugging Face Spaces.
|
| 3 |
+
|
| 4 |
+
Run locally:
|
| 5 |
+
python app.py
|
| 6 |
+
|
| 7 |
+
On Hugging Face Spaces:
|
| 8 |
+
The Dockerfile now defaults to running this module.
|
| 9 |
+
Set GROQ_API_KEY (and optionally GITHUB_TOKEN) as Space secrets.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import json
|
| 15 |
+
import logging
|
| 16 |
+
import os
|
| 17 |
+
import uuid
|
| 18 |
+
|
| 19 |
+
import gradio as gr
|
| 20 |
+
from langgraph.types import Command
|
| 21 |
+
|
| 22 |
+
from graph import build_graph
|
| 23 |
+
from main import _cleanup_db, SYNTHETIC_STATE
|
| 24 |
+
from state import Verdict
|
| 25 |
+
|
| 26 |
+
logging.basicConfig(
|
| 27 |
+
level=logging.INFO,
|
| 28 |
+
format="%(asctime)s [%(levelname)s] %(name)s β %(message)s",
|
| 29 |
+
)
|
| 30 |
+
logger = logging.getLogger(__name__)
|
| 31 |
+
|
| 32 |
+
DB_PATH = "checkpoints.db"
|
| 33 |
+
|
| 34 |
+
SEVERITY_COLORS = {
|
| 35 |
+
"critical": "#dc2626",
|
| 36 |
+
"high": "#ea580c",
|
| 37 |
+
"medium": "#ca8a04",
|
| 38 |
+
"low": "#16a34a",
|
| 39 |
+
"info": "#2563eb",
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
RECOMMENDATION_ICONS = {
|
| 43 |
+
"approve": "β
",
|
| 44 |
+
"request_changes": "π",
|
| 45 |
+
"block": "π«",
|
| 46 |
+
"comment": "π¬",
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
# βββ Orchestration βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _build_and_stream(repo: str, pr_number: int) -> tuple:
|
| 54 |
+
"""Build the graph, stream up to the interrupt, and return state + config."""
|
| 55 |
+
graph = build_graph(DB_PATH)
|
| 56 |
+
thread_id = str(uuid.uuid4())
|
| 57 |
+
config = {"configurable": {"thread_id": f"web-{thread_id}"}}
|
| 58 |
+
|
| 59 |
+
initial = {"repo": repo, "pr_number": pr_number}
|
| 60 |
+
list(graph.stream(initial, config))
|
| 61 |
+
state = graph.get_state(config)
|
| 62 |
+
return state, config
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _format_findings_table(findings: list) -> str:
|
| 66 |
+
"""Build an HTML table of findings with severity-coloured badges."""
|
| 67 |
+
if not findings:
|
| 68 |
+
return '<p style="color:#666">No issues found.</p>'
|
| 69 |
+
|
| 70 |
+
rows: list[str] = []
|
| 71 |
+
for f in findings:
|
| 72 |
+
color = SEVERITY_COLORS.get(f.severity.value, "#666")
|
| 73 |
+
rows.append(
|
| 74 |
+
f"<tr>"
|
| 75 |
+
f'<td><span style="display:inline-block;padding:2px 10px;'
|
| 76 |
+
f'border-radius:12px;background:{color}22;'
|
| 77 |
+
f'color:{color};font-weight:700;font-size:0.85em">'
|
| 78 |
+
f"{f.severity.value.upper()}</span></td>"
|
| 79 |
+
f"<td>{f.category}</td>"
|
| 80 |
+
f'<td><code>{f.file_path}:{f.line_start}β{f.line_end}</code></td>'
|
| 81 |
+
f"<td>{f.comment}</td>"
|
| 82 |
+
f'<td style="text-align:center">{f.confidence:.0%}</td>'
|
| 83 |
+
f"</tr>"
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
return (
|
| 87 |
+
'<div style="overflow-x:auto">'
|
| 88 |
+
'<table style="width:100%;border-collapse:collapse;font-size:0.9em">'
|
| 89 |
+
"<thead>"
|
| 90 |
+
'<tr style="background:#f3f4f6;border-bottom:2px solid #e5e7eb">'
|
| 91 |
+
'<th style="padding:10px 12px;text-align:left">Severity</th>'
|
| 92 |
+
'<th style="padding:10px 12px;text-align:left">Category</th>'
|
| 93 |
+
'<th style="padding:10px 12px;text-align:left">Location</th>'
|
| 94 |
+
'<th style="padding:10px 12px;text-align:left">Comment</th>'
|
| 95 |
+
'<th style="padding:10px 12px;text-align:left">Confidence</th>'
|
| 96 |
+
"</tr>"
|
| 97 |
+
"</thead>"
|
| 98 |
+
"<tbody>" + "".join(rows) + "</tbody>"
|
| 99 |
+
"</table>"
|
| 100 |
+
"</div>"
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def _format_verdict(verdict: Verdict | None) -> str:
|
| 105 |
+
"""Build a verdict summary card."""
|
| 106 |
+
if verdict is None:
|
| 107 |
+
return '<p style="color:#666">No verdict produced.</p>'
|
| 108 |
+
|
| 109 |
+
icon = RECOMMENDATION_ICONS.get(verdict.recommendation, "π")
|
| 110 |
+
color = (
|
| 111 |
+
"#16a34a" if verdict.recommendation == "approve"
|
| 112 |
+
else "#dc2626" if verdict.recommendation == "block"
|
| 113 |
+
else "#ea580c"
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
return (
|
| 117 |
+
f'<div style="border:1px solid #e5e7eb;border-radius:12px;'
|
| 118 |
+
f'padding:16px 20px;background:#f9fafb">'
|
| 119 |
+
f'<div style="display:flex;align-items:center;gap:12px;margin-bottom:8px">'
|
| 120 |
+
f'<span style="font-size:2em">{icon}</span>'
|
| 121 |
+
f'<span style="font-size:1.4em;font-weight:700;color:{color}">'
|
| 122 |
+
f"{verdict.recommendation.upper()}</span>"
|
| 123 |
+
f'<span style="margin-left:auto;font-size:1.2em;font-weight:600">'
|
| 124 |
+
f"Score: {verdict.overall_score}/10</span>"
|
| 125 |
+
f"</div>"
|
| 126 |
+
f"<p style='margin:0;color:#4b5563'>{verdict.summary}</p>"
|
| 127 |
+
f"</div>"
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def _format_findings_count(findings: list) -> str:
|
| 132 |
+
"""Build a compact summary count per severity."""
|
| 133 |
+
counts: dict[str, int] = {}
|
| 134 |
+
for f in findings:
|
| 135 |
+
counts[f.severity.value] = counts.get(f.severity.value, 0) + 1
|
| 136 |
+
|
| 137 |
+
parts = []
|
| 138 |
+
for sev in ("critical", "high", "medium", "low", "info"):
|
| 139 |
+
if counts.get(sev, 0) > 0:
|
| 140 |
+
color = SEVERITY_COLORS.get(sev, "#666")
|
| 141 |
+
parts.append(
|
| 142 |
+
f'<span style="color:{color};font-weight:600">'
|
| 143 |
+
f"{sev}: {counts[sev]}</span>"
|
| 144 |
+
)
|
| 145 |
+
return " | ".join(parts) if parts else "No issues"
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
# βββ Gradio callbacks βββββββββββββββββββββββββββββββββββββββοΏ½οΏ½βββββββββββββββ
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
# _prune_db replaced with direct _cleanup_db() calls below
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def run_review(repo: str, pr_number: int, progress=gr.Progress()):
|
| 155 |
+
"""Run the review pipeline up to human-in-the-loop interrupt."""
|
| 156 |
+
if not repo or "/" not in repo:
|
| 157 |
+
yield [None, None, None, None], "β Enter a repo in `owner/name` format."
|
| 158 |
+
return
|
| 159 |
+
|
| 160 |
+
_cleanup_db()
|
| 161 |
+
|
| 162 |
+
progress(0.1, desc="Building graphβ¦")
|
| 163 |
+
|
| 164 |
+
try:
|
| 165 |
+
state, config = _build_and_stream(repo.strip(), pr_number)
|
| 166 |
+
except Exception as exc:
|
| 167 |
+
logger.exception("Review failed")
|
| 168 |
+
yield [None, None, None, None], f"β Review failed: {exc}"
|
| 169 |
+
return
|
| 170 |
+
|
| 171 |
+
tasks = state.tasks
|
| 172 |
+
values = state.values
|
| 173 |
+
|
| 174 |
+
if not tasks:
|
| 175 |
+
yield [None, None, None, None], "βΉοΈ Review completed without findings."
|
| 176 |
+
return
|
| 177 |
+
|
| 178 |
+
verdict: Verdict | None = values.get("verdict")
|
| 179 |
+
findings: list = values.get("final_findings", [])
|
| 180 |
+
|
| 181 |
+
progress(0.8, desc="Formatting resultsβ¦")
|
| 182 |
+
|
| 183 |
+
verdict_html = _format_verdict(verdict)
|
| 184 |
+
findings_html = _format_findings_table(findings)
|
| 185 |
+
count_html = _format_findings_count(findings)
|
| 186 |
+
config_json = json.dumps(config)
|
| 187 |
+
|
| 188 |
+
yield (
|
| 189 |
+
[verdict_html, findings_html, count_html, config_json],
|
| 190 |
+
None,
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def resume_review(config_json: str, action: str, progress=gr.Progress()):
|
| 195 |
+
"""Resume the paused graph with approve/reject."""
|
| 196 |
+
if not config_json:
|
| 197 |
+
return "βΉοΈ No pending review to resume. Run a review first."
|
| 198 |
+
|
| 199 |
+
config = json.loads(config_json)
|
| 200 |
+
graph = build_graph(DB_PATH)
|
| 201 |
+
|
| 202 |
+
progress(0.3, desc=f"Processing {action}β¦")
|
| 203 |
+
|
| 204 |
+
try:
|
| 205 |
+
graph.invoke(Command(resume={"action": action}), config)
|
| 206 |
+
final_state = graph.get_state(config)
|
| 207 |
+
approved = final_state.values.get("human_approved")
|
| 208 |
+
msg = (
|
| 209 |
+
f"β
Review **approved**! Findings posted to GitHub."
|
| 210 |
+
if approved
|
| 211 |
+
else "β Review **rejected**. No comments posted."
|
| 212 |
+
)
|
| 213 |
+
return msg
|
| 214 |
+
except Exception as exc:
|
| 215 |
+
logger.exception("Resume failed")
|
| 216 |
+
return f"β Error: {exc}"
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def run_smoke(progress=gr.Progress()):
|
| 220 |
+
"""Run the synthetic smoke test."""
|
| 221 |
+
_cleanup_db()
|
| 222 |
+
|
| 223 |
+
progress(0.1, desc="Building graphβ¦")
|
| 224 |
+
graph = build_graph(DB_PATH)
|
| 225 |
+
thread_id = str(uuid.uuid4())
|
| 226 |
+
config = {"configurable": {"thread_id": f"smoke-web-{thread_id}"}}
|
| 227 |
+
|
| 228 |
+
progress(0.3, desc="Running on synthetic dataβ¦")
|
| 229 |
+
list(graph.stream(SYNTHETIC_STATE, config))
|
| 230 |
+
state = graph.get_state(config)
|
| 231 |
+
tasks = state.tasks
|
| 232 |
+
|
| 233 |
+
if not tasks:
|
| 234 |
+
yield [None, None, None, None, None], "βΉοΈ Smoke test completed without findings."
|
| 235 |
+
return
|
| 236 |
+
|
| 237 |
+
verdict: Verdict | None = state.values.get("verdict")
|
| 238 |
+
findings: list = state.values.get("final_findings", [])
|
| 239 |
+
|
| 240 |
+
progress(0.8, desc="Formattingβ¦")
|
| 241 |
+
verdict_html = _format_verdict(verdict)
|
| 242 |
+
findings_html = _format_findings_table(findings)
|
| 243 |
+
|
| 244 |
+
yield [verdict_html, findings_html, json.dumps(config), verdict_html, findings_html], None
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
# βββ UI ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 251 |
+
|
| 252 |
+
CSS = """
|
| 253 |
+
.gr-container { max-width: 960px; margin: 0 auto; }
|
| 254 |
+
h1 { display: flex; align-items: center; gap: 10px; }
|
| 255 |
+
.footer { text-align: center; color: #9ca3af; font-size: 0.85em; padding: 20px 0; }
|
| 256 |
+
details { margin-top: 8px; }
|
| 257 |
+
details summary { cursor: pointer; color: #4b5563; font-weight: 500; }
|
| 258 |
+
"""
|
| 259 |
+
|
| 260 |
+
with gr.Blocks(css=CSS, title="OpenCodeReview", theme=gr.themes.Soft()) as demo:
|
| 261 |
+
gr.HTML(
|
| 262 |
+
'<h1>π OpenCodeReview</h1>'
|
| 263 |
+
'<p style="color:#6b7280;margin-top:-8px">'
|
| 264 |
+
"AI-powered PR review with human-in-the-loop approval</p>"
|
| 265 |
+
)
|
| 266 |
+
|
| 267 |
+
# ββ State ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 268 |
+
pr_state = gr.State()
|
| 269 |
+
smoke_state = gr.State()
|
| 270 |
+
|
| 271 |
+
# ββ Tab: Review a PR βββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 272 |
+
with gr.Tab("Review a PR"):
|
| 273 |
+
with gr.Row():
|
| 274 |
+
repo_input = gr.Textbox(
|
| 275 |
+
label="Repository",
|
| 276 |
+
placeholder="owner/repo (e.g. psf/requests)",
|
| 277 |
+
scale=3,
|
| 278 |
+
)
|
| 279 |
+
pr_input = gr.Number(
|
| 280 |
+
label="PR #",
|
| 281 |
+
value=1,
|
| 282 |
+
minimum=1,
|
| 283 |
+
precision=0,
|
| 284 |
+
scale=1,
|
| 285 |
+
)
|
| 286 |
+
run_btn = gr.Button("βΆ Run Review", variant="primary", size="lg")
|
| 287 |
+
|
| 288 |
+
status_msg = gr.Markdown(visible=False)
|
| 289 |
+
|
| 290 |
+
with gr.Column(visible=False) as results_panel:
|
| 291 |
+
verdict_display = gr.HTML()
|
| 292 |
+
count_display = gr.HTML()
|
| 293 |
+
findings_display = gr.HTML()
|
| 294 |
+
|
| 295 |
+
with gr.Row():
|
| 296 |
+
approve_btn = gr.Button("β
Approve & Post", variant="primary")
|
| 297 |
+
reject_btn = gr.Button("β Reject", variant="secondary")
|
| 298 |
+
|
| 299 |
+
resume_msg = gr.Markdown()
|
| 300 |
+
|
| 301 |
+
# ββ Event wiring ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 302 |
+
def on_run_click(*args):
|
| 303 |
+
"""Generator that clears old state, runs review, shows results."""
|
| 304 |
+
for result, err in run_review(*args):
|
| 305 |
+
if err:
|
| 306 |
+
yield [
|
| 307 |
+
*[None, None, None, None],
|
| 308 |
+
gr.update(visible=True, value=err),
|
| 309 |
+
gr.update(visible=False),
|
| 310 |
+
]
|
| 311 |
+
else:
|
| 312 |
+
verdict_html, findings_html, count_html, config_json = result
|
| 313 |
+
yield [
|
| 314 |
+
gr.update(value=verdict_html),
|
| 315 |
+
gr.update(value=count_html),
|
| 316 |
+
gr.update(value=findings_html),
|
| 317 |
+
config_json,
|
| 318 |
+
gr.update(visible=False),
|
| 319 |
+
gr.update(visible=True),
|
| 320 |
+
]
|
| 321 |
+
|
| 322 |
+
run_event = run_btn.click(
|
| 323 |
+
fn=on_run_click,
|
| 324 |
+
inputs=[repo_input, pr_input],
|
| 325 |
+
outputs=[
|
| 326 |
+
verdict_display,
|
| 327 |
+
count_display,
|
| 328 |
+
findings_display,
|
| 329 |
+
pr_state,
|
| 330 |
+
status_msg,
|
| 331 |
+
results_panel,
|
| 332 |
+
],
|
| 333 |
+
)
|
| 334 |
+
|
| 335 |
+
def on_approve(config_json):
|
| 336 |
+
msg = resume_review(config_json, "approve")
|
| 337 |
+
return gr.update(value=msg)
|
| 338 |
+
|
| 339 |
+
def on_reject(config_json):
|
| 340 |
+
msg = resume_review(config_json, "reject")
|
| 341 |
+
return gr.update(value=msg)
|
| 342 |
+
|
| 343 |
+
approve_btn.click(
|
| 344 |
+
fn=on_approve,
|
| 345 |
+
inputs=[pr_state],
|
| 346 |
+
outputs=[resume_msg],
|
| 347 |
+
)
|
| 348 |
+
reject_btn.click(
|
| 349 |
+
fn=on_reject,
|
| 350 |
+
inputs=[pr_state],
|
| 351 |
+
outputs=[resume_msg],
|
| 352 |
+
)
|
| 353 |
+
|
| 354 |
+
# ββ Tab: Smoke Test ββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 355 |
+
with gr.Tab("Smoke Test"):
|
| 356 |
+
gr.Markdown(
|
| 357 |
+
"Run the review pipeline on **synthetic demo data** "
|
| 358 |
+
"(no API keys needed, no interrupt required)."
|
| 359 |
+
)
|
| 360 |
+
smoke_btn = gr.Button("βΆ Run Smoke Test", variant="primary", size="lg")
|
| 361 |
+
|
| 362 |
+
with gr.Column(visible=False) as smoke_results:
|
| 363 |
+
smoke_verdict = gr.HTML()
|
| 364 |
+
smoke_findings = gr.HTML()
|
| 365 |
+
with gr.Row():
|
| 366 |
+
smoke_approve = gr.Button("β
Approve (demo)", variant="primary")
|
| 367 |
+
smoke_reject = gr.Button("β Reject (demo)", variant="secondary")
|
| 368 |
+
smoke_resume_msg = gr.Markdown()
|
| 369 |
+
|
| 370 |
+
def on_smoke_click():
|
| 371 |
+
for result, err in run_smoke():
|
| 372 |
+
if err:
|
| 373 |
+
yield [
|
| 374 |
+
gr.update(visible=True, value=err),
|
| 375 |
+
gr.update(visible=False),
|
| 376 |
+
None,
|
| 377 |
+
gr.update(value=""),
|
| 378 |
+
gr.update(value=""),
|
| 379 |
+
]
|
| 380 |
+
else:
|
| 381 |
+
verdict_html, findings_html, config_json, s_verdict, s_findings = result
|
| 382 |
+
yield [
|
| 383 |
+
gr.update(visible=False),
|
| 384 |
+
gr.update(visible=True),
|
| 385 |
+
config_json,
|
| 386 |
+
gr.update(value=s_verdict),
|
| 387 |
+
gr.update(value=s_findings),
|
| 388 |
+
]
|
| 389 |
+
|
| 390 |
+
smoke_btn.click(
|
| 391 |
+
fn=on_smoke_click,
|
| 392 |
+
outputs=[status_msg, smoke_results, smoke_state,
|
| 393 |
+
smoke_verdict, smoke_findings],
|
| 394 |
+
)
|
| 395 |
+
|
| 396 |
+
smoke_approve.click(
|
| 397 |
+
fn=lambda c: resume_review(c, "approve"),
|
| 398 |
+
inputs=[smoke_state],
|
| 399 |
+
outputs=[smoke_resume_msg],
|
| 400 |
+
)
|
| 401 |
+
smoke_reject.click(
|
| 402 |
+
fn=lambda c: resume_review(c, "reject"),
|
| 403 |
+
inputs=[smoke_state],
|
| 404 |
+
outputs=[smoke_resume_msg],
|
| 405 |
+
)
|
| 406 |
+
|
| 407 |
+
# ββ Environment status footer ββββββββββββββββββββββββββββββββββββββ
|
| 408 |
+
with gr.Accordion("π Configured Keys", open=False):
|
| 409 |
+
groq_ok = bool(os.environ.get("GROQ_API_KEY", "").strip())
|
| 410 |
+
gh_ok = bool(os.environ.get("GITHUB_TOKEN", "").strip())
|
| 411 |
+
groq_status = "β
Set" if groq_ok else "β Not set β reviewers will be skipped"
|
| 412 |
+
gh_status = "β
Set" if gh_ok else "β Not set β cannot fetch real PRs"
|
| 413 |
+
gr.HTML(
|
| 414 |
+
f"<ul>"
|
| 415 |
+
f"<li>GROQ_API_KEY: {groq_status}</li>"
|
| 416 |
+
f"<li>GITHUB_TOKEN: {gh_status}</li>"
|
| 417 |
+
f"</ul>"
|
| 418 |
+
)
|
| 419 |
+
|
| 420 |
+
# ββ Footer ββββββββββββοΏ½οΏ½ββββββββββββββββββββββββββββββββββββββββββββ
|
| 421 |
+
gr.HTML(
|
| 422 |
+
'<p class="footer">Built with LangGraph Β· Groq Β· ChromaDB Β· Gradio</p>'
|
| 423 |
+
)
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
def main() -> None:
|
| 427 |
+
port = int(os.environ.get("PORT", 7860))
|
| 428 |
+
demo.queue(max_size=10).launch(
|
| 429 |
+
server_name="0.0.0.0",
|
| 430 |
+
server_port=port,
|
| 431 |
+
share=False,
|
| 432 |
+
)
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
if __name__ == "__main__":
|
| 436 |
+
main()
|
auth.py
ADDED
|
@@ -0,0 +1,353 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""GitHub OAuth Device Flow authentication for OpenCodeReview.
|
| 3 |
+
|
| 4 |
+
Usage
|
| 5 |
+
-----
|
| 6 |
+
export GITHUB_OAUTH_CLIENT_ID="Iv23li..."
|
| 7 |
+
opencodereview auth login
|
| 8 |
+
opencodereview auth status
|
| 9 |
+
opencodereview auth logout
|
| 10 |
+
|
| 11 |
+
The Device Flow is used instead of the Authorization Code flow because
|
| 12 |
+
there is no web server to handle a redirect URI.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
import logging
|
| 18 |
+
import os
|
| 19 |
+
import sys
|
| 20 |
+
import time
|
| 21 |
+
from typing import Optional
|
| 22 |
+
|
| 23 |
+
import click
|
| 24 |
+
import keyring
|
| 25 |
+
import requests
|
| 26 |
+
|
| 27 |
+
logger = logging.getLogger(__name__)
|
| 28 |
+
|
| 29 |
+
# βββ Constants βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 30 |
+
|
| 31 |
+
SERVICE_NAME = "opencodereview"
|
| 32 |
+
GH_DEVICE_CODE_URL = "https://github.com/login/device/code"
|
| 33 |
+
GH_ACCESS_TOKEN_URL = "https://github.com/login/oauth/access_token"
|
| 34 |
+
GH_API_BASE = "https://api.github.com"
|
| 35 |
+
DEFAULT_SCOPE = "repo" # Full control of private repositories β needed for
|
| 36 |
+
# reading PRs and posting review comments on
|
| 37 |
+
# private repos.
|
| 38 |
+
POLL_SAFETY_MARGIN = 1 # Extra seconds to wait beyond the server's interval
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
# βββ Exceptions βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class AuthError(Exception):
|
| 45 |
+
"""Base exception for auth operations."""
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class DeviceFlowExpired(AuthError):
|
| 49 |
+
"""The device code expired before the user approved."""
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class DeviceFlowDenied(AuthError):
|
| 53 |
+
"""The user denied the authorization request."""
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
# βββ Auth Service ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _resolve_client_id(client_id: Optional[str] = None) -> str:
|
| 60 |
+
"""Return the GitHub OAuth client ID from the argument or environment."""
|
| 61 |
+
cid = client_id or os.environ.get("GITHUB_OAUTH_CLIENT_ID")
|
| 62 |
+
if not cid:
|
| 63 |
+
raise AuthError(
|
| 64 |
+
"GitHub OAuth client ID is required.\n\n"
|
| 65 |
+
" 1. Register a new OAuth App at:\n"
|
| 66 |
+
" https://github.com/settings/developers\n\n"
|
| 67 |
+
" 2. Enable Device Flow in the app settings.\n\n"
|
| 68 |
+
" 3. Set the client ID:\n"
|
| 69 |
+
f" export GITHUB_OAUTH_CLIENT_ID=\"<your_client_id>\"\n"
|
| 70 |
+
" Or pass --client-id to the login command.",
|
| 71 |
+
)
|
| 72 |
+
return cid
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class AuthService:
|
| 76 |
+
"""Manage GitHub OAuth tokens via the Device Flow."""
|
| 77 |
+
|
| 78 |
+
def __init__(self, client_id: Optional[str] = None) -> None:
|
| 79 |
+
self._client_id = client_id or os.environ.get("GITHUB_OAUTH_CLIENT_ID")
|
| 80 |
+
self._session = requests.Session()
|
| 81 |
+
self._session.headers.update({
|
| 82 |
+
"Accept": "application/json",
|
| 83 |
+
"User-Agent": "opencodereview/1.0",
|
| 84 |
+
})
|
| 85 |
+
|
| 86 |
+
# ββ Device Flow Login ββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 87 |
+
|
| 88 |
+
def login(self) -> str:
|
| 89 |
+
"""Run the GitHub Device Flow and return the access token.
|
| 90 |
+
|
| 91 |
+
Steps
|
| 92 |
+
-----
|
| 93 |
+
1. POST to ``/login/device/code`` to get a device + user code.
|
| 94 |
+
2. Print the user code + verification URL for the user.
|
| 95 |
+
3. Poll ``/login/oauth/access_token`` until the user approves.
|
| 96 |
+
4. Validate that the granted scopes include what was requested.
|
| 97 |
+
5. Save the token to the system keyring.
|
| 98 |
+
6. Return the access token.
|
| 99 |
+
"""
|
| 100 |
+
# Validate client_id before making any API calls
|
| 101 |
+
self._client_id = _resolve_client_id(self._client_id)
|
| 102 |
+
|
| 103 |
+
device_code, user_code, verification_uri, interval, expires_in = (
|
| 104 |
+
self._request_device_code()
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
self._print_login_instructions(user_code, verification_uri, expires_in)
|
| 108 |
+
|
| 109 |
+
access_token, granted_scope = self._poll_for_token(device_code, interval)
|
| 110 |
+
|
| 111 |
+
# Validate that the granted scopes include what we asked for
|
| 112 |
+
self._validate_scopes(granted_scope)
|
| 113 |
+
|
| 114 |
+
# Save to keyring
|
| 115 |
+
keyring.set_password(SERVICE_NAME, "github_token", access_token)
|
| 116 |
+
logger.info("Token saved to system credential store (keyring).")
|
| 117 |
+
|
| 118 |
+
# Fetch and display user info
|
| 119 |
+
user = self._get_user(access_token)
|
| 120 |
+
click.echo(f" Logged in as: {user['login']}")
|
| 121 |
+
|
| 122 |
+
return access_token
|
| 123 |
+
|
| 124 |
+
def _request_device_code(
|
| 125 |
+
self,
|
| 126 |
+
) -> tuple[str, str, str, int, int]:
|
| 127 |
+
"""POST to the device-code endpoint and return the response fields."""
|
| 128 |
+
resp = self._session.post(
|
| 129 |
+
GH_DEVICE_CODE_URL,
|
| 130 |
+
data={
|
| 131 |
+
"client_id": self._client_id,
|
| 132 |
+
"scope": DEFAULT_SCOPE,
|
| 133 |
+
},
|
| 134 |
+
)
|
| 135 |
+
resp.raise_for_status()
|
| 136 |
+
data = resp.json()
|
| 137 |
+
|
| 138 |
+
if "error" in data:
|
| 139 |
+
raise AuthError(
|
| 140 |
+
f"Device code request failed: {data.get('error_description', data['error'])}"
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
return (
|
| 144 |
+
data["device_code"],
|
| 145 |
+
data["user_code"],
|
| 146 |
+
data["verification_uri"],
|
| 147 |
+
data.get("interval", 5),
|
| 148 |
+
data.get("expires_in", 900),
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
@staticmethod
|
| 152 |
+
def _print_login_instructions(
|
| 153 |
+
user_code: str, verification_uri: str, expires_in: int,
|
| 154 |
+
) -> None:
|
| 155 |
+
"""Print the user code and instructions to the terminal."""
|
| 156 |
+
click.echo()
|
| 157 |
+
click.echo("=" * 60)
|
| 158 |
+
click.echo(" GitHub Device Authentication")
|
| 159 |
+
click.echo("=" * 60)
|
| 160 |
+
click.echo()
|
| 161 |
+
click.echo(f" 1. Open this URL in your browser:")
|
| 162 |
+
click.echo(f" {verification_uri}")
|
| 163 |
+
click.echo()
|
| 164 |
+
click.echo(f" 2. Enter the following code:")
|
| 165 |
+
click.echo(f" {user_code}")
|
| 166 |
+
click.echo()
|
| 167 |
+
click.echo(f" 3. Authorize the OpenCodeReview application.")
|
| 168 |
+
click.echo()
|
| 169 |
+
click.echo(f" This code expires in {expires_in // 60} minute(s).")
|
| 170 |
+
click.echo(f" Waiting for you to approve...")
|
| 171 |
+
click.echo()
|
| 172 |
+
|
| 173 |
+
def _poll_for_token(self, device_code: str, interval: int) -> tuple[str, str]:
|
| 174 |
+
"""Poll the access-token endpoint until the user approves or the code expires.
|
| 175 |
+
|
| 176 |
+
Returns ``(access_token, granted_scope)`` where ``granted_scope`` is the
|
| 177 |
+
space-separated scope string returned by GitHub (may be empty if the
|
| 178 |
+
response omitted it).
|
| 179 |
+
"""
|
| 180 |
+
poll_interval = interval
|
| 181 |
+
start_time = time.monotonic()
|
| 182 |
+
|
| 183 |
+
while True:
|
| 184 |
+
time.sleep(poll_interval + POLL_SAFETY_MARGIN)
|
| 185 |
+
|
| 186 |
+
resp = self._session.post(
|
| 187 |
+
GH_ACCESS_TOKEN_URL,
|
| 188 |
+
data={
|
| 189 |
+
"client_id": self._client_id,
|
| 190 |
+
"device_code": device_code,
|
| 191 |
+
"grant_type": "urn:ietf:params:oauth:grant-type:device_code",
|
| 192 |
+
},
|
| 193 |
+
)
|
| 194 |
+
resp.raise_for_status()
|
| 195 |
+
data = resp.json()
|
| 196 |
+
|
| 197 |
+
if "access_token" in data:
|
| 198 |
+
return data["access_token"], data.get("scope", "")
|
| 199 |
+
|
| 200 |
+
error = data.get("error", "")
|
| 201 |
+
|
| 202 |
+
if error == "authorization_pending":
|
| 203 |
+
# User hasn't acted yet β keep polling
|
| 204 |
+
continue
|
| 205 |
+
elif error == "slow_down":
|
| 206 |
+
# Polling too fast β increase interval by 5 seconds
|
| 207 |
+
poll_interval += 5
|
| 208 |
+
logger.debug("Polling rate limited β increasing interval to %ds", poll_interval)
|
| 209 |
+
continue
|
| 210 |
+
elif error == "expired_token":
|
| 211 |
+
raise DeviceFlowExpired(
|
| 212 |
+
"The device code has expired. Run 'opencodereview auth login' again."
|
| 213 |
+
)
|
| 214 |
+
elif error == "access_denied":
|
| 215 |
+
raise DeviceFlowDenied("The authorization request was denied.")
|
| 216 |
+
else:
|
| 217 |
+
raise AuthError(
|
| 218 |
+
f"Unexpected polling response: {data.get('error_description', error)}"
|
| 219 |
+
)
|
| 220 |
+
|
| 221 |
+
# ββ Status ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 222 |
+
|
| 223 |
+
def status(self) -> Optional[dict]:
|
| 224 |
+
"""Check whether a valid token is stored and return the authenticated user.
|
| 225 |
+
|
| 226 |
+
Returns ``None`` if no token is stored.
|
| 227 |
+
Raises ``AuthError`` if the token is invalid or expired.
|
| 228 |
+
"""
|
| 229 |
+
token = keyring.get_password(SERVICE_NAME, "github_token")
|
| 230 |
+
if not token:
|
| 231 |
+
return None
|
| 232 |
+
|
| 233 |
+
user = self._get_user(token)
|
| 234 |
+
return user
|
| 235 |
+
|
| 236 |
+
# ββ Logout ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 237 |
+
|
| 238 |
+
def logout(self) -> bool:
|
| 239 |
+
"""Delete the stored token from the keyring.
|
| 240 |
+
|
| 241 |
+
Returns ``True`` if a token was deleted, ``False`` if none existed.
|
| 242 |
+
"""
|
| 243 |
+
existing = keyring.get_password(SERVICE_NAME, "github_token")
|
| 244 |
+
if existing:
|
| 245 |
+
try:
|
| 246 |
+
keyring.delete_password(SERVICE_NAME, "github_token")
|
| 247 |
+
except keyring.errors.PasswordDeleteError:
|
| 248 |
+
logger.warning("Failed to delete token from keyring (back-end error).")
|
| 249 |
+
return False
|
| 250 |
+
return True
|
| 251 |
+
return False
|
| 252 |
+
|
| 253 |
+
# ββ Helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 254 |
+
|
| 255 |
+
def _validate_scopes(self, granted_scope_str: str) -> None:
|
| 256 |
+
"""Compare the scopes GitHub actually granted against what was requested.
|
| 257 |
+
|
| 258 |
+
The ``scope`` field in the access-token response is a space-separated
|
| 259 |
+
string. If the user denied some scopes, we warn them on stderr so
|
| 260 |
+
they know certain features may not work.
|
| 261 |
+
"""
|
| 262 |
+
if not granted_scope_str.strip():
|
| 263 |
+
# Older GitHub Enterprise or unusual config β skip validation
|
| 264 |
+
return
|
| 265 |
+
|
| 266 |
+
requested = set(DEFAULT_SCOPE.split(","))
|
| 267 |
+
granted = set(granted_scope_str.strip().split())
|
| 268 |
+
missing = requested - granted
|
| 269 |
+
|
| 270 |
+
if missing:
|
| 271 |
+
click.echo(
|
| 272 |
+
"\n"
|
| 273 |
+
"Warning: Some requested permissions were not granted.\n"
|
| 274 |
+
f" Missing scopes: {', '.join(sorted(missing))}\n"
|
| 275 |
+
f" Granted scopes: {', '.join(sorted(granted))}\n"
|
| 276 |
+
"\n"
|
| 277 |
+
" Features that need these scopes may not work correctly.\n"
|
| 278 |
+
" Re-run 'opencodereview auth login' and ensure you\n"
|
| 279 |
+
" authorize all requested permissions.\n",
|
| 280 |
+
err=True,
|
| 281 |
+
)
|
| 282 |
+
|
| 283 |
+
def _get_user(self, token: str) -> dict:
|
| 284 |
+
"""Fetch the authenticated GitHub user via the API."""
|
| 285 |
+
resp = self._session.get(
|
| 286 |
+
f"{GH_API_BASE}/user",
|
| 287 |
+
headers={"Authorization": f"token {token}"},
|
| 288 |
+
)
|
| 289 |
+
if resp.status_code == 401:
|
| 290 |
+
raise AuthError(
|
| 291 |
+
"The stored token is invalid or has been revoked.\n"
|
| 292 |
+
"Run 'opencodereview auth login' to re-authenticate."
|
| 293 |
+
)
|
| 294 |
+
resp.raise_for_status()
|
| 295 |
+
return resp.json()
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
# βββ CLI βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
@click.group()
|
| 302 |
+
def auth() -> None:
|
| 303 |
+
"""Authenticate with GitHub via the OAuth Device Flow."""
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
@auth.command()
|
| 307 |
+
@click.option(
|
| 308 |
+
"--client-id",
|
| 309 |
+
envvar="GITHUB_OAUTH_CLIENT_ID",
|
| 310 |
+
default=None,
|
| 311 |
+
help="GitHub OAuth App client ID (or set GITHUB_OAUTH_CLIENT_ID).",
|
| 312 |
+
)
|
| 313 |
+
def login(client_id: Optional[str]) -> None:
|
| 314 |
+
"""Authenticate with GitHub and store the token securely."""
|
| 315 |
+
try:
|
| 316 |
+
svc = AuthService(client_id=client_id)
|
| 317 |
+
svc.login()
|
| 318 |
+
except (AuthError, requests.RequestException) as exc:
|
| 319 |
+
click.echo(f"Error: {exc}", err=True)
|
| 320 |
+
sys.exit(1)
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
@auth.command()
|
| 324 |
+
def logout() -> None:
|
| 325 |
+
"""Remove the stored GitHub token."""
|
| 326 |
+
svc = AuthService()
|
| 327 |
+
if svc.logout():
|
| 328 |
+
click.echo("Token removed from credential store.")
|
| 329 |
+
else:
|
| 330 |
+
click.echo("No token found. Nothing to remove.")
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
@auth.command()
|
| 334 |
+
def status() -> None:
|
| 335 |
+
"""Show whether a valid token is stored and which user it belongs to."""
|
| 336 |
+
svc = AuthService()
|
| 337 |
+
try:
|
| 338 |
+
user = svc.status()
|
| 339 |
+
except AuthError as exc:
|
| 340 |
+
click.echo(f"Token status: invalid ({exc})", err=True)
|
| 341 |
+
sys.exit(1)
|
| 342 |
+
except requests.RequestException as exc:
|
| 343 |
+
click.echo(f"Error checking token: {exc}", err=True)
|
| 344 |
+
sys.exit(1)
|
| 345 |
+
|
| 346 |
+
if user is None:
|
| 347 |
+
click.echo("No token stored. Run 'opencodereview auth login'.", err=True)
|
| 348 |
+
sys.exit(1)
|
| 349 |
+
else:
|
| 350 |
+
click.echo(f"Authenticated as: {user['login']}")
|
| 351 |
+
click.echo(f"Token: valid")
|
| 352 |
+
if user.get("name"):
|
| 353 |
+
click.echo(f"Name: {user['name']}")
|
config.py
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Configuration management for OpenCodeReview.
|
| 3 |
+
|
| 4 |
+
Resolves secrets in priority order: **environment variable > keyring > error**.
|
| 5 |
+
|
| 6 |
+
Providers
|
| 7 |
+
---------
|
| 8 |
+
- ``anthropic`` β ``ANTHROPIC_API_KEY`` β stored as ``opencodereview / anthropic_api_key``
|
| 9 |
+
|
| 10 |
+
Usage
|
| 11 |
+
-----
|
| 12 |
+
opencodereview config set-key --provider anthropic
|
| 13 |
+
opencodereview config show
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import logging
|
| 19 |
+
import os
|
| 20 |
+
import sys
|
| 21 |
+
from typing import Optional
|
| 22 |
+
|
| 23 |
+
import click
|
| 24 |
+
import keyring
|
| 25 |
+
from pydantic import Field
|
| 26 |
+
from pydantic_settings import BaseSettings, SettingsConfigDict
|
| 27 |
+
|
| 28 |
+
logger = logging.getLogger(__name__)
|
| 29 |
+
|
| 30 |
+
SERVICE_NAME = "opencodereview"
|
| 31 |
+
|
| 32 |
+
# βββ Provider registry ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 33 |
+
# slug β (keyring_key, env_var_name, display_name)
|
| 34 |
+
|
| 35 |
+
PROVIDERS: dict[str, tuple[str, str, str]] = {
|
| 36 |
+
"anthropic": (
|
| 37 |
+
"anthropic_api_key", # keyring key
|
| 38 |
+
"OPENCODEREVIEW_ANTHROPIC_KEY", # env var
|
| 39 |
+
"Anthropic API key", # display name
|
| 40 |
+
),
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
# βββ Exceptions βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class ConfigError(Exception):
|
| 48 |
+
"""Configuration-related error with a user-facing message."""
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
# βββ Settings (pydantic-settings) βββββββββββββββββββββββββββββββββββββββββββ
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class Settings(BaseSettings):
|
| 55 |
+
"""Resolve configuration from env vars, falling back to the system keyring.
|
| 56 |
+
|
| 57 |
+
Priority
|
| 58 |
+
--------
|
| 59 |
+
1. Environment variable (``OPENCODEREVIEW_<FIELD>``)
|
| 60 |
+
2. System keyring (``opencodereview / <keyring_key>``)
|
| 61 |
+
3. :class:`ConfigError` with a helpful message telling the user how to set it.
|
| 62 |
+
"""
|
| 63 |
+
|
| 64 |
+
model_config = SettingsConfigDict(
|
| 65 |
+
env_prefix="OPENCODEREVIEW_",
|
| 66 |
+
extra="ignore",
|
| 67 |
+
validate_default=False,
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
anthropic_api_key: Optional[str] = Field(default=None)
|
| 71 |
+
|
| 72 |
+
def model_post_init(self, __context) -> None: # noqa: ANN101
|
| 73 |
+
"""After env-var resolution, fall back to keyring for any unset values."""
|
| 74 |
+
for keyring_key, _, _ in PROVIDERS.values():
|
| 75 |
+
if getattr(self, keyring_key) is None:
|
| 76 |
+
stored = keyring.get_password(SERVICE_NAME, keyring_key)
|
| 77 |
+
if stored:
|
| 78 |
+
setattr(self, keyring_key, stored)
|
| 79 |
+
|
| 80 |
+
def get_anthropic_api_key(self) -> str:
|
| 81 |
+
"""Return the Anthropic API key or raise ``ConfigError``."""
|
| 82 |
+
key = self.anthropic_api_key
|
| 83 |
+
if not key:
|
| 84 |
+
raise ConfigError(
|
| 85 |
+
"Anthropic API key is not configured.\n\n"
|
| 86 |
+
" Set it interactively:\n"
|
| 87 |
+
" opencodereview config set-key --provider anthropic\n\n"
|
| 88 |
+
" Or as an environment variable:\n"
|
| 89 |
+
" export OPENCODEREVIEW_ANTHROPIC_KEY=\"sk-ant-...\"\n"
|
| 90 |
+
)
|
| 91 |
+
return key
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
# βββ Key masking βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def _mask_key(key: str) -> str:
|
| 98 |
+
"""Return a masked version showing only the prefix and last characters.
|
| 99 |
+
|
| 100 |
+
Examples
|
| 101 |
+
--------
|
| 102 |
+
``sk-ant-abcdefgh12345678`` β ``sk-ant-...5678``
|
| 103 |
+
``ghp_abc123def456`` β ``ghp_abc...f456``
|
| 104 |
+
``abcdefg`` β ``abcd...fg``
|
| 105 |
+
``tiny`` β ``t...``
|
| 106 |
+
"""
|
| 107 |
+
n = len(key)
|
| 108 |
+
if n <= 4:
|
| 109 |
+
return key[:1] + "..."
|
| 110 |
+
if n <= 8:
|
| 111 |
+
return key[:4] + "..." + key[-2:]
|
| 112 |
+
return key[:7] + "..." + key[-4:]
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
# βββ CLI βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
@click.group()
|
| 119 |
+
def config() -> None:
|
| 120 |
+
"""Manage API keys and configuration."""
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
@config.command()
|
| 124 |
+
@click.option(
|
| 125 |
+
"--provider",
|
| 126 |
+
required=True,
|
| 127 |
+
type=click.Choice(sorted(PROVIDERS), case_sensitive=True),
|
| 128 |
+
help="Which provider's API key to store.",
|
| 129 |
+
)
|
| 130 |
+
def set_key(provider: str) -> None:
|
| 131 |
+
"""Prompt for an API key and store it securely in the system keyring.
|
| 132 |
+
|
| 133 |
+
The key is entered via hidden input and never echoed to the terminal.
|
| 134 |
+
"""
|
| 135 |
+
keyring_key, env_var, display_name = PROVIDERS[provider]
|
| 136 |
+
|
| 137 |
+
# Warn if env var is already set (keyring value would be ignored)
|
| 138 |
+
if os.environ.get(env_var):
|
| 139 |
+
click.echo(
|
| 140 |
+
f"Warning: {display_name} is already set via the"
|
| 141 |
+
f" {env_var} environment variable.\n"
|
| 142 |
+
f" A keyring-stored key won't take effect until the env var is unset.\n",
|
| 143 |
+
err=True,
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
api_key = click.prompt(
|
| 147 |
+
f"Enter your {display_name}",
|
| 148 |
+
hide_input=True,
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
if not api_key.strip():
|
| 152 |
+
click.echo("Error: Key cannot be empty.", err=True)
|
| 153 |
+
sys.exit(1)
|
| 154 |
+
|
| 155 |
+
keyring.set_password(SERVICE_NAME, keyring_key, api_key.strip())
|
| 156 |
+
click.echo(f"{display_name} saved to system credential store (keyring).")
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
@config.command()
|
| 160 |
+
def show() -> None:
|
| 161 |
+
"""Display which keys and tokens are configured (values masked).
|
| 162 |
+
|
| 163 |
+
Full secrets are never printed β only the first 7 + last 4 characters.
|
| 164 |
+
"""
|
| 165 |
+
click.echo()
|
| 166 |
+
click.echo("=" * 50)
|
| 167 |
+
click.echo(" Configuration Summary")
|
| 168 |
+
click.echo("=" * 50)
|
| 169 |
+
click.echo()
|
| 170 |
+
has_any = False
|
| 171 |
+
|
| 172 |
+
# ββ GitHub token (managed by auth) ββββββββββββββββββββββββββββββββββββββ
|
| 173 |
+
gh_token = keyring.get_password(SERVICE_NAME, "github_token")
|
| 174 |
+
token_env = os.environ.get("GITHUB_TOKEN")
|
| 175 |
+
if token_env:
|
| 176 |
+
click.echo(f" GitHub token: {_mask_key(token_env)} (from env)")
|
| 177 |
+
has_any = True
|
| 178 |
+
elif gh_token:
|
| 179 |
+
click.echo(f" GitHub token: {_mask_key(gh_token)} (from keyring)")
|
| 180 |
+
has_any = True
|
| 181 |
+
else:
|
| 182 |
+
click.echo(" GitHub token: not set")
|
| 183 |
+
|
| 184 |
+
# ββ Provider API keys βββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 185 |
+
for provider_slug, (keyring_key, env_var, display_name) in sorted(PROVIDERS.items()):
|
| 186 |
+
env_value = os.environ.get(env_var)
|
| 187 |
+
if env_value:
|
| 188 |
+
click.echo(
|
| 189 |
+
f" {display_name}: {_mask_key(env_value)} (from env)"
|
| 190 |
+
)
|
| 191 |
+
has_any = True
|
| 192 |
+
else:
|
| 193 |
+
stored = keyring.get_password(SERVICE_NAME, keyring_key)
|
| 194 |
+
if stored:
|
| 195 |
+
click.echo(
|
| 196 |
+
f" {display_name}: {_mask_key(stored)} (from keyring)"
|
| 197 |
+
)
|
| 198 |
+
has_any = True
|
| 199 |
+
else:
|
| 200 |
+
click.echo(f" {display_name}: not set")
|
| 201 |
+
|
| 202 |
+
click.echo()
|
| 203 |
+
if not has_any:
|
| 204 |
+
click.echo(" No keys or tokens configured.")
|
| 205 |
+
click.echo(" Run: opencodereview config set-key --provider anthropic")
|
| 206 |
+
click.echo()
|
docker-compose.yml
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# =============================================================================
|
| 2 |
+
# OpenCodeReview β Docker Compose
|
| 3 |
+
# =============================================================================
|
| 4 |
+
#
|
| 5 |
+
# Quick start
|
| 6 |
+
# -----------
|
| 7 |
+
# 1. Set your API keys in a .env file:
|
| 8 |
+
# GROQ_API_KEY=gsk_your_key_here
|
| 9 |
+
# GITHUB_TOKEN=ghp_your_token_here
|
| 10 |
+
#
|
| 11 |
+
# 2. Build and run the smoke test:
|
| 12 |
+
# docker compose build
|
| 13 |
+
# docker compose run --rm opencodereview review --smoke
|
| 14 |
+
#
|
| 15 |
+
# 3. Review a real PR:
|
| 16 |
+
# docker compose run --rm opencodereview review --repo org/repo --pr 42
|
| 17 |
+
#
|
| 18 |
+
# 4. Run evaluation:
|
| 19 |
+
# docker compose run --rm opencodereview python eval_data/evaluate.py --max-prs 2
|
| 20 |
+
#
|
| 21 |
+
# Data persistence
|
| 22 |
+
# ----------------
|
| 23 |
+
# The vector store (ChromaDB) is persisted in a named volume so embeddings
|
| 24 |
+
# don't need to be rebuilt every run. The checkpoint database is ephemeral
|
| 25 |
+
# (cleaned up after each run by the app).
|
| 26 |
+
# =============================================================================
|
| 27 |
+
|
| 28 |
+
services:
|
| 29 |
+
opencodereview:
|
| 30 |
+
build: .
|
| 31 |
+
image: opencodereview:latest
|
| 32 |
+
entrypoint: ["python", "-m", "main"]
|
| 33 |
+
environment:
|
| 34 |
+
# AI provider keys
|
| 35 |
+
- GROQ_API_KEY=${GROQ_API_KEY:-}
|
| 36 |
+
- OPENCODEREVIEW_ANTHROPIC_KEY=${OPENCODEREVIEW_ANTHROPIC_KEY:-}
|
| 37 |
+
# GitHub
|
| 38 |
+
- GITHUB_TOKEN=${GITHUB_TOKEN:-}
|
| 39 |
+
# Language
|
| 40 |
+
- LANG=en_US.UTF-8
|
| 41 |
+
volumes:
|
| 42 |
+
# Persist vector store across runs
|
| 43 |
+
- opencodereview_vectors:/tmp/opencodereview_vectors
|
| 44 |
+
# Optionally mount config for keyring (useful on Linux)
|
| 45 |
+
# - ~/.local/share/keyring:/home/appuser/.local/share/keyring
|
| 46 |
+
profiles:
|
| 47 |
+
- cli
|
| 48 |
+
|
| 49 |
+
volumes:
|
| 50 |
+
opencodereview_vectors:
|
docker-entrypoint.sh
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# =============================================================================
|
| 3 |
+
# OpenCodeReview β Docker Entrypoint
|
| 4 |
+
# =============================================================================
|
| 5 |
+
# Runs as root to ensure the ChromaDB vector store directory is writable by
|
| 6 |
+
# the non-root appuser (uid 1000). Then drops privileges and execs the CMD.
|
| 7 |
+
#
|
| 8 |
+
# This fixes the "unable to open database file" error that occurs when a
|
| 9 |
+
# Docker named volume (owned by root) is mounted at /tmp/opencodereview_vectors
|
| 10 |
+
# and the app runs as a non-root user.
|
| 11 |
+
# =============================================================================
|
| 12 |
+
|
| 13 |
+
set -e
|
| 14 |
+
|
| 15 |
+
VECTOR_DIR="/tmp/opencodereview_vectors"
|
| 16 |
+
|
| 17 |
+
# Ensure the vector store directory exists and is writable by appuser
|
| 18 |
+
mkdir -p "$VECTOR_DIR"
|
| 19 |
+
chown -R appuser:appuser "$VECTOR_DIR"
|
| 20 |
+
|
| 21 |
+
# Drop privileges to appuser and execute the main command
|
| 22 |
+
exec su -s /bin/sh appuser -c "exec $*"
|
eval_data/eval_results.json
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[
|
| 2 |
+
{
|
| 3 |
+
"tp": 0,
|
| 4 |
+
"fp": 0,
|
| 5 |
+
"fn": 1,
|
| 6 |
+
"precision": 0.0,
|
| 7 |
+
"recall": 0.0,
|
| 8 |
+
"f1": 0.0,
|
| 9 |
+
"agent_findings": 0,
|
| 10 |
+
"human_comments": 1,
|
| 11 |
+
"id": "test_repo_test_1",
|
| 12 |
+
"repo": "demo-org/demo-repo",
|
| 13 |
+
"pr_number": 1,
|
| 14 |
+
"title": "Test PR for evaluation"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requires ground-truth dataset from fetcher.py)
|
| 7 |
+
python eval_data/evaluate.py
|
| 8 |
+
|
| 9 |
+
# Only process the first 2 PRs (quick smoke test)
|
| 10 |
+
python eval_data/evaluate.py --max-prs 2
|
| 11 |
+
|
| 12 |
+
# Show per-PR details (matched/unmatched findings)
|
| 13 |
+
python eval_data/evaluate.py --verbose
|
| 14 |
+
|
| 15 |
+
# Enable keyword-based semantic matching (bonus for keyword overlap)
|
| 16 |
+
python eval_data/evaluate.py --match-keywords
|
| 17 |
+
|
| 18 |
+
# Bypass the GITHUB_TOKEN guard (use with caution)
|
| 19 |
+
python eval_data/evaluate.py --force
|
| 20 |
+
|
| 21 |
+
Input
|
| 22 |
+
-----
|
| 23 |
+
``eval_data/prs.jsonl`` -- ground-truth dataset produced by ``fetcher.py``.
|
| 24 |
+
|
| 25 |
+
Output
|
| 26 |
+
------
|
| 27 |
+
``eval_data/eval_results.json`` -- per-PR and aggregate metrics.
|
| 28 |
+
|
| 29 |
+
Notes
|
| 30 |
+
-----
|
| 31 |
+
Human PR review comments don't carry explicit category labels, so
|
| 32 |
+
category matching is approximated via keyword overlap when
|
| 33 |
+
``--match-keywords`` is used.
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
from __future__ import annotations
|
| 37 |
+
|
| 38 |
+
import argparse
|
| 39 |
+
import json
|
| 40 |
+
import logging
|
| 41 |
+
import os
|
| 42 |
+
import re
|
| 43 |
+
import sys
|
| 44 |
+
import time
|
| 45 |
+
import uuid
|
| 46 |
+
from typing import Optional
|
| 47 |
+
|
| 48 |
+
from langgraph.types import Command
|
| 49 |
+
|
| 50 |
+
# Add project root to sys.path so we can import graph/state
|
| 51 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 52 |
+
|
| 53 |
+
from graph import build_graph
|
| 54 |
+
from state import ChangedFile, Finding
|
| 55 |
+
|
| 56 |
+
logger = logging.getLogger(__name__)
|
| 57 |
+
|
| 58 |
+
# --- Constants ---------------------------------------------------------------
|
| 59 |
+
|
| 60 |
+
LINE_TOLERANCE = 3
|
| 61 |
+
DATA_PATH = os.path.join(os.path.dirname(__file__), "prs.jsonl")
|
| 62 |
+
RESULTS_PATH = os.path.join(os.path.dirname(__file__), "eval_results.json")
|
| 63 |
+
|
| 64 |
+
# Common English stopwords (lightweight -- no dependency needed)
|
| 65 |
+
STOPWORDS: set[str] = {
|
| 66 |
+
"the", "a", "an", "this", "that", "these", "those", "it", "its",
|
| 67 |
+
"is", "are", "was", "were", "be", "been", "being", "have", "has",
|
| 68 |
+
"had", "do", "does", "did", "will", "would", "could", "should",
|
| 69 |
+
"may", "might", "shall", "can", "need", "not", "no", "nor",
|
| 70 |
+
"or", "and", "but", "if", "in", "on", "at", "to", "for", "of",
|
| 71 |
+
"by", "with", "from", "as", "into", "through", "during", "before",
|
| 72 |
+
"after", "above", "below", "between", "out", "off", "over", "under",
|
| 73 |
+
"again", "further", "then", "once", "here", "there", "when", "where",
|
| 74 |
+
"why", "how", "all", "each", "every", "both", "few", "more", "most",
|
| 75 |
+
"other", "some", "such", "only", "own", "same", "so", "than", "too",
|
| 76 |
+
"very", "just", "because", "also", "any", "get", "use", "using",
|
| 77 |
+
"used", "like", "make", "made", "take", "know", "see", "look",
|
| 78 |
+
"come", "want", "give", "tell", "work", "call", "try", "ask",
|
| 79 |
+
"feel", "become", "leave", "put", "mean", "keep", "let", "begin",
|
| 80 |
+
"seem", "help", "turn", "show", "play", "run", "move", "live",
|
| 81 |
+
"hold", "bring", "happen", "write", "provide", "sit", "stand",
|
| 82 |
+
"lose", "pay", "meet", "include", "continue", "set", "learn",
|
| 83 |
+
"change", "lead", "follow", "stop", "create", "read", "allow",
|
| 84 |
+
"add", "spend", "grow", "open", "win", "offer", "remember",
|
| 85 |
+
"consider", "appear", "buy", "wait", "serve", "send", "expect",
|
| 86 |
+
"build", "stay", "fall", "cut", "reach", "remain", "suggest",
|
| 87 |
+
"raise", "pass", "sell", "require", "report", "decide", "pull",
|
| 88 |
+
"push", "please", "thanks", "thank", "hi", "hello", "hey",
|
| 89 |
+
"one", "two", "way", "thing", "things", "much", "many",
|
| 90 |
+
"yes", "no", "sure", "right", "good", "great", "nice", "fine",
|
| 91 |
+
"well", "bad", "wrong", "new", "old", "first", "last", "next",
|
| 92 |
+
"previous", "still", "already", "even", "ever", "never", "always",
|
| 93 |
+
"really", "actually", "basically", "essentially", "probably",
|
| 94 |
+
"maybe", "perhaps", "quite", "pretty", "rather", "little",
|
| 95 |
+
"big", "large", "small", "long", "short", "high", "low",
|
| 96 |
+
"whole", "entire", "full", "empty", "part", "piece", "bit",
|
| 97 |
+
"type", "kind", "sort", "way", "case", "example", "instance",
|
| 98 |
+
"instead", "rather", "else", "otherwise", "well",
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
# --- Fuzzy Matching ----------------------------------------------------------
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def _extract_keywords(text: str) -> set[str]:
|
| 106 |
+
"""Extract meaningful keywords from a comment."""
|
| 107 |
+
words = re.findall(r"[a-zA-Z_][a-zA-Z0-9_]*", text.lower())
|
| 108 |
+
return {w for w in words if w not in STOPWORDS and len(w) > 2}
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def _lines_overlap(
|
| 112 |
+
f_start: int, f_end: int, gt_line: int, tolerance: int = LINE_TOLERANCE,
|
| 113 |
+
) -> bool:
|
| 114 |
+
"""Check if a ground-truth line falls within a finding's line range
|
| 115 |
+
(with tolerance)."""
|
| 116 |
+
lo = min(f_start, f_end) - tolerance
|
| 117 |
+
hi = max(f_start, f_end) + tolerance
|
| 118 |
+
return lo <= gt_line <= hi
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def _fuzzy_match(
|
| 122 |
+
finding: Finding,
|
| 123 |
+
ground_truth: list[dict],
|
| 124 |
+
already_matched: set[int],
|
| 125 |
+
use_keywords: bool = False,
|
| 126 |
+
) -> Optional[int]:
|
| 127 |
+
"""Find the best ground-truth comment that matches this agent finding.
|
| 128 |
+
|
| 129 |
+
Matching criteria (in order):
|
| 130 |
+
1. File path (exact match)
|
| 131 |
+
2. Line proximity (within +/-LINE_TOLERANCE)
|
| 132 |
+
3. Keyword overlap bonus (optional, via --match-keywords)
|
| 133 |
+
|
| 134 |
+
Returns the index of the best match, or None.
|
| 135 |
+
"""
|
| 136 |
+
best_idx: Optional[int] = None
|
| 137 |
+
best_score = -1.0
|
| 138 |
+
|
| 139 |
+
for i, gt in enumerate(ground_truth):
|
| 140 |
+
if i in already_matched:
|
| 141 |
+
continue
|
| 142 |
+
|
| 143 |
+
# File must match (exact path)
|
| 144 |
+
if finding.file_path != gt.get("file_path", ""):
|
| 145 |
+
continue
|
| 146 |
+
|
| 147 |
+
# Line proximity
|
| 148 |
+
gt_line = gt.get("line", 0)
|
| 149 |
+
if not _lines_overlap(finding.line_start, finding.line_end, gt_line):
|
| 150 |
+
continue
|
| 151 |
+
|
| 152 |
+
# Base score: line proximity (closer = better)
|
| 153 |
+
line_distance = min(
|
| 154 |
+
abs(finding.line_start - gt_line),
|
| 155 |
+
abs(finding.line_end - gt_line),
|
| 156 |
+
)
|
| 157 |
+
score = 1.0 - (line_distance / (LINE_TOLERANCE + 1))
|
| 158 |
+
assert 0.0 <= score <= 1.0
|
| 159 |
+
|
| 160 |
+
# Keyword overlap bonus (optional)
|
| 161 |
+
if use_keywords:
|
| 162 |
+
f_kw = _extract_keywords(finding.comment)
|
| 163 |
+
g_kw = _extract_keywords(gt.get("comment", ""))
|
| 164 |
+
if g_kw:
|
| 165 |
+
overlap = len(f_kw & g_kw) / len(g_kw)
|
| 166 |
+
score += overlap * 0.5 # up to 0.5 bonus
|
| 167 |
+
|
| 168 |
+
if score > best_score:
|
| 169 |
+
best_score = score
|
| 170 |
+
best_idx = i
|
| 171 |
+
|
| 172 |
+
return best_idx
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
# --- Graph Runner ------------------------------------------------------------
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def _run_graph_for_pr(
|
| 179 |
+
entry: dict, graph,
|
| 180 |
+
) -> tuple[list[Finding], Optional[dict]]:
|
| 181 |
+
"""Run the full OpenCodeReview graph on a single PR.
|
| 182 |
+
|
| 183 |
+
Returns ``(final_findings, verdict_dict_or_None)``.
|
| 184 |
+
"""
|
| 185 |
+
thread_id = str(uuid.uuid4())
|
| 186 |
+
config = {"configurable": {"thread_id": f"eval-{thread_id}"}}
|
| 187 |
+
|
| 188 |
+
# Build initial state from pre-fetched data to avoid API calls
|
| 189 |
+
changed_files = [
|
| 190 |
+
ChangedFile(**cf) for cf in entry.get("changed_files", [])
|
| 191 |
+
]
|
| 192 |
+
initial_state = {
|
| 193 |
+
"repo": entry["repo"],
|
| 194 |
+
"pr_number": entry["pr_number"],
|
| 195 |
+
"diff": entry.get("diff", ""),
|
| 196 |
+
"changed_files": changed_files,
|
| 197 |
+
}
|
| 198 |
+
|
| 199 |
+
# Run -- the graph will pause at human_approval (interrupt)
|
| 200 |
+
try:
|
| 201 |
+
list(graph.stream(initial_state, config))
|
| 202 |
+
except Exception as exc:
|
| 203 |
+
logger.warning(" Graph stream error: %s", exc)
|
| 204 |
+
|
| 205 |
+
state = graph.get_state(config)
|
| 206 |
+
tasks = state.tasks
|
| 207 |
+
values = state.values
|
| 208 |
+
|
| 209 |
+
if not tasks:
|
| 210 |
+
# Graph completed without interrupt -- no findings to review
|
| 211 |
+
return values.get("final_findings", []), values.get("verdict")
|
| 212 |
+
|
| 213 |
+
# Auto-approve to continue through the executor
|
| 214 |
+
try:
|
| 215 |
+
graph.invoke(Command(resume={"action": "approve"}), config)
|
| 216 |
+
except Exception as exc:
|
| 217 |
+
logger.warning(" Resume error: %s", exc)
|
| 218 |
+
return values.get("final_findings", []), values.get("verdict")
|
| 219 |
+
|
| 220 |
+
final_state = graph.get_state(config)
|
| 221 |
+
return (
|
| 222 |
+
final_state.values.get("final_findings", []),
|
| 223 |
+
final_state.values.get("verdict"),
|
| 224 |
+
)
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
# --- Metrics -----------------------------------------------------------------
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def _compute_metrics(
|
| 231 |
+
findings: list[Finding],
|
| 232 |
+
ground_truth: list[dict],
|
| 233 |
+
use_keywords: bool = False,
|
| 234 |
+
) -> dict:
|
| 235 |
+
"""Compute TP / FP / FN and derived metrics."""
|
| 236 |
+
matched: set[int] = set()
|
| 237 |
+
tp = 0
|
| 238 |
+
fp = 0
|
| 239 |
+
|
| 240 |
+
for f in findings:
|
| 241 |
+
match_idx = _fuzzy_match(f, ground_truth, matched, use_keywords)
|
| 242 |
+
if match_idx is not None:
|
| 243 |
+
tp += 1
|
| 244 |
+
matched.add(match_idx)
|
| 245 |
+
else:
|
| 246 |
+
fp += 1
|
| 247 |
+
|
| 248 |
+
fn = len(ground_truth) - len(matched)
|
| 249 |
+
|
| 250 |
+
precision = tp / (tp + fp) if (tp + fp) > 0 else 0.0
|
| 251 |
+
recall = tp / (tp + fn) if (tp + fn) > 0 else 0.0
|
| 252 |
+
f1 = (
|
| 253 |
+
2 * precision * recall / (precision + recall)
|
| 254 |
+
if (precision + recall) > 0
|
| 255 |
+
else 0.0
|
| 256 |
+
)
|
| 257 |
+
|
| 258 |
+
return {
|
| 259 |
+
"tp": tp,
|
| 260 |
+
"fp": fp,
|
| 261 |
+
"fn": fn,
|
| 262 |
+
"precision": round(precision, 3),
|
| 263 |
+
"recall": round(recall, 3),
|
| 264 |
+
"f1": round(f1, 3),
|
| 265 |
+
"agent_findings": len(findings),
|
| 266 |
+
"human_comments": len(ground_truth),
|
| 267 |
+
}
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
# --- Output ------------------------------------------------------------------
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
def _print_results(results: list[dict]) -> None:
|
| 274 |
+
"""Print a formatted evaluation results table."""
|
| 275 |
+
print()
|
| 276 |
+
print("=" * 100)
|
| 277 |
+
hdr = f"{'PR':<40} {'Agent':>6} {'Human':>6} {'TP':>4} {'FP':>4} {'FN':>4}"
|
| 278 |
+
hdr += f" {'Prec':>6} {'Recall':>6} {'F1':>6}"
|
| 279 |
+
print(hdr)
|
| 280 |
+
print("-" * 100)
|
| 281 |
+
|
| 282 |
+
for r in results:
|
| 283 |
+
label = f"{r['repo']}#{r['pr_number']}"
|
| 284 |
+
print(
|
| 285 |
+
f"{label:<40} {r['agent_findings']:>6} {r['human_comments']:>6} "
|
| 286 |
+
f"{r['tp']:>4} {r['fp']:>4} {r['fn']:>4} "
|
| 287 |
+
f"{r['precision']:>6.1%} {r['recall']:>6.1%} {r['f1']:>6.1%}"
|
| 288 |
+
)
|
| 289 |
+
|
| 290 |
+
print("-" * 100)
|
| 291 |
+
|
| 292 |
+
# Micro-average (pool all TP/FP/FN)
|
| 293 |
+
total_tp = sum(r["tp"] for r in results)
|
| 294 |
+
total_fp = sum(r["fp"] for r in results)
|
| 295 |
+
total_fn = sum(r["fn"] for r in results)
|
| 296 |
+
total_agent = sum(r["agent_findings"] for r in results)
|
| 297 |
+
total_human = sum(r["human_comments"] for r in results)
|
| 298 |
+
|
| 299 |
+
micro_p = total_tp / (total_tp + total_fp) if (total_tp + total_fp) > 0 else 0.0
|
| 300 |
+
micro_r = total_tp / (total_tp + total_fn) if (total_tp + total_fn) > 0 else 0.0
|
| 301 |
+
micro_f = (
|
| 302 |
+
2 * micro_p * micro_r / (micro_p + micro_r)
|
| 303 |
+
if (micro_p + micro_r) > 0
|
| 304 |
+
else 0.0
|
| 305 |
+
)
|
| 306 |
+
|
| 307 |
+
# Macro-average (average per-PR metrics, excluding PRs with no findings AND no comments)
|
| 308 |
+
nonzero = [r for r in results if r["agent_findings"] > 0 or r["human_comments"] > 0]
|
| 309 |
+
macro_p = sum(r["precision"] for r in nonzero) / len(nonzero) if nonzero else 0.0
|
| 310 |
+
macro_r = sum(r["recall"] for r in nonzero) / len(nonzero) if nonzero else 0.0
|
| 311 |
+
macro_f = sum(r["f1"] for r in nonzero) / len(nonzero) if nonzero else 0.0
|
| 312 |
+
|
| 313 |
+
print(
|
| 314 |
+
f"{'MICRO AVG':<40} {total_agent:>6} {total_human:>6} "
|
| 315 |
+
f"{total_tp:>4} {total_fp:>4} {total_fn:>4} "
|
| 316 |
+
f"{micro_p:>6.1%} {micro_r:>6.1%} {micro_f:>6.1%}"
|
| 317 |
+
)
|
| 318 |
+
print(
|
| 319 |
+
f"{'MACRO AVG':<40} {' ':>6} {' ':>6} "
|
| 320 |
+
f"{' ':>4} {' ':>4} {' ':>4} "
|
| 321 |
+
f"{macro_p:>6.1%} {macro_r:>6.1%} {macro_f:>6.1%}"
|
| 322 |
+
)
|
| 323 |
+
print("=" * 100)
|
| 324 |
+
print()
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
# --- CLI ---------------------------------------------------------------------
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
def main() -> None:
|
| 331 |
+
parser = argparse.ArgumentParser(
|
| 332 |
+
description="Evaluate OpenCodeReview against ground-truth human reviews",
|
| 333 |
+
)
|
| 334 |
+
parser.add_argument(
|
| 335 |
+
"--data", default=DATA_PATH,
|
| 336 |
+
help="Path to JSONL dataset (default: %(default)s)",
|
| 337 |
+
)
|
| 338 |
+
parser.add_argument(
|
| 339 |
+
"--verbose", action="store_true",
|
| 340 |
+
help="Show per-PR details (matched / unmatched findings)",
|
| 341 |
+
)
|
| 342 |
+
parser.add_argument(
|
| 343 |
+
"--match-keywords", action="store_true",
|
| 344 |
+
help="Enable keyword-based semantic matching bonus "
|
| 345 |
+
"(human comments don't carry explicit category labels, so "
|
| 346 |
+
"keyword overlap approximates category matching)",
|
| 347 |
+
)
|
| 348 |
+
parser.add_argument(
|
| 349 |
+
"--skip", nargs="*", default=[],
|
| 350 |
+
help="IDs of PRs to skip (space-separated)",
|
| 351 |
+
)
|
| 352 |
+
parser.add_argument(
|
| 353 |
+
"--max-prs", type=int, default=None,
|
| 354 |
+
help="Max PRs to process (for quick smoke tests)",
|
| 355 |
+
)
|
| 356 |
+
parser.add_argument(
|
| 357 |
+
"--force", action="store_true",
|
| 358 |
+
help="Bypass GITHUB_TOKEN guard and proceed with posting "
|
| 359 |
+
"(use with caution -- comments WILL be posted to real PRs)",
|
| 360 |
+
)
|
| 361 |
+
args = parser.parse_args()
|
| 362 |
+
|
| 363 |
+
logging.basicConfig(
|
| 364 |
+
level=logging.WARNING,
|
| 365 |
+
format="%(asctime)s [%(levelname)s] - %(message)s",
|
| 366 |
+
)
|
| 367 |
+
|
| 368 |
+
# -- Guard: GITHUB_TOKEN -> accidental posting --------------------------
|
| 369 |
+
github_token_warning = (
|
| 370 |
+
"WARNING: GITHUB_TOKEN is set! The executor will POST comments "
|
| 371 |
+
"to real GitHub PRs.\n"
|
| 372 |
+
" Unset it for safe evaluation:\n"
|
| 373 |
+
" unset GITHUB_TOKEN\n"
|
| 374 |
+
" Pass --force to acknowledge and proceed anyway."
|
| 375 |
+
)
|
| 376 |
+
if "GITHUB_TOKEN" in os.environ and not args.force:
|
| 377 |
+
print(f"\n{'=' * 60}\n {github_token_warning}\n{'=' * 60}\n", file=sys.stderr)
|
| 378 |
+
sys.exit(1)
|
| 379 |
+
|
| 380 |
+
# --- Load dataset ---
|
| 381 |
+
if not os.path.exists(args.data):
|
| 382 |
+
print(
|
| 383 |
+
f"Dataset not found at {args.data}. Run fetcher.py first:\n"
|
| 384 |
+
f" python eval_data/fetcher.py\n"
|
| 385 |
+
f"Note: fetcher.py requires GITHUB_TOKEN for API access.\n",
|
| 386 |
+
file=sys.stderr,
|
| 387 |
+
)
|
| 388 |
+
sys.exit(1)
|
| 389 |
+
|
| 390 |
+
with open(args.data, "r", encoding="utf-8") as f:
|
| 391 |
+
entries = [json.loads(line) for line in f if line.strip()]
|
| 392 |
+
|
| 393 |
+
logger.info("Loaded %d PRs from %s", len(entries), args.data)
|
| 394 |
+
|
| 395 |
+
if args.max_prs:
|
| 396 |
+
entries = entries[: args.max_prs]
|
| 397 |
+
|
| 398 |
+
# --- Build graph ---
|
| 399 |
+
print("Building graph ... ", end="", flush=True)
|
| 400 |
+
graph = build_graph(":memory:")
|
| 401 |
+
print("OK")
|
| 402 |
+
|
| 403 |
+
# --- Evaluate each PR ---
|
| 404 |
+
results: list[dict] = []
|
| 405 |
+
|
| 406 |
+
for idx, entry in enumerate(entries, 1):
|
| 407 |
+
pr_id = entry["id"]
|
| 408 |
+
if pr_id in args.skip:
|
| 409 |
+
logger.info("[%d/%d] Skipping %s", idx, len(entries), pr_id)
|
| 410 |
+
continue
|
| 411 |
+
|
| 412 |
+
print(
|
| 413 |
+
f"[{idx}/{len(entries)}] {entry['repo']}#{entry['pr_number']} "
|
| 414 |
+
f"-- {entry.get('title', '')[:50]} ... ",
|
| 415 |
+
end="", flush=True,
|
| 416 |
+
)
|
| 417 |
+
|
| 418 |
+
try:
|
| 419 |
+
findings, verdict = _run_graph_for_pr(entry, graph)
|
| 420 |
+
except Exception as exc:
|
| 421 |
+
print(f"ERROR: {exc}")
|
| 422 |
+
continue
|
| 423 |
+
|
| 424 |
+
metrics = _compute_metrics(
|
| 425 |
+
findings, entry["ground_truth"],
|
| 426 |
+
use_keywords=args.match_keywords,
|
| 427 |
+
)
|
| 428 |
+
metrics.update({
|
| 429 |
+
"id": pr_id,
|
| 430 |
+
"repo": entry["repo"],
|
| 431 |
+
"pr_number": entry["pr_number"],
|
| 432 |
+
"title": entry.get("title", ""),
|
| 433 |
+
})
|
| 434 |
+
results.append(metrics)
|
| 435 |
+
|
| 436 |
+
print(
|
| 437 |
+
f"{metrics['agent_findings']} findings vs "
|
| 438 |
+
f"{metrics['human_comments']} human "
|
| 439 |
+
f"(P={metrics['precision']:.0%} R={metrics['recall']:.0%})",
|
| 440 |
+
)
|
| 441 |
+
|
| 442 |
+
if args.verbose:
|
| 443 |
+
_print_verbose(entry, findings, metrics, use_keywords=args.match_keywords)
|
| 444 |
+
|
| 445 |
+
# --- Print results ---
|
| 446 |
+
_print_results(results)
|
| 447 |
+
|
| 448 |
+
# --- Save ---
|
| 449 |
+
with open(RESULTS_PATH, "w", encoding="utf-8") as f:
|
| 450 |
+
json.dump(results, f, indent=2, ensure_ascii=False)
|
| 451 |
+
print(f"Detailed results saved to {RESULTS_PATH}")
|
| 452 |
+
|
| 453 |
+
|
| 454 |
+
def _print_verbose(entry: dict, findings: list[Finding], metrics: dict, use_keywords: bool = False) -> None:
|
| 455 |
+
"""Print per-finding details for a single PR."""
|
| 456 |
+
matched_gt: set[int] = set()
|
| 457 |
+
|
| 458 |
+
print(f"\n {'=' * 60}")
|
| 459 |
+
print(f" Agent findings ({metrics['agent_findings']}):")
|
| 460 |
+
for f in findings:
|
| 461 |
+
match_idx = _fuzzy_match(f, entry["ground_truth"], matched_gt, use_keywords)
|
| 462 |
+
flag = "[MATCHED]" if match_idx is not None else "[MISSED]"
|
| 463 |
+
if match_idx is not None:
|
| 464 |
+
matched_gt.add(match_idx)
|
| 465 |
+
print(
|
| 466 |
+
f" {flag} [{f.severity.value}] {f.file_path}:{f.line_start}"
|
| 467 |
+
f"-{f.line_end} - {f.comment[:100]}",
|
| 468 |
+
)
|
| 469 |
+
|
| 470 |
+
print(f" Human ground-truth ({metrics['human_comments']}):")
|
| 471 |
+
for i, gt in enumerate(entry["ground_truth"]):
|
| 472 |
+
flag = " [HIT]" if i in matched_gt else " [MISS]"
|
| 473 |
+
print(
|
| 474 |
+
f" {flag} {gt['file_path']}:{gt['line']} - "
|
| 475 |
+
f"{gt['comment'][:100]}",
|
| 476 |
+
)
|
| 477 |
+
print()
|
| 478 |
+
|
| 479 |
+
|
| 480 |
+
if __name__ == "__main__":
|
| 481 |
+
main()
|
eval_data/fetcher.py
ADDED
|
@@ -0,0 +1,287 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Fetch 15 real past PRs with human-written review comments from popular
|
| 3 |
+
open-source Python repos for use as ground-truth evaluation data.
|
| 4 |
+
|
| 5 |
+
Requires a GITHUB_TOKEN environment variable for higher API rate limits.
|
| 6 |
+
|
| 7 |
+
Output: ``eval_data/prs.jsonl`` (one JSON line per PR with pre-fetched diff,
|
| 8 |
+
``changed_files``, and ``ground_truth`` review comments).
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import json
|
| 14 |
+
import logging
|
| 15 |
+
import os
|
| 16 |
+
import sys
|
| 17 |
+
import time
|
| 18 |
+
from typing import Any, Optional
|
| 19 |
+
|
| 20 |
+
import requests
|
| 21 |
+
|
| 22 |
+
logging.basicConfig(
|
| 23 |
+
level=logging.INFO,
|
| 24 |
+
format="%(asctime)s [%(levelname)s] %(name)s - %(message)s",
|
| 25 |
+
)
|
| 26 |
+
logger = logging.getLogger(__name__)
|
| 27 |
+
|
| 28 |
+
GITHUB_API_BASE = "https://api.github.com"
|
| 29 |
+
RAW_CONTENT_BASE = "https://raw.githubusercontent.com"
|
| 30 |
+
|
| 31 |
+
# Popular Python repos with active PR reviews β we will fetch up to 3
|
| 32 |
+
# merged PRs per repo that bear review comments.
|
| 33 |
+
REPOS = [
|
| 34 |
+
"psf/requests",
|
| 35 |
+
"pydantic/pydantic",
|
| 36 |
+
"fastapi/fastapi",
|
| 37 |
+
"django/django",
|
| 38 |
+
"pallets/flask",
|
| 39 |
+
]
|
| 40 |
+
|
| 41 |
+
PRS_PER_REPO = 3
|
| 42 |
+
TOTAL_TARGET = 15
|
| 43 |
+
OUTPUT_PATH = os.path.join(os.path.dirname(__file__), "prs.jsonl")
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
# βββ Helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _headers() -> dict[str, str]:
|
| 50 |
+
headers: dict[str, str] = {
|
| 51 |
+
"Accept": "application/vnd.github.v3+json",
|
| 52 |
+
"User-Agent": "OpenCodeReviewEval/1.0",
|
| 53 |
+
}
|
| 54 |
+
token = os.environ.get("GITHUB_TOKEN", "").strip()
|
| 55 |
+
if token:
|
| 56 |
+
headers["Authorization"] = f"Bearer {token}"
|
| 57 |
+
return headers
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _fetch_all_pages(url: str, headers: dict) -> list[dict]:
|
| 61 |
+
"""Follow GitHub Link-header pagination."""
|
| 62 |
+
items: list[dict] = []
|
| 63 |
+
while url:
|
| 64 |
+
try:
|
| 65 |
+
resp = requests.get(url, headers=headers, timeout=30)
|
| 66 |
+
if resp.status_code != 200:
|
| 67 |
+
logger.warning("HTTP %s for %s", resp.status_code, url)
|
| 68 |
+
break
|
| 69 |
+
items.extend(resp.json())
|
| 70 |
+
except requests.RequestException as exc:
|
| 71 |
+
logger.warning("Request failed: %s", exc)
|
| 72 |
+
break
|
| 73 |
+
|
| 74 |
+
link = resp.headers.get("Link", "")
|
| 75 |
+
next_url: Optional[str] = None
|
| 76 |
+
for part in link.split(","):
|
| 77 |
+
part = part.strip()
|
| 78 |
+
if 'rel="next"' in part:
|
| 79 |
+
start = part.index("<") + 1
|
| 80 |
+
end = part.index(">")
|
| 81 |
+
next_url = part[start:end]
|
| 82 |
+
break
|
| 83 |
+
url = next_url
|
| 84 |
+
return items
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def _find_prs(repo: str, headers: dict, max_count: int) -> list[dict]:
|
| 88 |
+
"""Find merged PRs that have at least one review comment."""
|
| 89 |
+
url = (
|
| 90 |
+
f"{GITHUB_API_BASE}/repos/{repo}/pulls?"
|
| 91 |
+
f"state=closed&sort=updated&direction=desc&per_page=100"
|
| 92 |
+
)
|
| 93 |
+
all_prs = _fetch_all_pages(url, headers)
|
| 94 |
+
|
| 95 |
+
candidates = [
|
| 96 |
+
pr for pr in all_prs
|
| 97 |
+
if pr.get("merged_at") and pr.get("review_comments", 0) > 0
|
| 98 |
+
]
|
| 99 |
+
|
| 100 |
+
logger.info(
|
| 101 |
+
" Found %d candidate PRs in %s (from %s total, %s merged)",
|
| 102 |
+
len(candidates), repo, len(all_prs),
|
| 103 |
+
sum(1 for p in all_prs if p.get("merged_at")),
|
| 104 |
+
)
|
| 105 |
+
return candidates[:max_count]
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def _fetch_review_comments(
|
| 109 |
+
owner: str, repo: str, pr_number: int, headers: dict,
|
| 110 |
+
) -> list[dict]:
|
| 111 |
+
url = (
|
| 112 |
+
f"{GITHUB_API_BASE}/repos/{owner}/{repo}/pulls"
|
| 113 |
+
f"/{pr_number}/comments"
|
| 114 |
+
)
|
| 115 |
+
return _fetch_all_pages(url, headers)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def _fetch_changed_files(
|
| 119 |
+
owner: str, repo: str, pr_number: int, headers: dict,
|
| 120 |
+
) -> list[dict]:
|
| 121 |
+
url = (
|
| 122 |
+
f"{GITHUB_API_BASE}/repos/{owner}/{repo}/pulls"
|
| 123 |
+
f"/{pr_number}/files"
|
| 124 |
+
)
|
| 125 |
+
return _fetch_all_pages(url, headers)
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def _fetch_file_content(owner: str, repo: str, ref: str, path: str) -> str:
|
| 129 |
+
url = f"{RAW_CONTENT_BASE}/{owner}/{repo}/{ref}/{path}"
|
| 130 |
+
try:
|
| 131 |
+
resp = requests.get(url, timeout=30)
|
| 132 |
+
if resp.status_code == 200:
|
| 133 |
+
return resp.text
|
| 134 |
+
return ""
|
| 135 |
+
except requests.RequestException:
|
| 136 |
+
return ""
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def _build_ground_truth(review_comments: list[dict]) -> list[dict]:
|
| 140 |
+
"""Convert GitHub PR review comments to the ground-truth schema."""
|
| 141 |
+
gt = []
|
| 142 |
+
for rc in review_comments:
|
| 143 |
+
# Use the line number from the diff; fall back to the original line.
|
| 144 |
+
line = rc.get("line") or rc.get("original_line") or 0
|
| 145 |
+
gt.append({
|
| 146 |
+
"file_path": rc.get("path", ""),
|
| 147 |
+
"line": line,
|
| 148 |
+
"comment": rc.get("body", ""),
|
| 149 |
+
"reviewer": rc.get("user", {}).get("login", "unknown"),
|
| 150 |
+
"created_at": rc.get("created_at", ""),
|
| 151 |
+
})
|
| 152 |
+
return gt
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
# βββ Main ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def main() -> None:
|
| 159 |
+
headers = _headers()
|
| 160 |
+
entries: list[dict] = []
|
| 161 |
+
|
| 162 |
+
if "GITHUB_TOKEN" not in os.environ:
|
| 163 |
+
logger.error(
|
| 164 |
+
"GITHUB_TOKEN is not set! The GitHub API enforces very "
|
| 165 |
+
"restrictive rate limits (60 req/hr) for unauthenticated "
|
| 166 |
+
"requests β the fetcher WILL FAIL with HTTP 403 errors.\n"
|
| 167 |
+
" Set the environment variable and re-run:\n"
|
| 168 |
+
" export GITHUB_TOKEN=ghp_..."
|
| 169 |
+
)
|
| 170 |
+
logger.info("Exiting β no GITHUB_TOKEN set")
|
| 171 |
+
sys.exit(1)
|
| 172 |
+
|
| 173 |
+
for repo in REPOS:
|
| 174 |
+
if len(entries) >= TOTAL_TARGET:
|
| 175 |
+
break
|
| 176 |
+
|
| 177 |
+
owner, repo_name = repo.split("/")
|
| 178 |
+
prs = _find_prs(repo, headers, PRS_PER_REPO)
|
| 179 |
+
|
| 180 |
+
for pr in prs:
|
| 181 |
+
if len(entries) >= TOTAL_TARGET:
|
| 182 |
+
break
|
| 183 |
+
|
| 184 |
+
pr_number = pr["number"]
|
| 185 |
+
title = pr.get("title", "") or "(no title)"
|
| 186 |
+
head_sha = pr["head"]["sha"]
|
| 187 |
+
|
| 188 |
+
logger.info(
|
| 189 |
+
"Fetching %s/%s#%d β %s",
|
| 190 |
+
owner, repo_name, pr_number, title[:80],
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
# --- Diff ---
|
| 194 |
+
diff_headers = {**headers, "Accept": "application/vnd.github.v3.diff"}
|
| 195 |
+
try:
|
| 196 |
+
diff_resp = requests.get(
|
| 197 |
+
pr["url"], headers=diff_headers, timeout=30,
|
| 198 |
+
)
|
| 199 |
+
diff_text = diff_resp.text if diff_resp.status_code == 200 else ""
|
| 200 |
+
except requests.RequestException as exc:
|
| 201 |
+
logger.warning(" Diff fetch failed: %s", exc)
|
| 202 |
+
diff_text = ""
|
| 203 |
+
|
| 204 |
+
# --- Changed files with content ---
|
| 205 |
+
files_data = _fetch_changed_files(owner, repo_name, pr_number, headers)
|
| 206 |
+
changed_files: list[dict] = []
|
| 207 |
+
for fd in files_data:
|
| 208 |
+
file_path = fd["filename"]
|
| 209 |
+
status = fd["status"]
|
| 210 |
+
patch = fd.get("patch") or ""
|
| 211 |
+
|
| 212 |
+
# Fetch file content from the head commit
|
| 213 |
+
content = _fetch_file_content(owner, repo_name, head_sha, file_path)
|
| 214 |
+
if status == "removed":
|
| 215 |
+
content = ""
|
| 216 |
+
|
| 217 |
+
# For fork PRs, try the head repo (different from base)
|
| 218 |
+
if not content:
|
| 219 |
+
head_full = pr["head"]["repo"].get("full_name", "")
|
| 220 |
+
if head_full and head_full != repo:
|
| 221 |
+
h_owner, h_repo = head_full.split("/", 1)
|
| 222 |
+
content = _fetch_file_content(
|
| 223 |
+
h_owner, h_repo, head_sha, file_path,
|
| 224 |
+
)
|
| 225 |
+
|
| 226 |
+
changed_files.append({
|
| 227 |
+
"path": file_path,
|
| 228 |
+
"status": status,
|
| 229 |
+
"content": content,
|
| 230 |
+
"diff_hunk": patch,
|
| 231 |
+
})
|
| 232 |
+
|
| 233 |
+
# --- Review comments (ground truth) ---
|
| 234 |
+
review_comments = _fetch_review_comments(
|
| 235 |
+
owner, repo_name, pr_number, headers,
|
| 236 |
+
)
|
| 237 |
+
ground_truth = _build_ground_truth(review_comments)
|
| 238 |
+
|
| 239 |
+
if not ground_truth:
|
| 240 |
+
logger.info(" Skipping β no review comments found")
|
| 241 |
+
continue
|
| 242 |
+
|
| 243 |
+
entry: dict[str, Any] = {
|
| 244 |
+
"id": f"{repo.replace('/', '_')}_{pr_number}",
|
| 245 |
+
"repo": repo,
|
| 246 |
+
"pr_number": pr_number,
|
| 247 |
+
"title": title,
|
| 248 |
+
"diff": diff_text,
|
| 249 |
+
"changed_files": changed_files,
|
| 250 |
+
"ground_truth": ground_truth,
|
| 251 |
+
}
|
| 252 |
+
entries.append(entry)
|
| 253 |
+
|
| 254 |
+
logger.info(
|
| 255 |
+
" -> %d files, %d review comments, diff=%s",
|
| 256 |
+
len(changed_files), len(ground_truth),
|
| 257 |
+
f"{len(diff_text)} B" if diff_text else "empty",
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
# Polite rate-limiting
|
| 261 |
+
time.sleep(0.5)
|
| 262 |
+
|
| 263 |
+
# --- Write output ---
|
| 264 |
+
os.makedirs(os.path.dirname(OUTPUT_PATH), exist_ok=True)
|
| 265 |
+
with open(OUTPUT_PATH, "w", encoding="utf-8") as f:
|
| 266 |
+
for entry in entries:
|
| 267 |
+
f.write(json.dumps(entry, ensure_ascii=False) + "\n")
|
| 268 |
+
|
| 269 |
+
total_gt = sum(len(e["ground_truth"]) for e in entries)
|
| 270 |
+
logger.info(
|
| 271 |
+
"Wrote %d PRs to %s β %d ground-truth comments (avg %.1f/PR)",
|
| 272 |
+
len(entries), OUTPUT_PATH, total_gt,
|
| 273 |
+
total_gt / len(entries) if entries else 0,
|
| 274 |
+
)
|
| 275 |
+
|
| 276 |
+
# Summary line for easy terminal inspection
|
| 277 |
+
print(f"\n{'='*70}")
|
| 278 |
+
print(f" Dataset: {OUTPUT_PATH}")
|
| 279 |
+
print(f" PRs: {len(entries)}")
|
| 280 |
+
print(f" Ground-truth comments: {total_gt}")
|
| 281 |
+
for e in entries:
|
| 282 |
+
print(f" {e['id']:40s} {len(e['ground_truth']):3d} comments {e['title'][:50]}")
|
| 283 |
+
print(f"{'='*70}")
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
if __name__ == "__main__":
|
| 287 |
+
main()
|
eval_data/prs.jsonl
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"id": "test_repo_test_1", "repo": "demo-org/demo-repo", "pr_number": 1, "title": "Test PR for evaluation", "diff": "diff --git a/src/auth.py b/src/auth.py\nindex abc123..def456 100644\n--- a/src/auth.py\n+++ b/src/auth.py\n@@ -42,7 +42,9 @@ def login(username, password):\n user = db.get_user(username)\n- if user.password == password:\n+ if constant_time_compare(password, user.password):\n return create_session(user)\n return None\n", "changed_files": [{"path": "src/auth.py", "status": "modified", "content": "def login(username, password):\n user = db.get_user(username)\n if constant_time_compare(password, user.password):\n return create_session(user)\n return None\n", "diff_hunk": "@@ -42,7 +42,9 @@ def login(username, password): ..."}], "ground_truth": [{"file_path": "src/auth.py", "line": 42, "comment": "Should use constant-time comparison for passwords", "reviewer": "test-human"}]}
|
github_client.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Shared GitHub API client with automatic token resolution and 401 resilience.
|
| 3 |
+
|
| 4 |
+
Usage
|
| 5 |
+
-----
|
| 6 |
+
from github_client import GitHubSession, resolve_token, guard_401
|
| 7 |
+
|
| 8 |
+
# Preferred: use the session for all API calls
|
| 9 |
+
session = GitHubSession()
|
| 10 |
+
resp = session.get("https://api.github.com/repos/psf/requests")
|
| 11 |
+
|
| 12 |
+
# Decorator for standalone functions
|
| 13 |
+
@guard_401
|
| 14 |
+
def my_api_call():
|
| 15 |
+
...
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
import functools
|
| 21 |
+
import logging
|
| 22 |
+
import os
|
| 23 |
+
from typing import Optional
|
| 24 |
+
|
| 25 |
+
import keyring
|
| 26 |
+
import requests
|
| 27 |
+
|
| 28 |
+
logger = logging.getLogger(__name__)
|
| 29 |
+
|
| 30 |
+
SERVICE_NAME = "opencodereview"
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
# βββ Exceptions ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class TokenRevokedError(Exception):
|
| 37 |
+
"""Raised when a GitHub API call returns 401 (token invalid or revoked)."""
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
# βββ Token resolution βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def resolve_token() -> Optional[str]:
|
| 44 |
+
"""Return a GitHub token from:
|
| 45 |
+
|
| 46 |
+
1. The system keyring (set via ``opencodereview auth login``)
|
| 47 |
+
2. The ``GITHUB_TOKEN`` environment variable
|
| 48 |
+
|
| 49 |
+
Returns ``None`` if neither source has a token, so callers can fall back
|
| 50 |
+
gracefully (e.g., dry-run mode in the executor).
|
| 51 |
+
"""
|
| 52 |
+
# Try keyring first (auth login stores here)
|
| 53 |
+
try:
|
| 54 |
+
token = keyring.get_password(SERVICE_NAME, "github_token")
|
| 55 |
+
if token:
|
| 56 |
+
return token
|
| 57 |
+
except Exception:
|
| 58 |
+
pass # keyring back-end unavailable (headless CI, etc.)
|
| 59 |
+
|
| 60 |
+
# Fall back to env var
|
| 61 |
+
token = os.environ.get("GITHUB_TOKEN")
|
| 62 |
+
return token.strip() if token else None
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
# βββ 401 decorator ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def guard_401(func):
|
| 69 |
+
"""Decorator: catch 401 responses from GitHub API calls and raise
|
| 70 |
+
:class:`TokenRevokedError` with a helpful message.
|
| 71 |
+
|
| 72 |
+
Use this on any standalone function that makes GitHub API calls and
|
| 73 |
+
calls ``raise_for_status()``.
|
| 74 |
+
|
| 75 |
+
For functions that use :class:`GitHubSession` the 401 handling happens
|
| 76 |
+
automatically β no decorator needed.
|
| 77 |
+
"""
|
| 78 |
+
@functools.wraps(func)
|
| 79 |
+
def wrapper(*args, **kwargs):
|
| 80 |
+
try:
|
| 81 |
+
return func(*args, **kwargs)
|
| 82 |
+
except requests.HTTPError as exc:
|
| 83 |
+
if exc.response is not None and exc.response.status_code == 401:
|
| 84 |
+
raise TokenRevokedError(
|
| 85 |
+
"Your GitHub token appears to be invalid or has been "
|
| 86 |
+
"revoked.\n\n"
|
| 87 |
+
" Re-authenticate:\n"
|
| 88 |
+
" opencodereview auth login\n\n"
|
| 89 |
+
" Or update the GITHUB_TOKEN environment variable.\n"
|
| 90 |
+
) from exc
|
| 91 |
+
raise
|
| 92 |
+
return wrapper
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
# βββ Custom Session βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
class GitHubSession(requests.Session):
|
| 99 |
+
"""A :class:`requests.Session` subclass that:
|
| 100 |
+
|
| 101 |
+
* Auto-resolves the GitHub token from keyring then env var
|
| 102 |
+
* Sends ``Authorization`` and standard headers on every request
|
| 103 |
+
* Raises :class:`TokenRevokedError` on ``401`` responses from
|
| 104 |
+
``api.github.com``
|
| 105 |
+
|
| 106 |
+
Usage
|
| 107 |
+
-----
|
| 108 |
+
session = GitHubSession()
|
| 109 |
+
resp = session.get("https://api.github.com/repos/psf/requests")
|
| 110 |
+
"""
|
| 111 |
+
|
| 112 |
+
def __init__(self, token: Optional[str] = None) -> None:
|
| 113 |
+
super().__init__()
|
| 114 |
+
self.token = token or resolve_token()
|
| 115 |
+
self.headers.update({
|
| 116 |
+
"Accept": "application/vnd.github.v3+json",
|
| 117 |
+
"User-Agent": "OpenCodeReview/1.0",
|
| 118 |
+
})
|
| 119 |
+
if self.token:
|
| 120 |
+
self.headers["Authorization"] = f"Bearer {self.token}"
|
| 121 |
+
|
| 122 |
+
def request(self, method, url, *args, **kwargs):
|
| 123 |
+
"""Override :meth:`requests.Session.request` to intercept 401
|
| 124 |
+
responses from ``api.github.com``."""
|
| 125 |
+
resp = super().request(method, url, *args, **kwargs)
|
| 126 |
+
# Only intercept 401 from the GitHub API, not raw content or other hosts
|
| 127 |
+
if resp.status_code == 401 and "api.github.com" in url:
|
| 128 |
+
raise TokenRevokedError(
|
| 129 |
+
"Your GitHub token appears to be invalid or has been "
|
| 130 |
+
"revoked.\n\n"
|
| 131 |
+
" Re-authenticate:\n"
|
| 132 |
+
" opencodereview auth login\n\n"
|
| 133 |
+
" Or update the GITHUB_TOKEN environment variable.\n"
|
| 134 |
+
)
|
| 135 |
+
return resp
|
graph.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
import sqlite3
|
| 5 |
+
|
| 6 |
+
from langgraph.checkpoint.serde.jsonplus import JsonPlusSerializer
|
| 7 |
+
from langgraph.checkpoint.sqlite import SqliteSaver
|
| 8 |
+
from langgraph.graph import END, START, StateGraph
|
| 9 |
+
|
| 10 |
+
from nodes import (
|
| 11 |
+
aggregator_node,
|
| 12 |
+
correctness_reviewer_node,
|
| 13 |
+
executor_node,
|
| 14 |
+
human_approval_node,
|
| 15 |
+
ingestion_node,
|
| 16 |
+
retrieval_node,
|
| 17 |
+
security_reviewer_node,
|
| 18 |
+
test_coverage_reviewer_node,
|
| 19 |
+
)
|
| 20 |
+
from state import OpenCodeReviewState
|
| 21 |
+
|
| 22 |
+
logger = logging.getLogger(__name__)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def build_graph(db_path: str = "checkpoints.db") -> StateGraph:
|
| 26 |
+
"""Build and compile the OpenCodeReview graph with SqliteSaver checkpointing.
|
| 27 |
+
|
| 28 |
+
Topology:
|
| 29 |
+
|
| 30 |
+
START β ingestion β retrieval
|
| 31 |
+
β
|
| 32 |
+
βββββββββββββββΌββββββββββββββ
|
| 33 |
+
βΌ βΌ βΌ
|
| 34 |
+
correctness security test_coverage
|
| 35 |
+
β β β
|
| 36 |
+
βββββββββββββββΌββββββββββββββ
|
| 37 |
+
βΌ
|
| 38 |
+
aggregator
|
| 39 |
+
β
|
| 40 |
+
βΌ
|
| 41 |
+
human_approval βββ interrupt() pauses here
|
| 42 |
+
β
|
| 43 |
+
βΌ
|
| 44 |
+
executor
|
| 45 |
+
ββββββ΄βββββ
|
| 46 |
+
ββββββββββΌββΌβββββββββ
|
| 47 |
+
β Inline review β
|
| 48 |
+
β comments at file β
|
| 49 |
+
β /line positions β
|
| 50 |
+
β 422 β issue cmt β
|
| 51 |
+
ββββββββββ¬ββ¬βββββββββ
|
| 52 |
+
β
|
| 53 |
+
END
|
| 54 |
+
"""
|
| 55 |
+
builder = StateGraph(OpenCodeReviewState)
|
| 56 |
+
|
| 57 |
+
# -- Nodes ----------------------------------------------------------------
|
| 58 |
+
builder.add_node("ingestion", ingestion_node)
|
| 59 |
+
builder.add_node("retrieval", retrieval_node)
|
| 60 |
+
builder.add_node("correctness_review", correctness_reviewer_node)
|
| 61 |
+
builder.add_node("security_review", security_reviewer_node)
|
| 62 |
+
builder.add_node("test_coverage_review", test_coverage_reviewer_node)
|
| 63 |
+
builder.add_node("aggregator", aggregator_node)
|
| 64 |
+
builder.add_node("human_approval", human_approval_node)
|
| 65 |
+
builder.add_node("executor", executor_node)
|
| 66 |
+
|
| 67 |
+
# -- Linear prefix --------------------------------------------------------
|
| 68 |
+
builder.add_edge(START, "ingestion")
|
| 69 |
+
builder.add_edge("ingestion", "retrieval")
|
| 70 |
+
|
| 71 |
+
# -- Fan-out: retrieval β all three reviewers in parallel -----------------
|
| 72 |
+
builder.add_edge("retrieval", "correctness_review")
|
| 73 |
+
builder.add_edge("retrieval", "security_review")
|
| 74 |
+
builder.add_edge("retrieval", "test_coverage_review")
|
| 75 |
+
|
| 76 |
+
# -- Fan-in: all three reviewers β aggregator -----------------------------
|
| 77 |
+
builder.add_edge("correctness_review", "aggregator")
|
| 78 |
+
builder.add_edge("security_review", "aggregator")
|
| 79 |
+
builder.add_edge("test_coverage_review", "aggregator")
|
| 80 |
+
|
| 81 |
+
# -- HITL + posting -------------------------------------------------------
|
| 82 |
+
builder.add_edge("aggregator", "human_approval")
|
| 83 |
+
builder.add_edge("human_approval", "executor")
|
| 84 |
+
builder.add_edge("executor", END)
|
| 85 |
+
|
| 86 |
+
# -- Checkpointer (required for interrupt/resume to work) -----------------
|
| 87 |
+
serde = JsonPlusSerializer(allowed_msgpack_modules=[
|
| 88 |
+
("state", "ChangedFile"),
|
| 89 |
+
("state", "ContextChunk"),
|
| 90 |
+
("state", "Severity"),
|
| 91 |
+
("state", "Finding"),
|
| 92 |
+
("state", "Verdict"),
|
| 93 |
+
])
|
| 94 |
+
|
| 95 |
+
conn = sqlite3.connect(db_path, check_same_thread=False)
|
| 96 |
+
saver = SqliteSaver(conn, serde=serde)
|
| 97 |
+
|
| 98 |
+
return builder.compile(checkpointer=saver)
|
main.py
ADDED
|
@@ -0,0 +1,270 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""OpenCodeReview β AI-powered PR review with human-in-the-loop approval.
|
| 3 |
+
|
| 4 |
+
Usage
|
| 5 |
+
-----
|
| 6 |
+
opencodereview auth login
|
| 7 |
+
opencodereview auth status
|
| 8 |
+
opencodereview auth logout
|
| 9 |
+
opencodereview review [--smoke]
|
| 10 |
+
opencodereview --help
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import logging
|
| 16 |
+
import os
|
| 17 |
+
import sys
|
| 18 |
+
import uuid
|
| 19 |
+
|
| 20 |
+
import click
|
| 21 |
+
from langgraph.types import Command
|
| 22 |
+
|
| 23 |
+
from auth import auth as auth_group
|
| 24 |
+
from config import config as config_group
|
| 25 |
+
from graph import build_graph
|
| 26 |
+
from state import ChangedFile, ContextChunk, Finding, Severity, Verdict
|
| 27 |
+
|
| 28 |
+
logging.basicConfig(
|
| 29 |
+
level=logging.INFO,
|
| 30 |
+
format="%(asctime)s [%(levelname)s] %(name)s β %(message)s",
|
| 31 |
+
)
|
| 32 |
+
logger = logging.getLogger(__name__)
|
| 33 |
+
|
| 34 |
+
DB_PATH = "checkpoints.db"
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
# βββ Synthetic payload for offline testing ββββββββββββββββββββββββββββββββββ
|
| 38 |
+
|
| 39 |
+
SYNTHETIC_STATE = {
|
| 40 |
+
"repo": "demo-org/demo-repo",
|
| 41 |
+
"pr_number": 1,
|
| 42 |
+
"diff": (
|
| 43 |
+
"diff --git a/src/auth.py b/src/auth.py\n"
|
| 44 |
+
"index abc123..def456 100644\n"
|
| 45 |
+
"--- a/src/auth.py\n"
|
| 46 |
+
"+++ b/src/auth.py\n"
|
| 47 |
+
"@@ -42,7 +42,9 @@ def login(username, password):\n"
|
| 48 |
+
" user = db.get_user(username)\n"
|
| 49 |
+
"- if user.password == password:\n"
|
| 50 |
+
"+ if constant_time_compare(password, user.password):\n"
|
| 51 |
+
" return create_session(user)\n"
|
| 52 |
+
" return None\n"
|
| 53 |
+
),
|
| 54 |
+
"changed_files": [
|
| 55 |
+
ChangedFile(
|
| 56 |
+
path="src/auth.py",
|
| 57 |
+
status="modified",
|
| 58 |
+
content="def login(username, password):\n"
|
| 59 |
+
" user = db.get_user(username)\n"
|
| 60 |
+
" if constant_time_compare(password, user.password):\n"
|
| 61 |
+
" return create_session(user)\n"
|
| 62 |
+
" return None\n",
|
| 63 |
+
diff_hunk="@@ -42,7 +42,9 @@ def login(username, password): ...",
|
| 64 |
+
),
|
| 65 |
+
],
|
| 66 |
+
"context_chunks": [
|
| 67 |
+
ContextChunk(
|
| 68 |
+
source="codebase", file_path="src/db.py",
|
| 69 |
+
content="def get_user(username): ...",
|
| 70 |
+
relevance_score=0.92,
|
| 71 |
+
),
|
| 72 |
+
],
|
| 73 |
+
"findings": [
|
| 74 |
+
Finding(
|
| 75 |
+
file_path="src/auth.py", line_start=42, line_end=50,
|
| 76 |
+
severity=Severity.CRITICAL, category="security",
|
| 77 |
+
comment="Use constant-time comparison for passwords.",
|
| 78 |
+
confidence=0.95,
|
| 79 |
+
),
|
| 80 |
+
],
|
| 81 |
+
"verdict": Verdict(
|
| 82 |
+
summary="Critical security vulnerability found.",
|
| 83 |
+
approved=False, overall_score=3.5, critical_count=1,
|
| 84 |
+
high_count=0, recommendation="block",
|
| 85 |
+
),
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
# βββ Review Command βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
@click.command()
|
| 93 |
+
@click.option(
|
| 94 |
+
"--smoke", is_flag=True,
|
| 95 |
+
help="Non-interactive smoke test (skips HITL prompt).",
|
| 96 |
+
)
|
| 97 |
+
@click.option(
|
| 98 |
+
"--repo",
|
| 99 |
+
default="demo-org/demo-repo",
|
| 100 |
+
show_default=True,
|
| 101 |
+
help="GitHub repository (owner/name).",
|
| 102 |
+
)
|
| 103 |
+
@click.option(
|
| 104 |
+
"--pr", "pr_number",
|
| 105 |
+
default=1,
|
| 106 |
+
show_default=True,
|
| 107 |
+
help="Pull request number.",
|
| 108 |
+
)
|
| 109 |
+
def review(repo: str, pr_number: int, smoke: bool) -> None:
|
| 110 |
+
"""Run a PR review with human-in-the-loop approval.
|
| 111 |
+
|
| 112 |
+
By default this runs with a synthetic PR payload for demonstration.
|
| 113 |
+
"""
|
| 114 |
+
graph = build_graph(DB_PATH)
|
| 115 |
+
|
| 116 |
+
if smoke:
|
| 117 |
+
_test_offline(graph)
|
| 118 |
+
else:
|
| 119 |
+
_run_with_hitl(graph, repo, pr_number)
|
| 120 |
+
|
| 121 |
+
_cleanup_db()
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def _run_with_hitl(graph, repo: str, pr_number: int) -> None:
|
| 125 |
+
"""Run the graph on a real PR β fetches data from GitHub, pauses for
|
| 126 |
+
human approval, then posts findings back as PR comments."""
|
| 127 |
+
thread_id = str(uuid.uuid4())
|
| 128 |
+
config = {"configurable": {"thread_id": f"hitl-{thread_id}"}}
|
| 129 |
+
|
| 130 |
+
# Use synthetic demo data by default; only fetch real PRs when the
|
| 131 |
+
# user explicitly provides a custom repo or PR number.
|
| 132 |
+
is_default = (repo == "demo-org/demo-repo" and pr_number == 1)
|
| 133 |
+
if is_default:
|
| 134 |
+
logger.info(
|
| 135 |
+
"Using synthetic demo data β pass --repo and --pr to "
|
| 136 |
+
"review a real PR from GitHub.\n"
|
| 137 |
+
)
|
| 138 |
+
initial_state = SYNTHETIC_STATE
|
| 139 |
+
else:
|
| 140 |
+
logger.info(
|
| 141 |
+
"Starting review of %s#%d β¦ fetching PR data from GitHub.\n",
|
| 142 |
+
repo, pr_number,
|
| 143 |
+
)
|
| 144 |
+
initial_state = {
|
| 145 |
+
"repo": repo,
|
| 146 |
+
"pr_number": pr_number,
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
events = list(graph.stream(initial_state, config))
|
| 150 |
+
|
| 151 |
+
state = graph.get_state(config)
|
| 152 |
+
tasks = state.tasks
|
| 153 |
+
|
| 154 |
+
if tasks:
|
| 155 |
+
logger.info("\n" + "=" * 60)
|
| 156 |
+
logger.info(" REVIEW RESULTS β HUMAN APPROVAL REQUIRED")
|
| 157 |
+
logger.info("=" * 60)
|
| 158 |
+
|
| 159 |
+
if state.values.get("verdict"):
|
| 160 |
+
v = state.values["verdict"]
|
| 161 |
+
logger.info(" Verdict: %s", v.recommendation.upper())
|
| 162 |
+
logger.info(" Score: %.1f/10", v.overall_score)
|
| 163 |
+
logger.info(" Summary: %s", v.summary)
|
| 164 |
+
|
| 165 |
+
final_findings = state.values.get("final_findings", [])
|
| 166 |
+
logger.info(" Findings: %d", len(final_findings))
|
| 167 |
+
for i, f in enumerate(final_findings, 1):
|
| 168 |
+
logger.info(
|
| 169 |
+
" %d. [%.0f%%] %s:%dβ%d (%s)",
|
| 170 |
+
i, f.confidence * 100, f.file_path,
|
| 171 |
+
f.line_start, f.line_end, f.severity.value,
|
| 172 |
+
)
|
| 173 |
+
logger.info(" %s", f.comment[:120])
|
| 174 |
+
|
| 175 |
+
logger.info("=" * 60)
|
| 176 |
+
|
| 177 |
+
click.echo()
|
| 178 |
+
click.echo("-" * 50)
|
| 179 |
+
click.echo(" HUMAN-IN-THE-LOOP: Approve this review for posting?")
|
| 180 |
+
click.echo("-" * 50)
|
| 181 |
+
click.echo(" [a] Approve β post findings as GitHub comments")
|
| 182 |
+
click.echo(" [r] Reject β discard results, post nothing")
|
| 183 |
+
click.echo(" [q] Quit β leave graph paused")
|
| 184 |
+
click.echo()
|
| 185 |
+
|
| 186 |
+
choice = click.prompt(" Your choice", type=click.Choice(["a", "r", "q"], case_sensitive=False))
|
| 187 |
+
|
| 188 |
+
if choice == "a":
|
| 189 |
+
logger.info(" β Approved! Resuming graph to post results β¦")
|
| 190 |
+
graph.invoke(Command(resume={"action": "approve"}), config)
|
| 191 |
+
elif choice == "r":
|
| 192 |
+
logger.info(" β Rejected. Resuming graph without posting β¦")
|
| 193 |
+
graph.invoke(Command(resume={"action": "reject"}), config)
|
| 194 |
+
else:
|
| 195 |
+
logger.info(" β Exiting. Graph remains paused β resume later")
|
| 196 |
+
logger.info(
|
| 197 |
+
" Resume with: graph.invoke(Command(resume=...), %s)",
|
| 198 |
+
config,
|
| 199 |
+
)
|
| 200 |
+
return
|
| 201 |
+
|
| 202 |
+
final_state = graph.get_state(config)
|
| 203 |
+
final_values = final_state.values
|
| 204 |
+
|
| 205 |
+
logger.info("\n" + "=" * 60)
|
| 206 |
+
logger.info(" FINAL STATE")
|
| 207 |
+
logger.info("=" * 60)
|
| 208 |
+
logger.info(" Human approved: %s", final_values.get("human_approved"))
|
| 209 |
+
if final_values.get("verdict"):
|
| 210 |
+
logger.info(" Verdict: %s", final_values["verdict"].recommendation)
|
| 211 |
+
logger.info(" Final findings: %d", len(final_values.get("final_findings", [])))
|
| 212 |
+
logger.info("=" * 60)
|
| 213 |
+
else:
|
| 214 |
+
logger.info("Graph completed without interrupt (no findings to review?)")
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def _test_offline(graph) -> None:
|
| 218 |
+
"""Non-interactive test that the graph compiles and runs up to interrupt."""
|
| 219 |
+
thread_id = str(uuid.uuid4())
|
| 220 |
+
config = {"configurable": {"thread_id": f"smoke-{thread_id}"}}
|
| 221 |
+
|
| 222 |
+
list(graph.stream(SYNTHETIC_STATE, config))
|
| 223 |
+
state = graph.get_state(config)
|
| 224 |
+
tasks = state.tasks
|
| 225 |
+
values = state.values
|
| 226 |
+
|
| 227 |
+
verdict = values.get("verdict")
|
| 228 |
+
final_findings = values.get("final_findings", [])
|
| 229 |
+
|
| 230 |
+
print(f"Smoke test: paused=True, tasks={len(tasks)}, "
|
| 231 |
+
f"findings={len(final_findings)}, "
|
| 232 |
+
f"verdict={verdict.recommendation if verdict else 'None'}")
|
| 233 |
+
|
| 234 |
+
assert len(tasks) > 0, "Graph did not pause at interrupt"
|
| 235 |
+
assert verdict is not None, "No verdict produced"
|
| 236 |
+
assert len(final_findings) >= 0, "Missing final_findings"
|
| 237 |
+
|
| 238 |
+
graph.invoke(Command(resume={"action": "reject"}), config)
|
| 239 |
+
print("Smoke test: resume OK, graph completed")
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def _cleanup_db() -> None:
|
| 243 |
+
"""Remove the checkpoint database after a run."""
|
| 244 |
+
if os.path.exists(DB_PATH):
|
| 245 |
+
try:
|
| 246 |
+
os.remove(DB_PATH)
|
| 247 |
+
logger.info("Cleaned up %s", DB_PATH)
|
| 248 |
+
except PermissionError:
|
| 249 |
+
pass
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
# βββ Root CLI βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
@click.group()
|
| 256 |
+
def cli() -> None:
|
| 257 |
+
"""OpenCodeReview β AI-powered PR review with human-in-the-loop approval."""
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
cli.add_command(review)
|
| 261 |
+
cli.add_command(auth_group)
|
| 262 |
+
cli.add_command(config_group)
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def main() -> None:
|
| 266 |
+
cli(auto_envvar_prefix="OCR")
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
if __name__ == "__main__":
|
| 270 |
+
main()
|
nodes/__init__.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from nodes.aggregator import aggregator_node
|
| 2 |
+
from nodes.correctness_reviewer import correctness_reviewer_node
|
| 3 |
+
from nodes.executor import executor_node
|
| 4 |
+
from nodes.human_approval import human_approval_node
|
| 5 |
+
from nodes.ingestion import ingestion_node
|
| 6 |
+
from nodes.passthrough import passthrough_node
|
| 7 |
+
from nodes.post_results import post_results_node
|
| 8 |
+
from nodes.retrieval import retrieval_node
|
| 9 |
+
from nodes.security_reviewer import security_reviewer_node
|
| 10 |
+
from nodes.test_coverage_reviewer import test_coverage_reviewer_node
|
| 11 |
+
|
| 12 |
+
__all__ = [
|
| 13 |
+
"aggregator_node",
|
| 14 |
+
"correctness_reviewer_node",
|
| 15 |
+
"executor_node",
|
| 16 |
+
"human_approval_node",
|
| 17 |
+
"ingestion_node",
|
| 18 |
+
"passthrough_node",
|
| 19 |
+
"post_results_node",
|
| 20 |
+
"retrieval_node",
|
| 21 |
+
"security_reviewer_node",
|
| 22 |
+
"test_coverage_reviewer_node",
|
| 23 |
+
]
|
nodes/aggregator.py
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
import os
|
| 5 |
+
from langchain_groq import ChatGroq
|
| 6 |
+
from pydantic import BaseModel, Field
|
| 7 |
+
|
| 8 |
+
from state import Finding, OpenCodeReviewState, Severity, Verdict
|
| 9 |
+
|
| 10 |
+
logger = logging.getLogger(__name__)
|
| 11 |
+
|
| 12 |
+
GROQ_MODEL = "llama-3.3-70b-versatile"
|
| 13 |
+
DEFAULT_TEMPERATURE = 0.0
|
| 14 |
+
|
| 15 |
+
# Findings below this confidence are dropped before the LLM step
|
| 16 |
+
MIN_CONFIDENCE = 0.25
|
| 17 |
+
# Files/line pairs within this many lines are considered duplicates
|
| 18 |
+
LINE_TOLERANCE = 5
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
# βββ LLM output schema ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class AggregatedReview(BaseModel):
|
| 25 |
+
"""Final, noise-filtered findings and overall verdict."""
|
| 26 |
+
findings: list[Finding] = Field(
|
| 27 |
+
default_factory=list,
|
| 28 |
+
description="Deduplicated, noise-filtered findings worth a senior engineer's time.",
|
| 29 |
+
)
|
| 30 |
+
verdict: Verdict = Field(
|
| 31 |
+
description="Overall PR verdict after considering all findings.",
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
# βββ Pre-LLM heuristic deduplication ββββββββββββββββββββββββββββββββββββββββ
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _deduplicate(findings: list[Finding]) -> list[Finding]:
|
| 39 |
+
"""Heuristic dedup: group by ``(file_path, line_start)`` with a line
|
| 40 |
+
tolerance, keeping the highest-confidence finding per group."""
|
| 41 |
+
if not findings:
|
| 42 |
+
return []
|
| 43 |
+
|
| 44 |
+
# Sort by (file, line_start) so we can iterate and merge neighbours
|
| 45 |
+
sorted_fs = sorted(findings, key=lambda f: (f.file_path, f.line_start))
|
| 46 |
+
|
| 47 |
+
merged: list[Finding] = []
|
| 48 |
+
current: Finding = sorted_fs[0]
|
| 49 |
+
|
| 50 |
+
for f in sorted_fs[1:]:
|
| 51 |
+
same_file = f.file_path == current.file_path
|
| 52 |
+
close_lines = abs(f.line_start - current.line_start) <= LINE_TOLERANCE
|
| 53 |
+
if same_file and close_lines:
|
| 54 |
+
# Keep the higher-confidence finding, merge comments
|
| 55 |
+
if f.confidence > current.confidence:
|
| 56 |
+
current = f
|
| 57 |
+
if current.confidence < 0.9:
|
| 58 |
+
current.confidence = round(
|
| 59 |
+
(current.confidence + f.confidence) / 2, 2
|
| 60 |
+
)
|
| 61 |
+
# Prefer the specific comment over a generic one
|
| 62 |
+
if len(f.comment) > len(current.comment):
|
| 63 |
+
current.comment = f.comment
|
| 64 |
+
if f.suggested_fix and not current.suggested_fix:
|
| 65 |
+
current.suggested_fix = f.suggested_fix
|
| 66 |
+
# Escalate severity if either finding is more severe
|
| 67 |
+
current.severity = _more_severe(current.severity, f.severity)
|
| 68 |
+
else:
|
| 69 |
+
merged.append(current)
|
| 70 |
+
current = f
|
| 71 |
+
merged.append(current)
|
| 72 |
+
|
| 73 |
+
# Drop low-confidence noise
|
| 74 |
+
merged = [f for f in merged if f.confidence >= MIN_CONFIDENCE]
|
| 75 |
+
|
| 76 |
+
return merged
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
_SEVERITY_ORDER = {
|
| 80 |
+
Severity.CRITICAL: 0,
|
| 81 |
+
Severity.HIGH: 1,
|
| 82 |
+
Severity.MEDIUM: 2,
|
| 83 |
+
Severity.LOW: 3,
|
| 84 |
+
Severity.INFO: 4,
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def _more_severe(a: Severity, b: Severity) -> Severity:
|
| 89 |
+
return a if _SEVERITY_ORDER.get(a, 5) < _SEVERITY_ORDER.get(b, 5) else b
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
# βββ Rule-based fallback verdict ββββββββββββββββββββββββββββββββββββββββββββ
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def _rule_verdict(findings: list[Finding]) -> Verdict:
|
| 96 |
+
"""Build a verdict from deduplicated findings without an LLM call."""
|
| 97 |
+
counts = {s: 0 for s in Severity}
|
| 98 |
+
for f in findings:
|
| 99 |
+
counts[f.severity] = counts.get(f.severity, 0) + 1
|
| 100 |
+
|
| 101 |
+
critical = counts[Severity.CRITICAL]
|
| 102 |
+
high = counts[Severity.HIGH]
|
| 103 |
+
|
| 104 |
+
if critical > 0:
|
| 105 |
+
recommendation = "block"
|
| 106 |
+
approved = False
|
| 107 |
+
elif high > 0:
|
| 108 |
+
recommendation = "request_changes"
|
| 109 |
+
approved = False
|
| 110 |
+
elif len(findings) > 0:
|
| 111 |
+
recommendation = "comment"
|
| 112 |
+
approved = True
|
| 113 |
+
else:
|
| 114 |
+
recommendation = "approve"
|
| 115 |
+
approved = True
|
| 116 |
+
|
| 117 |
+
# Score: 10 - penalty based on severity
|
| 118 |
+
score = max(0.0, min(10.0, 10.0 - critical * 4.0 - high * 2.0 - counts.get(Severity.MEDIUM, 0) * 0.5))
|
| 119 |
+
|
| 120 |
+
severity_counts = {s.value: counts.get(s, 0) for s in Severity}
|
| 121 |
+
|
| 122 |
+
return Verdict(
|
| 123 |
+
summary=_rule_summary(recommendation, severity_counts),
|
| 124 |
+
approved=approved,
|
| 125 |
+
overall_score=round(score, 1),
|
| 126 |
+
critical_count=critical,
|
| 127 |
+
high_count=high,
|
| 128 |
+
recommendation=recommendation,
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def _rule_summary(recommendation: str, counts: dict) -> str:
|
| 133 |
+
parts = [f"{v} {k}" for k, v in counts.items() if v > 0]
|
| 134 |
+
if not parts:
|
| 135 |
+
return "No issues found β PR looks clean."
|
| 136 |
+
body = ", ".join(parts)
|
| 137 |
+
if recommendation == "block":
|
| 138 |
+
return f"Blocking: {body} β critical issues must be resolved."
|
| 139 |
+
elif recommendation == "request_changes":
|
| 140 |
+
return f"Changes requested: {body} β high-severity issues should be addressed."
|
| 141 |
+
elif recommendation == "comment":
|
| 142 |
+
return f"Minor concerns: {body} β consider addressing for best practices."
|
| 143 |
+
return f"Approved: {body} β no significant issues."
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
# βββ LLM prompt βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
SYSTEM_PROMPT = """You are a senior engineer acting as a **critic** of a code review.
|
| 150 |
+
Your job is to look at the list of raw findings produced by automated reviewers
|
| 151 |
+
and decide which ones are genuinely worth sharing with the PR author.
|
| 152 |
+
|
| 153 |
+
Apply these rules strictly:
|
| 154 |
+
|
| 155 |
+
1. **Deduplicate** β if two findings point at the same issue (same file,
|
| 156 |
+
overlapping lines, similar comment), keep only the more specific one.
|
| 157 |
+
2. **Drop noise** β remove findings that are:
|
| 158 |
+
- Overly pedantic or stylistic (a senior engineer wouldn't mention them).
|
| 159 |
+
- Speculative with very low confidence (< 0.4).
|
| 160 |
+
- Vague or generic ("consider improving this code" without specifics).
|
| 161 |
+
3. **Escalate appropriately** β if a finding is genuinely important but the
|
| 162 |
+
automated reviewer gave it a low severity, bump it up. Conversely, if it's
|
| 163 |
+
a minor nitpick flagged as "critical", bump it down.
|
| 164 |
+
4. **Produce a verdict** β based on the *filtered* set of findings, decide:
|
| 165 |
+
- `approve` β no significant issues, or only minor suggestions.
|
| 166 |
+
- `request_changes` β issues that should be addressed before merging.
|
| 167 |
+
- `block` β a critical bug that must not be merged.
|
| 168 |
+
|
| 169 |
+
The verdict's `overall_score` should reflect how healthy the PR is:
|
| 170 |
+
- 9β10: clean, trivial suggestions only
|
| 171 |
+
- 7β8: minor issues worth noting
|
| 172 |
+
- 5β6: should fix before merging
|
| 173 |
+
- 3β4: several problems, strongly consider rework
|
| 174 |
+
- 0β2: critical, must not merge
|
| 175 |
+
|
| 176 |
+
Return the filtered list of findings plus your verdict.
|
| 177 |
+
"""
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
# βββ Prompt builder βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def _build_prompt(findings: list[Finding]) -> str:
|
| 184 |
+
lines = [
|
| 185 |
+
"Below are the raw findings from automated code reviewers "
|
| 186 |
+
"(correctness, security, test-coverage).",
|
| 187 |
+
"",
|
| 188 |
+
"Filter out noise and return only the findings a senior engineer "
|
| 189 |
+
"would actually leave on this PR.",
|
| 190 |
+
"",
|
| 191 |
+
"## Raw findings",
|
| 192 |
+
]
|
| 193 |
+
for i, f in enumerate(findings, 1):
|
| 194 |
+
lines.append(f"\n--- Finding {i} ---")
|
| 195 |
+
lines.append(f" File: {f.file_path}")
|
| 196 |
+
lines.append(f" Lines: {f.line_start}β{f.line_end}")
|
| 197 |
+
lines.append(f" Severity: {f.severity.value}")
|
| 198 |
+
lines.append(f" Category: {f.category}")
|
| 199 |
+
lines.append(f" Comment: {f.comment}")
|
| 200 |
+
lines.append(f" Confidence: {f.confidence}")
|
| 201 |
+
if f.suggested_fix:
|
| 202 |
+
lines.append(f" Fix: {f.suggested_fix[:200]}")
|
| 203 |
+
|
| 204 |
+
lines.append("\nNow apply the deduplication, noise-filtering, and verdict rules.")
|
| 205 |
+
return "\n".join(lines)
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
# βββ Node ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def aggregator_node(state: OpenCodeReviewState) -> dict:
|
| 212 |
+
"""Deduplicate, filter, and aggregate all findings into a final verdict.
|
| 213 |
+
|
| 214 |
+
Returns state updates for ``findings`` (overwritten with the filtered
|
| 215 |
+
list) and ``verdict`` (set-once by this node).
|
| 216 |
+
|
| 217 |
+
Two-phase approach:
|
| 218 |
+
1. Pre-LLM heuristic deduplication (groups by file/line proximity).
|
| 219 |
+
2. LLM noise-filter + verdict (if GROQ_API_KEY is available), else
|
| 220 |
+
rule-based fallback.
|
| 221 |
+
"""
|
| 222 |
+
raw_findings = state.findings
|
| 223 |
+
if not raw_findings:
|
| 224 |
+
logger.info("No findings to aggregate β producing empty verdict")
|
| 225 |
+
empty_verdict = Verdict(
|
| 226 |
+
summary="No issues found β PR looks clean.",
|
| 227 |
+
approved=True,
|
| 228 |
+
overall_score=10.0,
|
| 229 |
+
critical_count=0,
|
| 230 |
+
high_count=0,
|
| 231 |
+
recommendation="approve",
|
| 232 |
+
)
|
| 233 |
+
return {"final_findings": [], "verdict": empty_verdict}
|
| 234 |
+
|
| 235 |
+
# -- Phase 1: Heuristic dedup --------------------------------------------
|
| 236 |
+
deduped = _deduplicate(raw_findings)
|
| 237 |
+
logger.info(
|
| 238 |
+
"Dedup heuristic: %d raw β %d merged",
|
| 239 |
+
len(raw_findings), len(deduped),
|
| 240 |
+
)
|
| 241 |
+
|
| 242 |
+
# -- Phase 2: LLM critic or rule-based fallback --------------------------
|
| 243 |
+
api_key = os.environ.get("GROQ_API_KEY", "").strip()
|
| 244 |
+
|
| 245 |
+
if api_key:
|
| 246 |
+
logger.info("Invoking aggregator LLM critic β¦")
|
| 247 |
+
try:
|
| 248 |
+
llm = ChatGroq(
|
| 249 |
+
model=GROQ_MODEL,
|
| 250 |
+
temperature=DEFAULT_TEMPERATURE,
|
| 251 |
+
api_key=api_key,
|
| 252 |
+
)
|
| 253 |
+
structured_llm = llm.with_structured_output(AggregatedReview)
|
| 254 |
+
|
| 255 |
+
messages = [
|
| 256 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 257 |
+
{"role": "user", "content": _build_prompt(deduped)},
|
| 258 |
+
]
|
| 259 |
+
result: AggregatedReview = structured_llm.invoke(messages) # type: ignore[assignment]
|
| 260 |
+
except Exception as exc:
|
| 261 |
+
logger.warning("Aggregator LLM call failed β falling back to rule-based: %s", exc)
|
| 262 |
+
result = None
|
| 263 |
+
|
| 264 |
+
if result is not None:
|
| 265 |
+
final_findings = result.findings
|
| 266 |
+
verdict = result.verdict
|
| 267 |
+
logger.info(
|
| 268 |
+
"LLM aggregator: %d deduped β %d final, recommendation=%s",
|
| 269 |
+
len(deduped), len(final_findings),
|
| 270 |
+
verdict.recommendation,
|
| 271 |
+
)
|
| 272 |
+
else:
|
| 273 |
+
final_findings = deduped
|
| 274 |
+
verdict = _rule_verdict(deduped)
|
| 275 |
+
else:
|
| 276 |
+
logger.info("GROQ_API_KEY not set β using rule-based aggregation")
|
| 277 |
+
final_findings = deduped
|
| 278 |
+
verdict = _rule_verdict(deduped)
|
| 279 |
+
|
| 280 |
+
return {
|
| 281 |
+
"final_findings": final_findings, # plain list, overwrites
|
| 282 |
+
"verdict": verdict, # set-once, no reducer needed
|
| 283 |
+
}
|
nodes/correctness_reviewer.py
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
import os
|
| 5 |
+
from langchain_groq import ChatGroq
|
| 6 |
+
from pydantic import BaseModel, Field
|
| 7 |
+
|
| 8 |
+
from state import Finding, OpenCodeReviewState, Severity
|
| 9 |
+
|
| 10 |
+
logger = logging.getLogger(__name__)
|
| 11 |
+
|
| 12 |
+
# Model used on Groq β good at function calling / structured output
|
| 13 |
+
GROQ_MODEL = "llama-3.3-70b-versatile"
|
| 14 |
+
DEFAULT_TEMPERATURE = 0.0
|
| 15 |
+
|
| 16 |
+
# Max characters of context to include in the prompt (soft limit)
|
| 17 |
+
MAX_CONTEXT_CHARS = 6_000
|
| 18 |
+
# Max changed-file content to include per file
|
| 19 |
+
MAX_FILE_CONTENT_CHARS = 4_000
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
# βββ Wrapper schema for structured output βββββββββββββββββββββββββββββββββββ
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class CorrectnessReview(BaseModel):
|
| 26 |
+
"""A list of correctness issues found during code review.
|
| 27 |
+
|
| 28 |
+
The LLM MUST populate this with every correctness-relevant finding in the
|
| 29 |
+
diff. Return an empty list if no correctness issues are found.
|
| 30 |
+
"""
|
| 31 |
+
findings: list[Finding] = Field(
|
| 32 |
+
default_factory=list,
|
| 33 |
+
description=(
|
| 34 |
+
"Correctness issues found in the PR diff. "
|
| 35 |
+
"Each issue must reference a specific file and line range."
|
| 36 |
+
),
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
# βββ Prompt template ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
SYSTEM_PROMPT = """You are a seasoned code reviewer focused exclusively on **correctness**.
|
| 44 |
+
|
| 45 |
+
Analyse the PR diff and changed files below. Look ONLY for:
|
| 46 |
+
|
| 47 |
+
1. **Logic errors** β incorrect boolean conditions, wrong operators, inverted
|
| 48 |
+
if/else branches, incorrect variable shadowing, wrong function calls.
|
| 49 |
+
2. **Missed edge cases** β empty collections, None/null values, zero-length
|
| 50 |
+
inputs, singleton lists, boundary values, negative numbers, overflow.
|
| 51 |
+
3. **Off-by-one errors** β loop bounds, slice indices, fencepost mistakes.
|
| 52 |
+
4. **Missing null/None checks** β unchecked return values, unchecked
|
| 53 |
+
parameters that can be None, missing `is None` / `is not None` guards.
|
| 54 |
+
5. **Resource / state mismanagement** β unclosed handles, leaked connections,
|
| 55 |
+
double-close, use-after-free, invalidated iterators.
|
| 56 |
+
6. **Concurrency hazards in the diff** β shared-mutation without locks, race
|
| 57 |
+
windows, incorrect locking order.
|
| 58 |
+
|
| 59 |
+
**Do NOT** comment on:
|
| 60 |
+
- Code style, formatting, naming conventions, or readability.
|
| 61 |
+
- Performance (unless it's a correctness issue like an infinite loop).
|
| 62 |
+
- Security (that is handled by a separate reviewer).
|
| 63 |
+
- Tests being absent (unless the diff itself adds broken tests).
|
| 64 |
+
|
| 65 |
+
For each issue return a `Finding` with:
|
| 66 |
+
- `file_path`: the file the issue is in.
|
| 67 |
+
- `line_start` / `line_end`: the relevant line range (best guess from the diff).
|
| 68 |
+
- `severity`: `critical` (will definitely break), `high` (very likely to break),
|
| 69 |
+
`medium` (edge-case bug), `low` (minor, unlikely to trigger), or `info`
|
| 70 |
+
(informational).
|
| 71 |
+
- `category`: always `"correctness"`.
|
| 72 |
+
- `comment`: a concise, specific explanation of the bug.
|
| 73 |
+
- `confidence`: 0.0β1.0 reflecting how sure you are.
|
| 74 |
+
- `suggested_fix`: a concrete code snippet of how to fix it, if applicable.
|
| 75 |
+
|
| 76 |
+
If you find NO correctness issues, return an empty findings list.
|
| 77 |
+
"""
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def _build_prompt(state: OpenCodeReviewState) -> str:
|
| 81 |
+
"""Build the user-facing prompt from the current graph state."""
|
| 82 |
+
lines: list[str] = []
|
| 83 |
+
|
| 84 |
+
lines.append("## Diff\n```diff")
|
| 85 |
+
lines.append(state.diff or "")
|
| 86 |
+
lines.append("```\n")
|
| 87 |
+
|
| 88 |
+
# Changed files with full content (truncated per file)
|
| 89 |
+
if state.changed_files:
|
| 90 |
+
lines.append("## Changed files\n")
|
| 91 |
+
for cf in state.changed_files:
|
| 92 |
+
header = f"### {cf.path} ({cf.status})"
|
| 93 |
+
lines.append(header)
|
| 94 |
+
content = cf.content or ""
|
| 95 |
+
if len(content) > MAX_FILE_CONTENT_CHARS:
|
| 96 |
+
content = content[:MAX_FILE_CONTENT_CHARS] + "\n⦠(truncated)"
|
| 97 |
+
lines.append(f"```\n{content}\n```\n")
|
| 98 |
+
|
| 99 |
+
# Context chunks (truncated total)
|
| 100 |
+
if state.context_chunks:
|
| 101 |
+
lines.append("## Retrieved context\n")
|
| 102 |
+
ctx_chars = 0
|
| 103 |
+
for chunk in state.context_chunks:
|
| 104 |
+
snippet = chunk.content
|
| 105 |
+
if ctx_chars + len(snippet) > MAX_CONTEXT_CHARS:
|
| 106 |
+
remaining = MAX_CONTEXT_CHARS - ctx_chars
|
| 107 |
+
if remaining > 200:
|
| 108 |
+
lines.append(f"> {snippet[:remaining]}β¦ (truncated)")
|
| 109 |
+
break
|
| 110 |
+
if chunk.source == "past_pr":
|
| 111 |
+
lines.append(f"> [Past PR β {chunk.file_path}]: {snippet}")
|
| 112 |
+
else:
|
| 113 |
+
lines.append(f"> [{chunk.file_path}]: {snippet}")
|
| 114 |
+
ctx_chars += len(snippet)
|
| 115 |
+
|
| 116 |
+
return "\n".join(lines)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
# βββ Node ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def correctness_reviewer_node(state: OpenCodeReviewState) -> dict:
|
| 123 |
+
"""Analyse the diff and context chunks for correctness issues using an LLM.
|
| 124 |
+
|
| 125 |
+
Returns state updates for ``findings`` (accumulated via the ``add``
|
| 126 |
+
reducer).
|
| 127 |
+
"""
|
| 128 |
+
# --- Sanity checks -------------------------------------------------------
|
| 129 |
+
api_key = os.environ.get("GROQ_API_KEY", "").strip()
|
| 130 |
+
if not api_key:
|
| 131 |
+
logger.warning("GROQ_API_KEY not set β skipping correctness review")
|
| 132 |
+
return {}
|
| 133 |
+
|
| 134 |
+
if not state.diff:
|
| 135 |
+
logger.info("No diff to review β skipping correctness review")
|
| 136 |
+
return {}
|
| 137 |
+
|
| 138 |
+
# --- Build the LLM -------------------------------------------------------
|
| 139 |
+
llm = ChatGroq(
|
| 140 |
+
model=GROQ_MODEL,
|
| 141 |
+
temperature=DEFAULT_TEMPERATURE,
|
| 142 |
+
api_key=api_key,
|
| 143 |
+
)
|
| 144 |
+
structured_llm = llm.with_structured_output(CorrectnessReview)
|
| 145 |
+
|
| 146 |
+
# --- Build the prompt ----------------------------------------------------
|
| 147 |
+
user_prompt = _build_prompt(state)
|
| 148 |
+
logger.info(
|
| 149 |
+
"Invoking correctness reviewer (diff=%s, context=%d chunks, prompt=%s)",
|
| 150 |
+
_human_size(len(state.diff or "")),
|
| 151 |
+
len(state.context_chunks),
|
| 152 |
+
_human_size(len(user_prompt)),
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
# --- Invoke --------------------------------------------------------------
|
| 156 |
+
try:
|
| 157 |
+
messages = [
|
| 158 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 159 |
+
{"role": "user", "content": user_prompt},
|
| 160 |
+
]
|
| 161 |
+
result: CorrectnessReview = structured_llm.invoke(messages) # type: ignore[assignment]
|
| 162 |
+
except Exception as exc:
|
| 163 |
+
logger.warning("Correctness review LLM call failed: %s", exc)
|
| 164 |
+
return {}
|
| 165 |
+
|
| 166 |
+
# --- Log and return findings ---------------------------------------------
|
| 167 |
+
if result and result.findings:
|
| 168 |
+
logger.info(
|
| 169 |
+
"Correctness review found %d issue(s)",
|
| 170 |
+
len(result.findings),
|
| 171 |
+
)
|
| 172 |
+
for f in result.findings:
|
| 173 |
+
logger.debug(
|
| 174 |
+
" [%.2f] %s:%dβ%d β %s",
|
| 175 |
+
f.confidence, f.file_path, f.line_start, f.line_end,
|
| 176 |
+
f.comment[:80],
|
| 177 |
+
)
|
| 178 |
+
else:
|
| 179 |
+
logger.info("Correctness review found no issues")
|
| 180 |
+
|
| 181 |
+
return {
|
| 182 |
+
"findings": result.findings,
|
| 183 |
+
}
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
# βββ Utility βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def _human_size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
| 6 |
+
|
| 7 |
+
from github_client import GitHubSession, resolve_token
|
| 8 |
+
from state import Finding, OpenCodeReviewState
|
| 9 |
+
|
| 10 |
+
logger = logging.getLogger(__name__)
|
| 11 |
+
|
| 12 |
+
GITHUB_API_BASE = "https://api.github.com"
|
| 13 |
+
|
| 14 |
+
# βββ Helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
_GITHUB_SESSION: GitHubSession | None = None
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def _gh_session() -> GitHubSession:
|
| 21 |
+
"""Return a lazily-initialized :class:`GitHubSession`."""
|
| 22 |
+
global _GITHUB_SESSION
|
| 23 |
+
if _GITHUB_SESSION is None:
|
| 24 |
+
_GITHUB_SESSION = GitHubSession()
|
| 25 |
+
return _GITHUB_SESSION
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _fetch_pr_head_sha(owner: str, repo: str, pr_number: int) -> str | None:
|
| 29 |
+
"""Fetch the latest head SHA of the PR so inline comments target the correct
|
| 30 |
+
commit even if the PR was updated since ingestion."""
|
| 31 |
+
url = f"{GITHUB_API_BASE}/repos/{owner}/{repo}/pulls/{pr_number}"
|
| 32 |
+
try:
|
| 33 |
+
resp = _gh_session().get(url, timeout=30)
|
| 34 |
+
if resp.status_code == 200:
|
| 35 |
+
return resp.json()["head"]["sha"]
|
| 36 |
+
logger.warning(
|
| 37 |
+
"Could not fetch PR metadata: HTTP %s β %s",
|
| 38 |
+
resp.status_code, resp.text[:120],
|
| 39 |
+
)
|
| 40 |
+
return None
|
| 41 |
+
except requests.RequestException as exc:
|
| 42 |
+
logger.warning("Request failed while fetching PR metadata: %s", exc)
|
| 43 |
+
return None
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _post_review_comment(
|
| 47 |
+
owner: str,
|
| 48 |
+
repo: str,
|
| 49 |
+
pr_number: int,
|
| 50 |
+
commit_id: str,
|
| 51 |
+
path: str,
|
| 52 |
+
line: int,
|
| 53 |
+
side: str,
|
| 54 |
+
body: str,
|
| 55 |
+
start_line: int | None = None,
|
| 56 |
+
) -> bool:
|
| 57 |
+
"""Post an inline PR review comment at the given file/line position.
|
| 58 |
+
|
| 59 |
+
Uses ``POST /repos/{owner}/{repo}/pulls/{pull_number}/comments``.
|
| 60 |
+
|
| 61 |
+
Parameters
|
| 62 |
+
----------
|
| 63 |
+
line : int
|
| 64 |
+
The line number in the diff. For multi-line comments this is the
|
| 65 |
+
*last* line of the range.
|
| 66 |
+
side : str
|
| 67 |
+
``"LEFT"`` or ``"RIGHT"`` β which side of the diff the comment
|
| 68 |
+
targets. We always use ``"RIGHT"`` (the new/post-PR version).
|
| 69 |
+
start_line : int | None
|
| 70 |
+
When set, creates a multi-line comment spanning *start_line* β
|
| 71 |
+
*line*.
|
| 72 |
+
"""
|
| 73 |
+
payload: dict[str, Any] = {
|
| 74 |
+
"body": body,
|
| 75 |
+
"commit_id": commit_id,
|
| 76 |
+
"path": path,
|
| 77 |
+
"line": line,
|
| 78 |
+
"side": side,
|
| 79 |
+
}
|
| 80 |
+
if start_line is not None:
|
| 81 |
+
payload["start_line"] = start_line
|
| 82 |
+
payload["start_side"] = side
|
| 83 |
+
|
| 84 |
+
url = f"{GITHUB_API_BASE}/repos/{owner}/{repo}/pulls/{pr_number}/comments"
|
| 85 |
+
try:
|
| 86 |
+
resp = _gh_session().post(url, json=payload, timeout=30)
|
| 87 |
+
if resp.status_code in (201, 200):
|
| 88 |
+
logger.debug(
|
| 89 |
+
"Inline comment posted to %s:%d (%s)", path, line, side,
|
| 90 |
+
)
|
| 91 |
+
return True
|
| 92 |
+
if resp.status_code == 422:
|
| 93 |
+
# Stale line: the line no longer exists in the latest diff.
|
| 94 |
+
logger.info(
|
| 95 |
+
"Line %d no longer exists in %s (422) β will fall back "
|
| 96 |
+
"to issue comment", line, path,
|
| 97 |
+
)
|
| 98 |
+
return False
|
| 99 |
+
logger.warning(
|
| 100 |
+
"Failed to post inline comment: HTTP %s β %s",
|
| 101 |
+
resp.status_code, resp.text[:200],
|
| 102 |
+
)
|
| 103 |
+
return False
|
| 104 |
+
except requests.RequestException as exc:
|
| 105 |
+
logger.warning("Request failed for inline comment: %s", exc)
|
| 106 |
+
return False
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def _post_issue_comment(owner: str, repo: str, pr_number: int, body: str) -> bool:
|
| 110 |
+
"""Post a general (non-inline) issue/PR comment as a fallback.
|
| 111 |
+
|
| 112 |
+
Uses ``POST /repos/{owner}/{repo}/issues/{issue_number}/comments``.
|
| 113 |
+
"""
|
| 114 |
+
url = f"{GITHUB_API_BASE}/repos/{owner}/{repo}/issues/{pr_number}/comments"
|
| 115 |
+
try:
|
| 116 |
+
resp = _gh_session().post(
|
| 117 |
+
url, json={"body": body}, timeout=30,
|
| 118 |
+
)
|
| 119 |
+
if resp.status_code in (201, 200):
|
| 120 |
+
logger.debug("Fallback issue comment posted")
|
| 121 |
+
return True
|
| 122 |
+
logger.warning(
|
| 123 |
+
"Failed to post fallback comment: HTTP %s β %s",
|
| 124 |
+
resp.status_code, resp.text[:200],
|
| 125 |
+
)
|
| 126 |
+
return False
|
| 127 |
+
except requests.RequestException as exc:
|
| 128 |
+
logger.warning("Request failed for fallback comment: %s", exc)
|
| 129 |
+
return False
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
# βββ Formatting ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 133 |
+
|
| 134 |
+
SEVERITY_EMOJI = {
|
| 135 |
+
"critical": "\U0001f6a8", # π¨
|
| 136 |
+
"high": "\u26a0\ufe0f", # β οΈ
|
| 137 |
+
"medium": "\U0001f4cc", # π
|
| 138 |
+
"low": "\U0001f4a1", # π‘
|
| 139 |
+
"info": "\u2139\ufe0f", # βΉοΈ
|
| 140 |
+
}
|
| 141 |
+
VERDICT_ICON = {
|
| 142 |
+
"approve": "\u2705",
|
| 143 |
+
"request_changes": "\U0001f504",
|
| 144 |
+
"block": "\U0001f6ab",
|
| 145 |
+
"comment": "\U0001f4ac",
|
| 146 |
+
}
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def _finding_body(finding: Finding) -> str:
|
| 150 |
+
"""Format a single finding as Markdown for the comment body."""
|
| 151 |
+
emoji = SEVERITY_EMOJI.get(finding.severity.value, "\U0001f50d")
|
| 152 |
+
fix = ""
|
| 153 |
+
if finding.suggested_fix:
|
| 154 |
+
fix = f"\n\n**Suggested fix:**\n```\n{finding.suggested_fix}\n```"
|
| 155 |
+
return (
|
| 156 |
+
f"{emoji} **{finding.severity.value.upper()}** β "
|
| 157 |
+
f"*{finding.category}* \n"
|
| 158 |
+
f"**Confidence:** {finding.confidence:.0%} \n\n"
|
| 159 |
+
f"{finding.comment}{fix}"
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def _finding_fallback_body(finding: Finding) -> str:
|
| 164 |
+
"""Format a finding for a fallback issue comment when the line is stale."""
|
| 165 |
+
return (
|
| 166 |
+
f"*(This comment refers to a previous version of the code β "
|
| 167 |
+
f"the line may no longer exist in the latest diff.)*\n\n"
|
| 168 |
+
f"{_finding_body(finding)}\n\n"
|
| 169 |
+
f"**Original location:** `{finding.file_path}` "
|
| 170 |
+
f"(lines {finding.line_start}\u2013{finding.line_end})"
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def _verdict_body(verdict_dict: dict) -> str:
|
| 175 |
+
"""Format the overall verdict as a Markdown PR comment."""
|
| 176 |
+
emoji = VERDICT_ICON.get(verdict_dict.get("recommendation", ""), "\U0001f4cb")
|
| 177 |
+
summary = verdict_dict.get("summary", "")
|
| 178 |
+
score = verdict_dict.get("overall_score", 0)
|
| 179 |
+
return (
|
| 180 |
+
f"## OpenCodeReview \u2014 {emoji} "
|
| 181 |
+
f"{verdict_dict['recommendation'].upper()}\n\n"
|
| 182 |
+
f"**Score:** {score}/10 \n"
|
| 183 |
+
f"**Summary:** {summary}\n"
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
# βββ Node ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def executor_node(state: OpenCodeReviewState) -> dict:
|
| 191 |
+
"""Post approved findings as GitHub **PR review comments** at the correct
|
| 192 |
+
file/line positions.
|
| 193 |
+
|
| 194 |
+
Workflow
|
| 195 |
+
--------
|
| 196 |
+
1. Only runs if ``state.human_approved is True``.
|
| 197 |
+
2. Fetches the latest PR head SHA every time (handles PR updates).
|
| 198 |
+
3. For each finding:
|
| 199 |
+
a. Try ``POST /pulls/{pr}/comments`` (inline review comment).
|
| 200 |
+
b. On **422** (stale line): fall back to
|
| 201 |
+
``POST /issues/{pr}/comments`` (general comment).
|
| 202 |
+
4. Posts the verdict as a general issue comment.
|
| 203 |
+
|
| 204 |
+
Requires ``GITHUB_TOKEN`` to post. Without it, logs what it *would*
|
| 205 |
+
have posted.
|
| 206 |
+
"""
|
| 207 |
+
if not state.human_approved:
|
| 208 |
+
logger.info("Not approved \u2014 skipping executor")
|
| 209 |
+
return {}
|
| 210 |
+
|
| 211 |
+
parts = state.repo.split("/")
|
| 212 |
+
if len(parts) != 2:
|
| 213 |
+
logger.warning("Cannot post results: invalid repo '%s'", state.repo)
|
| 214 |
+
return {}
|
| 215 |
+
owner, repo_name = parts
|
| 216 |
+
pr_number = state.pr_number
|
| 217 |
+
|
| 218 |
+
gh_token = os.environ.get("GITHUB_TOKEN", "").strip()
|
| 219 |
+
if not gh_token:
|
| 220 |
+
gh_token = resolve_token() or ""
|
| 221 |
+
if not gh_token:
|
| 222 |
+
logger.warning(
|
| 223 |
+
"No GitHub token available \u2014 cannot post to %s/%s#%d. "
|
| 224 |
+
"Run 'opencodereview auth login' or set GITHUB_TOKEN.",
|
| 225 |
+
owner, repo_name, pr_number,
|
| 226 |
+
)
|
| 227 |
+
if state.verdict:
|
| 228 |
+
logger.info("[WOULD POST] Verdict: %s", state.verdict.summary)
|
| 229 |
+
for f in state.final_findings:
|
| 230 |
+
logger.info(
|
| 231 |
+
"[WOULD POST] %s:%d\u2013%d %s \u2014 %s",
|
| 232 |
+
f.file_path, f.line_start, f.line_end,
|
| 233 |
+
f.severity.value, f.comment[:60],
|
| 234 |
+
)
|
| 235 |
+
return {}
|
| 236 |
+
|
| 237 |
+
# ββ 1. Fetch latest head SHA βββββββββββββββββββββββββββββββββββββββββ
|
| 238 |
+
commit_id = _fetch_pr_head_sha(owner, repo_name, pr_number)
|
| 239 |
+
if commit_id is None:
|
| 240 |
+
logger.warning(
|
| 241 |
+
"Could not fetch PR head SHA \u2014 cannot post inline "
|
| 242 |
+
"comments. Falling back to issue-level comments."
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
# ββ 2. Post each finding βββββββββββββββββββββββββββββββββββββββββββββ
|
| 246 |
+
inline_ok = 0
|
| 247 |
+
inline_failed = 0
|
| 248 |
+
fallback_ok = 0
|
| 249 |
+
|
| 250 |
+
for f in state.final_findings:
|
| 251 |
+
body = _finding_body(f)
|
| 252 |
+
|
| 253 |
+
if commit_id:
|
| 254 |
+
# Try inline review comment
|
| 255 |
+
if f.line_start == f.line_end:
|
| 256 |
+
ok = _post_review_comment(
|
| 257 |
+
owner, repo_name, pr_number,
|
| 258 |
+
commit_id, f.file_path, f.line_start, "RIGHT", body,
|
| 259 |
+
)
|
| 260 |
+
else:
|
| 261 |
+
# Multi-line: end_line is the "line" param, start_line
|
| 262 |
+
# marks the range start.
|
| 263 |
+
ok = _post_review_comment(
|
| 264 |
+
owner, repo_name, pr_number,
|
| 265 |
+
commit_id, f.file_path, f.line_end, "RIGHT", body,
|
| 266 |
+
start_line=f.line_start,
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
if ok:
|
| 270 |
+
inline_ok += 1
|
| 271 |
+
continue
|
| 272 |
+
inline_failed += 1
|
| 273 |
+
|
| 274 |
+
# Fallback: issue-level comment with stale-line context
|
| 275 |
+
fallback_body = (
|
| 276 |
+
_finding_fallback_body(f) if commit_id else body
|
| 277 |
+
)
|
| 278 |
+
if _post_issue_comment(owner, repo_name, pr_number, fallback_body):
|
| 279 |
+
fallback_ok += 1
|
| 280 |
+
|
| 281 |
+
# ββ 3. Post the verdict ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 282 |
+
if state.verdict:
|
| 283 |
+
verdict_body = _verdict_body(state.verdict.model_dump())
|
| 284 |
+
_post_issue_comment(owner, repo_name, pr_number, verdict_body)
|
| 285 |
+
|
| 286 |
+
total = len(state.final_findings)
|
| 287 |
+
logger.info(
|
| 288 |
+
"Executor: %d/%d inline, %d/%d fallback, verdict %s \u2014 "
|
| 289 |
+
"%s/%s#%d",
|
| 290 |
+
inline_ok, total, fallback_ok, total - inline_ok,
|
| 291 |
+
"posted" if state.verdict else "skipped",
|
| 292 |
+
owner, repo_name, pr_number,
|
| 293 |
+
)
|
| 294 |
+
return {}
|
nodes/human_approval.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
from typing import Literal
|
| 5 |
+
|
| 6 |
+
from langgraph.types import interrupt
|
| 7 |
+
|
| 8 |
+
from state import OpenCodeReviewState
|
| 9 |
+
|
| 10 |
+
logger = logging.getLogger(__name__)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
# βββ Approval result that the human returns when resuming ββββββββββββββββββββ
|
| 14 |
+
|
| 15 |
+
ApprovalAction = Literal["approve", "reject", "edit"]
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
# βββ Node ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def human_approval_node(state: OpenCodeReviewState) -> dict:
|
| 22 |
+
"""Pause graph execution and wait for a human to approve or reject the
|
| 23 |
+
review findings before anything is posted to GitHub.
|
| 24 |
+
|
| 25 |
+
The value passed to ``interrupt()`` is returned to the caller (the CLI
|
| 26 |
+
or frontend). The caller must resume with ``Command(resume=...)`` whose
|
| 27 |
+
value becomes the return value of ``interrupt()``.
|
| 28 |
+
"""
|
| 29 |
+
verdict = state.verdict
|
| 30 |
+
findings = state.final_findings
|
| 31 |
+
repo = state.repo
|
| 32 |
+
pr_number = state.pr_number
|
| 33 |
+
|
| 34 |
+
logger.info("=== HUMAN APPROVAL REQUIRED ===")
|
| 35 |
+
logger.info("Repo: %s | PR #%d", repo, pr_number)
|
| 36 |
+
|
| 37 |
+
if verdict:
|
| 38 |
+
logger.info(
|
| 39 |
+
"Verdict: %s (score=%.1f, approved=%s)",
|
| 40 |
+
verdict.recommendation, verdict.overall_score, verdict.approved,
|
| 41 |
+
)
|
| 42 |
+
logger.info("Summary: %s", verdict.summary)
|
| 43 |
+
|
| 44 |
+
logger.info("Filtered findings: %d", len(findings))
|
| 45 |
+
for f in findings:
|
| 46 |
+
logger.info(
|
| 47 |
+
" [%.2f] %s %s:%dβ%d β %s",
|
| 48 |
+
f.confidence, f.severity.value, f.file_path,
|
| 49 |
+
f.line_start, f.line_end, f.comment[:80],
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
# ββ Interrupt: pause here until the human resumes βββββββββββββββββββββ
|
| 53 |
+
interrupt_payload = {
|
| 54 |
+
"type": "human_approval",
|
| 55 |
+
"repo": repo,
|
| 56 |
+
"pr_number": pr_number,
|
| 57 |
+
"verdict": verdict.model_dump() if verdict else None,
|
| 58 |
+
"findings_count": len(findings),
|
| 59 |
+
"findings": [
|
| 60 |
+
{
|
| 61 |
+
"file_path": f.file_path,
|
| 62 |
+
"line_start": f.line_start,
|
| 63 |
+
"line_end": f.line_end,
|
| 64 |
+
"severity": f.severity.value,
|
| 65 |
+
"category": f.category,
|
| 66 |
+
"comment": f.comment,
|
| 67 |
+
"confidence": f.confidence,
|
| 68 |
+
"suggested_fix": f.suggested_fix,
|
| 69 |
+
}
|
| 70 |
+
for f in findings
|
| 71 |
+
],
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
# This call blocks the graph until the human provides input via resume.
|
| 75 |
+
# The return value is whatever was passed to `Command(resume=...)`.
|
| 76 |
+
human_input: dict = interrupt(interrupt_payload)
|
| 77 |
+
|
| 78 |
+
action: ApprovalAction = human_input.get("action", "reject")
|
| 79 |
+
logger.info("Human decision: %s", action)
|
| 80 |
+
|
| 81 |
+
if action == "reject":
|
| 82 |
+
logger.info("Review rejected by human β no comments will be posted.")
|
| 83 |
+
|
| 84 |
+
if action == "edit":
|
| 85 |
+
edited_findings_raw = human_input.get("findings")
|
| 86 |
+
if edited_findings_raw:
|
| 87 |
+
logger.info("Human edited %d findings before approval.", len(edited_findings_raw))
|
| 88 |
+
|
| 89 |
+
return {
|
| 90 |
+
"human_approved": action == "approve" or action == "edit",
|
| 91 |
+
}
|
nodes/ingestion.py
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
import time
|
| 5 |
+
from typing import Optional
|
| 6 |
+
|
| 7 |
+
import requests
|
| 8 |
+
|
| 9 |
+
from github_client import GitHubSession, resolve_token
|
| 10 |
+
from state import ChangedFile, OpenCodeReviewState
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
logger = logging.getLogger(__name__)
|
| 14 |
+
|
| 15 |
+
GITHUB_API_BASE = "https://api.github.com"
|
| 16 |
+
RAW_CONTENT_BASE = "https://raw.githubusercontent.com"
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
# βββ Custom Exception ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class IngestionError(Exception):
|
| 23 |
+
"""Raised when PR data ingestion fails and the graph cannot continue."""
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _check_rate_limit(response: requests.Response) -> None:
|
| 27 |
+
"""Raise ``IngestionError`` if the API quota is exhausted."""
|
| 28 |
+
remaining = response.headers.get("X-RateLimit-Remaining")
|
| 29 |
+
if remaining is not None and int(remaining) == 0:
|
| 30 |
+
reset_ts = int(response.headers.get("X-RateLimit-Reset", "0"))
|
| 31 |
+
reset_at = time.strftime("%H:%M:%S UTC", time.gmtime(reset_ts))
|
| 32 |
+
raise IngestionError(
|
| 33 |
+
f"GitHub API rate limit exhausted β resets at {reset_at}. "
|
| 34 |
+
"Set the GITHUB_TOKEN environment variable for a much higher limit."
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _parse_owner_repo(repo: str) -> tuple[str, str]:
|
| 39 |
+
"""Split ``owner/repo`` returning ``(owner, repo)``."""
|
| 40 |
+
parts = repo.split("/")
|
| 41 |
+
if len(parts) != 2 or not all(parts):
|
| 42 |
+
raise IngestionError(
|
| 43 |
+
f"Invalid repo format: '{repo}'. Expected 'owner/repo' "
|
| 44 |
+
"(e.g. 'psf/requests')."
|
| 45 |
+
)
|
| 46 |
+
return parts[0], parts[1]
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _fetch_all_pages(url: str, session: requests.Session) -> list[dict]:
|
| 50 |
+
"""Follow ``Link``-header pagination and return every result item.
|
| 51 |
+
|
| 52 |
+
Uses the provided ``session`` (should be a :class:`GitHubSession`) so
|
| 53 |
+
that 401 handling and auth headers are applied automatically.
|
| 54 |
+
"""
|
| 55 |
+
items: list[dict] = []
|
| 56 |
+
while url:
|
| 57 |
+
resp = session.get(url, timeout=30)
|
| 58 |
+
resp.raise_for_status()
|
| 59 |
+
items.extend(resp.json())
|
| 60 |
+
|
| 61 |
+
link_header = resp.headers.get("Link", "")
|
| 62 |
+
next_url: Optional[str] = None
|
| 63 |
+
for part in link_header.split(","):
|
| 64 |
+
part = part.strip()
|
| 65 |
+
if 'rel="next"' in part:
|
| 66 |
+
start = part.index("<") + 1
|
| 67 |
+
end = part.index(">")
|
| 68 |
+
next_url = part[start:end]
|
| 69 |
+
break
|
| 70 |
+
url = next_url
|
| 71 |
+
return items
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def _fetch_file_content(
|
| 75 |
+
owner: str, repo: str, ref: str, path: str, status: str
|
| 76 |
+
) -> str:
|
| 77 |
+
"""Return the full file content from the head branch of the PR.
|
| 78 |
+
|
| 79 |
+
Deleted/removed files return an empty string. Binary files that fail to
|
| 80 |
+
fetch also return an empty string with a warning.
|
| 81 |
+
"""
|
| 82 |
+
if status == "removed":
|
| 83 |
+
return ""
|
| 84 |
+
|
| 85 |
+
url = f"{RAW_CONTENT_BASE}/{owner}/{repo}/{ref}/{path}"
|
| 86 |
+
try:
|
| 87 |
+
resp = requests.get(url, timeout=30)
|
| 88 |
+
if resp.status_code == 404:
|
| 89 |
+
logger.warning("Content not found at %s (may have been deleted/renamed)", path)
|
| 90 |
+
return ""
|
| 91 |
+
resp.raise_for_status()
|
| 92 |
+
return resp.text
|
| 93 |
+
except requests.exceptions.RequestException as exc:
|
| 94 |
+
logger.warning("Could not fetch content for %s: %s", path, exc)
|
| 95 |
+
return ""
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
# βββ Node ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def ingestion_node(state: OpenCodeReviewState) -> dict:
|
| 102 |
+
"""Fetch PR metadata, diff, and changed-file contents from the GitHub API.
|
| 103 |
+
|
| 104 |
+
Requires ``state.repo`` (``"owner/repo"``) and ``state.pr_number`` to be
|
| 105 |
+
set. Returns updates for ``diff`` and ``changed_files``.
|
| 106 |
+
|
| 107 |
+
If ``state.diff`` is already populated (e.g. in tests with a synthetic
|
| 108 |
+
payload) the node is a no-op.
|
| 109 |
+
"""
|
| 110 |
+
# --- Early exit when data is already present (e.g. synthetic payloads) ----
|
| 111 |
+
if state.diff:
|
| 112 |
+
logger.info("PR data already populated β skipping ingestion")
|
| 113 |
+
return {}
|
| 114 |
+
|
| 115 |
+
# ββ Token check before any API calls βββββββββββββββββββββββββββββββββ
|
| 116 |
+
if not resolve_token():
|
| 117 |
+
raise IngestionError(
|
| 118 |
+
"No GitHub token found. OpenCodeReview needs a GitHub token to "
|
| 119 |
+
"fetch PR data.\n\n"
|
| 120 |
+
" Authenticate via GitHub OAuth (recommended):\n"
|
| 121 |
+
" opencodereview auth login\n\n"
|
| 122 |
+
" Or set the GITHUB_TOKEN environment variable:\n"
|
| 123 |
+
" export GITHUB_TOKEN=\"ghp_...\"\n"
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
owner, repo_name = _parse_owner_repo(state.repo)
|
| 127 |
+
pr_number = state.pr_number
|
| 128 |
+
|
| 129 |
+
logger.info("Ingesting PR %s/%s#%d β¦", owner, repo_name, pr_number)
|
| 130 |
+
|
| 131 |
+
# Use GitHubSession for automatic auth + 401 interception
|
| 132 |
+
session = GitHubSession()
|
| 133 |
+
|
| 134 |
+
# -- 1. PR metadata (to obtain the head SHA for content URLs) -------------
|
| 135 |
+
pr_url = f"{GITHUB_API_BASE}/repos/{owner}/{repo_name}/pulls/{pr_number}"
|
| 136 |
+
pr_resp = session.get(pr_url, timeout=30)
|
| 137 |
+
|
| 138 |
+
if pr_resp.status_code == 404:
|
| 139 |
+
raise IngestionError(
|
| 140 |
+
f"PR {owner}/{repo_name}#{pr_number} was not found."
|
| 141 |
+
)
|
| 142 |
+
if pr_resp.status_code in (403, 401):
|
| 143 |
+
_check_rate_limit(pr_resp)
|
| 144 |
+
raise IngestionError(
|
| 145 |
+
f"Access denied to {owner}/{repo_name}#{pr_number}. "
|
| 146 |
+
"If the repo is private, set a valid GITHUB_TOKEN."
|
| 147 |
+
)
|
| 148 |
+
if pr_resp.status_code == 410:
|
| 149 |
+
raise IngestionError(
|
| 150 |
+
f"PR {owner}/{repo_name}#{pr_number} has been deleted."
|
| 151 |
+
)
|
| 152 |
+
pr_resp.raise_for_status()
|
| 153 |
+
|
| 154 |
+
pr_data = pr_resp.json()
|
| 155 |
+
head_sha = pr_data["head"]["sha"]
|
| 156 |
+
head_ref = pr_data["head"]["ref"]
|
| 157 |
+
base_ref = pr_data["base"]["ref"]
|
| 158 |
+
|
| 159 |
+
logger.info(
|
| 160 |
+
"PR #%d β %s β %s β %s (%s)",
|
| 161 |
+
pr_number, pr_data.get("title", "(no title)"),
|
| 162 |
+
base_ref, head_ref, head_sha[:7],
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
# -- 2. Determine where to fetch file content -----------------------------
|
| 166 |
+
# For PRs from forks, the head SHA lives in the fork, not the base repo.
|
| 167 |
+
head_repo_full: str = pr_data["head"]["repo"]["full_name"] # "owner/repo"
|
| 168 |
+
head_owner, head_repo_n = head_repo_full.split("/", 1)
|
| 169 |
+
|
| 170 |
+
# -- 3. Raw unified diff of the whole PR ----------------------------------
|
| 171 |
+
diff_resp = session.get(
|
| 172 |
+
pr_url,
|
| 173 |
+
headers={"Accept": "application/vnd.github.v3.diff"},
|
| 174 |
+
timeout=30,
|
| 175 |
+
)
|
| 176 |
+
diff_resp.raise_for_status()
|
| 177 |
+
diff_text = diff_resp.text
|
| 178 |
+
logger.info("Fetched diff (%s)", _human_size(len(diff_text)))
|
| 179 |
+
|
| 180 |
+
# -- 4. Changed files with per-file patches -------------------------------
|
| 181 |
+
files_url = (
|
| 182 |
+
f"{GITHUB_API_BASE}/repos/{owner}/{repo_name}/pulls/{pr_number}/files"
|
| 183 |
+
)
|
| 184 |
+
logger.info("Fetching changed-files list β¦")
|
| 185 |
+
files_data = _fetch_all_pages(files_url, session)
|
| 186 |
+
logger.info("Changed files: %d", len(files_data))
|
| 187 |
+
|
| 188 |
+
# -- 5. Build ChangedFile objects (full content from the head branch) -----
|
| 189 |
+
changed_files: list[ChangedFile] = []
|
| 190 |
+
for file_info in files_data:
|
| 191 |
+
file_path: str = file_info["filename"]
|
| 192 |
+
status: str = file_info["status"]
|
| 193 |
+
patch: str = file_info.get("patch") or ""
|
| 194 |
+
additions: int = file_info.get("additions", 0)
|
| 195 |
+
deletions: int = file_info.get("deletions", 0)
|
| 196 |
+
|
| 197 |
+
# Fetch from the HEAD repo of the PR (handles fork PRs correctly)
|
| 198 |
+
content = _fetch_file_content(
|
| 199 |
+
head_owner, head_repo_n, head_sha, file_path, status
|
| 200 |
+
)
|
| 201 |
+
|
| 202 |
+
changed_files.append(ChangedFile(
|
| 203 |
+
path=file_path,
|
| 204 |
+
status=status,
|
| 205 |
+
content=content,
|
| 206 |
+
diff_hunk=patch,
|
| 207 |
+
))
|
| 208 |
+
|
| 209 |
+
logger.debug(
|
| 210 |
+
" %s β %s (+%d/-%d, %s content)",
|
| 211 |
+
file_path, status, additions, deletions,
|
| 212 |
+
_human_size(len(content)),
|
| 213 |
+
)
|
| 214 |
+
|
| 215 |
+
return {
|
| 216 |
+
"diff": diff_text,
|
| 217 |
+
"changed_files": changed_files,
|
| 218 |
+
}
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
# βββ Utility βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def _human_size(bytes_: int) -> str:
|
| 225 |
+
"""Return a short human-readable string for a byte count."""
|
| 226 |
+
if bytes_ < 1024:
|
| 227 |
+
return f"{bytes_} B"
|
| 228 |
+
elif bytes_ < 1024 * 1024:
|
| 229 |
+
return f"{bytes_ / 1024:.1f} KiB"
|
| 230 |
+
else:
|
| 231 |
+
return f"{bytes_ / (1024 * 1024):.1f} MiB"
|
nodes/passthrough.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
|
| 5 |
+
from state import OpenCodeReviewState
|
| 6 |
+
|
| 7 |
+
logger = logging.getLogger(__name__)
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def passthrough_node(state: OpenCodeReviewState) -> dict:
|
| 11 |
+
"""Log the current state and return unchanged.
|
| 12 |
+
|
| 13 |
+
This is a placeholder node that proves the graph wiring and checkpointing
|
| 14 |
+
work before any real review logic is added.
|
| 15 |
+
"""
|
| 16 |
+
logger.info("=== Passthrough Node β %s#%d ===", state.repo, state.pr_number)
|
| 17 |
+
logger.info("Files: %d | Chunks: %d | Findings: %d",
|
| 18 |
+
len(state.changed_files),
|
| 19 |
+
len(state.context_chunks),
|
| 20 |
+
len(state.findings))
|
| 21 |
+
logger.info("Verdict: %s", state.verdict.model_dump() if state.verdict else None)
|
| 22 |
+
|
| 23 |
+
# Return empty dict β no state mutations in this placeholder
|
| 24 |
+
return {}
|
nodes/post_results.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
import os
|
| 5 |
+
|
| 6 |
+
import requests
|
| 7 |
+
|
| 8 |
+
from state import OpenCodeReviewState
|
| 9 |
+
|
| 10 |
+
logger = logging.getLogger(__name__)
|
| 11 |
+
|
| 12 |
+
GITHUB_API_BASE = "https://api.github.com"
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def _github_headers() -> dict[str, str]:
|
| 16 |
+
headers: dict[str, str] = {
|
| 17 |
+
"Accept": "application/vnd.github.v3+json",
|
| 18 |
+
"User-Agent": "OpenCodeReview/1.0",
|
| 19 |
+
}
|
| 20 |
+
token = os.environ.get("GITHUB_TOKEN", "").strip()
|
| 21 |
+
if token:
|
| 22 |
+
headers["Authorization"] = f"Bearer {token}"
|
| 23 |
+
return headers
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _post_comment(owner: str, repo: str, pr_number: int, body: str) -> bool:
|
| 27 |
+
"""Post a single PR review comment. Returns True on success."""
|
| 28 |
+
url = (
|
| 29 |
+
f"{GITHUB_API_BASE}/repos/{owner}/{repo}/issues/{pr_number}/comments"
|
| 30 |
+
)
|
| 31 |
+
try:
|
| 32 |
+
resp = requests.post(
|
| 33 |
+
url,
|
| 34 |
+
headers=_github_headers(),
|
| 35 |
+
json={"body": body},
|
| 36 |
+
timeout=30,
|
| 37 |
+
)
|
| 38 |
+
if resp.status_code in (201, 200):
|
| 39 |
+
logger.info("Comment posted to %s/%s#%d", owner, repo, pr_number)
|
| 40 |
+
return True
|
| 41 |
+
else:
|
| 42 |
+
logger.warning(
|
| 43 |
+
"Failed to post comment: HTTP %s β %s",
|
| 44 |
+
resp.status_code, resp.text[:200],
|
| 45 |
+
)
|
| 46 |
+
return False
|
| 47 |
+
except requests.RequestException as exc:
|
| 48 |
+
logger.warning("Failed to post comment: %s", exc)
|
| 49 |
+
return False
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def _build_comment_body(finding: dict) -> str:
|
| 53 |
+
"""Format a single finding as a Markdown PR comment."""
|
| 54 |
+
sev_emoji = {
|
| 55 |
+
"critical": "π¨",
|
| 56 |
+
"high": "β οΈ",
|
| 57 |
+
"medium": "π",
|
| 58 |
+
"low": "π‘",
|
| 59 |
+
"info": "βΉοΈ",
|
| 60 |
+
}
|
| 61 |
+
emoji = sev_emoji.get(finding["severity"], "π")
|
| 62 |
+
fix_section = ""
|
| 63 |
+
if finding.get("suggested_fix"):
|
| 64 |
+
fix_section = f"\n\n**Suggested fix:**\n```\n{finding['suggested_fix']}\n```"
|
| 65 |
+
|
| 66 |
+
return (
|
| 67 |
+
f"{emoji} **{finding['severity'].upper()}** β "
|
| 68 |
+
f"*{finding['category']}* \n"
|
| 69 |
+
f"**File:** `{finding['file_path']}` \n"
|
| 70 |
+
f"**Lines:** {finding['line_start']}β{finding['line_end']} \n"
|
| 71 |
+
f"**Confidence:** {finding['confidence']:.0%} \n\n"
|
| 72 |
+
f"{finding['comment']}{fix_section}"
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def _build_verdict_body(verdict_dict: dict) -> str:
|
| 77 |
+
"""Format the overall verdict as a Markdown PR comment."""
|
| 78 |
+
icon = {"approve": "β
", "request_changes": "π", "block": "π«", "comment": "π¬"}
|
| 79 |
+
emoji = icon.get(verdict_dict.get("recommendation", ""), "π")
|
| 80 |
+
summary = verdict_dict.get("summary", "")
|
| 81 |
+
score = verdict_dict.get("overall_score", 0)
|
| 82 |
+
return (
|
| 83 |
+
f"## OpenCodeReview β {emoji} {verdict_dict['recommendation'].upper()}\n\n"
|
| 84 |
+
f"**Score:** {score}/10 \n"
|
| 85 |
+
f"**Summary:** {summary}\n"
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def post_results_node(state: OpenCodeReviewState) -> dict:
|
| 90 |
+
"""Post the approved findings and verdict as GitHub PR comments.
|
| 91 |
+
|
| 92 |
+
Only runs if the human approved (``state.human_approved is True``).
|
| 93 |
+
Requires ``GITHUB_TOKEN`` to post.
|
| 94 |
+
"""
|
| 95 |
+
if not state.human_approved:
|
| 96 |
+
logger.info("Not approved β skipping PR comment posting")
|
| 97 |
+
return {}
|
| 98 |
+
|
| 99 |
+
# Parse owner/repo
|
| 100 |
+
parts = state.repo.split("/")
|
| 101 |
+
if len(parts) != 2:
|
| 102 |
+
logger.warning("Cannot post results: invalid repo '%s'", state.repo)
|
| 103 |
+
return {}
|
| 104 |
+
owner, repo_name = parts
|
| 105 |
+
pr_number = state.pr_number
|
| 106 |
+
|
| 107 |
+
gh_token = os.environ.get("GITHUB_TOKEN", "").strip()
|
| 108 |
+
if not gh_token:
|
| 109 |
+
logger.warning(
|
| 110 |
+
"GITHUB_TOKEN not set β cannot post to %s/%s#%d. "
|
| 111 |
+
"Results logged instead.",
|
| 112 |
+
owner, repo_name, pr_number,
|
| 113 |
+
)
|
| 114 |
+
# Log what we would have posted
|
| 115 |
+
if state.verdict:
|
| 116 |
+
logger.info("[WOULD POST] Verdict: %s", state.verdict.summary)
|
| 117 |
+
for f in state.final_findings:
|
| 118 |
+
logger.info(
|
| 119 |
+
"[WOULD POST] %s:%dβ%d %s β %s",
|
| 120 |
+
f.file_path, f.line_start, f.line_end,
|
| 121 |
+
f.severity.value, f.comment[:60],
|
| 122 |
+
)
|
| 123 |
+
return {}
|
| 124 |
+
|
| 125 |
+
# Post verdict as the first comment
|
| 126 |
+
if state.verdict:
|
| 127 |
+
verdict_body = _build_verdict_body(state.verdict.model_dump())
|
| 128 |
+
_post_comment(owner, repo_name, pr_number, verdict_body)
|
| 129 |
+
|
| 130 |
+
# Post each finding as a separate comment
|
| 131 |
+
findings_data = [
|
| 132 |
+
{
|
| 133 |
+
"file_path": f.file_path,
|
| 134 |
+
"line_start": f.line_start,
|
| 135 |
+
"line_end": f.line_end,
|
| 136 |
+
"severity": f.severity.value,
|
| 137 |
+
"category": f.category,
|
| 138 |
+
"comment": f.comment,
|
| 139 |
+
"confidence": f.confidence,
|
| 140 |
+
"suggested_fix": f.suggested_fix,
|
| 141 |
+
}
|
| 142 |
+
for f in state.final_findings
|
| 143 |
+
]
|
| 144 |
+
|
| 145 |
+
for fd in findings_data:
|
| 146 |
+
comment_body = _build_comment_body(fd)
|
| 147 |
+
_post_comment(owner, repo_name, pr_number, comment_body)
|
| 148 |
+
|
| 149 |
+
logger.info(
|
| 150 |
+
"Posted %d finding(s) + verdict to %s/%s#%d",
|
| 151 |
+
len(findings_data), owner, repo_name, pr_number,
|
| 152 |
+
)
|
| 153 |
+
return {}
|
nodes/retrieval.py
ADDED
|
@@ -0,0 +1,455 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
import os
|
| 5 |
+
import re
|
| 6 |
+
import tempfile
|
| 7 |
+
import uuid
|
| 8 |
+
from typing import Optional
|
| 9 |
+
|
| 10 |
+
import requests
|
| 11 |
+
|
| 12 |
+
# --- ChromaDB needs to be imported with a guard because the ONNX runtime may
|
| 13 |
+
# pull in extra dependencies on first load.
|
| 14 |
+
try:
|
| 15 |
+
import chromadb
|
| 16 |
+
from chromadb.api.models.Collection import Collection
|
| 17 |
+
from chromadb.utils import embedding_functions
|
| 18 |
+
except ImportError:
|
| 19 |
+
chromadb = None # type: ignore[assignment]
|
| 20 |
+
Collection = None # type: ignore[assignment,misc]
|
| 21 |
+
embedding_functions = None # type: ignore[assignment]
|
| 22 |
+
|
| 23 |
+
from github_client import GitHubSession
|
| 24 |
+
from state import ContextChunk, OpenCodeReviewState
|
| 25 |
+
|
| 26 |
+
logger = logging.getLogger(__name__)
|
| 27 |
+
|
| 28 |
+
GITHUB_API_BASE = "https://api.github.com"
|
| 29 |
+
RAW_CONTENT_BASE = "https://raw.githubusercontent.com"
|
| 30 |
+
|
| 31 |
+
# How many chunks to retrieve per query
|
| 32 |
+
TOP_K = 15
|
| 33 |
+
# Max size (characters) for a single chunk
|
| 34 |
+
CHUNK_MAX_CHARS = 1_200
|
| 35 |
+
# How many merged PR discussions to fetch
|
| 36 |
+
MERGED_PR_LIMIT = 20
|
| 37 |
+
|
| 38 |
+
# Extensions we consider "source code" worth embedding
|
| 39 |
+
SOURCE_EXTENSIONS = {
|
| 40 |
+
".py", ".js", ".ts", ".jsx", ".tsx", ".go", ".rs", ".java", ".rb", ".php",
|
| 41 |
+
".c", ".cpp", ".h", ".hpp", ".cs", ".swift", ".kt", ".scala",
|
| 42 |
+
".md", ".rst", ".txt",
|
| 43 |
+
".yml", ".yaml", ".toml", ".cfg", ".ini",
|
| 44 |
+
".sql", ".sh", ".bash", ".zsh",
|
| 45 |
+
".html", ".css", ".scss",
|
| 46 |
+
}
|
| 47 |
+
# Files we always include if they exist
|
| 48 |
+
ALWAYS_INCLUDE = {
|
| 49 |
+
"CONTRIBUTING.md", "CONTRIBUTING.rst",
|
| 50 |
+
"README.md", "README.rst",
|
| 51 |
+
"CODE_OF_CONDUCT.md",
|
| 52 |
+
"STYLE_GUIDE.md",
|
| 53 |
+
".github/CONTRIBUTING.md",
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
# βββ Helpers: GitHub API ββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
_GITHUB_SESSION: GitHubSession | None = None
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def _gh_session() -> GitHubSession:
|
| 64 |
+
"""Return a lazily-initialized :class:`GitHubSession` for the retrieval
|
| 65 |
+
node. The session is cached across calls within the same PR review."""
|
| 66 |
+
global _GITHUB_SESSION
|
| 67 |
+
if _GITHUB_SESSION is None:
|
| 68 |
+
_GITHUB_SESSION = GitHubSession()
|
| 69 |
+
return _GITHUB_SESSION
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def _get_json(url: str) -> Optional[dict | list]:
|
| 73 |
+
"""GET and return parsed JSON, or None on non-200, logging warnings.
|
| 74 |
+
|
| 75 |
+
Uses :class:`GitHubSession` so 401 responses raise
|
| 76 |
+
:class:`TokenRevokedError` automatically.
|
| 77 |
+
"""
|
| 78 |
+
try:
|
| 79 |
+
resp = _gh_session().get(url, timeout=30)
|
| 80 |
+
if resp.status_code == 200:
|
| 81 |
+
return resp.json()
|
| 82 |
+
logger.warning("GitHub API %s returned %s", url.split("?")[0], resp.status_code)
|
| 83 |
+
return None
|
| 84 |
+
except requests.RequestException as exc:
|
| 85 |
+
logger.warning("GitHub API request failed for %s: %s", url.split("?")[0], exc)
|
| 86 |
+
return None
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
# βββ Helpers: chunking ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def _chunk_python_source(file_path: str, content: str) -> list[dict]:
|
| 93 |
+
"""Split Python source at top-level ``def`` / ``class`` / ``async def``."""
|
| 94 |
+
chunks: list[dict] = []
|
| 95 |
+
lines = content.splitlines(keepends=True)
|
| 96 |
+
# Regex matches start of a top-level (non-indented) definition
|
| 97 |
+
pattern = re.compile(r"^(async\s+)?(def |class )")
|
| 98 |
+
current_start = 0
|
| 99 |
+
for i, line in enumerate(lines):
|
| 100 |
+
if i > 0 and pattern.match(line) and not line.startswith(" "):
|
| 101 |
+
block = "".join(lines[current_start:i]).strip()
|
| 102 |
+
if block:
|
| 103 |
+
chunks.append({
|
| 104 |
+
"text": block,
|
| 105 |
+
"type": _classify_chunk(block),
|
| 106 |
+
})
|
| 107 |
+
current_start = i
|
| 108 |
+
# Last block
|
| 109 |
+
remaining = "".join(lines[current_start:]).strip()
|
| 110 |
+
if remaining:
|
| 111 |
+
chunks.append({"text": remaining, "type": _classify_chunk(remaining)})
|
| 112 |
+
return chunks
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def _chunk_generic(content: str) -> list[dict]:
|
| 116 |
+
"""Split text by blank lines into paragraphs, merging very short ones."""
|
| 117 |
+
paragraphs = re.split(r"\n\s*\n", content)
|
| 118 |
+
chunks: list[dict] = []
|
| 119 |
+
buffer = ""
|
| 120 |
+
for para in paragraphs:
|
| 121 |
+
para = para.strip()
|
| 122 |
+
if not para:
|
| 123 |
+
continue
|
| 124 |
+
if len(buffer) + len(para) < CHUNK_MAX_CHARS:
|
| 125 |
+
buffer = (buffer + "\n\n" + para).strip()
|
| 126 |
+
else:
|
| 127 |
+
if buffer:
|
| 128 |
+
chunks.append({"text": buffer, "type": "paragraph"})
|
| 129 |
+
buffer = para
|
| 130 |
+
if buffer:
|
| 131 |
+
chunks.append({"text": buffer, "type": "paragraph"})
|
| 132 |
+
return chunks
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def _classify_chunk(text: str) -> str:
|
| 136 |
+
"""Return ``function``, ``class``, or ``code``."""
|
| 137 |
+
if text.startswith("class "):
|
| 138 |
+
return "class"
|
| 139 |
+
if text.startswith(("def ", "async def ")):
|
| 140 |
+
return "function"
|
| 141 |
+
return "code"
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def _chunk_source(file_path: str, content: str) -> list[dict]:
|
| 145 |
+
"""Chunk a source file into semantically meaningful pieces."""
|
| 146 |
+
if file_path.endswith(".py"):
|
| 147 |
+
return _chunk_python_source(file_path, content)
|
| 148 |
+
return _chunk_generic(content)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def _should_include(path: str) -> bool:
|
| 152 |
+
"""Return True for file paths we want to embed (source code, docs)."""
|
| 153 |
+
if path in ALWAYS_INCLUDE:
|
| 154 |
+
return True
|
| 155 |
+
# Skip hidden files, test data, vendored deps
|
| 156 |
+
parts = path.replace("\\", "/").split("/")
|
| 157 |
+
if any(p.startswith(".") for p in parts):
|
| 158 |
+
return False
|
| 159 |
+
if "test" in path.lower() or "spec" in path.lower() or "__pycache__" in path:
|
| 160 |
+
return False
|
| 161 |
+
if any(p in ("venv", ".venv", "node_modules", "vendor", "dist", "build") for p in parts):
|
| 162 |
+
return False
|
| 163 |
+
ext = os.path.splitext(path)[1].lower()
|
| 164 |
+
return ext in SOURCE_EXTENSIONS
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
# βββ Helpers: building the vector store βββββββββββββββββββββββββββββββββββββ
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
_VECTOR_DIR: str | None = None
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def _ensure_vector_dir() -> str:
|
| 174 |
+
global _VECTOR_DIR
|
| 175 |
+
if _VECTOR_DIR is None:
|
| 176 |
+
_VECTOR_DIR = os.path.join(
|
| 177 |
+
tempfile.gettempdir(), "opencodereview_vectors"
|
| 178 |
+
)
|
| 179 |
+
os.makedirs(_VECTOR_DIR, exist_ok=True)
|
| 180 |
+
return _VECTOR_DIR
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def _repo_collection_name(repo: str) -> str:
|
| 184 |
+
return f"repo_{repo.replace('/', '_')}"
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def _build_vector_store(
|
| 188 |
+
owner: str, repo_name: str,
|
| 189 |
+
head_sha: str,
|
| 190 |
+
exclude_paths: set[str],
|
| 191 |
+
) -> Collection:
|
| 192 |
+
"""Fetch, chunk, embed, and index the non-changed files + past PRs.
|
| 193 |
+
|
| 194 |
+
Each data source (codebase, past PRs, docs) is added to ChromaDB
|
| 195 |
+
incrementally so a transient failure in one source does not lose
|
| 196 |
+
progress from earlier sources.
|
| 197 |
+
"""
|
| 198 |
+
|
| 199 |
+
if chromadb is None:
|
| 200 |
+
raise RuntimeError("chromadb is not installed β cannot build vector store")
|
| 201 |
+
|
| 202 |
+
ef = embedding_functions.SentenceTransformerEmbeddingFunction(
|
| 203 |
+
model_name="all-MiniLM-L6-v2"
|
| 204 |
+
)
|
| 205 |
+
client = chromadb.PersistentClient(path=_ensure_vector_dir())
|
| 206 |
+
coll_name = _repo_collection_name(f"{owner}/{repo_name}")
|
| 207 |
+
|
| 208 |
+
# Drop and rebuild so the index is always fresh
|
| 209 |
+
try:
|
| 210 |
+
client.delete_collection(coll_name)
|
| 211 |
+
except Exception:
|
| 212 |
+
pass
|
| 213 |
+
collection = client.create_collection(
|
| 214 |
+
name=coll_name,
|
| 215 |
+
metadata={"hnsw:space": "cosine"},
|
| 216 |
+
embedding_function=ef,
|
| 217 |
+
)
|
| 218 |
+
|
| 219 |
+
total_added = 0
|
| 220 |
+
|
| 221 |
+
# ---- 1. Source files from the repo (excluding changed files) ------------
|
| 222 |
+
logger.info("Fetching repo file tree (base branch) β¦")
|
| 223 |
+
tree_url = (
|
| 224 |
+
f"{GITHUB_API_BASE}/repos/{owner}/{repo_name}/git/trees/"
|
| 225 |
+
f"{head_sha}?recursive=1"
|
| 226 |
+
)
|
| 227 |
+
tree_data = _get_json(tree_url)
|
| 228 |
+
if tree_data and isinstance(tree_data, dict):
|
| 229 |
+
tree_items: list[dict] = tree_data.get("tree", [])
|
| 230 |
+
source_paths = [
|
| 231 |
+
item["path"]
|
| 232 |
+
for item in tree_items
|
| 233 |
+
if item["type"] == "blob"
|
| 234 |
+
and _should_include(item["path"])
|
| 235 |
+
and item["path"] not in exclude_paths
|
| 236 |
+
]
|
| 237 |
+
logger.info("Source files to embed (excl. changed): %d", len(source_paths))
|
| 238 |
+
|
| 239 |
+
code_docs: list[str] = []
|
| 240 |
+
code_metadatas: list[dict] = []
|
| 241 |
+
code_ids: list[str] = []
|
| 242 |
+
|
| 243 |
+
for fp in source_paths:
|
| 244 |
+
raw_url = f"{RAW_CONTENT_BASE}/{owner}/{repo_name}/{head_sha}/{fp}"
|
| 245 |
+
try:
|
| 246 |
+
resp = requests.get(raw_url, timeout=30)
|
| 247 |
+
if resp.status_code != 200:
|
| 248 |
+
continue
|
| 249 |
+
content = resp.text
|
| 250 |
+
except requests.RequestException:
|
| 251 |
+
continue
|
| 252 |
+
|
| 253 |
+
file_chunks = _chunk_source(fp, content)
|
| 254 |
+
for chunk in file_chunks:
|
| 255 |
+
code_docs.append(chunk["text"])
|
| 256 |
+
code_metadatas.append({
|
| 257 |
+
"source": "codebase",
|
| 258 |
+
"file_path": fp,
|
| 259 |
+
"chunk_type": chunk["type"],
|
| 260 |
+
})
|
| 261 |
+
code_ids.append(str(uuid.uuid4()))
|
| 262 |
+
|
| 263 |
+
if code_docs:
|
| 264 |
+
collection.add(
|
| 265 |
+
documents=code_docs,
|
| 266 |
+
metadatas=code_metadatas,
|
| 267 |
+
ids=code_ids,
|
| 268 |
+
)
|
| 269 |
+
total_added += len(code_docs)
|
| 270 |
+
logger.info("Code chunks indexed: %d", len(code_docs))
|
| 271 |
+
else:
|
| 272 |
+
logger.warning("Could not fetch repo file tree β continuing with past PRs only")
|
| 273 |
+
|
| 274 |
+
# ---- 2. Past merged PR discussions --------------------------------------
|
| 275 |
+
prs_url = (
|
| 276 |
+
f"{GITHUB_API_BASE}/repos/{owner}/{repo_name}/pulls"
|
| 277 |
+
f"?state=closed&per_page={MERGED_PR_LIMIT}&sort=updated&direction=desc"
|
| 278 |
+
)
|
| 279 |
+
try:
|
| 280 |
+
prs_data = _get_json(prs_url)
|
| 281 |
+
if prs_data and isinstance(prs_data, list):
|
| 282 |
+
pr_docs: list[str] = []
|
| 283 |
+
pr_metadatas: list[dict] = []
|
| 284 |
+
pr_ids: list[str] = []
|
| 285 |
+
|
| 286 |
+
for pr_item in prs_data:
|
| 287 |
+
if not pr_item.get("merged_at"):
|
| 288 |
+
continue
|
| 289 |
+
pr_number = pr_item["number"]
|
| 290 |
+
title = pr_item.get("title", "")
|
| 291 |
+
body = pr_item.get("body") or ""
|
| 292 |
+
text = f"PR #{pr_number}: {title}\n\n{body}".strip()
|
| 293 |
+
if len(text) < 50:
|
| 294 |
+
continue
|
| 295 |
+
chunks = _chunk_generic(text)
|
| 296 |
+
for chunk in chunks:
|
| 297 |
+
pr_docs.append(chunk["text"])
|
| 298 |
+
pr_metadatas.append({
|
| 299 |
+
"source": "past_pr",
|
| 300 |
+
"file_path": f"PR #{pr_number}",
|
| 301 |
+
"chunk_type": "discussion",
|
| 302 |
+
})
|
| 303 |
+
pr_ids.append(str(uuid.uuid4()))
|
| 304 |
+
|
| 305 |
+
if pr_docs:
|
| 306 |
+
collection.add(
|
| 307 |
+
documents=pr_docs,
|
| 308 |
+
metadatas=pr_metadatas,
|
| 309 |
+
ids=pr_ids,
|
| 310 |
+
)
|
| 311 |
+
total_added += len(pr_docs)
|
| 312 |
+
logger.info("Past-PR chunks indexed: %d", len(pr_docs))
|
| 313 |
+
except Exception as exc:
|
| 314 |
+
logger.warning("Failed to fetch past PRs (continuing without them): %s", exc)
|
| 315 |
+
|
| 316 |
+
# ---- 3. CONTRIBUTING.md / docs ------------------------------------------
|
| 317 |
+
doc_batch_docs: list[str] = []
|
| 318 |
+
doc_batch_metas: list[dict] = []
|
| 319 |
+
doc_batch_ids: list[str] = []
|
| 320 |
+
|
| 321 |
+
for doc_path in ALWAYS_INCLUDE:
|
| 322 |
+
raw_url = f"{RAW_CONTENT_BASE}/{owner}/{repo_name}/{head_sha}/{doc_path}"
|
| 323 |
+
try:
|
| 324 |
+
resp = requests.get(raw_url, timeout=15)
|
| 325 |
+
if resp.status_code == 200 and len(resp.text) > 50:
|
| 326 |
+
chunks = _chunk_generic(resp.text)
|
| 327 |
+
for chunk in chunks:
|
| 328 |
+
doc_batch_docs.append(chunk["text"])
|
| 329 |
+
doc_batch_metas.append({
|
| 330 |
+
"source": "codebase",
|
| 331 |
+
"file_path": doc_path,
|
| 332 |
+
"chunk_type": "docs",
|
| 333 |
+
})
|
| 334 |
+
doc_batch_ids.append(str(uuid.uuid4()))
|
| 335 |
+
logger.info(" Added docs: %s", doc_path)
|
| 336 |
+
except requests.RequestException:
|
| 337 |
+
pass
|
| 338 |
+
|
| 339 |
+
if doc_batch_docs:
|
| 340 |
+
collection.add(
|
| 341 |
+
documents=doc_batch_docs,
|
| 342 |
+
metadatas=doc_batch_metas,
|
| 343 |
+
ids=doc_batch_ids,
|
| 344 |
+
)
|
| 345 |
+
total_added += len(doc_batch_docs)
|
| 346 |
+
|
| 347 |
+
if total_added:
|
| 348 |
+
logger.info(
|
| 349 |
+
"Vector store built β %d total chunks in '%s'",
|
| 350 |
+
total_added, coll_name,
|
| 351 |
+
)
|
| 352 |
+
else:
|
| 353 |
+
logger.warning("Vector store is empty β no documents to index")
|
| 354 |
+
|
| 355 |
+
return collection
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
# βββ Retrieval node ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
def retrieval_node(state: OpenCodeReviewState) -> dict:
|
| 362 |
+
"""Build (once per repo) a vector store of the codebase + past PRs, then
|
| 363 |
+
query it with the current PR diff to find relevant context chunks.
|
| 364 |
+
|
| 365 |
+
Returns state updates for ``context_chunks``.
|
| 366 |
+
"""
|
| 367 |
+
# -- Bail out early if there is no diff to query against ------------------
|
| 368 |
+
if not state.diff:
|
| 369 |
+
logger.info("No diff available β skipping retrieval")
|
| 370 |
+
return {}
|
| 371 |
+
|
| 372 |
+
# -- Parse identifiers ----------------------------------------------------
|
| 373 |
+
parts = state.repo.split("/")
|
| 374 |
+
if len(parts) != 2:
|
| 375 |
+
logger.warning("Invalid repo format '%s' β skipping retrieval", state.repo)
|
| 376 |
+
return {}
|
| 377 |
+
owner, repo_name = parts
|
| 378 |
+
|
| 379 |
+
changed_paths: set[str] = {f.path for f in state.changed_files}
|
| 380 |
+
|
| 381 |
+
# -- Build (or load) the vector store for this repo -----------------------
|
| 382 |
+
# Use head_sha from the diff structure β we don't have it directly, so we
|
| 383 |
+
# parse the first line of the diff for the repo context.
|
| 384 |
+
# For the vector store, we use a placeholder ref β the store is rebuilt
|
| 385 |
+
# each session anyway.
|
| 386 |
+
head_sha_for_tree = "HEAD" # GitHub resolves this to the default branch
|
| 387 |
+
|
| 388 |
+
if chromadb is None:
|
| 389 |
+
logger.warning("chromadb not available β returning empty context")
|
| 390 |
+
return {}
|
| 391 |
+
|
| 392 |
+
try:
|
| 393 |
+
collection = _build_vector_store(
|
| 394 |
+
owner, repo_name, head_sha_for_tree, changed_paths,
|
| 395 |
+
)
|
| 396 |
+
except Exception as exc:
|
| 397 |
+
logger.warning("Failed to build vector store: %s", exc)
|
| 398 |
+
return {}
|
| 399 |
+
|
| 400 |
+
# -- Query the store with the diff ----------------------------------------
|
| 401 |
+
# Use a truncated version of the diff as the query for relevance
|
| 402 |
+
query = state.diff
|
| 403 |
+
if len(query) > 8_000:
|
| 404 |
+
# Chroma has a max input length for the embedding model
|
| 405 |
+
query = query[:8_000]
|
| 406 |
+
|
| 407 |
+
try:
|
| 408 |
+
results = collection.query(
|
| 409 |
+
query_texts=[query],
|
| 410 |
+
n_results=TOP_K,
|
| 411 |
+
)
|
| 412 |
+
except Exception as exc:
|
| 413 |
+
logger.warning("Vector store query failed: %s", exc)
|
| 414 |
+
return {}
|
| 415 |
+
|
| 416 |
+
# -- Build ContextChunk objects from results ------------------------------
|
| 417 |
+
context_chunks: list[ContextChunk] = []
|
| 418 |
+
if results and results.get("documents") and results["documents"][0]:
|
| 419 |
+
docs_list = results["documents"][0]
|
| 420 |
+
meta_list = results["metadatas"][0] if results.get("metadatas") else []
|
| 421 |
+
dist_list = results["distances"][0] if results.get("distances") else []
|
| 422 |
+
|
| 423 |
+
for i, doc_text in enumerate(docs_list):
|
| 424 |
+
meta: dict = meta_list[i] if i < len(meta_list) else {}
|
| 425 |
+
dist: float = dist_list[i] if i < len(dist_list) else 0.0
|
| 426 |
+
# Convert distance to a relevance score (cosine distance β 1 - d)
|
| 427 |
+
relevance = max(0.0, min(1.0, 1.0 - dist))
|
| 428 |
+
|
| 429 |
+
context_chunks.append(ContextChunk(
|
| 430 |
+
source=meta.get("source", "codebase"),
|
| 431 |
+
file_path=meta.get("file_path", ""),
|
| 432 |
+
content=doc_text,
|
| 433 |
+
relevance_score=round(relevance, 3),
|
| 434 |
+
))
|
| 435 |
+
|
| 436 |
+
logger.info(
|
| 437 |
+
"Retrieved %d context chunks (query=%s)",
|
| 438 |
+
len(context_chunks), _human_size(len(state.diff)),
|
| 439 |
+
)
|
| 440 |
+
|
| 441 |
+
return {
|
| 442 |
+
"context_chunks": context_chunks, # Annotated[..., add] β accumulated
|
| 443 |
+
}
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
# βββ Utility βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 447 |
+
|
| 448 |
+
|
| 449 |
+
def _human_size(bytes_: int) -> str:
|
| 450 |
+
if bytes_ < 1024:
|
| 451 |
+
return f"{bytes_} B"
|
| 452 |
+
elif bytes_ < 1024 * 1024:
|
| 453 |
+
return f"{bytes_ / 1024:.1f} KiB"
|
| 454 |
+
else:
|
| 455 |
+
return f"{bytes_ / (1024 * 1024):.1f} MiB"
|
nodes/security_reviewer.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
import os
|
| 5 |
+
|
| 6 |
+
from langchain_groq import ChatGroq
|
| 7 |
+
from pydantic import BaseModel, Field
|
| 8 |
+
|
| 9 |
+
from state import Finding, OpenCodeReviewState
|
| 10 |
+
|
| 11 |
+
logger = logging.getLogger(__name__)
|
| 12 |
+
|
| 13 |
+
GROQ_MODEL = "llama-3.3-70b-versatile"
|
| 14 |
+
DEFAULT_TEMPERATURE = 0.0
|
| 15 |
+
MAX_CONTEXT_CHARS = 6_000
|
| 16 |
+
MAX_FILE_CONTENT_CHARS = 4_000
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
# βββ Wrapper schema ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class SecurityReview(BaseModel):
|
| 23 |
+
"""Security issues found during code review."""
|
| 24 |
+
findings: list[Finding] = Field(
|
| 25 |
+
default_factory=list,
|
| 26 |
+
description="Security issues found in the PR diff.",
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
# βββ Prompt βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
SYSTEM_PROMPT = """You are a security-focused code reviewer. Analyse the PR diff and
|
| 34 |
+
changed files for security vulnerabilities ONLY. Look for:
|
| 35 |
+
|
| 36 |
+
1. **Injection** β SQL, NoSQL, command, template (SSTI), LDAP, XSS, path
|
| 37 |
+
traversal via unsanitized user input.
|
| 38 |
+
2. **Secrets / credentials** β hardcoded API keys, tokens, passwords, or
|
| 39 |
+
connection strings that should use environment variables or a secret store.
|
| 40 |
+
3. **Unsafe deserialization** β `pickle.loads`, `yaml.load(β¦)` without
|
| 41 |
+
SafeLoader, `eval`, `exec`, or `marshal` on untrusted data.
|
| 42 |
+
4. **Authentication / authorisation** β missing or broken access control
|
| 43 |
+
checks, privilege escalation paths, session fixation, weak password hashing.
|
| 44 |
+
5. **Input validation** β missing or insufficient validation of user-supplied
|
| 45 |
+
data that could lead to buffer overflows, integer overflows, or format-string
|
| 46 |
+
bugs.
|
| 47 |
+
6. **Cryptographic misuse** β weak algorithms (MD5, SHA1 for signatures),
|
| 48 |
+
hardcoded IVs/nonces, ECB mode, insufficient key lengths, missing TLS.
|
| 49 |
+
7. **Information disclosure** β stack traces leaked to users, verbose error
|
| 50 |
+
messages exposing internals, debug endpoints left enabled.
|
| 51 |
+
|
| 52 |
+
**Do NOT** comment on:
|
| 53 |
+
- Code style, formatting, naming conventions.
|
| 54 |
+
- Performance (unless it creates a denial-of-service vector).
|
| 55 |
+
- General logic errors or edge cases (handled by correctness reviewer).
|
| 56 |
+
|
| 57 |
+
For each issue return a `Finding` with:
|
| 58 |
+
- `file_path`, `line_start`, `line_end`: location in the diff.
|
| 59 |
+
- `severity`: `critical` (remotely exploitable), `high` (privilege escalation),
|
| 60 |
+
`medium` (information disclosure), `low` (defence in depth), or `info`.
|
| 61 |
+
- `category`: always `"security"`.
|
| 62 |
+
- `comment`: concise, actionable explanation.
|
| 63 |
+
- `confidence`: 0.0β1.0.
|
| 64 |
+
- `suggested_fix`: concrete code snippet if applicable.
|
| 65 |
+
|
| 66 |
+
Return an empty findings list if no security issues are found.
|
| 67 |
+
"""
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _build_prompt(state: OpenCodeReviewState) -> str:
|
| 71 |
+
lines: list[str] = []
|
| 72 |
+
|
| 73 |
+
lines.append("## Diff\n```diff")
|
| 74 |
+
lines.append(state.diff or "")
|
| 75 |
+
lines.append("```\n")
|
| 76 |
+
|
| 77 |
+
if state.changed_files:
|
| 78 |
+
lines.append("## Changed files\n")
|
| 79 |
+
for cf in state.changed_files:
|
| 80 |
+
lines.append(f"### {cf.path} ({cf.status})")
|
| 81 |
+
content = cf.content or ""
|
| 82 |
+
if len(content) > MAX_FILE_CONTENT_CHARS:
|
| 83 |
+
content = content[:MAX_FILE_CONTENT_CHARS] + "\n⦠(truncated)"
|
| 84 |
+
lines.append(f"```\n{content}\n```\n")
|
| 85 |
+
|
| 86 |
+
if state.context_chunks:
|
| 87 |
+
lines.append("## Retrieved context\n")
|
| 88 |
+
ctx_chars = 0
|
| 89 |
+
for chunk in state.context_chunks:
|
| 90 |
+
snippet = chunk.content
|
| 91 |
+
if ctx_chars + len(snippet) > MAX_CONTEXT_CHARS:
|
| 92 |
+
remaining = MAX_CONTEXT_CHARS - ctx_chars
|
| 93 |
+
if remaining > 200:
|
| 94 |
+
lines.append(f"> {snippet[:remaining]}β¦ (truncated)")
|
| 95 |
+
break
|
| 96 |
+
prefix = "Past PR" if chunk.source == "past_pr" else chunk.file_path
|
| 97 |
+
lines.append(f"> [{prefix}]: {snippet}")
|
| 98 |
+
ctx_chars += len(snippet)
|
| 99 |
+
|
| 100 |
+
return "\n".join(lines)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
# βββ Node ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def security_reviewer_node(state: OpenCodeReviewState) -> dict:
|
| 107 |
+
api_key = os.environ.get("GROQ_API_KEY", "").strip()
|
| 108 |
+
if not api_key:
|
| 109 |
+
logger.warning("GROQ_API_KEY not set β skipping security review")
|
| 110 |
+
return {}
|
| 111 |
+
|
| 112 |
+
if not state.diff:
|
| 113 |
+
logger.info("No diff to review β skipping security review")
|
| 114 |
+
return {}
|
| 115 |
+
|
| 116 |
+
llm = ChatGroq(model=GROQ_MODEL, temperature=DEFAULT_TEMPERATURE, api_key=api_key)
|
| 117 |
+
structured_llm = llm.with_structured_output(SecurityReview)
|
| 118 |
+
|
| 119 |
+
user_prompt = _build_prompt(state)
|
| 120 |
+
logger.info(
|
| 121 |
+
"Invoking security reviewer (diff=%s, context=%d chunks)",
|
| 122 |
+
_human_size(len(state.diff or "")),
|
| 123 |
+
len(state.context_chunks),
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
try:
|
| 127 |
+
messages = [
|
| 128 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 129 |
+
{"role": "user", "content": user_prompt},
|
| 130 |
+
]
|
| 131 |
+
result: SecurityReview = structured_llm.invoke(messages) # type: ignore[assignment]
|
| 132 |
+
except Exception as exc:
|
| 133 |
+
logger.warning("Security review LLM call failed: %s", exc)
|
| 134 |
+
return {}
|
| 135 |
+
|
| 136 |
+
if result.findings:
|
| 137 |
+
logger.info("Security review found %d issue(s)", len(result.findings))
|
| 138 |
+
for f in result.findings:
|
| 139 |
+
logger.debug(" [%.2f] %s:%dβ%d β %s", f.confidence, f.file_path, f.line_start, f.line_end, f.comment[:80])
|
| 140 |
+
else:
|
| 141 |
+
logger.info("Security review found no issues")
|
| 142 |
+
|
| 143 |
+
return {"findings": result.findings}
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def _human_size(bytes_: int) -> str:
|
| 147 |
+
if bytes_ < 1024:
|
| 148 |
+
return f"{bytes_} B"
|
| 149 |
+
elif bytes_ < 1024 * 1024:
|
| 150 |
+
return f"{bytes_ / 1024:.1f} KiB"
|
| 151 |
+
else:
|
| 152 |
+
return f"{bytes_ / (1024 * 1024):.1f} MiB"
|
nodes/test_coverage_reviewer.py
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
import os
|
| 5 |
+
|
| 6 |
+
from langchain_groq import ChatGroq
|
| 7 |
+
from pydantic import BaseModel, Field
|
| 8 |
+
|
| 9 |
+
from state import Finding, OpenCodeReviewState
|
| 10 |
+
|
| 11 |
+
logger = logging.getLogger(__name__)
|
| 12 |
+
|
| 13 |
+
GROQ_MODEL = "llama-3.3-70b-versatile"
|
| 14 |
+
DEFAULT_TEMPERATURE = 0.0
|
| 15 |
+
MAX_CONTEXT_CHARS = 6_000
|
| 16 |
+
MAX_FILE_CONTENT_CHARS = 4_000
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
# βββ Wrapper schema ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class TestCoverageReview(BaseModel):
|
| 23 |
+
"""Test-coverage gaps found during code review."""
|
| 24 |
+
findings: list[Finding] = Field(
|
| 25 |
+
default_factory=list,
|
| 26 |
+
description="Test-coverage issues found in the PR diff.",
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
# βββ Prompt βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
SYSTEM_PROMPT = """You are a code reviewer focused on **test coverage**. Analyse the
|
| 34 |
+
PR diff and determine whether the changed logic has adequate test coverage.
|
| 35 |
+
|
| 36 |
+
Look for:
|
| 37 |
+
|
| 38 |
+
1. **New logic without tests** β new functions, classes, or modules added in
|
| 39 |
+
this diff that have no corresponding test file or test function.
|
| 40 |
+
2. **Modified behaviour without updated assertions** β existing logic that was
|
| 41 |
+
changed in a semantically meaningful way (not just refactoring) but the
|
| 42 |
+
corresponding tests were left unchanged, meaning they now pass vacuously or
|
| 43 |
+
no longer cover the modified path.
|
| 44 |
+
3. **Edge-case branches left untested** β new `if`/`elif` branches, `try`/
|
| 45 |
+
`except` handlers, or `match`/`case` arms that are not exercised by any
|
| 46 |
+
test in the diff.
|
| 47 |
+
4. **Error / failure paths** β new error-return or exception-throwing paths
|
| 48 |
+
that have no test asserting the error behaviour.
|
| 49 |
+
5. **Configuration / environment changes** β changes to config files,
|
| 50 |
+
environment variables, or feature flags that affect behaviour but are not
|
| 51 |
+
validated in tests.
|
| 52 |
+
|
| 53 |
+
For each gap return a `Finding` with:
|
| 54 |
+
- `file_path`: the source file with the gap (not the test file).
|
| 55 |
+
- `line_start` / `line_end`: best guess of the affected lines.
|
| 56 |
+
- `severity`: `high` (entirely new untested logic), `medium` (modified path
|
| 57 |
+
untested), `low` (edge case not covered), `info` (suggestion).
|
| 58 |
+
- `category`: always `"test_coverage"`.
|
| 59 |
+
- `comment`: explain what changed and why it needs a test.
|
| 60 |
+
- `confidence`: 0.0β1.0.
|
| 61 |
+
- `suggested_fix`: what a good test should cover (not full code, just
|
| 62 |
+
the scenario to test).
|
| 63 |
+
|
| 64 |
+
**Do NOT** comment on:
|
| 65 |
+
- Purely cosmetic or refactoring changes (rename, extract method).
|
| 66 |
+
- Third-party dependencies or generated files.
|
| 67 |
+
- Changes to test files themselves (they are the solution, not the problem).
|
| 68 |
+
- Correctness of the logic itself (handled by correctness reviewer).
|
| 69 |
+
|
| 70 |
+
Return an empty findings list if every changed path has adequate test coverage.
|
| 71 |
+
"""
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def _build_prompt(state: OpenCodeReviewState) -> str:
|
| 75 |
+
lines: list[str] = []
|
| 76 |
+
|
| 77 |
+
lines.append("## Diff\n```diff")
|
| 78 |
+
lines.append(state.diff or "")
|
| 79 |
+
lines.append("```\n")
|
| 80 |
+
|
| 81 |
+
if state.changed_files:
|
| 82 |
+
lines.append("## Changed files\n")
|
| 83 |
+
for cf in state.changed_files:
|
| 84 |
+
lines.append(f"### {cf.path} ({cf.status})")
|
| 85 |
+
content = cf.content or ""
|
| 86 |
+
if len(content) > MAX_FILE_CONTENT_CHARS:
|
| 87 |
+
content = content[:MAX_FILE_CONTENT_CHARS] + "\n⦠(truncated)"
|
| 88 |
+
lines.append(f"```\n{content}\n```\n")
|
| 89 |
+
|
| 90 |
+
if state.context_chunks:
|
| 91 |
+
lines.append("## Retrieved context\n")
|
| 92 |
+
ctx_chars = 0
|
| 93 |
+
for chunk in state.context_chunks:
|
| 94 |
+
snippet = chunk.content
|
| 95 |
+
if ctx_chars + len(snippet) > MAX_CONTEXT_CHARS:
|
| 96 |
+
remaining = MAX_CONTEXT_CHARS - ctx_chars
|
| 97 |
+
if remaining > 200:
|
| 98 |
+
lines.append(f"> {snippet[:remaining]}β¦ (truncated)")
|
| 99 |
+
break
|
| 100 |
+
prefix = "Past PR" if chunk.source == "past_pr" else chunk.file_path
|
| 101 |
+
lines.append(f"> [{prefix}]: {snippet}")
|
| 102 |
+
ctx_chars += len(snippet)
|
| 103 |
+
|
| 104 |
+
return "\n".join(lines)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
# βββ Node ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def test_coverage_reviewer_node(state: OpenCodeReviewState) -> dict:
|
| 111 |
+
api_key = os.environ.get("GROQ_API_KEY", "").strip()
|
| 112 |
+
if not api_key:
|
| 113 |
+
logger.warning("GROQ_API_KEY not set β skipping test-coverage review")
|
| 114 |
+
return {}
|
| 115 |
+
|
| 116 |
+
if not state.diff:
|
| 117 |
+
logger.info("No diff to review β skipping test-coverage review")
|
| 118 |
+
return {}
|
| 119 |
+
|
| 120 |
+
llm = ChatGroq(model=GROQ_MODEL, temperature=DEFAULT_TEMPERATURE, api_key=api_key)
|
| 121 |
+
structured_llm = llm.with_structured_output(TestCoverageReview)
|
| 122 |
+
|
| 123 |
+
user_prompt = _build_prompt(state)
|
| 124 |
+
logger.info(
|
| 125 |
+
"Invoking test-coverage reviewer (diff=%s, context=%d chunks)",
|
| 126 |
+
_human_size(len(state.diff or "")),
|
| 127 |
+
len(state.context_chunks),
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
try:
|
| 131 |
+
messages = [
|
| 132 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 133 |
+
{"role": "user", "content": user_prompt},
|
| 134 |
+
]
|
| 135 |
+
result: TestCoverageReview = structured_llm.invoke(messages) # type: ignore[assignment]
|
| 136 |
+
except Exception as exc:
|
| 137 |
+
logger.warning("Test-coverage review LLM call failed: %s", exc)
|
| 138 |
+
return {}
|
| 139 |
+
|
| 140 |
+
if result.findings:
|
| 141 |
+
logger.info("Test-coverage review found %d issue(s)", len(result.findings))
|
| 142 |
+
for f in result.findings:
|
| 143 |
+
logger.debug(" [%.2f] %s:%dβ%d β %s", f.confidence, f.file_path, f.line_start, f.line_end, f.comment[:80])
|
| 144 |
+
else:
|
| 145 |
+
logger.info("Test-coverage review found no issues")
|
| 146 |
+
|
| 147 |
+
return {"findings": result.findings}
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def _human_size(bytes_: int) -> str:
|
| 151 |
+
if bytes_ < 1024:
|
| 152 |
+
return f"{bytes_} B"
|
| 153 |
+
elif bytes_ < 1024 * 1024:
|
| 154 |
+
return f"{bytes_ / 1024:.1f} KiB"
|
| 155 |
+
else:
|
| 156 |
+
return f"{bytes_ / (1024 * 1024):.1f} MiB"
|
nodes__init__.py
ADDED
|
File without changes
|
requirements.txt
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
langgraph>=1.1
|
| 2 |
+
pydantic>=2
|
| 3 |
+
pydantic-settings>=2
|
| 4 |
+
langgraph-checkpoint-sqlite>=3
|
| 5 |
+
requests>=2.31
|
| 6 |
+
keyring>=25
|
| 7 |
+
click>=8.1
|
| 8 |
+
gradio>=4.0
|
| 9 |
+
langchain-groq
|
| 10 |
+
chromadb
|
state.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import enum
|
| 4 |
+
from operator import add
|
| 5 |
+
from typing import Annotated, Optional
|
| 6 |
+
|
| 7 |
+
from pydantic import BaseModel, Field
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
# βββ Sub-models ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class ChangedFile(BaseModel):
|
| 14 |
+
"""A single file modified in the PR."""
|
| 15 |
+
path: str
|
| 16 |
+
status: str # "added" | "modified" | "removed" | "renamed"
|
| 17 |
+
content: str # Full file content after the PR
|
| 18 |
+
diff_hunk: str # The unified-diff hunk for this file
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class ContextChunk(BaseModel):
|
| 22 |
+
"""A chunk of relevant context retrieved from the repo's codebase or past PRs."""
|
| 23 |
+
source: str # "codebase" | "past_pr"
|
| 24 |
+
file_path: str # Where the chunk came from
|
| 25 |
+
content: str # The relevant code/text
|
| 26 |
+
relevance_score: float = Field(default=0.0, ge=0.0, le=1.0)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class Severity(str, enum.Enum):
|
| 30 |
+
CRITICAL = "critical"
|
| 31 |
+
HIGH = "high"
|
| 32 |
+
MEDIUM = "medium"
|
| 33 |
+
LOW = "low"
|
| 34 |
+
INFO = "info"
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class Finding(BaseModel):
|
| 38 |
+
"""A single issue found during review."""
|
| 39 |
+
file_path: str
|
| 40 |
+
line_start: int
|
| 41 |
+
line_end: int
|
| 42 |
+
severity: Severity
|
| 43 |
+
category: str # "logic" | "security" | "style" | "performance" | "correctness"
|
| 44 |
+
comment: str # Human-readable explanation
|
| 45 |
+
confidence: float = Field(default=0.5, ge=0.0, le=1.0)
|
| 46 |
+
suggested_fix: Optional[str] = None
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class Verdict(BaseModel):
|
| 50 |
+
"""Aggregated final verdict across all findings."""
|
| 51 |
+
summary: str
|
| 52 |
+
approved: bool
|
| 53 |
+
overall_score: float = Field(ge=0.0, le=10.0)
|
| 54 |
+
critical_count: int = 0
|
| 55 |
+
high_count: int = 0
|
| 56 |
+
recommendation: str # "approve" | "request_changes" | "block"
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
# βββ Graph State βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class OpenCodeReviewState(BaseModel):
|
| 63 |
+
"""Shared state for the OpenCodeReview LangGraph agent."""
|
| 64 |
+
|
| 65 |
+
# PR metadata: set-once, single values
|
| 66 |
+
repo: str = ""
|
| 67 |
+
pr_number: int = 0
|
| 68 |
+
diff: Optional[str] = None
|
| 69 |
+
changed_files: list[ChangedFile] = Field(default_factory=list)
|
| 70 |
+
|
| 71 |
+
# Retrieved context: accumulated across parallel retrieval nodes
|
| 72 |
+
context_chunks: Annotated[list[ContextChunk], add] = Field(default_factory=list)
|
| 73 |
+
|
| 74 |
+
# Review findings: accumulated across parallel review agents
|
| 75 |
+
findings: Annotated[list[Finding], add] = Field(default_factory=list)
|
| 76 |
+
|
| 77 |
+
# Aggregated (deduped, noise-filtered) findings: set-once by aggregator
|
| 78 |
+
final_findings: list[Finding] = Field(default_factory=list)
|
| 79 |
+
|
| 80 |
+
# Final verdict: set-once by the aggregation node
|
| 81 |
+
verdict: Optional[Verdict] = None
|
| 82 |
+
|
| 83 |
+
# Human-in-the-loop: set by the human_approval node
|
| 84 |
+
human_approved: bool = False
|