Skip to main content
Normalized for Mintlify from knowledge-base/neurigraph-memory-architecture/neurigraph-tool-references/05-SQL-Native-Entity-Memory-Layer.mdx.

Clean-Room Specification: SQL-Native Entity Memory Layer with Vector Search

Purpose of This Document

This document specifies the complete architecture, data model, and API surface of an SQL-native entity memory system for AI assistants. Unlike JSONL-file approaches, this system uses a relational database (PostgreSQL with pgvector, or SQLite with sqlite-vec) as the primary store, providing ACID transactions, proper indexing, vector similarity search, confidence scoring, memory type classification, and temporal decay. The system is exposed via both MCP tools and a REST API with Server-Sent Events. This specification is detailed enough that a professional AI coding model can produce a functionally identical working system without reference to any existing codebase.

1. System Overview

1.1 Core Concept

An AI assistant accumulates memories during conversations — facts about users, decisions made, patterns observed, errors encountered, and lessons learned. This system provides:
  1. Structured storage: Memories stored in SQL tables with proper types, tags, and confidence scores
  2. Semantic search: Vector embeddings enable meaning-based retrieval
  3. Knowledge graph: Entities connected by typed, weighted relations
  4. Temporal management: Confidence decay over time, reinforcement on access
  5. Memory consolidation: Automatic deduplication and merging of overlapping memories
  6. Multi-client: Supports concurrent AI assistant connections

1.2 Architecture

1.3 Design Principles

  1. SQL-native: All data in proper relational tables with constraints and indexes
  2. Dual access: Both MCP tools (for AI assistants) and REST API (for applications)
  3. Embedding-first: Every memory gets a vector embedding for semantic retrieval
  4. Confidence-scored: Every memory and relation has a confidence value that decays over time
  5. Type-classified: Memories are categorized for targeted retrieval

2. Database Schema

2.1 Memories Table

The core storage for all atomic memory units.
Vector index (PostgreSQL with pgvector):
Memory types (enumerated, extensible):

2.2 Entities Table

Named entities that memories can be associated with.
Entity types: person, organization, project, concept, location, technology, event

2.3 Relations Table

Directed, typed connections between entities.
Relation types (active voice):
  • works_at, manages, reports_to, collaborates_with
  • uses, implements, depends_on, related_to
  • located_in, part_of, created_by

2.4 Entity-Memory Association

Many-to-many mapping between entities and memories.

2.5 Memory Versions Table

Track history of memory modifications.

2.6 Full-Text Search (SQLite Alternative)

When using SQLite instead of PostgreSQL:
Vector storage (SQLite with sqlite-vec):

3. Embedding System

3.1 Provider Interface

3.2 Supported Providers

3.3 Embedding Generation

Embeddings are generated automatically:
  • On memory creation: embed the content field
  • On entity creation: embed name + " " + description
  • On memory update: re-embed if content changed
  • Batch processing: Queue new memories, embed in batches of 32

3.4 Similarity Computation

PostgreSQL (pgvector):
The <=> operator computes cosine distance. Similarity = 1 - distance. SQLite (sqlite-vec):
Convert L2 distance to cosine similarity: similarity = 1 - (distance² / 2) (for normalized vectors).

4. Confidence and Temporal Decay

4.1 Confidence Model

Every memory has a confidence score in [0.0, 1.0]:
  • 1.0: Just created, highly confident
  • 0.5: Moderate confidence
  • 0.0: No confidence, candidate for pruning

4.2 Decay Formula

Confidence decays exponentially over time since last access:

4.3 Reinforcement

When a memory is accessed (read, searched, or returned in results):
  1. Increment access_count
  2. Update last_accessed_at to now
  3. Boost confidence: confidence = min(1.0, confidence + 0.1)
This creates a “use it or lose it” dynamic where frequently-accessed memories stay strong.

4.4 Decay Application

Decay is computed at read time, not continuously updated:

4.5 Pruning

A periodic background job removes memories with effective confidence below a threshold:
  • Default threshold: 0.05
  • Run interval: daily
  • Pruned memories are permanently deleted (or moved to archive table if configured)

5. Search System

5.1 Search Modes

PostgreSQL:
SQLite (FTS5):
  1. Embed the query text
  2. Find nearest neighbors by cosine similarity
  3. Filter by minimum similarity threshold (default: 0.5)
  4. Return top-k results (default: 20)
