<!-- source: https://deepwiki.com/qhkm/zeptoclaw/9.1-memory-systems -->

# Memory Systems

- src/cli/memory.rs
- src/memory/bm25_searcher.rs
- src/memory/builtin_searcher.rs
- src/memory/embedding_searcher.rs
- src/memory/factory.rs
- src/memory/hnsw_searcher.rs
- src/memory/hygiene.rs
- src/memory/longterm.rs
- src/memory/mod.rs
- src/memory/snapshot.rs
- src/memory/traits.rs
- src/tools/longterm_memory.rs

This page documents ZeptoClaw's memory subsystems: `LongTermMemory` (persistent key-value store), `WorkspaceMemory` (markdown search), and the pluggable search backends (BM25, Builtin, Embedding, HNSW). It covers storage formats, decay scoring algorithms, memory injection into agent context, and CLI/tool interfaces for memory management.

## Architecture Overview

ZeptoClaw implements a multi-layered memory architecture. Memory search uses a pluggable backend architecture via the `MemorySearcher` trait [src/memory/traits.rs12-40](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/memory/traits.rs#L12-L40)

### Memory System Components

```

```

**Sources:**

- src/memory/mod.rs 29-52
- src/memory/longterm.rs 71-113
- src/memory/traits.rs 12-40
- src/memory/factory.rs 33-100
- src/memory/longterm.rs 137-143 (Injection Guard)

## Long-Term Memory Store

The `LongTermMemory` class provides a persistent JSON-backed store for facts and preferences. It is stored at `~/.zeptoclaw/memory/longterm.json` [src/memory/longterm.rs3-5](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/memory/longterm.rs#L3-L5)

### Memory Entry Structure

A `MemoryEntry` contains metadata used for both retrieval and maintenance [src/memory/longterm.rs35-54](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/memory/longterm.rs#L35-L54)

### Decay and Scoring

Memories (unless in the "pinned" category) decay over time to prioritize fresh information [src/memory/longterm.rs60-69](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/memory/longterm.rs#L60-L69)

- Half-life: 50% decay every 30 days.
- Pinned: Entries with category: "pinned" (case-insensitive) always return a score of 1.0 src/memory/longterm.rs 61-63

### Injection Protection

The `set()` method passes all values through `sanitizer::check_injection` [src/memory/longterm.rs137-143](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/memory/longterm.rs#L137-L143) If a prompt injection pattern (like role markers "system:") is detected, the write is rejected to prevent memory poisoning.

### Hygiene and Maintenance

ZeptoClaw performs periodic cleanup via the `HygieneConfig` [src/memory/hygiene.rs16-29](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/memory/hygiene.rs#L16-L29)

- run_hygiene_cycle_memory_only : Removes expired entries and caps the total count to max_entries (default 1000) src/memory/hygiene.rs 79-113
- Scheduler : A background task checks every hour if a cycle is due based on interval_hours src/memory/hygiene.rs 120-156

**Sources:**

- src/memory/longterm.rs 35-69
- src/memory/longterm.rs 122-174
- src/memory/hygiene.rs 16-156

## Pluggable Search Backends

ZeptoClaw uses the `MemorySearcher` trait to allow different ranking strategies [src/memory/traits.rs12-40](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/memory/traits.rs#L12-L40)

### 1. BuiltinSearcher

The default, zero-dependency searcher [src/memory/builtin_searcher.rs16-40](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/memory/builtin_searcher.rs#L16-L40)

- Algorithm: score = coverage * 0.7 + density * 0.3 + phrase_bonus src/memory/builtin_searcher.rs 15
- Coverage: Percentage of query terms found in the chunk src/memory/builtin_searcher.rs 62
- Phrase Bonus: +0.25 if the exact query string exists in the chunk src/memory/builtin_searcher.rs 64-68

### 2. Bm25Searcher

A pure Rust implementation of Okapi BM25 scoring [src/memory/bm25_searcher.rs32-35](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/memory/bm25_searcher.rs#L32-L35)

- Features: Maintains an inverted index of term frequencies and document lengths src/memory/bm25_searcher.rs 37-44
- Tuning: Uses standard parameters K1 = 1.2 and B = 0.75 src/memory/bm25_searcher.rs 15-16
- IDF: Penalizes common terms across the memory corpus using logarithmic weighting src/memory/bm25_searcher.rs 122-128

### 3. EmbeddingSearcher

Uses LLM providers to generate vector representations of text [src/memory/embedding_searcher.rs48-52](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/memory/embedding_searcher.rs#L48-L52)

- Cosine Similarity: Ranks chunks by vector similarity src/memory/embedding_searcher.rs 113-124
- Persistence: Vectors are stored in embeddings.json src/memory/embedding_searcher.rs 9
- Batching: Implements score_batch to minimize API round-trips src/memory/embedding_searcher.rs 142-174

### 4. HnswSearcher

Hierarchical Navigable Small World index for fast approximate nearest-neighbor search [src/memory/hnsw_searcher.rs183-188](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/memory/hnsw_searcher.rs#L183-L188)

- Efficiency: Provides $O(\log n)$ search time, suitable for stores with >1,000 entries src/memory/hnsw_searcher.rs 9-14
- Distance: Uses 1.0 - cosine_similarity as the distance metric src/memory/hnsw_searcher.rs 88-94

**Sources:**

- src/memory/builtin_searcher.rs 42-71
- src/memory/bm25_searcher.rs 93-139
- src/memory/embedding_searcher.rs 127-174
- src/memory/hnsw_searcher.rs 1-35
- src/memory/factory.rs 33-100

## Workspace Memory

Workspace memory allows the agent to search markdown files within its project environment.

### Data Flow: Search to Snippet

```

```

### Implementation Details

- Chunking: Files are split into windows of 18 lines with a 4-line overlap to preserve context src/memory/mod.rs 29-30
- Async Safety: IO and CPU-bound search operations are wrapped in tokio::task::spawn_blocking to prevent blocking the main executor src/memory/mod.rs 75-101
- Citations: Results can include optional citations in the format path#Lx-Ly src/memory/mod.rs 51-176

**Sources:**

- src/memory/mod.rs 75-197
- src/tools/longterm_memory.rs 205-226

## Safety and Auditing

The memory system is integrated with the security and auditing layers to detect malicious behavior.

### Dangerous Tool Chains

The `ChainTracker` monitors sequences of tool calls. One specific dangerous pattern is `longterm_memory` followed by `shell_execute`, which may indicate an attempt to exploit memory poisoning.

### Injection Guard

All writes to `LongTermMemory` are validated against `sanitizer::check_injection` [src/memory/longterm.rs137-143](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/memory/longterm.rs#L137-L143) This prevents "stored injection" where a malicious value persists in `longterm.json` and is later injected into a system prompt.

**Sources:**

- src/memory/longterm.rs 130-143

## CLI and Tool Reference

### Memory CLI ( cmd_memory )

The CLI provides administrative access to the `LongTermMemory` store [src/cli/memory.rs9-24](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/cli/memory.rs#L9-L24)

- list : Shows memories by category src/cli/memory.rs 27-57
- cleanup : Removes entries below a specific decay threshold src/cli/memory.rs 152-167
- export/import : Manages memory snapshots via src/memory/snapshot.rs src/cli/memory.rs 169-197
- stats : Displays entry counts, categories, and storage file size src/cli/memory.rs 113-150

### Agent Tools

- longterm_memory : Allows the LLM to perform set , get , search , delete , list , categories , and pin actions src/tools/longterm_memory.rs 105-117
- MemorySearcher Indexing : Stateful searchers (like Bm25Searcher ) automatically update their internal indices when the longterm_memory tool is used to set or delete entries src/memory/longterm.rs 171-201

**Sources:**

- src/cli/memory.rs 9-197
- src/tools/longterm_memory.rs 43-120
- src/memory/snapshot.rs 31-91
