DEV Community

Cover image for Open Source Project #126: code-review-graph — Build a Structural Map of Your Codebase to Cut AI Review Tokens by 82x
WonderLab
WonderLab

Posted on

Open Source Project #126: code-review-graph — Build a Structural Map of Your Codebase to Cut AI Review Tokens by 82x

Introduction

"Stop burning tokens. Start reviewing smarter."

This is article #126 in the "One Open Source Project a Day" series. Today's project is code-review-graph — a local-first tool that builds a persistent structural map of your codebase and delivers precise context to AI coding tools via MCP.

AI coding agents have a hidden inefficiency during code reviews: they don't know "if I change this function, what else breaks?" — so they either read large portions of the codebase to build context, or rely on grep and hope for the best. code-review-graph's solution: pre-build a structural graph (functions, classes, call edges, inheritance, test coverage), then at review time query the graph to compute the "blast radius" of a change, and give the AI only the files that actually matter.

Benchmark: ~82x median token reduction. 528x best case.

19,762 Stars. Created February 2026. Supports 14 AI coding platforms.

What You'll Learn

  • How blast-radius analysis works: tracing from changed files to callers, dependents, and tests
  • The full architecture: Tree-sitter AST → SQLite graph → MCP tool chain
  • The incremental update mechanism: why a 2,900-file repo re-indexes in under 2 seconds
  • Three-tier edge confidence scoring (EXTRACTED/INFERRED/AMBIGUOUS) and what it means
  • An honest reading of the benchmark numbers: 528x is the best case, not the median

Prerequisites

  • Basic experience with Claude Code or other AI coding tools
  • Familiarity with MCP (Model Context Protocol)
  • Basic understanding of static analysis and call graphs

Project Background

Overview

code-review-graph (CRG) is a local-first code intelligence tool with four core functions:

  1. Parse your codebase with Tree-sitter into a graph of functions, classes, imports, and call relationships
  2. Persist the graph as a SQLite file in .code-review-graph/ — zero network dependencies
  3. Expose 30 MCP tools so your AI assistant can query "what does this change affect?"
  4. Support incremental updates — on a change, re-parse only the modified files

Author / Team

  • Author: tirth8205
  • Language: Python 3.10+
  • License: MIT
  • Version: v2.3.6
  • Website: code-review-graph.com

Project Stats

  • ⭐ GitHub Stars: 19,762+
  • 🍴 Forks: 2,107+
  • 📄 License: MIT
  • 📅 Created: February 26, 2026

Features

Quick Start

pip install code-review-graph        # or: pipx install code-review-graph
code-review-graph install            # auto-detects platforms, writes MCP configs
code-review-graph build              # parse codebase, build graph
Enter fullscreen mode Exit fullscreen mode

Three commands. install detects every AI coding tool on your machine, writes the correct MCP configuration for each, injects graph-aware instructions into your platform rules files, and installs platform-native hooks/skills. Restart your editor, then ask the AI:

Build the code review graph for this project
Enter fullscreen mode Exit fullscreen mode

Initial build: ~10 seconds for a 500-file project. After that, incremental.

Platform Support

One install, 14 platforms: Codex, Claude Code, CodeBuddy Code, Cursor, Windsurf, Zed, Continue, OpenCode, Antigravity, Gemini CLI, Qwen, Qoder, Kiro, GitHub Copilot.

Target-specific installs:

code-review-graph install --platform claude-code
code-review-graph install --platform cursor
code-review-graph install --platform codex
Enter fullscreen mode Exit fullscreen mode

Token Savings Panel

┌─────────────────────── Token Savings ────────────────────────┐
│ Full context would be:     12,921 tokens                     │
│ Graph context used:           762 tokens                     │
│ Saved:                     12,159 tokens (~94%)              │
│ Breakdown: Functions 244 · Tests 191 · Risk 244 · Other 83   │
└──────────────────────────────────────────────────────────────┘
Enter fullscreen mode Exit fullscreen mode

Printed by detect-changes --brief or update --brief. Add --verify to cross-check against OpenAI's cl100k_base tokenizer; the estimate stays within ~1% of real tokens in practice.


Deep Dive

Core Architecture

Repository
    │
    ▼ git ls-files (only tracked files indexed)
Tree-sitter parsers
    │ extracts: functions / classes / imports / calls / inheritance / test coverage
    ▼
