Sdm0 commited on
Commit
bfc1f67
·
verified ·
1 Parent(s): 415308d

Deploy 67faf9fd

Browse files
QUALITY_IMPROVEMENTS.md ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.
api.py CHANGED
@@ -89,7 +89,7 @@ def _init_jobs() -> None:
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"}}
93
  if "config" in payload:
94
  payload["config"] = {"configurable": payload["config"].get("configurable", {})}
95
  pg = _postgres_connect()
@@ -150,6 +150,11 @@ class DecisionRequest(BaseModel):
150
  action: Literal["approve", "reject"]
151
 
152
 
 
 
 
 
 
153
  def _authorize(token: str | None) -> None:
154
  expected = os.getenv("OCR_API_KEY", "").strip()
155
  # Authentication is opt-in for local development, but deployments can
@@ -220,7 +225,7 @@ def github_logout(request: Request) -> dict[str, str]:
220
 
221
 
222
  def _public_job(job: dict[str, Any]) -> dict[str, Any]:
223
- result = {key: value for key, value in job.items() if key not in {"config", "future", "request_fingerprint", "owner_id"}}
224
  now = time.time()
225
  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)
226
  if job.get("status") == "queued":
@@ -230,6 +235,21 @@ def _public_job(job: dict[str, Any]) -> dict[str, Any]:
230
  def _with_ragas(job: dict[str, Any]) -> dict[str, Any]:
231
  result = _public_job(job)
232
  task_id = result.get("ragas_task_id")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
233
  if not task_id:
234
  result["ragas"] = {
235
  "status": "skipped",
@@ -243,7 +263,7 @@ def _with_ragas(job: dict[str, Any]) -> dict[str, Any]:
243
  "scores": job.get("ragas_scores") or {},
244
  "error": job.get("ragas_error"),
245
  }
246
- return result
247
  with _ragas_lock:
248
  task = _ragas_tasks.get(task_id)
249
  if not task:
@@ -260,7 +280,7 @@ def _with_ragas(job: dict[str, Any]) -> dict[str, Any]:
260
  live["ragas_error"] = result["ragas"]["error"]
261
  _save_job(live)
262
  elif not task.get("done"):
263
- timeout = float(os.getenv("OCR_RAGAS_TIMEOUT_SECONDS", "90"))
264
  started = float(task.get("started", 0) or 0)
265
  if started and datetime.now(timezone.utc).timestamp() - started > timeout:
266
  result["ragas"] = {"status": "failed", "error": f"RAGAS exceeded {int(timeout)} second timeout"}
@@ -299,7 +319,7 @@ def _with_ragas(job: dict[str, Any]) -> dict[str, Any]:
299
  live["ragas_status"] = "completed_no_scores"
300
  live["ragas_error"] = result["ragas"]["error"]
301
  _save_job(live)
302
- return result
303
 
304
 
305
  def _run_job(job_id: str, request: ReviewRequest) -> None:
@@ -373,7 +393,7 @@ def _run_job(job_id: str, request: ReviewRequest) -> None:
373
  _jobs[job_id]["head_sha"] = actual_head
374
  stages = state.values.get("review_stages", [])
375
  incomplete = bool(verdict and verdict.recommendation == "incomplete")
376
- _jobs[job_id].update(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, ragas_task_id=ragas if isinstance(ragas, str) else None, ragas_scores=ragas if isinstance(ragas, dict) else None, ragas_inputs=ragas_inputs or None)
377
  _save_job(_jobs[job_id])
378
  except Exception as exc:
379
  with _lock:
@@ -388,6 +408,11 @@ def _run_job(job_id: str, request: ReviewRequest) -> None:
388
  def _hydrate_jobs() -> None:
389
  """Restore persisted jobs after a process restart and resume interrupted work."""
390
  for persisted in _load_jobs():
 
 
 
 
 
391
  job_id = persisted.get("id")
392
  if not job_id:
393
  continue
