How code-review-graph Determines Relevant Code Context for AI Review
code-review-graph determines relevant code context for AI review by detecting changed files via Git operations, computing an impact radius through dependency graph traversal, and assembling a token-efficient payload that includes risk assessments, test gaps, and targeted source snippets.
code-review-graph is an open-source Python tool that transforms raw code changes into structured, AI-consumable context. When developers invoke the review pipeline, the tool automatically filters repository noise and surfaces only the dependency paths, risk indicators, and source lines that matter for automated analysis. Understanding how code-review-graph determines relevant code context for AI review enables teams to optimize token usage while ensuring comprehensive coverage of potential side effects.
Stage 1: Detecting Changed Files via Git Operations
The process begins in [code_review_graph/tools/review.py](https://github.com/tirth8205/code-review-graph/blob/main/code_review_graph/tools/review.py#L28-L44) where the get_review_context function initializes the review pipeline. If the caller does not provide an explicit file list, the tool executes git diff --name-only and git status --porcelain to capture both staged and unstaged modifications. The output is normalized to absolute POSIX paths, creating the baseline set of changed files that drives all subsequent analysis.
Stage 2: Computing the Impact Radius
Once changed files are identified, the tool queries the code-dependency graph to calculate the blast radius. In [code_review_graph/tools/review.py](https://github.com/tirth8205/code-review-graph/blob/main/code_review_graph/tools/review.py#L70-L73), the changed paths are fed to the graph store's get_impact_radius method, which traverses relationships up to a configurable depth (defaulting to two hops) to identify:
- Changed nodes: Specific functions, classes, or variables residing in the modified files
- Impacted nodes: Dependencies reachable within the depth budget, including call targets and inheritance parents
- Impacted files: The union of all source files touched by the impacted nodes
This traversal captures cross-file dependencies that a simple text diff would miss, such as indirect function calls or inheritance chains.
Stage 3: Building the Token-Efficient Context Payload
With the impact subgraph identified, the tool constructs a focused context payload designed for LLM consumption while respecting token limits.
Risk Assessment and Test Gap Detection
The system assigns a risk level—high, medium, or low—based on the density of impacted nodes. When the count exceeds twenty unique impacted entities, the context is flagged as high risk according to the heuristic implemented in [code_review_graph/tools/review.py](https://github.com/tirth8205/code-review-graph/blob/main/code_review_graph/tools/review.py#L74-L82). Simultaneously, the tool scans for test gaps by identifying changed functions that lack incoming TESTED_BY edges in the graph, quantifying uncovered logic that requires manual verification as shown in lines 87-99.
Source Snippet Extraction
To prevent context window exhaustion, the tool applies intelligent truncation. It first attempts to include up to 200 lines per changed file. When files exceed this threshold, the _extract_relevant_lines helper selects only the regions surrounding changed nodes, preserving three lines of context and collapsing intervening gaps with ellipsis markers. This logic spans lines 46-64 and lines 92-110 of the review module.
Context Savings Metadata
The payload includes metadata quantifying the compression achieved. The attach_context_savings utility in [code_review_graph/tools/review.py](https://github.com/tirth8205/code-review-graph/blob/main/code_review_graph/tools/review.py#L22-L24) calculates the token delta between the full source dump and the filtered subgraph, allowing downstream agents to report efficiency metrics.
Review Guidance Generation
Finally, the _generate_review_guidance function synthesizes the impact data into actionable recommendations. It flags missing tests when gaps are detected, warns of wide blast radii when impacted files exceed five, and highlights inheritance modifications that could affect downstream consumers, as implemented in lines 31-78.
Minimal Context Mode for Token-Constrained Agents
For agents operating under severe token constraints, the get_minimal_context function in code_review_graph/tools/context.py provides a streamlined alternative. This mode executes the same Git detection and graph analysis but returns only high-level statistics: total node counts, risk scores, top-five key entities, test-gap tallies, and recommended next tools. The resulting payload typically stays under 100 tokens, making it ideal for initiating multi-step review workflows before diving into detailed analysis.
Implementation Examples
The following examples demonstrate how to invoke the context generation tools directly from Python:
from code_review_graph.tools.review import get_review_context
# Generate full review context with source snippets
result = get_review_context(
repo_root="/path/to/repo",
max_depth=2,
include_source=True,
max_lines_per_file=200,
detail_level="standard"
)
print(result["summary"])
print(result["context"]["graph"]["changed_nodes"][:3]) # First three changed nodes
print(result["review_guidance"])
from code_review_graph.tools.context import get_minimal_context
# Generate compact context for token-constrained agents
mini = get_minimal_context(
task="review PR #42",
repo_root="/path/to/repo"
)
print(mini["summary"])
print(mini["key_entities"])
print(mini["next_tool_suggestions"])
# CLI invocation for the review context tool
code-review-graph get_review_context --repo /path/to/repo --detail-level standard
Key Source Files
Understanding the architecture requires examining these core modules:
-
[
code_review_graph/tools/review.py](https://github.com/tirth8205/code-review-graph/blob/main/code_review_graph/tools/review.py#L26-L34): Implementsget_review_context, the primary entry point that orchestrates Git detection, impact analysis, and payload assembly. -
[
code_review_graph/tools/context.py](https://github.com/tirth8205/code-review-graph/blob/main/code_review_graph/tools/context.py#L49-L57): Providesget_minimal_context, the ultra-compact alternative for high-level review initiation. -
[
code_review_graph/graph.py](https://github.com/tirth8205/code-review-graph/blob/main/code_review_graph/graph.py#L1317-L1352): Contains the graph storage layer and theget_impact_radiusmethod that powers dependency traversal. -
[
code_review_graph/main.py](https://github.com/tirth8205/code-review-graph/blob/main/code_review_graph/main.py#L220-L289): Registers the tool functions for command-line interface consumption, mapping arguments to the underlying review and context tools.
Summary
- code-review-graph determines relevant context by first detecting changed files via Git operations, then computing an impact radius through dependency graph traversal.
- The tool applies risk-based filtering to flag high-impact changes and identifies test gaps by checking for missing
TESTED_BYrelationships in the graph. - Intelligent truncation limits source snippets to 200 lines per file or extracts only relevant regions around changed nodes to respect token budgets.
- Two modes are available: full
get_review_contextfor comprehensive analysis andget_minimal_contextfor ultra-compact, high-level overviews under 100 tokens. - All operations are backed by a persistent SQLite graph database that maps code entities and their relationships, enabling accurate cross-file impact detection.
Frequently Asked Questions
How does code-review-graph identify which files have changed?
The tool executes git diff --name-only and git status --porcelain within the repository root to capture both staged and unstaged modifications across the working directory. It normalizes these paths to absolute POSIX format in [code_review_graph/tools/review.py](https://github.com/tirth8205/code-review-graph/blob/main/code_review_graph/tools/review.py#L28-L44), ensuring consistent matching against the internal graph database when no explicit file list is provided by the caller.
What is the difference between get_review_context and get_minimal_context?
get_review_context returns a comprehensive payload including the full impact subgraph, source code snippets, risk assessments, and detailed review guidance, making it suitable for deep analysis. In contrast, get_minimal_context—defined in [code_review_graph/tools/context.py](https://github.com/tirth8205/code-review-graph/blob/main/code_review_graph/tools/context.py#L49-L57)—provides a compressed summary containing only high-level metrics, top entities, and tool recommendations, optimized for scenarios where token budgets are severely constrained.
How does the impact radius calculation work?
The get_impact_radius method in [code_review_graph/graph.py](https://github.com/tirth8205/code-review-graph/blob/main/code_review_graph/graph.py#L1317-L1352) performs a breadth-first traversal starting from nodes in the changed files, following edges such as function calls, class inheritance, and variable references up to a configurable depth (default two hops). This identifies not only direct modifications but also indirect dependencies that might be affected by the changes.
Can I customize the source snippet length or impact depth?
Yes. Both functions accept parameters such as max_depth for graph traversal radius and max_lines_per_file for source inclusion limits. These can be adjusted via the Python API when calling get_review_context or through corresponding CLI flags when using the command-line interface registered in [code_review_graph/main.py](https://github.com/tirth8205/code-review-graph/blob/main/code_review_graph/main.py#L220-L289).
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →