<!-- source: https://deepwiki.com/qhkm/zeptoclaw/9-memory-and-context -->

# Memory and Context

- src/memory/bm25_searcher.rs
- src/memory/builtin_searcher.rs
- src/memory/factory.rs
- src/memory/mod.rs
- src/memory/traits.rs

This document covers ZeptoClaw's dual memory systems and context management mechanisms. It explains how the agent maintains conversation state, retrieves relevant information, assembles prompts for LLM calls, and handles context window overflow.

**Scope**: This page provides an architectural overview of memory storage, retrieval, context building, and session management. For implementation details, see:

- Memory Systems — LongTermMemory , WorkspaceMemory , memory backends (BM25, embedding, HNSW, Tantivy, QMD), and injection.
- Context Management — ContextBuilder , system prompts, skills injection, runtime context, and memory override mechanism.
- Context Overflow and Compaction — Three-tier compaction (Normal/Emergency/Critical), memory flush, and session repair.
- Session Management — SessionManager , session keys, persistence, discovery, cleanup, and in-memory vs file backends.

## Overview

ZeptoClaw maintains two independent memory systems:

Context for each LLM call is assembled by `ContextBuilder` which combines:

1. System prompt (agent template + runtime context)
2. Skills (markdown instructions)
3. Memory injection (query-matched LongTermMemory entries)
4. Conversation history (messages from SessionManager )
5. Current user message

Token usage is tracked by `TokenBudget` and monitored by `ContextMonitor`. When thresholds are exceeded, `Compactor` reduces context size through summarization or truncation.

**Sources**: [src/memory/mod.rs1-35](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/memory/mod.rs#L1-L35) [src/memory/traits.rs1-20](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/memory/traits.rs#L1-L20)

## Memory and Context Architecture

```

```

**Diagram: Memory and Context System Components**

This diagram shows the storage layers (`LongTermMemory`, `WorkspaceMemory`, `SessionManager`), pluggable search backends (`MemorySearcher` trait implementations), and context assembly via `ContextBuilder`.

**Sources**: [src/memory/mod.rs75-101](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/memory/mod.rs#L75-L101) [src/memory/factory.rs1-15](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/memory/factory.rs#L1-L15)

## Context Building Pipeline

```

```

**Diagram: Context Assembly for LLM Call**

This diagram traces how an `InboundMessage` is combined with session history, memory injection, and system prompts. Token estimation happens to determine if compaction is needed.

**Sources**: [src/memory/mod.rs34-35](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/memory/mod.rs#L34-L35) [src/memory/builtin_searcher.rs42-71](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/memory/builtin_searcher.rs#L42-L71)

## Memory Systems

ZeptoClaw supports two memory systems with pluggable search backends:

### LongTermMemory

Persistent key-value store providing cross-session persistence for facts and preferences.

- Categories : Organize entries (e.g., user , fact , learning ).
- Decay : Entries decay over time, scaled by importance.
- Pinning : Entries in the "pinned" category are exempt from decay.
- Injection Guard : Updates are validated against prompt injection patterns.

### WorkspaceMemory

Markdown file search in workspace directories using the `MemorySearcher` trait.

- Chunking : Files are processed in chunks of 18 lines ( CHUNK_LINES ) with a 4-line overlap ( CHUNK_OVERLAP ) src/memory/mod.rs 29-30
- Budget : Memory injection into system prompts is limited to MEMORY_INJECTION_BUDGET (~2000 characters) src/memory/mod.rs 35

### Search Backends

Searchers are created via `factory::create_searcher_with_provider` [src/memory/factory.rs33-36](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/memory/factory.rs#L33-L36) and implement the `MemorySearcher` trait [src/memory/traits.rs12-40](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/memory/traits.rs#L12-L40)

**Sources**: [src/memory/mod.rs3-14](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/memory/mod.rs#L3-L14) [src/memory/traits.rs12-40](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/memory/traits.rs#L12-L40) [src/memory/factory.rs37-99](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/memory/factory.rs#L37-L99)

## Context Management

### ContextBuilder

Assembles the final message array for LLM calls. It integrates system prompts, skills, and memory snippets.

### Memory Injection

- Selection Strategy : search_workspace_memory_sync uses MemorySearcher::score to rank snippets src/memory/mod.rs 155
- Citations : Optionally includes citations in the format path#Lx-Ly via format_citation src/memory/mod.rs 168-170
- Format : Snippets are truncated to a configurable max_snippet_chars (minimum 64) src/memory/mod.rs 127-166

### Hygiene and Snapshots

- Hygiene : Periodic cleanup of stale entries based on decay scores and max_entries limits, configured via HygieneConfig src/memory/hygiene.rs 18-29
- Snapshots : export_snapshot and import_snapshot allow backup and migration of LongTermMemory as JSON src/memory/snapshot.rs 31-91

**Sources**: [src/memory/mod.rs123-130](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/memory/mod.rs#L123-L130) [src/memory/snapshot.rs31-53](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/memory/snapshot.rs#L31-L53)

## Tool Result Memory Flow

```

```

**Diagram: Tool Result to Memory Cycle**

This diagram shows how tool execution results flow into session history and long-term memory.

**Sources**: [src/memory/mod.rs75-101](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/memory/mod.rs#L75-L101)

## Memory Tool Interface

## CLI Reference

The `memory` CLI command provides direct management of the long-term store:

- list : Enumerate entries by category.
- search : Query the store using LongTermMemory::search .
- cleanup : Remove expired entries below a threshold.
- export / import : Manage snapshots.

**Sources**: [src/memory/snapshot.rs31-91](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/memory/snapshot.rs#L31-L91)
