Skip to content

๐Ÿง  Spector Memory

The Cognitive Memory Engine for Autonomous AI Agents.

A biologically-inspired, off-heap memory system that gives AI agents the ability to remember, forget, consolidate, and associate โ€” with microsecond latency and zero garbage collection pressure. Built on Java Project Panama, SIMD-accelerated vector math, and Virtual Threads.

Java License Panama SIMD Virtual Threads


Why Cognitive Memory?

Traditional vector databases treat memories as static documents in a flat index. Real cognition is fundamentally different:

Traditional Vector DB Spector Memory
Flat document store 4-tier cognitive architecture (Working โ†’ Episodic โ†’ Semantic โ†’ Procedural)
Static similarity search Fused scoring โ€” similarity ร— importance ร— temporal decay in a single SIMD pass
No temporal awareness Reconsolidation โ€” frequently recalled memories resist forgetting
No emotional context Valence tracking โ€” memories carry emotional coloring
No contextual gating Synaptic tags โ€” 64-bit Bloom filter eliminates 99% of candidates in 1 CPU cycle
Python + network hops Zero-GC, off-heap Panama โ€” microsecond latency, no serialization

Architecture

spector-memory/
โ”œโ”€โ”€ SpectorMemory.java              โ† Faรงade (Builder pattern entry point)
โ”œโ”€โ”€ pipeline/                       โ† "Neural Pathways" โ€” ingestion + recall pipelines
โ”‚     โ”œโ”€โ”€ IngestionPipeline.java        (10-step remember pipeline)
โ”‚     โ”œโ”€โ”€ RecallPipeline.java           (parallel tier scanning + scoring)
โ”‚     โ””โ”€โ”€ HebbianCoActivationListener   (Observer pattern post-recall)
โ”‚
โ”œโ”€โ”€ kernel/                         โ† "Memory Kernel" โ€” Memory<Layout> & Shapes
โ”‚     โ”œโ”€โ”€ Memory.java                   (Base interface)
โ”‚     โ”œโ”€โ”€ RegionPreamble.java           (On-disk SMKM region preamble)
โ”‚     โ”œโ”€โ”€ layout/                       (Layout types for records, entities, graphs)
โ”‚     โ””โ”€โ”€ shape/                        (RecordMemory, AppendMemory, GraphMemory, etc.)
โ”‚
โ”œโ”€โ”€ cortex/                         โ† "Cerebral Cortex" โ€” 4 tier stores
โ”‚     โ”œโ”€โ”€ TierStore.java                (Strategy interface)
โ”‚     โ”œโ”€โ”€ TierRouter.java               (Registry + polymorphic dispatch)
โ”‚     โ”œโ”€โ”€ WorkingMemoryStore.java       (Prefrontal Cortex โ€” volatile circular buffer)
โ”‚     โ”œโ”€โ”€ EpisodicPartitionedMemory.java      (Hippocampus โ€” time-partitioned mmap)
โ”‚     โ”œโ”€โ”€ SemanticMemoryStore.java      (Neocortex โ€” single-file semantic storage)
โ”‚     โ”œโ”€โ”€ PartitionedSemanticStore.java (Neocortex โ€” rolling partitioned semantic storage)
โ”‚     โ”œโ”€โ”€ StorageMigrator.java          (Single-file โ†’ partitioned migration)
โ”‚     โ””โ”€โ”€ ProceduralMemoryStore.java    (Basal Ganglia โ€” learned procedures)
โ”‚
โ”œโ”€โ”€ synapse/                        โ† "Synaptic Machinery" โ€” header layout + scoring
โ”‚     โ”œโ”€โ”€ EngramLayout.java    (64-byte cache-line-aligned synaptic header)
โ”‚     โ”œโ”€โ”€ CognitiveScorer.java          (6-phase fused scoring hot-loop)
โ”‚     โ”œโ”€โ”€ SynapticTagEncoder.java       (64-bit inline Bloom filter)
โ”‚     โ”œโ”€โ”€ EncodingHeaderFields.java     (offsets, masks, field sizes)
โ”‚     โ”œโ”€โ”€ TemperatureSoftmax.java       (numerically stable retrieval temperature)
โ”‚     โ””โ”€โ”€ DecayStrategy.java            (SIMD-friendly temporal decay)
โ”‚
โ”œโ”€โ”€ dopamine/                       โ† "Dopamine System" โ€” surprise & importance
โ”‚     โ”œโ”€โ”€ SurpriseDetector.java         (Welford online statistics + Z-score)
โ”‚     โ”œโ”€โ”€ FlashbulbPolicy.java          (extreme surprise โ†’ pinned memory)
โ”‚     โ””โ”€โ”€ WelfordStats.java             (running mean/variance tracker)
โ”‚
โ”œโ”€โ”€ amygdala/                       โ† "Amygdala" โ€” emotional valence
โ”‚     โ””โ”€โ”€ ValenceTracker.java           (emotional coloring of memories)
โ”‚
โ”œโ”€โ”€ hebbian/                        โ† "Hebbian Learning" โ€” associations
โ”‚     โ”œโ”€โ”€ CoActivationTracker.java      (tag co-occurrence tracking)
โ”‚     โ””โ”€โ”€ HebbianGraph.java             (associative memory network)
โ”‚
โ”œโ”€โ”€ graph/                          โ† "Entity-Relationship Graph" + temporal
โ”‚     โ”œโ”€โ”€ EntityGraph.java              (LLM-powered knowledge graph)
โ”‚     โ”œโ”€โ”€ EntityType.java               (21 well-known entity types)
โ”‚     โ”œโ”€โ”€ RelationType.java             (21 well-known relation types)
โ”‚     โ”œโ”€โ”€ TypeRegistry.java             (open-schema string โ†” int registry)
โ”‚     โ”œโ”€โ”€ TemporalChain.java            (session-linked causal sequences)
โ”‚     โ””โ”€โ”€ LlmEntityExtractor.java       (LLM entity extraction SPI impl)
โ”‚
โ”œโ”€โ”€ hippocampus/                    โ† "Hippocampus" โ€” consolidation & cleanup
โ”‚     โ”œโ”€โ”€ ReflectDaemon.java            (sleep consolidation K-Means)
โ”‚     โ””โ”€โ”€ TombstoneCompactor.java       (partition rebuild)
โ”‚
โ”œโ”€โ”€ habituation/                    โ† "Habituation" โ€” anti-filter bubble
โ”‚     โ””โ”€โ”€ HabituationPenalty.java       (frequency-based score decay)
โ”‚
โ”œโ”€โ”€ inhibition/                     โ† "Inhibition" โ€” suppression
โ”‚     โ””โ”€โ”€ SuppressionSet.java           (explicit memory blocking)
โ”‚
โ”œโ”€โ”€ interference/                   โ† "Proactive Interference" โ€” deduplication
โ”‚     โ””โ”€โ”€ SemanticDeduplicator.java     (near-duplicate detection + merge)
โ”‚
โ”œโ”€โ”€ prospective/                    โ† "Prospective Memory" โ€” future intents
โ”‚     โ”œโ”€โ”€ ProspectiveScheduler.java     (time-triggered reminders)
โ”‚     โ””โ”€โ”€ Reminder.java                 (scheduled memory record)
โ”‚
โ”œโ”€โ”€ metamemory/                     โ† "Metamemory" โ€” self-reflection
โ”‚     โ””โ”€โ”€ MemoryIntrospector.java       (memory health stats & analytics)
โ”‚
โ”œโ”€โ”€ index/                          โ† O(1) reverse index
โ”‚     โ””โ”€โ”€ MemoryIndex.java              (ConcurrentHashMap forward + reverse)
โ”‚
โ””โ”€โ”€ sync/                           โ† Persistence & replication
      โ”œโ”€โ”€ MemoryWal.java                (Write-Ahead Log)
      โ””โ”€โ”€ CrdtMergeStrategy.java        (CRDT merge for distributed sync)

