Generated banner for code-review-graph
Generated logo for code-review-graph

code-review-graph

Memory server

Created by Tirth

Published in tirth8205/code-review-graph. Publisher page

32,711 GitHub stars

What it is

Local-first code intelligence graph for MCP and CLI. Builds a persistent map of your codebase so AI coding tools read only what matters, with benchmarked context reductions on reviews and large-repo workflows.
— the description by Tirth

AutoGineer overview, from the brain’s own files

code-review-graph is a local-first memory system designed to solve the token-heavy problem of AI code review. By parsing a repository into a structural map of functions, classes, imports, and tests using Tree-sitter, it stores the codebase as a graph in a local SQLite database. When an AI agent needs to review a change, the system calculates the blast radius—identifying only the relevant callers, dependents, and tests—and serves this compact context over the Model Context Protocol (MCP). This approach significantly reduces the token count required for agents to understand code impact, often by orders of magnitude. The system supports incremental updates via file system hooks and watch mode, ensuring the graph remains accurate without full re-parsing. It is designed for local execution, keeping data on the user's machine, and integrates directly with various AI coding tools and CLI environments.

How it works

Memory model: Hybrid

AutoGineer overview, from the brain’s own files

The system uses Tree-sitter to parse source code into an Abstract Syntax Tree (AST), which is then stored as nodes and edges in a local SQLite database. When a user requests a review or code analysis, the system queries this graph to determine the blast radius of a change. It then provides the AI agent with a minimal, relevant subset of the codebase rather than the entire repository. The graph is kept up-to-date incrementally; hooks and watch mode detect file changes, diff them, and re-parse only the affected files and their immediate dependents.

Folders
FolderRoleFiles
.githubagent-config15
docsdocs13
hookshooks2
scriptsscripts7
skillsagent-instructions7
teststests354
.beadsfolder9
code-review-graph-vscodefolder32
code_review_graphfolder103
diagramsfolder12
evaluatefolder24

The agent reads

The agent writes

Requirements

Apps: Docker

Runtimes: Python >=3.10

Databases: Neo4j, SQLite

API keys (by name): CRG_OPENAI_API_KEY, GITHUB_TOKEN, GOOGLE_API_KEY, MINIMAX_API_KEY, VOYAGE_API_KEY

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Google Antigravity, Kiro, OpenCode, Amp, Roo Code, Cline, JetBrains Junie, Devin (ex-Windsurf)

Set it up

  1. This brain runs code automatically: 3 hooks (claude-code). Review hooks/hooks.json before opening the folder in Claude Code. No step below turns a hook on for you.

    • hooks/hooks.json: cat >/dev/null || true; command -v code-review-graph >/dev/null 2>&1 || exit 0; git rev-parse --git-dir >/dev/null 2>&1 && code-review-graph status --repo "$(git rev-parse --show-toplevel 2>/dev/null)" || echo 'Not a git repo, skipping'
    • hooks/hooks.json: cat >/dev/null || true; code-review-graph build >/dev/null 2>&1 &
    • hooks/hooks.json: command -v code-review-graph >/dev/null 2>&1 && code-review-graph hook-update; cat >/dev/null || true
  2. Not scanned by AutoGineerIts dependencies are installed by pip or uv when you run it and were not scanned by AutoGineer (9 declared). https://pypi.org/project/code-review-graph/
  3. Created by Tirth. Published in tirth8205/code-review-graph. Licence: MIT License.

Usage

AutoGineer overview, from the brain’s own files

  • Install the tool via pip and run the install command to configure your AI coding tools.
  • Build the initial knowledge graph for your project.
  • Use MCP-enabled AI agents to query the graph for impact analysis, code reviews, or architectural questions.
  • Rely on automatic incremental updates triggered by file changes to keep the graph in sync.
“Build the code review graph for this project”
The system parses the repository and initializes the SQLite graph database for use by AI agents.
“What is the impact of changing this function?”
The agent uses the graph to identify and present the callers, dependents, and tests affected by the change.

Documentation by Tirth

<h1 align="center">code-review-graph</h1>

<p align="center"> <a href="https://trendshift.io/repositories/23329?utm_source=repository-badge&amp;utm_medium=badge&amp;utm_campaign=badge-repository-23329" target="_blank" rel="noopener noreferrer"> <img src="https://trendshift.io/api/badge/repositories/23329" alt="tirth8205%2Fcode-review-graph | Trendshift" width="250" height="55" /> </a> </p>

<p align="center"> <strong>A local code knowledge graph that gives AI coding tools precise review context over MCP.</strong> </p> <p align="center"> <a href="README.md">English</a> | <a href="README.zh-CN.md">简体中文</a> | <a href="README.ja-JP.md">日本語</a> | <a href="README.ko-KR.md">한국어</a> | <a href="README.hi-IN.md">हिन्दी</a> </p>

<p align="center"> <a href="https://pypi.org/project/code-review-graph/"><img src="https://img.shields.io/pypi/v/code-review-graph?style=flat-square&color=blue" alt="PyPI"></a> <a href="https://pepy.tech/project/code-review-graph"><img src="https://img.shields.io/pepy/dt/code-review-graph?style=flat-square" alt="Downloads"></a> <a href="https://github.com/tirth8205/code-review-graph/stargazers"><img src="https://img.shields.io/github/stars/tirth8205/code-review-graph?style=flat-square" alt="Stars"></a> <a href="https://opensource.org/licenses/MIT"><img src="https://img.shields.io/badge/License-MIT-yellow.svg?style=flat-square" alt="MIT Licence"></a> <a href="https://github.com/tirth8205/code-review-graph/actions/workflows/ci.yml"><img src="https://github.com/tirth8205/code-review-graph/actions/workflows/ci.yml/badge.svg?branch=staging" alt="CI"></a> <a href="https://www.python.org/"><img src="https://img.shields.io/badge/python-3.10%2B-blue.svg?style=flat-square" alt="Python 3.10+"></a> <a href="https://modelcontextprotocol.io/"><img src="https://img.shields.io/badge/MCP-compatible-green.svg?style=flat-square" alt="MCP"></a> <a href="https://code-review-graph.com"><img src="https://img.shields.io/badge/website-code--review--graph.com-blue?style=flat-square" alt="Website"></a> <a href="https://discord.gg/3p58KXqGFN"><img src="https://img.shields.io/badge/discord-join-5865F2?style=flat-square&logo=discord&logoColor=white" alt="Discord"></a> </p>

<p align="center"> <a href="docs/USAGE.md">Usage</a> · <a href="docs/COMMANDS.md">Commands</a> · <a href="docs/FAQ.md">FAQ</a> · <a href="docs/TROUBLESHOOTING.md">Troubleshooting</a> · <a href="docs/GITHUB_ACTION.md">GitHub Action</a> · <a href="docs/REPRODUCING.md">Reproducing the benchmarks</a> · <a href="docs/ROADMAP.md">Roadmap</a> </p>

<br>

AI coding tools often re-read large parts of a codebase to review a change. code-review-graph builds a structural map of the code with Tree-sitter, keeps it updated incrementally, and serves compact context over MCP, so the assistant reads only the files a change touches.

<p align="center"> <img src="diagrams/diagram1_before_vs_after.png" alt="The Token Problem: reading flask's whole corpus costs 143,594 tokens, a graph answer costs 2,196 (65x fewer)" width="85%" /> </p>

What it does

  • Maps your code. Functions, classes, imports, calls and tests become one graph.

  • Shows what a change can break. The callers, dependents and tests it can reach, with a risk score.

  • Stays up to date. Hooks and watch mode parse again only the files that changed.

  • Works with your AI tools. One install sets up each tool it finds.

  • Stays on your machine. One SQLite file, no cloud service; cloud embeddings are opt-in.


Quick Start

Requires Python 3.10+.

pip install code-review-graph          # or: pipx install code-review-graph
code-review-graph install              # detect installed AI coding tools and configure each one
code-review-graph build                # parse the codebase

<details> <summary><strong>What <code>install</code> changes, and how to preview it first</strong></summary> <br>

install detects which AI coding tools you have, writes an MCP server entry for each, installs hooks and skills where the platform supports them, and adds graph instructions to the platform's rules file. The MCP entry uses poetry run or uv run inside a Poetry or uv project environment, uvx code-review-graph serve when uvx is on PATH, and otherwise the current Python interpreter. Nothing is written until install has listed the files it will change and you have answered its question about instruction files; install --dry-run shows each change as a diff and writes nothing. Restart the editor or tool afterwards.

The files install writes, such as .claude/ and .mcp.json, stay visible to git in case your team commits them. install --gitignore adds the ones that run created to a marked block in .gitignore; uninstall removes the block.

