# How to Surgically Edit Code Using Code-Graph-RAG: AST-Level Precision

> Surgically edit code with Code-Graph-RAG. Transform natural language edits into precise AST-level diffs and apply minimal patches to your codebase. Learn how.

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

---

**Code-Graph-RAG enables surgical code editing by parsing your repository into an AST-backed knowledge graph in Memgraph, allowing you to submit natural-language edit requests that get translated into precise, previewable diffs before applying minimal patches to source files.**

Code-Graph-RAG (from the `vitali87/code-graph-rag` repository) provides an agentic interface for modifying codebases at the abstract syntax tree level. This approach ensures that when you surgically edit code using Code-Graph-RAG, changes are structurally aware, preserving formatting and imports while targeting only the intended logic nodes.

## Build the Knowledge Graph Foundation

Before performing any edits, you must parse the repository into the graph database. This creates the AST representation that enables precise transformations.

Start the required services and index your codebase:

```bash
cgr daemon up                     # launches Memgraph + Qdrant

cgr start --repo-path /my/project --update-graph   # parses the repo

```

The `--update-graph` flag ensures the full AST and relationships are stored in Memgraph, creating the foundation for surgical modifications.

## CLI-Based Surgical Editing Workflow

The primary interface for editing is the `cgr edit` command, which translates natural language into AST transformations.

### Submit an Edit Request

Describe the change you want in plain English:

```bash
cgr edit "Replace the for‑loop in utils.py that builds a list of squares with a list comprehension"

```

The system queries the knowledge graph to locate the specific AST nodes, generates a transformation, and prints a diff preview:

```diff
--- a/utils.py
+++ b/utils.py
@@ -12,7 +12,5 @@
- squares = []
- for i in range(10):
-     squares.append(i*i)
+ squares = [i*i for i in range(10)]

```

### Preview Changes with Dry-Run

Review modifications without touching the filesystem:

```bash
cgr edit --dry-run "Rename function `old_name` to `new_name` in module foo.py"

```

This mode is essential for validating that the agent correctly interpreted your intent before any files are modified.

### Apply the Patch

After reviewing the diff, confirm the change:

```bash
cgr edit --apply   # CLI prompts for confirmation before writing

```

Code-Graph-RAG writes minimal patches that preserve surrounding formatting, comments, and import statements.

## Programmatic Editing with the Python SDK

For automation or integration into larger workflows, use the Python SDK to surgically edit code using Code-Graph-RAG programmatically.

```python
from codebase_rag.graph_loader import GraphLoader
from codebase_rag.cgr_state import CgrState

loader = GraphLoader(uri="bolt://localhost:7687")
state = CgrState(loader)

# Generate an edit request

edit_query = "Replace the recursive call in `factorial` with an iterative loop"
diff = state.propose_edit(edit_query)   # returns a diff string

print(diff)                             # review before applying

state.apply_edit(diff)                  # applies the patch to source

```

The `CgrState` class in [`codebase_rag/cgr_state.py`](https://github.com/vitali87/code-graph-rag/blob/main/codebase_rag/cgr_state.py) maintains graph state and coordinates edit proposals, while `propose_edit()` generates the diff and `apply_edit()` executes the transformation.

## Architecture of AST-Based Transformations

Understanding the core components demonstrates how Code-Graph-RAG achieves surgical precision:

- **[`codebase_rag/cli.py`](https://github.com/vitali87/code-graph-rag/blob/main/codebase_rag/cli.py)** – Parses the `edit` sub-command and forwards natural language requests to the agent.
- **[`codebase_rag/cgr_state.py`](https://github.com/vitali87/code-graph-rag/blob/main/codebase_rag/cgr_state.py)** – Records the current graph state and prepares edit proposals by coordinating between the knowledge graph and transformation engine.
- **[`codebase_rag/decorators.py`](https://github.com/vitali87/code-graph-rag/blob/main/codebase_rag/decorators.py)** – Contains the decorator logic that wraps generated edit functions and creates AST-based diffs, ensuring structural integrity during transformations.

This architecture supports multiple languages including Python, JavaScript, Rust, Go, Java, C/C++, C#, PHP, Lua, and Dart, applying the same AST-level safety across diverse codebases.

Documentation references:
- **CLI Reference**: Detailed `edit` command usage at [`docs/guide/cli-reference.md`](https://github.com/vitali87/code-graph-rag/blob/main/docs/guide/cli-reference.md)
- **Interactive Querying**: Natural-language to Cypher translation at [`docs/guide/interactive-querying.md`](https://github.com/vitali87/code-graph-rag/blob/main/docs/guide/interactive-querying.md)

## Summary

- **Build the graph** first with `cgr start` to enable AST-aware operations
- **Use natural language** via `cgr edit` to request changes, then review the generated diff
- **Leverage `--dry-run`** to preview modifications without risk, then `--apply` to confirm
- **Access programmatically** through the Python SDK using `CgrState.propose_edit()` and `apply_edit()`
- **Trust AST precision**—the system modifies specific nodes rather than performing text-based find-and-replace, preserving formatting and imports

## Frequently Asked Questions

### What makes Code-Graph-RAG "surgical" compared to traditional find-and-replace?

Traditional text replacement operates on strings and can accidentally modify comments, strings, or similar variable names across scopes. Code-Graph-RAG operates on the abstract syntax tree, targeting specific semantic nodes (loops, functions, classes) while preserving formatting, import order, and comments. The transformation logic in [`codebase_rag/decorators.py`](https://github.com/vitali87/code-graph-rag/blob/main/codebase_rag/decorators.py) ensures only the intended AST nodes are modified.

### Which programming languages support surgical editing?

Code-Graph-RAG supports surgical editing for Python, JavaScript, Rust, Go, Java, C/C++, C#, PHP, Lua, Dart, and more. The AST parser creates language-specific node representations in Memgraph, allowing the agent to understand each language's grammar and scope rules when generating transformations.

### How does the diff preview ensure safety before applying changes?

When you run `cgr edit` or `state.propose_edit()`, the system generates a complete diff showing exact line additions and removals without writing to disk. This preview reveals exactly which AST nodes are being replaced, added, or removed, allowing you to verify semantic correctness before using `--apply` or `state.apply_edit()` to commit changes.

### Can I integrate Code-Graph-RAG into automated CI/CD pipelines?

Yes. While the CLI supports interactive confirmation flows, the Python SDK (`CgrState` and `GraphLoader` classes) enables fully automated surgical editing. You can script edit proposals, apply conditional logic based on the generated diff content, and programmatically apply patches using `state.apply_edit()`, making it suitable for automated refactoring tasks in CI/CD environments.