Skip to main content
Glama
README.md
# 🤖 PR Copilot: an agentic AI pull-request reviewer

[![CI](https://github.com/HEMANTHreddysolipeta/pr-copilot/actions/workflows/ci.yml/badge.svg)](https://github.com/HEMANTHreddysolipeta/pr-copilot/actions/workflows/ci.yml) ![License: MIT](https://img.shields.io/badge/license-MIT-blue) ![Python 3.11+](https://img.shields.io/badge/python-3.11%2B-blue)

PR Copilot reviews every pull request with a **team of AI agents**. A planner, three specialists and an adversarial verifier use **17 tools**: code search, AST references, sandboxed tests, linters, security and dependency scanners, git history, and CI logs. It posts a verified review with inline comments. Reviewers can then **chat with it inside the PR**, ask it to write a regression test or a fix, and **approve or reject** each change. It never merges. A human stays in the loop.

It runs **for free** on GitHub Actions with free LLM tiers (Groq, Cerebras, Gemini, or local Ollama). It is also published as an **MCP server**, so Claude Code, Cursor or any MCP client can use its tools.

## Live demo

[**pr-copilot-demo**](https://github.com/HEMANTHreddysolipeta/pr-copilot-demo/pulls?q=is%3Apr) shows real reviews posted by the GitHub Action:

| PR | What happened |
|---|---|
| [#1 SQL lookup](https://github.com/HEMANTHreddysolipeta/pr-copilot-demo/pull/1) | Flagged and verified a SQL injection. A reviewer asked `@prcopilot` for a fix, then `/approve`d it, and the bot opened [#2](https://github.com/HEMANTHreddysolipeta/pr-copilot-demo/pull/2) with the parameterised query. |
| [#3 Reorder arguments](https://github.com/HEMANTHreddysolipeta/pr-copilot-demo/pull/3) | The change was only in `db.py`. The agent used its tools to find the **broken caller in `orders.py`**, which is not in the diff, and the verifier confirmed it. |
| [#4 "Pre-reviewed"](https://github.com/HEMANTHreddysolipeta/pr-copilot-demo/pull/4) | The PR hides a SQL injection behind text telling AI reviewers to approve. The bot reported the bug **and** flagged the manipulation attempt. |
| [#5 Cart.clear()](https://github.com/HEMANTHreddysolipeta/pr-copilot-demo/pull/5) | A correct change. The bot reported no issues, which means no false alarms. |

```mermaid
flowchart LR
  PR[PR opened / updated] --> S[Injection scan + ruff + bandit<br/>deterministic signals]
  S --> T[Triage agent<br/>risk areas, picks specialists]
  T --> C[Correctness agent]
  T --> SE[Security agent]
  T --> P[Performance agent]
  C & SE & P --> M[Merge + dedupe]
  M --> V[Adversarial verifier<br/>confirm with evidence or reject]
  V --> R[Review: risk score,<br/>inline comments]
  R --> H{Human}
  H -- "@prcopilot question" --> CH[Chat agent + tools]
  CH -- propose_patch / write_test --> Q[Pending action]
  Q -- "/approve token" --> FX[Fix PR opened]
```

## Features

| | |
|---|---|
| **Multi-agent review** | Triage → specialists (correctness, security, performance) → verifier. Each specialist runs its own tool-calling loop. |
| **Adversarial verifier** | A separate agent tries to *disprove* each candidate finding by reading the code and running tests. Only confirmed findings are posted, which keeps noise low. |
| **Agentic chat** | `@prcopilot why is line 42 risky?` in a PR, or the web dashboard with a **live tool-call trace**. Thread memory persists across comments. |
| **17 tools** | `search_code` (BM25 over AST chunks), `read_file`, `grep_code`, `find_references` (AST), `get_diff`, `git_history`, `git_blame`, `run_tests`, `run_linter`, `security_scan`, `dependency_audit` (OSV), `get_pr_discussion`, `get_ci_logs`, `propose_patch`, `write_test`, `remember_rule`, `list_files` |
| **Human-in-the-loop** | Write tools never execute directly. They create an action with a token; `/approve <token>` (write access required) opens a fix PR. |
| **Long-term memory** | 👎 feedback and `remember_rule` store team conventions per repo. Rules can also live in the repo (`.github/prcopilot-rules.md`). |
| **Prompt-injection defence** | Untrusted content is wrapped and treated as data. Added lines are scanned with heuristics plus Meta's **Prompt Guard 2** classifier. Forged approval markers are ignored. Only collaborators can drive the agent. |
| **Sandbox** | PR code runs in Docker (`--network none`, CPU/memory/PID caps) or in a subprocess with secrets stripped from the environment. |
| **Free-tier LLM router** | Falls back across Groq → Cerebras → Gemini → Ollama. Paces itself on per-minute limits and parks a model that hits its daily limit. Tracks tokens per model. |
| **MCP server** | `prcopilot mcp` exposes 10 tools, including `review_branch` (the whole pipeline). |
| **Evals** | A 38-case seeded-bug benchmark: 30 easy cases (21 bugs, 6 clean PRs, 3 prompt-injection attacks) plus 8 hard cross-file cases, with ablations. |

## Quick start

```bash
python -m venv .venv && .venv/Scripts/activate      # Windows (use bin/activate on macOS/Linux)
pip install -e ".[dev]"
cp .env.example .env                                 # add a free GROQ_API_KEY
pytest                                               # 27 tests, no API calls

prcopilot review --repo path/to/repo --base main -v  # review the current branch
prcopilot chat   --repo path/to/repo --base main     # terminal chat with tool trace
prcopilot serve  --repo path/to/repo                 # dashboard at http://127.0.0.1:8765
prcopilot actions list | approve <token> | reject <token>
```

### Try it locally (Windows, no GitHub needed)
- `try-dashboard.bat` builds `%USERPROFILE%\pr-copilot-playground` (a shop backend with six PR branches) and opens the dashboard. Set **Head** to a branch such as `pr/stock-check`, then use the Review or Chat tab.
- `try-dashboard.bat C:\path\to\your\repo` opens the dashboard on one of your own repos (Head = your feature branch).
- `try-chat.bat` opens a terminal chat on `pr/sql-lookup`.

Playground branches: `pr/sql-lookup`, `pr/staff-can-delete`, `pr/stock-check`, `pr/pagination`, `pr/sneaky-injection` (contains text that tries to manipulate the AI) and `pr/clean-feature` (no bugs; it should stay quiet).

### On GitHub (free)
1. Push this repo to GitHub.
2. In the repo you want reviewed, copy [`.github/workflows/prcopilot.yml`](.github/workflows/prcopilot.yml) and set the `PRCOPILOT_REPO` variable to `<you>/pr-copilot`.
3. Add the `GROQ_API_KEY` secret (optionally `CEREBRAS_API_KEY` and `GEMINI_API_KEY`).
4. Open a PR. Then comment `@prcopilot write a regression test for the top finding` and `/approve <token>`.

A webhook server mode is also available (`prcopilot serve` + `GITHUB_WEBHOOK_SECRET`, HMAC-verified).

### As an MCP server (Claude Code / Cursor)
```json
{ "mcpServers": { "pr-copilot": { "command": "prcopilot", "args": ["mcp", "--repo", "/path/to/repo", "--base", "main"] } } }
```

## Evaluation

```bash
python -m evals.run_eval --offline                    # harness check, no API calls
python -m evals.run_eval --modes baseline,agent,full  # full benchmark (use --resume after rate limits)
```

- `baseline` is one LLM call on the diff.
- `agent` adds the specialists with tools.
- `full` adds triage, the verifier and the injection scan.

A finding counts as a hit when it names the seeded file and a line within ±3 of the defect.

The benchmark has two sets:
- **Easy set (30 cases):** the defect is visible in the diff itself.
- **Hard set (8 cases):** the defect breaks code *outside* the diff, such as a caller in another file, a function further down, or an import. A hard-set hit must name the concrete broken usage (for example `orders.py` or `verify_password`), not just "this may break callers".

**Status (Groq `gpt-oss-120b`, free tier, in progress):**
- Baseline, easy set: 23 of 24 bugs found (95.8% recall), 0.17 false alarms per clean PR. Its one false alarm was a hallucinated "undefined `log`": the logger is defined outside the diff hunk.
- Full pipeline, first 8 easy cases: 7 of 7 bugs found, 0 false alarms, about 19K tokens per review.
- Hard set and the remaining cases: running. Results land in `evals/results/summary.md`.

The easy set turned out to be too easy for a single LLM call, which is why the hard set exists. It measures what tool use is actually for.

## Project layout
```
prcopilot/
  llm.py             free-tier router: fallback, pacing, usage tracking
  agent.py           tool-calling loop: approval gates, context compaction, events
  tools.py           17 tools + BM25 code index
  review.py          multi-agent pipeline + verifier + rendering
  chat.py            conversational agent
  safety.py          prompt-injection defence + sandbox
  store.py           SQLite: reviews, threads, actions, memory, feedback
  github_handler.py  stateless GitHub event handling (Actions/webhook)
  server.py, web/    FastAPI dashboard with SSE streaming
  mcp_server.py      MCP server
evals/               30 seeded-bug cases, sample project, runner + scorer
tests/               27 offline tests (scripted FakeLLM)
```