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

Deploy df344f5d

Browse files
Files changed (1) hide show
  1. README.md +97 -540
README.md CHANGED
@@ -1,601 +1,158 @@
1
- ---
2
- title: OpenCodeReview
3
- emoji: 🔍
4
- colorFrom: indigo
5
- colorTo: purple
6
- sdk: docker
7
- app_file: app.py
8
- pinned: false
9
- ---
10
-
11
- <h1 align="center">🔍 OpenCodeReview</h1>
12
 
13
  <p align="center">
14
- <b>AI-powered pull request review with human-in-the-loop approval.</b><br>
15
- Three specialist LLM reviewers (correctness · security · test coverage) analyze every PR,
16
- a vector store grounds them in your codebase's history, and nothing is posted to GitHub
17
- until a human approves it.
18
  </p>
19
 
20
  <p align="center">
21
- <a href="https://huggingface.co/spaces/sdm0/opencodereview"><img src="https://img.shields.io/badge/🤗%20Hugging%20Face-Space-blue" alt="Hugging Face Space"></a>
22
- <a href="#"><img src="https://img.shields.io/badge/Python-3.12%2B-3776AB?logo=python&logoColor=white" alt="Python 3.12+"></a>
23
- <a href="#"><img src="https://img.shields.io/badge/LangGraph-1.x-1C3C3C?logo=langchain" alt="LangGraph"></a>
24
- <a href="#"><img src="https://img.shields.io/badge/LLMs-Gemini%20%7C%20Groq-blueviolet" alt="LLMs"></a>
25
- <a href="#"><img src="https://img.shields.io/badge/License-Unlicensed-lightgrey" alt="License"></a>
26
  </p>
27
 
