Sdm0 commited on
Commit
d70e0e0
Β·
verified Β·
1 Parent(s): ce491e5

Sync from GitHub via hub-sync

Browse files
.env.example ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # =============================================================================
2
+ # OpenCodeReview β€” Environment Variables
3
+ # =============================================================================
4
+ #
5
+ # Copy this file to .env and fill in your values:
6
+ # cp .env.example .env
7
+ #
8
+ # Docker Compose automatically loads from .env. For direct CLI usage,
9
+ # export vars manually or use a tool like direnv / dotenv.
10
+ #
11
+ # Required vars are marked [REQUIRED]; all others are optional.
12
+ # =============================================================================
13
+
14
+
15
+ # ─── AI Provider ─────────────────────────────────────────────────────────────
16
+ # [REQUIRED] Groq API key for the AI reviewers (correctness, security,
17
+ # test-coverage, aggregator). Get one at https://console.groq.com
18
+ GROQ_API_KEY=gsk_your_key_here
19
+
20
+
21
+ # ─── GitHub API ──────────────────────────────────────────────────────────────
22
+ # [REQUIRED] GitHub personal access token with "repo" scope.
23
+ # Used for:
24
+ # - Fetching PR diffs and changed files
25
+ # - Posting review comments
26
+ # - Fetching evaluation data (eval_data/fetcher.py)
27
+ # - Building vector-store indexes from repo file trees
28
+ #
29
+ # Create one at: https://github.com/settings/tokens
30
+ GITHUB_TOKEN=ghp_your_token_here
31
+
32
+
33
+ # ─── GitHub OAuth (Device Flow) ──────────────────────────────────────────────
34
+ # [Optional] OAuth App client ID for interactive login via:
35
+ # opencodereview auth login
36
+ #
37
+ # Register a new OAuth App at https://github.com/settings/developers
38
+ # and enable Device Flow in the app settings.
39
+ # GITHUB_OAUTH_CLIENT_ID=Iv23li_your_client_id_here
40
+
41
+
42
+ # ─── Observability: LangSmith (Tracing) ──────────────────────────────────────
43
+ # [Optional] LangSmith enables full run tracing via LangChain/LangGraph.
44
+ # Get a key at: https://smith.langchain.com
45
+ # LANGCHAIN_API_KEY=lsv2_your_key_here
46
+ #
47
+ # [Optional] LangSmith project name (default: "opencodereview")
48
+ # LANGCHAIN_PROJECT=opencodereview
49
+
50
+
51
+ # ─── Observability: Langfuse (Tracing) ──────────────────────────────────────
52
+ # [Optional] Langfuse provides an alternative tracing backend.
53
+ # Both public and secret keys are required to enable it.
54
+ # Sign up at: https://cloud.langfuse.com
55
+ # LANGFUSE_PUBLIC_KEY=pk_your_public_key_here
56
+ # LANGFUSE_SECRET_KEY=sk_your_secret_key_here
57
+ #
58
+ # [Optional] Langfuse host URL (default: https://cloud.langfuse.com)
59
+ # For self-hosted: http://localhost:3000
60
+ # LANGFUSE_HOST=https://cloud.langfuse.com
61
+
62
+
63
+ # ─── Fallback AI Provider ────────────────────────────────────────────────────
64
+ # [Optional] Anthropic API key (used as fallback via config.py/Settings).
65
+ # OPENCODEREVIEW_ANTHROPIC_KEY=sk-ant_your_key_here
66
+
67
+
68
+ # ─── Alerting Webhooks ───────────────────────────────────────────────────────
69
+ # [Optional] Webhook URLs for the smoke-test alerting monitor
70
+ # (scripts/alert.py). Set at least one to receive notifications when the
71
+ # smoke-test score deviates significantly from baseline.
72
+ #
73
+ # Create a Discord webhook at: Server Settings β†’ Integrations β†’ Webhooks
74
+ # DISCORD_WEBHOOK=https://discord.com/api/webhooks/your_webhook_id
75
+ #
76
+ # Create a Slack webhook at: https://api.slack.com/messaging/webhooks
77
+ # SLACK_WEBHOOK=https://hooks.slack.com/services/your_webhook
78
+
79
+
80
+ # ─── Hugging Face Spaces (Deployment) ───────────────────────────────────────
81
+ # [Optional] Used by .github/workflows/deploy-hf.yml to sync to HF Spaces.
82
+ # Get a token at: https://huggingface.co/settings/tokens
83
+ # HF_TOKEN=hf_your_token_here
84
+
85
+
86
+ # ─── Server ──────────────────────────────────────────────────────────────────
87
+ # [Optional] Port for the Gradio web UI (default: 7860).
88
+ # HF Spaces sets this automatically.
89
+ # PORT=7860
app.py CHANGED
@@ -21,6 +21,20 @@ from langgraph.types import Command
21
 
22
  from graph import build_graph
23
  from main import _cleanup_db, SYNTHETIC_STATE
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  from state import Verdict
25
 
26
  import subprocess
@@ -53,16 +67,46 @@ RECOMMENDATION_ICONS = {
53
  # ─── Orchestration ───────────────────────────────────────────────────────────
54
 
55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
  def _build_and_stream(repo: str, pr_number: int) -> tuple:
57
  """Build the graph, stream up to the interrupt, and return state + config."""
58
  graph = build_graph(DB_PATH)
59
  thread_id = str(uuid.uuid4())
60
- config = {"configurable": {"thread_id": f"web-{thread_id}"}}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
62
- initial = {"repo": repo, "pr_number": pr_number}
63
- list(graph.stream(initial, config))
64
  state = graph.get_state(config)
65
- return state, config
66
 
67
 
68
  def _format_findings_table(findings: list) -> str:
@@ -185,9 +229,9 @@ def run_review(repo: str, pr_number: int, progress=gr.Progress()):
185
  progress(0.1, desc="Building graph…")
186
 
187
  try:
188
- state, config = _build_and_stream(repo.strip(), pr_number)
189
  except Exception as exc:
190
- logger.exception("Review failed")
191
  yield [None, None, None, None], f"❌ Review failed: {exc}"
192
  return
193
 
@@ -206,7 +250,12 @@ def run_review(repo: str, pr_number: int, progress=gr.Progress()):
206
  verdict_html = _format_verdict(verdict)
207
  findings_html = _format_findings_table(findings)
208
  count_html = _format_findings_count(findings)
209
- config_json = json.dumps(config)
 
 
 
 
 
210
 
211
  yield (
212
  [verdict_html, findings_html, count_html, config_json],
@@ -221,6 +270,12 @@ def resume_review(config_json: str, action: str, progress=gr.Progress()):
221
 
222
  config = json.loads(config_json)
223
  graph = build_graph(DB_PATH)
 
 
 
 
 
 
224
 
225
  progress(0.3, desc=f"Processing {action}…")
226
 
@@ -233,9 +288,11 @@ def resume_review(config_json: str, action: str, progress=gr.Progress()):
233
  if approved
234
  else "❌ Review **rejected**. No comments posted."
235
  )
 
 
236
  return msg
237
  except Exception as exc:
238
- logger.exception("Resume failed")
239
  return f"❌ Error: {exc}"
240
 
241
 
@@ -246,10 +303,26 @@ def run_smoke(progress=gr.Progress()):
246
  progress(0.1, desc="Building graph…")
247
  graph = build_graph(DB_PATH)
248
  thread_id = str(uuid.uuid4())
249
- config = {"configurable": {"thread_id": f"smoke-web-{thread_id}"}}
 
 
 
 
 
 
 
 
 
 
 
 
250
 
251
  progress(0.3, desc="Running on synthetic data…")
252
- list(graph.stream(SYNTHETIC_STATE, config))
 
 
 
 
253
  state = graph.get_state(config)
254
  tasks = state.tasks
255
 
@@ -263,8 +336,13 @@ def run_smoke(progress=gr.Progress()):
263
  progress(0.8, desc="Formatting…")
264
  verdict_html = _format_verdict(verdict)
265
  findings_html = _format_findings_table(findings)
 
 
 
 
 
266
 
267
- yield [verdict_html, findings_html, json.dumps(config), verdict_html, findings_html], None
268
 
269
 
270
 
@@ -393,6 +471,9 @@ JS_TOGGLE_THEME = """
393
  }
394
  """
395
 
 
 
 
396
  with gr.Blocks(css=CSS, title="OpenCodeReview", theme=gr.themes.Soft()) as demo:
397
  demo.load(js=JS_RESTORE_THEME)
398
 
@@ -604,17 +685,20 @@ with gr.Blocks(css=CSS, title="OpenCodeReview", theme=gr.themes.Soft()) as demo:
604
  )
605
 
606
  # ── Environment status footer ──────────────────────────────────────
607
- with gr.Accordion("πŸ”‘ Configured Keys", open=False):
 
 
608
  groq_ok = bool(os.environ.get("GROQ_API_KEY", "").strip())
609
  gh_ok = bool(os.environ.get("GITHUB_TOKEN", "").strip())
610
- groq_status = "βœ… Set" if groq_ok else "❌ Not set β€” reviewers will be skipped"
611
- gh_status = "βœ… Set" if gh_ok else "❌ Not set β€” cannot fetch real PRs"
612
- gr.HTML(
613
- f"<ul>"
614
- f"<li>GROQ_API_KEY: {groq_status}</li>"
615
- f"<li>GITHUB_TOKEN: {gh_status}</li>"
616
- f"</ul>"
617
- )
 
618
 
619
  # ── Footer ─────────────────────────────────────────────────────────
620
  _commit, _ts = _get_deploy_info()
 
21
 
22
  from graph import build_graph
23
  from main import _cleanup_db, SYNTHETIC_STATE
24
+ from observability import (
25
+ build_run_metadata,
26
+ enable_langsmith,
27
+ get_langfuse_handler,
28
+ is_langfuse_enabled,
29
+ is_langsmith_enabled,
30
+ estimate_groq_cost,
31
+ format_cost,
32
+ log_error_to_backends,
33
+ HealthStatus,
34
+ TokenCostCallback,
35
+ check_groq_connectivity,
36
+ check_langfuse_connectivity,
37
+ )
38
  from state import Verdict
39
 
40
  import subprocess
 
67
  # ─── Orchestration ───────────────────────────────────────────────────────────
68
 
69
 
70
+ def _init_observability_ui() -> None:
71
+ """Initialise observability backends from env vars for the Gradio UI."""
72
+ # LangSmith: enable if key is in environment
73
+ ls_key = os.environ.get("LANGCHAIN_API_KEY", "").strip()
74
+ if ls_key and not is_langsmith_enabled():
75
+ project = os.environ.get("LANGCHAIN_PROJECT", "opencodereview")
76
+ enable_langsmith(ls_key, project)
77
+ if is_langsmith_enabled():
78
+ logger.info("Observability: LangSmith enabled for Gradio UI")
79
+ if get_langfuse_handler():
80
+ logger.info("Observability: Langfuse enabled for Gradio UI")
81
+
82
+
83
  def _build_and_stream(repo: str, pr_number: int) -> tuple:
84
  """Build the graph, stream up to the interrupt, and return state + config."""
85
  graph = build_graph(DB_PATH)
86
  thread_id = str(uuid.uuid4())
87
+ handler = get_langfuse_handler()
88
+ cost_tracker = TokenCostCallback()
89
+ metadata = build_run_metadata(
90
+ source="gradio_ui", repo=repo, pr_number=pr_number, session_id=thread_id,
91
+ )
92
+ config: dict = {
93
+ "configurable": {"thread_id": f"web-{thread_id}"},
94
+ "metadata": metadata,
95
+ }
96
+ callbacks = [cost_tracker]
97
+ if handler:
98
+ callbacks.append(handler)
99
+ config["callbacks"] = callbacks
100
+
101
+ try:
102
+ initial = {"repo": repo, "pr_number": pr_number}
103
+ list(graph.stream(initial, config))
104
+ except Exception as exc:
105
+ log_error_to_backends(exc, context={"source": "gradio_ui", "phase": "stream", "repo": repo, "pr_number": pr_number})
106
+ raise
107
 
 
 