Biological System โ†’ Package Mapping

Brain Region Package Java Classes Function
๐Ÿ’พ Sub-cortical Core kernel/ Memory, RegionPreamble, MemoryShape Core Panama storage abstractions (RecordMemory, AppendMemory, etc.)
๐Ÿง  Cerebral Cortex cortex/ TierRouter, TierStore, 4 stores 4-tier memory storage (Working โ†’ Episodic โ†’ Semantic โ†’ Procedural)
๐Ÿ”— Synapses synapse/ CognitiveScorer, SynapticTagEncoder, EngramLayout 64-byte header, 6-phase scoring, Bloom filter gating
โšก Dopamine System dopamine/ SurpriseDetector, FlashbulbPolicy Surprise detection, auto-importance, flashbulb pinning
๐Ÿ˜ฑ Amygdala amygdala/ ValenceTracker Emotional coloring (positive/negative/neutral)
๐Ÿ”„ Hebbian Learning hebbian/ CoActivationTracker, HebbianGraph "Neurons that fire together wire together"
๐Ÿ”— Entity Knowledge graph/ EntityGraph, TypeRegistry, LlmEntityExtractor LLM-powered entity-relationship graph with open-schema types
โณ Temporal Chain graph/ TemporalChain Session-linked causal sequences ("what happened next?")
๐Ÿ›๏ธ Hippocampus hippocampus/ ReflectDaemon, TombstoneCompactor Sleep consolidation, synaptic pruning, partition rebuild
๐Ÿ˜ด Habituation habituation/ HabituationPenalty Anti-filter bubble โ€” penalizes repetitive recall
๐Ÿšซ Inhibition inhibition/ SuppressionSet Explicit memory suppression (user redaction)
๐Ÿ”ฎ Prospective Memory prospective/ ProspectiveScheduler, Reminder Future-oriented intent reminders
๐Ÿชž Metamemory metamemory/ MemoryIntrospector Self-reflective memory health analytics