@@ -522,6 +547,29 @@ def get_review(job_id: str, request: Request, x_api_key: str | None = Header(def
522
  return _with_ragas(job)
523
 
524
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
525
  @app.post("/api/reviews/{job_id}/decision")
526
  def decide_review(job_id: str, request: DecisionRequest, http_request: Request, x_api_key: str | None = Header(default=None)) -> dict[str, Any]:
527
  _authorize_request(x_api_key, http_request)
 
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()
 
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
 
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":
 
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",
 
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:
 
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"}
 
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:
 
393
  _jobs[job_id]["head_sha"] = actual_head
394
  stages = state.values.get("review_stages", [])
395
  incomplete = bool(verdict and verdict.recommendation == "incomplete")
396
+ _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)
397
  _save_job(_jobs[job_id])
398
  except Exception as exc:
399
  with _lock:
 
408
  def _hydrate_jobs() -> None:
409
  """Restore persisted jobs after a process restart and resume interrupted work."""
410
  for persisted in _load_jobs():
411
+ # Evaluation inputs may include an in-memory endpoint object. Never
412
+ # retain or expose that snapshot: it can contain a user's provider key.
413
+ if "ragas_inputs" in persisted:
414
+ persisted.pop("ragas_inputs", None)
415
+ _save_job(persisted)
416
  job_id = persisted.get("id")
417
  if not job_id:
418
  continue
 
547
  return _with_ragas(job)
548
 
549
 
550
+ @app.post('/api/reviews/{job_id}/feedback')
551
+ def finding_feedback(job_id: str, payload: FindingFeedbackRequest, request: Request,
552
+ x_api_key: str | None = Header(default=None)) -> dict[str, Any]:
553
+ _authorize_request(x_api_key, request)
554
+ _rate_limit(request)
555
+ owner = str((_session(request) or {}).get('github_id') or 'api-key')
556
+ with _lock:
557
+ job = _jobs.get(job_id) or _load_job(job_id)
558
+ if not job or job.get('owner_id', 'api-key') != owner:
559
+ raise HTTPException(status_code=404, detail='Review not found')
560
+ if job.get('status') not in {'awaiting_approval', 'incomplete', 'posted', 'partially_posted', 'rejected', 'post_failed'}:
561
+ raise HTTPException(status_code=409, detail='Wait until the review finishes before giving feedback')
562
+ if payload.finding_index >= len(job.get('findings') or []):
563
+ raise HTTPException(status_code=422, detail='Finding does not exist')
564
+ feedback = dict(job.get('feedback') or {})
565
+ feedback[str(payload.finding_index)] = payload.label
566
+ job['feedback'] = feedback
567
+ job['feedback_updated_at'] = datetime.now(timezone.utc).isoformat()
568
+ _jobs[job_id] = job
569
+ _save_job(job)
570
+ return {'feedback': feedback}
571
+
572
+
573
  @app.post("/api/reviews/{job_id}/decision")
574
  def decide_review(job_id: str, request: DecisionRequest, http_request: Request, x_api_key: str | None = Header(default=None)) -> dict[str, Any]:
575
  _authorize_request(x_api_key, http_request)
app.py CHANGED
@@ -12,6 +12,7 @@ On Hugging Face Spaces:
12
  from __future__ import annotations
13
 
14
  import html
 
15
  import json
16
  import ipaddress
17
  import logging
@@ -248,6 +249,7 @@ def _build_and_stream(
248
  conn.close()
249
  flush_langfuse()
250
 
 
251
  return state, config, cost_tracker.summary(), ragas_out, ({**ragas_inputs, "endpoint": None} if ragas_inputs else None)
252
 
253
 
@@ -477,6 +479,7 @@ def _ragas_inputs_from_state(state, endpoint_name: str) -> dict | None:
477
  answer_text = "\n".join(answer_lines) if answer_lines else None
478
  return {
479
  "query": query,
 
480
  "contexts": contexts,
481
  "answer": answer_text,
482
  "endpoint": __import__("endpoints").get_endpoint(endpoint_name) if endpoint_name else None,
@@ -489,18 +492,23 @@ def _compute_and_log_ragas(
489
  pr_number: int,
490
  run_trace_id: str | None,
491
  handler,
 
492
  ) -> dict[str, float | None]:
493
  """Compute RAGAS scores and log them to Langfuse. Never raises."""
494
  scores: dict[str, float | None] = {}
495
  try:
496
- from eval_data.ragas_eval import compute_ragas_retrieval_scores
497
 
498
- scores = compute_ragas_retrieval_scores(
499
  query=inputs["query"],
500
  retrieved_contexts=inputs["contexts"],
501
  answer=inputs["answer"],
502
  endpoint=inputs["endpoint"],
 
503
  )
 
 
 
504
  for metric_name, value in scores.items():
505
  if value is None:
506
  continue
@@ -534,30 +542,42 @@ def _ragas_worker(
534
  result_callback=None,
535
  ) -> None:
536
  """Daemon thread body: compute scores, stash them for the Timer poll."""
537
- timeout = float(os.getenv("OCR_RAGAS_TIMEOUT_SECONDS", "90"))
 
 
 
 
 
 
 
 
 
 
538
  try:
539
  # The provider call may block on a network timeout. Keep the task
540
  # terminal and observable even when the provider does not return.
541
  pool = ThreadPoolExecutor(max_workers=1, thread_name_prefix="ragas-call")
542
  future = pool.submit(
 
543
  _compute_and_log_ragas,
544
  inputs,
545
  repo,
546
  pr_number,
547
  run_trace_id,
548
  handler,
 
549
  )
550
  try:
551
  scores = future.result(timeout=timeout)
552
  except FutureTimeoutError:
553
- scores = {}
554
  with _ragas_lock:
555
  entry = _ragas_tasks.get(task_id)
 
556
  if entry is not None:
557
  entry["error"] = f"RAGAS exceeded {int(timeout)} second timeout"
558
  entry["done"] = True
559
  if result_callback:
560
- result_callback({}, f"RAGAS exceeded {int(timeout)} second timeout")
561
  pool.shutdown(wait=False, cancel_futures=True)
562
  return
563
  else:
@@ -603,8 +623,8 @@ def _spawn_ragas_background(
603
  if len(_ragas_tasks) <= 64:
604
  break
605
  threading.Thread(
606
- target=_ragas_worker,
607
- args=(task_id, inputs, repo, pr_number, run_trace_id, handler, result_callback),
608
  name=f"ragas-{task_id}",
609
  daemon=True,
610
  ).start()
 
12
  from __future__ import annotations
13
 
14
  import html
15
+ from contextvars import copy_context
16
  import json
17
  import ipaddress
18
  import logging
 
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
 
 
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,
 
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
 
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:
 
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()
eval_data/curated_located_fixture.jsonl ADDED
@@ -0,0 +1 @@
 
 
1
+ {"repo":"calcom/cal.diy","pr_number":10600,"pr_url":"https://github.com/calcom/cal.diy/pull/10600","label_scope":"partial","label_notes":"Two manually located code-review concerns, not an exhaustive gold set. Diff locations must be rechecked if the PR changes. Does not establish production vulnerability exploitability.","gold_issues":[{"file_path":"packages/features/auth/lib/next-auth-options.ts","line_start":136,"line_end":155,"category":"security","severity":"medium","comment":"Non-atomic backup-code read-modify-write permits concurrent reuse or lost updates.","concept_terms":["concurrent","race","atomic","reuse"]},{"file_path":"packages/features/auth/lib/next-auth-options.ts","line_start":143,"line_end":145,"category":"correctness","severity":"low","comment":"Backup code comparison rejects uppercase hex input because it is not normalized to lowercase.","concept_terms":["uppercase","lowercase","sensitive","normalize"]}]}
eval_data/offline_regression.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Offline location/category/concept matching, with no provider or model calls.
2
+
3
+ Usage: python -m eval_data.offline_regression --predictions review.json --fixture labelled.jsonl --output report.json
4
+ Gold rows require repo/pr_number (or pr_url) and findings/gold_issues with
5
+ file_path, line_start/line_end, category, comment, and optional concept_terms.
6
+ Scores are deterministic matching proxies, not proof of semantic correctness.
7
+ """
8
+ from __future__ import annotations
9
+ import argparse
10
+ import json
11
+ import re
12
+ from pathlib import Path
13
+
14
+
15
+ def identity(row):
16
+ url = row.get("pr_url") or row.get("task_id")
17
+ if url:
18
+ return str(url).replace("https://github.com/", "").replace("/pull/", "#")
19
+ return f"{row.get('repo')}#{row.get('pr_number')}"
20
+
21
+
22
+ def load_rows(path):
23
+ text = Path(path).read_text(encoding="utf-8")
24
+ try:
25
+ rows = json.loads(text)
26
+ return rows if isinstance(rows, list) else [rows]
27
+ except json.JSONDecodeError:
28
+ return [json.loads(line) for line in text.splitlines() if line.strip()]
29
+
30
+
31
+ def match_score(prediction, gold):
32
+ if prediction.get("file_path") != gold.get("file_path") or not gold.get("file_path"):
33
+ return None
34
+ if prediction.get("category") != gold.get("category") or not gold.get("category"):
35
+ return None
36
+ ps = int(prediction.get("line_start") or 0)
37
+ gs = int(gold.get("line_start") or gold.get("line") or 0)
38
+ if not ps or not gs:
39
+ return None
40
+ pe, ge = int(prediction.get("line_end") or ps), int(gold.get("line_end") or gs)
41
+ if ps > ge + 3 or gs > pe + 3:
42
+ return None
43
+ words = set(re.findall(r"[a-z]+", prediction.get("comment", "").lower()))
44
+ concepts = gold.get("concept_terms") or re.findall(r"[a-z]{4,}", gold.get("comment", "").lower())
45
+ overlap = sum(1 for term in concepts if term.lower() in words)
46
+ return overlap / max(1, len(concepts)) if overlap else None
47
+
48
+
49
+ def evaluate(predictions, fixtures):
50
+ indexed = {identity(row): row for row in fixtures}
51
+ partial_labels = False
52
+ total = dict(matched=0, predicted_bugs=0, gold_bugs=0, suggestions=0, duplicate_predictions=0, unlocatable_gold=0, rows=0)
53
+ cases = []
54
+ for prediction in predictions:
55
+ key = identity(prediction)
56
+ if key not in indexed:
57
+ cases.append({"id": key, "status": "skipped", "reason": "No labelled fixture"})
58
+ continue
59
+ total["rows"] += 1
60
+ partial_labels = partial_labels or indexed[key].get("label_scope") != "exhaustive"
61
+ gold = indexed[key].get("findings") or indexed[key].get("gold_issues") or []
62
+ total["unlocatable_gold"] += sum(not item.get("file_path") or not (item.get("line_start") or item.get("line")) for item in gold)
63
+ valid = [item for item in gold if item.get("file_path") and (item.get("line_start") or item.get("line"))]
64
+ bugs = [item for item in prediction.get("findings", []) if item.get("category") != "test_coverage" and item.get("kind") not in {"suggestion", "test_suggestion"}]
65
+ total["suggestions"] += len(prediction.get("findings", [])) - len(bugs)
66
+ total["predicted_bugs"] += len(bugs)
67
+ total["gold_bugs"] += len(valid)
68
+ edges = sorted([(score, pi, gi) for pi, pred in enumerate(bugs) for gi, item in enumerate(valid) if (score := match_score(pred, item)) is not None], reverse=True)
69
+ used_predictions, used_gold = set(), set()
70
+ for score, pi, gi in edges:
71
+ if pi not in used_predictions and gi not in used_gold:
72
+ used_predictions.add(pi)
73
+ used_gold.add(gi)
74
+ total["matched"] += len(used_gold)
75
+ duplicate = sum(any(match_score(pred, item) is not None for item in valid) for pi, pred in enumerate(bugs) if pi not in used_predictions)
76
+ total["duplicate_predictions"] += duplicate
77
+ cases.append({"id": key, "status": prediction.get("status"), "matched": len(used_gold), "false_positives": len(bugs) - len(used_predictions), "missed": len(valid) - len(used_gold), "elapsed_seconds": prediction.get("elapsed_seconds"), "reviewer_failures": sum(item.get("status") == "failed" for item in prediction.get("review_stages", []))})
78
+ return {"method": "location_category_concept_proxy_v1", "limitations": "Deterministic matching is not a semantic correctness judge. Labels and unmatched/duplicate predictions require human review. Unlocatable gold is excluded, never counted as a pass.", "totals": total, "label_scope": "partial" if partial_labels else "exhaustive", "precision": total["matched"] / total["predicted_bugs"] if total["predicted_bugs"] and not partial_labels and total["gold_bugs"] else None, "annotated_match_rate": total["matched"] / total["predicted_bugs"] if total["predicted_bugs"] and total["gold_bugs"] else None, "recall": total["matched"] / total["gold_bugs"] if total["gold_bugs"] else None, "cases": cases}
79
+
80
+
81
+ def main():
82
+ parser = argparse.ArgumentParser(description=__doc__)
83
+ parser.add_argument("--predictions", required=True)
84
+ parser.add_argument("--fixture", required=True)
85
+ parser.add_argument("--output", default="eval_data/regression_report.json")
86
+ args = parser.parse_args()
87
+ report = evaluate(load_rows(args.predictions), load_rows(args.fixture))
88
+ Path(args.output).write_text(json.dumps(report, indent=2), encoding="utf-8")
89
+ print(json.dumps(report, indent=2))
90
+
91
+
92
+ if __name__ == "__main__":
93
+ main()
eval_data/ragas_eval.py CHANGED
@@ -26,6 +26,7 @@ Lazy imports minimise overhead when RAGAS is not installed.
26
 
27
  from __future__ import annotations
28
 
 
29
  import logging
30
  import os
31
  import threading
@@ -69,6 +70,7 @@ def _check_ragas() -> bool:
69
  # OCR_RAGAS_INTERVAL env var (float seconds, 0 disables).
70
  _RAGAS_INTERVAL = float(os.environ.get("OCR_RAGAS_INTERVAL", "0.5") or 0.5)
71
  _ragas_throttle_lock = threading.Lock()
 
72
 
73
 
74
  class _ThrottledChatModel:
@@ -104,6 +106,9 @@ class _ThrottledChatModel:
104
  raise
105
 
106
  def _wait(self) -> None:
 
 
 
107
  if self._quota_exhausted:
108
  raise RuntimeError("Evaluation stopped: provider authentication or quota limit; no further calls will be made for this evaluation.")
109
  if self._interval > 0:
@@ -166,6 +171,12 @@ class _ThrottledChatModel:
166
  return getattr(self._model, name)
167
 
168
 
 
 
 
 
 
 
169
  def _get_evaluator_llm(endpoint: Optional[str] = None):
170
  """Return a RAGAS-compatible LLM, reusing the project's LLM factory.
171
 
@@ -190,7 +201,7 @@ def _get_evaluator_llm(endpoint: Optional[str] = None):
190
 
191
  llm = create_llm(endpoint=endpoint, temperature=0, timeout=15, max_retries=0)
192
  logger.info("RAGAS evaluator: using custom endpoint %s", endpoint)
193
- return LangchainLLMWrapper(_ThrottledChatModel(llm))
194
 
195
  from llm_factory import _get_groq_chat, _get_gemini_chat
196
 
@@ -218,7 +229,7 @@ def _get_evaluator_llm(endpoint: Optional[str] = None):
218
  type(llm).__name__,
219
  _RAGAS_INTERVAL,
220
  )
221
- return LangchainLLMWrapper(_ThrottledChatModel(llm))
222
  except ValueError as exc:
223
  logger.warning("RAGAS evaluator: %s", exc)
224
  raise RuntimeError(
@@ -230,209 +241,97 @@ def _get_evaluator_llm(endpoint: Optional[str] = None):
230
  # ─── Score computation ─────────────────────────────────────────────────────
231
 
232
 
233
- def compute_ragas_retrieval_scores(
234
- query: str,
235
- retrieved_contexts: list[str],
236
- ground_truth: Optional[str] = None,
237
- answer: Optional[str] = None,
238
- endpoint: Optional[str] = None,
239
- ) -> dict[str, float | None]:
240
- """Compute RAGAS retrieval & generation quality metrics.
241
-
242
- Computes up to five metrics depending on available inputs:
243
-
244
- +---------------------------+------------------------------------------+
245
- | Metric | Required inputs |
246
- +===========================+==========================================+
247
- | ``context_precision`` | query, retrieved_contexts |
248
- | ``context_recall`` | query, retrieved_contexts, ground_truth |
249
- | ``faithfulness`` | query, retrieved_contexts, answer |
250
- | ``answer_relevancy`` | query, answer |
251
- | ``mmr`` (Mean Reciprocal | query, retrieved_contexts |
252
- | Rank) | (custom LLM-judged) |
253
- +---------------------------+------------------------------------------+
254
 
255
- Parameters
256
- ----------
257
- query : str
258
- The search query — in OpenCodeReview this is the PR diff text.
259
- retrieved_contexts : list[str]
260
- The code/document chunks returned by the retrieval node.
261
- ground_truth : str or None
262
- Ground-truth reference text (e.g. human review comment). Required
263
- for ``context_recall``.
264
- answer : str or None
265
- The generated answer (e.g. concatenated review findings / verdict).
266
- Required for ``faithfulness`` and ``answer_relevancy``.
267
- endpoint : str or None
268
- Optional name of a configured custom LLM endpoint
269
- (``OCR_ENDPOINT_*``) to score with. ``None`` uses the built-in
270
- Groq → Gemini priority.
271
 
272
- Returns
273
- -------
274
- dict
275
- Mapping of metric name → score (0–1 range, higher is better),
276
- or ``None`` when that metric's computation failed (e.g. LLM
277
- rate limit / error). Possible keys: ``context_precision``,
278
- ``context_recall``, ``faithfulness``, ``answer_relevancy``,
279
- ``mmr``.
280
 
281
- Raises
282
- ------
283
- RuntimeError
284
- If RAGAS or a suitable LLM backend is not available.
285
  """
286
- if not _check_ragas():
287
- raise RuntimeError(
288
- "RAGAS is not installed. Run: pip install ragas litellm"
289
- )
290
-
291
- if not retrieved_contexts:
292
- logger.warning("No retrieved contexts — RAGAS scores set to 0.0")
293
- result: dict[str, float] = {"context_precision": 0.0, "mmr": 0.0}
294
- if ground_truth:
295
- result["context_recall"] = 0.0
296
- if answer:
297
- result["faithfulness"] = 0.0
298
- result["answer_relevancy"] = 0.0
299
- return result
300
-
301
- from ragas.dataset_schema import SingleTurnSample
302
-
303
- llm = _get_evaluator_llm(endpoint=endpoint)
304
- scores: dict[str, float | None] = {}
305
-
306
- # ── Context Precision (reference-free) ───────────────────────────
307
- # Uses LLMContextPrecisionWithoutReference which needs user_input +
308
- # response + retrieved_contexts (no ground-truth reference required).
309
- if answer:
310
- try:
311
- from ragas.metrics import LLMContextPrecisionWithoutReference
312
-
313
- scorer = LLMContextPrecisionWithoutReference(llm=llm)
314
- sample = SingleTurnSample(
315
- user_input=query,
316
- response=answer,
317
- retrieved_contexts=retrieved_contexts,
318
- )
319
- result = scorer.single_turn_score(sample)
320
- scores["context_precision"] = round(float(result), 4)
321
- logger.info("RAGAS context_precision: %.4f", scores["context_precision"])
322
- except Exception as exc:
323
- logger.warning("RAGAS context_precision failed: %s", exc)
324
- scores["context_precision"] = None
325
-
326
- # ── Context Recall (requires ground_truth) ───────────────────────
327
  if ground_truth:
328
- try:
329
- from ragas.metrics import ContextRecall
330
-
331
- recall_scorer = ContextRecall(llm=llm)
332
- recall_sample = SingleTurnSample(
333
- user_input=query,
334
- retrieved_contexts=retrieved_contexts,
335
- reference=ground_truth,
336
- )
337
- recall_result = recall_scorer.single_turn_score(recall_sample)
338
- scores["context_recall"] = round(float(recall_result), 4)
339
- logger.info("RAGAS context_recall: %.4f", scores["context_recall"])
340
- except Exception as exc:
341
- logger.warning("RAGAS context_recall failed: %s", exc)
342
- scores["context_recall"] = None
343
-
344
- # ── Faithfulness ─────────────────────────────────────────────────
345
- if answer:
346
- try:
347
- from ragas.metrics import Faithfulness
348
-
349
- faithfulness_scorer = Faithfulness(llm=llm)
350
- faithful_sample = SingleTurnSample(
351
- user_input=query,
352
- response=answer,
353
- retrieved_contexts=retrieved_contexts,
354
- )
355
- faithful_result = faithfulness_scorer.single_turn_score(faithful_sample)
356
- scores["faithfulness"] = round(float(faithful_result), 4)
357
- logger.info("RAGAS faithfulness: %.4f", scores["faithfulness"])
358
- except Exception as exc:
359
- logger.warning("RAGAS faithfulness failed: %s", exc)
360
- scores["faithfulness"] = None
361
-
362
- # ── Answer Relevancy (ResponseRelevancy) ─────────────────────────
363
- if answer:
364
- try:
365
- from ragas.metrics import ResponseRelevancy
366
-
367
- # ResponseRelevancy also needs an embedding model for cosine
368
- # similarity. We create a lightweight one from the project's
369
- # ChromaDB embedding function (ONNX MiniLM, already cached).
370
- embeddings = _create_ragas_embeddings()
371
- if embeddings is None:
372
- raise RuntimeError(
373
- "No embedding model available for ResponseRelevancy — "
374
- "install chromadb"
375
- )
376
-
377
- relevancy_scorer = ResponseRelevancy(
378
- llm=llm,
379
- embeddings=embeddings,
380
- strictness=1, # Groq only supports n=1
381
- )
382
- relevancy_sample = SingleTurnSample(
383
- user_input=query,
384
- response=answer,
385
- )
386
- relevancy_result = relevancy_scorer.single_turn_score(relevancy_sample)
387
- scores["answer_relevancy"] = round(float(relevancy_result), 4)
388
- logger.info("RAGAS answer_relevancy: %.4f", scores["answer_relevancy"])
389
- except Exception as exc:
390
- logger.warning("RAGAS answer_relevancy failed: %s", exc)
391
- scores["answer_relevancy"] = None
392
-
393
- # ── MMR (Mean Reciprocal Rank) — custom implementation ───────────
394
  try:
395
- mmr = _compute_mmr(query, retrieved_contexts, llm)
396
- scores["mmr"] = round(mmr, 4)
397
- logger.info("RAGAS mmr: %.4f", scores["mmr"])
 
 
398
  except Exception as exc:
399
- logger.warning("RAGAS mmr failed: %s", exc)
400
- scores["mmr"] = None
401
-
402
- # ── Context Precision (reference-based, fallback when no answer) ─
403
- if "context_precision" not in scores and ground_truth:
404
- try:
405
- from ragas.metrics import ContextPrecision
406
-
407
- scorer = ContextPrecision(llm=llm)
408
- sample = SingleTurnSample(
409
- user_input=query,
410
- retrieved_contexts=retrieved_contexts,
411
- reference=ground_truth,
412
- )
413
- result = scorer.single_turn_score(sample)
414
- scores["context_precision"] = round(float(result), 4)
415
- logger.info("RAGAS context_precision: %.4f", scores["context_precision"])
416
- except Exception as exc:
417
- logger.warning("RAGAS context_precision failed: %s", exc)
418
- scores["context_precision"] = None
419
-
420
- # Deterministic fallback: retrieval-only reviews may not have an answer or
421
- # reference, and provider-backed judges can fail or rate-limit. Preserve a
422
- # truthful numeric signal from lexical query/context coverage instead of
423
- # returning an empty score map.
424
- if not any(value is not None for value in scores.values()):
425
- query_terms = {term.lower() for term in query.split() if len(term) >= 4}
426
- overlaps = []
427
- for context in retrieved_contexts:
428
- context_terms = {term.lower() for term in context.split() if len(term) >= 4}
429
- overlaps.append(len(query_terms & context_terms) / max(1, len(query_terms)))
430
- coverage = round(sum(overlaps) / max(1, len(overlaps)), 4)
431
- first_relevant = next((index for index, value in enumerate(overlaps, 1) if value > 0), None)
432
- scores["context_precision"] = coverage
433
- scores["mmr"] = round(1 / first_relevant, 4) if first_relevant else 0.0
434
- logger.info("RAGAS deterministic fallback: context_precision=%.4f mmr=%.4f", scores["context_precision"], scores["mmr"])
435
- return scores
 
 
 
 
 
 
 
 
436
 
437
 
438
  def _create_ragas_embeddings():
 
26
 
27
  from __future__ import annotations
28
 
29
+ from contextvars import ContextVar
30
  import logging
31
  import os
32
  import threading
 
70
  # OCR_RAGAS_INTERVAL env var (float seconds, 0 disables).
71
  _RAGAS_INTERVAL = float(os.environ.get("OCR_RAGAS_INTERVAL", "0.5") or 0.5)
72
  _ragas_throttle_lock = threading.Lock()
73
+ _metric_deadline = ContextVar("ragas_metric_deadline", default=None)
74
 
75
 
76
  class _ThrottledChatModel:
 
106
  raise
107
 
108
  def _wait(self) -> None:
109
+ deadline = _metric_deadline.get()
110
+ if deadline is not None and time.monotonic() >= deadline:
111
+ raise TimeoutError("Metric deadline exceeded; no further judge calls")
112
  if self._quota_exhausted:
113
  raise RuntimeError("Evaluation stopped: provider authentication or quota limit; no further calls will be made for this evaluation.")
114
  if self._interval > 0:
 
171
  return getattr(self._model, name)
172
 
173
 
174
+ def _wrap_evaluator(llm):
175
+ from ragas.llms import LangchainLLMWrapper
176
+ from ragas.run_config import RunConfig
177
+ return LangchainLLMWrapper(_ThrottledChatModel(llm), run_config=RunConfig(timeout=12, max_retries=1, max_wait=0, max_workers=1))
178
+
179
+
180
  def _get_evaluator_llm(endpoint: Optional[str] = None):
181
  """Return a RAGAS-compatible LLM, reusing the project's LLM factory.
182
 
 
201
 
202
  llm = create_llm(endpoint=endpoint, temperature=0, timeout=15, max_retries=0)
203
  logger.info("RAGAS evaluator: using custom endpoint %s", endpoint)
204
+ return _wrap_evaluator(llm)
205
 
206
  from llm_factory import _get_groq_chat, _get_gemini_chat
207
 
 
229
  type(llm).__name__,
230
  _RAGAS_INTERVAL,
231
  )
232
+ return _wrap_evaluator(llm)
233
  except ValueError as exc:
234
  logger.warning("RAGAS evaluator: %s", exc)
235
  raise RuntimeError(
 
241
  # ─── Score computation ─────────────────────────────────────────────────────
242
 
243
 
244
+ def _score_one_metric(name, sample, llm, timeout):
245
+ from ragas import metrics
246
+ from ragas.run_config import RunConfig
247
+ classes = {"context_precision": "LLMContextPrecisionWithoutReference", "faithfulness": "Faithfulness", "context_recall": "ContextRecall"}
248
+ scorer = getattr(metrics, classes[name])(llm=llm)
249
+ scorer.init(RunConfig(timeout=timeout, max_retries=1, max_wait=0, max_workers=1))
250
+ return float(scorer.single_turn_score(sample))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
251
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
252
 
253
+ def compute_ragas_report(query, retrieved_contexts, ground_truth=None, answer=None, endpoint=None, *, metric_timeout=None, progress_callback=None):
254
+ """Run independent bounded RAGAS metrics, preserving successes and real failures.
 
 
 
 
 
 
255
 
256
+ No local embedding model is loaded. Lexical overlap is never substituted for
257
+ RAGAS. Input caps reduce judge latency and are disclosed in the report.
 
 
258
  """
259
+ import math
260
+ import queue
261
+ from contextvars import copy_context
262
+ started = time.monotonic()
263
+ total_budget = max(1.0, float(os.getenv("OCR_RAGAS_TIMEOUT_SECONDS", "30")))
264
+ per_metric = max(.05, float(metric_timeout or os.getenv("OCR_RAGAS_METRIC_TIMEOUT_SECONDS", "12")))
265
+ names = ["context_precision", "faithfulness"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
266
  if ground_truth:
267
+ names.append("context_recall")
268
+ report = {"scores": {}, "metrics": {}, "evaluation": {"engine": "RAGAS", "local_models": False, "metric_timeout_seconds": per_metric, "input_truncated": len(query) > 6000 or len(answer or "") > 4000 or len(retrieved_contexts) > 2 or any(len(c) > 4000 for c in retrieved_contexts)}}
269
+ def finish(name, status, value=None, error=None, duration=0):
270
+ report["metrics"][name] = {"status": status, "value": value, "error": error, "duration_seconds": round(duration, 3)}
271
+ if value is not None:
272
+ report["scores"][name] = value
273
+ if progress_callback:
274
+ progress_callback(report)
275
+ for name, reason in [("answer_relevancy", "Requires embeddings; local models are disabled"), ("mmr", "Extra judge calls disabled in hosted evaluation")]:
276
+ finish(name, "skipped", error=reason)
277
+ if not ground_truth:
278
+ finish("context_recall", "skipped", error="No reference answer provided")
279
+ if not answer or not retrieved_contexts:
280
+ for name in names:
281
+ finish(name, "skipped", error="A complete answer and context are required")
282
+ return report
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
283
  try:
284
+ if not _check_ragas():
285
+ raise RuntimeError("RAGAS is not installed")
286
+ from ragas.dataset_schema import SingleTurnSample
287
+ llm = _get_evaluator_llm(endpoint=endpoint)
288
+ sample = SingleTurnSample(user_input=query[:6000], response=answer[:4000], retrieved_contexts=[c[:4000] for c in retrieved_contexts[:2]], reference=ground_truth[:4000] if ground_truth else None)
289
  except Exception as exc:
290
+ for name in names:
291
+ finish(name, "failed", error=type(exc).__name__)
292
+ return report
293
+ pending = {}
294
+ for name in names:
295
+ remaining = total_budget - (time.monotonic() - started) - 1
296
+ if remaining <= 0:
297
+ finish(name, "timed_out", error="Evaluation setup exhausted deadline")
298
+ continue
299
+ deadline = time.monotonic() + min(per_metric, remaining)
300
+ output = queue.Queue(maxsize=1)
301
+ def run(metric=name, target=output, limit=min(per_metric, remaining)):
302
+ metric_started = time.monotonic()
303
+ token = _metric_deadline.set(metric_started + limit)
304
+ try:
305
+ value = _score_one_metric(metric, sample, llm, limit)
306
+ if not math.isfinite(value) or not 0 <= value <= 1:
307
+ raise ValueError("Invalid metric value")
308
+ target.put(("completed", round(value, 4), None, time.monotonic() - metric_started))
309
+ except Exception as exc:
310
+ target.put(("failed", None, type(exc).__name__, time.monotonic() - metric_started))
311
+ finally:
312
+ _metric_deadline.reset(token)
313
+ threading.Thread(target=copy_context().run, args=(run,), daemon=True).start()
314
+ pending[name] = (output, deadline)
315
+ while pending:
316
+ for name, (output, deadline) in list(pending.items()):
317
+ try:
318
+ status, value, error, duration = output.get_nowait()
319
+ except queue.Empty:
320
+ if time.monotonic() < deadline:
321
+ continue
322
+ status, value, error, duration = "timed_out", None, "Metric deadline exceeded", per_metric
323
+ finish(name, status, value, error, duration)
324
+ del pending[name]
325
+ if pending:
326
+ time.sleep(.01)
327
+ report["evaluation"]["duration_seconds"] = round(time.monotonic() - started, 3)
328
+ return report
329
+
330
+
331
+ def compute_ragas_retrieval_scores(query, retrieved_contexts, ground_truth=None, answer=None, endpoint=None):
332
+ """Compatibility mapping. Failed/skipped metrics remain None, never invented scores."""
333
+ report = compute_ragas_report(query, retrieved_contexts, ground_truth, answer, endpoint)
334
+ return {name: metric["value"] for name, metric in report["metrics"].items()}
335
 
336
 
337
  def _create_ragas_embeddings():
frontend/api/provider-test.js CHANGED
@@ -21,6 +21,10 @@ export default async function handler(req, res) {
21
  url = `${base.origin}${base.pathname.replace(/\/$/,'')}/chat/completions`;
22
  headers = {Authorization:`Bearer ${apiKey}`};
23
  body = {model,max_tokens:256,messages:[{role:'user',content:prompt}]};
 
 
 
 
24
  }
25
  const response = await fetch(url,{method:'POST',redirect:'error',signal:AbortSignal.timeout(20000),headers:{'Content-Type':'application/json',...headers},body:JSON.stringify(body)});
26
  const data = await response.json();
 
21
  url = `${base.origin}${base.pathname.replace(/\/$/,'')}/chat/completions`;
22
  headers = {Authorization:`Bearer ${apiKey}`};
23
  body = {model,max_tokens:256,messages:[{role:'user',content:prompt}]};
24
+ if (base.hostname === 'openrouter.ai' && model.toLowerCase().includes('minimax-m3.1')) {
25
+ body.max_tokens = 8192;
26
+ body.reasoning = {effort:'low'};
27
+ }
28
  }
29
  const response = await fetch(url,{method:'POST',redirect:'error',signal:AbortSignal.timeout(20000),headers:{'Content-Type':'application/json',...headers},body:JSON.stringify(body)});
30
  const data = await response.json();
frontend/api/provider-test.test.js CHANGED
@@ -34,3 +34,17 @@ test('probe rejects private destinations and redacts provider error credentials'
34
  await handler(req,res); assert.equal(res.code,400); assert.ok(!res.body.error.includes('test-secret'));
35
  } finally { globalThis.fetch=original; }
36
  });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  await handler(req,res); assert.equal(res.code,400); assert.ok(!res.body.error.includes('test-secret'));
35
  } finally { globalThis.fetch=original; }
36
  });
37
+
38
+ test('MiniMax probe reserves reasoning budget consistently with review calls', async () => {
39
+ const original = globalThis.fetch;
40
+ try {
41
+ globalThis.fetch = async (url, options) => {
42
+ const body = JSON.parse(options.body);
43
+ assert.equal(body.max_tokens,8192);
44
+ assert.deepEqual(body.reasoning,{effort:'low'});
45
+ return {ok:true,json:async()=>({choices:[{message:{content:'{"findings":[]}'}}]})};
46
+ };
47
+ const req = request(), res = response(); req.body.model='minimax/minimax-m3.1-flash:free';
48
+ await handler(req,res); assert.equal(res.code,200);
49
+ } finally { globalThis.fetch=original; }
50
+ });
frontend/src/main.jsx CHANGED
@@ -1,7 +1,7 @@
1
  import React, { useEffect, useMemo, useState } from "react";
2
  import { createRoot } from "react-dom/client";
3
  import "./styles.css";
4
- import { reviewPayload, readProviders } from "./review-client.js";
5
 
6
  const API_BASE = (import.meta.env.VITE_REVIEW_API_URL || "").replace(/\/$/, "");
7
  const TERMINAL = new Set(["awaiting_approval", "rejected", "posted", "partially_posted", "post_failed", "failed", "incomplete", "cancelled"]);
@@ -11,26 +11,50 @@ const pretty = (value) => String(value || "").replaceAll("_", " ");
11
  function Verdict({ job }) {
12
  if (!job?.verdict) return null;
13
  const v = job.verdict;
14
- const blocking = ["block", "request_changes", "incomplete"].includes(v.recommendation);
15
  const score = typeof v.overall_score === "number" ? v.overall_score : null;
16
  const scoreLabel = score == null ? "Not scored" : score < 4 ? "High risk" : score < 7 ? "Review carefully" : "Low risk";
17
- const scoreHelp = score == null ? "Review incomplete: a reliable overall score is unavailable. Check the reviewer statuses below." : score < 4 ? "Resolve the high-severity findings before merging." : score < 7 ? "Read the findings and confirm the risk before merging." : "No major risks were detected by the review.";
18
- return <section className={`result-card verdict ${blocking ? "blocking" : "approved"}`} aria-labelledby="verdict-title">
19
  <div className="result-title"><div><span className="panel-kicker">Review decision</span><h3 id="verdict-title">{pretty(v.recommendation).toUpperCase()}</h3></div><div className="score-block"><strong className="score">{score == null ? "—" : `${score.toFixed(1)}/10`}</strong><span>{scoreLabel}</span></div></div>
20
- <p className="verdict-summary">{v.summary || "The review is ready for your decision."}</p><div className="score-explanation"><strong>What this means</strong><span>{scoreHelp}</span></div><div className="metrics"><span>{job.findings?.length || 0} findings</span>{job.cost && <span>Cost {typeof job.cost === "string" ? job.cost : JSON.stringify(job.cost)}</span>}</div>
 
 
 
21
  </section>;
22
  }
23
 
24
- function Findings({ findings = [] }) {
25
- return <section aria-labelledby="findings-title"><div className="section-heading"><h3 id="findings-title">Findings</h3><span>{findings.length}</span></div>{findings.length ? <div className="findings">{findings.map((f, i) => <article className="finding" key={`${f.file_path || "finding"}-${f.line_start || 0}-${i}`}><div className="finding-meta"><span className={`severity ${String(f.severity || "info").toLowerCase()}`}>{f.severity || "info"}</span>{f.category && <span className="category">{f.category}</span>}<span className="finding-location">{f.file_path || "Unknown file"}{f.line_start ? `:${f.line_start}${f.line_end && f.line_end !== f.line_start ? `–${f.line_end}` : ""}` : ""}</span></div><p>{f.comment || f.description || "No explanation provided."}</p>{f.confidence != null && <small>Confidence {Math.round(Number(f.confidence) * 100)}%</small>}</article>)}</div> : <div className="empty-result"><strong>No findings</strong><span>The reviewers did not identify actionable issues.</span></div>}</section>;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
  }
27
 
28
  function Receipt({ result }) {
29
  if (!result) return null;
30
- return <section className="result-card receipt" aria-labelledby="receipt-title"><span className="panel-kicker">Delivery receipt</span><h3 id="receipt-title">{pretty(result.status || "completed")}</h3><div className="metrics"><span>Inline: {result.inline_posted || 0}</span><span>Fallback: {result.fallback_posted || 0}</span><span>Finding failures: {result.finding_failed || 0}</span><span>Verdict: {result.verdict_posted ? "posted" : "failed"}</span></div></section>;
31
  }
32
 
33
- function Ragas({ ragas }) { if (!ragas) return null; const text = ragas.status === "pending" ? "Computing scores in the background…" : ragas.status === "failed" ? `Scoring failed: ${ragas.error || "provider error"}` : ragas.status === "skipped" ? `Skipped: ${ragas.reason || "retrieval context was unavailable"}` : ragas.status === "unavailable" ? `Unavailable: ${ragas.error || "the scoring task was lost"}` : ragas.status === "completed_no_scores" ? (ragas.error || "Completed without metric values") : Object.entries(ragas.scores || {}).map(([key, value]) => `${key}: ${typeof value === "number" ? value.toFixed(3) : value}`).join(" · ") || "Completed without scores"; return <section className="result-card receipt" aria-label="RAGAS retrieval quality"><span className="panel-kicker">Retrieval quality (RAGAS)</span><p>{text}</p></section>; }
 
 
 
 
 
 
34
 
35
  function ReviewProgress({ job }) {
36
  if (!job) return null;
@@ -49,7 +73,12 @@ function App() {
49
  const [reviewMode, setReviewMode] = useState("fast");
50
  const [baselineSha, setBaselineSha] = useState("");
51
  const [testingProvider, setTestingProvider] = useState(false);
52
- const [repo, setRepo] = useState(""); const [pr, setPr] = useState(""); const [endpoint, setEndpoint] = useState("auto"); const [provider, setProvider] = useState("openai"); const [model, setModel] = useState(""); const [apiKey, setApiKey] = useState(""); const [baseUrl, setBaseUrl] = useState("");
 
 
 
 
 
53
  const [savedProviders, setSavedProviders] = useState(() => readProviders(localStorage));
54
  const [theme, setTheme] = useState(() => localStorage.getItem("ocr-theme") || "light"); const [job, setJob] = useState(null); const [message, setMessage] = useState(""); const [error, setError] = useState(""); const [busy, setBusy] = useState(false); const [user, setUser] = useState(null);
55
  useEffect(() => { fetch(apiUrl("/api/auth/me"), { credentials: "include" }).then(r => r.ok ? r.json() : null).then(setUser).catch(() => setUser(null)); }, []);
@@ -62,27 +91,67 @@ function App() {
62
  poll(); const timer = window.setInterval(poll, 3000); return () => { stopped = true; window.clearInterval(timer); };
63
  }, [job?.id, isTerminal, job?.ragas?.status]);
64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
  async function testProvider() {
66
  if (!model.trim() || !apiKey.trim()) { setError("Enter a model and API key before testing."); return; }
 
67
  setError(""); setMessage("Testing response time and JSON output…"); setTestingProvider(true);
68
  try {
69
- const response = await fetch("/api/provider-test", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ provider: provider || "openai", model: model.trim(), apiKey: apiKey.trim(), baseUrl: baseUrl.trim() }) });
70
  const result = await response.json();
71
  if (!response.ok) throw new Error(result.error || "Provider test failed.");
 
 
 
 
72
  setMessage(`Connection verified in ${(result.latency_ms / 1000).toFixed(1)}s. JSON response: ${result.json_object_valid ? "valid" : "invalid — this model may need a different output format"}.`);
73
- } catch (err) { setMessage(""); setError(err.message); } finally { setTestingProvider(false); }
74
  }
75
  function addProvider() {
76
  if (!model.trim() || !apiKey.trim()) { setError("Enter a model and API key first."); return; }
77
- const type = provider || "openai";
78
- const name = `${type} / ${model.trim()}`;
79
- const item = { name, provider: type, model: model.trim(), apiKey: apiKey.trim(), baseUrl: baseUrl.trim() };
 
 
80
  try {
81
- const next = [...savedProviders.filter(entry => entry.name !== name), item];
82
- localStorage.setItem("ocr-providers", JSON.stringify(next));
83
- setSavedProviders(next); setEndpoint(`saved:${name}`); setError(""); setMessage(`${name} saved. Select it in Review.`);
84
  } catch { setMessage(""); setError("Browser storage is unavailable. Provider could not be saved."); }
85
  }
 
 
 
 
 
 
 
 
 
 
86
  async function startReview(e) {
87
  e.preventDefault(); setError("");
88
  if (!/^[-\w.]+\/[-\w.]+$/.test(repo.trim()) || !Number.isInteger(Number(pr)) || Number(pr) < 1) { setError("Enter a repository as owner/name and a valid PR number."); return; }
@@ -105,7 +174,7 @@ function App() {
105
  } catch (err) { setError(err.message); } finally { setBusy(false); }
106
  }
107
  async function decide(action) { if (!job?.id) return; setBusy(true); setError(""); setMessage(action === "approve" ? "Posting approved review…" : "Rejecting review…"); try { const r = await fetch(apiUrl(`/api/reviews/${job.id}/decision`), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action }) }); const data = await r.json().catch(() => ({})); if (!r.ok) throw new Error(data.detail || `Decision failed (${r.status})`); setJob(data); setMessage(action === "approve" ? "Review delivery finished." : "Review rejected. Nothing was posted to GitHub."); } catch (e) { setError(e.message); } finally { setBusy(false); } }
108
- return <div className="shell"><header className="topbar"><div className="brand"><span className="brand-mark">OC</span><span>OpenCodeReview</span></div><div>{user ? <><span className="status-dot">Signed in as {user.login}</span><button className="auth-button" onClick={logout}>Sign out</button></> : <a className="status-dot" href={`${API_BASE}/api/auth/github/start`}>Sign in with GitHub</a>}<span className="status-dot">Human approval required</span><button className="theme-toggle" type="button" onClick={() => setTheme(theme === "dark" ? "light" : "dark")} aria-label="Toggle color theme">{theme === "dark" ? "Light" : "Dark"}</button></div></header><main className="content"><section className="hero"><p className="eyebrow">Pull request intelligence</p><h1>Review changes with<br /><em>evidence before action.</em></h1><p className="lede">Parallel analysis for correctness, security, and test coverage. Nothing is posted to GitHub until you approve it.</p></section><section className="intro-band"><div className="intro-copy"><p className="eyebrow">AI code review with a human checkpoint</p><h2>Know what changed<br /><em>before it ships.</em></h2><p>OpenCodeReview traces pull requests back to the diff, checks correctness and security, then gives you the evidence to decide what reaches GitHub.</p><div className="intro-actions"><a className="primary-link" href={user ? "#new-review" : `${API_BASE}/api/auth/github/start`}>Start a review <span>&rarr;</span></a><a className="quiet-link" href="#how-it-works">See how it works</a></div></div><div className="review-preview" aria-label="Review workflow preview"><div className="preview-top"><span className="live-dot"></span><span>REVIEW PIPELINE</span><span className="preview-time">LIVE</span></div><div className="preview-row"><strong>01</strong><span><b>Read the diff</b><small>Files, lines, and context</small></span><i>done</i></div><div className="preview-row"><strong>02</strong><span><b>Cross-check findings</b><small>Evidence, severity, confidence</small></span><i>done</i></div><div className="preview-row active"><strong>03</strong><span><b>Your decision</b><small>Approve, reject, or inspect</small></span><i>waiting</i></div></div></section><section className="trust-strip" id="how-it-works"><div><strong>Evidence first</strong><span>Every finding points to code.</span></div><div><strong>Human controlled</strong><span>Nothing posts without approval.</span></div><div><strong>Measurable quality</strong><span>RAGAS scores show retrieval quality.</span></div></section>{user ? <section className="workspace" id="new-review"><nav className="workspace-tabs" aria-label="Workspace"><button type="button" className={activeTab === "review" ? "active" : ""} onClick={() => setActiveTab("review")}>Review</button><button type="button" className={activeTab === "providers" ? "active" : ""} onClick={() => setActiveTab("providers")}>Providers</button></nav>{activeTab === "providers" && <section className="panel provider-manager" id="providers"><div className="panel-kicker">Provider library</div><h2>Saved providers</h2><p className="provider-hint">Keep your model connections ready for future reviews.</p>{savedProviders.length ? <div className="saved-provider-list">{savedProviders.map(item => <div className="saved-provider" key={item.name}><strong>{item.name}</strong><small>{item.baseUrl || "Default API endpoint"}</small></div>)}</div> : <p className="provider-hint">No providers saved yet.</p>}<label htmlFor="provider-manager-type">Provider type<select id="provider-manager-type" value={provider || "openai"} onChange={e => setProvider(e.target.value)}><option value="openai">OpenAI-compatible</option><option value="anthropic">Anthropic</option><option value="google">Google</option></select></label><label htmlFor="provider-manager-model">Model<input id="provider-manager-model" value={model} onChange={e => setModel(e.target.value)} placeholder="model-name" /></label><label htmlFor="provider-manager-key">API key<input id="provider-manager-key" type="password" value={apiKey} onChange={e => setApiKey(e.target.value)} placeholder="Used for reviews" /></label><label htmlFor="provider-manager-base">Base URL <span>(optional)</span><input id="provider-manager-base" value={baseUrl} onChange={e => setBaseUrl(e.target.value)} placeholder="https://api.example.com/v1" /></label><div className="provider-actions"><button type="button" onClick={testProvider} disabled={testingProvider}>{testingProvider ? "Testing…" : "Test speed & JSON"}</button><button type="button" onClick={addProvider}>Add provider <span>+</span></button></div>{(error || message) && <div className={`message ${error ? "error" : "success"}`} role="status" aria-live="polite">{error || message}</div>}</section>}<form className={`panel form-panel ${activeTab === "providers" ? "is-hidden" : ""}`} onSubmit={startReview} aria-busy={busy}><div className="panel-kicker">New review</div><h2>Inspect a pull request</h2><label htmlFor="repo">Repository<input id="repo" value={repo} onChange={e => setRepo(e.target.value)} placeholder="owner/repository" autoComplete="off" /></label><label htmlFor="pr">Pull request<input id="pr" value={pr} onChange={e => setPr(e.target.value)} placeholder="42" inputMode="numeric" /></label><label htmlFor="endpoint">Provider<select id="endpoint" value={endpoint} onChange={e => setEndpoint(e.target.value)}><option value="auto">Automatic fallback</option><option value="gemini">Gemini</option><option value="groq">Groq</option>{savedProviders.map(item => <option key={item.name} value={`saved:${item.name}`}>{item.name}</option>)}</select></label><fieldset className="review-mode"><legend>Review depth</legend><label><input type="radio" name="review-mode" value="fast" checked={reviewMode === "fast"} onChange={() => setReviewMode("fast")} />Fast<span>Smaller prompts and response budget</span></label><label><input type="radio" name="review-mode" value="thorough" checked={reviewMode === "thorough"} onChange={() => setReviewMode("thorough")} />Thorough<span>More context and analysis</span></label></fieldset><details className="incremental-options"><summary>Review only changes since a commit</summary><label htmlFor="baseline-sha">Previously reviewed commit SHA<input id="baseline-sha" value={baselineSha} onChange={e => setBaselineSha(e.target.value)} placeholder="40-character commit SHA (optional)" pattern="[a-fA-F0-9]{40}" autoComplete="off" /></label><p className="provider-hint">When set, this reviews only changes since that commit, not the whole pull request.</p></details><button type="submit" disabled={busy}>{busy && !job ? "Queueing review…" : "Start review"}<span aria-hidden="true">↗</span></button>{(error || message) && <div className={`message ${error ? "error" : "success"}`} role="status" aria-live="polite">{error || message}</div>}{job && <div className="job-card"><div><strong>Review {job.id?.slice(0, 8)}</strong><small>{job.repo} · PR #{job.pr_number}</small></div><span className={`pill ${job.status}`}>{pretty(job.status)}</span></div>}{job && !isTerminal && <div className="progress" role="progressbar" aria-label={`Review ${pretty(job.status)}`}><span /><small>{job.queue_position ? `Queue position: ${job.queue_position}` : `Current stage: ${pretty(job.progress?.stage || job.status)}`}</small><button type="button" className="secondary" onClick={cancelReview} disabled={busy}>Cancel review</button></div>}<div className="results"><ReviewProgress job={job} /><Verdict job={job} /><Ragas ragas={job?.ragas} />{job?.findings?.length > 0 && <Findings findings={job.findings} />}{job?.status === "awaiting_approval" && job?.findings?.length === 0 && <Findings findings={[]} />}{job?.status === "awaiting_approval" && <div className="actions"><button type="button" onClick={() => decide("approve")} disabled={busy}>Approve &amp; post</button><button type="button" className="secondary" onClick={() => decide("reject")} disabled={busy}>Reject</button></div>}<Receipt result={job?.posting_result} />{job?.error && <div className="error detail">{job.error}</div>}</div></form><aside className={`panel signal-panel ${activeTab === "providers" ? "is-hidden" : ""}`}><div className="panel-kicker">What you receive</div><div className="signal"><strong>01</strong><span><b>Evidence-grounded findings</b><small>Code locations, severity, and confidence</small></span></div><div className="signal"><strong>02</strong><span><b>Human checkpoint</b><small>Approve or reject before GitHub comments</small></span></div><div className="signal"><strong>03</strong><span><b>Delivery receipt</b><small>See exactly what reached GitHub</small></span></div></aside></section> : <section className="auth-wall"><p className="eyebrow">Private review workspace</p><h2>Sign in to inspect a pull request.</h2><p>Your GitHub identity keeps reviews tied to your account and protects the review results.</p><a className="primary-link" href={`${API_BASE}/api/auth/github/start`}>Continue with GitHub <span>&rarr;</span></a></section>}</main><footer>OpenCodeReview <span>·</span> React review workspace <span>·</span> API keys stay server-side</footer></div>;
109
  }
110
  createRoot(document.getElementById("root")).render(<App />);
111
 
 
1
  import React, { useEffect, useMemo, useState } from "react";
2
  import { createRoot } from "react-dom/client";
3
  import "./styles.css";
4
+ import { reviewPayload, readProviders, initialEndpoint, groupFindings, formatCost, upsertProvider } from "./review-client.js";
5
 
6
  const API_BASE = (import.meta.env.VITE_REVIEW_API_URL || "").replace(/\/$/, "");
7
  const TERMINAL = new Set(["awaiting_approval", "rejected", "posted", "partially_posted", "post_failed", "failed", "incomplete", "cancelled"]);
 
11
  function Verdict({ job }) {
12
  if (!job?.verdict) return null;
13
  const v = job.verdict;
 
14
  const score = typeof v.overall_score === "number" ? v.overall_score : null;
15
  const scoreLabel = score == null ? "Not scored" : score < 4 ? "High risk" : score < 7 ? "Review carefully" : "Low risk";
16
+ const cost = formatCost(job.cost_details || job.cost);
17
+ return <section className={`result-card verdict ${["block", "request_changes", "incomplete"].includes(v.recommendation) ? "blocking" : "approved"}`} aria-labelledby="verdict-title">
18
  <div className="result-title"><div><span className="panel-kicker">Review decision</span><h3 id="verdict-title">{pretty(v.recommendation).toUpperCase()}</h3></div><div className="score-block"><strong className="score">{score == null ? "—" : `${score.toFixed(1)}/10`}</strong><span>{scoreLabel}</span></div></div>
19
+ <p>{v.summary || "The review is ready for your decision."}</p>
20
+ <div className="score-explanation"><strong>Risk estimate, not answer accuracy</strong><span>{v.score_explanation || (score == null ? "A reliable score is unavailable because review stages did not finish." : "The score reflects reported code risks. Test suggestions and unverified claims should be assessed separately.")}</span></div>
21
+ {v.score_breakdown && Object.keys(v.score_breakdown).length > 0 && <details><summary>How the score was calculated</summary><ul>{Object.entries(v.score_breakdown).map(([key,value]) => <li key={key}>{pretty(key)}: {typeof value === "object" ? JSON.stringify(value) : String(value)}</li>)}</ul></details>}
22
+ <div className="metrics"><span>{job.findings?.length || 0} findings and suggestions</span>{cost && <span>{cost}</span>}</div>
23
  </section>;
24
  }
25
 
26
+ function Findings({ findings = [], feedback = {}, onFeedback, feedbackBusy }) {
27
+ const groups = groupFindings(findings);
28
+ const titles = {bug: "Bugs", security_concern: "Security concerns", test_suggestion: "Suggested tests"};
29
+ return <section aria-labelledby="findings-title"><div className="section-heading"><h3 id="findings-title">Review findings</h3><span>{findings.length}</span></div>{findings.length ? Object.entries(groups).map(([kind, entries]) => entries.length > 0 && <section className="finding-group" key={kind} aria-label={titles[kind]}><h4>{titles[kind]} <span>{entries.length}</span></h4>{entries.map(({finding:f,index}) => <article className="finding" key={`${f.file_path}-${index}`}>
30
+ <div className="finding-meta"><span className={`severity ${String(f.severity || "info").toLowerCase()}`}>{f.severity || "info"}</span><span className="finding-location">{f.file_path || "Unknown file"}{f.line_start ? `:${f.line_start}${f.line_end && f.line_end !== f.line_start ? `–${f.line_end}` : ""}` : ""}</span></div>
31
+ <p>{f.comment || f.description || "No explanation provided."}</p>
32
+ <span className={`evidence-label ${f.evidence_status === "source_grounded" ? "grounded" : "uncertain"}`}>{f.evidence_status === "source_grounded" ? "Source location checked · claim needs your review" : f.evidence_status === "outside_diff" ? "Outside reviewed changes · needs verification" : "Needs verification"}</span>
33
+ {f.calibration_note && <p className="calibration-note">{f.calibration_note}</p>}
34
+ {f.evidence_excerpt && <details><summary>Supporting source excerpt</summary><pre className="evidence-excerpt">{f.evidence_excerpt}</pre></details>}
35
+ {f.suggested_fix && <details><summary>Suggested fix</summary><p>{f.suggested_fix}</p></details>}
36
+ {f.confidence != null && <small>Model confidence (uncalibrated) {Math.round(Number(f.confidence) * 100)}% · not independently measured</small>}
37
+ {onFeedback && <div className="finding-feedback" aria-label={`Feedback for finding ${index + 1}`}><span>Was this helpful?</span>{["correct","incorrect","useful"].map(label => <button type="button" key={label} disabled={feedbackBusy === index} aria-pressed={feedback[String(index)] === label} onClick={() => onFeedback(index,label)}>{label === "useful" ? "Useful suggestion" : pretty(label)}</button>)}{feedback[String(index)] && <small>Feedback saved</small>}</div>}
38
+ </article>)}</section>) : <div className="empty-result"><strong>No findings returned</strong><span>This does not prove the changes are free of issues. Check the review coverage and reviewer statuses.</span></div>}</section>;
39
+ }
40
+
41
+ function Coverage({ coverage }) {
42
+ if (!coverage) return null;
43
+ return <section className="result-card review-coverage" aria-label="Review coverage"><span className="panel-kicker">What was reviewed</span><p>{coverage.files_available ?? coverage.files_changed ?? "Unknown"} files available · {coverage.incremental ? "incremental preview · " : ""}{pretty(coverage.mode || "review")} mode · {coverage.diff_chars ?? "Unknown"} diff characters</p>{coverage.changed_file_paths?.length > 0 && <details><summary>Files in scope</summary><ul>{coverage.changed_file_paths.map(path => <li key={path}>{path}</li>)}</ul></details>}{coverage.limitations?.length > 0 && <ul>{coverage.limitations.map((note,index) => <li key={index}>{note}</li>)}</ul>}{coverage.reviewers?.length > 0 && <details><summary>Reviewer coverage</summary><ul>{coverage.reviewers.map((reviewer,index) => <li key={index}>{pretty(reviewer.reviewer || reviewer.name)}: {pretty(reviewer.status)}{reviewer.diff_chars_included != null ? ` · ${reviewer.diff_chars_included} diff characters included` : ""}{reviewer.limitations?.map((note,i) => <p key={i}>{note}</p>)}</li>)}</ul></details>}</section>;
44
  }
45
 
46
  function Receipt({ result }) {
47
  if (!result) return null;
48
+ return <section className="result-card receipt" aria-labelledby="receipt-title"><span className="panel-kicker">Delivery receipt</span><h3 id="receipt-title">{pretty(result.status || "completed")}</h3><div className="metrics"><span>Inline: {result.inline_posted || 0}</span><span>Fallback: {result.fallback_posted || 0}</span><span>Finding failures: {result.finding_failed || 0}</span><span>Unverified findings withheld: {result.withheld_unverified || 0}</span><span>Verdict: {result.verdict_posted ? "posted" : "failed"}</span></div></section>;
49
  }
50
 
51
+ function Ragas({ ragas }) {
52
+ if (!ragas) return null;
53
+ const scores = ragas.scores || {};
54
+ const metrics = ragas.metrics || {};
55
+ const text = ragas.status === "pending" ? "Evaluating in the background…" : ragas.status === "failed" ? `Evaluation failed: ${ragas.error || "provider error"}` : ragas.status === "skipped" ? `Skipped: ${ragas.reason || "evaluation unavailable"}` : ragas.status === "unavailable" ? `Unavailable: ${ragas.error || "the scoring task was interrupted"}` : ragas.error || pretty(ragas.status);
56
+ return <section className="result-card receipt" aria-label="RAGAS evaluation"><span className="panel-kicker">Review evaluation (RAGAS)</span><p>{text}</p><p className="provider-hint">These metrics assess specific aspects of the response; they do not establish whether every code finding is correct.</p>{Object.keys(metrics).length > 0 ? <ul className="evaluation-metrics">{Object.entries(metrics).map(([key,metric]) => <li key={key}><strong>{pretty(key)}</strong><span>{pretty(metric.status)}{typeof metric.value === "number" ? ` · ${metric.value.toFixed(3)}` : ""}{metric.duration_seconds != null ? ` · ${Number(metric.duration_seconds).toFixed(1)}s` : ""}</span>{metric.error && <small>{metric.error}</small>}</li>)}</ul> : Object.keys(scores).length > 0 && <ul>{Object.entries(scores).map(([key,value]) => <li key={key}>{pretty(key)}: {typeof value === "number" ? value.toFixed(3) : String(value)}</li>)}</ul>}{ragas.evaluation && <details><summary>Evaluation configuration</summary><pre className="evidence-excerpt">{JSON.stringify(ragas.evaluation,null,2)}</pre></details>}</section>;
57
+ }
58
 
59
  function ReviewProgress({ job }) {
60
  if (!job) return null;
 
73
  const [reviewMode, setReviewMode] = useState("fast");
74
  const [baselineSha, setBaselineSha] = useState("");
75
  const [testingProvider, setTestingProvider] = useState(false);
76
+ const [editingProvider, setEditingProvider] = useState(null);
77
+ const [lastTest, setLastTest] = useState(null);
78
+ const [defaultProvider, setDefaultProvider] = useState(() => { try { return localStorage.getItem("ocr-default-provider") || ""; } catch { return ""; } });
79
+ const [feedbackBusy, setFeedbackBusy] = useState(null);
80
+
81
+ const [repo, setRepo] = useState(""); const [pr, setPr] = useState(""); const [endpoint, setEndpoint] = useState(() => initialEndpoint(localStorage)); const [provider, setProvider] = useState("openai"); const [model, setModel] = useState(""); const [apiKey, setApiKey] = useState(""); const [baseUrl, setBaseUrl] = useState("");
82
  const [savedProviders, setSavedProviders] = useState(() => readProviders(localStorage));
83
  const [theme, setTheme] = useState(() => localStorage.getItem("ocr-theme") || "light"); const [job, setJob] = useState(null); const [message, setMessage] = useState(""); const [error, setError] = useState(""); const [busy, setBusy] = useState(false); const [user, setUser] = useState(null);
84
  useEffect(() => { fetch(apiUrl("/api/auth/me"), { credentials: "include" }).then(r => r.ok ? r.json() : null).then(setUser).catch(() => setUser(null)); }, []);
 
91
  poll(); const timer = window.setInterval(poll, 3000); return () => { stopped = true; window.clearInterval(timer); };
92
  }, [job?.id, isTerminal, job?.ragas?.status]);
93
 
94
+ function providerDraft() {
95
+ return {name: `${provider || "openai"} / ${model.trim()}`, provider: provider || "openai", model: model.trim(), apiKey: apiKey.trim(), baseUrl: baseUrl.trim()};
96
+ }
97
+ function saveEntries(entries) {
98
+ localStorage.setItem("ocr-providers", JSON.stringify(entries)); setSavedProviders(entries);
99
+ }
100
+ function editProvider(item) {
101
+ setEditingProvider(item.name); setProvider(item.provider); setModel(item.model); setApiKey(item.apiKey); setBaseUrl(item.baseUrl || ""); setLastTest(item.lastTest || null); setError(""); setMessage(`Editing ${item.name}. Changes are saved when you click Save changes.`);
102
+ }
103
+ function removeProvider(item) {
104
+ try {
105
+ saveEntries(savedProviders.filter(entry => entry.name !== item.name));
106
+ if (defaultProvider === item.name) { localStorage.removeItem("ocr-default-provider"); setDefaultProvider(""); }
107
+ if (endpoint === `saved:${item.name}`) setEndpoint("auto");
108
+ if (editingProvider === item.name) resetProviderDraft();
109
+ setError(""); setMessage(`${item.name} removed from this browser.`);
110
+ } catch { setError("Could not remove provider from browser storage."); }
111
+ }
112
+ function makeDefault(item) {
113
+ try { localStorage.setItem("ocr-default-provider",item.name); setDefaultProvider(item.name); setEndpoint(`saved:${item.name}`); setError(""); setMessage(`${item.name} is the default for new reviews.`); }
114
+ catch { setError("Could not save the default provider."); }
115
+ }
116
+ function resetProviderDraft() { setEditingProvider(null); setModel(""); setApiKey(""); setBaseUrl(""); setProvider("openai"); setLastTest(null); setError(""); setMessage(""); }
117
  async function testProvider() {
118
  if (!model.trim() || !apiKey.trim()) { setError("Enter a model and API key before testing."); return; }
119
+ const draft = providerDraft();
120
  setError(""); setMessage("Testing response time and JSON output…"); setTestingProvider(true);
121
  try {
122
+ const response = await fetch("/api/provider-test", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({provider:draft.provider, model:draft.model, apiKey:draft.apiKey, baseUrl:draft.baseUrl}) });
123
  const result = await response.json();
124
  if (!response.ok) throw new Error(result.error || "Provider test failed.");
125
+ const tested = {at: new Date().toISOString(), latency_ms:result.latency_ms, json_valid:result.json_object_valid, fingerprint:JSON.stringify(draft)};
126
+ setLastTest(tested);
127
+ const saved = savedProviders.find(item => item.name === draft.name && item.apiKey === draft.apiKey && item.baseUrl === draft.baseUrl);
128
+ if (saved) saveEntries(savedProviders.map(item => item.name === saved.name ? {...item,lastTest:{at:tested.at,latency_ms:tested.latency_ms,json_valid:tested.json_valid}} : item));
129
  setMessage(`Connection verified in ${(result.latency_ms / 1000).toFixed(1)}s. JSON response: ${result.json_object_valid ? "valid" : "invalid — this model may need a different output format"}.`);
130
+ } catch (err) { setLastTest(null); setMessage(""); setError(err.message); } finally { setTestingProvider(false); }
131
  }
132
  function addProvider() {
133
  if (!model.trim() || !apiKey.trim()) { setError("Enter a model and API key first."); return; }
134
+ const item = providerDraft();
135
+ const freshTest = lastTest?.fingerprint === JSON.stringify(item) ? lastTest : null;
136
+ if (freshTest) item.lastTest = {at:freshTest.at,latency_ms:freshTest.latency_ms,json_valid:freshTest.json_valid};
137
+ const previous = savedProviders.find(entry => entry.name === editingProvider);
138
+ if (!freshTest && previous && previous.provider === item.provider && previous.model === item.model && previous.apiKey === item.apiKey && (previous.baseUrl || "") === item.baseUrl) item.lastTest = previous.lastTest;
139
  try {
140
+ saveEntries(upsertProvider(savedProviders,item,editingProvider));
141
+ if (editingProvider && defaultProvider === editingProvider) { localStorage.setItem("ocr-default-provider",item.name); setDefaultProvider(item.name); }
142
+ setEditingProvider(item.name); setEndpoint(`saved:${item.name}`); setError(""); setMessage(`${item.name} saved. Select it in Review.`);
143
  } catch { setMessage(""); setError("Browser storage is unavailable. Provider could not be saved."); }
144
  }
145
+ async function saveFeedback(index,label) {
146
+ if (!job?.id) return;
147
+ setFeedbackBusy(index); setError("");
148
+ try {
149
+ const response = await fetch(apiUrl(`/api/reviews/${job.id}/feedback`), {method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({finding_index:index,label})});
150
+ const result = await response.json();
151
+ if (!response.ok) throw new Error(result.detail || "Could not save feedback.");
152
+ setJob(current => current?.id === job.id ? {...current,feedback:result.feedback} : current);
153
+ } catch(err) { setError(err.message); } finally { setFeedbackBusy(null); }
154
+ }
155
  async function startReview(e) {
156
  e.preventDefault(); setError("");
157
  if (!/^[-\w.]+\/[-\w.]+$/.test(repo.trim()) || !Number.isInteger(Number(pr)) || Number(pr) < 1) { setError("Enter a repository as owner/name and a valid PR number."); return; }
 
174
  } catch (err) { setError(err.message); } finally { setBusy(false); }
175
  }
176
  async function decide(action) { if (!job?.id) return; setBusy(true); setError(""); setMessage(action === "approve" ? "Posting approved review…" : "Rejecting review…"); try { const r = await fetch(apiUrl(`/api/reviews/${job.id}/decision`), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action }) }); const data = await r.json().catch(() => ({})); if (!r.ok) throw new Error(data.detail || `Decision failed (${r.status})`); setJob(data); setMessage(action === "approve" ? "Review delivery finished." : "Review rejected. Nothing was posted to GitHub."); } catch (e) { setError(e.message); } finally { setBusy(false); } }
177
+ return <div className="shell"><header className="topbar"><div className="brand"><span className="brand-mark">OC</span><span>OpenCodeReview</span></div><div>{user ? <><span className="status-dot">Signed in as {user.login}</span><button className="auth-button" onClick={logout}>Sign out</button></> : <a className="status-dot" href={`${API_BASE}/api/auth/github/start`}>Sign in with GitHub</a>}<span className="status-dot">Human approval required</span><button className="theme-toggle" type="button" onClick={() => setTheme(theme === "dark" ? "light" : "dark")} aria-label="Toggle color theme">{theme === "dark" ? "Light" : "Dark"}</button></div></header><main className="content"><section className="hero"><p className="eyebrow">Pull request intelligence</p><h1>Review changes with<br /><em>evidence before action.</em></h1><p className="lede">Parallel analysis for correctness, security, and test coverage. Nothing is posted to GitHub until you approve it.</p></section><section className="intro-band"><div className="intro-copy"><p className="eyebrow">AI code review with a human checkpoint</p><h2>Know what changed<br /><em>before it ships.</em></h2><p>OpenCodeReview traces pull requests back to the diff, checks correctness and security, then gives you the evidence to decide what reaches GitHub.</p><div className="intro-actions"><a className="primary-link" href={user ? "#new-review" : `${API_BASE}/api/auth/github/start`}>Start a review <span>&rarr;</span></a><a className="quiet-link" href="#how-it-works">See how it works</a></div></div><div className="review-preview" aria-label="Review workflow preview"><div className="preview-top"><span className="live-dot"></span><span>REVIEW PIPELINE</span><span className="preview-time">LIVE</span></div><div className="preview-row"><strong>01</strong><span><b>Read the diff</b><small>Files, lines, and context</small></span><i>done</i></div><div className="preview-row"><strong>02</strong><span><b>Cross-check findings</b><small>Evidence, severity, confidence</small></span><i>done</i></div><div className="preview-row active"><strong>03</strong><span><b>Your decision</b><small>Approve, reject, or inspect</small></span><i>waiting</i></div></div></section><section className="trust-strip" id="how-it-works"><div><strong>Evidence first</strong><span>Every finding points to code.</span></div><div><strong>Human controlled</strong><span>Nothing posts without approval.</span></div><div><strong>Measurable quality</strong><span>RAGAS scores show retrieval quality.</span></div></section>{user ? <section className="workspace" id="new-review"><nav className="workspace-tabs" aria-label="Workspace"><button type="button" className={activeTab === "review" ? "active" : ""} onClick={() => { setActiveTab("review"); setError(""); setMessage(""); }}>Review</button><button type="button" className={activeTab === "providers" ? "active" : ""} onClick={() => { setActiveTab("providers"); setError(""); setMessage(""); }}>Providers</button></nav>{activeTab === "providers" && <section className="panel provider-manager" id="providers"><div className="panel-kicker">Provider library</div><h2>Saved providers</h2><p className="provider-hint">Keep your model connections ready for future reviews.</p>{savedProviders.length ? <div className="saved-provider-list">{savedProviders.map(item => <div className="saved-provider" key={item.name}><div className="provider-entry-title"><strong>{item.name}</strong>{defaultProvider === item.name && <span className="pill">Default</span>}</div><small>{item.baseUrl || "Default API endpoint"}</small><small>{item.lastTest ? `Last successful connection: ${new Date(item.lastTest.at).toLocaleString()} · ${(Number(item.lastTest.latency_ms) / 1000).toFixed(1)}s · JSON ${item.lastTest.json_valid ? "valid" : "invalid"}` : "Connection has not been tested"}</small><div className="provider-entry-actions"><button type="button" onClick={() => editProvider(item)} aria-label={`Edit ${item.name}`}>Edit</button><button type="button" onClick={() => makeDefault(item)} disabled={defaultProvider === item.name} aria-label={`Make ${item.name} default`}>Make default</button><button type="button" onClick={() => removeProvider(item)} aria-label={`Delete ${item.name}`}>Delete</button></div></div>)}</div> : <p className="provider-hint">No providers saved yet.</p>}<div className="provider-form-heading"><h3>{editingProvider ? "Edit provider" : "Add a provider"}</h3>{editingProvider && <button type="button" onClick={resetProviderDraft}>New provider</button>}</div><p className="provider-hint">Saved on this browser. Keys are hidden from the list and sent only when a provider is tested or used.</p><label htmlFor="provider-manager-type">Provider type<select id="provider-manager-type" value={provider || "openai"} onChange={e => setProvider(e.target.value)}><option value="openai">OpenAI-compatible</option><option value="anthropic">Anthropic</option><option value="google">Google</option></select></label><label htmlFor="provider-manager-model">Model<input id="provider-manager-model" value={model} onChange={e => setModel(e.target.value)} placeholder="model-name" /></label><label htmlFor="provider-manager-key">API key<input id="provider-manager-key" type="password" value={apiKey} onChange={e => setApiKey(e.target.value)} placeholder="Used for reviews" /></label><label htmlFor="provider-manager-base">Base URL <span>(optional)</span><input id="provider-manager-base" value={baseUrl} onChange={e => setBaseUrl(e.target.value)} placeholder="https://api.example.com/v1" /></label><div className="provider-actions"><button type="button" onClick={testProvider} disabled={testingProvider}>{testingProvider ? "Testing…" : "Test speed & JSON"}</button><button type="button" onClick={addProvider}>{editingProvider ? "Save changes" : "Add provider"}<span>+</span></button></div>{(error || message) && <div className={`message ${error ? "error" : "success"}`} role="status" aria-live="polite">{error || message}</div>}</section>}<form className={`panel form-panel ${activeTab === "providers" ? "is-hidden" : ""}`} onSubmit={startReview} aria-busy={busy}><div className="panel-kicker">New review</div><h2>Inspect a pull request</h2><label htmlFor="repo">Repository<input id="repo" value={repo} onChange={e => setRepo(e.target.value)} placeholder="owner/repository" autoComplete="off" /></label><label htmlFor="pr">Pull request<input id="pr" value={pr} onChange={e => setPr(e.target.value)} placeholder="42" inputMode="numeric" /></label><label htmlFor="endpoint">Provider<select id="endpoint" value={endpoint} onChange={e => setEndpoint(e.target.value)}><option value="auto">Automatic fallback</option><option value="gemini">Gemini</option><option value="groq">Groq</option>{savedProviders.map(item => <option key={item.name} value={`saved:${item.name}`}>{item.name}</option>)}</select></label><fieldset className="review-mode"><legend>Review depth</legend><label><input type="radio" name="review-mode" value="fast" checked={reviewMode === "fast"} onChange={() => setReviewMode("fast")} />Fast<span>Smaller prompts and response budget</span></label><label><input type="radio" name="review-mode" value="thorough" checked={reviewMode === "thorough"} onChange={() => setReviewMode("thorough")} />Thorough<span>More context and analysis</span></label></fieldset><details className="incremental-options"><summary>Review only changes since a commit</summary><label htmlFor="baseline-sha">Previously reviewed commit SHA<input id="baseline-sha" value={baselineSha} onChange={e => setBaselineSha(e.target.value)} placeholder="40-character commit SHA (optional)" pattern="[a-fA-F0-9]{40}" autoComplete="off" /></label><p className="provider-hint">When set, this reviews only changes since that commit, not the whole pull request.</p></details><button type="submit" disabled={busy}>{busy && !job ? "Queueing review…" : "Start review"}<span aria-hidden="true">↗</span></button>{(error || message) && <div className={`message ${error ? "error" : "success"}`} role="status" aria-live="polite">{error || message}</div>}{job && <div className="job-card"><div><strong>Review {job.id?.slice(0, 8)}</strong><small>{job.repo} · PR #{job.pr_number}</small></div><span className={`pill ${job.status}`}>{pretty(job.status)}</span></div>}{job && !isTerminal && <div className="progress" role="progressbar" aria-label={`Review ${pretty(job.status)}`}><span /><small>{job.queue_position ? `Queue position: ${job.queue_position}` : `Current stage: ${pretty(job.progress?.stage || job.status)}`}</small><button type="button" className="secondary" onClick={cancelReview} disabled={busy}>Cancel review</button></div>}<div className="results"><ReviewProgress job={job} /><Verdict job={job} /><Coverage coverage={job?.review_coverage || job?.coverage} /><Ragas ragas={job?.ragas} />{job?.findings?.length > 0 && <Findings findings={job.findings} feedback={job.feedback} onFeedback={isTerminal ? saveFeedback : undefined} feedbackBusy={feedbackBusy} />}{job?.status === "awaiting_approval" && job?.findings?.length === 0 && <Findings findings={[]} />}{job?.status === "awaiting_approval" && <div className="actions"><button type="button" onClick={() => decide("approve")} disabled={busy}>Approve &amp; post</button><button type="button" className="secondary" onClick={() => decide("reject")} disabled={busy}>Reject</button></div>}<Receipt result={job?.posting_result} />{job?.error && <div className="error detail">{job.error}</div>}</div></form><aside className={`panel signal-panel ${activeTab === "providers" ? "is-hidden" : ""}`}><div className="panel-kicker">What you receive</div><div className="signal"><strong>01</strong><span><b>Evidence-grounded findings</b><small>Code locations, severity, and confidence</small></span></div><div className="signal"><strong>02</strong><span><b>Human checkpoint</b><small>Approve or reject before GitHub comments</small></span></div><div className="signal"><strong>03</strong><span><b>Delivery receipt</b><small>See exactly what reached GitHub</small></span></div></aside></section> : <section className="auth-wall"><p className="eyebrow">Private review workspace</p><h2>Sign in to inspect a pull request.</h2><p>Your GitHub identity keeps reviews tied to your account and protects the review results.</p><a className="primary-link" href={`${API_BASE}/api/auth/github/start`}>Continue with GitHub <span>&rarr;</span></a></section>}</main><footer>OpenCodeReview <span>·</span> React review workspace <span>·</span> API keys stay server-side</footer></div>;
178
  }
179
  createRoot(document.getElementById("root")).render(<App />);
180
 
frontend/src/review-client.js CHANGED
@@ -5,6 +5,38 @@ export function readProviders(storage) {
5
  } catch { return []; }
6
  }
7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  export function reviewPayload(repo, pr, endpoint, savedProviders, reviewMode, baselineSha = "") {
9
  const payload = { repo: repo.trim(), pr_number: Number(pr), endpoint, review_mode: reviewMode };
10
  if (baselineSha.trim()) {
 
5
  } catch { return []; }
6
  }
7
 
8
+ export function initialEndpoint(storage) {
9
+ try {
10
+ const name = storage.getItem('ocr-default-provider');
11
+ return readProviders(storage).some(item => item.name === name) ? `saved:${name}` : 'auto';
12
+ } catch { return 'auto'; }
13
+ }
14
+
15
+ export function groupFindings(findings) {
16
+ const groups = {bug: [], security_concern: [], test_suggestion: []};
17
+ findings.forEach((finding, index) => {
18
+ const fallback = finding.category === 'test_coverage' ? 'test_suggestion' : finding.category === 'security' ? 'security_concern' : 'bug';
19
+ groups[Object.hasOwn(groups, finding.kind) ? finding.kind : fallback].push({finding, index});
20
+ });
21
+ return groups;
22
+ }
23
+
24
+ export function formatCost(cost) {
25
+ if (!cost) return null;
26
+ if (typeof cost === 'string') return cost.replace(/^Cost:\s*/i, '');
27
+ if (typeof cost === 'object') {
28
+ const source = cost.source || cost.cost_source || 'unknown';
29
+ const amount = cost.total_cost ?? cost.amount;
30
+ const labels = {provider_reported:'Provider-reported',provider:'Provider-reported',measured:'Provider-reported',estimated:'Estimated, not a confirmed charge',free_model_estimate:'Free-model estimate, not a confirmed charge',mixed:'Mixed reported and estimated cost',unknown:'Cost information'};
31
+ return `${labels[source] || 'Cost information'}${typeof amount === 'number' ? `: $${amount.toFixed(4)}` : ': unavailable'}${cost.complete === false ? ' · partial usage data' : ''}`;
32
+ }
33
+ return 'Cost unavailable';
34
+ }
35
+
36
+ export function upsertProvider(entries, item, previousName = null) {
37
+ return [...entries.filter(entry => entry.name !== item.name && entry.name !== previousName), item];
38
+ }
39
+
40
  export function reviewPayload(repo, pr, endpoint, savedProviders, reviewMode, baselineSha = "") {
41
  const payload = { repo: repo.trim(), pr_number: Number(pr), endpoint, review_mode: reviewMode };
42
  if (baselineSha.trim()) {
frontend/src/review-client.test.js CHANGED
@@ -1,6 +1,6 @@
1
  import test from 'node:test';
2
  import assert from 'node:assert/strict';
3
- import { readProviders, reviewPayload } from './review-client.js';
4
 
5
  test('saved model supplies its own credentials even when provider draft differs', () => {
6
  const entries = [{name:'openrouter/test',provider:'openai',model:' model-a ',apiKey:' saved-key ',baseUrl:' https://openrouter.ai/api/v1 '}];
@@ -24,3 +24,27 @@ test('incremental baseline is explicit and requires a full commit SHA', () => {
24
  assert.throws(() => reviewPayload('owner/repo',1,'groq',[],'fast','abc'), /40-character/);
25
  assert.equal(reviewPayload('owner/repo',1,'groq',[],'fast','A'.repeat(40)).baseline_sha,'a'.repeat(40));
26
  });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import test from 'node:test';
2
  import assert from 'node:assert/strict';
3
+ import { readProviders, reviewPayload, initialEndpoint, groupFindings, formatCost, upsertProvider } from './review-client.js';
4
 
5
  test('saved model supplies its own credentials even when provider draft differs', () => {
6
  const entries = [{name:'openrouter/test',provider:'openai',model:' model-a ',apiKey:' saved-key ',baseUrl:' https://openrouter.ai/api/v1 '}];
 
24
  assert.throws(() => reviewPayload('owner/repo',1,'groq',[],'fast','abc'), /40-character/);
25
  assert.equal(reviewPayload('owner/repo',1,'groq',[],'fast','A'.repeat(40)).baseline_sha,'a'.repeat(40));
26
  });
27
+
28
+ test('finding groups preserve original feedback indices while separating suggestions', () => {
29
+ const input = [{category:'test_coverage'}, {kind:'security_concern'}, {kind:'bug'}];
30
+ const groups = groupFindings(input);
31
+ assert.equal(groups.test_suggestion[0].index,0);
32
+ assert.equal(groups.security_concern[0].index,1);
33
+ assert.equal(groups.bug[0].index,2);
34
+ });
35
+
36
+ test('default provider is selected only while its saved connection exists', () => {
37
+ const storage = {getItem:key => key === 'ocr-default-provider' ? 'saved-one' : JSON.stringify([{name:'saved-one',provider:'openai',model:'m',apiKey:'k'}])};
38
+ assert.equal(initialEndpoint(storage),'saved:saved-one');
39
+ assert.equal(initialEndpoint({getItem:key => key === 'ocr-default-provider' ? 'removed' : '[]'}),'auto');
40
+ });
41
+
42
+ test('editing a renamed provider replaces the old entry instead of duplicating it', () => {
43
+ assert.deepEqual(upsertProvider([{name:'old'},{name:'other'}],{name:'new'},'old'),[{name:'other'},{name:'new'}]);
44
+ });
45
+
46
+ test('cost display distinguishes estimates and does not duplicate the Cost label', () => {
47
+ assert.equal(formatCost('Cost: Estimated $0.05'),'Estimated $0.05');
48
+ assert.equal(formatCost({source:'estimated',amount:0.05}),'Estimated, not a confirmed charge: $0.0500');
49
+ assert.equal(formatCost({source:'provider',total_cost:0}),'Provider-reported: $0.0000');
50
+ });
frontend/src/styles.css CHANGED
@@ -45,3 +45,4 @@ html:not([data-theme="dark"]) .verdict.blocking{background:#fff8f8;color:#2f3437
45
  .provider-actions{display:flex;gap:10px;margin-top:12px}.provider-actions button{width:auto;flex:1;margin:0}.provider-actions button:first-child{background:transparent;border:1px solid var(--line);color:var(--muted)}
46
 
47
  .review-mode{border:1px solid var(--line);border-radius:6px;padding:12px;margin:20px 0;display:grid;gap:10px}.review-mode legend{font-size:12px;color:var(--muted);padding:0 6px}.review-mode label{display:grid;grid-template-columns:20px 1fr;gap:6px;margin:0;text-transform:none;letter-spacing:0;font:600 14px Arial,sans-serif;color:inherit}.review-mode input{width:16px;height:16px;margin:0;grid-row:1/3;box-shadow:none}.review-mode label span{grid-column:2;font-size:12px;font-weight:400;color:var(--muted)}.review-progress{margin:16px 0}.reviewer-stages{padding:0;list-style:none;display:grid;gap:8px}.reviewer-stages li{border:1px solid var(--line);padding:10px;display:grid;gap:5px;border-radius:6px}.reviewer-stages small,.reviewer-stages span{color:var(--muted);overflow-wrap:anywhere}.reviewer-stages .reviewer-error{color:#b74335}html[data-theme="dark"] .reviewer-stages .reviewer-error{color:#ffb4a9}.review-progress details{margin:14px 0;color:var(--muted);font-size:12px}.review-progress summary{cursor:pointer}.progress button{width:auto;font-size:12px;padding:8px 12px}.provider-actions button:disabled{cursor:wait;opacity:.6}
 
 
45
  .provider-actions{display:flex;gap:10px;margin-top:12px}.provider-actions button{width:auto;flex:1;margin:0}.provider-actions button:first-child{background:transparent;border:1px solid var(--line);color:var(--muted)}
46
 
47
  .review-mode{border:1px solid var(--line);border-radius:6px;padding:12px;margin:20px 0;display:grid;gap:10px}.review-mode legend{font-size:12px;color:var(--muted);padding:0 6px}.review-mode label{display:grid;grid-template-columns:20px 1fr;gap:6px;margin:0;text-transform:none;letter-spacing:0;font:600 14px Arial,sans-serif;color:inherit}.review-mode input{width:16px;height:16px;margin:0;grid-row:1/3;box-shadow:none}.review-mode label span{grid-column:2;font-size:12px;font-weight:400;color:var(--muted)}.review-progress{margin:16px 0}.reviewer-stages{padding:0;list-style:none;display:grid;gap:8px}.reviewer-stages li{border:1px solid var(--line);padding:10px;display:grid;gap:5px;border-radius:6px}.reviewer-stages small,.reviewer-stages span{color:var(--muted);overflow-wrap:anywhere}.reviewer-stages .reviewer-error{color:#b74335}html[data-theme="dark"] .reviewer-stages .reviewer-error{color:#ffb4a9}.review-progress details{margin:14px 0;color:var(--muted);font-size:12px}.review-progress summary{cursor:pointer}.progress button{width:auto;font-size:12px;padding:8px 12px}.provider-actions button:disabled{cursor:wait;opacity:.6}
48
+ .finding-group{margin-top:24px}.finding-group h4{font-size:15px;display:flex;gap:8px;align-items:center}.finding-group h4 span{font-size:12px;color:var(--muted)}.evidence-label{display:inline-block;font-size:11px;line-height:1.6;margin:6px 0;color:#42614a}.evidence-label.uncertain{color:#855c20}.evidence-excerpt{white-space:pre-wrap;overflow-wrap:anywhere;font:12px/1.65 'DM Mono',monospace;max-height:280px;overflow:auto;padding:12px;border:1px solid var(--line);border-radius:5px}.calibration-note{font-size:12px!important;color:var(--muted)!important}.finding-feedback{display:flex;gap:7px;align-items:center;flex-wrap:wrap;margin-top:14px;padding-top:12px;border-top:1px solid var(--line)}.finding-feedback>span{font-size:12px;color:var(--muted)}.finding-feedback button,.provider-entry-actions button,.provider-form-heading button{width:auto;margin:0;padding:7px 11px;display:inline-flex;justify-content:center;border:1px solid var(--line);font-size:12px;font-weight:500;background:transparent;color:inherit}.finding-feedback button[aria-pressed="true"]{background:#dbe8dc;border-color:#799b7c;color:#24482b}.finding-feedback small{width:100%}.provider-entry-title,.provider-form-heading{display:flex;gap:10px;justify-content:space-between;align-items:center;flex-wrap:wrap}.provider-entry-actions{display:flex;gap:8px;flex-wrap:wrap;margin-top:10px}.provider-form-heading{margin-top:28px}.provider-form-heading h3{margin:0}.provider-entry-actions button:disabled{opacity:.5;cursor:default}.review-coverage{overflow-wrap:anywhere}.review-coverage ul,.evaluation-metrics{padding-left:18px;font-size:13px;line-height:1.7}.evaluation-metrics li{margin-bottom:10px}.evaluation-metrics strong,.evaluation-metrics span,.evaluation-metrics small{display:block}.evaluation-metrics small{color:var(--muted)}html[data-theme="dark"] .evidence-label{color:#b2d4b7}html[data-theme="dark"] .evidence-label.uncertain{color:#e4c48c}html[data-theme="dark"] .finding-feedback button,html[data-theme="dark"] .provider-entry-actions button,html[data-theme="dark"] .provider-form-heading button{background:transparent;color:#e8edf0}html[data-theme="dark"] .finding-feedback button[aria-pressed="true"]{background:#294334;color:#d4edda;border-color:#759b7e}
nodes/aggregator.py CHANGED
@@ -5,6 +5,7 @@ import os
5
  from pathlib import Path
6
 
7
  from llm_factory import create_llm
 
8
  from pydantic import BaseModel, Field
9
 
10
  from state import Finding, OpenCodeReviewState, Severity, Verdict
@@ -79,7 +80,8 @@ def _deduplicate(findings: list[Finding]) -> list[Finding]:
79
  for f in sorted_fs[1:]:
80
  same_file = f.file_path == current.file_path
81
  close_lines = abs(f.line_start - current.line_start) <= LINE_TOLERANCE
82
- if same_file and close_lines:
 
83
  # Keep the higher-confidence finding, merge comments
84
  if f.confidence > current.confidence:
85
  current = f
@@ -123,8 +125,11 @@ def _more_severe(a: Severity, b: Severity) -> Severity:
123
 
124
  def _rule_verdict(findings: list[Finding]) -> Verdict:
125
  """Build a verdict from deduplicated findings without an LLM call."""
 
 
 
126
  counts = {s: 0 for s in Severity}
127
- for f in findings:
128
  counts[f.severity] = counts.get(f.severity, 0) + 1
129
 
130
  critical = counts[Severity.CRITICAL]
@@ -136,7 +141,7 @@ def _rule_verdict(findings: list[Finding]) -> Verdict:
136
  elif high > 0:
137
  recommendation = "request_changes"
138
  approved = False
139
- elif len(findings) > 0:
140
  recommendation = "comment"
141
  approved = True
142
  else:
@@ -149,19 +154,23 @@ def _rule_verdict(findings: list[Finding]) -> Verdict:
149
  severity_counts = {s.value: counts.get(s, 0) for s in Severity}
150
 
151
  return Verdict(
152
- summary=_rule_summary(recommendation, severity_counts),
153
  approved=approved,
154
  overall_score=round(score, 1),
155
  critical_count=critical,
156
  high_count=high,
157
  recommendation=recommendation,
 
 
 
 
158
  )
159
 
160
 
161
  def _rule_summary(recommendation: str, counts: dict) -> str:
162
  parts = [f"{v} {k}" for k, v in counts.items() if v > 0]
163
  if not parts:
164
- return "No issues found — PR looks clean."
165
  body = ", ".join(parts)
166
  if recommendation == "block":
167
  return f"Blocking: {body} — critical issues must be resolved."
@@ -214,25 +223,20 @@ def aggregator_node(state: OpenCodeReviewState) -> dict:
214
  2. Rule-based verdict by default (fast, ~10ms), or optional LLM critic
215
  when ``USE_LLM_CRITIC`` is enabled.
216
  """
 
 
217
  failed = [stage for stage in state.review_stages if stage.get("status") == "failed"]
218
  if failed:
219
  names = ", ".join(stage["reviewer"] for stage in failed)
220
- return {"final_findings": _deduplicate(state.findings), "verdict": Verdict(
221
  summary=f"Review incomplete: {names} failed. Findings are partial; no approval or quality score is available.",
222
  approved=False, overall_score=None, recommendation="incomplete",
 
223
  )}
224
- raw_findings = state.findings
225
  if not raw_findings:
226
  logger.info("No findings to aggregate — producing empty verdict")
227
- empty_verdict = Verdict(
228
- summary="No issues found — PR looks clean.",
229
- approved=True,
230
- overall_score=10.0,
231
- critical_count=0,
232
- high_count=0,
233
- recommendation="approve",
234
- )
235
- return {"final_findings": [], "verdict": empty_verdict}
236
 
237
  # -- Phase 1: Heuristic dedup --------------------------------------------
238
  deduped = _deduplicate(raw_findings)
@@ -266,14 +270,14 @@ def aggregator_node(state: OpenCodeReviewState) -> dict:
266
  result = None
267
 
268
  if result is not None:
269
- final_findings = result.findings
270
- verdict = result.verdict
271
  logger.info(
272
  "LLM aggregator: %d deduped → %d final, recommendation=%s",
273
  len(deduped), len(final_findings),
274
  verdict.recommendation,
275
  )
276
- return {"final_findings": final_findings, "verdict": verdict}
277
 
278
  # Rule-based path (default) — zero LLM overhead
279
  logger.info("Using rule-based aggregation (fast path)")
@@ -281,6 +285,7 @@ def aggregator_node(state: OpenCodeReviewState) -> dict:
281
  verdict = _rule_verdict(deduped)
282
 
283
  return {
 
284
  "final_findings": final_findings, # plain list, overwrites
285
  "verdict": verdict, # set-once, no reducer needed
286
  }
 
5
  from pathlib import Path
6
 
7
  from llm_factory import create_llm
8
+ from nodes.finding_quality import calibrate_findings, review_coverage
9
  from pydantic import BaseModel, Field
10
 
11
  from state import Finding, OpenCodeReviewState, Severity, Verdict
 
80
  for f in sorted_fs[1:]:
81
  same_file = f.file_path == current.file_path
82
  close_lines = abs(f.line_start - current.line_start) <= LINE_TOLERANCE
83
+ same_claim = " ".join(f.comment.lower().split()) == " ".join(current.comment.lower().split())
84
+ if same_file and close_lines and f.kind == current.kind and f.category == current.category and same_claim:
85
  # Keep the higher-confidence finding, merge comments
86
  if f.confidence > current.confidence:
87
  current = f
 
125
 
126
  def _rule_verdict(findings: list[Finding]) -> Verdict:
127
  """Build a verdict from deduplicated findings without an LLM call."""
128
+ eligible = [f for f in findings if f.kind != "test_suggestion" and f.evidence_status == "source_grounded"]
129
+ suggestions = sum(f.kind == "test_suggestion" for f in findings)
130
+ unverified = sum(f.kind != "test_suggestion" and f.evidence_status != "source_grounded" for f in findings)
131
  counts = {s: 0 for s in Severity}
132
+ for f in eligible:
133
  counts[f.severity] = counts.get(f.severity, 0) + 1
134
 
135
  critical = counts[Severity.CRITICAL]
 
141
  elif high > 0:
142
  recommendation = "request_changes"
143
  approved = False
144
+ elif eligible or suggestions or unverified:
145
  recommendation = "comment"
146
  approved = True
147
  else:
 
154
  severity_counts = {s.value: counts.get(s, 0) for s in Severity}
155
 
156
  return Verdict(
157
+ summary=_rule_summary(recommendation, severity_counts) + (f" {suggestions} test suggestion(s), {unverified} unverified claim(s) are excluded from the score." if suggestions or unverified else ""),
158
  approved=approved,
159
  overall_score=round(score, 1),
160
  critical_count=critical,
161
  high_count=high,
162
  recommendation=recommendation,
163
+ score_explanation="Risk estimate from source-grounded findings, not answer correctness or proof of safety. Test suggestions and claims without source grounding do not lower the score.",
164
+ score_breakdown={"starting_score": 10, "critical_penalty": critical * 4, "high_penalty": high * 2,
165
+ "medium_penalty": counts[Severity.MEDIUM] * .5, "scored_findings": len(eligible),
166
+ "test_suggestions_excluded": suggestions, "unverified_claims_excluded": unverified},
167
  )
168
 
169
 
170
  def _rule_summary(recommendation: str, counts: dict) -> str:
171
  parts = [f"{v} {k}" for k, v in counts.items() if v > 0]
172
  if not parts:
173
+ return "No source-grounded defects detected. This does not establish that the PR is safe."
174
  body = ", ".join(parts)
175
  if recommendation == "block":
176
  return f"Blocking: {body} — critical issues must be resolved."
 
223
  2. Rule-based verdict by default (fast, ~10ms), or optional LLM critic
224
  when ``USE_LLM_CRITIC`` is enabled.
225
  """
226
+ coverage = review_coverage(state)
227
+ calibrated = calibrate_findings(state.findings, state)
228
  failed = [stage for stage in state.review_stages if stage.get("status") == "failed"]
229
  if failed:
230
  names = ", ".join(stage["reviewer"] for stage in failed)
231
+ return {"review_coverage": coverage, "final_findings": _deduplicate(calibrated), "verdict": Verdict(
232
  summary=f"Review incomplete: {names} failed. Findings are partial; no approval or quality score is available.",
233
  approved=False, overall_score=None, recommendation="incomplete",
234
+ score_explanation="No overall risk score is available because one or more reviewers failed. Remaining findings are partial.",
235
  )}
236
+ raw_findings = calibrated
237
  if not raw_findings:
238
  logger.info("No findings to aggregate — producing empty verdict")
239
+ return {"review_coverage": coverage, "final_findings": [], "verdict": _rule_verdict([])}
 
 
 
 
 
 
 
 
240
 
241
  # -- Phase 1: Heuristic dedup --------------------------------------------
242
  deduped = _deduplicate(raw_findings)
 
270
  result = None
271
 
272
  if result is not None:
273
+ final_findings = calibrate_findings(result.findings, state)
274
+ verdict = _rule_verdict(final_findings)
275
  logger.info(
276
  "LLM aggregator: %d deduped → %d final, recommendation=%s",
277
  len(deduped), len(final_findings),
278
  verdict.recommendation,
279
  )
280
+ return {"review_coverage": coverage, "final_findings": final_findings, "verdict": verdict}
281
 
282
  # Rule-based path (default) — zero LLM overhead
283
  logger.info("Using rule-based aggregation (fast path)")
 
285
  verdict = _rule_verdict(deduped)
286
 
287
  return {
288
+ "review_coverage": coverage,
289
  "final_findings": final_findings, # plain list, overwrites
290
  "verdict": verdict, # set-once, no reducer needed
291
  }
nodes/correctness_reviewer.py CHANGED
@@ -7,6 +7,7 @@ import re
7
  from pathlib import Path
8
 
9
  from llm_factory import create_llm
 
10
  from nodes.review_runtime import changed_context, invoke_review, stage_result
11
  from pydantic import BaseModel, Field
12
 
@@ -166,6 +167,7 @@ def correctness_reviewer_node(state: OpenCodeReviewState) -> dict:
166
  result.findings.extend(static_findings)
167
 
168
  # --- Log and return findings ---------------------------------------------
 
169
  if result and result.findings:
170
  logger.info(
171
  "Correctness review found %d issue(s)",
 
7
  from pathlib import Path
8
 
9
  from llm_factory import create_llm
10
+ from nodes.finding_quality import calibrate_findings
11
  from nodes.review_runtime import changed_context, invoke_review, stage_result
12
  from pydantic import BaseModel, Field
13
 
 
167
  result.findings.extend(static_findings)
168
 
169
  # --- Log and return findings ---------------------------------------------
170
+ result.findings = calibrate_findings(result.findings, state)
171
  if result and result.findings:
172
  logger.info(
173
  "Correctness review found %d issue(s)",
nodes/executor.py CHANGED
@@ -160,7 +160,8 @@ def _finding_body(finding: Finding) -> str:
160
  return (
161
  f"{emoji} **{finding.severity.value.upper()}** — "
162
  f"*{finding.category}* \n"
163
- f"**Confidence:** {finding.confidence:.0%} \n\n"
 
164
  f"{finding.comment}{fix}"
165
  )
166
 
@@ -184,7 +185,7 @@ def _verdict_body(verdict_dict: dict) -> str:
184
  return (
185
  f"## OpenCodeReview \u2014 {emoji} "
186
  f"{verdict_dict['recommendation'].upper()}\n\n"
187
- f"**Score:** {score}/10 \n"
188
  f"**Summary:** {summary}\n"
189
  )
190
 
@@ -215,6 +216,8 @@ def executor_node(state: OpenCodeReviewState) -> dict:
215
  logger.info("Not approved \u2014 skipping executor")
216
  return {"posting_result": {"status": "skipped", "reason": "not_approved"}}
217
 
 
 
218
  _POST_ERRORS.clear()
219
 
220
  parts = state.repo.split("/")
@@ -235,7 +238,7 @@ def executor_node(state: OpenCodeReviewState) -> dict:
235
  )
236
  if state.verdict:
237
  logger.info("[WOULD POST] Verdict: %s", state.verdict.summary)
238
- for f in state.final_findings:
239
  logger.info(
240
  "[WOULD POST] %s:%d\u2013%d %s \u2014 %s",
241
  f.file_path, f.line_start, f.line_end,
@@ -256,7 +259,7 @@ def executor_node(state: OpenCodeReviewState) -> dict:
256
  inline_failed = 0
257
  fallback_ok = 0
258
 
259
- for f in state.final_findings:
260
  body = _finding_body(f)
261
 
262
  if commit_id:
@@ -293,7 +296,7 @@ def executor_node(state: OpenCodeReviewState) -> dict:
293
  verdict_body = _verdict_body(state.verdict.model_dump())
294
  verdict_posted = _post_issue_comment(owner, repo_name, pr_number, verdict_body)
295
 
296
- total = len(state.final_findings)
297
  logger.info(
298
  "Executor: %d/%d inline, %d/%d fallback, verdict %s \u2014 "
299
  "%s/%s#%d",
@@ -317,8 +320,11 @@ def executor_node(state: OpenCodeReviewState) -> dict:
317
  status = "partially_posted"
318
  else:
319
  status = "post_failed"
 
 
320
  return {"posting_result": {
321
  "status": status,
 
322
  "total_findings": total,
323
  "inline_posted": inline_ok,
324
  "fallback_posted": fallback_ok,
 
160
  return (
161
  f"{emoji} **{finding.severity.value.upper()}** — "
162
  f"*{finding.category}* \n"
163
+ f"**Model confidence (uncalibrated):** {finding.confidence:.0%} \n"
164
+ f"**Evidence:** {finding.evidence_status} — source location checked; behavior not independently reproduced. \n\n"
165
  f"{finding.comment}{fix}"
166
  )
167
 
 
185
  return (
186
  f"## OpenCodeReview \u2014 {emoji} "
187
  f"{verdict_dict['recommendation'].upper()}\n\n"
188
+ f"**Risk estimate:** {score}/10 (not answer correctness) \n"
189
  f"**Summary:** {summary}\n"
190
  )
191
 
 
216
  logger.info("Not approved \u2014 skipping executor")
217
  return {"posting_result": {"status": "skipped", "reason": "not_approved"}}
218
 
219
+ postable_findings = [finding for finding in state.final_findings if finding.evidence_status == "source_grounded"]
220
+ withheld = len(state.final_findings) - len(postable_findings)
221
  _POST_ERRORS.clear()
222
 
223
  parts = state.repo.split("/")
 
238
  )
239
  if state.verdict:
240
  logger.info("[WOULD POST] Verdict: %s", state.verdict.summary)
241
+ for f in postable_findings:
242
  logger.info(
243
  "[WOULD POST] %s:%d\u2013%d %s \u2014 %s",
244
  f.file_path, f.line_start, f.line_end,
 
259
  inline_failed = 0
260
  fallback_ok = 0
261
 
262
+ for f in postable_findings:
263
  body = _finding_body(f)
264
 
265
  if commit_id:
 
296
  verdict_body = _verdict_body(state.verdict.model_dump())
297
  verdict_posted = _post_issue_comment(owner, repo_name, pr_number, verdict_body)
298
 
299
+ total = len(postable_findings)
300
  logger.info(
301
  "Executor: %d/%d inline, %d/%d fallback, verdict %s \u2014 "
302
  "%s/%s#%d",
 
320
  status = "partially_posted"
321
  else:
322
  status = "post_failed"
323
+ if withheld and status == "posted":
324
+ status = "partially_posted"
325
  return {"posting_result": {
326
  "status": status,
327
+ "withheld_unverified": withheld,
328
  "total_findings": total,
329
  "inline_posted": inline_ok,
330
  "fallback_posted": fallback_ok,
nodes/finding_quality.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Deterministic source checks and conservative severity calibration.
2
+
3
+ Source grounding validates a location in the changed code; it is deliberately
4
+ not presented as execution, compilation, or semantic verification.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import re
9
+
10
+ from state import Finding, OpenCodeReviewState, Severity
11
+
12
+
13
+ def patch_lines(patch: str) -> tuple[dict[int, str], set[int]]:
14
+ source: dict[int, str] = {}
15
+ added: set[int] = set()
16
+ line = None
17
+ for raw in patch.splitlines():
18
+ if raw.startswith('@@'):
19
+ match = re.search(r'\+(\d+)(?:,\d+)?', raw)
20
+ line = int(match.group(1)) if match else None
21
+ elif line is not None and raw.startswith(('+', ' ')):
22
+ source[line] = raw[1:]
23
+ if raw.startswith('+'):
24
+ added.add(line)
25
+ line += 1
26
+ return source, added
27
+
28
+
29
+ def calibrate_findings(findings: list[Finding], state: OpenCodeReviewState) -> list[Finding]:
30
+ files = {item.path: item for item in state.changed_files}
31
+ results = []
32
+ for original in findings:
33
+ finding = original.model_copy(deep=True)
34
+ notes = []
35
+ category = finding.category.lower()
36
+ if category in {'test_coverage', 'test coverage', 'testing', 'tests'} or finding.kind == 'test_suggestion':
37
+ finding.kind = 'test_suggestion'
38
+ finding.severity = Severity.LOW if finding.severity != Severity.INFO else Severity.INFO
39
+ notes.append('Test suggestion, not an established runtime defect; excluded from the risk score. Test availability outside the supplied context is unknown.')
40
+ else:
41
+ finding.kind = 'security_concern' if category == 'security' else 'bug'
42
+
43
+ file = files.get(finding.file_path)
44
+ finding.evidence_excerpt = '' # Never trust an unverified model-supplied quote.
45
+ finding.evidence_status = 'outside_diff'
46
+ if file and finding.line_start > 0 and finding.line_end >= finding.line_start:
47
+ source, added = patch_lines(file.diff_hunk)
48
+ content_lines = file.content.splitlines()
49
+ start, end = finding.line_start, finding.line_end
50
+ location_exists = end <= len(content_lines) if content_lines else all(i in source for i in range(start, end + 1))
51
+ overlaps_change = any(start <= number <= end for number in added)
52
+ if location_exists and overlaps_change:
53
+ finding.evidence_status = 'source_grounded'
54
+ excerpt = []
55
+ for number in range(start, min(end + 1, start + 12)):
56
+ text = content_lines[number - 1] if content_lines else source[number]
57
+ excerpt.append(f'{number}: {text}')
58
+ finding.evidence_excerpt = '\n'.join(excerpt)[:1800]
59
+ notes.append('Location matches changed source. The claimed behavior has not been reproduced or independently verified.')
60
+ else:
61
+ notes.append('Location could not be matched to added/modified lines in the supplied diff; excluded from the risk score.')
62
+ else:
63
+ notes.append('File or line range is outside the supplied changed code; excluded from the risk score.')
64
+
65
+ # Source text alone cannot prove compiler outcomes. In particular,
66
+ # response.json() is commonly any, so useState([]) is not itself proof
67
+ # of the reported TypeScript assignment error.
68
+ if finding.kind != 'test_suggestion' and re.search(
69
+ r'compil(?:ation|e|ing)|type[- ]?check|type[- ]?error|will not build|cannot build|never\[\]',
70
+ finding.comment, re.IGNORECASE,
71
+ ):
72
+ finding.evidence_status = 'needs_verification'
73
+ notes.append('Compiler/type-system claim requires a reproducible compiler diagnostic; none was run by this review. Excluded from the risk score.')
74
+ finding.calibration_note = ' '.join(notes)
75
+ results.append(finding)
76
+ return results
77
+
78
+
79
+ def review_coverage(state: OpenCodeReviewState) -> dict:
80
+ """Report actual input bounds without claiming all source was inspected."""
81
+ limits = {'correctness': (9000, 600, 2000), 'security': (None, 4000, 6000), 'test_coverage': (None, 4000, 6000)}
82
+ reviewers = []
83
+ for stage in state.review_stages:
84
+ reviewer = stage.get('reviewer', '')
85
+ diff_limit, file_limit, context_limit = limits.get(reviewer, (None, None, None))
86
+ limitations = ['Source checks validate location only; code and tests were not executed.']
87
+ if diff_limit and len(state.diff or '') > diff_limit:
88
+ limitations.append('Diff truncated in this reviewer prompt.')
89
+ if file_limit and any(len(file.content) > file_limit for file in state.changed_files):
90
+ limitations.append('Changed-file context has a per-file character limit.')
91
+ if state.review_mode == 'fast':
92
+ limitations.append('Fast mode supplies windows around changed lines rather than complete files.')
93
+ if sum(len(chunk.content) for chunk in state.context_chunks) > (context_limit or 0):
94
+ limitations.append('Retrieved context truncated to the reviewer context limit.')
95
+ reviewers.append({**stage, 'diff_chars_included': min(len(state.diff or ''), diff_limit) if diff_limit else len(state.diff or ''),
96
+ 'file_context_limit_chars': file_limit, 'context_limit_chars': context_limit, 'limitations': limitations})
97
+ return {'mode': state.review_mode, 'incremental': bool(state.incremental_base_sha),
98
+ 'files_changed': len(state.changed_files), 'files_available': sum(bool(file.content) for file in state.changed_files),
99
+ 'changed_file_paths': [file.path for file in state.changed_files], 'diff_chars': len(state.diff or ''),
100
+ 'reviewers': reviewers, 'limitations': ['Review quality is not proven by the risk score. Missing repository context can hide issues.']}
nodes/human_approval.py CHANGED
@@ -66,6 +66,10 @@ def human_approval_node(state: OpenCodeReviewState) -> dict:
66
  "comment": f.comment,
67
  "confidence": f.confidence,
68
  "suggested_fix": f.suggested_fix,
 
 
 
 
69
  }
70
  for f in findings
71
  ],
 
66
  "comment": f.comment,
67
  "confidence": f.confidence,
68
  "suggested_fix": f.suggested_fix,
69
+ "kind": f.kind,
70
+ "evidence_status": f.evidence_status,
71
+ "evidence_excerpt": f.evidence_excerpt,
72
+ "calibration_note": f.calibration_note,
73
  }
74
  for f in findings
75
  ],
nodes/security_reviewer.py CHANGED
@@ -6,6 +6,7 @@ import os
6
  from pathlib import Path
7
 
8
  from llm_factory import create_llm
 
9
  from nodes.review_runtime import changed_context, invoke_review, stage_result
10
  from pydantic import BaseModel, Field
11
 
@@ -124,6 +125,7 @@ def security_reviewer_node(state: OpenCodeReviewState) -> dict:
124
  logger.warning("Security review LLM call failed: %s", exc)
125
  return {"review_stages": [stage_result("security", started, error=exc, llm=locals().get("llm"))]}
126
 
 
127
  if result.findings:
128
  logger.info("Security review found %d issue(s)", len(result.findings))
129
  for f in result.findings:
 
6
  from pathlib import Path
7
 
8
  from llm_factory import create_llm
9
+ from nodes.finding_quality import calibrate_findings
10
  from nodes.review_runtime import changed_context, invoke_review, stage_result
11
  from pydantic import BaseModel, Field
12
 
 
125
  logger.warning("Security review LLM call failed: %s", exc)
126
  return {"review_stages": [stage_result("security", started, error=exc, llm=locals().get("llm"))]}
127
 
128
+ result.findings = calibrate_findings(result.findings, state)
129
  if result.findings:
130
  logger.info("Security review found %d issue(s)", len(result.findings))
131
  for f in result.findings:
nodes/test_coverage_reviewer.py CHANGED
@@ -6,6 +6,7 @@ import os
6
  from pathlib import Path
7
 
8
  from llm_factory import create_llm
 
9
  from nodes.review_runtime import changed_context, invoke_review, stage_result
10
  from pydantic import BaseModel, Field
11
 
@@ -131,6 +132,7 @@ def test_coverage_reviewer_node(state: OpenCodeReviewState) -> dict:
131
  logger.warning("Test-coverage review LLM call failed: %s", exc)
132
  return {"review_stages": [stage_result("test_coverage", started, error=exc, llm=locals().get("llm"))]}
133
 
 
134
  if result.findings:
135
  logger.info("Test-coverage review found %d issue(s)", len(result.findings))
136
  for f in result.findings:
 
6
  from pathlib import Path
7
 
8
  from llm_factory import create_llm
9
+ from nodes.finding_quality import calibrate_findings
10
  from nodes.review_runtime import changed_context, invoke_review, stage_result
11
  from pydantic import BaseModel, Field
12
 
 
132
  logger.warning("Test-coverage review LLM call failed: %s", exc)
133
  return {"review_stages": [stage_result("test_coverage", started, error=exc, llm=locals().get("llm"))]}
134
 
135
+ result.findings = calibrate_findings(result.findings, state)
136
  if result.findings:
137
  logger.info("Test-coverage review found %d issue(s)", len(result.findings))
138
  for f in result.findings:
observability.py CHANGED
@@ -295,15 +295,14 @@ def estimate_model_cost(
295
  model: str,
296
  input_tokens: int,
297
  output_tokens: int,
298
- ) -> float:
299
  """Estimate the USD cost of an LLM call by looking up ``MODEL_PRICING``.
300
 
301
  Parameters
302
  ----------
303
  model : str
304
- Model name (e.g. ``"llama-3.3-70b-versatile"`` or
305
- ``"gemini-3.1-flash-lite"``). Unknown models fall back to the
306
- pessimistic ``__default__`` rate.
307
  input_tokens : int
308
  Number of tokens in the prompt (system + user messages).
309
  output_tokens : int
@@ -312,9 +311,13 @@ def estimate_model_cost(
312
  Returns
313
  -------
314
  float
315
- Estimated cost in USD.
316
  """
317
- pricing = MODEL_PRICING.get(model, MODEL_PRICING["__default__"])
 
 
 
 
318
  input_cost = (input_tokens / 1_000_000) * pricing["input"]
319
  output_cost = (output_tokens / 1_000_000) * pricing["output"]
320
  return round(input_cost + output_cost, 6)
@@ -324,7 +327,7 @@ def estimate_groq_cost(
324
  model: str,
325
  input_tokens: int,
326
  output_tokens: int,
327
- ) -> float:
328
  """Estimate the USD cost of a Groq LLM call (backward-compatible).
329
 
330
  Thin wrapper around :func:`estimate_model_cost`. Kept so existing
@@ -474,7 +477,7 @@ class TokenCostCallback:
474
 
475
  @property
476
  def total_cost(self) -> float:
477
- return sum(u.get("cost", 0.0) for u in self.usage)
478
 
479
  @property
480
  def total_ttft(self) -> float:
@@ -546,12 +549,18 @@ class TokenCostCallback:
546
  output_tokens = token_usage.get("completion_tokens", 0) or 0
547
 
548
  if input_tokens > 0 or output_tokens > 0:
549
- cost = estimate_groq_cost(model, input_tokens, output_tokens)
 
 
 
 
 
550
  entry: dict[str, Any] = {
551
  "model": model,
552
  "input_tokens": input_tokens,
553
  "output_tokens": output_tokens,
554
  "cost": cost,
 
555
  }
556
  if ttft is not None:
557
  entry["ttft_seconds"] = ttft
@@ -567,22 +576,27 @@ class TokenCostCallback:
567
  if run_id:
568
  self._start_times.pop(str(run_id), None)
569
 
570
- def summary(self) -> str:
571
- """Return a human-readable cost & TTFT summary."""
572
- calls = len(self.usage)
573
- if calls == 0:
574
- return "Cost: N/A (no LLM calls captured)"
575
-
576
- parts = [
577
- f"Cost: {format_cost(self.total_cost)}",
578
- f"{calls} LLM call(s)",
579
- f"{self.total_input_tokens:,} in / {self.total_output_tokens:,} out tokens",
580
- ]
581
 
 
 
 
 
 
 
 
 
 
 
582
  avg = self.avg_ttft
583
  if avg is not None:
584
- parts.append(f"TTFT: {self.total_ttft:.1f}s total / {avg:.2f}s avg")
585
-
586
  return " · ".join(parts)
587
 
588
  def reset(self) -> None:
@@ -620,11 +634,10 @@ def _resolve_langfuse_trace_id(handler: Any) -> Optional[str]:
620
  pass
621
 
622
  try:
623
- from langfuse import Langfuse
624
-
625
- tid = Langfuse().get_current_trace_id()
626
- if tid:
627
- return tid
628
  except Exception:
629
  pass
630
 
@@ -688,6 +701,9 @@ def log_langfuse_score(
688
  return
689
 
690
  resolved_trace_id = trace_id or _resolve_langfuse_trace_id(handler)
 
 
 
691
 
692
  # Visibility log: lets you confirm the score will land on the right
693
  # trace (or spot a None that would create an orphaned score).
 
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
 
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)
 
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
 
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:
 
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
 
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:
 
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
 
 
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).
prompts/correctness_v1.txt CHANGED
@@ -37,3 +37,10 @@ For each issue return a `Finding` with:
37
  - `suggested_fix`: a concrete code snippet of how to fix it, if applicable.
38
 
39
  If you find NO correctness issues, return an empty findings list.
 
 
 
 
 
 
 
 
37
  - `suggested_fix`: a concrete code snippet of how to fix it, if applicable.
38
 
39
  If you find NO correctness issues, return an empty findings list.
40
+
41
+ Evidence and uncertainty rules:
42
+ - Cite exact changed file/line locations and include a short evidence_excerpt from supplied code.
43
+ - Do not invent absent repository context or claim tests/compiler execution. Model confidence is not measured correctness.
44
+ - Distinguish observed code patterns from demonstrated runtime defects. Explain the concrete trigger and impact; omit claims that depend on unknown assumptions.
45
+ - A TypeScript useState([]) declaration alone does not prove a build failure: response.json() commonly returns any. Without actual compiler diagnostics, phrase compiler concerns as requiring verification.
46
+ - Do not claim missing tests repository-wide from a partial diff; say the supplied context does not demonstrate coverage.
prompts/security_v1.txt CHANGED
@@ -32,3 +32,10 @@ For each issue return a `Finding` with:
32
  - `suggested_fix`: concrete code snippet if applicable.
33
 
34
  Return an empty findings list if no security issues are found.
 
 
 
 
 
 
 
 
32
  - `suggested_fix`: concrete code snippet if applicable.
33
 
34
  Return an empty findings list if no security issues are found.
35
+
36
+ Evidence and uncertainty rules:
37
+ - Cite exact changed file/line locations and include a short evidence_excerpt from supplied code.
38
+ - Do not invent absent repository context or claim tests/compiler execution. Model confidence is not measured correctness.
39
+ - Distinguish observed code patterns from demonstrated runtime defects. Explain the concrete trigger and impact; omit claims that depend on unknown assumptions.
40
+ - A TypeScript useState([]) declaration alone does not prove a build failure: response.json() commonly returns any. Without actual compiler diagnostics, phrase compiler concerns as requiring verification.
41
+ - Do not claim missing tests repository-wide from a partial diff; say the supplied context does not demonstrate coverage.
prompts/test_coverage_v1.txt CHANGED
@@ -21,8 +21,7 @@ Look for:
21
  For each gap return a `Finding` with:
22
  - `file_path`: the source file with the gap (not the test file).
23
  - `line_start` / `line_end`: best guess of the affected lines.
24
- - `severity`: `high` (entirely new untested logic), `medium` (modified path
25
- untested), `low` (edge case not covered), `info` (suggestion).
26
  - `category`: always `"test_coverage"`.
27
  - `comment`: explain what changed and why it needs a test.
28
  - `confidence`: 0.0–1.0.
@@ -36,3 +35,11 @@ For each gap return a `Finding` with:
36
  - Correctness of the logic itself (handled by correctness reviewer).
37
 
38
  Return an empty findings list if every changed path has adequate test coverage.
 
 
 
 
 
 
 
 
 
21
  For each gap return a `Finding` with:
22
  - `file_path`: the source file with the gap (not the test file).
23
  - `line_start` / `line_end`: best guess of the affected lines.
24
+ - `severity`: `low` or `info`. Missing tests are suggestions, not demonstrated production bugs.
 
25
  - `category`: always `"test_coverage"`.
26
  - `comment`: explain what changed and why it needs a test.
27
  - `confidence`: 0.0–1.0.
 
35
  - Correctness of the logic itself (handled by correctness reviewer).
36
 
37
  Return an empty findings list if every changed path has adequate test coverage.
38
+
39
+ Evidence and uncertainty rules:
40
+ - Cite exact changed file/line locations and include a short evidence_excerpt from supplied code.
41
+ - Do not invent absent repository context or claim tests/compiler execution. Model confidence is not measured correctness.
42
+ - Distinguish observed code patterns from demonstrated runtime defects. Explain the concrete trigger and impact; omit claims that depend on unknown assumptions.
43
+ - A TypeScript useState([]) declaration alone does not prove a build failure: response.json() commonly returns any. Without actual compiler diagnostics, phrase compiler concerns as requiring verification.
44
+ - Do not claim missing tests repository-wide from a partial diff; say the supplied context does not demonstrate coverage.
45
+ - Set kind to "test_suggestion". Group related coverage gaps into concise test scenarios instead of emitting one high-severity finding per component.
state.py CHANGED
@@ -2,7 +2,7 @@ from __future__ import annotations
2
 
3
  import enum
4
  from operator import add
5
- from typing import Annotated, Optional
6
 
7
  from pydantic import BaseModel, Field
8
 
@@ -44,6 +44,10 @@ class Finding(BaseModel):
44
  comment: str # Human-readable explanation
45
  confidence: float = Field(default=0.5, ge=0.0, le=1.0)
46
  suggested_fix: Optional[str] = None
 
 
 
 
47
 
48
 
49
  class Verdict(BaseModel):
@@ -54,6 +58,8 @@ class Verdict(BaseModel):
54
  critical_count: int = 0
55
  high_count: int = 0
56
  recommendation: str # "approve" | "request_changes" | "block"
 
 
57
 
58
 
59
  # ─── Graph State ─────────────────────────────────────────────────────────────
@@ -83,6 +89,7 @@ class OpenCodeReviewState(BaseModel):
83
  findings: Annotated[list[Finding], add] = Field(default_factory=list)
84
 
85
  review_stages: Annotated[list[dict], add] = Field(default_factory=list)
 
86
 
87
  # Aggregated (deduped, noise-filtered) findings: set-once by aggregator
88
  final_findings: list[Finding] = Field(default_factory=list)
 
2
 
3
  import enum
4
  from operator import add
5
+ from typing import Annotated, Literal, Optional
6
 
7
  from pydantic import BaseModel, Field
8
 
 
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):
 
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 ─────────────────────────────────────────────────────────────
 
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)
tests/test_evaluation_quality.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import time
3
+ from types import SimpleNamespace
4
+
5
+ import pytest
6
+
7
+ from eval_data import ragas_eval
8
+ from observability import TokenCostCallback, estimate_model_cost
9
+ from eval_data.offline_regression import evaluate
10
+
11
+
12
+ def prepare(monkeypatch):
13
+ monkeypatch.setattr(ragas_eval, "_check_ragas", lambda: True)
14
+ monkeypatch.setattr(ragas_eval, "_get_evaluator_llm", lambda endpoint: object())
15
+ monkeypatch.setitem(sys.modules, "ragas.dataset_schema", SimpleNamespace(SingleTurnSample=lambda **kwargs: kwargs))
16
+
17
+
18
+ def test_metrics_keep_success_when_other_metric_times_out(monkeypatch):
19
+ prepare(monkeypatch)
20
+ def score(name, *args):
21
+ if name == "faithfulness":
22
+ time.sleep(.2)
23
+ return .75
24
+ monkeypatch.setattr(ragas_eval, "_score_one_metric", score)
25
+ report = ragas_eval.compute_ragas_report("query", ["context"], answer="answer", metric_timeout=.03)
26
+ assert report["scores"] == {"context_precision": .75}
27
+ assert report["metrics"]["faithfulness"]["status"] == "timed_out"
28
+ assert report["metrics"]["answer_relevancy"]["status"] == "skipped"
29
+
30
+
31
+ def test_failed_judges_never_generate_fake_fallback_scores(monkeypatch):
32
+ prepare(monkeypatch)
33
+ def fail(*args):
34
+ raise RuntimeError("provider unavailable")
35
+ monkeypatch.setattr(ragas_eval, "_score_one_metric", fail)
36
+ report = ragas_eval.compute_ragas_report("same text", ["same text"], answer="same text")
37
+ assert report["scores"] == {}
38
+ assert report["metrics"]["context_precision"]["value"] is None
39
+
40
+
41
+ def test_no_context_is_not_a_zero_quality_measurement():
42
+ report = ragas_eval.compute_ragas_report("query", [], answer="answer")
43
+ assert report["scores"] == {}
44
+ assert all(metric["status"] == "skipped" for metric in report["metrics"].values())
45
+
46
+
47
+ def test_cost_free_estimate_is_distinct_from_provider_report():
48
+ callback = TokenCostCallback()
49
+ callback.on_llm_end(SimpleNamespace(llm_output={"model_name": "minimax/test:free", "token_usage": {"prompt_tokens": 1000, "completion_tokens": 2000}}))
50
+ assert callback.details()["amount"] == 0
51
+ assert callback.details()["source"] == "free_model_estimate"
52
+ assert "not billing" in callback.summary()
53
+ callback.reset()
54
+ callback.on_llm_end(SimpleNamespace(llm_output={"model_name": "unknown", "token_usage": {"prompt_tokens": 10, "completion_tokens": 20, "cost": .123}}))
55
+ assert callback.details()["source"] == "provider_reported"
56
+ assert callback.details()["amount"] == .123
57
+
58
+
59
+ def test_unknown_model_cost_stays_unknown():
60
+ assert estimate_model_cost("unknown", 10000, 10000) is None
61
+ callback = TokenCostCallback()
62
+ callback.on_llm_end(SimpleNamespace(llm_output={"model_name": "unknown", "token_usage": {"prompt_tokens": 10, "completion_tokens": 20}}))
63
+ assert callback.details()["amount"] is None
64
+ assert "unknown" in callback.summary().lower()
65
+
66
+
67
+ def test_offline_matching_counts_duplicate_only_once():
68
+ finding = {"file_path": "auth.ts", "line_start": 10, "category": "security", "comment": "Concurrent race allows reuse"}
69
+ fixtures = [{"label_scope": "exhaustive", "repo": "test/repo", "pr_number": 1, "findings": [{**finding, "concept_terms": ["race", "reuse"]}]}]
70
+ report = evaluate([{"repo": "test/repo", "pr_number": 1, "findings": [finding, finding]}], fixtures)
71
+ assert report["totals"]["matched"] == 1
72
+ assert report["totals"]["duplicate_predictions"] == 1
73
+ assert report["precision"] == .5
74
+ assert report["recall"] == 1
tests/test_finding_quality.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from unittest.mock import Mock
2
+
3
+ from nodes.aggregator import aggregator_node, _deduplicate
4
+ from nodes.finding_quality import calibrate_findings, review_coverage
5
+ from nodes.executor import executor_node, _finding_body
6
+ from state import ChangedFile, Finding, OpenCodeReviewState, Severity, Verdict
7
+
8
+
9
+ def state_for(*findings):
10
+ return OpenCodeReviewState(repo='owner/repo', pr_number=1, diff='diff', changed_files=[ChangedFile(
11
+ path='auth.ts', status='modified', content='const codes = read();\nconsume(codes);\nreturn true;',
12
+ diff_hunk='@@ -1,2 +1,3 @@\n const codes = read();\n+consume(codes);\n return true;')], findings=list(findings))
13
+
14
+
15
+ def finding(**changes):
16
+ return Finding(file_path='auth.ts', line_start=2, line_end=2, severity=Severity.HIGH,
17
+ category='correctness', comment='Concurrent calls consume the same code.', confidence=.98, **changes)
18
+
19
+
20
+ def test_test_suggestions_cannot_drive_risk_score_to_zero():
21
+ raw = finding()
22
+ raw.category = 'test_coverage'
23
+ raw.comment = 'The supplied test context does not exercise this branch.'
24
+ result = aggregator_node(state_for(raw))
25
+ calibrated = result['final_findings'][0]
26
+ assert calibrated.kind == 'test_suggestion'
27
+ assert calibrated.severity == Severity.LOW
28
+ assert result['verdict'].overall_score == 10
29
+ assert result['verdict'].high_count == 0
30
+ assert result['verdict'].score_breakdown['test_suggestions_excluded'] == 1
31
+ assert result['verdict'].recommendation == 'comment'
32
+
33
+
34
+ def test_evidence_is_taken_from_actual_source_not_model_quote():
35
+ raw = finding(evidence_excerpt='invented code')
36
+ calibrated = calibrate_findings([raw], state_for(raw))[0]
37
+ assert calibrated.evidence_status == 'source_grounded'
38
+ assert calibrated.evidence_excerpt == '2: consume(codes);'
39
+ assert 'not been reproduced' in calibrated.calibration_note
40
+ assert raw.evidence_excerpt == 'invented code'
41
+
42
+
43
+ def test_wrong_file_and_unchanged_line_are_not_scored():
44
+ bad_file = finding()
45
+ bad_file.file_path = 'not-in-pr.ts'
46
+ unchanged = finding()
47
+ unchanged.line_start = unchanged.line_end = 1
48
+ result = aggregator_node(state_for(bad_file, unchanged))
49
+ assert result['verdict'].overall_score == 10
50
+ assert all(f.evidence_status == 'outside_diff' for f in result['final_findings'])
51
+ assert result['verdict'].score_breakdown['unverified_claims_excluded'] == 2
52
+
53
+
54
+ def test_compile_claim_needs_diagnostic_not_pattern_guess():
55
+ raw = finding()
56
+ raw.comment = 'useState([]) infers never[] so setCodes(body.codes) causes a compilation failure.'
57
+ result = aggregator_node(state_for(raw))
58
+ assert result['final_findings'][0].evidence_status == 'needs_verification'
59
+ assert result['verdict'].overall_score == 10
60
+ assert result['verdict'].score_breakdown['unverified_claims_excluded'] == 1
61
+
62
+
63
+ def test_distinct_bug_and_test_suggestion_on_same_line_are_not_merged():
64
+ bug = finding()
65
+ test = finding()
66
+ test.kind = 'test_suggestion'
67
+ test.category = 'test_coverage'
68
+ assert len(_deduplicate([bug, test])) == 2
69
+
70
+
71
+ def test_review_coverage_discloses_prompt_bounds_and_no_execution():
72
+ state = state_for()
73
+ state.diff = 'x' * 10000
74
+ state.review_mode = 'fast'
75
+ state.review_stages = [{'reviewer': 'correctness', 'status': 'completed'}]
76
+ result = review_coverage(state)
77
+ stage = result['reviewers'][0]
78
+ assert stage['diff_chars_included'] == 9000
79
+ assert any('truncated' in note for note in stage['limitations'])
80
+ assert any('not executed' in note for note in stage['limitations'])
81
+ assert result['changed_file_paths'] == ['auth.ts']
82
+
83
+
84
+ def test_executor_withholds_unverified_comments(monkeypatch):
85
+ raw = finding()
86
+ state = state_for(raw)
87
+ state.final_findings = [raw]
88
+ state.human_approved = True
89
+ state.verdict = Verdict(summary='Unverified concern', approved=True, overall_score=10, recommendation='comment')
90
+ monkeypatch.setenv('GITHUB_TOKEN', 'fake')
91
+ monkeypatch.setattr('nodes.executor._fetch_pr_head_sha', Mock(return_value='sha'))
92
+ inline = Mock()
93
+ issue = Mock(return_value=True)
94
+ monkeypatch.setattr('nodes.executor._post_review_comment', inline)
95
+ monkeypatch.setattr('nodes.executor._post_issue_comment', issue)
96
+ receipt = executor_node(state)['posting_result']
97
+ assert receipt['withheld_unverified'] == 1
98
+ assert receipt['status'] == 'partially_posted'
99
+ assert inline.call_count == 0
100
+ assert issue.call_count == 1 # risk summary only
101
+
102
+
103
+ def test_posted_finding_does_not_claim_semantic_verification():
104
+ raw = finding(evidence_status='source_grounded')
105
+ body = _finding_body(raw)
106
+ assert 'behavior not independently reproduced' in body
107
+ assert 'uncalibrated' in body
tests/test_job_speed.py CHANGED
@@ -25,14 +25,34 @@ def test_incomplete_review_never_starts_ragas():
25
  assert ns['_ragas_inputs_from_state'](state, 'custom') is None
26
 
27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  def scheduler():
29
  tree = ast.parse(Path('api.py').read_text(encoding='utf-8'))
30
- names = {'create_review', 'cancel_review', '_public_job', 'get_review', 'decide_review'}
31
  nodes = [node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name in names]
32
  for node in nodes:
33
  node.decorator_list = []
34
  ns = dict(__file__=str(Path('api.py').resolve()), Path=Path, Any=Any, Request=object, ReviewRequest=object,
35
- Header=lambda *a, **k: None, DecisionRequest=object, HTTPException=HTTPException, hashlib=hashlib, json=json,
36
  threading=threading, time=time, uuid=uuid, datetime=datetime, timezone=timezone,
37
  os=SimpleNamespace(getenv=lambda *a: ''), requests=SimpleNamespace(get=Mock()),
38
  _jobs={}, _lock=threading.Lock(), _save_job=Mock(), _executor=SimpleNamespace(submit=Mock()),
 
25
  assert ns['_ragas_inputs_from_state'](state, 'custom') is None
26
 
27
 
28
+ def test_feedback_is_persisted_for_existing_finding_only():
29
+ ns = scheduler()
30
+ ns['_jobs']['job'] = {'id': 'job', 'owner_id': '1', 'status': 'awaiting_approval', 'findings': [{'comment': 'evidence'}]}
31
+ vote = SimpleNamespace(finding_index=0, label='incorrect')
32
+ assert ns['finding_feedback']('job', vote, SimpleNamespace(owner=1)) == {'feedback': {'0': 'incorrect'}}
33
+ ns['_save_job'].assert_called_once()
34
+ with pytest.raises(HTTPException) as absent:
35
+ ns['finding_feedback']('job', SimpleNamespace(finding_index=1, label='correct'), SimpleNamespace(owner=1))
36
+ assert absent.value.status_code == 422
37
+ with pytest.raises(HTTPException) as foreign:
38
+ ns['finding_feedback']('job', vote, SimpleNamespace(owner=2))
39
+ assert foreign.value.status_code == 404
40
+
41
+
42
+ def test_public_job_never_exposes_evaluator_endpoint_snapshot():
43
+ ns = scheduler()
44
+ job = {'id': 'job', 'status': 'incomplete', 'ragas_inputs': {'endpoint': {'api_key': 'private'}}, 'config': {}}
45
+ assert 'ragas_inputs' not in ns['_public_job'](job)
46
+
47
+
48
  def scheduler():
49
  tree = ast.parse(Path('api.py').read_text(encoding='utf-8'))
50
+ names = {'create_review', 'cancel_review', '_public_job', 'get_review', 'decide_review', 'finding_feedback'}
51
  nodes = [node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name in names]
52
  for node in nodes:
53
  node.decorator_list = []
54
  ns = dict(__file__=str(Path('api.py').resolve()), Path=Path, Any=Any, Request=object, ReviewRequest=object,
55
+ Header=lambda *a, **k: None, DecisionRequest=object, FindingFeedbackRequest=object, HTTPException=HTTPException, hashlib=hashlib, json=json,
56
  threading=threading, time=time, uuid=uuid, datetime=datetime, timezone=timezone,
57
  os=SimpleNamespace(getenv=lambda *a: ''), requests=SimpleNamespace(get=Mock()),
58
  _jobs={}, _lock=threading.Lock(), _save_job=Mock(), _executor=SimpleNamespace(submit=Mock()),
tests/test_ragas_api_report.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ast
2
+ import threading
3
+ import time
4
+ from pathlib import Path
5
+ from typing import Any
6
+ from unittest.mock import Mock
7
+
8
+
9
+ def test_metric_report_survives_top_level_completion():
10
+ job = {'id': 'job', 'ragas_task_id': 'task'}
11
+ metrics = {'faithfulness': {'status': 'completed', 'score': .8},
12
+ 'context_precision': {'status': 'failed', 'error': 'Timeout'}}
13
+ task = {'done': True, 'scores': {'faithfulness': .8}, 'metrics': metrics,
14
+ 'evaluation': {'engine': 'RAGAS'}}
15
+ tree = ast.parse(Path('api.py').read_text(encoding='utf-8'))
16
+ node = next(n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name == '_with_ragas')
17
+ ns = {'Any': Any, '_public_job': lambda item: dict(item), '_ragas_lock': threading.Lock(),
18
+ '_lock': threading.Lock(), '_ragas_tasks': {'task': task}, '_jobs': {'job': job}, '_save_job': Mock()}
19
+ exec(compile(ast.Module(body=[node], type_ignores=[]), 'api.py', 'exec'), ns)
20
+ result = ns['_with_ragas'](job)
21
+ assert result['ragas']['status'] == 'partial'
22
+ assert result['ragas']['metrics'] == metrics
23
+ assert job['ragas_metrics'] == metrics