Sdm0 commited on
Commit
2dadd40
·
verified ·
1 Parent(s): 25628f6

Fix RAGAS evaluator timeouts and hide scores from users

Browse files
backend/api.py CHANGED
@@ -1,586 +1,586 @@
1
- """Small HTTP boundary for the React client.
2
-
3
- The review engine remains in the existing LangGraph modules. This service only
4
- owns job lifecycle and approval state; production deployments should replace
5
- the process-local registry with a durable store and queue.
6
- """
7
- from __future__ import annotations
8
-
9
- import os
10
- import hashlib
11
- import time
12
- from pathlib import Path
13
- import json
14
- import logging
15
- import secrets
16
- import sqlite3
17
- import threading
18
- import uuid
19
- import requests
20
- from concurrent.futures import ThreadPoolExecutor
21
- from datetime import datetime, timezone
22
- from typing import Any, Literal
23
-
24
- from fastapi import FastAPI, Header, HTTPException, Request
25
- from fastapi.responses import RedirectResponse
26
- from fastapi.middleware.cors import CORSMiddleware
27
- from langgraph.types import Command
28
- from pydantic import BaseModel, Field
29
-
30
- from backend.app import DB_PATH, _build_and_stream, _normalize_endpoint_name, _spawn_ragas_background
31
- from backend.graph import build_graph
32
- from backend.observability import TokenCostCallback, flush_langfuse, get_langfuse_handler
33
- from backend.state import Finding, Verdict
34
- from backend.integrations.endpoints import register_endpoint, unregister_endpoint
35
-
36
- app = FastAPI(title="OpenCodeReview API", version="0.1.0")
37
- logger = logging.getLogger(__name__)
38
-
39
-
40
-
41
-
42
-
43
-
44
-
45
-
46
- allowed_origins = [item.strip() for item in os.getenv("OCR_ALLOWED_ORIGINS", "http://localhost:5173").split(",") if item.strip()]
47
- app.add_middleware(CORSMiddleware, allow_origins=allowed_origins, allow_methods=["GET", "POST"], allow_headers=["*"], allow_credentials=True)
48
-
49
- _jobs: dict[str, dict[str, Any]] = {}
50
- _lock = threading.Lock()
51
- _executor = ThreadPoolExecutor(max_workers=int(os.getenv("OCR_MAX_WORKERS", "2")))
52
- _rate_lock = threading.Lock()
53
- _rate_windows: dict[str, list[float]] = {}
54
- _oauth_states: set[str] = set()
55
- _sessions: dict[str, dict[str, Any]] = {}
56
-
57
- def _rate_limit(request: Request) -> None:
58
- limit = int(os.getenv("OCR_RATE_LIMIT_PER_MINUTE", "0") or 0)
59
- if limit <= 0:
60
- return
61
- now = datetime.now(timezone.utc).timestamp()
62
- forwarded = request.headers.get("x-forwarded-for") or request.headers.get("x-real-ip")
63
- key = (forwarded.split(",", 1)[0].strip() if forwarded else None) or "global"
64
- with _rate_lock:
65
- window = [stamp for stamp in _rate_windows.get(key, []) if now - stamp < 60]
66
- if len(window) >= limit:
67
- raise HTTPException(status_code=429, detail="Rate limit exceeded")
68
- window.append(now)
69
- _rate_windows[key] = window
70
-
71
-
72
- def _postgres_connect():
73
- """Return a Supabase Postgres connection when configured, else None."""
74
- url = os.getenv("SUPABASE_DB_URL", "").strip()
75
- if not url:
76
- return None
77
- try:
78
- import psycopg
79
- return psycopg.connect(url)
80
- except Exception as exc:
81
- # Connection strings and provider errors can include credentials.
82
- logger.warning("Shared database connection failed (%s); using local storage", type(exc).__name__)
83
- return None
84
-
85
- def _sqlite_connect():
86
- """Open the fallback store and ensure its schema exists on every path."""
87
- conn = sqlite3.connect(DB_PATH)
88
- conn.execute("CREATE TABLE IF NOT EXISTS review_jobs (id TEXT PRIMARY KEY, payload TEXT NOT NULL)")
89
- conn.commit()
90
- return conn
91
-
92
- def _init_jobs() -> None:
93
- # Prepare the fallback even when Postgres is available at startup: it can
94
- # become unavailable later, while the process is still running.
95
- with _sqlite_connect():
96
- pass
97
- pg = _postgres_connect()
98
- if pg is not None:
99
- with pg:
100
- with pg.cursor() as cur:
101
- cur.execute("""create table if not exists public.review_jobs (
102
- id uuid primary key, repo text not null, pr_number integer not null,
103
- endpoint text, status text not null, payload jsonb not null,
104
- created_at timestamptz not null default now(), updated_at timestamptz not null default now())""")
105
- cur.execute("create index if not exists review_jobs_status_idx on public.review_jobs (status)")
106
- pg.close()
107
- return
108
-
109
- _init_jobs()
110
-
111
- def _save_job(job: dict[str, Any]) -> None:
112
- payload = {k: v for k, v in job.items() if k not in {"future", "ragas_inputs"}}
113
- if "config" in payload:
114
- payload["config"] = {"configurable": payload["config"].get("configurable", {})}
115
- pg = None if job.get("persistence") == "local_fallback" else _postgres_connect()
116
- if pg is not None:
117
- with pg:
118
- with pg.cursor() as cur:
119
- cur.execute("""insert into public.review_jobs (id, repo, pr_number, endpoint, status, payload, updated_at)
120
- values (%s, %s, %s, %s, %s, %s::jsonb, now())
121
- on conflict (id) do update set repo=excluded.repo, pr_number=excluded.pr_number,
122
- endpoint=excluded.endpoint, status=excluded.status, payload=excluded.payload, updated_at=now()""",
123
- (job["id"], job["repo"], job["pr_number"], job.get("endpoint"), job["status"], json.dumps(payload, default=str)))
124
- pg.close()
125
- return
126
- job["persistence"] = "local_fallback"
127
- payload["persistence"] = "local_fallback"
128
- with _sqlite_connect() as conn:
129
- conn.execute("INSERT OR REPLACE INTO review_jobs (id, payload) VALUES (?, ?)", (job["id"], json.dumps(payload, default=str)))
130
- conn.commit()
131
-
132
- def _load_job(job_id: str) -> dict[str, Any] | None:
133
- pg = _postgres_connect()
134
- if pg is not None:
135
- with pg.cursor() as cur:
136
- cur.execute("select payload from public.review_jobs where id = %s", (job_id,))
137
- row = cur.fetchone()
138
- pg.close()
139
- if row:
140
- return json.loads(row[0]) if isinstance(row[0], str) else row[0]
141
- with _sqlite_connect() as conn:
142
- row = conn.execute("SELECT payload FROM review_jobs WHERE id = ?", (job_id,)).fetchone()
143
- return json.loads(row[0]) if row else None
144
-
145
- def _load_jobs() -> list[dict[str, Any]]:
146
- pg = _postgres_connect()
147
- if pg is not None:
148
- with pg.cursor() as cur:
149
- cur.execute("select payload from public.review_jobs")
150
- rows = cur.fetchall()
151
- pg.close()
152
- return [json.loads(row[0]) if isinstance(row[0], str) else row[0] for row in rows]
153
- with _sqlite_connect() as conn:
154
- rows = conn.execute("SELECT payload FROM review_jobs").fetchall()
155
- return [json.loads(row[0]) if isinstance(row[0], str) else row[0] for row in rows]
156
-
157
-
158
- class ReviewRequest(BaseModel):
159
- repo: str = Field(pattern=r"^[\w.-]+/[\w.-]+$")
160
- pr_number: int = Field(gt=0)
161
- endpoint: str | None = None
162
- provider: str | None = Field(default=None, pattern=r"^(openai|anthropic|google)$")
163
- model: str | None = None
164
- api_key: str | None = None
165
- base_url: str | None = None
166
- review_mode: Literal["fast", "thorough"] = "thorough"
167
- baseline_sha: str | None = Field(default=None, pattern=r"^[0-9a-fA-F]{40}$")
168
-
169
-
170
- class DecisionRequest(BaseModel):
171
- action: Literal["approve", "reject"]
172
-
173
-
174
- class FindingFeedbackRequest(BaseModel):
175
- finding_index: int = Field(ge=0)
176
- label: Literal['correct', 'incorrect', 'useful']
177
-
178
-
179
- def _authorize(token: str | None) -> None:
180
- expected = os.getenv("OCR_API_KEY", "").strip()
181
- # Authentication is opt-in for local development, but deployments can
182
- # require it explicitly. Never silently treat a missing production key
183
- # as authenticated.
184
- require_auth = os.getenv("OCR_REQUIRE_AUTH", "false").strip().lower() in {"1", "true", "yes", "on"}
185
- if require_auth and not expected:
186
- raise HTTPException(status_code=503, detail="API authentication is not configured")
187
- if expected and (not token or not secrets.compare_digest(token, expected)):
188
- raise HTTPException(status_code=401, detail="Invalid API key")
189
-
190
- def _authorize_request(token: str | None, request: Request) -> None:
191
- if _session(request):
192
- return
193
- _authorize(token)
194
-
195
- def _session(request: Request) -> dict[str, Any] | None:
196
- sid = request.cookies.get("ocr_session")
197
- return _sessions.get(sid) if sid else None
198
-
199
- @app.get("/api/auth/github/start")
200
- def github_login() -> RedirectResponse:
201
- client_id = os.getenv("GITHUB_OAUTH_CLIENT_ID", "").strip()
202
- if not client_id:
203
- raise HTTPException(status_code=503, detail="GitHub OAuth is not configured")
204
- state = secrets.token_urlsafe(32)
205
- _oauth_states.add(state)
206
- callback = os.getenv("GITHUB_OAUTH_CALLBACK_URL", "").strip() or "http://localhost:8000/api/auth/github/callback"
207
- url = "https://github.com/login/oauth/authorize?" + requests.compat.urlencode({"client_id": client_id, "redirect_uri": callback, "scope": "read:user user:email repo", "state": state})
208
- return RedirectResponse(url)
209
-
210
- @app.get("/api/auth/github/callback")
211
- def github_callback(code: str, state: str, response: Request) -> RedirectResponse:
212
- if state not in _oauth_states:
213
- raise HTTPException(status_code=400, detail="Invalid OAuth state")
214
- _oauth_states.discard(state)
215
- client_id = os.getenv("GITHUB_OAUTH_CLIENT_ID", "").strip()
216
- client_secret = os.getenv("GITHUB_OAUTH_CLIENT_SECRET", "").strip()
217
- callback = os.getenv("GITHUB_OAUTH_CALLBACK_URL", "").strip() or "http://localhost:8000/api/auth/github/callback"
218
- token_resp = requests.post("https://github.com/login/oauth/access_token", data={"client_id": client_id, "client_secret": client_secret, "code": code, "redirect_uri": callback}, headers={"Accept": "application/json"}, timeout=20)
219
- token_resp.raise_for_status()
220
- access_token = token_resp.json().get("access_token")
221
- if not access_token:
222
- raise HTTPException(status_code=502, detail="GitHub did not return an access token")
223
- user_resp = requests.get("https://api.github.com/user", headers={"Authorization": f"Bearer {access_token}", "Accept": "application/vnd.github+json"}, timeout=20)
224
- user_resp.raise_for_status()
225
- user = user_resp.json()
226
- sid = secrets.token_urlsafe(32)
227
- _sessions[sid] = {"token": access_token, "github_id": user.get("id"), "login": user.get("login")}
228
- frontend = os.getenv("OCR_FRONTEND_URL", allowed_origins[0] if allowed_origins else "http://localhost:5173")
229
- out = RedirectResponse(frontend)
230
- out.set_cookie("ocr_session", sid, httponly=True, secure=frontend.startswith("https://"), samesite="lax", max_age=86400)
231
- return out
232
-
233
- @app.get("/api/auth/me")
234
- def github_me(request: Request) -> dict[str, Any]:
235
- session = _session(request)
236
- if not session:
237
- raise HTTPException(status_code=401, detail="Not authenticated")
238
- return {"github_id": session["github_id"], "login": session["login"]}
239
-
240
- @app.post("/api/auth/logout")
241
- def github_logout(request: Request) -> dict[str, str]:
242
- sid = request.cookies.get("ocr_session")
243
- if sid:
244
- _sessions.pop(sid, None)
245
- return {"status": "logged_out"}
246
-
247
-
248
- def _public_job(job: dict[str, Any]) -> dict[str, Any]:
249
- private_keys = {
250
- "config", "future", "request_fingerprint", "owner_id",
251
- }
252
- result = {
253
- key: value for key, value in job.items()
254
- if key not in private_keys and not key.startswith("ragas")
255
- }
256
- now = time.time()
257
- result["elapsed_seconds"] = round(max(0, now - job.get("started_timestamp", now)), 1) if job.get("status") in {"processing", "queued"} else job.get("elapsed_seconds", 0)
258
- if job.get("status") == "queued":
259
- result["queue_position"] = sum(1 for item in _jobs.values() if item.get("status") == "queued" and item.get("created_at", "") <= job.get("created_at", ""))
260
- return result
261
-
262
-
263
- def _run_job(job_id: str, request: ReviewRequest) -> None:
264
- with _lock:
265
- if _jobs.get(job_id, {}).get("status") == "cancelled":
266
- return
267
- if job_id in _jobs:
268
- _jobs[job_id].update(status="processing", started_timestamp=time.time(), progress={"stage": "ingestion", "completed_stages": []})
269
- _save_job(_jobs[job_id])
270
- try:
271
- ephemeral_endpoint = None
272
- ragas_started = False
273
- endpoint_name = _normalize_endpoint_name(request.endpoint)
274
- if request.api_key:
275
- if not request.provider or not request.model:
276
- raise ValueError("provider and model are required when supplying a user API key")
277
- ephemeral_endpoint = f"user-{job_id}"
278
- register_endpoint(ephemeral_endpoint, request.provider, request.api_key, request.base_url, request.model)
279
- endpoint_name = ephemeral_endpoint
280
- def save_ragas(scores: dict, error: str | None) -> None:
281
- try:
282
- with _lock:
283
- live = _jobs.get(job_id)
284
- if live is None:
285
- return
286
- live["ragas_scores"] = scores or None
287
- live["ragas_status"] = "failed" if error else ("completed" if scores else "completed_no_scores")
288
- live["ragas_error"] = error
289
- _save_job(live)
290
- finally:
291
- # Custom providers are registered only for this job. Keep the
292
- # endpoint alive until the background RAGAS task has finished;
293
- # otherwise evaluation silently falls back to built-ins.
294
- if ephemeral_endpoint:
295
- unregister_endpoint(ephemeral_endpoint)
296
-
297
- def progress(stage: str, elapsed: float, update: dict | None = None) -> None:
298
- with _lock:
299
- live = _jobs[job_id]
300
- if live.get("status") == "cancelled":
301
- raise RuntimeError("Review cancelled")
302
- completed = live.setdefault("progress", {}).setdefault("completed_stages", [])
303
- if stage not in completed:
304
- completed.append(stage)
305
- live["progress"]["stage"] = stage
306
- live.setdefault("stage_timings", {})[stage] = round(elapsed, 2)
307
- if isinstance(update, dict):
308
- stages = update.get("review_stages", [])
309
- if isinstance(stages, list):
310
- live.setdefault("review_stages", []).extend(stages)
311
- for key in ("findings",):
312
- for finding in update.get(key, []) or []:
313
- if hasattr(finding, "model_dump"):
314
- finding = finding.model_dump(mode="json")
315
- if isinstance(finding, dict):
316
- live.setdefault("findings", []).append(finding)
317
- _save_job(live)
318
-
319
- state, config, cost, ragas, ragas_inputs = _build_and_stream(
320
- request.repo,
321
- request.pr_number,
322
- endpoint_name,
323
- ragas_background=True,
324
- ragas_result_callback=save_ragas,
325
- progress_callback=progress,
326
- review_mode=request.review_mode,
327
- baseline_sha=request.baseline_sha,
328
- )
329
- ragas_started = isinstance(ragas, str)
330
- actual_head = state.values.get("head_sha")
331
- verdict: Verdict | None = state.values.get("verdict")
332
- findings: list[Finding] = state.values.get("final_findings", [])
333
- with _lock:
334
- if _jobs[job_id].get("status") == "cancelled":
335
- return
336
- if actual_head and _jobs[job_id].get("head_sha") != actual_head:
337
- # The PR moved between metadata lookup and ingestion. The result
338
- # can still be viewed, but must not satisfy the old cache key.
339
- _jobs[job_id]["request_fingerprint"] = None
340
- _jobs[job_id]["head_sha"] = actual_head
341
- stages = state.values.get("review_stages", [])
342
- incomplete = bool(verdict and verdict.recommendation == "incomplete")
343
- _jobs[job_id].update(review_coverage=state.values.get("review_coverage", {}), review_stages=stages, elapsed_seconds=round(time.time() - _jobs[job_id]["started_timestamp"], 2), status="incomplete" if incomplete else "awaiting_approval", config=config, verdict=verdict.model_dump(mode="json") if verdict else None, findings=[item.model_dump(mode="json") for item in findings], cost=cost, cost_details=config.get("metadata", {}).get("cost_details"), ragas_task_id=ragas if isinstance(ragas, str) else None, ragas_scores=ragas if isinstance(ragas, dict) else None, ragas_inputs=None)
344
- _save_job(_jobs[job_id])
345
- except Exception as exc:
346
- with _lock:
347
- if _jobs[job_id].get("status") != "cancelled":
348
- _jobs[job_id].update(status="failed", error=str(exc)[:500])
349
- _save_job(_jobs[job_id])
350
- finally:
351
- if 'ephemeral_endpoint' in locals() and ephemeral_endpoint and not ragas_started:
352
- unregister_endpoint(ephemeral_endpoint)
353
-
354
-
355
- def _hydrate_jobs() -> None:
356
- """Restore persisted jobs after a process restart and resume interrupted work."""
357
- for persisted in _load_jobs():
358
- # Evaluation inputs may include an in-memory endpoint object. Never
359
- # retain or expose that snapshot: it can contain a user's provider key.
360
- if "ragas_inputs" in persisted:
361
- persisted.pop("ragas_inputs", None)
362
- _save_job(persisted)
363
- job_id = persisted.get("id")
364
- if not job_id:
365
- continue
366
- status = persisted.get("status")
367
- _jobs[job_id] = persisted
368
- if persisted.get("ragas_task_id") and not persisted.get("ragas_status"):
369
- persisted.update(ragas_status="unavailable", ragas_error="Evaluation interrupted by restart; it was not automatically replayed.")
370
- _save_job(persisted)
371
- if status in {"queued", "processing"} and persisted.get("custom_provider"):
372
- persisted.update(status="failed", error="Provider credentials were not persisted; resubmit this review after restart.")
373
- _save_job(persisted)
374
- continue
375
- if status in {"queued", "processing", "processing_decision"}:
376
- # Decision processing cannot be safely replayed without an explicit
377
- # user action; review execution can be resumed idempotently.
378
- if status == "processing_decision":
379
- _jobs[job_id]["status"] = "awaiting_approval"
380
- _save_job(_jobs[job_id])
381
- continue
382
- try:
383
- request = ReviewRequest(repo=persisted["repo"], pr_number=int(persisted["pr_number"]), endpoint=persisted.get("endpoint"))
384
- except Exception:
385
- _jobs[job_id].update(status="failed", error="Persisted job request is invalid")
386
- _save_job(_jobs[job_id])
387
- continue
388
- _jobs[job_id]["status"] = "queued"
389
- _save_job(_jobs[job_id])
390
- _jobs[job_id]["future"] = _executor.submit(_run_job, job_id, request)
391
-
392
-
393
- _hydrate_jobs()
394
-
395
-
396
- @app.get("/api/health")
397
- def health() -> dict[str, Any]:
398
- provider_configured = any(
399
- os.getenv(name, "").strip()
400
- for name in ("GEMINI_API_KEY", "GROQ_API_KEY", "OPENAI_API_KEY", "ANTHROPIC_API_KEY")
401
- )
402
- provider_configured = provider_configured or bool(os.getenv("CLOUDFLARE_API_TOKEN", "").strip() and os.getenv("CLOUDFLARE_ACCOUNT_ID", "").strip())
403
- require_auth = os.getenv("OCR_REQUIRE_AUTH", "false").strip().lower() in {"1", "true", "yes", "on"}
404
- persistence = "local_default_path"
405
- if os.getenv("SUPABASE_DB_URL"):
406
- probe = _postgres_connect()
407
- if probe is not None:
408
- probe.close()
409
- persistence = "supabase_postgres"
410
- else:
411
- persistence = "supabase_configured_unreachable"
412
- elif os.getenv("OPENCODEREVIEW_DB_PATH"):
413
- persistence = "configured_path"
414
- return {
415
- "status": "ok",
416
- "inference": "remote_provider_configured" if provider_configured else "fallback_or_unconfigured",
417
- "authentication": "required" if require_auth else "optional",
418
- "rate_limit_per_minute": int(os.getenv("OCR_RATE_LIMIT_PER_MINUTE", "0") or 0),
419
- "persistence": persistence,
420
- "local_embeddings": os.getenv("OPENCODEREVIEW_ALLOW_LOCAL_EMBEDDINGS", "false").lower()
421
- in {"1", "true", "yes", "on"},
422
- }
423
-
424
-
425
- @app.post("/api/reviews", status_code=202)
426
- def create_review(request: ReviewRequest, http_request: Request, x_api_key: str | None = Header(default=None), idempotency_key: str | None = Header(default=None, alias="Idempotency-Key")) -> dict[str, Any]:
427
- _authorize_request(x_api_key, http_request)
428
- _rate_limit(http_request)
429
- owner = str((_session(http_request) or {}).get("github_id") or "api-key")
430
- material = request.model_dump()
431
- head_sha = base_sha = None
432
- try:
433
- token = (_session(http_request) or {}).get("token") or os.getenv("GITHUB_TOKEN", "")
434
- headers = {"Accept": "application/vnd.github+json", "Cache-Control": "no-cache"}
435
- if token:
436
- headers["Authorization"] = f"Bearer {token}"
437
- response = requests.get(f"https://api.github.com/repos/{request.repo}/pulls/{request.pr_number}", headers=headers, timeout=6)
438
- response.raise_for_status()
439
- pull = response.json()
440
- head_sha, base_sha = pull["head"]["sha"], pull["base"]["sha"]
441
- except (requests.RequestException, KeyError, ValueError):
442
- pass # Active deduplication still works if GitHub metadata is unavailable.
443
- prompt_hash = hashlib.sha256()
444
- project_root = Path(__file__).resolve().parent.parent
445
- for source in sorted(project_root.joinpath("prompts").glob("*.txt")):
446
- prompt_hash.update(source.read_bytes())
447
- for source in sorted(project_root.joinpath("nodes").glob("*.py")):
448
- prompt_hash.update(source.read_bytes())
449
- material.update(head_sha=head_sha, base_sha=base_sha, pipeline_version=prompt_hash.hexdigest())
450
- fingerprint = hashlib.sha256(json.dumps({"owner": owner, "request": material}, sort_keys=True).encode()).hexdigest()
451
- # Reuse completed previews only for an identical immutable diff and configuration.
452
- with _lock:
453
- existing = next((item for item in _jobs.values() if item.get("owner_id") == owner and item.get("request_fingerprint") == fingerprint and (item.get("status") in {"queued", "processing"} or (head_sha and base_sha and item.get("status") == "awaiting_approval" and time.time() - item.get("started_timestamp", 0) < 900))), None)
454
- if existing is None:
455
- job_id = str(uuid.uuid4())
456
- job = {"id": job_id, "repo": request.repo, "pr_number": request.pr_number, "endpoint": request.endpoint, "review_mode": request.review_mode, "baseline_sha": request.baseline_sha, "custom_provider": bool(request.api_key), "head_sha": head_sha, "base_sha": base_sha, "owner_id": owner, "request_fingerprint": fingerprint, "status": "queued", "created_at": datetime.now(timezone.utc).isoformat()}
457
- _jobs[job_id] = job
458
- _save_job(job)
459
- else:
460
- job = existing
461
- if existing is not None:
462
- return {**_public_job(job), "reused": True}
463
- job["future"] = _executor.submit(_run_job, job_id, request)
464
- return _public_job(job)
465
-
466
-
467
- @app.post("/api/reviews/{job_id}/cancel")
468
- def cancel_review(job_id: str, request: Request, x_api_key: str | None = Header(default=None)) -> dict[str, Any]:
469
- _authorize_request(x_api_key, request)
470
- owner = str((_session(request) or {}).get("github_id") or "api-key")
471
- with _lock:
472
- job = _jobs.get(job_id)
473
- if not job or job.get("owner_id", "api-key") != owner:
474
- raise HTTPException(status_code=404, detail="Review not found")
475
- if job.get("status") not in {"queued", "processing"}:
476
- raise HTTPException(status_code=409, detail="Only queued or processing reviews can be cancelled")
477
- future = job.get("future")
478
- if future:
479
- future.cancel()
480
- job.update(status="cancelled", cancellation_note="Running calls finish within their timeout; no results will be posted.")
481
- _save_job(job)
482
- return _public_job(job)
483
-
484
-
485
- @app.get("/api/reviews/{job_id}")
486
- def get_review(job_id: str, request: Request, x_api_key: str | None = Header(default=None)) -> dict[str, Any]:
487
- # API-key authorization remains supported for polling; OAuth callers use the cookie path.
488
- _authorize_request(x_api_key, request)
489
- with _lock:
490
- job = _jobs.get(job_id)
491
- if not job:
492
- job = _load_job(job_id)
493
- owner = str((_session(request) or {}).get("github_id") or "api-key")
494
- if not job or job.get("owner_id", "api-key") != owner:
495
- raise HTTPException(status_code=404, detail="Review not found")
496
- return _public_job(job)
497
-
498
-
499
- @app.post('/api/reviews/{job_id}/feedback')
500
- def finding_feedback(job_id: str, payload: FindingFeedbackRequest, request: Request,
501
- x_api_key: str | None = Header(default=None)) -> dict[str, Any]:
502
- _authorize_request(x_api_key, request)
503
- _rate_limit(request)
504
- owner = str((_session(request) or {}).get('github_id') or 'api-key')
505
- with _lock:
506
- job = _jobs.get(job_id) or _load_job(job_id)
507
- if not job or job.get('owner_id', 'api-key') != owner:
508
- raise HTTPException(status_code=404, detail='Review not found')
509
- if job.get('status') not in {'awaiting_approval', 'incomplete', 'posted', 'partially_posted', 'rejected', 'post_failed'}:
510
- raise HTTPException(status_code=409, detail='Wait until the review finishes before giving feedback')
511
- if payload.finding_index >= len(job.get('findings') or []):
512
- raise HTTPException(status_code=422, detail='Finding does not exist')
513
- feedback = dict(job.get('feedback') or {})
514
- feedback[str(payload.finding_index)] = payload.label
515
- job['feedback'] = feedback
516
- job['feedback_updated_at'] = datetime.now(timezone.utc).isoformat()
517
- _jobs[job_id] = job
518
- _save_job(job)
519
- return {'feedback': feedback}
520
-
521
-
522
- @app.post("/api/reviews/{job_id}/decision")
523
- def decide_review(job_id: str, request: DecisionRequest, http_request: Request, x_api_key: str | None = Header(default=None)) -> dict[str, Any]:
524
- _authorize_request(x_api_key, http_request)
525
- _rate_limit(http_request)
526
- with _lock:
527
- preview = _jobs.get(job_id) or _load_job(job_id)
528
- owner = str((_session(http_request) or {}).get("github_id") or "api-key")
529
- if not preview or preview.get("owner_id", "api-key") != owner:
530
- raise HTTPException(status_code=404, detail="Review not found")
531
- if request.action == "approve" and preview.get("baseline_sha"):
532
- raise HTTPException(status_code=409, detail="Incremental reviews are preview-only. Run a full review before posting.")
533
- if preview and request.action == "approve" and preview.get("head_sha"):
534
- headers = {"Accept": "application/vnd.github+json", "Cache-Control": "no-cache"}
535
- token = (_session(http_request) or {}).get("token") or os.getenv("GITHUB_TOKEN", "")
536
- if token:
537
- headers["Authorization"] = f"Bearer {token}"
538
- try:
539
- response = requests.get(f"https://api.github.com/repos/{preview['repo']}/pulls/{preview['pr_number']}", headers=headers, timeout=6)
540
- response.raise_for_status()
541
- current = response.json()
542
- if current["head"]["sha"] != preview["head_sha"] or current["base"]["sha"] != preview.get("base_sha"):
543
- raise HTTPException(status_code=409, detail="PR changed since this review; start a new review before posting.")
544
- except (requests.RequestException, KeyError, ValueError) as exc:
545
- raise HTTPException(status_code=503, detail="Cannot verify the current PR commit; retry before posting.") from exc
546
- with _lock:
547
- job = _jobs.get(job_id)
548
- if not job:
549
- job = _load_job(job_id)
550
- if not job:
551
- raise HTTPException(status_code=404, detail="Review not found")
552
- if job.get("status") != "awaiting_approval":
553
- raise HTTPException(status_code=409, detail="Review is not awaiting approval")
554
- config = job["config"]
555
- job["status"] = "processing_decision"
556
- _save_job(job)
557
- if request.action == "reject":
558
- with _lock:
559
- job.update(status="rejected", decision="reject")
560
- _save_job(job)
561
- return _public_job(job)
562
- graph = build_graph(DB_PATH)
563
- try:
564
- callbacks = [TokenCostCallback()]
565
- handler = get_langfuse_handler()
566
- if handler:
567
- callbacks.append(handler)
568
- config = dict(config)
569
- config["callbacks"] = callbacks
570
- result = graph.invoke(Command(resume={"action": "approve"}), config)
571
- posting_result = result.get("posting_result") if isinstance(result, dict) else None
572
- final_status = (posting_result or {}).get("status", "posted")
573
- with _lock:
574
- job.update(status=final_status, decision="approve", posting_result=posting_result)
575
- _save_job(job)
576
- return _public_job(job)
577
- except Exception as exc:
578
- with _lock:
579
- job.update(status="failed", error=str(exc)[:500])
580
- _save_job(job)
581
- raise HTTPException(status_code=500, detail="Decision processing failed") from exc
582
- finally:
583
- conn = getattr(graph, "_opencodereview_conn", None)
584
- if conn:
585
- conn.close()
586
- flush_langfuse()
 
1
+ """Small HTTP boundary for the React client.
2
+
3
+ The review engine remains in the existing LangGraph modules. This service only
4
+ owns job lifecycle and approval state; production deployments should replace
5
+ the process-local registry with a durable store and queue.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ import hashlib
11
+ import time
12
+ from pathlib import Path
13
+ import json
14
+ import logging
15
+ import secrets
16
+ import sqlite3
17
+ import threading
18
+ import uuid
19
+ import requests
20
+ from concurrent.futures import ThreadPoolExecutor
21
+ from datetime import datetime, timezone
22
+ from typing import Any, Literal
23
+
24
+ from fastapi import FastAPI, Header, HTTPException, Request
25
+ from fastapi.responses import RedirectResponse
26
+ from fastapi.middleware.cors import CORSMiddleware
27
+ from langgraph.types import Command
28
+ from pydantic import BaseModel, Field
29
+
30
+ from backend.app import DB_PATH, _build_and_stream, _normalize_endpoint_name, _spawn_ragas_background
31
+ from backend.graph import build_graph
32
+ from backend.observability import TokenCostCallback, flush_langfuse, get_langfuse_handler
33
+ from backend.state import Finding, Verdict
34
+ from backend.integrations.endpoints import register_endpoint, unregister_endpoint
35
+
36
+ app = FastAPI(title="OpenCodeReview API", version="0.1.0")
37
+ logger = logging.getLogger(__name__)
38
+
39
+
40
+
41
+
42
+
43
+
44
+
45
+
46
+ allowed_origins = [item.strip() for item in os.getenv("OCR_ALLOWED_ORIGINS", "http://localhost:5173").split(",") if item.strip()]
47
+ app.add_middleware(CORSMiddleware, allow_origins=allowed_origins, allow_methods=["GET", "POST"], allow_headers=["*"], allow_credentials=True)
48
+
49
+ _jobs: dict[str, dict[str, Any]] = {}
50
+ _lock = threading.Lock()
51
+ _executor = ThreadPoolExecutor(max_workers=int(os.getenv("OCR_MAX_WORKERS", "2")))
52
+ _rate_lock = threading.Lock()
53
+ _rate_windows: dict[str, list[float]] = {}
54
+ _oauth_states: set[str] = set()
55
+ _sessions: dict[str, dict[str, Any]] = {}
56
+
57
+ def _rate_limit(request: Request) -> None:
58
+ limit = int(os.getenv("OCR_RATE_LIMIT_PER_MINUTE", "0") or 0)
59
+ if limit <= 0:
60
+ return
61
+ now = datetime.now(timezone.utc).timestamp()
62
+ forwarded = request.headers.get("x-forwarded-for") or request.headers.get("x-real-ip")
63
+ key = (forwarded.split(",", 1)[0].strip() if forwarded else None) or "global"
64
+ with _rate_lock:
65
+ window = [stamp for stamp in _rate_windows.get(key, []) if now - stamp < 60]
66
+ if len(window) >= limit:
67
+ raise HTTPException(status_code=429, detail="Rate limit exceeded")
68
+ window.append(now)
69
+ _rate_windows[key] = window
70
+
71
+
72
+ def _postgres_connect():
73
+ """Return a Supabase Postgres connection when configured, else None."""
74
+ url = os.getenv("SUPABASE_DB_URL", "").strip()
75
+ if not url:
76
+ return None
77
+ try:
78
+ import psycopg
79
+ return psycopg.connect(url)
80
+ except Exception as exc:
81
+ # Connection strings and provider errors can include credentials.
82
+ logger.warning("Shared database connection failed (%s); using local storage", type(exc).__name__)
83
+ return None
84
+
85
+ def _sqlite_connect():
86
+ """Open the fallback store and ensure its schema exists on every path."""
87
+ conn = sqlite3.connect(DB_PATH)
88
+ conn.execute("CREATE TABLE IF NOT EXISTS review_jobs (id TEXT PRIMARY KEY, payload TEXT NOT NULL)")
89
+ conn.commit()
90
+ return conn
91
+
92
+ def _init_jobs() -> None:
93
+ # Prepare the fallback even when Postgres is available at startup: it can
94
+ # become unavailable later, while the process is still running.
95
+ with _sqlite_connect():
96
+ pass
97
+ pg = _postgres_connect()
98
+ if pg is not None:
99
+ with pg:
100
+ with pg.cursor() as cur:
101
+ cur.execute("""create table if not exists public.review_jobs (
102
+ id uuid primary key, repo text not null, pr_number integer not null,
103
+ endpoint text, status text not null, payload jsonb not null,
104
+ created_at timestamptz not null default now(), updated_at timestamptz not null default now())""")
105
+ cur.execute("create index if not exists review_jobs_status_idx on public.review_jobs (status)")
106
+ pg.close()
107
+ return
108
+
109
+ _init_jobs()
110
+
111
+ def _save_job(job: dict[str, Any]) -> None:
112
+ payload = {k: v for k, v in job.items() if k not in {"future", "ragas_inputs"}}
113
+ if "config" in payload:
114
+ payload["config"] = {"configurable": payload["config"].get("configurable", {})}
115
+ pg = None if job.get("persistence") == "local_fallback" else _postgres_connect()
116
+ if pg is not None:
117
+ with pg:
118
+ with pg.cursor() as cur:
119
+ cur.execute("""insert into public.review_jobs (id, repo, pr_number, endpoint, status, payload, updated_at)
120
+ values (%s, %s, %s, %s, %s, %s::jsonb, now())
121
+ on conflict (id) do update set repo=excluded.repo, pr_number=excluded.pr_number,
122
+ endpoint=excluded.endpoint, status=excluded.status, payload=excluded.payload, updated_at=now()""",
123
+ (job["id"], job["repo"], job["pr_number"], job.get("endpoint"), job["status"], json.dumps(payload, default=str)))
124
+ pg.close()
125
+ return
126
+ job["persistence"] = "local_fallback"
127
+ payload["persistence"] = "local_fallback"
128
+ with _sqlite_connect() as conn:
129
+ conn.execute("INSERT OR REPLACE INTO review_jobs (id, payload) VALUES (?, ?)", (job["id"], json.dumps(payload, default=str)))
130
+ conn.commit()
131
+
132
+ def _load_job(job_id: str) -> dict[str, Any] | None:
133
+ pg = _postgres_connect()
134
+ if pg is not None:
135
+ with pg.cursor() as cur:
136
+ cur.execute("select payload from public.review_jobs where id = %s", (job_id,))
137
+ row = cur.fetchone()
138
+ pg.close()
139
+ if row:
140
+ return json.loads(row[0]) if isinstance(row[0], str) else row[0]
141
+ with _sqlite_connect() as conn:
142
+ row = conn.execute("SELECT payload FROM review_jobs WHERE id = ?", (job_id,)).fetchone()
143
+ return json.loads(row[0]) if row else None
144
+
145
+ def _load_jobs() -> list[dict[str, Any]]:
146
+ pg = _postgres_connect()
147
+ if pg is not None:
148
+ with pg.cursor() as cur:
149
+ cur.execute("select payload from public.review_jobs")
150
+ rows = cur.fetchall()
151
+ pg.close()
152
+ return [json.loads(row[0]) if isinstance(row[0], str) else row[0] for row in rows]
153
+ with _sqlite_connect() as conn:
154
+ rows = conn.execute("SELECT payload FROM review_jobs").fetchall()
155
+ return [json.loads(row[0]) if isinstance(row[0], str) else row[0] for row in rows]
156
+
157
+
158
+ class ReviewRequest(BaseModel):
159
+ repo: str = Field(pattern=r"^[\w.-]+/[\w.-]+$")
160
+ pr_number: int = Field(gt=0)
161
+ endpoint: str | None = None
162
+ provider: str | None = Field(default=None, pattern=r"^(openai|anthropic|google)$")
163
+ model: str | None = None
164
+ api_key: str | None = None
165
+ base_url: str | None = None
166
+ review_mode: Literal["fast", "thorough"] = "thorough"
167
+ baseline_sha: str | None = Field(default=None, pattern=r"^[0-9a-fA-F]{40}$")
168
+
169
+
170
+ class DecisionRequest(BaseModel):
171
+ action: Literal["approve", "reject"]
172
+
173
+
174
+ class FindingFeedbackRequest(BaseModel):
175
+ finding_index: int = Field(ge=0)
176
+ label: Literal['correct', 'incorrect', 'useful']
177
+
178
+
179
+ def _authorize(token: str | None) -> None:
180
+ expected = os.getenv("OCR_API_KEY", "").strip()
181
+ # Authentication is opt-in for local development, but deployments can
182
+ # require it explicitly. Never silently treat a missing production key
183
+ # as authenticated.
184
+ require_auth = os.getenv("OCR_REQUIRE_AUTH", "false").strip().lower() in {"1", "true", "yes", "on"}
185
+ if require_auth and not expected:
186
+ raise HTTPException(status_code=503, detail="API authentication is not configured")
187
+ if expected and (not token or not secrets.compare_digest(token, expected)):
188
+ raise HTTPException(status_code=401, detail="Invalid API key")
189
+
190
+ def _authorize_request(token: str | None, request: Request) -> None:
191
+ if _session(request):
192
+ return
193
+ _authorize(token)
194
+
195
+ def _session(request: Request) -> dict[str, Any] | None:
196
+ sid = request.cookies.get("ocr_session")
197
+ return _sessions.get(sid) if sid else None
198
+
199
+ @app.get("/api/auth/github/start")
200
+ def github_login() -> RedirectResponse:
201
+ client_id = os.getenv("GITHUB_OAUTH_CLIENT_ID", "").strip()
202
+ if not client_id:
203
+ raise HTTPException(status_code=503, detail="GitHub OAuth is not configured")
204
+ state = secrets.token_urlsafe(32)
205
+ _oauth_states.add(state)
206
+ callback = os.getenv("GITHUB_OAUTH_CALLBACK_URL", "").strip() or "http://localhost:8000/api/auth/github/callback"
207
+ url = "https://github.com/login/oauth/authorize?" + requests.compat.urlencode({"client_id": client_id, "redirect_uri": callback, "scope": "read:user user:email repo", "state": state})
208
+ return RedirectResponse(url)
209
+
210
+ @app.get("/api/auth/github/callback")
211
+ def github_callback(code: str, state: str, response: Request) -> RedirectResponse:
212
+ if state not in _oauth_states:
213
+ raise HTTPException(status_code=400, detail="Invalid OAuth state")
214
+ _oauth_states.discard(state)
215
+ client_id = os.getenv("GITHUB_OAUTH_CLIENT_ID", "").strip()
216
+ client_secret = os.getenv("GITHUB_OAUTH_CLIENT_SECRET", "").strip()
217
+ callback = os.getenv("GITHUB_OAUTH_CALLBACK_URL", "").strip() or "http://localhost:8000/api/auth/github/callback"
218
+ token_resp = requests.post("https://github.com/login/oauth/access_token", data={"client_id": client_id, "client_secret": client_secret, "code": code, "redirect_uri": callback}, headers={"Accept": "application/json"}, timeout=20)
219
+ token_resp.raise_for_status()
220
+ access_token = token_resp.json().get("access_token")
221
+ if not access_token:
222
+ raise HTTPException(status_code=502, detail="GitHub did not return an access token")
223
+ user_resp = requests.get("https://api.github.com/user", headers={"Authorization": f"Bearer {access_token}", "Accept": "application/vnd.github+json"}, timeout=20)
224
+ user_resp.raise_for_status()
225
+ user = user_resp.json()
226
+ sid = secrets.token_urlsafe(32)
227
+ _sessions[sid] = {"token": access_token, "github_id": user.get("id"), "login": user.get("login")}
228
+ frontend = os.getenv("OCR_FRONTEND_URL", allowed_origins[0] if allowed_origins else "http://localhost:5173")
229
+ out = RedirectResponse(frontend)
230
+ out.set_cookie("ocr_session", sid, httponly=True, secure=frontend.startswith("https://"), samesite="lax", max_age=86400)
231
+ return out
232
+
233
+ @app.get("/api/auth/me")
234
+ def github_me(request: Request) -> dict[str, Any]:
235
+ session = _session(request)
236
+ if not session:
237
+ raise HTTPException(status_code=401, detail="Not authenticated")
238
+ return {"github_id": session["github_id"], "login": session["login"]}
239
+
240
+ @app.post("/api/auth/logout")
241
+ def github_logout(request: Request) -> dict[str, str]:
242
+ sid = request.cookies.get("ocr_session")
243
+ if sid:
244
+ _sessions.pop(sid, None)
245
+ return {"status": "logged_out"}
246
+
247
+
248
+ def _public_job(job: dict[str, Any]) -> dict[str, Any]:
249
+ private_keys = {
250
+ "config", "future", "request_fingerprint", "owner_id",
251
+ }
252
+ result = {
253
+ key: value for key, value in job.items()
254
+ if key not in private_keys and not key.startswith("ragas")
255
+ }
256
+ now = time.time()
257
+ result["elapsed_seconds"] = round(max(0, now - job.get("started_timestamp", now)), 1) if job.get("status") in {"processing", "queued"} else job.get("elapsed_seconds", 0)
258
+ if job.get("status") == "queued":
259
+ result["queue_position"] = sum(1 for item in _jobs.values() if item.get("status") == "queued" and item.get("created_at", "") <= job.get("created_at", ""))
260
+ return result
261
+
262
+
263
+ def _run_job(job_id: str, request: ReviewRequest) -> None:
264
+ with _lock:
265
+ if _jobs.get(job_id, {}).get("status") == "cancelled":
266
+ return
267
+ if job_id in _jobs:
268
+ _jobs[job_id].update(status="processing", started_timestamp=time.time(), progress={"stage": "ingestion", "completed_stages": []})
269
+ _save_job(_jobs[job_id])
270
+ try:
271
+ ephemeral_endpoint = None
272
+ ragas_started = False
273
+ endpoint_name = _normalize_endpoint_name(request.endpoint)
274
+ if request.api_key:
275
+ if not request.provider or not request.model:
276
+ raise ValueError("provider and model are required when supplying a user API key")
277
+ ephemeral_endpoint = f"user-{job_id}"
278
+ register_endpoint(ephemeral_endpoint, request.provider, request.api_key, request.base_url, request.model)
279
+ endpoint_name = ephemeral_endpoint
280
+ def save_ragas(scores: dict, error: str | None) -> None:
281
+ try:
282
+ with _lock:
283
+ live = _jobs.get(job_id)
284
+ if live is None:
285
+ return
286
+ live["ragas_scores"] = scores or None
287
+ live["ragas_status"] = "failed" if error else ("completed" if scores else "completed_no_scores")
288
+ live["ragas_error"] = error
289
+ _save_job(live)
290
+ finally:
291
+ # Custom providers are registered only for this job. Keep the
292
+ # endpoint alive until the background RAGAS task has finished;
293
+ # otherwise evaluation silently falls back to built-ins.
294
+ if ephemeral_endpoint:
295
+ unregister_endpoint(ephemeral_endpoint)
296
+
297
+ def progress(stage: str, elapsed: float, update: dict | None = None) -> None:
298
+ with _lock:
299
+ live = _jobs[job_id]
300
+ if live.get("status") == "cancelled":
301
+ raise RuntimeError("Review cancelled")
302
+ completed = live.setdefault("progress", {}).setdefault("completed_stages", [])
303
+ if stage not in completed:
304
+ completed.append(stage)
305
+ live["progress"]["stage"] = stage
306
+ live.setdefault("stage_timings", {})[stage] = round(elapsed, 2)
307
+ if isinstance(update, dict):
308
+ stages = update.get("review_stages", [])
309
+ if isinstance(stages, list):
310
+ live.setdefault("review_stages", []).extend(stages)
311
+ for key in ("findings",):
312
+ for finding in update.get(key, []) or []:
313
+ if hasattr(finding, "model_dump"):
314
+ finding = finding.model_dump(mode="json")
315
+ if isinstance(finding, dict):
316
+ live.setdefault("findings", []).append(finding)
317
+ _save_job(live)
318
+
319
+ state, config, cost, ragas, ragas_inputs = _build_and_stream(
320
+ request.repo,
321
+ request.pr_number,
322
+ endpoint_name,
323
+ ragas_background=True,
324
+ ragas_result_callback=save_ragas,
325
+ progress_callback=progress,
326
+ review_mode=request.review_mode,
327
+ baseline_sha=request.baseline_sha,
328
+ )
329
+ ragas_started = isinstance(ragas, str)
330
+ actual_head = state.values.get("head_sha")
331
+ verdict: Verdict | None = state.values.get("verdict")
332
+ findings: list[Finding] = state.values.get("final_findings", [])
333
+ with _lock:
334
+ if _jobs[job_id].get("status") == "cancelled":
335
+ return
336
+ if actual_head and _jobs[job_id].get("head_sha") != actual_head:
337
+ # The PR moved between metadata lookup and ingestion. The result
338
+ # can still be viewed, but must not satisfy the old cache key.
339
+ _jobs[job_id]["request_fingerprint"] = None
340
+ _jobs[job_id]["head_sha"] = actual_head
341
+ stages = state.values.get("review_stages", [])
342
+ incomplete = bool(verdict and verdict.recommendation == "incomplete")
343
+ _jobs[job_id].update(review_coverage=state.values.get("review_coverage", {}), review_stages=stages, elapsed_seconds=round(time.time() - _jobs[job_id]["started_timestamp"], 2), status="incomplete" if incomplete else "awaiting_approval", config=config, verdict=verdict.model_dump(mode="json") if verdict else None, findings=[item.model_dump(mode="json") for item in findings], cost=cost, cost_details=config.get("metadata", {}).get("cost_details"), ragas_task_id=ragas if isinstance(ragas, str) else None, ragas_scores=ragas if isinstance(ragas, dict) else None, ragas_inputs=None)
344
+ _save_job(_jobs[job_id])
345
+ except Exception as exc:
346
+ with _lock:
347
+ if _jobs[job_id].get("status") != "cancelled":
348
+ _jobs[job_id].update(status="failed", error=str(exc)[:500])
349
+ _save_job(_jobs[job_id])
350
+ finally:
351
+ if 'ephemeral_endpoint' in locals() and ephemeral_endpoint and not ragas_started:
352
+ unregister_endpoint(ephemeral_endpoint)
353
+
354
+
355
+ def _hydrate_jobs() -> None:
356
+ """Restore persisted jobs after a process restart and resume interrupted work."""
357
+ for persisted in _load_jobs():
358
+ # Evaluation inputs may include an in-memory endpoint object. Never
359
+ # retain or expose that snapshot: it can contain a user's provider key.
360
+ if "ragas_inputs" in persisted:
361
+ persisted.pop("ragas_inputs", None)
362
+ _save_job(persisted)
363
+ job_id = persisted.get("id")
364
+ if not job_id:
365
+ continue
366
+ status = persisted.get("status")
367
+ _jobs[job_id] = persisted
368
+ if persisted.get("ragas_task_id") and not persisted.get("ragas_status"):
369
+ persisted.update(ragas_status="unavailable", ragas_error="Evaluation interrupted by restart; it was not automatically replayed.")
370
+ _save_job(persisted)
371
+ if status in {"queued", "processing"} and persisted.get("custom_provider"):
372
+ persisted.update(status="failed", error="Provider credentials were not persisted; resubmit this review after restart.")
373
+ _save_job(persisted)
374
+ continue
375
+ if status in {"queued", "processing", "processing_decision"}:
376
+ # Decision processing cannot be safely replayed without an explicit
377
+ # user action; review execution can be resumed idempotently.
378
+ if status == "processing_decision":
379
+ _jobs[job_id]["status"] = "awaiting_approval"
380
+ _save_job(_jobs[job_id])
381
+ continue
382
+ try:
383
+ request = ReviewRequest(repo=persisted["repo"], pr_number=int(persisted["pr_number"]), endpoint=persisted.get("endpoint"))
384
+ except Exception:
385
+ _jobs[job_id].update(status="failed", error="Persisted job request is invalid")
386
+ _save_job(_jobs[job_id])
387
+ continue
388
+ _jobs[job_id]["status"] = "queued"
389
+ _save_job(_jobs[job_id])
390
+ _jobs[job_id]["future"] = _executor.submit(_run_job, job_id, request)
391
+
392
+
393
+ _hydrate_jobs()
394
+
395
+
396
+ @app.get("/api/health")
397
+ def health() -> dict[str, Any]:
398
+ provider_configured = any(
399
+ os.getenv(name, "").strip()
400
+ for name in ("GEMINI_API_KEY", "GROQ_API_KEY", "OPENAI_API_KEY", "ANTHROPIC_API_KEY")
401
+ )
402
+ provider_configured = provider_configured or bool(os.getenv("CLOUDFLARE_API_TOKEN", "").strip() and os.getenv("CLOUDFLARE_ACCOUNT_ID", "").strip())
403
+ require_auth = os.getenv("OCR_REQUIRE_AUTH", "false").strip().lower() in {"1", "true", "yes", "on"}
404
+ persistence = "local_default_path"
405
+ if os.getenv("SUPABASE_DB_URL"):
406
+ probe = _postgres_connect()
407
+ if probe is not None:
408
+ probe.close()
409
+ persistence = "supabase_postgres"
410
+ else:
411
+ persistence = "supabase_configured_unreachable"
412
+ elif os.getenv("OPENCODEREVIEW_DB_PATH"):
413
+ persistence = "configured_path"
414
+ return {
415
+ "status": "ok",
416
+ "inference": "remote_provider_configured" if provider_configured else "fallback_or_unconfigured",
417
+ "authentication": "required" if require_auth else "optional",
418
+ "rate_limit_per_minute": int(os.getenv("OCR_RATE_LIMIT_PER_MINUTE", "0") or 0),
419
+ "persistence": persistence,
420
+ "local_embeddings": os.getenv("OPENCODEREVIEW_ALLOW_LOCAL_EMBEDDINGS", "false").lower()
421
+ in {"1", "true", "yes", "on"},
422
+ }
423
+
424
+
425
+ @app.post("/api/reviews", status_code=202)
426
+ def create_review(request: ReviewRequest, http_request: Request, x_api_key: str | None = Header(default=None), idempotency_key: str | None = Header(default=None, alias="Idempotency-Key")) -> dict[str, Any]:
427
+ _authorize_request(x_api_key, http_request)
428
+ _rate_limit(http_request)
429
+ owner = str((_session(http_request) or {}).get("github_id") or "api-key")
430
+ material = request.model_dump()
431
+ head_sha = base_sha = None
432
+ try:
433
+ token = (_session(http_request) or {}).get("token") or os.getenv("GITHUB_TOKEN", "")
434
+ headers = {"Accept": "application/vnd.github+json", "Cache-Control": "no-cache"}
435
+ if token:
436
+ headers["Authorization"] = f"Bearer {token}"
437
+ response = requests.get(f"https://api.github.com/repos/{request.repo}/pulls/{request.pr_number}", headers=headers, timeout=6)
438
+ response.raise_for_status()
439
+ pull = response.json()
440
+ head_sha, base_sha = pull["head"]["sha"], pull["base"]["sha"]
441
+ except (requests.RequestException, KeyError, ValueError):
442
+ pass # Active deduplication still works if GitHub metadata is unavailable.
443
+ prompt_hash = hashlib.sha256()
444
+ project_root = Path(__file__).resolve().parent.parent
445
+ for source in sorted(project_root.joinpath("prompts").glob("*.txt")):
446
+ prompt_hash.update(source.read_bytes())
447
+ for source in sorted(project_root.joinpath("nodes").glob("*.py")):
448
+ prompt_hash.update(source.read_bytes())
449
+ material.update(head_sha=head_sha, base_sha=base_sha, pipeline_version=prompt_hash.hexdigest())
450
+ fingerprint = hashlib.sha256(json.dumps({"owner": owner, "request": material}, sort_keys=True).encode()).hexdigest()
451
+ # Reuse completed previews only for an identical immutable diff and configuration.
452
+ with _lock:
453
+ existing = next((item for item in _jobs.values() if item.get("owner_id") == owner and item.get("request_fingerprint") == fingerprint and (item.get("status") in {"queued", "processing"} or (head_sha and base_sha and item.get("status") == "awaiting_approval" and time.time() - item.get("started_timestamp", 0) < 900))), None)
454
+ if existing is None:
455
+ job_id = str(uuid.uuid4())
456
+ job = {"id": job_id, "repo": request.repo, "pr_number": request.pr_number, "endpoint": request.endpoint, "review_mode": request.review_mode, "baseline_sha": request.baseline_sha, "custom_provider": bool(request.api_key), "head_sha": head_sha, "base_sha": base_sha, "owner_id": owner, "request_fingerprint": fingerprint, "status": "queued", "created_at": datetime.now(timezone.utc).isoformat()}
457
+ _jobs[job_id] = job
458
+ _save_job(job)
459
+ else:
460
+ job = existing
461
+ if existing is not None:
462
+ return {**_public_job(job), "reused": True}
463
+ job["future"] = _executor.submit(_run_job, job_id, request)
464
+ return _public_job(job)
465
+
466
+
467
+ @app.post("/api/reviews/{job_id}/cancel")
468
+ def cancel_review(job_id: str, request: Request, x_api_key: str | None = Header(default=None)) -> dict[str, Any]:
469
+ _authorize_request(x_api_key, request)
470
+ owner = str((_session(request) or {}).get("github_id") or "api-key")
471
+ with _lock:
472
+ job = _jobs.get(job_id)
473
+ if not job or job.get("owner_id", "api-key") != owner:
474
+ raise HTTPException(status_code=404, detail="Review not found")
475
+ if job.get("status") not in {"queued", "processing"}:
476
+ raise HTTPException(status_code=409, detail="Only queued or processing reviews can be cancelled")
477
+ future = job.get("future")
478
+ if future:
479
+ future.cancel()
480
+ job.update(status="cancelled", cancellation_note="Running calls finish within their timeout; no results will be posted.")
481
+ _save_job(job)
482
+ return _public_job(job)
483
+
484
+
485
+ @app.get("/api/reviews/{job_id}")
486
+ def get_review(job_id: str, request: Request, x_api_key: str | None = Header(default=None)) -> dict[str, Any]:
487
+ # API-key authorization remains supported for polling; OAuth callers use the cookie path.
488
+ _authorize_request(x_api_key, request)
489
+ with _lock:
490
+ job = _jobs.get(job_id)
491
+ if not job:
492
+ job = _load_job(job_id)
493
+ owner = str((_session(request) or {}).get("github_id") or "api-key")
494
+ if not job or job.get("owner_id", "api-key") != owner:
495
+ raise HTTPException(status_code=404, detail="Review not found")
496
+ return _public_job(job)
497
+
498
+
499
+ @app.post('/api/reviews/{job_id}/feedback')
500
+ def finding_feedback(job_id: str, payload: FindingFeedbackRequest, request: Request,
501
+ x_api_key: str | None = Header(default=None)) -> dict[str, Any]:
502
+ _authorize_request(x_api_key, request)
503
+ _rate_limit(request)
504
+ owner = str((_session(request) or {}).get('github_id') or 'api-key')
505
+ with _lock:
506
+ job = _jobs.get(job_id) or _load_job(job_id)
507
+ if not job or job.get('owner_id', 'api-key') != owner:
508
+ raise HTTPException(status_code=404, detail='Review not found')
509
+ if job.get('status') not in {'awaiting_approval', 'incomplete', 'posted', 'partially_posted', 'rejected', 'post_failed'}:
510
+ raise HTTPException(status_code=409, detail='Wait until the review finishes before giving feedback')
511
+ if payload.finding_index >= len(job.get('findings') or []):
512
+ raise HTTPException(status_code=422, detail='Finding does not exist')
513
+ feedback = dict(job.get('feedback') or {})
514
+ feedback[str(payload.finding_index)] = payload.label
515
+ job['feedback'] = feedback
516
+ job['feedback_updated_at'] = datetime.now(timezone.utc).isoformat()
517
+ _jobs[job_id] = job
518
+ _save_job(job)
519
+ return {'feedback': feedback}
520
+
521
+
522
+ @app.post("/api/reviews/{job_id}/decision")
523
+ def decide_review(job_id: str, request: DecisionRequest, http_request: Request, x_api_key: str | None = Header(default=None)) -> dict[str, Any]:
524
+ _authorize_request(x_api_key, http_request)
525
+ _rate_limit(http_request)
526
+ with _lock:
527
+ preview = _jobs.get(job_id) or _load_job(job_id)
528
+ owner = str((_session(http_request) or {}).get("github_id") or "api-key")
529
+ if not preview or preview.get("owner_id", "api-key") != owner:
530
+ raise HTTPException(status_code=404, detail="Review not found")
531
+ if request.action == "approve" and preview.get("baseline_sha"):
532
+ raise HTTPException(status_code=409, detail="Incremental reviews are preview-only. Run a full review before posting.")
533
+ if preview and request.action == "approve" and preview.get("head_sha"):
534
+ headers = {"Accept": "application/vnd.github+json", "Cache-Control": "no-cache"}
535
+ token = (_session(http_request) or {}).get("token") or os.getenv("GITHUB_TOKEN", "")
536
+ if token:
537
+ headers["Authorization"] = f"Bearer {token}"
538
+ try:
539
+ response = requests.get(f"https://api.github.com/repos/{preview['repo']}/pulls/{preview['pr_number']}", headers=headers, timeout=6)
540
+ response.raise_for_status()
541
+ current = response.json()
542
+ if current["head"]["sha"] != preview["head_sha"] or current["base"]["sha"] != preview.get("base_sha"):
543
+ raise HTTPException(status_code=409, detail="PR changed since this review; start a new review before posting.")
544
+ except (requests.RequestException, KeyError, ValueError) as exc:
545
+ raise HTTPException(status_code=503, detail="Cannot verify the current PR commit; retry before posting.") from exc
546
+ with _lock:
547
+ job = _jobs.get(job_id)
548
+ if not job:
549
+ job = _load_job(job_id)
550
+ if not job:
551
+ raise HTTPException(status_code=404, detail="Review not found")
552
+ if job.get("status") != "awaiting_approval":
553
+ raise HTTPException(status_code=409, detail="Review is not awaiting approval")
554
+ config = job["config"]
555
+ job["status"] = "processing_decision"
556
+ _save_job(job)
557
+ if request.action == "reject":
558
+ with _lock:
559
+ job.update(status="rejected", decision="reject")
560
+ _save_job(job)
561
+ return _public_job(job)
562
+ graph = build_graph(DB_PATH)
563
+ try:
564
+ callbacks = [TokenCostCallback()]
565
+ handler = get_langfuse_handler()
566
+ if handler:
567
+ callbacks.append(handler)
568
+ config = dict(config)
569
+ config["callbacks"] = callbacks
570
+ result = graph.invoke(Command(resume={"action": "approve"}), config)
571
+ posting_result = result.get("posting_result") if isinstance(result, dict) else None
572
+ final_status = (posting_result or {}).get("status", "posted")
573
+ with _lock:
574
+ job.update(status=final_status, decision="approve", posting_result=posting_result)
575
+ _save_job(job)
576
+ return _public_job(job)
577
+ except Exception as exc:
578
+ with _lock:
579
+ job.update(status="failed", error=str(exc)[:500])
580
+ _save_job(job)
581
+ raise HTTPException(status_code=500, detail="Decision processing failed") from exc
582
+ finally:
583
+ conn = getattr(graph, "_opencodereview_conn", None)
584
+ if conn:
585
+ conn.close()
586
+ flush_langfuse()
backend/app.py CHANGED
The diff for this file is too large to render. See raw diff
 
backend/integrations/llm_factory.py CHANGED
@@ -1,364 +1,364 @@
1
- """Create chat models with Cloudflare, Groq, Gemini, and custom endpoints."""
2
-
3
- from __future__ import annotations
4
-
5
- import logging
6
- import os
7
- import re
8
- import threading
9
- import time
10
- from collections import deque
11
- from typing import Any, Optional
12
- from langchain_core.rate_limiters import BaseRateLimiter, InMemoryRateLimiter
13
- from backend.integrations.cloudflare_transport import CloudflareTransport, AsyncCloudflareTransport, ReachableCloudflareRoutes
14
-
15
- logger = logging.getLogger(__name__)
16
-
17
- # Gemini 3.1 Flash model name as of 2026-07
18
- # Verified via Google AI documentation: gemini-3.1-flash-lite is the correct name.
19
- # The base 'gemini-3.1-flash' does not exist in the API.
20
- GEMINI_MODEL = "gemini-3.1-flash-lite"
21
- GROQ_MODEL = os.getenv("GROQ_MODEL", "openai/gpt-oss-20b")
22
- CLOUDFLARE_MODEL = os.getenv("CLOUDFLARE_MODEL", "@cf/zai-org/glm-4.7-flash")
23
- class CloudflareRateLimiter(BaseRateLimiter):
24
- """Conservative per-process pacing and rolling daily attempt budget."""
25
-
26
- def __init__(self, daily_limit: int = 50):
27
- self.pacer = InMemoryRateLimiter(requests_per_second=0.2, check_every_n_seconds=0.1, max_bucket_size=1)
28
- self.daily_limit = daily_limit
29
- self.attempts = deque()
30
- self.lock = threading.Lock()
31
-
32
- def _reserve(self):
33
- now = time.monotonic()
34
- with self.lock:
35
- while self.attempts and self.attempts[0] <= now - 86400:
36
- self.attempts.popleft()
37
- if len(self.attempts) >= self.daily_limit:
38
- raise ValueError("Cloudflare local daily request budget reached; try later or choose another provider.")
39
- self.attempts.append(now)
40
-
41
- def acquire(self, *, blocking: bool = True) -> bool:
42
- if not self.pacer.acquire(blocking=blocking):
43
- return False
44
- self._reserve()
45
- return True
46
-
47
- async def aacquire(self, *, blocking: bool = True) -> bool:
48
- if not await self.pacer.aacquire(blocking=blocking):
49
- return False
50
- self._reserve()
51
- return True
52
-
53
-
54
- # Shared by reviewers and evaluation in this process. This request budget is
55
- # a conservative application cap, not a measurement of Cloudflare neurons.
56
- _cloudflare_limiter = CloudflareRateLimiter(max(1, int(os.getenv("CLOUDFLARE_DAILY_REQUEST_LIMIT", "50"))))
57
- _cloudflare_routes = ReachableCloudflareRoutes()
58
- DEFAULT_TEMPERATURE = 0.0
59
- DEFAULT_REQUEST_TIMEOUT = float(os.getenv("OCR_MODEL_TIMEOUT_SECONDS", "60"))
60
- DEFAULT_OUTPUT_TOKENS = int(os.getenv("OCR_MODEL_MAX_OUTPUT_TOKENS", "2000"))
61
-
62
-
63
- def _get_gemini_chat(**kwargs: Any) -> Optional[Any]:
64
- """Create a ``ChatGoogleGenerativeAI`` instance if ``GEMINI_API_KEY`` is set.
65
-
66
- Returns ``None`` silently when the key is missing or the package is not
67
- installed — callers are expected to fall back.
68
- """
69
- kwargs.setdefault("timeout", DEFAULT_REQUEST_TIMEOUT)
70
- kwargs.setdefault("max_retries", 0)
71
- kwargs.setdefault("max_tokens", DEFAULT_OUTPUT_TOKENS)
72
- api_key = os.environ.get("GEMINI_API_KEY", "").strip()
73
- if not api_key:
74
- return None
75
-
76
- try:
77
- from langchain_google_genai import ChatGoogleGenerativeAI
78
-
79
- return ChatGoogleGenerativeAI(
80
- model=kwargs.pop("model", GEMINI_MODEL),
81
- temperature=kwargs.pop("temperature", DEFAULT_TEMPERATURE),
82
- google_api_key=api_key,
83
- **kwargs,
84
- )
85
- except ImportError:
86
- logger.warning("langchain-google-genai not installed — skipping Gemini")
87
- return None
88
- except Exception as exc:
89
- logger.warning("Failed to initialise Gemini: %s", exc)
90
- return None
91
-
92
-
93
- def _get_groq_chat(**kwargs: Any) -> Optional[Any]:
94
- """Create a ``ChatGroq`` instance if ``GROQ_API_KEY`` is set."""
95
- kwargs.setdefault("timeout", DEFAULT_REQUEST_TIMEOUT)
96
- kwargs.setdefault("max_retries", 0)
97
- kwargs.setdefault("max_tokens", DEFAULT_OUTPUT_TOKENS)
98
- api_key = os.environ.get("GROQ_API_KEY", "").strip()
99
- if not api_key:
100
- return None
101
-
102
- try:
103
- from langchain_groq import ChatGroq
104
-
105
- return ChatGroq(
106
- model=kwargs.pop("model", GROQ_MODEL),
107
- temperature=kwargs.pop("temperature", DEFAULT_TEMPERATURE),
108
- api_key=api_key,
109
- **kwargs,
110
- )
111
- except ImportError:
112
- logger.warning("langchain-groq not installed")
113
- return None
114
- except Exception as exc:
115
- logger.warning("Failed to initialise Groq: %s", exc)
116
- return None
117
-
118
-
119
- def _get_cloudflare_chat(**kwargs: Any) -> Optional[Any]:
120
- """Use Workers AI when an account ID and API token are configured."""
121
- api_key = os.environ.get("CLOUDFLARE_API_TOKEN", "").strip()
122
- account_id = os.environ.get("CLOUDFLARE_ACCOUNT_ID", "").strip()
123
- gateway_id = os.environ.get("CLOUDFLARE_GATEWAY_ID", "").strip()
124
- gateway_token = os.environ.get("CLOUDFLARE_GATEWAY_TOKEN", "").strip()
125
- if not api_key or not account_id:
126
- return None
127
- if not re.fullmatch(r"[0-9a-fA-F]{32}", account_id):
128
- raise ValueError("CLOUDFLARE_ACCOUNT_ID must be a 32-character hexadecimal account ID.")
129
- if gateway_id and not re.fullmatch(r"[A-Za-z0-9_-]{1,64}", gateway_id):
130
- raise ValueError("CLOUDFLARE_GATEWAY_ID contains invalid characters.")
131
- from langchain_openai import ChatOpenAI
132
- import httpx
133
- timeout = kwargs.pop("timeout", DEFAULT_REQUEST_TIMEOUT)
134
- if isinstance(timeout, (int, float)):
135
- timeout = httpx.Timeout(timeout, connect=min(float(timeout), 4.0))
136
- # Retry only failures while establishing a connection, before an HTTP
137
- # request is sent. Preserve normal TLS certificate and hostname checks.
138
- # IPv6 is unavailable on the hosted Space; keep DNS and TLS SNI intact.
139
- if gateway_id:
140
- # Cloudflare's AI Gateway is an official alternate route to Workers AI.
141
- # Request no gateway cache or stored logs for potentially private code.
142
- headers = dict(kwargs.pop("default_headers", {}) or {})
143
- headers.update({"cf-aig-authorization": f"Bearer {gateway_token or api_key}", "cf-aig-collect-log": "false", "cf-aig-skip-cache": "true"})
144
- kwargs["default_headers"] = headers
145
- # The gateway's hostname route was reachable with normal TLS/SNI, while
146
- # pinning its resolved IPs produced intermittent connect errors from HF.
147
- # Let HTTPX resolve the official hostname and retry connection setup.
148
- kwargs.setdefault("http_client", httpx.Client(transport=httpx.HTTPTransport(retries=2), timeout=timeout))
149
- kwargs.setdefault("http_async_client", httpx.AsyncClient(transport=httpx.AsyncHTTPTransport(retries=2), timeout=timeout))
150
- base_url = f"https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/compat"
151
- else:
152
- kwargs.setdefault("http_client", httpx.Client(transport=CloudflareTransport(_cloudflare_routes), timeout=timeout))
153
- kwargs.setdefault("http_async_client", httpx.AsyncClient(transport=AsyncCloudflareTransport(_cloudflare_routes), timeout=timeout))
154
- base_url = f"https://api.cloudflare.com/client/v4/accounts/{account_id}/ai/v1"
155
- kwargs["timeout"] = timeout
156
- kwargs.setdefault("max_retries", 0)
157
- kwargs["max_tokens"] = max(int(kwargs.get("max_tokens") or DEFAULT_OUTPUT_TOKENS), 4096)
158
- kwargs.setdefault("reasoning_effort", "low")
159
- kwargs.setdefault("rate_limiter", _cloudflare_limiter)
160
- model = kwargs.pop("model", CLOUDFLARE_MODEL)
161
- if gateway_id and model.startswith("@cf/"):
162
- model = f"workers-ai/{model}"
163
- return ChatOpenAI(model=model, api_key=api_key,
164
- base_url=base_url,
165
- temperature=kwargs.pop("temperature", DEFAULT_TEMPERATURE), **kwargs)
166
-
167
-
168
- def create_endpoint_llm(endpoint, **kwargs: Any) -> Any:
169
- """Create a chat model from a user-configured custom endpoint.
170
-
171
- Supports OpenAI-compatible APIs (DeepSeek, OpenRouter, vLLM, Ollama,
172
- Groq, Together, ...), Anthropic Claude, and Google Gemini.
173
-
174
- Parameters
175
- ----------
176
- endpoint : EndpointConfig
177
- The user's endpoint config (name, provider, api_key, base_url, model).
178
- **kwargs
179
- Passed through to the underlying LangChain constructor (e.g.
180
- ``temperature``). ``model`` / ``api_key`` / ``base_url`` come from
181
- the endpoint and cannot be overridden here.
182
-
183
- Returns
184
- -------
185
- Any
186
- A LangChain chat model instance (``ChatOpenAI``, ``ChatAnthropic``
187
- or ``ChatGoogleGenerativeAI``).
188
-
189
- Raises
190
- ------
191
- ValueError
192
- If the endpoint's provider package is not installed or the config
193
- is incomplete.
194
- """
195
- if not endpoint.api_key or not endpoint.model:
196
- raise ValueError(
197
- f"Endpoint '{endpoint.name}' is missing an API key or model name."
198
- )
199
-
200
- kwargs.setdefault("timeout", DEFAULT_REQUEST_TIMEOUT)
201
- kwargs.setdefault("max_retries", 0)
202
- kwargs.setdefault("max_tokens", DEFAULT_OUTPUT_TOKENS)
203
- provider = endpoint.provider
204
- model = endpoint.model
205
- # MiniMax M3.1 requires reasoning and OpenRouter defaults to max effort.
206
- # Reserve room for reasoning + visible JSON rather than truncating at 1200.
207
- if 'minimax-m3.1' in model.lower():
208
- kwargs['max_tokens'] = max(int(kwargs.get('max_tokens') or 0), 8192)
209
- if endpoint.base_url and 'openrouter.ai' in endpoint.base_url:
210
- extra = dict(kwargs.get('extra_body') or {})
211
- extra['reasoning'] = {'effort': 'low'}
212
- kwargs['extra_body'] = extra
213
- temperature = kwargs.pop("temperature", DEFAULT_TEMPERATURE)
214
-
215
- if provider == "anthropic":
216
- try:
217
- from langchain_anthropic import ChatAnthropic
218
- except ImportError:
219
- raise ValueError(
220
- "langchain-anthropic is not installed — cannot use endpoint "
221
- f"'{endpoint.name}'. Run: pip install langchain-anthropic"
222
- ) from None
223
- params: dict[str, Any] = {
224
- "model": model,
225
- "api_key": endpoint.api_key,
226
- "temperature": temperature,
227
- }
228
- if endpoint.base_url:
229
- params["base_url"] = endpoint.base_url
230
- params.update(kwargs)
231
- return ChatAnthropic(**params)
232
-
233
- if provider == "google":
234
- try:
235
- from langchain_google_genai import ChatGoogleGenerativeAI
236
- except ImportError:
237
- raise ValueError(
238
- "langchain-google-genai is not installed — cannot use endpoint "
239
- f"'{endpoint.name}'. Run: pip install langchain-google-genai"
240
- ) from None
241
- params = {
242
- "model": model,
243
- "google_api_key": endpoint.api_key,
244
- "temperature": temperature,
245
- }
246
- params.update(kwargs)
247
- return ChatGoogleGenerativeAI(**params)
248
-
249
- # Default: OpenAI-compatible
250
- try:
251
- from langchain_openai import ChatOpenAI
252
- except ImportError:
253
- raise ValueError(
254
- "langchain-openai is not installed — cannot use endpoint "
255
- f"'{endpoint.name}'. Run: pip install langchain-openai"
256
- ) from None
257
- params = {
258
- "model": model,
259
- "api_key": endpoint.api_key,
260
- "temperature": temperature,
261
- }
262
- if endpoint.base_url:
263
- params["base_url"] = endpoint.base_url
264
- if "api.cloudflare.com/client/v4/accounts/" in endpoint.base_url.lower():
265
- kwargs.setdefault("rate_limiter", _cloudflare_limiter)
266
- params.update(kwargs)
267
- return ChatOpenAI(**params)
268
-
269
-
270
- def create_llm(endpoint=None, **kwargs: Any) -> Any:
271
- """Create a chat LLM — selected endpoint first, else Gemini → Groq → Cloudflare.
272
-
273
- Parameters
274
- ----------
275
- endpoint : EndpointConfig or str or None
276
- A custom endpoint to run on (``EndpointConfig`` object or its name).
277
- ``None`` (default) falls back to the built-in providers.
278
- **kwargs
279
- Passed through to the underlying LangChain constructor.
280
- Common overrides: ``model``, ``temperature``.
281
-
282
- Returns
283
- -------
284
- Any
285
- A LangChain chat model instance (``ChatOpenAI``/``ChatAnthropic``/
286
- ``ChatGoogleGenerativeAI`` from a custom endpoint, or the built-in
287
- ``ChatGoogleGenerativeAI`` / ``ChatGroq``).
288
-
289
- Raises
290
- ------
291
- ValueError
292
- If a custom endpoint is named but not found, or no provider key is set.
293
- """
294
- if endpoint:
295
- from backend.integrations.endpoints import EndpointConfig, get_endpoint
296
-
297
- # The browser historically sent lowercase builtin ids while the
298
- # endpoint registry uses display names. Accept both for API clients.
299
- if isinstance(endpoint, str):
300
- endpoint = {"gemini": "Gemini", "groq": "Grok", "cloudflare": "Cloudflare"}.get(endpoint.lower(), endpoint)
301
- ep = endpoint if isinstance(endpoint, EndpointConfig) else get_endpoint(endpoint)
302
- if ep is not None:
303
- if getattr(ep, "builtin", False):
304
- if ep.name == "Cloudflare":
305
- llm = _get_cloudflare_chat(**kwargs)
306
- if llm is not None:
307
- return llm
308
- raise ValueError("Cloudflare selected but CLOUDFLARE_ACCOUNT_ID or CLOUDFLARE_API_TOKEN is not set.")
309
- # Built-in providers use their native constructors so the
310
- # behaviour is identical to the default (no-endpoint) path.
311
- if ep.name == "Gemini":
312
- llm = _get_gemini_chat(**kwargs)
313
- if llm is not None:
314
- logger.info(
315
- "Using built-in Gemini endpoint (model=%s)",
316
- kwargs.get("model", GEMINI_MODEL),
317
- )
318
- return llm
319
- raise ValueError(
320
- "Gemini selected but GEMINI_API_KEY is not set."
321
- )
322
- if ep.name == "Grok":
323
- llm = _get_groq_chat(**kwargs)
324
- if llm is not None:
325
- logger.info(
326
- "Using built-in Grok endpoint (model=%s)",
327
- kwargs.get("model", GROQ_MODEL),
328
- )
329
- return llm
330
- raise ValueError(
331
- "Grok selected but GROQ_API_KEY is not set."
332
- )
333
- try:
334
- llm = create_endpoint_llm(ep, **kwargs)
335
- logger.info("Using custom endpoint %s (%s/%s)", ep.name, ep.provider, ep.model)
336
- return llm
337
- except ValueError:
338
- raise
339
- else:
340
- raise ValueError(
341
- f"Custom endpoint '{endpoint}' not found. "
342
- "Configure it via OCR_ENDPOINT_* environment variables "
343
- "or add it in the UI."
344
- )
345
-
346
- llm = _get_gemini_chat(**kwargs)
347
- if llm is not None:
348
- logger.debug("Using Gemini (model=%s)", kwargs.get("model", GEMINI_MODEL))
349
- return llm
350
-
351
- llm = _get_groq_chat(**kwargs)
352
- if llm is not None:
353
- logger.debug("Falling back to Groq (model=%s)", kwargs.get("model", GROQ_MODEL))
354
- return llm
355
-
356
- llm = _get_cloudflare_chat(**kwargs)
357
- if llm is not None:
358
- logger.debug("Falling back to Cloudflare (model=%s)", kwargs.get("model", CLOUDFLARE_MODEL))
359
- return llm
360
-
361
- raise ValueError(
362
- "No LLM available. Set GEMINI_API_KEY, GROQ_API_KEY, or both "
363
- "CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_API_TOKEN."
364
- )
 
1
+ """Create chat models with Cloudflare, Groq, Gemini, and custom endpoints."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import os
7
+ import re
8
+ import threading
9
+ import time
10
+ from collections import deque
11
+ from typing import Any, Optional
12
+ from langchain_core.rate_limiters import BaseRateLimiter, InMemoryRateLimiter
13
+ from backend.integrations.cloudflare_transport import CloudflareTransport, AsyncCloudflareTransport, ReachableCloudflareRoutes
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+ # Gemini 3.1 Flash model name as of 2026-07
18
+ # Verified via Google AI documentation: gemini-3.1-flash-lite is the correct name.
19
+ # The base 'gemini-3.1-flash' does not exist in the API.
20
+ GEMINI_MODEL = "gemini-3.1-flash-lite"
21
+ GROQ_MODEL = os.getenv("GROQ_MODEL", "openai/gpt-oss-20b")
22
+ CLOUDFLARE_MODEL = os.getenv("CLOUDFLARE_MODEL", "@cf/zai-org/glm-4.7-flash")
23
+ class CloudflareRateLimiter(BaseRateLimiter):
24
+ """Conservative per-process pacing and rolling daily attempt budget."""
25
+
26
+ def __init__(self, daily_limit: int = 50):
27
+ self.pacer = InMemoryRateLimiter(requests_per_second=0.2, check_every_n_seconds=0.1, max_bucket_size=1)
28
+ self.daily_limit = daily_limit
29
+ self.attempts = deque()
30
+ self.lock = threading.Lock()
31
+
32
+ def _reserve(self):
33
+ now = time.monotonic()
34
+ with self.lock:
35
+ while self.attempts and self.attempts[0] <= now - 86400:
36
+ self.attempts.popleft()
37
+ if len(self.attempts) >= self.daily_limit:
38
+ raise ValueError("Cloudflare local daily request budget reached; try later or choose another provider.")
39
+ self.attempts.append(now)
40
+
41
+ def acquire(self, *, blocking: bool = True) -> bool:
42
+ if not self.pacer.acquire(blocking=blocking):
43
+ return False
44
+ self._reserve()
45
+ return True
46
+
47
+ async def aacquire(self, *, blocking: bool = True) -> bool:
48
+ if not await self.pacer.aacquire(blocking=blocking):
49
+ return False
50
+ self._reserve()
51
+ return True
52
+
53
+
54
+ # Shared by reviewers and evaluation in this process. This request budget is
55
+ # a conservative application cap, not a measurement of Cloudflare neurons.
56
+ _cloudflare_limiter = CloudflareRateLimiter(max(1, int(os.getenv("CLOUDFLARE_DAILY_REQUEST_LIMIT", "50"))))
57
+ _cloudflare_routes = ReachableCloudflareRoutes()
58
+ DEFAULT_TEMPERATURE = 0.0
59
+ DEFAULT_REQUEST_TIMEOUT = float(os.getenv("OCR_MODEL_TIMEOUT_SECONDS", "60"))
60
+ DEFAULT_OUTPUT_TOKENS = int(os.getenv("OCR_MODEL_MAX_OUTPUT_TOKENS", "2000"))
61
+
62
+
63
+ def _get_gemini_chat(**kwargs: Any) -> Optional[Any]:
64
+ """Create a ``ChatGoogleGenerativeAI`` instance if ``GEMINI_API_KEY`` is set.
65
+
66
+ Returns ``None`` silently when the key is missing or the package is not
67
+ installed — callers are expected to fall back.
68
+ """
69
+ kwargs.setdefault("timeout", DEFAULT_REQUEST_TIMEOUT)
70
+ kwargs.setdefault("max_retries", 0)
71
+ kwargs.setdefault("max_tokens", DEFAULT_OUTPUT_TOKENS)
72
+ api_key = os.environ.get("GEMINI_API_KEY", "").strip()
73
+ if not api_key:
74
+ return None
75
+
76
+ try:
77
+ from langchain_google_genai import ChatGoogleGenerativeAI
78
+
79
+ return ChatGoogleGenerativeAI(
80
+ model=kwargs.pop("model", GEMINI_MODEL),
81
+ temperature=kwargs.pop("temperature", DEFAULT_TEMPERATURE),
82
+ google_api_key=api_key,
83
+ **kwargs,
84
+ )
85
+ except ImportError:
86
+ logger.warning("langchain-google-genai not installed — skipping Gemini")
87
+ return None
88
+ except Exception as exc:
89
+ logger.warning("Failed to initialise Gemini: %s", exc)
90
+ return None
91
+
92
+
93
+ def _get_groq_chat(**kwargs: Any) -> Optional[Any]:
94
+ """Create a ``ChatGroq`` instance if ``GROQ_API_KEY`` is set."""
95
+ kwargs.setdefault("timeout", DEFAULT_REQUEST_TIMEOUT)
96
+ kwargs.setdefault("max_retries", 0)
97
+ kwargs.setdefault("max_tokens", DEFAULT_OUTPUT_TOKENS)
98
+ api_key = os.environ.get("GROQ_API_KEY", "").strip()
99
+ if not api_key:
100
+ return None
101
+
102
+ try:
103
+ from langchain_groq import ChatGroq
104
+
105
+ return ChatGroq(
106
+ model=kwargs.pop("model", GROQ_MODEL),
107
+ temperature=kwargs.pop("temperature", DEFAULT_TEMPERATURE),
108
+ api_key=api_key,
109
+ **kwargs,
110
+ )
111
+ except ImportError:
112
+ logger.warning("langchain-groq not installed")
113
+ return None
114
+ except Exception as exc:
115
+ logger.warning("Failed to initialise Groq: %s", exc)
116
+ return None
117
+
118
+
119
+ def _get_cloudflare_chat(**kwargs: Any) -> Optional[Any]:
120
+ """Use Workers AI when an account ID and API token are configured."""
121
+ api_key = os.environ.get("CLOUDFLARE_API_TOKEN", "").strip()
122
+ account_id = os.environ.get("CLOUDFLARE_ACCOUNT_ID", "").strip()
123
+ gateway_id = os.environ.get("CLOUDFLARE_GATEWAY_ID", "").strip()
124
+ gateway_token = os.environ.get("CLOUDFLARE_GATEWAY_TOKEN", "").strip()
125
+ if not api_key or not account_id:
126
+ return None
127
+ if not re.fullmatch(r"[0-9a-fA-F]{32}", account_id):
128
+ raise ValueError("CLOUDFLARE_ACCOUNT_ID must be a 32-character hexadecimal account ID.")
129
+ if gateway_id and not re.fullmatch(r"[A-Za-z0-9_-]{1,64}", gateway_id):
130
+ raise ValueError("CLOUDFLARE_GATEWAY_ID contains invalid characters.")
131
+ from langchain_openai import ChatOpenAI
132
+ import httpx
133
+ timeout = kwargs.pop("timeout", DEFAULT_REQUEST_TIMEOUT)
134
+ if isinstance(timeout, (int, float)):
135
+ timeout = httpx.Timeout(timeout, connect=min(float(timeout), 4.0))
136
+ # Retry only failures while establishing a connection, before an HTTP
137
+ # request is sent. Preserve normal TLS certificate and hostname checks.
138
+ # IPv6 is unavailable on the hosted Space; keep DNS and TLS SNI intact.
139
+ if gateway_id:
140
+ # Cloudflare's AI Gateway is an official alternate route to Workers AI.
141
+ # Request no gateway cache or stored logs for potentially private code.
142
+ headers = dict(kwargs.pop("default_headers", {}) or {})
143
+ headers.update({"cf-aig-authorization": f"Bearer {gateway_token or api_key}", "cf-aig-collect-log": "false", "cf-aig-skip-cache": "true"})
144
+ kwargs["default_headers"] = headers
145
+ # The gateway's hostname route was reachable with normal TLS/SNI, while
146
+ # pinning its resolved IPs produced intermittent connect errors from HF.
147
+ # Let HTTPX resolve the official hostname and retry connection setup.
148
+ kwargs.setdefault("http_client", httpx.Client(transport=httpx.HTTPTransport(retries=2), timeout=timeout))
149
+ kwargs.setdefault("http_async_client", httpx.AsyncClient(transport=httpx.AsyncHTTPTransport(retries=2), timeout=timeout))
150
+ base_url = f"https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/compat"
151
+ else:
152
+ kwargs.setdefault("http_client", httpx.Client(transport=CloudflareTransport(_cloudflare_routes), timeout=timeout))
153
+ kwargs.setdefault("http_async_client", httpx.AsyncClient(transport=AsyncCloudflareTransport(_cloudflare_routes), timeout=timeout))
154
+ base_url = f"https://api.cloudflare.com/client/v4/accounts/{account_id}/ai/v1"
155
+ kwargs["timeout"] = timeout
156
+ kwargs.setdefault("max_retries", 0)
157
+ kwargs["max_tokens"] = max(int(kwargs.get("max_tokens") or DEFAULT_OUTPUT_TOKENS), 4096)
158
+ kwargs.setdefault("reasoning_effort", "low")
159
+ kwargs.setdefault("rate_limiter", _cloudflare_limiter)
160
+ model = kwargs.pop("model", CLOUDFLARE_MODEL)
161
+ if gateway_id and model.startswith("@cf/"):
162
+ model = f"workers-ai/{model}"
163
+ return ChatOpenAI(model=model, api_key=api_key,
164
+ base_url=base_url,
165
+ temperature=kwargs.pop("temperature", DEFAULT_TEMPERATURE), **kwargs)
166
+
167
+
168
+ def create_endpoint_llm(endpoint, **kwargs: Any) -> Any:
169
+ """Create a chat model from a user-configured custom endpoint.
170
+
171
+ Supports OpenAI-compatible APIs (DeepSeek, OpenRouter, vLLM, Ollama,
172
+ Groq, Together, ...), Anthropic Claude, and Google Gemini.
173
+
174
+ Parameters
175
+ ----------
176
+ endpoint : EndpointConfig
177
+ The user's endpoint config (name, provider, api_key, base_url, model).
178
+ **kwargs
179
+ Passed through to the underlying LangChain constructor (e.g.
180
+ ``temperature``). ``model`` / ``api_key`` / ``base_url`` come from
181
+ the endpoint and cannot be overridden here.
182
+
183
+ Returns
184
+ -------
185
+ Any
186
+ A LangChain chat model instance (``ChatOpenAI``, ``ChatAnthropic``
187
+ or ``ChatGoogleGenerativeAI``).
188
+
189
+ Raises
190
+ ------
191
+ ValueError
192
+ If the endpoint's provider package is not installed or the config
193
+ is incomplete.
194
+ """
195
+ if not endpoint.api_key or not endpoint.model:
196
+ raise ValueError(
197
+ f"Endpoint '{endpoint.name}' is missing an API key or model name."
198
+ )
199
+
200
+ kwargs.setdefault("timeout", DEFAULT_REQUEST_TIMEOUT)
201
+ kwargs.setdefault("max_retries", 0)
202
+ kwargs.setdefault("max_tokens", DEFAULT_OUTPUT_TOKENS)
203
+ provider = endpoint.provider
204
+ model = endpoint.model
205
+ # MiniMax M3.1 requires reasoning and OpenRouter defaults to max effort.
206
+ # Reserve room for reasoning + visible JSON rather than truncating at 1200.
207
+ if 'minimax-m3.1' in model.lower():
208
+ kwargs['max_tokens'] = max(int(kwargs.get('max_tokens') or 0), 8192)
209
+ if endpoint.base_url and 'openrouter.ai' in endpoint.base_url:
210
+ extra = dict(kwargs.get('extra_body') or {})
211
+ extra['reasoning'] = {'effort': 'low'}
212
+ kwargs['extra_body'] = extra
213
+ temperature = kwargs.pop("temperature", DEFAULT_TEMPERATURE)
214
+
215
+ if provider == "anthropic":
216
+ try:
217
+ from langchain_anthropic import ChatAnthropic
218
+ except ImportError:
219
+ raise ValueError(
220
+ "langchain-anthropic is not installed — cannot use endpoint "
221
+ f"'{endpoint.name}'. Run: pip install langchain-anthropic"
222
+ ) from None
223
+ params: dict[str, Any] = {
224
+ "model": model,
225
+ "api_key": endpoint.api_key,
226
+ "temperature": temperature,
227
+ }
228
+ if endpoint.base_url:
229
+ params["base_url"] = endpoint.base_url
230
+ params.update(kwargs)
231
+ return ChatAnthropic(**params)
232
+
233
+ if provider == "google":
234
+ try:
235
+ from langchain_google_genai import ChatGoogleGenerativeAI
236
+ except ImportError:
237
+ raise ValueError(
238
+ "langchain-google-genai is not installed — cannot use endpoint "
239
+ f"'{endpoint.name}'. Run: pip install langchain-google-genai"
240
+ ) from None
241
+ params = {
242
+ "model": model,
243
+ "google_api_key": endpoint.api_key,
244
+ "temperature": temperature,
245
+ }
246
+ params.update(kwargs)
247
+ return ChatGoogleGenerativeAI(**params)
248
+
249
+ # Default: OpenAI-compatible
250
+ try:
251
+ from langchain_openai import ChatOpenAI
252
+ except ImportError:
253
+ raise ValueError(
254
+ "langchain-openai is not installed — cannot use endpoint "
255
+ f"'{endpoint.name}'. Run: pip install langchain-openai"
256
+ ) from None
257
+ params = {
258
+ "model": model,
259
+ "api_key": endpoint.api_key,
260
+ "temperature": temperature,
261
+ }
262
+ if endpoint.base_url:
263
+ params["base_url"] = endpoint.base_url
264
+ if "api.cloudflare.com/client/v4/accounts/" in endpoint.base_url.lower():
265
+ kwargs.setdefault("rate_limiter", _cloudflare_limiter)
266
+ params.update(kwargs)
267
+ return ChatOpenAI(**params)
268
+
269
+
270
+ def create_llm(endpoint=None, **kwargs: Any) -> Any:
271
+ """Create a chat LLM — selected endpoint first, else Gemini → Groq → Cloudflare.
272
+
273
+ Parameters
274
+ ----------
275
+ endpoint : EndpointConfig or str or None
276
+ A custom endpoint to run on (``EndpointConfig`` object or its name).
277
+ ``None`` (default) falls back to the built-in providers.
278
+ **kwargs
279
+ Passed through to the underlying LangChain constructor.
280
+ Common overrides: ``model``, ``temperature``.
281
+
282
+ Returns
283
+ -------
284
+ Any
285
+ A LangChain chat model instance (``ChatOpenAI``/``ChatAnthropic``/
286
+ ``ChatGoogleGenerativeAI`` from a custom endpoint, or the built-in
287
+ ``ChatGoogleGenerativeAI`` / ``ChatGroq``).
288
+
289
+ Raises
290
+ ------
291
+ ValueError
292
+ If a custom endpoint is named but not found, or no provider key is set.
293
+ """
294
+ if endpoint:
295
+ from backend.integrations.endpoints import EndpointConfig, get_endpoint
296
+
297
+ # The browser historically sent lowercase builtin ids while the
298
+ # endpoint registry uses display names. Accept both for API clients.
299
+ if isinstance(endpoint, str):
300
+ endpoint = {"gemini": "Gemini", "groq": "Grok", "cloudflare": "Cloudflare"}.get(endpoint.lower(), endpoint)
301
+ ep = endpoint if isinstance(endpoint, EndpointConfig) else get_endpoint(endpoint)
302
+ if ep is not None:
303
+ if getattr(ep, "builtin", False):
304
+ if ep.name == "Cloudflare":
305
+ llm = _get_cloudflare_chat(**kwargs)
306
+ if llm is not None:
307
+ return llm
308
+ raise ValueError("Cloudflare selected but CLOUDFLARE_ACCOUNT_ID or CLOUDFLARE_API_TOKEN is not set.")
309
+ # Built-in providers use their native constructors so the
310
+ # behaviour is identical to the default (no-endpoint) path.
311
+ if ep.name == "Gemini":
312
+ llm = _get_gemini_chat(**kwargs)
313
+ if llm is not None:
314
+ logger.info(
315
+ "Using built-in Gemini endpoint (model=%s)",
316
+ kwargs.get("model", GEMINI_MODEL),
317
+ )
318
+ return llm
319
+ raise ValueError(
320
+ "Gemini selected but GEMINI_API_KEY is not set."
321
+ )
322
+ if ep.name == "Grok":
323
+ llm = _get_groq_chat(**kwargs)
324
+ if llm is not None:
325
+ logger.info(
326
+ "Using built-in Grok endpoint (model=%s)",
327
+ kwargs.get("model", GROQ_MODEL),
328
+ )
329
+ return llm
330
+ raise ValueError(
331
+ "Grok selected but GROQ_API_KEY is not set."
332
+ )
333
+ try:
334
+ llm = create_endpoint_llm(ep, **kwargs)
335
+ logger.info("Using custom endpoint %s (%s/%s)", ep.name, ep.provider, ep.model)
336
+ return llm
337
+ except ValueError:
338
+ raise
339
+ else:
340
+ raise ValueError(
341
+ f"Custom endpoint '{endpoint}' not found. "
342
+ "Configure it via OCR_ENDPOINT_* environment variables "
343
+ "or add it in the UI."
344
+ )
345
+
346
+ llm = _get_gemini_chat(**kwargs)
347
+ if llm is not None:
348
+ logger.debug("Using Gemini (model=%s)", kwargs.get("model", GEMINI_MODEL))
349
+ return llm
350
+
351
+ llm = _get_groq_chat(**kwargs)
352
+ if llm is not None:
353
+ logger.debug("Falling back to Groq (model=%s)", kwargs.get("model", GROQ_MODEL))
354
+ return llm
355
+
356
+ llm = _get_cloudflare_chat(**kwargs)
357
+ if llm is not None:
358
+ logger.debug("Falling back to Cloudflare (model=%s)", kwargs.get("model", CLOUDFLARE_MODEL))
359
+ return llm
360
+
361
+ raise ValueError(
362
+ "No LLM available. Set GEMINI_API_KEY, GROQ_API_KEY, or both "
363
+ "CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_API_TOKEN."
364
+ )
eval_data/ragas_eval.py CHANGED
@@ -1,690 +1,690 @@
1
- #!/usr/bin/env python3
2
- """RAGAS-based evaluation of retrieval quality for OpenCodeReview.
3
-
4
- Computes **context_precision** and **context_recall** metrics from the
5
- RAGAS framework (https://docs.ragas.io/) on the retrieved context chunks
6
- produced by the ``retrieval_node``.
7
-
8
- These metrics answer:
9
- - **Context Precision**: Are the most relevant code chunks ranked first?
10
- - **Context Recall**: Does the retrieved set contain all the information
11
- needed for the reviewers to produce accurate findings?
12
-
13
- Usage
14
- -----
15
- from eval_data.ragas_eval import compute_ragas_retrieval_scores
16
-
17
- score = compute_ragas_retrieval_scores(
18
- query="diff of PR ...",
19
- retrieved_contexts=["chunk1 text", "chunk2 text", ...],
20
- ground_truth="Human review comment text ...",
21
- )
22
- # score == {"context_precision": 0.85, "context_recall": 0.72}
23
-
24
- Lazy imports minimise overhead when RAGAS is not installed.
25
- """
26
-
27
- from __future__ import annotations
28
-
29
- from contextvars import ContextVar
30
- import logging
31
- import os
32
- import threading
33
- import time
34
- import sys
35
- from pathlib import Path
36
- from typing import Any, Optional
37
-
38
- # Keep direct execution via ``python eval_data/ragas_eval.py`` working after
39
- # backend modules were moved into the backend package.
40
- _PROJECT_ROOT = Path(__file__).resolve().parent.parent
41
- if str(_PROJECT_ROOT) not in sys.path:
42
- sys.path.insert(0, str(_PROJECT_ROOT))
43
-
44
- logger = logging.getLogger(__name__)
45
-
46
- # ─── Lazy RAGAS imports with graceful fallback ──────────────────────────────
47
-
48
- _RAGAS_AVAILABLE: bool | None = None
49
-
50
-
51
- def _check_ragas() -> bool:
52
- """Return True if RAGAS is available.
53
-
54
- Note: ``litellm`` is NOT required because RAGAS scoring uses the
55
- project's own LLM factory (Gemini or Groq via LangChain), not
56
- litellm internally.
57
- """
58
- global _RAGAS_AVAILABLE
59
- if _RAGAS_AVAILABLE is not None:
60
- return _RAGAS_AVAILABLE
61
- try:
62
- import ragas # noqa: F401
63
- _RAGAS_AVAILABLE = True
64
- except ImportError:
65
- logger.warning(
66
- "ragas not installed. Install with: pip install ragas"
67
- )
68
- _RAGAS_AVAILABLE = False
69
- return _RAGAS_AVAILABLE
70
-
71
-
72
- # Seconds to sleep before every RAGAS LLM call. RAGAS scoring fires a
73
- # burst of ~20-30 model calls per review (context-precision judgments,
74
- # faithfulness verification, answer relevancy, MMR relevance checks).
75
- # Spacing them keeps the burst under Groq/Gemini free-tier per-minute rate
76
- # limits so scoring completes instead of tripping 429s — which previously
77
- # caused long retry backoffs and 0.0000 scores. Override with the
78
- # OCR_RAGAS_INTERVAL env var (float seconds, 0 disables).
79
- _RAGAS_INTERVAL = float(os.environ.get("OCR_RAGAS_INTERVAL", "0.5") or 0.5)
80
- _ragas_throttle_lock = threading.Lock()
81
- _metric_deadline = ContextVar("ragas_metric_deadline", default=None)
82
-
83
-
84
- class _ThrottledChatModel:
85
- """Wrap a LangChain chat model so every underlying API call RAGAS makes
86
- is spaced by a fixed interval.
87
-
88
- RAGAS's ``LangchainLLMWrapper`` (deprecated shim in 0.4.x, forwards to
89
- the langchain model) and the custom MMR path call the model through
90
- different entry points (sync/async, single/batched). Intercepting
91
- ``invoke`` / ``generate`` / ``ainvoke`` / ``agenerate`` here guarantees
92
- every request is throttled regardless of ragas version.
93
- """
94
-
95
- def __init__(self, model, interval: float | None = None):
96
- self._model = model
97
- self._interval = _RAGAS_INTERVAL if interval is None else interval
98
- self._quota_exhausted = False
99
-
100
- def _call(self, method, *args, **kwargs):
101
- try:
102
- return method(*args, **kwargs)
103
- except Exception as exc:
104
- if getattr(exc, "status_code", None) in {401, 403, 429} or any(value in str(exc).lower() for value in ("rate_limit_exceeded", "insufficient_quota")):
105
- self._quota_exhausted = True
106
- raise
107
-
108
- async def _acall(self, method, *args, **kwargs):
109
- try:
110
- return await method(*args, **kwargs)
111
- except Exception as exc:
112
- if getattr(exc, "status_code", None) in {401, 403, 429} or any(value in str(exc).lower() for value in ("rate_limit_exceeded", "insufficient_quota")):
113
- self._quota_exhausted = True
114
- raise
115
-
116
- def _wait(self) -> None:
117
- deadline = _metric_deadline.get()
118
- if deadline is not None and time.monotonic() >= deadline:
119
- raise TimeoutError("Metric deadline exceeded; no further judge calls")
120
- if self._quota_exhausted:
121
- raise RuntimeError("Evaluation stopped: provider authentication or quota limit; no further calls will be made for this evaluation.")
122
- if self._interval > 0:
123
- with _ragas_throttle_lock:
124
- time.sleep(self._interval)
125
-
126
- # ── Sync entry points ───────────────────────────────────────────────
127
- def invoke(self, *args, **kwargs):
128
- self._wait()
129
- return self._call(self._model.invoke, *args, **kwargs)
130
-
131
- def generate(self, messages, *args, **kwargs):
132
- # Serialize LangChain batch calls into individual throttled
133
- # requests so every underlying API call is spaced by the interval.
134
- if (
135
- isinstance(messages, list)
136
- and messages
137
- and isinstance(messages[0], list)
138
- ):
139
- from langchain_core.outputs import Generation, LLMResult
140
-
141
- generations = []
142
- for msgs in messages:
143
- self._wait()
144
- # invoke() does not accept callbacks/run_manager/config that
145
- # ragas may forward to generate() — drop them here.
146
- resp = self._call(self._model.invoke, msgs)
147
- text = resp.content if hasattr(resp, "content") else str(resp)
148
- generations.append([Generation(text=text, message=resp)])
149
- return LLMResult(generations=generations, llm_output=None)
150
- self._wait()
151
- return self._call(self._model.generate, messages, *args, **kwargs)
152
-
153
- # ── Async entry points ──────────────────────────────────────────────
154
- async def ainvoke(self, *args, **kwargs):
155
- self._wait()
156
- return await self._acall(self._model.ainvoke, *args, **kwargs)
157
-
158
- async def agenerate(self, messages, *args, **kwargs):
159
- if (
160
- isinstance(messages, list)
161
- and messages
162
- and isinstance(messages[0], list)
163
- ):
164
- from langchain_core.outputs import Generation, LLMResult
165
-
166
- generations = []
167
- for msgs in messages:
168
- self._wait()
169
- # Same kwargs caveat as generate(): ainvoke has no callbacks.
170
- resp = await self._acall(self._model.ainvoke, msgs)
171
- text = resp.content if hasattr(resp, "content") else str(resp)
172
- generations.append([Generation(text=text, message=resp)])
173
- return LLMResult(generations=generations, llm_output=None)
174
- self._wait()
175
- return await self._acall(self._model.agenerate, messages, *args, **kwargs)
176
-
177
- # ── Everything else passes through ──────────────────────────────────
178
- def __getattr__(self, name: str):
179
- return getattr(self._model, name)
180
-
181
-
182
- def _wrap_evaluator(llm, timeout=12):
183
- from ragas.llms import LangchainLLMWrapper
184
- from ragas.run_config import RunConfig
185
- return LangchainLLMWrapper(_ThrottledChatModel(llm), run_config=RunConfig(timeout=max(1, int(timeout)), max_retries=0, max_wait=0, max_workers=1))
186
-
187
-
188
- def _get_evaluator_llm(endpoint: Optional[str] = None, *, timeout=12):
189
- """Return a RAGAS-compatible LLM, reusing the project's LLM factory.
190
-
191
- Priority:
192
- 1. **Custom endpoint** — when *endpoint* names a configured
193
- ``OCR_ENDPOINT_*`` config, it is used (any provider the user added).
194
- 2. **Groq** (``llama-3.3-70b-versatile``) via ``GROQ_API_KEY``
195
- 3. **Google Gemini** (``gemini-3.1-flash-lite``) via ``GEMINI_API_KEY``
196
-
197
- Groq is preferred over Gemini because scoring fires many LLM calls per
198
- review and the Gemini free tier (15 req/min) is already shared with the
199
- main review pipeline — using Groq's separate quota pool avoids the 429
200
- rate-limit failures that used to zero out the metrics.
201
-
202
- RAGAS v0.3+ uses ``LangchainLLMWrapper`` to wrap LangChain models.
203
- """
204
- from ragas.llms import LangchainLLMWrapper
205
-
206
- try:
207
- if endpoint:
208
- from backend.integrations.llm_factory import create_llm
209
- from backend.integrations.endpoints import EndpointConfig, get_endpoint
210
- configured = endpoint if isinstance(endpoint, EndpointConfig) else get_endpoint(endpoint)
211
- request_timeout = timeout
212
- if configured and not getattr(configured, "builtin", False) and configured.provider not in {"google", "anthropic"}:
213
- import httpx
214
- # LangChain caches HTTP clients for hashable timeout values.
215
- # An unhashable Timeout forces a private pool for this loop.
216
- request_timeout = httpx.Timeout(timeout)
217
- llm = create_llm(endpoint=endpoint, temperature=0, timeout=request_timeout, max_retries=0)
218
- logger.info("RAGAS evaluator: using selected custom endpoint")
219
- return _wrap_evaluator(llm, timeout)
220
-
221
- from backend.integrations.llm_factory import _get_cloudflare_chat, _get_groq_chat, _get_gemini_chat
222
-
223
- llm = _get_cloudflare_chat(temperature=0, max_retries=0, timeout=timeout)
224
- if llm is not None:
225
- logger.info("RAGAS evaluator: using Cloudflare Workers AI")
226
- return _wrap_evaluator(llm, timeout)
227
-
228
- # Keep evaluation bounded: RAGAS runs several provider calls and
229
- # retrying each one can otherwise hold a review open for minutes.
230
- configured_model = os.getenv("RAGAS_MODEL", "").strip()
231
- if configured_model.startswith("groq/"):
232
- configured_model = configured_model.split("/", 1)[1]
233
- groq_kwargs = {"temperature": 0, "max_retries": 0, "timeout": timeout}
234
- if configured_model:
235
- groq_kwargs["model"] = configured_model
236
- llm = _get_groq_chat(**groq_kwargs)
237
- if llm is None:
238
- logger.info(
239
- "RAGAS evaluator: GROQ_API_KEY not set — falling back to Gemini"
240
- )
241
- llm = _get_gemini_chat(temperature=0, max_retries=0, timeout=timeout)
242
- if llm is None:
243
- raise ValueError(
244
- "No LLM available for RAGAS scoring. "
245
- "Set GROQ_API_KEY (preferred) or GEMINI_API_KEY."
246
- )
247
- logger.info(
248
- "RAGAS evaluator: using %s (throttled %ss)",
249
- type(llm).__name__,
250
- _RAGAS_INTERVAL,
251
- )
252
- return _wrap_evaluator(llm, timeout)
253
- except ValueError as exc:
254
- logger.warning("RAGAS evaluator: %s", exc)
255
- raise RuntimeError(
256
- "No LLM available for RAGAS scoring. "
257
- "Set GROQ_API_KEY (preferred) or GEMINI_API_KEY."
258
- ) from exc
259
-
260
-
261
- # ─── Score computation ─────────────────────────────────────────────────────
262
-
263
-
264
- def _score_one_metric(name, sample, llm, timeout):
265
- from ragas import metrics
266
- from ragas.run_config import RunConfig
267
- classes = {"context_precision": "LLMContextPrecisionWithoutReference", "faithfulness": "Faithfulness", "context_recall": "ContextRecall"}
268
- scorer = getattr(metrics, classes[name])(llm=llm)
269
- scorer.init(RunConfig(timeout=timeout, max_retries=1, max_wait=0, max_workers=1))
270
- return float(scorer.single_turn_score(sample))
271
-
272
-
273
- def _safe_metric_error(exc):
274
- """Classify failures without exposing provider responses or credentials."""
275
- chain = []
276
- current = exc
277
- while current is not None and len(chain) < 5:
278
- chain.append(type(current).__name__.lower())
279
- current = current.__cause__ or current.__context__
280
- kinds = " ".join(chain)
281
- if "timeout" in kinds:
282
- return "timed_out", "Evaluator provider timed out. Retry or select a faster model."
283
- if "connection" in kinds or "connecterror" in kinds:
284
- return "failed", "Evaluator provider connection failed. Retry; check provider availability if it persists."
285
- if "ratelimit" in kinds:
286
- return "failed", "Evaluator provider rate limit reached. Wait or select another saved provider."
287
- if "authentication" in kinds or "permission" in kinds:
288
- return "failed", "Evaluator provider rejected access. Check the saved provider credentials and permissions."
289
- return "failed", type(exc).__name__
290
-
291
-
292
- def ragas_time_limits(endpoint=None):
293
- """Account for paced, remote Cloudflare inference in both deadlines."""
294
- total = max(1.0, float(os.getenv("OCR_RAGAS_TIMEOUT_SECONDS", "90")))
295
- per_metric = max(.05, float(os.getenv("OCR_RAGAS_METRIC_TIMEOUT_SECONDS", "30")))
296
- name = endpoint if isinstance(endpoint, str) else getattr(endpoint, "name", "")
297
- uses_cloudflare = str(name).lower() == "cloudflare" or (
298
- not endpoint and bool(os.getenv("CLOUDFLARE_API_TOKEN") and os.getenv("CLOUDFLARE_ACCOUNT_ID"))
299
- )
300
- if uses_cloudflare:
301
- total = max(total, float(os.getenv("OCR_CLOUDFLARE_RAGAS_TIMEOUT_SECONDS", "210")))
302
- per_metric = max(per_metric, float(os.getenv("OCR_CLOUDFLARE_RAGAS_METRIC_TIMEOUT_SECONDS", "150")))
303
- return total, per_metric
304
-
305
-
306
- def compute_ragas_report(query, retrieved_contexts, ground_truth=None, answer=None, endpoint=None, *, metric_timeout=None, progress_callback=None):
307
- """Run independent bounded RAGAS metrics, preserving successes and real failures.
308
-
309
- No local embedding model is loaded. Lexical overlap is never substituted for
310
- RAGAS. Input caps reduce judge latency and are disclosed in the report.
311
- """
312
- import math
313
- import queue
314
- from contextvars import copy_context
315
- started = time.monotonic()
316
- total_budget, default_metric_timeout = ragas_time_limits(endpoint)
317
- per_metric = max(.05, float(metric_timeout if metric_timeout is not None else default_metric_timeout))
318
- names = ["context_precision", "faithfulness"]
319
- if ground_truth:
320
- names.append("context_recall")
321
- report = {"scores": {}, "metrics": {}, "evaluation": {"engine": "RAGAS", "local_models": False, "metric_timeout_seconds": per_metric, "input_truncated": len(query) > 6000 or len(answer or "") > 4000 or len(retrieved_contexts) > 2 or any(len(c) > 4000 for c in retrieved_contexts)}}
322
- def finish(name, status, value=None, error=None, duration=0):
323
- report["metrics"][name] = {"status": status, "value": value, "error": error, "duration_seconds": round(duration, 3)}
324
- if value is not None:
325
- report["scores"][name] = value
326
- if progress_callback:
327
- progress_callback(report)
328
- for name, reason in [("answer_relevancy", "Requires embeddings; local models are disabled"), ("mmr", "Extra judge calls disabled in hosted evaluation")]:
329
- finish(name, "skipped", error=reason)
330
- if not ground_truth:
331
- finish("context_recall", "skipped", error="No reference answer provided")
332
- if not answer or not retrieved_contexts:
333
- for name in names:
334
- finish(name, "skipped", error="A complete answer and context are required")
335
- return report
336
- try:
337
- if not _check_ragas():
338
- raise RuntimeError("RAGAS is not installed")
339
- from ragas.dataset_schema import SingleTurnSample
340
- sample = SingleTurnSample(user_input=query[:6000], response=answer[:4000], retrieved_contexts=[c[:4000] for c in retrieved_contexts[:2]], reference=ground_truth[:4000] if ground_truth else None)
341
- except Exception as exc:
342
- for name in names:
343
- finish(name, "failed", error=type(exc).__name__)
344
- return report
345
- pending = {}
346
- for name in names:
347
- remaining = total_budget - (time.monotonic() - started) - 1
348
- if remaining <= 0:
349
- finish(name, "timed_out", error="Evaluation setup exhausted deadline")
350
- continue
351
- deadline = time.monotonic() + min(per_metric, remaining)
352
- output = queue.Queue(maxsize=1)
353
- def run(metric=name, target=output, limit=min(per_metric, remaining)):
354
- metric_started = time.monotonic()
355
- token = _metric_deadline.set(metric_started + limit)
356
- try:
357
- # Each metric runs its own asyncio loop. Sharing an async HTTP
358
- # client across these threads can bind its pool to another loop.
359
- # Keep the provider request timeout and RAGAS RunConfig aligned
360
- # with this metric's actual deadline.
361
- llm = _get_evaluator_llm(endpoint=endpoint, timeout=limit)
362
- value = _score_one_metric(metric, sample, llm, limit)
363
- if not math.isfinite(value) or not 0 <= value <= 1:
364
- raise ValueError("Invalid metric value")
365
- target.put(("completed", round(value, 4), None, time.monotonic() - metric_started))
366
- except Exception as exc:
367
- status, error = _safe_metric_error(exc)
368
- logger.warning("RAGAS metric %s failed (%s)", metric, type(exc).__name__)
369
- target.put((status, None, error, time.monotonic() - metric_started))
370
- finally:
371
- _metric_deadline.reset(token)
372
- threading.Thread(target=copy_context().run, args=(run,), daemon=True).start()
373
- pending[name] = (output, deadline)
374
- while pending:
375
- for name, (output, deadline) in list(pending.items()):
376
- try:
377
- status, value, error, duration = output.get_nowait()
378
- except queue.Empty:
379
- if time.monotonic() < deadline:
380
- continue
381
- status, value, error, duration = "timed_out", None, "Metric deadline exceeded", per_metric
382
- finish(name, status, value, error, duration)
383
- del pending[name]
384
- if pending:
385
- time.sleep(.01)
386
- report["evaluation"]["duration_seconds"] = round(time.monotonic() - started, 3)
387
- return report
388
-
389
-
390
- def compute_ragas_retrieval_scores(query, retrieved_contexts, ground_truth=None, answer=None, endpoint=None):
391
- """Compatibility mapping. Failed/skipped metrics remain None, never invented scores."""
392
- report = compute_ragas_report(query, retrieved_contexts, ground_truth, answer, endpoint)
393
- return {name: metric["value"] for name, metric in report["metrics"].items()}
394
-
395
-
396
- def _create_ragas_embeddings():
397
- """Return a lightweight embedding object compatible with RAGAS metrics.
398
-
399
- Wraps the ChromaDB ONNX MiniLM embedding function so that metrics like
400
- ``ResponseRelevancy`` can compute cosine similarity between embeddings.
401
- The underlying ONNX model is cached globally and loads in <1 s.
402
- """
403
- if os.getenv("OPENCODEREVIEW_ALLOW_LOCAL_EMBEDDINGS", "false").lower() not in {"1", "true", "yes"}:
404
- logger.info("Local RAGAS embeddings disabled; skipping answer relevancy")
405
- return None
406
- try:
407
- from chromadb.utils import embedding_functions
408
-
409
- if hasattr(embedding_functions, "ONNXMiniLM_L6_V2"):
410
- ef = embedding_functions.ONNXMiniLM_L6_V2()
411
- else:
412
- ef = embedding_functions.SentenceTransformerEmbeddingFunction(
413
- model_name="all-MiniLM-L6-v2"
414
- )
415
-
416
- class _RagasEmbeddings:
417
- def __init__(self, ef):
418
- self._ef = ef
419
-
420
- def embed_query(self, text: str) -> list[float]:
421
- result = self._ef([text])[0]
422
- return list(result) if not isinstance(result, list) else result
423
-
424
- def embed_documents(self, texts: list[str]) -> list[list[float]]:
425
- results = self._ef(texts)
426
- return [list(r) if not isinstance(r, list) else r for r in results]
427
-
428
- return _RagasEmbeddings(ef)
429
- except Exception as exc:
430
- logger.warning("Cannot create RAGAS embeddings: %s", exc)
431
- return None
432
-
433
-
434
- def _compute_mmr(
435
- query: str,
436
- retrieved_contexts: list[str],
437
- llm: Any,
438
- ) -> float:
439
- """Compute Mean Reciprocal Rank — how early the first relevant chunk appears.
440
-
441
- Uses the LLM to judge each chunk's relevance to the query in order.
442
- The first chunk judged relevant determines the reciprocal rank:
443
- ``1 / rank_of_first_relevant``. Returns 0.0 if none are relevant.
444
-
445
- Parameters
446
- ----------
447
- query : str
448
- The search query (PR diff).
449
- retrieved_contexts : list[str]
450
- Ranked list of retrieved code chunks.
451
- llm : LangchainLLMWrapper
452
- RAGAS-wrapped LLM for relevance judgments.
453
-
454
- Returns
455
- -------
456
- float
457
- MMR score in [0, 1]; 0.0 when chunks were judged but none were
458
- relevant.
459
-
460
- Raises
461
- ------
462
- RuntimeError
463
- If every relevance judgment failed (e.g. LLM rate-limited) —
464
- callers treat this as a failed metric rather than a fake 0.0.
465
- """
466
- if not retrieved_contexts:
467
- return 0.0
468
-
469
- # Score up to the first 5 chunks for relevance using the LLM.
470
- # Top-5 MMR is standard — rank 5 yields 1/5 = 0.20, and
471
- # anything beyond rank 5 barely changes the score anyway.
472
- MAX_MMR_RANK = 2
473
- top_chunks = retrieved_contexts[:MAX_MMR_RANK]
474
-
475
- judged = 0
476
- for rank, chunk in enumerate(top_chunks, start=1):
477
- try:
478
- prompt = (
479
- f"Is the following code/document chunk relevant to the question?\n\n"
480
- f"Question: {query[:2_000]}\n\n"
481
- f"Chunk: {chunk[:2_000]}\n\n"
482
- f"Answer with exactly one word: YES or NO"
483
- )
484
- # Use the wrapped LangChain model for fast synchronous invoke.
485
- # LangchainLLMWrapper stores the model as .langchain_llm in ragas
486
- # 0.4.x and as .llm in 0.3.x — accept both.
487
- langchain_model = getattr(llm, "langchain_llm", None) or getattr(llm, "llm", None)
488
- # Space the relevance judgments too — this unwrapped path bypasses
489
- # the model wrapper on some ragas versions, so sleep explicitly
490
- # (unless the wrapper is already in the path, to avoid double-sleep).
491
- if not isinstance(langchain_model, _ThrottledChatModel):
492
- time.sleep(_RAGAS_INTERVAL)
493
- raw = langchain_model.invoke(prompt)
494
- response_text = raw.content.strip().upper() if hasattr(raw, "content") else str(raw).strip().upper()
495
- if response_text.startswith("Y"):
496
- return 1.0 / rank
497
- judged += 1 # judge responded — chunk deemed not relevant
498
- except Exception:
499
- continue
500
-
501
- if judged == 0:
502
- # Every relevance judgment failed (e.g. LLM rate-limited) — surface
503
- # this as a failed metric instead of a misleading 0.0.
504
- raise RuntimeError("all MMR relevance judgments failed")
505
-
506
- return 0.0
507
-
508
-
509
- def log_ragas_scores_to_langfuse(
510
- scores: dict[str, float | None],
511
- repo: str = "",
512
- pr_number: int = 0,
513
- handler: Any = None,
514
- ) -> None:
515
- """Log RAGAS metrics as Langfuse scores (linked to the review trace).
516
-
517
- Parameters
518
- ----------
519
- scores : dict
520
- Output of :func:`compute_ragas_retrieval_scores`.
521
- repo : str
522
- GitHub repository name (e.g. ``\"psf/requests\"``).
523
- pr_number : int
524
- Pull request number.
525
- handler : Langfuse CallbackHandler or None
526
- Handler from the current review run, used to link scores to the trace.
527
- """
528
- try:
529
- from backend.observability import log_langfuse_score
530
- except ImportError:
531
- logger.debug("observability module not available — skipping Langfuse")
532
- return
533
-
534
- for metric_name, value in scores.items():
535
- if value is None:
536
- continue
537
- log_langfuse_score(
538
- name=f"ragas_{metric_name}",
539
- value=value,
540
- comment=f"{repo}#{pr_number} — {metric_name}",
541
- handler=handler,
542
- )
543
-
544
-
545
- # ─── Standalone CLI ─────────────────────────────────────────────────────────
546
-
547
-
548
- def main() -> None:
549
- """CLI entry point: compute RAGAS scores from a JSONL dataset.
550
-
551
- Usage::
552
-
553
- python eval_data/ragas_eval.py --data eval_data/prs.jsonl
554
- """
555
- import argparse
556
- import json
557
-
558
- parser = argparse.ArgumentParser(
559
- description="Compute RAGAS retrieval quality scores on evaluation data",
560
- )
561
- parser.add_argument(
562
- "--data", default=None,
563
- help="Path to JSONL dataset (same format as evaluate.py)",
564
- )
565
- parser.add_argument(
566
- "--output", default=None,
567
- help="Path to write per-PR RAGAS scores (JSON)",
568
- )
569
- parser.add_argument(
570
- "--max-prs", type=int, default=None,
571
- help="Max PRs to process",
572
- )
573
- parser.add_argument(
574
- "--log-to-observability", action="store_true",
575
- help="Log RAGAS scores to Langfuse",
576
- )
577
- args = parser.parse_args()
578
-
579
- logging.basicConfig(
580
- level=logging.INFO,
581
- format="%(asctime)s [%(levelname)s] %(name)s — %(message)s",
582
- )
583
-
584
- if not args.data:
585
- # If no data file specified, try default location
586
- default_path = os.path.join(
587
- os.path.dirname(__file__), "prs.jsonl"
588
- )
589
- if os.path.exists(default_path):
590
- args.data = default_path
591
- else:
592
- logger.error(
593
- "No --data provided and default not found at %s. "
594
- "Run eval_data/fetcher.py first.",
595
- default_path,
596
- )
597
- return
598
-
599
- with open(args.data, "r", encoding="utf-8") as f:
600
- entries = [json.loads(line) for line in f if line.strip()]
601
-
602
- if args.max_prs:
603
- entries = entries[: args.max_prs]
604
-
605
- all_scores: list[dict] = []
606
- for entry in entries:
607
- repo = entry.get("repo", "?")
608
- pr = entry.get("pr_number", 0)
609
- diff = entry.get("diff", "")
610
- ground_truth_list = entry.get("ground_truth", [])
611
-
612
- # Use the diff as the query, and first few human comments
613
- # as a proxy for "what the retrieval should have found"
614
- query = diff[:8_000] if diff else entry.get("title", "")
615
- gt_text = (
616
- " ".join(
617
- g.get("comment", "")
618
- for g in ground_truth_list[:5]
619
- )
620
- if ground_truth_list
621
- else None
622
- )
623
-
624
- # Retrieved contexts come from the graph run, but for the CLI
625
- # we don't re-run the graph — we just skip if no retrieval data
626
- # is available in the entry.
627
- stored_contexts = entry.get("retrieved_contexts", [])
628
- if not stored_contexts:
629
- logger.info(
630
- "[%s#%d] No stored retrieval contexts — skipping RAGAS",
631
- repo, pr,
632
- )
633
- continue
634
-
635
- logger.info("[%s#%d] Computing RAGAS scores …", repo, pr)
636
- try:
637
- scores = compute_ragas_retrieval_scores(
638
- query=query,
639
- retrieved_contexts=stored_contexts,
640
- ground_truth=gt_text,
641
- )
642
- except RuntimeError as exc:
643
- logger.warning("[%s#%d] %s", repo, pr, exc)
644
- break
645
-
646
- scores.update({"repo": repo, "pr_number": pr, "id": entry.get("id")})
647
- all_scores.append(scores)
648
-
649
- if args.log_to_observability:
650
- log_ragas_scores_to_langfuse(scores, repo=repo, pr_number=pr)
651
-
652
- print(
653
- f" {repo}#{pr}: "
654
- + " | ".join(
655
- f"{k}={v:.3f}" for k, v in scores.items()
656
- if k not in ("repo", "pr_number", "id") and v is not None
657
- )
658
- )
659
-
660
- # Print aggregate
661
- if all_scores:
662
- print()
663
- print("=" * 60)
664
- print(" Aggregate RAGAS scores")
665
- print("=" * 60)
666
- metrics = [
667
- k for k in all_scores[0].keys()
668
- if k not in ("repo", "pr_number", "id")
669
- ]
670
- for metric in metrics:
671
- values = [
672
- s.get(metric) for s in all_scores
673
- if s.get(metric) is not None
674
- ]
675
- if not values:
676
- print(f" {metric:30s}: n/a (no successful scores)")
677
- continue
678
- avg = sum(values) / len(values)
679
- print(f" {metric:30s}: {avg:.4f} (over {len(values)} PRs)")
680
- print()
681
-
682
- # Save output
683
- if args.output and all_scores:
684
- with open(args.output, "w", encoding="utf-8") as f:
685
- json.dump(all_scores, f, indent=2)
686
- logger.info("Saved RAGAS scores to %s", args.output)
687
-
688
-
689
- if __name__ == "__main__":
690
- main()
 
1
+ #!/usr/bin/env python3
2
+ """RAGAS-based evaluation of retrieval quality for OpenCodeReview.
3
+
4
+ Computes **context_precision** and **context_recall** metrics from the
5
+ RAGAS framework (https://docs.ragas.io/) on the retrieved context chunks
6
+ produced by the ``retrieval_node``.
7
+
8
+ These metrics answer:
9
+ - **Context Precision**: Are the most relevant code chunks ranked first?
10
+ - **Context Recall**: Does the retrieved set contain all the information
11
+ needed for the reviewers to produce accurate findings?
12
+
13
+ Usage
14
+ -----
15
+ from eval_data.ragas_eval import compute_ragas_retrieval_scores
16
+
17
+ score = compute_ragas_retrieval_scores(
18
+ query="diff of PR ...",
19
+ retrieved_contexts=["chunk1 text", "chunk2 text", ...],
20
+ ground_truth="Human review comment text ...",
21
+ )
22
+ # score == {"context_precision": 0.85, "context_recall": 0.72}
23
+
24
+ Lazy imports minimise overhead when RAGAS is not installed.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ from contextvars import ContextVar
30
+ import logging
31
+ import os
32
+ import threading
33
+ import time
34
+ import sys
35
+ from pathlib import Path
36
+ from typing import Any, Optional
37
+
38
+ # Keep direct execution via ``python eval_data/ragas_eval.py`` working after
39
+ # backend modules were moved into the backend package.
40
+ _PROJECT_ROOT = Path(__file__).resolve().parent.parent
41
+ if str(_PROJECT_ROOT) not in sys.path:
42
+ sys.path.insert(0, str(_PROJECT_ROOT))
43
+
44
+ logger = logging.getLogger(__name__)
45
+
46
+ # ─── Lazy RAGAS imports with graceful fallback ──────────────────────────────
47
+
48
+ _RAGAS_AVAILABLE: bool | None = None
49
+
50
+
51
+ def _check_ragas() -> bool:
52
+ """Return True if RAGAS is available.
53
+
54
+ Note: ``litellm`` is NOT required because RAGAS scoring uses the
55
+ project's own LLM factory (Gemini or Groq via LangChain), not
56
+ litellm internally.
57
+ """
58
+ global _RAGAS_AVAILABLE
59
+ if _RAGAS_AVAILABLE is not None:
60
+ return _RAGAS_AVAILABLE
61
+ try:
62
+ import ragas # noqa: F401
63
+ _RAGAS_AVAILABLE = True
64
+ except ImportError:
65
+ logger.warning(
66
+ "ragas not installed. Install with: pip install ragas"
67
+ )
68
+ _RAGAS_AVAILABLE = False
69
+ return _RAGAS_AVAILABLE
70
+
71
+
72
+ # Seconds to sleep before every RAGAS LLM call. RAGAS scoring fires a
73
+ # burst of ~20-30 model calls per review (context-precision judgments,
74
+ # faithfulness verification, answer relevancy, MMR relevance checks).
75
+ # Spacing them keeps the burst under Groq/Gemini free-tier per-minute rate
76
+ # limits so scoring completes instead of tripping 429s — which previously
77
+ # caused long retry backoffs and 0.0000 scores. Override with the
78
+ # OCR_RAGAS_INTERVAL env var (float seconds, 0 disables).
79
+ _RAGAS_INTERVAL = float(os.environ.get("OCR_RAGAS_INTERVAL", "0.5") or 0.5)
80
+ _ragas_throttle_lock = threading.Lock()
81
+ _metric_deadline = ContextVar("ragas_metric_deadline", default=None)
82
+
83
+
84
+ class _ThrottledChatModel:
85
+ """Wrap a LangChain chat model so every underlying API call RAGAS makes
86
+ is spaced by a fixed interval.
87
+
88
+ RAGAS's ``LangchainLLMWrapper`` (deprecated shim in 0.4.x, forwards to
89
+ the langchain model) and the custom MMR path call the model through
90
+ different entry points (sync/async, single/batched). Intercepting
91
+ ``invoke`` / ``generate`` / ``ainvoke`` / ``agenerate`` here guarantees
92
+ every request is throttled regardless of ragas version.
93
+ """
94
+
95
+ def __init__(self, model, interval: float | None = None):
96
+ self._model = model
97
+ self._interval = _RAGAS_INTERVAL if interval is None else interval
98
+ self._quota_exhausted = False
99
+
100
+ def _call(self, method, *args, **kwargs):
101
+ try:
102
+ return method(*args, **kwargs)
103
+ except Exception as exc:
104
+ if getattr(exc, "status_code", None) in {401, 403, 429} or any(value in str(exc).lower() for value in ("rate_limit_exceeded", "insufficient_quota")):
105
+ self._quota_exhausted = True
106
+ raise
107
+
108
+ async def _acall(self, method, *args, **kwargs):
109
+ try:
110
+ return await method(*args, **kwargs)
111
+ except Exception as exc:
112
+ if getattr(exc, "status_code", None) in {401, 403, 429} or any(value in str(exc).lower() for value in ("rate_limit_exceeded", "insufficient_quota")):
113
+ self._quota_exhausted = True
114
+ raise
115
+
116
+ def _wait(self) -> None:
117
+ deadline = _metric_deadline.get()
118
+ if deadline is not None and time.monotonic() >= deadline:
119
+ raise TimeoutError("Metric deadline exceeded; no further judge calls")
120
+ if self._quota_exhausted:
121
+ raise RuntimeError("Evaluation stopped: provider authentication or quota limit; no further calls will be made for this evaluation.")
122
+ if self._interval > 0:
123
+ with _ragas_throttle_lock:
124
+ time.sleep(self._interval)
125
+
126
+ # ── Sync entry points ───────────────────────────────────────────────
127
+ def invoke(self, *args, **kwargs):
128
+ self._wait()
129
+ return self._call(self._model.invoke, *args, **kwargs)
130
+
131
+ def generate(self, messages, *args, **kwargs):
132
+ # Serialize LangChain batch calls into individual throttled
133
+ # requests so every underlying API call is spaced by the interval.
134
+ if (
135
+ isinstance(messages, list)
136
+ and messages
137
+ and isinstance(messages[0], list)
138
+ ):
139
+ from langchain_core.outputs import Generation, LLMResult
140
+
141
+ generations = []
142
+ for msgs in messages:
143
+ self._wait()
144
+ # invoke() does not accept callbacks/run_manager/config that
145
+ # ragas may forward to generate() — drop them here.
146
+ resp = self._call(self._model.invoke, msgs)
147
+ text = resp.content if hasattr(resp, "content") else str(resp)
148
+ generations.append([Generation(text=text, message=resp)])
149
+ return LLMResult(generations=generations, llm_output=None)
150
+ self._wait()
151
+ return self._call(self._model.generate, messages, *args, **kwargs)
152
+
153
+ # ── Async entry points ──────────────────────────────────────────────
154
+ async def ainvoke(self, *args, **kwargs):
155
+ self._wait()
156
+ return await self._acall(self._model.ainvoke, *args, **kwargs)
157
+
158
+ async def agenerate(self, messages, *args, **kwargs):
159
+ if (
160
+ isinstance(messages, list)
161
+ and messages
162
+ and isinstance(messages[0], list)
163
+ ):
164
+ from langchain_core.outputs import Generation, LLMResult
165
+
166
+ generations = []
167
+ for msgs in messages:
168
+ self._wait()
169
+ # Same kwargs caveat as generate(): ainvoke has no callbacks.
170
+ resp = await self._acall(self._model.ainvoke, msgs)
171
+ text = resp.content if hasattr(resp, "content") else str(resp)
172
+ generations.append([Generation(text=text, message=resp)])
173
+ return LLMResult(generations=generations, llm_output=None)
174
+ self._wait()
175
+ return await self._acall(self._model.agenerate, messages, *args, **kwargs)
176
+
177
+ # ── Everything else passes through ──────────────────────────────────
178
+ def __getattr__(self, name: str):
179
+ return getattr(self._model, name)
180
+
181
+
182
+ def _wrap_evaluator(llm, timeout=12):
183
+ from ragas.llms import LangchainLLMWrapper
184
+ from ragas.run_config import RunConfig
185
+ return LangchainLLMWrapper(_ThrottledChatModel(llm), run_config=RunConfig(timeout=max(1, int(timeout)), max_retries=0, max_wait=0, max_workers=1))
186
+
187
+
188
+ def _get_evaluator_llm(endpoint: Optional[str] = None, *, timeout=12):
189
+ """Return a RAGAS-compatible LLM, reusing the project's LLM factory.
190
+
191
+ Priority:
192
+ 1. **Custom endpoint** — when *endpoint* names a configured
193
+ ``OCR_ENDPOINT_*`` config, it is used (any provider the user added).
194
+ 2. **Groq** (``llama-3.3-70b-versatile``) via ``GROQ_API_KEY``
195
+ 3. **Google Gemini** (``gemini-3.1-flash-lite``) via ``GEMINI_API_KEY``
196
+
197
+ Groq is preferred over Gemini because scoring fires many LLM calls per
198
+ review and the Gemini free tier (15 req/min) is already shared with the
199
+ main review pipeline — using Groq's separate quota pool avoids the 429
200
+ rate-limit failures that used to zero out the metrics.
201
+
202
+ RAGAS v0.3+ uses ``LangchainLLMWrapper`` to wrap LangChain models.
203
+ """
204
+ from ragas.llms import LangchainLLMWrapper
205
+
206
+ try:
207
+ if endpoint:
208
+ from backend.integrations.llm_factory import create_llm
209
+ from backend.integrations.endpoints import EndpointConfig, get_endpoint
210
+ configured = endpoint if isinstance(endpoint, EndpointConfig) else get_endpoint(endpoint)
211
+ request_timeout = timeout
212
+ if configured and not getattr(configured, "builtin", False) and configured.provider not in {"google", "anthropic"}:
213
+ import httpx
214
+ # LangChain caches HTTP clients for hashable timeout values.
215
+ # An unhashable Timeout forces a private pool for this loop.
216
+ request_timeout = httpx.Timeout(timeout)
217
+ llm = create_llm(endpoint=endpoint, temperature=0, timeout=request_timeout, max_retries=0)
218
+ logger.info("RAGAS evaluator: using selected custom endpoint")
219
+ return _wrap_evaluator(llm, timeout)
220
+
221
+ from backend.integrations.llm_factory import _get_cloudflare_chat, _get_groq_chat, _get_gemini_chat
222
+
223
+ llm = _get_cloudflare_chat(temperature=0, max_retries=0, timeout=timeout)
224
+ if llm is not None:
225
+ logger.info("RAGAS evaluator: using Cloudflare Workers AI")
226
+ return _wrap_evaluator(llm, timeout)
227
+
228
+ # Keep evaluation bounded: RAGAS runs several provider calls and
229
+ # retrying each one can otherwise hold a review open for minutes.
230
+ configured_model = os.getenv("RAGAS_MODEL", "").strip()
231
+ if configured_model.startswith("groq/"):
232
+ configured_model = configured_model.split("/", 1)[1]
233
+ groq_kwargs = {"temperature": 0, "max_retries": 0, "timeout": timeout}
234
+ if configured_model:
235
+ groq_kwargs["model"] = configured_model
236
+ llm = _get_groq_chat(**groq_kwargs)
237
+ if llm is None:
238
+ logger.info(
239
+ "RAGAS evaluator: GROQ_API_KEY not set — falling back to Gemini"
240
+ )
241
+ llm = _get_gemini_chat(temperature=0, max_retries=0, timeout=timeout)
242
+ if llm is None:
243
+ raise ValueError(
244
+ "No LLM available for RAGAS scoring. "
245
+ "Set GROQ_API_KEY (preferred) or GEMINI_API_KEY."
246
+ )
247
+ logger.info(
248
+ "RAGAS evaluator: using %s (throttled %ss)",
249
+ type(llm).__name__,
250
+ _RAGAS_INTERVAL,
251
+ )
252
+ return _wrap_evaluator(llm, timeout)
253
+ except ValueError as exc:
254
+ logger.warning("RAGAS evaluator: %s", exc)
255
+ raise RuntimeError(
256
+ "No LLM available for RAGAS scoring. "
257
+ "Set GROQ_API_KEY (preferred) or GEMINI_API_KEY."
258
+ ) from exc
259
+
260
+
261
+ # ─── Score computation ─────────────────────────────────────────────────────
262
+
263
+
264
+ def _score_one_metric(name, sample, llm, timeout):
265
+ from ragas import metrics
266
+ from ragas.run_config import RunConfig
267
+ classes = {"context_precision": "LLMContextPrecisionWithoutReference", "faithfulness": "Faithfulness", "context_recall": "ContextRecall"}
268
+ scorer = getattr(metrics, classes[name])(llm=llm)
269
+ scorer.init(RunConfig(timeout=timeout, max_retries=1, max_wait=0, max_workers=1))
270
+ return float(scorer.single_turn_score(sample))
271
+
272
+
273
+ def _safe_metric_error(exc):
274
+ """Classify failures without exposing provider responses or credentials."""
275
+ chain = []
276
+ current = exc
277
+ while current is not None and len(chain) < 5:
278
+ chain.append(type(current).__name__.lower())
279
+ current = current.__cause__ or current.__context__
280
+ kinds = " ".join(chain)
281
+ if "timeout" in kinds:
282
+ return "timed_out", "Evaluator provider timed out. Retry or select a faster model."
283
+ if "connection" in kinds or "connecterror" in kinds:
284
+ return "failed", "Evaluator provider connection failed. Retry; check provider availability if it persists."
285
+ if "ratelimit" in kinds:
286
+ return "failed", "Evaluator provider rate limit reached. Wait or select another saved provider."
287
+ if "authentication" in kinds or "permission" in kinds:
288
+ return "failed", "Evaluator provider rejected access. Check the saved provider credentials and permissions."
289
+ return "failed", type(exc).__name__
290
+
291
+
292
+ def ragas_time_limits(endpoint=None):
293
+ """Account for paced, remote Cloudflare inference in both deadlines."""
294
+ total = max(1.0, float(os.getenv("OCR_RAGAS_TIMEOUT_SECONDS", "90")))
295
+ per_metric = max(.05, float(os.getenv("OCR_RAGAS_METRIC_TIMEOUT_SECONDS", "30")))
296
+ name = endpoint if isinstance(endpoint, str) else getattr(endpoint, "name", "")
297
+ uses_cloudflare = str(name).lower() == "cloudflare" or (
298
+ not endpoint and bool(os.getenv("CLOUDFLARE_API_TOKEN") and os.getenv("CLOUDFLARE_ACCOUNT_ID"))
299
+ )
300
+ if uses_cloudflare:
301
+ total = max(total, float(os.getenv("OCR_CLOUDFLARE_RAGAS_TIMEOUT_SECONDS", "210")))
302
+ per_metric = max(per_metric, float(os.getenv("OCR_CLOUDFLARE_RAGAS_METRIC_TIMEOUT_SECONDS", "150")))
303
+ return total, per_metric
304
+
305
+
306
+ def compute_ragas_report(query, retrieved_contexts, ground_truth=None, answer=None, endpoint=None, *, metric_timeout=None, progress_callback=None):
307
+ """Run independent bounded RAGAS metrics, preserving successes and real failures.
308
+
309
+ No local embedding model is loaded. Lexical overlap is never substituted for
310
+ RAGAS. Input caps reduce judge latency and are disclosed in the report.
311
+ """
312
+ import math
313
+ import queue
314
+ from contextvars import copy_context
315
+ started = time.monotonic()
316
+ total_budget, default_metric_timeout = ragas_time_limits(endpoint)
317
+ per_metric = max(.05, float(metric_timeout if metric_timeout is not None else default_metric_timeout))
318
+ names = ["context_precision", "faithfulness"]
319
+ if ground_truth:
320
+ names.append("context_recall")
321
+ report = {"scores": {}, "metrics": {}, "evaluation": {"engine": "RAGAS", "local_models": False, "metric_timeout_seconds": per_metric, "input_truncated": len(query) > 6000 or len(answer or "") > 4000 or len(retrieved_contexts) > 2 or any(len(c) > 4000 for c in retrieved_contexts)}}
322
+ def finish(name, status, value=None, error=None, duration=0):
323
+ report["metrics"][name] = {"status": status, "value": value, "error": error, "duration_seconds": round(duration, 3)}
324
+ if value is not None:
325
+ report["scores"][name] = value
326
+ if progress_callback:
327
+ progress_callback(report)
328
+ for name, reason in [("answer_relevancy", "Requires embeddings; local models are disabled"), ("mmr", "Extra judge calls disabled in hosted evaluation")]:
329
+ finish(name, "skipped", error=reason)
330
+ if not ground_truth:
331
+ finish("context_recall", "skipped", error="No reference answer provided")
332
+ if not answer or not retrieved_contexts:
333
+ for name in names:
334
+ finish(name, "skipped", error="A complete answer and context are required")
335
+ return report
336
+ try:
337
+ if not _check_ragas():
338
+ raise RuntimeError("RAGAS is not installed")
339
+ from ragas.dataset_schema import SingleTurnSample
340
+ sample = SingleTurnSample(user_input=query[:6000], response=answer[:4000], retrieved_contexts=[c[:4000] for c in retrieved_contexts[:2]], reference=ground_truth[:4000] if ground_truth else None)
341
+ except Exception as exc:
342
+ for name in names:
343
+ finish(name, "failed", error=type(exc).__name__)
344
+ return report
345
+ pending = {}
346
+ for name in names:
347
+ remaining = total_budget - (time.monotonic() - started) - 1
348
+ if remaining <= 0:
349
+ finish(name, "timed_out", error="Evaluation setup exhausted deadline")
350
+ continue
351
+ deadline = time.monotonic() + min(per_metric, remaining)
352
+ output = queue.Queue(maxsize=1)
353
+ def run(metric=name, target=output, limit=min(per_metric, remaining)):
354
+ metric_started = time.monotonic()
355
+ token = _metric_deadline.set(metric_started + limit)
356
+ try:
357
+ # Each metric runs its own asyncio loop. Sharing an async HTTP
358
+ # client across these threads can bind its pool to another loop.
359
+ # Keep the provider request timeout and RAGAS RunConfig aligned
360
+ # with this metric's actual deadline.
361
+ llm = _get_evaluator_llm(endpoint=endpoint, timeout=limit)
362
+ value = _score_one_metric(metric, sample, llm, limit)
363
+ if not math.isfinite(value) or not 0 <= value <= 1:
364
+ raise ValueError("Invalid metric value")
365
+ target.put(("completed", round(value, 4), None, time.monotonic() - metric_started))
366
+ except Exception as exc:
367
+ status, error = _safe_metric_error(exc)
368
+ logger.warning("RAGAS metric %s failed (%s)", metric, type(exc).__name__)
369
+ target.put((status, None, error, time.monotonic() - metric_started))
370
+ finally:
371
+ _metric_deadline.reset(token)
372
+ threading.Thread(target=copy_context().run, args=(run,), daemon=True).start()
373
+ pending[name] = (output, deadline)
374
+ while pending:
375
+ for name, (output, deadline) in list(pending.items()):
376
+ try:
377
+ status, value, error, duration = output.get_nowait()
378
+ except queue.Empty:
379
+ if time.monotonic() < deadline:
380
+ continue
381
+ status, value, error, duration = "timed_out", None, "Metric deadline exceeded", per_metric
382
+ finish(name, status, value, error, duration)
383
+ del pending[name]
384
+ if pending:
385
+ time.sleep(.01)
386
+ report["evaluation"]["duration_seconds"] = round(time.monotonic() - started, 3)
387
+ return report
388
+
389
+
390
+ def compute_ragas_retrieval_scores(query, retrieved_contexts, ground_truth=None, answer=None, endpoint=None):
391
+ """Compatibility mapping. Failed/skipped metrics remain None, never invented scores."""
392
+ report = compute_ragas_report(query, retrieved_contexts, ground_truth, answer, endpoint)
393
+ return {name: metric["value"] for name, metric in report["metrics"].items()}
394
+
395
+
396
+ def _create_ragas_embeddings():
397
+ """Return a lightweight embedding object compatible with RAGAS metrics.
398
+
399
+ Wraps the ChromaDB ONNX MiniLM embedding function so that metrics like
400
+ ``ResponseRelevancy`` can compute cosine similarity between embeddings.
401
+ The underlying ONNX model is cached globally and loads in <1 s.
402
+ """
403
+ if os.getenv("OPENCODEREVIEW_ALLOW_LOCAL_EMBEDDINGS", "false").lower() not in {"1", "true", "yes"}:
404
+ logger.info("Local RAGAS embeddings disabled; skipping answer relevancy")
405
+ return None
406
+ try:
407
+ from chromadb.utils import embedding_functions
408
+
409
+ if hasattr(embedding_functions, "ONNXMiniLM_L6_V2"):
410
+ ef = embedding_functions.ONNXMiniLM_L6_V2()
411
+ else:
412
+ ef = embedding_functions.SentenceTransformerEmbeddingFunction(
413
+ model_name="all-MiniLM-L6-v2"
414
+ )
415
+
416
+ class _RagasEmbeddings:
417
+ def __init__(self, ef):
418
+ self._ef = ef
419
+
420
+ def embed_query(self, text: str) -> list[float]:
421
+ result = self._ef([text])[0]
422
+ return list(result) if not isinstance(result, list) else result
423
+
424
+ def embed_documents(self, texts: list[str]) -> list[list[float]]:
425
+ results = self._ef(texts)
426
+ return [list(r) if not isinstance(r, list) else r for r in results]
427
+
428
+ return _RagasEmbeddings(ef)
429
+ except Exception as exc:
430
+ logger.warning("Cannot create RAGAS embeddings: %s", exc)
431
+ return None
432
+
433
+
434
+ def _compute_mmr(
435
+ query: str,
436
+ retrieved_contexts: list[str],
437
+ llm: Any,
438
+ ) -> float:
439
+ """Compute Mean Reciprocal Rank — how early the first relevant chunk appears.
440
+
441
+ Uses the LLM to judge each chunk's relevance to the query in order.
442
+ The first chunk judged relevant determines the reciprocal rank:
443
+ ``1 / rank_of_first_relevant``. Returns 0.0 if none are relevant.
444
+
445
+ Parameters
446
+ ----------
447
+ query : str
448
+ The search query (PR diff).
449
+ retrieved_contexts : list[str]
450
+ Ranked list of retrieved code chunks.
451
+ llm : LangchainLLMWrapper
452
+ RAGAS-wrapped LLM for relevance judgments.
453
+
454
+ Returns
455
+ -------
456
+ float
457
+ MMR score in [0, 1]; 0.0 when chunks were judged but none were
458
+ relevant.
459
+
460
+ Raises
461
+ ------
462
+ RuntimeError
463
+ If every relevance judgment failed (e.g. LLM rate-limited) —
464
+ callers treat this as a failed metric rather than a fake 0.0.
465
+ """
466
+ if not retrieved_contexts:
467
+ return 0.0
468
+
469
+ # Score up to the first 5 chunks for relevance using the LLM.
470
+ # Top-5 MMR is standard — rank 5 yields 1/5 = 0.20, and
471
+ # anything beyond rank 5 barely changes the score anyway.
472
+ MAX_MMR_RANK = 2
473
+ top_chunks = retrieved_contexts[:MAX_MMR_RANK]
474
+
475
+ judged = 0
476
+ for rank, chunk in enumerate(top_chunks, start=1):
477
+ try:
478
+ prompt = (
479
+ f"Is the following code/document chunk relevant to the question?\n\n"
480
+ f"Question: {query[:2_000]}\n\n"
481
+ f"Chunk: {chunk[:2_000]}\n\n"
482
+ f"Answer with exactly one word: YES or NO"
483
+ )
484
+ # Use the wrapped LangChain model for fast synchronous invoke.
485
+ # LangchainLLMWrapper stores the model as .langchain_llm in ragas
486
+ # 0.4.x and as .llm in 0.3.x — accept both.
487
+ langchain_model = getattr(llm, "langchain_llm", None) or getattr(llm, "llm", None)
488
+ # Space the relevance judgments too — this unwrapped path bypasses
489
+ # the model wrapper on some ragas versions, so sleep explicitly
490
+ # (unless the wrapper is already in the path, to avoid double-sleep).
491
+ if not isinstance(langchain_model, _ThrottledChatModel):
492
+ time.sleep(_RAGAS_INTERVAL)
493
+ raw = langchain_model.invoke(prompt)
494
+ response_text = raw.content.strip().upper() if hasattr(raw, "content") else str(raw).strip().upper()
495
+ if response_text.startswith("Y"):
496
+ return 1.0 / rank
497
+ judged += 1 # judge responded — chunk deemed not relevant
498
+ except Exception:
499
+ continue
500
+
501
+ if judged == 0:
502
+ # Every relevance judgment failed (e.g. LLM rate-limited) — surface
503
+ # this as a failed metric instead of a misleading 0.0.
504
+ raise RuntimeError("all MMR relevance judgments failed")
505
+
506
+ return 0.0
507
+
508
+
509
+ def log_ragas_scores_to_langfuse(
510
+ scores: dict[str, float | None],
511
+ repo: str = "",
512
+ pr_number: int = 0,
513
+ handler: Any = None,
514
+ ) -> None:
515
+ """Log RAGAS metrics as Langfuse scores (linked to the review trace).
516
+
517
+ Parameters
518
+ ----------
519
+ scores : dict
520
+ Output of :func:`compute_ragas_retrieval_scores`.
521
+ repo : str
522
+ GitHub repository name (e.g. ``\"psf/requests\"``).
523
+ pr_number : int
524
+ Pull request number.
525
+ handler : Langfuse CallbackHandler or None
526
+ Handler from the current review run, used to link scores to the trace.
527
+ """
528
+ try:
529
+ from backend.observability import log_langfuse_score
530
+ except ImportError:
531
+ logger.debug("observability module not available — skipping Langfuse")
532
+ return
533
+
534
+ for metric_name, value in scores.items():
535
+ if value is None:
536
+ continue
537
+ log_langfuse_score(
538
+ name=f"ragas_{metric_name}",
539
+ value=value,
540
+ comment=f"{repo}#{pr_number} — {metric_name}",
541
+ handler=handler,
542
+ )
543
+
544
+
545
+ # ─── Standalone CLI ─────────────────────────────────────────────────────────
546
+
547
+
548
+ def main() -> None:
549
+ """CLI entry point: compute RAGAS scores from a JSONL dataset.
550
+
551
+ Usage::
552
+
553
+ python eval_data/ragas_eval.py --data eval_data/prs.jsonl
554
+ """
555
+ import argparse
556
+ import json
557
+
558
+ parser = argparse.ArgumentParser(
559
+ description="Compute RAGAS retrieval quality scores on evaluation data",
560
+ )
561
+ parser.add_argument(
562
+ "--data", default=None,
563
+ help="Path to JSONL dataset (same format as evaluate.py)",
564
+ )
565
+ parser.add_argument(
566
+ "--output", default=None,
567
+ help="Path to write per-PR RAGAS scores (JSON)",
568
+ )
569
+ parser.add_argument(
570
+ "--max-prs", type=int, default=None,
571
+ help="Max PRs to process",
572
+ )
573
+ parser.add_argument(
574
+ "--log-to-observability", action="store_true",
575
+ help="Log RAGAS scores to Langfuse",
576
+ )
577
+ args = parser.parse_args()
578
+
579
+ logging.basicConfig(
580
+ level=logging.INFO,
581
+ format="%(asctime)s [%(levelname)s] %(name)s — %(message)s",
582
+ )
583
+
584
+ if not args.data:
585
+ # If no data file specified, try default location
586
+ default_path = os.path.join(
587
+ os.path.dirname(__file__), "prs.jsonl"
588
+ )
589
+ if os.path.exists(default_path):
590
+ args.data = default_path
591
+ else:
592
+ logger.error(
593
+ "No --data provided and default not found at %s. "
594
+ "Run eval_data/fetcher.py first.",
595
+ default_path,
596
+ )
597
+ return
598
+
599
+ with open(args.data, "r", encoding="utf-8") as f:
600
+ entries = [json.loads(line) for line in f if line.strip()]
601
+
602
+ if args.max_prs:
603
+ entries = entries[: args.max_prs]
604
+
605
+ all_scores: list[dict] = []
606
+ for entry in entries:
607
+ repo = entry.get("repo", "?")
608
+ pr = entry.get("pr_number", 0)
609
+ diff = entry.get("diff", "")
610
+ ground_truth_list = entry.get("ground_truth", [])
611
+
612
+ # Use the diff as the query, and first few human comments
613
+ # as a proxy for "what the retrieval should have found"
614
+ query = diff[:8_000] if diff else entry.get("title", "")
615
+ gt_text = (
616
+ " ".join(
617
+ g.get("comment", "")
618
+ for g in ground_truth_list[:5]
619
+ )
620
+ if ground_truth_list
621
+ else None
622
+ )
623
+
624
+ # Retrieved contexts come from the graph run, but for the CLI
625
+ # we don't re-run the graph — we just skip if no retrieval data
626
+ # is available in the entry.
627
+ stored_contexts = entry.get("retrieved_contexts", [])
628
+ if not stored_contexts:
629
+ logger.info(
630
+ "[%s#%d] No stored retrieval contexts — skipping RAGAS",
631
+ repo, pr,
632
+ )
633
+ continue
634
+
635
+ logger.info("[%s#%d] Computing RAGAS scores …", repo, pr)
636
+ try:
637
+ scores = compute_ragas_retrieval_scores(
638
+ query=query,
639
+ retrieved_contexts=stored_contexts,
640
+ ground_truth=gt_text,
641
+ )
642
+ except RuntimeError as exc:
643
+ logger.warning("[%s#%d] %s", repo, pr, exc)
644
+ break
645
+
646
+ scores.update({"repo": repo, "pr_number": pr, "id": entry.get("id")})
647
+ all_scores.append(scores)
648
+
649
+ if args.log_to_observability:
650
+ log_ragas_scores_to_langfuse(scores, repo=repo, pr_number=pr)
651
+
652
+ print(
653
+ f" {repo}#{pr}: "
654
+ + " | ".join(
655
+ f"{k}={v:.3f}" for k, v in scores.items()
656
+ if k not in ("repo", "pr_number", "id") and v is not None
657
+ )
658
+ )
659
+
660
+ # Print aggregate
661
+ if all_scores:
662
+ print()
663
+ print("=" * 60)
664
+ print(" Aggregate RAGAS scores")
665
+ print("=" * 60)
666
+ metrics = [
667
+ k for k in all_scores[0].keys()
668
+ if k not in ("repo", "pr_number", "id")
669
+ ]
670
+ for metric in metrics:
671
+ values = [
672
+ s.get(metric) for s in all_scores
673
+ if s.get(metric) is not None
674
+ ]
675
+ if not values:
676
+ print(f" {metric:30s}: n/a (no successful scores)")
677
+ continue
678
+ avg = sum(values) / len(values)
679
+ print(f" {metric:30s}: {avg:.4f} (over {len(values)} PRs)")
680
+ print()
681
+
682
+ # Save output
683
+ if args.output and all_scores:
684
+ with open(args.output, "w", encoding="utf-8") as f:
685
+ json.dump(all_scores, f, indent=2)
686
+ logger.info("Saved RAGAS scores to %s", args.output)
687
+
688
+
689
+ if __name__ == "__main__":
690
+ main()
frontend/src/main.jsx CHANGED
@@ -1,189 +1,189 @@
1
- import React, { useEffect, useMemo, useState } from "react";
2
- import { createRoot } from "react-dom/client";
3
- import "./styles.css";
4
- import { reviewPayload, readProviders, initialEndpoint, groupFindings, formatCost, upsertProvider } from "./review-client.js";
5
-
6
- const API_BASE = (import.meta.env.VITE_REVIEW_API_URL || "").replace(/\/$/, "");
7
- const TERMINAL = new Set(["awaiting_approval", "rejected", "posted", "partially_posted", "post_failed", "failed", "incomplete", "cancelled"]);
8
- const apiUrl = (path) => `${API_BASE}${path}`;
9
- const pretty = (value) => String(value || "").replaceAll("_", " ");
10
-
11
- function Verdict({ job }) {
12
- if (!job?.verdict) return null;
13
- const v = job.verdict;
14
- const score = typeof v.overall_score === "number" ? v.overall_score : null;
15
- const scoreLabel = score == null ? "Not scored" : score < 4 ? "High risk" : score < 7 ? "Review carefully" : "Low risk";
16
- const cost = formatCost(job.cost_details || job.cost);
17
- return <section className={`result-card verdict ${["block", "request_changes", "incomplete"].includes(v.recommendation) ? "blocking" : "approved"}`} aria-labelledby="verdict-title">
18
- <div className="result-title"><div><span className="panel-kicker">Review decision</span><h3 id="verdict-title">{pretty(v.recommendation).toUpperCase()}</h3></div><div className="score-block"><strong className="score">{score == null ? "—" : `${score.toFixed(1)}/10`}</strong><span>{scoreLabel}</span></div></div>
19
- <p>{v.summary || "The review is ready for your decision."}</p>
20
- <div className="score-explanation"><strong>Risk estimate, not answer accuracy</strong><span>{v.score_explanation || (score == null ? "A reliable score is unavailable because review stages did not finish." : "The score reflects reported code risks. Test suggestions and unverified claims should be assessed separately.")}</span></div>
21
- {v.score_breakdown && Object.keys(v.score_breakdown).length > 0 && <details><summary>How the score was calculated</summary><ul>{Object.entries(v.score_breakdown).map(([key,value]) => <li key={key}>{pretty(key)}: {typeof value === "object" ? JSON.stringify(value) : String(value)}</li>)}</ul></details>}
22
- <div className="metrics"><span>{job.findings?.length || 0} findings and suggestions</span>{cost && <span>{cost}</span>}</div>
23
- </section>;
24
- }
25
-
26
- function Findings({ findings = [], feedback = {}, onFeedback, feedbackBusy }) {
27
- const groups = groupFindings(findings);
28
- const titles = {bug: "Bugs", security_concern: "Security concerns", test_suggestion: "Suggested tests"};
29
- return <section aria-labelledby="findings-title"><div className="section-heading"><h3 id="findings-title">Review findings</h3><span>{findings.length}</span></div>{findings.length ? Object.entries(groups).map(([kind, entries]) => entries.length > 0 && <section className="finding-group" key={kind} aria-label={titles[kind]}><h4>{titles[kind]} <span>{entries.length}</span></h4>{entries.map(({finding:f,index}) => <article className="finding" key={`${f.file_path}-${index}`}>
30
- <div className="finding-meta"><span className={`severity ${String(f.severity || "info").toLowerCase()}`}>{f.severity || "info"}</span><span className="finding-location">{f.file_path || "Unknown file"}{f.line_start ? `:${f.line_start}${f.line_end && f.line_end !== f.line_start ? `–${f.line_end}` : ""}` : ""}</span></div>
31
- <p>{f.comment || f.description || "No explanation provided."}</p>
32
- <span className={`evidence-label ${f.evidence_status === "source_grounded" ? "grounded" : "uncertain"}`}>{f.evidence_status === "source_grounded" ? "Source location checked · claim needs your review" : f.evidence_status === "outside_diff" ? "Outside reviewed changes · needs verification" : "Needs verification"}</span>
33
- {f.calibration_note && <p className="calibration-note">{f.calibration_note}</p>}
34
- {f.evidence_excerpt && <details><summary>Supporting source excerpt</summary><pre className="evidence-excerpt">{f.evidence_excerpt}</pre></details>}
35
- {f.suggested_fix && <details><summary>Suggested fix</summary><p>{f.suggested_fix}</p></details>}
36
- {f.confidence != null && <small>Model confidence (uncalibrated) {Math.round(Number(f.confidence) * 100)}% · not independently measured</small>}
37
- {onFeedback && <div className="finding-feedback" aria-label={`Feedback for finding ${index + 1}`}><span>Was this helpful?</span>{["correct","incorrect","useful"].map(label => <button type="button" key={label} disabled={feedbackBusy === index} aria-pressed={feedback[String(index)] === label} onClick={() => onFeedback(index,label)}>{label === "useful" ? "Useful suggestion" : pretty(label)}</button>)}{feedback[String(index)] && <small>Feedback saved</small>}</div>}
38
- </article>)}</section>) : <div className="empty-result"><strong>No findings returned</strong><span>This does not prove the changes are free of issues. Check the review coverage and reviewer statuses.</span></div>}</section>;
39
- }
40
-
41
- function Coverage({ coverage }) {
42
- if (!coverage) return null;
43
- return <section className="result-card review-coverage" aria-label="Review coverage"><span className="panel-kicker">What was reviewed</span><p>{coverage.files_available ?? coverage.files_changed ?? "Unknown"} files available · {coverage.incremental ? "incremental preview · " : ""}{pretty(coverage.mode || "review")} mode · {coverage.diff_chars ?? "Unknown"} diff characters</p>{coverage.changed_file_paths?.length > 0 && <details><summary>Files in scope</summary><ul>{coverage.changed_file_paths.map(path => <li key={path}>{path}</li>)}</ul></details>}{coverage.limitations?.length > 0 && <ul>{coverage.limitations.map((note,index) => <li key={index}>{note}</li>)}</ul>}{coverage.reviewers?.length > 0 && <details><summary>Reviewer coverage</summary><ul>{coverage.reviewers.map((reviewer,index) => <li key={index}>{pretty(reviewer.reviewer || reviewer.name)}: {pretty(reviewer.status)}{reviewer.diff_chars_included != null ? ` · ${reviewer.diff_chars_included} diff characters included` : ""}{reviewer.limitations?.map((note,i) => <p key={i}>{note}</p>)}</li>)}</ul></details>}</section>;
44
- }
45
-
46
- function Receipt({ result }) {
47
- if (!result) return null;
48
- return <section className="result-card receipt" aria-labelledby="receipt-title"><span className="panel-kicker">Delivery receipt</span><h3 id="receipt-title">{pretty(result.status || "completed")}</h3><div className="metrics"><span>Inline: {result.inline_posted || 0}</span><span>Fallback: {result.fallback_posted || 0}</span><span>Finding failures: {result.finding_failed || 0}</span><span>Unverified findings withheld: {result.withheld_unverified || 0}</span><span>Verdict: {result.verdict_posted ? "posted" : "failed"}</span></div></section>;
49
- }
50
-
51
- function ReviewProgress({ job }) {
52
- if (!job) return null;
53
- const stages = job.review_stages || [];
54
- const timings = job.stage_timings || {};
55
- return <section className="review-progress" aria-label="Review progress" aria-live="polite">
56
- {job.persistence === "local_fallback" && <p className="message error">This review is stored locally because the shared database is unavailable. It may be lost if the server restarts.</p>}
57
- {job.status === "incomplete" && <p className="message error">Review incomplete. Failed reviewers do not mean the code is free of issues.</p>}
58
- <div className="metrics">{job.elapsed_seconds != null && <span>Elapsed: {Math.round(job.elapsed_seconds)}s</span>}{job.review_mode && <span>{pretty(job.review_mode)} review</span>}{job.progress?.completed_stages?.length > 0 && <span>{job.progress.completed_stages.length} stages finished</span>}</div>
59
- {stages.length > 0 && <ul className="reviewer-stages">{stages.map((stage, index) => <li key={`${stage.reviewer}-${index}`}><strong>{pretty(stage.reviewer)}</strong><span>{pretty(stage.status)}{stage.duration_seconds != null ? ` · ${stage.duration_seconds.toFixed(1)}s` : ""}</span>{stage.model && <small>{stage.model}</small>}{stage.reason && <small>{stage.reason}</small>}{stage.error && <small className="reviewer-error">{stage.error}</small>}</li>)}</ul>}
60
- {Object.keys(timings).length > 0 && <details><summary>Stage completion times (since review start)</summary><ul>{Object.entries(timings).map(([name, seconds]) => <li key={name}>{pretty(name)}: {Number(seconds).toFixed(1)}s</li>)}</ul></details>}
61
- </section>;
62
- }
63
-
64
- function App() {
65
- const [activeTab, setActiveTab] = useState("review");
66
- const [reviewMode, setReviewMode] = useState("fast");
67
- const [baselineSha, setBaselineSha] = useState("");
68
- const [testingProvider, setTestingProvider] = useState(false);
69
- const [editingProvider, setEditingProvider] = useState(null);
70
- const [lastTest, setLastTest] = useState(null);
71
- const [defaultProvider, setDefaultProvider] = useState(() => { try { return localStorage.getItem("ocr-default-provider") || ""; } catch { return ""; } });
72
- const [feedbackBusy, setFeedbackBusy] = useState(null);
73
-
74
- const [repo, setRepo] = useState(""); const [pr, setPr] = useState(""); const [endpoint, setEndpoint] = useState(() => initialEndpoint(localStorage)); const [provider, setProvider] = useState("openai"); const [model, setModel] = useState(""); const [apiKey, setApiKey] = useState(""); const [baseUrl, setBaseUrl] = useState("");
75
- const [savedProviders, setSavedProviders] = useState(() => readProviders(localStorage));
76
- const [theme, setTheme] = useState(() => localStorage.getItem("ocr-theme") || "light"); const [job, setJob] = useState(null); const [message, setMessage] = useState(""); const [error, setError] = useState(""); const [busy, setBusy] = useState(false); const [user, setUser] = useState(null);
77
- useEffect(() => { fetch(apiUrl("/api/auth/me"), { credentials: "include" }).then(r => r.ok ? r.json() : null).then(setUser).catch(() => setUser(null)); }, []);
78
- async function logout() { await fetch(apiUrl("/api/auth/logout"), { method: "POST", credentials: "include" }); setUser(null); }
79
- useEffect(() => { document.documentElement.dataset.theme = theme; localStorage.setItem("ocr-theme", theme); }, [theme]);
80
- const isTerminal = useMemo(() => TERMINAL.has(job?.status), [job?.status]);
81
- useEffect(() => {
82
- if (!job?.id || isTerminal) return undefined; let stopped = false;
83
- const poll = async () => { try { const r = await fetch(apiUrl(`/api/reviews/${job.id}`)); if (!r.ok) throw new Error(`Status check failed (${r.status})`); const next = await r.json(); if (!stopped) { setJob(next); setMessage(next.status === "awaiting_approval" ? "Review complete. Inspect the findings before posting." : next.status === "incomplete" ? "Review incomplete. Some reviewers could not finish; these findings are partial." : next.status === "cancelled" ? "Review cancelled." : `Review ${pretty(next.status)}…`); } } catch (e) { if (!stopped) setError(e.message); } };
84
- poll(); const timer = window.setInterval(poll, 3000); return () => { stopped = true; window.clearInterval(timer); };
85
- }, [job?.id, isTerminal]);
86
-
87
- function providerDraft() {
88
- return {name: `${provider || "openai"} / ${model.trim()}`, provider: provider || "openai", model: model.trim(), apiKey: apiKey.trim(), baseUrl: baseUrl.trim()};
89
- }
90
- function saveEntries(entries) {
91
- localStorage.setItem("ocr-providers", JSON.stringify(entries)); setSavedProviders(entries);
92
- }
93
- function editProvider(item) {
94
- setEditingProvider(item.name); setProvider(item.provider); setModel(item.model); setApiKey(item.apiKey); setBaseUrl(item.baseUrl || ""); setLastTest(item.lastTest || null); setError(""); setMessage(`Editing ${item.name}. Changes are saved when you click Save changes.`);
95
- }
96
- function removeProvider(item) {
97
- try {
98
- saveEntries(savedProviders.filter(entry => entry.name !== item.name));
99
- if (defaultProvider === item.name) { localStorage.removeItem("ocr-default-provider"); setDefaultProvider(""); }
100
- if (endpoint === `saved:${item.name}`) setEndpoint("auto");
101
- if (editingProvider === item.name) resetProviderDraft();
102
- setError(""); setMessage(`${item.name} removed from this browser.`);
103
- } catch { setError("Could not remove provider from browser storage."); }
104
- }
105
- function makeDefault(item) {
106
- try { localStorage.setItem("ocr-default-provider",item.name); setDefaultProvider(item.name); setEndpoint(`saved:${item.name}`); setError(""); setMessage(`${item.name} is the default for new reviews.`); }
107
- catch { setError("Could not save the default provider."); }
108
- }
109
- function resetProviderDraft() { setEditingProvider(null); setModel(""); setApiKey(""); setBaseUrl(""); setProvider("openai"); setLastTest(null); setError(""); setMessage(""); }
110
- async function testProvider() {
111
- if (!model.trim() || !apiKey.trim()) { setError("Enter a model and API key before testing."); return; }
112
- const draft = providerDraft();
113
- setError(""); setMessage("Testing response time and JSON output…"); setTestingProvider(true);
114
- try {
115
- const response = await fetch("/api/provider-test", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({provider:draft.provider, model:draft.model, apiKey:draft.apiKey, baseUrl:draft.baseUrl}) });
116
- const result = await response.json();
117
- if (!response.ok) throw new Error(result.error || "Provider test failed.");
118
- const tested = {at: new Date().toISOString(), latency_ms:result.latency_ms, json_valid:result.json_object_valid, fingerprint:JSON.stringify(draft)};
119
- setLastTest(tested);
120
- const saved = savedProviders.find(item => item.name === draft.name && item.apiKey === draft.apiKey && item.baseUrl === draft.baseUrl);
121
- if (saved) saveEntries(savedProviders.map(item => item.name === saved.name ? {...item,lastTest:{at:tested.at,latency_ms:tested.latency_ms,json_valid:tested.json_valid}} : item));
122
- setMessage(`Connection verified in ${(result.latency_ms / 1000).toFixed(1)}s. JSON response: ${result.json_object_valid ? "valid" : "invalid — this model may need a different output format"}.`);
123
- } catch (err) { setLastTest(null); setMessage(""); setError(err.message); } finally { setTestingProvider(false); }
124
- }
125
- function addProvider() {
126
- if (!model.trim() || !apiKey.trim()) { setError("Enter a model and API key first."); return; }
127
- const item = providerDraft();
128
- const freshTest = lastTest?.fingerprint === JSON.stringify(item) ? lastTest : null;
129
- if (freshTest) item.lastTest = {at:freshTest.at,latency_ms:freshTest.latency_ms,json_valid:freshTest.json_valid};
130
- const previous = savedProviders.find(entry => entry.name === editingProvider);
131
- if (!freshTest && previous && previous.provider === item.provider && previous.model === item.model && previous.apiKey === item.apiKey && (previous.baseUrl || "") === item.baseUrl) item.lastTest = previous.lastTest;
132
- try {
133
- saveEntries(upsertProvider(savedProviders,item,editingProvider));
134
- if (editingProvider && defaultProvider === editingProvider) { localStorage.setItem("ocr-default-provider",item.name); setDefaultProvider(item.name); }
135
- setEditingProvider(item.name); setEndpoint(`saved:${item.name}`); setError(""); setMessage(`${item.name} saved. Select it in Review.`);
136
- } catch { setMessage(""); setError("Browser storage is unavailable. Provider could not be saved."); }
137
- }
138
- async function saveFeedback(index,label) {
139
- if (!job?.id) return;
140
- setFeedbackBusy(index); setError("");
141
- try {
142
- const response = await fetch(apiUrl(`/api/reviews/${job.id}/feedback`), {method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({finding_index:index,label})});
143
- const result = await response.json();
144
- if (!response.ok) throw new Error(result.detail || "Could not save feedback.");
145
- setJob(current => current?.id === job.id ? {...current,feedback:result.feedback} : current);
146
- } catch(err) { setError(err.message); } finally { setFeedbackBusy(null); }
147
- }
148
- async function startReview(e) {
149
- e.preventDefault(); setError("");
150
- if (!/^[-\w.]+\/[-\w.]+$/.test(repo.trim()) || !Number.isInteger(Number(pr)) || Number(pr) < 1) { setError("Enter a repository as owner/name and a valid PR number."); return; }
151
- setBusy(true); setJob(null); setMessage("Queueing review…");
152
- try {
153
- const response = await fetch(apiUrl("/api/reviews"), { method: "POST", credentials: "include", headers: { "Content-Type": "application/json" }, body: JSON.stringify(reviewPayload(repo, pr, endpoint, savedProviders, reviewMode, baselineSha)) });
154
- const data = await response.json().catch(() => ({}));
155
- if (!response.ok) throw new Error(data.detail || `Request failed (${response.status})`);
156
- setJob(data); setMessage(data.cache_hit ? "Previous review reused for this exact commit and configuration." : data.reused ? "An existing review is already running. Following its progress." : "Review queued. Findings appear as reviewers finish.");
157
- } catch (err) { setError(err.message); } finally { setBusy(false); }
158
- }
159
- async function cancelReview() {
160
- if (!job?.id) return;
161
- setBusy(true); setError("");
162
- try {
163
- const response = await fetch(apiUrl(`/api/reviews/${job.id}/cancel`), { method: "POST", credentials: "include" });
164
- const data = await response.json().catch(() => ({}));
165
- if (!response.ok) throw new Error(data.detail || "Could not cancel review.");
166
- setJob(data); setMessage("Cancellation requested. A model call already in progress may finish before the worker stops.");
167
- } catch (err) { setError(err.message); } finally { setBusy(false); }
168
- }
169
- async function decide(action) { if (!job?.id) return; setBusy(true); setError(""); setMessage(action === "approve" ? "Posting approved review…" : "Rejecting review…"); try { const r = await fetch(apiUrl(`/api/reviews/${job.id}/decision`), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action }) }); const data = await r.json().catch(() => ({})); if (!r.ok) throw new Error(data.detail || `Decision failed (${r.status})`); setJob(data); setMessage(action === "approve" ? "Review delivery finished." : "Review rejected. Nothing was posted to GitHub."); } catch (e) { setError(e.message); } finally { setBusy(false); } }
170
- return <div className="shell"><header className="topbar"><div className="brand"><span className="brand-mark">OC</span><span>OpenCodeReview</span></div><div>{user ? <><span className="status-dot">Signed in as {user.login}</span><button className="auth-button" onClick={logout}>Sign out</button></> : <a className="status-dot" href={`${API_BASE}/api/auth/github/start`}>Sign in with GitHub</a>}<span className="status-dot">Human approval required</span><button className="theme-toggle" type="button" onClick={() => setTheme(theme === "dark" ? "light" : "dark")} aria-label="Toggle color theme">{theme === "dark" ? "Light" : "Dark"}</button></div></header><main className="content"><section className="hero"><p className="eyebrow">Pull request intelligence</p><h1>Review changes with<br /><em>evidence before action.</em></h1><p className="lede">Parallel analysis for correctness, security, and test coverage. Nothing is posted to GitHub until you approve it.</p></section><section className="intro-band"><div className="intro-copy"><p className="eyebrow">AI code review with a human checkpoint</p><h2>Know what changed<br /><em>before it ships.</em></h2><p>OpenCodeReview traces pull requests back to the diff, checks correctness and security, then gives you the evidence to decide what reaches GitHub.</p><div className="intro-actions"><a className="primary-link" href={user ? "#new-review" : `${API_BASE}/api/auth/github/start`}>Start a review <span>&rarr;</span></a><a className="quiet-link" href="#how-it-works">See how it works</a></div></div><div className="review-preview" aria-label="Review workflow preview"><div className="preview-top"><span className="live-dot"></span><span>REVIEW PIPELINE</span><span className="preview-time">LIVE</span></div><div className="preview-row"><strong>01</strong><span><b>Read the diff</b><small>Files, lines, and context</small></span><i>done</i></div><div className="preview-row"><strong>02</strong><span><b>Cross-check findings</b><small>Evidence, severity, confidence</small></span><i>done</i></div><div className="preview-row active"><strong>03</strong><span><b>Your decision</b><small>Approve, reject, or inspect</small></span><i>waiting</i></div></div></section><section className="trust-strip" id="how-it-works"><div><strong>Evidence first</strong><span>Every finding points to code.</span></div><div><strong>Human controlled</strong><span>Nothing posts without approval.</span></div><div><strong>Focused review</strong><span>Correctness, security, and test coverage.</span></div></section>{user ? <section className="workspace" id="new-review"><nav className="workspace-tabs" aria-label="Workspace"><button type="button" className={activeTab === "review" ? "active" : ""} onClick={() => { setActiveTab("review"); setError(""); setMessage(""); }}>Review</button><button type="button" className={activeTab === "providers" ? "active" : ""} onClick={() => { setActiveTab("providers"); setError(""); setMessage(""); }}>Providers</button></nav>{activeTab === "providers" && <section className="panel provider-manager" id="providers"><div className="panel-kicker">Provider library</div><h2>Saved providers</h2><p className="provider-hint">Keep your model connections ready for future reviews.</p>{savedProviders.length ? <div className="saved-provider-list">{savedProviders.map(item => <div className="saved-provider" key={item.name}><div className="provider-entry-title"><strong>{item.name}</strong>{defaultProvider === item.name && <span className="pill">Default</span>}</div><small>{item.baseUrl || "Default API endpoint"}</small><small>{item.lastTest ? `Last successful connection: ${new Date(item.lastTest.at).toLocaleString()} · ${(Number(item.lastTest.latency_ms) / 1000).toFixed(1)}s · JSON ${item.lastTest.json_valid ? "valid" : "invalid"}` : "Connection has not been tested"}</small><div className="provider-entry-actions"><button type="button" onClick={() => editProvider(item)} aria-label={`Edit ${item.name}`}>Edit</button><button type="button" onClick={() => makeDefault(item)} disabled={defaultProvider === item.name} aria-label={`Make ${item.name} default`}>Make default</button><button type="button" onClick={() => removeProvider(item)} aria-label={`Delete ${item.name}`}>Delete</button></div></div>)}</div> : <p className="provider-hint">No providers saved yet.</p>}<div className="provider-form-heading"><h3>{editingProvider ? "Edit provider" : "Add a provider"}</h3>{editingProvider && <button type="button" onClick={resetProviderDraft}>New provider</button>}</div><p className="provider-hint">Saved on this browser. Keys are hidden from the list and sent only when a provider is tested or used.</p><label htmlFor="provider-manager-type">Provider type<select id="provider-manager-type" value={provider || "openai"} onChange={e => setProvider(e.target.value)}><option value="openai">OpenAI-compatible</option><option value="anthropic">Anthropic</option><option value="google">Google</option></select></label><label htmlFor="provider-manager-model">Model<input id="provider-manager-model" value={model} onChange={e => setModel(e.target.value)} placeholder="model-name" /></label><label htmlFor="provider-manager-key">API key<input id="provider-manager-key" type="password" value={apiKey} onChange={e => setApiKey(e.target.value)} placeholder="Used for reviews" /></label><label htmlFor="provider-manager-base">Base URL <span>(optional)</span><input id="provider-manager-base" value={baseUrl} onChange={e => setBaseUrl(e.target.value)} placeholder="https://api.example.com/v1" /></label><div className="provider-actions"><button type="button" onClick={testProvider} disabled={testingProvider}>{testingProvider ? "Testing…" : "Test speed & JSON"}</button><button type="button" onClick={addProvider}>{editingProvider ? "Save changes" : "Add provider"}<span>+</span></button></div>{(error || message) && <div className={`message ${error ? "error" : "success"}`} role="status" aria-live="polite">{error || message}</div>}</section>}<form className={`panel form-panel ${activeTab === "providers" ? "is-hidden" : ""}`} onSubmit={startReview} aria-busy={busy}><div className="panel-kicker">New review</div><h2>Inspect a pull request</h2><label htmlFor="repo">Repository<input id="repo" value={repo} onChange={e => setRepo(e.target.value)} placeholder="owner/repository" autoComplete="off" /></label><label htmlFor="pr">Pull request<input id="pr" value={pr} onChange={e => setPr(e.target.value)} placeholder="42" inputMode="numeric" /></label><label htmlFor="endpoint">Provider<select id="endpoint" value={endpoint} onChange={e => setEndpoint(e.target.value)}><option value="auto">Automatic fallback</option><option value="cloudflare">Cloudflare GLM 4.7 Flash</option><option value="gemini">Gemini</option><option value="groq">Groq</option>{savedProviders.map(item => <option key={item.name} value={`saved:${item.name}`}>{item.name}</option>)}</select></label><fieldset className="review-mode"><legend>Review depth</legend><label><input type="radio" name="review-mode" value="fast" checked={reviewMode === "fast"} onChange={() => setReviewMode("fast")} />Fast<span>Smaller prompts and response budget</span></label><label><input type="radio" name="review-mode" value="thorough" checked={reviewMode === "thorough"} onChange={() => setReviewMode("thorough")} />Thorough<span>More context and analysis</span></label></fieldset><details className="incremental-options"><summary>Review only changes since a commit</summary><label htmlFor="baseline-sha">Previously reviewed commit SHA<input id="baseline-sha" value={baselineSha} onChange={e => setBaselineSha(e.target.value)} placeholder="40-character commit SHA (optional)" pattern="[a-fA-F0-9]{40}" autoComplete="off" /></label><p className="provider-hint">When set, this reviews only changes since that commit, not the whole pull request.</p></details><button type="submit" disabled={busy}>{busy && !job ? "Queueing review…" : "Start review"}<span aria-hidden="true">↗</span></button>{(error || message) && <div className={`message ${error ? "error" : "success"}`} role="status" aria-live="polite">{error || message}</div>}{job && <div className="job-card"><div><strong>Review {job.id?.slice(0, 8)}</strong><small>{job.repo} · PR #{job.pr_number}</small></div><span className={`pill ${job.status}`}>{pretty(job.status)}</span></div>}{job && !isTerminal && <div className="progress" role="progressbar" aria-label={`Review ${pretty(job.status)}`}><span /><small>{job.queue_position ? `Queue position: ${job.queue_position}` : `Current stage: ${pretty(job.progress?.stage || job.status)}`}</small><button type="button" className="secondary" onClick={cancelReview} disabled={busy}>Cancel review</button></div>}<div className="results"><ReviewProgress job={job} /><Verdict job={job} /><Coverage coverage={job?.review_coverage || job?.coverage} />{job?.findings?.length > 0 && <Findings findings={job.findings} feedback={job.feedback} onFeedback={isTerminal ? saveFeedback : undefined} feedbackBusy={feedbackBusy} />}{job?.status === "awaiting_approval" && job?.findings?.length === 0 && <Findings findings={[]} />}{job?.status === "awaiting_approval" && <div className="actions"><button type="button" onClick={() => decide("approve")} disabled={busy}>Approve &amp; post</button><button type="button" className="secondary" onClick={() => decide("reject")} disabled={busy}>Reject</button></div>}<Receipt result={job?.posting_result} />{job?.error && <div className="error detail">{job.error}</div>}</div></form><aside className={`panel signal-panel ${activeTab === "providers" ? "is-hidden" : ""}`}><div className="panel-kicker">What you receive</div><div className="signal"><strong>01</strong><span><b>Evidence-grounded findings</b><small>Code locations, severity, and confidence</small></span></div><div className="signal"><strong>02</strong><span><b>Human checkpoint</b><small>Approve or reject before GitHub comments</small></span></div><div className="signal"><strong>03</strong><span><b>Delivery receipt</b><small>See exactly what reached GitHub</small></span></div></aside></section> : <section className="auth-wall"><p className="eyebrow">Private review workspace</p><h2>Sign in to inspect a pull request.</h2><p>Your GitHub identity keeps reviews tied to your account and protects the review results.</p><a className="primary-link" href={`${API_BASE}/api/auth/github/start`}>Continue with GitHub <span>&rarr;</span></a></section>}</main><footer>OpenCodeReview <span>·</span> React review workspace <span>·</span> Saved keys stay in this browser</footer></div>;
171
- }
172
- createRoot(document.getElementById("root")).render(<App />);
173
-
174
-
175
-
176
-
177
-
178
-
179
-
180
-
181
-
182
-
183
-
184
-
185
-
186
-
187
-
188
-
189
-
 
1
+ import React, { useEffect, useMemo, useState } from "react";
2
+ import { createRoot } from "react-dom/client";
3
+ import "./styles.css";
4
+ import { reviewPayload, readProviders, initialEndpoint, groupFindings, formatCost, upsertProvider } from "./review-client.js";
5
+
6
+ const API_BASE = (import.meta.env.VITE_REVIEW_API_URL || "").replace(/\/$/, "");
7
+ const TERMINAL = new Set(["awaiting_approval", "rejected", "posted", "partially_posted", "post_failed", "failed", "incomplete", "cancelled"]);
8
+ const apiUrl = (path) => `${API_BASE}${path}`;
9
+ const pretty = (value) => String(value || "").replaceAll("_", " ");
10
+
11
+ function Verdict({ job }) {
12
+ if (!job?.verdict) return null;
13
+ const v = job.verdict;
14
+ const score = typeof v.overall_score === "number" ? v.overall_score : null;
15
+ const scoreLabel = score == null ? "Not scored" : score < 4 ? "High risk" : score < 7 ? "Review carefully" : "Low risk";
16
+ const cost = formatCost(job.cost_details || job.cost);
17
+ return <section className={`result-card verdict ${["block", "request_changes", "incomplete"].includes(v.recommendation) ? "blocking" : "approved"}`} aria-labelledby="verdict-title">
18
+ <div className="result-title"><div><span className="panel-kicker">Review decision</span><h3 id="verdict-title">{pretty(v.recommendation).toUpperCase()}</h3></div><div className="score-block"><strong className="score">{score == null ? "—" : `${score.toFixed(1)}/10`}</strong><span>{scoreLabel}</span></div></div>
19
+ <p>{v.summary || "The review is ready for your decision."}</p>
20
+ <div className="score-explanation"><strong>Risk estimate, not answer accuracy</strong><span>{v.score_explanation || (score == null ? "A reliable score is unavailable because review stages did not finish." : "The score reflects reported code risks. Test suggestions and unverified claims should be assessed separately.")}</span></div>
21
+ {v.score_breakdown && Object.keys(v.score_breakdown).length > 0 && <details><summary>How the score was calculated</summary><ul>{Object.entries(v.score_breakdown).map(([key,value]) => <li key={key}>{pretty(key)}: {typeof value === "object" ? JSON.stringify(value) : String(value)}</li>)}</ul></details>}
22
+ <div className="metrics"><span>{job.findings?.length || 0} findings and suggestions</span>{cost && <span>{cost}</span>}</div>
23
+ </section>;
24
+ }
25
+
26
+ function Findings({ findings = [], feedback = {}, onFeedback, feedbackBusy }) {
27
+ const groups = groupFindings(findings);
28
+ const titles = {bug: "Bugs", security_concern: "Security concerns", test_suggestion: "Suggested tests"};
29
+ return <section aria-labelledby="findings-title"><div className="section-heading"><h3 id="findings-title">Review findings</h3><span>{findings.length}</span></div>{findings.length ? Object.entries(groups).map(([kind, entries]) => entries.length > 0 && <section className="finding-group" key={kind} aria-label={titles[kind]}><h4>{titles[kind]} <span>{entries.length}</span></h4>{entries.map(({finding:f,index}) => <article className="finding" key={`${f.file_path}-${index}`}>
30
+ <div className="finding-meta"><span className={`severity ${String(f.severity || "info").toLowerCase()}`}>{f.severity || "info"}</span><span className="finding-location">{f.file_path || "Unknown file"}{f.line_start ? `:${f.line_start}${f.line_end && f.line_end !== f.line_start ? `–${f.line_end}` : ""}` : ""}</span></div>
31
+ <p>{f.comment || f.description || "No explanation provided."}</p>
32
+ <span className={`evidence-label ${f.evidence_status === "source_grounded" ? "grounded" : "uncertain"}`}>{f.evidence_status === "source_grounded" ? "Source location checked · claim needs your review" : f.evidence_status === "outside_diff" ? "Outside reviewed changes · needs verification" : "Needs verification"}</span>
33
+ {f.calibration_note && <p className="calibration-note">{f.calibration_note}</p>}
34
+ {f.evidence_excerpt && <details><summary>Supporting source excerpt</summary><pre className="evidence-excerpt">{f.evidence_excerpt}</pre></details>}
35
+ {f.suggested_fix && <details><summary>Suggested fix</summary><p>{f.suggested_fix}</p></details>}
36
+ {f.confidence != null && <small>Model confidence (uncalibrated) {Math.round(Number(f.confidence) * 100)}% · not independently measured</small>}
37
+ {onFeedback && <div className="finding-feedback" aria-label={`Feedback for finding ${index + 1}`}><span>Was this helpful?</span>{["correct","incorrect","useful"].map(label => <button type="button" key={label} disabled={feedbackBusy === index} aria-pressed={feedback[String(index)] === label} onClick={() => onFeedback(index,label)}>{label === "useful" ? "Useful suggestion" : pretty(label)}</button>)}{feedback[String(index)] && <small>Feedback saved</small>}</div>}
38
+ </article>)}</section>) : <div className="empty-result"><strong>No findings returned</strong><span>This does not prove the changes are free of issues. Check the review coverage and reviewer statuses.</span></div>}</section>;
39
+ }
40
+
41
+ function Coverage({ coverage }) {
42
+ if (!coverage) return null;
43
+ return <section className="result-card review-coverage" aria-label="Review coverage"><span className="panel-kicker">What was reviewed</span><p>{coverage.files_available ?? coverage.files_changed ?? "Unknown"} files available · {coverage.incremental ? "incremental preview · " : ""}{pretty(coverage.mode || "review")} mode · {coverage.diff_chars ?? "Unknown"} diff characters</p>{coverage.changed_file_paths?.length > 0 && <details><summary>Files in scope</summary><ul>{coverage.changed_file_paths.map(path => <li key={path}>{path}</li>)}</ul></details>}{coverage.limitations?.length > 0 && <ul>{coverage.limitations.map((note,index) => <li key={index}>{note}</li>)}</ul>}{coverage.reviewers?.length > 0 && <details><summary>Reviewer coverage</summary><ul>{coverage.reviewers.map((reviewer,index) => <li key={index}>{pretty(reviewer.reviewer || reviewer.name)}: {pretty(reviewer.status)}{reviewer.diff_chars_included != null ? ` · ${reviewer.diff_chars_included} diff characters included` : ""}{reviewer.limitations?.map((note,i) => <p key={i}>{note}</p>)}</li>)}</ul></details>}</section>;
44
+ }
45
+
46
+ function Receipt({ result }) {
47
+ if (!result) return null;
48
+ return <section className="result-card receipt" aria-labelledby="receipt-title"><span className="panel-kicker">Delivery receipt</span><h3 id="receipt-title">{pretty(result.status || "completed")}</h3><div className="metrics"><span>Inline: {result.inline_posted || 0}</span><span>Fallback: {result.fallback_posted || 0}</span><span>Finding failures: {result.finding_failed || 0}</span><span>Unverified findings withheld: {result.withheld_unverified || 0}</span><span>Verdict: {result.verdict_posted ? "posted" : "failed"}</span></div></section>;
49
+ }
50
+
51
+ function ReviewProgress({ job }) {
52
+ if (!job) return null;
53
+ const stages = job.review_stages || [];
54
+ const timings = job.stage_timings || {};
55
+ return <section className="review-progress" aria-label="Review progress" aria-live="polite">
56
+ {job.persistence === "local_fallback" && <p className="message error">This review is stored locally because the shared database is unavailable. It may be lost if the server restarts.</p>}
57
+ {job.status === "incomplete" && <p className="message error">Review incomplete. Failed reviewers do not mean the code is free of issues.</p>}
58
+ <div className="metrics">{job.elapsed_seconds != null && <span>Elapsed: {Math.round(job.elapsed_seconds)}s</span>}{job.review_mode && <span>{pretty(job.review_mode)} review</span>}{job.progress?.completed_stages?.length > 0 && <span>{job.progress.completed_stages.length} stages finished</span>}</div>
59
+ {stages.length > 0 && <ul className="reviewer-stages">{stages.map((stage, index) => <li key={`${stage.reviewer}-${index}`}><strong>{pretty(stage.reviewer)}</strong><span>{pretty(stage.status)}{stage.duration_seconds != null ? ` · ${stage.duration_seconds.toFixed(1)}s` : ""}</span>{stage.model && <small>{stage.model}</small>}{stage.reason && <small>{stage.reason}</small>}{stage.error && <small className="reviewer-error">{stage.error}</small>}</li>)}</ul>}
60
+ {Object.keys(timings).length > 0 && <details><summary>Stage completion times (since review start)</summary><ul>{Object.entries(timings).map(([name, seconds]) => <li key={name}>{pretty(name)}: {Number(seconds).toFixed(1)}s</li>)}</ul></details>}
61
+ </section>;
62
+ }
63
+
64
+ function App() {
65
+ const [activeTab, setActiveTab] = useState("review");
66
+ const [reviewMode, setReviewMode] = useState("fast");
67
+ const [baselineSha, setBaselineSha] = useState("");
68
+ const [testingProvider, setTestingProvider] = useState(false);
69
+ const [editingProvider, setEditingProvider] = useState(null);
70
+ const [lastTest, setLastTest] = useState(null);
71
+ const [defaultProvider, setDefaultProvider] = useState(() => { try { return localStorage.getItem("ocr-default-provider") || ""; } catch { return ""; } });
72
+ const [feedbackBusy, setFeedbackBusy] = useState(null);
73
+
74
+ const [repo, setRepo] = useState(""); const [pr, setPr] = useState(""); const [endpoint, setEndpoint] = useState(() => initialEndpoint(localStorage)); const [provider, setProvider] = useState("openai"); const [model, setModel] = useState(""); const [apiKey, setApiKey] = useState(""); const [baseUrl, setBaseUrl] = useState("");
75
+ const [savedProviders, setSavedProviders] = useState(() => readProviders(localStorage));
76
+ const [theme, setTheme] = useState(() => localStorage.getItem("ocr-theme") || "light"); const [job, setJob] = useState(null); const [message, setMessage] = useState(""); const [error, setError] = useState(""); const [busy, setBusy] = useState(false); const [user, setUser] = useState(null);
77
+ useEffect(() => { fetch(apiUrl("/api/auth/me"), { credentials: "include" }).then(r => r.ok ? r.json() : null).then(setUser).catch(() => setUser(null)); }, []);
78
+ async function logout() { await fetch(apiUrl("/api/auth/logout"), { method: "POST", credentials: "include" }); setUser(null); }
79
+ useEffect(() => { document.documentElement.dataset.theme = theme; localStorage.setItem("ocr-theme", theme); }, [theme]);
80
+ const isTerminal = useMemo(() => TERMINAL.has(job?.status), [job?.status]);
81
+ useEffect(() => {
82
+ if (!job?.id || isTerminal) return undefined; let stopped = false;
83
+ const poll = async () => { try { const r = await fetch(apiUrl(`/api/reviews/${job.id}`)); if (!r.ok) throw new Error(`Status check failed (${r.status})`); const next = await r.json(); if (!stopped) { setJob(next); setMessage(next.status === "awaiting_approval" ? "Review complete. Inspect the findings before posting." : next.status === "incomplete" ? "Review incomplete. Some reviewers could not finish; these findings are partial." : next.status === "cancelled" ? "Review cancelled." : `Review ${pretty(next.status)}…`); } } catch (e) { if (!stopped) setError(e.message); } };
84
+ poll(); const timer = window.setInterval(poll, 3000); return () => { stopped = true; window.clearInterval(timer); };
85
+ }, [job?.id, isTerminal]);
86
+
87
+ function providerDraft() {
88
+ return {name: `${provider || "openai"} / ${model.trim()}`, provider: provider || "openai", model: model.trim(), apiKey: apiKey.trim(), baseUrl: baseUrl.trim()};
89
+ }
90
+ function saveEntries(entries) {
91
+ localStorage.setItem("ocr-providers", JSON.stringify(entries)); setSavedProviders(entries);
92
+ }
93
+ function editProvider(item) {
94
+ setEditingProvider(item.name); setProvider(item.provider); setModel(item.model); setApiKey(item.apiKey); setBaseUrl(item.baseUrl || ""); setLastTest(item.lastTest || null); setError(""); setMessage(`Editing ${item.name}. Changes are saved when you click Save changes.`);
95
+ }
96
+ function removeProvider(item) {
97
+ try {
98
+ saveEntries(savedProviders.filter(entry => entry.name !== item.name));
99
+ if (defaultProvider === item.name) { localStorage.removeItem("ocr-default-provider"); setDefaultProvider(""); }
100
+ if (endpoint === `saved:${item.name}`) setEndpoint("auto");
101
+ if (editingProvider === item.name) resetProviderDraft();
102
+ setError(""); setMessage(`${item.name} removed from this browser.`);
103
+ } catch { setError("Could not remove provider from browser storage."); }
104
+ }
105
+ function makeDefault(item) {
106
+ try { localStorage.setItem("ocr-default-provider",item.name); setDefaultProvider(item.name); setEndpoint(`saved:${item.name}`); setError(""); setMessage(`${item.name} is the default for new reviews.`); }
107
+ catch { setError("Could not save the default provider."); }
108
+ }
109
+ function resetProviderDraft() { setEditingProvider(null); setModel(""); setApiKey(""); setBaseUrl(""); setProvider("openai"); setLastTest(null); setError(""); setMessage(""); }
110
+ async function testProvider() {
111
+ if (!model.trim() || !apiKey.trim()) { setError("Enter a model and API key before testing."); return; }
112
+ const draft = providerDraft();
113
+ setError(""); setMessage("Testing response time and JSON output…"); setTestingProvider(true);
114
+ try {
115
+ const response = await fetch("/api/provider-test", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({provider:draft.provider, model:draft.model, apiKey:draft.apiKey, baseUrl:draft.baseUrl}) });
116
+ const result = await response.json();
117
+ if (!response.ok) throw new Error(result.error || "Provider test failed.");
118
+ const tested = {at: new Date().toISOString(), latency_ms:result.latency_ms, json_valid:result.json_object_valid, fingerprint:JSON.stringify(draft)};
119
+ setLastTest(tested);
120
+ const saved = savedProviders.find(item => item.name === draft.name && item.apiKey === draft.apiKey && item.baseUrl === draft.baseUrl);
121
+ if (saved) saveEntries(savedProviders.map(item => item.name === saved.name ? {...item,lastTest:{at:tested.at,latency_ms:tested.latency_ms,json_valid:tested.json_valid}} : item));
122
+ setMessage(`Connection verified in ${(result.latency_ms / 1000).toFixed(1)}s. JSON response: ${result.json_object_valid ? "valid" : "invalid — this model may need a different output format"}.`);
123
+ } catch (err) { setLastTest(null); setMessage(""); setError(err.message); } finally { setTestingProvider(false); }
124
+ }
125
+ function addProvider() {
126
+ if (!model.trim() || !apiKey.trim()) { setError("Enter a model and API key first."); return; }
127
+ const item = providerDraft();
128
+ const freshTest = lastTest?.fingerprint === JSON.stringify(item) ? lastTest : null;
129
+ if (freshTest) item.lastTest = {at:freshTest.at,latency_ms:freshTest.latency_ms,json_valid:freshTest.json_valid};
130
+ const previous = savedProviders.find(entry => entry.name === editingProvider);
131
+ if (!freshTest && previous && previous.provider === item.provider && previous.model === item.model && previous.apiKey === item.apiKey && (previous.baseUrl || "") === item.baseUrl) item.lastTest = previous.lastTest;
132
+ try {
133
+ saveEntries(upsertProvider(savedProviders,item,editingProvider));
134
+ if (editingProvider && defaultProvider === editingProvider) { localStorage.setItem("ocr-default-provider",item.name); setDefaultProvider(item.name); }
135
+ setEditingProvider(item.name); setEndpoint(`saved:${item.name}`); setError(""); setMessage(`${item.name} saved. Select it in Review.`);
136
+ } catch { setMessage(""); setError("Browser storage is unavailable. Provider could not be saved."); }
137
+ }
138
+ async function saveFeedback(index,label) {
139
+ if (!job?.id) return;
140
+ setFeedbackBusy(index); setError("");
141
+ try {
142
+ const response = await fetch(apiUrl(`/api/reviews/${job.id}/feedback`), {method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({finding_index:index,label})});
143
+ const result = await response.json();
144
+ if (!response.ok) throw new Error(result.detail || "Could not save feedback.");
145
+ setJob(current => current?.id === job.id ? {...current,feedback:result.feedback} : current);
146
+ } catch(err) { setError(err.message); } finally { setFeedbackBusy(null); }
147
+ }
148
+ async function startReview(e) {
149
+ e.preventDefault(); setError("");
150
+ if (!/^[-\w.]+\/[-\w.]+$/.test(repo.trim()) || !Number.isInteger(Number(pr)) || Number(pr) < 1) { setError("Enter a repository as owner/name and a valid PR number."); return; }
151
+ setBusy(true); setJob(null); setMessage("Queueing review…");
152
+ try {
153
+ const response = await fetch(apiUrl("/api/reviews"), { method: "POST", credentials: "include", headers: { "Content-Type": "application/json" }, body: JSON.stringify(reviewPayload(repo, pr, endpoint, savedProviders, reviewMode, baselineSha)) });
154
+ const data = await response.json().catch(() => ({}));
155
+ if (!response.ok) throw new Error(data.detail || `Request failed (${response.status})`);
156
+ setJob(data); setMessage(data.cache_hit ? "Previous review reused for this exact commit and configuration." : data.reused ? "An existing review is already running. Following its progress." : "Review queued. Findings appear as reviewers finish.");
157
+ } catch (err) { setError(err.message); } finally { setBusy(false); }
158
+ }
159
+ async function cancelReview() {
160
+ if (!job?.id) return;
161
+ setBusy(true); setError("");
162
+ try {
163
+ const response = await fetch(apiUrl(`/api/reviews/${job.id}/cancel`), { method: "POST", credentials: "include" });
164
+ const data = await response.json().catch(() => ({}));
165
+ if (!response.ok) throw new Error(data.detail || "Could not cancel review.");
166
+ setJob(data); setMessage("Cancellation requested. A model call already in progress may finish before the worker stops.");
167
+ } catch (err) { setError(err.message); } finally { setBusy(false); }
168
+ }
169
+ async function decide(action) { if (!job?.id) return; setBusy(true); setError(""); setMessage(action === "approve" ? "Posting approved review…" : "Rejecting review…"); try { const r = await fetch(apiUrl(`/api/reviews/${job.id}/decision`), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action }) }); const data = await r.json().catch(() => ({})); if (!r.ok) throw new Error(data.detail || `Decision failed (${r.status})`); setJob(data); setMessage(action === "approve" ? "Review delivery finished." : "Review rejected. Nothing was posted to GitHub."); } catch (e) { setError(e.message); } finally { setBusy(false); } }
170
+ return <div className="shell"><header className="topbar"><div className="brand"><span className="brand-mark">OC</span><span>OpenCodeReview</span></div><div>{user ? <><span className="status-dot">Signed in as {user.login}</span><button className="auth-button" onClick={logout}>Sign out</button></> : <a className="status-dot" href={`${API_BASE}/api/auth/github/start`}>Sign in with GitHub</a>}<span className="status-dot">Human approval required</span><button className="theme-toggle" type="button" onClick={() => setTheme(theme === "dark" ? "light" : "dark")} aria-label="Toggle color theme">{theme === "dark" ? "Light" : "Dark"}</button></div></header><main className="content"><section className="hero"><p className="eyebrow">Pull request intelligence</p><h1>Review changes with<br /><em>evidence before action.</em></h1><p className="lede">Parallel analysis for correctness, security, and test coverage. Nothing is posted to GitHub until you approve it.</p></section><section className="intro-band"><div className="intro-copy"><p className="eyebrow">AI code review with a human checkpoint</p><h2>Know what changed<br /><em>before it ships.</em></h2><p>OpenCodeReview traces pull requests back to the diff, checks correctness and security, then gives you the evidence to decide what reaches GitHub.</p><div className="intro-actions"><a className="primary-link" href={user ? "#new-review" : `${API_BASE}/api/auth/github/start`}>Start a review <span>&rarr;</span></a><a className="quiet-link" href="#how-it-works">See how it works</a></div></div><div className="review-preview" aria-label="Review workflow preview"><div className="preview-top"><span className="live-dot"></span><span>REVIEW PIPELINE</span><span className="preview-time">LIVE</span></div><div className="preview-row"><strong>01</strong><span><b>Read the diff</b><small>Files, lines, and context</small></span><i>done</i></div><div className="preview-row"><strong>02</strong><span><b>Cross-check findings</b><small>Evidence, severity, confidence</small></span><i>done</i></div><div className="preview-row active"><strong>03</strong><span><b>Your decision</b><small>Approve, reject, or inspect</small></span><i>waiting</i></div></div></section><section className="trust-strip" id="how-it-works"><div><strong>Evidence first</strong><span>Every finding points to code.</span></div><div><strong>Human controlled</strong><span>Nothing posts without approval.</span></div><div><strong>Focused review</strong><span>Correctness, security, and test coverage.</span></div></section>{user ? <section className="workspace" id="new-review"><nav className="workspace-tabs" aria-label="Workspace"><button type="button" className={activeTab === "review" ? "active" : ""} onClick={() => { setActiveTab("review"); setError(""); setMessage(""); }}>Review</button><button type="button" className={activeTab === "providers" ? "active" : ""} onClick={() => { setActiveTab("providers"); setError(""); setMessage(""); }}>Providers</button></nav>{activeTab === "providers" && <section className="panel provider-manager" id="providers"><div className="panel-kicker">Provider library</div><h2>Saved providers</h2><p className="provider-hint">Keep your model connections ready for future reviews.</p>{savedProviders.length ? <div className="saved-provider-list">{savedProviders.map(item => <div className="saved-provider" key={item.name}><div className="provider-entry-title"><strong>{item.name}</strong>{defaultProvider === item.name && <span className="pill">Default</span>}</div><small>{item.baseUrl || "Default API endpoint"}</small><small>{item.lastTest ? `Last successful connection: ${new Date(item.lastTest.at).toLocaleString()} · ${(Number(item.lastTest.latency_ms) / 1000).toFixed(1)}s · JSON ${item.lastTest.json_valid ? "valid" : "invalid"}` : "Connection has not been tested"}</small><div className="provider-entry-actions"><button type="button" onClick={() => editProvider(item)} aria-label={`Edit ${item.name}`}>Edit</button><button type="button" onClick={() => makeDefault(item)} disabled={defaultProvider === item.name} aria-label={`Make ${item.name} default`}>Make default</button><button type="button" onClick={() => removeProvider(item)} aria-label={`Delete ${item.name}`}>Delete</button></div></div>)}</div> : <p className="provider-hint">No providers saved yet.</p>}<div className="provider-form-heading"><h3>{editingProvider ? "Edit provider" : "Add a provider"}</h3>{editingProvider && <button type="button" onClick={resetProviderDraft}>New provider</button>}</div><p className="provider-hint">Saved on this browser. Keys are hidden from the list and sent only when a provider is tested or used.</p><label htmlFor="provider-manager-type">Provider type<select id="provider-manager-type" value={provider || "openai"} onChange={e => setProvider(e.target.value)}><option value="openai">OpenAI-compatible</option><option value="anthropic">Anthropic</option><option value="google">Google</option></select></label><label htmlFor="provider-manager-model">Model<input id="provider-manager-model" value={model} onChange={e => setModel(e.target.value)} placeholder="model-name" /></label><label htmlFor="provider-manager-key">API key<input id="provider-manager-key" type="password" value={apiKey} onChange={e => setApiKey(e.target.value)} placeholder="Used for reviews" /></label><label htmlFor="provider-manager-base">Base URL <span>(optional)</span><input id="provider-manager-base" value={baseUrl} onChange={e => setBaseUrl(e.target.value)} placeholder="https://api.example.com/v1" /></label><div className="provider-actions"><button type="button" onClick={testProvider} disabled={testingProvider}>{testingProvider ? "Testing…" : "Test speed & JSON"}</button><button type="button" onClick={addProvider}>{editingProvider ? "Save changes" : "Add provider"}<span>+</span></button></div>{(error || message) && <div className={`message ${error ? "error" : "success"}`} role="status" aria-live="polite">{error || message}</div>}</section>}<form className={`panel form-panel ${activeTab === "providers" ? "is-hidden" : ""}`} onSubmit={startReview} aria-busy={busy}><div className="panel-kicker">New review</div><h2>Inspect a pull request</h2><label htmlFor="repo">Repository<input id="repo" value={repo} onChange={e => setRepo(e.target.value)} placeholder="owner/repository" autoComplete="off" /></label><label htmlFor="pr">Pull request<input id="pr" value={pr} onChange={e => setPr(e.target.value)} placeholder="42" inputMode="numeric" /></label><label htmlFor="endpoint">Provider<select id="endpoint" value={endpoint} onChange={e => setEndpoint(e.target.value)}><option value="auto">Automatic fallback</option><option value="cloudflare">Cloudflare GLM 4.7 Flash</option><option value="gemini">Gemini</option><option value="groq">Groq</option>{savedProviders.map(item => <option key={item.name} value={`saved:${item.name}`}>{item.name}</option>)}</select></label><fieldset className="review-mode"><legend>Review depth</legend><label><input type="radio" name="review-mode" value="fast" checked={reviewMode === "fast"} onChange={() => setReviewMode("fast")} />Fast<span>Smaller prompts and response budget</span></label><label><input type="radio" name="review-mode" value="thorough" checked={reviewMode === "thorough"} onChange={() => setReviewMode("thorough")} />Thorough<span>More context and analysis</span></label></fieldset><details className="incremental-options"><summary>Review only changes since a commit</summary><label htmlFor="baseline-sha">Previously reviewed commit SHA<input id="baseline-sha" value={baselineSha} onChange={e => setBaselineSha(e.target.value)} placeholder="40-character commit SHA (optional)" pattern="[a-fA-F0-9]{40}" autoComplete="off" /></label><p className="provider-hint">When set, this reviews only changes since that commit, not the whole pull request.</p></details><button type="submit" disabled={busy}>{busy && !job ? "Queueing review…" : "Start review"}<span aria-hidden="true">↗</span></button>{(error || message) && <div className={`message ${error ? "error" : "success"}`} role="status" aria-live="polite">{error || message}</div>}{job && <div className="job-card"><div><strong>Review {job.id?.slice(0, 8)}</strong><small>{job.repo} · PR #{job.pr_number}</small></div><span className={`pill ${job.status}`}>{pretty(job.status)}</span></div>}{job && !isTerminal && <div className="progress" role="progressbar" aria-label={`Review ${pretty(job.status)}`}><span /><small>{job.queue_position ? `Queue position: ${job.queue_position}` : `Current stage: ${pretty(job.progress?.stage || job.status)}`}</small><button type="button" className="secondary" onClick={cancelReview} disabled={busy}>Cancel review</button></div>}<div className="results"><ReviewProgress job={job} /><Verdict job={job} /><Coverage coverage={job?.review_coverage || job?.coverage} />{job?.findings?.length > 0 && <Findings findings={job.findings} feedback={job.feedback} onFeedback={isTerminal ? saveFeedback : undefined} feedbackBusy={feedbackBusy} />}{job?.status === "awaiting_approval" && job?.findings?.length === 0 && <Findings findings={[]} />}{job?.status === "awaiting_approval" && <div className="actions"><button type="button" onClick={() => decide("approve")} disabled={busy}>Approve &amp; post</button><button type="button" className="secondary" onClick={() => decide("reject")} disabled={busy}>Reject</button></div>}<Receipt result={job?.posting_result} />{job?.error && <div className="error detail">{job.error}</div>}</div></form><aside className={`panel signal-panel ${activeTab === "providers" ? "is-hidden" : ""}`}><div className="panel-kicker">What you receive</div><div className="signal"><strong>01</strong><span><b>Evidence-grounded findings</b><small>Code locations, severity, and confidence</small></span></div><div className="signal"><strong>02</strong><span><b>Human checkpoint</b><small>Approve or reject before GitHub comments</small></span></div><div className="signal"><strong>03</strong><span><b>Delivery receipt</b><small>See exactly what reached GitHub</small></span></div></aside></section> : <section className="auth-wall"><p className="eyebrow">Private review workspace</p><h2>Sign in to inspect a pull request.</h2><p>Your GitHub identity keeps reviews tied to your account and protects the review results.</p><a className="primary-link" href={`${API_BASE}/api/auth/github/start`}>Continue with GitHub <span>&rarr;</span></a></section>}</main><footer>OpenCodeReview <span>·</span> React review workspace <span>·</span> Saved keys stay in this browser</footer></div>;
171
+ }
172
+ createRoot(document.getElementById("root")).render(<App />);
173
+
174
+
175
+
176
+
177
+
178
+
179
+
180
+
181
+
182
+
183
+
184
+
185
+
186
+
187
+
188
+
189
+
frontend/src/styles.css CHANGED
@@ -1,48 +1,48 @@
1
- @import url('https://fonts.googleapis.com/css2?family=DM+Mono:wght@400;500&family=Manrope:wght@400;500;600;700;800&display=swap');
2
- :root{font-family:Manrope,system-ui,sans-serif;color:#e8e9e5;background:#111311;font-synthesis:none;--line:#30352f;--muted:#949a91;--lime:#c7f36b}
3
- *{box-sizing:border-box}body{margin:0;min-width:320px;background:radial-gradient(circle at 78% 4%,#273320 0,#111311 34rem);min-height:100vh}.shell{min-height:100vh;display:flex;flex-direction:column}.topbar{height:76px;padding:0 clamp(20px,5vw,76px);display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--line)}.brand{display:flex;gap:12px;align-items:center;font-weight:700;letter-spacing:-.03em}.brand-mark{display:grid;place-items:center;width:31px;height:31px;border:1px solid var(--lime);color:var(--lime);font:500 11px 'DM Mono',monospace}.status-dot{font:500 11px 'DM Mono',monospace;color:var(--muted);text-transform:uppercase;letter-spacing:.08em}.status-dot:before{content:'';display:inline-block;width:7px;height:7px;margin-right:8px;border-radius:50%;background:var(--lime);box-shadow:0 0 14px var(--lime)}.content{width:min(1180px,calc(100% - 40px));margin:auto;padding:clamp(70px,10vw,140px) 0 80px}.eyebrow,.panel-kicker{font:500 11px 'DM Mono',monospace;letter-spacing:.12em;text-transform:uppercase;color:var(--lime)}h1{margin:18px 0 24px;font-size:clamp(48px,7vw,92px);line-height:.98;letter-spacing:-.075em;max-width:840px}h1 em{font-style:normal;color:var(--muted)}.lede{max-width:510px;color:var(--muted);line-height:1.7;font-size:16px}.workspace{display:grid;grid-template-columns:minmax(0,1.1fr) minmax(280px,.9fr);gap:20px;margin-top:78px}.panel{border:1px solid var(--line);background:#161a15cc;backdrop-filter:blur(16px);padding:30px}.form-panel h2{margin:10px 0 28px;font-size:25px;letter-spacing:-.04em}label{display:grid;gap:9px;margin:18px 0;font:500 12px 'DM Mono',monospace;color:var(--muted);text-transform:uppercase;letter-spacing:.06em}input,select{width:100%;border:1px solid #3b4438;background:#10130f;color:#eef2e7;padding:14px 15px;font:500 15px Manrope;outline:none}input:focus,select:focus{border-color:var(--lime);box-shadow:0 0 0 3px #c7f36b18}button{width:100%;margin-top:12px;border:0;background:var(--lime);color:#11170d;padding:15px 18px;font-weight:800;font-size:14px;cursor:pointer;display:flex;justify-content:space-between}button:hover{background:#d9ff8d}button:disabled{opacity:.6;cursor:wait}.message{font-size:13px;line-height:1.5;margin:17px 0 0}.message.error{color:#ff9f8d}.message.queued{color:var(--lime)}.signal-panel{display:flex;flex-direction:column;gap:25px}.signal{display:grid;grid-template-columns:35px 1fr;gap:14px;padding-top:21px;border-top:1px solid var(--line)}.signal strong{font:500 12px 'DM Mono',monospace;color:var(--lime)}.signal b{display:block;font-size:14px}.signal small{display:block;color:var(--muted);line-height:1.5;margin-top:5px}footer{padding:24px clamp(20px,5vw,76px);border-top:1px solid var(--line);color:var(--muted);font:11px 'DM Mono',monospace}footer span{color:var(--lime);padding:0 8px}@media(max-width:760px){.topbar{height:64px}.status-dot{display:none}.content{padding-top:70px}.workspace{grid-template-columns:1fr;margin-top:55px}h1{font-size:54px}}
4
- .job-card,.result-card,.finding{margin-top:14px;border:1px solid rgba(255,255,255,.12);border-radius:14px;padding:14px;background:rgba(255,255,255,.04)}
5
- .job-card{display:flex;justify-content:space-between;align-items:center;font-size:.85rem}.pill,.severity,.category{font-size:.72rem;text-transform:uppercase;letter-spacing:.08em;border-radius:999px;padding:4px 8px;background:rgba(255,255,255,.1)}
6
- .result-title{display:flex;justify-content:space-between;align-items:flex-start;color:#d6ff70}.result-title h3{margin:5px 0 0;font-size:1.1rem}.score{font-size:1.35rem}.result-card p{margin:10px 0;color:#c1c8bc;line-height:1.55}.verdict{border-left:3px solid #c7f36b}.verdict.blocking{border-left-color:#ff9f8d}.metrics{display:flex;gap:14px;flex-wrap:wrap;color:#949a91;font:11px 'DM Mono',monospace;text-transform:uppercase}.section-heading{display:flex;justify-content:space-between;align-items:center;margin-top:22px}.section-heading h3{margin:0;font-size:1rem}.section-heading span{color:#c7f36b;font:12px 'DM Mono',monospace}.finding{background:rgba(255,255,255,.025)}.finding-meta{display:flex;gap:8px;align-items:center;flex-wrap:wrap;margin-bottom:8px}.finding-location{margin-left:auto;color:#c7f36b;font:11px 'DM Mono',monospace}.severity{color:#ffb3a7}.severity.low,.severity.info{color:#c7f36b}.category{color:#c0c8ba}.finding p{margin:8px 0;color:#c1c8bc;line-height:1.45}.finding small,.result-card small,.job-card small{display:block;color:#949a91;margin-top:6px}.job-card small{font-size:.72rem}.actions{display:flex;gap:10px;margin-top:14px}.actions button{margin:0}.actions .secondary{background:transparent;border:1px solid rgba(255,255,255,.2);color:#e8e9e5}.message{border-radius:10px;padding:11px 13px;margin-top:14px;font-size:13px;line-height:1.45}.message.success{color:#c7f36b;background:#c7f36b12}.message.error,.error.detail{color:#ff9f8d;background:#ff9f8d12}.progress{margin-top:15px;padding:12px;border:1px solid #30352f;border-radius:10px;color:#949a91}.progress span{display:block;height:3px;background:linear-gradient(90deg,transparent,#c7f36b,transparent);background-size:200% 100%;animation:load 1.4s linear infinite}.progress small{display:block;margin-top:8px}.empty-result{margin-top:14px;border:1px dashed #3b4438;padding:16px;color:#949a91;display:grid;gap:5px}.empty-result strong{color:#c7f36b}@keyframes load{to{background-position:-200% 0}}
7
-
8
- .intro-band{display:grid;grid-template-columns:minmax(0,1.1fr) minmax(320px,.9fr);gap:clamp(2rem,7vw,7rem);align-items:end;padding:clamp(3.5rem,9vw,8rem) 0 3.5rem;border-bottom:1px solid var(--line)}
9
- .intro-copy h2{max-width:780px;margin:.8rem 0 1.4rem;font-size:clamp(3.5rem,8vw,7.6rem);line-height:.9;letter-spacing:-.075em}.intro-copy h2 em{color:var(--accent);font-style:normal}.intro-copy>p:not(.eyebrow){max-width:560px;color:var(--muted);font-size:1.08rem;line-height:1.65}.intro-actions{display:flex;gap:1.2rem;align-items:center;margin-top:2rem}.primary-link,.quiet-link{font-size:.82rem;text-transform:uppercase;letter-spacing:.12em;text-decoration:none}.primary-link{background:var(--accent);color:var(--ink);padding:.95rem 1.2rem;font-weight:700}.primary-link span{margin-left:.8rem}.quiet-link{color:var(--muted);border-bottom:1px solid var(--line);padding-bottom:.35rem}.review-preview{border:1px solid var(--line);background:rgba(255,255,255,.035);padding:1.2rem;box-shadow:18px 18px 0 rgba(255,255,255,.025)}.preview-top{display:flex;gap:.55rem;align-items:center;border-bottom:1px solid var(--line);padding-bottom:.9rem;font-size:.68rem;letter-spacing:.14em;color:var(--muted)}.preview-time{margin-left:auto;color:var(--accent)}.live-dot{width:7px;height:7px;border-radius:50%;background:var(--accent);box-shadow:0 0 0 5px rgba(184,255,74,.12)}.preview-row{display:grid;grid-template-columns:2rem 1fr auto;gap:.8rem;align-items:center;padding:1.2rem 0;border-bottom:1px solid var(--line)}.preview-row:last-child{border-bottom:0}.preview-row>strong{color:var(--muted);font-size:.75rem}.preview-row b{display:block;font-size:.95rem}.preview-row small{display:block;color:var(--muted);margin-top:.25rem}.preview-row i{font-size:.65rem;text-transform:uppercase;color:var(--muted);font-style:normal}.preview-row.active{color:var(--accent)}.trust-strip{display:grid;grid-template-columns:repeat(3,1fr);gap:1rem;padding:2rem 0 3.5rem;border-bottom:1px solid var(--line)}.trust-strip div{display:flex;flex-direction:column;gap:.4rem}.trust-strip strong{text-transform:uppercase;letter-spacing:.1em;font-size:.72rem}.trust-strip span{color:var(--muted);font-size:.9rem}@media(max-width:800px){.intro-band{grid-template-columns:1fr;padding-top:3rem}.intro-copy h2{font-size:clamp(3.4rem,16vw,6rem)}.trust-strip{grid-template-columns:1fr}.intro-actions{flex-wrap:wrap}}
10
- .auth-wall{border:1px solid var(--line);padding:clamp(2rem,6vw,5rem);margin:2rem 0 4rem;background:rgba(255,255,255,.025)}.auth-wall h2{font-size:clamp(2rem,5vw,4rem);letter-spacing:-.06em;margin:.7rem 0 1rem}.auth-wall p:not(.eyebrow){max-width:520px;color:var(--muted);line-height:1.6;margin-bottom:2rem}
11
-
12
- /* Minimalist editorial skin */
13
- :root{font-family:'Helvetica Neue',Arial,sans-serif;color:#2f3437;background:#fbfbfa;--line:#eaeaea;--muted:#787774;--accent:#111111;--ink:#ffffff;--lime:#346538}
14
- body{background:#fbfbfa;color:#2f3437}.topbar{background:#fff;border-color:#eaeaea}.brand{color:#111}.brand-mark{border-color:#111;color:#111}.status-dot{color:#787774}.status-dot:before{background:#346538;box-shadow:none}.content{padding-top:clamp(56px,8vw,110px)}h1{font-family:Georgia,'Times New Roman',serif;font-weight:500;color:#111;letter-spacing:-.055em}h1 em{color:#787774}.eyebrow,.panel-kicker{color:#346538}.panel,.review-preview,.auth-wall{background:#fff;border-color:#eaeaea;backdrop-filter:none;box-shadow:none}.workspace{gap:24px}.form-panel h2{font-family:Georgia,'Times New Roman',serif;font-weight:500;color:#111}input,select{background:#fff;color:#2f3437;border-color:#eaeaea;border-radius:4px;font-family:'Helvetica Neue',Arial,sans-serif}input:focus,select:focus{border-color:#111;box-shadow:0 0 0 3px rgba(0,0,0,.05)}button,.primary-link{background:#111;color:#fff;border-radius:5px}.primary-link:hover,button:hover{background:#333}.quiet-link{color:#787774;border-color:#eaeaea}.signal-panel{background:#fff}.signal{border-color:#eaeaea}.signal strong{color:#346538}.job-card,.result-card,.finding{background:#fff;border-color:#eaeaea;border-radius:8px}.pill,.severity,.category{border-radius:999px;background:#edf3ec}.result-title{color:#346538}.result-card p,.finding p{color:#2f3437}.metrics,.finding small,.result-card small,.job-card small{color:#787774}.finding-location{color:#346538}.finding{box-shadow:none}.progress{border-color:#eaeaea;border-radius:8px}.progress span{background:#346538;animation:none}.intro-copy h2,.auth-wall h2{font-family:Georgia,'Times New Roman',serif;font-weight:500;color:#111;line-height:1.02}.intro-copy h2 em{color:#787774}.review-preview{box-shadow:none}.preview-top{border-color:#eaeaea}.live-dot{background:#346538;box-shadow:none}.preview-row{border-color:#eaeaea}.preview-row.active{color:#346538}.trust-strip{border-color:#eaeaea}.trust-strip strong{color:#111}.auth-button{width:auto;margin:0;padding:0;background:transparent;color:#787774;font:500 11px 'DM Mono',monospace;text-transform:uppercase;letter-spacing:.08em}.auth-button:hover{background:transparent;color:#111}footer{border-color:#eaeaea;color:#787774}
15
-
16
- /* Friendly canvas: soft sage tint with warm white reading surfaces */
17
- :root{background:#f3f7f4}body{background:#f3f7f4}.topbar,.panel,.review-preview,.auth-wall{background:#fffdf9}.content{background:transparent}
18
-
19
- /* Powder-blue canvas for stronger separation from white surfaces */
20
- :root{background:#dfeaf1}body{background:#dfeaf1}.topbar{background:#eaf2f6}.panel,.review-preview,.auth-wall{background:#f8fbfc}
21
-
22
- .theme-toggle{width:auto;margin:0 0 0 14px;padding:7px 10px;background:transparent;color:#2f3437;border:1px solid #cbd7dd;border-radius:4px;font:500 10px 'DM Mono',monospace;text-transform:uppercase;letter-spacing:.08em}.theme-toggle:hover{background:#fff;color:#111}
23
- :root[data-theme="dark"]{background:#11151a;color:#e8edf0;--line:#303840;--muted:#9ca8b0;--accent:#f0f4f5;--ink:#11151a}html[data-theme="dark"] body{background:#11151a;color:#e8edf0}html[data-theme="dark"] .topbar{background:#151b21;border-color:#303840}.dark .brand,html[data-theme="dark"] .brand{color:#f4f7f8}html[data-theme="dark"] .brand-mark{border-color:#e8edf0;color:#e8edf0}html[data-theme="dark"] .panel,html[data-theme="dark"] .review-preview,html[data-theme="dark"] .auth-wall{background:#182027;border-color:#303840}html[data-theme="dark"] h1,html[data-theme="dark"] .intro-copy h2,html[data-theme="dark"] .auth-wall h2,html[data-theme="dark"] .form-panel h2{color:#f4f7f8}html[data-theme="dark"] input,html[data-theme="dark"] select{background:#11171c;color:#e8edf0;border-color:#3b4650}html[data-theme="dark"] .theme-toggle{color:#e8edf0;border-color:#53616b}html[data-theme="dark"] .theme-toggle:hover{background:#2a333b}html[data-theme="dark"] .primary-link,html[data-theme="dark"] button:not(.theme-toggle){background:#f0f4f5;color:#11151a}html[data-theme="dark"] .job-card,html[data-theme="dark"] .result-card,html[data-theme="dark"] .finding{background:#182027;border-color:#303840}html[data-theme="dark"] footer{border-color:#303840}
24
-
25
- /* Premium header treatment */
26
- .topbar{position:sticky;top:0;z-index:10;height:72px;padding:0 clamp(24px,6vw,88px);background:rgba(234,242,246,.88);backdrop-filter:blur(14px);border-bottom:1px solid rgba(47,52,55,.1)}.brand{gap:11px;font-size:15px;letter-spacing:-.04em}.brand-mark{width:34px;height:34px;border-radius:8px;background:#111;color:#fff;border:0;font:600 10px 'DM Mono',monospace;letter-spacing:.05em}.topbar>div:last-child{display:flex;align-items:center;gap:16px}.topbar .status-dot:last-of-type{padding-left:16px;border-left:1px solid rgba(47,52,55,.14)}.topbar .status-dot:before{width:6px;height:6px}.theme-toggle{margin-left:2px;padding:8px 12px;border-color:rgba(47,52,55,.18);background:rgba(255,255,255,.55)}.theme-toggle:hover{background:#fff;transform:translateY(-1px)}html[data-theme="dark"] .topbar{background:rgba(21,27,33,.9);border-color:rgba(255,255,255,.1)}html[data-theme="dark"] .brand-mark{background:#f0f4f5;color:#11151a}html[data-theme="dark"] .topbar .status-dot:last-of-type{border-color:rgba(255,255,255,.14)}
27
-
28
- @media(max-width:760px){.topbar{height:64px;padding:0 16px}.topbar>div:last-child{gap:8px;min-width:0}.topbar .status-dot{display:inline-block;max-width:92px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:9px}.topbar .status-dot:last-of-type{display:none}.topbar .status-dot:before{margin-right:5px}.brand{font-size:13px;gap:8px}.brand-mark{width:30px;height:30px}.theme-toggle{font-size:9px;padding:7px 9px;margin-left:0}.content{width:min(100% - 32px,1180px);padding-top:46px}.intro-band{gap:2.5rem;padding-bottom:2.5rem}.intro-copy>p:not(.eyebrow){font-size:1rem}.review-preview{padding:1rem}.trust-strip{padding-bottom:2.5rem}.auth-wall{padding:2rem 1.25rem}}
29
-
30
- .score-block{display:flex;flex-direction:column;align-items:flex-end;gap:3px}.score-block>span{font:500 10px 'DM Mono',monospace;text-transform:uppercase;letter-spacing:.06em;color:#9f2f2d}.score-explanation{display:grid;gap:4px;margin:14px 0;padding:12px 14px;border-radius:6px;background:#fbf3db;color:#956400;font-size:13px;line-height:1.45}.score-explanation strong{font-size:11px;text-transform:uppercase;letter-spacing:.08em}.verdict-summary{font-size:15px!important}.verdict.approved .score-block>span{color:#346538}.verdict.approved .score-explanation{background:#edf3ec;color:#346538}
31
-
32
- /* Result readability */
33
- .result-card{color:#2f3437}.result-card h3,.result-card .panel-kicker,.section-heading h3{color:#111}.verdict.blocking{border-left:4px solid #9f2f2d;background:#fff8f8}.verdict.blocking .score-block>span{color:#9f2f2d}.verdict.approved{border-left:4px solid #346538;background:#f7fbf7}.score{color:#111}.score-explanation{border:1px solid #f0dfad}.finding-meta .severity{font-weight:700}.finding-location{color:#1f6c9f!important}.finding p{color:#2f3437!important}.finding small{color:#5f6669!important}.receipt{background:#f9fbfc}.receipt .panel-kicker{color:#1f6c9f}html[data-theme="dark"] .result-card{color:#e8edf0}html[data-theme="dark"] .result-card h3,html[data-theme="dark"] .result-card .panel-kicker,html[data-theme="dark"] .section-heading h3,html[data-theme="dark"] .score{color:#f4f7f8}.verdict.blocking{background:#291c1e}.verdict.approved{background:#18241d}.score-explanation{background:#332c1c;color:#f2d98c;border-color:#66562c}.finding p{color:#e8edf0!important}.finding small{color:#aeb9bf!important}.finding-location{color:#8ec9ef!important}
34
-
35
- html[data-theme="dark"] .finding p,html[data-theme="dark"] .result-card p{color:#e8edf0!important}html[data-theme="dark"] .finding small{color:#c1cbd1!important}html[data-theme="dark"] .finding-location{color:#9bd4f5!important}
36
-
37
- /* Final theme scoping for verdict surfaces */
38
- html:not([data-theme="dark"]) .verdict.blocking{background:#fff8f8;color:#2f3437}html:not([data-theme="dark"]) .verdict.approved{background:#f7fbf7;color:#2f3437}html:not([data-theme="dark"]) .score-explanation{background:#fbf3db;color:#956400;border-color:#f0dfad}html:not([data-theme="dark"]) .finding p{color:#2f3437!important}html:not([data-theme="dark"]) .finding small{color:#5f6669!important}html[data-theme="dark"] .verdict.blocking{background:#291c1e;color:#e8edf0}html[data-theme="dark"] .verdict.approved{background:#18241d;color:#e8edf0}html[data-theme="dark"] .score-explanation{background:#332c1c;color:#f2d98c;border-color:#66562c}
39
- .provider-use{width:100%;margin:10px 0 4px;padding:11px 12px;background:#edf3ec;color:#346538;border:1px solid #cfe1d0;border-radius:5px;font:600 11px 'DM Mono',monospace;text-transform:uppercase;letter-spacing:.04em}.provider-use:hover{background:#dfeee0;color:#234d28}.provider-use span{font-size:14px}html[data-theme="dark"] .provider-use{background:#203325;color:#b9e3bd;border-color:#3e6042}html[data-theme="dark"] .provider-use:hover{background:#2b4430}
40
-
41
- .is-hidden{display:none!important}.workspace-tabs{display:flex;gap:8px;margin-bottom:14px}.workspace-tabs button{background:transparent;border:1px solid var(--line);padding:9px 14px;border-radius:6px;color:var(--muted);cursor:pointer}.workspace-tabs button.active{background:var(--ink);color:var(--paper)}.provider-manager{margin-bottom:16px}.saved-provider-list{display:grid;gap:8px;margin:16px 0}.saved-provider{border:1px solid var(--line);padding:12px;border-radius:6px;display:flex;flex-direction:column;gap:4px}.saved-provider small{color:var(--muted)}
42
-
43
- .workspace-tabs{grid-column:1/-1;align-self:start;height:auto}.workspace-tabs button{width:auto;margin:0;display:inline-flex;justify-content:center}.provider-manager{grid-column:1/-1}
44
-
45
- .provider-actions{display:flex;gap:10px;margin-top:12px}.provider-actions button{width:auto;flex:1;margin:0}.provider-actions button:first-child{background:transparent;border:1px solid var(--line);color:var(--muted)}
46
-
47
- .review-mode{border:1px solid var(--line);border-radius:6px;padding:12px;margin:20px 0;display:grid;gap:10px}.review-mode legend{font-size:12px;color:var(--muted);padding:0 6px}.review-mode label{display:grid;grid-template-columns:20px 1fr;gap:6px;margin:0;text-transform:none;letter-spacing:0;font:600 14px Arial,sans-serif;color:inherit}.review-mode input{width:16px;height:16px;margin:0;grid-row:1/3;box-shadow:none}.review-mode label span{grid-column:2;font-size:12px;font-weight:400;color:var(--muted)}.review-progress{margin:16px 0}.reviewer-stages{padding:0;list-style:none;display:grid;gap:8px}.reviewer-stages li{border:1px solid var(--line);padding:10px;display:grid;gap:5px;border-radius:6px}.reviewer-stages small,.reviewer-stages span{color:var(--muted);overflow-wrap:anywhere}.reviewer-stages .reviewer-error{color:#b74335}html[data-theme="dark"] .reviewer-stages .reviewer-error{color:#ffb4a9}.review-progress details{margin:14px 0;color:var(--muted);font-size:12px}.review-progress summary{cursor:pointer}.progress button{width:auto;font-size:12px;padding:8px 12px}.provider-actions button:disabled{cursor:wait;opacity:.6}
48
- .finding-group{margin-top:24px}.finding-group h4{font-size:15px;display:flex;gap:8px;align-items:center}.finding-group h4 span{font-size:12px;color:var(--muted)}.evidence-label{display:inline-block;font-size:11px;line-height:1.6;margin:6px 0;color:#42614a}.evidence-label.uncertain{color:#855c20}.evidence-excerpt{white-space:pre-wrap;overflow-wrap:anywhere;font:12px/1.65 'DM Mono',monospace;max-height:280px;overflow:auto;padding:12px;border:1px solid var(--line);border-radius:5px}.calibration-note{font-size:12px!important;color:var(--muted)!important}.finding-feedback{display:flex;gap:7px;align-items:center;flex-wrap:wrap;margin-top:14px;padding-top:12px;border-top:1px solid var(--line)}.finding-feedback>span{font-size:12px;color:var(--muted)}.finding-feedback button,.provider-entry-actions button,.provider-form-heading button{width:auto;margin:0;padding:7px 11px;display:inline-flex;justify-content:center;border:1px solid var(--line);font-size:12px;font-weight:500;background:transparent;color:inherit}.finding-feedback button[aria-pressed="true"]{background:#dbe8dc;border-color:#799b7c;color:#24482b}.finding-feedback small{width:100%}.provider-entry-title,.provider-form-heading{display:flex;gap:10px;justify-content:space-between;align-items:center;flex-wrap:wrap}.provider-entry-actions{display:flex;gap:8px;flex-wrap:wrap;margin-top:10px}.provider-form-heading{margin-top:28px}.provider-form-heading h3{margin:0}.provider-entry-actions button:disabled{opacity:.5;cursor:default}.review-coverage{overflow-wrap:anywhere}.review-coverage ul{padding-left:18px;font-size:13px;line-height:1.7}html[data-theme="dark"] .evidence-label{color:#b2d4b7}html[data-theme="dark"] .evidence-label.uncertain{color:#e4c48c}html[data-theme="dark"] .finding-feedback button,html[data-theme="dark"] .provider-entry-actions button,html[data-theme="dark"] .provider-form-heading button{background:transparent;color:#e8edf0}html[data-theme="dark"] .finding-feedback button[aria-pressed="true"]{background:#294334;color:#d4edda;border-color:#759b7e}
 
1
+ @import url('https://fonts.googleapis.com/css2?family=DM+Mono:wght@400;500&family=Manrope:wght@400;500;600;700;800&display=swap');
2
+ :root{font-family:Manrope,system-ui,sans-serif;color:#e8e9e5;background:#111311;font-synthesis:none;--line:#30352f;--muted:#949a91;--lime:#c7f36b}
3
+ *{box-sizing:border-box}body{margin:0;min-width:320px;background:radial-gradient(circle at 78% 4%,#273320 0,#111311 34rem);min-height:100vh}.shell{min-height:100vh;display:flex;flex-direction:column}.topbar{height:76px;padding:0 clamp(20px,5vw,76px);display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--line)}.brand{display:flex;gap:12px;align-items:center;font-weight:700;letter-spacing:-.03em}.brand-mark{display:grid;place-items:center;width:31px;height:31px;border:1px solid var(--lime);color:var(--lime);font:500 11px 'DM Mono',monospace}.status-dot{font:500 11px 'DM Mono',monospace;color:var(--muted);text-transform:uppercase;letter-spacing:.08em}.status-dot:before{content:'';display:inline-block;width:7px;height:7px;margin-right:8px;border-radius:50%;background:var(--lime);box-shadow:0 0 14px var(--lime)}.content{width:min(1180px,calc(100% - 40px));margin:auto;padding:clamp(70px,10vw,140px) 0 80px}.eyebrow,.panel-kicker{font:500 11px 'DM Mono',monospace;letter-spacing:.12em;text-transform:uppercase;color:var(--lime)}h1{margin:18px 0 24px;font-size:clamp(48px,7vw,92px);line-height:.98;letter-spacing:-.075em;max-width:840px}h1 em{font-style:normal;color:var(--muted)}.lede{max-width:510px;color:var(--muted);line-height:1.7;font-size:16px}.workspace{display:grid;grid-template-columns:minmax(0,1.1fr) minmax(280px,.9fr);gap:20px;margin-top:78px}.panel{border:1px solid var(--line);background:#161a15cc;backdrop-filter:blur(16px);padding:30px}.form-panel h2{margin:10px 0 28px;font-size:25px;letter-spacing:-.04em}label{display:grid;gap:9px;margin:18px 0;font:500 12px 'DM Mono',monospace;color:var(--muted);text-transform:uppercase;letter-spacing:.06em}input,select{width:100%;border:1px solid #3b4438;background:#10130f;color:#eef2e7;padding:14px 15px;font:500 15px Manrope;outline:none}input:focus,select:focus{border-color:var(--lime);box-shadow:0 0 0 3px #c7f36b18}button{width:100%;margin-top:12px;border:0;background:var(--lime);color:#11170d;padding:15px 18px;font-weight:800;font-size:14px;cursor:pointer;display:flex;justify-content:space-between}button:hover{background:#d9ff8d}button:disabled{opacity:.6;cursor:wait}.message{font-size:13px;line-height:1.5;margin:17px 0 0}.message.error{color:#ff9f8d}.message.queued{color:var(--lime)}.signal-panel{display:flex;flex-direction:column;gap:25px}.signal{display:grid;grid-template-columns:35px 1fr;gap:14px;padding-top:21px;border-top:1px solid var(--line)}.signal strong{font:500 12px 'DM Mono',monospace;color:var(--lime)}.signal b{display:block;font-size:14px}.signal small{display:block;color:var(--muted);line-height:1.5;margin-top:5px}footer{padding:24px clamp(20px,5vw,76px);border-top:1px solid var(--line);color:var(--muted);font:11px 'DM Mono',monospace}footer span{color:var(--lime);padding:0 8px}@media(max-width:760px){.topbar{height:64px}.status-dot{display:none}.content{padding-top:70px}.workspace{grid-template-columns:1fr;margin-top:55px}h1{font-size:54px}}
4
+ .job-card,.result-card,.finding{margin-top:14px;border:1px solid rgba(255,255,255,.12);border-radius:14px;padding:14px;background:rgba(255,255,255,.04)}
5
+ .job-card{display:flex;justify-content:space-between;align-items:center;font-size:.85rem}.pill,.severity,.category{font-size:.72rem;text-transform:uppercase;letter-spacing:.08em;border-radius:999px;padding:4px 8px;background:rgba(255,255,255,.1)}
6
+ .result-title{display:flex;justify-content:space-between;align-items:flex-start;color:#d6ff70}.result-title h3{margin:5px 0 0;font-size:1.1rem}.score{font-size:1.35rem}.result-card p{margin:10px 0;color:#c1c8bc;line-height:1.55}.verdict{border-left:3px solid #c7f36b}.verdict.blocking{border-left-color:#ff9f8d}.metrics{display:flex;gap:14px;flex-wrap:wrap;color:#949a91;font:11px 'DM Mono',monospace;text-transform:uppercase}.section-heading{display:flex;justify-content:space-between;align-items:center;margin-top:22px}.section-heading h3{margin:0;font-size:1rem}.section-heading span{color:#c7f36b;font:12px 'DM Mono',monospace}.finding{background:rgba(255,255,255,.025)}.finding-meta{display:flex;gap:8px;align-items:center;flex-wrap:wrap;margin-bottom:8px}.finding-location{margin-left:auto;color:#c7f36b;font:11px 'DM Mono',monospace}.severity{color:#ffb3a7}.severity.low,.severity.info{color:#c7f36b}.category{color:#c0c8ba}.finding p{margin:8px 0;color:#c1c8bc;line-height:1.45}.finding small,.result-card small,.job-card small{display:block;color:#949a91;margin-top:6px}.job-card small{font-size:.72rem}.actions{display:flex;gap:10px;margin-top:14px}.actions button{margin:0}.actions .secondary{background:transparent;border:1px solid rgba(255,255,255,.2);color:#e8e9e5}.message{border-radius:10px;padding:11px 13px;margin-top:14px;font-size:13px;line-height:1.45}.message.success{color:#c7f36b;background:#c7f36b12}.message.error,.error.detail{color:#ff9f8d;background:#ff9f8d12}.progress{margin-top:15px;padding:12px;border:1px solid #30352f;border-radius:10px;color:#949a91}.progress span{display:block;height:3px;background:linear-gradient(90deg,transparent,#c7f36b,transparent);background-size:200% 100%;animation:load 1.4s linear infinite}.progress small{display:block;margin-top:8px}.empty-result{margin-top:14px;border:1px dashed #3b4438;padding:16px;color:#949a91;display:grid;gap:5px}.empty-result strong{color:#c7f36b}@keyframes load{to{background-position:-200% 0}}
7
+
8
+ .intro-band{display:grid;grid-template-columns:minmax(0,1.1fr) minmax(320px,.9fr);gap:clamp(2rem,7vw,7rem);align-items:end;padding:clamp(3.5rem,9vw,8rem) 0 3.5rem;border-bottom:1px solid var(--line)}
9
+ .intro-copy h2{max-width:780px;margin:.8rem 0 1.4rem;font-size:clamp(3.5rem,8vw,7.6rem);line-height:.9;letter-spacing:-.075em}.intro-copy h2 em{color:var(--accent);font-style:normal}.intro-copy>p:not(.eyebrow){max-width:560px;color:var(--muted);font-size:1.08rem;line-height:1.65}.intro-actions{display:flex;gap:1.2rem;align-items:center;margin-top:2rem}.primary-link,.quiet-link{font-size:.82rem;text-transform:uppercase;letter-spacing:.12em;text-decoration:none}.primary-link{background:var(--accent);color:var(--ink);padding:.95rem 1.2rem;font-weight:700}.primary-link span{margin-left:.8rem}.quiet-link{color:var(--muted);border-bottom:1px solid var(--line);padding-bottom:.35rem}.review-preview{border:1px solid var(--line);background:rgba(255,255,255,.035);padding:1.2rem;box-shadow:18px 18px 0 rgba(255,255,255,.025)}.preview-top{display:flex;gap:.55rem;align-items:center;border-bottom:1px solid var(--line);padding-bottom:.9rem;font-size:.68rem;letter-spacing:.14em;color:var(--muted)}.preview-time{margin-left:auto;color:var(--accent)}.live-dot{width:7px;height:7px;border-radius:50%;background:var(--accent);box-shadow:0 0 0 5px rgba(184,255,74,.12)}.preview-row{display:grid;grid-template-columns:2rem 1fr auto;gap:.8rem;align-items:center;padding:1.2rem 0;border-bottom:1px solid var(--line)}.preview-row:last-child{border-bottom:0}.preview-row>strong{color:var(--muted);font-size:.75rem}.preview-row b{display:block;font-size:.95rem}.preview-row small{display:block;color:var(--muted);margin-top:.25rem}.preview-row i{font-size:.65rem;text-transform:uppercase;color:var(--muted);font-style:normal}.preview-row.active{color:var(--accent)}.trust-strip{display:grid;grid-template-columns:repeat(3,1fr);gap:1rem;padding:2rem 0 3.5rem;border-bottom:1px solid var(--line)}.trust-strip div{display:flex;flex-direction:column;gap:.4rem}.trust-strip strong{text-transform:uppercase;letter-spacing:.1em;font-size:.72rem}.trust-strip span{color:var(--muted);font-size:.9rem}@media(max-width:800px){.intro-band{grid-template-columns:1fr;padding-top:3rem}.intro-copy h2{font-size:clamp(3.4rem,16vw,6rem)}.trust-strip{grid-template-columns:1fr}.intro-actions{flex-wrap:wrap}}
10
+ .auth-wall{border:1px solid var(--line);padding:clamp(2rem,6vw,5rem);margin:2rem 0 4rem;background:rgba(255,255,255,.025)}.auth-wall h2{font-size:clamp(2rem,5vw,4rem);letter-spacing:-.06em;margin:.7rem 0 1rem}.auth-wall p:not(.eyebrow){max-width:520px;color:var(--muted);line-height:1.6;margin-bottom:2rem}
11
+
12
+ /* Minimalist editorial skin */
13
+ :root{font-family:'Helvetica Neue',Arial,sans-serif;color:#2f3437;background:#fbfbfa;--line:#eaeaea;--muted:#787774;--accent:#111111;--ink:#ffffff;--lime:#346538}
14
+ body{background:#fbfbfa;color:#2f3437}.topbar{background:#fff;border-color:#eaeaea}.brand{color:#111}.brand-mark{border-color:#111;color:#111}.status-dot{color:#787774}.status-dot:before{background:#346538;box-shadow:none}.content{padding-top:clamp(56px,8vw,110px)}h1{font-family:Georgia,'Times New Roman',serif;font-weight:500;color:#111;letter-spacing:-.055em}h1 em{color:#787774}.eyebrow,.panel-kicker{color:#346538}.panel,.review-preview,.auth-wall{background:#fff;border-color:#eaeaea;backdrop-filter:none;box-shadow:none}.workspace{gap:24px}.form-panel h2{font-family:Georgia,'Times New Roman',serif;font-weight:500;color:#111}input,select{background:#fff;color:#2f3437;border-color:#eaeaea;border-radius:4px;font-family:'Helvetica Neue',Arial,sans-serif}input:focus,select:focus{border-color:#111;box-shadow:0 0 0 3px rgba(0,0,0,.05)}button,.primary-link{background:#111;color:#fff;border-radius:5px}.primary-link:hover,button:hover{background:#333}.quiet-link{color:#787774;border-color:#eaeaea}.signal-panel{background:#fff}.signal{border-color:#eaeaea}.signal strong{color:#346538}.job-card,.result-card,.finding{background:#fff;border-color:#eaeaea;border-radius:8px}.pill,.severity,.category{border-radius:999px;background:#edf3ec}.result-title{color:#346538}.result-card p,.finding p{color:#2f3437}.metrics,.finding small,.result-card small,.job-card small{color:#787774}.finding-location{color:#346538}.finding{box-shadow:none}.progress{border-color:#eaeaea;border-radius:8px}.progress span{background:#346538;animation:none}.intro-copy h2,.auth-wall h2{font-family:Georgia,'Times New Roman',serif;font-weight:500;color:#111;line-height:1.02}.intro-copy h2 em{color:#787774}.review-preview{box-shadow:none}.preview-top{border-color:#eaeaea}.live-dot{background:#346538;box-shadow:none}.preview-row{border-color:#eaeaea}.preview-row.active{color:#346538}.trust-strip{border-color:#eaeaea}.trust-strip strong{color:#111}.auth-button{width:auto;margin:0;padding:0;background:transparent;color:#787774;font:500 11px 'DM Mono',monospace;text-transform:uppercase;letter-spacing:.08em}.auth-button:hover{background:transparent;color:#111}footer{border-color:#eaeaea;color:#787774}
15
+
16
+ /* Friendly canvas: soft sage tint with warm white reading surfaces */
17
+ :root{background:#f3f7f4}body{background:#f3f7f4}.topbar,.panel,.review-preview,.auth-wall{background:#fffdf9}.content{background:transparent}
18
+
19
+ /* Powder-blue canvas for stronger separation from white surfaces */
20
+ :root{background:#dfeaf1}body{background:#dfeaf1}.topbar{background:#eaf2f6}.panel,.review-preview,.auth-wall{background:#f8fbfc}
21
+
22
+ .theme-toggle{width:auto;margin:0 0 0 14px;padding:7px 10px;background:transparent;color:#2f3437;border:1px solid #cbd7dd;border-radius:4px;font:500 10px 'DM Mono',monospace;text-transform:uppercase;letter-spacing:.08em}.theme-toggle:hover{background:#fff;color:#111}
23
+ :root[data-theme="dark"]{background:#11151a;color:#e8edf0;--line:#303840;--muted:#9ca8b0;--accent:#f0f4f5;--ink:#11151a}html[data-theme="dark"] body{background:#11151a;color:#e8edf0}html[data-theme="dark"] .topbar{background:#151b21;border-color:#303840}.dark .brand,html[data-theme="dark"] .brand{color:#f4f7f8}html[data-theme="dark"] .brand-mark{border-color:#e8edf0;color:#e8edf0}html[data-theme="dark"] .panel,html[data-theme="dark"] .review-preview,html[data-theme="dark"] .auth-wall{background:#182027;border-color:#303840}html[data-theme="dark"] h1,html[data-theme="dark"] .intro-copy h2,html[data-theme="dark"] .auth-wall h2,html[data-theme="dark"] .form-panel h2{color:#f4f7f8}html[data-theme="dark"] input,html[data-theme="dark"] select{background:#11171c;color:#e8edf0;border-color:#3b4650}html[data-theme="dark"] .theme-toggle{color:#e8edf0;border-color:#53616b}html[data-theme="dark"] .theme-toggle:hover{background:#2a333b}html[data-theme="dark"] .primary-link,html[data-theme="dark"] button:not(.theme-toggle){background:#f0f4f5;color:#11151a}html[data-theme="dark"] .job-card,html[data-theme="dark"] .result-card,html[data-theme="dark"] .finding{background:#182027;border-color:#303840}html[data-theme="dark"] footer{border-color:#303840}
24
+
25
+ /* Premium header treatment */
26
+ .topbar{position:sticky;top:0;z-index:10;height:72px;padding:0 clamp(24px,6vw,88px);background:rgba(234,242,246,.88);backdrop-filter:blur(14px);border-bottom:1px solid rgba(47,52,55,.1)}.brand{gap:11px;font-size:15px;letter-spacing:-.04em}.brand-mark{width:34px;height:34px;border-radius:8px;background:#111;color:#fff;border:0;font:600 10px 'DM Mono',monospace;letter-spacing:.05em}.topbar>div:last-child{display:flex;align-items:center;gap:16px}.topbar .status-dot:last-of-type{padding-left:16px;border-left:1px solid rgba(47,52,55,.14)}.topbar .status-dot:before{width:6px;height:6px}.theme-toggle{margin-left:2px;padding:8px 12px;border-color:rgba(47,52,55,.18);background:rgba(255,255,255,.55)}.theme-toggle:hover{background:#fff;transform:translateY(-1px)}html[data-theme="dark"] .topbar{background:rgba(21,27,33,.9);border-color:rgba(255,255,255,.1)}html[data-theme="dark"] .brand-mark{background:#f0f4f5;color:#11151a}html[data-theme="dark"] .topbar .status-dot:last-of-type{border-color:rgba(255,255,255,.14)}
27
+
28
+ @media(max-width:760px){.topbar{height:64px;padding:0 16px}.topbar>div:last-child{gap:8px;min-width:0}.topbar .status-dot{display:inline-block;max-width:92px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:9px}.topbar .status-dot:last-of-type{display:none}.topbar .status-dot:before{margin-right:5px}.brand{font-size:13px;gap:8px}.brand-mark{width:30px;height:30px}.theme-toggle{font-size:9px;padding:7px 9px;margin-left:0}.content{width:min(100% - 32px,1180px);padding-top:46px}.intro-band{gap:2.5rem;padding-bottom:2.5rem}.intro-copy>p:not(.eyebrow){font-size:1rem}.review-preview{padding:1rem}.trust-strip{padding-bottom:2.5rem}.auth-wall{padding:2rem 1.25rem}}
29
+
30
+ .score-block{display:flex;flex-direction:column;align-items:flex-end;gap:3px}.score-block>span{font:500 10px 'DM Mono',monospace;text-transform:uppercase;letter-spacing:.06em;color:#9f2f2d}.score-explanation{display:grid;gap:4px;margin:14px 0;padding:12px 14px;border-radius:6px;background:#fbf3db;color:#956400;font-size:13px;line-height:1.45}.score-explanation strong{font-size:11px;text-transform:uppercase;letter-spacing:.08em}.verdict-summary{font-size:15px!important}.verdict.approved .score-block>span{color:#346538}.verdict.approved .score-explanation{background:#edf3ec;color:#346538}
31
+
32
+ /* Result readability */
33
+ .result-card{color:#2f3437}.result-card h3,.result-card .panel-kicker,.section-heading h3{color:#111}.verdict.blocking{border-left:4px solid #9f2f2d;background:#fff8f8}.verdict.blocking .score-block>span{color:#9f2f2d}.verdict.approved{border-left:4px solid #346538;background:#f7fbf7}.score{color:#111}.score-explanation{border:1px solid #f0dfad}.finding-meta .severity{font-weight:700}.finding-location{color:#1f6c9f!important}.finding p{color:#2f3437!important}.finding small{color:#5f6669!important}.receipt{background:#f9fbfc}.receipt .panel-kicker{color:#1f6c9f}html[data-theme="dark"] .result-card{color:#e8edf0}html[data-theme="dark"] .result-card h3,html[data-theme="dark"] .result-card .panel-kicker,html[data-theme="dark"] .section-heading h3,html[data-theme="dark"] .score{color:#f4f7f8}.verdict.blocking{background:#291c1e}.verdict.approved{background:#18241d}.score-explanation{background:#332c1c;color:#f2d98c;border-color:#66562c}.finding p{color:#e8edf0!important}.finding small{color:#aeb9bf!important}.finding-location{color:#8ec9ef!important}
34
+
35
+ html[data-theme="dark"] .finding p,html[data-theme="dark"] .result-card p{color:#e8edf0!important}html[data-theme="dark"] .finding small{color:#c1cbd1!important}html[data-theme="dark"] .finding-location{color:#9bd4f5!important}
36
+
37
+ /* Final theme scoping for verdict surfaces */
38
+ html:not([data-theme="dark"]) .verdict.blocking{background:#fff8f8;color:#2f3437}html:not([data-theme="dark"]) .verdict.approved{background:#f7fbf7;color:#2f3437}html:not([data-theme="dark"]) .score-explanation{background:#fbf3db;color:#956400;border-color:#f0dfad}html:not([data-theme="dark"]) .finding p{color:#2f3437!important}html:not([data-theme="dark"]) .finding small{color:#5f6669!important}html[data-theme="dark"] .verdict.blocking{background:#291c1e;color:#e8edf0}html[data-theme="dark"] .verdict.approved{background:#18241d;color:#e8edf0}html[data-theme="dark"] .score-explanation{background:#332c1c;color:#f2d98c;border-color:#66562c}
39
+ .provider-use{width:100%;margin:10px 0 4px;padding:11px 12px;background:#edf3ec;color:#346538;border:1px solid #cfe1d0;border-radius:5px;font:600 11px 'DM Mono',monospace;text-transform:uppercase;letter-spacing:.04em}.provider-use:hover{background:#dfeee0;color:#234d28}.provider-use span{font-size:14px}html[data-theme="dark"] .provider-use{background:#203325;color:#b9e3bd;border-color:#3e6042}html[data-theme="dark"] .provider-use:hover{background:#2b4430}
40
+
41
+ .is-hidden{display:none!important}.workspace-tabs{display:flex;gap:8px;margin-bottom:14px}.workspace-tabs button{background:transparent;border:1px solid var(--line);padding:9px 14px;border-radius:6px;color:var(--muted);cursor:pointer}.workspace-tabs button.active{background:var(--ink);color:var(--paper)}.provider-manager{margin-bottom:16px}.saved-provider-list{display:grid;gap:8px;margin:16px 0}.saved-provider{border:1px solid var(--line);padding:12px;border-radius:6px;display:flex;flex-direction:column;gap:4px}.saved-provider small{color:var(--muted)}
42
+
43
+ .workspace-tabs{grid-column:1/-1;align-self:start;height:auto}.workspace-tabs button{width:auto;margin:0;display:inline-flex;justify-content:center}.provider-manager{grid-column:1/-1}
44
+
45
+ .provider-actions{display:flex;gap:10px;margin-top:12px}.provider-actions button{width:auto;flex:1;margin:0}.provider-actions button:first-child{background:transparent;border:1px solid var(--line);color:var(--muted)}
46
+
47
+ .review-mode{border:1px solid var(--line);border-radius:6px;padding:12px;margin:20px 0;display:grid;gap:10px}.review-mode legend{font-size:12px;color:var(--muted);padding:0 6px}.review-mode label{display:grid;grid-template-columns:20px 1fr;gap:6px;margin:0;text-transform:none;letter-spacing:0;font:600 14px Arial,sans-serif;color:inherit}.review-mode input{width:16px;height:16px;margin:0;grid-row:1/3;box-shadow:none}.review-mode label span{grid-column:2;font-size:12px;font-weight:400;color:var(--muted)}.review-progress{margin:16px 0}.reviewer-stages{padding:0;list-style:none;display:grid;gap:8px}.reviewer-stages li{border:1px solid var(--line);padding:10px;display:grid;gap:5px;border-radius:6px}.reviewer-stages small,.reviewer-stages span{color:var(--muted);overflow-wrap:anywhere}.reviewer-stages .reviewer-error{color:#b74335}html[data-theme="dark"] .reviewer-stages .reviewer-error{color:#ffb4a9}.review-progress details{margin:14px 0;color:var(--muted);font-size:12px}.review-progress summary{cursor:pointer}.progress button{width:auto;font-size:12px;padding:8px 12px}.provider-actions button:disabled{cursor:wait;opacity:.6}
48
+ .finding-group{margin-top:24px}.finding-group h4{font-size:15px;display:flex;gap:8px;align-items:center}.finding-group h4 span{font-size:12px;color:var(--muted)}.evidence-label{display:inline-block;font-size:11px;line-height:1.6;margin:6px 0;color:#42614a}.evidence-label.uncertain{color:#855c20}.evidence-excerpt{white-space:pre-wrap;overflow-wrap:anywhere;font:12px/1.65 'DM Mono',monospace;max-height:280px;overflow:auto;padding:12px;border:1px solid var(--line);border-radius:5px}.calibration-note{font-size:12px!important;color:var(--muted)!important}.finding-feedback{display:flex;gap:7px;align-items:center;flex-wrap:wrap;margin-top:14px;padding-top:12px;border-top:1px solid var(--line)}.finding-feedback>span{font-size:12px;color:var(--muted)}.finding-feedback button,.provider-entry-actions button,.provider-form-heading button{width:auto;margin:0;padding:7px 11px;display:inline-flex;justify-content:center;border:1px solid var(--line);font-size:12px;font-weight:500;background:transparent;color:inherit}.finding-feedback button[aria-pressed="true"]{background:#dbe8dc;border-color:#799b7c;color:#24482b}.finding-feedback small{width:100%}.provider-entry-title,.provider-form-heading{display:flex;gap:10px;justify-content:space-between;align-items:center;flex-wrap:wrap}.provider-entry-actions{display:flex;gap:8px;flex-wrap:wrap;margin-top:10px}.provider-form-heading{margin-top:28px}.provider-form-heading h3{margin:0}.provider-entry-actions button:disabled{opacity:.5;cursor:default}.review-coverage{overflow-wrap:anywhere}.review-coverage ul{padding-left:18px;font-size:13px;line-height:1.7}html[data-theme="dark"] .evidence-label{color:#b2d4b7}html[data-theme="dark"] .evidence-label.uncertain{color:#e4c48c}html[data-theme="dark"] .finding-feedback button,html[data-theme="dark"] .provider-entry-actions button,html[data-theme="dark"] .provider-form-heading button{background:transparent;color:#e8edf0}html[data-theme="dark"] .finding-feedback button[aria-pressed="true"]{background:#294334;color:#d4edda;border-color:#759b7e}
nodes/aggregator.py CHANGED
@@ -1,288 +1,288 @@
1
- from __future__ import annotations
2
-
3
- import logging
4
- import os
5
- from pathlib import Path
6
-
7
- from backend.integrations.llm_factory import create_llm
8
- from nodes.finding_quality import calibrate_findings, review_coverage
9
- from pydantic import BaseModel, Field
10
-
11
- from backend.state import Finding, OpenCodeReviewState, Severity, Verdict
12
-
13
- logger = logging.getLogger(__name__)
14
-
15
- # Prompt version — tied to the file on disk
16
- PROMPT_VERSION = "v1"
17
- PROMPT_FILE = Path(__file__).resolve().parent.parent / "prompts" / f"aggregator_{PROMPT_VERSION}.txt"
18
-
19
- # Findings below this confidence are dropped before the LLM step
20
- MIN_CONFIDENCE = 0.25
21
- # Files/line pairs within this many lines are considered duplicates
22
- LINE_TOLERANCE = 5
23
-
24
- # Default to rule-based aggregation (skips expensive LLM critic call).
25
- # Set AGGREGATOR_USE_LLM_CRITIC=true in env to re-enable the LLM pass.
26
- USE_LLM_CRITIC = os.environ.get("AGGREGATOR_USE_LLM_CRITIC", "").lower() in ("1", "true", "yes")
27
-
28
-
29
- # ─── Load prompt from file ──────────────────────────────────────────────────
30
-
31
-
32
- def _load_prompt() -> str:
33
- """Load the system prompt from the versioned prompt file."""
34
- try:
35
- return PROMPT_FILE.read_text(encoding="utf-8")
36
- except FileNotFoundError:
37
- logger.warning("Prompt file %s not found — using fallback", PROMPT_FILE)
38
- return (
39
- "You are a senior engineer acting as a critic of a code review. "
40
- "Filter out noise, deduplicate findings, and produce a verdict. "
41
- "Return the filtered list of findings plus your verdict."
42
- )
43
-
44
-
45
- SYSTEM_PROMPT = _load_prompt()
46
-
47
-
48
- # ─── LLM output schema ──────────────────────────────────────────────────────
49
-
50
-
51
- class AggregatedReview(BaseModel):
52
- """Final, noise-filtered findings and overall verdict."""
53
- findings: list[Finding] = Field(
54
- default_factory=list,
55
- description="Deduplicated, noise-filtered findings worth a senior engineer's time.",
56
- )
57
- verdict: Verdict = Field(
58
- description="Overall PR verdict after considering all findings.",
59
- )
60
-
61
-
62
- # ─── Pre-LLM heuristic deduplication ────────────────────────────────────────
63
-
64
-
65
- def _deduplicate(findings: list[Finding]) -> list[Finding]:
66
- """Heuristic dedup: group by ``(file_path, line_start)`` with a line
67
- tolerance, keeping the highest-confidence finding per group."""
68
- if not findings:
69
- return []
70
-
71
- # Sort by (file, line_start) so we can iterate and merge neighbours
72
- sorted_fs = sorted(findings, key=lambda f: (f.file_path, f.line_start))
73
-
74
- merged: list[Finding] = []
75
- current: Finding = sorted_fs[0]
76
-
77
- for f in sorted_fs[1:]:
78
- same_file = f.file_path == current.file_path
79
- close_lines = abs(f.line_start - current.line_start) <= LINE_TOLERANCE
80
- same_claim = " ".join(f.comment.lower().split()) == " ".join(current.comment.lower().split())
81
- if same_file and close_lines and f.kind == current.kind and f.category == current.category and same_claim:
82
- # Keep the higher-confidence finding, merge comments
83
- if f.confidence > current.confidence:
84
- current = f
85
- if current.confidence < 0.9:
86
- current.confidence = round(
87
- (current.confidence + f.confidence) / 2, 2
88
- )
89
- # Prefer the specific comment over a generic one
90
- if len(f.comment) > len(current.comment):
91
- current.comment = f.comment
92
- if f.suggested_fix and not current.suggested_fix:
93
- current.suggested_fix = f.suggested_fix
94
- # Escalate severity if either finding is more severe
95
- current.severity = _more_severe(current.severity, f.severity)
96
- else:
97
- merged.append(current)
98
- current = f
99
- merged.append(current)
100
-
101
- # Drop low-confidence noise
102
- merged = [f for f in merged if f.confidence >= MIN_CONFIDENCE]
103
-
104
- return merged
105
-
106
-
107
- _SEVERITY_ORDER = {
108
- Severity.CRITICAL: 0,
109
- Severity.HIGH: 1,
110
- Severity.MEDIUM: 2,
111
- Severity.LOW: 3,
112
- Severity.INFO: 4,
113
- }
114
-
115
-
116
- def _more_severe(a: Severity, b: Severity) -> Severity:
117
- return a if _SEVERITY_ORDER.get(a, 5) < _SEVERITY_ORDER.get(b, 5) else b
118
-
119
-
120
- # ─── Rule-based fallback verdict ────────────────────────────────────────────
121
-
122
-
123
- def _rule_verdict(findings: list[Finding]) -> Verdict:
124
- """Build a verdict from deduplicated findings without an LLM call."""
125
- eligible = [f for f in findings if f.kind != "test_suggestion" and f.evidence_status == "source_grounded"]
126
- suggestions = sum(f.kind == "test_suggestion" for f in findings)
127
- unverified = sum(f.kind != "test_suggestion" and f.evidence_status != "source_grounded" for f in findings)
128
- counts = {s: 0 for s in Severity}
129
- for f in eligible:
130
- counts[f.severity] = counts.get(f.severity, 0) + 1
131
-
132
- critical = counts[Severity.CRITICAL]
133
- high = counts[Severity.HIGH]
134
-
135
- if critical > 0:
136
- recommendation = "block"
137
- approved = False
138
- elif high > 0:
139
- recommendation = "request_changes"
140
- approved = False
141
- elif eligible or suggestions or unverified:
142
- recommendation = "comment"
143
- approved = True
144
- else:
145
- recommendation = "approve"
146
- approved = True
147
-
148
- # Score: 10 - penalty based on severity
149
- score = max(0.0, min(10.0, 10.0 - critical * 4.0 - high * 2.0 - counts.get(Severity.MEDIUM, 0) * 0.5))
150
-
151
- severity_counts = {s.value: counts.get(s, 0) for s in Severity}
152
-
153
- return Verdict(
154
- summary=_rule_summary(recommendation, severity_counts) + (f" {suggestions} test suggestion(s), {unverified} unverified claim(s) are excluded from the score." if suggestions or unverified else ""),
155
- approved=approved,
156
- overall_score=round(score, 1),
157
- critical_count=critical,
158
- high_count=high,
159
- recommendation=recommendation,
160
- score_explanation="Risk estimate from source-grounded findings, not answer correctness or proof of safety. Test suggestions and claims without source grounding do not lower the score.",
161
- score_breakdown={"starting_score": 10, "critical_penalty": critical * 4, "high_penalty": high * 2,
162
- "medium_penalty": counts[Severity.MEDIUM] * .5, "scored_findings": len(eligible),
163
- "test_suggestions_excluded": suggestions, "unverified_claims_excluded": unverified},
164
- )
165
-
166
-
167
- def _rule_summary(recommendation: str, counts: dict) -> str:
168
- parts = [f"{v} {k}" for k, v in counts.items() if v > 0]
169
- if not parts:
170
- return "No source-grounded defects detected. This does not establish that the PR is safe."
171
- body = ", ".join(parts)
172
- if recommendation == "block":
173
- return f"Blocking: {body} — critical issues must be resolved."
174
- elif recommendation == "request_changes":
175
- return f"Changes requested: {body} — high-severity issues should be addressed."
176
- elif recommendation == "comment":
177
- return f"Minor concerns: {body} — consider addressing for best practices."
178
- return f"Approved: {body} — no significant issues."
179
-
180
-
181
- # ─── Prompt builder ─────────────────────────────────────────────────────────
182
-
183
-
184
- def _build_prompt(findings: list[Finding]) -> str:
185
- lines = [
186
- "Below are the raw findings from automated code reviewers "
187
- "(correctness, security, test-coverage).",
188
- "",
189
- "Filter out noise and return only the findings a senior engineer "
190
- "would actually leave on this PR.",
191
- "",
192
- "## Raw findings",
193
- ]
194
- for i, f in enumerate(findings, 1):
195
- lines.append(f"\n--- Finding {i} ---")
196
- lines.append(f" File: {f.file_path}")
197
- lines.append(f" Lines: {f.line_start}–{f.line_end}")
198
- lines.append(f" Severity: {f.severity.value}")
199
- lines.append(f" Category: {f.category}")
200
- lines.append(f" Comment: {f.comment}")
201
- lines.append(f" Confidence: {f.confidence}")
202
- if f.suggested_fix:
203
- lines.append(f" Fix: {f.suggested_fix[:200]}")
204
-
205
- lines.append("\nNow apply the deduplication, noise-filtering, and verdict rules.")
206
- return "\n".join(lines)
207
-
208
-
209
- # ─── Node ────────────────────────────────────────────────────────────────────
210
-
211
-
212
- def aggregator_node(state: OpenCodeReviewState) -> dict:
213
- """Deduplicate, filter, and aggregate all findings into a final verdict.
214
-
215
- Returns state updates for ``findings`` (overwritten with the filtered
216
- list) and ``verdict`` (set-once by this node).
217
-
218
- Two-phase approach:
219
- 1. Pre-LLM heuristic deduplication (groups by file/line proximity).
220
- 2. Rule-based verdict by default (fast, ~10ms), or optional LLM critic
221
- when ``USE_LLM_CRITIC`` is enabled.
222
- """
223
- coverage = review_coverage(state)
224
- calibrated = calibrate_findings(state.findings, state)
225
- failed = [stage for stage in state.review_stages if stage.get("status") == "failed"]
226
- if failed:
227
- names = ", ".join(stage["reviewer"] for stage in failed)
228
- return {"review_coverage": coverage, "final_findings": _deduplicate(calibrated), "verdict": Verdict(
229
- summary=f"Review incomplete: {names} failed. Findings are partial; no approval or quality score is available.",
230
- approved=False, overall_score=None, recommendation="incomplete",
231
- score_explanation="No overall risk score is available because one or more reviewers failed. Remaining findings are partial.",
232
- )}
233
- raw_findings = calibrated
234
- if not raw_findings:
235
- logger.info("No findings to aggregate — producing empty verdict")
236
- return {"review_coverage": coverage, "final_findings": [], "verdict": _rule_verdict([])}
237
-
238
- # -- Phase 1: Heuristic dedup --------------------------------------------
239
- deduped = _deduplicate(raw_findings)
240
- logger.info(
241
- "Dedup heuristic: %d raw → %d merged",
242
- len(raw_findings), len(deduped),
243
- )
244
-
245
- # -- Phase 2: Rule-based (default, fast) or LLM critic (opt-in) ----------
246
- if USE_LLM_CRITIC:
247
- try:
248
- llm = create_llm(endpoint=state.endpoint or None)
249
- except ValueError as exc:
250
- logger.warning("LLM critic unavailable — using rule-based: %s", exc)
251
- llm = None
252
-
253
- if llm is not None:
254
- logger.info(
255
- "Invoking aggregator LLM critic (prompt_version=%s) …",
256
- PROMPT_VERSION,
257
- )
258
- try:
259
- structured_llm = llm.with_structured_output(AggregatedReview)
260
- messages = [
261
- {"role": "system", "content": SYSTEM_PROMPT},
262
- {"role": "user", "content": _build_prompt(deduped)},
263
- ]
264
- result: AggregatedReview = structured_llm.invoke(messages) # type: ignore[assignment]
265
- except Exception as exc:
266
- logger.warning("LLM critic failed — falling back to rule-based: %s", exc)
267
- result = None
268
-
269
- if result is not None:
270
- final_findings = calibrate_findings(result.findings, state)
271
- verdict = _rule_verdict(final_findings)
272
- logger.info(
273
- "LLM aggregator: %d deduped → %d final, recommendation=%s",
274
- len(deduped), len(final_findings),
275
- verdict.recommendation,
276
- )
277
- return {"review_coverage": coverage, "final_findings": final_findings, "verdict": verdict}
278
-
279
- # Rule-based path (default) — zero LLM overhead
280
- logger.info("Using rule-based aggregation (fast path)")
281
- final_findings = deduped
282
- verdict = _rule_verdict(deduped)
283
-
284
- return {
285
- "review_coverage": coverage,
286
- "final_findings": final_findings, # plain list, overwrites
287
- "verdict": verdict, # set-once, no reducer needed
288
- }
 
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ import os
5
+ from pathlib import Path
6
+
7
+ from backend.integrations.llm_factory import create_llm
8
+ from nodes.finding_quality import calibrate_findings, review_coverage
9
+ from pydantic import BaseModel, Field
10
+
11
+ from backend.state import Finding, OpenCodeReviewState, Severity, Verdict
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+ # Prompt version — tied to the file on disk
16
+ PROMPT_VERSION = "v1"
17
+ PROMPT_FILE = Path(__file__).resolve().parent.parent / "prompts" / f"aggregator_{PROMPT_VERSION}.txt"
18
+
19
+ # Findings below this confidence are dropped before the LLM step
20
+ MIN_CONFIDENCE = 0.25
21
+ # Files/line pairs within this many lines are considered duplicates
22
+ LINE_TOLERANCE = 5
23
+
24
+ # Default to rule-based aggregation (skips expensive LLM critic call).
25
+ # Set AGGREGATOR_USE_LLM_CRITIC=true in env to re-enable the LLM pass.
26
+ USE_LLM_CRITIC = os.environ.get("AGGREGATOR_USE_LLM_CRITIC", "").lower() in ("1", "true", "yes")
27
+
28
+
29
+ # ─── Load prompt from file ──────────────────────────────────────────────────
30
+
31
+
32
+ def _load_prompt() -> str:
33
+ """Load the system prompt from the versioned prompt file."""
34
+ try:
35
+ return PROMPT_FILE.read_text(encoding="utf-8")
36
+ except FileNotFoundError:
37
+ logger.warning("Prompt file %s not found — using fallback", PROMPT_FILE)
38
+ return (
39
+ "You are a senior engineer acting as a critic of a code review. "
40
+ "Filter out noise, deduplicate findings, and produce a verdict. "
41
+ "Return the filtered list of findings plus your verdict."
42
+ )
43
+
44
+
45
+ SYSTEM_PROMPT = _load_prompt()
46
+
47
+
48
+ # ─── LLM output schema ──────────────────────────────────────────────────────
49
+
50
+
51
+ class AggregatedReview(BaseModel):
52
+ """Final, noise-filtered findings and overall verdict."""
53
+ findings: list[Finding] = Field(
54
+ default_factory=list,
55
+ description="Deduplicated, noise-filtered findings worth a senior engineer's time.",
56
+ )
57
+ verdict: Verdict = Field(
58
+ description="Overall PR verdict after considering all findings.",
59
+ )
60
+
61
+
62
+ # ─── Pre-LLM heuristic deduplication ────────────────────────────────────────
63
+
64
+
65
+ def _deduplicate(findings: list[Finding]) -> list[Finding]:
66
+ """Heuristic dedup: group by ``(file_path, line_start)`` with a line
67
+ tolerance, keeping the highest-confidence finding per group."""
68
+ if not findings:
69
+ return []
70
+
71
+ # Sort by (file, line_start) so we can iterate and merge neighbours
72
+ sorted_fs = sorted(findings, key=lambda f: (f.file_path, f.line_start))
73
+
74
+ merged: list[Finding] = []
75
+ current: Finding = sorted_fs[0]
76
+
77
+ for f in sorted_fs[1:]:
78
+ same_file = f.file_path == current.file_path
79
+ close_lines = abs(f.line_start - current.line_start) <= LINE_TOLERANCE
80
+ same_claim = " ".join(f.comment.lower().split()) == " ".join(current.comment.lower().split())
81
+ if same_file and close_lines and f.kind == current.kind and f.category == current.category and same_claim:
82
+ # Keep the higher-confidence finding, merge comments
83
+ if f.confidence > current.confidence:
84
+ current = f
85
+ if current.confidence < 0.9:
86
+ current.confidence = round(
87
+ (current.confidence + f.confidence) / 2, 2
88
+ )
89
+ # Prefer the specific comment over a generic one
90
+ if len(f.comment) > len(current.comment):
91
+ current.comment = f.comment
92
+ if f.suggested_fix and not current.suggested_fix:
93
+ current.suggested_fix = f.suggested_fix
94
+ # Escalate severity if either finding is more severe
95
+ current.severity = _more_severe(current.severity, f.severity)
96
+ else:
97
+ merged.append(current)
98
+ current = f
99
+ merged.append(current)
100
+
101
+ # Drop low-confidence noise
102
+ merged = [f for f in merged if f.confidence >= MIN_CONFIDENCE]
103
+
104
+ return merged
105
+
106
+
107
+ _SEVERITY_ORDER = {
108
+ Severity.CRITICAL: 0,
109
+ Severity.HIGH: 1,
110
+ Severity.MEDIUM: 2,
111
+ Severity.LOW: 3,
112
+ Severity.INFO: 4,
113
+ }
114
+
115
+
116
+ def _more_severe(a: Severity, b: Severity) -> Severity:
117
+ return a if _SEVERITY_ORDER.get(a, 5) < _SEVERITY_ORDER.get(b, 5) else b
118
+
119
+
120
+ # ─── Rule-based fallback verdict ────────────────────────────────────────────
121
+
122
+
123
+ def _rule_verdict(findings: list[Finding]) -> Verdict:
124
+ """Build a verdict from deduplicated findings without an LLM call."""
125
+ eligible = [f for f in findings if f.kind != "test_suggestion" and f.evidence_status == "source_grounded"]
126
+ suggestions = sum(f.kind == "test_suggestion" for f in findings)
127
+ unverified = sum(f.kind != "test_suggestion" and f.evidence_status != "source_grounded" for f in findings)
128
+ counts = {s: 0 for s in Severity}
129
+ for f in eligible:
130
+ counts[f.severity] = counts.get(f.severity, 0) + 1
131
+
132
+ critical = counts[Severity.CRITICAL]
133
+ high = counts[Severity.HIGH]
134
+
135
+ if critical > 0:
136
+ recommendation = "block"
137
+ approved = False
138
+ elif high > 0:
139
+ recommendation = "request_changes"
140
+ approved = False
141
+ elif eligible or suggestions or unverified:
142
+ recommendation = "comment"
143
+ approved = True
144
+ else:
145
+ recommendation = "approve"
146
+ approved = True
147
+
148
+ # Score: 10 - penalty based on severity
149
+ score = max(0.0, min(10.0, 10.0 - critical * 4.0 - high * 2.0 - counts.get(Severity.MEDIUM, 0) * 0.5))
150
+
151
+ severity_counts = {s.value: counts.get(s, 0) for s in Severity}
152
+
153
+ return Verdict(
154
+ summary=_rule_summary(recommendation, severity_counts) + (f" {suggestions} test suggestion(s), {unverified} unverified claim(s) are excluded from the score." if suggestions or unverified else ""),
155
+ approved=approved,
156
+ overall_score=round(score, 1),
157
+ critical_count=critical,
158
+ high_count=high,
159
+ recommendation=recommendation,
160
+ score_explanation="Risk estimate from source-grounded findings, not answer correctness or proof of safety. Test suggestions and claims without source grounding do not lower the score.",
161
+ score_breakdown={"starting_score": 10, "critical_penalty": critical * 4, "high_penalty": high * 2,
162
+ "medium_penalty": counts[Severity.MEDIUM] * .5, "scored_findings": len(eligible),
163
+ "test_suggestions_excluded": suggestions, "unverified_claims_excluded": unverified},
164
+ )
165
+
166
+
167
+ def _rule_summary(recommendation: str, counts: dict) -> str:
168
+ parts = [f"{v} {k}" for k, v in counts.items() if v > 0]
169
+ if not parts:
170
+ return "No source-grounded defects detected. This does not establish that the PR is safe."
171
+ body = ", ".join(parts)
172
+ if recommendation == "block":
173
+ return f"Blocking: {body} — critical issues must be resolved."
174
+ elif recommendation == "request_changes":
175
+ return f"Changes requested: {body} — high-severity issues should be addressed."
176
+ elif recommendation == "comment":
177
+ return f"Minor concerns: {body} — consider addressing for best practices."
178
+ return f"Approved: {body} — no significant issues."
179
+
180
+
181
+ # ─── Prompt builder ─────────────────────────────────────────────────────────
182
+
183
+
184
+ def _build_prompt(findings: list[Finding]) -> str:
185
+ lines = [
186
+ "Below are the raw findings from automated code reviewers "
187
+ "(correctness, security, test-coverage).",
188
+ "",
189
+ "Filter out noise and return only the findings a senior engineer "
190
+ "would actually leave on this PR.",
191
+ "",
192
+ "## Raw findings",
193
+ ]
194
+ for i, f in enumerate(findings, 1):
195
+ lines.append(f"\n--- Finding {i} ---")
196
+ lines.append(f" File: {f.file_path}")
197
+ lines.append(f" Lines: {f.line_start}–{f.line_end}")
198
+ lines.append(f" Severity: {f.severity.value}")
199
+ lines.append(f" Category: {f.category}")
200
+ lines.append(f" Comment: {f.comment}")
201
+ lines.append(f" Confidence: {f.confidence}")
202
+ if f.suggested_fix:
203
+ lines.append(f" Fix: {f.suggested_fix[:200]}")
204
+
205
+ lines.append("\nNow apply the deduplication, noise-filtering, and verdict rules.")
206
+ return "\n".join(lines)
207
+
208
+
209
+ # ─── Node ────────────────────────────────────────────────────────────────────
210
+
211
+
212
+ def aggregator_node(state: OpenCodeReviewState) -> dict:
213
+ """Deduplicate, filter, and aggregate all findings into a final verdict.
214
+
215
+ Returns state updates for ``findings`` (overwritten with the filtered
216
+ list) and ``verdict`` (set-once by this node).
217
+
218
+ Two-phase approach:
219
+ 1. Pre-LLM heuristic deduplication (groups by file/line proximity).
220
+ 2. Rule-based verdict by default (fast, ~10ms), or optional LLM critic
221
+ when ``USE_LLM_CRITIC`` is enabled.
222
+ """
223
+ coverage = review_coverage(state)
224
+ calibrated = calibrate_findings(state.findings, state)
225
+ failed = [stage for stage in state.review_stages if stage.get("status") == "failed"]
226
+ if failed:
227
+ names = ", ".join(stage["reviewer"] for stage in failed)
228
+ return {"review_coverage": coverage, "final_findings": _deduplicate(calibrated), "verdict": Verdict(
229
+ summary=f"Review incomplete: {names} failed. Findings are partial; no approval or quality score is available.",
230
+ approved=False, overall_score=None, recommendation="incomplete",
231
+ score_explanation="No overall risk score is available because one or more reviewers failed. Remaining findings are partial.",
232
+ )}
233
+ raw_findings = calibrated
234
+ if not raw_findings:
235
+ logger.info("No findings to aggregate — producing empty verdict")
236
+ return {"review_coverage": coverage, "final_findings": [], "verdict": _rule_verdict([])}
237
+
238
+ # -- Phase 1: Heuristic dedup --------------------------------------------
239
+ deduped = _deduplicate(raw_findings)
240
+ logger.info(
241
+ "Dedup heuristic: %d raw → %d merged",
242
+ len(raw_findings), len(deduped),
243
+ )
244
+
245
+ # -- Phase 2: Rule-based (default, fast) or LLM critic (opt-in) ----------
246
+ if USE_LLM_CRITIC:
247
+ try:
248
+ llm = create_llm(endpoint=state.endpoint or None)
249
+ except ValueError as exc:
250
+ logger.warning("LLM critic unavailable — using rule-based: %s", exc)
251
+ llm = None
252
+
253
+ if llm is not None:
254
+ logger.info(
255
+ "Invoking aggregator LLM critic (prompt_version=%s) …",
256
+ PROMPT_VERSION,
257
+ )
258
+ try:
259
+ structured_llm = llm.with_structured_output(AggregatedReview)
260
+ messages = [
261
+ {"role": "system", "content": SYSTEM_PROMPT},
262
+ {"role": "user", "content": _build_prompt(deduped)},
263
+ ]
264
+ result: AggregatedReview = structured_llm.invoke(messages) # type: ignore[assignment]
265
+ except Exception as exc:
266
+ logger.warning("LLM critic failed — falling back to rule-based: %s", exc)
267
+ result = None
268
+
269
+ if result is not None:
270
+ final_findings = calibrate_findings(result.findings, state)
271
+ verdict = _rule_verdict(final_findings)
272
+ logger.info(
273
+ "LLM aggregator: %d deduped → %d final, recommendation=%s",
274
+ len(deduped), len(final_findings),
275
+ verdict.recommendation,
276
+ )
277
+ return {"review_coverage": coverage, "final_findings": final_findings, "verdict": verdict}
278
+
279
+ # Rule-based path (default) — zero LLM overhead
280
+ logger.info("Using rule-based aggregation (fast path)")
281
+ final_findings = deduped
282
+ verdict = _rule_verdict(deduped)
283
+
284
+ return {
285
+ "review_coverage": coverage,
286
+ "final_findings": final_findings, # plain list, overwrites
287
+ "verdict": verdict, # set-once, no reducer needed
288
+ }
nodes/correctness_reviewer.py CHANGED
@@ -1,196 +1,196 @@
1
- from __future__ import annotations
2
-
3
- import time
4
- import logging
5
- import os
6
- import re
7
- from pathlib import Path
8
-
9
- from backend.integrations.llm_factory import create_llm
10
- from nodes.finding_quality import calibrate_findings
11
- from nodes.review_runtime import changed_context, invoke_review, stage_result, reviewer_timeout
12
- from pydantic import BaseModel, Field
13
-
14
- from backend.state import Finding, OpenCodeReviewState, Severity
15
-
16
- logger = logging.getLogger(__name__)
17
-
18
- # Prompt version — tied to the file on disk
19
- PROMPT_VERSION = "v1"
20
- PROMPT_FILE = Path(__file__).resolve().parent.parent / "prompts" / f"correctness_{PROMPT_VERSION}.txt"
21
-
22
- # Max characters of context to include in the prompt (soft limit)
23
- MAX_CONTEXT_CHARS = 2_000
24
- # Max changed-file content to include per file
25
- MAX_FILE_CONTENT_CHARS = 600
26
- # Keep model requests below free-provider token limits. Deterministic checks
27
- # still inspect the complete diff from state.diff.
28
- MAX_DIFF_CHARS = 9_000
29
-
30
-
31
- # ─── Load prompt from file ──────────────────────────────────────────────────
32
-
33
-
34
- def _load_prompt() -> str:
35
- """Load the system prompt from the versioned prompt file."""
36
- try:
37
- return PROMPT_FILE.read_text(encoding="utf-8")
38
- except FileNotFoundError:
39
- logger.warning("Prompt file %s not found — using fallback", PROMPT_FILE)
40
- return (
41
- "You are a seasoned code reviewer focused exclusively on correctness. "
42
- "Analyse the PR diff and look for logic errors, edge cases, "
43
- "off-by-one errors, missing null checks, resource mismanagement, "
44
- "and concurrency hazards. Return a list of findings."
45
- )
46
-
47
-
48
- SYSTEM_PROMPT = _load_prompt()
49
-
50
-
51
- # ─── Wrapper schema for structured output ───────────────────────────────────
52
-
53
-
54
- class CorrectnessReview(BaseModel):
55
- """A list of correctness issues found during code review.
56
-
57
- The LLM MUST populate this with every correctness-relevant finding in the
58
- diff. Return an empty list if no correctness issues are found.
59
- """
60
- findings: list[Finding] = Field(
61
- default_factory=list,
62
- description=(
63
- "Correctness issues found in the PR diff. "
64
- "Each issue must reference a specific file and line range."
65
- ),
66
- )
67
-
68
-
69
- # ─── Prompt builder ─────────────────────────────────────────────────────────
70
-
71
-
72
- def _build_prompt(state: OpenCodeReviewState) -> str:
73
- """Build the user-facing prompt from the current graph state."""
74
- lines: list[str] = []
75
-
76
- lines.append("## Diff\n```diff")
77
- diff = state.diff or ""
78
- if len(diff) > MAX_DIFF_CHARS:
79
- diff = diff[:MAX_DIFF_CHARS] + "\n… (diff truncated for model context)"
80
- lines.append(diff)
81
- lines.append("```\n")
82
-
83
- # Changed files with full content (truncated per file)
84
- if state.changed_files:
85
- lines.append("## Changed files\n")
86
- for cf in state.changed_files:
87
- header = f"### {cf.path} ({cf.status})"
88
- lines.append(header)
89
- content = changed_context(cf, state.review_mode)
90
- if len(content) > MAX_FILE_CONTENT_CHARS:
91
- content = content[:MAX_FILE_CONTENT_CHARS] + "\n… (truncated)"
92
- lines.append(f"```\n{content}\n```\n")
93
-
94
- # Context chunks (truncated total)
95
- if state.context_chunks:
96
- lines.append("## Retrieved context\n")
97
- ctx_chars = 0
98
- for chunk in state.context_chunks:
99
- snippet = chunk.content
100
- if ctx_chars + len(snippet) > MAX_CONTEXT_CHARS:
101
- remaining = MAX_CONTEXT_CHARS - ctx_chars
102
- if remaining > 200:
103
- lines.append(f"> {snippet[:remaining]}… (truncated)")
104
- break
105
- if chunk.source == "past_pr":
106
- lines.append(f"> [Past PR — {chunk.file_path}]: {snippet}")
107
- else:
108
- lines.append(f"> [{chunk.file_path}]: {snippet}")
109
- ctx_chars += len(snippet)
110
-
111
- return "\n".join(lines)
112
-
113
-
114
- # ─── Node ────────────────────────────────────────────────────────────────────
115
-
116
-
117
- def correctness_reviewer_node(state: OpenCodeReviewState) -> dict:
118
- started = time.monotonic()
119
- """Analyse the diff and context chunks for correctness issues using an LLM.
120
-
121
- Returns state updates for ``findings`` (accumulated via the ``add``
122
- reducer).
123
- """
124
- # --- Sanity checks -------------------------------------------------------
125
- if not state.diff:
126
- logger.info("No diff to review — skipping correctness review")
127
- return {}
128
-
129
- # A regex match cannot establish whether async side effects must be awaited.
130
- # Retain findings only when the reviewer has evaluated the surrounding code.
131
- static_findings = []
132
-
133
- # --- Build the LLM (Gemini primary → Groq fallback) -----------------------
134
- try:
135
- llm = create_llm(endpoint=state.endpoint or None, timeout=reviewer_timeout(state.review_mode), **({"max_tokens": 1200} if state.review_mode == "fast" else {}))
136
- except ValueError as exc:
137
- logger.warning("LLM unavailable — skipping correctness review: %s", exc)
138
- return {"findings": static_findings, "review_stages": [stage_result("correctness", started, error=exc, llm=locals().get("llm"))]}
139
-
140
- # --- Build the prompt ----------------------------------------------------
141
- user_prompt = _build_prompt(state)
142
- logger.info(
143
- "Invoking correctness reviewer (diff=%s, context=%d chunks, prompt=%s, prompt_version=%s)",
144
- _human_size(len(state.diff or "")),
145
- len(state.context_chunks),
146
- _human_size(len(user_prompt)),
147
- PROMPT_VERSION,
148
- )
149
-
150
- # --- Invoke --------------------------------------------------------------
151
- try:
152
- messages = [
153
- {"role": "system", "content": SYSTEM_PROMPT},
154
- {"role": "user", "content": user_prompt},
155
- ]
156
- result: CorrectnessReview = invoke_review(llm, CorrectnessReview, messages, mode=state.review_mode) # type: ignore[assignment]
157
- except Exception as exc:
158
- logger.warning("Correctness review LLM call failed: %s", exc)
159
- return {"findings": static_findings, "review_stages": [stage_result("correctness", started, error=exc, llm=llm)]}
160
-
161
- # Deterministic guard for a high-impact async anti-pattern that LLMs can
162
- # miss: promises created by forEach are not awaited by the caller.
163
- result.findings.extend(static_findings)
164
-
165
- # --- Log and return findings ---------------------------------------------
166
- result.findings = calibrate_findings(result.findings, state)
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
- "review_stages": [stage_result("correctness", started, llm=llm)],
184
- }
185
-
186
-
187
- # ─── Utility ─────────────────────────────────────────────────────────────────
188
-
189
-
190
- def _human_size(bytes_: int) -> str:
191
- if bytes_ < 1024:
192
- return f"{bytes_} B"
193
- elif bytes_ < 1024 * 1024:
194
- return f"{bytes_ / 1024:.1f} KiB"
195
- else:
196
- return f"{bytes_ / (1024 * 1024):.1f} MiB"
 
1
+ from __future__ import annotations
2
+
3
+ import time
4
+ import logging
5
+ import os
6
+ import re
7
+ from pathlib import Path
8
+
9
+ from backend.integrations.llm_factory import create_llm
10
+ from nodes.finding_quality import calibrate_findings
11
+ from nodes.review_runtime import changed_context, invoke_review, stage_result, reviewer_timeout
12
+ from pydantic import BaseModel, Field
13
+
14
+ from backend.state import Finding, OpenCodeReviewState, Severity
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+ # Prompt version — tied to the file on disk
19
+ PROMPT_VERSION = "v1"
20
+ PROMPT_FILE = Path(__file__).resolve().parent.parent / "prompts" / f"correctness_{PROMPT_VERSION}.txt"
21
+
22
+ # Max characters of context to include in the prompt (soft limit)
23
+ MAX_CONTEXT_CHARS = 2_000
24
+ # Max changed-file content to include per file
25
+ MAX_FILE_CONTENT_CHARS = 600
26
+ # Keep model requests below free-provider token limits. Deterministic checks
27
+ # still inspect the complete diff from state.diff.
28
+ MAX_DIFF_CHARS = 9_000
29
+
30
+
31
+ # ─── Load prompt from file ──────────────────────────────────────────────────
32
+
33
+
34
+ def _load_prompt() -> str:
35
+ """Load the system prompt from the versioned prompt file."""
36
+ try:
37
+ return PROMPT_FILE.read_text(encoding="utf-8")
38
+ except FileNotFoundError:
39
+ logger.warning("Prompt file %s not found — using fallback", PROMPT_FILE)
40
+ return (
41
+ "You are a seasoned code reviewer focused exclusively on correctness. "
42
+ "Analyse the PR diff and look for logic errors, edge cases, "
43
+ "off-by-one errors, missing null checks, resource mismanagement, "
44
+ "and concurrency hazards. Return a list of findings."
45
+ )
46
+
47
+
48
+ SYSTEM_PROMPT = _load_prompt()
49
+
50
+
51
+ # ─── Wrapper schema for structured output ───────────────────────────────────
52
+
53
+
54
+ class CorrectnessReview(BaseModel):
55
+ """A list of correctness issues found during code review.
56
+
57
+ The LLM MUST populate this with every correctness-relevant finding in the
58
+ diff. Return an empty list if no correctness issues are found.
59
+ """
60
+ findings: list[Finding] = Field(
61
+ default_factory=list,
62
+ description=(
63
+ "Correctness issues found in the PR diff. "
64
+ "Each issue must reference a specific file and line range."
65
+ ),
66
+ )
67
+
68
+
69
+ # ─── Prompt builder ─────────────────────────────────────────────────────────
70
+
71
+
72
+ def _build_prompt(state: OpenCodeReviewState) -> str:
73
+ """Build the user-facing prompt from the current graph state."""
74
+ lines: list[str] = []
75
+
76
+ lines.append("## Diff\n```diff")
77
+ diff = state.diff or ""
78
+ if len(diff) > MAX_DIFF_CHARS:
79
+ diff = diff[:MAX_DIFF_CHARS] + "\n… (diff truncated for model context)"
80
+ lines.append(diff)
81
+ lines.append("```\n")
82
+
83
+ # Changed files with full content (truncated per file)
84
+ if state.changed_files:
85
+ lines.append("## Changed files\n")
86
+ for cf in state.changed_files:
87
+ header = f"### {cf.path} ({cf.status})"
88
+ lines.append(header)
89
+ content = changed_context(cf, state.review_mode)
90
+ if len(content) > MAX_FILE_CONTENT_CHARS:
91
+ content = content[:MAX_FILE_CONTENT_CHARS] + "\n… (truncated)"
92
+ lines.append(f"```\n{content}\n```\n")
93
+
94
+ # Context chunks (truncated total)
95
+ if state.context_chunks:
96
+ lines.append("## Retrieved context\n")
97
+ ctx_chars = 0
98
+ for chunk in state.context_chunks:
99
+ snippet = chunk.content
100
+ if ctx_chars + len(snippet) > MAX_CONTEXT_CHARS:
101
+ remaining = MAX_CONTEXT_CHARS - ctx_chars
102
+ if remaining > 200:
103
+ lines.append(f"> {snippet[:remaining]}… (truncated)")
104
+ break
105
+ if chunk.source == "past_pr":
106
+ lines.append(f"> [Past PR — {chunk.file_path}]: {snippet}")
107
+ else:
108
+ lines.append(f"> [{chunk.file_path}]: {snippet}")
109
+ ctx_chars += len(snippet)
110
+
111
+ return "\n".join(lines)
112
+
113
+
114
+ # ─── Node ────────────────────────────────────────────────────────────────────
115
+
116
+
117
+ def correctness_reviewer_node(state: OpenCodeReviewState) -> dict:
118
+ started = time.monotonic()
119
+ """Analyse the diff and context chunks for correctness issues using an LLM.
120
+
121
+ Returns state updates for ``findings`` (accumulated via the ``add``
122
+ reducer).
123
+ """
124
+ # --- Sanity checks -------------------------------------------------------
125
+ if not state.diff:
126
+ logger.info("No diff to review — skipping correctness review")
127
+ return {}
128
+
129
+ # A regex match cannot establish whether async side effects must be awaited.
130
+ # Retain findings only when the reviewer has evaluated the surrounding code.
131
+ static_findings = []
132
+
133
+ # --- Build the LLM (Gemini primary → Groq fallback) -----------------------
134
+ try:
135
+ llm = create_llm(endpoint=state.endpoint or None, timeout=reviewer_timeout(state.review_mode), **({"max_tokens": 1200} if state.review_mode == "fast" else {}))
136
+ except ValueError as exc:
137
+ logger.warning("LLM unavailable — skipping correctness review: %s", exc)
138
+ return {"findings": static_findings, "review_stages": [stage_result("correctness", started, error=exc, llm=locals().get("llm"))]}
139
+
140
+ # --- Build the prompt ----------------------------------------------------
141
+ user_prompt = _build_prompt(state)
142
+ logger.info(
143
+ "Invoking correctness reviewer (diff=%s, context=%d chunks, prompt=%s, prompt_version=%s)",
144
+ _human_size(len(state.diff or "")),
145
+ len(state.context_chunks),
146
+ _human_size(len(user_prompt)),
147
+ PROMPT_VERSION,
148
+ )
149
+
150
+ # --- Invoke --------------------------------------------------------------
151
+ try:
152
+ messages = [
153
+ {"role": "system", "content": SYSTEM_PROMPT},
154
+ {"role": "user", "content": user_prompt},
155
+ ]
156
+ result: CorrectnessReview = invoke_review(llm, CorrectnessReview, messages, mode=state.review_mode) # type: ignore[assignment]
157
+ except Exception as exc:
158
+ logger.warning("Correctness review LLM call failed: %s", exc)
159
+ return {"findings": static_findings, "review_stages": [stage_result("correctness", started, error=exc, llm=llm)]}
160
+
161
+ # Deterministic guard for a high-impact async anti-pattern that LLMs can
162
+ # miss: promises created by forEach are not awaited by the caller.
163
+ result.findings.extend(static_findings)
164
+
165
+ # --- Log and return findings ---------------------------------------------
166
+ result.findings = calibrate_findings(result.findings, state)
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
+ "review_stages": [stage_result("correctness", started, llm=llm)],
184
+ }
185
+
186
+
187
+ # ─── Utility ─────────────────────────────────────────────────────────────────
188
+
189
+
190
+ def _human_size(bytes_: int) -> str:
191
+ if bytes_ < 1024:
192
+ return f"{bytes_} B"
193
+ elif bytes_ < 1024 * 1024:
194
+ return f"{bytes_ / 1024:.1f} KiB"
195
+ else:
196
+ return f"{bytes_ / (1024 * 1024):.1f} MiB"
nodes/security_reviewer.py CHANGED
@@ -1,143 +1,143 @@
1
- from __future__ import annotations
2
-
3
- import time
4
- import logging
5
- import os
6
- from pathlib import Path
7
-
8
- from backend.integrations.llm_factory import create_llm
9
- from nodes.finding_quality import calibrate_findings
10
- from nodes.review_runtime import changed_context, invoke_review, stage_result, reviewer_timeout
11
- from pydantic import BaseModel, Field
12
-
13
- from backend.state import Finding, OpenCodeReviewState
14
-
15
- logger = logging.getLogger(__name__)
16
-
17
- MAX_CONTEXT_CHARS = 6_000
18
- MAX_FILE_CONTENT_CHARS = 4_000
19
-
20
- # Prompt version — tied to the file on disk
21
- PROMPT_VERSION = "v1"
22
- PROMPT_FILE = Path(__file__).resolve().parent.parent / "prompts" / f"security_{PROMPT_VERSION}.txt"
23
-
24
-
25
- # ─── Load prompt from file ──────────────────────────────────────────────────
26
-
27
-
28
- def _load_prompt() -> str:
29
- """Load the system prompt from the versioned prompt file."""
30
- try:
31
- return PROMPT_FILE.read_text(encoding="utf-8")
32
- except FileNotFoundError:
33
- logger.warning("Prompt file %s not found — using fallback", PROMPT_FILE)
34
- return (
35
- "You are a security-focused code reviewer. "
36
- "Analyse the PR diff for security vulnerabilities: injection, "
37
- "secrets, unsafe deserialisation, auth issues, input validation, "
38
- "cryptographic misuse, and information disclosure. "
39
- "Return a list of findings."
40
- )
41
-
42
-
43
- SYSTEM_PROMPT = _load_prompt()
44
-
45
-
46
- # ─── Wrapper schema ──────────────────────────────────────────────────────────
47
-
48
-
49
- class SecurityReview(BaseModel):
50
- """Security issues found during code review."""
51
- findings: list[Finding] = Field(
52
- default_factory=list,
53
- description="Security issues found in the PR diff.",
54
- )
55
-
56
-
57
- # ─── Prompt builder ─────────────────────────────────────────────────────────
58
-
59
-
60
- def _build_prompt(state: OpenCodeReviewState) -> str:
61
- lines: list[str] = []
62
-
63
- lines.append("## Diff\n```diff")
64
- lines.append(state.diff or "")
65
- lines.append("```\n")
66
-
67
- if state.changed_files:
68
- lines.append("## Changed files\n")
69
- for cf in state.changed_files:
70
- lines.append(f"### {cf.path} ({cf.status})")
71
- content = changed_context(cf, state.review_mode)
72
- if len(content) > MAX_FILE_CONTENT_CHARS:
73
- content = content[:MAX_FILE_CONTENT_CHARS] + "\n… (truncated)"
74
- lines.append(f"```\n{content}\n```\n")
75
-
76
- if state.context_chunks:
77
- lines.append("## Retrieved context\n")
78
- ctx_chars = 0
79
- for chunk in state.context_chunks:
80
- snippet = chunk.content
81
- if ctx_chars + len(snippet) > MAX_CONTEXT_CHARS:
82
- remaining = MAX_CONTEXT_CHARS - ctx_chars
83
- if remaining > 200:
84
- lines.append(f"> {snippet[:remaining]}… (truncated)")
85
- break
86
- prefix = "Past PR" if chunk.source == "past_pr" else chunk.file_path
87
- lines.append(f"> [{prefix}]: {snippet}")
88
- ctx_chars += len(snippet)
89
-
90
- return "\n".join(lines)
91
-
92
-
93
- # ─── Node ────────────────────────────────────────────────────────────────────
94
-
95
-
96
- def security_reviewer_node(state: OpenCodeReviewState) -> dict:
97
- started = time.monotonic()
98
- if not state.diff:
99
- logger.info("No diff to review — skipping security review")
100
- return {}
101
-
102
- try:
103
- llm = create_llm(endpoint=state.endpoint or None, timeout=reviewer_timeout(state.review_mode), **({"max_tokens": 1200} if state.review_mode == "fast" else {}))
104
- except ValueError as exc:
105
- logger.warning("LLM unavailable — skipping security review: %s", exc)
106
- return {"review_stages": [stage_result("security", started, error=exc, llm=locals().get("llm"))]}
107
-
108
- user_prompt = _build_prompt(state)
109
- logger.info(
110
- "Invoking security reviewer (diff=%s, context=%d chunks, prompt_version=%s)",
111
- _human_size(len(state.diff or "")),
112
- len(state.context_chunks),
113
- PROMPT_VERSION,
114
- )
115
-
116
- try:
117
- messages = [
118
- {"role": "system", "content": SYSTEM_PROMPT},
119
- {"role": "user", "content": user_prompt},
120
- ]
121
- result: SecurityReview = invoke_review(llm, SecurityReview, messages, mode=state.review_mode) # type: ignore[assignment]
122
- except Exception as exc:
123
- logger.warning("Security review LLM call failed: %s", exc)
124
- return {"review_stages": [stage_result("security", started, error=exc, llm=locals().get("llm"))]}
125
-
126
- result.findings = calibrate_findings(result.findings, state)
127
- if result.findings:
128
- logger.info("Security review found %d issue(s)", len(result.findings))
129
- for f in result.findings:
130
- logger.debug(" [%.2f] %s:%d–%d — %s", f.confidence, f.file_path, f.line_start, f.line_end, f.comment[:80])
131
- else:
132
- logger.info("Security review found no issues")
133
-
134
- return {"findings": result.findings, "review_stages": [stage_result("security", started, llm=llm)]}
135
-
136
-
137
- def _human_size(bytes_: int) -> str:
138
- if bytes_ < 1024:
139
- return f"{bytes_} B"
140
- elif bytes_ < 1024 * 1024:
141
- return f"{bytes_ / 1024:.1f} KiB"
142
- else:
143
- return f"{bytes_ / (1024 * 1024):.1f} MiB"
 
1
+ from __future__ import annotations
2
+
3
+ import time
4
+ import logging
5
+ import os
6
+ from pathlib import Path
7
+
8
+ from backend.integrations.llm_factory import create_llm
9
+ from nodes.finding_quality import calibrate_findings
10
+ from nodes.review_runtime import changed_context, invoke_review, stage_result, reviewer_timeout
11
+ from pydantic import BaseModel, Field
12
+
13
+ from backend.state import Finding, OpenCodeReviewState
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+ MAX_CONTEXT_CHARS = 6_000
18
+ MAX_FILE_CONTENT_CHARS = 4_000
19
+
20
+ # Prompt version — tied to the file on disk
21
+ PROMPT_VERSION = "v1"
22
+ PROMPT_FILE = Path(__file__).resolve().parent.parent / "prompts" / f"security_{PROMPT_VERSION}.txt"
23
+
24
+
25
+ # ─── Load prompt from file ──────────────────────────────────────────────────
26
+
27
+
28
+ def _load_prompt() -> str:
29
+ """Load the system prompt from the versioned prompt file."""
30
+ try:
31
+ return PROMPT_FILE.read_text(encoding="utf-8")
32
+ except FileNotFoundError:
33
+ logger.warning("Prompt file %s not found — using fallback", PROMPT_FILE)
34
+ return (
35
+ "You are a security-focused code reviewer. "
36
+ "Analyse the PR diff for security vulnerabilities: injection, "
37
+ "secrets, unsafe deserialisation, auth issues, input validation, "
38
+ "cryptographic misuse, and information disclosure. "
39
+ "Return a list of findings."
40
+ )
41
+
42
+
43
+ SYSTEM_PROMPT = _load_prompt()
44
+
45
+
46
+ # ─── Wrapper schema ──────────────────────────────────────────────────────────
47
+
48
+
49
+ class SecurityReview(BaseModel):
50
+ """Security issues found during code review."""
51
+ findings: list[Finding] = Field(
52
+ default_factory=list,
53
+ description="Security issues found in the PR diff.",
54
+ )
55
+
56
+
57
+ # ─── Prompt builder ─────────────────────────────────────────────────────────
58
+
59
+
60
+ def _build_prompt(state: OpenCodeReviewState) -> str:
61
+ lines: list[str] = []
62
+
63
+ lines.append("## Diff\n```diff")
64
+ lines.append(state.diff or "")
65
+ lines.append("```\n")
66
+
67
+ if state.changed_files:
68
+ lines.append("## Changed files\n")
69
+ for cf in state.changed_files:
70
+ lines.append(f"### {cf.path} ({cf.status})")
71
+ content = changed_context(cf, state.review_mode)
72
+ if len(content) > MAX_FILE_CONTENT_CHARS:
73
+ content = content[:MAX_FILE_CONTENT_CHARS] + "\n… (truncated)"
74
+ lines.append(f"```\n{content}\n```\n")
75
+
76
+ if state.context_chunks:
77
+ lines.append("## Retrieved context\n")
78
+ ctx_chars = 0
79
+ for chunk in state.context_chunks:
80
+ snippet = chunk.content
81
+ if ctx_chars + len(snippet) > MAX_CONTEXT_CHARS:
82
+ remaining = MAX_CONTEXT_CHARS - ctx_chars
83
+ if remaining > 200:
84
+ lines.append(f"> {snippet[:remaining]}… (truncated)")
85
+ break
86
+ prefix = "Past PR" if chunk.source == "past_pr" else chunk.file_path
87
+ lines.append(f"> [{prefix}]: {snippet}")
88
+ ctx_chars += len(snippet)
89
+
90
+ return "\n".join(lines)
91
+
92
+
93
+ # ─── Node ────────────────────────────────────────────────────────────────────
94
+
95
+
96
+ def security_reviewer_node(state: OpenCodeReviewState) -> dict:
97
+ started = time.monotonic()
98
+ if not state.diff:
99
+ logger.info("No diff to review — skipping security review")
100
+ return {}
101
+
102
+ try:
103
+ llm = create_llm(endpoint=state.endpoint or None, timeout=reviewer_timeout(state.review_mode), **({"max_tokens": 1200} if state.review_mode == "fast" else {}))
104
+ except ValueError as exc:
105
+ logger.warning("LLM unavailable — skipping security review: %s", exc)
106
+ return {"review_stages": [stage_result("security", started, error=exc, llm=locals().get("llm"))]}
107
+
108
+ user_prompt = _build_prompt(state)
109
+ logger.info(
110
+ "Invoking security reviewer (diff=%s, context=%d chunks, prompt_version=%s)",
111
+ _human_size(len(state.diff or "")),
112
+ len(state.context_chunks),
113
+ PROMPT_VERSION,
114
+ )
115
+
116
+ try:
117
+ messages = [
118
+ {"role": "system", "content": SYSTEM_PROMPT},
119
+ {"role": "user", "content": user_prompt},
120
+ ]
121
+ result: SecurityReview = invoke_review(llm, SecurityReview, messages, mode=state.review_mode) # type: ignore[assignment]
122
+ except Exception as exc:
123
+ logger.warning("Security review LLM call failed: %s", exc)
124
+ return {"review_stages": [stage_result("security", started, error=exc, llm=locals().get("llm"))]}
125
+
126
+ result.findings = calibrate_findings(result.findings, state)
127
+ if result.findings:
128
+ logger.info("Security review found %d issue(s)", len(result.findings))
129
+ for f in result.findings:
130
+ logger.debug(" [%.2f] %s:%d–%d — %s", f.confidence, f.file_path, f.line_start, f.line_end, f.comment[:80])
131
+ else:
132
+ logger.info("Security review found no issues")
133
+
134
+ return {"findings": result.findings, "review_stages": [stage_result("security", started, llm=llm)]}
135
+
136
+
137
+ def _human_size(bytes_: int) -> str:
138
+ if bytes_ < 1024:
139
+ return f"{bytes_} B"
140
+ elif bytes_ < 1024 * 1024:
141
+ return f"{bytes_ / 1024:.1f} KiB"
142
+ else:
143
+ return f"{bytes_ / (1024 * 1024):.1f} MiB"
nodes/test_coverage_reviewer.py CHANGED
@@ -1,154 +1,154 @@
1
- from __future__ import annotations
2
-
3
- import time
4
- import logging
5
- import os
6
- from pathlib import Path
7
-
8
- from backend.integrations.llm_factory import create_llm
9
- from nodes.finding_quality import calibrate_findings
10
- from nodes.review_runtime import changed_context, invoke_review, stage_result, reviewer_timeout
11
- from pydantic import BaseModel, Field
12
-
13
- from backend.state import Finding, OpenCodeReviewState
14
-
15
- # This module contains a workflow node whose name starts with ``test_``.
16
- # Prevent pytest from treating that production function as a test case.
17
- __test__ = False
18
-
19
- logger = logging.getLogger(__name__)
20
-
21
- MAX_CONTEXT_CHARS = 6_000
22
- MAX_FILE_CONTENT_CHARS = 4_000
23
-
24
- # Prompt version — tied to the file on disk
25
- PROMPT_VERSION = "v1"
26
- PROMPT_FILE = Path(__file__).resolve().parent.parent / "prompts" / f"test_coverage_{PROMPT_VERSION}.txt"
27
-
28
-
29
- # ─── Load prompt from file ──────────────────────────────────────────────────
30
-
31
-
32
- def _load_prompt() -> str:
33
- """Load the system prompt from the versioned prompt file."""
34
- try:
35
- return PROMPT_FILE.read_text(encoding="utf-8")
36
- except FileNotFoundError:
37
- logger.warning("Prompt file %s not found — using fallback", PROMPT_FILE)
38
- return (
39
- "You are a code reviewer focused on test coverage. "
40
- "Analyse the PR diff and determine whether the changed logic "
41
- "has adequate test coverage. Return a list of findings."
42
- )
43
-
44
-
45
- SYSTEM_PROMPT = _load_prompt()
46
-
47
-
48
- # ─── Wrapper schema ──────────────────────────────────────────────────────────
49
-
50
-
51
- class TestCoverageReview(BaseModel):
52
- """Test-coverage gaps found during code review."""
53
- findings: list[Finding] = Field(
54
- default_factory=list,
55
- description="Test-coverage issues found in the PR diff.",
56
- )
57
-
58
-
59
- # ─── Prompt builder ─────────────────────────────────────────────────────────
60
-
61
-
62
- def _build_prompt(state: OpenCodeReviewState) -> str:
63
- lines: list[str] = []
64
-
65
- lines.append("## Diff\n```diff")
66
- lines.append(state.diff or "")
67
- lines.append("```\n")
68
-
69
- if state.changed_files:
70
- lines.append("## Changed files\n")
71
- for cf in state.changed_files:
72
- lines.append(f"### {cf.path} ({cf.status})")
73
- content = changed_context(cf, state.review_mode)
74
- if len(content) > MAX_FILE_CONTENT_CHARS:
75
- content = content[:MAX_FILE_CONTENT_CHARS] + "\n… (truncated)"
76
- lines.append(f"```\n{content}\n```\n")
77
-
78
- if state.context_chunks:
79
- lines.append("## Retrieved context\n")
80
- ctx_chars = 0
81
- for chunk in state.context_chunks:
82
- snippet = chunk.content
83
- if ctx_chars + len(snippet) > MAX_CONTEXT_CHARS:
84
- remaining = MAX_CONTEXT_CHARS - ctx_chars
85
- if remaining > 200:
86
- lines.append(f"> {snippet[:remaining]}… (truncated)")
87
- break
88
- prefix = "Past PR" if chunk.source == "past_pr" else chunk.file_path
89
- lines.append(f"> [{prefix}]: {snippet}")
90
- ctx_chars += len(snippet)
91
-
92
- return "\n".join(lines)
93
-
94
-
95
- # ─── Node ────────────────────────────────────────────────────────────────────
96
-
97
-
98
- def test_coverage_reviewer_node(state: OpenCodeReviewState) -> dict:
99
- started = time.monotonic()
100
- if not state.diff:
101
- logger.info("No diff to review — skipping test-coverage review")
102
- return {}
103
-
104
- # Fast mode avoids a test specialist for documentation-only changes.
105
- # Security and correctness still run; executable/config/unknown files
106
- # always retain all reviewers, as does Thorough mode.
107
- if state.review_mode == 'fast' and state.changed_files and all(
108
- cf.path.lower().endswith(('.md', '.rst', '.txt')) for cf in state.changed_files
109
- ):
110
- return {'review_stages': [{'reviewer': 'test_coverage', 'status': 'skipped',
111
- 'reason': 'Fast mode: documentation-only changes', 'duration_seconds': 0.0, 'model': ''}]}
112
-
113
- try:
114
- llm = create_llm(endpoint=state.endpoint or None, timeout=reviewer_timeout(state.review_mode), **({"max_tokens": 1200} if state.review_mode == "fast" else {}))
115
- except ValueError as exc:
116
- logger.warning("LLM unavailable — skipping test-coverage review: %s", exc)
117
- return {"review_stages": [stage_result("test_coverage", started, error=exc, llm=locals().get("llm"))]}
118
-
119
- user_prompt = _build_prompt(state)
120
- logger.info(
121
- "Invoking test-coverage reviewer (diff=%s, context=%d chunks, prompt_version=%s)",
122
- _human_size(len(state.diff or "")),
123
- len(state.context_chunks),
124
- PROMPT_VERSION,
125
- )
126
-
127
- try:
128
- messages = [
129
- {"role": "system", "content": SYSTEM_PROMPT},
130
- {"role": "user", "content": user_prompt},
131
- ]
132
- result: TestCoverageReview = invoke_review(llm, TestCoverageReview, messages, mode=state.review_mode) # type: ignore[assignment]
133
- except Exception as exc:
134
- logger.warning("Test-coverage review LLM call failed: %s", exc)
135
- return {"review_stages": [stage_result("test_coverage", started, error=exc, llm=locals().get("llm"))]}
136
-
137
- result.findings = calibrate_findings(result.findings, state)
138
- if result.findings:
139
- logger.info("Test-coverage review found %d issue(s)", len(result.findings))
140
- for f in result.findings:
141
- logger.debug(" [%.2f] %s:%d–%d — %s", f.confidence, f.file_path, f.line_start, f.line_end, f.comment[:80])
142
- else:
143
- logger.info("Test-coverage review found no issues")
144
-
145
- return {"findings": result.findings, "review_stages": [stage_result("test_coverage", started, llm=llm)]}
146
-
147
-
148
- def _human_size(bytes_: int) -> str:
149
- if bytes_ < 1024:
150
- return f"{bytes_} B"
151
- elif bytes_ < 1024 * 1024:
152
- return f"{bytes_ / 1024:.1f} KiB"
153
- else:
154
- return f"{bytes_ / (1024 * 1024):.1f} MiB"
 
1
+ from __future__ import annotations
2
+
3
+ import time
4
+ import logging
5
+ import os
6
+ from pathlib import Path
7
+
8
+ from backend.integrations.llm_factory import create_llm
9
+ from nodes.finding_quality import calibrate_findings
10
+ from nodes.review_runtime import changed_context, invoke_review, stage_result, reviewer_timeout
11
+ from pydantic import BaseModel, Field
12
+
13
+ from backend.state import Finding, OpenCodeReviewState
14
+
15
+ # This module contains a workflow node whose name starts with ``test_``.
16
+ # Prevent pytest from treating that production function as a test case.
17
+ __test__ = False
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+ MAX_CONTEXT_CHARS = 6_000
22
+ MAX_FILE_CONTENT_CHARS = 4_000
23
+
24
+ # Prompt version — tied to the file on disk
25
+ PROMPT_VERSION = "v1"
26
+ PROMPT_FILE = Path(__file__).resolve().parent.parent / "prompts" / f"test_coverage_{PROMPT_VERSION}.txt"
27
+
28
+
29
+ # ─── Load prompt from file ──────────────────────────────────────────────────
30
+
31
+
32
+ def _load_prompt() -> str:
33
+ """Load the system prompt from the versioned prompt file."""
34
+ try:
35
+ return PROMPT_FILE.read_text(encoding="utf-8")
36
+ except FileNotFoundError:
37
+ logger.warning("Prompt file %s not found — using fallback", PROMPT_FILE)
38
+ return (
39
+ "You are a code reviewer focused on test coverage. "
40
+ "Analyse the PR diff and determine whether the changed logic "
41
+ "has adequate test coverage. Return a list of findings."
42
+ )
43
+
44
+
45
+ SYSTEM_PROMPT = _load_prompt()
46
+
47
+
48
+ # ─── Wrapper schema ──────────────────────────────────────────────────────────
49
+
50
+
51
+ class TestCoverageReview(BaseModel):
52
+ """Test-coverage gaps found during code review."""
53
+ findings: list[Finding] = Field(
54
+ default_factory=list,
55
+ description="Test-coverage issues found in the PR diff.",
56
+ )
57
+
58
+
59
+ # ─── Prompt builder ─────────────────────────────────────────────────────────
60
+
61
+
62
+ def _build_prompt(state: OpenCodeReviewState) -> str:
63
+ lines: list[str] = []
64
+
65
+ lines.append("## Diff\n```diff")
66
+ lines.append(state.diff or "")
67
+ lines.append("```\n")
68
+
69
+ if state.changed_files:
70
+ lines.append("## Changed files\n")
71
+ for cf in state.changed_files:
72
+ lines.append(f"### {cf.path} ({cf.status})")
73
+ content = changed_context(cf, state.review_mode)
74
+ if len(content) > MAX_FILE_CONTENT_CHARS:
75
+ content = content[:MAX_FILE_CONTENT_CHARS] + "\n… (truncated)"
76
+ lines.append(f"```\n{content}\n```\n")
77
+
78
+ if state.context_chunks:
79
+ lines.append("## Retrieved context\n")
80
+ ctx_chars = 0
81
+ for chunk in state.context_chunks:
82
+ snippet = chunk.content
83
+ if ctx_chars + len(snippet) > MAX_CONTEXT_CHARS:
84
+ remaining = MAX_CONTEXT_CHARS - ctx_chars
85
+ if remaining > 200:
86
+ lines.append(f"> {snippet[:remaining]}… (truncated)")
87
+ break
88
+ prefix = "Past PR" if chunk.source == "past_pr" else chunk.file_path
89
+ lines.append(f"> [{prefix}]: {snippet}")
90
+ ctx_chars += len(snippet)
91
+
92
+ return "\n".join(lines)
93
+
94
+
95
+ # ─── Node ───────────────────────────────────��────────────────────────────────
96
+
97
+
98
+ def test_coverage_reviewer_node(state: OpenCodeReviewState) -> dict:
99
+ started = time.monotonic()
100
+ if not state.diff:
101
+ logger.info("No diff to review — skipping test-coverage review")
102
+ return {}
103
+
104
+ # Fast mode avoids a test specialist for documentation-only changes.
105
+ # Security and correctness still run; executable/config/unknown files
106
+ # always retain all reviewers, as does Thorough mode.
107
+ if state.review_mode == 'fast' and state.changed_files and all(
108
+ cf.path.lower().endswith(('.md', '.rst', '.txt')) for cf in state.changed_files
109
+ ):
110
+ return {'review_stages': [{'reviewer': 'test_coverage', 'status': 'skipped',
111
+ 'reason': 'Fast mode: documentation-only changes', 'duration_seconds': 0.0, 'model': ''}]}
112
+
113
+ try:
114
+ llm = create_llm(endpoint=state.endpoint or None, timeout=reviewer_timeout(state.review_mode), **({"max_tokens": 1200} if state.review_mode == "fast" else {}))
115
+ except ValueError as exc:
116
+ logger.warning("LLM unavailable — skipping test-coverage review: %s", exc)
117
+ return {"review_stages": [stage_result("test_coverage", started, error=exc, llm=locals().get("llm"))]}
118
+
119
+ user_prompt = _build_prompt(state)
120
+ logger.info(
121
+ "Invoking test-coverage reviewer (diff=%s, context=%d chunks, prompt_version=%s)",
122
+ _human_size(len(state.diff or "")),
123
+ len(state.context_chunks),
124
+ PROMPT_VERSION,
125
+ )
126
+
127
+ try:
128
+ messages = [
129
+ {"role": "system", "content": SYSTEM_PROMPT},
130
+ {"role": "user", "content": user_prompt},
131
+ ]
132
+ result: TestCoverageReview = invoke_review(llm, TestCoverageReview, messages, mode=state.review_mode) # type: ignore[assignment]
133
+ except Exception as exc:
134
+ logger.warning("Test-coverage review LLM call failed: %s", exc)
135
+ return {"review_stages": [stage_result("test_coverage", started, error=exc, llm=locals().get("llm"))]}
136
+
137
+ result.findings = calibrate_findings(result.findings, state)
138
+ if result.findings:
139
+ logger.info("Test-coverage review found %d issue(s)", len(result.findings))
140
+ for f in result.findings:
141
+ logger.debug(" [%.2f] %s:%d–%d — %s", f.confidence, f.file_path, f.line_start, f.line_end, f.comment[:80])
142
+ else:
143
+ logger.info("Test-coverage review found no issues")
144
+
145
+ return {"findings": result.findings, "review_stages": [stage_result("test_coverage", started, llm=llm)]}
146
+
147
+
148
+ def _human_size(bytes_: int) -> str:
149
+ if bytes_ < 1024:
150
+ return f"{bytes_} B"
151
+ elif bytes_ < 1024 * 1024:
152
+ return f"{bytes_ / 1024:.1f} KiB"
153
+ else:
154
+ return f"{bytes_ / (1024 * 1024):.1f} MiB"
tests/test_evaluation_quality.py CHANGED
@@ -1,133 +1,133 @@
1
- import sys
2
- import time
3
- from types import SimpleNamespace
4
-
5
- import pytest
6
-
7
- from eval_data import ragas_eval
8
- from observability import TokenCostCallback, estimate_model_cost
9
- from eval_data.offline_regression import evaluate
10
-
11
-
12
- def prepare(monkeypatch):
13
- monkeypatch.setattr(ragas_eval, "_check_ragas", lambda: True)
14
- monkeypatch.setattr(ragas_eval, "_get_evaluator_llm", lambda endpoint, **kwargs: object())
15
- monkeypatch.setitem(sys.modules, "ragas.dataset_schema", SimpleNamespace(SingleTurnSample=lambda **kwargs: kwargs))
16
-
17
-
18
- def test_metrics_keep_success_when_other_metric_times_out(monkeypatch):
19
- prepare(monkeypatch)
20
- def score(name, *args):
21
- if name == "faithfulness":
22
- time.sleep(.2)
23
- return .75
24
- monkeypatch.setattr(ragas_eval, "_score_one_metric", score)
25
- report = ragas_eval.compute_ragas_report("query", ["context"], answer="answer", metric_timeout=.03)
26
- assert report["scores"] == {"context_precision": .75}
27
- assert report["metrics"]["faithfulness"]["status"] == "timed_out"
28
- assert report["metrics"]["answer_relevancy"]["status"] == "skipped"
29
-
30
-
31
- def test_failed_judges_never_generate_fake_fallback_scores(monkeypatch):
32
- prepare(monkeypatch)
33
- def fail(*args):
34
- raise RuntimeError("provider unavailable")
35
- monkeypatch.setattr(ragas_eval, "_score_one_metric", fail)
36
- report = ragas_eval.compute_ragas_report("same text", ["same text"], answer="same text")
37
- assert report["scores"] == {}
38
- assert report["metrics"]["context_precision"]["value"] is None
39
-
40
-
41
- def test_no_context_is_not_a_zero_quality_measurement():
42
- report = ragas_eval.compute_ragas_report("query", [], answer="answer")
43
- assert report["scores"] == {}
44
- assert all(metric["status"] == "skipped" for metric in report["metrics"].values())
45
-
46
-
47
- def test_parallel_metrics_have_independent_evaluators(monkeypatch):
48
- prepare(monkeypatch)
49
- evaluators = []
50
- def factory(endpoint, **kwargs):
51
- evaluator = object()
52
- evaluators.append(evaluator)
53
- return evaluator
54
- monkeypatch.setattr(ragas_eval, "_get_evaluator_llm", factory)
55
- monkeypatch.setattr(ragas_eval, "_score_one_metric", lambda *args: .5)
56
- report = ragas_eval.compute_ragas_report("query", ["context"], answer="answer")
57
- assert len(evaluators) == 2
58
- assert evaluators[0] is not evaluators[1]
59
- assert len(report["scores"]) == 2
60
-
61
-
62
- def test_metric_deadline_is_passed_to_evaluator(monkeypatch):
63
- prepare(monkeypatch)
64
- timeouts = []
65
- monkeypatch.setattr(
66
- ragas_eval,
67
- "_get_evaluator_llm",
68
- lambda endpoint, *, timeout: timeouts.append(timeout) or object(),
69
- )
70
- monkeypatch.setattr(ragas_eval, "_score_one_metric", lambda *args: .5)
71
- report = ragas_eval.compute_ragas_report(
72
- "query", ["context"], answer="answer", metric_timeout=3
73
- )
74
- assert timeouts == [3, 3]
75
- assert len(report["scores"]) == 2
76
-
77
-
78
- def test_evaluator_wrapper_uses_supplied_timeout(monkeypatch):
79
- captured = {}
80
-
81
- class FakeRunConfig:
82
- def __init__(self, **kwargs):
83
- captured.update(kwargs)
84
-
85
- class FakeWrapper:
86
- def __init__(self, model, *, run_config):
87
- captured["model"] = model
88
- captured["run_config"] = run_config
89
-
90
- monkeypatch.setitem(sys.modules, "ragas.llms", SimpleNamespace(LangchainLLMWrapper=FakeWrapper))
91
- monkeypatch.setitem(sys.modules, "ragas.run_config", SimpleNamespace(RunConfig=FakeRunConfig))
92
- ragas_eval._wrap_evaluator(object(), timeout=27)
93
- assert captured["timeout"] == 27
94
- assert captured["max_retries"] == 0
95
-
96
-
97
- def test_metric_errors_are_actionable_without_provider_secrets():
98
- connection_error = type("OpenAIConnectionError", (Exception,), {})
99
- status, error = ragas_eval._safe_metric_error(connection_error("secret-api-key"))
100
- assert status == "failed"
101
- assert "connection failed" in error
102
- assert "secret-api-key" not in error
103
- assert ragas_eval._safe_metric_error(TimeoutError())[0] == "timed_out"
104
-
105
-
106
- def test_cost_free_estimate_is_distinct_from_provider_report():
107
- callback = TokenCostCallback()
108
- callback.on_llm_end(SimpleNamespace(llm_output={"model_name": "minimax/test:free", "token_usage": {"prompt_tokens": 1000, "completion_tokens": 2000}}))
109
- assert callback.details()["amount"] == 0
110
- assert callback.details()["source"] == "free_model_estimate"
111
- assert "not billing" in callback.summary()
112
- callback.reset()
113
- callback.on_llm_end(SimpleNamespace(llm_output={"model_name": "unknown", "token_usage": {"prompt_tokens": 10, "completion_tokens": 20, "cost": .123}}))
114
- assert callback.details()["source"] == "provider_reported"
115
- assert callback.details()["amount"] == .123
116
-
117
-
118
- def test_unknown_model_cost_stays_unknown():
119
- assert estimate_model_cost("unknown", 10000, 10000) is None
120
- callback = TokenCostCallback()
121
- callback.on_llm_end(SimpleNamespace(llm_output={"model_name": "unknown", "token_usage": {"prompt_tokens": 10, "completion_tokens": 20}}))
122
- assert callback.details()["amount"] is None
123
- assert "unknown" in callback.summary().lower()
124
-
125
-
126
- def test_offline_matching_counts_duplicate_only_once():
127
- finding = {"file_path": "auth.ts", "line_start": 10, "category": "security", "comment": "Concurrent race allows reuse"}
128
- fixtures = [{"label_scope": "exhaustive", "repo": "test/repo", "pr_number": 1, "findings": [{**finding, "concept_terms": ["race", "reuse"]}]}]
129
- report = evaluate([{"repo": "test/repo", "pr_number": 1, "findings": [finding, finding]}], fixtures)
130
- assert report["totals"]["matched"] == 1
131
- assert report["totals"]["duplicate_predictions"] == 1
132
- assert report["precision"] == .5
133
- assert report["recall"] == 1
 
1
+ import sys
2
+ import time
3
+ from types import SimpleNamespace
4
+
5
+ import pytest
6
+
7
+ from eval_data import ragas_eval
8
+ from observability import TokenCostCallback, estimate_model_cost
9
+ from eval_data.offline_regression import evaluate
10
+
11
+
12
+ def prepare(monkeypatch):
13
+ monkeypatch.setattr(ragas_eval, "_check_ragas", lambda: True)
14
+ monkeypatch.setattr(ragas_eval, "_get_evaluator_llm", lambda endpoint, **kwargs: object())
15
+ monkeypatch.setitem(sys.modules, "ragas.dataset_schema", SimpleNamespace(SingleTurnSample=lambda **kwargs: kwargs))
16
+
17
+
18
+ def test_metrics_keep_success_when_other_metric_times_out(monkeypatch):
19
+ prepare(monkeypatch)
20
+ def score(name, *args):
21
+ if name == "faithfulness":
22
+ time.sleep(.2)
23
+ return .75
24
+ monkeypatch.setattr(ragas_eval, "_score_one_metric", score)
25
+ report = ragas_eval.compute_ragas_report("query", ["context"], answer="answer", metric_timeout=.03)
26
+ assert report["scores"] == {"context_precision": .75}
27
+ assert report["metrics"]["faithfulness"]["status"] == "timed_out"
28
+ assert report["metrics"]["answer_relevancy"]["status"] == "skipped"
29
+
30
+
31
+ def test_failed_judges_never_generate_fake_fallback_scores(monkeypatch):
32
+ prepare(monkeypatch)
33
+ def fail(*args):
34
+ raise RuntimeError("provider unavailable")
35
+ monkeypatch.setattr(ragas_eval, "_score_one_metric", fail)
36
+ report = ragas_eval.compute_ragas_report("same text", ["same text"], answer="same text")
37
+ assert report["scores"] == {}
38
+ assert report["metrics"]["context_precision"]["value"] is None
39
+
40
+
41
+ def test_no_context_is_not_a_zero_quality_measurement():
42
+ report = ragas_eval.compute_ragas_report("query", [], answer="answer")
43
+ assert report["scores"] == {}
44
+ assert all(metric["status"] == "skipped" for metric in report["metrics"].values())
45
+
46
+
47
+ def test_parallel_metrics_have_independent_evaluators(monkeypatch):
48
+ prepare(monkeypatch)
49
+ evaluators = []
50
+ def factory(endpoint, **kwargs):
51
+ evaluator = object()
52
+ evaluators.append(evaluator)
53
+ return evaluator
54
+ monkeypatch.setattr(ragas_eval, "_get_evaluator_llm", factory)
55
+ monkeypatch.setattr(ragas_eval, "_score_one_metric", lambda *args: .5)
56
+ report = ragas_eval.compute_ragas_report("query", ["context"], answer="answer")
57
+ assert len(evaluators) == 2
58
+ assert evaluators[0] is not evaluators[1]
59
+ assert len(report["scores"]) == 2
60
+
61
+
62
+ def test_metric_deadline_is_passed_to_evaluator(monkeypatch):
63
+ prepare(monkeypatch)
64
+ timeouts = []
65
+ monkeypatch.setattr(
66
+ ragas_eval,
67
+ "_get_evaluator_llm",
68
+ lambda endpoint, *, timeout: timeouts.append(timeout) or object(),
69
+ )
70
+ monkeypatch.setattr(ragas_eval, "_score_one_metric", lambda *args: .5)
71
+ report = ragas_eval.compute_ragas_report(
72
+ "query", ["context"], answer="answer", metric_timeout=3
73
+ )
74
+ assert timeouts == [3, 3]
75
+ assert len(report["scores"]) == 2
76
+
77
+
78
+ def test_evaluator_wrapper_uses_supplied_timeout(monkeypatch):
79
+ captured = {}
80
+
81
+ class FakeRunConfig:
82
+ def __init__(self, **kwargs):
83
+ captured.update(kwargs)
84
+
85
+ class FakeWrapper:
86
+ def __init__(self, model, *, run_config):
87
+ captured["model"] = model
88
+ captured["run_config"] = run_config
89
+
90
+ monkeypatch.setitem(sys.modules, "ragas.llms", SimpleNamespace(LangchainLLMWrapper=FakeWrapper))
91
+ monkeypatch.setitem(sys.modules, "ragas.run_config", SimpleNamespace(RunConfig=FakeRunConfig))
92
+ ragas_eval._wrap_evaluator(object(), timeout=27)
93
+ assert captured["timeout"] == 27
94
+ assert captured["max_retries"] == 0
95
+
96
+
97
+ def test_metric_errors_are_actionable_without_provider_secrets():
98
+ connection_error = type("OpenAIConnectionError", (Exception,), {})
99
+ status, error = ragas_eval._safe_metric_error(connection_error("secret-api-key"))
100
+ assert status == "failed"
101
+ assert "connection failed" in error
102
+ assert "secret-api-key" not in error
103
+ assert ragas_eval._safe_metric_error(TimeoutError())[0] == "timed_out"
104
+
105
+
106
+ def test_cost_free_estimate_is_distinct_from_provider_report():
107
+ callback = TokenCostCallback()
108
+ callback.on_llm_end(SimpleNamespace(llm_output={"model_name": "minimax/test:free", "token_usage": {"prompt_tokens": 1000, "completion_tokens": 2000}}))
109
+ assert callback.details()["amount"] == 0
110
+ assert callback.details()["source"] == "free_model_estimate"
111
+ assert "not billing" in callback.summary()
112
+ callback.reset()
113
+ callback.on_llm_end(SimpleNamespace(llm_output={"model_name": "unknown", "token_usage": {"prompt_tokens": 10, "completion_tokens": 20, "cost": .123}}))
114
+ assert callback.details()["source"] == "provider_reported"
115
+ assert callback.details()["amount"] == .123
116
+
117
+
118
+ def test_unknown_model_cost_stays_unknown():
119
+ assert estimate_model_cost("unknown", 10000, 10000) is None
120
+ callback = TokenCostCallback()
121
+ callback.on_llm_end(SimpleNamespace(llm_output={"model_name": "unknown", "token_usage": {"prompt_tokens": 10, "completion_tokens": 20}}))
122
+ assert callback.details()["amount"] is None
123
+ assert "unknown" in callback.summary().lower()
124
+
125
+
126
+ def test_offline_matching_counts_duplicate_only_once():
127
+ finding = {"file_path": "auth.ts", "line_start": 10, "category": "security", "comment": "Concurrent race allows reuse"}
128
+ fixtures = [{"label_scope": "exhaustive", "repo": "test/repo", "pr_number": 1, "findings": [{**finding, "concept_terms": ["race", "reuse"]}]}]
129
+ report = evaluate([{"repo": "test/repo", "pr_number": 1, "findings": [finding, finding]}], fixtures)
130
+ assert report["totals"]["matched"] == 1
131
+ assert report["totals"]["duplicate_predictions"] == 1
132
+ assert report["precision"] == .5
133
+ assert report["recall"] == 1
tests/test_job_speed.py CHANGED
@@ -1,138 +1,138 @@
1
- """Exercise API scheduling without importing the heavyweight model runtime."""
2
- import ast
3
- from contextvars import ContextVar
4
- from pathlib import Path
5
- from types import SimpleNamespace
6
- from unittest.mock import Mock
7
- import hashlib
8
- import json
9
- import secrets
10
- import threading
11
- import time
12
- import uuid
13
- from datetime import datetime, timezone
14
- from typing import Any
15
-
16
- import pytest
17
- from fastapi import HTTPException
18
-
19
-
20
- def test_incomplete_review_never_starts_ragas():
21
- tree = ast.parse(Path('backend/app.py').read_text(encoding='utf-8'))
22
- function = next(node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name == '_ragas_inputs_from_state')
23
- ns = {}
24
- exec(compile(ast.Module(body=[function], type_ignores=[]), 'backend/app.py', 'exec'), ns)
25
- state = SimpleNamespace(values={'verdict': SimpleNamespace(recommendation='incomplete'), 'diff': 'change'})
26
- assert ns['_ragas_inputs_from_state'](state, 'custom') is None
27
-
28
-
29
- def test_feedback_is_persisted_for_existing_finding_only():
30
- ns = scheduler()
31
- ns['_jobs']['job'] = {'id': 'job', 'owner_id': '1', 'status': 'awaiting_approval', 'findings': [{'comment': 'evidence'}]}
32
- vote = SimpleNamespace(finding_index=0, label='incorrect')
33
- assert ns['finding_feedback']('job', vote, SimpleNamespace(owner=1)) == {'feedback': {'0': 'incorrect'}}
34
- ns['_save_job'].assert_called_once()
35
- with pytest.raises(HTTPException) as absent:
36
- ns['finding_feedback']('job', SimpleNamespace(finding_index=1, label='correct'), SimpleNamespace(owner=1))
37
- assert absent.value.status_code == 422
38
- with pytest.raises(HTTPException) as foreign:
39
- ns['finding_feedback']('job', vote, SimpleNamespace(owner=2))
40
- assert foreign.value.status_code == 404
41
-
42
-
43
- def test_public_job_never_exposes_evaluator_endpoint_snapshot():
44
- ns = scheduler()
45
- job = {'id': 'job', 'status': 'incomplete', 'ragas_inputs': {'endpoint': {'api_key': 'private'}}, 'config': {}}
46
- assert 'ragas_inputs' not in ns['_public_job'](job)
47
-
48
-
49
- def scheduler():
50
- tree = ast.parse(Path('backend/api.py').read_text(encoding='utf-8'))
51
- names = {'create_review', 'cancel_review', '_public_job', 'get_review', 'decide_review', 'finding_feedback'}
52
- nodes = [node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name in names]
53
- for node in nodes:
54
- node.decorator_list = []
55
- ns = dict(__file__=str(Path('backend/api.py').resolve()), Path=Path, Any=Any, Request=object, ReviewRequest=object,
56
- Header=lambda *a, **k: None, DecisionRequest=object, FindingFeedbackRequest=object, HTTPException=HTTPException, hashlib=hashlib, json=json,
57
- threading=threading, time=time, uuid=uuid, datetime=datetime, timezone=timezone,
58
- os=SimpleNamespace(getenv=lambda *a: ''), requests=SimpleNamespace(get=Mock()),
59
- _jobs={}, _lock=threading.Lock(), _save_job=Mock(), _executor=SimpleNamespace(submit=Mock()),
60
- _run_job=Mock(), _load_job=Mock(return_value=None), _authorize_request=Mock(), _rate_limit=Mock(),
61
- _session=lambda request: {'github_id': request.owner})
62
- ns['requests'].RequestException = RuntimeError
63
- ns['requests'].get.return_value.json.return_value = {'head': {'sha': 'a'*40}, 'base': {'sha': 'b'*40}}
64
- exec(compile(ast.Module(body=nodes, type_ignores=[]), 'backend/api.py', 'exec'), ns)
65
- return ns
66
-
67
-
68
- def request(model='m1'):
69
- values = dict(repo='owner/repo', pr_number=1, endpoint='auto', review_mode='thorough',
70
- provider='openai', model=model, api_key='secret', base_url='', baseline_sha=None)
71
- return SimpleNamespace(**values, model_dump=lambda: values)
72
-
73
-
74
- def test_identical_active_request_reuses_job_but_other_model_does_not():
75
- ns = scheduler()
76
- create = ns['create_review']
77
- first = create(request(), SimpleNamespace(owner=1))
78
- second = create(request(), SimpleNamespace(owner=1))
79
- third = create(request('m2'), SimpleNamespace(owner=1))
80
- assert second['id'] == first['id'] and second['reused']
81
- assert third['id'] != first['id']
82
- assert ns['_executor'].submit.call_count == 2
83
-
84
-
85
- def test_cache_is_scoped_to_owner_and_immutable_commit():
86
- ns = scheduler()
87
- create = ns['create_review']
88
- first = create(request(), SimpleNamespace(owner=1))
89
- job = ns['_jobs'][first['id']]
90
- job.update(status='awaiting_approval', started_timestamp=time.time())
91
- assert create(request(), SimpleNamespace(owner=1))['id'] == first['id']
92
- assert create(request(), SimpleNamespace(owner=2))['id'] != first['id']
93
- ns['requests'].get.return_value.json.return_value['head']['sha'] = 'c'*40
94
- assert create(request(), SimpleNamespace(owner=1))['id'] != first['id']
95
-
96
-
97
- def test_cancellation_is_owner_scoped_and_terminal():
98
- ns = scheduler()
99
- job = ns['create_review'](request(), SimpleNamespace(owner=1))
100
- with pytest.raises(HTTPException):
101
- ns['cancel_review'](job['id'], SimpleNamespace(owner=2))
102
- assert ns['cancel_review'](job['id'], SimpleNamespace(owner=1))['status'] == 'cancelled'
103
- assert ns['create_review'](request(), SimpleNamespace(owner=1))['id'] != job['id']
104
- def test_evaluation_quota_stops_followup_calls():
105
- tree = ast.parse(Path('eval_data/ragas_eval.py').read_text(encoding='utf-8'))
106
- node = next(node for node in tree.body if isinstance(node, ast.ClassDef) and node.name == '_ThrottledChatModel')
107
- ns = {'_RAGAS_INTERVAL': 0, '_ragas_throttle_lock': threading.Lock(), 'time': time, '_metric_deadline': ContextVar('test_deadline', default=None)}
108
- exec(compile(ast.Module(body=[node], type_ignores=[]), 'ragas_eval.py', 'exec'), ns)
109
- model = Mock()
110
- quota = RuntimeError('rate_limit_exceeded')
111
- quota.status_code = 429
112
- model.invoke.side_effect = quota
113
- wrapped = ns['_ThrottledChatModel'](model)
114
- with pytest.raises(RuntimeError):
115
- wrapped.invoke('first')
116
- with pytest.raises(RuntimeError, match='Evaluation stopped'):
117
- wrapped.invoke('second')
118
- assert model.invoke.call_count == 1
119
-
120
-
121
- def test_read_and_decision_require_job_owner():
122
- ns = scheduler()
123
- job = ns['create_review'](request(), SimpleNamespace(owner=1))
124
- with pytest.raises(HTTPException) as error:
125
- ns['get_review'](job['id'], SimpleNamespace(owner=2))
126
- assert error.value.status_code == 404
127
- with pytest.raises(HTTPException) as error:
128
- ns['decide_review'](job['id'], SimpleNamespace(action='approve'), SimpleNamespace(owner=2))
129
- assert error.value.status_code == 404
130
-
131
-
132
- def test_incremental_review_cannot_post_approval():
133
- ns = scheduler()
134
- job = ns['create_review'](request(), SimpleNamespace(owner=1))
135
- ns['_jobs'][job['id']].update(status='awaiting_approval', baseline_sha='f'*40)
136
- with pytest.raises(HTTPException) as error:
137
- ns['decide_review'](job['id'], SimpleNamespace(action='approve'), SimpleNamespace(owner=1))
138
- assert error.value.status_code == 409
 
1
+ """Exercise API scheduling without importing the heavyweight model runtime."""
2
+ import ast
3
+ from contextvars import ContextVar
4
+ from pathlib import Path
5
+ from types import SimpleNamespace
6
+ from unittest.mock import Mock
7
+ import hashlib
8
+ import json
9
+ import secrets
10
+ import threading
11
+ import time
12
+ import uuid
13
+ from datetime import datetime, timezone
14
+ from typing import Any
15
+
16
+ import pytest
17
+ from fastapi import HTTPException
18
+
19
+
20
+ def test_incomplete_review_never_starts_ragas():
21
+ tree = ast.parse(Path('backend/app.py').read_text(encoding='utf-8'))
22
+ function = next(node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name == '_ragas_inputs_from_state')
23
+ ns = {}
24
+ exec(compile(ast.Module(body=[function], type_ignores=[]), 'backend/app.py', 'exec'), ns)
25
+ state = SimpleNamespace(values={'verdict': SimpleNamespace(recommendation='incomplete'), 'diff': 'change'})
26
+ assert ns['_ragas_inputs_from_state'](state, 'custom') is None
27
+
28
+
29
+ def test_feedback_is_persisted_for_existing_finding_only():
30
+ ns = scheduler()
31
+ ns['_jobs']['job'] = {'id': 'job', 'owner_id': '1', 'status': 'awaiting_approval', 'findings': [{'comment': 'evidence'}]}
32
+ vote = SimpleNamespace(finding_index=0, label='incorrect')
33
+ assert ns['finding_feedback']('job', vote, SimpleNamespace(owner=1)) == {'feedback': {'0': 'incorrect'}}
34
+ ns['_save_job'].assert_called_once()
35
+ with pytest.raises(HTTPException) as absent:
36
+ ns['finding_feedback']('job', SimpleNamespace(finding_index=1, label='correct'), SimpleNamespace(owner=1))
37
+ assert absent.value.status_code == 422
38
+ with pytest.raises(HTTPException) as foreign:
39
+ ns['finding_feedback']('job', vote, SimpleNamespace(owner=2))
40
+ assert foreign.value.status_code == 404
41
+
42
+
43
+ def test_public_job_never_exposes_evaluator_endpoint_snapshot():
44
+ ns = scheduler()
45
+ job = {'id': 'job', 'status': 'incomplete', 'ragas_inputs': {'endpoint': {'api_key': 'private'}}, 'config': {}}
46
+ assert 'ragas_inputs' not in ns['_public_job'](job)
47
+
48
+
49
+ def scheduler():
50
+ tree = ast.parse(Path('backend/api.py').read_text(encoding='utf-8'))
51
+ names = {'create_review', 'cancel_review', '_public_job', 'get_review', 'decide_review', 'finding_feedback'}
52
+ nodes = [node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name in names]
53
+ for node in nodes:
54
+ node.decorator_list = []
55
+ ns = dict(__file__=str(Path('backend/api.py').resolve()), Path=Path, Any=Any, Request=object, ReviewRequest=object,
56
+ Header=lambda *a, **k: None, DecisionRequest=object, FindingFeedbackRequest=object, HTTPException=HTTPException, hashlib=hashlib, json=json,
57
+ threading=threading, time=time, uuid=uuid, datetime=datetime, timezone=timezone,
58
+ os=SimpleNamespace(getenv=lambda *a: ''), requests=SimpleNamespace(get=Mock()),
59
+ _jobs={}, _lock=threading.Lock(), _save_job=Mock(), _executor=SimpleNamespace(submit=Mock()),
60
+ _run_job=Mock(), _load_job=Mock(return_value=None), _authorize_request=Mock(), _rate_limit=Mock(),
61
+ _session=lambda request: {'github_id': request.owner})
62
+ ns['requests'].RequestException = RuntimeError
63
+ ns['requests'].get.return_value.json.return_value = {'head': {'sha': 'a'*40}, 'base': {'sha': 'b'*40}}
64
+ exec(compile(ast.Module(body=nodes, type_ignores=[]), 'backend/api.py', 'exec'), ns)
65
+ return ns
66
+
67
+
68
+ def request(model='m1'):
69
+ values = dict(repo='owner/repo', pr_number=1, endpoint='auto', review_mode='thorough',
70
+ provider='openai', model=model, api_key='secret', base_url='', baseline_sha=None)
71
+ return SimpleNamespace(**values, model_dump=lambda: values)
72
+
73
+
74
+ def test_identical_active_request_reuses_job_but_other_model_does_not():
75
+ ns = scheduler()
76
+ create = ns['create_review']
77
+ first = create(request(), SimpleNamespace(owner=1))
78
+ second = create(request(), SimpleNamespace(owner=1))
79
+ third = create(request('m2'), SimpleNamespace(owner=1))
80
+ assert second['id'] == first['id'] and second['reused']
81
+ assert third['id'] != first['id']
82
+ assert ns['_executor'].submit.call_count == 2
83
+
84
+
85
+ def test_cache_is_scoped_to_owner_and_immutable_commit():
86
+ ns = scheduler()
87
+ create = ns['create_review']
88
+ first = create(request(), SimpleNamespace(owner=1))
89
+ job = ns['_jobs'][first['id']]
90
+ job.update(status='awaiting_approval', started_timestamp=time.time())
91
+ assert create(request(), SimpleNamespace(owner=1))['id'] == first['id']
92
+ assert create(request(), SimpleNamespace(owner=2))['id'] != first['id']
93
+ ns['requests'].get.return_value.json.return_value['head']['sha'] = 'c'*40
94
+ assert create(request(), SimpleNamespace(owner=1))['id'] != first['id']
95
+
96
+
97
+ def test_cancellation_is_owner_scoped_and_terminal():
98
+ ns = scheduler()
99
+ job = ns['create_review'](request(), SimpleNamespace(owner=1))
100
+ with pytest.raises(HTTPException):
101
+ ns['cancel_review'](job['id'], SimpleNamespace(owner=2))
102
+ assert ns['cancel_review'](job['id'], SimpleNamespace(owner=1))['status'] == 'cancelled'
103
+ assert ns['create_review'](request(), SimpleNamespace(owner=1))['id'] != job['id']
104
+ def test_evaluation_quota_stops_followup_calls():
105
+ tree = ast.parse(Path('eval_data/ragas_eval.py').read_text(encoding='utf-8'))
106
+ node = next(node for node in tree.body if isinstance(node, ast.ClassDef) and node.name == '_ThrottledChatModel')
107
+ ns = {'_RAGAS_INTERVAL': 0, '_ragas_throttle_lock': threading.Lock(), 'time': time, '_metric_deadline': ContextVar('test_deadline', default=None)}
108
+ exec(compile(ast.Module(body=[node], type_ignores=[]), 'ragas_eval.py', 'exec'), ns)
109
+ model = Mock()
110
+ quota = RuntimeError('rate_limit_exceeded')
111
+ quota.status_code = 429
112
+ model.invoke.side_effect = quota
113
+ wrapped = ns['_ThrottledChatModel'](model)
114
+ with pytest.raises(RuntimeError):
115
+ wrapped.invoke('first')
116
+ with pytest.raises(RuntimeError, match='Evaluation stopped'):
117
+ wrapped.invoke('second')
118
+ assert model.invoke.call_count == 1
119
+
120
+
121
+ def test_read_and_decision_require_job_owner():
122
+ ns = scheduler()
123
+ job = ns['create_review'](request(), SimpleNamespace(owner=1))
124
+ with pytest.raises(HTTPException) as error:
125
+ ns['get_review'](job['id'], SimpleNamespace(owner=2))
126
+ assert error.value.status_code == 404
127
+ with pytest.raises(HTTPException) as error:
128
+ ns['decide_review'](job['id'], SimpleNamespace(action='approve'), SimpleNamespace(owner=2))
129
+ assert error.value.status_code == 404
130
+
131
+
132
+ def test_incremental_review_cannot_post_approval():
133
+ ns = scheduler()
134
+ job = ns['create_review'](request(), SimpleNamespace(owner=1))
135
+ ns['_jobs'][job['id']].update(status='awaiting_approval', baseline_sha='f'*40)
136
+ with pytest.raises(HTTPException) as error:
137
+ ns['decide_review'](job['id'], SimpleNamespace(action='approve'), SimpleNamespace(owner=1))
138
+ assert error.value.status_code == 409