Spector Memory Kernel (SMK)

Spector Memory uses a unified Memory Kernel abstraction (Memory<Layout>) that standardizes all persistent and volatile storage structures using Project Panama's Foreign Function & Memory API. Rather than implementing individual binary layouts from scratch, every subsystem maps to a standardized kernel Shape:

  • RecordMemory / PartitionedRecordMemory: Fixed-size contiguous slots used by the cognitive tiers (Working, Semantic, and Procedural stores) and CoActivationTracker.
  • AppendMemory: Append-only log arrays with cursor offsets, backing TextDataStore and the Write-Ahead Log.
  • RegistryMemory: Open-schema string-to-int mapping used for metadata serialization (TypeRegistry).
  • GraphMemory: CSR (Compressed Sparse Row) and slab-allocated structures backing the EntityGraph and HebbianGraph.
  • ChainMemory: Causal sequence structures backing the TemporalChain.

All memory operations are journaled to the WAL at the kernel shape level, enabling complete state reconstruction on startup via WalRecoveryDispatcher.


Quick Start

// 1. Create a cognitive memory with Ollama embeddings
SpectorMemory memory = SpectorMemory.builder()
    .dimensions(4096)
    .embeddingProvider(OllamaEmbeddingProvider.create("qwen3-embedding"))
    .workingCapacity(100)
    .episodicPartitionCapacity(10_000)
    .nodesPerPartition(10_000)         // Semantic partition capacity (rolling files)
    .semanticCapacity(5_000)           // Single-file fallback capacity
    .proceduralCapacity(500)
    .build();

// 2. Remember โ€” 10-step ingestion pipeline
memory.remember("pref-dark-mode",
    "The user strongly prefers dark mode for all IDE editors.",
    MemoryType.EPISODIC, MemorySource.USER_STATED,
    "ui", "preferences", "coding");

// 3. Recall โ€” parallel SIMD-accelerated search with cognitive scoring
List<CognitiveResult> results = memory.recall("dark theme settings",
    RecallOptions.builder()
        .topK(5)
        .synapticFilter("preferences")    // Bloom filter pre-screen
        .minImportance(0.3f)              // Skip low-importance memories
        .build());

for (CognitiveResult r : results) {
    System.out.printf("%.4f [%s] %s%n", r.score(), r.memoryType(), r.text());
}

