@monomind/memory

High-performance memory module for Monomind V1 - LanceDB unification, HNSW indexing, vector search, self-learning knowledge graph, and hybrid SQLite+LanceDB backend (ADR-009).
Features
- Indexed Vector Search - HNSW (Hierarchical Navigable Small World) vector index for fast similarity search
- Hybrid Backend - SQLite for structured data + LanceDB for vectors (ADR-009)
- Auto Memory Bridge - Bidirectional sync between Claude Code auto memory and LanceDB (ADR-048)
- Self-Learning - LearningBridge connects insights to the ReasoningBank pattern store (ADR-049)
- Knowledge Graph - PageRank + label propagation community detection + HippoRAG PPR re-ranking (ADR-049)
- Agent-Scoped Memory - 3-scope agent memory (project/local/user) with cross-agent knowledge transfer (ADR-049)
- Vector Quantization - Binary, scalar, and product quantization for 4-32x memory reduction
- Multiple Distance Metrics - Cosine, Euclidean, dot product, and Manhattan distance
- Query Builder - Fluent API for building complex memory queries
- Cache Manager - LRU caching with configurable size and TTL
- Migration Tools - Seamless migration from V2 memory systems
- DiskANN Backend - SSD-resident Vamana ANN graph for million-scale entry search (arXiv:2305.04359)
- A-MEM Auto-Linking - Bidirectional reference edges auto-created on store (arXiv:2409.11987)
- GraphRAG Community Retrieval - Community-level summaries annotate semantic search results (arXiv:2404.16130)
- HippoRAG PPR Re-ranking - Personalised PageRank re-ranks semantic results via knowledge graph (arXiv:2405.14831)
- Collaborative Memory Promotion - Entries auto-promoted to team scope after 3+ agent reads/24 h (arXiv:2505.18279)
- Temporal Knowledge Graph - Causal/temporal edge typing inspired by Zep/Graphiti (arXiv:2501.13956)
- Injection Filter - Structural prompt-injection detection on semantic search results (arXiv:2302.12173, arXiv:2310.12815)
Installation
npm install @monomind/memory
Quick Start
import { HNSWIndex, LanceDBAdapter, CacheManager } from '@monomind/memory';
const index = new HNSWIndex({
dimensions: 1536,
M: 16,
efConstruction: 200,
metric: 'cosine'
});
await index.addPoint('memory-1', new Float32Array(embedding));
await index.addPoint('memory-2', new Float32Array(embedding2));
const results = await index.search(queryVector, 10);
API Reference
HNSW Index
import { HNSWIndex } from '@monomind/memory';
const index = new HNSWIndex({
dimensions: 1536,
M: 16,
efConstruction: 200,
maxElements: 1000000,
metric: 'cosine',
quantization: {
type: 'scalar',
bits: 8
}
});
await index.addPoint(id: string, vector: Float32Array);
const results = await index.search(
query: Float32Array,
k: number,
ef?: number
);
const filtered = await index.searchWithFilters(
query,
k,
(id) => id.startsWith('session-')
);
await index.removePoint(id);
const stats = index.getStats();
LanceDB Adapter
import { LanceDBAdapter } from '@monomind/memory';
const adapter = new LanceDBAdapter({
dimensions: 1536,
hnswM: 16,
hnswEfConstruction: 200,
cacheEnabled: true,
cacheSize: 10000,
cacheTtl: 300000,
defaultNamespace: 'default',
embeddingGenerator: async (text) => myEmbedder.embed(text),
});
await adapter.initialize();
await adapter.store({
id: 'mem-123',
key: 'user-preference',
content: 'User prefers dark mode',
type: 'semantic',
namespace: 'preferences',
tags: ['ui'],
metadata: {},
accessLevel: 'private',
createdAt: Date.now(),
updatedAt: Date.now(),
version: 1,
references: [],
accessCount: 0,
lastAccessedAt: Date.now(),
});
const results = await adapter.semanticSearch('dark mode preference', 10, 0.7);
const entry = await adapter.storeEntry({
key: 'my-fact',
content: 'TypeScript 5+ required',
namespace: 'learnings',
type: 'semantic',
tags: ['setup'],
metadata: {},
});
Cache Manager
import { CacheManager } from '@monomind/memory';
const cache = new CacheManager<MemoryEntry>({
maxSize: 1000,
ttl: 3_600_000,
maxMemory: 50 * 1024 * 1024,
lruEnabled: true,
});
cache.set('key', entry);
const entry = cache.get('key');
const exists = cache.has('key');
cache.delete('key');
cache.clear();
await cache.prefetch(['k1', 'k2'], async (keys) => loadFromDB(keys));
const stats = cache.getStats();
cache.shutdown();
Query Builder
import { query, QueryTemplates } from '@monomind/memory';
const q = query()
.semantic('authentication patterns')
.inNamespace('security')
.withTags(['auth', 'patterns'])
.ofType('semantic')
.threshold(0.7)
.limit(20)
.sortByNewest()
.build();
const exact = query().exact('my-key', 'my-namespace').build();
const prefix = query().prefix('session-').inNamespace('sessions').build();
query().semantic('...').sortBy('accessCount', 'desc').build();
query().semantic('...').oldestFirst().build();
query().semantic('...').recentlyAccessed().build();
const recent = QueryTemplates.recentInNamespace('learnings', 10);
const stale = QueryTemplates.staleEntries('session-cache', 10);
Migration
import { MemoryMigrator, createMigrator } from '@monomind/memory';
const migrator = createMigrator(targetAdapter, {
source: 'sqlite',
sourcePath: './data/v2-memory.db',
batchSize: 100,
generateEmbeddings: true,
continueOnError: true,
validateData: true,
});
const result = await migrator.migrate();
console.log(`Migrated ${result.progress.migrated} entries`);
console.log(`Failed: ${result.progress.failed}`);
Quantization Options
const binaryIndex = new HNSWIndex({
dimensions: 1536,
quantization: { type: 'binary' }
});
const scalarIndex = new HNSWIndex({
dimensions: 1536,
quantization: { type: 'scalar', bits: 8 }
});
const productIndex = new HNSWIndex({
dimensions: 1536,
quantization: { type: 'product', subquantizers: 8 }
});
Auto Memory Bridge (ADR-048)
Bidirectional sync between Claude Code's auto memory files and LanceDB. Auto memory is a persistent directory (~/.claude/projects/<project>/memory/) where Claude writes learnings as markdown. MEMORY.md (first 200 lines) is loaded into the system prompt; topic files are read on demand.
Quick Start
import { AutoMemoryBridge } from '@monomind/memory';
const bridge = new AutoMemoryBridge(memoryBackend, {
workingDir: '/workspaces/my-project',
syncMode: 'on-session-end',
pruneStrategy: 'confidence-weighted',
});
await bridge.recordInsight({
category: 'debugging',
summary: 'HNSW index requires initialization before search',
source: 'agent:tester',
confidence: 0.95,
});
const syncResult = await bridge.syncToAutoMemory();
const importResult = await bridge.importFromAutoMemory();
await bridge.curateIndex();
const status = bridge.getStatus();
Sync Modes
on-write | Writes to files immediately on recordInsight() |
on-session-end | Buffers insights, flushes on syncToAutoMemory() |
periodic | Auto-syncs on a configurable interval |
Insight Categories
project-patterns | patterns.md | Code patterns and conventions |
debugging | debugging.md | Bug fixes and debugging insights |
architecture | architecture.md | Design decisions and module relationships |
performance | performance.md | Benchmarks and optimization results |
security | security.md | Security findings and CVE notes |
preferences | preferences.md | User and project preferences |
swarm-results | swarm-results.md | Multi-agent swarm outcomes |
Key Optimizations
- Batch import -
bulkInsert() instead of individual store() calls
- Pre-fetched hashes - Single query for content-hash dedup during import
- Async I/O -
node:fs/promises for non-blocking writes
- Exact dedup -
hasSummaryLine() uses bullet-prefix matching, not substring
- O(1) sync tracking -
syncedInsightKeys Set prevents double-write race
- Prune-before-build - Avoids O(n^2) index rebuild loop
Utility Functions
import {
resolveAutoMemoryDir,
findGitRoot,
parseMarkdownEntries,
extractSummaries,
formatInsightLine,
hashContent,
pruneTopicFile,
hasSummaryLine,
} from '@monomind/memory';
Types
import type {
AutoMemoryBridgeConfig,
MemoryInsight,
InsightCategory,
SyncDirection,
SyncMode,
PruneStrategy,
SyncResult,
ImportResult,
} from '@monomind/memory';
Self-Learning Bridge (ADR-049)
Connects insights to the ReasoningBank pattern store. The optional neural learning system can be injected via neuralLoader; when none is provided, learning operations degrade to no-ops while pattern storage and retrieval continue to work.
Quick Start
import { AutoMemoryBridge, LearningBridge } from '@monomind/memory';
const bridge = new AutoMemoryBridge(backend, {
workingDir: '/workspaces/my-project',
learning: {
sonaMode: 'balanced',
confidenceDecayRate: 0.005,
accessBoostAmount: 0.03,
consolidationThreshold: 10,
},
});
await bridge.recordInsight({
category: 'debugging',
summary: 'Connection pool exhaustion on high load',
source: 'agent:tester',
confidence: 0.9,
});
await bridge.syncToAutoMemory();
Standalone Usage
import { LearningBridge } from '@monomind/memory';
const lb = new LearningBridge(backend, {
neuralLoader: async () => myNeuralLearningSystem,
});
await lb.onInsightAccessed('entry-123');
const decayed = await lb.decayConfidences('default');
const patterns = await lb.findSimilarPatterns('connection pooling');
const stats = lb.getStats();
Confidence Lifecycle
| Insight recorded | Initial confidence from source | 0.1 - 1.0 |
| Insight accessed | +0.03 per access | Capped at 1.0 |
| Time decay | -0.005 per hour since last access | Floored at 0.1 |
| Consolidation | Neural pipeline may adjust | 0.1 - 1.0 |
Knowledge Graph (ADR-049)
Pure TypeScript knowledge graph with PageRank and community detection. No external graph libraries required.
Quick Start
import { AutoMemoryBridge, MemoryGraph } from '@monomind/memory';
const bridge = new AutoMemoryBridge(backend, {
workingDir: '/workspaces/my-project',
graph: {
similarityThreshold: 0.8,
pageRankDamping: 0.85,
maxNodes: 5000,
},
});
await bridge.importFromAutoMemory();
await bridge.curateIndex();
Standalone Usage
import { MemoryGraph } from '@monomind/memory';
const graph = new MemoryGraph({
pageRankDamping: 0.85,
pageRankIterations: 50,
pageRankConvergence: 1e-6,
maxNodes: 5000,
});
await graph.buildFromBackend(backend, 'my-namespace');
graph.addNode(entry);
graph.addEdge('entry-1', 'entry-2', 'reference', 1.0);
graph.addEdge('entry-1', 'entry-3', 'similar', 0.9);
const ranks = graph.computePageRank();
const communities = graph.detectCommunities();
const ranked = graph.rankWithGraph(searchResults, 0.7);
const topNodes = graph.getTopNodes(20);
const neighbors = graph.getNeighbors('entry-1', 2);
Edge Types
reference | MemoryEntry.references | Explicit cross-references between entries |
similar | HNSW search | Auto-created when similarity > threshold |
temporal | Timestamps | Entries created in same time window |
co-accessed | Access patterns | Entries frequently accessed together |
causal | Learning pipeline | Cause-effect relationships |
Performance
| Graph build (1k nodes) | 2.78 ms | <200 ms |
| PageRank (1k nodes) | 12.21 ms | <100 ms |
| Community detection (1k) | 19.62 ms | — |
rankWithGraph(10) | 0.006 ms | — |
getTopNodes(20) | 0.308 ms | — |
getNeighbors(d=2) | 0.005 ms | — |
Agent-Scoped Memory (ADR-049)
Maps Claude Code's 3-scope agent memory directories for per-agent knowledge isolation and cross-agent transfer.
Quick Start
import { createAgentBridge, transferKnowledge } from '@monomind/memory';
const agentBridge = createAgentBridge(backend, {
agentName: 'my-coder',
scope: 'project',
workingDir: '/workspaces/my-project',
});
await agentBridge.recordInsight({
category: 'debugging',
summary: 'Use connection pooling for DB calls',
source: 'agent:my-coder',
confidence: 0.95,
});
const result = await transferKnowledge(sourceBackend, targetBridge, {
sourceNamespace: 'learnings',
minConfidence: 0.8,
maxEntries: 20,
categories: ['debugging', 'architecture'],
});
Scope Paths
project | <gitRoot>/.claude/agent-memory/<agent>/ | Project-specific learnings |
local | <gitRoot>/.claude/agent-memory-local/<agent>/ | Machine-local data |
user | ~/.claude/agent-memory/<agent>/ | Cross-project user knowledge |
Utilities
import {
resolveAgentMemoryDir,
createAgentBridge,
transferKnowledge,
listAgentScopes,
} from '@monomind/memory';
const dir = resolveAgentMemoryDir('my-agent', 'project');
const scopes = await listAgentScopes('/workspaces/my-project');
A-MEM Auto-Linking (arXiv:2409.11987)
When HybridBackend is configured with an embeddingGenerator, every stored entry
automatically discovers its top-3 semantic neighbors and creates bidirectional
references edges — implementing the Zettelkasten note-linking structure from A-MEM.
const backend = new HybridBackend({
embeddingGenerator: async (text) => myEmbeddingModel.embed(text),
});
await backend.store(entry);
backend.on('amem:linked', ({ id, linkedTo }) =>
console.log(`Linked ${id} to ${linkedTo.join(', ')}`));
Injection-Safe Semantic Search
Set filterInjection: true to remove entries containing prompt-injection patterns
from semantic search results before they reach the agent context:
const backend = new HybridBackend({
embeddingGenerator: myEmbedder,
filterInjection: true,
});
const entries = await backend.querySemantic({ content: 'OAuth patterns', k: 10 });
backend.on('injection:blocked', ({ id, namespace }) =>
securityLogger.warn(`Injection blocked from entry ${id}`));
Source: arXiv:2302.12173, arXiv:2310.12815 — indirect prompt injection in RAG pipelines.
querySemantic() now captures community summaries from MemoryGraph.getCommunitySummaries()
and annotates each returned entry with its GraphRAG community metadata. This implements
the community-level summarisation strategy from Microsoft GraphRAG.
const entries = await backend.querySemantic({ content: 'authentication patterns', k: 10 });
PPR re-ranking is handled by HippoRAG-style personalised PageRank (arXiv:2405.14831),
which propagates query-node scores through the knowledge graph before returning results.
Collaborative Memory Promotion (arXiv:2505.18279)
HybridBackend.get(id, agentId?) accepts an optional agentId parameter. When
provided, it fires a read-tracking call to the SQLite backend, which promotes the
entry's AccessLevel from 'private' to 'team' once 3 or more distinct agents
have accessed it within a 24-hour window.
const entry = await backend.get('entry-id-123', 'coder-agent');
Collaborative promotion is transparent to callers that don't pass agentId —
get(id) continues to work exactly as before (backwards-compatible).
Knowledge Graph & Temporal Edges (arXiv:2501.13956)
MemoryGraph models causal and temporal relationships between entries as typed
edges, inspired by the Zep/Graphiti episodic knowledge graph (arXiv:2501.13956).
Edge types include REFERENCES, CAUSES, PRECEDED_BY, RELATED_TO, and
CONTRADICTS, enabling episodic reasoning over the agent's memory history.
import { MemoryGraph, type EdgeType } from '@monomind/memory';
const graph = new MemoryGraph();
graph.addEdge('plan-123', 'code-456', EdgeType.CAUSES, 0.9);
graph.addEdge('code-456', 'test-789', EdgeType.PRECEDED_BY, 1.0);
const ranked = graph.pprRerank(['plan-123'], candidates, 0.85);
μACP Learning-Bridge Integration (arXiv:2601.03938)
LearningBridge integrates with the μACP coordination substrate: when consolidation
detects a pattern conflict between agents, it initiates a μACP round to resolve which
variant to promote. The result is stored as a causal edge in MemoryGraph.
await learningBridge.consolidate();
Source: arXiv:2601.03938.
Bi-Temporal Query Filtering (arXiv:2501.13956)
MemoryQuery now supports eventAfter and eventBefore filters that operate on the
eventAt field — the timestamp of when the event occurred (T), as opposed to
createdAt which records when the entry was ingested (T'). This is the bi-temporal
model from Zep/Graphiti that prevents retrieval failures when data arrives out-of-order
or is backdated.
const entries = await backend.query({
type: 'hybrid',
namespace: 'incidents',
limit: 50,
eventAfter: new Date('2026-01-01').getTime(),
eventBefore: new Date('2026-04-01').getTime(),
});
await backend.store({
key: 'outage-2026-02-14',
content: 'DB connection pool exhausted during peak traffic',
type: 'episodic',
namespace: 'incidents',
eventAt: new Date('2026-02-14T03:22:00Z').getTime(),
});
Source: arXiv:2501.13956 — Zep/Graphiti bi-temporal knowledge graph.
MemoRAG Query Rewriting (arXiv:2409.05591)
HybridBackend supports a memoragRewriter configuration option that adds a
"draft clue" query-expansion stage before HNSW search. When configured, querySemantic()
calls the rewriter to generate 2-3 reformulated sub-queries, searches HNSW independently
for each, then fuses all ranked result lists using Reciprocal Rank Fusion (RRF) before
continuing with HippoRAG PPR re-ranking and GraphRAG community annotation.
This addresses the MemoRAG insight that naive RAG fails when the user query does not
directly match any retrievable chunk — paraphrased sub-queries dramatically improve recall.
import { HybridBackend } from '@monomind/memory';
const backend = new HybridBackend({
embeddingGenerator: myEmbedder,
memoragRewriter: async (query) => {
const reformulated = await callClaude({
model: 'claude-haiku-4-5',
prompt: `Generate 3 alternative search queries for: "${query}"\nRespond with a JSON array of strings.`,
});
return JSON.parse(reformulated);
},
});
const results = await backend.querySemantic({ content: 'memory leak in production' });
Source: arXiv:2409.05591 — MemoRAG (TheWebConf 2025).
DiskANN Backend — Large-Scale ANN at Disk Scale (arXiv:2305.04359)
DiskAnnBackend is an IMemoryBackend decorator that activates SSD-resident Vamana ANN search above entry-count thresholds. Wraps any existing backend (typically the long-term SQLite/LanceDB backend in TierManager).
Architecture
- Disk-persisted adjacency list — Vamana graph written to
graphPath as JSON
- In-memory Int8-quantised vectors —
Map<string, Int8Array> for fast beam search
- Beam search — BFS traversal using Int8 dot-product as the candidate scorer
- Full-precision cosine re-ranking — fetches raw embeddings from the delegate backend
Quick Start
import { DiskAnnBackend, type DiskAnnBackendConfig } from '@monomind/memory';
const diskann = new DiskAnnBackend(existingBackend, {
graphPath: './data/diskann.graph.json',
R: 32,
L: 64,
beamWidth: 10,
dimensions: 128,
});
await diskann.store(entry);
await diskann.get(id);
const results = await diskann.search(queryVector, { k: 5 });
TierManager Integration
Pass diskAnnConfig to activate DiskANN on the long-term backend:
import { TierManager } from '@monomind/memory';
const tier = new TierManager(
longTermBackend,
{ shortTermCapacity: 1000 },
{},
{
graphPath: './data/diskann.graph.json',
R: 32,
beamWidth: 12,
},
);
const results = await tier.search('authentication patterns', 10);
DiskAnnBackendConfig
graphPath | './diskann.graph.json' | Path for persisted Vamana adjacency list |
R | 32 | Max out-degree per node |
L | 64 | Beam width during construction |
beamWidth | 10 | Beam width during search |
dimensions | 128 | Vector dimensions |
Performance Benchmarks
| Vector Search | 150ms | <1ms | 150x |
| Bulk Insert | 500ms | 5ms | 100x |
| Memory Write | 50ms | <5ms | 10x |
| Cache Hit | 5ms | <0.1ms | 50x |
| Index Build | 10s | 800ms | 12.5x |
ADR-049 Benchmarks
| Graph build (1k nodes) | 2.78 ms | <200 ms | 71.9x |
| PageRank (1k nodes) | 12.21 ms | <100 ms | 8.2x |
| Insight recording | 0.12 ms/each | <5 ms/each | 41.0x |
| Consolidation | 0.26 ms | <500 ms | 1,955x |
| Confidence decay (1k) | 0.23 ms | <50 ms | 215x |
| Knowledge transfer | 1.25 ms | <100 ms | 80.0x |
TypeScript Types
import type {
MemoryEntry, MemoryEntryInput, MemoryEntryUpdate,
MemoryQuery, MemoryType, AccessLevel,
SearchResult, SearchOptions,
SortField,
SortDirection,
HNSWConfig, HNSWStats, QuantizationConfig, DistanceMetric,
IMemoryBackend, BackendStats, HealthCheckResult,
CacheConfig, CacheStats,
AutoMemoryBridgeConfig, MemoryInsight, InsightCategory,
SyncMode, SyncResult, ImportResult,
AgentMemoryScope, AgentScopedConfig,
TransferOptions, TransferResult,
LearningBridgeConfig, ConsolidateResult, PatternMatch,
MemoryGraphConfig, GraphNode, GraphEdge,
GraphStats, RankedResult,
MemoryTier, EntityFact, SessionSummary,
MigrationSource, MigrationConfig, MigrationResult,
AgentState, SwarmCheckpoint, CheckpointMeta,
} from '@monomind/memory';
Dependencies
lancedb - Vector database engine
better-sqlite3 - SQLite driver (native)
sql.js - SQLite driver (WASM fallback)
Related Packages
License
MIT