SQLite graph database
(.code-review-graph/, git-ignored by default)
    │
    ├── MCP server (30 tools)
    │       ↓ AI assistant queries
    │   get_impact_radius_tool
    │   get_review_context_tool
    │   detect_changes_tool
    │   ...
    │
    └── CLI
        detect-changes --brief
        update --brief
        visualize
        ...
Enter fullscreen mode Exit fullscreen mode

Graph nodes: functions, classes, files, modules
Graph edges: call relationships, import relationships, inheritance, test coverage

Blast-Radius Analysis

The core concept. When a file changes:

Changed file (e.g. login() in auth/login.py)
    ↓
Query graph: which functions directly call login()?
    ↓
Query graph: which functions call those callers?
            (configurable depth; default depth=2)
    ↓
Query graph: which test files cover these functions?
    ↓
Output: blast radius = minimal set of functions/files affected
Enter fullscreen mode Exit fullscreen mode

The AI reads only this minimal set instead of scanning the whole codebase.

Accuracy note (from the README, unusually candid):

  • The current recall=1.0 is a graph-derived upper bound — the ground truth comes from the same graph edges the predictor walks, so the measurement is circular by construction
  • "Co-change mode" grades against files the author actually co-edited in the same commit — independent evidence from git history, not the graph — and will produce substantially lower numbers
  • Blast-radius analysis is deliberately conservative: it's better to flag extra files than to miss a broken dependency

Incremental Updates: < 2 Seconds

File saved (hook fires / watch mode / crg-daemon)
    │
    ▼
SHA-256 hash check: which files actually changed?
    │
    ▼
Re-parse only changed files
    │
    ▼
Find dependents of changed files, mark edges for refresh
    │
    ▼
Graph updated

Benchmark: 2,900-file repo → < 2 seconds
           500-file repo, initial build → ~10 seconds
Enter fullscreen mode Exit fullscreen mode

Three-Tier Edge Confidence

Graph edges carry confidence levels:

Level Meaning
EXTRACTED Explicit call parsed directly from the AST — high confidence
INFERRED Relationship derived via type inference or semantic analysis — medium confidence
AMBIGUOUS Dynamic dispatch, polymorphism, or cases that can't be statically resolved — low confidence

This lets the AI filter by confidence when querying — avoiding false alerts from low-quality edges in dynamically-typed code.

30 MCP Tools

Organized by purpose:

Context retrieval (code review core)

  • get_minimal_context_tool — ultra-compact context, ~100 tokens, call this first
  • get_impact_radius_tool — blast radius of changed files
  • get_review_context_tool — token-optimized review context with structural summary
  • detect_changes_tool — risk-scored change impact analysis

Graph queries

  • query_graph_tool — query callers, callees, tests, imports, inheritance
  • traverse_graph_tool — free-form BFS/DFS from any node with token budget
  • semantic_search_nodes_tool — search code entities by name or meaning (requires optional embeddings)

Architecture analysis

  • get_architecture_overview_tool — auto-generated architecture map from community structure
  • get_hub_nodes_tool — most-connected nodes (architectural hotspots)
  • get_bridge_nodes_tool — chokepoints via betweenness centrality
  • get_surprising_connections_tool — unexpected cross-community coupling
  • get_knowledge_gaps_tool — isolated nodes, untested hotspots, structural weaknesses

Other

  • refactor_tool — rename preview, dead code detection
  • generate_wiki_tool — Markdown wiki from community structure
  • cross_repo_search_tool — search across all registered repos

In token-constrained environments, expose only what you need:

code-review-graph serve --tools query_graph_tool,detect_changes_tool,get_review_context_tool
Enter fullscreen mode Exit fullscreen mode

Language Coverage

40+ languages and formats: Python, JavaScript/TypeScript/TSX, Go, Rust, Java, C/C++, C#, Ruby, Kotlin, Swift, PHP, Scala, Solidity, Dart, R, Elixir, Zig, Vue/Svelte SFCs, Jupyter/Databricks notebooks (.ipynb), Terraform, Ansible, and more.

For unsupported languages, drop a languages.toml in .code-review-graph/ — no fork or code changes:

[languages.erlang]
extensions = [".erl"]
grammar = "erlang"
function_node_types = ["function_clause"]
class_node_types = ["record_decl"]
import_node_types = ["import_attribute"]
call_node_types = ["call"]
Enter fullscreen mode Exit fullscreen mode