// 4. Forget โ€” tombstone a memory
memory.forget("pref-dark-mode");

// 5. Suppress โ€” temporarily hide from recall
memory.suppress("noisy-memory-id", "Not relevant right now");

// 6. Close โ€” releases all off-heap memory
memory.close();

The 6-Phase Scoring Pipeline

Every recall query executes a SIMD-optimized hot-loop that fuses six filtering and scoring phases into a single sequential scan. Each phase eliminates candidates before the expensive vector math:

Phase 1: Tombstone Check     (~1 cycle)    โ†’ Skip dead memories
Phase 2: Synaptic Tag Gating (~1 cycle)    โ†’ Bloom filter eliminates 99% of irrelevant
Phase 3: Valence Filter      (~2 cycles)   โ†’ Emotional range filtering
Phase 4: Importance/Decay    (~5 cycles)   โ†’ Skip old + low-importance
Phase 5: SIMD L2 Distance   (~200 cycles)  โ†’ Quantized INT8 Euclidean via Vector API
Phase 6: Fused Score         (~7 cycles)   โ†’ ฮฑยทsimilarity + ฮฒยทimportanceยทdecay

The math: If an agent has 1,000,000 episodic memories but only 10,000 match the active synaptic tags: - Phases 1-4 eliminate 990,000 memories in ~990ยตs (cheap header reads) - Phase 5 computes SIMD distance on only ~10,000 candidates - Total: Ultra-fast in-process scan vs ~200ms without gating


Performance

Benchmarked on Intel Core Ultra 9 285K, Java 25, AVX2 256-bit:

Benchmark Result
SIMD L2 Distance (768-dim) 2.2 ยตs/vector (1.4M vectors/sec)
SIMD L2 Distance (128-dim) 0.8 ยตs/vector (1.2M vectors/sec)
Reverse Index Lookup 180 ns/lookup (O(1) via ConcurrentHashMap)
CognitiveScorer (10K ร— 128-dim) 2.9 ms total
Batch Habituation (1K IDs) 101 ยตs total
Full Pipeline (1K ingest + 100 recall) < 50 ms/query
Real Embedding (qwen3-embedding 4096-dim) 31 ms/embed via Ollama

Test Suite

spector-core:   276 tests โœ…  (includes 15 SIMD kernel tests)
spector-memory: 167 tests โœ…  (includes 33 perf + index tests)
                + 10 Ollama real embedding E2E tests (gated by OLLAMA_LIVE=true)
Total: 443 tests, 0 failures

Competitive Landscape

Feature Spector Memory Mem0 Letta (MemGPT) Zep
Language Java 25 Python Python Go/Python
Storage Off-heap Panama Postgres/pgvector Postgres/Chroma Postgres
Latency Ultra-low latency ~50-200ms ~100-500ms ~20-100ms
GC Pressure Zero Python GC Python GC Go GC
Temporal Decay Fused SIMD Post-filter Post-filter Post-filter
Emotional Valence โœ… Built-in โŒ โŒ โŒ
Synaptic Tag Gating โœ… 1-cycle Bloom โŒ โŒ โŒ
Sleep Consolidation โœ… K-Means โŒ โŒ โŒ
Entity Knowledge Graph โœ… LLM-powered, open-schema โŒ โŒ โŒ
Temporal Causal Chains โœ… Session-linked โŒ โŒ โŒ
Surprise Detection โœ… Welford Z-score โŒ โŒ โŒ
Habituation โœ… Anti-filter bubble โŒ โŒ โŒ
MCP Integration โœ… Native โŒ โŒ โŒ

Documentation

๐Ÿ“– Full documentation: See the Cognitive Memory Guide for:


License

This module is licensed under the Business Source License 1.1 (BSL 1.1).

  • Permits free use for non-production purposes.
  • Permits production use for all purposes except offering it as a managed service or embedding/integrating it in a competing AI cognitive memory product or service.
  • Automatically transitions to the Apache License 2.0 on May 27, 2030 (4 years from release).

See the LICENSE file for the full terms and conditions.

Built with โšก by Spectrayan