For Codex, the installer also places a global code-review-graph Skill under $CODEX_HOME/skills/code-review-graph/ (default: ~/.codex/skills/code-review-graph/). It prefers CRG MCP tools and falls back to the bundled read-only CLI when MCP is unavailable; a missing, empty, or stale graph never triggers an implicit build or update. WSL and Windows Codex runtimes have separate CODEX_HOME directories and tool inventories, so install and refresh the runtime that will execute the task.

</details>

<details> <summary><strong>Every supported platform, and how to set up just one</strong></summary> <br>

<p align="center"> <img src="diagrams/diagram8_supported_platforms.png" alt="One install, every platform: detects Codex, Claude Code, CodeBuddy Code, Cursor, Windsurf, Zed, Continue, OpenCode, MiMo Code, Antigravity, Gemini CLI, Qwen Code, Qoder, Kiro, GitHub Copilot, GitHub Copilot CLI, Hermes Agent and DeepSeek Harness" width="85%" /> </p>

To configure one platform, pass --platform with one of codex, claude-code, cursor, windsurf, zed, continue, opencode, mimo, antigravity, gemini-cli, qwen, kiro, qoder, copilot, copilot-cli, codebuddy, hermes, or dsh:

code-review-graph install --platform cursor
code-review-graph install --platform codebuddy

Config file locations are listed in docs/USAGE.md. Requires Python 3.10+.

</details>

<details> <summary><strong>Remove it again with <code>uninstall</code></strong></summary> <br>

uninstall removes CRG-owned files and entries from a Git or SVN working tree and leaves other MCP servers, hooks, skills and JSONC comments alone. Run it from anywhere inside the tree. Shared config files are replaced atomically, so a failed write leaves the original intact.

code-review-graph uninstall --dry-run    # preview only
code-review-graph uninstall              # preview, confirm, apply
code-review-graph uninstall --yes        # apply without prompting
code-review-graph uninstall --all-repos  # also clean every registered repository
code-review-graph uninstall --keep-data  # remove integrations, keep graph databases
code-review-graph uninstall --keep-user-configs --repo .  # this project only

</details>

Restart the editor or tool after install. Then open the project and ask the assistant:

Build the code review graph for this project

<details> <summary><strong>How long a build takes, and what a partial build means</strong></summary> <br>

Build time scales with repository size; a cold build of a ~3,000-file repository took about 40 seconds (measured). After that, hooks and watch mode keep the graph updated. If some files fail to parse, the result has status partial and names them in its summary; the CLI also prints a Warning: line on stderr, and those files keep their previous graph rows.

</details>

Run with Docker or Podman

<details> <summary><strong>Build the image, then run it on your repository</strong></summary> <br>

Build the image from the repository root:

docker build -t code-review-graph:local .

From the repository you want to analyse, run:

docker run --rm \
  --user "$(id -u):$(id -g)" \
  --env HOME=/tmp \
  --volume "$PWD:/workspace" \
  code-review-graph:local build

The mounted repository must be writable. The command above uses your user and group IDs so the generated .code-review-graph/ directory remains owned by your user. Run these commands as a non-root host user.

For Podman, build the same Dockerfile and preserve your user mapping:

podman build -t code-review-graph:local .
podman run --rm \
  --userns=keep-id \
  --env HOME=/tmp \
  --volume "$PWD:/workspace" \
  code-review-graph:local build

The graph persists in .code-review-graph/ in the mounted repository and stores absolute container paths such as /workspace/app.py. Run update and detect-changes through Docker or Podman with the same /workspace mount. A host update on this graph can fail with "built with a different repository root". To switch to host commands, run code-review-graph build on the host to rebuild the graph with host paths.

Replace build with status to inspect the saved graph. The image includes Git and defaults to a non-root user. No graph is generated during image construction.

These examples use macOS/Linux shell syntax. On macOS, start your Docker-compatible engine or Podman machine before running them. On a host with SELinux on, such as Fedora, add :z to the mount ("$PWD:/workspace:z"), or the container is refused access to the repository.

</details>

How It Works

The repository is parsed into ASTs with Tree-sitter and stored as a graph of nodes (functions, classes, imports) and edges (calls, inheritance, test coverage). At review time the graph is queried for the smallest set of files the assistant needs to read.

<details> <summary><strong>Two diagrams: how the assistant uses the graph, and the build pipeline</strong></summary> <br>

<p align="center"> <img src="diagrams/diagram7_mcp_integration_flow.png" alt="How the assistant uses the graph: the user asks for a review, the assistant calls MCP tools, the graph returns blast radius and risk scores, the assistant reads only the affected files" width="80%" /> </p>

<p align="center"> <img src="diagrams/diagram2_architecture_pipeline.png" alt="Architecture pipeline: Repository to Tree-sitter parser to SQLite graph to blast radius to minimal review set" width="100%" /> </p>

</details>

Blast-radius analysis

<details> <summary><strong>Every caller, dependent and test a change can affect</strong></summary> <br>

When a file changes, the graph traces every caller, dependent and test that could be affected. The assistant reads those files instead of scanning the whole project.

<p align="center"> <img src="diagrams/diagram3_blast_radius.png" alt="Blast radius: a change to login() propagates to callers, dependents, and tests" width="70%" /> </p>

</details>

Incremental updates

<details> <summary><strong>Only changed files are parsed again (about 2.5 s for a two-file edit)</strong></summary> <br>

Editor hooks, git hooks (pre-commit, post-checkout, post-merge, post-rewrite) and watch mode trigger incremental updates. The update diffs changed files, finds their dependents through the graph's import and call edges, and re-parses only the files whose SHA-256 hash changed. On a ~3,000-file project (django) a two-file edit re-indexes in about 2.5 seconds on the path the hooks use, of which ~1.4 s is process start-up; a no-op update costs only that start-up. See Incremental update latency.

<p align="center"> <img src="diagrams/diagram4_incremental_update.png" alt="Incremental update flow: a hook or watch update triggers a git diff, dependents are found through graph edges, and only files whose SHA-256 hash changed are re-parsed" width="90%" /> </p>

</details>

Whole codebase or targeted answer?

<details> <summary><strong>A slice of the graph shaped to the question, not the whole codebase</strong></summary> <br>

Instead of feeding a whole corpus to the model, the graph returns a slice shaped to the question. In the 2026-08-02 capture of this repository at 84bde354, 208,821 source tokens became ~3,190 tokens per question. The repository has grown a lot since that snapshot, so both numbers are larger today.

<p align="center"> <img src="diagrams/diagram6_monorepo_funnel.png" alt="code-review-graph at the 84bde354 snapshot: 208,821 source tokens funnel down to ~3,190 token graph responses, about 65x fewer tokens per question" width="80%" /> </p>

</details>

Language coverage and notebooks

<details> <summary><strong>Python, JavaScript, TypeScript, Go, Rust, Java, C/C++, C# and many more, plus notebooks: the full list</strong></summary> <br>

<p align="center"> <img src="diagrams/diagram9_language_coverage.png" alt="Language coverage by category: Web, Backend, Systems, Mobile, Scripting, Shells, Domain, Config and Other, plus Jupyter and Databricks notebooks" width="90%" /> </p>

The parser extracts functions, classes, imports, call sites, inheritance and tests, using Tree-sitter where a grammar exists and targeted fallbacks elsewhere. Supported: Python, JavaScript/TypeScript/TSX (including .mjs, .cjs, .mts and .cts), Go, Rust, Java, C/C++, C#, VB.NET, Ruby, Kotlin (.kt, .kts), Swift, PHP, Scala, Solidity, Dart, R, Perl, Lua/Luau, Objective-C, shell scripts, Elixir, Zig, PowerShell, Julia, ReScript, GDScript, Nix, Verilog/SystemVerilog, SQL/PL/SQL (Oracle) and dbt models, Terraform/OpenTofu (.tf, and Terraform blocks in .hcl files; an .hcl file with no Terraform blocks keeps only a file node), Ansible YAML (playbooks, roles, tasks), Spring Boot application config (application.properties, application.yml, application.yaml and their application-<profile> variants; key names and value types only, never values), value-free generic YAML structure (translation files in folders such as locales/ become file nodes only), XSLT stylesheets (.xsl, .xslt), value-free JSON structure (.json; translation, test, docs, example and data files keep only a file node, and lock files are skipped), Vue/Svelte SFCs, HTML pages (.html, .htm; inline scripts, plus div, section and article blocks with an id as DocSection nodes), Astro files (parsed with the TypeScript grammar), Jupyter and Databricks notebooks (.ipynb, plus Databricks .py exports), Perl XS files (.xs), Robot Framework files (.robot, .resource), and Liquid templates (.liquid). Other .properties files are not treated as source code.

