How to Run Code Optimization Against Language Best Practices with Code‑Graph‑RAG
The cgr optimize command in Code‑Graph‑RAG runs LLM‑powered optimization passes across multi‑language codebases by building a Tree‑sitter knowledge graph, applying language‑specific best practices, and generating interactive AST‑preserving suggestions.
Code‑Graph‑RAG ("cgr") transforms how developers perform code optimization against language best practices. Instead of isolated linting or manual refactoring, it creates a unified knowledge graph of your entire codebase—spanning Python, JavaScript, Rust, Go, Java, C/C++, and more—then runs an AI agent that detects anti‑patterns against your chosen standards. This article walks through the complete optimization workflow, from parsing to interactive approval.
Parsing and Graph Construction
Every optimization run starts with Tree‑sitter powered parsing. The system walks every source file in your repository and extracts:
- Functions and classes with their signatures
- Modules and file boundaries
- Import relationships between components
- Call graphs showing execution flow
These extracted AST nodes feed into Memgraph under a unified schema. The graph stores Function, Class, and Module nodes, connected by CALLS and IMPORTS edges. According to the README.md in vitali87/code-graph-rag, this structure "stores the result as an interconnected graph."
This language‑agnostic representation is what enables cross‑language optimization. A Python function calling into a Java library can be analyzed as a single connected component, ensuring recommendations respect the full execution context.
The Optimization Agent Workflow
The cgr optimize command launches a five‑phase workflow:
1. Graph Analysis
codebase_rag/graph_updater.py loads the Memgraph instance and provides traversal utilities. The agent queries the graph to understand codebase structure—identifying hot paths, deeply nested call chains, and modules with high coupling.
2. Pattern Recognition
Implemented in codebase_rag/flow_verdict.py, this phase combines heuristics with LLM prompts to identify:
- Performance hotspots (inefficient loops, memory‑heavy constructs)
- Style violations against language idioms
- Architectural anti‑patterns (circular imports, god classes)
3. Best‑Practice Application
The agent ingests language‑specific best‑practice documentation at runtime. Provide a custom reference document via the --reference-document flag, or rely on built‑in guidance. The LLM uses this context to generate suggestions that align with your standards—not generic fixes.
4. Interactive Approval
Each suggestion appears with a full context diff. You respond with:
y— apply the changen— skip to next suggestionquit— end the session
This loop lives in codebase_rag/flow_verdict.py, ensuring you maintain control over every modification.
5. AST‑Based Rewrite
Approved changes execute through codebase_rag/decorators.py helpers, which perform AST‑preserving transformations. The system generates a preview diff, rewrites the source file, and updates the graph so subsequent passes see the new structure.
Command‑Line Usage Examples
Run optimization for a Python project using default settings:
cgr optimize python --repo-path /path/to/my_repo
Enforce a custom architectural guide on Java code:
cgr optimize java \
--repo-path /path/to/java_repo \
--reference-document ./ARCHITECTURE.md
Optimize JavaScript with a specific LLM provider and batch configuration:
cgr optimize javascript \
--repo-path /path/to/frontend \
--orchestrator google:gemini-3.6-flash \
--batch-size 5000
During execution, you'll see interactive output like:
Starting python optimisation session...
Analyzing codebase structure...
Found 23 Python modules with potential optimisations
Optimization Suggestion #1:
File: src/data_processor.py
Issue: List comprehension inside a loop – memory heavy
Suggestion: Replace with a generator expression
[y/n] Do you approve this optimisation?
Cross‑Language Optimization Capabilities
Because optimization runs on the graph, not isolated file analysis, Code‑Graph‑RAG handles polyglot codebases natively. Consider a Python service calling a Rust extension module:
- The
CALLSedge links the Python function to its Rust counterpart - The agent analyzes both implementations together
- Suggestions respect Python's calling conventions and Rust's memory safety guarantees
This holistic view prevents optimizations that improve one language while breaking interop contracts.
Key Implementation Files
| File | Purpose |
|---|---|
[docs/guide/code-optimization.md](https://github.com/vitali87/code-graph-rag/blob/main/docs/guide/code-optimization.md) |
Complete user documentation for cgr optimize |
[codebase_rag/graph_updater.py](https://github.com/vitali87/code-graph-rag/blob/main/codebase_rag/graph_updater.py) |
Graph loading and traversal utilities |
[codebase_rag/flow_verdict.py](https://github.com/vitali87/code-graph-rag/blob/main/codebase_rag/flow_verdict.py) |
Core decision logic and interactive approval loop |
[codebase_rag/decorators.py](https://github.com/vitali87/code-graph-rag/blob/main/codebase_rag/decorators.py) |
Safe AST transformation helpers |
Summary
cgr optimizeruns AI‑driven optimization by combining Tree‑sitter parsing, Memgraph storage, and LLM pattern recognition.- The knowledge graph enables cross‑language analysis and preserves relationships between components.
--reference-documentlets you supply custom best‑practice standards beyond built‑in language guides.- Interactive approval with
[y/n]prompts keeps you in control of every change. - AST‑based rewrites in
codebase_rag/decorators.pyensure transformations preserve code structure and update the graph atomically.
Frequently Asked Questions
How does Code‑Graph‑RAG know which best practices to apply?
The optimization agent reads language‑specific documentation at runtime. By default, it uses embedded guidance for each supported language. You can override or extend this with the --reference-document flag, pointing to any markdown file containing your project's architectural standards or style rules.
Can I use Code‑Graph‑RAG on a codebase with multiple languages?
Yes. The unified graph schema stores nodes and edges without language‑specific typing. Python functions, Rust structs, and Java classes coexist as Function, Class, and Module nodes with standardized relationships. The optimizer traverses across language boundaries via CALLS and IMPORTS edges.
What happens if I decline an optimization suggestion?
The interactive loop in codebase_rag/flow_verdict.py simply skips to the next suggestion. Your original source remains untouched, and the graph stays unchanged. You can also type quit to exit the session entirely while preserving all previously approved changes.
Is the optimization process deterministic?
Yes, with caveats. The graph construction (Tree‑sitter parsing) and AST transformation (codebase_rag/decorators.py) are fully deterministic. LLM‑generated suggestions may vary between runs unless you pin the model version and temperature. Use --orchestrator with a fixed model identifier for reproducible outputs.
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 →