# How the Memory Loop Feature in code-review-graph Persists Q&A Results

> Discover how the memory loop feature in code-review-graph saves Q&A results as markdown files. Learn to persist and reuse historical answers effectively.

- Repository: [Tirth Kanani/code-review-graph](https://github.com/tirth8205/code-review-graph)
- Tags: internals
- Published: 2026-07-22

---

**The memory loop feature in code-review-graph persists Q&A results by saving them as markdown files with YAML front-matter in a local `.code-review-graph/memory/` directory, enabling future retrieval and contextual reuse of historical answers.**

The memory loop is a built-in persistence mechanism in the `tirth8205/code-review-graph` repository that records questions, answers, and related graph nodes from MCP (Model-Center-Proxy) interactions. This feature ensures every query interaction is permanently stored within the repository, allowing the system to re-ingest historical data and enrich subsequent analysis without redundant computation.

## How the Memory Loop Works

When a user queries the system (e.g., "What types does this function return?"), the query handler invokes the persistence layer to create a durable record of the exchange. The implementation in [`code_review_graph/memory.py`](https://github.com/tirth8205/code-review-graph/blob/main/code_review_graph/memory.py) handles file I/O, serialization, and retrieval operations.

### Storage Location and File Structure

By default, the memory loop creates a hidden directory at `<repo-root>/.code-review-graph/memory/` to store all persisted interactions. As implemented in lines 36-44 of [`memory.py`](https://github.com/tirth8205/code-review-graph/blob/main/memory.py), the system determines the storage location by checking for a custom `memory_dir` parameter, falling back to the repository-local path if none is provided.

Each memory is stored as an individual markdown file containing:
- **YAML front-matter** with metadata including result type, Unix timestamp, and optional related node identifiers
- **Question text** as a level-1 heading
- **Answer body** as the document content

### The Persistence Process

The `save_result` function orchestrates the write operation through four distinct steps:

1. **Path resolution** – Constructs the storage directory path (lines 36-44)
2. **Filename generation** – Slugifies the question text and appends a Unix timestamp to create a unique identifier (lines 47-52)
3. **File writing** – Serializes the data to markdown format with YAML front-matter (lines 53-69)
4. **Debug logging** – Records the final file path for operational visibility (line 73)

## Core API Functions in memory.py

The [`code_review_graph/memory.py`](https://github.com/tirth8205/code-review-graph/blob/main/code_review_graph/memory.py) module exposes three primary functions that constitute the memory loop feature.

### save_result

The `save_result` function creates persistent records of Q&A interactions. It accepts the question string, answer text, optional related node identifiers, result type classification, and repository root path. This function implements the file generation logic described in lines 36-73.

### list_memories

The `list_memories` function enables retrieval of historical interactions. Scanning the memory directory (lines 77-118), it parses each markdown file's front-matter, extracts the question heading from the document body, and returns a list of dictionaries containing `timestamp`, `question`, `type`, and other metadata. This supports querying past interactions like "What did we answer about X last week?"

### clear_memories

The `clear_memories` function provides maintenance capabilities by removing all stored markdown files from the memory directory (lines 121-142). It returns the count of deleted files, useful for cleanup operations or privacy compliance.

## Practical Usage Examples

Implementing the memory loop feature requires only a few lines of Python code.

### Saving a Query Result

Persist a question-answer pair with related graph nodes:

```python
from pathlib import Path
from code_review_graph.memory import save_result

repo_root = Path.cwd()                     # your repository root

question = "What is the return type of `foo()`?"
answer = "`foo()` returns a `Result[int, Error]`."
related_nodes = ["my_pkg.foo", "my_pkg.errors.Error"]

save_result(
    question,
    answer,
    nodes=related_nodes,
    result_type="query",
    repo_root=repo_root,
)

```

### Listing Historical Memories

Retrieve all persisted Q&A results for review or context building:

```python
from code_review_graph.memory import list_memories

memories = list_memories(repo_root=Path.cwd())
for m in memories:
    print(f"{m['timestamp']}: {m['question']} ({m.get('type')})")

```

### Clearing the Memory Loop

Remove all stored memories when starting fresh or clearing sensitive data:

```python
from code_review_graph.memory import clear_memories

deleted = clear_memories(repo_root=Path.cwd())
print(f"Removed {deleted} memory files.")

```

## Benefits of the Memory Loop Feature

The file-based persistence system provides several architectural advantages for code review workflows:

- **Searchable archive** – Every Q&A exchange is recorded as a text file, enabling grep-based searching or indexing by external tools
- **Contextual continuity** – Subsequent queries can reference historical answers, enriching the graph's knowledge base with accumulated insights
- **Computational efficiency** – Previously computed answers can be reused rather than re-executing expensive graph traversals or analysis operations

## Summary

- The memory loop feature in code-review-graph persists Q&A results as markdown files in `.code-review-graph/memory/` via the `save_result` function in [`memory.py`](https://github.com/tirth8205/code-review-graph/blob/main/memory.py)
- Each file contains YAML front-matter with metadata and the full question-answer content, with filenames generated from slugified questions plus timestamps
- The `list_memories` function parses these files to enable retrieval and re-ingestion of historical interactions
- `clear_memories` provides bulk deletion capabilities for maintenance or privacy requirements
- This persistence mechanism supports building searchable archives, providing query context, and reducing redundant computation

## Frequently Asked Questions

### How does the memory loop feature store data physically?

The memory loop creates individual markdown files in a repository-local directory at `.code-review-graph/memory/`. Each file contains YAML front-matter metadata followed by the question as a markdown heading and the answer body. Files are named using a combination of the slugified question text and a Unix timestamp to ensure uniqueness.

### Can I specify a custom location for the memory loop storage?

Yes. While the default location is `<repo>/.code-review-graph/memory/`, the `save_result`, `list_memories`, and `clear_memories` functions all accept an optional `memory_dir` parameter. When provided, this path overrides the default directory resolution logic implemented in lines 36-44 of [`memory.py`](https://github.com/tirth8205/code-review-graph/blob/main/memory.py).

### What is the performance impact of the memory loop feature?

The memory loop uses simple file I/O operations with minimal overhead. Since each Q&A result is stored as a separate markdown file, read operations via `list_memories` scale linearly with the number of historical queries. For repositories with thousands of interactions, consider periodic cleanup using `clear_memories` or implementing external indexing on the `.code-review-graph/memory/` directory.

### How can I retrieve specific memories programmatically?

Use the `list_memories` function from [`code_review_graph/memory.py`](https://github.com/tirth8205/code-review-graph/blob/main/code_review_graph/memory.py), which scans the memory directory and returns a list of dictionaries containing parsed metadata. Each dictionary includes the `timestamp`, `question` text, result `type`, and optional node references, allowing you to filter results in Python or display them in review interfaces.