108
  state = graph.get_state(config)
109
+ return state, config, cost_tracker.summary()
110
 
111
 
112
  def _format_findings_table(findings: list) -> str:
 
229
  progress(0.1, desc="Building graph…")
230
 
231
  try:
232
+ state, config, cost_summary = _build_and_stream(repo.strip(), pr_number)
233
  except Exception as exc:
234
+ log_error_to_backends(exc, context={"source": "gradio_ui", "phase": "run_review", "repo": repo, "pr_number": pr_number})
235
  yield [None, None, None, None], f"❌ Review failed: {exc}"
236
  return
237
 
 
250
  verdict_html = _format_verdict(verdict)
251
  findings_html = _format_findings_table(findings)
252
  count_html = _format_findings_count(findings)
253
+ # Append cost info to count display
254
+ count_html += f'<p style="margin-top:8px;font-size:0.85em;color:var(--text-muted)">{cost_summary}</p>'
255
+ # Strip non-serializable callbacks before saving config to state
256
+ config_json = json.dumps(
257
+ {k: v for k, v in config.items() if k != "callbacks"}
258
+ )
259
 
260
  yield (
261
  [verdict_html, findings_html, count_html, config_json],
 
270
 
271
  config = json.loads(config_json)
272
  graph = build_graph(DB_PATH)
273
+ handler = get_langfuse_handler()
274
+ cost_tracker = TokenCostCallback()
275
+ callbacks = [cost_tracker]
276
+ if handler:
277
+ callbacks.append(handler)
278
+ config.setdefault("callbacks", []).extend(callbacks)
279
 
280
  progress(0.3, desc=f"Processing {action}…")
281
 
 
288
  if approved
289
  else "❌ Review **rejected**. No comments posted."
290
  )
291
+ if cost_tracker.usage:
292
+ msg += f" _{cost_tracker.summary()}_"
293
  return msg
294
  except Exception as exc:
295
+ log_error_to_backends(exc, context={"source": "gradio_ui", "phase": "resume_review", "action": action})
296
  return f"❌ Error: {exc}"
297
 
298
 
 
303
  progress(0.1, desc="Building graph…")
304
  graph = build_graph(DB_PATH)
305
  thread_id = str(uuid.uuid4())
306
+ handler = get_langfuse_handler()
307
+ cost_tracker = TokenCostCallback()
308
+ metadata = build_run_metadata(
309
+ source="gradio_ui", repo="demo-org/demo-repo", pr_number=1, session_id=thread_id,
310
+ )
311
+ config: dict = {
312
+ "configurable": {"thread_id": f"smoke-web-{thread_id}"},
313
+ "metadata": metadata,
314
+ }
315
+ callbacks = [cost_tracker]
316
+ if handler:
317
+ callbacks.append(handler)
318
+ config["callbacks"] = callbacks
319
 
320
  progress(0.3, desc="Running on synthetic data…")
321
+ try:
322
+ list(graph.stream(SYNTHETIC_STATE, config))
323
+ except Exception as exc:
324
+ log_error_to_backends(exc, context={"source": "gradio_ui", "phase": "smoke_stream"})
325
+ raise
326
  state = graph.get_state(config)
327
  tasks = state.tasks
328
 
 
336
  progress(0.8, desc="Formatting…")
337
  verdict_html = _format_verdict(verdict)
338
  findings_html = _format_findings_table(findings)
339
+ # Strip non-serializable callbacks before saving config to state
340
+ config_json = json.dumps(
341
+ {k: v for k, v in config.items() if k != "callbacks"}
342
+ )
343
+ cost_html = f'<p style="margin-top:8px;font-size:0.85em;color:var(--text-muted)">{cost_tracker.summary()}</p>'
344
 
345
+ yield [verdict_html, findings_html + cost_html, config_json, verdict_html, findings_html], None
346
 
347
 
348
 
 
471
  }
472
  """
473
 
474
+ # ── Initialise observability backends ────────────────────────────────
475
+ _init_observability_ui()
476
+
477
  with gr.Blocks(css=CSS, title="OpenCodeReview", theme=gr.themes.Soft()) as demo:
478
  demo.load(js=JS_RESTORE_THEME)
479
 
 
685
  )
686
 
687
  # ── Environment status footer ──────────────────────────────────────
688
+ with gr.Accordion("πŸ”‘ Configured Keys & Health", open=False):
689
+ h = HealthStatus()
690
+ health_data = h.summary()
691
  groq_ok = bool(os.environ.get("GROQ_API_KEY", "").strip())
692
  gh_ok = bool(os.environ.get("GITHUB_TOKEN", "").strip())
693
+ ls_ok = h.langsmith
694
+ lf_ok = h.langfuse
695
+ lines = [
696
+ f"<li>GROQ_API_KEY: {'βœ… Set' if groq_ok else '❌ Not set'}</li>",
697
+ f"<li>GITHUB_TOKEN: {'βœ… Set' if gh_ok else '❌ Not set'}</li>",
698
+ f"<li>LangSmith: {health_data['LangSmith']}</li>",
699
+ f"<li>Langfuse: {health_data['Langfuse']}</li>",
700
+ ]
701
+ gr.HTML(f"<ul>" + "".join(lines) + "</ul>")
702
 
703
  # ── Footer ─────────────────────────────────────────────────────────
704
  _commit, _ts = _get_deploy_info()
config.py CHANGED
@@ -69,6 +69,11 @@ class Settings(BaseSettings):
69
 
70
  anthropic_api_key: Optional[str] = Field(default=None)
71
 
 
 
 
 
 
72
  def model_post_init(self, __context) -> None: # noqa: ANN101
73
  """After env-var resolution, fall back to keyring for any unset values."""
74
  for keyring_key, _, _ in PROVIDERS.values():
@@ -91,6 +96,61 @@ class Settings(BaseSettings):
91
  return key
92
 
93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
  # ─── Key masking ─────────────────────────────────────────────────────────────
95
 
96
 
 
69
 
70
  anthropic_api_key: Optional[str] = Field(default=None)
71
 
72
+ # ── Langfuse observability (optional) ──────────────────────────────────
73
+ langfuse_public_key: Optional[str] = Field(default=None)
74
+ langfuse_secret_key: Optional[str] = Field(default=None)
75
+ langfuse_host: Optional[str] = Field(default=None)
76
+
77
  def model_post_init(self, __context) -> None: # noqa: ANN101
78
  """After env-var resolution, fall back to keyring for any unset values."""
79
  for keyring_key, _, _ in PROVIDERS.values():
 
96
  return key
97
 
98
 
99
+ # ─── Observability CLI ─────────────────────────────────────────────────────
100
+
101
+
102
+ @config.command(name="set-observability")
103
+ @click.option("--langsmith-api-key", help="LangSmith API key (for tracing)")
104
+ @click.option("--langsmith-project", default="opencodereview", show_default=True,
105
+ help="LangSmith project name")
106
+ @click.option("--langfuse-public-key", help="Langfuse public key")
107
+ @click.option("--langfuse-secret-key", help="Langfuse secret key")
108
+ @click.option("--langfuse-host", default="https://cloud.langfuse.com",
109
+ show_default=True, help="Langfuse host URL")
110
+ def set_observability(
111
+ langsmith_api_key: Optional[str],
112
+ langsmith_project: str,
113
+ langfuse_public_key: Optional[str],
114
+ langfuse_secret_key: Optional[str],
115
+ langfuse_host: str,
116
+ ) -> None:
117
+ """Configure observability backends (LangSmith and/or Langfuse).
118
+
119
+ Keys are stored in the system keyring. Both backends can be configured
120
+ simultaneously with no conflict. If neither is set, the app runs
121
+ exactly as before with zero tracing overhead.
122
+ """
123
+ if langsmith_api_key:
124
+ keyring.set_password(SERVICE_NAME, "langsmith_api_key", langsmith_api_key)
125
+ click.echo(f"LangSmith API key saved (project: {langsmith_project}).")
126
+
127
+ # Warn if env var is already set
128
+ if os.environ.get("LANGCHAIN_API_KEY"):
129
+ click.echo(
130
+ " Note: LANGCHAIN_API_KEY env var is already set β€” "
131
+ "it takes precedence over the keyring value.",
132
+ err=True,
133
+ )
134
+ else:
135
+ click.echo(" LangSmith: skipped (no --langsmith-api-key provided).")
136
+
137
+ if langfuse_public_key and langfuse_secret_key:
138
+ keyring.set_password(SERVICE_NAME, "langfuse_public_key", langfuse_public_key)
139
+ keyring.set_password(SERVICE_NAME, "langfuse_secret_key", langfuse_secret_key)
140
+ keyring.set_password(SERVICE_NAME, "langfuse_host", langfuse_host)
141
+ click.echo(f"Langfuse keys saved (host: {langfuse_host}).")
142
+
143
+ if os.environ.get("LANGFUSE_PUBLIC_KEY"):
144
+ click.echo(
145
+ " Note: LANGFUSE_PUBLIC_KEY env var is already set β€” "
146
+ "it takes precedence.",
147
+ err=True,
148
+ )
149
+ else:
150
+ click.echo(" Langfuse: skipped (need both --langfuse-public-key "
151
+ "and --langfuse-secret-key).")
152
+
153
+
154
  # ─── Key masking ─────────────────────────────────────────────────────────────
155
 
156
 
eval_data/evaluate.py CHANGED
@@ -358,6 +358,10 @@ def main() -> None:
358
  help="Bypass GITHUB_TOKEN guard and proceed with posting "
359
  "(use with caution -- comments WILL be posted to real PRs)",
360
  )
 
 
 
 
361
  args = parser.parse_args()
362
 
363
  logging.basicConfig(
@@ -445,6 +449,10 @@ def main() -> None:
445
  # --- Print results ---
446
  _print_results(results)
447
 
 
 
 
 
448
  # --- Save ---
449
  with open(RESULTS_PATH, "w", encoding="utf-8") as f:
450
  json.dump(results, f, indent=2, ensure_ascii=False)
@@ -477,5 +485,84 @@ def _print_verbose(entry: dict, findings: list[Finding], metrics: dict, use_keyw
477
  print()
478
 
479
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
480
  if __name__ == "__main__":
481
  main()
 
358
  help="Bypass GITHUB_TOKEN guard and proceed with posting "
359
  "(use with caution -- comments WILL be posted to real PRs)",
360
  )
361
+ parser.add_argument(
362
+ "--log-to-observability", action="store_true",
363
+ help="Log evaluation scores to LangSmith/Langfuse for quality-over-time tracking",
364
+ )
365
  args = parser.parse_args()
366
 
367
  logging.basicConfig(
 
449
  # --- Print results ---
450
  _print_results(results)
451
 
452
+ # --- Log to observability (optional) ---
453
+ if args.log_to_observability and results:
454
+ _log_to_observability(results)
455
+
456
  # --- Save ---
457
  with open(RESULTS_PATH, "w", encoding="utf-8") as f:
458
  json.dump(results, f, indent=2, ensure_ascii=False)
 
485
  print()
486
 
487
 
488
+ # ─── Quality-over-time: log to observability ───────────────────────────────
489
+
490
+
491
+ def _log_to_observability(results: list[dict], dataset_name: str = "opencodereview-eval") -> None:
492
+ """Log evaluation results to the active observability backend(s).
493
+
494
+ This creates a trace/run for the eval run with results as metadata,
495
+ so quality trends are visible in LangSmith / Langfuse dashboards.
496
+
497
+ For LangSmith: creates a dataset with the results (no separate SDK needed
498
+ β€” LangChain auto-traces the graph runs).
499
+ For Langfuse: creates a score for each metric via the Score API.
500
+
501
+ This function is called only when ``--log-to-observability`` is passed.
502
+ """
503
+ from observability import (
504
+ get_langfuse_handler,
505
+ is_langfuse_enabled,
506
+ is_langsmith_enabled,
507
+ )
508
+
509
+ # Compute aggregate metrics
510
+ total_tp = sum(r["tp"] for r in results)
511
+ total_fp = sum(r["fp"] for r in results)
512
+ total_fn = sum(r["fn"] for r in results)
513
+ micro_p = total_tp / (total_tp + total_fp) if (total_tp + total_fp) > 0 else 0.0
514
+ micro_r = total_tp / (total_tp + total_fn) if (total_tp + total_fn) > 0 else 0.0
515
+ micro_f = (
516
+ 2 * micro_p * micro_r / (micro_p + micro_r)
517
+ if (micro_p + micro_r) > 0
518
+ else 0.0
519
+ )
520
+
521
+ logger.info(
522
+ "Logging eval results to observability "
523
+ "(micro F1=%.3f, PRs=%d, LangSmith=%s, Langfuse=%s)",
524
+ micro_f, len(results),
525
+ is_langsmith_enabled(), is_langfuse_enabled(),
526
+ )
527
+
528
+ # ── Langfuse: create scores via SDK ──────────────────────────────────
529
+ if is_langfuse_enabled():
530
+ try:
531
+ from langfuse import Langfuse
532
+
533
+ lf = Langfuse()
534
+ run_name = f"eval-{datetime.now():%Y%m%d-%H%M%S}"
535
+
536
+ # Log per-PR scores
537
+ for r in results:
538
+ lf.score(
539
+ name=f"{dataset_name}/{r.get('id', 'unknown')}/f1",
540
+ value=r["f1"],
541
+ comment=f"{r.get('repo', '?')}#{r.get('pr_number', '?')}"
542
+ f" β€” P={r['precision']:.3f} R={r['recall']:.3f}",
543
+ )
544
+
545
+ # Log aggregate scores
546
+ lf.score(name=f"{dataset_name}/micro_f1", value=micro_f)
547
+ lf.score(name=f"{dataset_name}/micro_precision", value=micro_p)
548
+ lf.score(name=f"{dataset_name}/micro_recall", value=micro_r)
549
+ lf.score(name=f"{dataset_name}/pr_count", value=len(results))
550
+
551
+ # Flush to ensure scores are sent before process exits
552
+ lf.flush()
553
+ logger.info("Langfuse scores logged (run=%s)", run_name)
554
+ except Exception as exc:
555
+ logger.warning("Failed to log to Langfuse: %s", exc)
556
+
557
+ # ── LangSmith: scores are automatic via graph tracing ────────────────
558
+ # Every graph.invoke()/graph.stream() call is already traced by LangSmith.
559
+ # We just log the aggregate for visibility.
560
+ if is_langsmith_enabled():
561
+ logger.info(
562
+ "LangSmith tracing active β€” eval scores tracked in traced runs. "
563
+ "Check your LangSmith project for detailed per-PR traces."
564
+ )
565
+
566
+
567
  if __name__ == "__main__":
568
  main()
main.py CHANGED
@@ -23,6 +23,16 @@ from langgraph.types import Command
23
  from auth import auth as auth_group
24
  from config import config as config_group
25
  from graph import build_graph
 
 
 
 
 
 
 
 
 
 
26
  from state import ChangedFile, ContextChunk, Finding, Severity, Verdict
27
 
28
  logging.basicConfig(
@@ -34,6 +44,44 @@ logger = logging.getLogger(__name__)
34
  DB_PATH = "checkpoints.db"
35
 
36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  # ─── Synthetic payload for offline testing ──────────────────────────────────
38
 
39
  SYNTHETIC_STATE = {
@@ -111,6 +159,9 @@ def review(repo: str, pr_number: int, smoke: bool) -> None:
111
 
112
  By default this runs with a synthetic PR payload for demonstration.
113
  """
 
 
 