28
- ---
29
-
30
- ## 📑 Table of Contents
31
-
32
- - [✨ Features](#features)
33
- - [🔄 How It Works](#how-it-works)
34
- - [🏗️ Architecture](#architecture)
35
- - [🧱 Tech Stack](#tech-stack)
36
- - [🚀 Quick Start](#quick-start)
37
- - [💻 CLI Usage](#cli-usage)
38
- - [🖥️ Web UI (Gradio)](#web-ui-gradio)
39
- - [🔐 Authentication](#authentication)
40
- - [⚙️ Configuration](#configuration)
41
- - [🔑 Environment Variables](#environment-variables)
42
- - [🐳 Docker](#docker)
43
- - [📊 Evaluation](#evaluation)
44
- - [🔭 Observability](#observability)
45
- - [🔔 Alerting](#alerting)
46
- - [📁 Project Structure](#project-structure)
47
- - [🧪 Testing](#testing)
48
- - [📜 License](#license)
49
-
50
- ---
51
-
52
- ## ✨ Features
53
-
54
- - **Three parallel specialist reviewers** — correctness, security, and test-coverage reviewers
55
- run concurrently on the same diff, each with its own versioned system prompt.
56
- - **Retrieval-augmented review** — a persistent [ChromaDB](https://www.trychroma.com/) vector
57
- store indexes your repository's source code, past merged-PR discussions, and docs, so
58
- reviewers get relevant context (e.g. *"this function is called from X"*) — not just the diff.
59
- - **Human-in-the-loop approval** — the pipeline **pauses** before posting anything. A human
60
- reviews the verdict and findings, then approves, rejects, or quits.
61
- - **Inline comments** — approved findings are posted as **PR review comments at the exact
62
- file/line position**, with automatic fallback to issue-level comments when a line has gone stale (422).
63
- - **Smart aggregation** — heuristic deduplication (file/line proximity + confidence) plus a
64
- rule-based verdict (with an optional LLM critic pass) that filters noise before humans see it.
65
- - **LLM fallback chain** — Google Gemini (primary, generous free tier) → Groq (fallback),
66
- zero code changes required.
67
- - **Full observability** — LangSmith & Langfuse tracing, per-run token cost & TTFT tracking,
68
- RAGAS retrieval-quality scoring, and a health-check CLI (`doctor`).
69
- - **Evaluation harness** — measure precision/recall/F1 against ground-truth human review
70
- comments, plus RAGAS retrieval metrics.
71
- - **Web UI & CLI** — a polished Gradio interface and a full-featured Click CLI.
72
- - **GitHub OAuth (Device Flow)** — authenticate interactively; tokens stored in your OS keyring.
73
-
74
- ---
75
-
76
- ## 🔄 How It Works
77
 
78
- ```
79
- ┌────────────────────────────────────────────────┐
80
- │ GitHub Pull Request │
81
- └──────────────────────┬───────────────────────┘
82
- ▼
83
- ┌────────────────────────┐
84
- START ���───────────────────▶│ ingestion │ Fetch PR metadata, unified
85
- │ (no-op if diff │ diff, and full file contents
86
- │ already present) │ from the GitHub API
87
- └───────────┬────────────┘
88
- ▼
89
- ┌────────────────────────┐
90
- │ retrieval │ Build/load a ChromaDB vector
91
- │ │ store of the repo's source,
92
- │ │ past merged PRs & docs; query
93
- │ │ it with the diff → context
94
- └───────────┬────────────┘
95
- │
96
- ┌──────────────────────────┼──────────────────────────┐
97
- ▼ ▼ ▼
98
- ┌────────────────────┐ ┌────────────────────┐ ┌────────────────────┐
99
- │ correctness_review │ │ security_review │ │ test_coverage_review│
100
- │ (logic, edge cases,│ │ (injection, auth, │ │ (are the changes │
101
- │ null checks, ...) │ │ secrets, ...) │ │ properly tested?)│
102
- └─────────┬──────────┘ └─────────┬──────────┘ └─────────┬──────────┘
103
- │ │ │
104
- └──────────────────────────┼──────────────────────────┘
105
- ▼
106
- ┌────────────────────────┐
107
- │ aggregator │ Deduplicate findings, filter
108
- │ │ noise, produce final verdict
109
- │ │ (rule-based or LLM critic)
110
- └───────────┬────────────┘
111
- ▼
112
- ┌────────────────────────┐
113
- │ human_approval │ ⏸ PAUSES here — a human
114
- │ (interrupt() pause) │ must approve before posting
115
- └───────────┬────────────┘
116
- ▼
117
- ┌────────────────────────┐
118
- │ executor │ Post inline review comments
119
- │ │ (422 → issue-comment fallback)
120
- └───────────┬────────────┘
121
- ▼
122
- END
123
- ```
124
 
125
- ### Pipeline steps in detail
 
 
 
 
 
126
 
127
- | # | Node | What happens |
128
- |---|------|--------------|
129
- | 1 | **ingestion** | Fetches PR metadata, the full unified diff, and per-file content (handles fork PRs, pagination, rate limits). Uses the head commit SHA. |
130
- | 2 | **retrieval** | Builds (once per base-branch SHA, cached) a ChromaDB collection embedding the repo's source files, up to 20 past merged PRs, and docs (README, CONTRIBUTING…). Queries it with the diff, returns the top 15 context chunks. |
131
- | 3 | **correctness_review** | LLM scans for logic errors, off-by-one bugs, missing null checks, resource leaks, concurrency hazards. |
132
- | 4 | **security_review** | LLM scans for injection, secrets, unsafe deserialization, auth flaws, crypto misuse, information disclosure. |
133
- | 5 | **test_coverage_review** | LLM checks whether the changed logic has adequate test coverage. |
134
- | 6 | **aggregator** | Merges findings that point at the same file/line (±5 lines), keeps the highest-confidence one, drops noise below `0.25` confidence, then produces a verdict — either rule-based (default, ~10 ms, zero LLM cost) or via an optional LLM critic (`AGGREGATOR_USE_LLM_CRITIC=true`). |
135
- | 7 | **human_approval** | Calls LangGraph's `interrupt()` — the graph **pauses** and returns the verdict + findings to the caller. Nothing is posted until the human resumes with `approve` / `reject`. |
136
- | 8 | **executor** | Posts each finding as an **inline PR review comment** (right side of the diff, multi-line ranges supported). If GitHub returns `422` (stale line), falls back to a general issue comment. Finally posts the overall verdict as a summary comment. |
137
 
138
- ### Verdict logic (rule-based default)
139
 
140
- | Condition | Recommendation | Approved |
141
- |---|---|---|
142
- | ≥ 1 critical finding | `block` | ❌ |
143
- | ≥ 1 high finding | `request_changes` | ❌ |
144
- | any medium/low/info finding | `comment` | ✅ |
145
- | no findings | `approve` | ✅ |
146
 
147
- Score: `10 − 4·critical − 2·high − 0.5·medium` (clamped to 0–10).
148
-
149
- ---
 
 
 
 
 
 
 
 
 
 
 
150
 
151
- ## 🏗️ Architecture
152
 
153
- The system is a **LangGraph state machine** with a typed Pydantic state schema and SQLite
154
- checkpointing (needed for the interrupt/resume round-trip):
155
 
156
- - **`OpenCodeReviewState`** carries PR metadata (`repo`, `pr_number`, `base_sha`, `diff`,
157
- `changed_files`), retrieved context (`context_chunks`, accumulated via an `add` reducer),
158
- findings (`findings` → `final_findings`), the `verdict`, and the `human_approved` flag.
159
- - **Parallelism** — retrieval fans out to the three reviewers in parallel; LangGraph merges
160
- their accumulated findings at the aggregator.
161
- - **Checkpointing** — every run is persisted to SQLite (`SqliteSaver`), so a paused graph can
162
- be resumed after a page reload or a process restart via the same thread ID.
163
 
164
- ### Tech stack
165
 
166
- | Layer | Technology |
167
- |---|---|
168
- | Orchestration | [LangGraph](https://www.langchain.com/langgraph) (StateGraph + `interrupt()`) |
169
- | LLMs | Google Gemini `gemini-3.1-flash-lite` (primary) → Groq `llama-3.3-70b-versatile` (fallback) |
170
- | Structured output | Pydantic v2 schemas via `with_structured_output` |
171
- | Vector store | ChromaDB (PersistentClient) + ONNX MiniLM-L6-v2 embeddings |
172
- | GitHub integration | `requests`-based client with token resolution, 401 resilience, 15-min HTTP cache |
173
- | Web UI | Gradio (dark/light theme, live pipeline status) |
174
- | CLI | Click (with `OCR_` env-var prefix support) |
175
- | Tracing | LangSmith (auto) + Langfuse (explicit callback) |
176
- | Quality | RAGAS retrieval metrics + ground-truth eval harness |
177
- | Auth | GitHub OAuth Device Flow, tokens stored in OS keyring |
178
- | Deployment | Docker (multi-stage), Docker Compose, Hugging Face Spaces, GitHub Actions |
179
 
180
- ---
181
 
182
- ## 🚀 Quick Start
183
 
184
- ### Prerequisites
185
 
186
- - Python **3.12+**
187
- - A **GitHub token** (`GITHUB_TOKEN` or `opencodereview auth login`) — required to fetch PRs and post comments
188
- - **One LLM key**: `GEMINI_API_KEY` (preferred) or `GROQ_API_KEY` (fallback)
189
 
190
- ### Installation
191
 
192
- ```bash
193
- # 1. Clone & enter
194
  git clone https://github.com/sdm0p/opencodereview.git
195
  cd opencodereview
196
 
197
- # 2. (Recommended) Create a virtual environment
198
  python -m venv .venv
199
- source .venv/bin/activate # Windows: .venv\Scripts\activate
 
200
 
201
- # 3. Install dependencies
202
- pip install -r requirements.txt
203
-
204
- # 4. Set your API keys
205
- export GITHUB_TOKEN="ghp_..."
206
- export GEMINI_API_KEY="AIza..." # primary LLM
207
- # export GROQ_API_KEY="gsk_..." # fallback LLM
208
- ```
209
-
210
- ### Run your first review (smoke test)
211
-
212
- ```bash
213
- # Runs the full pipeline on a synthetic demo PR — no API keys or network needed
214
  python main.py review --smoke
215
  ```
216
 
217
- ### Review a real PR
218
-
219
- ```bash
220
- python main.py review --repo psf/requests --pr 42
221
- ```
222
-
223
- The pipeline fetches the PR, reviews it, and **pauses** for your decision:
224
 
225
- ```text
226
- HUMAN-IN-THE-LOOP: Approve this review for posting?
227
- [a] Approve — post findings as GitHub comments
228
- [r] Reject — discard results, post nothing
229
- [q] Quit — leave graph paused
230
- ```
231
-
232
- ---
233
 
234
- ## 💻 CLI Usage
235
 
 
 
 
 
236
  ```
237
- python main.py [COMMAND] [SUBCOMMAND] [OPTIONS]
238
- ```
239
-
240
- `review` and `doctor` are standalone commands; `auth` and `config` have their own subcommands
241
- (e.g. `python main.py auth login`, `python main.py config show`).
242
 
243
- Every option also works as an environment variable with the `OCR_` prefix
244
- (e.g. `--repo` → `OCR_REPO`, `--pr` → `OCR_PR_NUMBER`).
245
 
246
- ### `review` — run the review pipeline
247
 
248
- | Option | Default | Description |
249
- |---|---|---|
250
- | `--repo OWNER/REPO` | `demo-org/demo-repo` | GitHub repository to review |
251
- | `--pr N` | `1` | Pull request number |
252
- | `--smoke` | — | Non-interactive smoke test on synthetic data (skips the HITL prompt) |
253
 
254
- > **Note:** with the default repo/PR the CLI uses the built-in synthetic payload so you can
255
- > try the tool instantly. Pass real `--repo`/`--pr` values to review an actual PR.
256
-
257
- ```bash
258
- python main.py review --smoke # offline pipeline check
259
- python main.py review --repo psf/requests --pr 42 # review a real PR
260
- python main.py review --repo private/org --pr 7 # private repos need a token
261
  ```
262
 
263
- ### `doctor` — health checks
264
 
265
- ```bash
266
- python main.py doctor
 
 
 
267
  ```
268
 
269
- Checks Python version, API keys, observability backends, and live connectivity to
270
- Groq / Langfuse.
271
 
272
- ### `auth` — GitHub authentication
273
 
274
- ```bash
275
- python main.py auth login # OAuth Device Flow (prints a code to enter on GitHub)
276
- python main.py auth status # show the authenticated user
277
- python main.py auth logout # remove the stored token
278
- ```
279
-
280
- ### `config` — secrets & settings management
281
 
282
  ```bash
283
- python main.py config set-key --provider anthropic # store an API key in the keyring
284
- python main.py config show # masked summary of configured keys
285
- python main.py config set-observability \
286
- --langsmith-api-key ls_... \
287
- --langfuse-public-key pk-lf-... \
288
- --langfuse-secret-key sk-lf-...
289
  ```
290
 
291
- ---
292
-
293
- ## 🖥️ Web UI (Gradio)
294
-
295
- A full web interface ships with the project — this is also what runs on
296
- [Hugging Face Spaces](https://huggingface.co/spaces/sdm0/opencodereview).
297
-
298
- ```bash
299
- python app.py # serves at http://localhost:7860
300
- ```
301
-
302
- Features:
303
-
304
- - **Review a PR** tab — enter `owner/repo` + PR number, watch the pipeline run, then
305
- **Approve & Post** or **Reject** the results.
306
- - **Smoke Test** tab — run the pipeline on synthetic demo data (no keys needed).
307
- - Severity-colored findings table, verdict card, RAGAS retrieval-quality bars,
308
- per-run cost summary.
309
- - Dark/light theme toggle (persisted in `localStorage`).
310
- - **Configured Keys & Health** accordion showing which keys are set.
311
-
312
- ---
313
-
314
- ## 🔐 Authentication
315
-
316
- OpenCodeReview needs GitHub credentials to fetch PR data and (on approval) post comments.
317
- Tokens are resolved in this priority order: **OS keyring → `GITHUB_TOKEN` env var**.
318
-
319
- ### Option A — OAuth Device Flow (recommended)
320
-
321
- ```bash
322
- export GITHUB_OAUTH_CLIENT_ID="<your OAuth app client id>"
323
- python main.py auth login
324
- ```
325
-
326
- 1. Register an OAuth app at `https://github.com/settings/developers` and **enable Device Flow**.
327
- 2. Run `auth login` — you'll get a one-time code and a verification URL.
328
- 3. Open the URL, enter the code, authorize. The token is stored securely in your keyring
329
- (scope: `repo`).
330
-
331
- ### Option B — Personal access token
332
-
333
- ```bash
334
- export GITHUB_TOKEN="ghp_..."
335
- ```
336
-
337
- > 💡 The client automatically detects invalid/revoked tokens (HTTP 401) and raises a
338
- > helpful error telling you to re-authenticate.
339
-
340
- ---
341
-
342
- ## ⚙️ Configuration
343
-
344
- Configuration is resolved with the priority **environment variable → system keyring → error**:
345
-
346
- - Provider API keys (e.g. Anthropic via `config set-key`) follow
347
- `OPENCODEREVIEW_<FIELD>` env naming.
348
- - GitHub token and observability keys can be stored in the keyring via
349
- `auth login` / `config set-observability`; env vars always take precedence.
350
- - The HTTP cache (`requests-cache`, 15-min TTL) and the ChromaDB vector store live under
351
- `.opencodereview/` in the working directory unless overridden (see env vars below).
352
-
353
- ---
354
-
355
- ## 🔑 Environment Variables
356
-
357
- | Variable | Required | Description |
358
- |---|---|---|
359
- | `GEMINI_API_KEY` | Primary LLM | Google Gemini key — used for all reviewer nodes |
360
- | `GROQ_API_KEY` | Fallback LLM | Groq key — used when Gemini is unavailable |
361
- | `GITHUB_TOKEN` | Yes¹ | GitHub token for fetching PRs & posting comments |
362
- | `GITHUB_OAUTH_CLIENT_ID` | For `auth login` | GitHub OAuth App client ID (Device Flow) |
363
- | `LANGSMITH_API_KEY` | No | LangSmith tracing (legacy alias: `LANGCHAIN_API_KEY`) |
364
- | `LANGSMITH_PROJECT` | No | LangSmith project name (default `opencodereview`) |
365
- | `LANGFUSE_PUBLIC_KEY` | No | Langfuse public key |
366
- | `LANGFUSE_SECRET_KEY` | No | Langfuse secret key |
367
- | `LANGFUSE_HOST` | No | Langfuse host (default `https://cloud.langfuse.com`) |
368
- | `OPENCODEREVIEW_CACHE_DIR` | No | HTTP cache directory (default `.opencodereview/`) |
369
- | `OPENCODEREVIEW_VECTOR_DIR` | No | ChromaDB vector-store directory (default `.opencodereview/vectors`) |
370
- | `AGGREGATOR_USE_LLM_CRITIC` | No | `true` to enable the optional LLM aggregator pass (default: rule-based) |
371
- | `PORT` | No | Gradio server port (default `7860`) |
372
- | `DISCORD_WEBHOOK` / `SLACK_WEBHOOK` | For alerting | Alerting webhooks (see [Alerting](#alerting)) |
373
-
374
- ¹ No token is required when reviewing the built-in demo payload — a token is only strictly
375
- required to review real PRs.
376
-
377
- ---
378
-
379
- ## 🐳 Docker
380
-
381
- ### Build & run
382
-
383
- ```bash
384
- # Build
385
- docker build -t opencodereview .
386
-
387
- # Smoke test
388
- docker run --rm opencodereview python -m main review --smoke
389
-
390
- # Review a real PR
391
- docker run --rm \
392
- -e GROQ_API_KEY=gsk_... \
393
- -e GITHUB_TOKEN=ghp_... \
394
- opencodereview python -m main review --repo org/repo --pr 42
395
-
396
- # Web UI
397
- docker run --rm -p 7860:7860 \
398
- -e GROQ_API_KEY=gsk_... \
399
- -e GITHUB_TOKEN=ghp_... \
400
- opencodereview
401
- ```
402
 
403
- ### Docker Compose
404
 
405
- ```bash
406
- # 1. Put your keys in a .env file
407
- # GROQ_API_KEY=gsk_...
408
- # GITHUB_TOKEN=ghp_...
409
-
410
- # 2. Smoke test
411
- docker compose run --rm opencodereview review --smoke
412
-
413
- # 3. Review a real PR
414
- docker compose run --rm opencodereview review --repo org/repo --pr 42
415
-
416
- # 4. Run evaluation
417
- docker compose run --rm opencodereview python eval_data/evaluate.py --max-prs 2
418
- ```
419
-
420
- The vector store is persisted in a named volume (`opencodereview_vectors`) so embeddings are
421
- not rebuilt on every run.
422
-
423
- ### Image variants
424
-
425
- - **`runtime`** (default) — full app; vector-store retrieval uses the lightweight **ONNX**
426
- MiniLM embedder, so no PyTorch is needed.
427
- - **`runtime-full`** — adds `sentence-transformers` (PyTorch, ~800 MB) if you need it:
428
- `docker build --target runtime-full -t opencodereview:full .`
429
-
430
- ### Deployment
431
-
432
- - **Hugging Face Spaces**: push to `main` triggers
433
- `.github/workflows/deploy-hf.yml`, which syncs the repo to
434
- `sdm0/opencodereview` and restarts the Space (Docker SDK, port 7860). Set
435
- `GROQ_API_KEY` / `GITHUB_TOKEN` as Space secrets.
436
-
437
- ---
438
-
439
- ## 📊 Evaluation
440
-
441
- Evaluate the agent against **ground-truth human review comments**.
442
-
443
- ### 1. Build the dataset
444
-
445
- ```bash
446
- python eval_data/fetcher.py # requires GITHUB_TOKEN
447
- ```
448
-
449
- Produces `eval_data/prs.jsonl` — one JSON object per PR with its diff, changed files, and the
450
- human review comments used as ground truth.
451
-
452
- ### 2. Run evaluation
453
-
454
- ```bash
455
- python eval_data/evaluate.py # full run
456
- python eval_data/evaluate.py --max-prs 2 # quick smoke run
457
- python eval_data/evaluate.py --verbose # per-finding match details
458
- python eval_data/evaluate.py --match-keywords # keyword-overlap matching bonus
459
- python eval_data/evaluate.py --ragas # + RAGAS retrieval metrics
460
- python eval_data/evaluate.py --log-to-observability # log scores to LangSmith/Langfuse
461
- ```
462
-
463
- Findings are matched to human comments by **file path + line proximity (±3 lines)** (with an
464
- optional keyword-overlap bonus), then **precision / recall / F1** are computed per PR plus
465
- micro- and macro-averages. Results are written to `eval_data/eval_results.json`.
466
-
467
- > ⚠️ The evaluator refuses to run while `GITHUB_TOKEN` is set (the executor would post to real
468
- > PRs). Unset it, or pass `--force` to acknowledge.
469
-
470
- ### RAGAS retrieval metrics
471
-
472
- `eval_data/ragas_eval.py` scores retrieval & generation quality:
473
-
474
- | Metric | Question it answers |
475
  |---|---|
476
- | `context_precision` | Are the most relevant code chunks ranked first? |
477
- | `context_recall` | Did we find *all* the relevant code? (needs ground truth) |
478
- | `faithfulness` | Does the review stick to the retrieved code? |
479
- | `answer_relevancy` | Does the review address the PR diff? |
480
- | `mmr` | How early does the first useful chunk appear? |
481
-
482
- Standalone CLI: `python eval_data/ragas_eval.py --data eval_data/prs.jsonl`
483
-
484
- ---
485
 
486
- ## 🔭 Observability
487
 
488
- Two optional backends — the app runs fine with neither:
489
 
490
- - **LangSmith** — enabled automatically when `LANGSMITH_API_KEY` (or legacy
491
- `LANGCHAIN_API_KEY`) is set. Full graph traces out of the box.
492
- - **Langfuse** — enabled when `LANGFUSE_PUBLIC_KEY` + `LANGFUSE_SECRET_KEY` are set.
493
- The pipeline creates a trace per review, and logs **scores** linked to that trace:
494
- - `verdict_score`, `findings_count`
495
- - `ragas_context_precision`, `ragas_faithfulness`, `ragas_answer_relevancy`, `ragas_mmr`, …
496
 
497
- Every run also tracks **token cost** (USD, via Groq pricing) and **TTFT**, printed at the end
498
- of each CLI run and shown in the web UI.
499
-
500
- ---
501
-
502
- ## 🔔 Alerting
503
-
504
- `scripts/alert.py` is a continuous health monitor: it runs the smoke-test review, compares the
505
- resulting score against a stored baseline, and pings a **Discord or Slack webhook** when the
506
- score deviates by more than `2.5` points or the run fails.
507
-
508
- ```bash
509
- python scripts/alert.py \
510
- --baseline-file scripts/alert_baseline.json \
511
- --discord-webhook "$DISCORD_WEBHOOK"
512
-
513
- python scripts/alert.py --slack-webhook "$SLACK_WEBHOOK" --update-baseline
514
- ```
515
-
516
- A GitHub Actions workflow (`.github/workflows/alert.yml`) runs this **every 6 hours**
517
- (set `GROQ_API_KEY`, `GITHUB_TOKEN`, and the webhook URLs as repository secrets).
518
-
519
- ---
520
-
521
- ## 📁 Project Structure
522
-
523
- Root modules such as `main.py`, `app.py`, and `combined_server.py` remain as
524
- compatibility shims so existing commands and imports keep working.
525
-
526
- ```
527
- opencodereview/
528
- ├── docs/ # Architecture, runbooks, plans, and interview guide
529
- │ ├── architecture/
530
- │ ├── engineering/
531
- │ ├── evaluation/
532
- │ ├── operations/
533
- │ ├── planning/
534
- │ ├── project-guide/ # DOCX/PDF guide, source diagrams, and build tools
535
- │ ├── runbooks/
536
- │ └── specifications/
537
- ├── backend/ # Python application and workflow package
538
- │ ├── api.py # FastAPI job, approval, and persistence boundary
539
- │ ├── app.py # Gradio UI and review orchestration adapter
540
- │ ├── combined_server.py # Uvicorn app joining FastAPI and Gradio
541
- │ ├── graph.py # LangGraph workflow and checkpointing
542
- │ ├── main.py # Click CLI — review / doctor / auth / config
543
- │ ├── state.py # Typed Pydantic workflow state
544
- │ ├── observability.py # LangSmith/Langfuse, cost and health helpers
545
- │ └── integrations/ # GitHub auth, config, providers, and endpoints
546
- │ ├── auth.py
547
- │ ├── config.py
548
- │ ├── endpoints.py
549
- │ ├── github_client.py
550
- │ └── llm_factory.py
551
- ├── nodes/ # One module per LangGraph step
552
- ├── prompts/ # Versioned reviewer prompts
553
- ├── eval_data/ # Offline and RAGAS evaluation tools/data
554
- ├── tests/ # Unit and integration-style tests
555
- ├── scripts/ # Health alert tooling
556
- ├── frontend/ # React/Vite site deployed on Vercel
557
- ├── supabase/migrations/ # Database schema migrations
558
- ├── Dockerfile, Dockerfile.api # Backend container definitions
559
- ├── docker-compose.yml
560
- ├── docker-entrypoint.sh
561
- ├── requirements.txt
562
- └── .github/workflows/ # Deployment and scheduled health checks
563
- ```
564
-
565
- Supporting documentation is indexed in [`docs/README.md`](docs/README.md).
566
-
567
- The root Python entry points remain as compatibility shims. Existing commands
568
- such as `python main.py`, `python app.py`, and `uvicorn combined_server:app`
569
- continue to work while the implementation lives under `backend/`.
570
-
571
- ---
572
-
573
- ## 🧪 Testing
574
-
575
- The `tests/` directory contains focused checks for scheduling, finding
576
- grounding, ingestion, reviewer runtime, and evaluation behavior. Install
577
- `pytest` in the development environment if it is not already present, then run:
578
-
579
- ```bash
580
- python -m pytest
581
- ```
582
-
583
- Additional application checks include:
584
-
585
- ```bash
586
- # Smoke test: runs the graph on synthetic data and verifies interrupt/resume
587
- python main.py review --smoke
588
-
589
- # Doctor: checks env, keys, and connectivity
590
- python main.py doctor
591
-
592
- # Quick evaluation run on the first 2 PRs
593
- python eval_data/evaluate.py --max-prs 2
594
- ```
595
 
596
- ---
597
 
598
- ## 📜 License
599
 
600
- This project is currently **unlicensed** (all rights reserved) — no license file is
601
- distributed with the repository. Please contact the maintainers before reusing code.
 
1
+ # OpenCodeReview
 
 
 
 
 
 
 
 
 
 
2
 
3
  <p align="center">
4
+ <strong>AI-assisted pull request review, with a person in control of every post.</strong><br />
5
+ Focused reviewers analyze code changes, explain evidence, and wait for approval before comments go to GitHub.
 
 
6
  </p>
7
 
8
  <p align="center">
9
+ <img src="https://img.shields.io/badge/Python-3.12%2B-3776AB?logo=python&logoColor=white" alt="Python 3.12 or newer" />
10
+ <img src="https://img.shields.io/badge/FastAPI-backend-009688?logo=fastapi&logoColor=white" alt="FastAPI backend" />
11
+ <img src="https://img.shields.io/badge/LangGraph-workflows-1C3C3C" alt="LangGraph workflows" />
12
+ <img src="https://img.shields.io/badge/React-Vite-61DAFB?logo=react&logoColor=20232A" alt="React and Vite frontend" />
 
13
  </p>
14
 
15
+ OpenCodeReview is a GitHub pull request reviewer built around a simple rule: **AI proposes; a human decides what gets posted.** A FastAPI service starts a LangGraph review, specialist agents examine the change, and a reviewer can inspect the evidence before approving GitHub comments.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
+ ## What it does
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
 
19
+ - Reviews **correctness, security, and test coverage** with separate specialist steps that can run in parallel.
20
+ - Retrieves relevant context from selected repository files when optional RAG is enabled.
21
+ - Returns structured findings with locations, evidence status, severity, and suggested fixes.
22
+ - Makes incomplete reviewer stages visible; a failed stage is never presented as proof that code is safe.
23
+ - Pauses for human approval before the executor posts findings to GitHub.
24
+ - Includes a React and Vite frontend, a CLI, a FastAPI API, and an optional Gradio interface.
25
 
26
+ ## System architecture
 
 
 
 
 
 
 
 
 
27
 
28
+ ![OpenCodeReview deployment and runtime architecture](docs/project-guide/assets/architecture.png)
29
 
30
+ The review graph is:
 
 
 
 
 
31
 
32
+ ```mermaid
33
+ flowchart LR
34
+ A[Pull request] --> B[Ingestion]
35
+ B --> C[Optional repository retrieval]
36
+ C --> D1[Correctness reviewer]
37
+ C --> D2[Security reviewer]
38
+ C --> D3[Test coverage reviewer]
39
+ D1 --> E[Grounding and aggregation]
40
+ D2 --> E
41
+ D3 --> E
42
+ E --> F{Human approval}
43
+ F -->|Approve| G[Post comments to GitHub]
44
+ F -->|Reject| H[Finish without posting]
45
+ ```
46
 
47
+ The API persists job records in Supabase Postgres when configured and otherwise uses SQLite. LangGraph checkpoints use a separate SQLite saver. The current worker and some session state are process-local, so horizontal scaling needs a durable queue and shared runtime state.
48
 
49
+ ## How a review works
 
50
 
51
+ 1. **Submit a repository and pull request.** The frontend sends the job to FastAPI; GitHub credentials are resolved from the configured environment or OS keyring.
52
+ 2. **Collect evidence.** Ingestion fetches the pull request metadata, diff, changed files, and base revision.
53
+ 3. **Find useful context.** If retrieval is enabled, the system builds or reuses a ChromaDB collection for the repository's base revision. It selects supported source, documentation, and configuration files, skips excluded paths, and retrieves up to 15 relevant chunks. Python is split at top-level classes and functions; other supported text is split around paragraphs with a chunk target of about 1,200 characters.
54
+ 4. **Run focused reviews.** Correctness, security, and test-coverage steps use separate prompts and structured Pydantic outputs, with file and line references when available.
55
+ 5. **Check and combine findings.** Grounding checks compare findings with the changed lines. Aggregation removes overlap and produces a risk summary. These checks reduce unsupported comments but cannot guarantee that a model's claim is correct.
56
+ 6. **Ask a person.** The graph pauses so the reviewer can approve or reject the proposed comments.
57
+ 7. **Post only after approval.** The executor sends approved comments to GitHub and records the result.
58
 
59
+ ## Model and retrieval options
60
 
61
+ The model factory supports the built-in Groq and Google Gemini providers, plus configured custom endpoints such as OpenAI-compatible APIs and Anthropic. An explicitly selected endpoint is used for that run; otherwise the default path prefers Groq when configured and falls back to Gemini. Built-in provider keys are read from environment variables. GitHub access can use a token or the OAuth Device Flow, which stores its token in the OS keyring.
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
+ Retrieval is optional. It uses ChromaDB with local embeddings when enabled; the hosted workflow can continue with the pull request diff when retrieval is disabled or unavailable. The index is selective and revision-aware, rather than a blind copy of every repository file.
64
 
65
+ ## Try it locally
66
 
67
+ ### Requirements
68
 
69
+ - Python 3.12 or newer
70
+ - Node.js and npm, only if you want to run the React frontend
71
+ - For real pull requests: GitHub access and at least one supported model provider key
72
 
73
+ ### Install and run the offline smoke review
74
 
75
+ ```powershell
 
76
  git clone https://github.com/sdm0p/opencodereview.git
77
  cd opencodereview
78
 
 
79
  python -m venv .venv
80
+ .venv\Scripts\Activate.ps1
81
+ python -m pip install -r requirements.txt
82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
  python main.py review --smoke
84
  ```
85
 
86
+ The smoke review uses synthetic input and does not need GitHub or model credentials.
 
 
 
 
 
 
87
 
88
+ ### Review a real pull request
 
 
 
 
 
 
 
89
 
90
+ Copy `.env.example` to `.env`, then set a GitHub token and a supported model key. `.env` is ignored by Git; never commit credentials.
91
 
92
+ ```powershell
93
+ Copy-Item .env.example .env
94
+ # Edit .env, then:
95
+ python main.py review --repo OWNER/REPOSITORY --pr 123
96
  ```
 
 
 
 
 
97
 
98
+ The CLI supports GitHub OAuth Device Flow as well as token-based access. Run `python main.py --help` or `python main.py auth --help` for the current commands.
 
99
 
100
+ ### Run the API and frontend
101
 
102
+ In one terminal from the repository root:
 
 
 
 
103
 
104
+ ```powershell
105
+ uvicorn api:app --reload --port 8000
 
 
 
 
 
106
  ```
107
 
108
+ In another terminal:
109
 
110
+ ```powershell
111
+ cd frontend
112
+ npm ci
113
+ # Set VITE_REVIEW_API_URL=http://localhost:8000 in frontend/.env.local
114
+ npm run dev
115
  ```
116
 
117
+ The root Python modules are small compatibility shims, so existing launch commands continue to work while the implementation lives in `backend/`.
 
118
 
119
+ ## Development and evaluation
120
 
121
+ Run the automated checks with:
 
 
 
 
 
 
122
 
123
  ```bash
124
+ python -m pytest -q
 
 
 
 
 
125
  ```
126
 
127
+ The `eval_data/` tools provide an offline scorer against human review comments and a RAGAS evaluation path for retrieval and generation metrics. These tools are evaluation infrastructure, not a claim of a particular quality score. Results depend on the dataset, provider, and run configuration.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128
 
129
+ ## Project map
130
 
131
+ | Path | Responsibility |
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
  |---|---|
133
+ | `backend/` | FastAPI API, CLI, LangGraph construction, typed state, and observability |
134
+ | `backend/integrations/` | GitHub access, authentication, settings, model clients, and endpoints |
135
+ | `nodes/` | Ingestion, retrieval, specialist reviewers, grounding, approval, and execution |
136
+ | `prompts/` | Versioned reviewer and aggregator prompt templates |
137
+ | `frontend/` | React and Vite user interface, deployed separately from the Python service |
138
+ | `eval_data/`, `tests/` | Offline evaluation data, RAGAS tooling, and automated tests |
139
+ | `docs/` | Architecture, runbooks, engineering notes, specification, and interview guide |
140
+ | `Dockerfile*`, `docker-compose.yml` | Backend container and local orchestration |
141
+ | `.github/workflows/` | Deployment and scheduled alert workflows |
142
 
143
+ Start with the [documentation index](docs/README.md) or read the [architecture overview](docs/architecture/ARCHITECTURE.md). The editable interview guide and PDF are in [`docs/project-guide/`](docs/project-guide/README.md).
144
 
145
+ ## Current boundaries
146
 
147
+ - Model output can be wrong. Evidence checks and human approval are safeguards, not guarantees.
148
+ - The worker queue and some session data are process-local; production multi-replica use needs shared, durable infrastructure.
149
+ - RAG is opt-in and depends on GitHub access, ChromaDB, and embedding availability.
150
+ - The evaluation harness is included, but users should run it on their own representative dataset before making quality claims.
 
 
151
 
152
+ ## About
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
153
 
154
+ OpenCodeReview is a practical AI engineering project for human-reviewed code review. It brings together retrieval, multi-step agent orchestration, structured model output, GitHub integration, and evaluation while keeping the approval boundary visible.
155
 
156
+ ## License
157
 
158
+ No license file is currently included in this repository.