Spaces:
Running
Running
Deploy 0fd0428c
Browse files- .gitattributes +1 -0
- .opencodereview/vectors/chroma.sqlite3 +3 -0
- app.py +20 -4
- github_client.py +43 -0
- graph.py +8 -2
- main.py +31 -8
- nodes/aggregator.py +40 -37
- nodes/retrieval.py +57 -13
- requirements.txt +1 -0
.gitattributes
CHANGED
|
@@ -221,3 +221,4 @@
|
|
| 221 |
.venv/Scripts/watchfiles.exe filter=lfs diff=lfs merge=lfs -text
|
| 222 |
.venv/Scripts/websockets.exe filter=lfs diff=lfs merge=lfs -text
|
| 223 |
.venv/Scripts/wsdump.exe filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 221 |
.venv/Scripts/watchfiles.exe filter=lfs diff=lfs merge=lfs -text
|
| 222 |
.venv/Scripts/websockets.exe filter=lfs diff=lfs merge=lfs -text
|
| 223 |
.venv/Scripts/wsdump.exe filter=lfs diff=lfs merge=lfs -text
|
| 224 |
+
.opencodereview/vectors/chroma.sqlite3 filter=lfs diff=lfs merge=lfs -text
|
.opencodereview/vectors/chroma.sqlite3
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:639e44c09ed41890226167f52f6bd1ebb3916a13928fcda54c70a78c4effaa71
|
| 3 |
+
size 188416
|
app.py
CHANGED
|
@@ -14,13 +14,14 @@ from __future__ import annotations
|
|
| 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 observability import (
|
| 25 |
build_run_metadata,
|
| 26 |
enable_langsmith,
|
|
@@ -68,7 +69,10 @@ RECOMMENDATION_ICONS = {
|
|
| 68 |
|
| 69 |
|
| 70 |
def _init_observability_ui() -> None:
|
| 71 |
-
"""Initialise observability backends
|
|
|
|
|
|
|
|
|
|
| 72 |
# LangSmith: enable if key is in environment (check both modern and legacy names)
|
| 73 |
ls_key = (
|
| 74 |
os.environ.get("LANGSMITH_API_KEY", "").strip()
|
|
@@ -102,8 +106,13 @@ def _build_and_stream(repo: str, pr_number: int) -> tuple:
|
|
| 102 |
config["callbacks"] = callbacks
|
| 103 |
|
| 104 |
try:
|
|
|
|
| 105 |
initial = {"repo": repo, "pr_number": pr_number}
|
| 106 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
except Exception as exc:
|
| 108 |
log_error_to_backends(exc, context={"source": "gradio_ui", "phase": "stream", "repo": repo, "pr_number": pr_number})
|
| 109 |
raise
|
|
@@ -235,7 +244,14 @@ def run_review(repo: str, pr_number: int, progress=gr.Progress()):
|
|
| 235 |
state, config, cost_summary = _build_and_stream(repo.strip(), pr_number)
|
| 236 |
except Exception as exc:
|
| 237 |
log_error_to_backends(exc, context={"source": "gradio_ui", "phase": "run_review", "repo": repo, "pr_number": pr_number})
|
| 238 |
-
yield [
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 239 |
return
|
| 240 |
|
| 241 |
tasks = state.tasks
|
|
|
|
| 14 |
import json
|
| 15 |
import logging
|
| 16 |
import os
|
| 17 |
+
import time
|
| 18 |
import uuid
|
| 19 |
|
| 20 |
import gradio as gr
|
| 21 |
from langgraph.types import Command
|
| 22 |
|
| 23 |
from graph import build_graph
|
| 24 |
+
from main import NODE_LABELS, _cleanup_db, SYNTHETIC_STATE
|
| 25 |
from observability import (
|
| 26 |
build_run_metadata,
|
| 27 |
enable_langsmith,
|
|
|
|
| 69 |
|
| 70 |
|
| 71 |
def _init_observability_ui() -> None:
|
| 72 |
+
"""Initialise observability backends and HTTP cache for the Gradio UI."""
|
| 73 |
+
from github_client import _init_cache as _init_http_cache
|
| 74 |
+
_init_http_cache()
|
| 75 |
+
|
| 76 |
# LangSmith: enable if key is in environment (check both modern and legacy names)
|
| 77 |
ls_key = (
|
| 78 |
os.environ.get("LANGSMITH_API_KEY", "").strip()
|
|
|
|
| 106 |
config["callbacks"] = callbacks
|
| 107 |
|
| 108 |
try:
|
| 109 |
+
t0 = time.time()
|
| 110 |
initial = {"repo": repo, "pr_number": pr_number}
|
| 111 |
+
for event in graph.stream(initial, config):
|
| 112 |
+
for node_name in event:
|
| 113 |
+
label = NODE_LABELS.get(node_name, node_name)
|
| 114 |
+
logger.info(" β %s (+%.1fs)", label, time.time() - t0)
|
| 115 |
+
logger.info(" βββ Pipeline complete in %.1fs βββ", time.time() - t0)
|
| 116 |
except Exception as exc:
|
| 117 |
log_error_to_backends(exc, context={"source": "gradio_ui", "phase": "stream", "repo": repo, "pr_number": pr_number})
|
| 118 |
raise
|
|
|
|
| 244 |
state, config, cost_summary = _build_and_stream(repo.strip(), pr_number)
|
| 245 |
except Exception as exc:
|
| 246 |
log_error_to_backends(exc, context={"source": "gradio_ui", "phase": "run_review", "repo": repo, "pr_number": pr_number})
|
| 247 |
+
yield [
|
| 248 |
+
gr.update(visible=False),
|
| 249 |
+
gr.update(visible=False),
|
| 250 |
+
gr.update(visible=True),
|
| 251 |
+
gr.update(visible=True, value=f"β Review failed: {exc}"),
|
| 252 |
+
None, None, None, None,
|
| 253 |
+
gr.update(visible=False),
|
| 254 |
+
]
|
| 255 |
return
|
| 256 |
|
| 257 |
tasks = state.tasks
|
github_client.py
CHANGED
|
@@ -1,6 +1,12 @@
|
|
| 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
|
|
@@ -29,6 +35,43 @@ logger = logging.getLogger(__name__)
|
|
| 29 |
|
| 30 |
SERVICE_NAME = "opencodereview"
|
| 31 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
# βββ Exceptions ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 34 |
|
|
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
"""Shared GitHub API client with automatic token resolution and 401 resilience.
|
| 3 |
|
| 4 |
+
Caching
|
| 5 |
+
-------
|
| 6 |
+
All HTTP requests made through ``requests`` within this process are cached
|
| 7 |
+
to a local SQLite backend with a 15-minute TTL, so re-reviewing the same PR
|
| 8 |
+
does not re-fetch data from GitHub.
|
| 9 |
+
|
| 10 |
Usage
|
| 11 |
-----
|
| 12 |
from github_client import GitHubSession, resolve_token, guard_401
|
|
|
|
| 35 |
|
| 36 |
SERVICE_NAME = "opencodereview"
|
| 37 |
|
| 38 |
+
# βββ Global HTTP cache βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 39 |
+
# Cache all requests (GitHub API + raw content) to a local SQLite store
|
| 40 |
+
# so re-reviewing the same PR avoids redundant network fetches.
|
| 41 |
+
_CACHE_BACKEND = None
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _init_cache() -> None:
|
| 45 |
+
"""Install ``requests-cache`` with a 15-minute TTL.
|
| 46 |
+
|
| 47 |
+
Patches ``requests.Session`` globally, so :class:`GitHubSession`
|
| 48 |
+
(which inherits from it) automatically gets caching. Safe to call
|
| 49 |
+
multiple times β subsequent calls are no-ops.
|
| 50 |
+
"""
|
| 51 |
+
global _CACHE_BACKEND
|
| 52 |
+
if _CACHE_BACKEND is not None:
|
| 53 |
+
return
|
| 54 |
+
try:
|
| 55 |
+
import requests_cache
|
| 56 |
+
|
| 57 |
+
cache_dir = os.environ.get(
|
| 58 |
+
"OPENCODEREVIEW_CACHE_DIR",
|
| 59 |
+
os.path.join(os.getcwd(), ".opencodereview"),
|
| 60 |
+
)
|
| 61 |
+
os.makedirs(cache_dir, exist_ok=True)
|
| 62 |
+
db_path = os.path.join(cache_dir, "http_cache.sqlite")
|
| 63 |
+
_CACHE_BACKEND = requests_cache.install_cache(
|
| 64 |
+
cache_name=db_path,
|
| 65 |
+
backend="sqlite",
|
| 66 |
+
expire_after=900, # 15 minutes
|
| 67 |
+
allowable_codes=(200, 404),
|
| 68 |
+
)
|
| 69 |
+
logger.debug("HTTP cache initialised at %s", db_path)
|
| 70 |
+
except ImportError:
|
| 71 |
+
logger.debug("requests-cache not installed β skipping HTTP cache")
|
| 72 |
+
except Exception as exc:
|
| 73 |
+
logger.warning("Failed to initialise HTTP cache: %s", exc)
|
| 74 |
+
|
| 75 |
|
| 76 |
# βββ Exceptions ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 77 |
|
graph.py
CHANGED
|
@@ -22,9 +22,14 @@ from state import OpenCodeReviewState
|
|
| 22 |
logger = logging.getLogger(__name__)
|
| 23 |
|
| 24 |
|
| 25 |
-
def build_graph(db_path: str =
|
| 26 |
"""Build and compile the OpenCodeReview graph with SqliteSaver checkpointing.
|
| 27 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
Topology:
|
| 29 |
|
| 30 |
START β ingestion β retrieval
|
|
@@ -92,7 +97,8 @@ def build_graph(db_path: str = "checkpoints.db") -> StateGraph:
|
|
| 92 |
("state", "Verdict"),
|
| 93 |
])
|
| 94 |
|
| 95 |
-
|
|
|
|
| 96 |
saver = SqliteSaver(conn, serde=serde)
|
| 97 |
|
| 98 |
return builder.compile(checkpointer=saver)
|
|
|
|
| 22 |
logger = logging.getLogger(__name__)
|
| 23 |
|
| 24 |
|
| 25 |
+
def build_graph(db_path: str | None = None) -> StateGraph:
|
| 26 |
"""Build and compile the OpenCodeReview graph with SqliteSaver checkpointing.
|
| 27 |
|
| 28 |
+
When *db_path* is ``None`` an in-memory SQLite database is used so file
|
| 29 |
+
I/O is avoided β ideal for ephemeral CLI runs. Pass a file path to keep
|
| 30 |
+
checkpoints across process restarts (needed by the Gradio UI which may
|
| 31 |
+
resume after page reload).
|
| 32 |
+
|
| 33 |
Topology:
|
| 34 |
|
| 35 |
START β ingestion β retrieval
|
|
|
|
| 97 |
("state", "Verdict"),
|
| 98 |
])
|
| 99 |
|
| 100 |
+
resolved_path: str = db_path if db_path is not None else ":memory:"
|
| 101 |
+
conn = sqlite3.connect(resolved_path, check_same_thread=False)
|
| 102 |
saver = SqliteSaver(conn, serde=serde)
|
| 103 |
|
| 104 |
return builder.compile(checkpointer=saver)
|
main.py
CHANGED
|
@@ -15,6 +15,7 @@ from __future__ import annotations
|
|
| 15 |
import logging
|
| 16 |
import os
|
| 17 |
import sys
|
|
|
|
| 18 |
import uuid
|
| 19 |
|
| 20 |
import click
|
|
@@ -43,15 +44,27 @@ logger = logging.getLogger(__name__)
|
|
| 43 |
|
| 44 |
DB_PATH = "checkpoints.db"
|
| 45 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
|
| 47 |
# βββ Observability initialisation ββββββββββββββββββββββββββββββββββββββββββ
|
| 48 |
|
| 49 |
|
| 50 |
def _init_observability() -> None:
|
| 51 |
-
"""Initialise tracing backends from env vars / keyring.
|
| 52 |
|
| 53 |
Called once at the start of each ``review`` command.
|
| 54 |
"""
|
|
|
|
|
|
|
|
|
|
| 55 |
import keyring as _kr
|
| 56 |
from config import SERVICE_NAME as _svc
|
| 57 |
|
|
@@ -215,7 +228,12 @@ def _run_with_hitl(graph, repo: str, pr_number: int) -> None:
|
|
| 215 |
"pr_number": pr_number,
|
| 216 |
}
|
| 217 |
|
| 218 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 219 |
|
| 220 |
state = graph.get_state(config)
|
| 221 |
tasks = state.tasks
|
|
@@ -305,7 +323,12 @@ def _test_offline(graph) -> None:
|
|
| 305 |
callbacks.append(handler)
|
| 306 |
config["callbacks"] = callbacks
|
| 307 |
|
| 308 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 309 |
state = graph.get_state(config)
|
| 310 |
tasks = state.tasks
|
| 311 |
values = state.values
|
|
@@ -313,17 +336,17 @@ def _test_offline(graph) -> None:
|
|
| 313 |
verdict = values.get("verdict")
|
| 314 |
final_findings = values.get("final_findings", [])
|
| 315 |
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
|
| 321 |
assert len(tasks) > 0, "Graph did not pause at interrupt"
|
| 322 |
assert verdict is not None, "No verdict produced"
|
| 323 |
assert len(final_findings) >= 0, "Missing final_findings"
|
| 324 |
|
| 325 |
graph.invoke(Command(resume={"action": "reject"}), config)
|
| 326 |
-
|
| 327 |
|
| 328 |
|
| 329 |
def _cleanup_db() -> None:
|
|
|
|
| 15 |
import logging
|
| 16 |
import os
|
| 17 |
import sys
|
| 18 |
+
import time
|
| 19 |
import uuid
|
| 20 |
|
| 21 |
import click
|
|
|
|
| 44 |
|
| 45 |
DB_PATH = "checkpoints.db"
|
| 46 |
|
| 47 |
+
NODE_LABELS: dict[str, str] = {
|
| 48 |
+
"ingestion": "π₯ Ingestion",
|
| 49 |
+
"retrieval": "π Retrieval",
|
| 50 |
+
"correctness_review": "β
Correctness Review",
|
| 51 |
+
"security_review": "π Security Review",
|
| 52 |
+
"test_coverage_review": "π§ͺ Test Coverage Review",
|
| 53 |
+
"aggregator": "π Aggregation",
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
|
| 57 |
# βββ Observability initialisation ββββββββββββββββββββββββββββββββββββββββββ
|
| 58 |
|
| 59 |
|
| 60 |
def _init_observability() -> None:
|
| 61 |
+
"""Initialise tracing backends and HTTP cache from env vars / keyring.
|
| 62 |
|
| 63 |
Called once at the start of each ``review`` command.
|
| 64 |
"""
|
| 65 |
+
from github_client import _init_cache as _init_http_cache
|
| 66 |
+
_init_http_cache()
|
| 67 |
+
|
| 68 |
import keyring as _kr
|
| 69 |
from config import SERVICE_NAME as _svc
|
| 70 |
|
|
|
|
| 228 |
"pr_number": pr_number,
|
| 229 |
}
|
| 230 |
|
| 231 |
+
t0 = time.time()
|
| 232 |
+
for event in graph.stream(initial_state, config):
|
| 233 |
+
for node_name in event:
|
| 234 |
+
label = NODE_LABELS.get(node_name, node_name)
|
| 235 |
+
logger.info(" β %s (+%.1fs)", label, time.time() - t0)
|
| 236 |
+
logger.info(" βββ Pipeline complete in %.1fs βββ", time.time() - t0)
|
| 237 |
|
| 238 |
state = graph.get_state(config)
|
| 239 |
tasks = state.tasks
|
|
|
|
| 323 |
callbacks.append(handler)
|
| 324 |
config["callbacks"] = callbacks
|
| 325 |
|
| 326 |
+
t0 = time.time()
|
| 327 |
+
for event in graph.stream(SYNTHETIC_STATE, config):
|
| 328 |
+
for node_name in event:
|
| 329 |
+
label = NODE_LABELS.get(node_name, node_name)
|
| 330 |
+
logger.info(" β %s (+%.1fs)", label, time.time() - t0)
|
| 331 |
+
logger.info(" βββ Pipeline complete in %.1fs βββ", time.time() - t0)
|
| 332 |
state = graph.get_state(config)
|
| 333 |
tasks = state.tasks
|
| 334 |
values = state.values
|
|
|
|
| 336 |
verdict = values.get("verdict")
|
| 337 |
final_findings = values.get("final_findings", [])
|
| 338 |
|
| 339 |
+
logger.info("Smoke test: paused=True, tasks=%d, findings=%d, verdict=%s",
|
| 340 |
+
len(tasks), len(final_findings),
|
| 341 |
+
verdict.recommendation if verdict else 'None')
|
| 342 |
+
logger.info("%s", cost_tracker.summary())
|
| 343 |
|
| 344 |
assert len(tasks) > 0, "Graph did not pause at interrupt"
|
| 345 |
assert verdict is not None, "No verdict produced"
|
| 346 |
assert len(final_findings) >= 0, "Missing final_findings"
|
| 347 |
|
| 348 |
graph.invoke(Command(resume={"action": "reject"}), config)
|
| 349 |
+
logger.info("Smoke test: resume OK, graph completed")
|
| 350 |
|
| 351 |
|
| 352 |
def _cleanup_db() -> None:
|
nodes/aggregator.py
CHANGED
|
@@ -23,6 +23,10 @@ MIN_CONFIDENCE = 0.25
|
|
| 23 |
# Files/line pairs within this many lines are considered duplicates
|
| 24 |
LINE_TOLERANCE = 5
|
| 25 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
# βββ Load prompt from file ββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 28 |
|
|
@@ -207,8 +211,8 @@ def aggregator_node(state: OpenCodeReviewState) -> dict:
|
|
| 207 |
|
| 208 |
Two-phase approach:
|
| 209 |
1. Pre-LLM heuristic deduplication (groups by file/line proximity).
|
| 210 |
-
2.
|
| 211 |
-
|
| 212 |
"""
|
| 213 |
raw_findings = state.findings
|
| 214 |
if not raw_findings:
|
|
@@ -230,44 +234,43 @@ def aggregator_node(state: OpenCodeReviewState) -> dict:
|
|
| 230 |
len(raw_findings), len(deduped),
|
| 231 |
)
|
| 232 |
|
| 233 |
-
# -- Phase 2:
|
| 234 |
-
|
| 235 |
-
llm = create_llm()
|
| 236 |
-
except ValueError:
|
| 237 |
-
llm = None
|
| 238 |
-
|
| 239 |
-
if llm is not None:
|
| 240 |
-
logger.info(
|
| 241 |
-
"Invoking aggregator LLM critic (prompt_version=%s) β¦",
|
| 242 |
-
PROMPT_VERSION,
|
| 243 |
-
)
|
| 244 |
try:
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
]
|
| 251 |
-
result: AggregatedReview = structured_llm.invoke(messages) # type: ignore[assignment]
|
| 252 |
-
except Exception as exc:
|
| 253 |
-
logger.warning("Aggregator LLM call failed β falling back to rule-based: %s", exc)
|
| 254 |
-
result = None
|
| 255 |
-
|
| 256 |
-
if result is not None:
|
| 257 |
-
final_findings = result.findings
|
| 258 |
-
verdict = result.verdict
|
| 259 |
logger.info(
|
| 260 |
-
"
|
| 261 |
-
|
| 262 |
-
verdict.recommendation,
|
| 263 |
)
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 271 |
|
| 272 |
return {
|
| 273 |
"final_findings": final_findings, # plain list, overwrites
|
|
|
|
| 23 |
# Files/line pairs within this many lines are considered duplicates
|
| 24 |
LINE_TOLERANCE = 5
|
| 25 |
|
| 26 |
+
# Default to rule-based aggregation (skips expensive LLM critic call).
|
| 27 |
+
# Set AGGREGATOR_USE_LLM_CRITIC=true in env to re-enable the LLM pass.
|
| 28 |
+
USE_LLM_CRITIC = os.environ.get("AGGREGATOR_USE_LLM_CRITIC", "").lower() in ("1", "true", "yes")
|
| 29 |
+
|
| 30 |
|
| 31 |
# βββ Load prompt from file ββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 32 |
|
|
|
|
| 211 |
|
| 212 |
Two-phase approach:
|
| 213 |
1. Pre-LLM heuristic deduplication (groups by file/line proximity).
|
| 214 |
+
2. Rule-based verdict by default (fast, ~10ms), or optional LLM critic
|
| 215 |
+
when ``USE_LLM_CRITIC`` is enabled.
|
| 216 |
"""
|
| 217 |
raw_findings = state.findings
|
| 218 |
if not raw_findings:
|
|
|
|
| 234 |
len(raw_findings), len(deduped),
|
| 235 |
)
|
| 236 |
|
| 237 |
+
# -- Phase 2: Rule-based (default, fast) or LLM critic (opt-in) ----------
|
| 238 |
+
if USE_LLM_CRITIC:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 239 |
try:
|
| 240 |
+
llm = create_llm()
|
| 241 |
+
except ValueError:
|
| 242 |
+
llm = None
|
| 243 |
+
|
| 244 |
+
if llm is not None:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 245 |
logger.info(
|
| 246 |
+
"Invoking aggregator LLM critic (prompt_version=%s) β¦",
|
| 247 |
+
PROMPT_VERSION,
|
|
|
|
| 248 |
)
|
| 249 |
+
try:
|
| 250 |
+
structured_llm = llm.with_structured_output(AggregatedReview)
|
| 251 |
+
messages = [
|
| 252 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 253 |
+
{"role": "user", "content": _build_prompt(deduped)},
|
| 254 |
+
]
|
| 255 |
+
result: AggregatedReview = structured_llm.invoke(messages) # type: ignore[assignment]
|
| 256 |
+
except Exception as exc:
|
| 257 |
+
logger.warning("LLM critic failed β falling back to rule-based: %s", exc)
|
| 258 |
+
result = None
|
| 259 |
+
|
| 260 |
+
if result is not None:
|
| 261 |
+
final_findings = result.findings
|
| 262 |
+
verdict = result.verdict
|
| 263 |
+
logger.info(
|
| 264 |
+
"LLM aggregator: %d deduped β %d final, recommendation=%s",
|
| 265 |
+
len(deduped), len(final_findings),
|
| 266 |
+
verdict.recommendation,
|
| 267 |
+
)
|
| 268 |
+
return {"final_findings": final_findings, "verdict": verdict}
|
| 269 |
+
|
| 270 |
+
# Rule-based path (default) β zero LLM overhead
|
| 271 |
+
logger.info("Using rule-based aggregation (fast path)")
|
| 272 |
+
final_findings = deduped
|
| 273 |
+
verdict = _rule_verdict(deduped)
|
| 274 |
|
| 275 |
return {
|
| 276 |
"final_findings": final_findings, # plain list, overwrites
|
nodes/retrieval.py
CHANGED
|
@@ -171,10 +171,13 @@ _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.
|
| 177 |
-
|
|
|
|
| 178 |
)
|
| 179 |
os.makedirs(_VECTOR_DIR, exist_ok=True)
|
| 180 |
return _VECTOR_DIR
|
|
@@ -184,18 +187,18 @@ def _repo_collection_name(repo: str) -> str:
|
|
| 184 |
return f"repo_{repo.replace('/', '_')}"
|
| 185 |
|
| 186 |
|
| 187 |
-
def
|
| 188 |
owner: str, repo_name: str,
|
| 189 |
head_sha: str,
|
| 190 |
exclude_paths: set[str],
|
| 191 |
) -> Collection:
|
| 192 |
-
"""
|
|
|
|
| 193 |
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
"""
|
| 198 |
-
|
| 199 |
if chromadb is None:
|
| 200 |
raise RuntimeError("chromadb is not installed β cannot build vector store")
|
| 201 |
|
|
@@ -205,14 +208,55 @@ def _build_vector_store(
|
|
| 205 |
client = chromadb.PersistentClient(path=_ensure_vector_dir())
|
| 206 |
coll_name = _repo_collection_name(f"{owner}/{repo_name}")
|
| 207 |
|
| 208 |
-
#
|
| 209 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 210 |
client.delete_collection(coll_name)
|
| 211 |
except Exception:
|
| 212 |
-
pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 213 |
collection = client.create_collection(
|
| 214 |
name=coll_name,
|
| 215 |
-
metadata={
|
|
|
|
|
|
|
|
|
|
|
|
|
| 216 |
embedding_function=ef,
|
| 217 |
)
|
| 218 |
|
|
@@ -390,11 +434,11 @@ def retrieval_node(state: OpenCodeReviewState) -> dict:
|
|
| 390 |
return {}
|
| 391 |
|
| 392 |
try:
|
| 393 |
-
collection =
|
| 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 ----------------------------------------
|
|
|
|
| 171 |
|
| 172 |
|
| 173 |
def _ensure_vector_dir() -> str:
|
| 174 |
+
"""Return a persistent vector-store directory (not temp, so it survives
|
| 175 |
+
across runs). Override via OPENCODEREVIEW_VECTOR_DIR env var."""
|
| 176 |
global _VECTOR_DIR
|
| 177 |
if _VECTOR_DIR is None:
|
| 178 |
+
_VECTOR_DIR = os.environ.get(
|
| 179 |
+
"OPENCODEREVIEW_VECTOR_DIR",
|
| 180 |
+
os.path.join(os.getcwd(), ".opencodereview", "vectors"),
|
| 181 |
)
|
| 182 |
os.makedirs(_VECTOR_DIR, exist_ok=True)
|
| 183 |
return _VECTOR_DIR
|
|
|
|
| 187 |
return f"repo_{repo.replace('/', '_')}"
|
| 188 |
|
| 189 |
|
| 190 |
+
def _get_or_build_collection(
|
| 191 |
owner: str, repo_name: str,
|
| 192 |
head_sha: str,
|
| 193 |
exclude_paths: set[str],
|
| 194 |
) -> Collection:
|
| 195 |
+
"""Return a cached ChromaDB collection for ``repo``, rebuilding only when
|
| 196 |
+
the base-branch SHA changes.
|
| 197 |
|
| 198 |
+
The collection metadata key ``base_sha`` stores the SHA at build time.
|
| 199 |
+
On subsequent calls, if the collection exists with a matching ``base_sha``
|
| 200 |
+
it is returned immediately β no fetch, no chunk, no embedding.
|
| 201 |
"""
|
|
|
|
| 202 |
if chromadb is None:
|
| 203 |
raise RuntimeError("chromadb is not installed β cannot build vector store")
|
| 204 |
|
|
|
|
| 208 |
client = chromadb.PersistentClient(path=_ensure_vector_dir())
|
| 209 |
coll_name = _repo_collection_name(f"{owner}/{repo_name}")
|
| 210 |
|
| 211 |
+
# ββ Cache hit: collection exists with matching SHA ββββββββββββββββββββ
|
| 212 |
try:
|
| 213 |
+
existing = client.get_collection(name=coll_name, embedding_function=ef)
|
| 214 |
+
meta = existing.metadata or {}
|
| 215 |
+
if meta.get("base_sha") == head_sha:
|
| 216 |
+
logger.info(
|
| 217 |
+
"Vector store up-to-date (SHA=%s) β skipping rebuild",
|
| 218 |
+
head_sha[:7],
|
| 219 |
+
)
|
| 220 |
+
return existing
|
| 221 |
+
logger.info(
|
| 222 |
+
"SHA mismatch: cached=%s, current=%s β rebuilding",
|
| 223 |
+
(meta.get("base_sha") or "?"), head_sha[:7],
|
| 224 |
+
)
|
| 225 |
client.delete_collection(coll_name)
|
| 226 |
except Exception:
|
| 227 |
+
pass # First build or error β create fresh
|
| 228 |
+
|
| 229 |
+
return _build_vector_store(
|
| 230 |
+
owner, repo_name, head_sha, exclude_paths, client, coll_name, ef,
|
| 231 |
+
)
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def _build_vector_store(
|
| 235 |
+
owner: str, repo_name: str,
|
| 236 |
+
head_sha: str,
|
| 237 |
+
exclude_paths: set[str],
|
| 238 |
+
client: chromadb.PersistentClient,
|
| 239 |
+
coll_name: str,
|
| 240 |
+
ef,
|
| 241 |
+
) -> Collection:
|
| 242 |
+
"""Fetch, chunk, embed, and index the non-changed files + past PRs.
|
| 243 |
+
|
| 244 |
+
Each data source (codebase, past PRs, docs) is added to ChromaDB
|
| 245 |
+
incrementally so a transient failure in one source does not lose
|
| 246 |
+
progress from earlier sources.
|
| 247 |
+
|
| 248 |
+
.. note::
|
| 249 |
+
|
| 250 |
+
Prefer :func:`_get_or_build_collection` β this function always
|
| 251 |
+
rebuilds from scratch.
|
| 252 |
+
"""
|
| 253 |
collection = client.create_collection(
|
| 254 |
name=coll_name,
|
| 255 |
+
metadata={
|
| 256 |
+
"hnsw:space": "cosine",
|
| 257 |
+
"base_sha": head_sha, # β freshness key for cache lookups
|
| 258 |
+
"repo": f"{owner}/{repo_name}",
|
| 259 |
+
},
|
| 260 |
embedding_function=ef,
|
| 261 |
)
|
| 262 |
|
|
|
|
| 434 |
return {}
|
| 435 |
|
| 436 |
try:
|
| 437 |
+
collection = _get_or_build_collection(
|
| 438 |
owner, repo_name, head_sha_for_tree, changed_paths,
|
| 439 |
)
|
| 440 |
except Exception as exc:
|
| 441 |
+
logger.warning("Failed to build/get vector store: %s", exc)
|
| 442 |
return {}
|
| 443 |
|
| 444 |
# -- Query the store with the diff ----------------------------------------
|
requirements.txt
CHANGED
|
@@ -11,3 +11,4 @@ langchain
|
|
| 11 |
chromadb
|
| 12 |
langsmith>=0.7
|
| 13 |
langfuse
|
|
|
|
|
|
| 11 |
chromadb
|
| 12 |
langsmith>=0.7
|
| 13 |
langfuse
|
| 14 |
+
requests-cache>=1.2
|