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

> Optimize code with Code-Graph-RAG's AI powered CLI. Analyze your repo knowledge graph, detect anti-patterns, and apply optimizations interactively.

- Repository: [Vitali Avagyan/code-graph-rag](https://github.com/vitali87/code-graph-rag)
- Tags: how-to-guide
- Published: 2026-08-19

---

**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`](https://github.com/vitali87/code-graph-rag/blob/main/codebase_rag/main.py) ([lines 1752–1760](https://github.com/vitali87/code-graph-rag/blob/main/codebase_rag/main.py#L1752-L1760)), which implements the workflow documented in [`docs/guide/code-optimization.md`](https://github.com/vitali87/code-graph-rag/blob/main/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`](https://github.com/vitali87/code-graph-rag/blob/main/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`](https://github.com/vitali87/code-graph-rag/blob/main/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`](https://github.com/vitali87/code-graph-rag/blob/main/codebase_rag/cli.py) ([lines 57–63](https://github.com/vitali87/code-graph-rag/blob/main/codebase_rag/cli.py#L57-L63)) using Typer:

```python
@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](https://github.com/vitali87/code-graph-rag/blob/main/codebase_rag/cli.py#L75-L84)) 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:

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

```

Optimize a Java repository while enforcing a custom style guide:

```bash
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:

```bash
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:

- **[`codebase_rag/cli.py`](https://github.com/vitali87/code-graph-rag/blob/main/codebase_rag/cli.py)** – Defines the Typer command-line interface and handles early model validation.
- **[`codebase_rag/main.py`](https://github.com/vitali87/code-graph-rag/blob/main/codebase_rag/main.py)** – Contains `main_optimize_async`, the primary async orchestrator that coordinates graph analysis and LLM interaction.
- **[`codebase_rag/graph_updater.py`](https://github.com/vitali87/code-graph-rag/blob/main/codebase_rag/graph_updater.py)** – Manages graph construction and synchronization after code modifications.
- **[`codebase_rag/services/protobuf_service.py`](https://github.com/vitali87/code-graph-rag/blob/main/codebase_rag/services/protobuf_service.py)** and **[`codebase_rag/services/graph_service.py`](https://github.com/vitali87/code-graph-rag/blob/main/codebase_rag/services/graph_service.py)** – Backend services responsible for persisting the knowledge graph and embeddings used during the optimization process.

## 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`](https://github.com/vitali87/code-graph-rag/blob/main/codebase_rag/main.py) (`main_optimize_async`) and [`codebase_rag/cli.py`](https://github.com/vitali87/code-graph-rag/blob/main/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`](https://github.com/vitali87/code-graph-rag/blob/main/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`](https://github.com/vitali87/code-graph-rag/blob/main/codebase_rag/cli.py) (lines 57–63) registers the command; [`codebase_rag/main.py`](https://github.com/vitali87/code-graph-rag/blob/main/codebase_rag/main.py) (lines 1752–1760) defines `main_optimize_async` which orchestrates the five-stage pipeline; [`codebase_rag/graph_updater.py`](https://github.com/vitali87/code-graph-rag/blob/main/codebase_rag/graph_updater.py) handles graph reconstruction; and the backend services in `codebase_rag/services/` manage graph persistence and embedding updates.