PHP projects also get repository-bounded Composer PSR-4 resolution, Blade template references, and Laravel Route and Eloquent edges when the source shows explicit framework imports, model inheritance and receiver evidence. Static Laravel routes in routes/*.php emit Endpoint nodes and controller HANDLES edges, including literal group prefixes.

Java projects get Spring dependency-injection call resolution, request endpoints and WebFlux routes, scheduled triggers, application-event publisher-to-listener edges, Spring AOP advice-to-target edges, and Temporal workflow and activity edges. Each resolver runs after the parse and needs the injected field, published event or workflow stub to be visible in the repository.

</details>

Add your own language

<details> <summary><strong>Map a file extension to a bundled Tree-sitter grammar in <code>languages.toml</code></strong></summary> <br>

If your repository uses a language the parser does not cover, add a languages.toml to .code-review-graph/ that maps file extensions to any grammar bundled in tree_sitter_language_pack, plus the node types for functions, classes, imports and calls:

[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"]

The generic tree-sitter walker does the extraction. Built-in languages cannot be overridden. See docs/CUSTOM_LANGUAGES.md for the schema, validation rules and a worked example.

</details>

Risk-scored PR reviews in CI (GitHub Action)

<details> <summary><strong>One pull request comment with risk scores, affected flows and test gaps; see the sample workflow</strong></summary> <br>

The same analysis runs as a composite GitHub Action. The graph is built and queried on your CI runner; no source code is sent to an external service. On each pull request the action posts one sticky comment with risk-scored functions, affected execution flows and test gaps, updated in place on every push. The optional fail-on-risk input turns it into a merge gate. The optional details input adds more graph context, folded away and capped in size: why each top symbol scored what it did, the communities, hubs and cross-boundary links the change touches, its impact radius, its untested hotspots, and where the graph came from.

# .github/workflows/code-review-graph.yml
on:
  pull_request:

permissions:
  contents: read
  pull-requests: write

jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: tirth8205/[email protected]
        with:
          github-token: ${{ secrets.GITHUB_TOKEN }}

See docs/GITHUB_ACTION.md for inputs, risk levels and caching, or the workflow this repository runs on itself in .github/workflows/pr-review.yml.

</details>


Benchmarks

The median per-question token reduction across the 6 repositories is about 63x (whole-corpus baseline vs graph query). The 358x maximum is one repository (fastapi, the largest corpus), not the typical result.

<details> <summary><strong>The benchmark board, and how the numbers were made</strong></summary> <br>

<p align="center"> <img src="diagrams/diagram5_benchmark_board.png" alt="Benchmarks across 6 repositories: ~63x median per-question token reduction (358x max), 0.69 average impact F1 against graph-derived ground truth" width="85%" /> </p>

All numbers come from the evaluation runner against 6 open-source repositories (13 commits). Every config pins an upstream SHA, Leiden runs with a fixed seed, and embeddings are deterministic on CPU, so two runs on different machines produce the same numbers. The reproduction recipe is in docs/REPRODUCING.md. A weekly report-only run on the two smallest configs lives in .github/workflows/eval.yml.

</details>

<details> <summary><strong>Token efficiency: ~63x median per-question reduction (range 35x to 358x; whole-corpus vs graph query)</strong></summary> <br>

For a typical agent question ("how does authentication work", "what is the main entry point", and so on), the graph returns ~2,200 to 3,900 tokens of search hits plus neighbour edges instead of every source file. The table averages the 5 sample questions defined in code_review_graph/token_benchmark.py.

RepoSnapshot SHAnaive_corpus_tokensavg graph_tokensReduction
fastapi22381558948,7932,653357.6x
flaska29f88ce143,5942,19665.4x
code-review-graph84bde354208,8213,19065.5x
gin5c00df8a166,8682,76660.3x
httpxb55d4635142,3562,66153.5x
expressb4ab7d65136,0523,93634.6x

Captured 2026-08-02 from clean clones at the pinned SHAs (crg 2.3.7, local all-MiniLM-L6-v2 embeddings). These numbers are lower than the 2026-05-25 capture they replace: node embedding text became richer, so avg graph_tokens rose in every repo. fastapi is measured at its current pin 22381558 rather than the retired 0227991a.

The Reduction column is naive_corpus_tokens / avg graph_tokens, so it divides out from the two columns beside it. The benchmark's own average_reduction_ratio averages the five per-question ratios instead, which always reads higher; those per-question figures are in docs/REPRODUCING.md.

The code-review-graph row is a snapshot, not a current measurement. The repository has grown since 84bde354, so its corpus and graph are both much larger today.

The whole-corpus baseline is an upper bound no real agent pays; an agent greps for identifiers and reads the best-matching files. The agent_baseline eval benchmark measures that case (a pure-Python grep over the corpus, top-3 files by match count, token-counted against the graph query cost). Against that realistic baseline the median across 18 questions on 6 repositories is 6.65x (mean 14.8x, range 4.2x to 72.6x), captured 2026-09-22, before search and this baseline began ranking test files lower, so code-review-graph eval --benchmark agent_baseline --embed now gives different numbers until the capture is redone. The full table is in docs/REPRODUCING.md, under "Canonical capture, 2026-09-22".

The ratio tracks repository size, because the graph answer stays flat (2,432 to 4,021 tokens across every repo measured) while the grep baseline grows with the corpus: 4.5x on express, 52x on fastapi. Both figures measure retrieval cost, the tokens needed to locate an answer. An agent that then opens the files the graph named pays the graph on top of its usual reads rather than instead of them; semantic_search_nodes_tool(include_source=True) returns the code with the locations so it does not have to, and measuring that path end-to-end is open work.

The formal token_efficiency benchmark measures a different scenario, the full get_review_context() JSON against only the changed-file content of a commit, and reports ratios below 1 for small commits because the response carries impact-radius edges and source snippets. The two benchmarks answer different questions; see docs/REPRODUCING.md.

Review and impact tools attach a compact context_savings estimate to their responses. The CLI shows the same figures in the Token Savings panel (see Usage below) and --verify compares them with OpenAI's cl100k_base tokenizer. Calibration across 222 sample files puts the estimate within about 1% of real tokens in aggregate (data).

</details>

<details> <summary><strong>Impact accuracy: 0.69 average F1 against graph-derived ground truth (recall 1.0 is a circular upper bound)</strong></summary> <br>

Blast-radius analysis recovers every file in the ground truth on all 13 evaluation commits. Read that as an upper bound, not as "100% recall": the ground truth (changed files plus files with call or import edges into them) comes from the same graph the predictor traverses. The lower precision is deliberate; flagging an extra file costs less than missing a broken dependency.

RepoCommitsAvg F1Avg PrecisionRecall (graph-derived upper bound)
httpx20.8630.7851.0
code-review-graph20.7340.5841.0
fastapi20.6970.5391.0
express20.6670.5001.0
flask20.6330.4851.0
gin30.6090.4391.0
Average130.6930.5461.000

This table is from the 2026-08-02 capture, taken before the path fix described below. That bug also kept real neighbour files out of the graph-derived ground truth, so these numbers will change when the benchmark is re-run.

The benchmark also runs a co-change mode: the predictor is seeded with one changed file and graded against the other files the author touched in the same commit, which is evidence from git history rather than from the graph. Both modes appear in the result CSVs (ground_truth_mode column). In the 2026-08-02 capture co-change mode returned predicted_files = 0 on every graded commit, code seeds included (for example code_review_graph/cli.py and gin's context.go). The cause was a path bug in the benchmark: git diff gives repo-relative paths, the graph stores absolute ones, so the seed never matched a node. That bug is now fixed, but the benchmark has not been re-run yet, so no co-change number is quoted.

</details>

<details> <summary><strong>Build stats</strong></summary> <br>

From the same 2026-08-02 clean-room build at the pinned SHAs above. Embedding counts are lower than node counts because File nodes are not embedded. The code-review-graph row is that snapshot, not the repository as it stands now.

RepoNodesEdgesEmbeddings
fastapi6,28732,0365,159
express1,99019,4921,849
gin1,58917,2371,491
code-review-graph1,4469,0941,354
flask1,4158,2591,329
httpx1,2638,2361,193

</details>

Limitations

<details> <summary><strong>Five known limits: circular recall, small edits, search ranking, flow detection, false positives</strong></summary> <br>

  • Impact "recall 1.0" is circular. The historical ground truth comes from the same graph edges the predictor walks, so it is an upper bound by construction. Co-change numbers are not quoted until the benchmark is re-run with the path fix.

  • Small single-file changes. Graph context can exceed a plain file read for trivial edits. The overhead is the structural metadata that makes multi-file analysis possible.

  • Search ranking. Keyword search usually finds the right result near the top, but ranking needs work. Express queries can return no hits because of module-pattern naming.

  • Flow detection. Entry-point detection is strongest for Python and PHP/Laravel. JavaScript and Go flow detection needs work.

  • Precision vs recall. Impact analysis is conservative. It flags files that might be affected, which means false positives in large dependency graphs.

</details>


Features

Updates, impact analysis, search, visualisation, CI reviews, refactoring and multi-repo support, all kept on your machine.

<details> <summary><strong>The full feature table</strong></summary> <br>

FeatureDetails
Incremental updatesRe-parses only files whose hash changed. On a ~3,000-file repo a two-file edit takes ~2.5 s on the hook path (measured).
Language and notebook supportSee Language coverage above.
Framework-aware PHP parsingRepository-bounded Composer PSR-4 imports, Blade template references, evidence-gated Laravel Route-to-controller and Eloquent relationship edges
Framework-aware Java parsingSpring dependency-injection call resolution, request endpoints and WebFlux routes, scheduled triggers, application-event publisher-to-listener edges, Spring AOP advice edges, Temporal workflow and activity edges, and Spring Boot config keys indexed without their values
Blast-radius analysisWhich functions, classes and files are likely affected by a change
Auto-update hooksEditor hooks, git hooks (before each commit, after checkout, merge and rebase) and watch mode update the graph as you work
Semantic searchOptional vector embeddings via sentence-transformers, Google Gemini, MiniMax, Voyage AI, or any OpenAI-compatible endpoint
Interactive visualisationD3.js force-directed graph with search, community legend toggles and degree-scaled nodes, plus a neighbourhood view seeded from a symbol, file, flow or change
Hub and bridge detectionMost-connected nodes and chokepoints (betweenness centrality)
Surprise scoringUnexpected coupling: cross-community, cross-language, peripheral-to-hub edges
Knowledge gap analysisIsolated nodes, untested hotspots, thin communities, import cycles
Suggested questionsReview questions generated from bridges, hubs and surprises
Edge confidenceFour tiers (EXTRACTED, INFERRED, AMBIGUOUS, UNRESOLVED) with float scores on edges, so a call the graph could not bind says so
Graph traversalBFS/DFS from any node with configurable depth and token budget; path_to shows how one symbol reaches another and names the weakest hop
Export formatsGraphML, Neo4j Cypher, Obsidian vault, JSON, and SVG (SVG needs matplotlib from the eval extra)
Token benchmarkingcode_review_graph/token_benchmark.py measures whole-corpus tokens against graph query tokens per question
Estimated context savingscontext_savings metadata (estimated, saved_tokens, saved_percent) on review, impact, detect-changes and architecture responses
Community auto-splitCommunities above 25% of the graph are split recursively with Leiden
Execution flowsCall chains from entry points, sorted by weighted criticality
Community detectionLeiden clustering with resolution scaled to graph size
Architecture overviewCommunity-based architecture map with coupling warnings
Risk-scored reviewsdetect_changes maps diffs to affected functions, YAML and JSON paths, flows and test gaps
Custom languagesNew languages via .code-review-graph/languages.toml, no fork needed
GitHub ActionSticky risk-scored PR review comments in CI, with an optional fail-on-risk merge gate
Refactoring toolsRename preview, framework-aware dead code detection, community-driven suggestions
Wiki generationMarkdown wiki from community structure
Multi-repo registryRegister several repos and search across them
Multi-repo daemoncrg-daemon watches several repos as child processes, with health checks and restart
MCP prompts5 workflow templates: review, architecture, debug, onboard, pre-merge
Full-text searchFTS5 hybrid search combining keyword and vector similarity
Local storageOne SQLite file in .code-review-graph/; no external database or cloud service

</details>


Usage

Your assistant uses the graph by itself once it is built. Open a part below for skills, commands, MCP tools and settings.

<details> <summary><strong>Skills</strong></summary> <br>

install writes these four skills for the platforms that support them (Claude Code, Gemini CLI, CodeBuddy Code, Hermes Agent and Qoder). Ask for one by name.

SkillDescription
explore-codebaseNavigate and understand codebase structure using the knowledge graph
review-changesPerform a structured code review using change detection and impact
debug-issueSystematically debug issues using graph-powered code navigation
refactor-safelyPlan and execute safe refactoring using dependency analysis

Qoder also gets build-graph, review-delta and review-pr from the repository's skills/ directory.

</details>

<details> <summary><strong>CLI reference</strong></summary> <br>

code-review-graph install          # Detect and configure all platforms
code-review-graph install --platform <name>  # One platform
code-review-graph install --steering  # Claude Code: graph context beside each search and read
code-review-graph uninstall --dry-run  # Preview removal of installed artifacts
code-review-graph build            # Parse the whole codebase
code-review-graph build --follow-symlinks  # Also index symlinked folders
code-review-graph update           # Incremental update (changed files only)
code-review-graph status           # Graph statistics
code-review-graph watch            # Update on file changes
code-review-graph forget <path>    # Drop already-parsed files from the graph
code-review-graph dead-code        # Functions and classes with no callers or tests
code-review-graph query path_to <from> --to <to>  # How one symbol reaches another
code-review-graph impact --detail-level compact  # Blast radius as ranked file paths
code-review-graph visualize        # Interactive HTML graph
code-review-graph visualize --seed-symbol <name>  # Neighbourhood of one symbol
code-review-graph visualize --format json      # Export graph data as JSON
code-review-graph visualize --format graphml   # Export as GraphML
code-review-graph visualize --format svg       # Export as SVG (needs matplotlib)
code-review-graph visualize --format obsidian  # Export as Obsidian vault
code-review-graph visualize --format cypher    # Export as Neo4j Cypher
code-review-graph wiki             # Markdown wiki from communities
code-review-graph detect-changes --brief         # Risk panel + token savings (read-only)
code-review-graph detect-changes --brief --base main  # Against the merge base of main and HEAD
code-review-graph update --brief                 # Refresh graph + same panel
code-review-graph detect-changes --brief --verify  # Cross-check against tiktoken
code-review-graph detect-changes --details all  # Add graph context to the JSON
code-review-graph context-history  # Trend of the opt-in savings log (CRG_CONTEXT_HISTORY=1)
code-review-graph register <path>  # Register repo in the multi-repo registry
code-review-graph unregister <path|alias>  # Remove repo from the registry
code-review-graph repos            # List registered repositories
code-review-graph daemon start     # Start the multi-repo watch daemon
code-review-graph daemon stop      # Stop the daemon
code-review-graph daemon status    # Daemon status and repos
code-review-graph eval --all       # Run every evaluation benchmark
code-review-graph serve            # Start the MCP server (stdio)
code-review-graph serve --http     # MCP over Streamable HTTP on localhost:5555
code-review-graph serve --http --multi-repo  # One HTTP server for every registered repo
code-review-graph serve --multi-worktree  # One child server per linked Git worktree

This is a selection. code-review-graph --help lists every command, and docs/COMMANDS.md documents their flags.

When detect-changes --base names a branch, the diff runs against the merge base of that branch and HEAD. Commit hashes and other revisions are used as given.

visualize --format svg needs matplotlib, which ships in the eval extra (pip install "code-review-graph[eval]"). The other export formats need no extra install.

JSON exports are written inside the local graph data directory, which Git ignores by default. They can contain absolute paths and code-structure metadata, so inspect an export before publishing it.

</details>

<details> <summary><strong>Token Savings panel: <code>detect-changes --brief</code> vs <code>update --brief</code></strong></summary> <br>

Both commands print the same panel showing how many tokens the graph saved compared with handing the changed files to an agent raw. They differ in one thing: whether the graph is refreshed first.

┌─────────────────────── 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   │
└──────────────────────────────────────────────────────────────┘
CommandWhat it doesWhen to use
detect-changes --briefRead-only. Queries the existing graph for the current changes and prints the panel.Most of the time; hooks or crg-daemon keep the graph fresh.
update --briefRe-parses the changed files into the graph first, then prints the same panel.After a rebase, a large change set, or whenever the graph may be stale.

Add --verify to either command to compare the figures with OpenAI's cl100k_base tokenizer (needs pip install tiktoken). The estimate is within about 1% of real tokens in aggregate; see docs/REPRODUCING.md.

The same context_savings metadata is attached to the JSON responses of the get_impact_radius, get_review_context, detect_changes and get_architecture_overview MCP tools.

To see these estimates over time, set CRG_CONTEXT_HISTORY=1 (off by default). Each estimate then adds one line to a local log next to graph.db, holding token counts, tool names, a timestamp, a detail level and file and depth counts, never file names, paths or source text, and code-review-graph context-history prints it per day or per tool. See docs/USAGE.md.

</details>

<details> <summary><strong>Multi-repo daemon</strong></summary> <br>

If install gives your editor no hooks (for example Windsurf or Zed), or you want the graph kept fresh without editor integration, the daemon watches your repositories and updates their graphs. It ships with code-review-graph; no separate install.

# 1. Register the repos to watch
crg-daemon add ~/project-a --alias proj-a
crg-daemon add ~/project-b

# 2. Start the daemon (runs in the background)
crg-daemon start

# 3. Check on it
crg-daemon status                 # daemon and per-repo watcher status
crg-daemon logs --repo proj-a -f  # tail logs for one repo
crg-daemon stop                   # stop the daemon and all watchers

Also available as code-review-graph daemon start|stop|status|....

crg-daemon add writes to ~/.code-review-graph/watch.toml, which you can also edit directly:

[[repos]]
path = "/home/user/project-a"
alias = "proj-a"

[[repos]]
path = "/home/user/project-b"
alias = "project-b"

The daemon watches this file and starts or stops watcher processes as repos are added or removed. A health check every 30 seconds restarts dead watchers.

See docs/COMMANDS.md for the full config reference.

</details>

<details> <summary><strong>30 MCP tools</strong></summary> <br>

The assistant uses these once the graph is built. The 25 tools that only read carry readOnlyHint: true, so a client can run them without asking; the five that write (build_or_update_graph_tool, run_postprocess_tool, embed_graph_tool, apply_refactor_tool, generate_wiki_tool) do not.

ToolDescription
build_or_update_graph_toolBuild or incrementally update the graph
run_postprocess_toolRe-run flow detection, community detection and FTS indexing
get_minimal_context_toolCompact context (~100 tokens); call this first
get_impact_radius_toolBlast radius of changed files; detail_level="compact" gives ranked file paths
get_review_context_toolReview context with structural summary
query_graph_toolCallers, callees, tests, imports, inheritance, and path_to between two symbols
traverse_graph_toolBFS/DFS traversal from any node with a token budget
semantic_search_nodes_toolSearch code entities by name or meaning
embed_graph_toolCompute vector embeddings for semantic search
list_graph_stats_toolGraph size and health
get_docs_section_toolRetrieve documentation sections
find_large_functions_toolFunctions, classes or files above a line-count threshold
list_flows_toolExecution flows sorted by criticality
get_flow_toolOne execution flow
get_affected_flows_toolFlows affected by changed files
list_communities_toolDetected code communities
get_community_toolOne community
get_architecture_overview_toolArchitecture overview from community structure
detect_changes_toolRisk-scored change impact analysis
get_hub_nodes_toolMost-connected nodes
get_bridge_nodes_toolChokepoints by betweenness centrality
get_knowledge_gaps_toolStructural weaknesses, untested hotspots and import cycles
get_surprising_connections_toolUnexpected cross-community coupling
get_suggested_questions_toolReview questions generated from the analysis
refactor_toolRename preview, dead code detection, suggestions
apply_refactor_toolApply a previously previewed refactoring
generate_wiki_toolMarkdown wiki from communities
get_wiki_page_toolOne wiki page
list_repos_toolRegistered repositories
cross_repo_search_toolSearch registered repositories; repos limits the search to a subset

MCP prompts (5 workflow templates): review_changes, architecture_map, debug_issue, onboard_developer, pre_merge_check

</details>

<details> <summary><strong>Configuration</strong></summary> <br>

To exclude paths from indexing, create a .code-review-graphignore file in the repository root:

generated/**
*.generated.ts
vendor/**
node_modules/**

In git repositories a build reads tracked files plus untracked files git does not ignore (git ls-files and git ls-files --others --exclude-standard), so gitignored files are skipped. Use .code-review-graphignore to exclude other files or when git is not available. The default ignore list is in docs/USAGE.md.

Optional dependency groups:

pip install "code-review-graph[embeddings]"          # Local vector embeddings (sentence-transformers)
pip install "code-review-graph[google-embeddings]"   # Google Gemini embeddings
pip install "code-review-graph[communities]"         # Community detection (igraph)
pip install "code-review-graph[enrichment]"          # Python call resolution with Jedi (then build --enrich)
pip install "code-review-graph[eval]"                # Evaluation benchmarks and SVG export (matplotlib)
pip install "code-review-graph[wiki]"                # ollama client (not used by the current wiki generator)
pip install "code-review-graph[all]"                 # All optional dependencies
Environment Variables
VariableDescriptionDefault
CRG_GIT_TIMEOUTTimeout in seconds for Git operations (build, update, watch)30
CRG_DISCOVERY_TIMEOUTTimeout in seconds for each Git command that discovers what changed, when a review tool or command was not given an explicit file list. Running out reports an error, never "no changes"5, or CRG_GIT_TIMEOUT when you set that explicitly
CRG_DATA_DIRDirectory for graph databases and generated artefacts-
CRG_HOOK_WORKTREESSet to 1 to let the generated git hooks run in linked git worktrees-
CRG_EMBEDDING_MODELDefault model for local vector embeddingsall-MiniLM-L6-v2
CRG_ACCEPT_CLOUD_EMBEDDINGSSet to 1 to suppress the cloud embedding egress warning-
CRG_ALLOW_REMOTE_CODEAllow HuggingFace models that require trust_remote_code=True0
CRG_VECTOR_CACHESet to 1 to keep the decoded embedding vectors in memory between semantic searches instead of reading them all back from SQLite on every query. Costs RAM (vectors × dimensions × 4 bytes per cached index) and one open read connection per cached database for the life of the process: on Windows, graph.db cannot be deleted or replaced while it is open-
CRG_MAX_IMPACT_NODESMaximum nodes in impact analysis500
CRG_MAX_IMPACT_DEPTHSearch depth for blast-radius analysis2
CRG_MAX_BFS_DEPTHMaximum depth for graph traversal15
CRG_MAX_CHANGED_FUNCSMaximum changed functions analysed in one change report500
CRG_MAX_DELETION_FILESMaximum files whose old version is read in one change report, to name the functions and classes a diff deleted100
CRG_MAX_CHANGED_YAML_PATHSMaximum changed YAML paths analysed in one change report, and separately the same number of JSON paths200
CRG_MAX_TRANSITIVE_FRONTIERMaximum callees followed per hop when tests_for and detect-changes look for tests. The first by name are kept, so one graph always gives one answer50
CRG_CALLER_TEST_ROUTE_DEPTHHops to walk up incoming CALLS when looking for a tested caller of an untested changed symbol. Reported as a note, never as coverage2
CRG_CALLER_TEST_ROUTE_MAX_CALLERSMaximum callers examined while looking for that tested caller500
CRG_TOOL_TIMEOUTTimeout in seconds for read-only MCP tools (0 disables). Does not bound the tools that write: build, postprocess, embed, wiki and apply-refactor0
CRG_CHURN_WINDOW_DAYSWindow for detect-changes --churn commit counts90
CRG_CONTEXT_HISTORYSet to 1 to keep a local log of each context_savings estimate in .code-review-graph/context-history.jsonl; read it with code-review-graph context-history. Holds token counts, tool names, a timestamp, a detail level and file and depth counts, never file names, paths or source text, and is never sent anywhere-
CRG_LEIDEN_SEEDSeed for Leiden community detection42
CRG_RECURSE_SUBMODULESInclude git submodules when set to 1, true or yes-
CRG_FOLLOW_SYMLINKSFollow symlinked folders, inside or outside the repository, when set to 1, true, yes or on; same as --follow-symlinks. See Symlinked folders-
CRG_MAX_FOLLOWED_FILESMost files taken through followed symlinked folders10000
CRG_TOOLSComma-separated allowlist of MCP tools to expose when serving-
GOOGLE_API_KEYAPI key for Google Gemini embeddings-
MINIMAX_API_KEYAPI key for MiniMax embeddings-
VOYAGE_API_KEYAPI key for Voyage embeddings-
CRG_VOYAGE_MODELModel for Voyage embeddingsvoyage-code-3
CRG_VOYAGE_OUTPUT_DIMENSIONOutput dimension for Voyage embeddings1024
CRG_VOYAGE_OUTPUT_DTYPEOutput dtype for Voyage embeddingsfloat
CRG_VOYAGE_BASE_URLVoyage embeddings endpointhttps://api.voyageai.com/v1
CRG_VOYAGE_BATCH_SIZEBatch size for Voyage requests100
CRG_VOYAGE_MIN_INTERVAL_SECMinimum delay between Voyage requests0
CRG_OPENAI_BASE_URLOpenAI-compatible embeddings endpoint-
CRG_OPENAI_API_KEYAPI key for OpenAI-compatible embeddings-
CRG_OPENAI_MODELModel for OpenAI-compatible embeddings-
CRG_OPENAI_DIMENSIONPin the embedding dimension (v3 models support reduction)-
CRG_OPENAI_BATCH_SIZEBatch size for OpenAI-compatible requests100
NO_COLORDisable ANSI colours in the terminal-
CRG_SERIAL_PARSESet to 1 to disable parallel parsing (for debugging)-
CRG_ENABLE_ENRICHMENTSet to 1 to resolve Python method calls with Jedi on every build and update (needs the enrichment extra; about a second more per Python file). Same as build --enrichoff
CRG_DISABLE_ENRICHMENTSet to 1 to never run Jedi, even when asked for-

OpenAI-compatible embeddings need no extra install. Set the variables and pass provider="openai" to embed_graph:

export CRG_OPENAI_BASE_URL=http://127.0.0.1:3000/v1     # or https://api.openai.com/v1
export CRG_OPENAI_API_KEY=sk-...
export CRG_OPENAI_MODEL=text-embedding-3-small          # whatever your gateway serves
# optional:
export CRG_OPENAI_DIMENSION=1536                        # pin dim (v3 models support reduction)
export CRG_OPENAI_BATCH_SIZE=100                        # lower for gateways with tight limits

The cloud-egress warning is skipped when the base URL points at localhost (127.0.0.1, localhost, 0.0.0.0, ::1).

Voyage embeddings need no extra install. Set VOYAGE_API_KEY and pass provider="voyage" to embed_graph; the default model is voyage-code-3:

export VOYAGE_API_KEY=pa-...
export CRG_ACCEPT_CLOUD_EMBEDDINGS=1
code-review-graph embed --provider voyage --model voyage-code-3

Model selection. Avoid -preview, -beta or -exp model IDs for an index you plan to keep; preview models can change weights (a different dimension forces a full re-embed) or be withdrawn. Prefer GA releases such as text-embedding-3-small / text-embedding-3-large (OpenAI) or gemini-embedding-001 (native Gemini provider, which needs GOOGLE_API_KEY).

The embedding text is identifiers, signatures, structural context, and a bounded first-paragraph docstring or doc-comment summary. Function bodies are not sent. Graphs created before documentation extraction was added need one full code-review-graph build before re-embedding. Routine builds never refresh embeddings; to refresh after a build, pass both --embedding-provider and --embedding-model. Cloud providers receive this source-derived text and may charge for it.

Tool Filtering

CRG exposes 30 MCP tools by default. To limit the server to a subset, use --tools or the CRG_TOOLS environment variable:

# CLI flag
code-review-graph serve --tools query_graph_tool,semantic_search_nodes_tool,detect_changes_tool

# Environment variable
CRG_TOOLS=query_graph_tool,semantic_search_nodes_tool code-review-graph serve

The flag takes precedence over the variable. When neither is set, all tools are available. In an MCP client config:

{
  "mcpServers": {
    "code-review-graph": {
      "command": "code-review-graph",
      "args": ["serve", "--tools", "query_graph_tool,semantic_search_nodes_tool,detect_changes_tool,get_review_context_tool"]
    }
  }
}

</details>


FAQ and comparisons

Answers in docs/FAQ.md:

<details> <summary><strong>How it compares with LSP, RAG and grep, when not to use it, and more</strong></summary> <br>

</details>

Troubleshooting

More cases, including Windows/WSL, are in docs/TROUBLESHOOTING.md.

pip / pipx cannot download hatchling (or Errno 9 / Bad file descriptor to PyPI)

<details> <summary><strong>How to fix it</strong></summary> <br>

Installing from a source tree (for example pipx install .) needs build dependencies from PyPI. If you see Could not find a version that satisfies the requirement hatchling after connection warnings, the Python in that terminal may not be able to open an HTTPS connection to pypi.org. This is seen most often in an editor's integrated terminal, and sometimes with a VPN, firewall or proxy.

  1. Run the same command from a terminal outside the editor, such as Terminal.app.

  2. Install from a checkout with uv, which uses different download machinery:

    cd /path/to/code-review-graph
    uv tool install . --force
  3. For development in a clone, use uv sync and uv run code-review-graph ....

To diagnose: python3 scripts/diagnose_pypi_connectivity.py. If it prints FAILED, the problem is the network environment, not the package name.

</details>

Windows: Invalid JSON: EOF while parsing or MCP error -32000: Connection closed

<details> <summary><strong>How to fix it</strong></summary> <br>

Do not use a cmd /c wrapper in the Claude Code config. Point ~/.claude.json at the .exe directly and set UTF-8 through the config:

"code-review-graph": {
  "command": "C:\\path\\to\\your\\venv\\Scripts\\code-review-graph.exe",
  "args": ["serve", "--repo", "C:\\path\\to\\your\\project"],
  "env": { "PYTHONUTF8": "1" }
}

</details>

Contributing

Pull requests target staging (the default branch). Changes are promoted staging → testing → main, and releases are tagged from main. No promotion is automatic: a person reviews and merges each one. See CONTRIBUTING.md for the full flow.

<details> <summary><strong>Set up a development copy and run the tests</strong></summary> <br>

git clone https://github.com/tirth8205/code-review-graph.git
cd code-review-graph
python3 -m venv .venv && source .venv/bin/activate
pip install -e ".[dev]"
pytest

</details>

<details> <summary><strong>Add a built-in language</strong></summary> <br>

To add a built-in language, edit code_review_graph/parser.py: add the extension to EXTENSION_TO_LANGUAGE and node type mappings to _CLASS_TYPES, _FUNCTION_TYPES, _IMPORT_TYPES and _CALL_TYPES. Include a test fixture and open a PR. For a language you only need in one repository, use languages.toml instead.

</details>

Licence

MIT. See LICENSE.

<p align="center"> <br> <a href="https://code-review-graph.com">code-review-graph.com</a><br><br> <code>pip install code-review-graph && code-review-graph install</code> </p>

CONTRIBUTING.md

Contributing to code-review-graph

Development Setup

git clone https://github.com/tirth8205/code-review-graph.git
cd code-review-graph
uv sync --extra dev                  # requires uv
uv run pytest tests/ --tb=short -q   # check the setup

uv sync uses the newest Python it finds. CI tests 3.10 to 3.13, so add --python 3.13 to uv sync to match it.

You can run install inside this checkout: the root .gitignore lists what each platform writes here. Claude Code, CodeBuddy, Antigravity and Gemini CLI also change the tracked CLAUDE.md, GEMINI.md or .mcp.json; do not commit those changes by accident.

Running Tests

uv run pytest tests/ --tb=short -q                                                    # all tests
uv run pytest --cov=code_review_graph --cov-report=term-missing --cov-fail-under=65   # with the CI coverage gate
uv run pytest tests/test_parser.py -v                                                 # one file

CI runs the suite on Python 3.10, 3.11, 3.12 and 3.13 and fails below 65% coverage.

tests/test_parser_grammar_contract.py checks every built-in class, function, import, and call dispatch name against its bundled Tree-sitter grammar. When updating a grammar or adding dispatch entries, use the grammar's actual named node types. This contract checks configured dispatch names; language fixtures still verify extraction behaviour.

Linting and Type Checking

uv run ruff check code_review_graph/
uv run mypy code_review_graph/ --ignore-missing-imports --no-strict-optional

CI also runs bandit -r code_review_graph/ -c pyproject.toml and checks that LATEST_VERSION in code_review_graph/migrations.py equals SUPPORTED_SCHEMA_VERSION in the VS Code extension.

The minimum-dependencies job installs every direct dependency at the lowest version pyproject.toml allows, from .github/requirements-minimum.txt, and runs the tests on each supported Python. If you add a dependency or change its lower bound, change that file too; tests/test_dependency_floors.py fails if the two disagree.

Code Style

  • Line length: 100 characters.

  • Target: Python 3.10+.

  • Linter: ruff with rules E, F, I, N, W. Imports are sorted by ruff.

  • SQL: parameterised queries (? placeholders) only.

Making Changes

  1. Fork the repository and create a branch from staging: git checkout -b feature/your-feature origin/staging.

  2. Make the change and add tests for new behaviour.

  3. Run the tests, ruff and mypy as above.

  4. Update docs where behaviour changed (README, docs/, docstrings). README.md has four translations: README.zh-CN.md, README.ja-JP.md, README.ko-KR.md and README.hi-IN.md. If you add or remove a heading, change a code block or a link, or add or remove a table row in README.md, make the same change in all four. tests/test_readme_parity.py checks this.

  5. Open a pull request against staging (the default branch, so GitHub picks it for you). The template asks for the linked issue, what changed and why, and the commands you ran.

Branching and promotion

The repository keeps three long-lived branches. Code moves in one direction only:

feature branch --PR--> staging --PR--> testing --PR--> main --tag--> PyPI
BranchPurposeWho merges into it
stagingDefault branch. Every feature and fix PR lands here first.Maintainers, once CI is green.
testingCandidate for the next release. Gets a longer soak and manual QA.Maintainer only, by hand, via a promotion PR from staging.
mainReleased code. Nothing reaches main without passing QA on testing.Maintainer only, by hand, via a promotion PR from testing.

Rules that apply to all three branches (enforced by repository rulesets):

  • Changes arrive only through a pull request. Direct pushes, force-pushes and branch deletion are blocked for everyone, admins included.

  • The same status checks must pass on every PR: lint, type-check, security, schema-sync, and test on Python 3.10 through 3.13. Feature PRs into staging must also be up to date with staging before merging; promotion PRs are exempt from the up-to-date rule because a merge-commit promotion always leaves the target one commit ahead of its source.

  • Repository admins may bypass the check requirements only when merging a pull request, never by pushing.

Feature PRs target staging. Squash-merging is fine for a single-author PR; use a merge commit when a PR has several authors so nobody loses attribution. Rebase-merge is also allowed on staging.

Promotion PRs move everything on staging to testing, and later everything on testing to main. They are always merged with a merge commit, never squashed, so every contributor stays the author of their commits; the testing and main rulesets allow no other merge method. Opening a promotion PR re-queues every required check on a commit that already had them green from the push run, so the PR sits blocked for a quarter of an hour or so before it can be merged. That is normal.

No promotion is automatic. Green checks are necessary but not sufficient: a person reviews and merges every promotion, and no workflow may merge a pull request. tests/test_promotion_is_manual.py fails if one tries.

Promotion to testing. Open it with gh pr create --base testing --head staging, read what it brings in, wait for the required checks, and merge it yourself with a merge commit. The Promote workflow in the Actions tab can open the PR instead, but it needs Settings → Actions → General → Workflow permissions → Allow GitHub Actions to create and approve pull requests, which is off here on purpose. Merging into testing starts the promotion gate.

Promotion to main is never automatic. Open it by hand with gh pr create --base main --head testing (the Promote workflow, testing -> main, needs the same setting as above), read the promotion gate's verdict first, and merge it yourself. That is the maintainer's sign-off: CI green is necessary but not sufficient.

Hotfixes for a released version follow the same path. If a fix is urgent, open the PR against staging and promote twice in a row; do not open PRs against main.

The promotion gate

Every time something lands on testing, .github/workflows/promotion-gate.yml runs the slow checks that are too expensive for a pull request. It also runs on demand from the Actions tab. It never runs on a pull request, so no contributor waits for it.

It runs seven checks:

CheckWhat it doesIf it fails
upgrade-pathInstalls the last three PyPI releases, builds a real graph with each, then opens and updates that graph with the current code.Blocks
packagingBuilds the wheel and the sdist, installs each into a clean environment with the checkout out of reach, and drives the installed program.Blocks
determinismRebuilds one corpus nine times, serial and parallel, thread and process, under two hash seeds, and compares every table.Blocks
suiteThe ordinary test suite with the 65% coverage floor, on Python 3.10, 3.11, 3.12 and 3.13.Blocks
e2eDrives the real MCP server over stdio on Linux, macOS and Windows.Blocks on Linux and macOS, reports on Windows
corpusClones eight pinned third-party repositories, builds a graph over each, and compares twelve measured properties against recorded baselines.Reports
browserRenders the generated visualization page in headless Chromium.Reports

Blocks means: do not promote testing to main until it is green or the maintainer has decided in writing why it does not matter. Reports means the failure is recorded and shown but does not hold a release.

The split is not about how important a check is, it is about whether a failure is evidence about our code:

  • upgrade-path blocks because it is the only check that proves a database a user already has survives the upgrade. A migration that corrupts it cannot be undone by a later patch release.

  • packaging blocks because a wheel missing a data file is broken for every user at once and needs another release to fix. It installs from PyPI, which every other job here already does, so it adds no new way to fail.

  • determinism blocks because it needs no network and no third-party checkout: a failure is a real difference, never an outage.

  • suite blocks because it is the same suite the pull-request CI already requires, re-run against the merged state of testing, which no single pull request tested.

  • e2e blocks on Linux and macOS because the stdio MCP interface is what every editor integration speaks. The Windows leg reports, because process spawning and file-handle timing on the Windows runner is the flakiest surface in this repository and a runner hiccup must not hold a release.

  • corpus reports because it clones eight repositories that belong to other people. A rate limit, an outage or an upstream force-push fails it for a reason that has nothing to do with this code, and a failed clone must not stop a release. A property that moved is still a real regression: read the numbers and decide.

  • browser reports because it downloads a Chromium build at run time, and a page that fails to render damages nobody's data.

Reporting is not the same as ignoring. Every check is wrapped by scripts/promotion_gate.py, which fails it when its test module is not in the checkout, when the run collected almost nothing, or when the tests were skipped instead of run, including a browser run that skipped because Playwright was missing. A check that quietly tested nothing is recorded as a failure, not as a pass.

The result is posted twice: to the run's job summary, and as one comment on the open issue labelled promotion-gate (the workflow opens that issue the first time it needs it). The report names every check, whether it passed, and for a failure the exact assertion that moved: for example the property, its baseline and the measured delta.

The gate opens no pull request and merges nothing. Promotion to main stays the maintainer's decision.

To run any of these by hand:

CRG_UPGRADE_TEST=1 uv run pytest -m upgrade -q -rxX   # upgrade-path
uv run pytest tests/test_packaging.py -m packaging -q # packaging
uv run pytest -m determinism -q -rxX                  # determinism
uv run pytest -m corpus -q                            # corpus (clones 8 repos)
uv run pytest -m browser -q                           # browser (needs the browser-test extra and `uv run python -m playwright install chromium`)
uv run pytest -m e2e -q                               # e2e

Releases are cut from main only: bump the version, tag vX.Y.Z, publish a GitHub release, and the publish workflow uploads to PyPI. Nothing is ever released from staging or testing.

Archived branches. Old branches are not deleted outright. A branch that carried work not on main is kept as a tag under archive/<branch-name> (list them with git tag -l 'archive/*'), and local review copies live under the hidden namespace refs/archive/local/* (fetch them with git fetch origin 'refs/archive/*:refs/archive/*'). Nothing anyone contributed has been removed from history.

Project Structure

The module list is in the Architecture section of CLAUDE.md. In outline:

code_review_graph/         # core package: parser, graph store, incremental update, MCP server, CLI
  tools/                   # MCP tool implementations
  eval/                    # benchmark runner
tests/                     # pytest suite
  fixtures/                # sample files per language
code-review-graph-vscode/  # VS Code extension (separate package)
docs/                      # user documentation
skills/                    # shipped agent skills, bundled into the wheel

The text of skills/build-graph, skills/review-delta and skills/review-pr lives in DOCUMENTARY_SKILLS in code_review_graph/skills.py. Edit it there, then run uv run python scripts/generate_documentary_skills.py; a test fails if the files drift. The other four (debug-issue, explore-codebase, refactor-safely, review-changes) come from _SKILLS in the same file, which install writes out; change the text there and in skills/<name>/SKILL.md together, as tests/test_skill_template_schema_sync.py checks that they match byte for byte.

Adding Language Support

If you only need a language for your own repository, you may not need to change this project: add a .code-review-graph/languages.toml that maps extensions and node types to any grammar in tree-sitter-language-pack (see docs/CUSTOM_LANGUAGES.md). To add built-in support:

  1. Add the extension mapping to EXTENSION_TO_LANGUAGE in parser.py.

  2. Add the tree-sitter node types to _CLASS_TYPES, _FUNCTION_TYPES, _IMPORT_TYPES and _CALL_TYPES.

  3. Add a sample file in tests/fixtures/.

  4. Add parsing tests in tests/test_multilang.py.

Robot Framework is a built-in structural fallback rather than a Tree-sitter grammar. Its .robot and .resource files are handled in parser.py, where tests, user keywords, keyword calls, and Resource/Library/Variables settings are extracted. Changes to this support should include focused tests for both extensions in tests/test_parser.py.

Adding a Platform Target

Every supported AI tool is permanent maintenance surface: its config path, schema, install merge, uninstall and tests have to keep working on every release. Some existing targets were merged without evidence that they worked in a released client, and those are the ones that break. New targets are held to the bar below.

Start with a platform request issue (https://github.com/tirth8205/code-review-graph/issues/new/choose) so the client can be discussed before anyone writes code. A pull request that adds a platform will not be reviewed until it includes all of the following.

  1. A link to the platform's official MCP configuration documentation. Blog posts, forum replies and screenshots of a settings dialog are not enough.

  2. The exact config file path and the exact schema of a server entry: which top-level key holds the servers, whether that value is an object or an array, and whether a type field is required.

  3. The entry added through the existing PLATFORMS table in code_review_graph/skills.py, plus _PLATFORM_CHOICES in code_review_graph/cli.py. Use the fields already there: name, config_path, key, detect, format, needs_type, and where needed config_paths, legacy_keys, server_type, entry_fields. If the client needs something the table cannot express, say so in the pull request and explain why, rather than adding a separate code path beside it.

  4. Preservation of unrelated user settings. Install must merge only the code-review-graph server entry and leave every other server, key and top-level setting intact. If the file cannot be parsed, install must skip it rather than rewrite it.

  5. A byte-idempotent reinstall. Running install twice must leave the config file and any generated instruction file byte for byte identical.

  6. A working uninstall in code_review_graph/uninstall.py that removes only what install added, including any legacy keys, and leaves the rest of the file untouched.

  7. Lifecycle tests matching the existing ones: an install, reinstall and uninstall test in tests/test_cli_install.py shaped like test_copilot_cli_install_reinstall_uninstall_lifecycle, and a passing run of the all-platforms sweep in tests/test_uninstall.py (test_uninstall_removes_mcp_entry_for_every_current_platform_spec), which covers every new entry automatically. Also add the platform to EXPECTATIONS in tests/test_platform_lifecycle.py (and raise the platform count there), add its key to the --platform list in README.md and its translations, and list every file it writes inside the repository in the root .gitignore; tests/test_platform_lifecycle.py -m platform_lifecycle and tests/test_install_outputs_are_ignored.py fail otherwise.

  8. Evidence from a real released client: a screenshot or transcript of a session in that client where a code-review-graph tool is invoked and returns a result. A rendered image of text, a mockup or a description of what should happen is not evidence.

If no maintainer can install and run the client, the request may be declined or left open until someone who uses it is willing to own it and respond when it breaks. An existing target may also be removed if it breaks and nobody steps up to fix it.

Reporting Issues

License

By contributing, you agree that your contributions are licensed under the MIT License.

512 files · 480 not served here

Advantages

  • Drastically reduces token usage by providing only the relevant code context for a specific change. evidence: README.md
  • Maintains data privacy by storing the knowledge graph locally in a SQLite file without requiring cloud services. evidence: README.md

Limitations

Security

Risk level: Medium risk

This brain runs

MCP servers (2)

  • .mcp.json (code-review-graph): uvx code-review-graph serve
  • README.md (code-review-graph): code-review-graph serve --tools query_graph_tool,semantic_search_nodes_tool,detect_changes_tool,get_review_context_tool

Agent instructions that run or fetch something (38)

  • AGENTS.md: Other commands that may prompt: `scp` and `ssh` (`-o BatchMode=yes`), `apt-get` (`-y`), `brew` (`HOMEBREW_NO_AUTO_UPDATE=1`). · uses the network
  • CLAUDE.md: `locking.py`: the cross-process lock that lets one graph write run at a time.
  • CLAUDE.md: `skills.py`: `install` (platform MCP configs, hooks, skills, instruction blocks).
  • CLAUDE.md: `install_plan.py`: every install read and write goes through it, so `install --dry-run` can show each change as a diff and a real install writes nothing before its question is answered.
  • CLAUDE.md: `jsonc.py`: comment-preserving JSONC tokenising and splices, shared by install and uninstall so neither flattens a commented config.
  • CLAUDE.md: `install_gitignore.py`: the opt-in `install --gitignore` block listing the files a run created.
  • CLAUDE.md: `uninstall.py`: reverses `install`.
  • CLAUDE.md: uv run pytest tests/ --tb=short -q
  • CLAUDE.md: uv run ruff check code_review_graph/
  • CLAUDE.md: uv run mypy code_review_graph/ --ignore-missing-imports --no-strict-optional
  • CLAUDE.md: uv run code-review-graph build # full build
  • CLAUDE.md: uv run code-review-graph update # incremental update
  • CLAUDE.md: uv run code-review-graph status # graph statistics
  • CLAUDE.md: uv run code-review-graph detect-changes # risk-scored change analysis (read-only)
  • CLAUDE.md: uv run code-review-graph forget PATH # drop files from the graph
  • CLAUDE.md: uv run code-review-graph serve # MCP server (stdio; --http for localhost)
  • CLAUDE.md: uv run code-review-graph wiki # Markdown wiki
  • CLAUDE.md: uv run code-review-graph register <path> # add a repo to the multi-repo registry
  • CLAUDE.md: uv run code-review-graph eval --all # benchmarks
  • CLAUDE.md: uv run code-review-graph --help # full command list
  • CLAUDE.md: Install and platforms: `test_skills.py`, `test_cli_install.py`, `test_uninstall.py`, `test_git_hook_worktree.py`, `test_hermes_install.py`, `test_qoder_bundled_skills.py`, `test_installer_ownership.py` (what install may rewrite and what belongs to the user), `test_install_gitignore_blo …[+283 chars]
  • CLAUDE.md: Builds a wheel and an sdist with `python -m build`, installs each into its own virtual environment, and drives the installed program with the checkout out of reach.
  • CLAUDE.md: Run it before a release with `uv run --python 3.13 python -m pytest tests/test_packaging.py -m packaging`.
  • CLAUDE.md: upgrade-path: manual run only.
  • code_review_graph/assets/code-review-graph/SKILL.md: Resolve the active repository root from the workspace or `git rev-parse --show-toplevel`.
  • code_review_graph/assets/code-review-graph/SKILL.md: Without MCP, run the bundled helper’s `status` command (it forwards `--json` to the CLI).
  • code_review_graph/assets/code-review-graph/SKILL.md: python3 <skill-root>/scripts/crg_readonly.py status --repo "<repo-root>"
  • code_review_graph/assets/code-review-graph/SKILL.md: python3 <skill-root>/scripts/crg_readonly.py architecture --repo "<repo-root>"
  • code_review_graph/assets/code-review-graph/SKILL.md: python3 <skill-root>/scripts/crg_readonly.py search "<query>" --repo "<repo-root>"
  • code_review_graph/assets/code-review-graph/SKILL.md: python3 <skill-root>/scripts/crg_readonly.py query callers_of "<symbol>" --repo "<repo-root>"
  • code_review_graph/assets/code-review-graph/SKILL.md: python3 <skill-root>/scripts/crg_readonly.py query path_to "<symbol>" --to "<other>" --repo "<repo-root>"
  • code_review_graph/assets/code-review-graph/SKILL.md: python3 <skill-root>/scripts/crg_readonly.py impact --repo "<repo-root>"
  • code_review_graph/assets/code-review-graph/SKILL.md: python3 <skill-root>/scripts/crg_readonly.py detect-changes --brief --repo "<repo-root>"
  • code_review_graph/assets/code-review-graph/SKILL.md: A Windows-mounted path such as `/mnt/e/...` is not by itself a failure: verify that the selected runtime can execute the CLI and access that path.
  • skills/build-graph/SKILL.md: Hooks installed by `code-review-graph install` run an update after each edit, before each commit and after a branch switch, merge or rebase, so manual builds are rarely needed.
  • skills/review-delta/SKILL.md: Changes come from `git diff` against `HEAD~1`;
  • skills/review-pr/SKILL.md: The graph tools read the files on disk, so check out what you review first: `git switch <branch>`, or for a PR `git fetch origin pull/<n>/head:pr-<n>` then `git switch pr-<n>`, then call `build_or_update_graph_tool()`. · uses the network
  • skills/review-pr/SKILL.md: Diff it against `main` (or `master`) with `git diff --name-only main...HEAD`, and use that ref as `base` below.

Hooks (3)

  • hooks/hooks.json (SessionStart): cat >/dev/null || true; command -v code-review-graph >/dev/null 2>&1 || exit 0; git rev-parse --git-dir >/dev/null 2>&1 && code-review-graph status --repo "$(git rev-parse --show-toplevel 2>/dev/null)" || echo 'Not a git repo, skipping'
  • hooks/hooks.json (PostToolUse): cat >/dev/null || true; code-review-graph build >/dev/null 2>&1 &
  • hooks/hooks.json (PostToolUse): command -v code-review-graph >/dev/null 2>&1 && code-review-graph hook-update; cat >/dev/null || true
  • Medium risk: runs-mcp-server-unpinned-runner (.mcp.json)
  • Medium risk: runs-instruction-instruction-network (AGENTS.md:17)
  • Medium risk: runs-instruction-instruction-network (skills/review-pr/SKILL.md:13)

Attribution and licence

Created by
Tirth
Declared authors
  • Tirth (declared in pyproject.toml)
Publisher
Tirth Kanani (Community)
Source
tirth8205/code-review-graph · commit e7f2fb2
Licence
MIT License (files served here)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by Tirth.

Install from source

480 of its files are not served here, so there is no ZIP. tirth8205/code-review-graph at e7f2fb2