114
  graph = build_graph(DB_PATH)
115
 
116
  if smoke:
@@ -125,7 +176,20 @@ def _run_with_hitl(graph, repo: str, pr_number: int) -> None:
125
  """Run the graph on a real PR β€” fetches data from GitHub, pauses for
126
  human approval, then posts findings back as PR comments."""
127
  thread_id = str(uuid.uuid4())
128
- config = {"configurable": {"thread_id": f"hitl-{thread_id}"}}
 
 
 
 
 
 
 
 
 
 
 
 
 
129
 
130
  # Use synthetic demo data by default; only fetch real PRs when the
131
  # user explicitly provides a custom repo or PR number.
@@ -172,6 +236,9 @@ def _run_with_hitl(graph, repo: str, pr_number: int) -> None:
172
  )
173
  logger.info(" %s", f.comment[:120])
174
 
 
 
 
175
  logger.info("=" * 60)
176
 
177
  click.echo()
@@ -209,15 +276,29 @@ def _run_with_hitl(graph, repo: str, pr_number: int) -> None:
209
  if final_values.get("verdict"):
210
  logger.info(" Verdict: %s", final_values["verdict"].recommendation)
211
  logger.info(" Final findings: %d", len(final_values.get("final_findings", [])))
 
212
  logger.info("=" * 60)
213
  else:
214
  logger.info("Graph completed without interrupt (no findings to review?)")
 
215
 
216
 
217
  def _test_offline(graph) -> None:
218
  """Non-interactive test that the graph compiles and runs up to interrupt."""
219
  thread_id = str(uuid.uuid4())
220
- config = {"configurable": {"thread_id": f"smoke-{thread_id}"}}
 
 
 
 
 
 
 
 
 
 
 
 
221
 
222
  list(graph.stream(SYNTHETIC_STATE, config))
223
  state = graph.get_state(config)
@@ -230,6 +311,7 @@ def _test_offline(graph) -> None:
230
  print(f"Smoke test: paused=True, tasks={len(tasks)}, "
231
  f"findings={len(final_findings)}, "
232
  f"verdict={verdict.recommendation if verdict else 'None'}")
 
233
 
234
  assert len(tasks) > 0, "Graph did not pause at interrupt"
235
  assert verdict is not None, "No verdict produced"
@@ -252,12 +334,70 @@ def _cleanup_db() -> None:
252
  # ─── Root CLI ───────────────────────────────────────────────────────────────
253
 
254
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
255
  @click.group()
256
  def cli() -> None:
257
  """OpenCodeReview β€” AI-powered PR review with human-in-the-loop approval."""
258
 
259
 
260
  cli.add_command(review)
 
261
  cli.add_command(auth_group)
262
  cli.add_command(config_group)
263
 
 
23
  from auth import auth as auth_group
24
  from config import config as config_group
25
  from graph import build_graph
26
+ from observability import (
27
+ build_run_metadata,
28
+ enable_langsmith,
29
+ get_langfuse_handler,
30
+ is_langsmith_enabled,
31
+ estimate_groq_cost,
32
+ format_cost,
33
+ log_error_to_backends,
34
+ TokenCostCallback,
35
+ )
36
  from state import ChangedFile, ContextChunk, Finding, Severity, Verdict
37
 