Normalization: Both keyword and semantic scores are min-max normalized to [0, 1] within their respective result sets before combination. Merging: Union of results from both searches. If a memory appears in both, use hybrid score. If only in one, scale by its weight. Given a starting entity:
  1. Find all directly connected entities (1-hop)
  2. Collect all memories associated with those entities
  3. Optionally expand to 2-hop or N-hop neighbors
  4. Rank results by relation strength × confidence

5.6 Search Filters

All modes support these filters:

6. Memory Consolidation

6.1 Deduplication

When creating a new memory, check for duplicates:
  1. Exact match: SHA-256 hash of content matches existing memory → skip creation
  2. Near-duplicate: Cosine similarity > 0.95 with existing memory → merge
Merge strategy:
  • Keep the older memory (lower ID)
  • Update confidence: max(old.confidence, new.confidence)
  • Merge tags: union of both tag sets
  • Update metadata: shallow merge (new values override old)
  • Increment version

6.2 Consolidation Engine

A periodic process that combines related memories:
  1. Find clusters of memories with high pairwise similarity (> 0.85)
  2. For each cluster: a. Select the memory with highest confidence as the “primary” b. Merge observations from other memories into primary c. Create version records for audit trail d. Delete absorbed memories e. Reassign entity associations

6.3 Consolidation Triggers

  • Manual: Via MCP tool or API call
  • Automatic: After every N memory insertions (default: 50)
  • Scheduled: Configurable cron interval (default: daily)

7. MCP Server

7.1 Server Setup

Transport: stdio (JSON-RPC 2.0 over stdin/stdout) Initialization:
  1. Connect to database
  2. Run migrations if needed
  3. Initialize embedding provider
  4. Register tools

7.2 MCP Tools

7.2.1 store_memory

Create a new memory with automatic embedding and deduplication. Parameters: Behavior:
  1. Check for duplicates (exact hash, then semantic similarity)
  2. If duplicate found: merge and return existing memory
  3. Generate embedding for content
  4. Insert memory record
  5. Associate with entities (create entities if they don’t exist)
  6. Return created memory with ID

7.2.2 recall_memories

Search for relevant memories. Parameters: Returns: Array of memories with scores, sorted by relevance.

7.2.3 create_entities

Create one or more named entities. Parameters:
Behavior: Create entities, generate embeddings, deduplicate by (name, entity_type).

7.2.4 create_relations

Create typed connections between entities. Parameters:
Behavior: Look up entities by name, create relation records. If source or target entity doesn’t exist, auto-create with type “unknown”.

7.2.5 delete_memories

Delete memories by ID or filter. Parameters: Behavior: Delete matching memories and cascade to entity_memories associations. At least one filter must be provided.

7.2.6 delete_entities

Delete entities and optionally their associated memories. Parameters:

7.2.7 delete_relations

Delete specific relations. Parameters:

7.2.8 get_entity_graph

Retrieve a subgraph centered on an entity. Parameters: Returns: Graph structure with nodes (entities), edges (relations), and optionally memories per node.

7.2.9 consolidate_memories

Trigger manual consolidation. Parameters: Returns: Consolidation report (clusters found, memories merged, memories deleted).

7.2.10 get_memory_stats

Get analytics about the memory store. Parameters: None. Returns:

8. REST API

8.1 Memory Endpoints

8.2 Entity Endpoints

8.3 Relation Endpoints

8.4 Analytics Endpoints

8.5 Server-Sent Events

Event types:

9. Configuration

9.1 Environment Variables

9.2 Claude Desktop Integration


10. Behavioral Test Specifications

10.1 Memory CRUD Tests

10.2 Search Tests

10.3 Confidence and Decay Tests

10.4 Entity and Graph Tests

10.5 Consolidation Tests

10.6 REST API Tests


11. Key Implementation Algorithms

11.1 Hybrid Score Computation

11.2 Graph Traversal (BFS)

11.3 Deduplication Check

11.4 Confidence Decay Computation


12. Dependencies

12.1 Required (TypeScript/Node.js)

12.2 Optional


13. Directory Structure


14. Startup Sequence

  1. Load configuration from environment variables
  2. Initialize database connection (SQLite or PostgreSQL)
  3. Run pending migrations
  4. Initialize embedding provider (test with a sample embed call)
  5. Initialize MCP server with stdio transport
  6. Register all MCP tools
  7. Start REST API server (if enabled)
  8. Start background workers:
    • Confidence decay pruning (daily)
    • Consolidation (after every N insertions or on schedule)
    • Embedding backfill (for any memories missing embeddings)
  9. Begin accepting connections

This specification provides complete architectural and behavioral detail for independent implementation of an SQL-native entity memory layer with vector search, confidence decay, memory consolidation, and dual MCP/REST access.