Sdm0 commited on
Commit
5246c92
·
verified ·
1 Parent(s): c09fbc9

Deploy 2cced123

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +3 -0
  2. .local/README.md +6 -0
  3. README.md +53 -36
  4. api.py +4 -645
  5. app.py +6 -1960
  6. auth.py +4 -352
  7. backend/__init__.py +1 -0
  8. backend/api.py +647 -0
  9. backend/app.py +1962 -0
  10. backend/combined_server.py +8 -0
  11. backend/graph.py +114 -0
  12. backend/integrations/__init__.py +1 -0
  13. backend/integrations/auth.py +353 -0
  14. backend/integrations/config.py +266 -0
  15. backend/integrations/endpoints.py +306 -0
  16. backend/integrations/github_client.py +178 -0
  17. backend/integrations/llm_factory.py +273 -0
  18. backend/main.py +592 -0
  19. backend/observability.py +797 -0
  20. backend/state.py +102 -0
  21. combined_server.py +4 -7
  22. config.py +4 -266
  23. docs/README.md +15 -0
  24. docs/architecture/ARCHITECTURE.md +40 -0
  25. docs/engineering/FIXES.md +488 -0
  26. docs/engineering/QUALITY_IMPROVEMENTS.md +28 -0
  27. docs/engineering/SPEED_IMPROVEMENTS.md +21 -0
  28. docs/evaluation/OFFLINE_EVALUATION_PLAN.md +278 -0
  29. docs/operations/PRODUCTION_READINESS.md +40 -0
  30. docs/planning/revamp.md +670 -0
  31. docs/project-guide/OpenCodeReview_AI_Engineering_Architecture_Guide.docx +3 -0
  32. docs/project-guide/OpenCodeReview_AI_Engineering_Architecture_Guide.pdf +3 -0
  33. docs/project-guide/README.md +38 -0
  34. docs/project-guide/assets/architecture.png +3 -0
  35. docs/project-guide/assets/review_workflow.png +0 -0
  36. docs/project-guide/tools/build_opencodereview_guide.py +996 -0
  37. docs/project-guide/tools/docx_to_html_preview.py +130 -0
  38. docs/project-guide/tools/make_contact_sheets.py +20 -0
  39. docs/project-guide/tools/make_final_pdf_contact_sheets.py +19 -0
  40. docs/project-guide/tools/render_preview.cjs +30 -0
  41. docs/runbooks/AUTHENTICATION_RUNBOOK.md +31 -0
  42. docs/runbooks/DEPLOYMENT_RUNBOOK.md +25 -0
  43. docs/specifications/opencodereview-spec.md +335 -0
  44. endpoints.py +4 -305
  45. eval_data/evaluate.py +4 -4
  46. eval_data/ragas_eval.py +12 -4
  47. github_client.py +4 -177
  48. graph.py +4 -107
  49. llm_factory.py +4 -272
  50. main.py +6 -590
.gitattributes CHANGED
@@ -222,3 +222,6 @@
222
  .venv/Scripts/websockets.exe filter=lfs diff=lfs merge=lfs -text
223
  .venv/Scripts/wsdump.exe filter=lfs diff=lfs merge=lfs -text
224
  .opencodereview/vectors/chroma.sqlite3 filter=lfs diff=lfs merge=lfs -text
 
 
 
 
222
  .venv/Scripts/websockets.exe filter=lfs diff=lfs merge=lfs -text
223
  .venv/Scripts/wsdump.exe filter=lfs diff=lfs merge=lfs -text
224
  .opencodereview/vectors/chroma.sqlite3 filter=lfs diff=lfs merge=lfs -text
225
+ docs/project-guide/OpenCodeReview_AI_Engineering_Architecture_Guide.docx filter=lfs diff=lfs merge=lfs -text
226
+ docs/project-guide/OpenCodeReview_AI_Engineering_Architecture_Guide.pdf filter=lfs diff=lfs merge=lfs -text
227
+ docs/project-guide/assets/architecture.png filter=lfs diff=lfs merge=lfs -text
.local/README.md ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ # Local project data
2
+
3
+ Machine-specific files that should not be committed belong here. Diagnostics go in
4
+ `diagnostics/`; test-only checkpoint databases go in `checkpoints/`. The running
5
+ application's default `checkpoints.db` remains at the repository root because that
6
+ is its configured default path.
README.md CHANGED
@@ -520,53 +520,70 @@ A GitHub Actions workflow (`.github/workflows/alert.yml`) runs this **every 6 ho
520
 
521
  ## 📁 Project Structure
522
 
 
 
 
523
  ```
524
  opencodereview/
525
- ├── app.py # Gradio web UI (entry point for HF Spaces)
526
- ├── main.py # Click CLI — review / doctor / auth / config
527
- ├── auth.py # GitHub OAuth Device Flow
528
- ├── config.py # Settings resolution (env → keyring), config CLI
529
- ├── graph.py # LangGraph pipeline + SqliteSaver checkpointing
530
- ├── state.py # Typed Pydantic state schema (Findings, Verdict, …)
531
- ├── llm_factory.py # Gemini → Groq fallback model factory
532
- ├── github_client.py # GitHub API session, token resolution, HTTP caching
533
- ├── observability.py # LangSmith/Langfuse, cost & TTFT tracking, health checks
534
- ├── requirements.txt
535
- ├── Dockerfile # Multi-stage build (builder → runtime → runtime-full)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
536
  ├── docker-compose.yml
537
- ├── docker-entrypoint.sh # Fixes vector-store volume perms, drops to appuser
538
- ├── nodes/ # One module per graph node
539
- │ ├── ingestion.py # Fetch PR data from GitHub
540
- │ ├── retrieval.py # ChromaDB vector store + diff query
541
- │ ├── correctness_reviewer.py # LLM: logic & correctness issues
542
- │ ├── security_reviewer.py # LLM: security vulnerabilities
543
- │ ├── test_coverage_reviewer.py# LLM: test-coverage gaps
544
- │ ├── aggregator.py # Dedupe, filter, verdict
545
- │ ├── human_approval.py # interrupt() — human-in-the-loop gate
546
- │ └── executor.py # Post inline comments to GitHub
547
- ├── prompts/ # Versioned system prompts (correctness/security/…_v1.txt)
548
- ├── eval_data/ # Evaluation harness
549
- │ ├── fetcher.py # Build ground-truth dataset (prs.jsonl)
550
- │ ├── evaluate.py # Precision/recall/F1 vs human comments
551
- │ ├── ragas_eval.py # RAGAS retrieval & generation metrics
552
- │ ├── prs.jsonl # Ground-truth dataset
553
- │ └── eval_results.json # Latest evaluation results
554
- ├── scripts/
555
- │ └── alert.py # Smoke-test alert monitor (Discord/Slack)
556
- └── .github/workflows/
557
- ├── alert.yml # Every-6h smoke-test alert
558
- └── deploy-hf.yml # Deploy to Hugging Face Spaces on push to main
559
  ```
560
 
 
 
 
 
 
 
561
  ---
562
 
563
  ## 🧪 Testing
564
 
565
- There are no unit-test files yet — the built-in verification paths are:
 
 
 
 
 
 
 
 
566
 
567
  ```bash
568
- # Smoke test: compiles the graph, runs it on synthetic data, and verifies the
569
- # interrupt/resume round-trip (assertions included)
570
  python main.py review --smoke
571
 
572
  # Doctor: checks env, keys, and connectivity
 
520
 
521
  ## 📁 Project Structure
522
 
523
+ Root modules such as `main.py`, `app.py`, and `combined_server.py` remain as
524
+ compatibility shims so existing commands and imports keep working.
525
+
526
  ```
527
  opencodereview/
528
+ ├── docs/ # Architecture, runbooks, plans, and interview guide
529
+ │ ├── architecture/
530
+ │ ├── engineering/
531
+ │ ├── evaluation/
532
+ │ ├── operations/
533
+ │ ├── planning/
534
+ │ ├── project-guide/ # DOCX/PDF guide, source diagrams, and build tools
535
+ │ ├── runbooks/
536
+ │ └── specifications/
537
+ ├── backend/ # Python application and workflow package
538
+ │ ├── api.py # FastAPI job, approval, and persistence boundary
539
+ │ ├── app.py # Gradio UI and review orchestration adapter
540
+ │ ├── combined_server.py # Uvicorn app joining FastAPI and Gradio
541
+ │ ├── graph.py # LangGraph workflow and checkpointing
542
+ │ ├── main.py # Click CLI — review / doctor / auth / config
543
+ │ ├── state.py # Typed Pydantic workflow state
544
+ │ ├── observability.py # LangSmith/Langfuse, cost and health helpers
545
+ │ └── integrations/ # GitHub auth, config, providers, and endpoints
546
+ │ ├── auth.py
547
+ │ ├── config.py
548
+ │ ├── endpoints.py
549
+ │ ├── github_client.py
550
+ │ └── llm_factory.py
551
+ ├── nodes/ # One module per LangGraph step
552
+ ├── prompts/ # Versioned reviewer prompts
553
+ ├── eval_data/ # Offline and RAGAS evaluation tools/data
554
+ ├── tests/ # Unit and integration-style tests
555
+ ├── scripts/ # Health alert tooling
556
+ ├── frontend/ # React/Vite site deployed on Vercel
557
+ ├── supabase/migrations/ # Database schema migrations
558
+ ├── Dockerfile, Dockerfile.api # Backend container definitions
559
  ├── docker-compose.yml
560
+ ├── docker-entrypoint.sh
561
+ ├── requirements.txt
562
+ └── .github/workflows/ # Deployment and scheduled health checks
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
563
  ```
564
 
565
+ Supporting documentation is indexed in [`docs/README.md`](docs/README.md).
566
+
567
+ The root Python entry points remain as compatibility shims. Existing commands
568
+ such as `python main.py`, `python app.py`, and `uvicorn combined_server:app`
569
+ continue to work while the implementation lives under `backend/`.
570
+
571
  ---
572
 
573
  ## 🧪 Testing
574
 
575
+ The `tests/` directory contains focused checks for scheduling, finding
576
+ grounding, ingestion, reviewer runtime, and evaluation behavior. Install
577
+ `pytest` in the development environment if it is not already present, then run:
578
+
579
+ ```bash
580
+ python -m pytest
581
+ ```
582
+
583
+ Additional application checks include:
584
 
585
  ```bash
586
+ # Smoke test: runs the graph on synthetic data and verifies interrupt/resume
 
587
  python main.py review --smoke
588
 
589
  # Doctor: checks env, keys, and connectivity
api.py CHANGED
@@ -1,646 +1,5 @@
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 secrets
15
- import sqlite3
16
- import threading
17
- import uuid
18
- import requests
19
- from concurrent.futures import ThreadPoolExecutor
20
- from datetime import datetime, timezone
21
- from typing import Any, Literal
22
-
23
- from fastapi import FastAPI, Header, HTTPException, Request
24
- from fastapi.responses import RedirectResponse
25
- from fastapi.middleware.cors import CORSMiddleware
26
- from langgraph.types import Command
27
- from pydantic import BaseModel, Field
28
-
29
- from app import DB_PATH, _build_and_stream, _normalize_endpoint_name, _ragas_tasks, _ragas_lock, _spawn_ragas_background
30
- from graph import build_graph
31
- from observability import TokenCostCallback, flush_langfuse, get_langfuse_handler
32
- from state import Finding, Verdict
33
- from endpoints import register_endpoint, unregister_endpoint
34
-
35
- app = FastAPI(title="OpenCodeReview API", version="0.1.0")
36
- allowed_origins = [item.strip() for item in os.getenv("OCR_ALLOWED_ORIGINS", "http://localhost:5173").split(",") if item.strip()]
37
- app.add_middleware(CORSMiddleware, allow_origins=allowed_origins, allow_methods=["GET", "POST"], allow_headers=["*"], allow_credentials=True)
38
-
39
- _jobs: dict[str, dict[str, Any]] = {}
40
- _lock = threading.Lock()
41
- _executor = ThreadPoolExecutor(max_workers=int(os.getenv("OCR_MAX_WORKERS", "2")))
42
- _rate_lock = threading.Lock()
43
- _rate_windows: dict[str, list[float]] = {}
44
- _oauth_states: set[str] = set()
45
- _sessions: dict[str, dict[str, Any]] = {}
46
-
47
- def _rate_limit(request: Request) -> None:
48
- limit = int(os.getenv("OCR_RATE_LIMIT_PER_MINUTE", "0") or 0)
49
- if limit <= 0:
50
- return
51
- now = datetime.now(timezone.utc).timestamp()
52
- forwarded = request.headers.get("x-forwarded-for") or request.headers.get("x-real-ip")
53
- key = (forwarded.split(",", 1)[0].strip() if forwarded else None) or "global"
54
- with _rate_lock:
55
- window = [stamp for stamp in _rate_windows.get(key, []) if now - stamp < 60]
56
- if len(window) >= limit:
57
- raise HTTPException(status_code=429, detail="Rate limit exceeded")
58
- window.append(now)
59
- _rate_windows[key] = window
60
-
61
-
62
- def _postgres_connect():
63
- """Return a Supabase Postgres connection when configured, else None."""
64
- url = os.getenv("SUPABASE_DB_URL", "").strip()
65
- if not url:
66
- return None
67
- try:
68
- import psycopg
69
- return psycopg.connect(url)
70
- except Exception:
71
- return None
72
-
73
- def _init_jobs() -> None:
74
- pg = _postgres_connect()
75
- if pg is not None:
76
- with pg:
77
- with pg.cursor() as cur:
78
- cur.execute("""create table if not exists public.review_jobs (
79
- id uuid primary key, repo text not null, pr_number integer not null,
80
- endpoint text, status text not null, payload jsonb not null,
81
- created_at timestamptz not null default now(), updated_at timestamptz not null default now())""")
82
- cur.execute("create index if not exists review_jobs_status_idx on public.review_jobs (status)")
83
- pg.close()
84
- return
85
- with sqlite3.connect(DB_PATH) as conn:
86
- conn.execute("CREATE TABLE IF NOT EXISTS review_jobs (id TEXT PRIMARY KEY, payload TEXT NOT NULL)")
87
- conn.commit()
88
-
89
- _init_jobs()
90
-
91
- def _save_job(job: dict[str, Any]) -> None:
92
- payload = {k: v for k, v in job.items() if k not in {"future", "ragas_inputs"}}
93
- if "config" in payload:
94
- payload["config"] = {"configurable": payload["config"].get("configurable", {})}
95
- pg = _postgres_connect()
96
- if pg is not None:
97
- with pg:
98
- with pg.cursor() as cur:
99
- cur.execute("""insert into public.review_jobs (id, repo, pr_number, endpoint, status, payload, updated_at)
100
- values (%s, %s, %s, %s, %s, %s::jsonb, now())
101
- on conflict (id) do update set repo=excluded.repo, pr_number=excluded.pr_number,
102
- endpoint=excluded.endpoint, status=excluded.status, payload=excluded.payload, updated_at=now()""",
103
- (job["id"], job["repo"], job["pr_number"], job.get("endpoint"), job["status"], json.dumps(payload, default=str)))
104
- pg.close()
105
- return
106
- with sqlite3.connect(DB_PATH) as conn:
107
- conn.execute("INSERT OR REPLACE INTO review_jobs (id, payload) VALUES (?, ?)", (job["id"], json.dumps(payload, default=str)))
108
- conn.commit()
109
-
110
- def _load_job(job_id: str) -> dict[str, Any] | None:
111
- pg = _postgres_connect()
112
- if pg is not None:
113
- with pg.cursor() as cur:
114
- cur.execute("select payload from public.review_jobs where id = %s", (job_id,))
115
- row = cur.fetchone()
116
- pg.close()
117
- if not row:
118
- return None
119
- return json.loads(row[0]) if isinstance(row[0], str) else row[0]
120
- with sqlite3.connect(DB_PATH) as conn:
121
- row = conn.execute("SELECT payload FROM review_jobs WHERE id = ?", (job_id,)).fetchone()
122
- return json.loads(row[0]) if row else None
123
-
124
- def _load_jobs() -> list[dict[str, Any]]:
125
- pg = _postgres_connect()
126
- if pg is not None:
127
- with pg.cursor() as cur:
128
- cur.execute("select payload from public.review_jobs")
129
- rows = cur.fetchall()
130
- pg.close()
131
- return [json.loads(row[0]) if isinstance(row[0], str) else row[0] for row in rows]
132
- with sqlite3.connect(DB_PATH) as conn:
133
- rows = conn.execute("SELECT payload FROM review_jobs").fetchall()
134
- return [json.loads(row[0]) if isinstance(row[0], str) else row[0] for row in rows]
135
-
136
-
137
- class ReviewRequest(BaseModel):
138
- repo: str = Field(pattern=r"^[\w.-]+/[\w.-]+$")
139
- pr_number: int = Field(gt=0)
140
- endpoint: str | None = None
141
- provider: str | None = Field(default=None, pattern=r"^(openai|anthropic|google)$")
142
- model: str | None = None
143
- api_key: str | None = None
144
- base_url: str | None = None
145
- review_mode: Literal["fast", "thorough"] = "thorough"
146
- baseline_sha: str | None = Field(default=None, pattern=r"^[0-9a-fA-F]{40}$")
147
-
148
-
149
- class DecisionRequest(BaseModel):
150
- action: Literal["approve", "reject"]
151
-
152
-
153
- class FindingFeedbackRequest(BaseModel):
154
- finding_index: int = Field(ge=0)
155
- label: Literal['correct', 'incorrect', 'useful']
156
-
157
-
158
- def _authorize(token: str | None) -> None:
159
- expected = os.getenv("OCR_API_KEY", "").strip()
160
- # Authentication is opt-in for local development, but deployments can
161
- # require it explicitly. Never silently treat a missing production key
162
- # as authenticated.
163
- require_auth = os.getenv("OCR_REQUIRE_AUTH", "false").strip().lower() in {"1", "true", "yes", "on"}
164
- if require_auth and not expected:
165
- raise HTTPException(status_code=503, detail="API authentication is not configured")
166
- if expected and (not token or not secrets.compare_digest(token, expected)):
167
- raise HTTPException(status_code=401, detail="Invalid API key")
168
-
169
- def _authorize_request(token: str | None, request: Request) -> None:
170
- if _session(request):
171
- return
172
- _authorize(token)
173
-
174
- def _session(request: Request) -> dict[str, Any] | None:
175
- sid = request.cookies.get("ocr_session")
176
- return _sessions.get(sid) if sid else None
177
-
178
- @app.get("/api/auth/github/start")
179
- def github_login() -> RedirectResponse:
180
- client_id = os.getenv("GITHUB_OAUTH_CLIENT_ID", "").strip()
181
- if not client_id:
182
- raise HTTPException(status_code=503, detail="GitHub OAuth is not configured")
183
- state = secrets.token_urlsafe(32)
184
- _oauth_states.add(state)
185
- callback = os.getenv("GITHUB_OAUTH_CALLBACK_URL", "").strip() or "http://localhost:8000/api/auth/github/callback"
186
- 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})
187
- return RedirectResponse(url)
188
-
189
- @app.get("/api/auth/github/callback")
190
- def github_callback(code: str, state: str, response: Request) -> RedirectResponse:
191
- if state not in _oauth_states:
192
- raise HTTPException(status_code=400, detail="Invalid OAuth state")
193
- _oauth_states.discard(state)
194
- client_id = os.getenv("GITHUB_OAUTH_CLIENT_ID", "").strip()
195
- client_secret = os.getenv("GITHUB_OAUTH_CLIENT_SECRET", "").strip()
196
- callback = os.getenv("GITHUB_OAUTH_CALLBACK_URL", "").strip() or "http://localhost:8000/api/auth/github/callback"
197
- 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)
198
- token_resp.raise_for_status()
199
- access_token = token_resp.json().get("access_token")
200
- if not access_token:
201
- raise HTTPException(status_code=502, detail="GitHub did not return an access token")
202
- user_resp = requests.get("https://api.github.com/user", headers={"Authorization": f"Bearer {access_token}", "Accept": "application/vnd.github+json"}, timeout=20)
203
- user_resp.raise_for_status()
204
- user = user_resp.json()
205
- sid = secrets.token_urlsafe(32)
206
- _sessions[sid] = {"token": access_token, "github_id": user.get("id"), "login": user.get("login")}
207
- frontend = os.getenv("OCR_FRONTEND_URL", allowed_origins[0] if allowed_origins else "http://localhost:5173")
208
- out = RedirectResponse(frontend)
209
- out.set_cookie("ocr_session", sid, httponly=True, secure=frontend.startswith("https://"), samesite="lax", max_age=86400)
210
- return out
211
-
212
- @app.get("/api/auth/me")
213
- def github_me(request: Request) -> dict[str, Any]:
214
- session = _session(request)
215
- if not session:
216
- raise HTTPException(status_code=401, detail="Not authenticated")
217
- return {"github_id": session["github_id"], "login": session["login"]}
218
-
219
- @app.post("/api/auth/logout")
220
- def github_logout(request: Request) -> dict[str, str]:
221
- sid = request.cookies.get("ocr_session")
222
- if sid:
223
- _sessions.pop(sid, None)
224
- return {"status": "logged_out"}
225
-
226
-
227
- def _public_job(job: dict[str, Any]) -> dict[str, Any]:
228
- result = {key: value for key, value in job.items() if key not in {"config", "future", "request_fingerprint", "owner_id", "ragas_inputs"}}
229
- now = time.time()
230
- 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)
231
- if job.get("status") == "queued":
232
- result["queue_position"] = sum(1 for item in _jobs.values() if item.get("status") == "queued" and item.get("created_at", "") <= job.get("created_at", ""))
233
- return result
234
-
235
- def _with_ragas(job: dict[str, Any]) -> dict[str, Any]:
236
- result = _public_job(job)
237
- task_id = result.get("ragas_task_id")
238
- with _ragas_lock:
239
- task = _ragas_tasks.get(task_id) if task_id else None
240
- def finish():
241
- metrics = (task or {}).get('metrics') or job.get('ragas_metrics') or {}
242
- evaluation = (task or {}).get('evaluation') or job.get('ragas_evaluation') or {}
243
- result.setdefault('ragas', {}).update(metrics=metrics, evaluation=evaluation)
244
- if metrics and result['ragas'].get('scores') and any(m.get('status') != 'completed' for m in metrics.values()):
245
- result['ragas']['status'] = 'partial'
246
- if metrics != job.get('ragas_metrics', {}) or evaluation != job.get('ragas_evaluation', {}):
247
- with _lock:
248
- live = _jobs.get(job.get('id'))
249
- if live is not None:
250
- live.update(ragas_metrics=metrics, ragas_evaluation=evaluation)
251
- _save_job(live)
252
- return result
253
- if not task_id:
254
- result["ragas"] = {
255
- "status": "skipped",
256
- "scores": result.get("ragas_scores") or {},
257
- "reason": "Review incomplete; scoring was not started" if result.get("status") == "incomplete" else "No retrieval context was available for RAGAS evaluation",
258
- }
259
- else:
260
- if job.get("ragas_status") in {"failed", "unavailable", "completed_no_scores"}:
261
- result["ragas"] = {
262
- "status": job["ragas_status"],
263
- "scores": job.get("ragas_scores") or {},
264
- "error": job.get("ragas_error"),
265
- }
266
- return finish()
267
- with _ragas_lock:
268
- task = _ragas_tasks.get(task_id)
269
- if not task:
270
- # Task registries are process-local. A restart invalidates an
271
- # in-flight task instead of making the client poll forever.
272
- if result.get("ragas_scores"):
273
- result["ragas"] = {"status": "completed", "scores": result["ragas_scores"]}
274
- else:
275
- result["ragas"] = {"status": "unavailable", "error": "RAGAS task was lost during process restart"}
276
- with _lock:
277
- live = _jobs.get(job.get("id"))
278
- if live is not None:
279
- live["ragas_status"] = "unavailable"
280
- live["ragas_error"] = result["ragas"]["error"]
281
- _save_job(live)
282
- elif not task.get("done"):
283
- timeout = float(task.get("timeout_seconds") or os.getenv("OCR_RAGAS_TIMEOUT_SECONDS", "90"))
284
- started = float(task.get("started", 0) or 0)
285
- if started and datetime.now(timezone.utc).timestamp() - started > timeout:
286
- result["ragas"] = {"status": "failed", "error": f"RAGAS exceeded {int(timeout)} second timeout"}
287
- with _lock:
288
- live = _jobs.get(job.get("id"))
289
- if live is not None:
290
- live["ragas_status"] = "failed"
291
- live["ragas_error"] = result["ragas"]["error"]
292
- _save_job(live)
293
- else:
294
- result["ragas"] = {"status": "pending"}
295
- elif task.get("error"):
296
- result["ragas"] = {"status": "failed", "error": task.get("error")}
297
- with _lock:
298
- live = _jobs.get(job.get("id"))
299
- if live is not None:
300
- live["ragas_status"] = "failed"
301
- live["ragas_error"] = task.get("error")
302
- _save_job(live)
303
- else:
304
- scores = task.get("scores") or {}
305
- if scores:
306
- result["ragas"] = {"status": "completed", "scores": scores}
307
- if not job.get("ragas_scores"):
308
- with _lock:
309
- live = _jobs.get(job.get("id"))
310
- if live is not None:
311
- live["ragas_scores"] = scores
312
- live["ragas_status"] = "completed"
313
- _save_job(live)
314
- else:
315
- result["ragas"] = {"status": "completed_no_scores", "scores": {}, "error": "RAGAS completed without metric values"}
316
- with _lock:
317
- live = _jobs.get(job.get("id"))
318
- if live is not None:
319
- live["ragas_status"] = "completed_no_scores"
320
- live["ragas_error"] = result["ragas"]["error"]
321
- _save_job(live)
322
- return finish()
323
-
324
-
325
- def _run_job(job_id: str, request: ReviewRequest) -> None:
326
- with _lock:
327
- if _jobs.get(job_id, {}).get("status") == "cancelled":
328
- return
329
- if job_id in _jobs:
330
- _jobs[job_id].update(status="processing", started_timestamp=time.time(), progress={"stage": "ingestion", "completed_stages": []})
331
- _save_job(_jobs[job_id])
332
- try:
333
- ephemeral_endpoint = None
334
- ragas_started = False
335
- endpoint_name = _normalize_endpoint_name(request.endpoint)
336
- if request.api_key:
337
- if not request.provider or not request.model:
338
- raise ValueError("provider and model are required when supplying a user API key")
339
- ephemeral_endpoint = f"user-{job_id}"
340
- register_endpoint(ephemeral_endpoint, request.provider, request.api_key, request.base_url, request.model)
341
- endpoint_name = ephemeral_endpoint
342
- def save_ragas(scores: dict, error: str | None) -> None:
343
- try:
344
- with _lock:
345
- live = _jobs.get(job_id)
346
- if live is None:
347
- return
348
- live["ragas_scores"] = scores or None
349
- live["ragas_status"] = "failed" if error else ("completed" if scores else "completed_no_scores")
350
- live["ragas_error"] = error
351
- _save_job(live)
352
- finally:
353
- # Custom providers are registered only for this job. Keep the
354
- # endpoint alive until the background RAGAS task has finished;
355
- # otherwise evaluation silently falls back to built-ins.
356
- if ephemeral_endpoint:
357
- unregister_endpoint(ephemeral_endpoint)
358
-
359
- def progress(stage: str, elapsed: float, update: dict | None = None) -> None:
360
- with _lock:
361
- live = _jobs[job_id]
362
- if live.get("status") == "cancelled":
363
- raise RuntimeError("Review cancelled")
364
- completed = live.setdefault("progress", {}).setdefault("completed_stages", [])
365
- if stage not in completed:
366
- completed.append(stage)
367
- live["progress"]["stage"] = stage
368
- live.setdefault("stage_timings", {})[stage] = round(elapsed, 2)
369
- if isinstance(update, dict):
370
- stages = update.get("review_stages", [])
371
- if isinstance(stages, list):
372
- live.setdefault("review_stages", []).extend(stages)
373
- for key in ("findings",):
374
- for finding in update.get(key, []) or []:
375
- if hasattr(finding, "model_dump"):
376
- finding = finding.model_dump(mode="json")
377
- if isinstance(finding, dict):
378
- live.setdefault("findings", []).append(finding)
379
- _save_job(live)
380
-
381
- state, config, cost, ragas, ragas_inputs = _build_and_stream(
382
- request.repo,
383
- request.pr_number,
384
- endpoint_name,
385
- ragas_background=True,
386
- ragas_result_callback=save_ragas,
387
- progress_callback=progress,
388
- review_mode=request.review_mode,
389
- baseline_sha=request.baseline_sha,
390
- )
391
- ragas_started = isinstance(ragas, str)
392
- actual_head = state.values.get("head_sha")
393
- verdict: Verdict | None = state.values.get("verdict")
394
- findings: list[Finding] = state.values.get("final_findings", [])
395
- with _lock:
396
- if _jobs[job_id].get("status") == "cancelled":
397
- return
398
- if actual_head and _jobs[job_id].get("head_sha") != actual_head:
399
- # The PR moved between metadata lookup and ingestion. The result
400
- # can still be viewed, but must not satisfy the old cache key.
401
- _jobs[job_id]["request_fingerprint"] = None
402
- _jobs[job_id]["head_sha"] = actual_head
403
- stages = state.values.get("review_stages", [])
404
- incomplete = bool(verdict and verdict.recommendation == "incomplete")
405
- _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)
406
- _save_job(_jobs[job_id])
407
- except Exception as exc:
408
- with _lock:
409
- if _jobs[job_id].get("status") != "cancelled":
410
- _jobs[job_id].update(status="failed", error=str(exc)[:500])
411
- _save_job(_jobs[job_id])
412
- finally:
413
- if 'ephemeral_endpoint' in locals() and ephemeral_endpoint and not ragas_started:
414
- unregister_endpoint(ephemeral_endpoint)
415
-
416
-
417
- def _hydrate_jobs() -> None:
418
- """Restore persisted jobs after a process restart and resume interrupted work."""
419
- for persisted in _load_jobs():
420
- # Evaluation inputs may include an in-memory endpoint object. Never
421
- # retain or expose that snapshot: it can contain a user's provider key.
422
- if "ragas_inputs" in persisted:
423
- persisted.pop("ragas_inputs", None)
424
- _save_job(persisted)
425
- job_id = persisted.get("id")
426
- if not job_id:
427
- continue
428
- status = persisted.get("status")
429
- _jobs[job_id] = persisted
430
- if persisted.get("ragas_task_id") and not persisted.get("ragas_status"):
431
- persisted.update(ragas_status="unavailable", ragas_error="Evaluation interrupted by restart; it was not automatically replayed.")
432
- _save_job(persisted)
433
- if status in {"queued", "processing"} and persisted.get("custom_provider"):
434
- persisted.update(status="failed", error="Provider credentials were not persisted; resubmit this review after restart.")
435
- _save_job(persisted)
436
- continue
437
- if status in {"queued", "processing", "processing_decision"}:
438
- # Decision processing cannot be safely replayed without an explicit
439
- # user action; review execution can be resumed idempotently.
440
- if status == "processing_decision":
441
- _jobs[job_id]["status"] = "awaiting_approval"
442
- _save_job(_jobs[job_id])
443
- continue
444
- try:
445
- request = ReviewRequest(repo=persisted["repo"], pr_number=int(persisted["pr_number"]), endpoint=persisted.get("endpoint"))
446
- except Exception:
447
- _jobs[job_id].update(status="failed", error="Persisted job request is invalid")
448
- _save_job(_jobs[job_id])
449
- continue
450
- _jobs[job_id]["status"] = "queued"
451
- _save_job(_jobs[job_id])
452
- _jobs[job_id]["future"] = _executor.submit(_run_job, job_id, request)
453
-
454
-
455
- _hydrate_jobs()
456
-
457
-
458
- @app.get("/api/health")
459
- def health() -> dict[str, Any]:
460
- provider_configured = any(
461
- os.getenv(name, "").strip()
462
- for name in ("GEMINI_API_KEY", "GROQ_API_KEY", "OPENAI_API_KEY", "ANTHROPIC_API_KEY")
463
- )
464
- require_auth = os.getenv("OCR_REQUIRE_AUTH", "false").strip().lower() in {"1", "true", "yes", "on"}
465
- persistence = "local_default_path"
466
- if os.getenv("SUPABASE_DB_URL"):
467
- probe = _postgres_connect()
468
- if probe is not None:
469
- probe.close()
470
- persistence = "supabase_postgres"
471
- else:
472
- persistence = "supabase_configured_unreachable"
473
- elif os.getenv("OPENCODEREVIEW_DB_PATH"):
474
- persistence = "configured_path"
475
- return {
476
- "status": "ok",
477
- "inference": "remote_provider_configured" if provider_configured else "fallback_or_unconfigured",
478
- "authentication": "required" if require_auth else "optional",
479
- "rate_limit_per_minute": int(os.getenv("OCR_RATE_LIMIT_PER_MINUTE", "0") or 0),
480
- "persistence": persistence,
481
- "local_embeddings": os.getenv("OPENCODEREVIEW_ALLOW_LOCAL_EMBEDDINGS", "false").lower()
482
- in {"1", "true", "yes", "on"},
483
- }
484
-
485
-
486
- @app.post("/api/reviews", status_code=202)
487
- 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]:
488
- _authorize_request(x_api_key, http_request)
489
- _rate_limit(http_request)
490
- owner = str((_session(http_request) or {}).get("github_id") or "api-key")
491
- material = request.model_dump()
492
- head_sha = base_sha = None
493
- try:
494
- token = (_session(http_request) or {}).get("token") or os.getenv("GITHUB_TOKEN", "")
495
- headers = {"Accept": "application/vnd.github+json", "Cache-Control": "no-cache"}
496
- if token:
497
- headers["Authorization"] = f"Bearer {token}"
498
- response = requests.get(f"https://api.github.com/repos/{request.repo}/pulls/{request.pr_number}", headers=headers, timeout=6)
499
- response.raise_for_status()
500
- pull = response.json()
501
- head_sha, base_sha = pull["head"]["sha"], pull["base"]["sha"]
502
- except (requests.RequestException, KeyError, ValueError):
503
- pass # Active deduplication still works if GitHub metadata is unavailable.
504
- prompt_hash = hashlib.sha256()
505
- for source in sorted(Path(__file__).parent.joinpath("prompts").glob("*.txt")):
506
- prompt_hash.update(source.read_bytes())
507
- for source in sorted(Path(__file__).parent.joinpath("nodes").glob("*.py")):
508
- prompt_hash.update(source.read_bytes())
509
- material.update(head_sha=head_sha, base_sha=base_sha, pipeline_version=prompt_hash.hexdigest())
510
- fingerprint = hashlib.sha256(json.dumps({"owner": owner, "request": material}, sort_keys=True).encode()).hexdigest()
511
- # Reuse completed previews only for an identical immutable diff and configuration.
512
- with _lock:
513
- 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)
514
- if existing is None:
515
- job_id = str(uuid.uuid4())
516
- 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()}
517
- _jobs[job_id] = job
518
- _save_job(job)
519
- else:
520
- job = existing
521
- if existing is not None:
522
- return {**_with_ragas(job), "reused": True}
523
- job["future"] = _executor.submit(_run_job, job_id, request)
524
- return _with_ragas(job)
525
-
526
-
527
- @app.post("/api/reviews/{job_id}/cancel")
528
- def cancel_review(job_id: str, request: Request, x_api_key: str | None = Header(default=None)) -> dict[str, Any]:
529
- _authorize_request(x_api_key, request)
530
- owner = str((_session(request) or {}).get("github_id") or "api-key")
531
- with _lock:
532
- job = _jobs.get(job_id)
533
- if not job or job.get("owner_id", "api-key") != owner:
534
- raise HTTPException(status_code=404, detail="Review not found")
535
- if job.get("status") not in {"queued", "processing"}:
536
- raise HTTPException(status_code=409, detail="Only queued or processing reviews can be cancelled")
537
- future = job.get("future")
538
- if future:
539
- future.cancel()
540
- job.update(status="cancelled", cancellation_note="Running calls finish within their timeout; no results will be posted.")
541
- _save_job(job)
542
- return _public_job(job)
543
-
544
-
545
- @app.get("/api/reviews/{job_id}")
546
- def get_review(job_id: str, request: Request, x_api_key: str | None = Header(default=None)) -> dict[str, Any]:
547
- # API-key authorization remains supported for polling; OAuth callers use the cookie path.
548
- _authorize_request(x_api_key, request)
549
- with _lock:
550
- job = _jobs.get(job_id)
551
- if not job:
552
- job = _load_job(job_id)
553
- owner = str((_session(request) or {}).get("github_id") or "api-key")
554
- if not job or job.get("owner_id", "api-key") != owner:
555
- raise HTTPException(status_code=404, detail="Review not found")
556
- return _with_ragas(job)
557
-
558
-
559
- @app.post('/api/reviews/{job_id}/feedback')
560
- def finding_feedback(job_id: str, payload: FindingFeedbackRequest, request: Request,
561
- x_api_key: str | None = Header(default=None)) -> dict[str, Any]:
562
- _authorize_request(x_api_key, request)
563
- _rate_limit(request)
564
- owner = str((_session(request) or {}).get('github_id') or 'api-key')
565
- with _lock:
566
- job = _jobs.get(job_id) or _load_job(job_id)
567
- if not job or job.get('owner_id', 'api-key') != owner:
568
- raise HTTPException(status_code=404, detail='Review not found')
569
- if job.get('status') not in {'awaiting_approval', 'incomplete', 'posted', 'partially_posted', 'rejected', 'post_failed'}:
570
- raise HTTPException(status_code=409, detail='Wait until the review finishes before giving feedback')
571
- if payload.finding_index >= len(job.get('findings') or []):
572
- raise HTTPException(status_code=422, detail='Finding does not exist')
573
- feedback = dict(job.get('feedback') or {})
574
- feedback[str(payload.finding_index)] = payload.label
575
- job['feedback'] = feedback
576
- job['feedback_updated_at'] = datetime.now(timezone.utc).isoformat()
577
- _jobs[job_id] = job
578
- _save_job(job)
579
- return {'feedback': feedback}
580
-
581
-
582
- @app.post("/api/reviews/{job_id}/decision")
583
- def decide_review(job_id: str, request: DecisionRequest, http_request: Request, x_api_key: str | None = Header(default=None)) -> dict[str, Any]:
584
- _authorize_request(x_api_key, http_request)
585
- _rate_limit(http_request)
586
- with _lock:
587
- preview = _jobs.get(job_id) or _load_job(job_id)
588
- owner = str((_session(http_request) or {}).get("github_id") or "api-key")
589
- if not preview or preview.get("owner_id", "api-key") != owner:
590
- raise HTTPException(status_code=404, detail="Review not found")
591
- if request.action == "approve" and preview.get("baseline_sha"):
592
- raise HTTPException(status_code=409, detail="Incremental reviews are preview-only. Run a full review before posting.")
593
- if preview and request.action == "approve" and preview.get("head_sha"):
594
- headers = {"Accept": "application/vnd.github+json", "Cache-Control": "no-cache"}
595
- token = (_session(http_request) or {}).get("token") or os.getenv("GITHUB_TOKEN", "")
596
- if token:
597
- headers["Authorization"] = f"Bearer {token}"
598
- try:
599
- response = requests.get(f"https://api.github.com/repos/{preview['repo']}/pulls/{preview['pr_number']}", headers=headers, timeout=6)
600
- response.raise_for_status()
601
- current = response.json()
602
- if current["head"]["sha"] != preview["head_sha"] or current["base"]["sha"] != preview.get("base_sha"):
603
- raise HTTPException(status_code=409, detail="PR changed since this review; start a new review before posting.")
604
- except (requests.RequestException, KeyError, ValueError) as exc:
605
- raise HTTPException(status_code=503, detail="Cannot verify the current PR commit; retry before posting.") from exc
606
- with _lock:
607
- job = _jobs.get(job_id)
608
- if not job:
609
- job = _load_job(job_id)
610
- if not job:
611
- raise HTTPException(status_code=404, detail="Review not found")
612
- if job.get("status") != "awaiting_approval":
613
- raise HTTPException(status_code=409, detail="Review is not awaiting approval")
614
- config = job["config"]
615
- job["status"] = "processing_decision"
616
- _save_job(job)
617
- if request.action == "reject":
618
- with _lock:
619
- job.update(status="rejected", decision="reject")
620
- _save_job(job)
621
- return _public_job(job)
622
- graph = build_graph(DB_PATH)
623
- try:
624
- callbacks = [TokenCostCallback()]
625
- handler = get_langfuse_handler()
626
- if handler:
627
- callbacks.append(handler)
628
- config = dict(config)
629
- config["callbacks"] = callbacks
630
- result = graph.invoke(Command(resume={"action": "approve"}), config)
631
- posting_result = result.get("posting_result") if isinstance(result, dict) else None
632
- final_status = (posting_result or {}).get("status", "posted")
633
- with _lock:
634
- job.update(status=final_status, decision="approve", posting_result=posting_result)
635
- _save_job(job)
636
- return _public_job(job)
637
- except Exception as exc:
638
- with _lock:
639
- job.update(status="failed", error=str(exc)[:500])
640
- _save_job(job)
641
- raise HTTPException(status_code=500, detail="Decision processing failed") from exc
642
- finally:
643
- conn = getattr(graph, "_opencodereview_conn", None)
644
- if conn:
645
- conn.close()
646
- flush_langfuse()
 
1
+ """Backward-compatible import path for the packaged FastAPI application."""
2
+ import sys as _sys
3
+ from backend import api as _implementation
4
 
5
+ _sys.modules[__name__] = _implementation
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app.py CHANGED
@@ -1,1962 +1,8 @@
1
- #!/usr/bin/env python3
2
- """OpenCodeReview — Gradio Web UI for Hugging Face Spaces.
3
-
4
- Run locally:
5
- python app.py
6
-
7
- On Hugging Face Spaces:
8
- The Dockerfile now defaults to running this module.
9
- Set GROQ_API_KEY (and optionally GITHUB_TOKEN) as Space secrets.
10
- """
11
-
12
- from __future__ import annotations
13
-
14
- import html
15
- from contextvars import copy_context
16
- import json
17
- import ipaddress
18
- import logging
19
- import os
20
- import threading
21
- import time
22
- import uuid
23
- from concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeoutError
24
-
25
- import gradio as gr
26
- from langgraph.types import Command
27
-
28
- from graph import build_graph
29
- from main import NODE_LABELS, _cleanup_db, SYNTHETIC_STATE
30
- from observability import (
31
- build_run_metadata,
32
- enable_langsmith,
33
- get_langfuse_handler,
34
- is_langfuse_enabled,
35
- is_langsmith_enabled,
36
- estimate_groq_cost,
37
- flush_langfuse,
38
- format_cost,
39
- langfuse_trace,
40
- log_error_to_backends,
41
- log_langfuse_score,
42
- _resolve_langfuse_trace_id,
43
- HealthStatus,
44
- TokenCostCallback,
45
- check_groq_connectivity,
46
- check_langfuse_connectivity,
47
- )
48
- from endpoints import (
49
- EndpointConfig,
50
- clear_session_endpoints,
51
- discover_endpoints,
52
- dropdown_choices,
53
- register_endpoint,
54
- session_endpoints,
55
- )
56
- from state import Verdict
57
-
58
- import subprocess
59
- from datetime import datetime, timezone
60
-
61
- logging.basicConfig(
62
- level=logging.INFO,
63
- format="%(asctime)s [%(levelname)s] %(name)s — %(message)s",
64
- )
65
- logger = logging.getLogger(__name__)
66
-
67
- # Set this to a mounted volume or durable filesystem path in hosted
68
- # deployments. The default keeps local development self-contained.
69
- DB_PATH = os.environ.get("OPENCODEREVIEW_DB_PATH", "checkpoints.db")
70
-
71
- SEVERITY_COLORS = {
72
- "critical": "#dc2626",
73
- "high": "#ea580c",
74
- "medium": "#ca8a04",
75
- "low": "#16a34a",
76
- "info": "#2563eb",
77
- }
78
-
79
- RECOMMENDATION_ICONS = {
80
- "approve": "✅",
81
- "request_changes": "🔄",
82
- "block": "🚫",
83
- "comment": "💬",
84
- }
85
-
86
- # Default dropdown choice shown in the UI. Gradio 6's Dropdown has no
87
- # placeholder support, so a real choice is displayed and mapped back to
88
- # the "" (auto) sentinel wherever the value enters the pipeline.
89
- AUTO_ENDPOINT_CHOICE = "Auto (Gemini → Groq fallback)"
90
-
91
-
92
- def _normalize_endpoint_name(endpoint_name: str | None) -> str:
93
- return "" if endpoint_name == AUTO_ENDPOINT_CHOICE else (endpoint_name or "")
94
-
95
-
96
- # ─── Orchestration ───────────────────────────────────────────────────────────
97
-
98
-
99
- def _init_observability_ui() -> None:
100
- """Initialise observability backends and HTTP cache for the Gradio UI."""
101
- from github_client import _init_cache as _init_http_cache
102
- _init_http_cache()
103
-
104
- # LangSmith: enable if key is in environment (check both modern and legacy names)
105
- ls_key = (
106
- os.environ.get("LANGSMITH_API_KEY", "").strip()
107
- or os.environ.get("LANGCHAIN_API_KEY", "").strip()
108
- )
109
- if ls_key:
110
- project = os.environ.get("LANGSMITH_PROJECT",
111
- os.environ.get("LANGCHAIN_PROJECT", "opencodereview"))
112
- enable_langsmith(ls_key, project)
113
- logger.info("Observability: LangSmith enabled for Gradio UI")
114
- if get_langfuse_handler():
115
- logger.info("Observability: Langfuse enabled for Gradio UI")
116
-
117
-
118
- def _build_and_stream(
119
- repo: str,
120
- pr_number: int,
121
- endpoint_name: str = "",
122
- ragas_background: bool = False,
123
- ragas_result_callback=None,
124
- progress_callback=None,
125
- review_mode: str = "thorough",
126
- baseline_sha: str | None = None,
127
- ) -> tuple:
128
- """Build the graph, stream up to the interrupt, and return state + config.
129
-
130
- Parameters
131
- ----------
132
- endpoint_name : str
133
- Optional name of a configured custom LLM endpoint
134
- (``OCR_ENDPOINT_*``). Empty string uses the built-in provider.
135
- ragas_background : bool
136
- When True, RAGAS scoring runs on a background daemon thread and the
137
- fourth return element is a task id (str) to poll instead of the
138
- scores dict — so the UI can show results immediately.
139
- """
140
- graph = build_graph(DB_PATH)
141
- thread_id = str(uuid.uuid4())
142
- trace_name = f"opencodereview/review/{repo}#{pr_number}"
143
- tags = ["gradio_ui", repo]
144
- prompt_versions = {
145
- "correctness": "v1",
146
- "security": "v1",
147
- "test_coverage": "v1",
148
- "aggregator": "v1",
149
- }
150
- cost_tracker = TokenCostCallback()
151
- metadata = build_run_metadata(
152
- source="gradio_ui", repo=repo, pr_number=pr_number,
153
- session_id=thread_id,
154
- prompt_versions=prompt_versions,
155
- )
156
- config: dict = {
157
- "configurable": {"thread_id": f"web-{thread_id}"},
158
- "metadata": metadata,
159
- }
160
-
161
- # Use langfuse_trace context manager which sets trace metadata via
162
- # propagate_attributes() (langfuse v4+ API) and yields the handler.
163
- with langfuse_trace(
164
- trace_name=trace_name,
165
- tags=tags,
166
- session_id=thread_id,
167
- metadata={
168
- "source": "gradio_ui",
169
- "repo": repo,
170
- "pr_number": pr_number,
171
- "prompt_versions": prompt_versions,
172
- },
173
- ) as handler:
174
- callbacks = [cost_tracker]
175
- if handler:
176
- callbacks.append(handler)
177
- config["callbacks"] = callbacks
178
-
179
- try:
180
- t0 = time.time()
181
- initial = {"repo": repo, "pr_number": pr_number, "review_mode": review_mode, "incremental_base_sha": baseline_sha or ""}
182
- if endpoint_name:
183
- initial["endpoint"] = endpoint_name
184
- for event in graph.stream(initial, config):
185
- for node_name in event:
186
- label = NODE_LABELS.get(node_name, node_name)
187
- logger.info(" ✔ %s (+%.1fs)", label, time.time() - t0)
188
- if progress_callback:
189
- progress_callback(node_name, time.time() - t0, event.get(node_name))
190
- logger.info(" ─── Pipeline complete in %.1fs ───", time.time() - t0)
191
- except Exception as exc:
192
- log_error_to_backends(exc, context={"source": "gradio_ui", "phase": "stream", "repo": repo, "pr_number": pr_number})
193
- conn = getattr(graph, "_opencodereview_conn", None)
194
- if conn:
195
- conn.close()
196
- flush_langfuse()
197
- raise
198
-
199
- state = graph.get_state(config)
200
-
201
- # ── Log verdict/findings scores and capture trace_id ───────
202
- # Capture trace_id NOW (immediately after graph completes)
203
- # so it can be used after the long-running RAGAS computation.
204
- # _resolve_langfuse_trace_id() can return None after ~60s delays
205
- # because contextvars may be lost.
206
- run_trace_id = _resolve_langfuse_trace_id(handler)
207
-
208
- verdict = state.values.get("verdict")
209
- findings = state.values.get("final_findings", [])
210
- if verdict and verdict.overall_score is not None:
211
- log_langfuse_score(
212
- name="verdict_score",
213
- value=verdict.overall_score,
214
- comment=f"{repo}#{pr_number} — {verdict.recommendation}: {verdict.summary[:100]}",
215
- trace_id=run_trace_id,
216
- handler=handler,
217
- )
218
- log_langfuse_score(
219
- name="findings_count",
220
- value=len(findings),
221
- comment=f"{repo}#{pr_number}",
222
- trace_id=run_trace_id,
223
- handler=handler,
224
- )
225
-
226
- # ── Compute and log RAGAS retrieval scores ─────────────────
227
- # Background mode spawns a thread and returns a task id so the UI
228
- # can render results immediately; sync mode (CLI/health) waits.
229
- ragas_out: dict[str, float | None] | str = {}
230
- ragas_inputs = _ragas_inputs_from_state(state, endpoint_name)
231
- if ragas_inputs:
232
- if ragas_background:
233
- # handler is not shared across threads (langfuse contextvars
234
- # are lost in the worker); the captured trace_id is passed
235
- # explicitly instead.
236
- ragas_out = _spawn_ragas_background(
237
- ragas_inputs, repo, pr_number, run_trace_id, None,
238
- ragas_result_callback,
239
- )
240
- else:
241
- ragas_out = _compute_and_log_ragas(
242
- ragas_inputs, repo, pr_number, run_trace_id, handler,
243
- )
244
-
245
- # Close the checkpointer connection (checkpoints persist to disk so the
246
- # resume path opens a fresh one) and ship any queued Langfuse scores.
247
- conn = getattr(graph, "_opencodereview_conn", None)
248
- if conn:
249
- conn.close()
250
- flush_langfuse()
251
-
252
- config.setdefault("metadata", {})["cost_details"] = cost_tracker.details()
253
- return state, config, cost_tracker.summary(), ragas_out, ({**ragas_inputs, "endpoint": None} if ragas_inputs else None)
254
-
255
-
256
- def _format_findings_table(findings: list) -> str:
257
- """Build an HTML table of findings with severity-coloured badges."""
258
- if not findings:
259
- return '<p style="color:var(--text-muted)">No issues found.</p>'
260
-
261
- rows: list[str] = []
262
- for f in findings:
263
- color = SEVERITY_COLORS.get(f.severity.value, "#666")
264
- severity = html.escape(f.severity.value.upper())
265
- category = html.escape(str(f.category))
266
- location = html.escape(f"{f.file_path}:{f.line_start}–{f.line_end}")
267
- comment = html.escape(str(f.comment))
268
- rows.append(
269
- f"<tr>"
270
- f'<td><span style="display:inline-block;padding:2px 10px;'
271
- f'border-radius:12px;background:{color}22;'
272
- f'color:{color};font-weight:700;font-size:0.85em">'
273
- f"{severity}</span></td>"
274
- f"<td>{category}</td>"
275
- f"<td><code>{location}</code></td>"
276
- f"<td>{comment}</td>"
277
- f'<td style="text-align:center">{f.confidence:.0%}</td>'
278
- f"</tr>"
279
- )
280
-
281
- return (
282
- '<div style="overflow-x:auto">'
283
- '<table style="width:100%;border-collapse:collapse;font-size:0.9em">'
284
- "<thead>"
285
- f'<tr style="background:var(--bg-table-header);border-bottom:2px solid var(--border-color)">'
286
- '<th style="padding:10px 12px;text-align:left;color:var(--text-primary)">Severity</th>'
287
- '<th style="padding:10px 12px;text-align:left;color:var(--text-primary)">Category</th>'
288
- '<th style="padding:10px 12px;text-align:left;color:var(--text-primary)">Location</th>'
289
- '<th style="padding:10px 12px;text-align:left;color:var(--text-primary)">Comment</th>'
290
- '<th style="padding:10px 12px;text-align:left;color:var(--text-primary)">Confidence</th>'
291
- "</tr>"
292
- "</thead>"
293
- f'<tbody style="color:var(--text-secondary)">' + "".join(rows) + "</tbody>"
294
- "</table>"
295
- "</div>"
296
- )
297
-
298
-
299
- def _format_verdict(verdict: Verdict | None) -> str:
300
- """Build a verdict summary card with a score bar and severity chips."""
301
- if verdict is None:
302
- return '<p class="muted">No verdict produced.</p>'
303
-
304
- icon = RECOMMENDATION_ICONS.get(verdict.recommendation, "📋")
305
- color = (
306
- "#16a34a" if verdict.recommendation == "approve"
307
- else "#dc2626" if verdict.recommendation == "block"
308
- else "#ea580c"
309
- )
310
- pct = max(0, min(100, int((verdict.overall_score or 0) * 10)))
311
- score_label = f"{verdict.overall_score:.1f}/10" if verdict.overall_score is not None else "Not scored"
312
-
313
- chips = []
314
- if verdict.critical_count:
315
- chips.append(
316
- f'<span class="sev-chip" style="color:#dc2626;border-color:#dc262644;background:#dc262611">'
317
- f"critical × {verdict.critical_count}</span>"
318
- )
319
- if verdict.high_count:
320
- chips.append(
321
- f'<span class="sev-chip" style="color:#ea580c;border-color:#ea580c44;background:#ea580c11">'
322
- f"high × {verdict.high_count}</span>"
323
- )
324
- chips_html = (
325
- f'<div class="chips-row" style="margin-top:10px">' + "".join(chips) + "</div>"
326
- if chips else ""
327
- )
328
-
329
- return (
330
- '<div class="ocr-card verdict-card" '
331
- f'style="border-left-color:{color}">'
332
- '<div class="verdict-head">'
333
- f'<span class="verdict-icon">{icon}</span>'
334
- f'<span class="verdict-reco" style="color:{color}">{verdict.recommendation.upper()}</span>'
335
- f'<span class="verdict-score">Score <b>{score_label}</b></span>'
336
- "</div>"
337
- f'<div class="score-track"><div class="score-fill" style="width:{pct}%;background:{color}"></div></div>'
338
- f'<p class="verdict-summary">{html.escape(str(verdict.summary))}</p>'
339
- + chips_html
340
- + "</div>"
341
- )
342
-
343
-
344
- RAGAS_METRIC_LABELS = {
345
- "context_precision": "Context Precision",
346
- "context_recall": "Context Recall",
347
- "faithfulness": "Faithfulness",
348
- "answer_relevancy": "Answer Relevancy",
349
- "mmr": "Mean Reciprocal Rank",
350
- }
351
-
352
- RAGAS_METRIC_TOOLTIPS = {
353
- "context_precision": "Are the most relevant code chunks ranked first?",
354
- "context_recall": "Did we find ALL the relevant code? (requires ground truth)",
355
- "faithfulness": "Does the review answer stick to the retrieved code?",
356
- "answer_relevancy": "Does the review address the PR diff?",
357
- "mmr": "How early in the list does the first useful chunk appear?",
358
- }
359
-
360
-
361
- def _format_ragas_scores(scores: dict[str, float | None]) -> str:
362
- """Build an HTML card showing RAGAS retrieval quality metrics."""
363
- if not scores:
364
- return ""
365
-
366
- def _score_color(val: float) -> str:
367
- if val >= 0.8:
368
- return "#16a34a"
369
- elif val >= 0.5:
370
- return "#ca8a04"
371
- else:
372
- return "#dc2626"
373
-
374
- rows: list[str] = []
375
- failed = 0
376
- for key, value in scores.items():
377
- label = RAGAS_METRIC_LABELS.get(key, key.replace("_", " ").title())
378
- tooltip = RAGAS_METRIC_TOOLTIPS.get(key, "")
379
- tip_html = (
380
- f'<span class="tip" title="{tooltip}">ℹ️</span>' if tooltip else ""
381
- )
382
- if value is None:
383
- failed += 1
384
- rows.append(
385
- f'<div class="metric-row">'
386
- f'<span class="metric-label">{label} {tip_html}</span>'
387
- f'<span class="metric-value muted">N/A — failed</span>'
388
- f"</div>"
389
- )
390
- continue
391
- color = _score_color(value)
392
- pct = int(value * 100)
393
- rows.append(
394
- f'<div class="metric-row">'
395
- f'<span class="metric-label">{label} {tip_html}</span>'
396
- f'<span class="metric-value" style="color:{color}">{value:.3f}</span>'
397
- f"</div>"
398
- f'<div class="metric-track"><div class="metric-fill" style="width:{pct}%;background:{color}"></div></div>'
399
- )
400
-
401
- note = ""
402
- if failed:
403
- note = (
404
- '<p class="muted small" style="margin:10px 0 0">'
405
- f"{failed} metric(s) failed (likely LLM rate-limited) and are shown as N/A."
406
- "</p>"
407
- )
408
-
409
- return (
410
- '<div class="ocr-card">'
411
- '<div class="card-title">📊 Retrieval Quality (RAGAS)</div>'
412
- + "".join(rows)
413
- + note
414
- + "</div>"
415
- )
416
-
417
-
418
- RAGAS_PENDING_HTML = (
419
- '<div class="ocr-card">'
420
- '<div class="card-title">📊 Retrieval Quality (RAGAS)</div>'
421
- '<div class="loading-spinner" style="justify-content:flex-start;padding:10px 0">'
422
- '<div class="spinner"></div>'
423
- '<span class="label">Computing RAGAS scores in the background…</span>'
424
- "</div>"
425
- "</div>"
426
- )
427
-
428
- RAGAS_FAILED_HTML = (
429
- '<div class="ocr-card">'
430
- '<div class="card-title">📊 Retrieval Quality (RAGAS)</div>'
431
- '<p class="muted small">N/A — RAGAS scoring failed '
432
- "(likely LLM rate-limited or timed out). Check the logs for details.</p>"
433
- "</div>"
434
- )
435
-
436
- # After this long a background RAGAS task is considered stalled and the
437
- # placeholder is replaced with the failure card instead of spinning forever.
438
- RAGAS_TIMEOUT_SECONDS = 600
439
-
440
- # Background RAGAS task registry: the UI spawns scoring on a daemon thread
441
- # and a gr.Timer polls this dict, so review results render immediately
442
- # instead of waiting minutes for the RAGAS LLM calls.
443
- _ragas_tasks: dict[str, dict] = {}
444
- _ragas_lock = threading.Lock()
445
-
446
-
447
- def _ragas_inputs_from_state(state, endpoint_name: str) -> dict | None:
448
- """Extract the inputs RAGAS needs from the finished graph state."""
449
- verdict = state.values.get("verdict")
450
- if verdict and verdict.recommendation == "incomplete":
451
- return None
452
- context_chunks = state.values.get("context_chunks", [])
453
- query = state.values.get("diff", "") or ""
454
- if not query:
455
- changed = state.values.get("changed_files", [])
456
- paths = [getattr(item, "path", "") for item in changed if getattr(item, "path", "")]
457
- query = "Review changed files: " + ", ".join(paths) if paths else "Review the pull request changes"
458
- contexts = [c.content for c in context_chunks if c.content]
459
- # When vector retrieval is disabled on a small host, evaluate against the
460
- # PR diff itself. This preserves a grounded context for RAGAS instead of
461
- # silently dropping quality measurement altogether.
462
- if not contexts and query:
463
- contexts = [query]
464
- if not contexts:
465
- return None
466
-
467
- # Build answer text from findings + verdict for
468
- # faithfulness & answer_relevancy metrics
469
- answer_lines = []
470
- for f in state.values.get("final_findings", []):
471
- answer_lines.append(
472
- f"[{f.severity.value}] {f.file_path}:{f.line_start}-{f.line_end}: {f.comment}"
473
- )
474
- if state.values.get("verdict"):
475
- v = state.values["verdict"]
476
- answer_lines.append(
477
- f"Verdict: {v.recommendation} (score={v.overall_score}/10) — {v.summary}"
478
- )
479
- answer_text = "\n".join(answer_lines) if answer_lines else None
480
- return {
481
- "query": query,
482
- "context_source": "retrieved_context" if context_chunks else "pr_diff_proxy",
483
- "contexts": contexts,
484
- "answer": answer_text,
485
- "endpoint": __import__("endpoints").get_endpoint(endpoint_name) if endpoint_name else None,
486
- }
487
-
488
-
489
- def _compute_and_log_ragas(
490
- inputs: dict,
491
- repo: str,
492
- pr_number: int,
493
- run_trace_id: str | None,
494
- handler,
495
- progress_callback=None,
496
- ) -> dict[str, float | None]:
497
- """Compute RAGAS scores and log them to Langfuse. Never raises."""
498
- scores: dict[str, float | None] = {}
499
- try:
500
- from eval_data.ragas_eval import compute_ragas_report
501
-
502
- report = compute_ragas_report(
503
- query=inputs["query"],
504
- retrieved_contexts=inputs["contexts"],
505
- answer=inputs["answer"],
506
- endpoint=inputs["endpoint"],
507
- progress_callback=progress_callback,
508
- )
509
- scores = report["scores"]
510
- if progress_callback:
511
- progress_callback(report)
512
- for metric_name, value in scores.items():
513
- if value is None:
514
- continue
515
- log_langfuse_score(
516
- name=f"ragas_{metric_name}",
517
- value=value,
518
- comment=f"{repo}#{pr_number} — {metric_name}",
519
- trace_id=run_trace_id,
520
- handler=handler,
521
- )
522
- logger.info(
523
- "RAGAS scores logged to Langfuse: %s",
524
- " | ".join(
525
- f"{k}={v:.4f}" for k, v in scores.items() if v is not None
526
- ),
527
- )
528
- except ImportError:
529
- logger.info("RAGAS not installed — skipping RAGAS scoring (pip install ragas)")
530
- except Exception as exc:
531
- logger.warning("RAGAS scoring failed: %s", exc)
532
- return scores
533
-
534
-
535
- def _ragas_worker(
536
- task_id: str,
537
- inputs: dict,
538
- repo: str,
539
- pr_number: int,
540
- run_trace_id: str | None,
541
- handler,
542
- result_callback=None,
543
- ) -> None:
544
- """Daemon thread body: compute scores, stash them for the Timer poll."""
545
- timeout = float(os.getenv("OCR_RAGAS_TIMEOUT_SECONDS", "30"))
546
- def report_progress(report):
547
- with _ragas_lock:
548
- entry = _ragas_tasks.get(task_id)
549
- if entry is not None:
550
- entry["metrics"] = dict(report.get("metrics", {}))
551
- entry["evaluation"] = {**report.get("evaluation", {}), "context_source": inputs.get("context_source", "retrieved_context")}
552
- entry["scores"] = dict(report.get("scores", {}))
553
- with _ragas_lock:
554
- if task_id in _ragas_tasks:
555
- _ragas_tasks[task_id]["timeout_seconds"] = timeout
556
- try:
557
- # The provider call may block on a network timeout. Keep the task
558
- # terminal and observable even when the provider does not return.
559
- pool = ThreadPoolExecutor(max_workers=1, thread_name_prefix="ragas-call")
560
- future = pool.submit(
561
- copy_context().run,
562
- _compute_and_log_ragas,
563
- inputs,
564
- repo,
565
- pr_number,
566
- run_trace_id,
567
- handler,
568
- report_progress,
569
- )
570
- try:
571
- scores = future.result(timeout=timeout)
572
- except FutureTimeoutError:
573
- with _ragas_lock:
574
- entry = _ragas_tasks.get(task_id)
575
- scores = dict((entry or {}).get("scores") or {})
576
- if entry is not None:
577
- entry["error"] = f"RAGAS exceeded {int(timeout)} second timeout"
578
- entry["done"] = True
579
- if result_callback:
580
- result_callback(scores, f"RAGAS exceeded {int(timeout)} second timeout")
581
- pool.shutdown(wait=False, cancel_futures=True)
582
- return
583
- else:
584
- pool.shutdown(wait=True)
585
- except Exception as exc:
586
- logger.warning("RAGAS worker failed: %s", exc)
587
- with _ragas_lock:
588
- entry = _ragas_tasks.get(task_id)
589
- if entry is not None:
590
- entry["error"] = str(exc)[:500]
591
- entry["done"] = True
592
- if result_callback:
593
- result_callback({}, str(exc)[:500])
594
- return
595
- with _ragas_lock:
596
- entry = _ragas_tasks.get(task_id)
597
- if entry is not None:
598
- entry["scores"] = scores or {}
599
- entry["done"] = True
600
- if result_callback:
601
- result_callback(scores or {}, None)
602
- # Ship the Langfuse scores logged from this thread.
603
- flush_langfuse()
604
-
605
-
606
- def _spawn_ragas_background(
607
- inputs: dict,
608
- repo: str,
609
- pr_number: int,
610
- run_trace_id: str | None,
611
- handler,
612
- result_callback=None,
613
- ) -> str:
614
- """Start RAGAS scoring on a daemon thread; return a task id to poll."""
615
- task_id = f"ragas-{uuid.uuid4().hex[:12]}"
616
- with _ragas_lock:
617
- _ragas_tasks[task_id] = {"done": False, "scores": None, "started": time.time()}
618
- if len(_ragas_tasks) > 64:
619
- # Drop oldest finished entries to bound memory.
620
- for old_id in list(_ragas_tasks):
621
- if _ragas_tasks[old_id].get("done"):
622
- del _ragas_tasks[old_id]
623
- if len(_ragas_tasks) <= 64:
624
- break
625
- threading.Thread(
626
- target=copy_context().run,
627
- args=(_ragas_worker, task_id, inputs, repo, pr_number, run_trace_id, handler, result_callback),
628
- name=f"ragas-{task_id}",
629
- daemon=True,
630
- ).start()
631
- return task_id
632
-
633
-
634
- def _format_findings_count(findings: list) -> str:
635
- """Build a compact summary count per severity as pill chips."""
636
- counts: dict[str, int] = {}
637
- for f in findings:
638
- counts[f.severity.value] = counts.get(f.severity.value, 0) + 1
639
-
640
- parts = []
641
- for sev in ("critical", "high", "medium", "low", "info"):
642
- if counts.get(sev, 0) > 0:
643
- color = SEVERITY_COLORS.get(sev, "#666")
644
- parts.append(
645
- f'<span class="sev-chip" style="color:{color};border-color:{color}44;background:{color}11">'
646
- f"{sev} × {counts[sev]}</span>"
647
- )
648
- return (
649
- '<div class="chips-row">'
650
- + ("".join(parts) if parts else '<span class="muted">No issues</span>')
651
- + "</div>"
652
- )
653
-
654
-
655
- def _format_run_summary(
656
- repo: str, pr_number: int, endpoint_name: str, duration: float, cost_summary: str | dict
657
- ) -> str:
658
- """Build a compact run-summary card shown above the results."""
659
- endpoint_display = html.escape(endpoint_name or "built-in default")
660
- cost_text = cost_summary if isinstance(cost_summary, str) else str(cost_summary)
661
- return (
662
- '<div class="ocr-card" style="margin-top:12px">'
663
- '<div class="run-summary">'
664
- f'<span>📦 <b>{html.escape(repo)}</b>#{pr_number}</span>'
665
- f'<span>🤖 <b>{endpoint_display}</b></span>'
666
- f'<span>⏱️ <b>{duration:.1f}s</b></span>'
667
- f'<span>💰 {html.escape(cost_text)}</span>'
668
- "</div>"
669
- "</div>"
670
- )
671
-
672
-
673
- def _format_session_endpoints() -> str:
674
- """Render cards for endpoints added at runtime via the UI form."""
675
- eps = session_endpoints()
676
- if not eps:
677
- return (
678
- '<p class="muted small">No endpoints added in this session yet — '
679
- "fill the form above and click <b>Save &amp; use endpoint</b>.</p>"
680
- )
681
- cards = "".join(
682
- f'<div class="endpoint-card">'
683
- f'<div class="endpoint-name">{html.escape(ep.name)}'
684
- f'<span class="endpoint-badge">{html.escape(ep.provider)}</span></div>'
685
- f'<div class="endpoint-meta"><code>{html.escape(ep.model)}</code>'
686
- f' · {html.escape(ep.base_url or "default URL")} · key {ep.masked_key}</div>'
687
- f'</div>'
688
- for ep in eps
689
- )
690
- return (
691
- f'<div class="card-title" style="margin:6px 0 6px">'
692
- f'Added in this session ({len(eps)})</div><div>{cards}</div>'
693
- )
694
-
695
-
696
- def _probe_endpoint(ep) -> tuple[bool, str]:
697
- """Probe an endpoint and report whether it can serve the pipeline.
698
-
699
- HTTP status codes are classified so a 401/403 is reported as
700
- "reachable but the server rejected the key" instead of a misleading
701
- "unreachable". OpenAI-compatible servers that don't implement
702
- ``GET /models`` (many vLLM / proxy deployments) fall back to a
703
- minimal ``/chat/completions`` call — the real request the pipeline
704
- makes — so a blocked /models endpoint no longer looks broken.
705
- """
706
- import urllib.error as _ur_err
707
- import urllib.request as _ur
708
- from urllib.parse import urlsplit
709
-
710
- def _safe_base_url(raw_url: str | None, default: str) -> tuple[str | None, str | None]:
711
- """Allow only public HTTP(S) endpoints; never forward keys to private hosts."""
712
- value = (raw_url or default).strip().rstrip("/")
713
- try:
714
- parsed = urlsplit(value)
715
- if parsed.scheme not in {"http", "https"} or not parsed.hostname:
716
- return None, "base URL must use http(s) and include a hostname"
717
- if parsed.username or parsed.password:
718
- return None, "base URL must not contain embedded credentials"
719
- addresses = {item[4][0] for item in __import__("socket").getaddrinfo(parsed.hostname, parsed.port, type=__import__("socket").SOCK_STREAM)}
720
- for address in addresses:
721
- ip = ipaddress.ip_address(address)
722
- if not ip.is_global:
723
- return None, "base URL resolves to a private or otherwise non-public address"
724
- except Exception as exc:
725
- return None, f"invalid or unresolvable base URL: {type(exc).__name__}"
726
- return value, None
727
-
728
- class _NoRedirect(_ur.HTTPRedirectHandler):
729
- def redirect_request(self, req, fp, code, msg, headers, newurl):
730
- return None
731
-
732
- _opener = _ur.build_opener(_NoRedirect)
733
-
734
- def _open(req):
735
- return _opener.open(req, timeout=15)
736
-
737
- if ep.provider == "google":
738
- try:
739
- from google import genai
740
- client = genai.Client(api_key=ep.api_key)
741
- list(client.models.list())
742
- return True, "models.list OK"
743
- except Exception as exc:
744
- return False, f"{type(exc).__name__}: {exc}"[:140]
745
-
746
- def _auth_rejected(exc: _ur_err.HTTPError) -> str:
747
- return (
748
- f"endpoint is reachable but the server rejected the API key "
749
- f"(HTTP {exc.code}) — check the key and auth type"
750
- )
751
-
752
- # ── Anthropic ────────────────────────────────────────────────
753
- if ep.provider == "anthropic":
754
- base, error = _safe_base_url(ep.base_url, "https://api.anthropic.com/v1")
755
- if error:
756
- return False, error
757
- candidates = [f"{base}/models"]
758
- if not base.endswith("/v1"):
759
- candidates.append(f"{base}/v1/models")
760
- last_err = "no models endpoint responded"
761
- for url in candidates:
762
- try:
763
- req = _ur.Request(
764
- url,
765
- headers={
766
- "x-api-key": ep.api_key,
767
- "anthropic-version": "2023-06-01",
768
- },
769
- )
770
- with _open(req) as resp:
771
- if resp.status == 200:
772
- return True, f"HTTP 200 · {url}"
773
- except _ur_err.HTTPError as exc:
774
- if exc.code in (401, 403):
775
- # Same key on every candidate — auth failure is final.
776
- return False, f"{_auth_rejected(exc)} ({url})"
777
- hint = " — check base_url (should end in /v1)" if exc.code == 404 else ""
778
- last_err = f"reachable but returned HTTP {exc.code} ({url}){hint}"
779
- except Exception as exc:
780
- return False, f"unreachable — {type(exc).__name__}: {exc}"[:140]
781
- return False, last_err
782
-
783
- # ── OpenAI-compatible ──────────────────────────────────��─────
784
- base, error = _safe_base_url(ep.base_url, "https://api.openai.com/v1")
785
- if error:
786
- return False, error
787
- candidates = [f"{base}/models"]
788
- if not base.endswith("/v1"):
789
- candidates.append(f"{base}/v1/models")
790
-
791
- for url in candidates:
792
- try:
793
- req = _ur.Request(
794
- url, headers={"Authorization": f"Bearer {ep.api_key}"}
795
- )
796
- with _open(req) as resp:
797
- if resp.status == 200:
798
- return True, f"HTTP 200 · {url}"
799
- except _ur_err.HTTPError as exc:
800
- if exc.code in (401, 403):
801
- # Bad key on /models means chat would fail the same way.
802
- return False, f"{_auth_rejected(exc)} ({url})"
803
- except Exception as exc:
804
- # Genuinely unreachable — chat probe below would only repeat it.
805
- return False, f"unreachable — {type(exc).__name__}: {exc}"[:140]
806
-
807
- # /models missing or blocked (404/405/501…) — probe the real call.
808
- try:
809
- payload = json.dumps({
810
- "model": ep.model,
811
- "messages": [{"role": "user", "content": "ping"}],
812
- "max_tokens": 1,
813
- }).encode()
814
- chat_url = f"{base}/chat/completions"
815
- req = _ur.Request(
816
- chat_url,
817
- data=payload,
818
- headers={
819
- "Authorization": f"Bearer {ep.api_key}",
820
- "Content-Type": "application/json",
821
- },
822
- method="POST",
823
- )
824
- with _open(req) as resp:
825
- if resp.status == 200:
826
- return True, f"chat/completions OK · {chat_url}"
827
- return False, f"reachable but returned HTTP {resp.status} (chat/completions)"
828
- except _ur_err.HTTPError as exc:
829
- if exc.code in (401, 403):
830
- return False, f"{_auth_rejected(exc)} (chat/completions)"
831
- hint = " — check base_url (should end in /v1)" if exc.code == 404 else ""
832
- return False, f"reachable but returned HTTP {exc.code} (chat/completions){hint}"
833
- except Exception as exc:
834
- return False, f"unreachable — {type(exc).__name__}: {exc}"[:140]
835
-
836
-
837
- def test_endpoints() -> str:
838
- """Probe every configured endpoint and render status cards.
839
-
840
- Built-in providers (Gemini/Grok) whose key is not set are skipped with
841
- a ``⏭️ key not set`` note instead of being probed (a probe would just
842
- fail with 401 / an auth error).
843
- """
844
- eps = discover_endpoints()
845
-
846
- cards = []
847
- for ep in eps:
848
- if ep.builtin and not ep.api_key:
849
- cards.append(
850
- f'<div class="endpoint-card">'
851
- f'<div class="endpoint-name">{html.escape(ep.name)}'
852
- f'<span class="endpoint-badge">{html.escape(ep.provider)}</span></div>'
853
- f'<div class="endpoint-meta"><code>{html.escape(ep.model)}</code>'
854
- f' · {html.escape(ep.base_url or "default URL")} · key {html.escape(ep.masked_key)}</div>'
855
- f'<div class="endpoint-meta" style="color:var(--text-muted);font-weight:700">'
856
- f'⏭️ key not set (add GEMINI_API_KEY / GROQ_API_KEY)</div>'
857
- f'</div>'
858
- )
859
- continue
860
- ok, detail = _probe_endpoint(ep)
861
- status_color = "#16a34a" if ok else "#dc2626"
862
- cards.append(
863
- f'<div class="endpoint-card">'
864
- f'<div class="endpoint-name">{html.escape(ep.name)}'
865
- f'<span class="endpoint-badge">{html.escape(ep.provider)}</span></div>'
866
- f'<div class="endpoint-meta"><code>{html.escape(ep.model)}</code>'
867
- f' · {html.escape(ep.base_url or "default URL")} · key {html.escape(ep.masked_key)}</div>'
868
- f'<div class="endpoint-meta" style="color:{status_color};font-weight:700">'
869
- f'{"✅" if ok else "❌"} {html.escape(detail)}</div>'
870
- f'</div>'
871
- )
872
- return '<div>' + "".join(cards) + '</div>'
873
-
874
-
875
- # ─── Helpers ─────────────────────────────────────────────────────────────────
876
-
877
-
878
- def _get_deploy_info() -> tuple[str, str]:
879
- """Return Git commit hash and deploy timestamp for the footer."""
880
- commit = "unknown"
881
- try:
882
- result = subprocess.run(
883
- ["git", "rev-parse", "--short", "HEAD"],
884
- capture_output=True, text=True, timeout=5,
885
- )
886
- if result.returncode == 0:
887
- commit = result.stdout.strip()
888
- except Exception:
889
- pass
890
- ts = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
891
- return commit, ts
892
-
893
-
894
- # ─── Gradio callbacks ───────────────────────────────────────────────────────
895
-
896
-
897
- # _prune_db replaced with direct _cleanup_db() calls below
898
-
899
-
900
- def run_review(repo: str, pr_number: int, endpoint_name: str = "", progress=gr.Progress()):
901
- """Run the review pipeline up to human-in-the-loop interrupt."""
902
- if not repo or "/" not in repo:
903
- yield [None, None, None, None, None, None], "❌ Enter a repo in `owner/name` format."
904
- return
905
-
906
- endpoint_name = _normalize_endpoint_name(endpoint_name)
907
-
908
- # Fail fast on an unknown endpoint name (allow_custom_value lets any
909
- # string through the dropdown; the reviewer nodes would otherwise
910
- # swallow the ValueError and report a confusing empty review).
911
- if endpoint_name:
912
- from endpoints import get_endpoint
913
-
914
- ep = get_endpoint(endpoint_name)
915
- if ep is None:
916
- yield [None, None, None, None, None, None], (
917
- f"❌ Endpoint '{endpoint_name}' not found — pick one from "
918
- "the list or add it in the form above."
919
- )
920
- return
921
- if ep.builtin and not ep.api_key:
922
- key_var = "GEMINI_API_KEY" if ep.name == "Gemini" else "GROQ_API_KEY"
923
- yield [None, None, None, None, None, None], (
924
- f"❌ Endpoint '{ep.name}' is selected but its key is not set — "
925
- f"add `{key_var}` as a Space secret, or add a custom endpoint "
926
- "in the form above."
927
- )
928
- return
929
-
930
- _cleanup_db()
931
-
932
- progress(0.1, desc="Building graph…")
933
-
934
- t0 = time.time()
935
- try:
936
- state, config, cost_summary, ragas_out, _ragas_inputs = _build_and_stream(
937
- repo.strip(), int(pr_number), endpoint_name, ragas_background=True,
938
- )
939
- except Exception as exc:
940
- log_error_to_backends(exc, context={"source": "gradio_ui", "phase": "run_review", "repo": repo, "pr_number": pr_number})
941
- yield ([None, None, None, None, None, None], f"❌ Review failed: {exc}")
942
- return
943
-
944
- duration = time.time() - t0
945
-
946
- tasks = state.tasks
947
- values = state.values
948
-
949
- if not tasks:
950
- yield [None, None, None, None, None, None], "ℹ️ Review completed without findings."
951
- return
952
-
953
- verdict: Verdict | None = values.get("verdict")
954
- findings: list = values.get("final_findings", [])
955
-
956
- progress(0.8, desc="Formatting results…")
957
-
958
- verdict_html = _format_verdict(verdict)
959
- if isinstance(ragas_out, str):
960
- ragas_task_id = ragas_out
961
- ragas_html = RAGAS_PENDING_HTML
962
- else:
963
- ragas_task_id = ""
964
- ragas_html = _format_ragas_scores(ragas_out)
965
- findings_html = _format_findings_table(findings)
966
- count_html = _format_findings_count(findings)
967
- # Strip non-serializable callbacks before saving config to state
968
- config_json = json.dumps(
969
- {k: v for k, v in config.items() if k != "callbacks"}
970
- )
971
-
972
- run_summary_html = _format_run_summary(
973
- repo.strip(), pr_number, endpoint_name, duration, cost_summary,
974
- )
975
-
976
- yield (
977
- [run_summary_html, verdict_html, findings_html, count_html, ragas_html, config_json, ragas_task_id],
978
- None,
979
- )
980
-
981
-
982
- def resume_review(config_json: str, action: str, progress=gr.Progress()):
983
- """Resume the paused graph with approve/reject."""
984
- if not config_json:
985
- return "ℹ️ No pending review to resume. Run a review first."
986
-
987
- try:
988
- config = json.loads(config_json)
989
- if not isinstance(config, dict):
990
- raise ValueError("pending review state must be a JSON object")
991
- except (TypeError, ValueError, json.JSONDecodeError) as exc:
992
- return f"❌ Invalid pending review state: {html.escape(str(exc))}"
993
- graph = build_graph(DB_PATH)
994
- handler = get_langfuse_handler()
995
- cost_tracker = TokenCostCallback()
996
- callbacks = [cost_tracker]
997
- if handler:
998
- callbacks.append(handler)
999
- config.setdefault("callbacks", []).extend(callbacks)
1000
-
1001
- progress(0.3, desc=f"Processing {action}…")
1002
-
1003
- try:
1004
- graph.invoke(Command(resume={"action": action}), config)
1005
- final_state = graph.get_state(config)
1006
- approved = final_state.values.get("human_approved")
1007
- msg = (
1008
- f"✅ Review **approved**! Findings posted to GitHub."
1009
- if approved
1010
- else "❌ Review **rejected**. No comments posted."
1011
- )
1012
- if cost_tracker.usage:
1013
- msg += f" _{cost_tracker.summary()}_"
1014
- except Exception as exc:
1015
- log_error_to_backends(exc, context={"source": "gradio_ui", "phase": "resume_review", "action": action})
1016
- msg = f"❌ Error: {exc}"
1017
- finally:
1018
- # Close the checkpointer connection and ship any queued scores.
1019
- conn = getattr(graph, "_opencodereview_conn", None)
1020
- if conn:
1021
- conn.close()
1022
- flush_langfuse()
1023
- return msg
1024
-
1025
-
1026
- def run_smoke(progress=gr.Progress()):
1027
- """Run the synthetic smoke test."""
1028
- _cleanup_db()
1029
-
1030
- progress(0.1, desc="Building graph…")
1031
- graph = build_graph(DB_PATH)
1032
- thread_id = str(uuid.uuid4())
1033
- prompt_versions = {
1034
- "correctness": "v1",
1035
- "security": "v1",
1036
- "test_coverage": "v1",
1037
- "aggregator": "v1",
1038
- }
1039
- cost_tracker = TokenCostCallback()
1040
- metadata = build_run_metadata(
1041
- source="gradio_ui", repo="demo-org/demo-repo", pr_number=1,
1042
- session_id=thread_id,
1043
- prompt_versions=prompt_versions,
1044
- )
1045
- config: dict = {
1046
- "configurable": {"thread_id": f"smoke-web-{thread_id}"},
1047
- "metadata": metadata,
1048
- }
1049
-
1050
- progress(0.3, desc="Running on synthetic data…")
1051
- with langfuse_trace(
1052
- trace_name="opencodereview/smoke-test",
1053
- tags=["gradio_ui", "smoke", "demo-org/demo-repo"],
1054
- session_id=thread_id,
1055
- metadata={"prompt_versions": prompt_versions},
1056
- ) as handler:
1057
- callbacks = [cost_tracker]
1058
- if handler:
1059
- callbacks.append(handler)
1060
- config["callbacks"] = callbacks
1061
-
1062
- try:
1063
- list(graph.stream(SYNTHETIC_STATE, config))
1064
- except Exception as exc:
1065
- log_error_to_backends(exc, context={"source": "gradio_ui", "phase": "smoke_stream"})
1066
- logger.exception("Smoke test failed: %s", exc)
1067
- raise
1068
-
1069
- state = graph.get_state(config)
1070
- tasks = state.tasks
1071
-
1072
- # Close the checkpointer connection and ship any queued Langfuse scores.
1073
- conn = getattr(graph, "_opencodereview_conn", None)
1074
- if conn:
1075
- conn.close()
1076
- flush_langfuse()
1077
-
1078
- if not tasks:
1079
- yield [None, None, None, None, None], "ℹ️ Smoke test completed without findings."
1080
- return
1081
-
1082
- verdict: Verdict | None = state.values.get("verdict")
1083
- findings: list = state.values.get("final_findings", [])
1084
-
1085
- progress(0.8, desc="Formatting…")
1086
- verdict_html = _format_verdict(verdict)
1087
- findings_html = _format_findings_table(findings)
1088
- # Strip non-serializable callbacks before saving config to state
1089
- config_json = json.dumps(
1090
- {k: v for k, v in config.items() if k != "callbacks"}
1091
- )
1092
- cost_html = f'<p style="margin-top:8px;font-size:0.85em;color:var(--text-muted)">{cost_tracker.summary()}</p>'
1093
-
1094
- yield [verdict_html, findings_html + cost_html, config_json, verdict_html, findings_html], None
1095
-
1096
-
1097
- # ─── UI ──────────────────────────────────────────────────────────────────────
1098
-
1099
- CSS = """
1100
- /* ── CSS Custom Properties (light mode) ───────────────────────────── */
1101
- :root {
1102
- --bg-page: #f1f5f9;
1103
- --bg-card: #ffffff;
1104
- --bg-card-alt: #f8fafc;
1105
- --bg-table-header: #f1f5f9;
1106
- --border-color: #e2e8f0;
1107
- --text-primary: #0f172a;
1108
- --text-secondary: #475569;
1109
- --text-muted: #64748b;
1110
- --text-footer: #94a3b8;
1111
- --spinner-track: #e2e8f0;
1112
- --accent: #52525b;
1113
- --accent-soft: rgba(82, 82, 91, 0.10);
1114
- --glass: rgba(255, 255, 255, 0.55);
1115
- --glass-border: rgba(15, 23, 42, 0.10);
1116
- --glass-field: rgba(255, 255, 255, 0.72);
1117
- --glass-edge: rgba(15, 23, 42, 0.18);
1118
- --glass-hover: rgba(15, 23, 42, 0.05);
1119
- --glass-highlight: inset 0 1px 0 rgba(255, 255, 255, 0.8);
1120
- --radius: 14px;
1121
- --shadow: 0 1px 2px rgba(15, 23, 42, 0.05), 0 10px 30px rgba(15, 23, 42, 0.06);
1122
- }
1123
-
1124
- /* ── Dark Mode — true black, glass surfaces, no blue ────────────── */
1125
- body.dark {
1126
- --bg-page: #000000;
1127
- --bg-card: #0a0a0a;
1128
- --bg-card-alt: #101010;
1129
- --bg-table-header: #0a0a0a;
1130
- --border-color: #1f1f1f;
1131
- --text-primary: #f5f5f5;
1132
- --text-secondary: #d4d4d4;
1133
- --text-muted: #8a8a8a;
1134
- --text-footer: #5c5c5c;
1135
- --spinner-track: #1c1c1c;
1136
- --accent: #a1a1aa;
1137
- --accent-soft: rgba(255, 255, 255, 0.07);
1138
- --shadow: none;
1139
- --glass: rgba(255, 255, 255, 0.035);
1140
- --glass-border: rgba(255, 255, 255, 0.09);
1141
- --glass-field: rgba(255, 255, 255, 0.045);
1142
- --glass-edge: rgba(255, 255, 255, 0.12);
1143
- --glass-hover: rgba(255, 255, 255, 0.12);
1144
- --glass-highlight: inset 0 1px 0 rgba(255, 255, 255, 0.07);
1145
- }
1146
- /* Glass buttons — replace Gradio's solid blue primary / gray secondary
1147
- with frosted neutral surfaces (scoped to the app area, not Gradio's
1148
- own footer controls). */
1149
- .gradio-container main button.primary {
1150
- background: var(--glass-hover) !important;
1151
- color: var(--text-primary) !important;
1152
- border: 1px solid var(--glass-edge) !important;
1153
- border-radius: 12px !important;
1154
- font-weight: 600 !important;
1155
- box-shadow: var(--glass-highlight) !important;
1156
- backdrop-filter: blur(12px) !important;
1157
- transition: background 0.18s ease, border-color 0.18s ease !important;
1158
- }
1159
- .gradio-container main button.primary:hover {
1160
- background: var(--accent-soft) !important;
1161
- border-color: var(--text-muted) !important;
1162
- }
1163
- .gradio-container main button:not(.primary) {
1164
- background: var(--glass) !important;
1165
- color: var(--text-secondary) !important;
1166
- border: 1px solid var(--glass-border) !important;
1167
- border-radius: 12px !important;
1168
- font-weight: 500 !important;
1169
- box-shadow: var(--glass-highlight) !important;
1170
- backdrop-filter: blur(10px) !important;
1171
- transition: background 0.18s ease, color 0.18s ease, border-color 0.18s ease !important;
1172
- }
1173
- .gradio-container main button:not(.primary):hover {
1174
- background: var(--glass-hover) !important;
1175
- color: var(--text-primary) !important;
1176
- border-color: var(--glass-edge) !important;
1177
- }
1178
- /* Frosted input fields in both themes. */
1179
- .gradio-container input, .gradio-container textarea, .gradio-container select {
1180
- background-color: var(--glass-field) !important;
1181
- border-color: var(--glass-edge) !important;
1182
- backdrop-filter: blur(8px);
1183
- }
1184
- /* Fill the dropdown wrapper so it reads as one glass field. */
1185
- .gradio-container .glass-dropdown .wrap {
1186
- background-color: var(--glass-field) !important;
1187
- border-color: var(--glass-edge) !important;
1188
- backdrop-filter: blur(8px);
1189
- }
1190
- body.dark .gradio-container {
1191
- background: var(--bg-page) !important;
1192
- }
1193
- /* Blend Gradio's component panels into the page: no boxes, no
1194
- borders — only inputs keep a faint field tint so they stay legible. */
1195
- body.dark .block,
1196
- body.dark .form,
1197
- body.dark .tabs,
1198
- body.dark .tabitem {
1199
- background: transparent !important;
1200
- border-color: transparent !important;
1201
- box-shadow: none !important;
1202
- }
1203
- body.dark .tab-nav {
1204
- border-bottom: 1px solid var(--border-color) !important;
1205
- background: transparent !important;
1206
- }
1207
- body.dark input, body.dark textarea, body.dark select {
1208
- background-color: var(--glass-field) !important;
1209
- color: var(--text-primary) !important;
1210
- border-color: var(--glass-edge) !important;
1211
- backdrop-filter: blur(8px);
1212
- }
1213
- body.dark .gradio-container .glass-dropdown .wrap {
1214
- color: var(--text-primary) !important;
1215
- }
1216
- body.dark label { color: var(--text-secondary) !important; }
1217
- /* Field labels render as small pills in the Soft theme — restyle them
1218
- as quiet glass chips instead of the default saturated background. */
1219
- label span[data-testid="block-info"],
1220
- span.has-info,
1221
- span[data-testid="block-info"] {
1222
- background: var(--glass) !important;
1223
- color: var(--text-primary) !important;
1224
- border: 1px solid var(--glass-border);
1225
- border-radius: 9px;
1226
- padding: 2px 10px;
1227
- font-weight: 500 !important;
1228
- backdrop-filter: blur(8px);
1229
- box-shadow: var(--glass-highlight);
1230
- }
1231
- body.dark button:not(.lg) { color: var(--text-primary) !important; }
1232
- body.dark .footer { color: var(--text-footer) !important; }
1233
- body.dark details summary { color: var(--text-secondary) !important; }
1234
- body.dark [data-testid="block-info"] { color: var(--text-primary) !important; }
1235
-
1236
- /* ── Global ──────────────────────────────────────────────────────── */
1237
- /* Component forms blend into the page in both themes; inputs keep
1238
- their own field background so they stay clearly interactive. */
1239
- .gradio-container .form {
1240
- background: transparent !important;
1241
- border: none !important;
1242
- box-shadow: none !important;
1243
- }
1244
- .gradio-container {
1245
- background: radial-gradient(1200px 500px at 20% -10%, #eef2ff66, transparent 60%),
1246
- radial-gradient(1000px 400px at 90% 10%, #e0f2fe55, transparent 55%),
1247
- var(--bg-page) !important;
1248
- }
1249
- .gradio-container { max-width: 1024px; margin: 0 auto; }
1250
- .footer { text-align: center; color: var(--text-footer); font-size: 0.85em; padding: 22px 0; }
1251
- details { margin-top: 8px; }
1252
- details summary { cursor: pointer; color: var(--text-secondary); font-weight: 500; }
1253
- code { background: var(--bg-card-alt); padding: 1px 6px; border-radius: 6px; font-size: 0.92em; }
1254
- .muted { color: var(--text-muted) !important; }
1255
- .small { font-size: 0.85em; }
1256
-
1257
- /* ── Hero ────────────────────────────────────────────────────────── */
1258
- .hero { display: flex; align-items: center; gap: 16px; padding: 8px 0 4px; }
1259
- .hero-icon {
1260
- font-size: 1.5em; width: 48px; height: 48px; display: flex; align-items: center;
1261
- justify-content: center; border-radius: 14px;
1262
- background: var(--glass);
1263
- border: 1px solid var(--glass-border);
1264
- box-shadow: var(--glass-highlight);
1265
- backdrop-filter: blur(12px);
1266
- }
1267
- .hero-title { margin: 0; font-size: 1.35em; font-weight: 650; letter-spacing: -0.015em; color: var(--text-primary); }
1268
- .hero-sub { margin: 2px 0 0; color: var(--text-muted); font-size: 0.95em; }
1269
-
1270
- /* ── Cards ───────────────────────────────────────────────────────── */
1271
- .ocr-card {
1272
- background: var(--glass);
1273
- border: 1px solid var(--glass-border);
1274
- border-radius: var(--radius); padding: 16px 20px; margin-top: 12px;
1275
- box-shadow: var(--glass-highlight);
1276
- backdrop-filter: blur(14px);
1277
- }
1278
- .card-title { font-weight: 600; color: var(--text-primary); margin-bottom: 12px; font-size: 1.0em; letter-spacing: 0.01em; }
1279
- .chips-row { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }
1280
-
1281
- /* ── Chips / badges ──────────────────────────────────────────────── */
1282
- .key-chip {
1283
- display: inline-block; padding: 3px 12px; border-radius: 999px;
1284
- font-size: 0.82em; font-weight: 500; border: 1px solid var(--glass-border);
1285
- background: var(--glass); color: var(--text-secondary);
1286
- backdrop-filter: blur(8px);
1287
- }
1288
- .key-chip.ok { color: #4ade80; border-color: rgba(74, 222, 128, 0.25); background: rgba(74, 222, 128, 0.07); }
1289
- .sev-chip {
1290
- display: inline-block; padding: 3px 12px; border-radius: 999px;
1291
- font-size: 0.82em; font-weight: 600; border: 1px solid var(--glass-border);
1292
- background: var(--glass);
1293
- }
1294
-
1295
- /* ── Endpoint cards ──────────────────────────────────────────────── */
1296
- .endpoint-card {
1297
- border: 1px solid var(--glass-border); border-radius: 12px;
1298
- padding: 10px 14px; margin-bottom: 8px; background: var(--glass);
1299
- backdrop-filter: blur(10px);
1300
- }
1301
- .endpoint-name { font-weight: 600; color: var(--text-primary); display: flex; gap: 8px; align-items: center; }
1302
- .endpoint-badge {
1303
- font-size: 0.7em; font-weight: 600; text-transform: uppercase; letter-spacing: 0.05em;
1304
- padding: 2px 8px; border-radius: 999px; color: var(--text-muted);
1305
- background: var(--accent-soft); border: 1px solid var(--glass-border);
1306
- }
1307
- .endpoint-meta { margin-top: 4px; font-size: 0.88em; color: var(--text-secondary); }
1308
-
1309
- /* ── Run summary ─────────────────────────────────────────────────── */
1310
- .run-summary { display: flex; gap: 20px; flex-wrap: wrap; align-items: center; font-size: 0.92em; color: var(--text-secondary); }
1311
- .run-summary b { color: var(--text-primary); }
1312
-
1313
- /* ── Verdict ─────────────────────────────────────────────────────── */
1314
- .verdict-card { border-left: 5px solid var(--accent); }
1315
- .verdict-head { display: flex; align-items: center; gap: 12px; margin-bottom: 10px; flex-wrap: wrap; }
1316
- .verdict-icon { font-size: 1.8em; }
1317
- .verdict-reco { font-size: 1.35em; font-weight: 800; letter-spacing: 0.02em; }
1318
- .verdict-score { margin-left: auto; font-size: 1.05em; color: var(--text-secondary); }
1319
- .verdict-score b { color: var(--text-primary); font-size: 1.25em; }
1320
- .verdict-summary { margin: 10px 0 0; color: var(--text-secondary); line-height: 1.55; }
1321
- .score-track { height: 10px; background: var(--spinner-track); border-radius: 999px; overflow: hidden; margin-top: 4px; }
1322
- .score-fill { height: 100%; border-radius: 999px; transition: width 0.7s ease; }
1323
-
1324
- /* ── RAGAS metrics ───────────────────────────────────────────────── */
1325
- .metric-row { display: flex; justify-content: space-between; align-items: center; margin: 8px 0 4px; }
1326
- .metric-label { font-weight: 600; color: var(--text-secondary); font-size: 0.93em; }
1327
- .metric-value { font-weight: 800; font-size: 0.98em; }
1328
- .metric-track { height: 8px; background: var(--spinner-track); border-radius: 999px; overflow: hidden; }
1329
- .metric-fill { height: 100%; border-radius: 999px; transition: width 0.6s ease; }
1330
- .tip { cursor: help; font-size: 0.85em; }
1331
-
1332
- /* ── Findings table ──────────────────────────────────────────────── */
1333
- table { width: 100%; border-collapse: collapse; font-size: 0.9em; }
1334
- thead tr { background: var(--bg-table-header); border-bottom: 2px solid var(--border-color); }
1335
- th { padding: 10px 12px; text-align: left; color: var(--text-primary); }
1336
- td { padding: 10px 12px; color: var(--text-secondary); border-bottom: 1px solid var(--border-color); vertical-align: top; }
1337
- tbody tr:hover { background: var(--bg-card-alt); }
1338
-
1339
- /* ── Theme toggle ────────────────────────────────────────────────── */
1340
- #theme-toggle-btn {
1341
- float: right; margin-top: 18px !important; background: var(--glass) !important;
1342
- border: 1px solid var(--glass-border) !important; border-radius: 10px !important;
1343
- padding: 4px 10px !important; font-size: 1.1em !important; min-width: 44px !important;
1344
- transition: all 0.2s ease !important;
1345
- box-shadow: var(--glass-highlight) !important;
1346
- backdrop-filter: blur(10px) !important;
1347
- }
1348
- #theme-toggle-btn:hover { background: var(--accent-soft) !important; border-color: var(--glass-edge) !important; }
1349
-
1350
- /* ── Loading spinner ─────────────────────────────────────────────── */
1351
- @keyframes spin { to { transform: rotate(360deg); } }
1352
- .loading-spinner {
1353
- display: flex; align-items: center; gap: 12px; padding: 24px 0; justify-content: center;
1354
- }
1355
- .loading-spinner .spinner {
1356
- width: 24px; height: 24px; border: 3px solid var(--spinner-track);
1357
- border-top-color: var(--accent); border-radius: 50%; animation: spin 0.8s linear infinite;
1358
- }
1359
- .loading-spinner .label { color: var(--text-muted); font-size: 0.95em; }
1360
- """
1361
-
1362
- JS_RESTORE_THEME = """
1363
- () => {
1364
- // Single source of truth for the theme: the body.dark class that
1365
- // Gradio itself also uses for dark mode. Our own key in localStorage
1366
- // only records an explicit choice; when absent, whatever Gradio picked
1367
- // (OS preference) is left untouched.
1368
- const saved = localStorage.getItem("ocr-theme");
1369
- if (saved === "dark") document.body.classList.add("dark");
1370
- if (saved === "light") document.body.classList.remove("dark");
1371
- const btn = document.querySelector("#theme-toggle-btn");
1372
- if (btn) btn.textContent = document.body.classList.contains("dark") ? "☀️" : "🌙";
1373
- }
1374
- """
1375
-
1376
- JS_TOGGLE_THEME = """
1377
- () => {
1378
- const isDark = document.body.classList.toggle("dark");
1379
- localStorage.setItem("ocr-theme", isDark ? "dark" : "light");
1380
- const btn = document.querySelector("#theme-toggle-btn");
1381
- if (btn) btn.textContent = isDark ? "☀️" : "🌙";
1382
- return [];
1383
- }
1384
- """
1385
-
1386
- # ── Initialise observability backends ────────────────────────────────
1387
- # Wrap in try/except so a failure here doesn't prevent the UI from loading.
1388
- # This is important on Hugging Face Spaces where dependencies may have
1389
- # version incompatibilities.
1390
- try:
1391
- _init_observability_ui()
1392
- except Exception as exc:
1393
- logger.warning("Observability initialisation failed (non-fatal): %s", exc)
1394
-
1395
- with gr.Blocks(title="OpenCodeReview") as demo:
1396
- demo.load(js=JS_RESTORE_THEME)
1397
-
1398
- # Discover configured endpoints once — reused by the hero chip and the
1399
- # health accordion. (The dropdown builds its grouped choices live via
1400
- # endpoints.dropdown_choices() so built-ins + added endpoints stay in sync.)
1401
- _configured_endpoints = discover_endpoints()
1402
-
1403
- with gr.Row():
1404
- with gr.Column(scale=4):
1405
- gr.HTML(
1406
- '<div class="hero">'
1407
- '<div class="hero-icon">◈</div>'
1408
- '<div>'
1409
- '<h1 class="hero-title">OpenCodeReview</h1>'
1410
- '<p class="hero-sub">AI-powered PR review with human-in-the-loop approval</p>'
1411
- f'<div class="chips-row" style="margin-top:8px">'
1412
- f'<span class="key-chip ok">{len(_configured_endpoints)} endpoint'
1413
- f'{"s" if len(_configured_endpoints) != 1 else ""} configured</span>'
1414
- '<span class="key-chip">Built-ins: Gemini · Groq</span>'
1415
- '<span class="key-chip">Bring your own keys</span>'
1416
- '</div>'
1417
- '</div>'
1418
- '</div>'
1419
- )
1420
- with gr.Column(scale=1, min_width=60):
1421
- theme_toggle = gr.Button("🌙", elem_id="theme-toggle-btn", size="sm", min_width=50, visible=True)
1422
- theme_toggle.click(js=JS_TOGGLE_THEME)
1423
-
1424
- # ── State ────────────────────────────────────────────────────────────
1425
- pr_state = gr.State()
1426
- smoke_state = gr.State()
1427
- # Id of this session's background RAGAS task — the gr.Timer below polls
1428
- # it so review results render immediately instead of waiting on RAGAS.
1429
- ragas_task_state = gr.State(value="")
1430
-
1431
- # ── Tab: Review ──────────────────────────────────────────────────
1432
- with gr.Tab("Review"):
1433
- with gr.Row():
1434
- repo_input = gr.Textbox(
1435
- label="Repository",
1436
- placeholder="owner/repo (e.g. psf/requests)",
1437
- scale=3,
1438
- )
1439
- pr_input = gr.Number(
1440
- label="PR #",
1441
- value=1,
1442
- minimum=1,
1443
- precision=0,
1444
- scale=1,
1445
- )
1446
-
1447
- with gr.Row():
1448
- endpoint_input = gr.Dropdown(
1449
- choices=[""] + dropdown_choices(),
1450
- value=AUTO_ENDPOINT_CHOICE,
1451
- label="LLM Endpoint",
1452
- info=(
1453
- "Built-ins: Gemini and Groq (Groq serves Llama models). "
1454
- "Defaults to Gemini → Groq fallback."
1455
- ),
1456
- # Grouped optgroup choices make Gradio's strict membership
1457
- # check reject values that sit inside a group (e.g. a custom
1458
- # endpoint registered moments ago). allow_custom_value lets
1459
- # any registered endpoint name pass through; unknown names
1460
- # still fail with a clear error at review time.
1461
- allow_custom_value=True,
1462
- scale=3,
1463
- elem_classes=["glass-dropdown"],
1464
- )
1465
- test_selected_btn = gr.Button("Test selected", size="sm", scale=1)
1466
- endpoint_test_msg = gr.Markdown()
1467
-
1468
- def on_test_selected(endpoint_name):
1469
- """Probe the currently selected endpoint (built-in or custom)."""
1470
- endpoint_name = _normalize_endpoint_name(endpoint_name)
1471
- if not endpoint_name:
1472
- return (
1473
- "ℹ️ Leave the endpoint empty for auto (Gemini → Groq fallback), "
1474
- "or pick one and test it here."
1475
- )
1476
- from endpoints import get_endpoint
1477
-
1478
- ep = get_endpoint(endpoint_name)
1479
- if ep is None:
1480
- return f"❌ Endpoint '{html.escape(endpoint_name)}' not found — add it in the form below first."
1481
- if ep.builtin and not ep.api_key:
1482
- key_var = "GEMINI_API_KEY" if ep.name == "Gemini" else "GROQ_API_KEY"
1483
- return (
1484
- f"⏭️ **{html.escape(ep.name)}** key is not set — add `{html.escape(key_var)}` "
1485
- "as a Space secret to test it."
1486
- )
1487
- ok, detail = _probe_endpoint(ep)
1488
- icon = "✅" if ok else "❌"
1489
- return f"{icon} **{html.escape(ep.name)}** (`{html.escape(ep.model)}`): {html.escape(detail)}"
1490
-
1491
- test_selected_btn.click(
1492
- fn=on_test_selected,
1493
- inputs=[endpoint_input],
1494
- outputs=[endpoint_test_msg],
1495
- )
1496
-
1497
- # ── Add your own endpoint (BYO key) ─────────────────────────
1498
- with gr.Accordion("Add a custom endpoint (BYO key)", open=False):
1499
- with gr.Row():
1500
- ep_name_input = gr.Textbox(
1501
- label="Endpoint name",
1502
- placeholder="e.g. My DeepSeek",
1503
- scale=1,
1504
- )
1505
- ep_type_input = gr.Dropdown(
1506
- choices=["openai", "anthropic", "google"],
1507
- value="openai",
1508
- label="Type",
1509
- info="openai = any OpenAI-compatible API (DeepSeek, OpenRouter, Ollama…)",
1510
- scale=1,
1511
- elem_classes=["glass-dropdown"],
1512
- )
1513
- with gr.Row():
1514
- ep_base_url_input = gr.Textbox(
1515
- label="API endpoint (base URL)",
1516
- placeholder="https://api.deepseek.com/v1 (optional for google)",
1517
- scale=2,
1518
- )
1519
- ep_model_input = gr.Textbox(
1520
- label="Model",
1521
- placeholder="deepseek-chat / claude-sonnet-4-20250514 / gemini-3.1-flash",
1522
- scale=2,
1523
- )
1524
- ep_api_key_input = gr.Textbox(
1525
- label="API key",
1526
- type="password",
1527
- placeholder="sk-... (stored in memory only, never written to disk)",
1528
- )
1529
- with gr.Row():
1530
- test_form_btn = gr.Button("Test this endpoint", size="sm")
1531
- add_endpoint_btn = gr.Button("Save & use endpoint", variant="primary", size="sm")
1532
- clear_endpoints_btn = gr.Button("Clear added endpoints", size="sm")
1533
- endpoint_save_msg = gr.Markdown()
1534
- session_endpoints_display = gr.HTML(value=_format_session_endpoints())
1535
-
1536
- with gr.Row():
1537
- run_btn = gr.Button("Run review", variant="primary", size="lg", scale=2)
1538
- cancel_btn = gr.Button("Cancel", variant="stop", size="lg", visible=False)
1539
-
1540
- loading_box = gr.HTML(
1541
- '<div class="loading-spinner"><div class="spinner"></div>'
1542
- '<span class="label">Running review pipeline...</span></div>',
1543
- visible=False,
1544
- )
1545
- status_msg = gr.Markdown(visible=False)
1546
-
1547
- with gr.Column(visible=False) as results_panel:
1548
- run_summary_display = gr.HTML()
1549
- verdict_display = gr.HTML()
1550
- count_display = gr.HTML()
1551
- findings_display = gr.HTML()
1552
- ragas_display = gr.HTML()
1553
-
1554
- with gr.Row():
1555
- approve_btn = gr.Button("Approve & post", variant="primary")
1556
- reject_btn = gr.Button("Reject", variant="secondary")
1557
-
1558
- resume_msg = gr.Markdown()
1559
-
1560
- # ── Event wiring ──────────────────────────────────────────────
1561
- def on_run_click(*args):
1562
- """Generator that clears old state, runs review, shows results."""
1563
- args = tuple(
1564
- _normalize_endpoint_name(a) if isinstance(a, str) else a
1565
- for a in args
1566
- )
1567
- # Yield initial loading state — must match the 12 outputs of
1568
- # run_btn.click in order (loading_box, cancel_btn, run_btn,
1569
- # status_msg, 5 result displays, pr_state, results_panel,
1570
- # ragas_task_state).
1571
- yield [
1572
- gr.update(visible=True),
1573
- gr.update(visible=True, variant="stop"),
1574
- gr.update(visible=False),
1575
- gr.update(visible=False, value=""),
1576
- gr.update(value=""),
1577
- *[None, None, None, None],
1578
- None,
1579
- gr.update(visible=False),
1580
- gr.update(value=""),
1581
- ]
1582
-
1583
- for result, err in run_review(*args):
1584
- if err:
1585
- yield [
1586
- gr.update(visible=False),
1587
- gr.update(visible=False),
1588
- gr.update(visible=True),
1589
- gr.update(visible=True, value=err),
1590
- gr.update(value=""),
1591
- *[None, None, None, None],
1592
- None,
1593
- gr.update(visible=False),
1594
- gr.update(value=""),
1595
- ]
1596
- else:
1597
- run_summary_html, verdict_html, findings_html, count_html, ragas_html, config_json, ragas_task_id = result
1598
- yield [
1599
- gr.update(visible=False),
1600
- gr.update(visible=False),
1601
- gr.update(visible=True),
1602
- gr.update(visible=False),
1603
- gr.update(value=run_summary_html),
1604
- gr.update(value=verdict_html),
1605
- gr.update(value=count_html),
1606
- gr.update(value=findings_html),
1607
- gr.update(value=ragas_html),
1608
- config_json,
1609
- gr.update(visible=True),
1610
- gr.update(value=ragas_task_id),
1611
- ]
1612
-
1613
- run_event = run_btn.click(
1614
- fn=on_run_click,
1615
- inputs=[repo_input, pr_input, endpoint_input],
1616
- outputs=[
1617
- loading_box,
1618
- cancel_btn,
1619
- run_btn,
1620
- status_msg,
1621
- run_summary_display,
1622
- verdict_display,
1623
- count_display,
1624
- findings_display,
1625
- ragas_display,
1626
- pr_state,
1627
- results_panel,
1628
- ragas_task_state,
1629
- ],
1630
- )
1631
- cancel_btn.click(fn=None, cancels=[run_event])
1632
-
1633
- def on_approve(config_json):
1634
- msg = resume_review(config_json, "approve")
1635
- return gr.update(value=msg)
1636
-
1637
- def on_reject(config_json):
1638
- msg = resume_review(config_json, "reject")
1639
- return gr.update(value=msg)
1640
-
1641
- approve_btn.click(
1642
- fn=on_approve,
1643
- inputs=[pr_state],
1644
- outputs=[resume_msg],
1645
- )
1646
- reject_btn.click(
1647
- fn=on_reject,
1648
- inputs=[pr_state],
1649
- outputs=[resume_msg],
1650
- )
1651
-
1652
- # ── Background RAGAS polling ────────────────────────────────────
1653
- # RAGAS scoring runs on a background thread so the review results
1654
- # render immediately; this Timer polls for the finished scores and
1655
- # swaps the "computing…" placeholder for the metric card.
1656
- ragas_timer = gr.Timer(5, active=True)
1657
-
1658
- def on_ragas_tick(task_id):
1659
- """Render background RAGAS scores when the task finishes."""
1660
- if not task_id:
1661
- return gr.update(), gr.update()
1662
- with _ragas_lock:
1663
- entry = _ragas_tasks.get(task_id)
1664
- if entry is None:
1665
- return gr.update(), gr.update()
1666
- if not entry.get("done"):
1667
- # Stalled guard: give up after the timeout instead of
1668
- # leaving the "computing…" placeholder forever.
1669
- started = entry.get("started") or 0
1670
- if time.time() - started > RAGAS_TIMEOUT_SECONDS:
1671
- with _ragas_lock:
1672
- _ragas_tasks.pop(task_id, None)
1673
- return gr.update(value=RAGAS_FAILED_HTML), gr.update(value="")
1674
- return gr.update(), gr.update()
1675
- scores = entry.get("scores") or {}
1676
- with _ragas_lock:
1677
- _ragas_tasks.pop(task_id, None)
1678
- if scores:
1679
- html_out = _format_ragas_scores(scores)
1680
- else:
1681
- html_out = RAGAS_FAILED_HTML
1682
- return gr.update(value=html_out), gr.update(value="")
1683
-
1684
- ragas_timer.tick(
1685
- fn=on_ragas_tick,
1686
- inputs=[ragas_task_state],
1687
- outputs=[ragas_display, ragas_task_state],
1688
- )
1689
-
1690
- # ── Add / clear custom endpoints ─────────────────────────────
1691
- def on_add_endpoint(name, ptype, base_url, api_key, model):
1692
- """Register the form values, refresh the dropdown, auto-select."""
1693
- try:
1694
- cfg = register_endpoint(name, ptype, api_key, base_url, model)
1695
- choices = dropdown_choices()
1696
- return (
1697
- gr.update(choices=choices, value=cfg.name),
1698
- f"✅ Saved **{cfg.name}** ({cfg.provider} / `{cfg.model}`) — "
1699
- "it's selected above. Hit **▶ Run Review** to use it. "
1700
- "Tip: use 🔌 Test endpoint connectivity (health tab) to check the key first.",
1701
- _format_session_endpoints(),
1702
- gr.update(value=""),
1703
- gr.update(value=""),
1704
- gr.update(value=""),
1705
- gr.update(value=""),
1706
- )
1707
- except ValueError as exc:
1708
- return (
1709
- gr.update(),
1710
- f"❌ {exc}",
1711
- gr.update(),
1712
- gr.update(),
1713
- gr.update(),
1714
- gr.update(),
1715
- gr.update(),
1716
- )
1717
-
1718
- def on_clear_endpoints():
1719
- """Remove all UI-added endpoints and reset the dropdown."""
1720
- clear_session_endpoints()
1721
- return (
1722
- gr.update(choices=[""] + dropdown_choices(), value=AUTO_ENDPOINT_CHOICE),
1723
- "🗑 Cleared — dropdown reset to the built-in default.",
1724
- _format_session_endpoints(),
1725
- )
1726
-
1727
- add_endpoint_btn.click(
1728
- fn=on_add_endpoint,
1729
- inputs=[
1730
- ep_name_input,
1731
- ep_type_input,
1732
- ep_base_url_input,
1733
- ep_api_key_input,
1734
- ep_model_input,
1735
- ],
1736
- outputs=[
1737
- endpoint_input,
1738
- endpoint_save_msg,
1739
- session_endpoints_display,
1740
- ep_name_input,
1741
- ep_base_url_input,
1742
- ep_api_key_input,
1743
- ep_model_input,
1744
- ],
1745
- )
1746
- clear_endpoints_btn.click(
1747
- fn=on_clear_endpoints,
1748
- outputs=[endpoint_input, endpoint_save_msg, session_endpoints_display],
1749
- )
1750
-
1751
- def on_test_form(name, ptype, base_url, api_key, model):
1752
- """Probe the form values WITHOUT saving them to the registry."""
1753
- name = (name or "").strip()
1754
- model = (model or "").strip()
1755
- api_key = (api_key or "").strip()
1756
- base_url = (base_url or "").strip() or None
1757
- if not (name and model and api_key):
1758
- return (
1759
- "❌ Fill in **name**, **model** and **API key** first "
1760
- "(use `dummy` for keyless local servers)."
1761
- )
1762
- from endpoints import SUPPORTED_PROVIDERS
1763
-
1764
- if (ptype or "openai").strip().lower() not in SUPPORTED_PROVIDERS:
1765
- return f"❌ Unsupported type — use one of {SUPPORTED_PROVIDERS}."
1766
- cfg = EndpointConfig(
1767
- name=name,
1768
- provider=ptype,
1769
- api_key=api_key,
1770
- base_url=base_url,
1771
- model=model,
1772
- )
1773
- ok, detail = _probe_endpoint(cfg)
1774
- icon = "✅" if ok else "❌"
1775
- if ok:
1776
- return f"{icon} **{html.escape(name)}** (`{html.escape(model)}`) — {html.escape(detail)}"
1777
- return f"{icon} **{html.escape(name)}** — {html.escape(detail)}"
1778
-
1779
- test_form_btn.click(
1780
- fn=on_test_form,
1781
- inputs=[
1782
- ep_name_input,
1783
- ep_type_input,
1784
- ep_base_url_input,
1785
- ep_api_key_input,
1786
- ep_model_input,
1787
- ],
1788
- outputs=[endpoint_save_msg],
1789
- )
1790
-
1791
- # ── Tab: Smoke test ──────────────────────────────────────────────
1792
- with gr.Tab("Smoke test"):
1793
- gr.Markdown(
1794
- "Run the review pipeline on **synthetic demo data** — no API keys needed."
1795
- )
1796
- with gr.Row():
1797
- smoke_btn = gr.Button("Run smoke test", variant="primary", size="lg", scale=2)
1798
- smoke_cancel_btn = gr.Button("Cancel", variant="stop", size="lg", visible=False)
1799
-
1800
- smoke_loading = gr.HTML(
1801
- '<div class="loading-spinner"><div class="spinner"></div>'
1802
- '<span class="label">Running smoke test...</span></div>',
1803
- visible=False,
1804
- )
1805
-
1806
- with gr.Column(visible=False) as smoke_results:
1807
- smoke_verdict = gr.HTML()
1808
- smoke_findings = gr.HTML()
1809
- with gr.Row():
1810
- smoke_approve = gr.Button("Approve (demo)", variant="primary")
1811
- smoke_reject = gr.Button("Reject (demo)", variant="secondary")
1812
- smoke_resume_msg = gr.Markdown()
1813
-
1814
- smoke_status = gr.Markdown(visible=False)
1815
-
1816
- def on_smoke_click():
1817
- # Show loading state
1818
- yield [
1819
- gr.update(visible=True),
1820
- gr.update(visible=True, variant="stop"),
1821
- gr.update(visible=False),
1822
- gr.update(visible=False),
1823
- None,
1824
- gr.update(value=""),
1825
- gr.update(value=""),
1826
- gr.update(visible=False),
1827
- ]
1828
- for result, err in run_smoke():
1829
- if err:
1830
- yield [
1831
- gr.update(visible=False),
1832
- gr.update(visible=False),
1833
- gr.update(visible=True),
1834
- gr.update(visible=False),
1835
- None,
1836
- gr.update(value=""),
1837
- gr.update(value=""),
1838
- gr.update(visible=True, value=err),
1839
- ]
1840
- else:
1841
- verdict_html, findings_html, config_json, s_verdict, s_findings = result
1842
- yield [
1843
- gr.update(visible=False),
1844
- gr.update(visible=False),
1845
- gr.update(visible=True),
1846
- gr.update(visible=True),
1847
- config_json,
1848
- gr.update(value=s_verdict),
1849
- gr.update(value=s_findings),
1850
- gr.update(visible=False),
1851
- ]
1852
-
1853
- smoke_event = smoke_btn.click(
1854
- fn=on_smoke_click,
1855
- outputs=[smoke_loading, smoke_cancel_btn, smoke_btn, smoke_results, smoke_state,
1856
- smoke_verdict, smoke_findings, smoke_status],
1857
- )
1858
- smoke_cancel_btn.click(fn=None, cancels=[smoke_event])
1859
-
1860
- smoke_approve.click(
1861
- fn=lambda c: resume_review(c, "approve"),
1862
- inputs=[smoke_state],
1863
- outputs=[smoke_resume_msg],
1864
- )
1865
- smoke_reject.click(
1866
- fn=lambda c: resume_review(c, "reject"),
1867
- inputs=[smoke_state],
1868
- outputs=[smoke_resume_msg],
1869
- )
1870
-
1871
- # ── Environment status footer ──────────────────────────────────────
1872
- with gr.Accordion("Configured keys & health", open=False):
1873
- h = HealthStatus()
1874
- health_data = h.summary()
1875
- gemini_ok = bool(os.environ.get("GEMINI_API_KEY", "").strip())
1876
- groq_ok = bool(os.environ.get("GROQ_API_KEY", "").strip())
1877
- gh_ok = bool(os.environ.get("GITHUB_TOKEN", "").strip())
1878
- lines = [
1879
- f"<li>GEMINI_API_KEY: {'✅ Set' if gemini_ok else '❌ Not set'}</li>",
1880
- f"<li>GROQ_API_KEY: {'✅ Set' if groq_ok else '❌ Not set'}</li>",
1881
- f"<li>GITHUB_TOKEN: {'✅ Set' if gh_ok else '❌ Not set'}</li>",
1882
- f"<li>LangSmith: {health_data['LangSmith']}</li>",
1883
- f"<li>Langfuse: {health_data['Langfuse']}</li>",
1884
- ]
1885
- gr.HTML("<ul>" + "".join(lines) + "</ul>")
1886
-
1887
- gr.HTML(
1888
- '<div class="card-title" style="margin:14px 0 8px">⚡ LLM Endpoints</div>'
1889
- )
1890
- if _configured_endpoints:
1891
- endpoint_cards = "".join(
1892
- f'<div class="endpoint-card">'
1893
- f'<div class="endpoint-name">{html.escape(ep.name)}'
1894
- f'<span class="endpoint-badge">{html.escape(ep.provider)}</span>'
1895
- + (
1896
- '<span class="endpoint-badge" style="color:#dc2626;background:#dc262611;border-color:#dc262644">missing key</span>'
1897
- if not ep.api_key else ""
1898
- )
1899
- + '</div>'
1900
- f'<div class="endpoint-meta"><code>{html.escape(ep.model)}</code>'
1901
- f' · {html.escape(ep.base_url or "default URL")} · key {ep.masked_key}</div>'
1902
- f'</div>'
1903
- for ep in _configured_endpoints
1904
- )
1905
- gr.HTML(f'<div>{endpoint_cards}</div>')
1906
- else:
1907
- gr.HTML(
1908
- '<p class="muted small">None configured — set '
1909
- '<code>OCR_ENDPOINT_1_NAME</code> / <code>_TYPE</code> / '
1910
- '<code>_API_KEY</code> / <code>_BASE_URL</code> / <code>_MODEL</code> '
1911
- 'as Space secrets to add one.</p>'
1912
- )
1913
- with gr.Row():
1914
- test_endpoints_btn = gr.Button("Test endpoint connectivity", size="sm", variant="secondary")
1915
- endpoint_test_out = gr.HTML()
1916
- test_endpoints_btn.click(fn=test_endpoints, outputs=[endpoint_test_out])
1917
-
1918
- # ── Footer ─────────────────────────────────────────────────────────
1919
- _commit, _ts = _get_deploy_info()
1920
- gr.HTML(
1921
- f'<p class="footer">'
1922
- f'Built with LangGraph · Groq · ChromaDB · Gradio'
1923
- f'<br><span style="opacity:0.5;font-size:0.85em;color:var(--text-footer)">'
1924
- f'deploy: <code>{_commit}</code> · {_ts}'
1925
- f'</span></p>'
1926
- )
1927
-
1928
-
1929
- def _resolve_port() -> int:
1930
- """Resolve the listen port from $PORT, falling back to 7860.
1931
-
1932
- HF Spaces always sets a valid $PORT, but locally the variable may be
1933
- empty or even 0 (e.g. inherited from an unrelated shell profile) —
1934
- binding port 0 makes Gradio's post-launch self-check fail with a
1935
- confusing connection traceback, so invalid values are rejected here.
1936
- """
1937
- raw = (os.environ.get("PORT") or "").strip()
1938
- try:
1939
- port = int(raw) if raw else 7860
1940
- except ValueError:
1941
- logger.warning("Ignoring non-numeric PORT=%r — using 7860", raw)
1942
- return 7860
1943
- if not 1 <= port <= 65535:
1944
- logger.warning("Ignoring out-of-range PORT=%d — using 7860", port)
1945
- return 7860
1946
- return port
1947
-
1948
-
1949
- def main() -> None:
1950
- port = _resolve_port()
1951
- # Gradio 6: theme/css moved from the Blocks constructor to launch().
1952
- demo.queue(max_size=10).launch(
1953
- server_name="0.0.0.0",
1954
- server_port=port,
1955
- share=False,
1956
- theme=gr.themes.Soft(),
1957
- css=CSS,
1958
- )
1959
-
1960
 
1961
  if __name__ == "__main__":
1962
- main()
 
 
 
1
+ """Backward-compatible import path and launcher for the Gradio UI."""
2
+ import sys as _sys
3
+ from backend import app as _implementation
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
  if __name__ == "__main__":
6
+ _implementation.main()
7
+ else:
8
+ _sys.modules[__name__] = _implementation
auth.py CHANGED
@@ -1,353 +1,5 @@
1
- #!/usr/bin/env python3
2
- """GitHub OAuth Device Flow authentication for OpenCodeReview.
 
3
 
4
- Usage
5
- -----
6
- export GITHUB_OAUTH_CLIENT_ID="Iv23li..."
7
- opencodereview auth login
8
- opencodereview auth status
9
- opencodereview auth logout
10
-
11
- The Device Flow is used instead of the Authorization Code flow because
12
- there is no web server to handle a redirect URI.
13
- """
14
-
15
- from __future__ import annotations
16
-
17
- import logging
18
- import os
19
- import sys
20
- import time
21
- from typing import Optional
22
-
23
- import click
24
- import keyring
25
- import requests
26
-
27
- logger = logging.getLogger(__name__)
28
-
29
- # ─── Constants ───────────────────────────────────────────────────────────────
30
-
31
- SERVICE_NAME = "opencodereview"
32
- GH_DEVICE_CODE_URL = "https://github.com/login/device/code"
33
- GH_ACCESS_TOKEN_URL = "https://github.com/login/oauth/access_token"
34
- GH_API_BASE = "https://api.github.com"
35
- DEFAULT_SCOPE = "repo" # Full control of private repositories — needed for
36
- # reading PRs and posting review comments on
37
- # private repos.
38
- POLL_SAFETY_MARGIN = 1 # Extra seconds to wait beyond the server's interval
39
-
40
-
41
- # ─── Exceptions ─────────────────────────────────────────────────────────────
42
-
43
-
44
- class AuthError(Exception):
45
- """Base exception for auth operations."""
46
-
47
-
48
- class DeviceFlowExpired(AuthError):
49
- """The device code expired before the user approved."""
50
-
51
-
52
- class DeviceFlowDenied(AuthError):
53
- """The user denied the authorization request."""
54
-
55
-
56
- # ─── Auth Service ────────────────────────────────────────────────────────────
57
-
58
-
59
- def _resolve_client_id(client_id: Optional[str] = None) -> str:
60
- """Return the GitHub OAuth client ID from the argument or environment."""
61
- cid = client_id or os.environ.get("GITHUB_OAUTH_CLIENT_ID")
62
- if not cid:
63
- raise AuthError(
64
- "GitHub OAuth client ID is required.\n\n"
65
- " 1. Register a new OAuth App at:\n"
66
- " https://github.com/settings/developers\n\n"
67
- " 2. Enable Device Flow in the app settings.\n\n"
68
- " 3. Set the client ID:\n"
69
- f" export GITHUB_OAUTH_CLIENT_ID=\"<your_client_id>\"\n"
70
- " Or pass --client-id to the login command.",
71
- )
72
- return cid
73
-
74
-
75
- class AuthService:
76
- """Manage GitHub OAuth tokens via the Device Flow."""
77
-
78
- def __init__(self, client_id: Optional[str] = None) -> None:
79
- self._client_id = client_id or os.environ.get("GITHUB_OAUTH_CLIENT_ID")
80
- self._session = requests.Session()
81
- self._session.headers.update({
82
- "Accept": "application/json",
83
- "User-Agent": "opencodereview/1.0",
84
- })
85
-
86
- # ── Device Flow Login ──────────────────────────────────────────────────
87
-
88
- def login(self) -> str:
89
- """Run the GitHub Device Flow and return the access token.
90
-
91
- Steps
92
- -----
93
- 1. POST to ``/login/device/code`` to get a device + user code.
94
- 2. Print the user code + verification URL for the user.
95
- 3. Poll ``/login/oauth/access_token`` until the user approves.
96
- 4. Validate that the granted scopes include what was requested.
97
- 5. Save the token to the system keyring.
98
- 6. Return the access token.
99
- """
100
- # Validate client_id before making any API calls
101
- self._client_id = _resolve_client_id(self._client_id)
102
-
103
- device_code, user_code, verification_uri, interval, expires_in = (
104
- self._request_device_code()
105
- )
106
-
107
- self._print_login_instructions(user_code, verification_uri, expires_in)
108
-
109
- access_token, granted_scope = self._poll_for_token(device_code, interval)
110
-
111
- # Validate that the granted scopes include what we asked for
112
- self._validate_scopes(granted_scope)
113
-
114
- # Save to keyring
115
- keyring.set_password(SERVICE_NAME, "github_token", access_token)
116
- logger.info("Token saved to system credential store (keyring).")
117
-
118
- # Fetch and display user info
119
- user = self._get_user(access_token)
120
- click.echo(f" Logged in as: {user['login']}")
121
-
122
- return access_token
123
-
124
- def _request_device_code(
125
- self,
126
- ) -> tuple[str, str, str, int, int]:
127
- """POST to the device-code endpoint and return the response fields."""
128
- resp = self._session.post(
129
- GH_DEVICE_CODE_URL,
130
- data={
131
- "client_id": self._client_id,
132
- "scope": DEFAULT_SCOPE,
133
- },
134
- )
135
- resp.raise_for_status()
136
- data = resp.json()
137
-
138
- if "error" in data:
139
- raise AuthError(
140
- f"Device code request failed: {data.get('error_description', data['error'])}"
141
- )
142
-
143
- return (
144
- data["device_code"],
145
- data["user_code"],
146
- data["verification_uri"],
147
- data.get("interval", 5),
148
- data.get("expires_in", 900),
149
- )
150
-
151
- @staticmethod
152
- def _print_login_instructions(
153
- user_code: str, verification_uri: str, expires_in: int,
154
- ) -> None:
155
- """Print the user code and instructions to the terminal."""
156
- click.echo()
157
- click.echo("=" * 60)
158
- click.echo(" GitHub Device Authentication")
159
- click.echo("=" * 60)
160
- click.echo()
161
- click.echo(f" 1. Open this URL in your browser:")
162
- click.echo(f" {verification_uri}")
163
- click.echo()
164
- click.echo(f" 2. Enter the following code:")
165
- click.echo(f" {user_code}")
166
- click.echo()
167
- click.echo(f" 3. Authorize the OpenCodeReview application.")
168
- click.echo()
169
- click.echo(f" This code expires in {expires_in // 60} minute(s).")
170
- click.echo(f" Waiting for you to approve...")
171
- click.echo()
172
-
173
- def _poll_for_token(self, device_code: str, interval: int) -> tuple[str, str]:
174
- """Poll the access-token endpoint until the user approves or the code expires.
175
-
176
- Returns ``(access_token, granted_scope)`` where ``granted_scope`` is the
177
- space-separated scope string returned by GitHub (may be empty if the
178
- response omitted it).
179
- """
180
- poll_interval = interval
181
- start_time = time.monotonic()
182
-
183
- while True:
184
- time.sleep(poll_interval + POLL_SAFETY_MARGIN)
185
-
186
- resp = self._session.post(
187
- GH_ACCESS_TOKEN_URL,
188
- data={
189
- "client_id": self._client_id,
190
- "device_code": device_code,
191
- "grant_type": "urn:ietf:params:oauth:grant-type:device_code",
192
- },
193
- )
194
- resp.raise_for_status()
195
- data = resp.json()
196
-
197
- if "access_token" in data:
198
- return data["access_token"], data.get("scope", "")
199
-
200
- error = data.get("error", "")
201
-
202
- if error == "authorization_pending":
203
- # User hasn't acted yet — keep polling
204
- continue
205
- elif error == "slow_down":
206
- # Polling too fast — increase interval by 5 seconds
207
- poll_interval += 5
208
- logger.debug("Polling rate limited — increasing interval to %ds", poll_interval)
209
- continue
210
- elif error == "expired_token":
211
- raise DeviceFlowExpired(
212
- "The device code has expired. Run 'opencodereview auth login' again."
213
- )
214
- elif error == "access_denied":
215
- raise DeviceFlowDenied("The authorization request was denied.")
216
- else:
217
- raise AuthError(
218
- f"Unexpected polling response: {data.get('error_description', error)}"
219
- )
220
-
221
- # ── Status ──────────────────────────────────────────────────────────────
222
-
223
- def status(self) -> Optional[dict]:
224
- """Check whether a valid token is stored and return the authenticated user.
225
-
226
- Returns ``None`` if no token is stored.
227
- Raises ``AuthError`` if the token is invalid or expired.
228
- """
229
- token = keyring.get_password(SERVICE_NAME, "github_token")
230
- if not token:
231
- return None
232
-
233
- user = self._get_user(token)
234
- return user
235
-
236
- # ── Logout ──────────────────────────────────────────────────────────────
237
-
238
- def logout(self) -> bool:
239
- """Delete the stored token from the keyring.
240
-
241
- Returns ``True`` if a token was deleted, ``False`` if none existed.
242
- """
243
- existing = keyring.get_password(SERVICE_NAME, "github_token")
244
- if existing:
245
- try:
246
- keyring.delete_password(SERVICE_NAME, "github_token")
247
- except keyring.errors.PasswordDeleteError:
248
- logger.warning("Failed to delete token from keyring (back-end error).")
249
- return False
250
- return True
251
- return False
252
-
253
- # ── Helpers ─────────────────────────────────────────────────────────────
254
-
255
- def _validate_scopes(self, granted_scope_str: str) -> None:
256
- """Compare the scopes GitHub actually granted against what was requested.
257
-
258
- The ``scope`` field in the access-token response is a space-separated
259
- string. If the user denied some scopes, we warn them on stderr so
260
- they know certain features may not work.
261
- """
262
- if not granted_scope_str.strip():
263
- # Older GitHub Enterprise or unusual config — skip validation
264
- return
265
-
266
- requested = set(DEFAULT_SCOPE.split(","))
267
- granted = set(granted_scope_str.strip().split())
268
- missing = requested - granted
269
-
270
- if missing:
271
- click.echo(
272
- "\n"
273
- "Warning: Some requested permissions were not granted.\n"
274
- f" Missing scopes: {', '.join(sorted(missing))}\n"
275
- f" Granted scopes: {', '.join(sorted(granted))}\n"
276
- "\n"
277
- " Features that need these scopes may not work correctly.\n"
278
- " Re-run 'opencodereview auth login' and ensure you\n"
279
- " authorize all requested permissions.\n",
280
- err=True,
281
- )
282
-
283
- def _get_user(self, token: str) -> dict:
284
- """Fetch the authenticated GitHub user via the API."""
285
- resp = self._session.get(
286
- f"{GH_API_BASE}/user",
287
- headers={"Authorization": f"token {token}"},
288
- )
289
- if resp.status_code == 401:
290
- raise AuthError(
291
- "The stored token is invalid or has been revoked.\n"
292
- "Run 'opencodereview auth login' to re-authenticate."
293
- )
294
- resp.raise_for_status()
295
- return resp.json()
296
-
297
-
298
- # ─── CLI ─────────────────────────────────────────────────────────────────────
299
-
300
-
301
- @click.group()
302
- def auth() -> None:
303
- """Authenticate with GitHub via the OAuth Device Flow."""
304
-
305
-
306
- @auth.command()
307
- @click.option(
308
- "--client-id",
309
- envvar="GITHUB_OAUTH_CLIENT_ID",
310
- default=None,
311
- help="GitHub OAuth App client ID (or set GITHUB_OAUTH_CLIENT_ID).",
312
- )
313
- def login(client_id: Optional[str]) -> None:
314
- """Authenticate with GitHub and store the token securely."""
315
- try:
316
- svc = AuthService(client_id=client_id)
317
- svc.login()
318
- except (AuthError, requests.RequestException) as exc:
319
- click.echo(f"Error: {exc}", err=True)
320
- sys.exit(1)
321
-
322
-
323
- @auth.command()
324
- def logout() -> None:
325
- """Remove the stored GitHub token."""
326
- svc = AuthService()
327
- if svc.logout():
328
- click.echo("Token removed from credential store.")
329
- else:
330
- click.echo("No token found. Nothing to remove.")
331
-
332
-
333
- @auth.command()
334
- def status() -> None:
335
- """Show whether a valid token is stored and which user it belongs to."""
336
- svc = AuthService()
337
- try:
338
- user = svc.status()
339
- except AuthError as exc:
340
- click.echo(f"Token status: invalid ({exc})", err=True)
341
- sys.exit(1)
342
- except requests.RequestException as exc:
343
- click.echo(f"Error checking token: {exc}", err=True)
344
- sys.exit(1)
345
-
346
- if user is None:
347
- click.echo("No token stored. Run 'opencodereview auth login'.", err=True)
348
- sys.exit(1)
349
- else:
350
- click.echo(f"Authenticated as: {user['login']}")
351
- click.echo(f"Token: valid")
352
- if user.get("name"):
353
- click.echo(f"Name: {user['name']}")
 
1
+ """Backward-compatible import path for GitHub authentication helpers."""
2
+ import sys as _sys
3
+ from backend.integrations import auth as _implementation
4
 
5
+ _sys.modules[__name__] = _implementation
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
backend/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """OpenCodeReview backend application package."""
backend/api.py ADDED
@@ -0,0 +1,647 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 secrets
15
+ import sqlite3
16
+ import threading
17
+ import uuid
18
+ import requests
19
+ from concurrent.futures import ThreadPoolExecutor
20
+ from datetime import datetime, timezone
21
+ from typing import Any, Literal
22
+
23
+ from fastapi import FastAPI, Header, HTTPException, Request
24
+ from fastapi.responses import RedirectResponse
25
+ from fastapi.middleware.cors import CORSMiddleware
26
+ from langgraph.types import Command
27
+ from pydantic import BaseModel, Field
28
+
29
+ from backend.app import DB_PATH, _build_and_stream, _normalize_endpoint_name, _ragas_tasks, _ragas_lock, _spawn_ragas_background
30
+ from backend.graph import build_graph
31
+ from backend.observability import TokenCostCallback, flush_langfuse, get_langfuse_handler
32
+ from backend.state import Finding, Verdict
33
+ from backend.integrations.endpoints import register_endpoint, unregister_endpoint
34
+
35
+ app = FastAPI(title="OpenCodeReview API", version="0.1.0")
36
+ allowed_origins = [item.strip() for item in os.getenv("OCR_ALLOWED_ORIGINS", "http://localhost:5173").split(",") if item.strip()]
37
+ app.add_middleware(CORSMiddleware, allow_origins=allowed_origins, allow_methods=["GET", "POST"], allow_headers=["*"], allow_credentials=True)
38
+
39
+ _jobs: dict[str, dict[str, Any]] = {}
40
+ _lock = threading.Lock()
41
+ _executor = ThreadPoolExecutor(max_workers=int(os.getenv("OCR_MAX_WORKERS", "2")))
42
+ _rate_lock = threading.Lock()
43
+ _rate_windows: dict[str, list[float]] = {}
44
+ _oauth_states: set[str] = set()
45
+ _sessions: dict[str, dict[str, Any]] = {}
46
+
47
+ def _rate_limit(request: Request) -> None:
48
+ limit = int(os.getenv("OCR_RATE_LIMIT_PER_MINUTE", "0") or 0)
49
+ if limit <= 0:
50
+ return
51
+ now = datetime.now(timezone.utc).timestamp()
52
+ forwarded = request.headers.get("x-forwarded-for") or request.headers.get("x-real-ip")
53
+ key = (forwarded.split(",", 1)[0].strip() if forwarded else None) or "global"
54
+ with _rate_lock:
55
+ window = [stamp for stamp in _rate_windows.get(key, []) if now - stamp < 60]
56
+ if len(window) >= limit:
57
+ raise HTTPException(status_code=429, detail="Rate limit exceeded")
58
+ window.append(now)
59
+ _rate_windows[key] = window
60
+
61
+
62
+ def _postgres_connect():
63
+ """Return a Supabase Postgres connection when configured, else None."""
64
+ url = os.getenv("SUPABASE_DB_URL", "").strip()
65
+ if not url:
66
+ return None
67
+ try:
68
+ import psycopg
69
+ return psycopg.connect(url)
70
+ except Exception:
71
+ return None
72
+
73
+ def _init_jobs() -> None:
74
+ pg = _postgres_connect()
75
+ if pg is not None:
76
+ with pg:
77
+ with pg.cursor() as cur:
78
+ cur.execute("""create table if not exists public.review_jobs (
79
+ id uuid primary key, repo text not null, pr_number integer not null,
80
+ endpoint text, status text not null, payload jsonb not null,
81
+ created_at timestamptz not null default now(), updated_at timestamptz not null default now())""")
82
+ cur.execute("create index if not exists review_jobs_status_idx on public.review_jobs (status)")
83
+ pg.close()
84
+ return
85
+ with sqlite3.connect(DB_PATH) as conn:
86
+ conn.execute("CREATE TABLE IF NOT EXISTS review_jobs (id TEXT PRIMARY KEY, payload TEXT NOT NULL)")
87
+ conn.commit()
88
+
89
+ _init_jobs()
90
+
91
+ def _save_job(job: dict[str, Any]) -> None:
92
+ payload = {k: v for k, v in job.items() if k not in {"future", "ragas_inputs"}}
93
+ if "config" in payload:
94
+ payload["config"] = {"configurable": payload["config"].get("configurable", {})}
95
+ pg = _postgres_connect()
96
+ if pg is not None:
97
+ with pg:
98
+ with pg.cursor() as cur:
99
+ cur.execute("""insert into public.review_jobs (id, repo, pr_number, endpoint, status, payload, updated_at)
100
+ values (%s, %s, %s, %s, %s, %s::jsonb, now())
101
+ on conflict (id) do update set repo=excluded.repo, pr_number=excluded.pr_number,
102
+ endpoint=excluded.endpoint, status=excluded.status, payload=excluded.payload, updated_at=now()""",
103
+ (job["id"], job["repo"], job["pr_number"], job.get("endpoint"), job["status"], json.dumps(payload, default=str)))
104
+ pg.close()
105
+ return
106
+ with sqlite3.connect(DB_PATH) as conn:
107
+ conn.execute("INSERT OR REPLACE INTO review_jobs (id, payload) VALUES (?, ?)", (job["id"], json.dumps(payload, default=str)))
108
+ conn.commit()
109
+
110
+ def _load_job(job_id: str) -> dict[str, Any] | None:
111
+ pg = _postgres_connect()
112
+ if pg is not None:
113
+ with pg.cursor() as cur:
114
+ cur.execute("select payload from public.review_jobs where id = %s", (job_id,))
115
+ row = cur.fetchone()
116
+ pg.close()
117
+ if not row:
118
+ return None
119
+ return json.loads(row[0]) if isinstance(row[0], str) else row[0]
120
+ with sqlite3.connect(DB_PATH) as conn:
121
+ row = conn.execute("SELECT payload FROM review_jobs WHERE id = ?", (job_id,)).fetchone()
122
+ return json.loads(row[0]) if row else None
123
+
124
+ def _load_jobs() -> list[dict[str, Any]]:
125
+ pg = _postgres_connect()
126
+ if pg is not None:
127
+ with pg.cursor() as cur:
128
+ cur.execute("select payload from public.review_jobs")
129
+ rows = cur.fetchall()
130
+ pg.close()
131
+ return [json.loads(row[0]) if isinstance(row[0], str) else row[0] for row in rows]
132
+ with sqlite3.connect(DB_PATH) as conn:
133
+ rows = conn.execute("SELECT payload FROM review_jobs").fetchall()
134
+ return [json.loads(row[0]) if isinstance(row[0], str) else row[0] for row in rows]
135
+
136
+
137
+ class ReviewRequest(BaseModel):
138
+ repo: str = Field(pattern=r"^[\w.-]+/[\w.-]+$")
139
+ pr_number: int = Field(gt=0)
140
+ endpoint: str | None = None
141
+ provider: str | None = Field(default=None, pattern=r"^(openai|anthropic|google)$")
142
+ model: str | None = None
143
+ api_key: str | None = None
144
+ base_url: str | None = None
145
+ review_mode: Literal["fast", "thorough"] = "thorough"
146
+ baseline_sha: str | None = Field(default=None, pattern=r"^[0-9a-fA-F]{40}$")
147
+
148
+
149
+ class DecisionRequest(BaseModel):
150
+ action: Literal["approve", "reject"]
151
+
152
+
153
+ class FindingFeedbackRequest(BaseModel):
154
+ finding_index: int = Field(ge=0)
155
+ label: Literal['correct', 'incorrect', 'useful']
156
+
157
+
158
+ def _authorize(token: str | None) -> None:
159
+ expected = os.getenv("OCR_API_KEY", "").strip()
160
+ # Authentication is opt-in for local development, but deployments can
161
+ # require it explicitly. Never silently treat a missing production key
162
+ # as authenticated.
163
+ require_auth = os.getenv("OCR_REQUIRE_AUTH", "false").strip().lower() in {"1", "true", "yes", "on"}
164
+ if require_auth and not expected:
165
+ raise HTTPException(status_code=503, detail="API authentication is not configured")
166
+ if expected and (not token or not secrets.compare_digest(token, expected)):
167
+ raise HTTPException(status_code=401, detail="Invalid API key")
168
+
169
+ def _authorize_request(token: str | None, request: Request) -> None:
170
+ if _session(request):
171
+ return
172
+ _authorize(token)
173
+
174
+ def _session(request: Request) -> dict[str, Any] | None:
175
+ sid = request.cookies.get("ocr_session")
176
+ return _sessions.get(sid) if sid else None
177
+
178
+ @app.get("/api/auth/github/start")
179
+ def github_login() -> RedirectResponse:
180
+ client_id = os.getenv("GITHUB_OAUTH_CLIENT_ID", "").strip()
181
+ if not client_id:
182
+ raise HTTPException(status_code=503, detail="GitHub OAuth is not configured")
183
+ state = secrets.token_urlsafe(32)
184
+ _oauth_states.add(state)
185
+ callback = os.getenv("GITHUB_OAUTH_CALLBACK_URL", "").strip() or "http://localhost:8000/api/auth/github/callback"
186
+ 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})
187
+ return RedirectResponse(url)
188
+
189
+ @app.get("/api/auth/github/callback")
190
+ def github_callback(code: str, state: str, response: Request) -> RedirectResponse:
191
+ if state not in _oauth_states:
192
+ raise HTTPException(status_code=400, detail="Invalid OAuth state")
193
+ _oauth_states.discard(state)
194
+ client_id = os.getenv("GITHUB_OAUTH_CLIENT_ID", "").strip()
195
+ client_secret = os.getenv("GITHUB_OAUTH_CLIENT_SECRET", "").strip()
196
+ callback = os.getenv("GITHUB_OAUTH_CALLBACK_URL", "").strip() or "http://localhost:8000/api/auth/github/callback"
197
+ 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)
198
+ token_resp.raise_for_status()
199
+ access_token = token_resp.json().get("access_token")
200
+ if not access_token:
201
+ raise HTTPException(status_code=502, detail="GitHub did not return an access token")
202
+ user_resp = requests.get("https://api.github.com/user", headers={"Authorization": f"Bearer {access_token}", "Accept": "application/vnd.github+json"}, timeout=20)
203
+ user_resp.raise_for_status()
204
+ user = user_resp.json()
205
+ sid = secrets.token_urlsafe(32)
206
+ _sessions[sid] = {"token": access_token, "github_id": user.get("id"), "login": user.get("login")}
207
+ frontend = os.getenv("OCR_FRONTEND_URL", allowed_origins[0] if allowed_origins else "http://localhost:5173")
208
+ out = RedirectResponse(frontend)
209
+ out.set_cookie("ocr_session", sid, httponly=True, secure=frontend.startswith("https://"), samesite="lax", max_age=86400)
210
+ return out
211
+
212
+ @app.get("/api/auth/me")
213
+ def github_me(request: Request) -> dict[str, Any]:
214
+ session = _session(request)
215
+ if not session:
216
+ raise HTTPException(status_code=401, detail="Not authenticated")
217
+ return {"github_id": session["github_id"], "login": session["login"]}
218
+
219
+ @app.post("/api/auth/logout")
220
+ def github_logout(request: Request) -> dict[str, str]:
221
+ sid = request.cookies.get("ocr_session")
222
+ if sid:
223
+ _sessions.pop(sid, None)
224
+ return {"status": "logged_out"}
225
+
226
+
227
+ def _public_job(job: dict[str, Any]) -> dict[str, Any]:
228
+ result = {key: value for key, value in job.items() if key not in {"config", "future", "request_fingerprint", "owner_id", "ragas_inputs"}}
229
+ now = time.time()
230
+ 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)
231
+ if job.get("status") == "queued":
232
+ result["queue_position"] = sum(1 for item in _jobs.values() if item.get("status") == "queued" and item.get("created_at", "") <= job.get("created_at", ""))
233
+ return result
234
+
235
+ def _with_ragas(job: dict[str, Any]) -> dict[str, Any]:
236
+ result = _public_job(job)
237
+ task_id = result.get("ragas_task_id")
238
+ with _ragas_lock:
239
+ task = _ragas_tasks.get(task_id) if task_id else None
240
+ def finish():
241
+ metrics = (task or {}).get('metrics') or job.get('ragas_metrics') or {}
242
+ evaluation = (task or {}).get('evaluation') or job.get('ragas_evaluation') or {}
243
+ result.setdefault('ragas', {}).update(metrics=metrics, evaluation=evaluation)
244
+ if metrics and result['ragas'].get('scores') and any(m.get('status') != 'completed' for m in metrics.values()):
245
+ result['ragas']['status'] = 'partial'
246
+ if metrics != job.get('ragas_metrics', {}) or evaluation != job.get('ragas_evaluation', {}):
247
+ with _lock:
248
+ live = _jobs.get(job.get('id'))
249
+ if live is not None:
250
+ live.update(ragas_metrics=metrics, ragas_evaluation=evaluation)
251
+ _save_job(live)
252
+ return result
253
+ if not task_id:
254
+ result["ragas"] = {
255
+ "status": "skipped",
256
+ "scores": result.get("ragas_scores") or {},
257
+ "reason": "Review incomplete; scoring was not started" if result.get("status") == "incomplete" else "No retrieval context was available for RAGAS evaluation",
258
+ }
259
+ else:
260
+ if job.get("ragas_status") in {"failed", "unavailable", "completed_no_scores"}:
261
+ result["ragas"] = {
262
+ "status": job["ragas_status"],
263
+ "scores": job.get("ragas_scores") or {},
264
+ "error": job.get("ragas_error"),
265
+ }
266
+ return finish()
267
+ with _ragas_lock:
268
+ task = _ragas_tasks.get(task_id)
269
+ if not task:
270
+ # Task registries are process-local. A restart invalidates an
271
+ # in-flight task instead of making the client poll forever.
272
+ if result.get("ragas_scores"):
273
+ result["ragas"] = {"status": "completed", "scores": result["ragas_scores"]}
274
+ else:
275
+ result["ragas"] = {"status": "unavailable", "error": "RAGAS task was lost during process restart"}
276
+ with _lock:
277
+ live = _jobs.get(job.get("id"))
278
+ if live is not None:
279
+ live["ragas_status"] = "unavailable"
280
+ live["ragas_error"] = result["ragas"]["error"]
281
+ _save_job(live)
282
+ elif not task.get("done"):
283
+ timeout = float(task.get("timeout_seconds") or os.getenv("OCR_RAGAS_TIMEOUT_SECONDS", "90"))
284
+ started = float(task.get("started", 0) or 0)
285
+ if started and datetime.now(timezone.utc).timestamp() - started > timeout:
286
+ result["ragas"] = {"status": "failed", "error": f"RAGAS exceeded {int(timeout)} second timeout"}
287
+ with _lock:
288
+ live = _jobs.get(job.get("id"))
289
+ if live is not None:
290
+ live["ragas_status"] = "failed"
291
+ live["ragas_error"] = result["ragas"]["error"]
292
+ _save_job(live)
293
+ else:
294
+ result["ragas"] = {"status": "pending"}
295
+ elif task.get("error"):
296
+ result["ragas"] = {"status": "failed", "error": task.get("error")}
297
+ with _lock:
298
+ live = _jobs.get(job.get("id"))
299
+ if live is not None:
300
+ live["ragas_status"] = "failed"
301
+ live["ragas_error"] = task.get("error")
302
+ _save_job(live)
303
+ else:
304
+ scores = task.get("scores") or {}
305
+ if scores:
306
+ result["ragas"] = {"status": "completed", "scores": scores}
307
+ if not job.get("ragas_scores"):
308
+ with _lock:
309
+ live = _jobs.get(job.get("id"))
310
+ if live is not None:
311
+ live["ragas_scores"] = scores
312
+ live["ragas_status"] = "completed"
313
+ _save_job(live)
314
+ else:
315
+ result["ragas"] = {"status": "completed_no_scores", "scores": {}, "error": "RAGAS completed without metric values"}
316
+ with _lock:
317
+ live = _jobs.get(job.get("id"))
318
+ if live is not None:
319
+ live["ragas_status"] = "completed_no_scores"
320
+ live["ragas_error"] = result["ragas"]["error"]
321
+ _save_job(live)
322
+ return finish()
323
+
324
+
325
+ def _run_job(job_id: str, request: ReviewRequest) -> None:
326
+ with _lock:
327
+ if _jobs.get(job_id, {}).get("status") == "cancelled":
328
+ return
329
+ if job_id in _jobs:
330
+ _jobs[job_id].update(status="processing", started_timestamp=time.time(), progress={"stage": "ingestion", "completed_stages": []})
331
+ _save_job(_jobs[job_id])
332
+ try:
333
+ ephemeral_endpoint = None
334
+ ragas_started = False
335
+ endpoint_name = _normalize_endpoint_name(request.endpoint)
336
+ if request.api_key:
337
+ if not request.provider or not request.model:
338
+ raise ValueError("provider and model are required when supplying a user API key")
339
+ ephemeral_endpoint = f"user-{job_id}"
340
+ register_endpoint(ephemeral_endpoint, request.provider, request.api_key, request.base_url, request.model)
341
+ endpoint_name = ephemeral_endpoint
342
+ def save_ragas(scores: dict, error: str | None) -> None:
343
+ try:
344
+ with _lock:
345
+ live = _jobs.get(job_id)
346
+ if live is None:
347
+ return
348
+ live["ragas_scores"] = scores or None
349
+ live["ragas_status"] = "failed" if error else ("completed" if scores else "completed_no_scores")
350
+ live["ragas_error"] = error
351
+ _save_job(live)
352
+ finally:
353
+ # Custom providers are registered only for this job. Keep the
354
+ # endpoint alive until the background RAGAS task has finished;
355
+ # otherwise evaluation silently falls back to built-ins.
356
+ if ephemeral_endpoint:
357
+ unregister_endpoint(ephemeral_endpoint)
358
+
359
+ def progress(stage: str, elapsed: float, update: dict | None = None) -> None:
360
+ with _lock:
361
+ live = _jobs[job_id]
362
+ if live.get("status") == "cancelled":
363
+ raise RuntimeError("Review cancelled")
364
+ completed = live.setdefault("progress", {}).setdefault("completed_stages", [])
365
+ if stage not in completed:
366
+ completed.append(stage)
367
+ live["progress"]["stage"] = stage
368
+ live.setdefault("stage_timings", {})[stage] = round(elapsed, 2)
369
+ if isinstance(update, dict):
370
+ stages = update.get("review_stages", [])
371
+ if isinstance(stages, list):
372
+ live.setdefault("review_stages", []).extend(stages)
373
+ for key in ("findings",):
374
+ for finding in update.get(key, []) or []:
375
+ if hasattr(finding, "model_dump"):
376
+ finding = finding.model_dump(mode="json")
377
+ if isinstance(finding, dict):
378
+ live.setdefault("findings", []).append(finding)
379
+ _save_job(live)
380
+
381
+ state, config, cost, ragas, ragas_inputs = _build_and_stream(
382
+ request.repo,
383
+ request.pr_number,
384
+ endpoint_name,
385
+ ragas_background=True,
386
+ ragas_result_callback=save_ragas,
387
+ progress_callback=progress,
388
+ review_mode=request.review_mode,
389
+ baseline_sha=request.baseline_sha,
390
+ )
391
+ ragas_started = isinstance(ragas, str)
392
+ actual_head = state.values.get("head_sha")
393
+ verdict: Verdict | None = state.values.get("verdict")
394
+ findings: list[Finding] = state.values.get("final_findings", [])
395
+ with _lock:
396
+ if _jobs[job_id].get("status") == "cancelled":
397
+ return
398
+ if actual_head and _jobs[job_id].get("head_sha") != actual_head:
399
+ # The PR moved between metadata lookup and ingestion. The result
400
+ # can still be viewed, but must not satisfy the old cache key.
401
+ _jobs[job_id]["request_fingerprint"] = None
402
+ _jobs[job_id]["head_sha"] = actual_head
403
+ stages = state.values.get("review_stages", [])
404
+ incomplete = bool(verdict and verdict.recommendation == "incomplete")
405
+ _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)
406
+ _save_job(_jobs[job_id])
407
+ except Exception as exc:
408
+ with _lock:
409
+ if _jobs[job_id].get("status") != "cancelled":
410
+ _jobs[job_id].update(status="failed", error=str(exc)[:500])
411
+ _save_job(_jobs[job_id])
412
+ finally:
413
+ if 'ephemeral_endpoint' in locals() and ephemeral_endpoint and not ragas_started:
414
+ unregister_endpoint(ephemeral_endpoint)
415
+
416
+
417
+ def _hydrate_jobs() -> None:
418
+ """Restore persisted jobs after a process restart and resume interrupted work."""
419
+ for persisted in _load_jobs():
420
+ # Evaluation inputs may include an in-memory endpoint object. Never
421
+ # retain or expose that snapshot: it can contain a user's provider key.
422
+ if "ragas_inputs" in persisted:
423
+ persisted.pop("ragas_inputs", None)
424
+ _save_job(persisted)
425
+ job_id = persisted.get("id")
426
+ if not job_id:
427
+ continue
428
+ status = persisted.get("status")
429
+ _jobs[job_id] = persisted
430
+ if persisted.get("ragas_task_id") and not persisted.get("ragas_status"):
431
+ persisted.update(ragas_status="unavailable", ragas_error="Evaluation interrupted by restart; it was not automatically replayed.")
432
+ _save_job(persisted)
433
+ if status in {"queued", "processing"} and persisted.get("custom_provider"):
434
+ persisted.update(status="failed", error="Provider credentials were not persisted; resubmit this review after restart.")
435
+ _save_job(persisted)
436
+ continue
437
+ if status in {"queued", "processing", "processing_decision"}:
438
+ # Decision processing cannot be safely replayed without an explicit
439
+ # user action; review execution can be resumed idempotently.
440
+ if status == "processing_decision":
441
+ _jobs[job_id]["status"] = "awaiting_approval"
442
+ _save_job(_jobs[job_id])
443
+ continue
444
+ try:
445
+ request = ReviewRequest(repo=persisted["repo"], pr_number=int(persisted["pr_number"]), endpoint=persisted.get("endpoint"))
446
+ except Exception:
447
+ _jobs[job_id].update(status="failed", error="Persisted job request is invalid")
448
+ _save_job(_jobs[job_id])
449
+ continue
450
+ _jobs[job_id]["status"] = "queued"
451
+ _save_job(_jobs[job_id])
452
+ _jobs[job_id]["future"] = _executor.submit(_run_job, job_id, request)
453
+
454
+
455
+ _hydrate_jobs()
456
+
457
+
458
+ @app.get("/api/health")
459
+ def health() -> dict[str, Any]:
460
+ provider_configured = any(
461
+ os.getenv(name, "").strip()
462
+ for name in ("GEMINI_API_KEY", "GROQ_API_KEY", "OPENAI_API_KEY", "ANTHROPIC_API_KEY")
463
+ )
464
+ require_auth = os.getenv("OCR_REQUIRE_AUTH", "false").strip().lower() in {"1", "true", "yes", "on"}
465
+ persistence = "local_default_path"
466
+ if os.getenv("SUPABASE_DB_URL"):
467
+ probe = _postgres_connect()
468
+ if probe is not None:
469
+ probe.close()
470
+ persistence = "supabase_postgres"
471
+ else:
472
+ persistence = "supabase_configured_unreachable"
473
+ elif os.getenv("OPENCODEREVIEW_DB_PATH"):
474
+ persistence = "configured_path"
475
+ return {
476
+ "status": "ok",
477
+ "inference": "remote_provider_configured" if provider_configured else "fallback_or_unconfigured",
478
+ "authentication": "required" if require_auth else "optional",
479
+ "rate_limit_per_minute": int(os.getenv("OCR_RATE_LIMIT_PER_MINUTE", "0") or 0),
480
+ "persistence": persistence,
481
+ "local_embeddings": os.getenv("OPENCODEREVIEW_ALLOW_LOCAL_EMBEDDINGS", "false").lower()
482
+ in {"1", "true", "yes", "on"},
483
+ }
484
+
485
+
486
+ @app.post("/api/reviews", status_code=202)
487
+ 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]:
488
+ _authorize_request(x_api_key, http_request)
489
+ _rate_limit(http_request)
490
+ owner = str((_session(http_request) or {}).get("github_id") or "api-key")
491
+ material = request.model_dump()
492
+ head_sha = base_sha = None
493
+ try:
494
+ token = (_session(http_request) or {}).get("token") or os.getenv("GITHUB_TOKEN", "")
495
+ headers = {"Accept": "application/vnd.github+json", "Cache-Control": "no-cache"}
496
+ if token:
497
+ headers["Authorization"] = f"Bearer {token}"
498
+ response = requests.get(f"https://api.github.com/repos/{request.repo}/pulls/{request.pr_number}", headers=headers, timeout=6)
499
+ response.raise_for_status()
500
+ pull = response.json()
501
+ head_sha, base_sha = pull["head"]["sha"], pull["base"]["sha"]
502
+ except (requests.RequestException, KeyError, ValueError):
503
+ pass # Active deduplication still works if GitHub metadata is unavailable.
504
+ prompt_hash = hashlib.sha256()
505
+ project_root = Path(__file__).resolve().parent.parent
506
+ for source in sorted(project_root.joinpath("prompts").glob("*.txt")):
507
+ prompt_hash.update(source.read_bytes())
508
+ for source in sorted(project_root.joinpath("nodes").glob("*.py")):
509
+ prompt_hash.update(source.read_bytes())
510
+ material.update(head_sha=head_sha, base_sha=base_sha, pipeline_version=prompt_hash.hexdigest())
511
+ fingerprint = hashlib.sha256(json.dumps({"owner": owner, "request": material}, sort_keys=True).encode()).hexdigest()
512
+ # Reuse completed previews only for an identical immutable diff and configuration.
513
+ with _lock:
514
+ 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)
515
+ if existing is None:
516
+ job_id = str(uuid.uuid4())
517
+ 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()}
518
+ _jobs[job_id] = job
519
+ _save_job(job)
520
+ else:
521
+ job = existing
522
+ if existing is not None:
523
+ return {**_with_ragas(job), "reused": True}
524
+ job["future"] = _executor.submit(_run_job, job_id, request)
525
+ return _with_ragas(job)
526
+
527
+
528
+ @app.post("/api/reviews/{job_id}/cancel")
529
+ def cancel_review(job_id: str, request: Request, x_api_key: str | None = Header(default=None)) -> dict[str, Any]:
530
+ _authorize_request(x_api_key, request)
531
+ owner = str((_session(request) or {}).get("github_id") or "api-key")
532
+ with _lock:
533
+ job = _jobs.get(job_id)
534
+ if not job or job.get("owner_id", "api-key") != owner:
535
+ raise HTTPException(status_code=404, detail="Review not found")
536
+ if job.get("status") not in {"queued", "processing"}:
537
+ raise HTTPException(status_code=409, detail="Only queued or processing reviews can be cancelled")
538
+ future = job.get("future")
539
+ if future:
540
+ future.cancel()
541
+ job.update(status="cancelled", cancellation_note="Running calls finish within their timeout; no results will be posted.")
542
+ _save_job(job)
543
+ return _public_job(job)
544
+
545
+
546
+ @app.get("/api/reviews/{job_id}")
547
+ def get_review(job_id: str, request: Request, x_api_key: str | None = Header(default=None)) -> dict[str, Any]:
548
+ # API-key authorization remains supported for polling; OAuth callers use the cookie path.
549
+ _authorize_request(x_api_key, request)
550
+ with _lock:
551
+ job = _jobs.get(job_id)
552
+ if not job:
553
+ job = _load_job(job_id)
554
+ owner = str((_session(request) or {}).get("github_id") or "api-key")
555
+ if not job or job.get("owner_id", "api-key") != owner:
556
+ raise HTTPException(status_code=404, detail="Review not found")
557
+ return _with_ragas(job)
558
+
559
+
560
+ @app.post('/api/reviews/{job_id}/feedback')
561
+ def finding_feedback(job_id: str, payload: FindingFeedbackRequest, request: Request,
562
+ x_api_key: str | None = Header(default=None)) -> dict[str, Any]:
563
+ _authorize_request(x_api_key, request)
564
+ _rate_limit(request)
565
+ owner = str((_session(request) or {}).get('github_id') or 'api-key')
566
+ with _lock:
567
+ job = _jobs.get(job_id) or _load_job(job_id)
568
+ if not job or job.get('owner_id', 'api-key') != owner:
569
+ raise HTTPException(status_code=404, detail='Review not found')
570
+ if job.get('status') not in {'awaiting_approval', 'incomplete', 'posted', 'partially_posted', 'rejected', 'post_failed'}:
571
+ raise HTTPException(status_code=409, detail='Wait until the review finishes before giving feedback')
572
+ if payload.finding_index >= len(job.get('findings') or []):
573
+ raise HTTPException(status_code=422, detail='Finding does not exist')
574
+ feedback = dict(job.get('feedback') or {})
575
+ feedback[str(payload.finding_index)] = payload.label
576
+ job['feedback'] = feedback
577
+ job['feedback_updated_at'] = datetime.now(timezone.utc).isoformat()
578
+ _jobs[job_id] = job
579
+ _save_job(job)
580
+ return {'feedback': feedback}
581
+
582
+
583
+ @app.post("/api/reviews/{job_id}/decision")
584
+ def decide_review(job_id: str, request: DecisionRequest, http_request: Request, x_api_key: str | None = Header(default=None)) -> dict[str, Any]:
585
+ _authorize_request(x_api_key, http_request)
586
+ _rate_limit(http_request)
587
+ with _lock:
588
+ preview = _jobs.get(job_id) or _load_job(job_id)
589
+ owner = str((_session(http_request) or {}).get("github_id") or "api-key")
590
+ if not preview or preview.get("owner_id", "api-key") != owner:
591
+ raise HTTPException(status_code=404, detail="Review not found")
592
+ if request.action == "approve" and preview.get("baseline_sha"):
593
+ raise HTTPException(status_code=409, detail="Incremental reviews are preview-only. Run a full review before posting.")
594
+ if preview and request.action == "approve" and preview.get("head_sha"):
595
+ headers = {"Accept": "application/vnd.github+json", "Cache-Control": "no-cache"}
596
+ token = (_session(http_request) or {}).get("token") or os.getenv("GITHUB_TOKEN", "")
597
+ if token:
598
+ headers["Authorization"] = f"Bearer {token}"
599
+ try:
600
+ response = requests.get(f"https://api.github.com/repos/{preview['repo']}/pulls/{preview['pr_number']}", headers=headers, timeout=6)
601
+ response.raise_for_status()
602
+ current = response.json()
603
+ if current["head"]["sha"] != preview["head_sha"] or current["base"]["sha"] != preview.get("base_sha"):
604
+ raise HTTPException(status_code=409, detail="PR changed since this review; start a new review before posting.")
605
+ except (requests.RequestException, KeyError, ValueError) as exc:
606
+ raise HTTPException(status_code=503, detail="Cannot verify the current PR commit; retry before posting.") from exc
607
+ with _lock:
608
+ job = _jobs.get(job_id)
609
+ if not job:
610
+ job = _load_job(job_id)
611
+ if not job:
612
+ raise HTTPException(status_code=404, detail="Review not found")
613
+ if job.get("status") != "awaiting_approval":
614
+ raise HTTPException(status_code=409, detail="Review is not awaiting approval")
615
+ config = job["config"]
616
+ job["status"] = "processing_decision"
617
+ _save_job(job)
618
+ if request.action == "reject":
619
+ with _lock:
620
+ job.update(status="rejected", decision="reject")
621
+ _save_job(job)
622
+ return _public_job(job)
623
+ graph = build_graph(DB_PATH)
624
+ try:
625
+ callbacks = [TokenCostCallback()]
626
+ handler = get_langfuse_handler()
627
+ if handler:
628
+ callbacks.append(handler)
629
+ config = dict(config)
630
+ config["callbacks"] = callbacks
631
+ result = graph.invoke(Command(resume={"action": "approve"}), config)
632
+ posting_result = result.get("posting_result") if isinstance(result, dict) else None
633
+ final_status = (posting_result or {}).get("status", "posted")
634
+ with _lock:
635
+ job.update(status=final_status, decision="approve", posting_result=posting_result)
636
+ _save_job(job)
637
+ return _public_job(job)
638
+ except Exception as exc:
639
+ with _lock:
640
+ job.update(status="failed", error=str(exc)[:500])
641
+ _save_job(job)
642
+ raise HTTPException(status_code=500, detail="Decision processing failed") from exc
643
+ finally:
644
+ conn = getattr(graph, "_opencodereview_conn", None)
645
+ if conn:
646
+ conn.close()
647
+ flush_langfuse()
backend/app.py ADDED
@@ -0,0 +1,1962 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """OpenCodeReview — Gradio Web UI for Hugging Face Spaces.
3
+
4
+ Run locally:
5
+ python app.py
6
+
7
+ On Hugging Face Spaces:
8
+ The combined server mounts this UI alongside the FastAPI application.
9
+ Set GROQ_API_KEY (and optionally GITHUB_TOKEN) as Space secrets.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import html
15
+ from contextvars import copy_context
16
+ import json
17
+ import ipaddress
18
+ import logging
19
+ import os
20
+ import threading
21
+ import time
22
+ import uuid
23
+ from concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeoutError
24
+
25
+ import gradio as gr
26
+ from langgraph.types import Command
27
+
28
+ from backend.graph import build_graph
29
+ from backend.main import NODE_LABELS, _cleanup_db, SYNTHETIC_STATE
30
+ from backend.observability import (
31
+ build_run_metadata,
32
+ enable_langsmith,
33
+ get_langfuse_handler,
34
+ is_langfuse_enabled,
35
+ is_langsmith_enabled,
36
+ estimate_groq_cost,
37
+ flush_langfuse,
38
+ format_cost,
39
+ langfuse_trace,
40
+ log_error_to_backends,
41
+ log_langfuse_score,
42
+ _resolve_langfuse_trace_id,
43
+ HealthStatus,
44
+ TokenCostCallback,
45
+ check_groq_connectivity,
46
+ check_langfuse_connectivity,
47
+ )
48
+ from backend.integrations.endpoints import (
49
+ EndpointConfig,
50
+ clear_session_endpoints,
51
+ discover_endpoints,
52
+ dropdown_choices,
53
+ register_endpoint,
54
+ session_endpoints,
55
+ )
56
+ from backend.state import Verdict
57
+
58
+ import subprocess
59
+ from datetime import datetime, timezone
60
+
61
+ logging.basicConfig(
62
+ level=logging.INFO,
63
+ format="%(asctime)s [%(levelname)s] %(name)s — %(message)s",
64
+ )
65
+ logger = logging.getLogger(__name__)
66
+
67
+ # Set this to a mounted volume or durable filesystem path in hosted
68
+ # deployments. The default keeps local development self-contained.
69
+ DB_PATH = os.environ.get("OPENCODEREVIEW_DB_PATH", "checkpoints.db")
70
+
71
+ SEVERITY_COLORS = {
72
+ "critical": "#dc2626",
73
+ "high": "#ea580c",
74
+ "medium": "#ca8a04",
75
+ "low": "#16a34a",
76
+ "info": "#2563eb",
77
+ }
78
+
79
+ RECOMMENDATION_ICONS = {
80
+ "approve": "✅",
81
+ "request_changes": "🔄",
82
+ "block": "🚫",
83
+ "comment": "💬",
84
+ }
85
+
86
+ # Default dropdown choice shown in the UI. Gradio 6's Dropdown has no
87
+ # placeholder support, so a real choice is displayed and mapped back to
88
+ # the "" (auto) sentinel wherever the value enters the pipeline.
89
+ AUTO_ENDPOINT_CHOICE = "Auto (Gemini → Groq fallback)"
90
+
91
+
92
+ def _normalize_endpoint_name(endpoint_name: str | None) -> str:
93
+ return "" if endpoint_name == AUTO_ENDPOINT_CHOICE else (endpoint_name or "")
94
+
95
+
96
+ # ─── Orchestration ───────────────────────────────────────────────────────────
97
+
98
+
99
+ def _init_observability_ui() -> None:
100
+ """Initialise observability backends and HTTP cache for the Gradio UI."""
101
+ from backend.integrations.github_client import _init_cache as _init_http_cache
102
+ _init_http_cache()
103
+
104
+ # LangSmith: enable if key is in environment (check both modern and legacy names)
105
+ ls_key = (
106
+ os.environ.get("LANGSMITH_API_KEY", "").strip()
107
+ or os.environ.get("LANGCHAIN_API_KEY", "").strip()
108
+ )
109
+ if ls_key:
110
+ project = os.environ.get("LANGSMITH_PROJECT",
111
+ os.environ.get("LANGCHAIN_PROJECT", "opencodereview"))
112
+ enable_langsmith(ls_key, project)
113
+ logger.info("Observability: LangSmith enabled for Gradio UI")
114
+ if get_langfuse_handler():
115
+ logger.info("Observability: Langfuse enabled for Gradio UI")
116
+
117
+
118
+ def _build_and_stream(
119
+ repo: str,
120
+ pr_number: int,
121
+ endpoint_name: str = "",
122
+ ragas_background: bool = False,
123
+ ragas_result_callback=None,
124
+ progress_callback=None,
125
+ review_mode: str = "thorough",
126
+ baseline_sha: str | None = None,
127
+ ) -> tuple:
128
+ """Build the graph, stream up to the interrupt, and return state + config.
129
+
130
+ Parameters
131
+ ----------
132
+ endpoint_name : str
133
+ Optional name of a configured custom LLM endpoint
134
+ (``OCR_ENDPOINT_*``). Empty string uses the built-in provider.
135
+ ragas_background : bool
136
+ When True, RAGAS scoring runs on a background daemon thread and the
137
+ fourth return element is a task id (str) to poll instead of the
138
+ scores dict — so the UI can show results immediately.
139
+ """
140
+ graph = build_graph(DB_PATH)
141
+ thread_id = str(uuid.uuid4())
142
+ trace_name = f"opencodereview/review/{repo}#{pr_number}"
143
+ tags = ["gradio_ui", repo]
144
+ prompt_versions = {
145
+ "correctness": "v1",
146
+ "security": "v1",
147
+ "test_coverage": "v1",
148
+ "aggregator": "v1",
149
+ }
150
+ cost_tracker = TokenCostCallback()
151
+ metadata = build_run_metadata(
152
+ source="gradio_ui", repo=repo, pr_number=pr_number,
153
+ session_id=thread_id,
154
+ prompt_versions=prompt_versions,
155
+ )
156
+ config: dict = {
157
+ "configurable": {"thread_id": f"web-{thread_id}"},
158
+ "metadata": metadata,
159
+ }
160
+
161
+ # Use langfuse_trace context manager which sets trace metadata via
162
+ # propagate_attributes() (langfuse v4+ API) and yields the handler.
163
+ with langfuse_trace(
164
+ trace_name=trace_name,
165
+ tags=tags,
166
+ session_id=thread_id,
167
+ metadata={
168
+ "source": "gradio_ui",
169
+ "repo": repo,
170
+ "pr_number": pr_number,
171
+ "prompt_versions": prompt_versions,
172
+ },
173
+ ) as handler:
174
+ callbacks = [cost_tracker]
175
+ if handler:
176
+ callbacks.append(handler)
177
+ config["callbacks"] = callbacks
178
+
179
+ try:
180
+ t0 = time.time()
181
+ initial = {"repo": repo, "pr_number": pr_number, "review_mode": review_mode, "incremental_base_sha": baseline_sha or ""}
182
+ if endpoint_name:
183
+ initial["endpoint"] = endpoint_name
184
+ for event in graph.stream(initial, config):
185
+ for node_name in event:
186
+ label = NODE_LABELS.get(node_name, node_name)
187
+ logger.info(" ✔ %s (+%.1fs)", label, time.time() - t0)
188
+ if progress_callback:
189
+ progress_callback(node_name, time.time() - t0, event.get(node_name))
190
+ logger.info(" ─── Pipeline complete in %.1fs ───", time.time() - t0)
191
+ except Exception as exc:
192
+ log_error_to_backends(exc, context={"source": "gradio_ui", "phase": "stream", "repo": repo, "pr_number": pr_number})
193
+ conn = getattr(graph, "_opencodereview_conn", None)
194
+ if conn:
195
+ conn.close()
196
+ flush_langfuse()
197
+ raise
198
+
199
+ state = graph.get_state(config)
200
+
201
+ # ── Log verdict/findings scores and capture trace_id ───────
202
+ # Capture trace_id NOW (immediately after graph completes)
203
+ # so it can be used after the long-running RAGAS computation.
204
+ # _resolve_langfuse_trace_id() can return None after ~60s delays
205
+ # because contextvars may be lost.
206
+ run_trace_id = _resolve_langfuse_trace_id(handler)
207
+
208
+ verdict = state.values.get("verdict")
209
+ findings = state.values.get("final_findings", [])
210
+ if verdict and verdict.overall_score is not None:
211
+ log_langfuse_score(
212
+ name="verdict_score",
213
+ value=verdict.overall_score,
214
+ comment=f"{repo}#{pr_number} — {verdict.recommendation}: {verdict.summary[:100]}",
215
+ trace_id=run_trace_id,
216
+ handler=handler,
217
+ )
218
+ log_langfuse_score(
219
+ name="findings_count",
220
+ value=len(findings),
221
+ comment=f"{repo}#{pr_number}",
222
+ trace_id=run_trace_id,
223
+ handler=handler,
224
+ )
225
+
226
+ # ── Compute and log RAGAS retrieval scores ─────────────────
227
+ # Background mode spawns a thread and returns a task id so the UI
228
+ # can render results immediately; sync mode (CLI/health) waits.
229
+ ragas_out: dict[str, float | None] | str = {}
230
+ ragas_inputs = _ragas_inputs_from_state(state, endpoint_name)
231
+ if ragas_inputs:
232
+ if ragas_background:
233
+ # handler is not shared across threads (langfuse contextvars
234
+ # are lost in the worker); the captured trace_id is passed
235
+ # explicitly instead.
236
+ ragas_out = _spawn_ragas_background(
237
+ ragas_inputs, repo, pr_number, run_trace_id, None,
238
+ ragas_result_callback,
239
+ )
240
+ else:
241
+ ragas_out = _compute_and_log_ragas(
242
+ ragas_inputs, repo, pr_number, run_trace_id, handler,
243
+ )
244
+
245
+ # Close the checkpointer connection (checkpoints persist to disk so the
246
+ # resume path opens a fresh one) and ship any queued Langfuse scores.
247
+ conn = getattr(graph, "_opencodereview_conn", None)
248
+ if conn:
249
+ conn.close()
250
+ flush_langfuse()
251
+
252
+ config.setdefault("metadata", {})["cost_details"] = cost_tracker.details()
253
+ return state, config, cost_tracker.summary(), ragas_out, ({**ragas_inputs, "endpoint": None} if ragas_inputs else None)
254
+
255
+
256
+ def _format_findings_table(findings: list) -> str:
257
+ """Build an HTML table of findings with severity-coloured badges."""
258
+ if not findings:
259
+ return '<p style="color:var(--text-muted)">No issues found.</p>'
260
+
261
+ rows: list[str] = []
262
+ for f in findings:
263
+ color = SEVERITY_COLORS.get(f.severity.value, "#666")
264
+ severity = html.escape(f.severity.value.upper())
265
+ category = html.escape(str(f.category))
266
+ location = html.escape(f"{f.file_path}:{f.line_start}–{f.line_end}")
267
+ comment = html.escape(str(f.comment))
268
+ rows.append(
269
+ f"<tr>"
270
+ f'<td><span style="display:inline-block;padding:2px 10px;'
271
+ f'border-radius:12px;background:{color}22;'
272
+ f'color:{color};font-weight:700;font-size:0.85em">'
273
+ f"{severity}</span></td>"
274
+ f"<td>{category}</td>"
275
+ f"<td><code>{location}</code></td>"
276
+ f"<td>{comment}</td>"
277
+ f'<td style="text-align:center">{f.confidence:.0%}</td>'
278
+ f"</tr>"
279
+ )
280
+
281
+ return (
282
+ '<div style="overflow-x:auto">'
283
+ '<table style="width:100%;border-collapse:collapse;font-size:0.9em">'
284
+ "<thead>"
285
+ f'<tr style="background:var(--bg-table-header);border-bottom:2px solid var(--border-color)">'
286
+ '<th style="padding:10px 12px;text-align:left;color:var(--text-primary)">Severity</th>'
287
+ '<th style="padding:10px 12px;text-align:left;color:var(--text-primary)">Category</th>'
288
+ '<th style="padding:10px 12px;text-align:left;color:var(--text-primary)">Location</th>'
289
+ '<th style="padding:10px 12px;text-align:left;color:var(--text-primary)">Comment</th>'
290
+ '<th style="padding:10px 12px;text-align:left;color:var(--text-primary)">Confidence</th>'
291
+ "</tr>"
292
+ "</thead>"
293
+ f'<tbody style="color:var(--text-secondary)">' + "".join(rows) + "</tbody>"
294
+ "</table>"
295
+ "</div>"
296
+ )
297
+
298
+
299
+ def _format_verdict(verdict: Verdict | None) -> str:
300
+ """Build a verdict summary card with a score bar and severity chips."""
301
+ if verdict is None:
302
+ return '<p class="muted">No verdict produced.</p>'
303
+
304
+ icon = RECOMMENDATION_ICONS.get(verdict.recommendation, "📋")
305
+ color = (
306
+ "#16a34a" if verdict.recommendation == "approve"
307
+ else "#dc2626" if verdict.recommendation == "block"
308
+ else "#ea580c"
309
+ )
310
+ pct = max(0, min(100, int((verdict.overall_score or 0) * 10)))
311
+ score_label = f"{verdict.overall_score:.1f}/10" if verdict.overall_score is not None else "Not scored"
312
+
313
+ chips = []
314
+ if verdict.critical_count:
315
+ chips.append(
316
+ f'<span class="sev-chip" style="color:#dc2626;border-color:#dc262644;background:#dc262611">'
317
+ f"critical × {verdict.critical_count}</span>"
318
+ )
319
+ if verdict.high_count:
320
+ chips.append(
321
+ f'<span class="sev-chip" style="color:#ea580c;border-color:#ea580c44;background:#ea580c11">'
322
+ f"high × {verdict.high_count}</span>"
323
+ )
324
+ chips_html = (
325
+ f'<div class="chips-row" style="margin-top:10px">' + "".join(chips) + "</div>"
326
+ if chips else ""
327
+ )
328
+
329
+ return (
330
+ '<div class="ocr-card verdict-card" '
331
+ f'style="border-left-color:{color}">'
332
+ '<div class="verdict-head">'
333
+ f'<span class="verdict-icon">{icon}</span>'
334
+ f'<span class="verdict-reco" style="color:{color}">{verdict.recommendation.upper()}</span>'
335
+ f'<span class="verdict-score">Score <b>{score_label}</b></span>'
336
+ "</div>"
337
+ f'<div class="score-track"><div class="score-fill" style="width:{pct}%;background:{color}"></div></div>'
338
+ f'<p class="verdict-summary">{html.escape(str(verdict.summary))}</p>'
339
+ + chips_html
340
+ + "</div>"
341
+ )
342
+
343
+
344
+ RAGAS_METRIC_LABELS = {
345
+ "context_precision": "Context Precision",
346
+ "context_recall": "Context Recall",
347
+ "faithfulness": "Faithfulness",
348
+ "answer_relevancy": "Answer Relevancy",
349
+ "mmr": "Mean Reciprocal Rank",
350
+ }
351
+
352
+ RAGAS_METRIC_TOOLTIPS = {
353
+ "context_precision": "Are the most relevant code chunks ranked first?",
354
+ "context_recall": "Did we find ALL the relevant code? (requires ground truth)",
355
+ "faithfulness": "Does the review answer stick to the retrieved code?",
356
+ "answer_relevancy": "Does the review address the PR diff?",
357
+ "mmr": "How early in the list does the first useful chunk appear?",
358
+ }
359
+
360
+
361
+ def _format_ragas_scores(scores: dict[str, float | None]) -> str:
362
+ """Build an HTML card showing RAGAS retrieval quality metrics."""
363
+ if not scores:
364
+ return ""
365
+
366
+ def _score_color(val: float) -> str:
367
+ if val >= 0.8:
368
+ return "#16a34a"
369
+ elif val >= 0.5:
370
+ return "#ca8a04"
371
+ else:
372
+ return "#dc2626"
373
+
374
+ rows: list[str] = []
375
+ failed = 0
376
+ for key, value in scores.items():
377
+ label = RAGAS_METRIC_LABELS.get(key, key.replace("_", " ").title())
378
+ tooltip = RAGAS_METRIC_TOOLTIPS.get(key, "")
379
+ tip_html = (
380
+ f'<span class="tip" title="{tooltip}">ℹ️</span>' if tooltip else ""
381
+ )
382
+ if value is None:
383
+ failed += 1
384
+ rows.append(
385
+ f'<div class="metric-row">'
386
+ f'<span class="metric-label">{label} {tip_html}</span>'
387
+ f'<span class="metric-value muted">N/A — failed</span>'
388
+ f"</div>"
389
+ )
390
+ continue
391
+ color = _score_color(value)
392
+ pct = int(value * 100)
393
+ rows.append(
394
+ f'<div class="metric-row">'
395
+ f'<span class="metric-label">{label} {tip_html}</span>'
396
+ f'<span class="metric-value" style="color:{color}">{value:.3f}</span>'
397
+ f"</div>"
398
+ f'<div class="metric-track"><div class="metric-fill" style="width:{pct}%;background:{color}"></div></div>'
399
+ )
400
+
401
+ note = ""
402
+ if failed:
403
+ note = (
404
+ '<p class="muted small" style="margin:10px 0 0">'
405
+ f"{failed} metric(s) failed (likely LLM rate-limited) and are shown as N/A."
406
+ "</p>"
407
+ )
408
+
409
+ return (
410
+ '<div class="ocr-card">'
411
+ '<div class="card-title">📊 Retrieval Quality (RAGAS)</div>'
412
+ + "".join(rows)
413
+ + note
414
+ + "</div>"
415
+ )
416
+
417
+
418
+ RAGAS_PENDING_HTML = (
419
+ '<div class="ocr-card">'
420
+ '<div class="card-title">📊 Retrieval Quality (RAGAS)</div>'
421
+ '<div class="loading-spinner" style="justify-content:flex-start;padding:10px 0">'
422
+ '<div class="spinner"></div>'
423
+ '<span class="label">Computing RAGAS scores in the background…</span>'
424
+ "</div>"
425
+ "</div>"
426
+ )
427
+
428
+ RAGAS_FAILED_HTML = (
429
+ '<div class="ocr-card">'
430
+ '<div class="card-title">📊 Retrieval Quality (RAGAS)</div>'
431
+ '<p class="muted small">N/A — RAGAS scoring failed '
432
+ "(likely LLM rate-limited or timed out). Check the logs for details.</p>"
433
+ "</div>"
434
+ )
435
+
436
+ # After this long a background RAGAS task is considered stalled and the
437
+ # placeholder is replaced with the failure card instead of spinning forever.
438
+ RAGAS_TIMEOUT_SECONDS = 600
439
+
440
+ # Background RAGAS task registry: the UI spawns scoring on a daemon thread
441
+ # and a gr.Timer polls this dict, so review results render immediately
442
+ # instead of waiting minutes for the RAGAS LLM calls.
443
+ _ragas_tasks: dict[str, dict] = {}
444
+ _ragas_lock = threading.Lock()
445
+
446
+
447
+ def _ragas_inputs_from_state(state, endpoint_name: str) -> dict | None:
448
+ """Extract the inputs RAGAS needs from the finished graph state."""
449
+ verdict = state.values.get("verdict")
450
+ if verdict and verdict.recommendation == "incomplete":
451
+ return None
452
+ context_chunks = state.values.get("context_chunks", [])
453
+ query = state.values.get("diff", "") or ""
454
+ if not query:
455
+ changed = state.values.get("changed_files", [])
456
+ paths = [getattr(item, "path", "") for item in changed if getattr(item, "path", "")]
457
+ query = "Review changed files: " + ", ".join(paths) if paths else "Review the pull request changes"
458
+ contexts = [c.content for c in context_chunks if c.content]
459
+ # When vector retrieval is disabled on a small host, evaluate against the
460
+ # PR diff itself. This preserves a grounded context for RAGAS instead of
461
+ # silently dropping quality measurement altogether.
462
+ if not contexts and query:
463
+ contexts = [query]
464
+ if not contexts:
465
+ return None
466
+
467
+ # Build answer text from findings + verdict for
468
+ # faithfulness & answer_relevancy metrics
469
+ answer_lines = []
470
+ for f in state.values.get("final_findings", []):
471
+ answer_lines.append(
472
+ f"[{f.severity.value}] {f.file_path}:{f.line_start}-{f.line_end}: {f.comment}"
473
+ )
474
+ if state.values.get("verdict"):
475
+ v = state.values["verdict"]
476
+ answer_lines.append(
477
+ f"Verdict: {v.recommendation} (score={v.overall_score}/10) — {v.summary}"
478
+ )
479
+ answer_text = "\n".join(answer_lines) if answer_lines else None
480
+ return {
481
+ "query": query,
482
+ "context_source": "retrieved_context" if context_chunks else "pr_diff_proxy",
483
+ "contexts": contexts,
484
+ "answer": answer_text,
485
+ "endpoint": __import__("endpoints").get_endpoint(endpoint_name) if endpoint_name else None,
486
+ }
487
+
488
+
489
+ def _compute_and_log_ragas(
490
+ inputs: dict,
491
+ repo: str,
492
+ pr_number: int,
493
+ run_trace_id: str | None,
494
+ handler,
495
+ progress_callback=None,
496
+ ) -> dict[str, float | None]:
497
+ """Compute RAGAS scores and log them to Langfuse. Never raises."""
498
+ scores: dict[str, float | None] = {}
499
+ try:
500
+ from eval_data.ragas_eval import compute_ragas_report
501
+
502
+ report = compute_ragas_report(
503
+ query=inputs["query"],
504
+ retrieved_contexts=inputs["contexts"],
505
+ answer=inputs["answer"],
506
+ endpoint=inputs["endpoint"],
507
+ progress_callback=progress_callback,
508
+ )
509
+ scores = report["scores"]
510
+ if progress_callback:
511
+ progress_callback(report)
512
+ for metric_name, value in scores.items():
513
+ if value is None:
514
+ continue
515
+ log_langfuse_score(
516
+ name=f"ragas_{metric_name}",
517
+ value=value,
518
+ comment=f"{repo}#{pr_number} — {metric_name}",
519
+ trace_id=run_trace_id,
520
+ handler=handler,
521
+ )
522
+ logger.info(
523
+ "RAGAS scores logged to Langfuse: %s",
524
+ " | ".join(
525
+ f"{k}={v:.4f}" for k, v in scores.items() if v is not None
526
+ ),
527
+ )
528
+ except ImportError:
529
+ logger.info("RAGAS not installed — skipping RAGAS scoring (pip install ragas)")
530
+ except Exception as exc:
531
+ logger.warning("RAGAS scoring failed: %s", exc)
532
+ return scores
533
+
534
+
535
+ def _ragas_worker(
536
+ task_id: str,
537
+ inputs: dict,
538
+ repo: str,
539
+ pr_number: int,
540
+ run_trace_id: str | None,
541
+ handler,
542
+ result_callback=None,
543
+ ) -> None:
544
+ """Daemon thread body: compute scores, stash them for the Timer poll."""
545
+ timeout = float(os.getenv("OCR_RAGAS_TIMEOUT_SECONDS", "30"))
546
+ def report_progress(report):
547
+ with _ragas_lock:
548
+ entry = _ragas_tasks.get(task_id)
549
+ if entry is not None:
550
+ entry["metrics"] = dict(report.get("metrics", {}))
551
+ entry["evaluation"] = {**report.get("evaluation", {}), "context_source": inputs.get("context_source", "retrieved_context")}
552
+ entry["scores"] = dict(report.get("scores", {}))
553
+ with _ragas_lock:
554
+ if task_id in _ragas_tasks:
555
+ _ragas_tasks[task_id]["timeout_seconds"] = timeout
556
+ try:
557
+ # The provider call may block on a network timeout. Keep the task
558
+ # terminal and observable even when the provider does not return.
559
+ pool = ThreadPoolExecutor(max_workers=1, thread_name_prefix="ragas-call")
560
+ future = pool.submit(
561
+ copy_context().run,
562
+ _compute_and_log_ragas,
563
+ inputs,
564
+ repo,
565
+ pr_number,
566
+ run_trace_id,
567
+ handler,
568
+ report_progress,
569
+ )
570
+ try:
571
+ scores = future.result(timeout=timeout)
572
+ except FutureTimeoutError:
573
+ with _ragas_lock:
574
+ entry = _ragas_tasks.get(task_id)
575
+ scores = dict((entry or {}).get("scores") or {})
576
+ if entry is not None:
577
+ entry["error"] = f"RAGAS exceeded {int(timeout)} second timeout"
578
+ entry["done"] = True
579
+ if result_callback:
580
+ result_callback(scores, f"RAGAS exceeded {int(timeout)} second timeout")
581
+ pool.shutdown(wait=False, cancel_futures=True)
582
+ return
583
+ else:
584
+ pool.shutdown(wait=True)
585
+ except Exception as exc:
586
+ logger.warning("RAGAS worker failed: %s", exc)
587
+ with _ragas_lock:
588
+ entry = _ragas_tasks.get(task_id)
589
+ if entry is not None:
590
+ entry["error"] = str(exc)[:500]
591
+ entry["done"] = True
592
+ if result_callback:
593
+ result_callback({}, str(exc)[:500])
594
+ return
595
+ with _ragas_lock:
596
+ entry = _ragas_tasks.get(task_id)
597
+ if entry is not None:
598
+ entry["scores"] = scores or {}
599
+ entry["done"] = True
600
+ if result_callback:
601
+ result_callback(scores or {}, None)
602
+ # Ship the Langfuse scores logged from this thread.
603
+ flush_langfuse()
604
+
605
+
606
+ def _spawn_ragas_background(
607
+ inputs: dict,
608
+ repo: str,
609
+ pr_number: int,
610
+ run_trace_id: str | None,
611
+ handler,
612
+ result_callback=None,
613
+ ) -> str:
614
+ """Start RAGAS scoring on a daemon thread; return a task id to poll."""
615
+ task_id = f"ragas-{uuid.uuid4().hex[:12]}"
616
+ with _ragas_lock:
617
+ _ragas_tasks[task_id] = {"done": False, "scores": None, "started": time.time()}
618
+ if len(_ragas_tasks) > 64:
619
+ # Drop oldest finished entries to bound memory.
620
+ for old_id in list(_ragas_tasks):
621
+ if _ragas_tasks[old_id].get("done"):
622
+ del _ragas_tasks[old_id]
623
+ if len(_ragas_tasks) <= 64:
624
+ break
625
+ threading.Thread(
626
+ target=copy_context().run,
627
+ args=(_ragas_worker, task_id, inputs, repo, pr_number, run_trace_id, handler, result_callback),
628
+ name=f"ragas-{task_id}",
629
+ daemon=True,
630
+ ).start()
631
+ return task_id
632
+
633
+
634
+ def _format_findings_count(findings: list) -> str:
635
+ """Build a compact summary count per severity as pill chips."""
636
+ counts: dict[str, int] = {}
637
+ for f in findings:
638
+ counts[f.severity.value] = counts.get(f.severity.value, 0) + 1
639
+
640
+ parts = []
641
+ for sev in ("critical", "high", "medium", "low", "info"):
642
+ if counts.get(sev, 0) > 0:
643
+ color = SEVERITY_COLORS.get(sev, "#666")
644
+ parts.append(
645
+ f'<span class="sev-chip" style="color:{color};border-color:{color}44;background:{color}11">'
646
+ f"{sev} × {counts[sev]}</span>"
647
+ )
648
+ return (
649
+ '<div class="chips-row">'
650
+ + ("".join(parts) if parts else '<span class="muted">No issues</span>')
651
+ + "</div>"
652
+ )
653
+
654
+
655
+ def _format_run_summary(
656
+ repo: str, pr_number: int, endpoint_name: str, duration: float, cost_summary: str | dict
657
+ ) -> str:
658
+ """Build a compact run-summary card shown above the results."""
659
+ endpoint_display = html.escape(endpoint_name or "built-in default")
660
+ cost_text = cost_summary if isinstance(cost_summary, str) else str(cost_summary)
661
+ return (
662
+ '<div class="ocr-card" style="margin-top:12px">'
663
+ '<div class="run-summary">'
664
+ f'<span>📦 <b>{html.escape(repo)}</b>#{pr_number}</span>'
665
+ f'<span>🤖 <b>{endpoint_display}</b></span>'
666
+ f'<span>⏱️ <b>{duration:.1f}s</b></span>'
667
+ f'<span>💰 {html.escape(cost_text)}</span>'
668
+ "</div>"
669
+ "</div>"
670
+ )
671
+
672
+
673
+ def _format_session_endpoints() -> str:
674
+ """Render cards for endpoints added at runtime via the UI form."""
675
+ eps = session_endpoints()
676
+ if not eps:
677
+ return (
678
+ '<p class="muted small">No endpoints added in this session yet — '
679
+ "fill the form above and click <b>Save &amp; use endpoint</b>.</p>"
680
+ )
681
+ cards = "".join(
682
+ f'<div class="endpoint-card">'
683
+ f'<div class="endpoint-name">{html.escape(ep.name)}'
684
+ f'<span class="endpoint-badge">{html.escape(ep.provider)}</span></div>'
685
+ f'<div class="endpoint-meta"><code>{html.escape(ep.model)}</code>'
686
+ f' · {html.escape(ep.base_url or "default URL")} · key {ep.masked_key}</div>'
687
+ f'</div>'
688
+ for ep in eps
689
+ )
690
+ return (
691
+ f'<div class="card-title" style="margin:6px 0 6px">'
692
+ f'Added in this session ({len(eps)})</div><div>{cards}</div>'
693
+ )
694
+
695
+
696
+ def _probe_endpoint(ep) -> tuple[bool, str]:
697
+ """Probe an endpoint and report whether it can serve the pipeline.
698
+
699
+ HTTP status codes are classified so a 401/403 is reported as
700
+ "reachable but the server rejected the key" instead of a misleading
701
+ "unreachable". OpenAI-compatible servers that don't implement
702
+ ``GET /models`` (many vLLM / proxy deployments) fall back to a
703
+ minimal ``/chat/completions`` call — the real request the pipeline
704
+ makes — so a blocked /models endpoint no longer looks broken.
705
+ """
706
+ import urllib.error as _ur_err
707
+ import urllib.request as _ur
708
+ from urllib.parse import urlsplit
709
+
710
+ def _safe_base_url(raw_url: str | None, default: str) -> tuple[str | None, str | None]:
711
+ """Allow only public HTTP(S) endpoints; never forward keys to private hosts."""
712
+ value = (raw_url or default).strip().rstrip("/")
713
+ try:
714
+ parsed = urlsplit(value)
715
+ if parsed.scheme not in {"http", "https"} or not parsed.hostname:
716
+ return None, "base URL must use http(s) and include a hostname"
717
+ if parsed.username or parsed.password:
718
+ return None, "base URL must not contain embedded credentials"
719
+ addresses = {item[4][0] for item in __import__("socket").getaddrinfo(parsed.hostname, parsed.port, type=__import__("socket").SOCK_STREAM)}
720
+ for address in addresses:
721
+ ip = ipaddress.ip_address(address)
722
+ if not ip.is_global:
723
+ return None, "base URL resolves to a private or otherwise non-public address"
724
+ except Exception as exc:
725
+ return None, f"invalid or unresolvable base URL: {type(exc).__name__}"
726
+ return value, None
727
+
728
+ class _NoRedirect(_ur.HTTPRedirectHandler):
729
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
730
+ return None
731
+
732
+ _opener = _ur.build_opener(_NoRedirect)
733
+
734
+ def _open(req):
735
+ return _opener.open(req, timeout=15)
736
+
737
+ if ep.provider == "google":
738
+ try:
739
+ from google import genai
740
+ client = genai.Client(api_key=ep.api_key)
741
+ list(client.models.list())
742
+ return True, "models.list OK"
743
+ except Exception as exc:
744
+ return False, f"{type(exc).__name__}: {exc}"[:140]
745
+
746
+ def _auth_rejected(exc: _ur_err.HTTPError) -> str:
747
+ return (
748
+ f"endpoint is reachable but the server rejected the API key "
749
+ f"(HTTP {exc.code}) — check the key and auth type"
750
+ )
751
+
752
+ # ── Anthropic ────────────────────────────────────────────────
753
+ if ep.provider == "anthropic":
754
+ base, error = _safe_base_url(ep.base_url, "https://api.anthropic.com/v1")
755
+ if error:
756
+ return False, error
757
+ candidates = [f"{base}/models"]
758
+ if not base.endswith("/v1"):
759
+ candidates.append(f"{base}/v1/models")
760
+ last_err = "no models endpoint responded"
761
+ for url in candidates:
762
+ try:
763
+ req = _ur.Request(
764
+ url,
765
+ headers={
766
+ "x-api-key": ep.api_key,
767
+ "anthropic-version": "2023-06-01",
768
+ },
769
+ )
770
+ with _open(req) as resp:
771
+ if resp.status == 200:
772
+ return True, f"HTTP 200 · {url}"
773
+ except _ur_err.HTTPError as exc:
774
+ if exc.code in (401, 403):
775
+ # Same key on every candidate — auth failure is final.
776
+ return False, f"{_auth_rejected(exc)} ({url})"
777
+ hint = " — check base_url (should end in /v1)" if exc.code == 404 else ""
778
+ last_err = f"reachable but returned HTTP {exc.code} ({url}){hint}"
779
+ except Exception as exc:
780
+ return False, f"unreachable — {type(exc).__name__}: {exc}"[:140]
781
+ return False, last_err
782
+
783
+ # ── OpenAI-compatible ────────────────────────────────────────
784
+ base, error = _safe_base_url(ep.base_url, "https://api.openai.com/v1")
785
+ if error:
786
+ return False, error
787
+ candidates = [f"{base}/models"]
788
+ if not base.endswith("/v1"):
789
+ candidates.append(f"{base}/v1/models")
790
+
791
+ for url in candidates:
792
+ try:
793
+ req = _ur.Request(
794
+ url, headers={"Authorization": f"Bearer {ep.api_key}"}
795
+ )
796
+ with _open(req) as resp:
797
+ if resp.status == 200:
798
+ return True, f"HTTP 200 · {url}"
799
+ except _ur_err.HTTPError as exc:
800
+ if exc.code in (401, 403):
801
+ # Bad key on /models means chat would fail the same way.
802
+ return False, f"{_auth_rejected(exc)} ({url})"
803
+ except Exception as exc:
804
+ # Genuinely unreachable — chat probe below would only repeat it.
805
+ return False, f"unreachable — {type(exc).__name__}: {exc}"[:140]
806
+
807
+ # /models missing or blocked (404/405/501…) — probe the real call.
808
+ try:
809
+ payload = json.dumps({
810
+ "model": ep.model,
811
+ "messages": [{"role": "user", "content": "ping"}],
812
+ "max_tokens": 1,
813
+ }).encode()
814
+ chat_url = f"{base}/chat/completions"
815
+ req = _ur.Request(
816
+ chat_url,
817
+ data=payload,
818
+ headers={
819
+ "Authorization": f"Bearer {ep.api_key}",
820
+ "Content-Type": "application/json",
821
+ },
822
+ method="POST",
823
+ )
824
+ with _open(req) as resp:
825
+ if resp.status == 200:
826
+ return True, f"chat/completions OK · {chat_url}"
827
+ return False, f"reachable but returned HTTP {resp.status} (chat/completions)"
828
+ except _ur_err.HTTPError as exc:
829
+ if exc.code in (401, 403):
830
+ return False, f"{_auth_rejected(exc)} (chat/completions)"
831
+ hint = " — check base_url (should end in /v1)" if exc.code == 404 else ""
832
+ return False, f"reachable but returned HTTP {exc.code} (chat/completions){hint}"
833
+ except Exception as exc:
834
+ return False, f"unreachable — {type(exc).__name__}: {exc}"[:140]
835
+
836
+
837
+ def test_endpoints() -> str:
838
+ """Probe every configured endpoint and render status cards.
839
+
840
+ Built-in providers (Gemini/Grok) whose key is not set are skipped with
841
+ a ``⏭️ key not set`` note instead of being probed (a probe would just
842
+ fail with 401 / an auth error).
843
+ """
844
+ eps = discover_endpoints()
845
+
846
+ cards = []
847
+ for ep in eps:
848
+ if ep.builtin and not ep.api_key:
849
+ cards.append(
850
+ f'<div class="endpoint-card">'
851
+ f'<div class="endpoint-name">{html.escape(ep.name)}'
852
+ f'<span class="endpoint-badge">{html.escape(ep.provider)}</span></div>'
853
+ f'<div class="endpoint-meta"><code>{html.escape(ep.model)}</code>'
854
+ f' · {html.escape(ep.base_url or "default URL")} · key {html.escape(ep.masked_key)}</div>'
855
+ f'<div class="endpoint-meta" style="color:var(--text-muted);font-weight:700">'
856
+ f'⏭️ key not set (add GEMINI_API_KEY / GROQ_API_KEY)</div>'
857
+ f'</div>'
858
+ )
859
+ continue
860
+ ok, detail = _probe_endpoint(ep)
861
+ status_color = "#16a34a" if ok else "#dc2626"
862
+ cards.append(
863
+ f'<div class="endpoint-card">'
864
+ f'<div class="endpoint-name">{html.escape(ep.name)}'
865
+ f'<span class="endpoint-badge">{html.escape(ep.provider)}</span></div>'
866
+ f'<div class="endpoint-meta"><code>{html.escape(ep.model)}</code>'
867
+ f' · {html.escape(ep.base_url or "default URL")} · key {html.escape(ep.masked_key)}</div>'
868
+ f'<div class="endpoint-meta" style="color:{status_color};font-weight:700">'
869
+ f'{"✅" if ok else "❌"} {html.escape(detail)}</div>'
870
+ f'</div>'
871
+ )
872
+ return '<div>' + "".join(cards) + '</div>'
873
+
874
+
875
+ # ─── Helpers ─────────────────────────────────────────────────────────────────
876
+
877
+
878
+ def _get_deploy_info() -> tuple[str, str]:
879
+ """Return Git commit hash and deploy timestamp for the footer."""
880
+ commit = "unknown"
881
+ try:
882
+ result = subprocess.run(
883
+ ["git", "rev-parse", "--short", "HEAD"],
884
+ capture_output=True, text=True, timeout=5,
885
+ )
886
+ if result.returncode == 0:
887
+ commit = result.stdout.strip()
888
+ except Exception:
889
+ pass
890
+ ts = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
891
+ return commit, ts
892
+
893
+
894
+ # ─── Gradio callbacks ───────────────────────────────────────────────────────
895
+
896
+
897
+ # _prune_db replaced with direct _cleanup_db() calls below
898
+
899
+
900
+ def run_review(repo: str, pr_number: int, endpoint_name: str = "", progress=gr.Progress()):
901
+ """Run the review pipeline up to human-in-the-loop interrupt."""
902
+ if not repo or "/" not in repo:
903
+ yield [None, None, None, None, None, None], "❌ Enter a repo in `owner/name` format."
904
+ return
905
+
906
+ endpoint_name = _normalize_endpoint_name(endpoint_name)
907
+
908
+ # Fail fast on an unknown endpoint name (allow_custom_value lets any
909
+ # string through the dropdown; the reviewer nodes would otherwise
910
+ # swallow the ValueError and report a confusing empty review).
911
+ if endpoint_name:
912
+ from backend.integrations.endpoints import get_endpoint
913
+
914
+ ep = get_endpoint(endpoint_name)
915
+ if ep is None:
916
+ yield [None, None, None, None, None, None], (
917
+ f"❌ Endpoint '{endpoint_name}' not found — pick one from "
918
+ "the list or add it in the form above."
919
+ )
920
+ return
921
+ if ep.builtin and not ep.api_key:
922
+ key_var = "GEMINI_API_KEY" if ep.name == "Gemini" else "GROQ_API_KEY"
923
+ yield [None, None, None, None, None, None], (
924
+ f"❌ Endpoint '{ep.name}' is selected but its key is not set — "
925
+ f"add `{key_var}` as a Space secret, or add a custom endpoint "
926
+ "in the form above."
927
+ )
928
+ return
929
+
930
+ _cleanup_db()
931
+
932
+ progress(0.1, desc="Building graph…")
933
+
934
+ t0 = time.time()
935
+ try:
936
+ state, config, cost_summary, ragas_out, _ragas_inputs = _build_and_stream(
937
+ repo.strip(), int(pr_number), endpoint_name, ragas_background=True,
938
+ )
939
+ except Exception as exc:
940
+ log_error_to_backends(exc, context={"source": "gradio_ui", "phase": "run_review", "repo": repo, "pr_number": pr_number})
941
+ yield ([None, None, None, None, None, None], f"❌ Review failed: {exc}")
942
+ return
943
+
944
+ duration = time.time() - t0
945
+
946
+ tasks = state.tasks
947
+ values = state.values
948
+
949
+ if not tasks:
950
+ yield [None, None, None, None, None, None], "ℹ️ Review completed without findings."
951
+ return
952
+
953
+ verdict: Verdict | None = values.get("verdict")
954
+ findings: list = values.get("final_findings", [])
955
+
956
+ progress(0.8, desc="Formatting results…")
957
+
958
+ verdict_html = _format_verdict(verdict)
959
+ if isinstance(ragas_out, str):
960
+ ragas_task_id = ragas_out
961
+ ragas_html = RAGAS_PENDING_HTML
962
+ else:
963
+ ragas_task_id = ""
964
+ ragas_html = _format_ragas_scores(ragas_out)
965
+ findings_html = _format_findings_table(findings)
966
+ count_html = _format_findings_count(findings)
967
+ # Strip non-serializable callbacks before saving config to state
968
+ config_json = json.dumps(
969
+ {k: v for k, v in config.items() if k != "callbacks"}
970
+ )
971
+
972
+ run_summary_html = _format_run_summary(
973
+ repo.strip(), pr_number, endpoint_name, duration, cost_summary,
974
+ )
975
+
976
+ yield (
977
+ [run_summary_html, verdict_html, findings_html, count_html, ragas_html, config_json, ragas_task_id],
978
+ None,
979
+ )
980
+
981
+
982
+ def resume_review(config_json: str, action: str, progress=gr.Progress()):
983
+ """Resume the paused graph with approve/reject."""
984
+ if not config_json:
985
+ return "ℹ️ No pending review to resume. Run a review first."
986
+
987
+ try:
988
+ config = json.loads(config_json)
989
+ if not isinstance(config, dict):
990
+ raise ValueError("pending review state must be a JSON object")
991
+ except (TypeError, ValueError, json.JSONDecodeError) as exc:
992
+ return f"❌ Invalid pending review state: {html.escape(str(exc))}"
993
+ graph = build_graph(DB_PATH)
994
+ handler = get_langfuse_handler()
995
+ cost_tracker = TokenCostCallback()
996
+ callbacks = [cost_tracker]
997
+ if handler:
998
+ callbacks.append(handler)
999
+ config.setdefault("callbacks", []).extend(callbacks)
1000
+
1001
+ progress(0.3, desc=f"Processing {action}…")
1002
+
1003
+ try:
1004
+ graph.invoke(Command(resume={"action": action}), config)
1005
+ final_state = graph.get_state(config)
1006
+ approved = final_state.values.get("human_approved")
1007
+ msg = (
1008
+ f"✅ Review **approved**! Findings posted to GitHub."
1009
+ if approved
1010
+ else "❌ Review **rejected**. No comments posted."
1011
+ )
1012
+ if cost_tracker.usage:
1013
+ msg += f" _{cost_tracker.summary()}_"
1014
+ except Exception as exc:
1015
+ log_error_to_backends(exc, context={"source": "gradio_ui", "phase": "resume_review", "action": action})
1016
+ msg = f"❌ Error: {exc}"
1017
+ finally:
1018
+ # Close the checkpointer connection and ship any queued scores.
1019
+ conn = getattr(graph, "_opencodereview_conn", None)
1020
+ if conn:
1021
+ conn.close()
1022
+ flush_langfuse()
1023
+ return msg
1024
+
1025
+
1026
+ def run_smoke(progress=gr.Progress()):
1027
+ """Run the synthetic smoke test."""
1028
+ _cleanup_db()
1029
+
1030
+ progress(0.1, desc="Building graph…")
1031
+ graph = build_graph(DB_PATH)
1032
+ thread_id = str(uuid.uuid4())
1033
+ prompt_versions = {
1034
+ "correctness": "v1",
1035
+ "security": "v1",
1036
+ "test_coverage": "v1",
1037
+ "aggregator": "v1",
1038
+ }
1039
+ cost_tracker = TokenCostCallback()
1040
+ metadata = build_run_metadata(
1041
+ source="gradio_ui", repo="demo-org/demo-repo", pr_number=1,
1042
+ session_id=thread_id,
1043
+ prompt_versions=prompt_versions,
1044
+ )
1045
+ config: dict = {
1046
+ "configurable": {"thread_id": f"smoke-web-{thread_id}"},
1047
+ "metadata": metadata,
1048
+ }
1049
+
1050
+ progress(0.3, desc="Running on synthetic data…")
1051
+ with langfuse_trace(
1052
+ trace_name="opencodereview/smoke-test",
1053
+ tags=["gradio_ui", "smoke", "demo-org/demo-repo"],
1054
+ session_id=thread_id,
1055
+ metadata={"prompt_versions": prompt_versions},
1056
+ ) as handler:
1057
+ callbacks = [cost_tracker]
1058
+ if handler:
1059
+ callbacks.append(handler)
1060
+ config["callbacks"] = callbacks
1061
+
1062
+ try:
1063
+ list(graph.stream(SYNTHETIC_STATE, config))
1064
+ except Exception as exc:
1065
+ log_error_to_backends(exc, context={"source": "gradio_ui", "phase": "smoke_stream"})
1066
+ logger.exception("Smoke test failed: %s", exc)
1067
+ raise
1068
+
1069
+ state = graph.get_state(config)
1070
+ tasks = state.tasks
1071
+
1072
+ # Close the checkpointer connection and ship any queued Langfuse scores.
1073
+ conn = getattr(graph, "_opencodereview_conn", None)
1074
+ if conn:
1075
+ conn.close()
1076
+ flush_langfuse()
1077
+
1078
+ if not tasks:
1079
+ yield [None, None, None, None, None], "ℹ️ Smoke test completed without findings."
1080
+ return
1081
+
1082
+ verdict: Verdict | None = state.values.get("verdict")
1083
+ findings: list = state.values.get("final_findings", [])
1084
+
1085
+ progress(0.8, desc="Formatting…")
1086
+ verdict_html = _format_verdict(verdict)
1087
+ findings_html = _format_findings_table(findings)
1088
+ # Strip non-serializable callbacks before saving config to state
1089
+ config_json = json.dumps(
1090
+ {k: v for k, v in config.items() if k != "callbacks"}
1091
+ )
1092
+ cost_html = f'<p style="margin-top:8px;font-size:0.85em;color:var(--text-muted)">{cost_tracker.summary()}</p>'
1093
+
1094
+ yield [verdict_html, findings_html + cost_html, config_json, verdict_html, findings_html], None
1095
+
1096
+
1097
+ # ─── UI ──────────────────────────────────────────────────────────────────────
1098
+
1099
+ CSS = """
1100
+ /* ── CSS Custom Properties (light mode) ───────────────────────────── */
1101
+ :root {
1102
+ --bg-page: #f1f5f9;
1103
+ --bg-card: #ffffff;
1104
+ --bg-card-alt: #f8fafc;
1105
+ --bg-table-header: #f1f5f9;
1106
+ --border-color: #e2e8f0;
1107
+ --text-primary: #0f172a;
1108
+ --text-secondary: #475569;
1109
+ --text-muted: #64748b;
1110
+ --text-footer: #94a3b8;
1111
+ --spinner-track: #e2e8f0;
1112
+ --accent: #52525b;
1113
+ --accent-soft: rgba(82, 82, 91, 0.10);
1114
+ --glass: rgba(255, 255, 255, 0.55);
1115
+ --glass-border: rgba(15, 23, 42, 0.10);
1116
+ --glass-field: rgba(255, 255, 255, 0.72);
1117
+ --glass-edge: rgba(15, 23, 42, 0.18);
1118
+ --glass-hover: rgba(15, 23, 42, 0.05);
1119
+ --glass-highlight: inset 0 1px 0 rgba(255, 255, 255, 0.8);
1120
+ --radius: 14px;
1121
+ --shadow: 0 1px 2px rgba(15, 23, 42, 0.05), 0 10px 30px rgba(15, 23, 42, 0.06);
1122
+ }
1123
+
1124
+ /* ── Dark Mode — true black, glass surfaces, no blue ────────────── */
1125
+ body.dark {
1126
+ --bg-page: #000000;
1127
+ --bg-card: #0a0a0a;
1128
+ --bg-card-alt: #101010;
1129
+ --bg-table-header: #0a0a0a;
1130
+ --border-color: #1f1f1f;
1131
+ --text-primary: #f5f5f5;
1132
+ --text-secondary: #d4d4d4;
1133
+ --text-muted: #8a8a8a;
1134
+ --text-footer: #5c5c5c;
1135
+ --spinner-track: #1c1c1c;
1136
+ --accent: #a1a1aa;
1137
+ --accent-soft: rgba(255, 255, 255, 0.07);
1138
+ --shadow: none;
1139
+ --glass: rgba(255, 255, 255, 0.035);
1140
+ --glass-border: rgba(255, 255, 255, 0.09);
1141
+ --glass-field: rgba(255, 255, 255, 0.045);
1142
+ --glass-edge: rgba(255, 255, 255, 0.12);
1143
+ --glass-hover: rgba(255, 255, 255, 0.12);
1144
+ --glass-highlight: inset 0 1px 0 rgba(255, 255, 255, 0.07);
1145
+ }
1146
+ /* Glass buttons — replace Gradio's solid blue primary / gray secondary
1147
+ with frosted neutral surfaces (scoped to the app area, not Gradio's
1148
+ own footer controls). */
1149
+ .gradio-container main button.primary {
1150
+ background: var(--glass-hover) !important;
1151
+ color: var(--text-primary) !important;
1152
+ border: 1px solid var(--glass-edge) !important;
1153
+ border-radius: 12px !important;
1154
+ font-weight: 600 !important;
1155
+ box-shadow: var(--glass-highlight) !important;
1156
+ backdrop-filter: blur(12px) !important;
1157
+ transition: background 0.18s ease, border-color 0.18s ease !important;
1158
+ }
1159
+ .gradio-container main button.primary:hover {
1160
+ background: var(--accent-soft) !important;
1161
+ border-color: var(--text-muted) !important;
1162
+ }
1163
+ .gradio-container main button:not(.primary) {
1164
+ background: var(--glass) !important;
1165
+ color: var(--text-secondary) !important;
1166
+ border: 1px solid var(--glass-border) !important;
1167
+ border-radius: 12px !important;
1168
+ font-weight: 500 !important;
1169
+ box-shadow: var(--glass-highlight) !important;
1170
+ backdrop-filter: blur(10px) !important;
1171
+ transition: background 0.18s ease, color 0.18s ease, border-color 0.18s ease !important;
1172
+ }
1173
+ .gradio-container main button:not(.primary):hover {
1174
+ background: var(--glass-hover) !important;
1175
+ color: var(--text-primary) !important;
1176
+ border-color: var(--glass-edge) !important;
1177
+ }
1178
+ /* Frosted input fields in both themes. */
1179
+ .gradio-container input, .gradio-container textarea, .gradio-container select {
1180
+ background-color: var(--glass-field) !important;
1181
+ border-color: var(--glass-edge) !important;
1182
+ backdrop-filter: blur(8px);
1183
+ }
1184
+ /* Fill the dropdown wrapper so it reads as one glass field. */
1185
+ .gradio-container .glass-dropdown .wrap {
1186
+ background-color: var(--glass-field) !important;
1187
+ border-color: var(--glass-edge) !important;
1188
+ backdrop-filter: blur(8px);
1189
+ }
1190
+ body.dark .gradio-container {
1191
+ background: var(--bg-page) !important;
1192
+ }
1193
+ /* Blend Gradio's component panels into the page: no boxes, no
1194
+ borders — only inputs keep a faint field tint so they stay legible. */
1195
+ body.dark .block,
1196
+ body.dark .form,
1197
+ body.dark .tabs,
1198
+ body.dark .tabitem {
1199
+ background: transparent !important;
1200
+ border-color: transparent !important;
1201
+ box-shadow: none !important;
1202
+ }
1203
+ body.dark .tab-nav {
1204
+ border-bottom: 1px solid var(--border-color) !important;
1205
+ background: transparent !important;
1206
+ }
1207
+ body.dark input, body.dark textarea, body.dark select {
1208
+ background-color: var(--glass-field) !important;
1209
+ color: var(--text-primary) !important;
1210
+ border-color: var(--glass-edge) !important;
1211
+ backdrop-filter: blur(8px);
1212
+ }
1213
+ body.dark .gradio-container .glass-dropdown .wrap {
1214
+ color: var(--text-primary) !important;
1215
+ }
1216
+ body.dark label { color: var(--text-secondary) !important; }
1217
+ /* Field labels render as small pills in the Soft theme — restyle them
1218
+ as quiet glass chips instead of the default saturated background. */
1219
+ label span[data-testid="block-info"],
1220
+ span.has-info,
1221
+ span[data-testid="block-info"] {
1222
+ background: var(--glass) !important;
1223
+ color: var(--text-primary) !important;
1224
+ border: 1px solid var(--glass-border);
1225
+ border-radius: 9px;
1226
+ padding: 2px 10px;
1227
+ font-weight: 500 !important;
1228
+ backdrop-filter: blur(8px);
1229
+ box-shadow: var(--glass-highlight);
1230
+ }
1231
+ body.dark button:not(.lg) { color: var(--text-primary) !important; }
1232
+ body.dark .footer { color: var(--text-footer) !important; }
1233
+ body.dark details summary { color: var(--text-secondary) !important; }
1234
+ body.dark [data-testid="block-info"] { color: var(--text-primary) !important; }
1235
+
1236
+ /* ── Global ──────────────────────────────────────────────────────── */
1237
+ /* Component forms blend into the page in both themes; inputs keep
1238
+ their own field background so they stay clearly interactive. */
1239
+ .gradio-container .form {
1240
+ background: transparent !important;
1241
+ border: none !important;
1242
+ box-shadow: none !important;
1243
+ }
1244
+ .gradio-container {
1245
+ background: radial-gradient(1200px 500px at 20% -10%, #eef2ff66, transparent 60%),
1246
+ radial-gradient(1000px 400px at 90% 10%, #e0f2fe55, transparent 55%),
1247
+ var(--bg-page) !important;
1248
+ }
1249
+ .gradio-container { max-width: 1024px; margin: 0 auto; }
1250
+ .footer { text-align: center; color: var(--text-footer); font-size: 0.85em; padding: 22px 0; }
1251
+ details { margin-top: 8px; }
1252
+ details summary { cursor: pointer; color: var(--text-secondary); font-weight: 500; }
1253
+ code { background: var(--bg-card-alt); padding: 1px 6px; border-radius: 6px; font-size: 0.92em; }
1254
+ .muted { color: var(--text-muted) !important; }
1255
+ .small { font-size: 0.85em; }
1256
+
1257
+ /* ── Hero ────────────────────────────────────────────────────────── */
1258
+ .hero { display: flex; align-items: center; gap: 16px; padding: 8px 0 4px; }
1259
+ .hero-icon {
1260
+ font-size: 1.5em; width: 48px; height: 48px; display: flex; align-items: center;
1261
+ justify-content: center; border-radius: 14px;
1262
+ background: var(--glass);
1263
+ border: 1px solid var(--glass-border);
1264
+ box-shadow: var(--glass-highlight);
1265
+ backdrop-filter: blur(12px);
1266
+ }
1267
+ .hero-title { margin: 0; font-size: 1.35em; font-weight: 650; letter-spacing: -0.015em; color: var(--text-primary); }
1268
+ .hero-sub { margin: 2px 0 0; color: var(--text-muted); font-size: 0.95em; }
1269
+
1270
+ /* ── Cards ───────────────────────────────────────────────────────── */
1271
+ .ocr-card {
1272
+ background: var(--glass);
1273
+ border: 1px solid var(--glass-border);
1274
+ border-radius: var(--radius); padding: 16px 20px; margin-top: 12px;
1275
+ box-shadow: var(--glass-highlight);
1276
+ backdrop-filter: blur(14px);
1277
+ }
1278
+ .card-title { font-weight: 600; color: var(--text-primary); margin-bottom: 12px; font-size: 1.0em; letter-spacing: 0.01em; }
1279
+ .chips-row { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }
1280
+
1281
+ /* ── Chips / badges ──────────────────────────────────────────────── */
1282
+ .key-chip {
1283
+ display: inline-block; padding: 3px 12px; border-radius: 999px;
1284
+ font-size: 0.82em; font-weight: 500; border: 1px solid var(--glass-border);
1285
+ background: var(--glass); color: var(--text-secondary);
1286
+ backdrop-filter: blur(8px);
1287
+ }
1288
+ .key-chip.ok { color: #4ade80; border-color: rgba(74, 222, 128, 0.25); background: rgba(74, 222, 128, 0.07); }
1289
+ .sev-chip {
1290
+ display: inline-block; padding: 3px 12px; border-radius: 999px;
1291
+ font-size: 0.82em; font-weight: 600; border: 1px solid var(--glass-border);
1292
+ background: var(--glass);
1293
+ }
1294
+
1295
+ /* ── Endpoint cards ──────────────────────────────────────────────── */
1296
+ .endpoint-card {
1297
+ border: 1px solid var(--glass-border); border-radius: 12px;
1298
+ padding: 10px 14px; margin-bottom: 8px; background: var(--glass);
1299
+ backdrop-filter: blur(10px);
1300
+ }
1301
+ .endpoint-name { font-weight: 600; color: var(--text-primary); display: flex; gap: 8px; align-items: center; }
1302
+ .endpoint-badge {
1303
+ font-size: 0.7em; font-weight: 600; text-transform: uppercase; letter-spacing: 0.05em;
1304
+ padding: 2px 8px; border-radius: 999px; color: var(--text-muted);
1305
+ background: var(--accent-soft); border: 1px solid var(--glass-border);
1306
+ }
1307
+ .endpoint-meta { margin-top: 4px; font-size: 0.88em; color: var(--text-secondary); }
1308
+
1309
+ /* ── Run summary ─────────────────────────────────────────────────── */
1310
+ .run-summary { display: flex; gap: 20px; flex-wrap: wrap; align-items: center; font-size: 0.92em; color: var(--text-secondary); }
1311
+ .run-summary b { color: var(--text-primary); }
1312
+
1313
+ /* ── Verdict ─────────────────────────────────────────────────────── */
1314
+ .verdict-card { border-left: 5px solid var(--accent); }
1315
+ .verdict-head { display: flex; align-items: center; gap: 12px; margin-bottom: 10px; flex-wrap: wrap; }
1316
+ .verdict-icon { font-size: 1.8em; }
1317
+ .verdict-reco { font-size: 1.35em; font-weight: 800; letter-spacing: 0.02em; }
1318
+ .verdict-score { margin-left: auto; font-size: 1.05em; color: var(--text-secondary); }
1319
+ .verdict-score b { color: var(--text-primary); font-size: 1.25em; }
1320
+ .verdict-summary { margin: 10px 0 0; color: var(--text-secondary); line-height: 1.55; }
1321
+ .score-track { height: 10px; background: var(--spinner-track); border-radius: 999px; overflow: hidden; margin-top: 4px; }
1322
+ .score-fill { height: 100%; border-radius: 999px; transition: width 0.7s ease; }
1323
+
1324
+ /* ── RAGAS metrics ───────────────────────────────────────────────── */
1325
+ .metric-row { display: flex; justify-content: space-between; align-items: center; margin: 8px 0 4px; }
1326
+ .metric-label { font-weight: 600; color: var(--text-secondary); font-size: 0.93em; }
1327
+ .metric-value { font-weight: 800; font-size: 0.98em; }
1328
+ .metric-track { height: 8px; background: var(--spinner-track); border-radius: 999px; overflow: hidden; }
1329
+ .metric-fill { height: 100%; border-radius: 999px; transition: width 0.6s ease; }
1330
+ .tip { cursor: help; font-size: 0.85em; }
1331
+
1332
+ /* ── Findings table ──────────────────────────────────────────────── */
1333
+ table { width: 100%; border-collapse: collapse; font-size: 0.9em; }
1334
+ thead tr { background: var(--bg-table-header); border-bottom: 2px solid var(--border-color); }
1335
+ th { padding: 10px 12px; text-align: left; color: var(--text-primary); }
1336
+ td { padding: 10px 12px; color: var(--text-secondary); border-bottom: 1px solid var(--border-color); vertical-align: top; }
1337
+ tbody tr:hover { background: var(--bg-card-alt); }
1338
+
1339
+ /* ── Theme toggle ────────────────────────────────────────────────── */
1340
+ #theme-toggle-btn {
1341
+ float: right; margin-top: 18px !important; background: var(--glass) !important;
1342
+ border: 1px solid var(--glass-border) !important; border-radius: 10px !important;
1343
+ padding: 4px 10px !important; font-size: 1.1em !important; min-width: 44px !important;
1344
+ transition: all 0.2s ease !important;
1345
+ box-shadow: var(--glass-highlight) !important;
1346
+ backdrop-filter: blur(10px) !important;
1347
+ }
1348
+ #theme-toggle-btn:hover { background: var(--accent-soft) !important; border-color: var(--glass-edge) !important; }
1349
+
1350
+ /* ── Loading spinner ─────────────────────────────────��───────────── */
1351
+ @keyframes spin { to { transform: rotate(360deg); } }
1352
+ .loading-spinner {
1353
+ display: flex; align-items: center; gap: 12px; padding: 24px 0; justify-content: center;
1354
+ }
1355
+ .loading-spinner .spinner {
1356
+ width: 24px; height: 24px; border: 3px solid var(--spinner-track);
1357
+ border-top-color: var(--accent); border-radius: 50%; animation: spin 0.8s linear infinite;
1358
+ }
1359
+ .loading-spinner .label { color: var(--text-muted); font-size: 0.95em; }
1360
+ """
1361
+
1362
+ JS_RESTORE_THEME = """
1363
+ () => {
1364
+ // Single source of truth for the theme: the body.dark class that
1365
+ // Gradio itself also uses for dark mode. Our own key in localStorage
1366
+ // only records an explicit choice; when absent, whatever Gradio picked
1367
+ // (OS preference) is left untouched.
1368
+ const saved = localStorage.getItem("ocr-theme");
1369
+ if (saved === "dark") document.body.classList.add("dark");
1370
+ if (saved === "light") document.body.classList.remove("dark");
1371
+ const btn = document.querySelector("#theme-toggle-btn");
1372
+ if (btn) btn.textContent = document.body.classList.contains("dark") ? "☀️" : "🌙";
1373
+ }
1374
+ """
1375
+
1376
+ JS_TOGGLE_THEME = """
1377
+ () => {
1378
+ const isDark = document.body.classList.toggle("dark");
1379
+ localStorage.setItem("ocr-theme", isDark ? "dark" : "light");
1380
+ const btn = document.querySelector("#theme-toggle-btn");
1381
+ if (btn) btn.textContent = isDark ? "☀️" : "🌙";
1382
+ return [];
1383
+ }
1384
+ """
1385
+
1386
+ # ── Initialise observability backends ────────────────────────────────
1387
+ # Wrap in try/except so a failure here doesn't prevent the UI from loading.
1388
+ # This is important on Hugging Face Spaces where dependencies may have
1389
+ # version incompatibilities.
1390
+ try:
1391
+ _init_observability_ui()
1392
+ except Exception as exc:
1393
+ logger.warning("Observability initialisation failed (non-fatal): %s", exc)
1394
+
1395
+ with gr.Blocks(title="OpenCodeReview") as demo:
1396
+ demo.load(js=JS_RESTORE_THEME)
1397
+
1398
+ # Discover configured endpoints once — reused by the hero chip and the
1399
+ # health accordion. (The dropdown builds its grouped choices live via
1400
+ # endpoints.dropdown_choices() so built-ins + added endpoints stay in sync.)
1401
+ _configured_endpoints = discover_endpoints()
1402
+
1403
+ with gr.Row():
1404
+ with gr.Column(scale=4):
1405
+ gr.HTML(
1406
+ '<div class="hero">'
1407
+ '<div class="hero-icon">◈</div>'
1408
+ '<div>'
1409
+ '<h1 class="hero-title">OpenCodeReview</h1>'
1410
+ '<p class="hero-sub">AI-powered PR review with human-in-the-loop approval</p>'
1411
+ f'<div class="chips-row" style="margin-top:8px">'
1412
+ f'<span class="key-chip ok">{len(_configured_endpoints)} endpoint'
1413
+ f'{"s" if len(_configured_endpoints) != 1 else ""} configured</span>'
1414
+ '<span class="key-chip">Built-ins: Gemini · Groq</span>'
1415
+ '<span class="key-chip">Bring your own keys</span>'
1416
+ '</div>'
1417
+ '</div>'
1418
+ '</div>'
1419
+ )
1420
+ with gr.Column(scale=1, min_width=60):
1421
+ theme_toggle = gr.Button("🌙", elem_id="theme-toggle-btn", size="sm", min_width=50, visible=True)
1422
+ theme_toggle.click(js=JS_TOGGLE_THEME)
1423
+
1424
+ # ── State ────────────────────────────────────────────────────────────
1425
+ pr_state = gr.State()
1426
+ smoke_state = gr.State()
1427
+ # Id of this session's background RAGAS task — the gr.Timer below polls
1428
+ # it so review results render immediately instead of waiting on RAGAS.
1429
+ ragas_task_state = gr.State(value="")
1430
+
1431
+ # ── Tab: Review ──────────────────────────────────────────────────
1432
+ with gr.Tab("Review"):
1433
+ with gr.Row():
1434
+ repo_input = gr.Textbox(
1435
+ label="Repository",
1436
+ placeholder="owner/repo (e.g. psf/requests)",
1437
+ scale=3,
1438
+ )
1439
+ pr_input = gr.Number(
1440
+ label="PR #",
1441
+ value=1,
1442
+ minimum=1,
1443
+ precision=0,
1444
+ scale=1,
1445
+ )
1446
+
1447
+ with gr.Row():
1448
+ endpoint_input = gr.Dropdown(
1449
+ choices=[""] + dropdown_choices(),
1450
+ value=AUTO_ENDPOINT_CHOICE,
1451
+ label="LLM Endpoint",
1452
+ info=(
1453
+ "Built-ins: Gemini and Groq (Groq serves Llama models). "
1454
+ "Defaults to Gemini → Groq fallback."
1455
+ ),
1456
+ # Grouped optgroup choices make Gradio's strict membership
1457
+ # check reject values that sit inside a group (e.g. a custom
1458
+ # endpoint registered moments ago). allow_custom_value lets
1459
+ # any registered endpoint name pass through; unknown names
1460
+ # still fail with a clear error at review time.
1461
+ allow_custom_value=True,
1462
+ scale=3,
1463
+ elem_classes=["glass-dropdown"],
1464
+ )
1465
+ test_selected_btn = gr.Button("Test selected", size="sm", scale=1)
1466
+ endpoint_test_msg = gr.Markdown()
1467
+
1468
+ def on_test_selected(endpoint_name):
1469
+ """Probe the currently selected endpoint (built-in or custom)."""
1470
+ endpoint_name = _normalize_endpoint_name(endpoint_name)
1471
+ if not endpoint_name:
1472
+ return (
1473
+ "ℹ️ Leave the endpoint empty for auto (Gemini → Groq fallback), "
1474
+ "or pick one and test it here."
1475
+ )
1476
+ from backend.integrations.endpoints import get_endpoint
1477
+
1478
+ ep = get_endpoint(endpoint_name)
1479
+ if ep is None:
1480
+ return f"❌ Endpoint '{html.escape(endpoint_name)}' not found — add it in the form below first."
1481
+ if ep.builtin and not ep.api_key:
1482
+ key_var = "GEMINI_API_KEY" if ep.name == "Gemini" else "GROQ_API_KEY"
1483
+ return (
1484
+ f"⏭️ **{html.escape(ep.name)}** key is not set — add `{html.escape(key_var)}` "
1485
+ "as a Space secret to test it."
1486
+ )
1487
+ ok, detail = _probe_endpoint(ep)
1488
+ icon = "✅" if ok else "❌"
1489
+ return f"{icon} **{html.escape(ep.name)}** (`{html.escape(ep.model)}`): {html.escape(detail)}"
1490
+
1491
+ test_selected_btn.click(
1492
+ fn=on_test_selected,
1493
+ inputs=[endpoint_input],
1494
+ outputs=[endpoint_test_msg],
1495
+ )
1496
+
1497
+ # ── Add your own endpoint (BYO key) ─────────────────────────
1498
+ with gr.Accordion("Add a custom endpoint (BYO key)", open=False):
1499
+ with gr.Row():
1500
+ ep_name_input = gr.Textbox(
1501
+ label="Endpoint name",
1502
+ placeholder="e.g. My DeepSeek",
1503
+ scale=1,
1504
+ )
1505
+ ep_type_input = gr.Dropdown(
1506
+ choices=["openai", "anthropic", "google"],
1507
+ value="openai",
1508
+ label="Type",
1509
+ info="openai = any OpenAI-compatible API (DeepSeek, OpenRouter, Ollama…)",
1510
+ scale=1,
1511
+ elem_classes=["glass-dropdown"],
1512
+ )
1513
+ with gr.Row():
1514
+ ep_base_url_input = gr.Textbox(
1515
+ label="API endpoint (base URL)",
1516
+ placeholder="https://api.deepseek.com/v1 (optional for google)",
1517
+ scale=2,
1518
+ )
1519
+ ep_model_input = gr.Textbox(
1520
+ label="Model",
1521
+ placeholder="deepseek-chat / claude-sonnet-4-20250514 / gemini-3.1-flash",
1522
+ scale=2,
1523
+ )
1524
+ ep_api_key_input = gr.Textbox(
1525
+ label="API key",
1526
+ type="password",
1527
+ placeholder="sk-... (stored in memory only, never written to disk)",
1528
+ )
1529
+ with gr.Row():
1530
+ test_form_btn = gr.Button("Test this endpoint", size="sm")
1531
+ add_endpoint_btn = gr.Button("Save & use endpoint", variant="primary", size="sm")
1532
+ clear_endpoints_btn = gr.Button("Clear added endpoints", size="sm")
1533
+ endpoint_save_msg = gr.Markdown()
1534
+ session_endpoints_display = gr.HTML(value=_format_session_endpoints())
1535
+
1536
+ with gr.Row():
1537
+ run_btn = gr.Button("Run review", variant="primary", size="lg", scale=2)
1538
+ cancel_btn = gr.Button("Cancel", variant="stop", size="lg", visible=False)
1539
+
1540
+ loading_box = gr.HTML(
1541
+ '<div class="loading-spinner"><div class="spinner"></div>'
1542
+ '<span class="label">Running review pipeline...</span></div>',
1543
+ visible=False,
1544
+ )
1545
+ status_msg = gr.Markdown(visible=False)
1546
+
1547
+ with gr.Column(visible=False) as results_panel:
1548
+ run_summary_display = gr.HTML()
1549
+ verdict_display = gr.HTML()
1550
+ count_display = gr.HTML()
1551
+ findings_display = gr.HTML()
1552
+ ragas_display = gr.HTML()
1553
+
1554
+ with gr.Row():
1555
+ approve_btn = gr.Button("Approve & post", variant="primary")
1556
+ reject_btn = gr.Button("Reject", variant="secondary")
1557
+
1558
+ resume_msg = gr.Markdown()
1559
+
1560
+ # ── Event wiring ──────────────────────────────────────────────
1561
+ def on_run_click(*args):
1562
+ """Generator that clears old state, runs review, shows results."""
1563
+ args = tuple(
1564
+ _normalize_endpoint_name(a) if isinstance(a, str) else a
1565
+ for a in args
1566
+ )
1567
+ # Yield initial loading state — must match the 12 outputs of
1568
+ # run_btn.click in order (loading_box, cancel_btn, run_btn,
1569
+ # status_msg, 5 result displays, pr_state, results_panel,
1570
+ # ragas_task_state).
1571
+ yield [
1572
+ gr.update(visible=True),
1573
+ gr.update(visible=True, variant="stop"),
1574
+ gr.update(visible=False),
1575
+ gr.update(visible=False, value=""),
1576
+ gr.update(value=""),
1577
+ *[None, None, None, None],
1578
+ None,
1579
+ gr.update(visible=False),
1580
+ gr.update(value=""),
1581
+ ]
1582
+
1583
+ for result, err in run_review(*args):
1584
+ if err:
1585
+ yield [
1586
+ gr.update(visible=False),
1587
+ gr.update(visible=False),
1588
+ gr.update(visible=True),
1589
+ gr.update(visible=True, value=err),
1590
+ gr.update(value=""),
1591
+ *[None, None, None, None],
1592
+ None,
1593
+ gr.update(visible=False),
1594
+ gr.update(value=""),
1595
+ ]
1596
+ else:
1597
+ run_summary_html, verdict_html, findings_html, count_html, ragas_html, config_json, ragas_task_id = result
1598
+ yield [
1599
+ gr.update(visible=False),
1600
+ gr.update(visible=False),
1601
+ gr.update(visible=True),
1602
+ gr.update(visible=False),
1603
+ gr.update(value=run_summary_html),
1604
+ gr.update(value=verdict_html),
1605
+ gr.update(value=count_html),
1606
+ gr.update(value=findings_html),
1607
+ gr.update(value=ragas_html),
1608
+ config_json,
1609
+ gr.update(visible=True),
1610
+ gr.update(value=ragas_task_id),
1611
+ ]
1612
+
1613
+ run_event = run_btn.click(
1614
+ fn=on_run_click,
1615
+ inputs=[repo_input, pr_input, endpoint_input],
1616
+ outputs=[
1617
+ loading_box,
1618
+ cancel_btn,
1619
+ run_btn,
1620
+ status_msg,
1621
+ run_summary_display,
1622
+ verdict_display,
1623
+ count_display,
1624
+ findings_display,
1625
+ ragas_display,
1626
+ pr_state,
1627
+ results_panel,
1628
+ ragas_task_state,
1629
+ ],
1630
+ )
1631
+ cancel_btn.click(fn=None, cancels=[run_event])
1632
+
1633
+ def on_approve(config_json):
1634
+ msg = resume_review(config_json, "approve")
1635
+ return gr.update(value=msg)
1636
+
1637
+ def on_reject(config_json):
1638
+ msg = resume_review(config_json, "reject")
1639
+ return gr.update(value=msg)
1640
+
1641
+ approve_btn.click(
1642
+ fn=on_approve,
1643
+ inputs=[pr_state],
1644
+ outputs=[resume_msg],
1645
+ )
1646
+ reject_btn.click(
1647
+ fn=on_reject,
1648
+ inputs=[pr_state],
1649
+ outputs=[resume_msg],
1650
+ )
1651
+
1652
+ # ── Background RAGAS polling ────────────────────────────────────
1653
+ # RAGAS scoring runs on a background thread so the review results
1654
+ # render immediately; this Timer polls for the finished scores and
1655
+ # swaps the "computing…" placeholder for the metric card.
1656
+ ragas_timer = gr.Timer(5, active=True)
1657
+
1658
+ def on_ragas_tick(task_id):
1659
+ """Render background RAGAS scores when the task finishes."""
1660
+ if not task_id:
1661
+ return gr.update(), gr.update()
1662
+ with _ragas_lock:
1663
+ entry = _ragas_tasks.get(task_id)
1664
+ if entry is None:
1665
+ return gr.update(), gr.update()
1666
+ if not entry.get("done"):
1667
+ # Stalled guard: give up after the timeout instead of
1668
+ # leaving the "computing…" placeholder forever.
1669
+ started = entry.get("started") or 0
1670
+ if time.time() - started > RAGAS_TIMEOUT_SECONDS:
1671
+ with _ragas_lock:
1672
+ _ragas_tasks.pop(task_id, None)
1673
+ return gr.update(value=RAGAS_FAILED_HTML), gr.update(value="")
1674
+ return gr.update(), gr.update()
1675
+ scores = entry.get("scores") or {}
1676
+ with _ragas_lock:
1677
+ _ragas_tasks.pop(task_id, None)
1678
+ if scores:
1679
+ html_out = _format_ragas_scores(scores)
1680
+ else:
1681
+ html_out = RAGAS_FAILED_HTML
1682
+ return gr.update(value=html_out), gr.update(value="")
1683
+
1684
+ ragas_timer.tick(
1685
+ fn=on_ragas_tick,
1686
+ inputs=[ragas_task_state],
1687
+ outputs=[ragas_display, ragas_task_state],
1688
+ )
1689
+
1690
+ # ── Add / clear custom endpoints ─────────────────────────────
1691
+ def on_add_endpoint(name, ptype, base_url, api_key, model):
1692
+ """Register the form values, refresh the dropdown, auto-select."""
1693
+ try:
1694
+ cfg = register_endpoint(name, ptype, api_key, base_url, model)
1695
+ choices = dropdown_choices()
1696
+ return (
1697
+ gr.update(choices=choices, value=cfg.name),
1698
+ f"✅ Saved **{cfg.name}** ({cfg.provider} / `{cfg.model}`) — "
1699
+ "it's selected above. Hit **▶ Run Review** to use it. "
1700
+ "Tip: use 🔌 Test endpoint connectivity (health tab) to check the key first.",
1701
+ _format_session_endpoints(),
1702
+ gr.update(value=""),
1703
+ gr.update(value=""),
1704
+ gr.update(value=""),
1705
+ gr.update(value=""),
1706
+ )
1707
+ except ValueError as exc:
1708
+ return (
1709
+ gr.update(),
1710
+ f"❌ {exc}",
1711
+ gr.update(),
1712
+ gr.update(),
1713
+ gr.update(),
1714
+ gr.update(),
1715
+ gr.update(),
1716
+ )
1717
+
1718
+ def on_clear_endpoints():
1719
+ """Remove all UI-added endpoints and reset the dropdown."""
1720
+ clear_session_endpoints()
1721
+ return (
1722
+ gr.update(choices=[""] + dropdown_choices(), value=AUTO_ENDPOINT_CHOICE),
1723
+ "🗑 Cleared — dropdown reset to the built-in default.",
1724
+ _format_session_endpoints(),
1725
+ )
1726
+
1727
+ add_endpoint_btn.click(
1728
+ fn=on_add_endpoint,
1729
+ inputs=[
1730
+ ep_name_input,
1731
+ ep_type_input,
1732
+ ep_base_url_input,
1733
+ ep_api_key_input,
1734
+ ep_model_input,
1735
+ ],
1736
+ outputs=[
1737
+ endpoint_input,
1738
+ endpoint_save_msg,
1739
+ session_endpoints_display,
1740
+ ep_name_input,
1741
+ ep_base_url_input,
1742
+ ep_api_key_input,
1743
+ ep_model_input,
1744
+ ],
1745
+ )
1746
+ clear_endpoints_btn.click(
1747
+ fn=on_clear_endpoints,
1748
+ outputs=[endpoint_input, endpoint_save_msg, session_endpoints_display],
1749
+ )
1750
+
1751
+ def on_test_form(name, ptype, base_url, api_key, model):
1752
+ """Probe the form values WITHOUT saving them to the registry."""
1753
+ name = (name or "").strip()
1754
+ model = (model or "").strip()
1755
+ api_key = (api_key or "").strip()
1756
+ base_url = (base_url or "").strip() or None
1757
+ if not (name and model and api_key):
1758
+ return (
1759
+ "❌ Fill in **name**, **model** and **API key** first "
1760
+ "(use `dummy` for keyless local servers)."
1761
+ )
1762
+ from backend.integrations.endpoints import SUPPORTED_PROVIDERS
1763
+
1764
+ if (ptype or "openai").strip().lower() not in SUPPORTED_PROVIDERS:
1765
+ return f"❌ Unsupported type — use one of {SUPPORTED_PROVIDERS}."
1766
+ cfg = EndpointConfig(
1767
+ name=name,
1768
+ provider=ptype,
1769
+ api_key=api_key,
1770
+ base_url=base_url,
1771
+ model=model,
1772
+ )
1773
+ ok, detail = _probe_endpoint(cfg)
1774
+ icon = "✅" if ok else "❌"
1775
+ if ok:
1776
+ return f"{icon} **{html.escape(name)}** (`{html.escape(model)}`) — {html.escape(detail)}"
1777
+ return f"{icon} **{html.escape(name)}** — {html.escape(detail)}"
1778
+
1779
+ test_form_btn.click(
1780
+ fn=on_test_form,
1781
+ inputs=[
1782
+ ep_name_input,
1783
+ ep_type_input,
1784
+ ep_base_url_input,
1785
+ ep_api_key_input,
1786
+ ep_model_input,
1787
+ ],
1788
+ outputs=[endpoint_save_msg],
1789
+ )
1790
+
1791
+ # ── Tab: Smoke test ──────────────────────────────────────────────
1792
+ with gr.Tab("Smoke test"):
1793
+ gr.Markdown(
1794
+ "Run the review pipeline on **synthetic demo data** — no API keys needed."
1795
+ )
1796
+ with gr.Row():
1797
+ smoke_btn = gr.Button("Run smoke test", variant="primary", size="lg", scale=2)
1798
+ smoke_cancel_btn = gr.Button("Cancel", variant="stop", size="lg", visible=False)
1799
+
1800
+ smoke_loading = gr.HTML(
1801
+ '<div class="loading-spinner"><div class="spinner"></div>'
1802
+ '<span class="label">Running smoke test...</span></div>',
1803
+ visible=False,
1804
+ )
1805
+
1806
+ with gr.Column(visible=False) as smoke_results:
1807
+ smoke_verdict = gr.HTML()
1808
+ smoke_findings = gr.HTML()
1809
+ with gr.Row():
1810
+ smoke_approve = gr.Button("Approve (demo)", variant="primary")
1811
+ smoke_reject = gr.Button("Reject (demo)", variant="secondary")
1812
+ smoke_resume_msg = gr.Markdown()
1813
+
1814
+ smoke_status = gr.Markdown(visible=False)
1815
+
1816
+ def on_smoke_click():
1817
+ # Show loading state
1818
+ yield [
1819
+ gr.update(visible=True),
1820
+ gr.update(visible=True, variant="stop"),
1821
+ gr.update(visible=False),
1822
+ gr.update(visible=False),
1823
+ None,
1824
+ gr.update(value=""),
1825
+ gr.update(value=""),
1826
+ gr.update(visible=False),
1827
+ ]
1828
+ for result, err in run_smoke():
1829
+ if err:
1830
+ yield [
1831
+ gr.update(visible=False),
1832
+ gr.update(visible=False),
1833
+ gr.update(visible=True),
1834
+ gr.update(visible=False),
1835
+ None,
1836
+ gr.update(value=""),
1837
+ gr.update(value=""),
1838
+ gr.update(visible=True, value=err),
1839
+ ]
1840
+ else:
1841
+ verdict_html, findings_html, config_json, s_verdict, s_findings = result
1842
+ yield [
1843
+ gr.update(visible=False),
1844
+ gr.update(visible=False),
1845
+ gr.update(visible=True),
1846
+ gr.update(visible=True),
1847
+ config_json,
1848
+ gr.update(value=s_verdict),
1849
+ gr.update(value=s_findings),
1850
+ gr.update(visible=False),
1851
+ ]
1852
+
1853
+ smoke_event = smoke_btn.click(
1854
+ fn=on_smoke_click,
1855
+ outputs=[smoke_loading, smoke_cancel_btn, smoke_btn, smoke_results, smoke_state,
1856
+ smoke_verdict, smoke_findings, smoke_status],
1857
+ )
1858
+ smoke_cancel_btn.click(fn=None, cancels=[smoke_event])
1859
+
1860
+ smoke_approve.click(
1861
+ fn=lambda c: resume_review(c, "approve"),
1862
+ inputs=[smoke_state],
1863
+ outputs=[smoke_resume_msg],
1864
+ )
1865
+ smoke_reject.click(
1866
+ fn=lambda c: resume_review(c, "reject"),
1867
+ inputs=[smoke_state],
1868
+ outputs=[smoke_resume_msg],
1869
+ )
1870
+
1871
+ # ── Environment status footer ──────────────────────────────────────
1872
+ with gr.Accordion("Configured keys & health", open=False):
1873
+ h = HealthStatus()
1874
+ health_data = h.summary()
1875
+ gemini_ok = bool(os.environ.get("GEMINI_API_KEY", "").strip())
1876
+ groq_ok = bool(os.environ.get("GROQ_API_KEY", "").strip())
1877
+ gh_ok = bool(os.environ.get("GITHUB_TOKEN", "").strip())
1878
+ lines = [
1879
+ f"<li>GEMINI_API_KEY: {'✅ Set' if gemini_ok else '❌ Not set'}</li>",
1880
+ f"<li>GROQ_API_KEY: {'✅ Set' if groq_ok else '❌ Not set'}</li>",
1881
+ f"<li>GITHUB_TOKEN: {'✅ Set' if gh_ok else '❌ Not set'}</li>",
1882
+ f"<li>LangSmith: {health_data['LangSmith']}</li>",
1883
+ f"<li>Langfuse: {health_data['Langfuse']}</li>",
1884
+ ]
1885
+ gr.HTML("<ul>" + "".join(lines) + "</ul>")
1886
+
1887
+ gr.HTML(
1888
+ '<div class="card-title" style="margin:14px 0 8px">⚡ LLM Endpoints</div>'
1889
+ )
1890
+ if _configured_endpoints:
1891
+ endpoint_cards = "".join(
1892
+ f'<div class="endpoint-card">'
1893
+ f'<div class="endpoint-name">{html.escape(ep.name)}'
1894
+ f'<span class="endpoint-badge">{html.escape(ep.provider)}</span>'
1895
+ + (
1896
+ '<span class="endpoint-badge" style="color:#dc2626;background:#dc262611;border-color:#dc262644">missing key</span>'
1897
+ if not ep.api_key else ""
1898
+ )
1899
+ + '</div>'
1900
+ f'<div class="endpoint-meta"><code>{html.escape(ep.model)}</code>'
1901
+ f' · {html.escape(ep.base_url or "default URL")} · key {ep.masked_key}</div>'
1902
+ f'</div>'
1903
+ for ep in _configured_endpoints
1904
+ )
1905
+ gr.HTML(f'<div>{endpoint_cards}</div>')
1906
+ else:
1907
+ gr.HTML(
1908
+ '<p class="muted small">None configured — set '
1909
+ '<code>OCR_ENDPOINT_1_NAME</code> / <code>_TYPE</code> / '
1910
+ '<code>_API_KEY</code> / <code>_BASE_URL</code> / <code>_MODEL</code> '
1911
+ 'as Space secrets to add one.</p>'
1912
+ )
1913
+ with gr.Row():
1914
+ test_endpoints_btn = gr.Button("Test endpoint connectivity", size="sm", variant="secondary")
1915
+ endpoint_test_out = gr.HTML()
1916
+ test_endpoints_btn.click(fn=test_endpoints, outputs=[endpoint_test_out])
1917
+
1918
+ # ── Footer ─────────────────────────────────────────────────────────
1919
+ _commit, _ts = _get_deploy_info()
1920
+ gr.HTML(
1921
+ f'<p class="footer">'
1922
+ f'Built with LangGraph · Groq · ChromaDB · Gradio'
1923
+ f'<br><span style="opacity:0.5;font-size:0.85em;color:var(--text-footer)">'
1924
+ f'deploy: <code>{_commit}</code> · {_ts}'
1925
+ f'</span></p>'
1926
+ )
1927
+
1928
+
1929
+ def _resolve_port() -> int:
1930
+ """Resolve the listen port from $PORT, falling back to 7860.
1931
+
1932
+ HF Spaces always sets a valid $PORT, but locally the variable may be
1933
+ empty or even 0 (e.g. inherited from an unrelated shell profile) —
1934
+ binding port 0 makes Gradio's post-launch self-check fail with a
1935
+ confusing connection traceback, so invalid values are rejected here.
1936
+ """
1937
+ raw = (os.environ.get("PORT") or "").strip()
1938
+ try:
1939
+ port = int(raw) if raw else 7860
1940
+ except ValueError:
1941
+ logger.warning("Ignoring non-numeric PORT=%r — using 7860", raw)
1942
+ return 7860
1943
+ if not 1 <= port <= 65535:
1944
+ logger.warning("Ignoring out-of-range PORT=%d — using 7860", port)
1945
+ return 7860
1946
+ return port
1947
+
1948
+
1949
+ def main() -> None:
1950
+ port = _resolve_port()
1951
+ # Gradio 6: theme/css moved from the Blocks constructor to launch().
1952
+ demo.queue(max_size=10).launch(
1953
+ server_name="0.0.0.0",
1954
+ server_port=port,
1955
+ share=False,
1956
+ theme=gr.themes.Soft(),
1957
+ css=CSS,
1958
+ )
1959
+
1960
+
1961
+ if __name__ == "__main__":
1962
+ main()
backend/combined_server.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ """Serve the React-facing API and legacy Gradio UI from one HF Space."""
2
+ from fastapi import FastAPI
3
+ import gradio as gr
4
+
5
+ from backend.api import app as api_app
6
+ from backend.app import demo
7
+
8
+ app: FastAPI = gr.mount_gradio_app(api_app, demo, path="/")
backend/graph.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ import sqlite3
5
+
6
+ from langgraph.checkpoint.serde.jsonplus import JsonPlusSerializer
7
+ from langgraph.checkpoint.sqlite import SqliteSaver
8
+ from langgraph.graph import END, START, StateGraph
9
+
10
+ from nodes import (
11
+ aggregator_node,
12
+ correctness_reviewer_node,
13
+ executor_node,
14
+ human_approval_node,
15
+ ingestion_node,
16
+ retrieval_node,
17
+ security_reviewer_node,
18
+ test_coverage_reviewer_node,
19
+ )
20
+ from backend.state import OpenCodeReviewState
21
+
22
+ logger = logging.getLogger(__name__)
23
+
24
+
25
+ def build_graph(db_path: str | None = None) -> StateGraph:
26
+ """Build and compile the OpenCodeReview graph with SqliteSaver checkpointing.
27
+
28
+ When *db_path* is ``None`` an in-memory SQLite database is used so file
29
+ I/O is avoided — ideal for ephemeral CLI runs. Pass a file path to keep
30
+ checkpoints across process restarts (needed by the Gradio UI which may
31
+ resume after page reload).
32
+
33
+ Topology:
34
+
35
+ START → ingestion → retrieval
36
+ │
37
+ ┌─────────────┼─────────────┐
38
+ ▼ ▼ ▼
39
+ correctness security test_coverage
40
+ │ │ │
41
+ └─────────────┼─────────────┘
42
+ ▼
43
+ aggregator
44
+ │
45
+ ▼
46
+ human_approval ←── interrupt() pauses here
47
+ │
48
+ ▼
49
+ executor
50
+ ┌────┴────┐
51
+ ┌────────▼─▼────────┐
52
+ │ Inline review │
53
+ │ comments at file │
54
+ │ /line positions │
55
+ │ 422 → issue cmt │
56
+ └────────┬─┬────────┘
57
+ │
58
+ END
59
+ """
60
+ builder = StateGraph(OpenCodeReviewState)
61
+
62
+ # -- Nodes ----------------------------------------------------------------
63
+ builder.add_node("ingestion", ingestion_node)
64
+ builder.add_node("retrieval", retrieval_node)
65
+ builder.add_node("correctness_review", correctness_reviewer_node)
66
+ builder.add_node("security_review", security_reviewer_node)
67
+ builder.add_node("test_coverage_review", test_coverage_reviewer_node)
68
+ builder.add_node("aggregator", aggregator_node)
69
+ builder.add_node("human_approval", human_approval_node)
70
+ builder.add_node("executor", executor_node)
71
+
72
+ # -- Linear prefix --------------------------------------------------------
73
+ builder.add_edge(START, "ingestion")
74
+ builder.add_edge("ingestion", "retrieval")
75
+
76
+ # -- Fan-out: retrieval → all three reviewers in parallel -----------------
77
+ builder.add_edge("retrieval", "correctness_review")
78
+ builder.add_edge("retrieval", "security_review")
79
+ builder.add_edge("retrieval", "test_coverage_review")
80
+
81
+ # -- Fan-in: all three reviewers → aggregator -----------------------------
82
+ builder.add_edge("correctness_review", "aggregator")
83
+ builder.add_edge("security_review", "aggregator")
84
+ builder.add_edge("test_coverage_review", "aggregator")
85
+
86
+ # -- HITL + posting -------------------------------------------------------
87
+ builder.add_edge("aggregator", "human_approval")
88
+ builder.add_edge("human_approval", "executor")
89
+ builder.add_edge("executor", END)
90
+
91
+ # -- Checkpointer (required for interrupt/resume to work) -----------------
92
+ serde = JsonPlusSerializer(allowed_msgpack_modules=[
93
+ ("backend.state", "ChangedFile"),
94
+ ("backend.state", "ContextChunk"),
95
+ ("backend.state", "Severity"),
96
+ ("backend.state", "Finding"),
97
+ ("backend.state", "Verdict"),
98
+ # Continue reading checkpoints written before the backend was packaged.
99
+ ("state", "ChangedFile"),
100
+ ("state", "ContextChunk"),
101
+ ("state", "Severity"),
102
+ ("state", "Finding"),
103
+ ("state", "Verdict"),
104
+ ])
105
+
106
+ resolved_path: str = db_path if db_path is not None else ":memory:"
107
+ conn = sqlite3.connect(resolved_path, check_same_thread=False)
108
+ saver = SqliteSaver(conn, serde=serde)
109
+
110
+ compiled = builder.compile(checkpointer=saver)
111
+ # Expose the connection so callers can close it once the graph run is
112
+ # fully finished (prevents file-handle leaks in the long-running UI).
113
+ compiled._opencodereview_conn = conn
114
+ return compiled
backend/integrations/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """External service and provider integrations used by the backend."""
backend/integrations/auth.py ADDED
@@ -0,0 +1,353 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """GitHub OAuth Device Flow authentication for OpenCodeReview.
3
+
4
+ Usage
5
+ -----
6
+ export GITHUB_OAUTH_CLIENT_ID="Iv23li..."
7
+ opencodereview auth login
8
+ opencodereview auth status
9
+ opencodereview auth logout
10
+
11
+ The Device Flow is used instead of the Authorization Code flow because
12
+ there is no web server to handle a redirect URI.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import logging
18
+ import os
19
+ import sys
20
+ import time
21
+ from typing import Optional
22
+
23
+ import click
24
+ import keyring
25
+ import requests
26
+
27
+ logger = logging.getLogger(__name__)
28
+
29
+ # ─── Constants ───────────────────────────────────────────────────────────────
30
+
31
+ SERVICE_NAME = "opencodereview"
32
+ GH_DEVICE_CODE_URL = "https://github.com/login/device/code"
33
+ GH_ACCESS_TOKEN_URL = "https://github.com/login/oauth/access_token"
34
+ GH_API_BASE = "https://api.github.com"
35
+ DEFAULT_SCOPE = "repo" # Full control of private repositories — needed for
36
+ # reading PRs and posting review comments on
37
+ # private repos.
38
+ POLL_SAFETY_MARGIN = 1 # Extra seconds to wait beyond the server's interval
39
+
40
+
41
+ # ─── Exceptions ─────────────────────────────────────────────────────────────
42
+
43
+
44
+ class AuthError(Exception):
45
+ """Base exception for auth operations."""
46
+
47
+
48
+ class DeviceFlowExpired(AuthError):
49
+ """The device code expired before the user approved."""
50
+
51
+
52
+ class DeviceFlowDenied(AuthError):
53
+ """The user denied the authorization request."""
54
+
55
+
56
+ # ─── Auth Service ────────────────────────────────────────────────────────────
57
+
58
+
59
+ def _resolve_client_id(client_id: Optional[str] = None) -> str:
60
+ """Return the GitHub OAuth client ID from the argument or environment."""
61
+ cid = client_id or os.environ.get("GITHUB_OAUTH_CLIENT_ID")
62
+ if not cid:
63
+ raise AuthError(
64
+ "GitHub OAuth client ID is required.\n\n"
65
+ " 1. Register a new OAuth App at:\n"
66
+ " https://github.com/settings/developers\n\n"
67
+ " 2. Enable Device Flow in the app settings.\n\n"
68
+ " 3. Set the client ID:\n"
69
+ f" export GITHUB_OAUTH_CLIENT_ID=\"<your_client_id>\"\n"
70
+ " Or pass --client-id to the login command.",
71
+ )
72
+ return cid
73
+
74
+
75
+ class AuthService:
76
+ """Manage GitHub OAuth tokens via the Device Flow."""
77
+
78
+ def __init__(self, client_id: Optional[str] = None) -> None:
79
+ self._client_id = client_id or os.environ.get("GITHUB_OAUTH_CLIENT_ID")
80
+ self._session = requests.Session()
81
+ self._session.headers.update({
82
+ "Accept": "application/json",
83
+ "User-Agent": "opencodereview/1.0",
84
+ })
85
+
86
+ # ── Device Flow Login ──────────────────────────────────────────────────
87
+
88
+ def login(self) -> str:
89
+ """Run the GitHub Device Flow and return the access token.
90
+
91
+ Steps
92
+ -----
93
+ 1. POST to ``/login/device/code`` to get a device + user code.
94
+ 2. Print the user code + verification URL for the user.
95
+ 3. Poll ``/login/oauth/access_token`` until the user approves.
96
+ 4. Validate that the granted scopes include what was requested.
97
+ 5. Save the token to the system keyring.
98
+ 6. Return the access token.
99
+ """
100
+ # Validate client_id before making any API calls
101
+ self._client_id = _resolve_client_id(self._client_id)
102
+
103
+ device_code, user_code, verification_uri, interval, expires_in = (
104
+ self._request_device_code()
105
+ )
106
+
107
+ self._print_login_instructions(user_code, verification_uri, expires_in)
108
+
109
+ access_token, granted_scope = self._poll_for_token(device_code, interval)
110
+
111
+ # Validate that the granted scopes include what we asked for
112
+ self._validate_scopes(granted_scope)
113
+
114
+ # Save to keyring
115
+ keyring.set_password(SERVICE_NAME, "github_token", access_token)
116
+ logger.info("Token saved to system credential store (keyring).")
117
+
118
+ # Fetch and display user info
119
+ user = self._get_user(access_token)
120
+ click.echo(f" Logged in as: {user['login']}")
121
+
122
+ return access_token
123
+
124
+ def _request_device_code(
125
+ self,
126
+ ) -> tuple[str, str, str, int, int]:
127
+ """POST to the device-code endpoint and return the response fields."""
128
+ resp = self._session.post(
129
+ GH_DEVICE_CODE_URL,
130
+ data={
131
+ "client_id": self._client_id,
132
+ "scope": DEFAULT_SCOPE,
133
+ },
134
+ )
135
+ resp.raise_for_status()
136
+ data = resp.json()
137
+
138
+ if "error" in data:
139
+ raise AuthError(
140
+ f"Device code request failed: {data.get('error_description', data['error'])}"
141
+ )
142
+
143
+ return (
144
+ data["device_code"],
145
+ data["user_code"],
146
+ data["verification_uri"],
147
+ data.get("interval", 5),
148
+ data.get("expires_in", 900),
149
+ )
150
+
151
+ @staticmethod
152
+ def _print_login_instructions(
153
+ user_code: str, verification_uri: str, expires_in: int,
154
+ ) -> None:
155
+ """Print the user code and instructions to the terminal."""
156
+ click.echo()
157
+ click.echo("=" * 60)
158
+ click.echo(" GitHub Device Authentication")
159
+ click.echo("=" * 60)
160
+ click.echo()
161
+ click.echo(f" 1. Open this URL in your browser:")
162
+ click.echo(f" {verification_uri}")
163
+ click.echo()
164
+ click.echo(f" 2. Enter the following code:")
165
+ click.echo(f" {user_code}")
166
+ click.echo()
167
+ click.echo(f" 3. Authorize the OpenCodeReview application.")
168
+ click.echo()
169
+ click.echo(f" This code expires in {expires_in // 60} minute(s).")
170
+ click.echo(f" Waiting for you to approve...")
171
+ click.echo()
172
+
173
+ def _poll_for_token(self, device_code: str, interval: int) -> tuple[str, str]:
174
+ """Poll the access-token endpoint until the user approves or the code expires.
175
+
176
+ Returns ``(access_token, granted_scope)`` where ``granted_scope`` is the
177
+ space-separated scope string returned by GitHub (may be empty if the
178
+ response omitted it).
179
+ """
180
+ poll_interval = interval
181
+ start_time = time.monotonic()
182
+
183
+ while True:
184
+ time.sleep(poll_interval + POLL_SAFETY_MARGIN)
185
+
186
+ resp = self._session.post(
187
+ GH_ACCESS_TOKEN_URL,
188
+ data={
189
+ "client_id": self._client_id,
190
+ "device_code": device_code,
191
+ "grant_type": "urn:ietf:params:oauth:grant-type:device_code",
192
+ },
193
+ )
194
+ resp.raise_for_status()
195
+ data = resp.json()
196
+
197
+ if "access_token" in data:
198
+ return data["access_token"], data.get("scope", "")
199
+
200
+ error = data.get("error", "")
201
+
202
+ if error == "authorization_pending":
203
+ # User hasn't acted yet — keep polling
204
+ continue
205
+ elif error == "slow_down":
206
+ # Polling too fast — increase interval by 5 seconds
207
+ poll_interval += 5
208
+ logger.debug("Polling rate limited — increasing interval to %ds", poll_interval)
209
+ continue
210
+ elif error == "expired_token":
211
+ raise DeviceFlowExpired(
212
+ "The device code has expired. Run 'opencodereview auth login' again."
213
+ )
214
+ elif error == "access_denied":
215
+ raise DeviceFlowDenied("The authorization request was denied.")
216
+ else:
217
+ raise AuthError(
218
+ f"Unexpected polling response: {data.get('error_description', error)}"
219
+ )
220
+
221
+ # ── Status ──────────────────────────────────────────────────────────────
222
+
223
+ def status(self) -> Optional[dict]:
224
+ """Check whether a valid token is stored and return the authenticated user.
225
+
226
+ Returns ``None`` if no token is stored.
227
+ Raises ``AuthError`` if the token is invalid or expired.
228
+ """
229
+ token = keyring.get_password(SERVICE_NAME, "github_token")
230
+ if not token:
231
+ return None
232
+
233
+ user = self._get_user(token)
234
+ return user
235
+
236
+ # ── Logout ──────────────────────────────────────────────────────────────
237
+
238
+ def logout(self) -> bool:
239
+ """Delete the stored token from the keyring.
240
+
241
+ Returns ``True`` if a token was deleted, ``False`` if none existed.
242
+ """
243
+ existing = keyring.get_password(SERVICE_NAME, "github_token")
244
+ if existing:
245
+ try:
246
+ keyring.delete_password(SERVICE_NAME, "github_token")
247
+ except keyring.errors.PasswordDeleteError:
248
+ logger.warning("Failed to delete token from keyring (back-end error).")
249
+ return False
250
+ return True
251
+ return False
252
+
253
+ # ── Helpers ─────────────────────────────────────────────────────────────
254
+
255
+ def _validate_scopes(self, granted_scope_str: str) -> None:
256
+ """Compare the scopes GitHub actually granted against what was requested.
257
+
258
+ The ``scope`` field in the access-token response is a space-separated
259
+ string. If the user denied some scopes, we warn them on stderr so
260
+ they know certain features may not work.
261
+ """
262
+ if not granted_scope_str.strip():
263
+ # Older GitHub Enterprise or unusual config — skip validation
264
+ return
265
+
266
+ requested = set(DEFAULT_SCOPE.split(","))
267
+ granted = set(granted_scope_str.strip().split())
268
+ missing = requested - granted
269
+
270
+ if missing:
271
+ click.echo(
272
+ "\n"
273
+ "Warning: Some requested permissions were not granted.\n"
274
+ f" Missing scopes: {', '.join(sorted(missing))}\n"
275
+ f" Granted scopes: {', '.join(sorted(granted))}\n"
276
+ "\n"
277
+ " Features that need these scopes may not work correctly.\n"
278
+ " Re-run 'opencodereview auth login' and ensure you\n"
279
+ " authorize all requested permissions.\n",
280
+ err=True,
281
+ )
282
+
283
+ def _get_user(self, token: str) -> dict:
284
+ """Fetch the authenticated GitHub user via the API."""
285
+ resp = self._session.get(
286
+ f"{GH_API_BASE}/user",
287
+ headers={"Authorization": f"token {token}"},
288
+ )
289
+ if resp.status_code == 401:
290
+ raise AuthError(
291
+ "The stored token is invalid or has been revoked.\n"
292
+ "Run 'opencodereview auth login' to re-authenticate."
293
+ )
294
+ resp.raise_for_status()
295
+ return resp.json()
296
+
297
+
298
+ # ─── CLI ─────────────────────────────────────────────────────────────────────
299
+
300
+
301
+ @click.group()
302
+ def auth() -> None:
303
+ """Authenticate with GitHub via the OAuth Device Flow."""
304
+
305
+
306
+ @auth.command()
307
+ @click.option(
308
+ "--client-id",
309
+ envvar="GITHUB_OAUTH_CLIENT_ID",
310
+ default=None,
311
+ help="GitHub OAuth App client ID (or set GITHUB_OAUTH_CLIENT_ID).",
312
+ )
313
+ def login(client_id: Optional[str]) -> None:
314
+ """Authenticate with GitHub and store the token securely."""
315
+ try:
316
+ svc = AuthService(client_id=client_id)
317
+ svc.login()
318
+ except (AuthError, requests.RequestException) as exc:
319
+ click.echo(f"Error: {exc}", err=True)
320
+ sys.exit(1)
321
+
322
+
323
+ @auth.command()
324
+ def logout() -> None:
325
+ """Remove the stored GitHub token."""
326
+ svc = AuthService()
327
+ if svc.logout():
328
+ click.echo("Token removed from credential store.")
329
+ else:
330
+ click.echo("No token found. Nothing to remove.")
331
+
332
+
333
+ @auth.command()
334
+ def status() -> None:
335
+ """Show whether a valid token is stored and which user it belongs to."""
336
+ svc = AuthService()
337
+ try:
338
+ user = svc.status()
339
+ except AuthError as exc:
340
+ click.echo(f"Token status: invalid ({exc})", err=True)
341
+ sys.exit(1)
342
+ except requests.RequestException as exc:
343
+ click.echo(f"Error checking token: {exc}", err=True)
344
+ sys.exit(1)
345
+
346
+ if user is None:
347
+ click.echo("No token stored. Run 'opencodereview auth login'.", err=True)
348
+ sys.exit(1)
349
+ else:
350
+ click.echo(f"Authenticated as: {user['login']}")
351
+ click.echo(f"Token: valid")
352
+ if user.get("name"):
353
+ click.echo(f"Name: {user['name']}")
backend/integrations/config.py ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Configuration management for OpenCodeReview.
3
+
4
+ Resolves secrets in priority order: **environment variable > keyring > error**.
5
+
6
+ Providers
7
+ ---------
8
+ - ``anthropic`` — ``ANTHROPIC_API_KEY`` → stored as ``opencodereview / anthropic_api_key``
9
+
10
+ Usage
11
+ -----
12
+ opencodereview config set-key --provider anthropic
13
+ opencodereview config show
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import logging
19
+ import os
20
+ import sys
21
+ from typing import Optional
22
+
23
+ import click
24
+ import keyring
25
+ from pydantic import Field
26
+ from pydantic_settings import BaseSettings, SettingsConfigDict
27
+
28
+ logger = logging.getLogger(__name__)
29
+
30
+ SERVICE_NAME = "opencodereview"
31
+
32
+ # ─── Provider registry ──────────────────────────────────────────────────────
33
+ # slug → (keyring_key, env_var_name, display_name)
34
+
35
+ PROVIDERS: dict[str, tuple[str, str, str]] = {
36
+ "anthropic": (
37
+ "anthropic_api_key", # keyring key
38
+ "OPENCODEREVIEW_ANTHROPIC_KEY", # env var
39
+ "Anthropic API key", # display name
40
+ ),
41
+ }
42
+
43
+
44
+ # ─── Exceptions ─────────────────────────────────────────────────────────────
45
+
46
+
47
+ class ConfigError(Exception):
48
+ """Configuration-related error with a user-facing message."""
49
+
50
+
51
+ # ─── Settings (pydantic-settings) ───────────────────────────────────────────
52
+
53
+
54
+ class Settings(BaseSettings):
55
+ """Resolve configuration from env vars, falling back to the system keyring.
56
+
57
+ Priority
58
+ --------
59
+ 1. Environment variable (``OPENCODEREVIEW_<FIELD>``)
60
+ 2. System keyring (``opencodereview / <keyring_key>``)
61
+ 3. :class:`ConfigError` with a helpful message telling the user how to set it.
62
+ """
63
+
64
+ model_config = SettingsConfigDict(
65
+ env_prefix="OPENCODEREVIEW_",
66
+ extra="ignore",
67
+ validate_default=False,
68
+ )
69
+
70
+ anthropic_api_key: Optional[str] = Field(default=None)
71
+
72
+ # ── Langfuse observability (optional) ──────────────────────────────────
73
+ langfuse_public_key: Optional[str] = Field(default=None)
74
+ langfuse_secret_key: Optional[str] = Field(default=None)
75
+ langfuse_host: Optional[str] = Field(default=None)
76
+
77
+ def model_post_init(self, __context) -> None: # noqa: ANN101
78
+ """After env-var resolution, fall back to keyring for any unset values."""
79
+ for keyring_key, _, _ in PROVIDERS.values():
80
+ if getattr(self, keyring_key) is None:
81
+ stored = keyring.get_password(SERVICE_NAME, keyring_key)
82
+ if stored:
83
+ setattr(self, keyring_key, stored)
84
+
85
+ def get_anthropic_api_key(self) -> str:
86
+ """Return the Anthropic API key or raise ``ConfigError``."""
87
+ key = self.anthropic_api_key
88
+ if not key:
89
+ raise ConfigError(
90
+ "Anthropic API key is not configured.\n\n"
91
+ " Set it interactively:\n"
92
+ " opencodereview config set-key --provider anthropic\n\n"
93
+ " Or as an environment variable:\n"
94
+ " export OPENCODEREVIEW_ANTHROPIC_KEY=\"sk-ant-...\"\n"
95
+ )
96
+ return key
97
+
98
+
99
+ # ─── Key masking ─────────────────────────────────────────────────────────────
100
+
101
+
102
+ def _mask_key(key: str) -> str:
103
+ """Return a masked version showing only the prefix and last characters.
104
+
105
+ Examples
106
+ --------
107
+ ``sk-ant-abcdefgh12345678`` → ``sk-ant-...5678``
108
+ ``ghp_abc123def456`` → ``ghp_abc...f456``
109
+ ``abcdefg`` → ``abcd...fg``
110
+ ``tiny`` → ``t...``
111
+ """
112
+ n = len(key)
113
+ if n <= 4:
114
+ return key[:1] + "..."
115
+ if n <= 8:
116
+ return key[:4] + "..." + key[-2:]
117
+ return key[:7] + "..." + key[-4:]
118
+
119
+
120
+ # ─── CLI ─────────────────────────────────────────────────────────────────────
121
+
122
+
123
+ @click.group()
124
+ def config() -> None:
125
+ """Manage API keys and configuration."""
126
+
127
+
128
+ @config.command()
129
+ @click.option(
130
+ "--provider",
131
+ required=True,
132
+ type=click.Choice(sorted(PROVIDERS), case_sensitive=True),
133
+ help="Which provider's API key to store.",
134
+ )
135
+ def set_key(provider: str) -> None:
136
+ """Prompt for an API key and store it securely in the system keyring.
137
+
138
+ The key is entered via hidden input and never echoed to the terminal.
139
+ """
140
+ keyring_key, env_var, display_name = PROVIDERS[provider]
141
+
142
+ # Warn if env var is already set (keyring value would be ignored)
143
+ if os.environ.get(env_var):
144
+ click.echo(
145
+ f"Warning: {display_name} is already set via the"
146
+ f" {env_var} environment variable.\n"
147
+ f" A keyring-stored key won't take effect until the env var is unset.\n",
148
+ err=True,
149
+ )
150
+
151
+ api_key = click.prompt(
152
+ f"Enter your {display_name}",
153
+ hide_input=True,
154
+ )
155
+
156
+ if not api_key.strip():
157
+ click.echo("Error: Key cannot be empty.", err=True)
158
+ sys.exit(1)
159
+
160
+ keyring.set_password(SERVICE_NAME, keyring_key, api_key.strip())
161
+ click.echo(f"{display_name} saved to system credential store (keyring).")
162
+
163
+
164
+ @config.command()
165
+ def show() -> None:
166
+ """Display which keys and tokens are configured (values masked).
167
+
168
+ Full secrets are never printed — only the first 7 + last 4 characters.
169
+ """
170
+ click.echo()
171
+ click.echo("=" * 50)
172
+ click.echo(" Configuration Summary")
173
+ click.echo("=" * 50)
174
+ click.echo()
175
+ has_any = False
176
+
177
+ # ── GitHub token (managed by auth) ──────────────────────────────────────
178
+ gh_token = keyring.get_password(SERVICE_NAME, "github_token")
179
+ token_env = os.environ.get("GITHUB_TOKEN")
180
+ if token_env:
181
+ click.echo(f" GitHub token: {_mask_key(token_env)} (from env)")
182
+ has_any = True
183
+ elif gh_token:
184
+ click.echo(f" GitHub token: {_mask_key(gh_token)} (from keyring)")
185
+ has_any = True
186
+ else:
187
+ click.echo(" GitHub token: not set")
188
+
189
+ # ── Provider API keys ───────────────────────────────────────────────────
190
+ for provider_slug, (keyring_key, env_var, display_name) in sorted(PROVIDERS.items()):
191
+ env_value = os.environ.get(env_var)
192
+ if env_value:
193
+ click.echo(
194
+ f" {display_name}: {_mask_key(env_value)} (from env)"
195
+ )
196
+ has_any = True
197
+ else:
198
+ stored = keyring.get_password(SERVICE_NAME, keyring_key)
199
+ if stored:
200
+ click.echo(
201
+ f" {display_name}: {_mask_key(stored)} (from keyring)"
202
+ )
203
+ has_any = True
204
+ else:
205
+ click.echo(f" {display_name}: not set")
206
+
207
+ click.echo()
208
+ if not has_any:
209
+ click.echo(" No keys or tokens configured.")
210
+ click.echo(" Run: opencodereview config set-key --provider anthropic")
211
+ click.echo()
212
+
213
+
214
+ # ─── Observability CLI ─────────────────────────────────────────────────────
215
+
216
+
217
+ @config.command(name="set-observability")
218
+ @click.option("--langsmith-api-key", help="LangSmith API key (for tracing)")
219
+ @click.option("--langsmith-project", default="opencodereview", show_default=True,
220
+ help="LangSmith project name")
221
+ @click.option("--langfuse-public-key", help="Langfuse public key")
222
+ @click.option("--langfuse-secret-key", help="Langfuse secret key")
223
+ @click.option("--langfuse-host", default="https://cloud.langfuse.com",
224
+ show_default=True, help="Langfuse host URL")
225
+ def set_observability(
226
+ langsmith_api_key: Optional[str],
227
+ langsmith_project: str,
228
+ langfuse_public_key: Optional[str],
229
+ langfuse_secret_key: Optional[str],
230
+ langfuse_host: str,
231
+ ) -> None:
232
+ """Configure observability backends (LangSmith and/or Langfuse).
233
+
234
+ Keys are stored in the system keyring. Both backends can be configured
235
+ simultaneously with no conflict. If neither is set, the app runs
236
+ exactly as before with zero tracing overhead.
237
+ """
238
+ if langsmith_api_key:
239
+ keyring.set_password(SERVICE_NAME, "langsmith_api_key", langsmith_api_key)
240
+ click.echo(f"LangSmith API key saved (project: {langsmith_project}).")
241
+
242
+ # Warn if env var is already set
243
+ if os.environ.get("LANGCHAIN_API_KEY"):
244
+ click.echo(
245
+ " Note: LANGCHAIN_API_KEY env var is already set — "
246
+ "it takes precedence over the keyring value.",
247
+ err=True,
248
+ )
249
+ else:
250
+ click.echo(" LangSmith: skipped (no --langsmith-api-key provided).")
251
+
252
+ if langfuse_public_key and langfuse_secret_key:
253
+ keyring.set_password(SERVICE_NAME, "langfuse_public_key", langfuse_public_key)
254
+ keyring.set_password(SERVICE_NAME, "langfuse_secret_key", langfuse_secret_key)
255
+ keyring.set_password(SERVICE_NAME, "langfuse_host", langfuse_host)
256
+ click.echo(f"Langfuse keys saved (host: {langfuse_host}).")
257
+
258
+ if os.environ.get("LANGFUSE_PUBLIC_KEY"):
259
+ click.echo(
260
+ " Note: LANGFUSE_PUBLIC_KEY env var is already set — "
261
+ "it takes precedence.",
262
+ err=True,
263
+ )
264
+ else:
265
+ click.echo(" Langfuse: skipped (need both --langfuse-public-key "
266
+ "and --langfuse-secret-key).")
backend/integrations/endpoints.py ADDED
@@ -0,0 +1,306 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Custom LLM endpoint registry.
2
+
3
+ Lets users register any number of custom model endpoints via environment
4
+ variables (set as Space secrets or in the shell), so a review can run on a
5
+ user-chosen model instead of the single built-in key.
6
+
7
+ Env-var convention (index *n* is any number ≥ 1)::
8
+
9
+ OCR_ENDPOINT_1_NAME=DeepSeek
10
+ OCR_ENDPOINT_1_TYPE=openai # openai | anthropic | google (default openai)
11
+ OCR_ENDPOINT_1_API_KEY=sk-...
12
+ OCR_ENDPOINT_1_BASE_URL=https://api.deepseek.com/v1
13
+ OCR_ENDPOINT_1_MODEL=deepseek-chat
14
+
15
+ OCR_ENDPOINT_2_NAME=Claude
16
+ OCR_ENDPOINT_2_TYPE=anthropic
17
+ OCR_ENDPOINT_2_API_KEY=sk-ant-...
18
+ OCR_ENDPOINT_2_MODEL=claude-sonnet-4-20250514
19
+
20
+ Supported ``TYPE`` values:
21
+ * ``openai`` — any OpenAI-compatible API (DeepSeek, OpenRouter, vLLM,
22
+ Ollama, Together, local proxies, ...)
23
+ * ``anthropic`` — Anthropic Claude (``base_url`` optional, e.g. a proxy)
24
+ * ``google`` — Google Gemini (``base_url`` not used)
25
+
26
+ Keys are only ever read from the environment — they are never written to
27
+ disk. Use :func:`mask_key` anywhere a key is shown in the UI.
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import logging
33
+ import os
34
+ import threading
35
+ from dataclasses import dataclass
36
+ from typing import Optional
37
+
38
+ logger = logging.getLogger(__name__)
39
+
40
+ ENDPOINT_ENV_PREFIX = "OCR_ENDPOINT_"
41
+
42
+ SUPPORTED_PROVIDERS = ("openai", "anthropic", "google")
43
+
44
+
45
+ @dataclass
46
+ class EndpointConfig:
47
+ """A single custom LLM endpoint the user has configured."""
48
+
49
+ name: str
50
+ provider: str = "openai" # openai | anthropic | google
51
+ api_key: str = ""
52
+ base_url: Optional[str] = None
53
+ model: str = ""
54
+ index: int = 0 # the env-var index the endpoint came from
55
+ builtin: bool = False # True for the always-available Gemini/Grok providers
56
+
57
+ def __post_init__(self) -> None:
58
+ self.provider = (self.provider or "openai").strip().lower()
59
+ if self.provider not in SUPPORTED_PROVIDERS:
60
+ logger.warning(
61
+ "Endpoint %r has unsupported type %r — treating as openai",
62
+ self.name, self.provider,
63
+ )
64
+ self.provider = "openai"
65
+
66
+ @property
67
+ def masked_key(self) -> str:
68
+ """API key with only the first/last few chars visible."""
69
+ return mask_key(self.api_key)
70
+
71
+ def describe(self) -> str:
72
+ """One-line human-readable summary for the UI / CLI."""
73
+ base = f" ({self.base_url})" if self.base_url else ""
74
+ return f"{self.name} [{self.provider}] {self.model}{base} — {self.masked_key}"
75
+
76
+
77
+ def mask_key(api_key: str) -> str:
78
+ """Mask an API key for display, e.g. ``sk-abc…wxyz``."""
79
+ if not api_key:
80
+ return "(empty)"
81
+ if len(api_key) <= 8:
82
+ return api_key[:2] + "…" + api_key[-2:]
83
+ return api_key[:6] + "…" + api_key[-4:]
84
+
85
+
86
+ # ── Runtime (UI-added) endpoints ────────────────────────────────────────────
87
+ # Endpoints entered in the web UI are kept in-memory only: they are never
88
+ # written to disk and disappear when the app process restarts. They are
89
+ # layered on top of the env-var endpoints below, so both are available and
90
+ # a UI-added endpoint with the same name as an env one takes precedence.
91
+ _session_endpoints: dict[str, EndpointConfig] = {}
92
+ # Guards the registry above — Gradio serves events from a thread pool, so
93
+ # concurrent visitors may register/clear endpoints at the same time.
94
+ _session_lock = threading.Lock()
95
+
96
+
97
+ def register_endpoint(
98
+ name: str,
99
+ provider: str = "openai",
100
+ api_key: str = "",
101
+ base_url: Optional[str] = None,
102
+ model: str = "",
103
+ ) -> EndpointConfig:
104
+ """Register (or replace) an endpoint added at runtime via the UI.
105
+
106
+ Validation is strict so a review never runs on a half-configured entry:
107
+
108
+ * ``name`` and ``model`` are required
109
+ * ``api_key`` is required (use a placeholder such as ``dummy`` for
110
+ keyless local servers like Ollama)
111
+ * ``provider`` must be one of :data:`SUPPORTED_PROVIDERS`
112
+
113
+ Returns the stored :class:`EndpointConfig`. Re-registering the same
114
+ name overwrites the previous entry.
115
+ """
116
+ name = (name or "").strip()
117
+ provider = (provider or "openai").strip().lower()
118
+ model = (model or "").strip()
119
+ api_key = (api_key or "").strip()
120
+ base_url = (base_url or "").strip() or None
121
+
122
+ if not name:
123
+ raise ValueError("Endpoint name is required.")
124
+ if not model:
125
+ raise ValueError("Model name is required.")
126
+ if not api_key:
127
+ raise ValueError("API key is required (use 'dummy' for keyless local servers).")
128
+ if provider not in SUPPORTED_PROVIDERS:
129
+ raise ValueError(
130
+ f"Unsupported type {provider!r} — use one of {SUPPORTED_PROVIDERS}."
131
+ )
132
+
133
+ cfg = EndpointConfig(
134
+ name=name,
135
+ provider=provider,
136
+ api_key=api_key,
137
+ base_url=base_url,
138
+ model=model,
139
+ )
140
+ with _session_lock:
141
+ if name in _scan_env_endpoints_by_name() or any(
142
+ ep.name == name for ep in builtin_endpoints()
143
+ ):
144
+ logger.warning(
145
+ "Session endpoint %r shadows an existing endpoint "
146
+ "(OCR_ENDPOINT_* env or built-in) with the same name for "
147
+ "the rest of this process.",
148
+ name,
149
+ )
150
+ _session_endpoints[name] = cfg
151
+ logger.info("Registered session endpoint %r (%s / %s)", name, provider, model)
152
+ return cfg
153
+
154
+
155
+ def clear_session_endpoints() -> None:
156
+ """Remove every endpoint that was added at runtime via the UI."""
157
+ with _session_lock:
158
+ _session_endpoints.clear()
159
+
160
+ def unregister_endpoint(name: str) -> None:
161
+ """Remove one ephemeral user endpoint and its API key from memory."""
162
+ with _session_lock:
163
+ _session_endpoints.pop(name, None)
164
+
165
+
166
+ def session_endpoints() -> list[EndpointConfig]:
167
+ """Endpoints added at runtime via the UI (env-var ones excluded)."""
168
+ with _session_lock:
169
+ return list(_session_endpoints.values())
170
+
171
+
172
+ def _scan_env_endpoints() -> list[EndpointConfig]:
173
+ """Scan the environment for ``OCR_ENDPOINT_<n>_*`` configs.
174
+
175
+ Each index is read independently. An endpoint is registered only when
176
+ it has at least a name and a model (the API key is required to actually
177
+ build a client, but a key-less entry is still listed so the UI can show
178
+ \"missing key\"). Entries are returned sorted by index.
179
+ """
180
+ groups: dict[int, dict[str, str]] = {}
181
+ for env_key, value in os.environ.items():
182
+ if not env_key.startswith(ENDPOINT_ENV_PREFIX):
183
+ continue
184
+ rest = env_key[len(ENDPOINT_ENV_PREFIX):]
185
+ if "_" not in rest:
186
+ continue
187
+ idx_str, attr = rest.split("_", 1)
188
+ if not idx_str.isdigit():
189
+ continue
190
+ groups.setdefault(int(idx_str), {})[attr.lower()] = value.strip()
191
+
192
+ endpoints: list[EndpointConfig] = []
193
+ for idx in sorted(groups):
194
+ g = groups[idx]
195
+ name = g.get("name") or f"endpoint-{idx}"
196
+ if not g.get("model"):
197
+ # Incomplete config — skip (must at least have a model)
198
+ continue
199
+ endpoints.append(
200
+ EndpointConfig(
201
+ index=idx,
202
+ name=name,
203
+ provider=g.get("type") or g.get("provider") or "openai",
204
+ api_key=g.get("api_key") or "",
205
+ base_url=g.get("base_url") or None,
206
+ model=g.get("model") or "",
207
+ )
208
+ )
209
+ return endpoints
210
+
211
+
212
+ def _scan_env_endpoints_by_name() -> dict[str, EndpointConfig]:
213
+ """Env endpoints keyed by name (helper for collision checks)."""
214
+ return {ep.name: ep for ep in _scan_env_endpoints()}
215
+
216
+
217
+ def builtin_endpoints() -> list[EndpointConfig]:
218
+ """The always-available built-in providers (Gemini, Grok).
219
+
220
+ These are surfaced as selectable endpoints so the UI/CLI can choose
221
+ explicitly between them. They read their keys from the standard
222
+ ``GEMINI_API_KEY`` / ``GROQ_API_KEY`` env vars and run on the same
223
+ models as the default (no-endpoint) path.
224
+ """
225
+ from backend.integrations.llm_factory import GEMINI_MODEL, GROQ_MODEL
226
+
227
+ return [
228
+ EndpointConfig(
229
+ name="Gemini",
230
+ provider="google",
231
+ api_key=os.environ.get("GEMINI_API_KEY", "").strip(),
232
+ model=GEMINI_MODEL,
233
+ builtin=True,
234
+ ),
235
+ EndpointConfig(
236
+ name="Grok",
237
+ provider="openai",
238
+ api_key=os.environ.get("GROQ_API_KEY", "").strip(),
239
+ base_url="https://api.groq.com/openai/v1",
240
+ model=GROQ_MODEL,
241
+ builtin=True,
242
+ ),
243
+ ]
244
+
245
+
246
+ def discover_endpoints() -> list[EndpointConfig]:
247
+ """All available endpoints: built-ins + env-var configs + UI-added ones.
248
+
249
+ Precedence on name collision: UI-added (session) > env-var > built-in.
250
+ Entries are returned sorted by name.
251
+ """
252
+ merged: dict[str, EndpointConfig] = {
253
+ ep.name: ep for ep in builtin_endpoints()
254
+ }
255
+ merged.update(_scan_env_endpoints_by_name())
256
+ with _session_lock:
257
+ for ep in _session_endpoints.values():
258
+ merged[ep.name] = ep
259
+ return [merged[k] for k in sorted(merged)]
260
+
261
+
262
+ def get_endpoint(name: str | None) -> Optional[EndpointConfig]:
263
+ """Return the endpoint whose name matches, or ``None``.
264
+
265
+ Resolution order: UI-added (session) → env-var → built-in.
266
+ """
267
+ if not name:
268
+ return None
269
+ with _session_lock:
270
+ session_ep = _session_endpoints.get(name)
271
+ if session_ep is not None:
272
+ return session_ep
273
+ env_ep = _scan_env_endpoints_by_name().get(name)
274
+ if env_ep is not None:
275
+ return env_ep
276
+ return next((b for b in builtin_endpoints() if b.name == name), None)
277
+
278
+
279
+ def dropdown_choices() -> list[str | tuple[str, list[str]]]:
280
+ """Choices for the UI dropdown.
281
+
282
+ Built-in providers (Gemini, Grok) appear under a ``"Built-in"``
283
+ optgroup so the user can pick a *section* for them. Custom endpoints
284
+ are listed as flat entries under their own specified name — NOT grouped
285
+ under a "Custom" header — so an added endpoint is immediately
286
+ identifiable by name in the list. An empty string entry keeps the
287
+ "auto" (no-endpoint) option first.
288
+
289
+ A built-in is omitted from its group when a custom endpoint shadows it
290
+ by name (session > env > built-in precedence), so each name appears
291
+ exactly once.
292
+ """
293
+ custom_names = [
294
+ ep.name for ep in discover_endpoints() if not ep.builtin
295
+ ]
296
+ builtin_names = [
297
+ ep.name for ep in builtin_endpoints()
298
+ if ep.name not in custom_names
299
+ ]
300
+ choices: list = [""]
301
+ if builtin_names:
302
+ choices.append(("Built-in", builtin_names))
303
+ # Custom endpoints appear as their own named entries (flat), so the
304
+ # user sees e.g. "DeepSeek V4" instead of a generic "Custom" group.
305
+ choices.extend(custom_names)
306
+ return choices
backend/integrations/github_client.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Shared GitHub API client with automatic token resolution and 401 resilience.
3
+
4
+ Caching
5
+ -------
6
+ All HTTP requests made through ``requests`` within this process are cached
7
+ to a local SQLite backend with a 15-minute TTL, so re-reviewing the same PR
8
+ does not re-fetch data from GitHub.
9
+
10
+ Usage
11
+ -----
12
+ from backend.integrations.github_client import GitHubSession, resolve_token, guard_401
13
+
14
+ # Preferred: use the session for all API calls
15
+ session = GitHubSession()
16
+ resp = session.get("https://api.github.com/repos/psf/requests")
17
+
18
+ # Decorator for standalone functions
19
+ @guard_401
20
+ def my_api_call():
21
+ ...
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import functools
27
+ import logging
28
+ import os
29
+ from typing import Optional
30
+
31
+ import keyring
32
+ import requests
33
+
34
+ logger = logging.getLogger(__name__)
35
+
36
+ SERVICE_NAME = "opencodereview"
37
+
38
+ # ─── Global HTTP cache ─────────────────────────────────────────────────────────
39
+ # Cache all requests (GitHub API + raw content) to a local SQLite store
40
+ # so re-reviewing the same PR avoids redundant network fetches.
41
+ _CACHE_BACKEND = None
42
+
43
+
44
+ def _init_cache() -> None:
45
+ """Install ``requests-cache`` with a 15-minute TTL.
46
+
47
+ Patches ``requests.Session`` globally, so :class:`GitHubSession`
48
+ (which inherits from it) automatically gets caching. Safe to call
49
+ multiple times — subsequent calls are no-ops.
50
+ """
51
+ global _CACHE_BACKEND
52
+ if _CACHE_BACKEND is not None:
53
+ return
54
+ try:
55
+ import requests_cache
56
+
57
+ cache_dir = os.environ.get(
58
+ "OPENCODEREVIEW_CACHE_DIR",
59
+ os.path.join(os.getcwd(), ".opencodereview"),
60
+ )
61
+ os.makedirs(cache_dir, exist_ok=True)
62
+ db_path = os.path.join(cache_dir, "http_cache.sqlite")
63
+ _CACHE_BACKEND = requests_cache.install_cache(
64
+ cache_name=db_path,
65
+ backend="sqlite",
66
+ expire_after=900, # 15 minutes
67
+ allowable_codes=(200, 404),
68
+ )
69
+ logger.debug("HTTP cache initialised at %s", db_path)
70
+ except ImportError:
71
+ logger.debug("requests-cache not installed — skipping HTTP cache")
72
+ except Exception as exc:
73
+ logger.warning("Failed to initialise HTTP cache: %s", exc)
74
+
75
+
76
+ # ─── Exceptions ──────────────────────────────────────────────────────────────
77
+
78
+
79
+ class TokenRevokedError(Exception):
80
+ """Raised when a GitHub API call returns 401 (token invalid or revoked)."""
81
+
82
+
83
+ # ─── Token resolution ───────────────────────────────────────────────────────
84
+
85
+
86
+ def resolve_token() -> Optional[str]:
87
+ """Return a GitHub token from:
88
+
89
+ 1. The system keyring (set via ``opencodereview auth login``)
90
+ 2. The ``GITHUB_TOKEN`` environment variable
91
+
92
+ Returns ``None`` if neither source has a token, so callers can fall back
93
+ gracefully (e.g., dry-run mode in the executor).
94
+ """
95
+ # Try keyring first (auth login stores here)
96
+ try:
97
+ token = keyring.get_password(SERVICE_NAME, "github_token")
98
+ if token:
99
+ return token
100
+ except Exception:
101
+ pass # keyring back-end unavailable (headless CI, etc.)
102
+
103
+ # Fall back to env var
104
+ token = os.environ.get("GITHUB_TOKEN")
105
+ return token.strip() if token else None
106
+
107
+
108
+ # ─── 401 decorator ──────────────────────────────────────────────────────────
109
+
110
+
111
+ def guard_401(func):
112
+ """Decorator: catch 401 responses from GitHub API calls and raise
113
+ :class:`TokenRevokedError` with a helpful message.
114
+
115
+ Use this on any standalone function that makes GitHub API calls and
116
+ calls ``raise_for_status()``.
117
+
118
+ For functions that use :class:`GitHubSession` the 401 handling happens
119
+ automatically — no decorator needed.
120
+ """
121
+ @functools.wraps(func)
122
+ def wrapper(*args, **kwargs):
123
+ try:
124
+ return func(*args, **kwargs)
125
+ except requests.HTTPError as exc:
126
+ if exc.response is not None and exc.response.status_code == 401:
127
+ raise TokenRevokedError(
128
+ "Your GitHub token appears to be invalid or has been "
129
+ "revoked.\n\n"
130
+ " Re-authenticate:\n"
131
+ " opencodereview auth login\n\n"
132
+ " Or update the GITHUB_TOKEN environment variable.\n"
133
+ ) from exc
134
+ raise
135
+ return wrapper
136
+
137
+
138
+ # ─── Custom Session ─────────────────────────────────────────────────────────
139
+
140
+
141
+ class GitHubSession(requests.Session):
142
+ """A :class:`requests.Session` subclass that:
143
+
144
+ * Auto-resolves the GitHub token from keyring then env var
145
+ * Sends ``Authorization`` and standard headers on every request
146
+ * Raises :class:`TokenRevokedError` on ``401`` responses from
147
+ ``api.github.com``
148
+
149
+ Usage
150
+ -----
151
+ session = GitHubSession()
152
+ resp = session.get("https://api.github.com/repos/psf/requests")
153
+ """
154
+
155
+ def __init__(self, token: Optional[str] = None) -> None:
156
+ super().__init__()
157
+ self.token = token or resolve_token()
158
+ self.headers.update({
159
+ "Accept": "application/vnd.github.v3+json",
160
+ "User-Agent": "OpenCodeReview/1.0",
161
+ })
162
+ if self.token:
163
+ self.headers["Authorization"] = f"Bearer {self.token}"
164
+
165
+ def request(self, method, url, *args, **kwargs):
166
+ """Override :meth:`requests.Session.request` to intercept 401
167
+ responses from ``api.github.com``."""
168
+ resp = super().request(method, url, *args, **kwargs)
169
+ # Only intercept 401 from the GitHub API, not raw content or other hosts
170
+ if resp.status_code == 401 and "api.github.com" in url:
171
+ raise TokenRevokedError(
172
+ "Your GitHub token appears to be invalid or has been "
173
+ "revoked.\n\n"
174
+ " Re-authenticate:\n"
175
+ " opencodereview auth login\n\n"
176
+ " Or update the GITHUB_TOKEN environment variable.\n"
177
+ )
178
+ return resp
backend/integrations/llm_factory.py ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """LLM factory — creates LangChain chat models with primary + fallback support.
2
+
3
+ Priority
4
+ --------
5
+ 1. **Google Gemini** (primary) — uses ``GEMINI_API_KEY`` env var.
6
+ Model: ``gemini-3.1-flash-lite`` — generous free tier.
7
+ 2. **Groq** (fallback) — uses ``GROQ_API_KEY`` env var.
8
+ Model: ``llama-3.3-70b-versatile`` — fast inference, lower free limit.
9
+
10
+ If neither key is set, functions raise ``ValueError`` so callers can skip
11
+ gracefully (as they already do for Groq-only today).
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import logging
17
+ import os
18
+ from typing import Any, Optional
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+ # Gemini 3.1 Flash model name as of 2026-07
23
+ # Verified via Google AI documentation: gemini-3.1-flash-lite is the correct name.
24
+ # The base 'gemini-3.1-flash' does not exist in the API.
25
+ GEMINI_MODEL = "gemini-3.1-flash-lite"
26
+ GROQ_MODEL = os.getenv("GROQ_MODEL", "openai/gpt-oss-20b")
27
+ DEFAULT_TEMPERATURE = 0.0
28
+ DEFAULT_REQUEST_TIMEOUT = float(os.getenv("OCR_MODEL_TIMEOUT_SECONDS", "60"))
29
+ DEFAULT_OUTPUT_TOKENS = int(os.getenv("OCR_MODEL_MAX_OUTPUT_TOKENS", "2000"))
30
+
31
+
32
+ def _get_gemini_chat(**kwargs: Any) -> Optional[Any]:
33
+ """Create a ``ChatGoogleGenerativeAI`` instance if ``GEMINI_API_KEY`` is set.
34
+
35
+ Returns ``None`` silently when the key is missing or the package is not
36
+ installed — callers are expected to fall back.
37
+ """
38
+ kwargs.setdefault("timeout", DEFAULT_REQUEST_TIMEOUT)
39
+ kwargs.setdefault("max_retries", 0)
40
+ kwargs.setdefault("max_tokens", DEFAULT_OUTPUT_TOKENS)
41
+ api_key = os.environ.get("GEMINI_API_KEY", "").strip()
42
+ if not api_key:
43
+ return None
44
+
45
+ try:
46
+ from langchain_google_genai import ChatGoogleGenerativeAI
47
+
48
+ return ChatGoogleGenerativeAI(
49
+ model=kwargs.pop("model", GEMINI_MODEL),
50
+ temperature=kwargs.pop("temperature", DEFAULT_TEMPERATURE),
51
+ google_api_key=api_key,
52
+ **kwargs,
53
+ )
54
+ except ImportError:
55
+ logger.warning("langchain-google-genai not installed — skipping Gemini")
56
+ return None
57
+ except Exception as exc:
58
+ logger.warning("Failed to initialise Gemini: %s", exc)
59
+ return None
60
+
61
+
62
+ def _get_groq_chat(**kwargs: Any) -> Optional[Any]:
63
+ """Create a ``ChatGroq`` instance if ``GROQ_API_KEY`` is set."""
64
+ kwargs.setdefault("timeout", DEFAULT_REQUEST_TIMEOUT)
65
+ kwargs.setdefault("max_retries", 0)
66
+ kwargs.setdefault("max_tokens", DEFAULT_OUTPUT_TOKENS)
67
+ api_key = os.environ.get("GROQ_API_KEY", "").strip()
68
+ if not api_key:
69
+ return None
70
+
71
+ try:
72
+ from langchain_groq import ChatGroq
73
+
74
+ return ChatGroq(
75
+ model=kwargs.pop("model", GROQ_MODEL),
76
+ temperature=kwargs.pop("temperature", DEFAULT_TEMPERATURE),
77
+ api_key=api_key,
78
+ **kwargs,
79
+ )
80
+ except ImportError:
81
+ logger.warning("langchain-groq not installed")
82
+ return None
83
+ except Exception as exc:
84
+ logger.warning("Failed to initialise Groq: %s", exc)
85
+ return None
86
+
87
+
88
+ def create_endpoint_llm(endpoint, **kwargs: Any) -> Any:
89
+ """Create a chat model from a user-configured custom endpoint.
90
+
91
+ Supports OpenAI-compatible APIs (DeepSeek, OpenRouter, vLLM, Ollama,
92
+ Groq, Together, ...), Anthropic Claude, and Google Gemini.
93
+
94
+ Parameters
95
+ ----------
96
+ endpoint : EndpointConfig
97
+ The user's endpoint config (name, provider, api_key, base_url, model).
98
+ **kwargs
99
+ Passed through to the underlying LangChain constructor (e.g.
100
+ ``temperature``). ``model`` / ``api_key`` / ``base_url`` come from
101
+ the endpoint and cannot be overridden here.
102
+
103
+ Returns
104
+ -------
105
+ Any
106
+ A LangChain chat model instance (``ChatOpenAI``, ``ChatAnthropic``
107
+ or ``ChatGoogleGenerativeAI``).
108
+
109
+ Raises
110
+ ------
111
+ ValueError
112
+ If the endpoint's provider package is not installed or the config
113
+ is incomplete.
114
+ """
115
+ if not endpoint.api_key or not endpoint.model:
116
+ raise ValueError(
117
+ f"Endpoint '{endpoint.name}' is missing an API key or model name."
118
+ )
119
+
120
+ kwargs.setdefault("timeout", DEFAULT_REQUEST_TIMEOUT)
121
+ kwargs.setdefault("max_retries", 0)
122
+ kwargs.setdefault("max_tokens", DEFAULT_OUTPUT_TOKENS)
123
+ provider = endpoint.provider
124
+ model = endpoint.model
125
+ # MiniMax M3.1 requires reasoning and OpenRouter defaults to max effort.
126
+ # Reserve room for reasoning + visible JSON rather than truncating at 1200.
127
+ if 'minimax-m3.1' in model.lower():
128
+ kwargs['max_tokens'] = max(int(kwargs.get('max_tokens') or 0), 8192)
129
+ if endpoint.base_url and 'openrouter.ai' in endpoint.base_url:
130
+ extra = dict(kwargs.get('extra_body') or {})
131
+ extra['reasoning'] = {'effort': 'low'}
132
+ kwargs['extra_body'] = extra
133
+ temperature = kwargs.pop("temperature", DEFAULT_TEMPERATURE)
134
+
135
+ if provider == "anthropic":
136
+ try:
137
+ from langchain_anthropic import ChatAnthropic
138
+ except ImportError:
139
+ raise ValueError(
140
+ "langchain-anthropic is not installed — cannot use endpoint "
141
+ f"'{endpoint.name}'. Run: pip install langchain-anthropic"
142
+ ) from None
143
+ params: dict[str, Any] = {
144
+ "model": model,
145
+ "api_key": endpoint.api_key,
146
+ "temperature": temperature,
147
+ }
148
+ if endpoint.base_url:
149
+ params["base_url"] = endpoint.base_url
150
+ params.update(kwargs)
151
+ return ChatAnthropic(**params)
152
+
153
+ if provider == "google":
154
+ try:
155
+ from langchain_google_genai import ChatGoogleGenerativeAI
156
+ except ImportError:
157
+ raise ValueError(
158
+ "langchain-google-genai is not installed — cannot use endpoint "
159
+ f"'{endpoint.name}'. Run: pip install langchain-google-genai"
160
+ ) from None
161
+ params = {
162
+ "model": model,
163
+ "google_api_key": endpoint.api_key,
164
+ "temperature": temperature,
165
+ }
166
+ params.update(kwargs)
167
+ return ChatGoogleGenerativeAI(**params)
168
+
169
+ # Default: OpenAI-compatible
170
+ try:
171
+ from langchain_openai import ChatOpenAI
172
+ except ImportError:
173
+ raise ValueError(
174
+ "langchain-openai is not installed — cannot use endpoint "
175
+ f"'{endpoint.name}'. Run: pip install langchain-openai"
176
+ ) from None
177
+ params = {
178
+ "model": model,
179
+ "api_key": endpoint.api_key,
180
+ "temperature": temperature,
181
+ }
182
+ if endpoint.base_url:
183
+ params["base_url"] = endpoint.base_url
184
+ params.update(kwargs)
185
+ return ChatOpenAI(**params)
186
+
187
+
188
+ def create_llm(endpoint=None, **kwargs: Any) -> Any:
189
+ """Create a chat LLM — custom endpoint first, else Gemini → Groq.
190
+
191
+ Parameters
192
+ ----------
193
+ endpoint : EndpointConfig or str or None
194
+ A custom endpoint to run on (``EndpointConfig`` object or its name).
195
+ ``None`` (default) falls back to the built-in providers.
196
+ **kwargs
197
+ Passed through to the underlying LangChain constructor.
198
+ Common overrides: ``model``, ``temperature``.
199
+
200
+ Returns
201
+ -------
202
+ Any
203
+ A LangChain chat model instance (``ChatOpenAI``/``ChatAnthropic``/
204
+ ``ChatGoogleGenerativeAI`` from a custom endpoint, or the built-in
205
+ ``ChatGoogleGenerativeAI`` / ``ChatGroq``).
206
+
207
+ Raises
208
+ ------
209
+ ValueError
210
+ If a custom endpoint is named but not found, or no provider key is set.
211
+ """
212
+ if endpoint:
213
+ from backend.integrations.endpoints import EndpointConfig, get_endpoint
214
+
215
+ # The browser historically sent lowercase builtin ids while the
216
+ # endpoint registry uses display names. Accept both for API clients.
217
+ if isinstance(endpoint, str):
218
+ endpoint = {"gemini": "Gemini", "groq": "Grok"}.get(endpoint.lower(), endpoint)
219
+ ep = endpoint if isinstance(endpoint, EndpointConfig) else get_endpoint(endpoint)
220
+ if ep is not None:
221
+ if getattr(ep, "builtin", False):
222
+ # Built-in providers use their native constructors so the
223
+ # behaviour is identical to the default (no-endpoint) path.
224
+ if ep.name == "Gemini":
225
+ llm = _get_gemini_chat(**kwargs)
226
+ if llm is not None:
227
+ logger.info(
228
+ "Using built-in Gemini endpoint (model=%s)",
229
+ kwargs.get("model", GEMINI_MODEL),
230
+ )
231
+ return llm
232
+ raise ValueError(
233
+ "Gemini selected but GEMINI_API_KEY is not set."
234
+ )
235
+ if ep.name == "Grok":
236
+ llm = _get_groq_chat(**kwargs)
237
+ if llm is not None:
238
+ logger.info(
239
+ "Using built-in Grok endpoint (model=%s)",
240
+ kwargs.get("model", GROQ_MODEL),
241
+ )
242
+ return llm
243
+ raise ValueError(
244
+ "Grok selected but GROQ_API_KEY is not set."
245
+ )
246
+ try:
247
+ llm = create_endpoint_llm(ep, **kwargs)
248
+ logger.info("Using custom endpoint %s (%s/%s)", ep.name, ep.provider, ep.model)
249
+ return llm
250
+ except ValueError:
251
+ raise
252
+ else:
253
+ raise ValueError(
254
+ f"Custom endpoint '{endpoint}' not found. "
255
+ "Configure it via OCR_ENDPOINT_* environment variables "
256
+ "or add it in the UI."
257
+ )
258
+
259
+ # Prefer Groq when configured: it has a separate quota pool and avoids
260
+ # stalling the review pipeline on Gemini free-tier exhaustion.
261
+ llm = _get_groq_chat(**kwargs)
262
+ if llm is not None:
263
+ logger.debug("Using Groq (model=%s)", kwargs.get("model", GROQ_MODEL))
264
+ return llm
265
+
266
+ llm = _get_gemini_chat(**kwargs)
267
+ if llm is not None:
268
+ logger.debug("Falling back to Gemini (model=%s)", kwargs.get("model", GEMINI_MODEL))
269
+ return llm
270
+
271
+ raise ValueError(
272
+ "No LLM available. Set GEMINI_API_KEY (primary) or GROQ_API_KEY (fallback)."
273
+ )
backend/main.py ADDED
@@ -0,0 +1,592 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """OpenCodeReview — AI-powered PR review with human-in-the-loop approval.
3
+
4
+ Usage
5
+ -----
6
+ opencodereview auth login
7
+ opencodereview auth status
8
+ opencodereview auth logout
9
+ opencodereview review [--smoke]
10
+ opencodereview --help
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import logging
16
+ import os
17
+ import sys
18
+ import time
19
+ import uuid
20
+
21
+ import click
22
+ from langgraph.types import Command
23
+
24
+ from backend.integrations.auth import auth as auth_group
25
+ from backend.integrations.config import config as config_group
26
+ from backend.graph import build_graph
27
+ from backend.observability import (
28
+ build_run_metadata,
29
+ enable_langsmith,
30
+ get_langfuse_handler,
31
+ is_langsmith_enabled,
32
+ estimate_groq_cost,
33
+ flush_langfuse,
34
+ format_cost,
35
+ langfuse_trace,
36
+ log_error_to_backends,
37
+ log_langfuse_score,
38
+ _resolve_langfuse_trace_id,
39
+ TokenCostCallback,
40
+ )
41
+ from backend.state import ChangedFile, ContextChunk, Finding, Severity, Verdict
42
+
43
+ logging.basicConfig(
44
+ level=logging.INFO,
45
+ format="%(asctime)s [%(levelname)s] %(name)s — %(message)s",
46
+ )
47
+ logger = logging.getLogger(__name__)
48
+
49
+ DB_PATH = "checkpoints.db"
50
+
51
+ NODE_LABELS: dict[str, str] = {
52
+ "ingestion": "📥 Ingestion",
53
+ "retrieval": "🔍 Retrieval",
54
+ "correctness_review": "✅ Correctness Review",
55
+ "security_review": "🔒 Security Review",
56
+ "test_coverage_review": "🧪 Test Coverage Review",
57
+ "aggregator": "📊 Aggregation",
58
+ }
59
+
60
+
61
+ # ─── Observability initialisation ──────────────────────────────────────────
62
+
63
+
64
+ def _init_observability() -> None:
65
+ """Initialise tracing backends and HTTP cache from env vars / keyring.
66
+
67
+ Called once at the start of each ``review`` command.
68
+ """
69
+ from backend.integrations.github_client import _init_cache as _init_http_cache
70
+ _init_http_cache()
71
+
72
+ import keyring as _kr
73
+ from backend.integrations.config import SERVICE_NAME as _svc
74
+
75
+ # LangSmith: favour env var (check modern LANGSMITH_API_KEY first, then legacy)
76
+ ls_key = (
77
+ os.environ.get("LANGSMITH_API_KEY")
78
+ or os.environ.get("LANGCHAIN_API_KEY")
79
+ or _kr.get_password(_svc, "langsmith_api_key")
80
+ )
81
+ if ls_key:
82
+ ls_project = (
83
+ os.environ.get("LANGSMITH_PROJECT")
84
+ or os.environ.get("LANGCHAIN_PROJECT")
85
+ or _kr.get_password(_svc, "langsmith_project")
86
+ or "opencodereview"
87
+ )
88
+ enable_langsmith(ls_key, ls_project)
89
+
90
+ # Langfuse: env var overrides keyring
91
+ for env_key, ring_key in [
92
+ ("LANGFUSE_PUBLIC_KEY", "langfuse_public_key"),
93
+ ("LANGFUSE_SECRET_KEY", "langfuse_secret_key"),
94
+ ("LANGFUSE_HOST", "langfuse_host"),
95
+ ]:
96
+ if not os.environ.get(env_key):
97
+ val = _kr.get_password(_svc, ring_key)
98
+ if val:
99
+ os.environ[env_key] = val
100
+
101
+ if is_langsmith_enabled():
102
+ logger.info("Observability: LangSmith enabled")
103
+ if get_langfuse_handler():
104
+ logger.info("Observability: Langfuse enabled")
105
+
106
+
107
+ # ─── Synthetic payload for offline testing ──────────────────────────────────
108
+
109
+ SYNTHETIC_STATE = {
110
+ "repo": "demo-org/demo-repo",
111
+ "pr_number": 1,
112
+ "diff": (
113
+ "diff --git a/src/auth.py b/src/auth.py\n"
114
+ "index abc123..def456 100644\n"
115
+ "--- a/src/auth.py\n"
116
+ "+++ b/src/auth.py\n"
117
+ "@@ -42,7 +42,9 @@ def login(username, password):\n"
118
+ " user = db.get_user(username)\n"
119
+ "- if user.password == password:\n"
120
+ "+ if constant_time_compare(password, user.password):\n"
121
+ " return create_session(user)\n"
122
+ " return None\n"
123
+ ),
124
+ "changed_files": [
125
+ ChangedFile(
126
+ path="src/auth.py",
127
+ status="modified",
128
+ content="def login(username, password):\n"
129
+ " user = db.get_user(username)\n"
130
+ " if constant_time_compare(password, user.password):\n"
131
+ " return create_session(user)\n"
132
+ " return None\n",
133
+ diff_hunk="@@ -42,7 +42,9 @@ def login(username, password): ...",
134
+ ),
135
+ ],
136
+ "context_chunks": [
137
+ ContextChunk(
138
+ source="codebase", file_path="src/db.py",
139
+ content="def get_user(username): ...",
140
+ relevance_score=0.92,
141
+ ),
142
+ ],
143
+ "findings": [
144
+ Finding(
145
+ file_path="src/auth.py", line_start=42, line_end=50,
146
+ severity=Severity.CRITICAL, category="security",
147
+ comment="Use constant-time comparison for passwords.",
148
+ confidence=0.95,
149
+ ),
150
+ ],
151
+ "verdict": Verdict(
152
+ summary="Critical security vulnerability found.",
153
+ approved=False, overall_score=3.5, critical_count=1,
154
+ high_count=0, recommendation="block",
155
+ ),
156
+ }
157
+
158
+
159
+ # ─── Review Command ─────────────────────────────────────────────────────────
160
+
161
+
162
+ @click.command()
163
+ @click.option(
164
+ "--smoke", is_flag=True,
165
+ help="Non-interactive smoke test (skips HITL prompt).",
166
+ )
167
+ @click.option(
168
+ "--repo",
169
+ default="demo-org/demo-repo",
170
+ show_default=True,
171
+ help="GitHub repository (owner/name).",
172
+ )
173
+ @click.option(
174
+ "--pr", "pr_number",
175
+ default=1,
176
+ show_default=True,
177
+ help="Pull request number.",
178
+ )
179
+ @click.option(
180
+ "--endpoint", "endpoint_name",
181
+ default="",
182
+ show_default=True,
183
+ help="LLM endpoint: Gemini/Grok (built-ins) or a custom name (see OCR_ENDPOINT_* env vars).",
184
+ )
185
+ def review(repo: str, pr_number: int, smoke: bool, endpoint_name: str) -> None:
186
+ """Run a PR review with human-in-the-loop approval.
187
+
188
+ By default this runs with a synthetic PR payload for demonstration.
189
+ """
190
+ # ── Enable LangSmith if key is available ─────────────────────────
191
+ _init_observability()
192
+
193
+ graph = build_graph(DB_PATH)
194
+
195
+ try:
196
+ if smoke:
197
+ _test_offline(graph)
198
+ else:
199
+ _run_with_hitl(graph, repo, pr_number, endpoint_name)
200
+ finally:
201
+ # Close the graph's SQLite connection (checkpoints persist to disk,
202
+ # so a later resume can open a fresh one) and clean up the DB file.
203
+ conn = getattr(graph, "_opencodereview_conn", None)
204
+ if conn:
205
+ conn.close()
206
+ _cleanup_db()
207
+ # Ship any queued Langfuse scores before the process exits.
208
+ flush_langfuse()
209
+
210
+
211
+ def _run_with_hitl(graph, repo: str, pr_number: int, endpoint_name: str = "") -> None:
212
+ """Run the graph on a real PR — fetches data from GitHub, pauses for
213
+ human approval, then posts findings back as PR comments.
214
+
215
+ Parameters
216
+ ----------
217
+ endpoint_name : str
218
+ Optional custom LLM endpoint name (``OCR_ENDPOINT_*``) to run the
219
+ reviewers on. Empty string uses the built-in default provider.
220
+ """
221
+ thread_id = str(uuid.uuid4())
222
+ trace_name = f"opencodereview/review/{repo}#{pr_number}"
223
+ tags = ["cli", repo]
224
+ prompt_versions = {
225
+ "correctness": "v1",
226
+ "security": "v1",
227
+ "test_coverage": "v1",
228
+ "aggregator": "v1",
229
+ }
230
+ cost_tracker = TokenCostCallback()
231
+ metadata = build_run_metadata(
232
+ source="cli", repo=repo, pr_number=pr_number,
233
+ session_id=thread_id,
234
+ prompt_versions=prompt_versions,
235
+ )
236
+ config: dict = {
237
+ "configurable": {"thread_id": f"hitl-{thread_id}"},
238
+ "metadata": metadata,
239
+ }
240
+
241
+ # Use synthetic demo data by default; only fetch real PRs when the
242
+ # user explicitly provides a custom repo or PR number.
243
+ is_default = (repo == "demo-org/demo-repo" and pr_number == 1)
244
+ if is_default:
245
+ logger.info(
246
+ "Using synthetic demo data — pass --repo and --pr to "
247
+ "review a real PR from GitHub.\n"
248
+ )
249
+ initial_state = SYNTHETIC_STATE
250
+ else:
251
+ logger.info(
252
+ "Starting review of %s#%d … fetching PR data from GitHub.\n",
253
+ repo, pr_number,
254
+ )
255
+ initial_state = {
256
+ "repo": repo,
257
+ "pr_number": pr_number,
258
+ }
259
+ if endpoint_name:
260
+ initial_state["endpoint"] = endpoint_name
261
+
262
+ with langfuse_trace(
263
+ trace_name=trace_name,
264
+ tags=tags,
265
+ session_id=thread_id,
266
+ metadata={
267
+ "source": "cli",
268
+ "repo": repo,
269
+ "pr_number": pr_number,
270
+ "prompt_versions": prompt_versions,
271
+ },
272
+ ) as handler:
273
+ callbacks = [cost_tracker]
274
+ if handler:
275
+ callbacks.append(handler)
276
+ config["callbacks"] = callbacks
277
+
278
+ t0 = time.time()
279
+ for event in graph.stream(initial_state, config):
280
+ for node_name in event:
281
+ label = NODE_LABELS.get(node_name, node_name)
282
+ logger.info(" ✔ %s (+%.1fs)", label, time.time() - t0)
283
+ logger.info(" ─── Pipeline complete in %.1fs ───", time.time() - t0)
284
+
285
+ state = graph.get_state(config)
286
+ tasks = state.tasks
287
+
288
+ if tasks:
289
+ logger.info("\n" + "=" * 60)
290
+ logger.info(" REVIEW RESULTS — HUMAN APPROVAL REQUIRED")
291
+ logger.info("=" * 60)
292
+
293
+ if state.values.get("verdict"):
294
+ v = state.values["verdict"]
295
+ logger.info(" Verdict: %s", v.recommendation.upper())
296
+ logger.info(" Score: %.1f/10", v.overall_score)
297
+ logger.info(" Summary: %s", v.summary)
298
+
299
+ final_findings = state.values.get("final_findings", [])
300
+ logger.info(" Findings: %d", len(final_findings))
301
+ for i, f in enumerate(final_findings, 1):
302
+ logger.info(
303
+ " %d. [%.0f%%] %s:%d–%d (%s)",
304
+ i, f.confidence * 100, f.file_path,
305
+ f.line_start, f.line_end, f.severity.value,
306
+ )
307
+ logger.info(" %s", f.comment[:120])
308
+
309
+ # Show cost & TTFT
310
+ logger.info(" %s", cost_tracker.summary())
311
+
312
+ # Capture trace_id NOW (immediately after graph completes)
313
+ # so it can be used after the long-running RAGAS computation.
314
+ run_trace_id = _resolve_langfuse_trace_id(handler)
315
+
316
+ # Log verdict score to Langfuse and update trace metadata
317
+ if state.values.get("verdict"):
318
+ v = state.values["verdict"]
319
+ log_langfuse_score(
320
+ name="verdict_score",
321
+ value=v.overall_score,
322
+ comment=f"{repo}#{pr_number} — {v.recommendation}: {v.summary[:100]}",
323
+ trace_id=run_trace_id,
324
+ handler=handler,
325
+ )
326
+ log_langfuse_score(
327
+ name="findings_count",
328
+ value=len(final_findings),
329
+ comment=f"{repo}#{pr_number}",
330
+ trace_id=run_trace_id,
331
+ handler=handler,
332
+ )
333
+
334
+ # ── Compute and log RAGAS retrieval scores ─────────────────
335
+ context_chunks = state.values.get("context_chunks", [])
336
+ if context_chunks:
337
+ try:
338
+ from eval_data.ragas_eval import compute_ragas_retrieval_scores
339
+
340
+ query = state.values.get("diff", "") or ""
341
+ contexts = [c.content for c in context_chunks if c.content]
342
+
343
+ # Build answer text from findings + verdict for
344
+ # faithfulness & answer_relevancy metrics
345
+ answer_lines = []
346
+ for f in final_findings:
347
+ answer_lines.append(
348
+ f"[{f.severity.value}] {f.file_path}:{f.line_start}-{f.line_end}: {f.comment}"
349
+ )
350
+ if state.values.get("verdict"):
351
+ v = state.values["verdict"]
352
+ answer_lines.append(
353
+ f"Verdict: {v.recommendation} (score={v.overall_score}/10) — {v.summary}"
354
+ )
355
+ answer_text = "\n".join(answer_lines) if answer_lines else None
356
+
357
+ ragas_scores = compute_ragas_retrieval_scores(
358
+ query=query,
359
+ retrieved_contexts=contexts,
360
+ answer=answer_text,
361
+ endpoint=endpoint_name or None,
362
+ )
363
+
364
+ # Log RAGAS scores with the explicitly captured trace_id
365
+ # to avoid contextvar loss during the long computation.
366
+ # handler=handler is also passed as fallback resolution.
367
+ for metric_name, value in ragas_scores.items():
368
+ if value is None:
369
+ continue
370
+ log_langfuse_score(
371
+ name=f"ragas_{metric_name}",
372
+ value=value,
373
+ comment=f"{repo}#{pr_number} — {metric_name}",
374
+ trace_id=run_trace_id,
375
+ handler=handler,
376
+ )
377
+
378
+ logger.info(
379
+ " RAGAS scores logged to Langfuse: %s",
380
+ " | ".join(
381
+ f"{k}={v:.4f}" for k, v in ragas_scores.items()
382
+ if v is not None
383
+ ),
384
+ )
385
+ except ImportError:
386
+ logger.info("RAGAS not installed — skipping RAGAS scoring (pip install ragas)")
387
+ except Exception as exc:
388
+ logger.warning("RAGAS scoring failed: %s", exc)
389
+
390
+ logger.info("=" * 60)
391
+
392
+ click.echo()
393
+ click.echo("-" * 50)
394
+ click.echo(" HUMAN-IN-THE-LOOP: Approve this review for posting?")
395
+ click.echo("-" * 50)
396
+ click.echo(" [a] Approve — post findings as GitHub comments")
397
+ click.echo(" [r] Reject — discard results, post nothing")
398
+ click.echo(" [q] Quit — leave graph paused")
399
+ click.echo()
400
+
401
+ choice = click.prompt(" Your choice", type=click.Choice(["a", "r", "q"], case_sensitive=False))
402
+
403
+ if choice == "a":
404
+ logger.info(" → Approved! Resuming graph to post results …")
405
+ graph.invoke(Command(resume={"action": "approve"}), config)
406
+ elif choice == "r":
407
+ logger.info(" → Rejected. Resuming graph without posting …")
408
+ graph.invoke(Command(resume={"action": "reject"}), config)
409
+ else:
410
+ logger.info(" → Exiting. Graph remains paused — resume later")
411
+ logger.info(
412
+ " Resume with: graph.invoke(Command(resume=...), %s)",
413
+ config,
414
+ )
415
+ return
416
+
417
+ final_state = graph.get_state(config)
418
+ final_values = final_state.values
419
+
420
+ logger.info("\n" + "=" * 60)
421
+ logger.info(" FINAL STATE")
422
+ logger.info("=" * 60)
423
+ logger.info(" Human approved: %s", final_values.get("human_approved"))
424
+ if final_values.get("verdict"):
425
+ logger.info(" Verdict: %s", final_values["verdict"].recommendation)
426
+ logger.info(" Final findings: %d", len(final_values.get("final_findings", [])))
427
+ logger.info(" %s", cost_tracker.summary())
428
+ logger.info("=" * 60)
429
+ else:
430
+ logger.info("Graph completed without interrupt (no findings to review?)")
431
+ logger.info(" %s", cost_tracker.summary())
432
+
433
+
434
+ def _test_offline(graph) -> None:
435
+ """Non-interactive test that the graph compiles and runs up to interrupt."""
436
+ thread_id = str(uuid.uuid4())
437
+ prompt_versions = {
438
+ "correctness": "v1",
439
+ "security": "v1",
440
+ "test_coverage": "v1",
441
+ "aggregator": "v1",
442
+ }
443
+ cost_tracker = TokenCostCallback()
444
+ metadata = build_run_metadata(
445
+ source="cli", repo="demo-org/demo-repo", pr_number=1,
446
+ session_id=thread_id,
447
+ prompt_versions=prompt_versions,
448
+ )
449
+ config: dict = {
450
+ "configurable": {"thread_id": f"smoke-{thread_id}"},
451
+ "metadata": metadata,
452
+ }
453
+
454
+ with langfuse_trace(
455
+ trace_name="opencodereview/smoke-test",
456
+ tags=["cli", "smoke", "demo-org/demo-repo"],
457
+ session_id=thread_id,
458
+ metadata={"prompt_versions": prompt_versions},
459
+ ) as handler:
460
+ callbacks = [cost_tracker]
461
+ if handler:
462
+ callbacks.append(handler)
463
+ config["callbacks"] = callbacks
464
+
465
+ t0 = time.time()
466
+ for event in graph.stream(SYNTHETIC_STATE, config):
467
+ for node_name in event:
468
+ label = NODE_LABELS.get(node_name, node_name)
469
+ logger.info(" ✔ %s (+%.1fs)", label, time.time() - t0)
470
+ logger.info(" ─── Pipeline complete in %.1fs ───", time.time() - t0)
471
+ state = graph.get_state(config)
472
+ tasks = state.tasks
473
+ values = state.values
474
+
475
+ verdict = values.get("verdict")
476
+ final_findings = values.get("final_findings", [])
477
+
478
+ logger.info("Smoke test: paused=True, tasks=%d, findings=%d, verdict=%s",
479
+ len(tasks), len(final_findings),
480
+ verdict.recommendation if verdict else 'None')
481
+ logger.info("%s", cost_tracker.summary())
482
+
483
+ assert len(tasks) > 0, "Graph did not pause at interrupt"
484
+ assert verdict is not None, "No verdict produced"
485
+ assert len(final_findings) >= 0, "Missing final_findings"
486
+
487
+ graph.invoke(Command(resume={"action": "reject"}), config)
488
+ logger.info("Smoke test: resume OK, graph completed")
489
+
490
+
491
+ def _cleanup_db() -> None:
492
+ """Remove the checkpoint database after a run."""
493
+ if os.path.exists(DB_PATH):
494
+ try:
495
+ os.remove(DB_PATH)
496
+ logger.info("Cleaned up %s", DB_PATH)
497
+ except PermissionError:
498
+ pass
499
+
500
+
501
+ # ─── Root CLI ───────────────────────────────────────────────────────────────
502
+
503
+
504
+ # ─── Doctor Command ─────────────────────────────────────────────────────────
505
+
506
+
507
+ @click.command()
508
+ def doctor() -> None:
509
+ """Run system health checks and report status."""
510
+ from backend.integrations.config import _mask_key
511
+ from backend.observability import (
512
+ HealthStatus,
513
+ check_groq_connectivity,
514
+ check_langfuse_connectivity,
515
+ )
516
+
517
+ click.echo()
518
+ click.echo("=" * 50)
519
+ click.echo(" OpenCodeReview — Health Check")
520
+ click.echo("=" * 50)
521
+ click.echo()
522
+
523
+ # ── Environment ────────────────────────────────────────────────────
524
+ click.echo("📦 Environment")
525
+ click.echo(f" Python: {sys.version.split()[0]}")
526
+ click.echo()
527
+
528
+ # ── API keys ───────────────────────────────────────────────────────
529
+ click.echo("🔑 API Keys")
530
+ groq_key = os.environ.get("GROQ_API_KEY", "").strip()
531
+ click.echo(f" GROQ_API_KEY: {'✅ Set' if groq_key else '❌ Not set'}")
532
+ gh_token = os.environ.get("GITHUB_TOKEN", "").strip()
533
+ click.echo(f" GITHUB_TOKEN: {'✅ Set' if gh_token else '❌ Not set'}")
534
+ click.echo()
535
+
536
+ # ── Observability ──────────────────────────────────────────────────
537
+ click.echo("🔭 Observability")
538
+ h = HealthStatus()
539
+ for comp, status in h.summary().items():
540
+ click.echo(f" {comp}: {status}")
541
+ click.echo()
542
+
543
+ # ── LLM endpoints (built-ins + custom) ───────────────────────────────
544
+ click.echo("🔌 LLM Endpoints")
545
+ from backend.integrations.endpoints import discover_endpoints
546
+
547
+ eps = discover_endpoints()
548
+ if eps:
549
+ for ep in eps:
550
+ click.echo(
551
+ f" {ep.describe()}"
552
+ + (" ✅" if ep.api_key else " ❌ missing key")
553
+ )
554
+ else:
555
+ click.echo(" None configured — set OCR_ENDPOINT_* env vars to add one")
556
+ click.echo()
557
+
558
+ # ── Connectivity tests ─────────────────────────────────────────────
559
+ click.echo("🌐 Connectivity")
560
+
561
+ # Groq
562
+ groq_ok, groq_msg = check_groq_connectivity()
563
+ click.echo(f" Groq API: {'✅' if groq_ok else '❌'} {groq_msg}")
564
+
565
+ # Langfuse (only if configured)
566
+ lf_ok, lf_msg = check_langfuse_connectivity()
567
+ click.echo(f" Langfuse: {'✅' if lf_ok else '⏭️'} {lf_msg}")
568
+
569
+ click.echo()
570
+ click.echo("=" * 50)
571
+
572
+
573
+ # ─── Root CLI ───────────────────────────────────────────────────────────────
574
+
575
+
576
+ @click.group()
577
+ def cli() -> None:
578
+ """OpenCodeReview — AI-powered PR review with human-in-the-loop approval."""
579
+
580
+
581
+ cli.add_command(review)
582
+ cli.add_command(doctor)
583
+ cli.add_command(auth_group)
584
+ cli.add_command(config_group)
585
+
586
+
587
+ def main() -> None:
588
+ cli(auto_envvar_prefix="OCR")
589
+
590
+
591
+ if __name__ == "__main__":
592
+ main()
backend/observability.py ADDED
@@ -0,0 +1,797 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Observability & monitoring for OpenCodeReview.
3
+
4
+ Provides a single-entry-point module for all tracing, cost tracking,
5
+ metadata attribution, health checks, and alerting concerns.
6
+
7
+ Backends
8
+ --------
9
+ * **LangSmith** — automatic via ``LANGSMITH_API_KEY`` / ``LANGSMITH_PROJECT``
10
+ (also accepts legacy ``LANGCHAIN_API_KEY`` for back-compat) env vars.
11
+ LangGraph/LangChain reads these at import time and starts tracing
12
+ without any per-call code.
13
+ * **Langfuse** — explicit ``CallbackHandler`` instantiated only when
14
+ ``LANGFUSE_PUBLIC_KEY`` and ``LANGFUSE_SECRET_KEY`` are set.
15
+
16
+ Usage
17
+ -----
18
+ from backend.observability import get_langfuse_handler, build_run_metadata
19
+
20
+ handler = get_langfuse_handler()
21
+ metadata = build_run_metadata(source="cli", repo="org/repo", pr_number=42)
22
+ config = {"configurable": {"thread_id": "..."}, "metadata": metadata}
23
+ if handler:
24
+ config["callbacks"] = [handler]
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import logging
30
+ import os
31
+ import platform
32
+ import time
33
+ import uuid
34
+ from contextlib import contextmanager
35
+ from datetime import datetime, timezone
36
+ from typing import Any, Generator, Optional
37
+
38
+ logger = logging.getLogger(__name__)
39
+
40
+ # ─── LangSmith (automatic, env-var-driven) ──────────────────────────────────
41
+
42
+
43
+ def is_langsmith_enabled() -> bool:
44
+ """Return True if LangSmith tracing is configured via env vars.
45
+
46
+ Checks both the new ``LANGSMITH_API_KEY`` (preferred) and legacy
47
+ ``LANGCHAIN_API_KEY`` env vars for backward compatibility.
48
+ """
49
+ return bool(
50
+ os.environ.get("LANGSMITH_API_KEY", "").strip()
51
+ or os.environ.get("LANGCHAIN_API_KEY", "").strip()
52
+ )
53
+
54
+
55
+ def enable_langsmith(api_key: str, project: str = "") -> None:
56
+ """Set the environment variables that LangSmith reads at runtime.
57
+
58
+ Per the official LangSmith docs (https://docs.langchain.com/langsmith/trace-with-langgraph):
59
+ the modern env vars are ``LANGSMITH_TRACING`` and ``LANGSMITH_API_KEY``.
60
+ We also set the legacy ``LANGCHAIN_*`` vars for backward compatibility
61
+ with older LangChain versions.
62
+
63
+ Call this at startup **before** any LangChain/LangGraph imports so that
64
+ the tracing is active from the first call.
65
+ """
66
+ # Modern env vars (required by langsmith-sdk >= 0.7)
67
+ os.environ["LANGSMITH_TRACING"] = "true"
68
+ os.environ["LANGSMITH_ENDPOINT"] = os.environ.get(
69
+ "LANGSMITH_ENDPOINT", "https://api.smith.langchain.com"
70
+ )
71
+ os.environ["LANGSMITH_API_KEY"] = api_key
72
+ # Legacy env vars (backward compat with older LangChain)
73
+ os.environ["LANGCHAIN_TRACING_V2"] = "true"
74
+ os.environ["LANGCHAIN_API_KEY"] = api_key
75
+ if project:
76
+ os.environ["LANGSMITH_PROJECT"] = project
77
+ os.environ["LANGCHAIN_PROJECT"] = project
78
+ logger.info(
79
+ "LangSmith tracing enabled (project=%s)",
80
+ project or os.environ.get("LANGSMITH_PROJECT", "default"),
81
+ )
82
+
83
+
84
+ def disable_langsmith() -> None:
85
+ """Remove LangSmith env vars so tracing stops."""
86
+ # Modern vars
87
+ os.environ.pop("LANGSMITH_TRACING", None)
88
+ os.environ.pop("LANGSMITH_ENDPOINT", None)
89
+ os.environ.pop("LANGSMITH_API_KEY", None)
90
+ # Legacy vars
91
+ os.environ.pop("LANGCHAIN_TRACING_V2", None)
92
+ os.environ.pop("LANGCHAIN_API_KEY", None)
93
+ # Keep project name in case user wants to set it separately
94
+
95
+
96
+ # ─── Langfuse (explicit callback) ──────────────────────────────────────────
97
+
98
+
99
+ def is_langfuse_enabled() -> bool:
100
+ """Return True if Langfuse keys are present in the environment."""
101
+ pk = os.environ.get("LANGFUSE_PUBLIC_KEY", "").strip()
102
+ sk = os.environ.get("LANGFUSE_SECRET_KEY", "").strip()
103
+ return bool(pk and sk)
104
+
105
+
106
+ def get_langfuse_handler():
107
+ """Return a bare Langfuse ``CallbackHandler`` if keys are configured, else None.
108
+
109
+ In langfuse v4+ the ``CallbackHandler`` constructor only accepts
110
+ ``public_key`` and ``trace_context`` — trace-level metadata (name, tags,
111
+ user_id, session_id, metadata) is set via the ``propagate_attributes()``
112
+ context manager instead. Use :func:`langfuse_trace` to wrap your graph
113
+ execution with proper trace attributes.
114
+ """
115
+ if not is_langfuse_enabled():
116
+ return None
117
+
118
+ try:
119
+ from langfuse.langchain import CallbackHandler
120
+
121
+ # CallbackHandler reads env vars automatically in v4+.
122
+ # No trace metadata params are passed — those go through
123
+ # propagate_attributes() instead.
124
+ return CallbackHandler()
125
+ except ImportError:
126
+ logger.warning(
127
+ "langfuse not available — skipping tracing",
128
+ exc_info=True,
129
+ )
130
+ return None
131
+ except Exception as exc:
132
+ logger.warning(
133
+ "Failed to initialise Langfuse handler: %s",
134
+ exc,
135
+ exc_info=True,
136
+ )
137
+ return None
138
+
139
+
140
+ @contextmanager
141
+ def langfuse_trace(
142
+ trace_name: str = "opencodereview",
143
+ tags: Optional[list[str]] = None,
144
+ user_id: Optional[str] = None,
145
+ session_id: Optional[str] = None,
146
+ metadata: Optional[dict[str, Any]] = None,
147
+ ) -> Generator[Any, None, None]:
148
+ """Context manager that wraps a LangGraph execution block in Langfuse trace attributes.
149
+
150
+ In langfuse v4+, trace-level metadata (name, tags, user_id, session_id,
151
+ metadata) must be set via the ``propagate_attributes()`` context manager
152
+ rather than passed to ``CallbackHandler()``. This helper creates the
153
+ handler and the ``propagate_attributes`` wrapper in one step.
154
+
155
+ Usage
156
+ -----
157
+ with langfuse_trace(
158
+ trace_name="opencodereview/review/psf/requests#42",
159
+ tags=["gradio_ui", "psf/requests"],
160
+ session_id=thread_id,
161
+ metadata={"repo": "psf/requests", "pr_number": 42},
162
+ ) as handler:
163
+ if handler:
164
+ config["callbacks"].append(handler)
165
+ graph.stream(initial_state, config)
166
+ """
167
+ handler = None
168
+ if not is_langfuse_enabled():
169
+ yield None
170
+ return
171
+
172
+ try:
173
+ from langfuse.langchain import CallbackHandler
174
+
175
+ handler = CallbackHandler()
176
+ except Exception:
177
+ yield None
178
+ return
179
+
180
+ # Build propagate_attributes kwargs
181
+ attrs: dict[str, Any] = {}
182
+ if trace_name:
183
+ attrs["trace_name"] = trace_name
184
+ if tags:
185
+ attrs["tags"] = tags
186
+ if user_id:
187
+ attrs["user_id"] = user_id
188
+ if session_id:
189
+ attrs["session_id"] = session_id
190
+ if metadata:
191
+ attrs["metadata"] = metadata
192
+
193
+ if attrs:
194
+ try:
195
+ from langfuse import propagate_attributes as _propagate_attributes
196
+ except Exception as exc:
197
+ logger.debug(
198
+ "propagate_attributes not available — yielding bare handler: %s",
199
+ exc,
200
+ )
201
+ yield handler
202
+ return
203
+
204
+ # yield is OUTSIDE try/except so user-code exceptions propagate
205
+ with _propagate_attributes(**attrs):
206
+ yield handler
207
+ else:
208
+ yield handler
209
+
210
+
211
+ # ─── Run metadata ──────────────────────────────────────────────────────────
212
+
213
+
214
+ def build_run_metadata(
215
+ source: str = "cli",
216
+ repo: str = "",
217
+ pr_number: int = 0,
218
+ session_id: Optional[str] = None,
219
+ user_id: Optional[str] = None,
220
+ prompt_versions: Optional[dict[str, str]] = None,
221
+ extra: Optional[dict[str, Any]] = None,
222
+ ) -> dict[str, Any]:
223
+ """Build a metadata dict attached to every trace/span.
224
+
225
+ Parameters
226
+ ----------
227
+ source : str
228
+ ``"cli"`` or ``"gradio_ui"``.
229
+ repo : str
230
+ GitHub repository being reviewed (e.g. ``"psf/requests"``).
231
+ pr_number : int
232
+ PR number being reviewed.
233
+ session_id : str or None
234
+ Unique session / thread identifier.
235
+ user_id : str or None
236
+ GitHub username (CLI) or anonymised token (Gradio).
237
+ prompt_versions : dict or None
238
+ Map of reviewer name → prompt file version (e.g.
239
+ ``{"correctness": "v1", "security": "v1"}``).
240
+ extra : dict or None
241
+ Any additional key-value pairs to attach.
242
+
243
+ Returns
244
+ -------
245
+ dict
246
+ Flat metadata dict suitable for ``config["metadata"]``.
247
+ """
248
+ meta: dict[str, Any] = {
249
+ "source": source,
250
+ "app": "opencodereview",
251
+ "host": platform.node(),
252
+ "timestamp": datetime.now(timezone.utc).isoformat(),
253
+ }
254
+
255
+ if repo:
256
+ meta["repo"] = repo
257
+ if pr_number:
258
+ meta["pr_number"] = pr_number
259
+ if session_id:
260
+ meta["session_id"] = session_id
261
+ if user_id:
262
+ meta["user_id"] = user_id
263
+ if prompt_versions:
264
+ meta["prompt_versions"] = prompt_versions
265
+ if extra:
266
+ meta.update(extra)
267
+
268
+ return meta
269
+
270
+
271
+ # ─── Cost tracking ─────────────────────────────────────────────────────────
272
+
273
+
274
+ # Per-1M-token pricing (USD), keyed by model name.
275
+ # Groq source: https://console.groq.com/docs/pricing (as of 2025-07)
276
+ # NOTE: Gemini rates below are APPROXIMATE published per-1M-token rates
277
+ # (USD) and may drift over time — verify against Google's pricing page
278
+ # before relying on them for billing reconciliation.
279
+ MODEL_PRICING: dict[str, dict[str, float]] = {
280
+ # ── Groq ──────────────────────────────────────────────────────────
281
+ "llama-3.3-70b-versatile": {"input": 0.59, "output": 0.79},
282
+ # ── Google Gemini ─────────────────────────────────────────────────
283
+ # Approximate published per-1M-token rates (USD) for Gemini Flash-Lite.
284
+ "gemini-3.1-flash-lite": {"input": 0.10, "output": 0.40},
285
+ # Fallback for unknown models — pessimistic estimate
286
+ "__default__": {"input": 1.00, "output": 1.00},
287
+ }
288
+
289
+ # Backward-compatible alias — previously Groq-only; now the shared table
290
+ # so any external references keep resolving.
291
+ GROQ_PRICING = MODEL_PRICING
292
+
293
+
294
+ def estimate_model_cost(
295
+ model: str,
296
+ input_tokens: int,
297
+ output_tokens: int,
298
+ ) -> float | None:
299
+ """Estimate the USD cost of an LLM call by looking up ``MODEL_PRICING``.
300
+
301
+ Parameters
302
+ ----------
303
+ model : str
304
+ Model name. Unknown models return None; free-suffix models have a
305
+ zero catalog estimate, never a claimed billing charge.
306
+ input_tokens : int
307
+ Number of tokens in the prompt (system + user messages).
308
+ output_tokens : int
309
+ Number of tokens in the completion.
310
+
311
+ Returns
312
+ -------
313
+ float
314
+ Estimated cost in USD, or None when no known price is available.
315
+ """
316
+ if model.endswith(":free"):
317
+ return 0.0
318
+ pricing = MODEL_PRICING.get(model)
319
+ if pricing is None:
320
+ return None
321
+ input_cost = (input_tokens / 1_000_000) * pricing["input"]
322
+ output_cost = (output_tokens / 1_000_000) * pricing["output"]
323
+ return round(input_cost + output_cost, 6)
324
+
325
+
326
+ def estimate_groq_cost(
327
+ model: str,
328
+ input_tokens: int,
329
+ output_tokens: int,
330
+ ) -> float | None:
331
+ """Estimate the USD cost of a Groq LLM call (backward-compatible).
332
+
333
+ Thin wrapper around :func:`estimate_model_cost`. Kept so existing
334
+ callers (``app.py``, ``main.py``, :class:`TokenCostCallback`) keep
335
+ working unchanged — it now also prices Gemini and any other model in
336
+ :data:`MODEL_PRICING` correctly instead of using the Groq-only table.
337
+ """
338
+ return estimate_model_cost(model, input_tokens, output_tokens)
339
+
340
+
341
+ def format_cost(cost_usd: float) -> str:
342
+ """Format a USD cost for human-readable display."""
343
+ if cost_usd < 0.001:
344
+ return f"${cost_usd * 1000:.2f} m¢"
345
+ return f"${cost_usd:.4f}"
346
+
347
+
348
+ # ─── Health check helpers ──────────────────────────────────────────────────
349
+
350
+
351
+ class HealthStatus:
352
+ """Aggregate health of the observability and API connectivity."""
353
+
354
+ def __init__(self) -> None:
355
+ self.langsmith: bool = is_langsmith_enabled()
356
+ self.langfuse: bool = is_langfuse_enabled()
357
+ self.groq: bool = bool(os.environ.get("GROQ_API_KEY", "").strip())
358
+ self.github: bool = bool(os.environ.get("GITHUB_TOKEN", "").strip())
359
+
360
+ @property
361
+ def any_tracing(self) -> bool:
362
+ return self.langsmith or self.langfuse
363
+
364
+ def summary(self) -> dict[str, str]:
365
+ """Return a dict of component → status string."""
366
+ return {
367
+ "LangSmith": "✅ Active" if self.langsmith else "⛔ Not configured",
368
+ "Langfuse": "✅ Active" if self.langfuse else "⛔ Not configured",
369
+ "Groq API": "✅ Key set" if self.groq else "⛔ No key",
370
+ "GitHub API": "✅ Token set" if self.github else "⛔ No token",
371
+ }
372
+
373
+
374
+ def check_groq_connectivity() -> tuple[bool, str]:
375
+ """Lightweight Groq connectivity check — does not consume quota.
376
+
377
+ Uses ``urllib.request`` from stdlib (no extra dependencies).
378
+
379
+ Returns ``(ok, message)``.
380
+ """
381
+ import json as _json
382
+ import urllib.error as _urlerror
383
+ import urllib.request as _urlreq
384
+
385
+ api_key = os.environ.get("GROQ_API_KEY", "").strip()
386
+ if not api_key:
387
+ return False, "No GROQ_API_KEY set"
388
+
389
+ try:
390
+ req = _urlreq.Request(
391
+ "https://api.groq.com/openai/v1/models",
392
+ headers={
393
+ "Authorization": f"Bearer {api_key}",
394
+ "Content-Type": "application/json",
395
+ },
396
+ method="GET",
397
+ )
398
+ with _urlreq.urlopen(req, timeout=10) as resp:
399
+ if resp.status == 200:
400
+ data = _json.loads(resp.read().decode("utf-8"))
401
+ models = data.get("data", [])
402
+ count = len(models)
403
+ return True, f"Reachable — {count} models available"
404
+ else:
405
+ return False, f"HTTP {resp.status}"
406
+ except _urlerror.HTTPError as exc:
407
+ if exc.code == 401:
408
+ return False, "Invalid API key (401)"
409
+ return False, f"HTTP {exc.code}"
410
+ except Exception as exc:
411
+ return False, str(exc)
412
+
413
+
414
+ def check_langfuse_connectivity() -> tuple[bool, str]:
415
+ """Lightweight Langfuse connectivity check.
416
+
417
+ Returns ``(ok, message)``.
418
+ """
419
+ if not is_langfuse_enabled():
420
+ return False, "Not configured"
421
+
422
+ try:
423
+ from langfuse import Langfuse
424
+
425
+ lf = Langfuse()
426
+ lf.auth_check()
427
+ return True, "Connected"
428
+ except Exception as exc:
429
+ return False, str(exc)
430
+
431
+
432
+ # ─── Token cost callback (accumulates LLM usage across a run) ────────────
433
+
434
+
435
+ class TokenCostCallback:
436
+ """Accumulates per-model token usage & TTFT from LangChain LLM calls.
437
+
438
+ Also tracks **TTFT** (Time to First Token) by recording a timestamp
439
+ at ``on_chat_model_start`` and computing elapsed time at ``on_llm_end``.
440
+ For non-streaming LLM calls this is effectively the full request duration;
441
+ for streaming it would be the time to the first chunk.
442
+
443
+ Lazily imports ``BaseCallbackHandler`` so that ``observability.py`` can
444
+ be imported even when ``langchain-core`` has version incompatibilities
445
+ (e.g. on Hugging Face Spaces). Only ``on_llm_end`` is overridden;
446
+ all other lifecycle events are ignored.
447
+
448
+ Usage
449
+ -----
450
+ counter = TokenCostCallback()
451
+ config["callbacks"] = [counter, langfuse_handler] # if langfuse
452
+ ... run graph ...
453
+ print(counter.summary())
454
+ """
455
+
456
+ raise_error: bool = False
457
+ ignore_llm: bool = False
458
+ ignore_chain: bool = False
459
+ ignore_agent: bool = False
460
+ ignore_retriever: bool = False
461
+ ignore_chat_model: bool = False
462
+ ignore_custom_event: bool = False
463
+ ignore_retry: bool = False
464
+ run_inline: bool = False
465
+
466
+ def __init__(self) -> None:
467
+ self.usage: list[dict[str, Any]] = []
468
+ self._start_times: dict[str, float] = {} # run_id -> timestamp
469
+
470
+ @property
471
+ def total_input_tokens(self) -> int:
472
+ return sum(u.get("input_tokens", 0) for u in self.usage)
473
+
474
+ @property
475
+ def total_output_tokens(self) -> int:
476
+ return sum(u.get("output_tokens", 0) for u in self.usage)
477
+
478
+ @property
479
+ def total_cost(self) -> float:
480
+ return sum(u.get("cost") or 0.0 for u in self.usage)
481
+
482
+ @property
483
+ def total_ttft(self) -> float:
484
+ """Total TTFT across all LLM calls, in seconds."""
485
+ ttfts = [u.get("ttft_seconds", 0.0) for u in self.usage if u.get("ttft_seconds") is not None]
486
+ return sum(ttfts)
487
+
488
+ @property
489
+ def avg_ttft(self) -> Optional[float]:
490
+ """Average TTFT across all LLM calls, in seconds (None if no calls)."""
491
+ ttfts = [u.get("ttft_seconds", 0.0) for u in self.usage if u.get("ttft_seconds") is not None]
492
+ if not ttfts:
493
+ return None
494
+ return sum(ttfts) / len(ttfts)
495
+
496
+ def on_chain_start(self, *args, **kwargs) -> None:
497
+ pass
498
+
499
+ def on_chain_end(self, *args, **kwargs) -> None:
500
+ pass
501
+
502
+ def on_chat_model_start(self, *args, **kwargs) -> None:
503
+ """Record start timestamp for TTFT measurement.
504
+
505
+ ``**kwargs`` contains ``run_id`` which we use as the key.
506
+ """
507
+ run_id = kwargs.get("run_id")
508
+ if run_id:
509
+ self._start_times[str(run_id)] = time.time()
510
+
511
+ def on_llm_start(self, *args, **kwargs) -> None:
512
+ """Fallback: record start timestamp if ``on_chat_model_start`` wasn't called."""
513
+ run_id = kwargs.get("run_id")
514
+ if run_id and str(run_id) not in self._start_times:
515
+ self._start_times[str(run_id)] = time.time()
516
+
517
+ def on_llm_error(self, error, **kwargs) -> None:
518
+ self._cleanup_run(kwargs.get("run_id"))
519
+
520
+ def on_chain_error(self, error, **kwargs) -> None:
521
+ pass
522
+
523
+ def on_tool_error(self, error, **kwargs) -> None:
524
+ pass
525
+
526
+ def on_retriever_error(self, error, **kwargs) -> None:
527
+ pass
528
+
529
+ def on_llm_end(self, response, **kwargs) -> None:
530
+ """LangChain callback — called after each LLM invocation.
531
+
532
+ Computes TTFT from the recorded start time and captures token usage.
533
+ ``**kwargs`` absorbs ``run_id``, ``parent_run_id``, and other
534
+ metadata that LangChain passes to callback handlers.
535
+ """
536
+ try:
537
+ run_key = str(kwargs.get("run_id", ""))
538
+
539
+ # Compute TTFT (time from start to first token / completion)
540
+ ttft: Optional[float] = None
541
+ if run_key in self._start_times:
542
+ ttft = round(time.time() - self._start_times.pop(run_key), 3)
543
+
544
+ usage = response.llm_output or {}
545
+ token_usage = usage.get("token_usage", {}) or {}
546
+ model = usage.get("model_name", "") or ""
547
+
548
+ input_tokens = token_usage.get("prompt_tokens", 0) or 0
549
+ output_tokens = token_usage.get("completion_tokens", 0) or 0
550
+
551
+ if input_tokens > 0 or output_tokens > 0:
552
+ reported = token_usage.get("cost", usage.get("cost"))
553
+ if isinstance(reported, (int, float)) and not isinstance(reported, bool) and reported >= 0:
554
+ cost, cost_source = float(reported), "provider_reported"
555
+ else:
556
+ cost = estimate_model_cost(model, input_tokens, output_tokens)
557
+ cost_source = "free_model_estimate" if model.endswith(":free") else "estimated" if cost is not None else "unknown"
558
+ entry: dict[str, Any] = {
559
+ "model": model,
560
+ "input_tokens": input_tokens,
561
+ "output_tokens": output_tokens,
562
+ "cost": cost,
563
+ "cost_source": cost_source,
564
+ }
565
+ if ttft is not None:
566
+ entry["ttft_seconds"] = ttft
567
+ self.usage.append(entry)
568
+ else:
569
+ self._cleanup_run(run_key)
570
+ except Exception:
571
+ self._cleanup_run(run_key)
572
+ pass # Best-effort — don't let cost tracking crash the run
573
+
574
+ def _cleanup_run(self, run_id: Any) -> None:
575
+ """Remove a run_id from the start times map (cleanup on error)."""
576
+ if run_id:
577
+ self._start_times.pop(str(run_id), None)
578
+
579
+ def details(self) -> dict:
580
+ sources = {item.get("cost_source", "estimated") for item in self.usage}
581
+ complete = bool(self.usage) and "unknown" not in sources
582
+ source = next(iter(sources)) if len(sources) == 1 else "mixed" if sources else "unknown"
583
+ return {"amount": self.total_cost if complete else None, "currency": "USD", "source": source,
584
+ "complete": complete, "calls": len(self.usage), "input_tokens": self.total_input_tokens,
585
+ "output_tokens": self.total_output_tokens, "model_response_seconds": round(self.total_ttft, 3)}
586
+
587
+ def summary(self) -> str:
588
+ """Human-readable attribution; estimates never imply a provider charge."""
589
+ details = self.details()
590
+ calls = details["calls"]
591
+ if not calls:
592
+ return "Usage unavailable (no successful model usage captured)"
593
+ labels = {"provider_reported": "Provider-reported cost", "free_model_estimate": "Free-model estimate (not billing)",
594
+ "estimated": "Estimated cost (not billing)", "mixed": "Mixed measured/estimated cost"}
595
+ cost = f"{labels.get(details['source'], 'Cost')}: {format_cost(details['amount'])}" if details['complete'] else "Cost unknown (provider did not report a charge; no matching price)"
596
+ parts = [cost, f"{calls} LLM call(s)", f"{self.total_input_tokens:,} in / {self.total_output_tokens:,} out tokens"]
597
+ avg = self.avg_ttft
598
+ if avg is not None:
599
+ parts.append(f"Model response time: {avg:.2f}s avg")
600
+ return " · ".join(parts)
601
+
602
+ def reset(self) -> None:
603
+ self.usage.clear()
604
+ self._start_times.clear()
605
+
606
+
607
+ # ─── Error event logging ─────────────────────────────────────────────────--
608
+
609
+
610
+ # ─── Score logging ──────────────────────────────────────────────────────────
611
+
612
+
613
+ def _resolve_langfuse_trace_id(handler: Any) -> Optional[str]:
614
+ """Resolve the current Langfuse trace ID from handler or context.
615
+
616
+ Tries, in order:
617
+ 1. ``handler.trace_id`` (langfuse v3-style — likely None on v4+)
618
+ 2. ``handler.last_trace_id`` (langfuse v4+)
619
+ 3. ``Langfuse().get_current_trace_id()`` (langfuse v4+, works
620
+ inside ``propagate_attributes`` context)
621
+ """
622
+ if handler is not None:
623
+ try:
624
+ tid = getattr(handler, "trace_id", None)
625
+ if tid:
626
+ return tid
627
+ except Exception:
628
+ pass
629
+ try:
630
+ tid = getattr(handler, "last_trace_id", None)
631
+ if tid:
632
+ return tid
633
+ except Exception:
634
+ pass
635
+
636
+ try:
637
+ from opentelemetry import trace
638
+ context = trace.get_current_span().get_span_context()
639
+ if context.is_valid:
640
+ return format(context.trace_id, "032x")
641
+ except Exception:
642
+ pass
643
+
644
+ return None
645
+
646
+
647
+ def flush_langfuse() -> None:
648
+ """Flush the shared Langfuse client's pending events once per run.
649
+
650
+ In langfuse v4+ ``get_client()`` returns a process-wide singleton; callers
651
+ (e.g. ``main.py`` after the RAGAS block, ``app.py`` after streaming) should
652
+ call this once at the end of a run so queued scores/traces are shipped
653
+ before the process exits — instead of flushing inside every
654
+ :func:`log_langfuse_score` call.
655
+
656
+ Set ``OCR_OBSERVABILITY_STRICT=1`` to surface flush failures as exceptions.
657
+ """
658
+ if not is_langfuse_enabled():
659
+ return
660
+ try:
661
+ from langfuse import get_client # v4 singleton — one shared client
662
+
663
+ get_client().flush()
664
+ except ImportError:
665
+ # Missing SDK degrades gracefully — tracing is optional.
666
+ logger.debug("langfuse SDK not installed — flush skipped")
667
+ except Exception as exc:
668
+ if os.environ.get("OCR_OBSERVABILITY_STRICT") == "1":
669
+ raise
670
+ logger.error("Failed to flush Langfuse client: %s", exc)
671
+
672
+
673
+ def log_langfuse_score(
674
+ name: str,
675
+ value: float,
676
+ comment: Optional[str] = None,
677
+ trace_id: Optional[str] = None,
678
+ handler: Optional[Any] = None,
679
+ ) -> None:
680
+ """Log a numeric score to Langfuse, linked to a specific trace.
681
+
682
+ Requires Langfuse to be enabled (keys in environment). The score is
683
+ associated with a trace by ``trace_id``. If neither ``trace_id`` nor
684
+ a resolvable handler is provided, the score is logged without a trace
685
+ link (appears in the Scores tab but not on the trace detail page).
686
+
687
+ Parameters
688
+ ----------
689
+ name : str
690
+ Score name (e.g. ``"verdict_score"``, ``"findings_count"``).
691
+ value : float
692
+ Numeric score value.
693
+ comment : str or None
694
+ Optional human-readable comment.
695
+ trace_id : str or None
696
+ Explicit trace ID. If ``None``, attempts to resolve via handler.
697
+ handler : Langfuse CallbackHandler or None
698
+ Langfuse ``CallbackHandler`` from which to extract the trace ID.
699
+ """
700
+ if not is_langfuse_enabled():
701
+ return
702
+
703
+ resolved_trace_id = trace_id or _resolve_langfuse_trace_id(handler)
704
+ if not resolved_trace_id:
705
+ logger.warning("Score %s was not logged: no captured trace ID", name)
706
+ return
707
+
708
+ # Visibility log: lets you confirm the score will land on the right
709
+ # trace (or spot a None that would create an orphaned score).
710
+ logger.info("Langfuse trace_id resolved: %s", resolved_trace_id)
711
+
712
+ try:
713
+ from langfuse import get_client # v4 singleton — one shared client
714
+
715
+ lf = get_client()
716
+ kwargs: dict[str, Any] = {
717
+ "name": name,
718
+ "value": value,
719
+ }
720
+ if resolved_trace_id:
721
+ kwargs["trace_id"] = resolved_trace_id
722
+ if comment:
723
+ kwargs["comment"] = comment
724
+
725
+ lf.create_score(**kwargs)
726
+ # NOTE: do not flush here — flushing once per run via
727
+ # flush_langfuse() at run-end (called by app.py/main.py owners).
728
+ except ImportError:
729
+ # Missing SDK degrades gracefully — tracing is optional.
730
+ logger.debug(
731
+ "langfuse SDK not installed — score '%s' not logged", name
732
+ )
733
+ except Exception as exc:
734
+ if os.environ.get("OCR_OBSERVABILITY_STRICT") == "1":
735
+ raise
736
+ logger.error(
737
+ "Failed to log Langfuse score '%s'=%.4f (trace_id=%s, comment=%s): %s",
738
+ name, value, resolved_trace_id, comment, exc,
739
+ )
740
+
741
+
742
+ def update_langfuse_trace(
743
+ trace_name: Optional[str] = None,
744
+ tags: Optional[list[str]] = None,
745
+ metadata: Optional[dict[str, Any]] = None,
746
+ trace_id: Optional[str] = None,
747
+ handler: Optional[Any] = None,
748
+ ) -> None:
749
+ """No-op in langfuse v4+ — trace attributes must be set upfront
750
+ via ``propagate_attributes()`` (see :func:`langfuse_trace`).
751
+
752
+ In langfuse v4 the trace API no longer supports ``update_trace``.
753
+ Trace-level metadata (name, tags, user_id, session_id, metadata)
754
+ must be provided at trace creation time via ``propagate_attributes``.
755
+ Use :func:`log_langfuse_score` instead for post-hoc annotations
756
+ like verdict score or findings count.
757
+ """
758
+ if resolved_trace_id := (trace_id or _resolve_langfuse_trace_id(handler)):
759
+ logger.debug(
760
+ "update_langfuse_trace is a no-op in langfuse v4 (trace=%s). "
761
+ "Set attributes upfront via langfuse_trace() instead.",
762
+ resolved_trace_id,
763
+ )
764
+ # Dedicated score logging is handled by log_langfuse_score() — nothing
765
+ # to do here.
766
+
767
+
768
+ def log_error_to_backends(
769
+ error: Exception,
770
+ context: Optional[dict[str, Any]] = None,
771
+ ) -> None:
772
+ """Log an error event to whichever observability backend(s) are active.
773
+
774
+ For LangSmith: logs via LangChain's callback system (automatic).
775
+ For Langfuse: creates an identifyable error event via the SDK.
776
+
777
+ This function primarily logs to ``logger`` with full traceback and
778
+ enriches the log record with context that the tracing backends pick up.
779
+
780
+ Parameters
781
+ ----------
782
+ error : Exception
783
+ The exception that occurred.
784
+ context : dict or None
785
+ Additional context about where/when the error happened.
786
+ """
787
+ extras = ""
788
+ if context:
789
+ extras = f" [{', '.join(f'{k}={v}' for k, v in context.items())}]"
790
+
791
+ logger.exception(
792
+ "OBSERVABILITY-ERROR%s: %s: %s",
793
+ extras,
794
+ type(error).__name__,
795
+ error,
796
+ exc_info=error,
797
+ )
backend/state.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import enum
4
+ from operator import add
5
+ from typing import Annotated, Literal, Optional
6
+
7
+ from pydantic import BaseModel, Field
8
+
9
+
10
+ # ─── Sub-models ──────────────────────────────────────────────────────────────
11
+
12
+
13
+ class ChangedFile(BaseModel):
14
+ """A single file modified in the PR."""
15
+ path: str
16
+ status: str # "added" | "modified" | "removed" | "renamed"
17
+ content: str # Full file content after the PR
18
+ diff_hunk: str # The unified-diff hunk for this file
19
+
20
+
21
+ class ContextChunk(BaseModel):
22
+ """A chunk of relevant context retrieved from the repo's codebase or past PRs."""
23
+ source: str # "codebase" | "past_pr"
24
+ file_path: str # Where the chunk came from
25
+ content: str # The relevant code/text
26
+ relevance_score: float = Field(default=0.0, ge=0.0, le=1.0)
27
+
28
+
29
+ class Severity(str, enum.Enum):
30
+ CRITICAL = "critical"
31
+ HIGH = "high"
32
+ MEDIUM = "medium"
33
+ LOW = "low"
34
+ INFO = "info"
35
+
36
+
37
+ class Finding(BaseModel):
38
+ """A single issue found during review."""
39
+ file_path: str
40
+ line_start: int
41
+ line_end: int
42
+ severity: Severity
43
+ category: str # "logic" | "security" | "style" | "performance" | "correctness"
44
+ comment: str # Human-readable explanation
45
+ confidence: float = Field(default=0.5, ge=0.0, le=1.0)
46
+ suggested_fix: Optional[str] = None
47
+ kind: Literal["bug", "security_concern", "test_suggestion"] = "bug"
48
+ evidence_status: Literal["source_grounded", "needs_verification", "outside_diff"] = "needs_verification"
49
+ evidence_excerpt: str = ""
50
+ calibration_note: str = ""
51
+
52
+
53
+ class Verdict(BaseModel):
54
+ """Aggregated final verdict across all findings."""
55
+ summary: str
56
+ approved: bool
57
+ overall_score: Optional[float] = Field(default=None, ge=0.0, le=10.0)
58
+ critical_count: int = 0
59
+ high_count: int = 0
60
+ recommendation: str # "approve" | "request_changes" | "block"
61
+ score_explanation: str = ""
62
+ score_breakdown: dict = Field(default_factory=dict)
63
+
64
+
65
+ # ─── Graph State ─────────────────────────────────────────────────────────────
66
+
67
+
68
+ class OpenCodeReviewState(BaseModel):
69
+ """Shared state for the OpenCodeReview LangGraph agent."""
70
+
71
+ # PR metadata: set-once, single values
72
+ repo: str = ""
73
+ pr_number: int = 0
74
+ head_sha: str = ""
75
+ incremental_base_sha: str = ""
76
+ base_sha: str = "" # SHA of the base branch (used as vector-store cache key)
77
+ diff: Optional[str] = None
78
+ changed_files: list[ChangedFile] = Field(default_factory=list)
79
+
80
+ # Custom LLM endpoint chosen for this run (name from OCR_ENDPOINT_* env
81
+ # configs). Empty string means "use the built-in default provider".
82
+ endpoint: str = ""
83
+ review_mode: str = "thorough"
84
+
85
+ # Retrieved context: accumulated across parallel retrieval nodes
86
+ context_chunks: Annotated[list[ContextChunk], add] = Field(default_factory=list)
87
+
88
+ # Review findings: accumulated across parallel review agents
89
+ findings: Annotated[list[Finding], add] = Field(default_factory=list)
90
+
91
+ review_stages: Annotated[list[dict], add] = Field(default_factory=list)
92
+ review_coverage: dict = Field(default_factory=dict)
93
+
94
+ # Aggregated (deduped, noise-filtered) findings: set-once by aggregator
95
+ final_findings: list[Finding] = Field(default_factory=list)
96
+
97
+ # Final verdict: set-once by the aggregation node
98
+ verdict: Optional[Verdict] = None
99
+
100
+ # Human-in-the-loop: set by the human_approval node
101
+ human_approved: bool = False
102
+ posting_result: Optional[dict] = None
combined_server.py CHANGED
@@ -1,8 +1,5 @@
1
- """Serve the React-facing API and legacy Gradio UI from one HF Space."""
2
- from fastapi import FastAPI
3
- import gradio as gr
4
 
5
- from api import app as api_app
6
- from app import demo
7
-
8
- app: FastAPI = gr.mount_gradio_app(api_app, demo, path="/")
 
1
+ """Backward-compatible Uvicorn entry point for the combined server."""
2
+ import sys as _sys
3
+ from backend import combined_server as _implementation
4
 
5
+ _sys.modules[__name__] = _implementation
 
 
 
config.py CHANGED
@@ -1,267 +1,5 @@
1
- #!/usr/bin/env python3
2
- """Configuration management for OpenCodeReview.
3
-
4
- Resolves secrets in priority order: **environment variable > keyring > error**.
5
-
6
- Providers
7
- ---------
8
- - ``anthropic`` — ``ANTHROPIC_API_KEY`` → stored as ``opencodereview / anthropic_api_key``
9
-
10
- Usage
11
- -----
12
- opencodereview config set-key --provider anthropic
13
- opencodereview config show
14
- """
15
-
16
- from __future__ import annotations
17
-
18
- import logging
19
- import os
20
- import sys
21
- from typing import Optional
22
-
23
- import click
24
- import keyring
25
- from pydantic import Field
26
- from pydantic_settings import BaseSettings, SettingsConfigDict
27
-
28
- logger = logging.getLogger(__name__)
29
-
30
- SERVICE_NAME = "opencodereview"
31
-
32
- # ─── Provider registry ──────────────────────────────────────────────────────
33
- # slug → (keyring_key, env_var_name, display_name)
34
-
35
- PROVIDERS: dict[str, tuple[str, str, str]] = {
36
- "anthropic": (
37
- "anthropic_api_key", # keyring key
38
- "OPENCODEREVIEW_ANTHROPIC_KEY", # env var
39
- "Anthropic API key", # display name
40
- ),
41
- }
42
-
43
-
44
- # ─── Exceptions ─────────────────────────────────────────────────────────────
45
-
46
-
47
- class ConfigError(Exception):
48
- """Configuration-related error with a user-facing message."""
49
-
50
-
51
- # ─── Settings (pydantic-settings) ───────────────────────────────────────────
52
-
53
-
54
- class Settings(BaseSettings):
55
- """Resolve configuration from env vars, falling back to the system keyring.
56
-
57
- Priority
58
- --------
59
- 1. Environment variable (``OPENCODEREVIEW_<FIELD>``)
60
- 2. System keyring (``opencodereview / <keyring_key>``)
61
- 3. :class:`ConfigError` with a helpful message telling the user how to set it.
62
- """
63
-
64
- model_config = SettingsConfigDict(
65
- env_prefix="OPENCODEREVIEW_",
66
- extra="ignore",
67
- validate_default=False,
68
- )
69
-
70
- anthropic_api_key: Optional[str] = Field(default=None)
71
-
72
- # ── Langfuse observability (optional) ──────────────────────────────────
73
- langfuse_public_key: Optional[str] = Field(default=None)
74
- langfuse_secret_key: Optional[str] = Field(default=None)
75
- langfuse_host: Optional[str] = Field(default=None)
76
-
77
- def model_post_init(self, __context) -> None: # noqa: ANN101
78
- """After env-var resolution, fall back to keyring for any unset values."""
79
- for keyring_key, _, _ in PROVIDERS.values():
80
- if getattr(self, keyring_key) is None:
81
- stored = keyring.get_password(SERVICE_NAME, keyring_key)
82
- if stored:
83
- setattr(self, keyring_key, stored)
84
-
85
- def get_anthropic_api_key(self) -> str:
86
- """Return the Anthropic API key or raise ``ConfigError``."""
87
- key = self.anthropic_api_key
88
- if not key:
89
- raise ConfigError(
90
- "Anthropic API key is not configured.\n\n"
91
- " Set it interactively:\n"
92
- " opencodereview config set-key --provider anthropic\n\n"
93
- " Or as an environment variable:\n"
94
- " export OPENCODEREVIEW_ANTHROPIC_KEY=\"sk-ant-...\"\n"
95
- )
96
- return key
97
-
98
-
99
- # ─── Key masking ─────────────────────────────────────────────────────────────
100
-
101
-
102
- def _mask_key(key: str) -> str:
103
- """Return a masked version showing only the prefix and last characters.
104
-
105
- Examples
106
- --------
107
- ``sk-ant-abcdefgh12345678`` → ``sk-ant-...5678``
108
- ``ghp_abc123def456`` → ``ghp_abc...f456``
109
- ``abcdefg`` → ``abcd...fg``
110
- ``tiny`` → ``t...``
111
- """
112
- n = len(key)
113
- if n <= 4:
114
- return key[:1] + "..."
115
- if n <= 8:
116
- return key[:4] + "..." + key[-2:]
117
- return key[:7] + "..." + key[-4:]
118
-
119
-
120
- # ─── CLI ─────────────────────────────────────────────────────────────────────
121
-
122
-
123
- @click.group()
124
- def config() -> None:
125
- """Manage API keys and configuration."""
126
-
127
-
128
- @config.command()
129
- @click.option(
130
- "--provider",
131
- required=True,
132
- type=click.Choice(sorted(PROVIDERS), case_sensitive=True),
133
- help="Which provider's API key to store.",
134
- )
135
- def set_key(provider: str) -> None:
136
- """Prompt for an API key and store it securely in the system keyring.
137
-
138
- The key is entered via hidden input and never echoed to the terminal.
139
- """
140
- keyring_key, env_var, display_name = PROVIDERS[provider]
141
-
142
- # Warn if env var is already set (keyring value would be ignored)
143
- if os.environ.get(env_var):
144
- click.echo(
145
- f"Warning: {display_name} is already set via the"
146
- f" {env_var} environment variable.\n"
147
- f" A keyring-stored key won't take effect until the env var is unset.\n",
148
- err=True,
149
- )
150
-
151
- api_key = click.prompt(
152
- f"Enter your {display_name}",
153
- hide_input=True,
154
- )
155
-
156
- if not api_key.strip():
157
- click.echo("Error: Key cannot be empty.", err=True)
158
- sys.exit(1)
159
-
160
- keyring.set_password(SERVICE_NAME, keyring_key, api_key.strip())
161
- click.echo(f"{display_name} saved to system credential store (keyring).")
162
-
163
-
164
- @config.command()
165
- def show() -> None:
166
- """Display which keys and tokens are configured (values masked).
167
-
168
- Full secrets are never printed — only the first 7 + last 4 characters.
169
- """
170
- click.echo()
171
- click.echo("=" * 50)
172
- click.echo(" Configuration Summary")
173
- click.echo("=" * 50)
174
- click.echo()
175
- has_any = False
176
-
177
- # ── GitHub token (managed by auth) ──────────────────────────────────────
178
- gh_token = keyring.get_password(SERVICE_NAME, "github_token")
179
- token_env = os.environ.get("GITHUB_TOKEN")
180
- if token_env:
181
- click.echo(f" GitHub token: {_mask_key(token_env)} (from env)")
182
- has_any = True
183
- elif gh_token:
184
- click.echo(f" GitHub token: {_mask_key(gh_token)} (from keyring)")
185
- has_any = True
186
- else:
187
- click.echo(" GitHub token: not set")
188
-
189
- # ── Provider API keys ───────────────────────────────────────────────────
190
- for provider_slug, (keyring_key, env_var, display_name) in sorted(PROVIDERS.items()):
191
- env_value = os.environ.get(env_var)
192
- if env_value:
193
- click.echo(
194
- f" {display_name}: {_mask_key(env_value)} (from env)"
195
- )
196
- has_any = True
197
- else:
198
- stored = keyring.get_password(SERVICE_NAME, keyring_key)
199
- if stored:
200
- click.echo(
201
- f" {display_name}: {_mask_key(stored)} (from keyring)"
202
- )
203
- has_any = True
204
- else:
205
- click.echo(f" {display_name}: not set")
206
-
207
- click.echo()
208
- if not has_any:
209
- click.echo(" No keys or tokens configured.")
210
- click.echo(" Run: opencodereview config set-key --provider anthropic")
211
- click.echo()
212
-
213
-
214
- # ─── Observability CLI ─────────────────────────────────────────────────────
215
-
216
-
217
- @config.command(name="set-observability")
218
- @click.option("--langsmith-api-key", help="LangSmith API key (for tracing)")
219
- @click.option("--langsmith-project", default="opencodereview", show_default=True,
220
- help="LangSmith project name")
221
- @click.option("--langfuse-public-key", help="Langfuse public key")
222
- @click.option("--langfuse-secret-key", help="Langfuse secret key")
223
- @click.option("--langfuse-host", default="https://cloud.langfuse.com",
224
- show_default=True, help="Langfuse host URL")
225
- def set_observability(
226
- langsmith_api_key: Optional[str],
227
- langsmith_project: str,
228
- langfuse_public_key: Optional[str],
229
- langfuse_secret_key: Optional[str],
230
- langfuse_host: str,
231
- ) -> None:
232
- """Configure observability backends (LangSmith and/or Langfuse).
233
-
234
- Keys are stored in the system keyring. Both backends can be configured
235
- simultaneously with no conflict. If neither is set, the app runs
236
- exactly as before with zero tracing overhead.
237
- """
238
- if langsmith_api_key:
239
- keyring.set_password(SERVICE_NAME, "langsmith_api_key", langsmith_api_key)
240
- click.echo(f"LangSmith API key saved (project: {langsmith_project}).")
241
-
242
- # Warn if env var is already set
243
- if os.environ.get("LANGCHAIN_API_KEY"):
244
- click.echo(
245
- " Note: LANGCHAIN_API_KEY env var is already set — "
246
- "it takes precedence over the keyring value.",
247
- err=True,
248
- )
249
- else:
250
- click.echo(" LangSmith: skipped (no --langsmith-api-key provided).")
251
-
252
- if langfuse_public_key and langfuse_secret_key:
253
- keyring.set_password(SERVICE_NAME, "langfuse_public_key", langfuse_public_key)
254
- keyring.set_password(SERVICE_NAME, "langfuse_secret_key", langfuse_secret_key)
255
- keyring.set_password(SERVICE_NAME, "langfuse_host", langfuse_host)
256
- click.echo(f"Langfuse keys saved (host: {langfuse_host}).")
257
-
258
- if os.environ.get("LANGFUSE_PUBLIC_KEY"):
259
- click.echo(
260
- " Note: LANGFUSE_PUBLIC_KEY env var is already set — "
261
- "it takes precedence.",
262
- err=True,
263
- )
264
- else:
265
- click.echo(" Langfuse: skipped (need both --langfuse-public-key "
266
- "and --langfuse-secret-key).")
267
 
 
 
1
+ """Backward-compatible import path for configuration helpers."""
2
+ import sys as _sys
3
+ from backend.integrations import config as _implementation
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
+ _sys.modules[__name__] = _implementation
docs/README.md ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Project documentation
2
+
3
+ Project documentation is grouped by purpose:
4
+
5
+ - [Architecture](architecture/ARCHITECTURE.md): application layers, workflow, and deployment structure.
6
+ - [Runbooks](runbooks/): authentication and deployment procedures.
7
+ - [Engineering notes](engineering/): verified fixes and quality or speed improvements.
8
+ - [Evaluation plan](evaluation/OFFLINE_EVALUATION_PLAN.md): offline and RAGAS evaluation.
9
+ - [Operations](operations/PRODUCTION_READINESS.md): production readiness checklist.
10
+ - [Planning](planning/revamp.md): longer-term project direction.
11
+ - [Specifications](specifications/opencodereview-spec.md): project specification snapshot.
12
+ - [AI engineer interview guide](project-guide/README.md): guide files, diagrams, and regeneration steps.
13
+
14
+ The guide's generated page images and preview files belong in its ignored `working/`
15
+ directory. Machine-specific diagnostics and test checkpoint data belong under `.local/`.
docs/architecture/ARCHITECTURE.md ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # OpenCodeReview architecture
2
+
3
+ The deployed path is intentionally remote-inference only. The API and Gradio
4
+ process orchestrate GitHub retrieval and LangGraph; Gemini, Groq, or another
5
+ configured OpenAI-compatible provider performs model inference. No model is
6
+ downloaded or executed by the hosted API by default.
7
+
8
+ ## Runtime boundaries
9
+
10
+ - `backend/api.py`: authenticated HTTP job lifecycle, persistence, approval, and
11
+ posting receipts.
12
+ - `backend/app.py`: Gradio UI and review orchestration adapter.
13
+ - `backend/graph.py`, `nodes/`, `backend/state.py`: LangGraph workflow and typed
14
+ state.
15
+ - `backend/integrations/github_client.py`: GitHub reads, caching, and writes.
16
+ - `backend/integrations/llm_factory.py` and
17
+ `backend/integrations/endpoints.py`: remote provider selection and fallback.
18
+ - `backend/integrations/auth.py` and `config.py`: authentication and settings.
19
+ - Root modules such as `main.py`, `app.py`, and `combined_server.py` are
20
+ compatibility entry points. The application implementation lives in
21
+ `backend/`.
22
+ - `frontend/`: Vercel React client; review requests use FastAPI, while provider
23
+ connectivity tests use the Vercel function.
24
+ - `eval_data/`: offline benchmark scorer and RAGAS evaluation utilities.
25
+ - `prompts/`: review prompts kept outside orchestration code.
26
+
27
+ ## Local model policy
28
+
29
+ Local embeddings are disabled unless `OPENCODEREVIEW_ALLOW_LOCAL_EMBEDDINGS=true`
30
+ is explicitly set. This keeps laptops and hosted containers from pulling
31
+ PyTorch or embedding models. Retrieval gracefully returns no extra context and
32
+ the review continues with the PR diff when the flag is disabled.
33
+
34
+ ## Persistence boundary
35
+
36
+ The API stores job records in Supabase Postgres when `SUPABASE_DB_URL` is
37
+ configured and otherwise uses SQLite. LangGraph checkpoints use a separate
38
+ SQLite saver. Process-local worker and session state is not shared between
39
+ replicas, so a durable queue and shared checkpoint/session storage are needed
40
+ before horizontal scaling.
docs/engineering/FIXES.md ADDED
@@ -0,0 +1,488 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🔧 OpenCodeReview — Necessary Fixes Guide
2
+
3
+ > A **plain-English, verified** guide to the issues found in `CODE_REVIEW.md`.
4
+ > Every issue below was **independently confirmed against the actual code**
5
+ > and the installed packages (langfuse 4.13.1, langchain 1.3.14, langgraph 1.2.9,
6
+ > langgraph-checkpoint-sqlite 3.1.0, langchain-groq 1.1.2, chromadb 1.5.8,
7
+ > ragas 0.3.8) on **2026-07-31**.
8
+ >
9
+ > ⚠️ Two claims in the original review turned out to be **wrong** — see
10
+ > [§8 "Claims that are NOT true"](#claims-in-code_reviewmd-that-are-not-true).
11
+
12
+ ---
13
+
14
+ ## 📑 Table of Contents
15
+
16
+ 1. [Fix Summary (TL;DR)](#fix-summary-tldr)
17
+ 2. [🐛 Real bugs — high priority](#real-bugs--high-priority)
18
+ 3. [📦 Dependency hardening](#dependency-hardening)
19
+ 4. [🔭 Observability & Langfuse](#observability--langfuse)
20
+ 5. [🧹 Code quality, eval & docs](#code-quality-eval--docs)
21
+ 6. [🧪 Testing](#testing)
22
+ 7. [Suggested order of work](#suggested-order-of-work)
23
+ 8. [Claims in CODE_REVIEW.md that are NOT true](#claims-in-code_reviewmd-that-are-not-true)
24
+ 9. [Master checklist](#master-checklist)
25
+
26
+ ---
27
+
28
+ ## 🗂️ Fix Summary (TL;DR)
29
+
30
+ | # | Fix | Priority | Effort | Verified? |
31
+ |---|-----|----------|--------|-----------|
32
+ | 1 | Add missing `import requests` in `nodes/executor.py` | 🟠 High | 1 line | ✅ |
33
+ | 2 | Close the SQLite connection in `graph.py` | 🟠 High | ~10 lines | ✅ |
34
+ | 3 | Pin `langfuse` + other unpinned dependencies | 🟠 High | 5 min | ✅ |
35
+ | 4 | Stop swallowing Langfuse/RAGAS errors silently | 🟠 High | ~20 lines | ✅ |
36
+ | 5 | Link Langfuse scores to a real trace id (the reported bug) | 🟠 High | ~30 lines | ✅ |
37
+ | 6 | One canonical RAGAS-score name (`ragas_` prefix everywhere) | 🟡 Medium | ~15 lines | ✅ |
38
+ | 7 | Forward observability env vars in `docker-compose.yml` | 🟡 Medium | 5 lines | ✅ |
39
+ | 8 | RAGAS: use `None` for failed metrics (NOT `0.0`) — with all consumers updated | 🟡 Medium | ~40 lines | ✅ |
40
+ | 9 | Remove dead `passthrough.py` / `post_results.py` nodes | 🟡 Medium | delete 2 files | ✅ |
41
+ | 10 | Centralise duplicated constants (`GROQ_MODEL`, `_human_size`, …) | 🟢 Low | ~30 lines | ✅ |
42
+ | 11 | Add Gemini pricing to cost tracking | 🟢 Low | ~10 lines | ✅ |
43
+ | 12 | Fix README Python-version mismatch + docstring nits | 🟢 Low | 2 lines | ✅ |
44
+ | 13 | Fix executor PR-head-SHA race logging | 🟢 Low | 3 lines | ✅ |
45
+ | 14 | Add automated tests (pytest) | 🟢 Low | ongoing | ✅ |
46
+
47
+ ---
48
+
49
+ ## 🐛 Real bugs — high priority
50
+
51
+ ### Fix 1 — Missing `import requests` in `nodes/executor.py` (latent crash)
52
+
53
+ **What's the problem?** `nodes/executor.py` uses `requests.RequestException`
54
+ at lines 46, 104 and 127 (in `_fetch_pr_head_sha`, `_post_review_comment`,
55
+ `_post_issue_comment`), but **never imports `requests`**.
56
+
57
+ **Why it matters?** The moment a GitHub API call fails with a network error, the
58
+ `except requests.RequestException` clause itself raises
59
+ `NameError: name 'requests' is not defined` — crashing the executor instead of
60
+ degrading gracefully. It hasn't bitten you only because the happy path never hits it.
61
+
62
+ **The fix — add one line to the imports:**
63
+ ```python
64
+ # nodes/executor.py, at the top with the other imports
65
+ import logging
66
+ import os
67
+ import requests # ← ADD THIS
68
+ from typing import Any
69
+ ```
70
+
71
+ **How to verify:** `python -c "import ast; ast.parse(open('nodes/executor.py').read())"` and grep that `requests` is imported before use.
72
+
73
+ ---
74
+
75
+ ### Fix 2 — SQLite connection never closed in `graph.py`
76
+
77
+ **What's the problem?** `graph.py` opens a SQLite connection
78
+ (`conn = sqlite3.connect(...)`, ~line 101) for the `SqliteSaver` checkpointer and
79
+ **never closes it**. The Gradio UI calls `build_graph()` on *every* review, so
80
+ each review leaks a file handle + DB.
81
+
82
+ **Why it matters?** On Windows, the open handle means `_cleanup_db()` hits
83
+ `PermissionError` (that's literally why the `except PermissionError: pass`
84
+ exists in `main.py:461`). Handles accumulate across reviews in the long-running UI.
85
+
86
+ **The fix — close the connection when the checkpointer is done.** Note:
87
+ `SqliteSaver.from_conn_string()` is a context manager, but it does **not** accept
88
+ your custom `serde=` (verified in langgraph 3.1.0), so keep the explicit `conn`
89
+ and close it explicitly. Stash the connection on the compiled graph so callers
90
+ can reach it — this works in langgraph 1.x (`CompiledStateGraph` is a plain
91
+ class; no `__slots__`), though it's an informal pattern:
92
+
93
+ ```python
94
+ # graph.py — after compile, expose the conn for cleanup
95
+ conn = sqlite3.connect(resolved_path, check_same_thread=False)
96
+ saver = SqliteSaver(conn, serde=serde)
97
+ compiled = builder.compile(checkpointer=saver)
98
+ compiled._opencodereview_conn = conn # informal handle for callers
99
+ return compiled
100
+ ```
101
+
102
+ Then close it where each run finishes. CLI (`main.py` `review()`):
103
+
104
+ ```python
105
+ graph = build_graph(DB_PATH)
106
+ try:
107
+ if smoke:
108
+ _test_offline(graph)
109
+ else:
110
+ _run_with_hitl(graph, repo, pr_number)
111
+ finally:
112
+ conn = getattr(graph, "_opencodereview_conn", None)
113
+ if conn:
114
+ conn.close()
115
+ _cleanup_db()
116
+ ```
117
+
118
+ For the Gradio UI (`app.py`), close the connection after the executor completes
119
+ in `resume_review()`, and in `run_smoke()` after streaming finishes.
120
+
121
+ **⚠️ Caution (important):** do **not** close while a graph run is still paused at
122
+ `human_approval` — the checkpointer must stay open across the interrupt/resume.
123
+ `resume_review()` builds a **fresh** graph from the same DB file, so closing the
124
+ first connection after `_build_and_stream()` completes is safe *only because*
125
+ checkpoints are persisted to disk; keep the close in the resume/cleanup path, not
126
+ mid-stream.
127
+
128
+ ---
129
+
130
+ ## 📦 Dependency hardening
131
+
132
+ ### Fix 3 — Pin dependencies (prevents this whole class of bug)
133
+
134
+ **What's the problem?** `requirements.txt` leaves several packages unpinned, so a
135
+ fresh `pip install` can silently pull breaking major versions. This is *why*
136
+ Langfuse broke: unpinned `langfuse` now resolves to v4 (4.13.1 installed here),
137
+ while parts of the code still use v3-style calls.
138
+
139
+ **The fix** — pin to the exact versions verified working in this environment:
140
+
141
+ ```text
142
+ langfuse>=4.13,<5 # ← pin! (v4 era; see Fix 5 for the API work)
143
+ langchain==1.3.14
144
+ langgraph==1.2.9
145
+ langgraph-checkpoint-sqlite==3.1.0
146
+ chromadb==1.5.8
147
+ langchain-groq==1.1.2
148
+ ```
149
+
150
+ Then generate a lockfile so builds are reproducible:
151
+ ```bash
152
+ pip freeze > requirements.lock
153
+ ```
154
+
155
+ ---
156
+
157
+ ## 🔭 Observability & Langfuse
158
+
159
+ ### Fix 4 — Stop silently swallowing errors (esp. Langfuse)
160
+
161
+ **What's the problem?** Several places catch `except Exception` and only log a
162
+ warning (or nothing), hiding real failures:
163
+
164
+ | Location | What's swallowed |
165
+ |---|---|
166
+ | `observability.py:652` `log_langfuse_score` | ALL Langfuse errors → score silently dropped |
167
+ | `observability.py:532` `TokenCostCallback.on_llm_end` | cost-tracking errors (fine) |
168
+ | `nodes/correctness_reviewer.py:147-149` | LLM failure → `return {}` (review silently empty) |
169
+ | `nodes/aggregator.py` (~247) | LLM critic failure → silent rule-based fallback |
170
+ | `eval_data/ragas_eval.py` (several) | metric failure → silently sets `0.0` |
171
+ | `eval_data/evaluate.py` (~530) | whole RAGAS block → warning, continues |
172
+
173
+ **Why it matters?** This is exactly why the Langfuse bug survived two "fix"
174
+ commits: you could never *see* the real error. Silent bugs are invisible bugs.
175
+
176
+ **The fix — fail loudly where it matters:**
177
+
178
+ 1. **`log_langfuse_score`** — log at **ERROR** with the full payload, and add a
179
+ debug mode that re-raises:
180
+ ```python
181
+ except Exception as exc:
182
+ if os.environ.get("OCR_OBSERVABILITY_STRICT") == "1":
183
+ raise
184
+ logger.error(
185
+ "Failed to log Langfuse score '%s'=%.4f (trace_id=%s, comment=%s): %s",
186
+ name, value, resolved_trace_id, comment, exc,
187
+ )
188
+ ```
189
+ 2. **Reviewer nodes** — when the LLM fails, emit a clear INFO so a missing review
190
+ is obvious in the run log:
191
+ ```python
192
+ except Exception as exc:
193
+ logger.warning("Correctness review LLM call failed: %s — skipping reviewer", exc)
194
+ ```
195
+
196
+ ---
197
+
198
+ ### Fix 5 — Make RAGAS/Langfuse scores actually appear on traces
199
+
200
+ **The verified picture (differs from CODE_REVIEW.md's "confirmed" root cause):**
201
+ - ✅ Real: `langfuse` is unpinned → v4 (4.13.1) is installed while the code mixes v3+v4 idioms.
202
+ - ✅ Real: `log_langfuse_score` builds a **new `Langfuse()` per call**, swallows all errors, and `create_score` with `trace_id=None` creates an **orphaned** score (won't show on the trace page).
203
+ - ✅ Real: the `run_trace_id` is captured *once* right after the graph completes — and the code's own comment admits it "can return None after ~60s delays because contextvars may be lost".
204
+ - ❌ **NOT true** (verified against installed v4.13.1): "v4 ignores `LANGFUSE_HOST`" — v4.13.1 still honours it (deprecated fallback); "the trace-ID accessors don't exist in v4" — `handler.last_trace_id` and `Langfuse().get_current_trace_id()` **both exist** in 4.13.1.
205
+
206
+ **The fix (practical, low-risk):**
207
+
208
+ 1. **Pin langfuse** (Fix 3) so the API can't shift under you again.
209
+ 2. **Capture the trace id as early as possible** — the code already does this
210
+ (`run_trace_id = _resolve_langfuse_trace_id(handler)` right after streaming);
211
+ keep it, and add a log line so you can *see* whether it's `None`:
212
+ ```python
213
+ logger.info("Langfuse trace_id resolved: %s", run_trace_id)
214
+ ```
215
+ 3. **Use one shared client** instead of a fresh `Langfuse()` per score call:
216
+ ```python
217
+ from langfuse import get_client # v4 singleton — verified available in 4.13.1
218
+ lf = get_client()
219
+ ```
220
+ 4. **Flush once per run, not per score.** Current code calls `lf.flush()` inside
221
+ `log_langfuse_score` (every score). Move flushing to the end of the run
222
+ (`main.py` after RAGAS block; `app.py` after `_build_and_stream`).
223
+ 5. **Set both env vars** (harmless, future-proof): in `.env` set
224
+ `LANGFUSE_BASE_URL` *and* keep `LANGFUSE_HOST` as an alias.
225
+ 6. **Remove the silent swallow** (see Fix 4) so a failing score is visible.
226
+
227
+ **How to verify:** run a review with Langfuse keys set, then check:
228
+ - the log prints a non-`None` `trace_id`;
229
+ - the Langfuse UI trace page shows `ragas_*` scores;
230
+ - no `ERROR Failed to log Langfuse score` lines appear.
231
+
232
+ ---
233
+
234
+ ### Fix 6 — One canonical RAGAS-score naming path
235
+
236
+ **What's the problem?** The same metric is logged under **different names**
237
+ depending on entry point:
238
+ - `app.py` / `main.py` → `ragas_<metric>` ✅ (canonical)
239
+ - `eval_data/ragas_eval.py` `log_ragas_scores_to_langfuse` → also `ragas_<metric>` ✅
240
+ - `eval_data/evaluate.py` `_log_to_observability` → raw `lf.create_score(name=ragas_key, …)` ❌ **no prefix**
241
+
242
+ So `ragas_context_precision` vs `context_precision` appear as *different* scores
243
+ in dashboards.
244
+
245
+ **The fix:** route everything through `observability.log_langfuse_score` with the
246
+ `ragas_` prefix. In `evaluate.py` `_log_to_observability`, replace the direct
247
+ `lf.create_score(name=ragas_key, ...)` loop with:
248
+
249
+ ```python
250
+ from observability import log_langfuse_score
251
+
252
+ for ragas_key in ("context_precision", "context_recall",
253
+ "faithfulness", "answer_relevancy", "mmr"):
254
+ if ragas_key in r:
255
+ log_langfuse_score(
256
+ name=f"ragas_{ragas_key}",
257
+ value=r[ragas_key],
258
+ comment=pr_comment,
259
+ trace_id=pr_trace_id,
260
+ )
261
+ ```
262
+
263
+ ---
264
+
265
+ ### Fix 7 — Forward observability env vars in `docker-compose.yml`
266
+
267
+ **What's the problem?** `docker-compose.yml` (lines 33-40) only forwards
268
+ `GROQ_API_KEY`, `OPENCODEREVIEW_ANTHROPIC_KEY`, `GITHUB_TOKEN`, and `LANG` — so
269
+ **Gemini, Langfuse and LangSmith are silently off** inside Docker/HF Spaces.
270
+
271
+ **The fix — add the missing lines to the `environment:` block:**
272
+ ```yaml
273
+ environment:
274
+ # AI provider keys
275
+ - GROQ_API_KEY=${GROQ_API_KEY:-}
276
+ - GEMINI_API_KEY=${GEMINI_API_KEY:-}
277
+ - OPENCODEREVIEW_ANTHROPIC_KEY=${OPENCODEREVIEW_ANTHROPIC_KEY:-}
278
+ # GitHub
279
+ - GITHUB_TOKEN=${GITHUB_TOKEN:-}
280
+ # Observability (optional)
281
+ - LANGFUSE_PUBLIC_KEY=${LANGFUSE_PUBLIC_KEY:-}
282
+ - LANGFUSE_SECRET_KEY=${LANGFUSE_SECRET_KEY:-}
283
+ - LANGFUSE_HOST=${LANGFUSE_HOST:-}
284
+ - LANGFUSE_BASE_URL=${LANGFUSE_BASE_URL:-}
285
+ - LANGSMITH_API_KEY=${LANGSMITH_API_KEY:-}
286
+ - LANGSMITH_PROJECT=${LANGSMITH_PROJECT:-}
287
+ # Language
288
+ - LANG=en_US.UTF-8
289
+ ```
290
+ On Hugging Face Spaces, add the same keys as **Secrets** (Settings → Secrets).
291
+
292
+ ---
293
+
294
+ ## 🧹 Code quality, eval & docs
295
+
296
+ ### Fix 8 — RAGAS: failed metric = `None`, not `0.0` (update ALL consumers)
297
+
298
+ **What's the problem?** In `eval_data/ragas_eval.py`, when a metric fails
299
+ (rate limit, LLM error) it sets that metric to `0.0`. A real failure becomes
300
+ indistinguishable from a genuine score of zero, and the averages in
301
+ `evaluate.py` / `ragas_eval.py` main() silently include these fake zeros.
302
+
303
+ **⚠️ Do this as a set — changing only `ragas_eval.py` will crash the UI and the
304
+ standalone CLI.** Five other places assume every value is a `float`:
305
+
306
+ **1. `eval_data/ragas_eval.py`** — set `None` on failure and widen the type:
307
+ ```python
308
+ scores: dict[str, float | None] = {}
309
+
310
+ # inside each except block:
311
+ except Exception as exc:
312
+ logger.warning("RAGAS context_precision failed: %s", exc)
313
+ scores["context_precision"] = None # ← not 0.0
314
+ ```
315
+
316
+ **2. `app.py` `_format_ragas_scores`** — skip `None` values (it currently does
317
+ `int(value * 100)` → `TypeError` on `None`):
318
+ ```python
319
+ for key, value in scores.items():
320
+ if value is None:
321
+ continue # ← skip failed metrics in the UI card
322
+ ...
323
+ ```
324
+
325
+ **3. `main.py` / `app.py` RAGAS-logging loops** — skip `None` before logging:
326
+ ```python
327
+ for metric_name, value in ragas_scores.items():
328
+ if value is None:
329
+ continue # ← don't send None to create_score
330
+ log_langfuse_score(name=f"ragas_{metric_name}", value=value, ...)
331
+ ```
332
+
333
+ **4. `eval_data/evaluate.py` + `ragas_eval.py` main() averages** — exclude `None`:
334
+ ```python
335
+ values = [s.get(metric) for s in all_scores if s.get(metric) is not None]
336
+ avg = sum(values) / len(values) if values else None
337
+ ```
338
+
339
+ **5. `ragas_eval.py` standalone CLI** — its per-PR print does `f"{k}={v:.3f}"`
340
+ which raises `TypeError` on `None`; filter them out:
341
+ ```python
342
+ print(f" {repo}#{pr}: " + " | ".join(
343
+ f"{k}={v:.3f}" for k, v in scores.items()
344
+ if k not in ("repo", "pr_number", "id") and v is not None
345
+ ))
346
+ ```
347
+
348
+ **6. Widen the function signatures** so type checkers stay happy:
349
+ ```python
350
+ # ragas_eval.py
351
+ def compute_ragas_retrieval_scores(...) -> dict[str, float | None]: ...
352
+ def log_ragas_scores_to_langfuse(scores: dict[str, float | None], ...) -> None: ...
353
+ # app.py
354
+ ragas_scores: dict[str, float | None] = {}
355
+ ```
356
+
357
+ ---
358
+
359
+ ### Fix 9 — Remove dead nodes
360
+
361
+ **What's the problem?** `nodes/__init__.py` imports `passthrough_node` and
362
+ `post_results_node`, but `graph.py` never wires them into the graph — they are
363
+ **dead code** (and `post_results.py` duplicates executor logic that was superseded).
364
+
365
+ **The fix:** delete `nodes/passthrough.py` and `nodes/post_results.py`, and remove
366
+ their two import/`__all__` lines from `nodes/__init__.py`.
367
+
368
+ ---
369
+
370
+ ### Fix 10 — Centralise duplicated constants
371
+
372
+ **What's the problem?** `GROQ_MODEL`, `DEFAULT_TEMPERATURE`, and `_human_size`
373
+ are copy-pasted across `llm_factory.py`, `nodes/aggregator.py`,
374
+ `nodes/correctness_reviewer.py`, and `nodes/retrieval.py`. Drift is inevitable.
375
+
376
+ **The fix:** create `constants.py` with the shared values, import everywhere:
377
+ ```python
378
+ # constants.py
379
+ GROQ_MODEL = "llama-3.3-70b-versatile"
380
+ GEMINI_MODEL = "gemini-3.1-flash-lite"
381
+ DEFAULT_TEMPERATURE = 0.0
382
+
383
+ def human_size(bytes_: int) -> str: ...
384
+ ```
385
+
386
+ ---
387
+
388
+ ### Fix 11 — Add Gemini pricing to cost tracking
389
+
390
+ **What's the problem?** `observability.py:275` `GROQ_PRICING` only knows
391
+ `llama-3.3-70b-versatile` + a pessimistic default. The **primary** LLM is Gemini
392
+ (`gemini-3.1-flash-lite`), so every Gemini run is costed at the wrong default rate.
393
+
394
+ **The fix:** add a `MODEL_PRICING` table keyed by model name (add Gemini's
395
+ published per-1M-token rates) and look up by `model` from `llm_output` (already
396
+ captured at `observability.py:514`).
397
+
398
+ ---
399
+
400
+ ### Fix 12 — README / docstring nits
401
+
402
+ - `README.md:22` badge says **Python 3.11+** but `Dockerfile:25,56` uses
403
+ **python:3.12-slim** — align both on 3.12.
404
+ - `observability.py` module docstring has a malformed `Backends -------- *`
405
+ header — tidy it.
406
+
407
+ ---
408
+
409
+ ### Fix 13 — Executor stale-SHA logging
410
+
411
+ **What's the problem?** `executor.py` fetches the PR head SHA right before posting;
412
+ a force-push in between can make the SHA fetch fail or target stale lines. The 422
413
+ fallback already handles it, but the failure reason is only a generic warning.
414
+
415
+ **The fix:** log the specific failure reason in `_fetch_pr_head_sha` and count
416
+ fallback occurrences (a small counter like `inline_failed` already exists — add
417
+ metrics for the 422 path).
418
+
419
+ ---
420
+
421
+ ## 🧪 Testing
422
+
423
+ ### Fix 14 — Add automated tests
424
+
425
+ **What's the problem?** There are **no tests** (README:566 admits it). Bugs like
426
+ the Langfuse one survive multiple fix attempts because nothing guards them.
427
+
428
+ **The fix — start with the cheap, pure-function tests:**
429
+ ```bash
430
+ pip install pytest
431
+ mkdir tests
432
+ ```
433
+ ```python
434
+ # tests/test_observability.py
435
+ def test_estimate_groq_cost():
436
+ from observability import estimate_groq_cost
437
+ assert estimate_groq_cost("llama-3.3-70b-versatile", 1_000_000, 0) == 0.59
438
+ ```
439
+ Cover first: `aggregator._deduplicate`, `evaluate._fuzzy_match`,
440
+ `observability.estimate_groq_cost`, `config._mask_key`. Then add a
441
+ **Langfuse-score test with a mocked client** asserting `create_score` is called
442
+ with a non-`None` trace_id — that single test would have caught the reported bug.
443
+
444
+ ---
445
+
446
+ ## 🗓️ Suggested order of work
447
+
448
+ 1. **This week:** Fix 1 (`import requests`) → Fix 2 (SQLite close) → Fix 3 (pin deps).
449
+ 2. **Then:** Fix 4 + Fix 5 (Langfuse visibility & score linking) → Fix 6 (naming).
450
+ 3. **When time allows:** Fixes 7–13, then Fix 14 (tests) as the safety net.
451
+
452
+ ---
453
+
454
+ ## ✅ Claims in CODE_REVIEW.md that are NOT true
455
+
456
+ | Claim | Reality (verified) |
457
+ |---|---|
458
+ | "v4 doesn't read `LANGFUSE_HOST` — host var is ignored" | ❌ **False.** langfuse 4.13.1 reads `LANGFUSE_BASE_URL` **or falls back to `LANGFUSE_HOST`** (`client.py:317-319`). `HOST` is deprecated, not ignored. |
459
+ | "v4 handler doesn't expose `trace_id`/`last_trace_id`; `get_current_trace_id()` is not a v4 idiom → all resolve to `None`" | ❌ **Mostly false.** In 4.13.1, `handler.last_trace_id` **exists** (set in `CallbackHandler.py:638`) and `Langfuse().get_current_trace_id()` **exists** (`client.py:2271`). Only `handler.trace_id` is v3-only. |
460
+ | "P1.5: `evaluate.py` never stores per-PR `trace_id`, so scores are always orphaned" | ❌ **Already fixed.** `evaluate.py` `_run_graph_for_pr` returns `trace_id` and `main()` stores it (`metrics["trace_id"] = trace_id`), passed to `lf.create_score(trace_id=…)`. (Commit `a24aa92` fixed this.) |
461
+ | "Unpinned `langfuse` pulls v4.14.2" | ⚠️ Version number off — installed here is **4.13.1** (still v4, so the v3/v4 mixing point stands). |
462
+
463
+ ---
464
+
465
+ ## 📋 Master checklist
466
+
467
+ - [ ] **1.** Add `import requests` to `nodes/executor.py`
468
+ - [ ] **2.** Expose + close the checkpointer connection in `graph.py` / `main.py` / `app.py`
469
+ - [ ] **3.** Pin `langfuse`, `langchain`, `langgraph`, `langgraph-checkpoint-sqlite`, `chromadb`, `langchain-groq`; add `requirements.lock`
470
+ - [ ] **4.** ERROR-log Langfuse failures (+ `OCR_OBSERVABILITY_STRICT=1` re-raise); INFO-log skipped reviewers
471
+ - [ ] **5.** Verify `run_trace_id` is non-`None`; use `get_client()`; flush once per run; set `LANGFUSE_BASE_URL` too
472
+ - [ ] **6.** Route `evaluate.py` RAGAS scores through `log_langfuse_score` with `ragas_` prefix
473
+ - [ ] **7.** Add `GEMINI_API_KEY` + `LANGFUSE_*` + `LANGSMITH_*` to `docker-compose.yml` + HF Secrets
474
+ - [ ] **8.** RAGAS failed metrics → `None` **and** guard app.py formatter, log loops, and averages
475
+ - [ ] **9.** Delete `nodes/passthrough.py` + `nodes/post_results.py` (+ `__init__` lines)
476
+ - [ ] **10.** Centralise `GROQ_MODEL` / `GEMINI_MODEL` / `DEFAULT_TEMPERATURE` / `human_size`
477
+ - [ ] **11.** Add Gemini pricing table to `observability.py`
478
+ - [ ] **12.** Align README badge ↔ Dockerfile on Python 3.12; tidy docstring
479
+ - [ ] **13.** Log executor 422/stale-SHA fallback metrics
480
+ - [ ] **14.** Add `pytest` + `tests/` (pure functions first, then a mocked Langfuse score test)
481
+
482
+ > **Verification commands after any change:**
483
+ > ```bash
484
+ > python -m compileall . # syntax check
485
+ > python -m main review --smoke # offline graph smoke test
486
+ > python -m main doctor # health check
487
+ > pip check # dependency consistency
488
+ > ```
docs/engineering/QUALITY_IMPROVEMENTS.md ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Review quality improvements
2
+
3
+ Implemented changes:
4
+ - Group test suggestions separately, cap low/info, and exclude them from the risk score.
5
+ - Check changed-file/line overlap and derive excerpts from actual source. Source grounding does not prove semantic correctness.
6
+ - Compiler claims without diagnostics are flagged for verification and excluded from the score.
7
+ - Explain risk-score deductions and disclose prompt truncation, reviewed files, Fast windows, incremental scope, and reviewer status.
8
+ - Withhold ungrounded findings from GitHub posting and report the withheld count.
9
+ - Record owner-scoped correct/incorrect/useful feedback on completed findings in the job database.
10
+ - Edit/delete/default provider controls, with browser-local persistence and last successful connection/JSON test metadata.
11
+ - RAGAS metrics have individual deadlines, independent result statuses, explicit skipped unsupported metrics, and bounded hosted inputs. No lexical fallback is labeled RAGAS.
12
+ - Preserve per-metric successes/failures and evaluation configuration through polling and database persistence. Diff-proxy context is disclosed.
13
+ - Distinguish provider-reported cost, estimates, free-model estimates, and unknown costs. Response latency is not mislabeled TTFT.
14
+ - Offline regression tool compares stored predictions against located labels with one-to-one matching; partial gold labels do not yield precision claims.
15
+
16
+ Run regression matching without inference:
17
+
18
+ ```
19
+ python -m eval_data.offline_regression --predictions review.json --fixture eval_data/curated_located_fixture.jsonl --output eval_data/regression_report.json
20
+ ```
21
+
22
+ The curated initial fixture is partial. Location/category/concept matches are evaluation proxies, not proof that a finding is correct. No local models are loaded.
23
+
24
+ Validation: backend and frontend regression tests plus the production frontend build. Live verification is reported separately; no improvement percentages are claimed without a controlled benchmark.
25
+
26
+ Live verification (2026-10-21): Vercel UI and HF backend; calcom/cal.diy PR #10600 with the saved MiniMax free endpoint in Fast mode completed in 40 seconds. All three reviewers completed. Results grouped 9 test suggestions separately from 3 low-severity findings; score breakdown excluded the suggestions. Feedback saved successfully. Provider connection test returned valid JSON in 1.2 seconds; default selection survived refresh. RAGAS context precision completed (1.000, using a truncated PR-diff proxy); faithfulness returned a provider connection error and the UI reported partial evaluation. This run is workflow evidence, not proof of finding correctness or retrieval accuracy.
27
+
28
+ Follow-up live verification after isolated evaluator clients: review f0fa11f7 completed in 53 seconds with all reviewers completed, 1 low bug, 1 medium security concern, 7 test suggestions, and a 9.5/10 risk estimate. Context precision completed (0.000); faithfulness reached its 12-second deadline and remained unscored. Differences between runs reinforce that this hosted judge/model is variable; these proxy scores are not correctness guarantees.
docs/engineering/SPEED_IMPROVEMENTS.md ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Review speed improvements
2
+
3
+ Implemented in this revision:
4
+ - Fast/Thorough modes: reviewer wall deadlines 45/90 seconds, native call timeouts 40/60 seconds; total pipeline also includes ingestion and aggregation.
5
+ - SDK retries disabled; one format repair within the reviewer deadline. No retries for auth/quota/transport failures.
6
+ - Failed reviewers make the result incomplete, with no numeric score and no posting.
7
+ - Background RAGAS uses a captured selected endpoint, stops after quota/auth failures, and is never automatically replayed after restart.
8
+ - Provider probe records real request latency and tests JSON output shape.
9
+ - Fast mode supplies numbered code windows around changes; Thorough retains existing full context bounds.
10
+ - Conservative routing: Fast documentation-only changes skip test coverage explicitly. Correctness/security remain; code, configuration, and unknown changes retain all specialists.
11
+ - Token budgets 1200/2000 per reviewer in Fast/Thorough. Model-specific reasoning parameters are deliberately not forced on incompatible providers.
12
+ - Polling streams completed stages, partial findings, reviewer statuses, timings, queue position, and background evaluation status.
13
+ - Cooperative cancellation discards late results; native network calls finish within their own timeout.
14
+ - Active duplicate prevention and 15-minute preview reuse require matching owner/configuration/prompt+node hashes and fresh GitHub head/base commits. Approval rechecks commits.
15
+ - Explicit incremental baseline comparisons reject divergent/truncated comparisons and are preview-only.
16
+ - GitHub file fetching runs concurrently with a maximum of four workers.
17
+ - User-selected saved providers remain the explicit alternative when a provider fails; no silent use of another user's/operator's key.
18
+
19
+ Validation: backend and frontend regression tests use fake providers; no local model runs. Live deployment verification is reported separately. No percentage speed improvement is claimed before measuring the same PR/model/configuration.
20
+
21
+ Known limits: cancellation is cooperative; browser-saved credentials remain local to the browser; cross-instance job dispatch requires a durable queue. Detailed provider-specific reasoning controls and automatic cross-provider failover are not implemented.
docs/evaluation/OFFLINE_EVALUATION_PLAN.md ADDED
@@ -0,0 +1,278 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # OpenCodeReview Production Revamp and Offline Evaluation Plan
2
+
3
+ ## Scope
4
+
5
+ This plan includes the earlier audit recommendations and adds a repeatable offline correctness benchmark using `code-review-bench/code-review-bench`.
6
+
7
+ The goal is to improve review correctness before allowing automatic use:
8
+
9
+ ```
10
+ offline benchmark -> inspect failures -> change prompts/retrieval/router -> rerun benchmark -> live PR cross-check
11
+ ```
12
+
13
+ ## Earlier recommendations included
14
+
15
+ - Durable job storage instead of the process-local API registry
16
+ - Durable LangGraph checkpoints instead of ephemeral SQLite
17
+ - Correct posting receipts with posted/partial/failed states
18
+ - React polling, findings, verdict, approval, rejection, and delivery status
19
+ - GitHub OAuth/GitHub App authentication
20
+ - Per-user authorization and rate limits
21
+ - Idempotent GitHub posting
22
+ - HF Bucket storage for diffs, vectors, reports, caches, and RAGAS artifacts
23
+ - Supabase/Postgres for jobs, users, approvals, and audit events
24
+ - RAGAS status and score persistence
25
+ - Fast/free model routing with fallback and budgets
26
+ - Repository policies and review modes
27
+ - Automated unit, integration, and browser tests
28
+ - CI deployment gates and health checks
29
+ - Model, prompt, latency, cost, and quality observability
30
+ - Live validation against a real pull request before release
31
+
32
+ ## Offline benchmark
33
+
34
+ ### Primary dataset
35
+
36
+ Use [code-review-bench/code-review-bench](https://huggingface.co/datasets/code-review-bench/code-review-bench).
37
+
38
+ Use the `offline` split first because it contains expert-curated golden issues. Use `online` later for comparison against other review tools.
39
+
40
+ The benchmark must run without:
41
+
42
+ - GitHub comments
43
+ - GitHub write permissions
44
+ - human approval
45
+ - repository mutation
46
+ - production credentials
47
+ - external posting
48
+
49
+ ### Prediction format
50
+
51
+ The review engine must export one JSON object per row:
52
+
53
+ ```json
54
+ {
55
+ "task_id": "stable-row-id",
56
+ "findings": [
57
+ {
58
+ "file_path": "src/example.py",
59
+ "line_start": 42,
60
+ "line_end": 44,
61
+ "severity": "high",
62
+ "category": "correctness",
63
+ "comment": "Explanation of the issue",
64
+ "confidence": 0.87
65
+ }
66
+ ],
67
+ "verdict": {
68
+ "recommendation": "request_changes",
69
+ "overall_score": 6.5
70
+ },
71
+ "model": "provider/model",
72
+ "prompt_version": "review-v1",
73
+ "latency_ms": 12000,
74
+ "cost": 0.0
75
+ }
76
+ ```
77
+
78
+ ### Offline scoring
79
+
80
+ Score every generated finding against the expert issue using:
81
+
82
+ - file path match
83
+ - line overlap with tolerance
84
+ - semantic keyword overlap
85
+ - severity agreement
86
+ - category agreement
87
+
88
+ Report:
89
+
90
+ - precision
91
+ - recall
92
+ - F1
93
+ - finding-level accuracy
94
+ - file-location accuracy
95
+ - severity accuracy
96
+ - false-positive rate
97
+ - no-issue accuracy
98
+ - average confidence
99
+ - confidence calibration
100
+ - latency
101
+ - cost
102
+
103
+ Do not use exact patch matching as the primary metric. Several valid fixes can solve the same issue.
104
+
105
+ ### Error buckets
106
+
107
+ Every failure should be assigned one bucket:
108
+
109
+ - missed issue
110
+ - wrong file
111
+ - wrong line
112
+ - wrong severity
113
+ - wrong category
114
+ - vague explanation
115
+ - false positive
116
+ - duplicate finding
117
+ - unsupported claim
118
+ - malformed output
119
+ - timeout/provider failure
120
+ - retrieval failure
121
+
122
+ ### Improvement loop
123
+
124
+ After each run:
125
+
126
+ 1. Save predictions and scores.
127
+ 2. Export false positives and missed issues.
128
+ 3. Inspect the worst examples.
129
+ 4. Classify root cause:
130
+ - ingestion
131
+ - retrieval
132
+ - prompt
133
+ - model
134
+ - aggregation
135
+ - line mapping
136
+ - schema validation
137
+ 5. Apply the smallest targeted change.
138
+ 6. Rerun the same fixed validation split.
139
+ 7. Compare against the previous result.
140
+ 8. Keep the change only if quality improves without unacceptable latency/cost regression.
141
+
142
+ Keep a regression set of every previously fixed failure.
143
+
144
+ ## Implementation phases
145
+
146
+ ### Phase 1: offline correctness harness
147
+
148
+ - Add `eval_data/code_review_bench_eval.py`.
149
+ - Download the dataset through `datasets`.
150
+ - Normalize offline rows into a stable input format.
151
+ - Accept agent predictions as JSONL.
152
+ - Compute matching metrics and failure buckets.
153
+ - Write `eval_data/code_review_bench_results.json`.
154
+ - Add a smoke fixture with three rows for CI.
155
+
156
+ ### Phase 2: dry-run review adapter
157
+
158
+ - Add a review-engine mode that accepts a prepared diff and changed files.
159
+ - Disable GitHub writes.
160
+ - Disable human interrupt.
161
+ - Return findings, verdict, model metadata, and RAGAS task metadata.
162
+ - Add `--dataset code-review-bench` and `--max-rows N`.
163
+ - Store large inputs/outputs in the HF Bucket.
164
+
165
+ ### Phase 3: RAGAS correctness
166
+
167
+ - Persist RAGAS task state with the review ID.
168
+ - Do not mark RAGAS complete when scores are empty.
169
+ - Return completed metric values or a clear failure reason.
170
+ - Compare retrieval metrics against issue-detection metrics.
171
+ - Add a no-LLM deterministic retrieval baseline.
172
+
173
+ ### Phase 4: durable production workflow
174
+
175
+ - Move jobs and approvals to Supabase/Postgres.
176
+ - Store LangGraph thread IDs and head SHAs.
177
+ - Use a durable queue/worker.
178
+ - Add retries, timeouts, cancellation, and dead-letter states.
179
+ - Store artifacts and reports in the HF Bucket.
180
+
181
+ ### Phase 5: authentication and GitHub
182
+
183
+ - Implement GitHub OAuth or GitHub App login.
184
+ - Use secure HTTP-only sessions.
185
+ - Associate jobs with users.
186
+ - Enforce repository access and job ownership.
187
+ - Add idempotency keys.
188
+ - Recheck PR head SHA before posting.
189
+ - Return exact GitHub comment URLs and failure counts.
190
+
191
+ ### Phase 6: model routing
192
+
193
+ - Add `fast`, `balanced`, and `deep` profiles.
194
+ - Prefer free/local providers when configured.
195
+ - Use provider health checks.
196
+ - Retry only transient errors.
197
+ - Enforce token, latency, and cost budgets.
198
+ - Record provider/model/prompt version for every run.
199
+
200
+ ### Phase 7: release verification
201
+
202
+ - Unit tests
203
+ - API contract tests
204
+ - Graph interrupt/resume tests
205
+ - Fake GitHub integration tests
206
+ - Browser tests
207
+ - Container build
208
+ - Vercel build
209
+ - Secret scan
210
+ - Dependency audit
211
+ - Deployment health check
212
+ - Offline benchmark gate
213
+ - Live PR cross-check
214
+
215
+ ## Release gates
216
+
217
+ Do not call a release production-ready unless:
218
+
219
+ - offline F1 meets the agreed threshold
220
+ - false-positive rate is measured
221
+ - no malformed predictions occur in the smoke set
222
+ - RAGAS returns real metrics or an explicit failure state
223
+ - review state survives a worker restart
224
+ - approval is authenticated
225
+ - posting is idempotent
226
+ - a live PR review matches an independent cross-check
227
+ - Vercel and backend health checks pass
228
+
229
+ ## Live cross-check procedure
230
+
231
+ 1. Select a public PR not used in development.
232
+ 2. Run it through the React/Vercel flow.
233
+ 3. Save the generated findings.
234
+ 4. Run the Hugging Face/legacy flow against the same repository, PR, and head SHA.
235
+ 5. Compare:
236
+ - finding count
237
+ - file and line locations
238
+ - severity
239
+ - explanation
240
+ - verdict
241
+ - RAGAS status and scores
242
+ 6. Do not approve or post until the comparison is complete.
243
+ 7. Record the result in the evaluation report.
244
+
245
+ ## Storage design
246
+
247
+ HF Bucket:
248
+
249
+ ```text
250
+ eval/<dataset>/<run-id>/
251
+ manifest.json
252
+ predictions.jsonl
253
+ scores.json
254
+ failures.jsonl
255
+ ragas.json
256
+ reports/
257
+ ```
258
+
259
+ Postgres:
260
+
261
+ ```text
262
+ reviews
263
+ review_findings
264
+ review_events
265
+ model_runs
266
+ approvals
267
+ evaluation_runs
268
+ ```
269
+
270
+ ## Correctness principles
271
+
272
+ - A finding is correct only when its claim is supported by the diff/context.
273
+ - A high confidence score must correspond to a high likelihood of correctness.
274
+ - A valid review may contain no findings.
275
+ - A patch that passes tests is not automatically a good review.
276
+ - The system must distinguish “no issue found” from “review failed.”
277
+ - Every result must include model, prompt version, dataset revision, and timestamp.
278
+
docs/operations/PRODUCTION_READINESS.md ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Production readiness checklist
2
+
3
+ ## Verified
4
+
5
+ - Supabase Postgres stores review jobs and survives a Space restart.
6
+ - Review findings and verdicts are recoverable after restart.
7
+ - RAGAS inputs and terminal failures are persisted in job payloads.
8
+ - Groq provider routing avoids an exhausted Gemini quota when Groq is configured.
9
+ - RAGAS can produce real context precision, faithfulness, and MMR values.
10
+ - RAGAS provider calls have bounded retries and timeouts.
11
+ - GitHub posting receipts distinguish inline, fallback, finding, and verdict failures.
12
+ - React production build and Vercel deployment succeed.
13
+ - A reproducible diff-backed benchmark fixture exists for five public PRs.
14
+ - Live validation on `calcom/cal.com#8087` detected all four unawaited
15
+ `forEach(async ...)` defects and returned `request_changes` with four high
16
+ findings (score 2/10).
17
+ - The approve path was exercised on that live job and persisted a truthful
18
+ `post_failed` receipt: 0 inline comments, 0 fallback comments, 4 finding
19
+ failures, and 1 verdict failure.
20
+ - API rate limiting is enabled at 10 requests/minute and was verified live
21
+ behind the Hugging Face proxy with a safe concurrent test producing HTTP 429.
22
+ - Review creation idempotency was verified live: repeated submissions with the
23
+ same `Idempotency-Key` returned the same persisted job ID.
24
+ - Deterministic correctness checks survive remote-provider failures, and model
25
+ prompts now bound diff and changed-file context to free-provider limits.
26
+
27
+ ## Required before production release
28
+
29
+ - Generate predictions from the five diff-backed fixtures and record precision,
30
+ recall, F1, severity, category, and false-positive results.
31
+ - Run an approve decision against a safe test PR and verify the GitHub posting
32
+ receipt and resulting comments.
33
+ - Add per-user GitHub OAuth or GitHub App authentication and job ownership.
34
+ - Enable required API authentication and rate limits after OAuth is wired into
35
+ the frontend.
36
+ - Add browser, API lifecycle, restart-recovery, and posting integration tests.
37
+ - Verify a second repository and PR independently of the project repository.
38
+
39
+ RAGAS scores must remain explicitly marked unavailable or failed when the
40
+ provider cannot return. The system must never substitute invented metrics.
docs/planning/revamp.md ADDED
@@ -0,0 +1,670 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # OpenCodeReview Revamp Plan
2
+
3
+ ## Vision
4
+
5
+ Turn OpenCodeReview into a reliable, fast, human-approved code review platform:
6
+
7
+ - React workspace on Vercel
8
+ - Python review API and worker on Hugging Face or another container host
9
+ - GitHub OAuth/App authentication
10
+ - Durable job and approval state
11
+ - Hugging Face Bucket for large artifacts and caches
12
+ - Fast, low-cost model routing
13
+ - Observable, testable, repeatable review results
14
+
15
+ The current Gradio Space remains useful as a reference implementation, but React should become the primary product surface.
16
+
17
+ ## Current baseline
18
+
19
+ Working today:
20
+
21
+ - React frontend deployed to Vercel
22
+ - FastAPI boundary deployed with the Hugging Face Space
23
+ - LangGraph review pipeline
24
+ - GitHub PR ingestion and comment posting
25
+ - Human approval checkpoint
26
+ - Correctness, security, and test-coverage reviewers
27
+ - Background RAGAS task creation
28
+ - Endpoint fallback support
29
+ - Basic CORS and token protection
30
+ - Live review polling, findings, verdict, approval, rejection, and delivery receipt in React
31
+
32
+ Known gaps:
33
+
34
+ - Job registry is process-local
35
+ - SQLite checkpoints are not durable on a restarted Space
36
+ - React does not yet receive reliable final RAGAS metric values
37
+ - Authentication is not implemented for browser users
38
+ - API rate limiting and per-user authorization are missing
39
+ - GitHub posting status needs durable receipts and idempotency
40
+ - Automated tests are incomplete
41
+ - Vercel and Hugging Face deployments are not fully release-gated
42
+
43
+ ## Target architecture
44
+
45
+ ```
46
+ Browser
47
+ |
48
+ | GitHub OAuth session
49
+ v
50
+ React/Vercel
51
+ |
52
+ | authenticated API requests
53
+ v
54
+ FastAPI API
55
+ |
56
+ +--> Supabase/Postgres
57
+ | users, installations, reviews, approvals, statuses
58
+ |
59
+ +--> Durable queue/workflow
60
+ | queued, retrying, running, awaiting approval, posting
61
+ |
62
+ +--> Review worker
63
+ | LangGraph, ingestion, retrieval, reviewers, aggregator
64
+ |
65
+ +--> Hugging Face Bucket
66
+ | diffs, vectors, reports, RAGAS, cache, traces
67
+ |
68
+ +--> GitHub App API
69
+ | read PR, create review, post approved comments
70
+ |
71
+ +--> LLM router
72
+ free/local/paid providers with fallback and budgets
73
+ ```
74
+
75
+ Use Postgres for transactional state. Use the HF Bucket for large mutable artifacts. Buckets provide S3-like object storage and `hf://buckets/` access, but they are not a transactional job database and do not provide Git-style history. See the [Hugging Face Buckets documentation](https://huggingface.co/docs/hub/main/en/storage-buckets).
76
+
77
+ ## Product features
78
+
79
+ ### Review workspace
80
+
81
+ - Repository and pull request input
82
+ - GitHub repository picker after OAuth
83
+ - Open PR picker with title, author, labels, and changed-file count
84
+ - Review mode:
85
+ - full review
86
+ - security only
87
+ - correctness only
88
+ - tests only
89
+ - quick review
90
+ - Model/provider selector with availability and latency
91
+ - Review policy selector
92
+ - Path ignore rules
93
+ - Start, cancel, retry, and duplicate-review detection
94
+ - Live progress timeline:
95
+ - fetching PR
96
+ - reading changed files
97
+ - retrieving context
98
+ - running reviewers
99
+ - aggregating findings
100
+ - computing RAGAS
101
+ - awaiting approval
102
+ - posting
103
+ - Findings grouped by severity and reviewer
104
+ - Finding filters:
105
+ - critical/high/medium/low/info
106
+ - security/correctness/tests/performance/style
107
+ - confidence threshold
108
+ - Diff viewer with source lines
109
+ - Suggested fix viewer
110
+ - Edit finding before approval
111
+ - Approve all, approve selected, reject, or request rerun
112
+ - GitHub posting receipt
113
+ - Review history
114
+ - Compare reviews across commits
115
+ - Download Markdown, JSON, and SARIF reports
116
+ - Shareable private review links
117
+ - Keyboard navigation and screen-reader support
118
+ - Mobile responsive layout
119
+ - Dark and light themes
120
+
121
+ ### GitHub integration
122
+
123
+ Use a GitHub App rather than a long-lived personal access token.
124
+
125
+ Required capabilities:
126
+
127
+ - Sign in with GitHub OAuth
128
+ - List repositories available to the user
129
+ - List open pull requests
130
+ - Read pull request metadata and diffs
131
+ - Read repository files
132
+ - Post approved review comments
133
+ - Submit one atomic pull request review
134
+ - Add GitHub Checks results
135
+ - Receive pull request webhooks
136
+ - Re-review only when the head SHA changes
137
+ - Avoid duplicate comments using a review marker
138
+ - Handle renamed/deleted files and stale lines
139
+ - Handle GitHub rate limits and retry-after headers
140
+ - Support private repositories only after explicit installation permission
141
+
142
+ Use least privilege:
143
+
144
+ - Contents: read
145
+ - Pull requests: read/write only for posting
146
+ - Checks: write if Checks integration is enabled
147
+ - Metadata: read
148
+
149
+ Never expose GitHub access tokens to the browser.
150
+
151
+ ### Repository policies
152
+
153
+ Per-repository configuration should support:
154
+
155
+ - Minimum confidence threshold
156
+ - Severity threshold for blocking
157
+ - Required reviewers
158
+ - Files or directories to ignore
159
+ - Generated-file patterns
160
+ - Test-file requirements
161
+ - Security-sensitive paths
162
+ - Maximum review cost
163
+ - Maximum changed-file count
164
+ - Required model or provider
165
+ - Auto-review on pull request event
166
+ - Whether approval is required for every run
167
+
168
+ Store policies in Postgres and export them as versioned JSON.
169
+
170
+ ### Team features
171
+
172
+ - Organizations and teams
173
+ - Repository ownership
174
+ - Reviewer roles
175
+ - Audit log
176
+ - Review activity dashboard
177
+ - Accepted/rejected finding feedback
178
+ - Team-level cost budgets
179
+ - Model quality dashboard
180
+ - Slack or email notifications
181
+ - Shared policies and prompt versions
182
+
183
+ ## Authentication and authorization
184
+
185
+ ### Browser login
186
+
187
+ Implement GitHub OAuth or GitHub App user authorization:
188
+
189
+ 1. React sends the user to the backend authorization route.
190
+ 2. Backend redirects to GitHub.
191
+ 3. GitHub redirects back with a short-lived code.
192
+ 4. Backend exchanges the code server-side.
193
+ 5. Backend creates a secure, HTTP-only session cookie.
194
+ 6. React calls `/api/me` to load the session.
195
+
196
+ Security requirements:
197
+
198
+ - HTTP-only, Secure, SameSite cookies
199
+ - State and nonce validation
200
+ - Short-lived sessions
201
+ - Refresh or reauthorization flow
202
+ - Logout endpoint
203
+ - CSRF protection for cookie-authenticated mutations
204
+ - Never store GitHub client secrets in Vite environment variables
205
+ - Never put access tokens in localStorage
206
+ - Per-user ownership checks on every review job
207
+ - Separate GitHub App installation access from user identity
208
+
209
+ ### API protection
210
+
211
+ - Require authentication outside local development
212
+ - Add per-user and per-IP rate limits
213
+ - Add idempotency keys to review creation
214
+ - Limit maximum repository/PR request size
215
+ - Validate repository access before queueing
216
+ - Return structured error codes
217
+ - Redact tokens, prompts, and repository secrets from logs
218
+
219
+ ## Model strategy
220
+
221
+ ### Routing principles
222
+
223
+ Use a model router rather than one fixed provider:
224
+
225
+ 1. Select the fastest eligible model for the requested review mode.
226
+ 2. Use a free or local model for quick triage.
227
+ 3. Use a stronger model only for high-risk or ambiguous findings.
228
+ 4. Retry only transient provider failures.
229
+ 5. Enforce per-review token and cost budgets.
230
+ 6. Record provider, model, prompt version, latency, tokens, and outcome.
231
+
232
+ ### Free and low-cost options
233
+
234
+ Availability and free quotas change, so configure them through environment variables and health checks instead of hard-coding promises.
235
+
236
+ Recommended tiers:
237
+
238
+ - Local development:
239
+ - Ollama with a small code model
240
+ - llama.cpp-compatible model
241
+ - Transformers.js for lightweight browser experiments
242
+ - Free/low-cost hosted fallback:
243
+ - Hugging Face Inference Providers when a suitable free quota is available
244
+ - Groq free tier when available
245
+ - Gemini free tier when available
246
+ - OpenAI-compatible community endpoints only when trusted and explicitly configured
247
+ - Stronger optional providers:
248
+ - paid Gemini, Anthropic, OpenAI-compatible providers, or Groq tiers
249
+
250
+ ### Fastest inference profile
251
+
252
+ Create a `fast` profile:
253
+
254
+ - Small code-capable model
255
+ - Low temperature
256
+ - Short context
257
+ - Diff-only input first
258
+ - Retrieval only for changed symbols
259
+ - Parallel reviewer calls
260
+ - Strict output schema
261
+ - Maximum latency budget
262
+ - Early exit when no actionable change is detected
263
+
264
+ Create a `deep` profile:
265
+
266
+ - Larger context
267
+ - Repository retrieval
268
+ - Three specialist reviewers
269
+ - More validation
270
+ - Higher token budget
271
+ - Required human approval
272
+
273
+ A useful default route:
274
+
275
+ ```
276
+ quick triage -> fast model
277
+ security/high-risk change -> stronger model
278
+ provider failure -> next configured provider
279
+ all providers unavailable -> clear failed state
280
+ ```
281
+
282
+ ### Model quality controls
283
+
284
+ - JSON schema validation for every model result
285
+ - Automatic retry for malformed output
286
+ - Finding deduplication
287
+ - Confidence calibration
288
+ - Prompt versioning
289
+ - Golden PR dataset
290
+ - Precision, recall, false-positive, and latency tracking
291
+ - Human feedback labels:
292
+ - useful
293
+ - duplicate
294
+ - false positive
295
+ - missed issue
296
+ - accepted fix
297
+
298
+ ## Hugging Face Bucket plan
299
+
300
+ Create a private bucket such as:
301
+
302
+ ```text
303
+ Sdm0/opencodereview-data
304
+ ```
305
+
306
+ Suggested layout:
307
+
308
+ ```text
309
+ review-artifacts/<owner>__<repo>/pr-<number>/<head-sha>/
310
+ request.json
311
+ metadata.json
312
+ diff.patch
313
+ changed-files.json
314
+ findings.json
315
+ verdict.json
316
+ report.md
317
+ report.sarif
318
+ ragas/<review-id>/
319
+ status.json
320
+ scores.json
321
+ vectors/<repository-key>/
322
+ chroma/
323
+ cache/github/<owner>__<repo>/pr-<number>/<head-sha>/
324
+ pull.json
325
+ files.json
326
+ diff.patch
327
+ logs/<date>/<review-id>.jsonl
328
+ ```
329
+
330
+ Use the Bucket for:
331
+
332
+ - Chroma/vector persistence
333
+ - PR diff cache
334
+ - Raw GitHub responses
335
+ - Review reports
336
+ - RAGAS results
337
+ - Evaluation runs
338
+ - Model comparison artifacts
339
+ - Debug traces
340
+ - Rolling backups
341
+
342
+ Do not use it as the only source of truth for:
343
+
344
+ - Job status
345
+ - User sessions
346
+ - Approvals
347
+ - Authorization
348
+ - Idempotency locks
349
+
350
+ Use Postgres/Supabase for those.
351
+
352
+ ## Job and persistence redesign
353
+
354
+ Create these tables:
355
+
356
+ ### users
357
+
358
+ - id
359
+ - github_user_id
360
+ - login
361
+ - avatar_url
362
+ - created_at
363
+ - last_seen_at
364
+
365
+ ### github_installations
366
+
367
+ - id
368
+ - owner
369
+ - installation_id
370
+ - encrypted credential reference
371
+ - permissions
372
+ - created_at
373
+
374
+ ### reviews
375
+
376
+ - id
377
+ - user_id
378
+ - repo
379
+ - pr_number
380
+ - head_sha
381
+ - status
382
+ - requested_mode
383
+ - requested_model
384
+ - created_at
385
+ - started_at
386
+ - completed_at
387
+ - error_code
388
+ - error_message
389
+
390
+ ### review_findings
391
+
392
+ - id
393
+ - review_id
394
+ - file_path
395
+ - line_start
396
+ - line_end
397
+ - severity
398
+ - category
399
+ - comment
400
+ - confidence
401
+ - suggested_fix
402
+ - decision
403
+
404
+ ### review_events
405
+
406
+ - id
407
+ - review_id
408
+ - event_type
409
+ - payload
410
+ - created_at
411
+
412
+ ### approvals
413
+
414
+ - id
415
+ - review_id
416
+ - user_id
417
+ - action
418
+ - created_at
419
+
420
+ ### model_runs
421
+
422
+ - id
423
+ - review_id
424
+ - provider
425
+ - model
426
+ - prompt_version
427
+ - latency_ms
428
+ - input_tokens
429
+ - output_tokens
430
+ - cost
431
+ - status
432
+
433
+ ## RAGAS implementation
434
+
435
+ - Persist a RAGAS task ID with the review.
436
+ - Write task state to Postgres and scores to the HF Bucket.
437
+ - Expose `GET /api/reviews/{id}/ragas`.
438
+ - Return:
439
+ - pending
440
+ - completed
441
+ - failed
442
+ - timed_out
443
+ - Persist individual metrics:
444
+ - context precision
445
+ - context recall
446
+ - faithfulness
447
+ - answer relevancy
448
+ - Show timestamps and model/provider used.
449
+ - Do not label a task “completed” when the score object is empty.
450
+ - Add a timeout and a clear failure reason.
451
+ - Add a rerun-RAGAS action without rerunning the full review.
452
+
453
+ ## API design
454
+
455
+ Recommended routes:
456
+
457
+ ```text
458
+ GET /api/health
459
+ GET /api/me
460
+ GET /api/auth/github/start
461
+ GET /api/auth/github/callback
462
+ POST /api/auth/logout
463
+
464
+ GET /api/repos
465
+ GET /api/repos/{owner}/{repo}/pulls
466
+
467
+ POST /api/reviews
468
+ GET /api/reviews/{id}
469
+ POST /api/reviews/{id}/cancel
470
+ POST /api/reviews/{id}/retry
471
+ POST /api/reviews/{id}/decision
472
+ GET /api/reviews/{id}/events
473
+ GET /api/reviews/{id}/ragas
474
+ GET /api/reviews/{id}/artifacts/{type}
475
+
476
+ POST /api/webhooks/github
477
+ GET /api/policies/{owner}/{repo}
478
+ PUT /api/policies/{owner}/{repo}
479
+ ```
480
+
481
+ Use Server-Sent Events for live progress. Keep polling as a fallback.
482
+
483
+ ## GitHub posting reliability
484
+
485
+ - Re-fetch the PR head SHA immediately before posting.
486
+ - Refuse to post if the SHA changed.
487
+ - Submit comments atomically where possible.
488
+ - Record each GitHub comment ID.
489
+ - Use idempotency keys to prevent duplicate comments.
490
+ - Return:
491
+ - inline posted count
492
+ - fallback posted count
493
+ - failed count
494
+ - verdict posted
495
+ - GitHub URLs
496
+ - Mark results as:
497
+ - posted
498
+ - partially_posted
499
+ - post_failed
500
+ - dry_run
501
+ - rejected
502
+
503
+ ## Testing strategy
504
+
505
+ ### Unit tests
506
+
507
+ - Repository and PR validation
508
+ - Endpoint validation
509
+ - RAGAS state transitions
510
+ - Finding deduplication
511
+ - Severity filtering
512
+ - GitHub line fallback
513
+ - Idempotency
514
+ - Authorization checks
515
+
516
+ ### Integration tests
517
+
518
+ - Fake GitHub API
519
+ - Fake LLM provider
520
+ - LangGraph interrupt/resume
521
+ - Review restart recovery
522
+ - Queue retry
523
+ - Bucket upload/download
524
+ - Postgres migrations
525
+ - API contract tests
526
+
527
+ ### Browser tests
528
+
529
+ - Login
530
+ - Start review
531
+ - Progress states
532
+ - Findings rendering
533
+ - RAGAS pending/completed/failed states
534
+ - Approve flow
535
+ - Reject flow
536
+ - Posting receipt
537
+ - Network failure recovery
538
+ - Mobile layout
539
+ - Keyboard navigation
540
+
541
+ ### CI gates
542
+
543
+ - Ruff/format/lint
544
+ - Mypy or pyright
545
+ - Pytest
546
+ - Frontend build
547
+ - ESLint
548
+ - Playwright smoke tests
549
+ - Secret scan
550
+ - Dependency audit
551
+ - Container build
552
+ - Container vulnerability scan
553
+ - Deployment health check
554
+ - Automatic rollback if health checks fail
555
+
556
+ ## Observability
557
+
558
+ Track:
559
+
560
+ - review duration
561
+ - queue delay
562
+ - ingestion duration
563
+ - retrieval duration
564
+ - reviewer duration
565
+ - aggregation duration
566
+ - RAGAS duration
567
+ - model latency
568
+ - tokens and cost
569
+ - provider failures
570
+ - GitHub API latency
571
+ - comment success/failure
572
+ - false-positive feedback
573
+ - restart recovery count
574
+
575
+ Use structured JSON logs with a review ID and user ID. Keep sensitive code and credentials out of logs.
576
+
577
+ ## Deployment plan
578
+
579
+ ### Vercel
580
+
581
+ - React frontend only
582
+ - Production environment points to the authenticated API
583
+ - Preview deployments use a staging API
584
+ - Add CSP and security headers
585
+ - Add runtime configuration endpoint for non-secret feature flags
586
+
587
+ ### Hugging Face
588
+
589
+ - API and worker container
590
+ - Private Bucket mounted at a stable path
591
+ - Secrets stored in Space secrets
592
+ - Health endpoint and readiness endpoint
593
+ - Separate worker process if supported
594
+ - Deployment smoke test after every build
595
+
596
+ ### Supabase
597
+
598
+ - Jobs, users, approvals, policies, model runs, and audit events
599
+ - Row-level security
600
+ - Database migrations
601
+ - Backups and retention
602
+ - Indexes on user ID, status, repo, PR number, and head SHA
603
+
604
+ ## Phased delivery
605
+
606
+ ### Phase 1: reliability
607
+
608
+ - Fix RAGAS empty-score handling
609
+ - Persist jobs and approvals
610
+ - Add restart recovery
611
+ - Add structured status transitions
612
+ - Add executor delivery receipts
613
+ - Add API tests and browser smoke tests
614
+
615
+ ### Phase 2: authentication
616
+
617
+ - GitHub OAuth/App login
618
+ - User-owned reviews
619
+ - Repository picker
620
+ - Private repository support
621
+ - Logout and session expiry
622
+
623
+ ### Phase 3: speed and cost
624
+
625
+ - Fast model profile
626
+ - Provider health checks
627
+ - Token budgets
628
+ - Cache GitHub responses
629
+ - Cache retrieval vectors in HF Bucket
630
+ - Parallel reviewer limits
631
+ - Early-exit triage
632
+
633
+ ### Phase 4: product depth
634
+
635
+ - Review history
636
+ - Diff viewer
637
+ - Editable findings
638
+ - Policy editor
639
+ - SARIF export
640
+ - GitHub Checks
641
+ - Webhooks
642
+ - Notifications
643
+ - Team dashboards
644
+
645
+ ### Phase 5: quality moat
646
+
647
+ - Golden benchmark dataset
648
+ - Human feedback loop
649
+ - Model comparison dashboard
650
+ - Prompt version management
651
+ - Confidence calibration
652
+ - Repository architecture memory
653
+ - Regression alerts
654
+
655
+ ## Definition of done
656
+
657
+ The revamp is complete when:
658
+
659
+ - A user can sign in with GitHub.
660
+ - The user can select an accessible repository and PR.
661
+ - A review survives an API/worker restart.
662
+ - The UI shows progress and findings.
663
+ - RAGAS reports real metric values or a clear failure state.
664
+ - Approval is authenticated and authorized.
665
+ - GitHub posting is idempotent and accurately reported.
666
+ - Artifacts are recoverable from the HF Bucket.
667
+ - Tests pass in CI.
668
+ - Deployments run health checks and can roll back.
669
+ - Free-tier operation has documented limits and graceful degradation.
670
+
docs/project-guide/OpenCodeReview_AI_Engineering_Architecture_Guide.docx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:22ec39ed87398360966f5afd10ad85e43f77851ed0515b2247e87435dd6e94e0
3
+ size 251046
docs/project-guide/OpenCodeReview_AI_Engineering_Architecture_Guide.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7296de6f40cd7c88d36a6ee022b1447a2d9ae5d3d80893da9572d7a4dc319312
3
+ size 371192
docs/project-guide/README.md ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # AI engineer interview guide
2
+
3
+ This folder contains the OpenCodeReview architecture guide in DOCX and PDF formats.
4
+ The guide explains the project in plain language and adds technical details for AI
5
+ engineering interviews.
6
+
7
+ ## Contents
8
+
9
+ - `OpenCodeReview_AI_Engineering_Architecture_Guide.docx` — editable document.
10
+ - `OpenCodeReview_AI_Engineering_Architecture_Guide.pdf` — shareable PDF.
11
+ - `assets/` — source diagrams used by the document builder.
12
+ - `tools/` — scripts that create the DOCX, HTML preview, PDF, and page contact sheets.
13
+ - `working/` — generated HTML/PDF previews and rendered page images; kept local and ignored by Git.
14
+
15
+ ## Rebuild
16
+
17
+ From the repository root, run the DOCX builder with Python packages `python-docx`
18
+ and `Pillow` available:
19
+
20
+ ```powershell
21
+ py -3 docs/project-guide/tools/build_opencodereview_guide.py
22
+ ```
23
+
24
+ To create an HTML preview, run:
25
+
26
+ ```powershell
27
+ py -3 docs/project-guide/tools/docx_to_html_preview.py
28
+ ```
29
+
30
+ The PDF renderer uses Playwright. Set `BROWSER_EXECUTABLE_PATH` if you want it to
31
+ use a specific installed browser; otherwise Playwright uses its configured browser:
32
+
33
+ ```powershell
34
+ node docs/project-guide/tools/render_preview.cjs
35
+ ```
36
+
37
+ Rendered PDF pages and contact sheets stay in `working/` so they do not clutter the
38
+ project's source folders.
docs/project-guide/assets/architecture.png ADDED

Git LFS Details

  • SHA256: 21e02a944708d1b542a7d9edca454c3adde0bd3853fbd8c86aa052507311a747
  • Pointer size: 131 Bytes
  • Size of remote file: 107 kB
docs/project-guide/assets/review_workflow.png ADDED
docs/project-guide/tools/build_opencodereview_guide.py ADDED
@@ -0,0 +1,996 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+ from textwrap import wrap
5
+
6
+ from PIL import Image, ImageDraw, ImageFont
7
+ from docx import Document
8
+ from docx.enum.section import WD_SECTION
9
+ from docx.enum.table import WD_CELL_VERTICAL_ALIGNMENT, WD_TABLE_ALIGNMENT
10
+ from docx.enum.text import WD_ALIGN_PARAGRAPH, WD_BREAK, WD_LINE_SPACING
11
+ from docx.oxml import OxmlElement
12
+ from docx.oxml.ns import qn
13
+ from docx.shared import Inches, Pt, RGBColor
14
+
15
+
16
+ ROOT = Path(__file__).resolve().parents[3]
17
+ GUIDE_DIR = ROOT / "docs" / "project-guide"
18
+ WORK = GUIDE_DIR / "working"
19
+ ASSETS = GUIDE_DIR / "assets"
20
+ OUTPUT = GUIDE_DIR / "OpenCodeReview_AI_Engineering_Architecture_Guide.docx"
21
+ ARCH_DIAGRAM = ASSETS / "architecture.png"
22
+ FLOW_DIAGRAM = ASSETS / "review_workflow.png"
23
+
24
+ BLACK = "1F2937"
25
+ MUTED = "52606D"
26
+ ACCENT = "0F6B78"
27
+ ACCENT_DARK = "0B4F59"
28
+ ACCENT_LIGHT = "DDEFF2"
29
+ LIGHT = "F6F8FA"
30
+ MID = "E7ECF0"
31
+ WHITE = "FFFFFF"
32
+ GREEN = "2F855A"
33
+ AMBER = "B7791F"
34
+ RED = "B23A48"
35
+
36
+
37
+ def font(size: int, bold: bool = False) -> ImageFont.FreeTypeFont:
38
+ candidates = [
39
+ Path(r"C:\Windows\Fonts\arialbd.ttf" if bold else r"C:\Windows\Fonts\arial.ttf"),
40
+ Path(r"C:\Windows\Fonts\calibrib.ttf" if bold else r"C:\Windows\Fonts\calibri.ttf"),
41
+ ]
42
+ for candidate in candidates:
43
+ if candidate.exists():
44
+ return ImageFont.truetype(str(candidate), size=size)
45
+ return ImageFont.load_default()
46
+
47
+
48
+ def draw_centered_text(draw: ImageDraw.ImageDraw, box, text: str, size: int, bold: bool = False, fill="#1F2937"):
49
+ x1, y1, x2, y2 = box
50
+ fnt = font(size, bold)
51
+ max_width = x2 - x1 - 30
52
+ words = text.split()
53
+ lines = []
54
+ line = ""
55
+ for word in words:
56
+ candidate = f"{line} {word}".strip()
57
+ if draw.textbbox((0, 0), candidate, font=fnt)[2] <= max_width:
58
+ line = candidate
59
+ else:
60
+ if line:
61
+ lines.append(line)
62
+ line = word
63
+ if line:
64
+ lines.append(line)
65
+ line_h = size + 7
66
+ total_h = len(lines) * line_h
67
+ y = y1 + ((y2 - y1) - total_h) / 2
68
+ for item in lines:
69
+ bounds = draw.textbbox((0, 0), item, font=fnt)
70
+ width = bounds[2] - bounds[0]
71
+ draw.text((x1 + ((x2 - x1) - width) / 2, y), item, font=fnt, fill=fill)
72
+ y += line_h
73
+
74
+
75
+ def rounded_box(draw, box, fill, outline="#8AA2AE", radius=18, width=3):
76
+ draw.rounded_rectangle(box, radius=radius, fill=fill, outline=outline, width=width)
77
+
78
+
79
+ def arrow(draw, start, end, fill="#52606D", width=5):
80
+ draw.line([start, end], fill=fill, width=width)
81
+ x2, y2 = end
82
+ x1, y1 = start
83
+ if abs(x2 - x1) >= abs(y2 - y1):
84
+ sign = 1 if x2 > x1 else -1
85
+ pts = [(x2, y2), (x2 - 15 * sign, y2 - 10), (x2 - 15 * sign, y2 + 10)]
86
+ else:
87
+ sign = 1 if y2 > y1 else -1
88
+ pts = [(x2, y2), (x2 - 10, y2 - 15 * sign), (x2 + 10, y2 - 15 * sign)]
89
+ draw.polygon(pts, fill=fill)
90
+
91
+
92
+ def create_architecture_diagram():
93
+ img = Image.new("RGB", (1800, 1050), "white")
94
+ d = ImageDraw.Draw(img)
95
+ title = font(42, True)
96
+ d.text((70, 42), "OpenCodeReview deployment and runtime architecture", font=title, fill="#1F2937")
97
+ d.text((72, 98), "Two deployments with one modular backend process", font=font(25), fill="#52606D")
98
+
99
+ # User and frontend
100
+ rounded_box(d, (70, 210, 340, 380), "#F6F8FA")
101
+ draw_centered_text(d, (70, 210, 340, 380), "Reviewer in browser", 29, True)
102
+ arrow(d, (340, 295), (430, 295))
103
+ rounded_box(d, (430, 180, 780, 410), "#DDEFF2", "#0F6B78")
104
+ draw_centered_text(d, (430, 195, 780, 270), "Vercel frontend", 31, True, "#0B4F59")
105
+ draw_centered_text(d, (450, 270, 760, 390), "React and Vite\nStatic UI\nProvider test function", 24)
106
+
107
+ # API and graph
108
+ arrow(d, (780, 295), (880, 295))
109
+ rounded_box(d, (880, 150, 1710, 720), "#F6F8FA", "#7C8B96")
110
+ draw_centered_text(d, (900, 165, 1690, 235), "Hugging Face Docker Space", 31, True)
111
+ rounded_box(d, (930, 265, 1220, 435), "#E8F4EA", "#2F855A")
112
+ draw_centered_text(d, (930, 265, 1220, 435), "FastAPI\nAuth and job API", 27, True)
113
+ arrow(d, (1220, 350), (1300, 350))
114
+ rounded_box(d, (1300, 250, 1650, 460), "#FFF4D6", "#B7791F")
115
+ draw_centered_text(d, (1300, 250, 1650, 460), "In process workers\nLangGraph review\nRAGAS evaluation", 26, True)
116
+ rounded_box(d, (930, 505, 1220, 655), "#F1EAFE", "#7559A8")
117
+ draw_centered_text(d, (930, 505, 1220, 655), "Legacy Gradio UI\nMounted at root", 25, True)
118
+ rounded_box(d, (1300, 520, 1650, 665), "#EAF2FF", "#3D6FB4")
119
+ draw_centered_text(d, (1300, 520, 1650, 665), "Job records SQLite or Supabase\nGraph checkpoints SQLite", 23, True)
120
+ arrow(d, (1475, 460), (1475, 520))
121
+
122
+ # External systems
123
+ rounded_box(d, (120, 820, 450, 980), "#F6F8FA")
124
+ draw_centered_text(d, (120, 820, 450, 980), "GitHub API\nPR data and comments", 26, True)
125
+ rounded_box(d, (570, 820, 930, 980), "#F6F8FA")
126
+ draw_centered_text(d, (570, 820, 930, 980), "Model provider APIs\nGroq Gemini or custom", 26, True)
127
+ rounded_box(d, (1050, 820, 1410, 980), "#F6F8FA")
128
+ draw_centered_text(d, (1050, 820, 1410, 980), "Chroma vector store\nOptional local retrieval", 26, True)
129
+ rounded_box(d, (1510, 820, 1730, 980), "#F6F8FA")
130
+ draw_centered_text(d, (1510, 820, 1730, 980), "LangSmith\nand Langfuse", 24, True)
131
+ arrow(d, (1120, 720), (365, 820))
132
+ arrow(d, (1380, 720), (760, 820))
133
+ arrow(d, (1490, 720), (1230, 820))
134
+ arrow(d, (1600, 720), (1620, 820))
135
+ img.save(ARCH_DIAGRAM, quality=95)
136
+
137
+
138
+ def create_flow_diagram():
139
+ img = Image.new("RGB", (1900, 990), "white")
140
+ d = ImageDraw.Draw(img)
141
+ d.text((70, 40), "LangGraph review workflow", font=font(42, True), fill="#1F2937")
142
+ d.text((72, 96), "Specialists run in parallel, then a human decides whether findings can be posted", font=font(25), fill="#52606D")
143
+
144
+ boxes = {
145
+ "ingestion": (90, 240, 350, 390),
146
+ "retrieval": (430, 240, 690, 390),
147
+ "correctness": (805, 175, 1095, 300),
148
+ "security": (805, 355, 1095, 480),
149
+ "tests": (805, 535, 1095, 660),
150
+ "aggregate": (1230, 320, 1510, 490),
151
+ "approval": (1600, 320, 1840, 490),
152
+ "executor": (1230, 700, 1510, 850),
153
+ }
154
+ rounded_box(d, boxes["ingestion"], "#DDEFF2", "#0F6B78")
155
+ draw_centered_text(d, boxes["ingestion"], "Ingestion\nPR diff and files", 27, True)
156
+ rounded_box(d, boxes["retrieval"], "#EAF2FF", "#3D6FB4")
157
+ draw_centered_text(d, boxes["retrieval"], "Retrieval\nRelevant repo context", 27, True)
158
+ for key, label in [("correctness", "Correctness reviewer"), ("security", "Security reviewer"), ("tests", "Test coverage reviewer")]:
159
+ rounded_box(d, boxes[key], "#FFF4D6", "#B7791F")
160
+ draw_centered_text(d, boxes[key], label, 25, True)
161
+ rounded_box(d, boxes["aggregate"], "#E8F4EA", "#2F855A")
162
+ draw_centered_text(d, boxes["aggregate"], "Aggregator\nGround deduplicate score", 26, True)
163
+ rounded_box(d, boxes["approval"], "#F1EAFE", "#7559A8")
164
+ draw_centered_text(d, boxes["approval"], "Human approval\nInterrupt and resume", 26, True)
165
+ rounded_box(d, boxes["executor"], "#FCE8EA", "#B23A48")
166
+ draw_centered_text(d, boxes["executor"], "Executor\nPost to GitHub", 27, True)
167
+
168
+ arrow(d, (350, 315), (430, 315))
169
+ for y in (237, 417, 597):
170
+ arrow(d, (690, 315), (805, y))
171
+ for y in (237, 417, 597):
172
+ arrow(d, (1095, y), (1230, 405))
173
+ arrow(d, (1510, 405), (1600, 405))
174
+ arrow(d, (1720, 490), (1450, 700))
175
+ d.text((1530, 610), "approved", font=font(23, True), fill="#2F855A")
176
+ d.text((1600, 535), "rejected ends without posting", font=font(22), fill="#B23A48")
177
+
178
+ rounded_box(d, (90, 760, 930, 900), "#F6F8FA", "#A7B3BC")
179
+ draw_centered_text(d, (90, 760, 930, 900), "State travels through every node\nChanged files Retrieved context Findings Verdict Review stages", 24)
180
+ img.save(FLOW_DIAGRAM, quality=95)
181
+
182
+
183
+ def set_font(run, name="Arial", size=None, bold=None, color=None, italic=None):
184
+ run.font.name = name
185
+ run._element.get_or_add_rPr().rFonts.set(qn("w:ascii"), name)
186
+ run._element.get_or_add_rPr().rFonts.set(qn("w:hAnsi"), name)
187
+ if size is not None:
188
+ run.font.size = Pt(size)
189
+ if bold is not None:
190
+ run.bold = bold
191
+ if italic is not None:
192
+ run.italic = italic
193
+ if color is not None:
194
+ run.font.color.rgb = RGBColor.from_string(color)
195
+
196
+
197
+ def shade_cell(cell, fill):
198
+ tc_pr = cell._tc.get_or_add_tcPr()
199
+ shd = tc_pr.find(qn("w:shd"))
200
+ if shd is None:
201
+ shd = OxmlElement("w:shd")
202
+ tc_pr.append(shd)
203
+ shd.set(qn("w:fill"), fill)
204
+
205
+
206
+ def set_cell_margins(cell, top=90, start=110, bottom=90, end=110):
207
+ tc = cell._tc
208
+ tc_pr = tc.get_or_add_tcPr()
209
+ tc_mar = tc_pr.first_child_found_in("w:tcMar")
210
+ if tc_mar is None:
211
+ tc_mar = OxmlElement("w:tcMar")
212
+ tc_pr.append(tc_mar)
213
+ for margin, value in (("top", top), ("start", start), ("bottom", bottom), ("end", end)):
214
+ node = tc_mar.find(qn(f"w:{margin}"))
215
+ if node is None:
216
+ node = OxmlElement(f"w:{margin}")
217
+ tc_mar.append(node)
218
+ node.set(qn("w:w"), str(value))
219
+ node.set(qn("w:type"), "dxa")
220
+
221
+
222
+ def set_repeat_table_header(row):
223
+ tr_pr = row._tr.get_or_add_trPr()
224
+ tbl_header = OxmlElement("w:tblHeader")
225
+ tbl_header.set(qn("w:val"), "true")
226
+ tr_pr.append(tbl_header)
227
+
228
+
229
+ def prevent_row_split(row):
230
+ tr_pr = row._tr.get_or_add_trPr()
231
+ cant_split = OxmlElement("w:cantSplit")
232
+ tr_pr.append(cant_split)
233
+
234
+
235
+ def add_alt_text(inline_shape, title, description):
236
+ doc_pr = inline_shape._inline.docPr
237
+ doc_pr.set("title", title)
238
+ doc_pr.set("descr", description)
239
+
240
+
241
+ def add_page_number(paragraph):
242
+ run = paragraph.add_run()
243
+ fld_char_1 = OxmlElement("w:fldChar")
244
+ fld_char_1.set(qn("w:fldCharType"), "begin")
245
+ instr_text = OxmlElement("w:instrText")
246
+ instr_text.set(qn("xml:space"), "preserve")
247
+ instr_text.text = " PAGE "
248
+ fld_char_2 = OxmlElement("w:fldChar")
249
+ fld_char_2.set(qn("w:fldCharType"), "end")
250
+ run._r.extend([fld_char_1, instr_text, fld_char_2])
251
+ set_font(run, size=9, color=MUTED)
252
+
253
+
254
+ def add_body(doc, text, before=0, after=6, keep_with_next=False):
255
+ p = doc.add_paragraph()
256
+ p.paragraph_format.space_before = Pt(before)
257
+ p.paragraph_format.space_after = Pt(after)
258
+ p.paragraph_format.line_spacing = 1.12
259
+ p.paragraph_format.keep_with_next = keep_with_next
260
+ r = p.add_run(text)
261
+ set_font(r, size=11, color=BLACK)
262
+ return p
263
+
264
+
265
+ def add_lead(doc, text):
266
+ p = doc.add_paragraph()
267
+ p.paragraph_format.space_after = Pt(10)
268
+ p.paragraph_format.line_spacing = 1.18
269
+ r = p.add_run(text)
270
+ set_font(r, size=12.5, color=BLACK)
271
+ return p
272
+
273
+
274
+ def add_bullets(doc, items, level=0):
275
+ for item in items:
276
+ p = doc.add_paragraph(style="List Bullet" if level == 0 else "List Bullet 2")
277
+ p.paragraph_format.left_indent = Inches(0.28 + 0.2 * level)
278
+ p.paragraph_format.first_line_indent = Inches(-0.18)
279
+ p.paragraph_format.space_after = Pt(3)
280
+ p.paragraph_format.line_spacing = 1.08
281
+ r = p.add_run(item)
282
+ set_font(r, size=10.7, color=BLACK)
283
+
284
+
285
+ def add_numbered(doc, items):
286
+ for item in items:
287
+ p = doc.add_paragraph(style="List Number")
288
+ p.paragraph_format.left_indent = Inches(0.3)
289
+ p.paragraph_format.first_line_indent = Inches(-0.2)
290
+ p.paragraph_format.space_after = Pt(4)
291
+ r = p.add_run(item)
292
+ set_font(r, size=10.7, color=BLACK)
293
+
294
+
295
+ def add_code_line(doc, text):
296
+ p = doc.add_paragraph()
297
+ p.paragraph_format.left_indent = Inches(0.28)
298
+ p.paragraph_format.space_before = Pt(2)
299
+ p.paragraph_format.space_after = Pt(6)
300
+ r = p.add_run(text)
301
+ set_font(r, name="Consolas", size=9.4, color=ACCENT_DARK)
302
+ return p
303
+
304
+
305
+ def add_table(doc, headers, rows, widths=None, font_size=9.2):
306
+ table = doc.add_table(rows=1, cols=len(headers))
307
+ table.alignment = WD_TABLE_ALIGNMENT.CENTER
308
+ table.autofit = False
309
+ table.style = "Table Grid"
310
+ hdr = table.rows[0]
311
+ set_repeat_table_header(hdr)
312
+ prevent_row_split(hdr)
313
+ for i, header in enumerate(headers):
314
+ cell = hdr.cells[i]
315
+ cell.text = ""
316
+ shade_cell(cell, ACCENT_DARK)
317
+ set_cell_margins(cell)
318
+ cell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
319
+ p = cell.paragraphs[0]
320
+ p.paragraph_format.space_after = Pt(0)
321
+ r = p.add_run(header)
322
+ set_font(r, size=font_size, bold=True, color=WHITE)
323
+ if widths:
324
+ cell.width = Inches(widths[i])
325
+ for ridx, row_data in enumerate(rows):
326
+ row = table.add_row()
327
+ prevent_row_split(row)
328
+ for i, value in enumerate(row_data):
329
+ cell = row.cells[i]
330
+ cell.text = ""
331
+ set_cell_margins(cell)
332
+ cell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.TOP
333
+ if ridx % 2 == 1:
334
+ shade_cell(cell, LIGHT)
335
+ p = cell.paragraphs[0]
336
+ p.paragraph_format.space_after = Pt(0)
337
+ p.paragraph_format.line_spacing = 1.03
338
+ r = p.add_run(str(value))
339
+ set_font(r, size=font_size, color=BLACK)
340
+ if widths:
341
+ cell.width = Inches(widths[i])
342
+ doc.add_paragraph().paragraph_format.space_after = Pt(1)
343
+ return table
344
+
345
+
346
+ def add_heading(doc, text, level=1):
347
+ p = doc.add_heading(text, level=level)
348
+ p.paragraph_format.keep_with_next = True
349
+ p.paragraph_format.page_break_before = level == 1
350
+ p.paragraph_format.space_before = Pt(8 if level == 1 else 7)
351
+ p.paragraph_format.space_after = Pt(5)
352
+ return p
353
+
354
+
355
+ def add_figure(doc, path, width, caption, title, alt):
356
+ p = doc.add_paragraph()
357
+ p.alignment = WD_ALIGN_PARAGRAPH.CENTER
358
+ p.paragraph_format.keep_with_next = True
359
+ shape = p.add_run().add_picture(str(path), width=Inches(width))
360
+ add_alt_text(shape, title, alt)
361
+ cap = doc.add_paragraph()
362
+ cap.alignment = WD_ALIGN_PARAGRAPH.CENTER
363
+ cap.paragraph_format.space_after = Pt(8)
364
+ r = cap.add_run(caption)
365
+ set_font(r, size=9, italic=True, color=MUTED)
366
+
367
+
368
+ def configure_document(doc):
369
+ section = doc.sections[0]
370
+ section.page_width = Inches(8.5)
371
+ section.page_height = Inches(11)
372
+ section.top_margin = Inches(0.72)
373
+ section.bottom_margin = Inches(0.68)
374
+ section.left_margin = Inches(0.78)
375
+ section.right_margin = Inches(0.78)
376
+
377
+ normal = doc.styles["Normal"]
378
+ normal.font.name = "Arial"
379
+ normal._element.rPr.rFonts.set(qn("w:ascii"), "Arial")
380
+ normal._element.rPr.rFonts.set(qn("w:hAnsi"), "Arial")
381
+ normal.font.size = Pt(11)
382
+ normal.font.color.rgb = RGBColor.from_string(BLACK)
383
+
384
+ title = doc.styles["Title"]
385
+ title.font.name = "Arial"
386
+ title._element.rPr.rFonts.set(qn("w:ascii"), "Arial")
387
+ title._element.rPr.rFonts.set(qn("w:hAnsi"), "Arial")
388
+ title.font.size = Pt(29)
389
+ title.font.bold = True
390
+ title.font.color.rgb = RGBColor.from_string(BLACK)
391
+
392
+ for style_name, size, color in (("Heading 1", 19, BLACK), ("Heading 2", 14, ACCENT_DARK), ("Heading 3", 11.5, BLACK)):
393
+ style = doc.styles[style_name]
394
+ style.font.name = "Arial"
395
+ style._element.rPr.rFonts.set(qn("w:ascii"), "Arial")
396
+ style._element.rPr.rFonts.set(qn("w:hAnsi"), "Arial")
397
+ style.font.size = Pt(size)
398
+ style.font.bold = True
399
+ style.font.color.rgb = RGBColor.from_string(color)
400
+
401
+ header = section.header
402
+ hp = header.paragraphs[0]
403
+ hp.alignment = WD_ALIGN_PARAGRAPH.RIGHT
404
+ hr = hp.add_run("OpenCodeReview AI Engineering Guide")
405
+ set_font(hr, size=8.5, color=MUTED)
406
+
407
+ footer = section.footer
408
+ fp = footer.paragraphs[0]
409
+ fp.alignment = WD_ALIGN_PARAGRAPH.CENTER
410
+ fr = fp.add_run("OpenCodeReview | Repository snapshot d939059 | Page ")
411
+ set_font(fr, size=8.5, color=MUTED)
412
+ add_page_number(fp)
413
+
414
+
415
+ def build_document():
416
+ WORK.mkdir(parents=True, exist_ok=True)
417
+ ASSETS.mkdir(parents=True, exist_ok=True)
418
+ create_architecture_diagram()
419
+ create_flow_diagram()
420
+
421
+ doc = Document()
422
+ configure_document(doc)
423
+
424
+ # Cover
425
+ p = doc.add_paragraph(style="Title")
426
+ p.alignment = WD_ALIGN_PARAGRAPH.LEFT
427
+ p.paragraph_format.space_before = Pt(86)
428
+ p.paragraph_format.space_after = Pt(14)
429
+ p.add_run("OpenCodeReview AI Engineering Architecture Guide")
430
+ sub = doc.add_paragraph()
431
+ sub.paragraph_format.space_after = Pt(22)
432
+ r = sub.add_run("A simple technical guide to the complete project and how to explain it in an AI engineer interview")
433
+ set_font(r, size=16, color=ACCENT_DARK)
434
+ add_body(doc, "Repository snapshot d939059", after=2)
435
+ add_body(doc, "Prepared 30 October 2026", after=2)
436
+ add_body(doc, "Scope: frontend, API, LangGraph workflow, RAG, prompting, evaluation, persistence, deployment, security, limitations, and interview answers", after=20)
437
+ p = doc.add_paragraph()
438
+ p.paragraph_format.space_before = Pt(130)
439
+ p.paragraph_format.space_after = Pt(0)
440
+ r = p.add_run("Accuracy note")
441
+ set_font(r, size=10.5, bold=True, color=BLACK)
442
+ add_body(doc, "This guide describes the code that exists in the repository. It separates implemented behavior from optional features, deployment assumptions, and recommended production improvements.", after=0)
443
+ add_heading(doc, "How to use this guide", 1)
444
+ add_lead(doc, "Read the first four sections for a clear project story. Use the middle sections to explain technical choices. Use the final sections to prepare for interview questions.")
445
+ add_table(doc, ["If you have", "Read"], [
446
+ ("Two minutes", "Project overview and the 30 second interview answer"),
447
+ ("Ten minutes", "Architecture, end to end flow, RAG, prompting, and evaluation"),
448
+ ("A technical interview", "LangGraph state, grounding, persistence, security, limitations, and tradeoffs"),
449
+ ("A system design round", "Deployment boundaries, failure handling, scaling plan, and production roadmap"),
450
+ ], widths=[1.5, 5.2])
451
+ add_heading(doc, "Guide map", 2)
452
+ add_bullets(doc, [
453
+ "Sections 1 through 4 explain the product, architecture, and complete request flow.",
454
+ "Sections 5 through 15 explain the AI pipeline, RAG, prompts, reviewers, grounding, approval, and execution.",
455
+ "Sections 16 through 22 explain storage, authentication, observability, evaluation, deployment, and failure handling.",
456
+ "Sections 23 through 27 explain limitations, design tradeoffs, source files, interview answers, and terminology.",
457
+ "Appendices list API routes, job states, configuration, and verification evidence.",
458
+ ])
459
+
460
+ add_heading(doc, "1 Project overview", 1)
461
+ add_lead(doc, "OpenCodeReview is an AI assisted GitHub pull request reviewer. It collects a pull request, asks three specialist reviewers to inspect it, combines and grounds their findings, pauses for human approval, and posts approved comments back to GitHub.")
462
+ add_heading(doc, "The problem it solves", 2)
463
+ add_body(doc, "A large pull request can contain correctness defects, security risks, and missing tests. A single general prompt can miss important details or mix unrelated concerns. OpenCodeReview divides the review into specialist tasks and keeps a human in control of publication.")
464
+ add_heading(doc, "The main engineering idea", 2)
465
+ add_body(doc, "The project is a modular monolith with a static web frontend. The backend is one Python process containing an API, an in process worker pool, a LangGraph workflow, optional retrieval, evaluation, and GitHub execution. The modules are separated in code, but they are not independently deployed microservices.")
466
+ add_table(doc, ["Question", "Short answer"], [
467
+ ("What kind of AI system is it", "A multi stage LLM workflow for pull request review with optional RAG and human approval"),
468
+ ("What is the orchestration framework", "LangGraph"),
469
+ ("What are the specialist roles", "Correctness, security, and test coverage"),
470
+ ("What is the frontend", "React and Vite deployed on Vercel"),
471
+ ("What is the backend", "FastAPI and Gradio in one Docker deployment on Hugging Face Spaces"),
472
+ ("What is the vector database", "ChromaDB with local MiniLM embeddings when explicitly enabled"),
473
+ ("What controls publishing", "A LangGraph interrupt that requires a human decision"),
474
+ ], widths=[2.2, 4.5])
475
+
476
+ add_heading(doc, "2 System architecture", 1)
477
+ add_lead(doc, "The system has two deployment surfaces and several external dependencies. Vercel serves the user interface. A Docker Space runs the Python backend. GitHub and model providers remain external services.")
478
+ add_figure(doc, ARCH_DIAGRAM, 6.8, "Figure 1 Deployment and runtime architecture", "OpenCodeReview architecture", "Architecture diagram showing a browser using a Vercel React frontend, a Hugging Face Docker backend containing FastAPI and LangGraph workers, and integrations with GitHub, model providers, ChromaDB, Supabase or SQLite, LangSmith, and Langfuse.")
479
+ add_heading(doc, "Deployment boundaries", 2)
480
+ add_table(doc, ["Boundary", "Responsibility", "Important detail"], [
481
+ ("Vercel", "Serves the React application and the provider test function", "Most API routes are rewritten to the Hugging Face backend"),
482
+ ("Hugging Face Docker Space", "Runs Uvicorn, FastAPI, worker threads, LangGraph, RAGAS, and the mounted Gradio UI", "These components share one process and failure domain"),
483
+ ("GitHub", "Supplies pull request data and accepts review comments", "Posting requires a valid token and an unchanged pull request head"),
484
+ ("Model providers", "Generate structured reviewer findings", "Built in and custom provider configurations are supported"),
485
+ ("Storage", "Stores job records, graph checkpoints, and optional embeddings", "The project uses separate storage mechanisms for separate concerns"),
486
+ ], widths=[1.35, 2.6, 2.75])
487
+ add_heading(doc, "Why this is a modular monolith", 2)
488
+ add_body(doc, "FastAPI, the worker pool, LangGraph, and RAGAS run inside the same Python service. The code has clear modules and nodes, but there is no external queue and no independently scalable reviewer service. Calling it a microservice architecture would overstate the current implementation.")
489
+
490
+ add_heading(doc, "3 End to end review flow", 1)
491
+ add_lead(doc, "A review moves from a browser request to a persisted job, then through the graph, approval, and GitHub posting. Each stage adds data or enforces a safety condition.")
492
+ add_numbered(doc, [
493
+ "The user signs in or supplies the configured API credential, enters a repository and pull request number, selects a review mode and model provider, and submits the job.",
494
+ "FastAPI validates the request, checks rate limits, resolves the current head and base commits when possible, creates a pipeline fingerprint, and reuses an equivalent active job when appropriate.",
495
+ "The API persists a job record and submits work to a process local ThreadPoolExecutor. The default maximum worker count is two.",
496
+ "The ingestion node downloads pull request metadata, the diff, changed files, and current file content from GitHub.",
497
+ "The retrieval node optionally builds or loads a Chroma collection for unchanged repository context and returns the fifteen most similar chunks.",
498
+ "Correctness, security, and test coverage reviewers run in parallel. Each reviewer receives the diff, changed file context, retrieved context, and a specialist prompt.",
499
+ "The aggregator grounds findings against changed lines, removes duplicates, calculates a risk oriented score, and creates the verdict.",
500
+ "LangGraph interrupts at the approval node. The frontend displays the result and waits for the user to approve or reject it.",
501
+ "After approval, the API verifies that the pull request commits have not changed. The executor posts valid inline comments and a summary to GitHub.",
502
+ "RAGAS can run in the background and attach evaluation metrics. The frontend polls the job endpoint every three seconds until it reaches a final state.",
503
+ ])
504
+ add_heading(doc, "Why the fingerprint matters", 2)
505
+ add_body(doc, "The job fingerprint combines the owner, request, pull request commits, selected configuration, prompts, and relevant node source. This prevents accidental duplicate work and makes a changed prompt or pipeline version produce a new review.")
506
+
507
+ add_heading(doc, "4 Frontend architecture", 1)
508
+ add_lead(doc, "The frontend is a lightweight React application. It creates jobs, polls status, renders review results, manages provider settings in the browser, and sends approval or rejection decisions.")
509
+ add_table(doc, ["File", "Responsibility"], [
510
+ ("frontend/src/main.jsx", "Page composition, form state, status polling, results, approval controls, saved providers, and user feedback"),
511
+ ("frontend/src/review-client.js", "HTTP client functions for authentication, reviews, decisions, cancellation, feedback, and provider tests"),
512
+ ("frontend/src/styles.css", "Responsive visual styling"),
513
+ ("frontend/api/provider-test.js", "Vercel serverless function that tests a user supplied model endpoint without starting a review"),
514
+ ("frontend/vercel.json", "Build output, API rewrites, and single page application routing"),
515
+ ], widths=[2.3, 4.4])
516
+ add_heading(doc, "Polling model", 2)
517
+ add_body(doc, "The browser asks for the latest job state every three seconds. Polling is simple and works well for a portfolio scale deployment. At higher volume, Server Sent Events or WebSockets would reduce repeated requests and deliver progress faster.")
518
+ add_heading(doc, "Provider settings", 2)
519
+ add_body(doc, "The UI keeps saved custom provider configurations in browser local storage and sends the selected configuration with the review request. This is convenient, but long lived API keys in local storage increase exposure if the site ever has a cross site scripting defect. A production design should use a server side encrypted secret store and short references from the browser.")
520
+
521
+ add_heading(doc, "5 FastAPI and job lifecycle", 1)
522
+ add_lead(doc, "FastAPI is the control plane. It authenticates the caller, creates and persists jobs, starts worker tasks, exposes progress, and accepts decisions and feedback.")
523
+ add_heading(doc, "Job creation", 2)
524
+ add_body(doc, "The create endpoint validates repository input, pull request number, review mode, provider choice, and authentication. It applies an optional per minute rate limit, derives a stable pipeline version, and records enough request data to reproduce the intended review configuration.")
525
+ add_heading(doc, "Worker execution", 2)
526
+ add_body(doc, "The worker pool is a Python ThreadPoolExecutor inside the API process. This avoids extra infrastructure and is appropriate for a small deployment. It is not a durable queue: queued work can be lost during a process restart, and another replica cannot see the process local queue.")
527
+ add_heading(doc, "Job states", 2)
528
+ add_table(doc, ["State", "Meaning"], [
529
+ ("queued", "The API accepted the request and scheduled the worker"),
530
+ ("processing", "The graph is ingesting, retrieving, reviewing, or aggregating"),
531
+ ("awaiting_approval", "The graph interrupted and is waiting for a human decision"),
532
+ ("processing_decision", "The graph resumed after approval and is preparing to post"),
533
+ ("posted", "The executor posted the review successfully"),
534
+ ("partially_posted", "Some comments posted and some failed or fell back"),
535
+ ("post_failed", "The review completed but GitHub publication failed"),
536
+ ("rejected", "The user rejected the review and nothing was posted"),
537
+ ("cancelled", "The user requested cancellation"),
538
+ ("incomplete or failed", "A reviewer or pipeline failure prevented a reliable result"),
539
+ ], widths=[1.65, 5.05])
540
+
541
+ add_heading(doc, "6 LangGraph state and orchestration", 1)
542
+ add_lead(doc, "LangGraph models the review as a state machine. Nodes read the shared state and return updates. The graph controls sequencing, parallel branches, interruption, and resume behavior.")
543
+ add_figure(doc, FLOW_DIAGRAM, 6.8, "Figure 2 LangGraph review workflow", "LangGraph review workflow", "Workflow diagram showing ingestion, retrieval, three parallel reviewers, aggregation, a human approval interrupt, and GitHub execution. Shared state contains changed files, retrieved context, findings, verdict, and stage metadata.")
544
+ add_heading(doc, "Graph topology", 2)
545
+ add_code_line(doc, "START -> ingestion -> retrieval -> {correctness | security | test coverage} -> aggregator -> human approval -> executor -> END")
546
+ add_heading(doc, "Shared state", 2)
547
+ add_body(doc, "OpenCodeReviewState is a Pydantic model that carries repository identifiers, commit SHAs, the diff, changed files, retrieved context, findings, reviewer stage results, the verdict, approval data, and execution receipts. List reducers append context chunks, findings, and stage metadata from parallel branches instead of overwriting them.")
548
+ add_table(doc, ["State object", "Purpose"], [
549
+ ("ChangedFile", "Path, status, patch, content, and line information for a changed file"),
550
+ ("ContextChunk", "Retrieved repository or pull request context with source metadata and similarity"),
551
+ ("Finding", "Structured issue with file, line, severity, category, explanation, confidence, and grounding flags"),
552
+ ("Verdict", "Aggregated recommendation, risk score, summary, and completeness information"),
553
+ ("Review stage metadata", "Timing, provider, status, and failure classification for each specialist"),
554
+ ], widths=[1.8, 4.9])
555
+ add_heading(doc, "Why use a graph", 2)
556
+ add_body(doc, "A graph makes parallel review, human interruption, and explicit state transitions visible. A simple chain could call the models, but it would make the approval pause and partial failure handling harder to reason about.")
557
+
558
+ add_heading(doc, "7 Ingestion and GitHub context", 1)
559
+ add_lead(doc, "Ingestion turns a pull request URL and number into the concrete evidence the reviewers need.")
560
+ add_bullets(doc, [
561
+ "Pull request metadata including head and base commits",
562
+ "The complete pull request diff where GitHub provides it",
563
+ "Changed file metadata and patches with pagination",
564
+ "Current file content for changed paths",
565
+ "Fork aware repository identifiers",
566
+ "Optional baseline comparison data for incremental review",
567
+ ])
568
+ add_heading(doc, "Incremental review", 2)
569
+ add_body(doc, "The system can compare a newer head against a previous baseline when the baseline is an ancestor and the comparison is not truncated. An incremental result is deliberately blocked from posting because line positions and coverage may not represent the full pull request.")
570
+ add_heading(doc, "Rate limits and failures", 2)
571
+ add_body(doc, "GitHub API calls use timeouts and surface authentication or rate limit problems. A missing token sharply reduces the public API allowance. The system should treat incomplete GitHub data as an incomplete review rather than silently presenting a confident verdict.")
572
+
573
+ add_heading(doc, "8 Retrieval augmented generation", 1)
574
+ add_lead(doc, "RAG supplies repository context that is not present in the pull request diff. It is optional and runs only when local embeddings are explicitly enabled.")
575
+ add_heading(doc, "What is indexed", 2)
576
+ add_table(doc, ["Indexed source", "What enters Chroma", "Why"], [
577
+ ("Unchanged repository files", "Eligible source, configuration, SQL, shell, markup, style, and documentation files from the base commit", "Gives reviewers definitions, conventions, and neighboring behavior outside the diff"),
578
+ ("Important repository documents", "README, CONTRIBUTING, code of conduct, style guide, and selected GitHub contribution docs", "Adds project rules and intended usage"),
579
+ ("Recent merged pull requests", "Title and body of up to twenty recently updated merged pull requests", "Adds historical design intent and related change descriptions"),
580
+ ], widths=[1.45, 3.15, 2.1])
581
+ add_heading(doc, "What is not indexed", 2)
582
+ add_bullets(doc, [
583
+ "Files changed by the current pull request because their diff and current content are already supplied directly to the reviewers",
584
+ "Tests and spec files selected by path naming rules",
585
+ "Hidden paths, dependency folders, virtual environments, vendored code, build output, and distribution output",
586
+ "Binary files and unsupported extensions",
587
+ "Full review comment discussions from old pull requests; the current implementation indexes only merged pull request title and body text",
588
+ ])
589
+ add_heading(doc, "Why the entire repository is not embedded", 2)
590
+ add_body(doc, "The goal is useful context, not a byte for byte archive. Embedding changed files would duplicate evidence already included in the prompt. Embedding dependencies, generated artifacts, and binary files would add cost and noise. Filtering also lowers indexing time and reduces irrelevant retrieval.")
591
+ add_body(doc, "A simple interview answer is: the system indexes eligible unchanged code and project documentation, then retrieves only the small set most relevant to the current diff. It does not send the entire repository to the model.")
592
+
593
+ add_heading(doc, "9 Chunking and vector search", 1)
594
+ add_lead(doc, "Chunking is structure aware for Python and paragraph based for other supported files. The current design favors simple, explainable rules over a language parser for every programming language.")
595
+ add_table(doc, ["Content", "Chunking method", "Technical detail"], [
596
+ ("Python", "Split at top level class, function, and async function definitions", "Keeps a logical unit together; preamble code becomes its own chunk"),
597
+ ("Other source and documents", "Split at blank lines and merge consecutive paragraphs", "Targets about 1,200 characters; a single long paragraph is not force split"),
598
+ ("Merged pull request text", "Use the same paragraph chunker", "Title and body are combined before chunking"),
599
+ ], widths=[1.35, 2.75, 2.6])
600
+ add_heading(doc, "Embedding model and store", 2)
601
+ add_body(doc, "ChromaDB uses a persistent collection for each repository. The preferred embedding function is ONNX MiniLM L6 V2. The collection uses cosine distance and records the base commit SHA as a freshness key. A matching SHA reuses the collection; a changed base SHA rebuilds it.")
602
+ add_heading(doc, "Retrieval query", 2)
603
+ add_body(doc, "The current pull request diff becomes the semantic query. It is truncated to 8,000 characters to stay within embedding limits. Chroma returns the top fifteen chunks. Each ContextChunk keeps the source type, file path, chunk type, text, and similarity information for later prompting and evaluation.")
604
+ add_heading(doc, "Chunking tradeoffs", 2)
605
+ add_body(doc, "The Python rule preserves semantic units better than fixed token windows. The generic rule is cheap and language independent, but it can combine unrelated paragraphs or keep an unusually long block intact. A future version could use tree sitter parsers, token aware limits, and small overlaps for more languages.")
606
+
607
+ add_heading(doc, "10 Prompt engineering", 1)
608
+ add_lead(doc, "The project uses specialist, zero shot, retrieval contextual prompts with structured outputs. Each reviewer gets a role specific system prompt and a user message containing the actual pull request evidence.")
609
+ add_table(doc, ["Prompting choice", "How it is used"], [
610
+ ("Zero shot", "The reviewer is given instructions and evidence without worked examples"),
611
+ ("Role specialization", "Separate prompts define correctness, security, and test coverage responsibilities"),
612
+ ("System and user separation", "Stable reviewer rules stay in the system message; repository and pull request data stay in the user message"),
613
+ ("RAG contextualization", "Retrieved chunks are included as supporting context when retrieval is enabled"),
614
+ ("Structured output", "Pydantic schemas require machine readable findings instead of free form prose"),
615
+ ("Repair prompting", "One retry asks the model to fix invalid output formatting"),
616
+ ("Token cut retry", "If output is truncated, a retry requests a shorter list focused on the top five findings"),
617
+ ], widths=[1.75, 4.95])
618
+ add_heading(doc, "Prompt inputs", 2)
619
+ add_bullets(doc, [
620
+ "Pull request metadata and review mode",
621
+ "The diff and changed file content",
622
+ "Retrieved repository context when available",
623
+ "Rules for severity, file and line references, confidence, and evidence",
624
+ "A strict output schema for findings",
625
+ ])
626
+ add_heading(doc, "Fast and thorough modes", 2)
627
+ add_body(doc, "Fast mode narrows changed file content to windows of about twelve lines around diff hunks. Thorough mode supplies more surrounding content. This is a latency and token tradeoff, not a different model architecture.")
628
+ add_heading(doc, "Why structured output matters", 2)
629
+ add_body(doc, "The aggregator and executor need fields such as path, line, severity, category, confidence, and comment text. A prose response is difficult to validate and post safely. Structured output makes the model response testable and lets later nodes reject malformed or ungrounded findings.")
630
+
631
+ add_heading(doc, "11 Specialist reviewer nodes", 1)
632
+ add_lead(doc, "The three reviewers are specialized LLM calls inside graph nodes. They are not autonomous services with separate memory or independent goals.")
633
+ add_table(doc, ["Reviewer", "Primary questions", "Typical output"], [
634
+ ("Correctness", "Can this change produce wrong behavior, exceptions, data loss, race conditions, or broken edge cases", "Defect findings tied to changed files and lines"),
635
+ ("Security", "Can untrusted input, authentication, authorization, secrets, injection, or unsafe execution be exploited", "Security findings with severity and evidence"),
636
+ ("Test coverage", "Which changed behaviors lack useful tests or assertions", "Test suggestions that do not directly increase the defect risk score"),
637
+ ], widths=[1.45, 3.45, 1.8])
638
+ add_heading(doc, "Parallel execution", 2)
639
+ add_body(doc, "LangGraph fans out from retrieval to all three reviewers. Parallel execution reduces total latency because the calls are independent. List reducers combine their outputs when the branches meet at the aggregator.")
640
+ add_heading(doc, "Runtime controls", 2)
641
+ add_body(doc, "Each reviewer runs with a timeout. The runtime records completion, provider details, token usage when available, and classified failures such as authentication, rate limiting, timeout, or generic model error. A failed specialist makes the review incomplete instead of pretending that all review dimensions were covered.")
642
+
643
+ add_heading(doc, "12 Grounding and hallucination controls", 1)
644
+ add_lead(doc, "The model can propose a plausible issue at the wrong location. OpenCodeReview therefore validates findings against the actual diff before scoring or posting them.")
645
+ add_heading(doc, "Line grounding", 2)
646
+ add_body(doc, "finding_quality.py checks whether a finding points to a real changed file and overlaps an added or changed line. It marks findings as source grounded, outside the diff, or needing verification. The executor posts only source grounded findings.")
647
+ add_heading(doc, "Claim calibration", 2)
648
+ add_body(doc, "Test suggestions are kept at low or informational severity and do not increase the defect score. Compiler or type checker claims require a reproducible diagnostic before they affect risk. These rules reduce confident comments that are not supported by source evidence.")
649
+ add_heading(doc, "Defense in depth", 2)
650
+ add_numbered(doc, [
651
+ "Prompts ask for concrete file and line evidence.",
652
+ "Pydantic validates the response shape.",
653
+ "The finding quality layer validates source location.",
654
+ "The aggregator excludes ungrounded items from scoring.",
655
+ "The human reviews the result before publication.",
656
+ "The executor checks the latest pull request head and GitHub line validity.",
657
+ ])
658
+
659
+ add_heading(doc, "13 Aggregation and risk scoring", 1)
660
+ add_lead(doc, "The aggregator converts three specialist outputs into one review result. It calibrates, deduplicates, scores, and summarizes findings while preserving failure information.")
661
+ add_heading(doc, "Deduplication", 2)
662
+ add_body(doc, "Findings are considered duplicates when they refer to the same file, are within five lines, have the same kind or category, and have the same normalized comment. A default confidence threshold of 0.25 removes very weak items.")
663
+ add_heading(doc, "Risk score", 2)
664
+ add_code_line(doc, "score = clamp(10 - 4 x critical - 2 x high - 0.5 x medium, 0, 10)")
665
+ add_body(doc, "The score is a review heuristic, not a probability that the code is correct. Only grounded defect findings contribute. Test suggestions and unsupported claims do not. If a specialist fails, the recommendation becomes incomplete and the system avoids presenting a normal overall score.")
666
+ add_heading(doc, "Optional critic", 2)
667
+ add_body(doc, "The default verdict uses deterministic rules. An optional LLM critic can be enabled with AGGREGATOR_USE_LLM_CRITIC. Keeping the rule based path as the default reduces cost and makes the final score easier to explain.")
668
+
669
+ add_heading(doc, "14 Human approval and checkpointing", 1)
670
+ add_lead(doc, "The human approval node calls LangGraph interrupt. This stops the graph after analysis and returns a review payload to the application. A later decision resumes the same graph with Command resume.")
671
+ add_heading(doc, "Approval safeguards", 2)
672
+ add_bullets(doc, [
673
+ "Rejection ends the workflow without posting comments",
674
+ "Approval triggers a fresh head and base commit check",
675
+ "A changed pull request is treated as stale and must be reviewed again",
676
+ "Incremental baseline reviews cannot be posted",
677
+ "Only grounded findings are eligible for execution",
678
+ ])
679
+ add_heading(doc, "Checkpoint limitation", 2)
680
+ add_body(doc, "LangGraph checkpoints use a separate SQLite database. A durable database path is required for approval to survive a backend restart. Supabase job persistence alone does not make graph checkpoints durable because the two stores serve different purposes.")
681
+
682
+ add_heading(doc, "15 GitHub executor", 1)
683
+ add_lead(doc, "The executor is the side effect boundary. It turns approved findings into GitHub review comments and records a posting receipt.")
684
+ add_heading(doc, "Posting sequence", 2)
685
+ add_numbered(doc, [
686
+ "Fetch the latest pull request head commit.",
687
+ "Stop if the reviewed head no longer matches.",
688
+ "Build right side inline comments for grounded locations.",
689
+ "Post multi line comments when the finding spans a valid range.",
690
+ "If GitHub rejects a line with HTTP 422, fall back to an issue level comment.",
691
+ "Post the verdict summary and persist a receipt with successful and failed comment counts.",
692
+ ])
693
+ add_heading(doc, "Possible receipts", 2)
694
+ add_body(doc, "The receipt can record posted, partially posted, post failed, dry run, or skipped outcomes. Keeping analysis separate from execution makes it possible to inspect a good review even if GitHub publication fails.")
695
+
696
+ add_heading(doc, "16 Model provider layer", 1)
697
+ add_lead(doc, "The LLM factory hides provider specific client setup from the reviewer nodes. Reviewers ask for a chat model and structured output without owning provider credentials or request formatting.")
698
+ add_table(doc, ["Provider path", "Current behavior"], [
699
+ ("Groq", "Preferred by the automatic selection path when GROQ_API_KEY is available; default model is openai/gpt-oss-20b"),
700
+ ("Google Gemini", "Used when configured; current default model is gemini-3.1-flash-lite"),
701
+ ("OpenAI compatible", "Custom base URL, model name, and API key can be registered for the job"),
702
+ ("Anthropic compatible", "Custom endpoint configuration supported by the endpoint layer"),
703
+ ("Google compatible", "Custom Google endpoint configuration supported"),
704
+ ], widths=[1.7, 5.0])
705
+ add_heading(doc, "Bring your own provider", 2)
706
+ add_body(doc, "The frontend can test and save endpoint configurations. The backend registers a temporary endpoint for a review and removes it after review and background evaluation work. A production system should avoid sending raw long lived keys in ordinary job payloads and should use encrypted server side secret references.")
707
+ add_heading(doc, "Provider naming detail", 2)
708
+ add_body(doc, "The user interface includes a label written as Grok while the implementation uses Groq. This should be corrected because Groq is the inference provider used by the code and Grok refers to a different model family.")
709
+
710
+ add_heading(doc, "17 Persistence and data ownership", 1)
711
+ add_lead(doc, "The project uses several stores. Understanding their boundaries is important because persistence is only as strong as the least durable state needed to resume a workflow.")
712
+ add_table(doc, ["Data", "Current store", "Durability note"], [
713
+ ("Job records", "Supabase Postgres when SUPABASE_DB_URL is set, otherwise SQLite", "Supabase is suitable for durable job status; local SQLite depends on the mounted filesystem"),
714
+ ("LangGraph checkpoints", "SQLite through SqliteSaver", "Must use a persistent path to survive restarts"),
715
+ ("Live queue and worker futures", "Process memory", "Lost when the process stops"),
716
+ ("OAuth sessions", "Process memory", "Lost during restart and not shared across replicas"),
717
+ ("Temporary provider registrations", "Process memory", "Removed after the job"),
718
+ ("Vector collections", "Chroma persistent directory", "Durable only when the configured directory is on persistent storage"),
719
+ ("Saved browser providers", "Browser local storage", "Specific to one browser profile and exposed to frontend script context"),
720
+ ], widths=[1.55, 2.1, 3.05])
721
+ add_heading(doc, "Supabase security", 2)
722
+ add_body(doc, "The migration enables row level security, revokes anonymous and authenticated access, and grants the service role access to review_jobs. The backend should hold the service credential. Browser code should never receive it.")
723
+ add_heading(doc, "Production improvement", 2)
724
+ add_body(doc, "Move the work queue to a durable service, store graph checkpoints in durable shared storage, and move OAuth sessions to a signed server side store. This would allow safe restarts and multiple backend replicas.")
725
+
726
+ add_heading(doc, "18 Authentication and security", 1)
727
+ add_lead(doc, "The web API supports GitHub OAuth and an optional API key. Job ownership checks prevent one signed in user from reading or controlling another user's job.")
728
+ add_heading(doc, "Authentication paths", 2)
729
+ add_table(doc, ["Path", "Use"], [
730
+ ("GitHub OAuth authorization code", "Browser login for the hosted application"),
731
+ ("OCR_API_KEY", "Optional API credential for controlled clients"),
732
+ ("GitHub device flow and keyring", "Command line authentication path"),
733
+ ("GITHUB_TOKEN", "Service credential used by core GitHub ingestion and execution when configured"),
734
+ ], widths=[2.2, 4.5])
735
+ add_heading(doc, "Important token boundary", 2)
736
+ add_body(doc, "The web API can identify a signed in user through an OAuth session, but core graph ingestion and execution resolve GitHub credentials through the shared GitHub client and environment or keyring. In the hosted architecture this behaves more like a service credential than full per user token propagation. Explain this honestly in an interview and propose explicit per job credential injection as the improvement.")
737
+ add_heading(doc, "Security controls", 2)
738
+ add_bullets(doc, [
739
+ "Configured CORS origins rather than a universal browser origin",
740
+ "Optional request authentication and per minute rate limiting",
741
+ "Owner checks on job reads, decisions, cancellation, and feedback",
742
+ "No posting before human approval",
743
+ "Stale commit checks before side effects",
744
+ "Structured output and source grounding before GitHub comments",
745
+ "Environment variables and OS keyring for long lived server or command line secrets",
746
+ ])
747
+
748
+ add_heading(doc, "19 Observability", 1)
749
+ add_lead(doc, "Observability covers model traces, token usage, latency, and stage failures. It helps separate a model quality problem from a network, provider, or orchestration problem.")
750
+ add_table(doc, ["Capability", "Implementation"], [
751
+ ("Tracing", "LangSmith is enabled when a LangSmith or legacy LangChain key is configured"),
752
+ ("LLM telemetry", "Langfuse callbacks can record model calls and scores"),
753
+ ("Cost and tokens", "TokenCostCallback records usage, estimated cost, and time to first token where available"),
754
+ ("Stage status", "Each reviewer records success, timing, provider, and failure type"),
755
+ ("Health", "The API health endpoint reports configuration and important runtime capabilities"),
756
+ ("External smoke checks", "A scheduled GitHub Actions workflow can alert through Slack or Discord webhooks"),
757
+ ], widths=[1.55, 5.15])
758
+ add_heading(doc, "What to monitor in production", 2)
759
+ add_bullets(doc, [
760
+ "Job queue wait time and end to end review latency",
761
+ "Reviewer timeout, authentication, rate limit, and invalid output rates",
762
+ "Grounded findings per review and human rejection rate",
763
+ "GitHub 422 fallback rate and stale pull request rate",
764
+ "Token usage and cost by provider, model, reviewer, and mode",
765
+ "Checkpoint resume success after deploys or restarts",
766
+ ])
767
+
768
+ add_heading(doc, "20 Evaluation", 1)
769
+ add_lead(doc, "The repository contains both online RAG evaluation and offline review evaluation. These tools measure different parts of the system and should not be combined into a single quality claim.")
770
+ add_heading(doc, "RAGAS evaluation", 2)
771
+ add_table(doc, ["Metric", "Meaning", "Condition"], [
772
+ ("Context precision", "How much retrieved context is relevant to the answer", "Runs when evaluation dependencies and provider access are available"),
773
+ ("Faithfulness", "Whether the answer is supported by supplied context", "Runs against generated findings and available context"),
774
+ ("Context recall", "Whether retrieved context covers a supplied reference answer", "Requires ground truth"),
775
+ ("Answer relevancy and diversity", "Additional hosted quality signals", "May be skipped in constrained hosted mode"),
776
+ ], widths=[1.4, 3.0, 2.3])
777
+ add_heading(doc, "Offline review evaluation", 2)
778
+ add_body(doc, "evaluate.py compares predicted findings with human review comments. A match uses the same file path and a line within about three lines, with optional keyword checks. The script reports precision, recall, and F1. Additional fixtures support located diff checks, regression tests, and CodeReviewBench style evaluation.")
779
+ add_heading(doc, "Current evidence", 2)
780
+ add_body(doc, "The committed evaluation snapshots do not demonstrate strong model quality. The current eval_results.json snapshot contains one pull request with zero predictions and zero precision, recall, and F1. offline_baseline.json records 136 gold items and zero predictions. The correct claim is that the project has evaluation infrastructure, not that it has proven high accuracy.")
781
+ add_heading(doc, "How to improve the evaluation", 2)
782
+ add_numbered(doc, [
783
+ "Create a versioned gold dataset with clearly located defects and reviewer rationale.",
784
+ "Evaluate each specialist separately before evaluating the aggregate verdict.",
785
+ "Measure grounded precision, recall, severity calibration, duplicate rate, latency, and cost.",
786
+ "Run the same dataset across prompt, model, and retrieval changes.",
787
+ "Require a regression threshold before deployment and report confidence intervals when the dataset is large enough.",
788
+ ])
789
+
790
+ add_heading(doc, "21 Deployment and continuous delivery", 1)
791
+ add_lead(doc, "The frontend and backend deploy separately. The frontend is static. The backend uses a Docker image because the Python stack includes FastAPI, Gradio, LangGraph, evaluation libraries, and optional local retrieval dependencies.")
792
+ add_table(doc, ["Artifact", "Deployment"], [
793
+ ("frontend", "Vercel builds the Vite application and serves the static output"),
794
+ ("frontend provider test", "Vercel serverless function under api/provider-test"),
795
+ ("backend", "Dockerfile.api starts Uvicorn with combined_server:app on Hugging Face Spaces"),
796
+ ("combined application", "combined_server.py exposes FastAPI routes and mounts the Gradio demo at the root"),
797
+ ("CI deployment", "A GitHub Actions workflow deploys the Hugging Face Space from the main branch"),
798
+ ("monitoring workflow", "A scheduled smoke workflow runs every six hours and can send alerts"),
799
+ ], widths=[1.9, 4.8])
800
+ add_heading(doc, "Vercel routing", 2)
801
+ add_body(doc, "The provider test route stays on Vercel. Other API requests are rewritten to the Hugging Face backend. The final fallback returns the React application for client side navigation.")
802
+ add_heading(doc, "Local deployment", 2)
803
+ add_body(doc, "Docker Compose supports a command line profile and a named Chroma volume. Durable local behavior still depends on mounting the checkpoint and job database paths, not only the vector directory.")
804
+
805
+ add_heading(doc, "22 Failure handling", 1)
806
+ add_lead(doc, "The system records partial failures instead of hiding them. This is essential for an AI review product because a missing reviewer changes the meaning of the result.")
807
+ add_table(doc, ["Failure", "Current response", "Recommended production action"], [
808
+ ("Model timeout", "Classify the reviewer stage as timed out and mark the review incomplete", "Retry through a durable queue with a bounded attempt count"),
809
+ ("Invalid model output", "Run one formatting repair attempt", "Track schema failure rate by model and prompt version"),
810
+ ("Token truncation", "Retry with a higher budget and request the top five findings", "Use adaptive input reduction and provider specific limits"),
811
+ ("GitHub rate limit or authentication", "Surface the error and avoid a normal verdict", "Refresh credentials or defer until reset"),
812
+ ("Stale pull request", "Block posting", "Start a fresh review for the new head"),
813
+ ("Inline comment rejected", "Fall back to an issue level comment", "Record the line mapping failure for analysis"),
814
+ ("Backend restart", "Process local queue and sessions are lost", "Use durable queue, session store, and shared checkpoints"),
815
+ ], widths=[1.35, 2.7, 2.65], font_size=9.0)
816
+
817
+ add_heading(doc, "23 Current limitations", 1)
818
+ add_lead(doc, "The project demonstrates a complete architecture, but several parts are portfolio scale rather than production scale. Naming these limits makes the design explanation stronger.")
819
+ add_bullets(doc, [
820
+ "The worker queue is process local and not restart safe.",
821
+ "OAuth sessions and temporary endpoint registrations are process local and not replica safe.",
822
+ "LangGraph checkpoints use SQLite and require explicitly durable storage.",
823
+ "Optional local retrieval is disabled by default on hosted deployments, so the hosted review may operate without vector context.",
824
+ "The generic chunker is not syntax aware for most languages and has no overlap.",
825
+ "The retrieval query uses only the first 8,000 characters of a long diff.",
826
+ "Core GitHub operations use a service style credential path rather than complete per user token propagation.",
827
+ "Saved provider keys in browser local storage are convenient but not ideal for production secret handling.",
828
+ "The committed evaluation files currently provide no positive accuracy result.",
829
+ "The UI label Grok does not match the Groq provider used by the implementation.",
830
+ ])
831
+ add_heading(doc, "Production roadmap", 2)
832
+ add_numbered(doc, [
833
+ "Replace the in process executor with a durable queue and idempotent workers.",
834
+ "Move checkpoints and OAuth sessions to durable shared stores.",
835
+ "Pass scoped per user GitHub credentials explicitly through each job.",
836
+ "Store provider secrets encrypted on the server and expose only secret references to the browser.",
837
+ "Use language aware chunking, diff hunk queries, reranking, and retrieval evaluation.",
838
+ "Build a versioned gold dataset and enforce regression gates for grounded precision and recall.",
839
+ "Add streaming progress, distributed tracing, quotas, abuse controls, and load tests.",
840
+ ])
841
+
842
+ add_heading(doc, "24 AI engineering decisions and tradeoffs", 1)
843
+ add_lead(doc, "The strongest interview explanation connects each technology to a concrete problem and admits the cost of that choice.")
844
+ add_table(doc, ["Decision", "Benefit", "Tradeoff"], [
845
+ ("Three specialist reviewers", "Better task focus and parallel latency", "More model calls, cost, and duplicate findings"),
846
+ ("LangGraph", "Explicit branches, shared state, interrupt, and resume", "More orchestration code than a simple sequential script"),
847
+ ("Structured output", "Validation, aggregation, and safe posting", "Schema failures require repair logic"),
848
+ ("Optional RAG", "Repository context beyond the diff", "Indexing cost, retrieval noise, and hosted resource requirements"),
849
+ ("Human approval", "Prevents automatic publication of weak findings", "Adds delay and requires durable checkpoints"),
850
+ ("Rule based score", "Cheap, consistent, and explainable", "Cannot capture every contextual risk"),
851
+ ("Process local worker pool", "Simple deployment and low infrastructure cost", "Not durable or horizontally scalable"),
852
+ ("Vercel plus Docker Space", "Simple frontend delivery and a flexible Python backend", "Two deployment surfaces and cross origin operational complexity"),
853
+ ], widths=[1.7, 2.5, 2.5], font_size=9.0)
854
+ add_heading(doc, "The architecture in one technical paragraph", 2)
855
+ add_body(doc, "OpenCodeReview uses a React and Vite frontend on Vercel and a FastAPI modular monolith on a Hugging Face Docker Space. FastAPI persists review jobs and starts an in process worker. A LangGraph state machine ingests GitHub pull request evidence, optionally retrieves base branch context from ChromaDB, fans out to three structured output LLM reviewers, grounds and aggregates their findings, interrupts for human approval, and resumes to post source grounded comments through the GitHub API. Supabase or SQLite stores job state, a separate SQLite saver stores graph checkpoints, and LangSmith, Langfuse, RAGAS, and offline fixtures support observability and evaluation.")
856
+
857
+ add_heading(doc, "25 Source code map", 1)
858
+ add_lead(doc, "Use this map when an interviewer asks where a behavior is implemented.")
859
+ add_table(doc, ["Area", "Files"], [
860
+ ("Web API and Gradio app", "backend/api.py and backend/app.py"),
861
+ ("Combined backend server", "backend/combined_server.py"),
862
+ ("Graph definition and shared state", "backend/graph.py and backend/state.py"),
863
+ ("CLI", "backend/main.py"),
864
+ ("GitHub access", "backend/integrations/github_client.py and auth.py"),
865
+ ("Model and endpoint setup", "backend/integrations/llm_factory.py, endpoints.py, and config.py"),
866
+ ("Graph nodes", "nodes/ingestion.py, retrieval.py, correctness_reviewer.py, security_reviewer.py, test_coverage_reviewer.py, finding_quality.py, aggregator.py, human_approval.py, executor.py"),
867
+ ("Prompt versions", "prompts/correctness_v1.txt, security_v1.txt, test_coverage_v1.txt, aggregator_v1.txt"),
868
+ ("Observability", "backend/observability.py"),
869
+ ("Evaluation", "eval_data/ragas_eval.py, evaluate.py, offline_regression.py, code_review_bench_eval.py, and fixtures"),
870
+ ("Frontend", "frontend/src/main.jsx, review-client.js, styles.css, frontend/api/provider-test.js"),
871
+ ("Deployment", "Dockerfile.api, docker-compose.yml, frontend/vercel.json, GitHub Actions workflows"),
872
+ ("Database migration", "supabase/migrations/20261020_create_review_jobs.sql"),
873
+ ("Project documentation", "docs/architecture, docs/runbooks, docs/evaluation, and docs/project-guide"),
874
+ ("Backward compatibility", "Root Python modules are small shims for existing imports and launch commands"),
875
+ ], widths=[1.65, 5.05], font_size=9.0)
876
+
877
+ add_heading(doc, "26 Interview answers", 1)
878
+ add_heading(doc, "Thirty second version", 2)
879
+ add_body(doc, "I built OpenCodeReview, an AI assisted pull request reviewer. A React frontend creates a review job in FastAPI. LangGraph then ingests the GitHub diff, optionally retrieves repository context from ChromaDB, and runs correctness, security, and test coverage reviewers in parallel. Their structured findings are grounded against changed lines, deduplicated, and scored. The graph pauses for human approval before an executor posts valid comments to GitHub. I also added tracing and both online and offline evaluation, while keeping the current quality claims evidence based.")
880
+ add_heading(doc, "Ninety second version", 2)
881
+ add_body(doc, "The frontend is a Vite React app on Vercel and the backend is a FastAPI modular monolith in a Hugging Face Docker Space. When a user submits a pull request, the API validates the request, fingerprints the pipeline, persists a job, and starts an in process worker. LangGraph orchestrates ingestion, optional retrieval, three parallel reviewer nodes, aggregation, human approval, and execution. RAG indexes eligible unchanged base branch code, important documentation, and recent merged pull request descriptions. Python is chunked at top level definitions, while other files use paragraph chunks around 1,200 characters. Each reviewer uses a specialist zero shot prompt with structured Pydantic output. A grounding layer checks that findings refer to real changed lines, and only grounded findings affect risk or get posted. The main production gaps are the process local queue and sessions, SQLite checkpoints, and the lack of a positive committed evaluation baseline. My next step would be durable workers, shared checkpoints, per user GitHub credentials, and regression gated evaluation.")
882
+ add_heading(doc, "Five minute structure", 2)
883
+ add_numbered(doc, [
884
+ "State the problem: pull requests need multiple review perspectives, but automated comments must remain grounded and human controlled.",
885
+ "Draw the system boundary: Vercel frontend, FastAPI Docker backend, GitHub, model providers, and storage.",
886
+ "Walk through the LangGraph nodes from ingestion to executor.",
887
+ "Explain RAG precisely, including what is indexed, chunking, top fifteen retrieval, and why changed files are excluded.",
888
+ "Explain prompting and structured output, then the repair and timeout paths.",
889
+ "Explain hallucination controls, scoring, and human approval.",
890
+ "Describe evaluation and state the current evidence honestly.",
891
+ "Finish with one production limitation and the concrete upgrade you would make.",
892
+ ])
893
+
894
+ add_heading(doc, "27 Interview questions and answers", 1)
895
+ qa = [
896
+ ("Why did you use multiple reviewers instead of one prompt", "Correctness, security, and test coverage require different attention. Separate prompts improve focus and allow parallel execution. The aggregator handles overlap and the extra cost."),
897
+ ("Is this really a multi agent system", "It is a graph of specialist LLM nodes with shared state. I call it a multi agent workflow in product language, but technically the specialists are controlled graph nodes, not independent long running agents."),
898
+ ("What type of chunking did you use", "Python uses structure aware top level class and function chunks. Other files use blank line paragraph chunks merged toward about 1,200 characters. There is currently no overlap."),
899
+ ("What is indexed in the vector database", "Eligible unchanged base branch code and documentation, selected project documents, and the title and body of up to twenty recent merged pull requests. Changed files, dependencies, build output, tests selected by path rules, and binaries are excluded."),
900
+ ("Why not index every file", "Changed files already enter the prompt directly, and dependencies or generated output add noise. Filtering reduces embedding time, storage, and irrelevant retrieval."),
901
+ ("What type of prompting did you use", "Specialist zero shot system and user prompts, augmented with retrieved context, plus structured Pydantic outputs. A repair prompt handles invalid formatting and a shorter retry handles truncated output."),
902
+ ("How do you reduce hallucinations", "I require structured file and line evidence, validate findings against changed lines, exclude unsupported items from scoring, require human approval, and recheck the pull request head before posting."),
903
+ ("How do you evaluate it", "RAGAS evaluates context related behavior, while offline fixtures compare findings with human comments using path and line matching. The infrastructure exists, but the committed snapshots currently show zero predictions, so I do not claim proven accuracy."),
904
+ ("What happens if one reviewer fails", "The stage records the failure and the aggregate recommendation becomes incomplete. The system should not present a normal score when one review dimension is missing."),
905
+ ("What would break at scale", "The in process queue, process local sessions, and SQLite checkpoints. I would replace them with a durable queue, shared session store, and durable graph checkpoint store before horizontal scaling."),
906
+ ("Why human approval", "LLM findings can be wrong even after grounding. Approval creates a clear control point before the system performs an external side effect."),
907
+ ("Why is the score not a quality guarantee", "It is a deterministic severity based heuristic over grounded findings. It does not prove that the model found every defect or that the code is correct."),
908
+ ]
909
+ add_table(doc, ["Question", "Answer"], qa, widths=[2.25, 4.45], font_size=9.0)
910
+
911
+ add_heading(doc, "28 Glossary", 1)
912
+ glossary = [
913
+ ("Agent node", "A graph step that asks an LLM to perform a specialized task"),
914
+ ("Base SHA", "Commit identifier for the target branch version used as review context"),
915
+ ("Checkpoint", "Saved graph state that allows an interrupted workflow to resume"),
916
+ ("Chunk", "A smaller unit of code or text stored and retrieved from the vector database"),
917
+ ("Cosine similarity", "A measure used to rank how close two embeddings are"),
918
+ ("Embedding", "A numeric vector representing the semantic meaning of text"),
919
+ ("Grounded finding", "A finding tied to a real changed file and line in the pull request"),
920
+ ("Head SHA", "Commit identifier for the pull request version being reviewed"),
921
+ ("Human in the loop", "A workflow that requires a human decision before it continues"),
922
+ ("LangGraph", "A framework for stateful graph based LLM workflows"),
923
+ ("Modular monolith", "One deployable backend process organized into well separated modules"),
924
+ ("RAG", "Retrieval augmented generation, where relevant stored context is supplied to an LLM"),
925
+ ("RAGAS", "A framework for measuring retrieval and answer quality"),
926
+ ("Structured output", "Model output constrained to a machine readable schema"),
927
+ ("Vector database", "A store that searches embeddings by semantic similarity"),
928
+ ]
929
+ add_table(doc, ["Term", "Meaning"], glossary, widths=[1.6, 5.1])
930
+
931
+ add_heading(doc, "Appendix A API routes", 1)
932
+ add_table(doc, ["Method and route", "Purpose"], [
933
+ ("GET /api/health", "Report backend health and selected capability configuration"),
934
+ ("GET /api/auth/github/start", "Begin GitHub OAuth"),
935
+ ("GET /api/auth/github/callback", "Complete OAuth and create the browser session"),
936
+ ("GET /api/auth/me", "Return the current signed in identity"),
937
+ ("POST /api/auth/logout", "Remove the current session"),
938
+ ("POST /api/reviews", "Create or reuse a review job"),
939
+ ("GET /api/reviews/{job_id}", "Read job progress and results"),
940
+ ("POST /api/reviews/{job_id}/cancel", "Request cancellation"),
941
+ ("POST /api/reviews/{job_id}/feedback", "Record finding feedback"),
942
+ ("POST /api/reviews/{job_id}/decision", "Approve or reject an interrupted review"),
943
+ ("POST /api/provider-test", "Test a custom provider from the Vercel frontend function"),
944
+ ], widths=[2.65, 4.05])
945
+
946
+ add_heading(doc, "Appendix B Important configuration", 1)
947
+ add_table(doc, ["Variable", "Purpose"], [
948
+ ("GITHUB_TOKEN", "GitHub service credential for ingestion and execution"),
949
+ ("GITHUB_OAUTH_CLIENT_ID and GITHUB_OAUTH_CLIENT_SECRET", "Browser OAuth configuration"),
950
+ ("GITHUB_OAUTH_CALLBACK_URL", "OAuth callback location"),
951
+ ("OCR_REQUIRE_AUTH and OCR_API_KEY", "API authentication policy"),
952
+ ("OCR_ALLOWED_ORIGINS", "CORS allowlist"),
953
+ ("OCR_FRONTEND_URL", "Frontend redirect target"),
954
+ ("OCR_MAX_WORKERS", "In process review worker count, default two"),
955
+ ("OCR_RATE_LIMIT_PER_MINUTE", "Optional API rate limit"),
956
+ ("SUPABASE_DB_URL", "Postgres job persistence"),
957
+ ("OPENCODEREVIEW_DB_PATH", "Local SQLite and graph checkpoint path used by application components"),
958
+ ("OPENCODEREVIEW_ALLOW_LOCAL_EMBEDDINGS", "Enables Chroma retrieval"),
959
+ ("OPENCODEREVIEW_VECTOR_DIR", "Persistent Chroma directory"),
960
+ ("GROQ_API_KEY and GROQ_MODEL", "Groq access and model selection"),
961
+ ("GEMINI_API_KEY", "Google Gemini access"),
962
+ ("OCR_MODEL_TIMEOUT_SECONDS", "Model request timeout"),
963
+ ("OCR_MODEL_MAX_OUTPUT_TOKENS", "Default model output budget"),
964
+ ("OCR_REVIEWER_TIMEOUT_SECONDS", "Per reviewer timeout"),
965
+ ("OCR_RAGAS_TIMEOUT_SECONDS", "Evaluation time budget"),
966
+ ("LANGSMITH_API_KEY", "LangSmith tracing"),
967
+ ("LANGFUSE_PUBLIC_KEY and LANGFUSE_SECRET_KEY", "Langfuse telemetry"),
968
+ ("AGGREGATOR_USE_LLM_CRITIC", "Optional LLM based aggregation critic"),
969
+ ], widths=[2.75, 3.95], font_size=9.0)
970
+
971
+ add_heading(doc, "Appendix C Verification and evidence limits", 1)
972
+ add_lead(doc, "The following checks were completed while preparing this guide. They confirm buildability and syntax, not full production correctness.")
973
+ add_table(doc, ["Check", "Result", "What it proves"], [
974
+ ("Frontend production build", "Passed with Vite 8.3.4", "The current frontend source bundles successfully"),
975
+ ("Backend Python compilation", "Passed for backend, nodes, eval_data, scripts, and tests", "The project Python modules have valid syntax"),
976
+ ("Automated Python tests", "Passed: 43 tests on Python 3.12", "The current automated test suite passed"),
977
+ ("Committed offline evaluation", "Zero predictions in the current snapshots", "Evaluation infrastructure exists, but quality is not established"),
978
+ ("End to end hosted review", "Not used as proof for this guide", "A reachable frontend alone does not prove durable jobs, posting, or evaluation quality"),
979
+ ], widths=[1.7, 2.0, 3.0], font_size=9.0)
980
+ add_heading(doc, "A final interview principle", 2)
981
+ add_body(doc, "Explain what the system does, then state what is optional, what is process local, what has been evaluated, and what you would change for production. Clear boundaries make the architecture credible.")
982
+
983
+ # Document properties
984
+ props = doc.core_properties
985
+ props.title = "OpenCodeReview AI Engineering Architecture Guide"
986
+ props.subject = "Complete architecture and interview guide for the OpenCodeReview project"
987
+ props.author = "OpenCodeReview project documentation"
988
+ props.keywords = "AI engineering, LangGraph, RAG, code review, architecture, prompting, evaluation"
989
+ props.comments = "Prepared from repository snapshot d939059"
990
+
991
+ doc.save(OUTPUT)
992
+ print(OUTPUT)
993
+
994
+
995
+ if __name__ == "__main__":
996
+ build_document()
docs/project-guide/tools/docx_to_html_preview.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import base64
4
+ import html
5
+ from pathlib import Path
6
+
7
+ from docx import Document
8
+ from docx.document import Document as DocumentType
9
+ from docx.oxml.ns import qn
10
+ from docx.table import Table
11
+ from docx.text.paragraph import Paragraph
12
+
13
+
14
+ ROOT = Path(__file__).resolve().parents[3]
15
+ GUIDE_DIR = ROOT / "docs" / "project-guide"
16
+ DOCX = GUIDE_DIR / "OpenCodeReview_AI_Engineering_Architecture_Guide.docx"
17
+ OUT = GUIDE_DIR / "working" / "preview.html"
18
+
19
+
20
+ def iter_blocks(parent):
21
+ parent_elm = parent.element.body if isinstance(parent, DocumentType) else parent._tc
22
+ for child in parent_elm.iterchildren():
23
+ if child.tag == qn("w:p"):
24
+ yield Paragraph(child, parent)
25
+ elif child.tag == qn("w:tbl"):
26
+ yield Table(child, parent)
27
+
28
+
29
+ def paragraph_image_data(paragraph: Paragraph):
30
+ blips = paragraph._p.xpath(".//a:blip")
31
+ if not blips:
32
+ return None
33
+ rid = blips[0].get(qn("r:embed"))
34
+ if not rid:
35
+ return None
36
+ part = paragraph.part.related_parts[rid]
37
+ content_type = part.content_type or "image/png"
38
+ return f"data:{content_type};base64,{base64.b64encode(part.blob).decode('ascii')}"
39
+
40
+
41
+ def para_html(paragraph: Paragraph, number_state: dict[str, int]):
42
+ text = html.escape(paragraph.text)
43
+ style = paragraph.style.name if paragraph.style else "Normal"
44
+ image = paragraph_image_data(paragraph)
45
+ if image:
46
+ return f'<div class="figure"><img src="{image}" alt="Embedded diagram"></div>'
47
+ if not text:
48
+ return '<div class="spacer"></div>'
49
+ if style == "Title":
50
+ return f"<h1 class='title'>{text}</h1>"
51
+ if style.startswith("Heading 1"):
52
+ return f"<h1 class='section'>{text}</h1>"
53
+ if style.startswith("Heading 2"):
54
+ return f"<h2>{text}</h2>"
55
+ if style.startswith("Heading 3"):
56
+ return f"<h3>{text}</h3>"
57
+ if style.startswith("List Bullet"):
58
+ return f"<p class='bullet'>• {text}</p>"
59
+ if style.startswith("List Number"):
60
+ number_state["n"] += 1
61
+ return f"<p class='number'><span>{number_state['n']}.</span> {text}</p>"
62
+ number_state["n"] = 0
63
+ is_code = any(run.font.name == "Consolas" for run in paragraph.runs)
64
+ if is_code:
65
+ return f"<pre>{text}</pre>"
66
+ is_caption = bool(paragraph.runs) and all(bool(run.italic) for run in paragraph.runs if run.text)
67
+ if is_caption:
68
+ return f"<p class='caption'>{text}</p>"
69
+ return f"<p>{text}</p>"
70
+
71
+
72
+ def table_html(table: Table):
73
+ rows = []
74
+ for r_idx, row in enumerate(table.rows):
75
+ cells = []
76
+ tag = "th" if r_idx == 0 else "td"
77
+ for cell in row.cells:
78
+ value = "<br>".join(html.escape(p.text) for p in cell.paragraphs)
79
+ cells.append(f"<{tag}>{value}</{tag}>")
80
+ rows.append("<tr>" + "".join(cells) + "</tr>")
81
+ return "<table>" + "".join(rows) + "</table>"
82
+
83
+
84
+ def main():
85
+ OUT.parent.mkdir(parents=True, exist_ok=True)
86
+ doc = Document(DOCX)
87
+ number_state = {"n": 0}
88
+ body = []
89
+ for block in iter_blocks(doc):
90
+ if isinstance(block, Paragraph):
91
+ fragment = para_html(block, number_state)
92
+ if fragment.startswith("<h1 class='section'"):
93
+ fragment = fragment.replace("class='section'", "class='section pagebreak'", 1)
94
+ body.append(fragment)
95
+ else:
96
+ body.append(table_html(block))
97
+ css = """
98
+ @page { size: Letter; margin: 0.72in 0.78in 0.68in; }
99
+ * { box-sizing: border-box; }
100
+ body { font-family: Arial, sans-serif; color: #1F2937; font-size: 11pt; line-height: 1.18; margin: 0; }
101
+ h1.title { font-size: 29pt; line-height: 1.08; margin: 0.9in 0 0.18in; }
102
+ h1.section { font-size: 19pt; margin: 0.08in 0 0.08in; break-after: avoid; }
103
+ h1.pagebreak { break-before: page; }
104
+ h2 { font-size: 14pt; color: #0B4F59; margin: 0.12in 0 0.05in; break-after: avoid; }
105
+ h3 { font-size: 11.5pt; margin: 0.1in 0 0.04in; break-after: avoid; }
106
+ p { margin: 0 0 0.075in; }
107
+ p.bullet { margin-left: 0.25in; text-indent: -0.16in; }
108
+ p.number { margin-left: 0.3in; text-indent: -0.2in; }
109
+ p.caption { text-align: center; color: #52606D; font-size: 9pt; font-style: italic; }
110
+ pre { font-family: Consolas, monospace; color: #0B4F59; font-size: 9.4pt; white-space: pre-wrap; margin: 0.03in 0 0.08in 0.28in; }
111
+ .figure { text-align: center; break-inside: avoid; }
112
+ .figure img { max-width: 6.8in; height: auto; }
113
+ .spacer { height: 0.04in; }
114
+ table { width: 100%; border-collapse: collapse; margin: 0.06in 0 0.12in; font-size: 9pt; break-inside: auto; }
115
+ tr { break-inside: avoid; }
116
+ th, td { border: 1px solid #D9D9D9; padding: 0.06in 0.075in; vertical-align: top; }
117
+ th { background: #0B4F59; color: white; text-align: left; }
118
+ tr:nth-child(odd) td { background: #F6F8FA; }
119
+ """
120
+ OUT.write_text(
121
+ "<!doctype html><html><head><meta charset='utf-8'>"
122
+ "<title>OpenCodeReview AI Engineering Architecture Guide</title>"
123
+ "<style>" + css + "</style></head><body>" + "".join(body) + "</body></html>",
124
+ encoding="utf-8",
125
+ )
126
+ print(OUT)
127
+
128
+
129
+ if __name__ == "__main__":
130
+ main()
docs/project-guide/tools/make_contact_sheets.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ from PIL import Image, ImageDraw, ImageFont
3
+
4
+ ROOT = Path(__file__).resolve().parents[3] / "docs" / "project-guide" / "working"
5
+ PAGES = sorted((ROOT / "preview_pages").glob("page-*.png"), key=lambda p: int(p.stem.split("-")[-1]))
6
+ FONT_PATH = Path(r"C:\Windows\Fonts\arial.ttf")
7
+ FONT = ImageFont.truetype(str(FONT_PATH), 20) if FONT_PATH.exists() else ImageFont.load_default()
8
+
9
+ for sheet_index in range(0, len(PAGES), 16):
10
+ selected = PAGES[sheet_index:sheet_index + 16]
11
+ canvas = Image.new("RGB", (1320, 1760), "#D9D9D9")
12
+ draw = ImageDraw.Draw(canvas)
13
+ for idx, page_path in enumerate(selected):
14
+ page = Image.open(page_path).convert("RGB")
15
+ page.thumbnail((300, 395))
16
+ col, row = idx % 4, idx // 4
17
+ x, y = 18 + col * 326, 35 + row * 430
18
+ canvas.paste(page, (x, y))
19
+ draw.text((x, 8 + row * 430), f"Page {sheet_index + idx + 1}", fill="#1F2937", font=FONT)
20
+ canvas.save(ROOT / f"contact-{sheet_index // 16 + 1}.png")
docs/project-guide/tools/make_final_pdf_contact_sheets.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ from PIL import Image, ImageDraw, ImageFont
3
+
4
+ ROOT = Path(__file__).resolve().parents[3] / "docs" / "project-guide" / "working" / "pdf-review"
5
+ PAGES = sorted(ROOT.glob("page-*.png"), key=lambda p: int(p.stem.split("-")[-1]))
6
+ FONT_PATH = Path(r"C:\Windows\Fonts\arial.ttf")
7
+ FONT = ImageFont.truetype(str(FONT_PATH), 20) if FONT_PATH.exists() else ImageFont.load_default()
8
+
9
+ for start in range(0, len(PAGES), 16):
10
+ canvas = Image.new("RGB", (1320, 1760), "#D9D9D9")
11
+ draw = ImageDraw.Draw(canvas)
12
+ for offset, page_path in enumerate(PAGES[start:start + 16]):
13
+ page = Image.open(page_path).convert("RGB")
14
+ page.thumbnail((300, 395))
15
+ col, row = offset % 4, offset // 4
16
+ x, y = 18 + col * 326, 35 + row * 430
17
+ canvas.paste(page, (x, y))
18
+ draw.text((x, 8 + row * 430), f"Page {start + offset + 1}", fill="#1F2937", font=FONT)
19
+ canvas.save(ROOT / f"contact-final-{start // 16 + 1}.png")
docs/project-guide/tools/render_preview.cjs ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const path = require('path');
2
+ const { pathToFileURL } = require('url');
3
+ const { chromium } = require('playwright');
4
+
5
+ (async () => {
6
+ const guideDir = path.resolve(__dirname, '..');
7
+ const workDir = path.join(guideDir, 'working');
8
+ const outputPdf = path.join(guideDir, 'OpenCodeReview_AI_Engineering_Architecture_Guide.pdf');
9
+ const launchOptions = { headless: true };
10
+ if (process.env.BROWSER_EXECUTABLE_PATH) {
11
+ launchOptions.executablePath = process.env.BROWSER_EXECUTABLE_PATH;
12
+ }
13
+ const browser = await chromium.launch(launchOptions);
14
+ const page = await browser.newPage({ viewport: { width: 1275, height: 1650 } });
15
+ await page.goto(pathToFileURL(path.join(workDir, 'preview.html')).href, { waitUntil: 'load' });
16
+ await page.pdf({
17
+ path: outputPdf,
18
+ format: 'Letter',
19
+ printBackground: true,
20
+ preferCSSPageSize: true,
21
+ displayHeaderFooter: true,
22
+ headerTemplate: '<div style="font-family:Arial,sans-serif;font-size:8px;color:#52606D;width:100%;text-align:right;padding-right:0.78in;">OpenCodeReview AI Engineering Guide</div>',
23
+ footerTemplate: '<div style="font-family:Arial,sans-serif;font-size:8px;color:#52606D;width:100%;text-align:center;">OpenCodeReview | Repository snapshot d939059 | Page <span class="pageNumber"></span> of <span class="totalPages"></span></div>',
24
+ });
25
+ await browser.close();
26
+ console.log(outputPdf);
27
+ })().catch((error) => {
28
+ console.error(error);
29
+ process.exit(1);
30
+ });
docs/runbooks/AUTHENTICATION_RUNBOOK.md ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # GitHub authentication runbook
2
+
3
+ The CLI already supports GitHub OAuth Device Flow through
4
+ `GITHUB_OAUTH_CLIENT_ID`. Web authentication is the final production gate and
5
+ must be enabled only after the core review and posting checks pass.
6
+
7
+ ## Required deployment values
8
+
9
+ - `GITHUB_OAUTH_CLIENT_ID`: GitHub OAuth App client ID.
10
+ - `GITHUB_OAUTH_CLIENT_SECRET`: OAuth App secret stored as a platform secret.
11
+ - `OCR_REQUIRE_AUTH=true`: require authenticated API requests in production.
12
+ - `OCR_ALLOWED_ORIGINS`: the exact Vercel frontend origin.
13
+
14
+ ## GitHub permissions
15
+
16
+ Use the least privilege needed to read pull requests and create pull-request
17
+ or issue comments. Validate the granted identity before creating a review and
18
+ store the user ID with every job. A user may read, approve, or post only jobs
19
+ owned by that identity.
20
+
21
+ ## Final acceptance checks
22
+
23
+ 1. Complete OAuth login and callback with a test GitHub account.
24
+ 2. Create a review from the authenticated frontend.
25
+ 3. Confirm the job is owned by that account in Supabase.
26
+ 4. Approve the review and verify the GitHub posting receipt and comments.
27
+ 5. Confirm a second account cannot read or approve the job.
28
+ 6. Revoke the token and confirm subsequent requests fail safely.
29
+
30
+ Never commit OAuth secrets or personal access tokens. Configure them only in
31
+ the deployment secret manager.
docs/runbooks/DEPLOYMENT_RUNBOOK.md ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Production deployment runbook
2
+
3
+ ## Required before enabling public access
4
+
5
+ 1. Set `GITHUB_TOKEN` or configure the GitHub App/OAuth flow.
6
+ 2. Set one remote inference credential (`GEMINI_API_KEY`, `GROQ_API_KEY`, or a configured endpoint).
7
+ 3. Set `OCR_REQUIRE_AUTH=true` and a strong `OCR_API_KEY` until web OAuth is enabled.
8
+ 4. Set `OCR_ALLOWED_ORIGINS` to the exact Vercel origin.
9
+ 5. Set `OPENCODEREVIEW_DB_PATH` to a mounted persistent path, or migrate the
10
+ job/checkpoint store to Postgres before running more than one replica.
11
+ 6. Keep `OPENCODEREVIEW_ALLOW_LOCAL_EMBEDDINGS=false` on small hosts.
12
+
13
+ ## Verification gates
14
+
15
+ - `GET /api/health` reports `remote_provider_configured` and `configured_path`.
16
+ - A real PR reaches `awaiting_approval` without posting comments automatically.
17
+ - The decision endpoint returns a structured posting receipt.
18
+ - RAGAS reaches `completed` with non-empty metric values, or reports a bounded
19
+ terminal failure with an actionable reason.
20
+ - Restart the worker and confirm an awaiting-approval job remains readable.
21
+ - Run the offline Code Review Bench scorer and retain its JSON result artifact.
22
+
23
+ The current Hugging Face Space passes the health and live-review gates, but its
24
+ default filesystem is ephemeral. Configure persistent storage before claiming
25
+ restart-safe production durability.
docs/specifications/opencodereview-spec.md ADDED
@@ -0,0 +1,335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # OpenCodeReview — Project Description
2
+
3
+ > **Spec file** · Audience: future maintainers & contributors · Goal: balanced
4
+ > overview (features + architecture + how to run) · Accuracy: **as-is**, i.e. the
5
+ > working tree is the source of truth, including uncommitted changes. No
6
+ > recommendations section — this document describes only.
7
+ >
8
+ > Written: 2026-08-12 · Based on code reading (no commands executed).
9
+
10
+ ---
11
+
12
+ ## 1. What the project is
13
+
14
+ **OpenCodeReview** is an AI-powered pull-request reviewer with a
15
+ **human-in-the-loop** approval gate. It runs a LangGraph pipeline in which three
16
+ specialist LLM reviewers — **correctness**, **security**, and **test coverage** —
17
+ analyze a PR in parallel, grounded by a ChromaDB vector store over the repo's
18
+ codebase history. Nothing is posted to GitHub until a human reviews the verdict
19
+ and explicitly approves it. Findings are posted as inline PR review comments with
20
+ an automatic fallback to issue-level comments when lines go stale.
21
+
22
+ It ships as both a **Click CLI** (`main.py`) and a **Gradio web UI** (`app.py`,
23
+ the entry point for Hugging Face Spaces), and includes an evaluation harness
24
+ (ground-truth precision/recall/F1 + RAGAS retrieval metrics), optional
25
+ observability (LangSmith + Langfuse), cost/TTFT tracking, a health-check CLI
26
+ (`doctor`), and a continuous alerting script.
27
+
28
+ **One-paragraph elevator summary:** "Enter `owner/repo` + PR number (or run the
29
+ CLI), the pipeline fetches the PR, indexes/retrieves relevant code context,
30
+ runs three parallel LLM reviews, dedupes and scores the findings, pauses for a
31
+ human decision, and only then posts comments back to GitHub."
32
+
33
+ ---
34
+
35
+ ## 2. Feature summary
36
+
37
+ - **Three parallel specialist reviewers** — correctness, security, and
38
+ test-coverage nodes run concurrently on the same diff, each with its own
39
+ versioned system prompt under `prompts/`.
40
+ - **Retrieval-augmented review** — a persistent ChromaDB store embeds the repo's
41
+ source, up to 20 past merged PRs, and docs (README, CONTRIBUTING…); the diff is
42
+ used as a query and the top ~15 chunks are injected as reviewer context.
43
+ - **Human-in-the-loop approval** — the graph calls LangGraph's `interrupt()` and
44
+ pauses; the caller (CLI prompt or UI buttons) resumes with `approve` / `reject`.
45
+ - **Inline comments** — approved findings are posted at the exact file/line
46
+ position; a GitHub `422` (stale line) triggers an issue-comment fallback.
47
+ - **Smart aggregation** — heuristic deduplication (file/line proximity ±5 lines +
48
+ confidence) and noise filtering (< 0.25 confidence dropped), plus a rule-based
49
+ verdict with an optional LLM-critic pass.
50
+ - **LLM flexibility** — Gemini primary → Groq fallback, plus **custom endpoints**
51
+ (BYO keys) for any OpenAI-compatible API, Anthropic, or Google, configured via
52
+ `OCR_ENDPOINT_*` env vars or added at runtime in the UI.
53
+ - **Evaluation & observability** — ground-truth eval harness, RAGAS retrieval
54
+ metrics, LangSmith/Langfuse tracing, per-run token cost & TTFT.
55
+ - **CLI + Web UI** — identical pipeline driven from either interface.
56
+ - **GitHub OAuth Device Flow** — interactive login, tokens stored in the OS
57
+ keyring (priority: keyring → `GITHUB_TOKEN` env).
58
+
59
+ ---
60
+
61
+ ## 3. System architecture (pipeline-focused)
62
+
63
+ The system is a **LangGraph state machine** (`graph.py`) with a typed Pydantic
64
+ state schema and SQLite checkpointing. Topology:
65
+
66
+ ```
67
+ START → ingestion → retrieval ──→ correctness_review ──┐
68
+ ├──→ security_review ├──→ aggregator → human_approval (interrupt ⏸) → executor → END
69
+ └──→ test_coverage_review ──┘
70
+ ```
71
+
72
+ ### 3.1 Pipeline nodes
73
+
74
+ | # | Node | Module | What it does |
75
+ |---|------|--------|--------------|
76
+ | 1 | `ingestion` | `nodes/ingestion.py` | Fetches PR metadata, the full unified diff, and per-file contents from the GitHub API (handles fork PRs, pagination, rate limits). No-op when a diff is already present in state (e.g. synthetic payloads). |
77
+ | 2 | `retrieval` | `nodes/retrieval.py` | Builds/loads a ChromaDB collection embedding the repo source, past merged PRs, and docs; queries it with the diff; returns top-15 context chunks. Cached per base-branch SHA so embeddings aren't rebuilt per run. |
78
+ | 3–5 | `correctness_review`, `security_review`, `test_coverage_review` | `nodes/{correctness,security,test_coverage}_reviewer.py` | Three parallel LLM reviewers. Each emits Pydantic-validated findings (category, severity, confidence, line range, suggested fix) via `with_structured_output`. Prompts live in `prompts/*_v1.txt`. |
79
+ | 6 | `aggregator` | `nodes/aggregator.py` | Merges findings pointing at the same file/line (±5 lines, highest confidence wins), drops noise below 0.25, then produces a verdict. Default is a rule-based verdict (~10 ms, zero LLM cost); `AGGREGATOR_USE_LLM_CRITIC=true` enables an optional LLM critic pass. |
80
+ | 7 | `human_approval` | `nodes/human_approval.py` | Calls `interrupt()` — the graph **pauses** and returns verdict + findings to the caller. Nothing is posted until resumed with `approve` / `reject`. |
81
+ | 8 | `executor` | `nodes/executor.py` | Posts each finding as an inline PR review comment (multi-line ranges supported). On GitHub `422` (stale line), falls back to a general issue comment. Posts the overall verdict as a summary comment. |
82
+
83
+ **Verdict rules (rule-based default):**
84
+
85
+ | Condition | Recommendation | Approved |
86
+ |---|---|---|
87
+ | ≥ 1 critical finding | `block` | ❌ |
88
+ | ≥ 1 high finding | `request_changes` | ❌ |
89
+ | any medium/low/info finding | `comment` | ✅ |
90
+ | no findings | `approve` | ✅ |
91
+
92
+ Score = `10 − 4·critical − 2·high − 0.5·medium`, clamped to 0–10.
93
+
94
+ ### 3.2 State schema (minimal)
95
+
96
+ `OpenCodeReviewState` (`state.py`) is a Pydantic `BaseModel`. Key fields:
97
+
98
+ - PR metadata: `repo`, `pr_number`, `base_sha`, `diff`, `changed_files`
99
+ - `endpoint` — chosen custom LLM endpoint name (empty = built-in default)
100
+ - Accumulated lists (`Annotated[list, add]` reducers so parallel branches merge):
101
+ `context_chunks`, `findings`
102
+ - Aggregated output: `final_findings`, `verdict` (`Verdict` model), `human_approved`
103
+
104
+ Sub-models: `ChangedFile`, `ContextChunk`, `Finding`, `Verdict`, and a `Severity`
105
+ enum (`critical`/`high`/`medium`/`low`/`info`). See `state.py` for field-level
106
+ detail.
107
+
108
+ ### 3.3 Checkpointing & resume
109
+
110
+ - Every run is persisted via **`SqliteSaver`** on a SQLite DB
111
+ (`graph.py`, `checkpoints.db` by default; `:memory:` for ephemeral runs).
112
+ - A `JsonPlusSerializer` with an allowlist of the Pydantic models handles state
113
+ (de)serialization.
114
+ - The compiled graph exposes `_opencodereview_conn` (informal handle) so callers
115
+ close the SQLite connection when a run finishes — prevents file-handle leaks in
116
+ the long-running UI. The DB file is cleaned up after runs (`_cleanup_db()`).
117
+ - Because checkpoints persist to disk, a paused graph can be resumed after a page
118
+ reload or process restart via the same `thread_id`.
119
+
120
+ ---
121
+
122
+ ## 4. Supporting layers
123
+
124
+ ### 4.1 LLM layer (`llm_factory.py`)
125
+
126
+ - **Default chain:** Google Gemini (`gemini-3.1-flash-lite`, primary) → Groq
127
+ (`llama-3.3-70b-versatile`, fallback); `temperature=0`. `ValueError` if no key.
128
+ - **Custom endpoints** (`endpoints.py` + `llm_factory.create_endpoint_llm`):
129
+ - OpenAI-compatible (`langchain-openai`) — DeepSeek, OpenRouter, vLLM, Ollama,
130
+ Together, local proxies…
131
+ - Anthropic (`langchain-anthropic`), Google (`langchain-google-genai`).
132
+ - **Endpoint registry** (`endpoints.py`):
133
+ - Env convention: `OCR_ENDPOINT_<n>_NAME/TYPE/API_KEY/BASE_URL/MODEL`
134
+ (`TYPE`: `openai` | `anthropic` | `google`; default `openai`).
135
+ - Built-in entries: `Gemini` and `Grok` are always selectable as endpoints.
136
+ - UI-added endpoints live in an in-memory, thread-locked session registry
137
+ (never written to disk; vanish on process restart).
138
+ - Name precedence on collision: **session (UI) > env-var > built-in**.
139
+ - Keys are only read from the environment and masked for display.
140
+
141
+ ### 4.2 GitHub integration (`github_client.py`, `auth.py`)
142
+
143
+ - `requests`-based client; token resolution priority **keyring → `GITHUB_TOKEN`
144
+ env**; 401 detection with a helpful re-auth error.
145
+ - HTTP caching via `requests-cache` (15-min TTL) under `.opencodereview/`.
146
+ - `auth.py`: GitHub OAuth **Device Flow** — `auth login` prints a one-time code;
147
+ token stored in the OS keyring (scope `repo`).
148
+
149
+ ### 4.3 Aggregation & verdict (see §3.1 node 6)
150
+
151
+ ### 4.4 Configuration (`config.py`)
152
+
153
+ - `Settings` (pydantic-settings) resolves env var → system keyring → error.
154
+ - Provider registry currently covers `anthropic` (`OPENCODEREVIEW_ANTHROPIC_KEY`).
155
+ - CLI: `config set-key`, `config show` (masked), `config set-observability`.
156
+
157
+ ---
158
+
159
+ ## 5. Interfaces & configuration
160
+
161
+ ### 5.1 CLI (`main.py`)
162
+
163
+ | Command | Purpose |
164
+ |---|---|
165
+ | `review [--smoke] [--repo OWNER/REPO] [--pr N] [--endpoint NAME]` | Run the pipeline. Default repo/pr uses a built-in synthetic payload (no keys/network needed). Interactive HITL prompt (`a`/`r`/`q`). |
166
+ | `doctor` | Health checks: Python version, API keys, LLM endpoints, Groq/Langfuse connectivity. |
167
+ | `auth login/status/logout` | GitHub OAuth Device Flow management. |
168
+ | `config …` | `set-key`, `show`, `set-observability` (see §4.4). |
169
+
170
+ Every option also works as an env var with the `OCR_` prefix
171
+ (e.g. `--repo` → `OCR_REPO`, `--pr` → `OCR_PR_NUMBER`).
172
+
173
+ ### 5.2 Gradio web UI (`app.py`)
174
+
175
+ - **Review a PR** tab (owner/repo + PR number, live pipeline status, then
176
+ **Approve & Post** / **Reject**).
177
+ - **Smoke Test** tab (synthetic demo, no keys).
178
+ - Severity-colored findings table, verdict card, RAGAS retrieval-quality bars,
179
+ per-run cost summary.
180
+ - **Configured Keys & Health** accordion; dark/light theme toggle (persisted).
181
+ - **LLM Endpoint** dropdown with a "Built-in" optgroup (Gemini, Grok) and flat
182
+ custom-endpoint entries; an add-any-custom-endpoint form (BYO name/type/base
183
+ URL/key/model); endpoint test buttons that probe connectivity
184
+ (`_probe_endpoint` — classifies 401/403 as "server rejected the key", falls
185
+ back to a `chat/completions` probe when `GET /models` is blocked/missing).
186
+
187
+ ### 5.3 Environment variables (key ones; full list in README)
188
+
189
+ | Variable | Purpose |
190
+ |---|---|
191
+ | `GEMINI_API_KEY` / `GROQ_API_KEY` | Primary / fallback LLM keys |
192
+ | `GITHUB_TOKEN` | GitHub token (keyring preferred) |
193
+ | `OCR_ENDPOINT_<n>_*` | Custom endpoint configs (name/type/key/base_url/model) |
194
+ | `AGGREGATOR_USE_LLM_CRITIC` | `true` enables LLM-critic aggregation pass |
195
+ | `LANGSMITH_API_KEY`, `LANGFUSE_*` | Observability backends |
196
+ | `PORT` | Gradio port (default 7860) |
197
+ | `OCR_RAGAS_INTERVAL` | RAGAS throttle interval in seconds (default 3.0; 0 disables) |
198
+
199
+ ---
200
+
201
+ ## 6. Evaluation & observability
202
+
203
+ ### 6.1 Ground-truth evaluation (`eval_data/`)
204
+
205
+ - `fetcher.py` builds `prs.jsonl` — one JSON per PR with diff, changed files, and
206
+ human review comments as ground truth (requires `GITHUB_TOKEN`).
207
+ - `evaluate.py` matches findings to human comments by **file path + line
208
+ proximity (±3 lines)** (optional keyword-overlap bonus), computes
209
+ **precision / recall / F1** per PR plus micro/macro averages →
210
+ `eval_data/eval_results.json`. Refuses to run while `GITHUB_TOKEN` is set
211
+ (executor would post to real PRs) unless `--force`.
212
+ - `ragas_eval.py` computes RAGAS retrieval metrics: `context_precision`,
213
+ `context_recall`, `faithfulness`, `answer_relevancy`, `mmr`.
214
+
215
+ ### 6.2 Observability (`observability.py`)
216
+
217
+ - **LangSmith** — enabled automatically when `LANGSMITH_API_KEY` (or legacy
218
+ `LANGCHAIN_API_KEY`) is set.
219
+ - **Langfuse** — enabled when public+secret keys are set; a trace per review;
220
+ scores logged: `verdict_score`, `findings_count`, `ragas_*` metrics.
221
+ - **Cost & TTFT** — `TokenCostCallback` tracks per-run USD cost (via a
222
+ `MODEL_PRICING` table covering Groq models and Gemini) and time-to-first-token;
223
+ printed by CLI and shown in the UI.
224
+ - **Health checks** — `HealthStatus`, `check_groq_connectivity`,
225
+ `check_langfuse_connectivity` (used by `doctor`).
226
+
227
+ ### 6.3 RAGAS details worth knowing
228
+
229
+ - RAGAS scoring is routed **Groq-first** (avoids Gemini's ~15 req/min quota),
230
+ then Gemini. Requires `GROQ_API_KEY` or `GEMINI_API_KEY`.
231
+ - Uncommitted work in the working tree throttles RAGAS LLM calls through a
232
+ `_ThrottledChatModel` wrapper (`OCR_RAGAS_INTERVAL`, default 3 s between calls)
233
+ to stay under free-tier per-minute rate limits, and failed metrics are logged
234
+ as `None` (not fake `0.0`), with consumers guarded against `None`.
235
+
236
+ ### 6.4 Alerting (`scripts/alert.py`)
237
+
238
+ Runs the smoke-test review, compares the score to a stored baseline, and pings a
239
+ **Discord or Slack webhook** when the score deviates by > 2.5 points or the run
240
+ fails. `alert.yml` runs it every 6 hours.
241
+
242
+ ---
243
+
244
+ ## 7. Deployment & CI
245
+
246
+ - **Dockerfile** — multi-stage: `builder` → `runtime` (default; ONNX MiniLM
247
+ embedder, no PyTorch) → `runtime-full` (adds sentence-transformers/PyTorch).
248
+ - **docker-compose.yml** — one service, named volume for the vector store
249
+ (`opencodereview_vectors`) so embeddings persist across runs;
250
+ `docker-entrypoint.sh` fixes volume permissions and drops to a non-root user.
251
+ - **Hugging Face Spaces** — `.github/workflows/deploy-hf.yml` syncs the repo to
252
+ the Space and restarts it (Docker SDK, port 7860) on push to `main`.
253
+ - **GitHub Actions** — `alert.yml` (every-6h smoke-test alert).
254
+
255
+ ---
256
+
257
+ ## 8. Project structure (file map)
258
+
259
+ ```
260
+ ├── app.py # Gradio web UI (HF Spaces entry point)
261
+ ├── main.py # Click CLI — review / doctor / auth / config
262
+ ├── graph.py # LangGraph pipeline + SqliteSaver checkpointing
263
+ ├── state.py # Typed Pydantic state schema
264
+ ├── llm_factory.py # Gemini → Groq fallback + custom-endpoint factory
265
+ ├── endpoints.py # Custom LLM endpoint registry (env + UI session)
266
+ ├── github_client.py # GitHub API client, token resolution, HTTP cache
267
+ ├── auth.py # GitHub OAuth Device Flow
268
+ ├── config.py # Settings (env → keyring → error) + config CLI
269
+ ├── observability.py # LangSmith/Langfuse, cost & TTFT, health checks
270
+ ├── nodes/ # One module per graph node (8 nodes)
271
+ ├── prompts/ # Versioned system prompts (…_v1.txt)
272
+ ├── eval_data/ # fetcher.py · evaluate.py · ragas_eval.py · prs.jsonl · eval_results.json
273
+ ├── scripts/alert.py # Continuous health monitor (Discord/Slack)
274
+ ├── .github/workflows/ # alert.yml · deploy-hf.yml
275
+ └── Dockerfile · docker-compose.yml · docker-entrypoint.sh
276
+ ```
277
+
278
+ ---
279
+
280
+ ## 9. Current state — known gaps & observations
281
+
282
+ These are the honest as-is observations a maintainer should know (no
283
+ recommendations here — just description):
284
+
285
+ - **No automated tests.** There is no `tests/` directory; verification relies on
286
+ `python main.py review --smoke`, `python main.py doctor`, and the eval harness.
287
+ The README acknowledges this.
288
+ - **Breadth-first exception swallowing.** Many layers catch `Exception` and only
289
+ warn or silently degrade: Langfuse score logging, reviewer nodes (LLM failure →
290
+ empty review), the aggregator's optional LLM critic, and RAGAS metric failures.
291
+ This historically hid real failures (documented in `FIXES.md`).
292
+ - **FIXES.md backlog** — 14 documented fixes, most already applied to the code
293
+ (verified: `import requests` in `nodes/executor.py`, the `_opencodereview_conn`
294
+ connection-close pattern in `graph.py`/`main.py`/`app.py`, deleted dead
295
+ `passthrough`/`post_results` nodes, and a `MODEL_PRICING` table incl. Gemini).
296
+ The master checklist at the end of `FIXES.md` is unchecked — treat it as a
297
+ record of intent rather than current status.
298
+ - **Uncommitted working-tree changes** (described as current state above):
299
+ - `app.py` — improved endpoint probing (401/403 classified as key-rejected,
300
+ chat/completions fallback probe for servers without `GET /models`, clearer
301
+ status text in cards and the test form).
302
+ - `eval_data/ragas_eval.py` — `_ThrottledChatModel` rate-limit throttle,
303
+ Groq-first with `max_retries=5`, failed metrics → `None`.
304
+ - **Minor artifacts:** a stray `nodes__init__.py` file sits at the repo root
305
+ (an accidental duplicate of `nodes/__init__.py`); `.opencodereview/vectors/`
306
+ contains a large checked-in ChromaDB sqlite file.
307
+ - **Naming inconsistencies:** the UI/CLI refer to the built-in Groq provider as
308
+ "Grok" (`builtin_endpoints()`), which differs from the actual provider name.
309
+ - **`nodes/aggregator.py`** (unlike the reviewers) imports a shared
310
+ `GROQ_MODEL`-style constant rather than a centralised `constants.py` — there is
311
+ no `constants.py`; constants are still duplicated across modules.
312
+
313
+ ---
314
+
315
+ ## 10. How to run it (quick reference)
316
+
317
+ ```bash
318
+ pip install -r requirements.txt
319
+ export GITHUB_TOKEN=ghp_... # real PRs only; keyring preferred
320
+ export GEMINI_API_KEY=AIza... # or GROQ_API_KEY
321
+
322
+ python main.py review --smoke # offline pipeline check
323
+ python main.py review --repo psf/requests --pr 42 # real PR
324
+ python main.py review --endpoint DeepSeek ... # custom endpoint
325
+ python main.py doctor # health checks
326
+ python app.py # web UI at :7860
327
+
328
+ python eval_data/evaluate.py --max-prs 2 # quick eval run
329
+ python eval_data/ragas_eval.py --data eval_data/prs.jsonl # RAGAS metrics
330
+ ```
331
+
332
+ ---
333
+
334
+ *End of project description. Source of truth: the working tree at commit
335
+ `bd08fdb` + uncommitted changes, verified by code reading on 2026-08-12.*
endpoints.py CHANGED
@@ -1,306 +1,5 @@
1
- """Custom LLM endpoint registry.
 
 
2
 
3
- Lets users register any number of custom model endpoints via environment
4
- variables (set as Space secrets or in the shell), so a review can run on a
5
- user-chosen model instead of the single built-in key.
6
-
7
- Env-var convention (index *n* is any number ≥ 1)::
8
-
9
- OCR_ENDPOINT_1_NAME=DeepSeek
10
- OCR_ENDPOINT_1_TYPE=openai # openai | anthropic | google (default openai)
11
- OCR_ENDPOINT_1_API_KEY=sk-...
12
- OCR_ENDPOINT_1_BASE_URL=https://api.deepseek.com/v1
13
- OCR_ENDPOINT_1_MODEL=deepseek-chat
14
-
15
- OCR_ENDPOINT_2_NAME=Claude
16
- OCR_ENDPOINT_2_TYPE=anthropic
17
- OCR_ENDPOINT_2_API_KEY=sk-ant-...
18
- OCR_ENDPOINT_2_MODEL=claude-sonnet-4-20250514
19
-
20
- Supported ``TYPE`` values:
21
- * ``openai`` — any OpenAI-compatible API (DeepSeek, OpenRouter, vLLM,
22
- Ollama, Together, local proxies, ...)
23
- * ``anthropic`` — Anthropic Claude (``base_url`` optional, e.g. a proxy)
24
- * ``google`` — Google Gemini (``base_url`` not used)
25
-
26
- Keys are only ever read from the environment — they are never written to
27
- disk. Use :func:`mask_key` anywhere a key is shown in the UI.
28
- """
29
-
30
- from __future__ import annotations
31
-
32
- import logging
33
- import os
34
- import threading
35
- from dataclasses import dataclass
36
- from typing import Optional
37
-
38
- logger = logging.getLogger(__name__)
39
-
40
- ENDPOINT_ENV_PREFIX = "OCR_ENDPOINT_"
41
-
42
- SUPPORTED_PROVIDERS = ("openai", "anthropic", "google")
43
-
44
-
45
- @dataclass
46
- class EndpointConfig:
47
- """A single custom LLM endpoint the user has configured."""
48
-
49
- name: str
50
- provider: str = "openai" # openai | anthropic | google
51
- api_key: str = ""
52
- base_url: Optional[str] = None
53
- model: str = ""
54
- index: int = 0 # the env-var index the endpoint came from
55
- builtin: bool = False # True for the always-available Gemini/Grok providers
56
-
57
- def __post_init__(self) -> None:
58
- self.provider = (self.provider or "openai").strip().lower()
59
- if self.provider not in SUPPORTED_PROVIDERS:
60
- logger.warning(
61
- "Endpoint %r has unsupported type %r — treating as openai",
62
- self.name, self.provider,
63
- )
64
- self.provider = "openai"
65
-
66
- @property
67
- def masked_key(self) -> str:
68
- """API key with only the first/last few chars visible."""
69
- return mask_key(self.api_key)
70
-
71
- def describe(self) -> str:
72
- """One-line human-readable summary for the UI / CLI."""
73
- base = f" ({self.base_url})" if self.base_url else ""
74
- return f"{self.name} [{self.provider}] {self.model}{base} — {self.masked_key}"
75
-
76
-
77
- def mask_key(api_key: str) -> str:
78
- """Mask an API key for display, e.g. ``sk-abc…wxyz``."""
79
- if not api_key:
80
- return "(empty)"
81
- if len(api_key) <= 8:
82
- return api_key[:2] + "…" + api_key[-2:]
83
- return api_key[:6] + "…" + api_key[-4:]
84
-
85
-
86
- # ── Runtime (UI-added) endpoints ────────────────────────────────────────────
87
- # Endpoints entered in the web UI are kept in-memory only: they are never
88
- # written to disk and disappear when the app process restarts. They are
89
- # layered on top of the env-var endpoints below, so both are available and
90
- # a UI-added endpoint with the same name as an env one takes precedence.
91
- _session_endpoints: dict[str, EndpointConfig] = {}
92
- # Guards the registry above — Gradio serves events from a thread pool, so
93
- # concurrent visitors may register/clear endpoints at the same time.
94
- _session_lock = threading.Lock()
95
-
96
-
97
- def register_endpoint(
98
- name: str,
99
- provider: str = "openai",
100
- api_key: str = "",
101
- base_url: Optional[str] = None,
102
- model: str = "",
103
- ) -> EndpointConfig:
104
- """Register (or replace) an endpoint added at runtime via the UI.
105
-
106
- Validation is strict so a review never runs on a half-configured entry:
107
-
108
- * ``name`` and ``model`` are required
109
- * ``api_key`` is required (use a placeholder such as ``dummy`` for
110
- keyless local servers like Ollama)
111
- * ``provider`` must be one of :data:`SUPPORTED_PROVIDERS`
112
-
113
- Returns the stored :class:`EndpointConfig`. Re-registering the same
114
- name overwrites the previous entry.
115
- """
116
- name = (name or "").strip()
117
- provider = (provider or "openai").strip().lower()
118
- model = (model or "").strip()
119
- api_key = (api_key or "").strip()
120
- base_url = (base_url or "").strip() or None
121
-
122
- if not name:
123
- raise ValueError("Endpoint name is required.")
124
- if not model:
125
- raise ValueError("Model name is required.")
126
- if not api_key:
127
- raise ValueError("API key is required (use 'dummy' for keyless local servers).")
128
- if provider not in SUPPORTED_PROVIDERS:
129
- raise ValueError(
130
- f"Unsupported type {provider!r} — use one of {SUPPORTED_PROVIDERS}."
131
- )
132
-
133
- cfg = EndpointConfig(
134
- name=name,
135
- provider=provider,
136
- api_key=api_key,
137
- base_url=base_url,
138
- model=model,
139
- )
140
- with _session_lock:
141
- if name in _scan_env_endpoints_by_name() or any(
142
- ep.name == name for ep in builtin_endpoints()
143
- ):
144
- logger.warning(
145
- "Session endpoint %r shadows an existing endpoint "
146
- "(OCR_ENDPOINT_* env or built-in) with the same name for "
147
- "the rest of this process.",
148
- name,
149
- )
150
- _session_endpoints[name] = cfg
151
- logger.info("Registered session endpoint %r (%s / %s)", name, provider, model)
152
- return cfg
153
-
154
-
155
- def clear_session_endpoints() -> None:
156
- """Remove every endpoint that was added at runtime via the UI."""
157
- with _session_lock:
158
- _session_endpoints.clear()
159
-
160
- def unregister_endpoint(name: str) -> None:
161
- """Remove one ephemeral user endpoint and its API key from memory."""
162
- with _session_lock:
163
- _session_endpoints.pop(name, None)
164
-
165
-
166
- def session_endpoints() -> list[EndpointConfig]:
167
- """Endpoints added at runtime via the UI (env-var ones excluded)."""
168
- with _session_lock:
169
- return list(_session_endpoints.values())
170
-
171
-
172
- def _scan_env_endpoints() -> list[EndpointConfig]:
173
- """Scan the environment for ``OCR_ENDPOINT_<n>_*`` configs.
174
-
175
- Each index is read independently. An endpoint is registered only when
176
- it has at least a name and a model (the API key is required to actually
177
- build a client, but a key-less entry is still listed so the UI can show
178
- \"missing key\"). Entries are returned sorted by index.
179
- """
180
- groups: dict[int, dict[str, str]] = {}
181
- for env_key, value in os.environ.items():
182
- if not env_key.startswith(ENDPOINT_ENV_PREFIX):
183
- continue
184
- rest = env_key[len(ENDPOINT_ENV_PREFIX):]
185
- if "_" not in rest:
186
- continue
187
- idx_str, attr = rest.split("_", 1)
188
- if not idx_str.isdigit():
189
- continue
190
- groups.setdefault(int(idx_str), {})[attr.lower()] = value.strip()
191
-
192
- endpoints: list[EndpointConfig] = []
193
- for idx in sorted(groups):
194
- g = groups[idx]
195
- name = g.get("name") or f"endpoint-{idx}"
196
- if not g.get("model"):
197
- # Incomplete config — skip (must at least have a model)
198
- continue
199
- endpoints.append(
200
- EndpointConfig(
201
- index=idx,
202
- name=name,
203
- provider=g.get("type") or g.get("provider") or "openai",
204
- api_key=g.get("api_key") or "",
205
- base_url=g.get("base_url") or None,
206
- model=g.get("model") or "",
207
- )
208
- )
209
- return endpoints
210
-
211
-
212
- def _scan_env_endpoints_by_name() -> dict[str, EndpointConfig]:
213
- """Env endpoints keyed by name (helper for collision checks)."""
214
- return {ep.name: ep for ep in _scan_env_endpoints()}
215
-
216
-
217
- def builtin_endpoints() -> list[EndpointConfig]:
218
- """The always-available built-in providers (Gemini, Grok).
219
-
220
- These are surfaced as selectable endpoints so the UI/CLI can choose
221
- explicitly between them. They read their keys from the standard
222
- ``GEMINI_API_KEY`` / ``GROQ_API_KEY`` env vars and run on the same
223
- models as the default (no-endpoint) path.
224
- """
225
- from llm_factory import GEMINI_MODEL, GROQ_MODEL
226
-
227
- return [
228
- EndpointConfig(
229
- name="Gemini",
230
- provider="google",
231
- api_key=os.environ.get("GEMINI_API_KEY", "").strip(),
232
- model=GEMINI_MODEL,
233
- builtin=True,
234
- ),
235
- EndpointConfig(
236
- name="Grok",
237
- provider="openai",
238
- api_key=os.environ.get("GROQ_API_KEY", "").strip(),
239
- base_url="https://api.groq.com/openai/v1",
240
- model=GROQ_MODEL,
241
- builtin=True,
242
- ),
243
- ]
244
-
245
-
246
- def discover_endpoints() -> list[EndpointConfig]:
247
- """All available endpoints: built-ins + env-var configs + UI-added ones.
248
-
249
- Precedence on name collision: UI-added (session) > env-var > built-in.
250
- Entries are returned sorted by name.
251
- """
252
- merged: dict[str, EndpointConfig] = {
253
- ep.name: ep for ep in builtin_endpoints()
254
- }
255
- merged.update(_scan_env_endpoints_by_name())
256
- with _session_lock:
257
- for ep in _session_endpoints.values():
258
- merged[ep.name] = ep
259
- return [merged[k] for k in sorted(merged)]
260
-
261
-
262
- def get_endpoint(name: str | None) -> Optional[EndpointConfig]:
263
- """Return the endpoint whose name matches, or ``None``.
264
-
265
- Resolution order: UI-added (session) → env-var → built-in.
266
- """
267
- if not name:
268
- return None
269
- with _session_lock:
270
- session_ep = _session_endpoints.get(name)
271
- if session_ep is not None:
272
- return session_ep
273
- env_ep = _scan_env_endpoints_by_name().get(name)
274
- if env_ep is not None:
275
- return env_ep
276
- return next((b for b in builtin_endpoints() if b.name == name), None)
277
-
278
-
279
- def dropdown_choices() -> list[str | tuple[str, list[str]]]:
280
- """Choices for the UI dropdown.
281
-
282
- Built-in providers (Gemini, Grok) appear under a ``"Built-in"``
283
- optgroup so the user can pick a *section* for them. Custom endpoints
284
- are listed as flat entries under their own specified name — NOT grouped
285
- under a "Custom" header — so an added endpoint is immediately
286
- identifiable by name in the list. An empty string entry keeps the
287
- "auto" (no-endpoint) option first.
288
-
289
- A built-in is omitted from its group when a custom endpoint shadows it
290
- by name (session > env > built-in precedence), so each name appears
291
- exactly once.
292
- """
293
- custom_names = [
294
- ep.name for ep in discover_endpoints() if not ep.builtin
295
- ]
296
- builtin_names = [
297
- ep.name for ep in builtin_endpoints()
298
- if ep.name not in custom_names
299
- ]
300
- choices: list = [""]
301
- if builtin_names:
302
- choices.append(("Built-in", builtin_names))
303
- # Custom endpoints appear as their own named entries (flat), so the
304
- # user sees e.g. "DeepSeek V4" instead of a generic "Custom" group.
305
- choices.extend(custom_names)
306
- return choices
 
1
+ """Backward-compatible import path for model endpoint configuration."""
2
+ import sys as _sys
3
+ from backend.integrations import endpoints as _implementation
4
 
5
+ _sys.modules[__name__] = _implementation
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eval_data/evaluate.py CHANGED
@@ -50,9 +50,9 @@ from langgraph.types import Command
50
  # Add project root to sys.path so we can import graph/state
51
  sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
52
 
53
- from graph import build_graph
54
- from observability import langfuse_trace, _resolve_langfuse_trace_id
55
- from state import ChangedFile, Finding
56
 
57
  logger = logging.getLogger(__name__)
58
 
@@ -594,7 +594,7 @@ def _log_to_observability(results: list[dict]) -> None:
594
 
595
  This function is called only when ``--log-to-observability`` is passed.
596
  """
597
- from observability import (
598
  is_langfuse_enabled,
599
  is_langsmith_enabled,
600
  log_langfuse_score,
 
50
  # Add project root to sys.path so we can import graph/state
51
  sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
52
 
53
+ from backend.graph import build_graph
54
+ from backend.observability import langfuse_trace, _resolve_langfuse_trace_id
55
+ from backend.state import ChangedFile, Finding
56
 
57
  logger = logging.getLogger(__name__)
58
 
 
594
 
595
  This function is called only when ``--log-to-observability`` is passed.
596
  """
597
+ from backend.observability import (
598
  is_langfuse_enabled,
599
  is_langsmith_enabled,
600
  log_langfuse_score,
eval_data/ragas_eval.py CHANGED
@@ -31,8 +31,16 @@ import logging
31
  import os
32
  import threading
33
  import time
 
 
34
  from typing import Any, Optional
35
 
 
 
 
 
 
 
36
  logger = logging.getLogger(__name__)
37
 
38
  # ─── Lazy RAGAS imports with graceful fallback ──────────────────────────────
@@ -197,8 +205,8 @@ def _get_evaluator_llm(endpoint: Optional[str] = None):
197
 
198
  try:
199
  if endpoint:
200
- from llm_factory import create_llm
201
- from endpoints import EndpointConfig, get_endpoint
202
  configured = endpoint if isinstance(endpoint, EndpointConfig) else get_endpoint(endpoint)
203
  timeout = 15
204
  if configured and not getattr(configured, "builtin", False) and configured.provider not in {"google", "anthropic"}:
@@ -210,7 +218,7 @@ def _get_evaluator_llm(endpoint: Optional[str] = None):
210
  logger.info("RAGAS evaluator: using selected custom endpoint")
211
  return _wrap_evaluator(llm)
212
 
213
- from llm_factory import _get_groq_chat, _get_gemini_chat
214
 
215
  # Keep evaluation bounded: RAGAS runs several provider calls and
216
  # retrying each one can otherwise hold a review open for minutes.
@@ -497,7 +505,7 @@ def log_ragas_scores_to_langfuse(
497
  Handler from the current review run, used to link scores to the trace.
498
  """
499
  try:
500
- from observability import log_langfuse_score
501
  except ImportError:
502
  logger.debug("observability module not available — skipping Langfuse")
503
  return
 
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 ──────────────────────────────
 
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
  timeout = 15
212
  if configured and not getattr(configured, "builtin", False) and configured.provider not in {"google", "anthropic"}:
 
218
  logger.info("RAGAS evaluator: using selected custom endpoint")
219
  return _wrap_evaluator(llm)
220
 
221
+ from backend.integrations.llm_factory import _get_groq_chat, _get_gemini_chat
222
 
223
  # Keep evaluation bounded: RAGAS runs several provider calls and
224
  # retrying each one can otherwise hold a review open for minutes.
 
505
  Handler from the current review run, used to link scores to the trace.
506
  """
507
  try:
508
+ from backend.observability import log_langfuse_score
509
  except ImportError:
510
  logger.debug("observability module not available — skipping Langfuse")
511
  return
github_client.py CHANGED
@@ -1,178 +1,5 @@
1
- #!/usr/bin/env python3
2
- """Shared GitHub API client with automatic token resolution and 401 resilience.
 
3
 
4
- Caching
5
- -------
6
- All HTTP requests made through ``requests`` within this process are cached
7
- to a local SQLite backend with a 15-minute TTL, so re-reviewing the same PR
8
- does not re-fetch data from GitHub.
9
-
10
- Usage
11
- -----
12
- from github_client import GitHubSession, resolve_token, guard_401
13
-
14
- # Preferred: use the session for all API calls
15
- session = GitHubSession()
16
- resp = session.get("https://api.github.com/repos/psf/requests")
17
-
18
- # Decorator for standalone functions
19
- @guard_401
20
- def my_api_call():
21
- ...
22
- """
23
-
24
- from __future__ import annotations
25
-
26
- import functools
27
- import logging
28
- import os
29
- from typing import Optional
30
-
31
- import keyring
32
- import requests
33
-
34
- logger = logging.getLogger(__name__)
35
-
36
- SERVICE_NAME = "opencodereview"
37
-
38
- # ─── Global HTTP cache ─────────────────────────────────────────────────────────
39
- # Cache all requests (GitHub API + raw content) to a local SQLite store
40
- # so re-reviewing the same PR avoids redundant network fetches.
41
- _CACHE_BACKEND = None
42
-
43
-
44
- def _init_cache() -> None:
45
- """Install ``requests-cache`` with a 15-minute TTL.
46
-
47
- Patches ``requests.Session`` globally, so :class:`GitHubSession`
48
- (which inherits from it) automatically gets caching. Safe to call
49
- multiple times — subsequent calls are no-ops.
50
- """
51
- global _CACHE_BACKEND
52
- if _CACHE_BACKEND is not None:
53
- return
54
- try:
55
- import requests_cache
56
-
57
- cache_dir = os.environ.get(
58
- "OPENCODEREVIEW_CACHE_DIR",
59
- os.path.join(os.getcwd(), ".opencodereview"),
60
- )
61
- os.makedirs(cache_dir, exist_ok=True)
62
- db_path = os.path.join(cache_dir, "http_cache.sqlite")
63
- _CACHE_BACKEND = requests_cache.install_cache(
64
- cache_name=db_path,
65
- backend="sqlite",
66
- expire_after=900, # 15 minutes
67
- allowable_codes=(200, 404),
68
- )
69
- logger.debug("HTTP cache initialised at %s", db_path)
70
- except ImportError:
71
- logger.debug("requests-cache not installed — skipping HTTP cache")
72
- except Exception as exc:
73
- logger.warning("Failed to initialise HTTP cache: %s", exc)
74
-
75
-
76
- # ─── Exceptions ──────────────────────────────────────────────────────────────
77
-
78
-
79
- class TokenRevokedError(Exception):
80
- """Raised when a GitHub API call returns 401 (token invalid or revoked)."""
81
-
82
-
83
- # ─── Token resolution ───────────────────────────────────────────────────────
84
-
85
-
86
- def resolve_token() -> Optional[str]:
87
- """Return a GitHub token from:
88
-
89
- 1. The system keyring (set via ``opencodereview auth login``)
90
- 2. The ``GITHUB_TOKEN`` environment variable
91
-
92
- Returns ``None`` if neither source has a token, so callers can fall back
93
- gracefully (e.g., dry-run mode in the executor).
94
- """
95
- # Try keyring first (auth login stores here)
96
- try:
97
- token = keyring.get_password(SERVICE_NAME, "github_token")
98
- if token:
99
- return token
100
- except Exception:
101
- pass # keyring back-end unavailable (headless CI, etc.)
102
-
103
- # Fall back to env var
104
- token = os.environ.get("GITHUB_TOKEN")
105
- return token.strip() if token else None
106
-
107
-
108
- # ─── 401 decorator ──────────────────────────────────────────────────────────
109
-
110
-
111
- def guard_401(func):
112
- """Decorator: catch 401 responses from GitHub API calls and raise
113
- :class:`TokenRevokedError` with a helpful message.
114
-
115
- Use this on any standalone function that makes GitHub API calls and
116
- calls ``raise_for_status()``.
117
-
118
- For functions that use :class:`GitHubSession` the 401 handling happens
119
- automatically — no decorator needed.
120
- """
121
- @functools.wraps(func)
122
- def wrapper(*args, **kwargs):
123
- try:
124
- return func(*args, **kwargs)
125
- except requests.HTTPError as exc:
126
- if exc.response is not None and exc.response.status_code == 401:
127
- raise TokenRevokedError(
128
- "Your GitHub token appears to be invalid or has been "
129
- "revoked.\n\n"
130
- " Re-authenticate:\n"
131
- " opencodereview auth login\n\n"
132
- " Or update the GITHUB_TOKEN environment variable.\n"
133
- ) from exc
134
- raise
135
- return wrapper
136
-
137
-
138
- # ─── Custom Session ─────────────────────────────────────────────────────────
139
-
140
-
141
- class GitHubSession(requests.Session):
142
- """A :class:`requests.Session` subclass that:
143
-
144
- * Auto-resolves the GitHub token from keyring then env var
145
- * Sends ``Authorization`` and standard headers on every request
146
- * Raises :class:`TokenRevokedError` on ``401`` responses from
147
- ``api.github.com``
148
-
149
- Usage
150
- -----
151
- session = GitHubSession()
152
- resp = session.get("https://api.github.com/repos/psf/requests")
153
- """
154
-
155
- def __init__(self, token: Optional[str] = None) -> None:
156
- super().__init__()
157
- self.token = token or resolve_token()
158
- self.headers.update({
159
- "Accept": "application/vnd.github.v3+json",
160
- "User-Agent": "OpenCodeReview/1.0",
161
- })
162
- if self.token:
163
- self.headers["Authorization"] = f"Bearer {self.token}"
164
-
165
- def request(self, method, url, *args, **kwargs):
166
- """Override :meth:`requests.Session.request` to intercept 401
167
- responses from ``api.github.com``."""
168
- resp = super().request(method, url, *args, **kwargs)
169
- # Only intercept 401 from the GitHub API, not raw content or other hosts
170
- if resp.status_code == 401 and "api.github.com" in url:
171
- raise TokenRevokedError(
172
- "Your GitHub token appears to be invalid or has been "
173
- "revoked.\n\n"
174
- " Re-authenticate:\n"
175
- " opencodereview auth login\n\n"
176
- " Or update the GITHUB_TOKEN environment variable.\n"
177
- )
178
- return resp
 
1
+ """Backward-compatible import path for GitHub API helpers."""
2
+ import sys as _sys
3
+ from backend.integrations import github_client as _implementation
4
 
5
+ _sys.modules[__name__] = _implementation
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
graph.py CHANGED
@@ -1,108 +1,5 @@
1
- from __future__ import annotations
 
 
2
 
3
- import logging
4
- import sqlite3
5
-
6
- from langgraph.checkpoint.serde.jsonplus import JsonPlusSerializer
7
- from langgraph.checkpoint.sqlite import SqliteSaver
8
- from langgraph.graph import END, START, StateGraph
9
-
10
- from nodes import (
11
- aggregator_node,
12
- correctness_reviewer_node,
13
- executor_node,
14
- human_approval_node,
15
- ingestion_node,
16
- retrieval_node,
17
- security_reviewer_node,
18
- test_coverage_reviewer_node,
19
- )
20
- from state import OpenCodeReviewState
21
-
22
- logger = logging.getLogger(__name__)
23
-
24
-
25
- def build_graph(db_path: str | None = None) -> StateGraph:
26
- """Build and compile the OpenCodeReview graph with SqliteSaver checkpointing.
27
-
28
- When *db_path* is ``None`` an in-memory SQLite database is used so file
29
- I/O is avoided — ideal for ephemeral CLI runs. Pass a file path to keep
30
- checkpoints across process restarts (needed by the Gradio UI which may
31
- resume after page reload).
32
-
33
- Topology:
34
-
35
- START → ingestion → retrieval
36
- │
37
- ┌─────────────┼─────────────┐
38
- ▼ ▼ ▼
39
- correctness security test_coverage
40
- │ │ │
41
- └─────────────┼─────────────┘
42
- ▼
43
- aggregator
44
- │
45
- ▼
46
- human_approval ←── interrupt() pauses here
47
- │
48
- ▼
49
- executor
50
- ┌────┴────┐
51
- ┌────────▼─▼────────┐
52
- │ Inline review │
53
- │ comments at file │
54
- │ /line positions │
55
- │ 422 → issue cmt │
56
- └────────┬─┬────────┘
57
- │
58
- END
59
- """
60
- builder = StateGraph(OpenCodeReviewState)
61
-
62
- # -- Nodes ----------------------------------------------------------------
63
- builder.add_node("ingestion", ingestion_node)
64
- builder.add_node("retrieval", retrieval_node)
65
- builder.add_node("correctness_review", correctness_reviewer_node)
66
- builder.add_node("security_review", security_reviewer_node)
67
- builder.add_node("test_coverage_review", test_coverage_reviewer_node)
68
- builder.add_node("aggregator", aggregator_node)
69
- builder.add_node("human_approval", human_approval_node)
70
- builder.add_node("executor", executor_node)
71
-
72
- # -- Linear prefix --------------------------------------------------------
73
- builder.add_edge(START, "ingestion")
74
- builder.add_edge("ingestion", "retrieval")
75
-
76
- # -- Fan-out: retrieval → all three reviewers in parallel -----------------
77
- builder.add_edge("retrieval", "correctness_review")
78
- builder.add_edge("retrieval", "security_review")
79
- builder.add_edge("retrieval", "test_coverage_review")
80
-
81
- # -- Fan-in: all three reviewers → aggregator -----------------------------
82
- builder.add_edge("correctness_review", "aggregator")
83
- builder.add_edge("security_review", "aggregator")
84
- builder.add_edge("test_coverage_review", "aggregator")
85
-
86
- # -- HITL + posting -------------------------------------------------------
87
- builder.add_edge("aggregator", "human_approval")
88
- builder.add_edge("human_approval", "executor")
89
- builder.add_edge("executor", END)
90
-
91
- # -- Checkpointer (required for interrupt/resume to work) -----------------
92
- serde = JsonPlusSerializer(allowed_msgpack_modules=[
93
- ("state", "ChangedFile"),
94
- ("state", "ContextChunk"),
95
- ("state", "Severity"),
96
- ("state", "Finding"),
97
- ("state", "Verdict"),
98
- ])
99
-
100
- resolved_path: str = db_path if db_path is not None else ":memory:"
101
- conn = sqlite3.connect(resolved_path, check_same_thread=False)
102
- saver = SqliteSaver(conn, serde=serde)
103
-
104
- compiled = builder.compile(checkpointer=saver)
105
- # Expose the connection so callers can close it once the graph run is
106
- # fully finished (prevents file-handle leaks in the long-running UI).
107
- compiled._opencodereview_conn = conn
108
- return compiled
 
1
+ """Backward-compatible import path for the LangGraph workflow."""
2
+ import sys as _sys
3
+ from backend import graph as _implementation
4
 
5
+ _sys.modules[__name__] = _implementation
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
llm_factory.py CHANGED
@@ -1,273 +1,5 @@
1
- """LLM factory — creates LangChain chat models with primary + fallback support.
 
 
2
 
3
- Priority
4
- --------
5
- 1. **Google Gemini** (primary) — uses ``GEMINI_API_KEY`` env var.
6
- Model: ``gemini-3.1-flash-lite`` — generous free tier.
7
- 2. **Groq** (fallback) — uses ``GROQ_API_KEY`` env var.
8
- Model: ``llama-3.3-70b-versatile`` — fast inference, lower free limit.
9
-
10
- If neither key is set, functions raise ``ValueError`` so callers can skip
11
- gracefully (as they already do for Groq-only today).
12
- """
13
-
14
- from __future__ import annotations
15
-
16
- import logging
17
- import os
18
- from typing import Any, Optional
19
-
20
- logger = logging.getLogger(__name__)
21
-
22
- # Gemini 3.1 Flash model name as of 2026-07
23
- # Verified via Google AI documentation: gemini-3.1-flash-lite is the correct name.
24
- # The base 'gemini-3.1-flash' does not exist in the API.
25
- GEMINI_MODEL = "gemini-3.1-flash-lite"
26
- GROQ_MODEL = os.getenv("GROQ_MODEL", "openai/gpt-oss-20b")
27
- DEFAULT_TEMPERATURE = 0.0
28
- DEFAULT_REQUEST_TIMEOUT = float(os.getenv("OCR_MODEL_TIMEOUT_SECONDS", "60"))
29
- DEFAULT_OUTPUT_TOKENS = int(os.getenv("OCR_MODEL_MAX_OUTPUT_TOKENS", "2000"))
30
-
31
-
32
- def _get_gemini_chat(**kwargs: Any) -> Optional[Any]:
33
- """Create a ``ChatGoogleGenerativeAI`` instance if ``GEMINI_API_KEY`` is set.
34
-
35
- Returns ``None`` silently when the key is missing or the package is not
36
- installed — callers are expected to fall back.
37
- """
38
- kwargs.setdefault("timeout", DEFAULT_REQUEST_TIMEOUT)
39
- kwargs.setdefault("max_retries", 0)
40
- kwargs.setdefault("max_tokens", DEFAULT_OUTPUT_TOKENS)
41
- api_key = os.environ.get("GEMINI_API_KEY", "").strip()
42
- if not api_key:
43
- return None
44
-
45
- try:
46
- from langchain_google_genai import ChatGoogleGenerativeAI
47
-
48
- return ChatGoogleGenerativeAI(
49
- model=kwargs.pop("model", GEMINI_MODEL),
50
- temperature=kwargs.pop("temperature", DEFAULT_TEMPERATURE),
51
- google_api_key=api_key,
52
- **kwargs,
53
- )
54
- except ImportError:
55
- logger.warning("langchain-google-genai not installed — skipping Gemini")
56
- return None
57
- except Exception as exc:
58
- logger.warning("Failed to initialise Gemini: %s", exc)
59
- return None
60
-
61
-
62
- def _get_groq_chat(**kwargs: Any) -> Optional[Any]:
63
- """Create a ``ChatGroq`` instance if ``GROQ_API_KEY`` is set."""
64
- kwargs.setdefault("timeout", DEFAULT_REQUEST_TIMEOUT)
65
- kwargs.setdefault("max_retries", 0)
66
- kwargs.setdefault("max_tokens", DEFAULT_OUTPUT_TOKENS)
67
- api_key = os.environ.get("GROQ_API_KEY", "").strip()
68
- if not api_key:
69
- return None
70
-
71
- try:
72
- from langchain_groq import ChatGroq
73
-
74
- return ChatGroq(
75
- model=kwargs.pop("model", GROQ_MODEL),
76
- temperature=kwargs.pop("temperature", DEFAULT_TEMPERATURE),
77
- api_key=api_key,
78
- **kwargs,
79
- )
80
- except ImportError:
81
- logger.warning("langchain-groq not installed")
82
- return None
83
- except Exception as exc:
84
- logger.warning("Failed to initialise Groq: %s", exc)
85
- return None
86
-
87
-
88
- def create_endpoint_llm(endpoint, **kwargs: Any) -> Any:
89
- """Create a chat model from a user-configured custom endpoint.
90
-
91
- Supports OpenAI-compatible APIs (DeepSeek, OpenRouter, vLLM, Ollama,
92
- Groq, Together, ...), Anthropic Claude, and Google Gemini.
93
-
94
- Parameters
95
- ----------
96
- endpoint : EndpointConfig
97
- The user's endpoint config (name, provider, api_key, base_url, model).
98
- **kwargs
99
- Passed through to the underlying LangChain constructor (e.g.
100
- ``temperature``). ``model`` / ``api_key`` / ``base_url`` come from
101
- the endpoint and cannot be overridden here.
102
-
103
- Returns
104
- -------
105
- Any
106
- A LangChain chat model instance (``ChatOpenAI``, ``ChatAnthropic``
107
- or ``ChatGoogleGenerativeAI``).
108
-
109
- Raises
110
- ------
111
- ValueError
112
- If the endpoint's provider package is not installed or the config
113
- is incomplete.
114
- """
115
- if not endpoint.api_key or not endpoint.model:
116
- raise ValueError(
117
- f"Endpoint '{endpoint.name}' is missing an API key or model name."
118
- )
119
-
120
- kwargs.setdefault("timeout", DEFAULT_REQUEST_TIMEOUT)
121
- kwargs.setdefault("max_retries", 0)
122
- kwargs.setdefault("max_tokens", DEFAULT_OUTPUT_TOKENS)
123
- provider = endpoint.provider
124
- model = endpoint.model
125
- # MiniMax M3.1 requires reasoning and OpenRouter defaults to max effort.
126
- # Reserve room for reasoning + visible JSON rather than truncating at 1200.
127
- if 'minimax-m3.1' in model.lower():
128
- kwargs['max_tokens'] = max(int(kwargs.get('max_tokens') or 0), 8192)
129
- if endpoint.base_url and 'openrouter.ai' in endpoint.base_url:
130
- extra = dict(kwargs.get('extra_body') or {})
131
- extra['reasoning'] = {'effort': 'low'}
132
- kwargs['extra_body'] = extra
133
- temperature = kwargs.pop("temperature", DEFAULT_TEMPERATURE)
134
-
135
- if provider == "anthropic":
136
- try:
137
- from langchain_anthropic import ChatAnthropic
138
- except ImportError:
139
- raise ValueError(
140
- "langchain-anthropic is not installed — cannot use endpoint "
141
- f"'{endpoint.name}'. Run: pip install langchain-anthropic"
142
- ) from None
143
- params: dict[str, Any] = {
144
- "model": model,
145
- "api_key": endpoint.api_key,
146
- "temperature": temperature,
147
- }
148
- if endpoint.base_url:
149
- params["base_url"] = endpoint.base_url
150
- params.update(kwargs)
151
- return ChatAnthropic(**params)
152
-
153
- if provider == "google":
154
- try:
155
- from langchain_google_genai import ChatGoogleGenerativeAI
156
- except ImportError:
157
- raise ValueError(
158
- "langchain-google-genai is not installed — cannot use endpoint "
159
- f"'{endpoint.name}'. Run: pip install langchain-google-genai"
160
- ) from None
161
- params = {
162
- "model": model,
163
- "google_api_key": endpoint.api_key,
164
- "temperature": temperature,
165
- }
166
- params.update(kwargs)
167
- return ChatGoogleGenerativeAI(**params)
168
-
169
- # Default: OpenAI-compatible
170
- try:
171
- from langchain_openai import ChatOpenAI
172
- except ImportError:
173
- raise ValueError(
174
- "langchain-openai is not installed — cannot use endpoint "
175
- f"'{endpoint.name}'. Run: pip install langchain-openai"
176
- ) from None
177
- params = {
178
- "model": model,
179
- "api_key": endpoint.api_key,
180
- "temperature": temperature,
181
- }
182
- if endpoint.base_url:
183
- params["base_url"] = endpoint.base_url
184
- params.update(kwargs)
185
- return ChatOpenAI(**params)
186
-
187
-
188
- def create_llm(endpoint=None, **kwargs: Any) -> Any:
189
- """Create a chat LLM — custom endpoint first, else Gemini → Groq.
190
-
191
- Parameters
192
- ----------
193
- endpoint : EndpointConfig or str or None
194
- A custom endpoint to run on (``EndpointConfig`` object or its name).
195
- ``None`` (default) falls back to the built-in providers.
196
- **kwargs
197
- Passed through to the underlying LangChain constructor.
198
- Common overrides: ``model``, ``temperature``.
199
-
200
- Returns
201
- -------
202
- Any
203
- A LangChain chat model instance (``ChatOpenAI``/``ChatAnthropic``/
204
- ``ChatGoogleGenerativeAI`` from a custom endpoint, or the built-in
205
- ``ChatGoogleGenerativeAI`` / ``ChatGroq``).
206
-
207
- Raises
208
- ------
209
- ValueError
210
- If a custom endpoint is named but not found, or no provider key is set.
211
- """
212
- if endpoint:
213
- from endpoints import EndpointConfig, get_endpoint
214
-
215
- # The browser historically sent lowercase builtin ids while the
216
- # endpoint registry uses display names. Accept both for API clients.
217
- if isinstance(endpoint, str):
218
- endpoint = {"gemini": "Gemini", "groq": "Grok"}.get(endpoint.lower(), endpoint)
219
- ep = endpoint if isinstance(endpoint, EndpointConfig) else get_endpoint(endpoint)
220
- if ep is not None:
221
- if getattr(ep, "builtin", False):
222
- # Built-in providers use their native constructors so the
223
- # behaviour is identical to the default (no-endpoint) path.
224
- if ep.name == "Gemini":
225
- llm = _get_gemini_chat(**kwargs)
226
- if llm is not None:
227
- logger.info(
228
- "Using built-in Gemini endpoint (model=%s)",
229
- kwargs.get("model", GEMINI_MODEL),
230
- )
231
- return llm
232
- raise ValueError(
233
- "Gemini selected but GEMINI_API_KEY is not set."
234
- )
235
- if ep.name == "Grok":
236
- llm = _get_groq_chat(**kwargs)
237
- if llm is not None:
238
- logger.info(
239
- "Using built-in Grok endpoint (model=%s)",
240
- kwargs.get("model", GROQ_MODEL),
241
- )
242
- return llm
243
- raise ValueError(
244
- "Grok selected but GROQ_API_KEY is not set."
245
- )
246
- try:
247
- llm = create_endpoint_llm(ep, **kwargs)
248
- logger.info("Using custom endpoint %s (%s/%s)", ep.name, ep.provider, ep.model)
249
- return llm
250
- except ValueError:
251
- raise
252
- else:
253
- raise ValueError(
254
- f"Custom endpoint '{endpoint}' not found. "
255
- "Configure it via OCR_ENDPOINT_* environment variables "
256
- "or add it in the UI."
257
- )
258
-
259
- # Prefer Groq when configured: it has a separate quota pool and avoids
260
- # stalling the review pipeline on Gemini free-tier exhaustion.
261
- llm = _get_groq_chat(**kwargs)
262
- if llm is not None:
263
- logger.debug("Using Groq (model=%s)", kwargs.get("model", GROQ_MODEL))
264
- return llm
265
-
266
- llm = _get_gemini_chat(**kwargs)
267
- if llm is not None:
268
- logger.debug("Falling back to Gemini (model=%s)", kwargs.get("model", GEMINI_MODEL))
269
- return llm
270
-
271
- raise ValueError(
272
- "No LLM available. Set GEMINI_API_KEY (primary) or GROQ_API_KEY (fallback)."
273
- )
 
1
+ """Backward-compatible import path for model provider setup."""
2
+ import sys as _sys
3
+ from backend.integrations import llm_factory as _implementation
4
 
5
+ _sys.modules[__name__] = _implementation
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
main.py CHANGED
@@ -1,592 +1,8 @@
1
- #!/usr/bin/env python3
2
- """OpenCodeReview — AI-powered PR review with human-in-the-loop approval.
3
-
4
- Usage
5
- -----
6
- opencodereview auth login
7
- opencodereview auth status
8
- opencodereview auth logout
9
- opencodereview review [--smoke]
10
- opencodereview --help
11
- """
12
-
13
- from __future__ import annotations
14
-
15
- import logging
16
- import os
17
- import sys
18
- import time
19
- import uuid
20
-
21
- import click
22
- from langgraph.types import Command
23
-
24
- from auth import auth as auth_group
25
- from config import config as config_group
26
- from graph import build_graph
27
- from observability import (
28
- build_run_metadata,
29
- enable_langsmith,
30
- get_langfuse_handler,
31
- is_langsmith_enabled,
32
- estimate_groq_cost,
33
- flush_langfuse,
34
- format_cost,
35
- langfuse_trace,
36
- log_error_to_backends,
37
- log_langfuse_score,
38
- _resolve_langfuse_trace_id,
39
- TokenCostCallback,
40
- )
41
- from state import ChangedFile, ContextChunk, Finding, Severity, Verdict
42
-
43
- logging.basicConfig(
44
- level=logging.INFO,
45
- format="%(asctime)s [%(levelname)s] %(name)s — %(message)s",
46
- )
47
- logger = logging.getLogger(__name__)
48
-
49
- DB_PATH = "checkpoints.db"
50
-
51
- NODE_LABELS: dict[str, str] = {
52
- "ingestion": "📥 Ingestion",
53
- "retrieval": "🔍 Retrieval",
54
- "correctness_review": "✅ Correctness Review",
55
- "security_review": "🔒 Security Review",
56
- "test_coverage_review": "🧪 Test Coverage Review",
57
- "aggregator": "📊 Aggregation",
58
- }
59
-
60
-
61
- # ─── Observability initialisation ──────────────────────────────────────────
62
-
63
-
64
- def _init_observability() -> None:
65
- """Initialise tracing backends and HTTP cache from env vars / keyring.
66
-
67
- Called once at the start of each ``review`` command.
68
- """
69
- from github_client import _init_cache as _init_http_cache
70
- _init_http_cache()
71
-
72
- import keyring as _kr
73
- from config import SERVICE_NAME as _svc
74
-
75
- # LangSmith: favour env var (check modern LANGSMITH_API_KEY first, then legacy)
76
- ls_key = (
77
- os.environ.get("LANGSMITH_API_KEY")
78
- or os.environ.get("LANGCHAIN_API_KEY")
79
- or _kr.get_password(_svc, "langsmith_api_key")
80
- )
81
- if ls_key:
82
- ls_project = (
83
- os.environ.get("LANGSMITH_PROJECT")
84
- or os.environ.get("LANGCHAIN_PROJECT")
85
- or _kr.get_password(_svc, "langsmith_project")
86
- or "opencodereview"
87
- )
88
- enable_langsmith(ls_key, ls_project)
89
-
90
- # Langfuse: env var overrides keyring
91
- for env_key, ring_key in [
92
- ("LANGFUSE_PUBLIC_KEY", "langfuse_public_key"),
93
- ("LANGFUSE_SECRET_KEY", "langfuse_secret_key"),
94
- ("LANGFUSE_HOST", "langfuse_host"),
95
- ]:
96
- if not os.environ.get(env_key):
97
- val = _kr.get_password(_svc, ring_key)
98
- if val:
99
- os.environ[env_key] = val
100
-
101
- if is_langsmith_enabled():
102
- logger.info("Observability: LangSmith enabled")
103
- if get_langfuse_handler():
104
- logger.info("Observability: Langfuse enabled")
105
-
106
-
107
- # ─── Synthetic payload for offline testing ──────────────────────────────────
108
-
109
- SYNTHETIC_STATE = {
110
- "repo": "demo-org/demo-repo",
111
- "pr_number": 1,
112
- "diff": (
113
- "diff --git a/src/auth.py b/src/auth.py\n"
114
- "index abc123..def456 100644\n"
115
- "--- a/src/auth.py\n"
116
- "+++ b/src/auth.py\n"
117
- "@@ -42,7 +42,9 @@ def login(username, password):\n"
118
- " user = db.get_user(username)\n"
119
- "- if user.password == password:\n"
120
- "+ if constant_time_compare(password, user.password):\n"
121
- " return create_session(user)\n"
122
- " return None\n"
123
- ),
124
- "changed_files": [
125
- ChangedFile(
126
- path="src/auth.py",
127
- status="modified",
128
- content="def login(username, password):\n"
129
- " user = db.get_user(username)\n"
130
- " if constant_time_compare(password, user.password):\n"
131
- " return create_session(user)\n"
132
- " return None\n",
133
- diff_hunk="@@ -42,7 +42,9 @@ def login(username, password): ...",
134
- ),
135
- ],
136
- "context_chunks": [
137
- ContextChunk(
138
- source="codebase", file_path="src/db.py",
139
- content="def get_user(username): ...",
140
- relevance_score=0.92,
141
- ),
142
- ],
143
- "findings": [
144
- Finding(
145
- file_path="src/auth.py", line_start=42, line_end=50,
146
- severity=Severity.CRITICAL, category="security",
147
- comment="Use constant-time comparison for passwords.",
148
- confidence=0.95,
149
- ),
150
- ],
151
- "verdict": Verdict(
152
- summary="Critical security vulnerability found.",
153
- approved=False, overall_score=3.5, critical_count=1,
154
- high_count=0, recommendation="block",
155
- ),
156
- }
157
-
158
-
159
- # ─── Review Command ───────────────���─────────────────────────────────────────
160
-
161
-
162
- @click.command()
163
- @click.option(
164
- "--smoke", is_flag=True,
165
- help="Non-interactive smoke test (skips HITL prompt).",
166
- )
167
- @click.option(
168
- "--repo",
169
- default="demo-org/demo-repo",
170
- show_default=True,
171
- help="GitHub repository (owner/name).",
172
- )
173
- @click.option(
174
- "--pr", "pr_number",
175
- default=1,
176
- show_default=True,
177
- help="Pull request number.",
178
- )
179
- @click.option(
180
- "--endpoint", "endpoint_name",
181
- default="",
182
- show_default=True,
183
- help="LLM endpoint: Gemini/Grok (built-ins) or a custom name (see OCR_ENDPOINT_* env vars).",
184
- )
185
- def review(repo: str, pr_number: int, smoke: bool, endpoint_name: str) -> None:
186
- """Run a PR review with human-in-the-loop approval.
187
-
188
- By default this runs with a synthetic PR payload for demonstration.
189
- """
190
- # ── Enable LangSmith if key is available ─────────────────────────
191
- _init_observability()
192
-
193
- graph = build_graph(DB_PATH)
194
-
195
- try:
196
- if smoke:
197
- _test_offline(graph)
198
- else:
199
- _run_with_hitl(graph, repo, pr_number, endpoint_name)
200
- finally:
201
- # Close the graph's SQLite connection (checkpoints persist to disk,
202
- # so a later resume can open a fresh one) and clean up the DB file.
203
- conn = getattr(graph, "_opencodereview_conn", None)
204
- if conn:
205
- conn.close()
206
- _cleanup_db()
207
- # Ship any queued Langfuse scores before the process exits.
208
- flush_langfuse()
209
-
210
-
211
- def _run_with_hitl(graph, repo: str, pr_number: int, endpoint_name: str = "") -> None:
212
- """Run the graph on a real PR — fetches data from GitHub, pauses for
213
- human approval, then posts findings back as PR comments.
214
-
215
- Parameters
216
- ----------
217
- endpoint_name : str
218
- Optional custom LLM endpoint name (``OCR_ENDPOINT_*``) to run the
219
- reviewers on. Empty string uses the built-in default provider.
220
- """
221
- thread_id = str(uuid.uuid4())
222
- trace_name = f"opencodereview/review/{repo}#{pr_number}"
223
- tags = ["cli", repo]
224
- prompt_versions = {
225
- "correctness": "v1",
226
- "security": "v1",
227
- "test_coverage": "v1",
228
- "aggregator": "v1",
229
- }
230
- cost_tracker = TokenCostCallback()
231
- metadata = build_run_metadata(
232
- source="cli", repo=repo, pr_number=pr_number,
233
- session_id=thread_id,
234
- prompt_versions=prompt_versions,
235
- )
236
- config: dict = {
237
- "configurable": {"thread_id": f"hitl-{thread_id}"},
238
- "metadata": metadata,
239
- }
240
-
241
- # Use synthetic demo data by default; only fetch real PRs when the
242
- # user explicitly provides a custom repo or PR number.
243
- is_default = (repo == "demo-org/demo-repo" and pr_number == 1)
244
- if is_default:
245
- logger.info(
246
- "Using synthetic demo data — pass --repo and --pr to "
247
- "review a real PR from GitHub.\n"
248
- )
249
- initial_state = SYNTHETIC_STATE
250
- else:
251
- logger.info(
252
- "Starting review of %s#%d … fetching PR data from GitHub.\n",
253
- repo, pr_number,
254
- )
255
- initial_state = {
256
- "repo": repo,
257
- "pr_number": pr_number,
258
- }
259
- if endpoint_name:
260
- initial_state["endpoint"] = endpoint_name
261
-
262
- with langfuse_trace(
263
- trace_name=trace_name,
264
- tags=tags,
265
- session_id=thread_id,
266
- metadata={
267
- "source": "cli",
268
- "repo": repo,
269
- "pr_number": pr_number,
270
- "prompt_versions": prompt_versions,
271
- },
272
- ) as handler:
273
- callbacks = [cost_tracker]
274
- if handler:
275
- callbacks.append(handler)
276
- config["callbacks"] = callbacks
277
-
278
- t0 = time.time()
279
- for event in graph.stream(initial_state, config):
280
- for node_name in event:
281
- label = NODE_LABELS.get(node_name, node_name)
282
- logger.info(" ✔ %s (+%.1fs)", label, time.time() - t0)
283
- logger.info(" ─── Pipeline complete in %.1fs ───", time.time() - t0)
284
-
285
- state = graph.get_state(config)
286
- tasks = state.tasks
287
-
288
- if tasks:
289
- logger.info("\n" + "=" * 60)
290
- logger.info(" REVIEW RESULTS — HUMAN APPROVAL REQUIRED")
291
- logger.info("=" * 60)
292
-
293
- if state.values.get("verdict"):
294
- v = state.values["verdict"]
295
- logger.info(" Verdict: %s", v.recommendation.upper())
296
- logger.info(" Score: %.1f/10", v.overall_score)
297
- logger.info(" Summary: %s", v.summary)
298
-
299
- final_findings = state.values.get("final_findings", [])
300
- logger.info(" Findings: %d", len(final_findings))
301
- for i, f in enumerate(final_findings, 1):
302
- logger.info(
303
- " %d. [%.0f%%] %s:%d–%d (%s)",
304
- i, f.confidence * 100, f.file_path,
305
- f.line_start, f.line_end, f.severity.value,
306
- )
307
- logger.info(" %s", f.comment[:120])
308
-
309
- # Show cost & TTFT
310
- logger.info(" %s", cost_tracker.summary())
311
-
312
- # Capture trace_id NOW (immediately after graph completes)
313
- # so it can be used after the long-running RAGAS computation.
314
- run_trace_id = _resolve_langfuse_trace_id(handler)
315
-
316
- # Log verdict score to Langfuse and update trace metadata
317
- if state.values.get("verdict"):
318
- v = state.values["verdict"]
319
- log_langfuse_score(
320
- name="verdict_score",
321
- value=v.overall_score,
322
- comment=f"{repo}#{pr_number} — {v.recommendation}: {v.summary[:100]}",
323
- trace_id=run_trace_id,
324
- handler=handler,
325
- )
326
- log_langfuse_score(
327
- name="findings_count",
328
- value=len(final_findings),
329
- comment=f"{repo}#{pr_number}",
330
- trace_id=run_trace_id,
331
- handler=handler,
332
- )
333
-
334
- # ── Compute and log RAGAS retrieval scores ─────────────────
335
- context_chunks = state.values.get("context_chunks", [])
336
- if context_chunks:
337
- try:
338
- from eval_data.ragas_eval import compute_ragas_retrieval_scores
339
-
340
- query = state.values.get("diff", "") or ""
341
- contexts = [c.content for c in context_chunks if c.content]
342
-
343
- # Build answer text from findings + verdict for
344
- # faithfulness & answer_relevancy metrics
345
- answer_lines = []
346
- for f in final_findings:
347
- answer_lines.append(
348
- f"[{f.severity.value}] {f.file_path}:{f.line_start}-{f.line_end}: {f.comment}"
349
- )
350
- if state.values.get("verdict"):
351
- v = state.values["verdict"]
352
- answer_lines.append(
353
- f"Verdict: {v.recommendation} (score={v.overall_score}/10) — {v.summary}"
354
- )
355
- answer_text = "\n".join(answer_lines) if answer_lines else None
356
-
357
- ragas_scores = compute_ragas_retrieval_scores(
358
- query=query,
359
- retrieved_contexts=contexts,
360
- answer=answer_text,
361
- endpoint=endpoint_name or None,
362
- )
363
-
364
- # Log RAGAS scores with the explicitly captured trace_id
365
- # to avoid contextvar loss during the long computation.
366
- # handler=handler is also passed as fallback resolution.
367
- for metric_name, value in ragas_scores.items():
368
- if value is None:
369
- continue
370
- log_langfuse_score(
371
- name=f"ragas_{metric_name}",
372
- value=value,
373
- comment=f"{repo}#{pr_number} — {metric_name}",
374
- trace_id=run_trace_id,
375
- handler=handler,
376
- )
377
-
378
- logger.info(
379
- " RAGAS scores logged to Langfuse: %s",
380
- " | ".join(
381
- f"{k}={v:.4f}" for k, v in ragas_scores.items()
382
- if v is not None
383
- ),
384
- )
385
- except ImportError:
386
- logger.info("RAGAS not installed — skipping RAGAS scoring (pip install ragas)")
387
- except Exception as exc:
388
- logger.warning("RAGAS scoring failed: %s", exc)
389
-
390
- logger.info("=" * 60)
391
-
392
- click.echo()
393
- click.echo("-" * 50)
394
- click.echo(" HUMAN-IN-THE-LOOP: Approve this review for posting?")
395
- click.echo("-" * 50)
396
- click.echo(" [a] Approve — post findings as GitHub comments")
397
- click.echo(" [r] Reject — discard results, post nothing")
398
- click.echo(" [q] Quit — leave graph paused")
399
- click.echo()
400
-
401
- choice = click.prompt(" Your choice", type=click.Choice(["a", "r", "q"], case_sensitive=False))
402
-
403
- if choice == "a":
404
- logger.info(" → Approved! Resuming graph to post results …")
405
- graph.invoke(Command(resume={"action": "approve"}), config)
406
- elif choice == "r":
407
- logger.info(" → Rejected. Resuming graph without posting …")
408
- graph.invoke(Command(resume={"action": "reject"}), config)
409
- else:
410
- logger.info(" → Exiting. Graph remains paused — resume later")
411
- logger.info(
412
- " Resume with: graph.invoke(Command(resume=...), %s)",
413
- config,
414
- )
415
- return
416
-
417
- final_state = graph.get_state(config)
418
- final_values = final_state.values
419
-
420
- logger.info("\n" + "=" * 60)
421
- logger.info(" FINAL STATE")
422
- logger.info("=" * 60)
423
- logger.info(" Human approved: %s", final_values.get("human_approved"))
424
- if final_values.get("verdict"):
425
- logger.info(" Verdict: %s", final_values["verdict"].recommendation)
426
- logger.info(" Final findings: %d", len(final_values.get("final_findings", [])))
427
- logger.info(" %s", cost_tracker.summary())
428
- logger.info("=" * 60)
429
- else:
430
- logger.info("Graph completed without interrupt (no findings to review?)")
431
- logger.info(" %s", cost_tracker.summary())
432
-
433
-
434
- def _test_offline(graph) -> None:
435
- """Non-interactive test that the graph compiles and runs up to interrupt."""
436
- thread_id = str(uuid.uuid4())
437
- prompt_versions = {
438
- "correctness": "v1",
439
- "security": "v1",
440
- "test_coverage": "v1",
441
- "aggregator": "v1",
442
- }
443
- cost_tracker = TokenCostCallback()
444
- metadata = build_run_metadata(
445
- source="cli", repo="demo-org/demo-repo", pr_number=1,
446
- session_id=thread_id,
447
- prompt_versions=prompt_versions,
448
- )
449
- config: dict = {
450
- "configurable": {"thread_id": f"smoke-{thread_id}"},
451
- "metadata": metadata,
452
- }
453
-
454
- with langfuse_trace(
455
- trace_name="opencodereview/smoke-test",
456
- tags=["cli", "smoke", "demo-org/demo-repo"],
457
- session_id=thread_id,
458
- metadata={"prompt_versions": prompt_versions},
459
- ) as handler:
460
- callbacks = [cost_tracker]
461
- if handler:
462
- callbacks.append(handler)
463
- config["callbacks"] = callbacks
464
-
465
- t0 = time.time()
466
- for event in graph.stream(SYNTHETIC_STATE, config):
467
- for node_name in event:
468
- label = NODE_LABELS.get(node_name, node_name)
469
- logger.info(" ✔ %s (+%.1fs)", label, time.time() - t0)
470
- logger.info(" ─── Pipeline complete in %.1fs ───", time.time() - t0)
471
- state = graph.get_state(config)
472
- tasks = state.tasks
473
- values = state.values
474
-
475
- verdict = values.get("verdict")
476
- final_findings = values.get("final_findings", [])
477
-
478
- logger.info("Smoke test: paused=True, tasks=%d, findings=%d, verdict=%s",
479
- len(tasks), len(final_findings),
480
- verdict.recommendation if verdict else 'None')
481
- logger.info("%s", cost_tracker.summary())
482
-
483
- assert len(tasks) > 0, "Graph did not pause at interrupt"
484
- assert verdict is not None, "No verdict produced"
485
- assert len(final_findings) >= 0, "Missing final_findings"
486
-
487
- graph.invoke(Command(resume={"action": "reject"}), config)
488
- logger.info("Smoke test: resume OK, graph completed")
489
-
490
-
491
- def _cleanup_db() -> None:
492
- """Remove the checkpoint database after a run."""
493
- if os.path.exists(DB_PATH):
494
- try:
495
- os.remove(DB_PATH)
496
- logger.info("Cleaned up %s", DB_PATH)
497
- except PermissionError:
498
- pass
499
-
500
-
501
- # ─── Root CLI ───────────────────────────────────────────────────────────────
502
-
503
-
504
- # ─── Doctor Command ─────────────────────────────────────────────────────────
505
-
506
-
507
- @click.command()
508
- def doctor() -> None:
509
- """Run system health checks and report status."""
510
- from config import _mask_key
511
- from observability import (
512
- HealthStatus,
513
- check_groq_connectivity,
514
- check_langfuse_connectivity,
515
- )
516
-
517
- click.echo()
518
- click.echo("=" * 50)
519
- click.echo(" OpenCodeReview — Health Check")
520
- click.echo("=" * 50)
521
- click.echo()
522
-
523
- # ── Environment ────────────────────────────────────────────────────
524
- click.echo("📦 Environment")
525
- click.echo(f" Python: {sys.version.split()[0]}")
526
- click.echo()
527
-
528
- # ── API keys ───────────────────────────────────────────────────────
529
- click.echo("🔑 API Keys")
530
- groq_key = os.environ.get("GROQ_API_KEY", "").strip()
531
- click.echo(f" GROQ_API_KEY: {'✅ Set' if groq_key else '❌ Not set'}")
532
- gh_token = os.environ.get("GITHUB_TOKEN", "").strip()
533
- click.echo(f" GITHUB_TOKEN: {'✅ Set' if gh_token else '❌ Not set'}")
534
- click.echo()
535
-
536
- # ── Observability ────────────────────────���─────────────────────────
537
- click.echo("🔭 Observability")
538
- h = HealthStatus()
539
- for comp, status in h.summary().items():
540
- click.echo(f" {comp}: {status}")
541
- click.echo()
542
-
543
- # ── LLM endpoints (built-ins + custom) ───────────────────────────────
544
- click.echo("🔌 LLM Endpoints")
545
- from endpoints import discover_endpoints
546
-
547
- eps = discover_endpoints()
548
- if eps:
549
- for ep in eps:
550
- click.echo(
551
- f" {ep.describe()}"
552
- + (" ✅" if ep.api_key else " ❌ missing key")
553
- )
554
- else:
555
- click.echo(" None configured — set OCR_ENDPOINT_* env vars to add one")
556
- click.echo()
557
-
558
- # ── Connectivity tests ─────────────────────────────────────────────
559
- click.echo("🌐 Connectivity")
560
-
561
- # Groq
562
- groq_ok, groq_msg = check_groq_connectivity()
563
- click.echo(f" Groq API: {'✅' if groq_ok else '❌'} {groq_msg}")
564
-
565
- # Langfuse (only if configured)
566
- lf_ok, lf_msg = check_langfuse_connectivity()
567
- click.echo(f" Langfuse: {'✅' if lf_ok else '⏭️'} {lf_msg}")
568
-
569
- click.echo()
570
- click.echo("=" * 50)
571
-
572
-
573
- # ─── Root CLI ───────────────────────────────────────────────────────────────
574
-
575
-
576
- @click.group()
577
- def cli() -> None:
578
- """OpenCodeReview — AI-powered PR review with human-in-the-loop approval."""
579
-
580
-
581
- cli.add_command(review)
582
- cli.add_command(doctor)
583
- cli.add_command(auth_group)
584
- cli.add_command(config_group)
585
-
586
-
587
- def main() -> None:
588
- cli(auto_envvar_prefix="OCR")
589
-
590
 
591
  if __name__ == "__main__":
592
- main()
 
 
 
1
+ """Backward-compatible CLI module and launcher."""
2
+ import sys as _sys
3
+ from backend import main as _implementation
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
  if __name__ == "__main__":
6
+ _implementation.main()
7
+ else:
8
+ _sys.modules[__name__] = _implementation