How to Optimize Code Using Code-Graph-RAG's AI-Powered CLI

The cgr optimize command runs an AI-assisted, language-aware refactoring pipeline that analyzes your repository's knowledge graph, detects anti-patterns, and applies approved optimizations through an interactive CLI workflow.

Code-Graph-RAG (cgr) ships with a dedicated optimize sub-command that transforms static code analysis into actionable refactoring. As implemented in vitali87/code-graph-rag, this tool leverages a multi-stage pipeline to identify performance bottlenecks and style violations across Python, JavaScript, Java, Rust, and other supported languages, presenting each suggestion for explicit developer approval before modification.

Understanding the Five-Stage Optimization Pipeline

The optimization logic is orchestrated by main_optimize_async in codebase_rag/main.py (lines 1752–1760), which implements the workflow documented in docs/guide/code-optimization.md. The pipeline follows a strict "analyze-suggest-approve-apply" loop:

Analysis Phase

The agent constructs a knowledge graph of your repository using the same parsers that power normal indexing. This graph captures module dependencies, function call hierarchies, and data flow patterns, providing the structural context required for intelligent refactoring.

Pattern Recognition

The system scans the graph for common anti-patterns, including unnecessary memory allocations, duplicated logic blocks, and computationally expensive loops. These patterns are identified through static analysis rules that operate on the graph representation rather than raw text.

Best-Practices Application

Language-specific optimization rules (Python, JavaScript, Rust, etc.) are applied against the detected patterns. When you supply a --reference-document, such as an internal ARCHITECTURE.md, the optimizer aligns its suggestions with your project-specific style guide.

Interactive Approval

Each optimization suggestion is presented in the console with explanatory diffs. You must explicitly confirm (y/n) before any file modification occurs. Type exit or quit to terminate the session prematurely without applying pending changes.

Guided Implementation

Approved changes are written to disk with full diff output, preserving project history. The codebase_rag/graph_updater.py module automatically refreshes embeddings and updates the Memgraph database to keep the knowledge graph synchronized with the newly optimized code.

CLI Entry Point and Command Structure

The optimize command is registered in codebase_rag/cli.py (lines 57–63) using Typer:

@app.command(
    help=ch.CMD_OPTIMIZE,
    short_help=ch.CMD_OPTIMIZE,
    epilog=ch.EXAMPLES_OPTIMIZE,
    rich_help_panel=ch.PANEL_USE,
)
def optimize(...):
    ...

When invoked, the CLI validates model configurations early through validate_models_early (lines 75–84) before delegating execution to main_optimize_async.

Configuration Options for Advanced Optimization

Reference Documentation

Supply --reference-document to ground the LLM in your team's architectural standards. This is particularly effective for enforcing internal naming conventions, API usage patterns, or specific design patterns documented in markdown files.

Model Orchestration

The --orchestrator flag allows you to specify any LLM that implements the orchestrator role, such as google:gemini-3.6-flash. The system validates model availability and API credentials before beginning the optimization session.

Batch Size Control

Use --batch-size to override the default Memgraph flush size. This parameter controls how many graph entities are processed in each batch during the initial analysis phase, which is useful for memory-constrained environments or massive codebases.

Practical Usage Examples

Run a basic Python optimization across your entire project:

cgr optimize python --repo-path /path/to/my/python/project

Optimize a Java repository while enforcing a custom style guide:

cgr optimize java \
    --repo-path /path/to/java/repo \
    --reference-document ./ARCHITECTURE.md

Use a specific LLM model for JavaScript optimization with increased batch processing:

cgr optimize javascript \
    --repo-path ./frontend \
    --orchestrator google:gemini-3.6-flash \
    --batch-size 5000

During an interactive session, you will see output similar to:


Starting python optimization session...
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ The agent will analyze your python codebase and propose specific          ┃
┃ optimizations. You'll be asked to approve each suggestion before          ┃
┃ implementation. Type 'exit' or 'quit' to end the session.                 ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
Analyzing codebase structure...
Found 23 Python modules with potential optimizations

Optimization Suggestion #1:
   File: src/data_processor.py
   Issue: Using list comprehension in a loop can be optimized
   Suggestion: Replace with generator expression for memory efficiency

[y/n] Do you approve this optimization?

Key Source Files and Backend Services

The optimization capability relies on several core components:

Summary

  • Use cgr optimize <language> to initiate AI-assisted refactoring for Python, JavaScript, Java, Rust, and other supported languages.
  • The pipeline runs in five stages: graph-based Analysis, Pattern Recognition, Best-Practices Application, Interactive Approval, and Guided Implementation.
  • Control the process with --reference-document for style alignment, --orchestrator for model selection, and --batch-size for performance tuning.
  • All changes require explicit approval through an interactive CLI prompt before files are modified.
  • Core implementation resides in codebase_rag/main.py (main_optimize_async) and codebase_rag/cli.py (command registration and validation).

Frequently Asked Questions

What languages does Code-Graph-RAG support for optimization?

Code-Graph-RAG supports Python, JavaScript, Java, Rust, and other languages through its extensible parser architecture. The optimize command accepts the language identifier as its first positional argument (e.g., cgr optimize python), and the system applies language-specific best-practice rules accordingly.

How does the interactive approval process work during optimization?

When main_optimize_async identifies an optimization opportunity, it renders a detailed description in the terminal showing the file path, the detected issue, and the proposed fix. You must input y to apply the change or n to skip it. This prevents automated modifications without developer oversight and allows you to audit each suggestion against your codebase context.

Can I configure which LLM model performs the optimization analysis?

Yes. Pass the --orchestrator flag followed by the model identifier (such as google:gemini-3.6-flash) to route optimization analysis through a specific LLM. The CLI validates model availability early via validate_models_early in codebase_rag/cli.py (lines 75–84), ensuring API credentials are configured before the expensive graph analysis begins.

Which source files implement the optimization pipeline?

The optimization workflow is implemented across several modules: codebase_rag/cli.py (lines 57–63) registers the command; codebase_rag/main.py (lines 1752–1760) defines main_optimize_async which orchestrates the five-stage pipeline; codebase_rag/graph_updater.py handles graph reconstruction; and the backend services in codebase_rag/services/ manage graph persistence and embedding updates.

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:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →