Graph-Based Code Intelligence Guide¶
Overview¶
Victor's graph-based code intelligence features provide deep understanding of code structure, dependencies, and context through three key technologies:
- Code Context Graph (CCG) - Statement-level control flow, control dependence, and data dependence graphs
- Graph RAG - Retrieval-augmented generation using graph traversal for context
- Multi-Hop Retrieval - Traverse dependency chains to find implicit code relationships
Architecture¶
The storage architecture diagram shows the
current code-graph store, dedicated SQLite worker, and separate workflow persistence.
Graph traversal and semantic retrieval combine context above those storage interfaces;
backend status distinguishes defaults from
opt-in ProximaDB work. The schemas and examples below describe this guide’s feature surfaces,
not a claim that every optional backend is enabled.
Quick Start¶
CLI Commands¶
# Index your codebase with CCG
victor graph index --path /path/to/code --ccg --embeddings
# Query using natural language
victor graph query "authentication function" --path /path/to/code
# Analyze impact of changes
victor graph impact login_function --type forward --depth 3
# View graph statistics
victor graph stats --path /path/to/code
# Export graph for visualization
victor graph export --output graph.json --format json
Python API¶
from victor.core.graph_rag import (
GraphIndexingPipeline,
GraphIndexConfig,
MultiHopRetriever,
RetrievalConfig,
)
from victor.storage.graph import create_graph_store
from pathlib import Path
# Create graph store
graph_store = create_graph_store("sqlite", None, Path("/path/to/code"))
await graph_store.initialize()
# Index codebase
config = GraphIndexConfig(
root_path=Path("/path/to/code"),
enable_ccg=True,
enable_embeddings=True,
)
pipeline = GraphIndexingPipeline(graph_store, config)
stats = await pipeline.index_repository()
# Multi-hop retrieval
retriever = MultiHopRetriever(graph_store, RetrievalConfig(max_hops=2))
result = await retriever.retrieve("how does authentication work?")
Code Context Graph (CCG)¶
What is CCG?¶
The Code Context Graph extends traditional symbol graphs with statement-level granularity and three types of edges:
- Control Flow Graph (CFG) - Shows execution paths through code
- Control Dependence Graph (CDG) - Shows which statements control others
- Data Dependence Graph (DDG) - Shows variable def-use relationships
Supported Languages¶
- Python
- JavaScript / TypeScript
- Go
- Rust
- Java
- C / C++
Example CCG Structure¶
# Source code
def process(items):
results = []
for item in items:
if item > 0:
results.append(item * 2)
return results
# CCG creates:
# - Statement nodes for each line
# - CFG edges showing the loop and conditional flow
# - DDG edges tracking 'item', 'results' variable usage
Edge Types¶
| Category | Edge Type | Description |
|---|---|---|
| CFG | CFG_SUCCESSOR |
Sequential execution |
| CFG | CFG_TRUE_BRANCH |
True branch of condition |
| CFG | CFG_FALSE_BRANCH |
False branch of condition |
| CDG | CDG |
Control dependence |
| DDG | DDG_DEF_USE |
Definition to use |
| DDG | DDG_RAW |
Read-after-write |
| DDG | DDG_WAR |
Write-after-read |
| DDG | DDG_WAW |
Write-after-write |
Graph RAG Pipeline¶
Three-Stage Framework¶
1. G-Indexing¶
Builds a unified graph combining:
- Symbol definitions (functions, classes, variables)
- CCG edges (control flow, data flow)
- Semantic embeddings for vector search
- Subgraph caches for fast retrieval
from victor.core.graph_rag import GraphIndexingPipeline, GraphIndexConfig
config = GraphIndexConfig(
root_path=Path("."),
enable_ccg=True,
enable_embeddings=True,
ccg_languages=["python", "javascript"],
)
pipeline = GraphIndexingPipeline(graph_store, config)
stats = await pipeline.index_repository()
# stats.files_processed, stats.nodes_created, stats.edges_created
2. G-Retrieval¶
Multi-hop retrieval combines:
- Seed selection - Vector search for relevant starting nodes
- Graph expansion - BFS traversal following dependency edges
- Relevance scoring - Decay-with-distance ranking
- Pruning - Remove low-relevance nodes
from victor.core.graph_rag import MultiHopRetriever, RetrievalConfig
config = RetrievalConfig(
seed_count=5, # Number of seed nodes
max_hops=2, # Max traversal depth
top_k=10, # Final result count
edge_types=["CALLS", "REFERENCES", "DDG_DEF_USE"],
)
retriever = MultiHopRetriever(graph_store, config)
result = await retriever.retrieve("how is user data validated?")
# result.nodes, result.edges, result.execution_time_ms
3. G-Generation¶
Builds prompts with graph context:
from victor.core.graph_rag import GraphAwarePromptBuilder, PromptConfig
builder = GraphAwarePromptBuilder()
prompt = builder.build_prompt(
query="explain the authentication flow",
subgraphs=result.subgraphs,
config=PromptConfig(format="hierarchical"),
)
Tools¶
graph_semantic_search Tool¶
Query your codebase using natural language:
from victor.tools.graph_query_tool import graph_semantic_search
result = await graph_semantic_search(
query="database connection handling",
path="/path/to/code",
mode="semantic", # semantic, structural, hybrid
max_hops=2,
)
impact_analysis Tool¶
Analyze downstream/upstream dependencies:
from victor.tools.graph_query_tool import impact_analysis
# Forward impact (what depends on this?)
result = await impact_analysis(
target="validate_user",
analysis_type="forward",
max_depth=3,
path="/path/to/code",
)
# Backward impact (what does this depend on?)
result = await impact_analysis(
target="handle_request",
analysis_type="backward",
max_depth=2,
path="/path/to/code",
)
Configuration¶
Settings¶
Add to your settings.yaml:
search:
graph:
# CCG Building
enable_ccg: true
ccg_languages:
- python
- javascript
- typescript
- go
- rust
# Graph RAG
enable_graph_rag: true
rag_seed_count: 5
rag_max_hops: 2
# Subgraph Caching
enable_subgraph_cache: true
subgraph_cache_ttl: 3600
# ADR-032 tier 3: compiler-accurate edges from offline SCIP dumps.
# Opt-in; degrades gracefully (one log line) when the toolchain is absent.
enable_precise_index: false
# Dump timeout ceiling in seconds. 0 = per-provider measured default
# (pyright 1200s, typescript 600s, rust-analyzer 120s) — those defaults
# are calibrated on small corpora; raise this for large workspaces.
precise_index_timeout_seconds: 0
# Provider selection: "auto" or an explicit provider name.
precise_index_tool: auto
Tier 3 can also be driven per-invocation from the CLI, overriding the
settings above:
victor index graph index --precise --precise-timeout 3600
# C/C++ with a build directory outside the indexed tree (optional):
victor index graph index --precise --compile-commands /path/to/build/compile_commands.json
--compile-commands PATH (or search.graph.precise_index_compile_commands) names
the scip-clang compilation database explicitly. It may sit outside the indexed
tree, but at least one entry must name a file under it; letter case is ignored on
volumes that ignore it. A relative file entry resolves against its own
directory, as scip-clang resolves it, so a database with source-relative
paths and a separate build directory is skipped rather than left to time out:
generate it from an absolute source path (cmake -S /abs/path). The database's
content digest keys the dump cache. A relative --compile-commands path
resolves against the invoking directory. A relative setting value resolves
against the indexed tree, because background refresh and watch read the
setting without an invoking directory.
Harvest health (per-provider outcome and join accounting) is printed in the
index summary and persisted to .victor/graph-index-summary.json, which
victor index graph stats surfaces afterwards.
Tier-3 toolchains (per language)¶
One provider per toolchain family; each degrades to a named outcome
(toolchain-absent, dump-failed, skip log line) and never blocks the
others. Grammars are pinned against real dumps — see ADR-032.
| Language(s) | Provider | Install | Project marker |
|---|---|---|---|
| Python | scip-python |
npm i -g scip-python |
python project |
| TypeScript/JavaScript | scip-typescript |
npm i -g scip-typescript |
tsconfig.json (root or one level down) |
| Rust | rust-analyzer |
rustup component add rust-analyzer |
Cargo.toml (root or one level down) |
| C / C++ | scip-clang |
scip-clang release binary on PATH | compile_commands.json (root, build/, one level down, or <dir>/build/<preset>/ and build/<preset>/ for CMake presets — generate with cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON or bear) |
| Java | scip-java |
scip-java launcher on PATH (needs a JDK) | pom.xml / gradle build file |
| Ruby | scip-ruby |
gem install scip-ruby (run as bundle exec scip-ruby) |
Gemfile with the scip-ruby gem in it, bundled |
| Go | scip-go |
go install github.com/scip-code/scip-go/cmd/scip-go@latest |
go.mod (root or one level down) |
Notes:
- scip-clang filters documents to its CWD — victor always runs it from
the repo root, so dumps include exactly the indexed corpus.
- scip-clang never picks among equal candidates or generates a database.
Two databases at the same discovery depth skip with
ambiguous-compile-database; none skips with no-compile-database; an
explicit path that does not exist skips with compile-database-missing;
a database whose entries all name files outside the indexed tree skips
with compile-database-outside-root (it would otherwise yield an empty
index).
- scip-ruby requires the indexed project to carry the gem in its
Gemfile (the wrapper refuses direct invocation); without that setup the
harvest reports a named dump failure rather than pretending.
- Scala has no verifiable emitter in scip-java 0.13.2 (sbt unsupported;
Gradle instrumentation attaches to JavaCompile only — zero shards on a
pure-Scala project). Revisit when scip-java ships Scala instrumentation.
Feature Flags¶
Enable/disable features via environment variables:
# Enable Graph RAG
export VICTOR_USE_GRAPH_RAG=true
# Enable CCG building
export VICTOR_USE_CCG=true
# Enable multi-hop retrieval
export VICTOR_USE_MULTI_HOP_RETRIEVAL=true
Performance¶
Benchmarks¶
| Operation | Target | Notes |
|---|---|---|
| CCG Building | <100ms/file | Per 100-line file |
| Multi-hop Retrieval | <500ms | 2-hop query |
| Graph Query | <200ms | Symbol search |
| Subgraph Cache Hit | <50ms | Cached retrieval |
Optimization Tips¶
- Enable subgraph caching for frequently-accessed code
- Limit CCG languages to only what you need
- Use semantic mode for conceptual queries
- Use structural mode for dependency analysis
- Adjust max_hops based on codebase size
Advanced Features¶
Requirement Graph¶
Map requirements to code symbols:
from victor.core.graph_rag.requirement_graph import RequirementGraphBuilder
req_builder = RequirementGraphBuilder(graph_store)
symbols = await req_builder.map_requirement(
requirement="User should be able to reset password via email",
)
Graph-Aware Embeddings¶
Generate embeddings that capture structure:
from victor.processing.graph_embeddings import GraphAwareEmbedder
embedder = GraphAwareEmbedder()
embedding = await embedder.embed_with_context(
node=graph_node,
graph=code_context_graph,
)
Graph Algorithms¶
Apply NetworkX algorithms:
from victor.processing.graph_algorithms import compute_all_metrics
# nodes and edges are lists of GraphNode and GraphEdge from the indexed graph.
metrics = compute_all_metrics(nodes, edges)
central_nodes = metrics.pagerank
communities = metrics.communities
These helpers operate on explicit node/edge lists. There is no GraphAlgorithmRunner
API. NetworkX is optional; inspect the helper's fallback behavior before relying on
an algorithm-specific result.
Schema Reference¶
GraphNode Fields¶
| Field | Type | Description |
|---|---|---|
node_id |
str | Unique identifier |
type |
str | function, class, statement, requirement |
name |
str | Symbol name |
file |
str | Source file path |
line |
int | Start line number |
ast_kind |
str | Tree-sitter node kind (CCG) |
scope_id |
str | Hierarchical scope (CCG) |
statement_type |
str | Statement category (CCG) |
requirement_id |
str | Linked requirement (new) |
GraphEdge Fields¶
| Field | Type | Description |
|---|---|---|
src |
str | Source node ID |
dst |
str | Destination node ID |
type |
str | Edge type (see EdgeType enum) |
weight |
float | Optional weight (0-1) |
Migration¶
v4 → v5 Schema Migration¶
The schema migration is automatic on first run after upgrade:
-- New CCG columns
ALTER TABLE graph_node ADD COLUMN ast_kind TEXT;
ALTER TABLE graph_node ADD COLUMN scope_id TEXT;
ALTER TABLE graph_node ADD COLUMN statement_type TEXT;
-- New tables
CREATE TABLE graph_requirement (...);
CREATE TABLE graph_subgraph (...);
No manual intervention required. Existing data is preserved.
Troubleshooting¶
CCG Building Fails¶
Issue: CCG building fails for certain files
Solution: Check that Tree-sitter parsers are installed for your language:
# Install the Python embedding/grammar dependencies used by Victor
pip install "victor-ai[embeddings]"
# Re-run indexing and inspect its skipped-file/parser diagnostics
victor graph index --path /path/to/code --ccg --force
Slow Multi-Hop Queries¶
Issue: Retrieval takes longer than expected
Solution:
- Reduce max_hops parameter
- Enable subgraph caching
- Limit query to specific directories
Missing Dependencies¶
Issue: Import errors for graph modules
Solution: Install optional dependencies:
Contributing¶
Adding New Edge Types¶
- Add to
victor/storage/graph/edge_types.py:
-
Update builder to create edges
-
Add tests for new edge type
Adding New Languages¶
- Add Tree-sitter parser to
ccg_builder.py - Implement language-specific mappings
- Add tests for new language