CI Integration: GitHub Action

on:
  pull_request:

permissions:
  contents: read
  pull-requests: write

jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: tirth8205/code-review-graph@v2.3.6
        with:
          github-token: ${{ secrets.GITHUB_TOKEN }}
Enter fullscreen mode Exit fullscreen mode

Graph built and queried entirely on the CI runner. No source code sent to any external service. Posts a sticky risk-scored comment on each PR, updated in place on every push. Optional fail-on-risk input turns the review into a merge gate.

Multi-Repo Daemon

crg-daemon add ~/project-a --alias proj-a
crg-daemon add ~/project-b
crg-daemon start
crg-daemon status
crg-daemon stop
Enter fullscreen mode Exit fullscreen mode

For editors that don't support hooks (Cursor, OpenCode, etc.). Watches multiple repos in the background, health-checks every 30 seconds, auto-restarts dead watchers. Config persists in ~/.code-review-graph/watch.toml.

Benchmark Numbers — An Honest Reading

The README handles the benchmark numbers with unusual candor:

Repo Corpus tokens Graph tokens Reduction
fastapi 951,071 2,169 528x
code-review-graph 208,821 2,495 93x
gin 166,868 1,990 92x
flask 125,022 1,986 71x
express 135,955 3,465 41x
httpx 89,492 2,438 38x
Median ~82x

528x is the best case (fastapi, the largest corpus). The median is 82x.

The whole-corpus baseline is an upper bound no real agent pays: a competent agent would grep for identifiers and read only the best-matching files. The agent_baseline benchmark measures this more realistic baseline — pure-python grep, top-3 files by match count — and that comparison is the honest one.

For small single-file changes, graph context can exceed naive file reads (the structural metadata overhead is larger than the file content). The express results show this. The README calls it out rather than hiding it.

vs. Related Tools

Tool Approach CRG difference
LSP / language servers Per-language, per-symbol precision CRG: one persistent cross-language graph; LSP stays more precise per symbol
RAG / embeddings Similarity chunks CRG: structural edges from AST parsing; embeddings are optional and only assist search
grep / agentic search One-hop lookups CRG wins on multi-hop questions: impact radius, callers-of-callers, tests-for, affected flows

When NOT to use CRG: small repos, trivial single-file diffs, one-off questions. The overhead of maintaining the graph isn't worth it for these cases.


Resources

Official Links


Summary

code-review-graph addresses a problem that gets worse as codebases grow: an AI agent doesn't know that changing A affects B, so it either reads too many files or relies on grep. CRG pre-builds the "what affects what" map so agents can query it directly.

Three engineering decisions worth noting:

Local-first with zero telemetry: the graph lives in SQLite, cloud embeddings are opt-in (off by default), and the GitHub Action runs entirely on your CI runner. Source code stays on your machine.

Honest benchmarks: 528x is labeled "best case," the median 82x is the headline; recall=1.0 is explicitly called out as circular (graph-derived ground truth); small-commit overhead is acknowledged rather than hidden. This level of transparency is genuinely uncommon in developer tooling.

Incremental updates as the primary path: the initial build is a one-time cost. Two-second incremental updates mean hooks and watch mode can keep the graph current as you work, not just when you remember to rebuild.

For medium-to-large codebases (hundreds to thousands of files), frequent code review workflows, or teams that regularly ask "if I change this, what breaks?" — CRG's MCP integration path is currently one of the most direct available. Three commands to onboard, then the agent queries the graph automatically from there.


Explore PrimeSkills — a curated marketplace of AI agents and skills, each validated against real enterprise workflows. No hype, just what actually works.

Visit my personal site for more insights and interesting products.

Top comments (1)

Collapse
 
mads_hansen_27b33ebfee4c9 profile image
Mads Hansen

The freshness boundary is as important as the token reduction. I would include the indexed commit/worktree hash and graph update timestamp in every MCP result, then fail or mark the answer stale when the current diff is newer than the graph. For impact analysis, the key benchmark is recall against independent ground truth, especially dynamic dispatch, generated code, configuration edges, and runtime wiring. Token reduction is valuable only after the tool can quantify what it may have missed; otherwise the smallest context can simply be an incomplete one.