38
  logging.basicConfig(
 
44
  DB_PATH = "checkpoints.db"
45
 
46
 
47
+ # ─── Observability initialisation ──────────────────────────────────────────
48
+
49
+
50
+ def _init_observability() -> None:
51
+ """Initialise tracing backends from env vars / keyring.
52
+
53
+ Called once at the start of each ``review`` command.
54
+ """
55
+ import keyring as _kr
56
+ from config import SERVICE_NAME as _svc
57
+
58
+ # LangSmith: favour env var, fall back to keyring
59
+ ls_key = os.environ.get("LANGCHAIN_API_KEY") or _kr.get_password(_svc, "langsmith_api_key")
60
+ if ls_key and not is_langsmith_enabled():
61
+ ls_project = (
62
+ os.environ.get("LANGCHAIN_PROJECT")
63
+ or _kr.get_password(_svc, "langsmith_project")
64
+ or "opencodereview"
65
+ )
66
+ enable_langsmith(ls_key, ls_project)
67
+
68
+ # Langfuse: env var overrides keyring
69
+ for env_key, ring_key in [
70
+ ("LANGFUSE_PUBLIC_KEY", "langfuse_public_key"),
71
+ ("LANGFUSE_SECRET_KEY", "langfuse_secret_key"),
72
+ ("LANGFUSE_HOST", "langfuse_host"),
73
+ ]:
74
+ if not os.environ.get(env_key):
75
+ val = _kr.get_password(_svc, ring_key)
76
+ if val:
77
+ os.environ[env_key] = val
78
+
79
+ if is_langsmith_enabled():
80
+ logger.info("Observability: LangSmith enabled")
81
+ if get_langfuse_handler():
82
+ logger.info("Observability: Langfuse enabled")
83
+
84
+
85
  # ─── Synthetic payload for offline testing ──────────────────────────────────
86
 
87
  SYNTHETIC_STATE = {
 
159
 
160
  By default this runs with a synthetic PR payload for demonstration.
161
  """
162
+ # ── Enable LangSmith if key is available ─────────────────────────
163
+ _init_observability()
164
+
165
  graph = build_graph(DB_PATH)
166
 
167
  if smoke:
 
176
  """Run the graph on a real PR β€” fetches data from GitHub, pauses for
177
  human approval, then posts findings back as PR comments."""
178
  thread_id = str(uuid.uuid4())
179
+ handler = get_langfuse_handler()
180
+ cost_tracker = TokenCostCallback()
181
+ metadata = build_run_metadata(
182
+ source="cli", repo=repo, pr_number=pr_number, session_id=thread_id,
183
+ )
184
+ config: dict = {
185
+ "configurable": {"thread_id": f"hitl-{thread_id}"},
186
+ "metadata": metadata,
187
+ }
188
+ # Build callbacks list with cost tracker + optional Langfuse
189
+ callbacks = [cost_tracker]
190
+ if handler:
191
+ callbacks.append(handler)
192
+ config["callbacks"] = callbacks
193
 
194
  # Use synthetic demo data by default; only fetch real PRs when the
195
  # user explicitly provides a custom repo or PR number.
 
236
  )
237
  logger.info(" %s", f.comment[:120])
238
 
239
+ # Show cost
240
+ logger.info(" %s", cost_tracker.summary())
241
+
242
  logger.info("=" * 60)
243
 
244
  click.echo()
 
276
  if final_values.get("verdict"):
277
  logger.info(" Verdict: %s", final_values["verdict"].recommendation)
278
  logger.info(" Final findings: %d", len(final_values.get("final_findings", [])))
279
+ logger.info(" %s", cost_tracker.summary())
280
  logger.info("=" * 60)
281
  else:
282
  logger.info("Graph completed without interrupt (no findings to review?)")
283
+ logger.info(" %s", cost_tracker.summary())
284
 
285
 
286
  def _test_offline(graph) -> None:
287
  """Non-interactive test that the graph compiles and runs up to interrupt."""
288
  thread_id = str(uuid.uuid4())
289
+ handler = get_langfuse_handler()
290
+ cost_tracker = TokenCostCallback()
291
+ metadata = build_run_metadata(
292
+ source="cli", repo="demo-org/demo-repo", pr_number=1, session_id=thread_id,
293
+ )
294
+ config: dict = {
295
+ "configurable": {"thread_id": f"smoke-{thread_id}"},
296
+ "metadata": metadata,
297
+ }
298
+ callbacks = [cost_tracker]
299
+ if handler:
300
+ callbacks.append(handler)
301
+ config["callbacks"] = callbacks
302
 
303
  list(graph.stream(SYNTHETIC_STATE, config))
304
  state = graph.get_state(config)
 
311
  print(f"Smoke test: paused=True, tasks={len(tasks)}, "
312
  f"findings={len(final_findings)}, "
313
  f"verdict={verdict.recommendation if verdict else 'None'}")
314
+ print(cost_tracker.summary())
315
 
316
  assert len(tasks) > 0, "Graph did not pause at interrupt"
317
  assert verdict is not None, "No verdict produced"
 
334
  # ─── Root CLI ───────────────────────────────────────────────────────────────
335
 
336
 
337
+ # ─── Doctor Command ─────────────────────────────────────────────────────────
338
+
339
+
340
+ @click.command()
341
+ def doctor() -> None:
342
+ """Run system health checks and report status."""
343
+ from config import _mask_key
344
+ from observability import (
345
+ HealthStatus,
346
+ check_groq_connectivity,
347
+ check_langfuse_connectivity,
348
+ )
349
+
350
+ click.echo()
351
+ click.echo("=" * 50)
352
+ click.echo(" OpenCodeReview β€” Health Check")
353
+ click.echo("=" * 50)
354
+ click.echo()
355
+
356
+ # ── Environment ────────────────────────────────────────────────────
357
+ click.echo("πŸ“¦ Environment")
358
+ click.echo(f" Python: {sys.version.split()[0]}")
359
+ click.echo()
360
+
361
+ # ── API keys ───────────────────────────────────────────────────────
362
+ click.echo("πŸ”‘ API Keys")
363
+ groq_key = os.environ.get("GROQ_API_KEY", "").strip()
364
+ click.echo(f" GROQ_API_KEY: {'βœ… Set' if groq_key else '❌ Not set'}")
365
+ gh_token = os.environ.get("GITHUB_TOKEN", "").strip()
366
+ click.echo(f" GITHUB_TOKEN: {'βœ… Set' if gh_token else '❌ Not set'}")
367
+ click.echo()
368
+
369
+ # ── Observability ──────────────────────────────────────────────────
370
+ click.echo("πŸ”­ Observability")
371
+ h = HealthStatus()
372
+ for comp, status in h.summary().items():
373
+ click.echo(f" {comp}: {status}")
374
+ click.echo()
375
+
376
+ # ── Connectivity tests ─────────────────────────────────────────────
377
+ click.echo("🌐 Connectivity")
378
+
379
+ # Groq
380
+ groq_ok, groq_msg = check_groq_connectivity()
381
+ click.echo(f" Groq API: {'βœ…' if groq_ok else '❌'} {groq_msg}")
382
+
383
+ # Langfuse (only if configured)
384
+ lf_ok, lf_msg = check_langfuse_connectivity()
385
+ click.echo(f" Langfuse: {'βœ…' if lf_ok else '⏭️'} {lf_msg}")
386
+
387
+ click.echo()
388
+ click.echo("=" * 50)
389
+
390
+
391
+ # ─── Root CLI ───────────────────────────────────────────────────────────────
392
+
393
+
394
  @click.group()
395
  def cli() -> None:
396
  """OpenCodeReview β€” AI-powered PR review with human-in-the-loop approval."""
397
 
398
 
399
  cli.add_command(review)
400
+ cli.add_command(doctor)
401
  cli.add_command(auth_group)
402
  cli.add_command(config_group)
403
 
nodes/aggregator.py CHANGED
@@ -2,6 +2,8 @@ from __future__ import annotations
2
 
3
  import logging
4
  import os
 
 
5
  from langchain_groq import ChatGroq
6
  from pydantic import BaseModel, Field
7
 
@@ -12,12 +14,35 @@ logger = logging.getLogger(__name__)
12
  GROQ_MODEL = "llama-3.3-70b-versatile"
13
  DEFAULT_TEMPERATURE = 0.0
14
 
 
 
 
 
15
  # Findings below this confidence are dropped before the LLM step
16
  MIN_CONFIDENCE = 0.25
17
  # Files/line pairs within this many lines are considered duplicates
18
  LINE_TOLERANCE = 5
19
 
20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  # ─── LLM output schema ──────────────────────────────────────────────────────
22
 
23
 
@@ -143,40 +168,6 @@ def _rule_summary(recommendation: str, counts: dict) -> str:
143
  return f"Approved: {body} β€” no significant issues."
144
 
145
 
146
- # ─── LLM prompt ─────────────────────────────────────────────────────────────
147
-
148
-
149
- SYSTEM_PROMPT = """You are a senior engineer acting as a **critic** of a code review.
150
- Your job is to look at the list of raw findings produced by automated reviewers
151
- and decide which ones are genuinely worth sharing with the PR author.
152
-
153
- Apply these rules strictly:
154
-
155
- 1. **Deduplicate** β€” if two findings point at the same issue (same file,
156
- overlapping lines, similar comment), keep only the more specific one.
157
- 2. **Drop noise** β€” remove findings that are:
158
- - Overly pedantic or stylistic (a senior engineer wouldn't mention them).
159
- - Speculative with very low confidence (< 0.4).
160
- - Vague or generic ("consider improving this code" without specifics).
161
- 3. **Escalate appropriately** β€” if a finding is genuinely important but the
162
- automated reviewer gave it a low severity, bump it up. Conversely, if it's
163
- a minor nitpick flagged as "critical", bump it down.
164
- 4. **Produce a verdict** β€” based on the *filtered* set of findings, decide:
165
- - `approve` β€” no significant issues, or only minor suggestions.
166
- - `request_changes` β€” issues that should be addressed before merging.
167
- - `block` β€” a critical bug that must not be merged.
168
-
169
- The verdict's `overall_score` should reflect how healthy the PR is:
170
- - 9–10: clean, trivial suggestions only
171
- - 7–8: minor issues worth noting
172
- - 5–6: should fix before merging
173
- - 3–4: several problems, strongly consider rework
174
- - 0–2: critical, must not merge
175
-
176
- Return the filtered list of findings plus your verdict.
177
- """
178
-
179
-
180
  # ─── Prompt builder ─────────────────────────────────────────────────────────
181
 
182
 
@@ -243,7 +234,10 @@ def aggregator_node(state: OpenCodeReviewState) -> dict:
243
  api_key = os.environ.get("GROQ_API_KEY", "").strip()
244
 
245
  if api_key:
246
- logger.info("Invoking aggregator LLM critic …")
 
 
 
247
  try:
248
  llm = ChatGroq(
249
  model=GROQ_MODEL,
 
2
 
3
  import logging
4
  import os
5
+ from pathlib import Path
6
+
7
  from langchain_groq import ChatGroq
8
  from pydantic import BaseModel, Field
9
 
 
14
  GROQ_MODEL = "llama-3.3-70b-versatile"
15
  DEFAULT_TEMPERATURE = 0.0
16
 
17
+ # Prompt version β€” tied to the file on disk
18
+ PROMPT_VERSION = "v1"
19
+ PROMPT_FILE = Path(__file__).resolve().parent.parent / "prompts" / f"aggregator_{PROMPT_VERSION}.txt"
20
+
21
  # Findings below this confidence are dropped before the LLM step
22
  MIN_CONFIDENCE = 0.25
23
  # Files/line pairs within this many lines are considered duplicates
24
  LINE_TOLERANCE = 5
25
 
26
 
27
+ # ─── Load prompt from file ──────────────────────────────────────────────────
28
+
29
+
30
+ def _load_prompt() -> str:
31
+ """Load the system prompt from the versioned prompt file."""
32
+ try:
33
+ return PROMPT_FILE.read_text(encoding="utf-8")
34
+ except FileNotFoundError:
35
+ logger.warning("Prompt file %s not found β€” using fallback", PROMPT_FILE)
36
+ return (
37
+ "You are a senior engineer acting as a critic of a code review. "
38
+ "Filter out noise, deduplicate findings, and produce a verdict. "
39
+ "Return the filtered list of findings plus your verdict."
40
+ )
41
+
42
+
43
+ SYSTEM_PROMPT = _load_prompt()
44
+
45
+
46
  # ─── LLM output schema ──────────────────────────────────────────────────────
47
 
48
 
 
168
  return f"Approved: {body} β€” no significant issues."
169
 
170
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
171
  # ─── Prompt builder ─────────────────────────────────────────────────────────
172
 
173
 
 
234
  api_key = os.environ.get("GROQ_API_KEY", "").strip()
235
 
236
  if api_key:
237
+ logger.info(
238
+ "Invoking aggregator LLM critic (prompt_version=%s) …",
239
+ PROMPT_VERSION,
240
+ )
241
  try:
242
  llm = ChatGroq(
243
  model=GROQ_MODEL,
nodes/correctness_reviewer.py CHANGED
@@ -2,6 +2,8 @@ from __future__ import annotations
2
 
3
  import logging
4
  import os
 
 
5
  from langchain_groq import ChatGroq
6
  from pydantic import BaseModel, Field
7
 
@@ -13,12 +15,36 @@ logger = logging.getLogger(__name__)
13
  GROQ_MODEL = "llama-3.3-70b-versatile"
14
  DEFAULT_TEMPERATURE = 0.0
15
 
 
 
 
 
16
  # Max characters of context to include in the prompt (soft limit)
17
  MAX_CONTEXT_CHARS = 6_000
18
  # Max changed-file content to include per file
19
  MAX_FILE_CONTENT_CHARS = 4_000
20
 
21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  # ─── Wrapper schema for structured output ───────────────────────────────────
23
 
24
 
@@ -37,44 +63,7 @@ class CorrectnessReview(BaseModel):
37
  )
38
 
39
 
40
- # ─── Prompt template ────────────────────────────────────────────────────────
41
-
42
-
43
- SYSTEM_PROMPT = """You are a seasoned code reviewer focused exclusively on **correctness**.
44
-
45
- Analyse the PR diff and changed files below. Look ONLY for:
46
-
47
- 1. **Logic errors** β€” incorrect boolean conditions, wrong operators, inverted
48
- if/else branches, incorrect variable shadowing, wrong function calls.
49
- 2. **Missed edge cases** β€” empty collections, None/null values, zero-length
50
- inputs, singleton lists, boundary values, negative numbers, overflow.
51
- 3. **Off-by-one errors** β€” loop bounds, slice indices, fencepost mistakes.
52
- 4. **Missing null/None checks** β€” unchecked return values, unchecked
53
- parameters that can be None, missing `is None` / `is not None` guards.
54
- 5. **Resource / state mismanagement** β€” unclosed handles, leaked connections,
55
- double-close, use-after-free, invalidated iterators.
56
- 6. **Concurrency hazards in the diff** β€” shared-mutation without locks, race
57
- windows, incorrect locking order.
58
-
59
- **Do NOT** comment on:
60
- - Code style, formatting, naming conventions, or readability.
61
- - Performance (unless it's a correctness issue like an infinite loop).
62
- - Security (that is handled by a separate reviewer).
63
- - Tests being absent (unless the diff itself adds broken tests).
64
-
65
- For each issue return a `Finding` with:
66
- - `file_path`: the file the issue is in.
67
- - `line_start` / `line_end`: the relevant line range (best guess from the diff).
68
- - `severity`: `critical` (will definitely break), `high` (very likely to break),
69
- `medium` (edge-case bug), `low` (minor, unlikely to trigger), or `info`
70
- (informational).
71
- - `category`: always `"correctness"`.
72
- - `comment`: a concise, specific explanation of the bug.
73
- - `confidence`: 0.0–1.0 reflecting how sure you are.
74
- - `suggested_fix`: a concrete code snippet of how to fix it, if applicable.
75
-
76
- If you find NO correctness issues, return an empty findings list.
77
- """
78
 
79
 
80
  def _build_prompt(state: OpenCodeReviewState) -> str:
@@ -146,10 +135,11 @@ def correctness_reviewer_node(state: OpenCodeReviewState) -> dict:
146
  # --- Build the prompt ----------------------------------------------------
147
  user_prompt = _build_prompt(state)
148
  logger.info(
149
- "Invoking correctness reviewer (diff=%s, context=%d chunks, prompt=%s)",
150
  _human_size(len(state.diff or "")),
151
  len(state.context_chunks),
152
  _human_size(len(user_prompt)),
 
153
  )
154
 
155
  # --- Invoke --------------------------------------------------------------
 
2
 
3
  import logging
4
  import os
5
+ from pathlib import Path
6
+
7
  from langchain_groq import ChatGroq
8
  from pydantic import BaseModel, Field
9
 
 
15
  GROQ_MODEL = "llama-3.3-70b-versatile"
16
  DEFAULT_TEMPERATURE = 0.0
17
 
18
+ # Prompt version β€” tied to the file on disk
19
+ PROMPT_VERSION = "v1"
20
+ PROMPT_FILE = Path(__file__).resolve().parent.parent / "prompts" / f"correctness_{PROMPT_VERSION}.txt"
21
+
22
  # Max characters of context to include in the prompt (soft limit)
23
  MAX_CONTEXT_CHARS = 6_000
24
  # Max changed-file content to include per file
25
  MAX_FILE_CONTENT_CHARS = 4_000
26
 
27
 
28
+ # ─── Load prompt from file ──────────────────────────────────────────────────
29
+
30
+
31
+ def _load_prompt() -> str:
32
+ """Load the system prompt from the versioned prompt file."""
33
+ try:
34
+ return PROMPT_FILE.read_text(encoding="utf-8")
35
+ except FileNotFoundError:
36
+ logger.warning("Prompt file %s not found β€” using fallback", PROMPT_FILE)
37
+ return (
38
+ "You are a seasoned code reviewer focused exclusively on correctness. "
39
+ "Analyse the PR diff and look for logic errors, edge cases, "
40
+ "off-by-one errors, missing null checks, resource mismanagement, "
41
+ "and concurrency hazards. Return a list of findings."
42
+ )
43
+
44
+
45
+ SYSTEM_PROMPT = _load_prompt()
46
+
47
+
48
  # ─── Wrapper schema for structured output ───────────────────────────────────
49
 
50
 
 
63
  )
64
 
65
 
66
+ # ─── Prompt builder ─────────────────────────────────────────────────────────
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
 
68
 
69
  def _build_prompt(state: OpenCodeReviewState) -> str:
 
135
  # --- Build the prompt ----------------------------------------------------
136
  user_prompt = _build_prompt(state)
137
  logger.info(
138
+ "Invoking correctness reviewer (diff=%s, context=%d chunks, prompt=%s, prompt_version=%s)",
139
  _human_size(len(state.diff or "")),
140
  len(state.context_chunks),
141
  _human_size(len(user_prompt)),
142
+ PROMPT_VERSION,
143
  )
144
 
145
  # --- Invoke --------------------------------------------------------------
nodes/security_reviewer.py CHANGED
@@ -2,6 +2,7 @@ from __future__ import annotations
2
 
3
  import logging
4
  import os
 
5
 
6
  from langchain_groq import ChatGroq
7
  from pydantic import BaseModel, Field
@@ -15,6 +16,31 @@ DEFAULT_TEMPERATURE = 0.0
15
  MAX_CONTEXT_CHARS = 6_000
16
  MAX_FILE_CONTENT_CHARS = 4_000
17
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
 
19
  # ─── Wrapper schema ──────────────────────────────────────────────────────────
20
 
@@ -27,44 +53,7 @@ class SecurityReview(BaseModel):
27
  )
28
 
29
 
30
- # ─── Prompt ─────────────────────────────────────────────────────────────────
31
-
32
-
33
- SYSTEM_PROMPT = """You are a security-focused code reviewer. Analyse the PR diff and
34
- changed files for security vulnerabilities ONLY. Look for:
35
-
36
- 1. **Injection** β€” SQL, NoSQL, command, template (SSTI), LDAP, XSS, path
37
- traversal via unsanitized user input.
38
- 2. **Secrets / credentials** β€” hardcoded API keys, tokens, passwords, or
39
- connection strings that should use environment variables or a secret store.
40
- 3. **Unsafe deserialization** β€” `pickle.loads`, `yaml.load(…)` without
41
- SafeLoader, `eval`, `exec`, or `marshal` on untrusted data.
42
- 4. **Authentication / authorisation** β€” missing or broken access control
43
- checks, privilege escalation paths, session fixation, weak password hashing.
44
- 5. **Input validation** β€” missing or insufficient validation of user-supplied
45
- data that could lead to buffer overflows, integer overflows, or format-string
46
- bugs.
47
- 6. **Cryptographic misuse** β€” weak algorithms (MD5, SHA1 for signatures),
48
- hardcoded IVs/nonces, ECB mode, insufficient key lengths, missing TLS.
49
- 7. **Information disclosure** β€” stack traces leaked to users, verbose error
50
- messages exposing internals, debug endpoints left enabled.
51
-
52
- **Do NOT** comment on:
53
- - Code style, formatting, naming conventions.
54
- - Performance (unless it creates a denial-of-service vector).
55
- - General logic errors or edge cases (handled by correctness reviewer).
56
-
57
- For each issue return a `Finding` with:
58
- - `file_path`, `line_start`, `line_end`: location in the diff.
59
- - `severity`: `critical` (remotely exploitable), `high` (privilege escalation),
60
- `medium` (information disclosure), `low` (defence in depth), or `info`.
61
- - `category`: always `"security"`.
62
- - `comment`: concise, actionable explanation.
63
- - `confidence`: 0.0–1.0.
64
- - `suggested_fix`: concrete code snippet if applicable.
65
-
66
- Return an empty findings list if no security issues are found.
67
- """
68
 
69
 
70
  def _build_prompt(state: OpenCodeReviewState) -> str:
@@ -118,9 +107,10 @@ def security_reviewer_node(state: OpenCodeReviewState) -> dict:
118
 
119
  user_prompt = _build_prompt(state)
120
  logger.info(
121
- "Invoking security reviewer (diff=%s, context=%d chunks)",
122
  _human_size(len(state.diff or "")),
123
  len(state.context_chunks),
 
124
  )
125
 
126
  try:
 
2
 
3
  import logging
4
  import os
5
+ from pathlib import Path
6
 
7
  from langchain_groq import ChatGroq
8
  from pydantic import BaseModel, Field
 
16
  MAX_CONTEXT_CHARS = 6_000
17
  MAX_FILE_CONTENT_CHARS = 4_000
18
 
19
+ # Prompt version β€” tied to the file on disk
20
+ PROMPT_VERSION = "v1"
21
+ PROMPT_FILE = Path(__file__).resolve().parent.parent / "prompts" / f"security_{PROMPT_VERSION}.txt"
22
+
23
+
24
+ # ─── Load prompt from file ──────────────────────────────────────────────────
25
+
26
+
27
+ def _load_prompt() -> str:
28
+ """Load the system prompt from the versioned prompt file."""
29
+ try:
30
+ return PROMPT_FILE.read_text(encoding="utf-8")
31
+ except FileNotFoundError:
32
+ logger.warning("Prompt file %s not found β€” using fallback", PROMPT_FILE)
33
+ return (
34
+ "You are a security-focused code reviewer. "
35
+ "Analyse the PR diff for security vulnerabilities: injection, "
36
+ "secrets, unsafe deserialisation, auth issues, input validation, "
37
+ "cryptographic misuse, and information disclosure. "
38
+ "Return a list of findings."
39
+ )
40
+
41
+
42
+ SYSTEM_PROMPT = _load_prompt()
43
+
44
 
45
  # ─── Wrapper schema ──────────────────────────────────────────────────────────
46
 
 
53
  )
54
 
55
 
56
+ # ─── Prompt builder ─────────────────────────────────────────────────────────
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
 
58
 
59
  def _build_prompt(state: OpenCodeReviewState) -> str:
 
107
 
108
  user_prompt = _build_prompt(state)
109
  logger.info(
110
+ "Invoking security reviewer (diff=%s, context=%d chunks, prompt_version=%s)",
111
  _human_size(len(state.diff or "")),
112
  len(state.context_chunks),
113
+ PROMPT_VERSION,
114
  )
115
 
116
  try:
nodes/test_coverage_reviewer.py CHANGED
@@ -2,6 +2,7 @@ from __future__ import annotations
2
 
3
  import logging
4
  import os
 
5
 
6
  from langchain_groq import ChatGroq
7
  from pydantic import BaseModel, Field
@@ -15,60 +16,42 @@ DEFAULT_TEMPERATURE = 0.0
15
  MAX_CONTEXT_CHARS = 6_000
16
  MAX_FILE_CONTENT_CHARS = 4_000
17
 
 
 
 
18
 
19
- # ─── Wrapper schema ──────────────────────────────────────────────────────────
20
 
 
21
 
22
- class TestCoverageReview(BaseModel):
23
- """Test-coverage gaps found during code review."""
24
- findings: list[Finding] = Field(
25
- default_factory=list,
26
- description="Test-coverage issues found in the PR diff.",
27
- )
28
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
- # ─── Prompt ─────────────────────────────────────────────────────────────────
31
 
 
32
 
33
- SYSTEM_PROMPT = """You are a code reviewer focused on **test coverage**. Analyse the
34
- PR diff and determine whether the changed logic has adequate test coverage.
35
 
36
- Look for:
37
 
38
- 1. **New logic without tests** β€” new functions, classes, or modules added in
39
- this diff that have no corresponding test file or test function.
40
- 2. **Modified behaviour without updated assertions** β€” existing logic that was
41
- changed in a semantically meaningful way (not just refactoring) but the
42
- corresponding tests were left unchanged, meaning they now pass vacuously or
43
- no longer cover the modified path.
44
- 3. **Edge-case branches left untested** β€” new `if`/`elif` branches, `try`/
45
- `except` handlers, or `match`/`case` arms that are not exercised by any
46
- test in the diff.
47
- 4. **Error / failure paths** β€” new error-return or exception-throwing paths
48
- that have no test asserting the error behaviour.
49
- 5. **Configuration / environment changes** β€” changes to config files,
50
- environment variables, or feature flags that affect behaviour but are not
51
- validated in tests.
52
 
53
- For each gap return a `Finding` with:
54
- - `file_path`: the source file with the gap (not the test file).
55
- - `line_start` / `line_end`: best guess of the affected lines.
56
- - `severity`: `high` (entirely new untested logic), `medium` (modified path
57
- untested), `low` (edge case not covered), `info` (suggestion).
58
- - `category`: always `"test_coverage"`.
59
- - `comment`: explain what changed and why it needs a test.
60
- - `confidence`: 0.0–1.0.
61
- - `suggested_fix`: what a good test should cover (not full code, just
62
- the scenario to test).
63
 
64
- **Do NOT** comment on:
65
- - Purely cosmetic or refactoring changes (rename, extract method).
66
- - Third-party dependencies or generated files.
67
- - Changes to test files themselves (they are the solution, not the problem).
68
- - Correctness of the logic itself (handled by correctness reviewer).
69
 
70
- Return an empty findings list if every changed path has adequate test coverage.
71
- """
72
 
73
 
74
  def _build_prompt(state: OpenCodeReviewState) -> str:
@@ -122,9 +105,10 @@ def test_coverage_reviewer_node(state: OpenCodeReviewState) -> dict:
122
 
123
  user_prompt = _build_prompt(state)
124
  logger.info(
125
- "Invoking test-coverage reviewer (diff=%s, context=%d chunks)",
126
  _human_size(len(state.diff or "")),
127
  len(state.context_chunks),
 
128
  )
129
 
130
  try:
 
2
 
3
  import logging
4
  import os
5
+ from pathlib import Path
6
 
7
  from langchain_groq import ChatGroq
8
  from pydantic import BaseModel, Field
 
16
  MAX_CONTEXT_CHARS = 6_000
17
  MAX_FILE_CONTENT_CHARS = 4_000
18
 
19
+ # Prompt version β€” tied to the file on disk
20
+ PROMPT_VERSION = "v1"
21
+ PROMPT_FILE = Path(__file__).resolve().parent.parent / "prompts" / f"test_coverage_{PROMPT_VERSION}.txt"
22
 
 
23
 
24
+ # ─── Load prompt from file ──────────────────────────────────────────────────
25
 
 
 
 
 
 
 
26
 
27
+ def _load_prompt() -> str:
28
+ """Load the system prompt from the versioned prompt file."""
29
+ try:
30
+ return PROMPT_FILE.read_text(encoding="utf-8")
31
+ except FileNotFoundError:
32
+ logger.warning("Prompt file %s not found β€” using fallback", PROMPT_FILE)
33
+ return (
34
+ "You are a code reviewer focused on test coverage. "
35
+ "Analyse the PR diff and determine whether the changed logic "
36
+ "has adequate test coverage. Return a list of findings."
37
+ )
38
 
 
39
 
40
+ SYSTEM_PROMPT = _load_prompt()
41
 
 
 
42
 
43
+ # ─── Wrapper schema ──────────────────────────────────────────────────────────
44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
 
46
+ class TestCoverageReview(BaseModel):
47
+ """Test-coverage gaps found during code review."""
48
+ findings: list[Finding] = Field(
49
+ default_factory=list,
50
+ description="Test-coverage issues found in the PR diff.",
51
+ )
 
 
 
 
52
 
 
 
 
 
 
53
 
54
+ # ─── Prompt builder ─────────────────────────────────────────────────────────
 
55
 
56
 
57
  def _build_prompt(state: OpenCodeReviewState) -> str:
 
105
 
106
  user_prompt = _build_prompt(state)
107
  logger.info(
108
+ "Invoking test-coverage reviewer (diff=%s, context=%d chunks, prompt_version=%s)",
109
  _human_size(len(state.diff or "")),
110
  len(state.context_chunks),
111
+ PROMPT_VERSION,
112
  )
113
 
114
  try:
observability.py ADDED
@@ -0,0 +1,396 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Observability & monitoring for OpenCodeReview.
3
+
4
+ Provides a single-entry-point module for all tracing, cost tracking,
5
+ metadata attribution, health checks, and alerting concerns.
6
+
7
+ Backends
8
+ --------
9
+ * **LangSmith** β€” automatic via ``LANGCHAIN_API_KEY`` / ``LANGCHAIN_PROJECT``
10
+ env vars. LangGraph/LangChain reads these at import time and starts
11
+ tracing without any per-call code.
12
+ * **Langfuse** β€” explicit ``CallbackHandler`` instantiated only when
13
+ ``LANGFUSE_PUBLIC_KEY`` and ``LANGFUSE_SECRET_KEY`` are set.
14
+
15
+ Usage
16
+ -----
17
+ from observability import get_langfuse_handler, build_run_metadata
18
+
19
+ handler = get_langfuse_handler()
20
+ metadata = build_run_metadata(source="cli", repo="org/repo", pr_number=42)
21
+ config = {"configurable": {"thread_id": "..."}, "metadata": metadata}
22
+ if handler:
23
+ config["callbacks"] = [handler]
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import logging
29
+ import os
30
+ import platform
31
+ import uuid
32
+ from datetime import datetime, timezone
33
+ from typing import Any, Optional
34
+
35
+ logger = logging.getLogger(__name__)
36
+
37
+ # ─── LangSmith (automatic, env-var-driven) ──────────────────────────────────
38
+
39
+
40
+ def is_langsmith_enabled() -> bool:
41
+ """Return True if LangSmith tracing is configured via env vars."""
42
+ return bool(os.environ.get("LANGCHAIN_API_KEY", "").strip())
43
+
44
+
45
+ def enable_langsmith(api_key: str, project: str = "") -> None:
46
+ """Set the environment variables that LangChain/LangGraph reads at runtime.
47
+
48
+ Call this at startup **before** any LangChain/LangGraph imports so that
49
+ the tracing is active from the first call.
50
+ """
51
+ os.environ["LANGCHAIN_TRACING_V2"] = "true"
52
+ os.environ["LANGCHAIN_API_KEY"] = api_key
53
+ if project:
54
+ os.environ["LANGCHAIN_PROJECT"] = project
55
+ logger.info(
56
+ "LangSmith tracing enabled (project=%s)",
57
+ project or os.environ.get("LANGCHAIN_PROJECT", "default"),
58
+ )
59
+
60
+
61
+ def disable_langsmith() -> None:
62
+ """Remove LangSmith env vars so tracing stops."""
63
+ os.environ.pop("LANGCHAIN_TRACING_V2", None)
64
+ os.environ.pop("LANGCHAIN_API_KEY", None)
65
+ # Keep LANGCHAIN_PROJECT in case user wants to set it separately
66
+
67
+
68
+ # ─── Langfuse (explicit callback) ──────────────────────────────────────────
69
+
70
+
71
+ def get_langfuse_handler():
72
+ """Return a Langfuse ``CallbackHandler`` if keys are configured, else None.
73
+
74
+ Reads ``LANGFUSE_PUBLIC_KEY``, ``LANGFUSE_SECRET_KEY``, and optionally
75
+ ``LANGFUSE_HOST`` from environment variables.
76
+ """
77
+ public_key = os.environ.get("LANGFUSE_PUBLIC_KEY", "").strip()
78
+ secret_key = os.environ.get("LANGFUSE_SECRET_KEY", "").strip()
79
+ host = os.environ.get(
80
+ "LANGFUSE_HOST", "https://cloud.langfuse.com"
81
+ ).strip()
82
+
83
+ if not public_key or not secret_key:
84
+ return None
85
+
86
+ try:
87
+ from langfuse.callback import CallbackHandler
88
+
89
+ return CallbackHandler(
90
+ public_key=public_key,
91
+ secret_key=secret_key,
92
+ host=host,
93
+ )
94
+ except ImportError:
95
+ logger.warning("langfuse package not installed β€” skipping tracing")
96
+ return None
97
+ except Exception as exc:
98
+ logger.warning("Failed to initialise Langfuse handler: %s", exc)
99
+ return None
100
+
101
+
102
+ def is_langfuse_enabled() -> bool:
103
+ """Return True if Langfuse keys are present in the environment."""
104
+ pk = os.environ.get("LANGFUSE_PUBLIC_KEY", "").strip()
105
+ sk = os.environ.get("LANGFUSE_SECRET_KEY", "").strip()
106
+ return bool(pk and sk)
107
+
108
+
109
+ # ─── Run metadata ──────────────────────────────────────────────────────────
110
+
111
+
112
+ def build_run_metadata(
113
+ source: str = "cli",
114
+ repo: str = "",
115
+ pr_number: int = 0,
116
+ session_id: Optional[str] = None,
117
+ user_id: Optional[str] = None,
118
+ prompt_versions: Optional[dict[str, str]] = None,
119
+ extra: Optional[dict[str, Any]] = None,
120
+ ) -> dict[str, Any]:
121
+ """Build a metadata dict attached to every trace/span.
122
+
123
+ Parameters
124
+ ----------
125
+ source : str
126
+ ``"cli"`` or ``"gradio_ui"``.
127
+ repo : str
128
+ GitHub repository being reviewed (e.g. ``"psf/requests"``).
129
+ pr_number : int
130
+ PR number being reviewed.
131
+ session_id : str or None
132
+ Unique session / thread identifier.
133
+ user_id : str or None
134
+ GitHub username (CLI) or anonymised token (Gradio).
135
+ prompt_versions : dict or None
136
+ Map of reviewer name β†’ prompt file version (e.g.
137
+ ``{"correctness": "v1", "security": "v1"}``).
138
+ extra : dict or None
139
+ Any additional key-value pairs to attach.
140
+
141
+ Returns
142
+ -------
143
+ dict
144
+ Flat metadata dict suitable for ``config["metadata"]``.
145
+ """
146
+ meta: dict[str, Any] = {
147
+ "source": source,
148
+ "app": "opencodereview",
149
+ "host": platform.node(),
150
+ "timestamp": datetime.now(timezone.utc).isoformat(),
151
+ }
152
+
153
+ if repo:
154
+ meta["repo"] = repo
155
+ if pr_number:
156
+ meta["pr_number"] = pr_number
157
+ if session_id:
158
+ meta["session_id"] = session_id
159
+ if user_id:
160
+ meta["user_id"] = user_id
161
+ if prompt_versions:
162
+ meta["prompt_versions"] = prompt_versions
163
+ if extra:
164
+ meta.update(extra)
165
+
166
+ return meta
167
+
168
+
169
+ # ─── Cost tracking ─────────────────────────────────────────────────────────
170
+
171
+
172
+ # Groq published per-1M-token pricing (USD) β€” as of 2025-07
173
+ # Source: https://console.groq.com/docs/pricing
174
+ GROQ_PRICING: dict[str, dict[str, float]] = {
175
+ "llama-3.3-70b-versatile": {"input": 0.59, "output": 0.79},
176
+ # Fallback for unknown models β€” pessimistic estimate
177
+ "__default__": {"input": 1.00, "output": 1.00},
178
+ }
179
+
180
+
181
+ def estimate_groq_cost(
182
+ model: str,
183
+ input_tokens: int,
184
+ output_tokens: int,
185
+ ) -> float:
186
+ """Estimate the USD cost of a Groq LLM call.
187
+
188
+ Parameters
189
+ ----------
190
+ model : str
191
+ Groq model name (e.g. ``"llama-3.3-70b-versatile"``).
192
+ input_tokens : int
193
+ Number of tokens in the prompt (system + user messages).
194
+ output_tokens : int
195
+ Number of tokens in the completion.
196
+
197
+ Returns
198
+ -------
199
+ float
200
+ Estimated cost in USD.
201
+ """
202
+ pricing = GROQ_PRICING.get(model, GROQ_PRICING["__default__"])
203
+ input_cost = (input_tokens / 1_000_000) * pricing["input"]
204
+ output_cost = (output_tokens / 1_000_000) * pricing["output"]
205
+ return round(input_cost + output_cost, 6)
206
+
207
+
208
+ def format_cost(cost_usd: float) -> str:
209
+ """Format a USD cost for human-readable display."""
210
+ if cost_usd < 0.001:
211
+ return f"${cost_usd * 1000:.2f}β€―mΒ’"
212
+ return f"${cost_usd:.4f}"
213
+
214
+
215
+ # ─── Health check helpers ──────────────────────────────────────────────────
216
+
217
+
218
+ class HealthStatus:
219
+ """Aggregate health of the observability and API connectivity."""
220
+
221
+ def __init__(self) -> None:
222
+ self.langsmith: bool = is_langsmith_enabled()
223
+ self.langfuse: bool = is_langfuse_enabled()
224
+ self.groq: bool = bool(os.environ.get("GROQ_API_KEY", "").strip())
225
+ self.github: bool = bool(os.environ.get("GITHUB_TOKEN", "").strip())
226
+
227
+ @property
228
+ def any_tracing(self) -> bool:
229
+ return self.langsmith or self.langfuse
230
+
231
+ def summary(self) -> dict[str, str]:
232
+ """Return a dict of component β†’ status string."""
233
+ return {
234
+ "LangSmith": "βœ… Active" if self.langsmith else "β›” Not configured",
235
+ "Langfuse": "βœ… Active" if self.langfuse else "β›” Not configured",
236
+ "Groq API": "βœ… Key set" if self.groq else "β›” No key",
237
+ "GitHub API": "βœ… Token set" if self.github else "β›” No token",
238
+ }
239
+
240
+
241
+ def check_groq_connectivity() -> tuple[bool, str]:
242
+ """Lightweight Groq connectivity check β€” does not consume quota.
243
+
244
+ Uses ``urllib.request`` from stdlib (no extra dependencies).
245
+
246
+ Returns ``(ok, message)``.
247
+ """
248
+ import json as _json
249
+ import urllib.error as _urlerror
250
+ import urllib.request as _urlreq
251
+
252
+ api_key = os.environ.get("GROQ_API_KEY", "").strip()
253
+ if not api_key:
254
+ return False, "No GROQ_API_KEY set"
255
+
256
+ try:
257
+ req = _urlreq.Request(
258
+ "https://api.groq.com/openai/v1/models",
259
+ headers={
260
+ "Authorization": f"Bearer {api_key}",
261
+ "Content-Type": "application/json",
262
+ },
263
+ method="GET",
264
+ )
265
+ with _urlreq.urlopen(req, timeout=10) as resp:
266
+ if resp.status == 200:
267
+ data = _json.loads(resp.read().decode("utf-8"))
268
+ models = data.get("data", [])
269
+ count = len(models)
270
+ return True, f"Reachable β€” {count} models available"
271
+ else:
272
+ return False, f"HTTP {resp.status}"
273
+ except _urlerror.HTTPError as exc:
274
+ if exc.code == 401:
275
+ return False, "Invalid API key (401)"
276
+ return False, f"HTTP {exc.code}"
277
+ except Exception as exc:
278
+ return False, str(exc)
279
+
280
+
281
+ def check_langfuse_connectivity() -> tuple[bool, str]:
282
+ """Lightweight Langfuse connectivity check.
283
+
284
+ Returns ``(ok, message)``.
285
+ """
286
+ if not is_langfuse_enabled():
287
+ return False, "Not configured"
288
+
289
+ try:
290
+ from langfuse import Langfuse
291
+
292
+ lf = Langfuse()
293
+ lf.auth_check()
294
+ return True, "Connected"
295
+ except Exception as exc:
296
+ return False, str(exc)
297
+
298
+
299
+ # ─── Token cost callback (accumulates LLM usage across a run) ────────────
300
+
301
+
302
+ class TokenCostCallback:
303
+ """Accumulates per-model token usage from LangChain LLM calls.
304
+
305
+ Usage
306
+ -----
307
+ counter = TokenCostCallback()
308
+ config["callbacks"] = [counter, langfuse_handler] # if langfuse
309
+ ... run graph ...
310
+ print(counter.summary())
311
+ """
312
+
313
+ def __init__(self) -> None:
314
+ self.usage: list[dict[str, Any]] = []
315
+
316
+ @property
317
+ def total_input_tokens(self) -> int:
318
+ return sum(u.get("input_tokens", 0) for u in self.usage)
319
+
320
+ @property
321
+ def total_output_tokens(self) -> int:
322
+ return sum(u.get("output_tokens", 0) for u in self.usage)
323
+
324
+ @property
325
+ def total_cost(self) -> float:
326
+ return sum(u.get("cost", 0.0) for u in self.usage)
327
+
328
+ def on_llm_end(self, response) -> None:
329
+ """LangChain callback β€” called after each LLM invocation."""
330
+ try:
331
+ usage = response.llm_output or {}
332
+ token_usage = usage.get("token_usage", {}) or {}
333
+ model = usage.get("model_name", "") or ""
334
+
335
+ input_tokens = token_usage.get("prompt_tokens", 0) or 0
336
+ output_tokens = token_usage.get("completion_tokens", 0) or 0
337
+
338
+ if input_tokens > 0 or output_tokens > 0:
339
+ cost = estimate_groq_cost(model, input_tokens, output_tokens)
340
+ self.usage.append({
341
+ "model": model,
342
+ "input_tokens": input_tokens,
343
+ "output_tokens": output_tokens,
344
+ "cost": cost,
345
+ })
346
+ except Exception:
347
+ pass # Best-effort β€” don't let cost tracking crash the run
348
+
349
+ def summary(self) -> str:
350
+ """Return a human-readable cost summary."""
351
+ calls = len(self.usage)
352
+ if calls == 0:
353
+ return "Cost: N/A (no LLM calls captured)"
354
+ return (
355
+ f"Cost: {format_cost(self.total_cost)}"
356
+ f" Β· {calls} LLM call(s)"
357
+ f" Β· {self.total_input_tokens:,} in / {self.total_output_tokens:,} out tokens"
358
+ )
359
+
360
+ def reset(self) -> None:
361
+ self.usage.clear()
362
+
363
+
364
+ # ─── Error event logging ─────────────────────────────────────────────────--
365
+
366
+
367
+ def log_error_to_backends(
368
+ error: Exception,
369
+ context: Optional[dict[str, Any]] = None,
370
+ ) -> None:
371
+ """Log an error event to whichever observability backend(s) are active.
372
+
373
+ For LangSmith: logs via LangChain's callback system (automatic).
374
+ For Langfuse: creates an identifyable error event via the SDK.
375
+
376
+ This function primarily logs to ``logger`` with full traceback and
377
+ enriches the log record with context that the tracing backends pick up.
378
+
379
+ Parameters
380
+ ----------
381
+ error : Exception
382
+ The exception that occurred.
383
+ context : dict or None
384
+ Additional context about where/when the error happened.
385
+ """
386
+ extras = ""
387
+ if context:
388
+ extras = f" [{', '.join(f'{k}={v}' for k, v in context.items())}]"
389
+
390
+ logger.exception(
391
+ "OBSERVABILITY-ERROR%s: %s: %s",
392
+ extras,
393
+ type(error).__name__,
394
+ error,
395
+ exc_info=error,
396
+ )
prompts/aggregator_v1.txt ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ You are a senior engineer acting as a **critic** of a code review.
2
+ Your job is to look at the list of raw findings produced by automated reviewers
3
+ and decide which ones are genuinely worth sharing with the PR author.
4
+
5
+ Apply these rules strictly:
6
+
7
+ 1. **Deduplicate** β€” if two findings point at the same issue (same file,
8
+ overlapping lines, similar comment), keep only the more specific one.
9
+ 2. **Drop noise** β€” remove findings that are:
10
+ - Overly pedantic or stylistic (a senior engineer wouldn't mention them).
11
+ - Speculative with very low confidence (< 0.4).
12
+ - Vague or generic ("consider improving this code" without specifics).
13
+ 3. **Escalate appropriately** β€” if a finding is genuinely important but the
14
+ automated reviewer gave it a low severity, bump it up. Conversely, if it's
15
+ a minor nitpick flagged as "critical", bump it down.
16
+ 4. **Produce a verdict** β€” based on the *filtered* set of findings, decide:
17
+ - `approve` β€” no significant issues, or only minor suggestions.
18
+ - `request_changes` β€” issues that should be addressed before merging.
19
+ - `block` β€” a critical bug that must not be merged.
20
+
21
+ The verdict's `overall_score` should reflect how healthy the PR is:
22
+ - 9–10: clean, trivial suggestions only
23
+ - 7–8: minor issues worth noting
24
+ - 5–6: should fix before merging
25
+ - 3–4: several problems, strongly consider rework
26
+ - 0–2: critical, must not merge
27
+
28
+ Return the filtered list of findings plus your verdict.
prompts/correctness_v1.txt ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ You are a seasoned code reviewer focused exclusively on **correctness**.
2
+
3
+ Analyse the PR diff and changed files below. Look ONLY for:
4
+
5
+ 1. **Logic errors** β€” incorrect boolean conditions, wrong operators, inverted
6
+ if/else branches, incorrect variable shadowing, wrong function calls.
7
+ 2. **Missed edge cases** β€” empty collections, None/null values, zero-length
8
+ inputs, singleton lists, boundary values, negative numbers, overflow.
9
+ 3. **Off-by-one errors** β€” loop bounds, slice indices, fencepost mistakes.
10
+ 4. **Missing null/None checks** β€” unchecked return values, unchecked
11
+ parameters that can be None, missing `is None` / `is not None` guards.
12
+ 5. **Resource / state mismanagement** β€” unclosed handles, leaked connections,
13
+ double-close, use-after-free, invalidated iterators.
14
+ 6. **Concurrency hazards in the diff** β€” shared-mutation without locks, race
15
+ windows, incorrect locking order.
16
+
17
+ **Do NOT** comment on:
18
+ - Code style, formatting, naming conventions, or readability.
19
+ - Performance (unless it's a correctness issue like an infinite loop).
20
+ - Security (that is handled by a separate reviewer).
21
+ - Tests being absent (unless the diff itself adds broken tests).
22
+
23
+ For each issue return a `Finding` with:
24
+ - `file_path`: the file the issue is in.
25
+ - `line_start` / `line_end`: the relevant line range (best guess from the diff).
26
+ - `severity`: `critical` (will definitely break), `high` (very likely to break),
27
+ `medium` (edge-case bug), `low` (minor, unlikely to trigger), or `info`
28
+ (informational).
29
+ - `category`: always `"correctness"`.
30
+ - `comment`: a concise, specific explanation of the bug.
31
+ - `confidence`: 0.0–1.0 reflecting how sure you are.
32
+ - `suggested_fix`: a concrete code snippet of how to fix it, if applicable.
33
+
34
+ If you find NO correctness issues, return an empty findings list.
prompts/security_v1.txt ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ You are a security-focused code reviewer. Analyse the PR diff and
2
+ changed files for security vulnerabilities ONLY. Look for:
3
+
4
+ 1. **Injection** β€” SQL, NoSQL, command, template (SSTI), LDAP, XSS, path
5
+ traversal via unsanitized user input.
6
+ 2. **Secrets / credentials** β€” hardcoded API keys, tokens, passwords, or
7
+ connection strings that should use environment variables or a secret store.
8
+ 3. **Unsafe deserialization** β€” `pickle.loads`, `yaml.load(…)` without
9
+ SafeLoader, `eval`, `exec`, or `marshal` on untrusted data.
10
+ 4. **Authentication / authorisation** β€” missing or broken access control
11
+ checks, privilege escalation paths, session fixation, weak password hashing.
12
+ 5. **Input validation** β€” missing or insufficient validation of user-supplied
13
+ data that could lead to buffer overflows, integer overflows, or format-string
14
+ bugs.
15
+ 6. **Cryptographic misuse** β€” weak algorithms (MD5, SHA1 for signatures),
16
+ hardcoded IVs/nonces, ECB mode, insufficient key lengths, missing TLS.
17
+ 7. **Information disclosure** β€” stack traces leaked to users, verbose error
18
+ messages exposing internals, debug endpoints left enabled.
19
+
20
+ **Do NOT** comment on:
21
+ - Code style, formatting, naming conventions.
22
+ - Performance (unless it creates a denial-of-service vector).
23
+ - General logic errors or edge cases (handled by correctness reviewer).
24
+
25
+ For each issue return a `Finding` with:
26
+ - `file_path`, `line_start`, `line_end`: location in the diff.
27
+ - `severity`: `critical` (remotely exploitable), `high` (privilege escalation),
28
+ `medium` (information disclosure), `low` (defence in depth), or `info`.
29
+ - `category`: always `"security"`.
30
+ - `comment`: concise, actionable explanation.
31
+ - `confidence`: 0.0–1.0.
32
+ - `suggested_fix`: concrete code snippet if applicable.
33
+
34
+ Return an empty findings list if no security issues are found.
prompts/test_coverage_v1.txt ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ You are a code reviewer focused on **test coverage**. Analyse the
2
+ PR diff and determine whether the changed logic has adequate test coverage.
3
+
4
+ Look for:
5
+
6
+ 1. **New logic without tests** β€” new functions, classes, or modules added in
7
+ this diff that have no corresponding test file or test function.
8
+ 2. **Modified behaviour without updated assertions** β€” existing logic that was
9
+ changed in a semantically meaningful way (not just refactoring) but the
10
+ corresponding tests were left unchanged, meaning they now pass vacuously or
11
+ no longer cover the modified path.
12
+ 3. **Edge-case branches left untested** β€” new `if`/`elif` branches, `try`/
13
+ `except` handlers, or `match`/`case` arms that are not exercised by any
14
+ test in the diff.
15
+ 4. **Error / failure paths** β€” new error-return or exception-throwing paths
16
+ that have no test asserting the error behaviour.
17
+ 5. **Configuration / environment changes** β€” changes to config files,
18
+ environment variables, or feature flags that affect behaviour but are not
19
+ validated in tests.
20
+
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.
29
+ - `suggested_fix`: what a good test should cover (not full code, just
30
+ the scenario to test).
31
+
32
+ **Do NOT** comment on:
33
+ - Purely cosmetic or refactoring changes (rename, extract method).
34
+ - Third-party dependencies or generated files.
35
+ - Changes to test files themselves (they are the solution, not the problem).
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.
requirements.txt CHANGED
@@ -8,3 +8,4 @@ click>=8.1
8
  gradio>=4.0
9
  langchain-groq
10
  chromadb
 
 
8
  gradio>=4.0
9
  langchain-groq
10
  chromadb
11
+ langfuse
scripts/alert.py ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Alerting monitor for OpenCodeReview.
3
+
4
+ Runs a smoke-test review against a known reference PR and compares the
5
+ verdict/score against a last-known-good baseline. Sends a webhook
6
+ notification (Discord or Slack) if the score deviates significantly or
7
+ the run errors out.
8
+
9
+ Usage
10
+ -----
11
+ python scripts/alert.py \\
12
+ --baseline-file alert_baseline.json \\
13
+ --discord-webhook "$DISCORD_WEBHOOK_URL"
14
+
15
+ # Or with Slack
16
+ python scripts/alert.py \\
17
+ --baseline-file alert_baseline.json \\
18
+ --slack-webhook "$SLACK_WEBHOOK_URL"
19
+
20
+ Cron (GitHub Actions)
21
+ ---------------------
22
+ Runs via .github/workflows/alert.yml every 6 hours.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import argparse
28
+ import json
29
+ import logging
30
+ import os
31
+ import sys
32
+ import uuid
33
+ from datetime import datetime, timezone
34
+ from pathlib import Path
35
+ from typing import Any, Optional
36
+
37
+ # Ensure project root is on sys.path
38
+ _project_root = Path(__file__).resolve().parent.parent
39
+ sys.path.insert(0, str(_project_root))
40
+
41
+ import urllib.request
42
+ import urllib.error
43
+
44
+ from graph import build_graph
45
+ from langgraph.types import Command
46
+ from main import SYNTHETIC_STATE
47
+ from observability import TokenCostCallback, get_langfuse_handler, build_run_metadata
48
+
49
+ logging.basicConfig(
50
+ level=logging.INFO,
51
+ format="%(asctime)s [%(levelname)s] %(name)s β€” %(message)s",
52
+ )
53
+ logger = logging.getLogger(__name__)
54
+
55
+ DEFAULT_BASELINE = Path(__file__).resolve().parent / "alert_baseline.json"
56
+
57
+ # A score deviation beyond this threshold (points) triggers alert
58
+ SCORE_TOLERANCE = 2.5
59
+
60
+
61
+ # ─── Baseline management ────────────────────────────────────────────────────
62
+
63
+
64
+ def _load_baseline(path: Path) -> dict[str, Any]:
65
+ """Load the last-known-good baseline from disk."""
66
+ if path.exists():
67
+ with open(path, encoding="utf-8") as f:
68
+ return json.load(f)
69
+ return {}
70
+
71
+
72
+ def _save_baseline(path: Path, data: dict[str, Any]) -> None:
73
+ """Save the current run result as the new baseline."""
74
+ with open(path, "w", encoding="utf-8") as f:
75
+ json.dump(data, f, indent=2, ensure_ascii=False)
76
+ logger.info("Baseline saved to %s", path)
77
+
78
+
79
+ # ─── Run smoke test ─────────────────────────────────────────────────────────
80
+
81
+
82
+ def _run_smoke_test() -> dict[str, Any]:
83
+ """Execute one smoke-test review and return the results.
84
+
85
+ Returns
86
+ -------
87
+ dict with keys: success, score, verdict, findings_count, cost, error
88
+ """
89
+ db_path = str(_project_root / "alert_checkpoints.db")
90
+ graph = build_graph(db_path)
91
+ thread_id = str(uuid.uuid4())
92
+ handler = get_langfuse_handler()
93
+ cost_tracker = TokenCostCallback()
94
+ metadata = build_run_metadata(
95
+ source="cli", repo="demo-org/demo-repo",
96
+ pr_number=1, session_id=thread_id,
97
+ )
98
+ config: dict = {
99
+ "configurable": {"thread_id": f"alert-{thread_id}"},
100
+ "metadata": metadata,
101
+ }
102
+ callbacks = [cost_tracker]
103
+ if handler:
104
+ callbacks.append(handler)
105
+ config["callbacks"] = callbacks
106
+
107
+ try:
108
+ list(graph.stream(SYNTHETIC_STATE, config))
109
+ state = graph.get_state(config)
110
+ tasks = state.tasks
111
+ values = state.values
112
+
113
+ if not tasks:
114
+ # Graph completed without findings
115
+ verdict = values.get("verdict")
116
+ score = verdict.overall_score if verdict else 0.0
117
+ result = {
118
+ "success": True,
119
+ "score": score,
120
+ "verdict": verdict.recommendation if verdict else "none",
121
+ "findings_count": len(values.get("final_findings", [])),
122
+ "cost": cost_tracker.summary(),
123
+ "error": None,
124
+ "timestamp": datetime.now(timezone.utc).isoformat(),
125
+ }
126
+ else:
127
+ # Resume with reject to complete
128
+ graph.invoke(Command(resume={"action": "reject"}), config)
129
+ final_state = graph.get_state(config)
130
+ verdict = final_state.values.get("verdict")
131
+ findings = final_state.values.get("final_findings", [])
132
+ score = verdict.overall_score if verdict else 0.0
133
+ result = {
134
+ "success": True,
135
+ "score": score,
136
+ "verdict": verdict.recommendation if verdict else "none",
137
+ "findings_count": len(findings),
138
+ "cost": cost_tracker.summary(),
139
+ "error": None,
140
+ "timestamp": datetime.now(timezone.utc).isoformat(),
141
+ }
142
+
143
+ # Cleanup
144
+ if os.path.exists(db_path):
145
+ try:
146
+ os.remove(db_path)
147
+ except PermissionError:
148
+ pass
149
+
150
+ return result
151
+
152
+ except Exception as exc:
153
+ # Cleanup on error
154
+ if os.path.exists(db_path):
155
+ try:
156
+ os.remove(db_path)
157
+ except PermissionError:
158
+ pass
159
+ return {
160
+ "success": False,
161
+ "score": 0.0,
162
+ "verdict": "error",
163
+ "findings_count": 0,
164
+ "cost": "N/A",
165
+ "error": str(exc),
166
+ "timestamp": datetime.now(timezone.utc).isoformat(),
167
+ }
168
+
169
+
170
+ # ─── Webhook notification ────────────────────────────────────────────────────
171
+
172
+
173
+ def _send_discord(webhook: str, message: str) -> None:
174
+ """Send a message to a Discord channel via webhook."""
175
+ payload = json.dumps({"content": message}).encode("utf-8")
176
+ req = urllib.request.Request(
177
+ webhook,
178
+ data=payload,
179
+ headers={"Content-Type": "application/json"},
180
+ method="POST",
181
+ )
182
+ try:
183
+ urllib.request.urlopen(req, timeout=15)
184
+ logger.info("Discord notification sent")
185
+ except urllib.error.URLError as exc:
186
+ logger.warning("Failed to send Discord webhook: %s", exc)
187
+
188
+
189
+ def _send_slack(webhook: str, message: str) -> None:
190
+ """Send a message to a Slack channel via webhook."""
191
+ payload = json.dumps({"text": message}).encode("utf-8")
192
+ req = urllib.request.Request(
193
+ webhook,
194
+ data=payload,
195
+ headers={"Content-Type": "application/json"},
196
+ method="POST",
197
+ )
198
+ try:
199
+ urllib.request.urlopen(req, timeout=15)
200
+ logger.info("Slack notification sent")
201
+ except urllib.error.URLError as exc:
202
+ logger.warning("Failed to send Slack webhook: %s", exc)
203
+
204
+
205
+ # ─── Main ────────────────────────────────────────────────────────────────────
206
+
207
+
208
+ def main() -> None:
209
+ parser = argparse.ArgumentParser(
210
+ description="Run smoke-test alert check for OpenCodeReview",
211
+ )
212
+ parser.add_argument(
213
+ "--baseline-file", type=Path, default=DEFAULT_BASELINE,
214
+ help="Path to baseline JSON file (default: %(default)s)",
215
+ )
216
+ parser.add_argument(
217
+ "--discord-webhook", default=os.environ.get("DISCORD_WEBHOOK", ""),
218
+ help="Discord webhook URL (or DISCORD_WEBHOOK env var)",
219
+ )
220
+ parser.add_argument(
221
+ "--slack-webhook", default=os.environ.get("SLACK_WEBHOOK", ""),
222
+ help="Slack webhook URL (or SLACK_WEBHOOK env var)",
223
+ )
224
+ parser.add_argument(
225
+ "--update-baseline", action="store_true",
226
+ help="Update the baseline file with this run's result (no alert on deviation)",
227
+ )
228
+ args = parser.parse_args()
229
+
230
+ if not args.discord_webhook and not args.slack_webhook:
231
+ logger.info("No webhook configured β€” running in dry-run mode (no notification)")
232
+
233
+ # --- Run smoke test ---
234
+ logger.info("Running smoke test alert check…")
235
+ result = _run_smoke_test()
236
+
237
+ if not result["success"]:
238
+ msg = (
239
+ f"🚨 **OpenCodeReview Alert β€” Smoke test FAILED**\n"
240
+ f"Error: {result['error']}\n"
241
+ f"Time: {result['timestamp']}"
242
+ )
243
+ logger.error(msg)
244
+ if args.discord_webhook:
245
+ _send_discord(args.discord_webhook, msg)
246
+ if args.slack_webhook:
247
+ _send_slack(args.slack_webhook, msg)
248
+ sys.exit(1)
249
+
250
+ logger.info(
251
+ "Smoke test OK β€” score=%.1f, findings=%d, verdict=%s, %s",
252
+ result["score"], result["findings_count"],
253
+ result["verdict"], result["cost"],
254
+ )
255
+
256
+ # --- Compare with baseline ---
257
+ baseline = _load_baseline(args.baseline_file)
258
+
259
+ if args.update_baseline or not baseline:
260
+ _save_baseline(args.baseline_file, result)
261
+ logger.info("Baseline set β€” no comparison performed")
262
+ return
263
+
264
+ baseline_score = baseline.get("score", 0.0)
265
+ deviation = abs(result["score"] - baseline_score)
266
+
267
+ if deviation > SCORE_TOLERANCE:
268
+ msg = (
269
+ f"⚠️ **OpenCodeReview Alert β€” Score deviation detected**\n"
270
+ f"Current score: {result['score']:.1f}/10 (baseline: {baseline_score:.1f}/10)\n"
271
+ f"Deviation: {deviation:.1f} points (tolerance: {SCORE_TOLERANCE})\n"
272
+ f"Verdict: {result['verdict']}\n"
273
+ f"Findings: {result['findings_count']}\n"
274
+ f"Cost: {result['cost']}\n"
275
+ f"Time: {result['timestamp']}"
276
+ )
277
+ logger.warning(msg)
278
+ if args.discord_webhook:
279
+ _send_discord(args.discord_webhook, msg)
280
+ if args.slack_webhook:
281
+ _send_slack(args.slack_webhook, msg)
282
+ else:
283
+ logger.info(
284
+ "Score within tolerance (deviation=%.1f) β€” no alert needed",
285
+ deviation,
286
+ )
287
+
288
+
289
+ if __name__ == "__main__":
290
+ main()