Code Review Graph

repository·main·Indexed 12 days ago

https://github.com/tirth8205/code-review-graph

A local-first knowledge graph for token-efficient code review using Tree-sitter and the Model Context Protocol (MCP). It builds a structural map of codebases to provide AI assistants with precise context, reducing token consumption. Features include blast-radius analysis, semantic search via vector embeddings, a VS Code extension, and a GitHub Action for risk-scored PR reviews. Supports a wide range of languages including Python, JavaScript, TypeScript, Go, Rust, and Java.

Tokens
79.4K
Snippets
221
Records
334
Agent score
98%

What's inside Code Review Graph

  1. Overview of code-review-graph features

    main

    The code-review-graph project provides a comprehensive suite of tools for analyzing codebases through graph-based representations. Key capabilities include:

    • Incremental Updates: Re-analyzes only changed files, completing updates in under 2 seconds.
    • Blast-radius Analysis: Identifies functions, classes, and files potentially affected by changes.
    • Semantic Search: Supports vector embeddings via sentence-transformers, Google Gemini, MiniMax, or OpenAI-compatible endpoints (including Azure, LiteLLM, vLLM, LocalAI).
    • Graph Analysis & Visualization: Uses D3.js for interactive layouts, detects architectural bottlenecks (Hubs/Bridges), and identifies unexpected couplings (Surprise Scoring).
    • Automated Review Support: Generates review questions based on graph analysis and provides risk-scored reviews via detect_changes mapping.
    • Community Detection: Uses the Leiden algorithm to cluster related code into communities.
    • Export Formats: Supports GraphML (for Gephi/yEd), Neo4j Cypher, Obsidian vaults (with wikilinks), and static SVG graphs.
    • Search Capabilities: Hybrid search combining keyword (FTS5) and vector similarity.
    • Local-first Storage: Uses a SQLite file within .code-review-graph/ for core graph storage, requiring no external database or cloud services.
  2. Review project features and capabilities

    main

    The code-review-graph provides a wide array of features for code analysis and review:

    • Analysis Tools: Blast-radius analysis, hub & bridge detection (centrality), surprise scoring (unexpected coupling), and knowledge gap analysis.
    • Search & Traversal: Semantic search (vector embeddings), full-text search (FTS5), and free-form BFS/DFS graph traversal.
    • Automation: Incremental updates (re-parsing only changed files), auto-update hooks, and a GitHub Action for risk-scored PR reviews.
    • Visualization & Export: D3.js interactive graphs, GraphML, Neo4j Cypher, Obsidian vaults, and SVG exports.
    • Developer Workflow: Watch mode, MCP prompts (review, architecture, debug, onboard, pre-merge), and refactoring tools (rename preview, dead code detection).
    • Infrastructure: Local SQLite storage in .code-review-graph/ and a crg-daemon for managing multiple repositories.
  3. Explore code-review-graph features

    main

    The code-review-graph project provides a comprehensive suite of tools for analyzing codebases through graph-based representations. Key capabilities include:

    • Incremental Updates: Re-parses only changed files, allowing updates in under 2 seconds.
    • Blast-radius Analysis: Identifies which functions, classes, and files are affected by a specific change.
    • Semantic Search: Supports vector embeddings via sentence-transformers, Google Gemini, MiniMax, or any OpenAI-compatible endpoint (e.g., Azure, LiteLLM, vLLM, LocalAI).
    • Graph Analysis: Includes Hub and Bridge detection (using betweenness centrality), Surprise Scoring (detecting unexpected coupling), and Knowledge Gap analysis.
    • Visualization & Export: Interactive D3.js force-directed graphs with search and community toggles. Supports exporting to GraphML (Gephi/yEd), Neo4j Cypher, Obsidian vaults (with wikilinks), and static SVG.
    • Automated Workflows: Auto-update hooks for file edits and git commits, and risk-scored PR reviews via GitHub Actions.
    • Advanced Graph Logic: Community detection using the Leiden algorithm, graph diffing (comparing snapshots), and configurable BFS/DFS traversal.
    • Developer Tools: Refactoring tools (rename preview, dead code detection), automated wiki generation, and MCP (Model Context Protocol) prompts for workflows like review, architecture, debug, onboard, and pre-merge.
  4. How code-review-graph differs from LSP and Language Servers

    main

    While Language Servers (LSP) provide compiler-backed, semantically precise results for editing (like exact go-to-definition and safe renames), code-review-graph (CRG) is optimized for structural code review and cross-language analysis.

    Key differences:

    • Persistence: Unlike LSPs that often rebuild state per session, CRG uses a persistent SQLite database (.code-review-graph/graph.db) that updates incrementally (e.g., ~2.5s for a 3,000-file repo).
    • Scope: CRG provides a single graph across ~35 languages, enabling cross-language edge detection that individual LSPs cannot model.
    • Review-Oriented Edges: CRG models relationships specifically for review, such as tests_for, execution flows, and risk-scored change analysis.
    • Precision Trade-off: CRG uses AST-level heuristics rather than a full compiler frontend. Consequently, edges carry a confidence tier: EXTRACTED, INFERRED, or AMBIGUOUS to account for dynamic dispatch or metaprogramming.
  5. Understand the Knowledge Graph Edge Types

    main

    Edges define the relationships between nodes in the graph. Common edge kinds include:

    • CALLS: A function calls another function.
    • IMPORTS_FROM: A file imports from another module/file.
    • INHERITS: A class extends another class.
    • IMPLEMENTS: A class implements an interface.
    • CONTAINS: Structural containment (e.g., File $\rightarrow$ Class, Class $\rightarrow$ Method).
    • TESTED_BY: A function is covered by a test function.
    • DEPENDS_ON_CONFIG: A binding from code to an external configuration key.
    • HANDLES: A relationship between a dispatch point (like an Endpoint) and the method that services it.
    • TRIGGERS: A link between a Scheduler node and the method it executes.
    • INJECTS: A dependency-injection relationship (e.g., Spring injected fields).
    • REFERENCES: A value-level reference (e.g., passing a function as a callback).
    • CONSUMES / PRODUCES: Data or event flow relationships.
  6. Blast-radius analysis

    main
    When a file is modified, the graph traces every caller, dependent, and test that could be affected. This set of affected entities is called the "blast radius." Instead of scanning the entire project, your AI assistant only reads the files within this blast radius, ensuring high precision and low token consumption.
  7. Supported languages and custom language support

    main

    The project uses tree-sitter via tree-sitter-language-pack to support a wide range of languages including Python, JS/TS, Go, Rust, Java, C/C++, C#, Ruby, Swift, SQL, Terraform, and more (see full list in docs).

    Adding Custom Languages: You can add support for new languages without forking the repository by creating a .code-review-graph/languages.toml file. This file defines file extensions and node types per grammar. Note that built-in languages cannot be overridden.

  8. Determine if code-review-graph is suitable for your codebase

    main

    The decision to use code-review-graph depends on both the size of your codebase and the frequency of multi-file queries.

    Codebase Size Guidelines

    • Below a few hundred files: Marginal benefit. While the graph builds quickly, LLM agents can often hold these repos in context, and the structural overhead might cost more tokens than it saves.
    • A few hundred to a few thousand files: High benefit. Benchmarks show 36x–376x reductions in token usage for whole-corpus agent questions compared to raw context.
    • Multi-thousand-file repos and monorepos: Strongest case. These repos exceed agent context limits (e.g., FastAPI is ~950k tokens), and code-review-graph's incremental updates keep the graph fresh in seconds.

    Query Frequency

    Even a smaller repository (e.g., 300 files) provides significant value if you frequently ask multi-file questions during daily reviews.

  9. Understand Julia canonical identities and scoping

    main

    The Julia parser uses a joined lexical scope model for NodeInfo.parent_name to ensure collision-free identities. Instead of replacing parent names, scopes are appended to create a unique qualified name.

    Identity Examples:

    • A function f in Outer.Inner has the qualified name file.jl::Outer.Inner.f.
    • A nested function g inside f has the qualified name file.jl::Outer.Inner.f.g.
    • A function Base.show defined inside Outer.Inner has the qualified name file.jl::Outer.Inner.Base.show.

    Note for Consumers: The explicit qualifier is still preserved in extra["julia_module_qualifier"] if you need the raw string, but you should use the qualified name for graph queries to avoid collisions between local and global symbols.

  10. Understand the four token benchmarks

    main

    The project provides four distinct benchmarks to measure token costs under different scenarios. Choose the one that matches your use case:

    BenchmarkNaive baselineGraph costQuestion answered
    code_review_graph/eval/benchmarks/token_efficiency.pysum of changed-file content for a specific commitfull get_review_context() JSON"Is the graph cheaper than just reading the diffed files?"
    code_review_graph/eval/benchmarks/agent_baseline.pygrep top-3 files for the question's identifiers5 search hits + 5 neighbor edges per question"Is the graph cheaper than a realistic grep-and-read agent?"
    code_review_graph/eval/token_benchmark.pynone — absolute per-workflow costsum of 5 MCP-tool responses"How many tokens does a complete agent workflow cost?"
    code_review_graph/token_benchmark.py (standalone)sum of all source files in repo5 search hits + 5 neighbor edges per question"Is the graph cheaper than reading the whole repo?"

    Key Notes:

    • token_efficiency.py can result in ratios less than 1.0× for small commits because get_review_context includes metadata and snippets that may exceed the size of a tiny diff.
    • The standalone benchmark always produces large ratios because it compares against the entire repository.
  11. How Julia scope and qualified identities are resolved

    main

    The Julia parser uses a hierarchical scope resolution model to handle qualified names (e.g., Base.show) and nested structures.

    Identity Resolution

    Identities are constructed by joining the lexical parent with the qualifier:

    1. lexical_parent = _julia_scope_join(enclosing_class, enclosing_func)
    2. identity_parent = _julia_scope_join(lexical_parent, qualifier)

    If no qualifier is present, the identity_parent defaults to the lexical_parent.

    Call Target Resolution

    When resolving calls in Julia, the parser follows a specific search order for a target f from a source Outer.Inner.caller:

    1. Outer.Inner.caller.f
    2. Outer.Inner.f
    3. Outer.f
    4. f (global/bare)

    For dotted calls, the parser replaces field-expression callees with their complete qualifier.leaf text and populates the julia_call_module field in the edge metadata.

  12. How code-review-graph works

    main

    The tool optimizes AI code reviews by reducing token consumption. Instead of feeding the entire codebase to an AI, it provides a targeted context.

    Core Workflow

    1. Parsing: Uses Tree-sitter to parse the repository into an Abstract Syntax Tree (AST).
    2. Graph Construction: Stores nodes (functions, classes, imports) and edges (calls, inheritance, test coverage) in a SQLite database.
    3. Context Retrieval: When a review is requested, the tool queries the graph to calculate the minimum set of files the AI needs to read.
    4. MCP Integration: Provides this precise context to AI assistants via the Model Context Protocol (MCP).

    Key Concepts

    • Blast-radius Analysis: When a file changes, the graph tracks all affected callers, dependencies, and tests. The AI only reads these specific files rather than scanning the whole project.
    • Incremental Updates: The tool supports watch modes or hooks to update the graph in seconds. It uses SHA-256 hashes to identify which files actually changed and only re-parses those, following dependency edges to update relevant parts of the graph.