Skip to content

munch2u-a11y/Cognitive-Spatial-Memory

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Spatial Memory

Gravity-modulated 8D cognitive memory system — a drop-in RAG replacement.

License: AGPL v3 Python 3.10+

What is this?

Spatial Memory replaces standard cosine-similarity RAG with a physics-inspired 8D manifold where memories and beliefs have:

  • Mass — derived from confidence and affective encoding
  • Temperature — recency heat that cools over time (Lorentzian decay)
  • GravityF = T × m / d² — hot, massive, nearby concepts pull attention

Instead of "find the 5 most similar documents," you get "what would naturally come to mind right now?" — gravitationally ranked retrieval that accounts for recency, confidence, and semantic clustering.

Architecture

                    ┌─────────────────────────────────┐
                    │         SpatialMemory           │  ← High-level API
                    │   store() / query() / context() │
                    └──────────────┬──────────────────┘
                                   │
                    ┌──────────────┴──────────────────┐
                    │        PhysicsEngine             │  ← Wrapper
                    │   step_pulse / query_neighborhood│
                    └──────────────┬──────────────────┘
                                   │
              ┌────────────────────┼────────────────────┐
              │                    │                     │
    ┌─────────┴────────┐  ┌───────┴───────┐  ┌─────────┴────────┐
    │   SpatialMind    │  │  BeliefStore  │  │  StorageBackend  │
    │  (dual 8D fields)│  │  (JSON files) │  │  (JSONL/SQLite/  │
    │                  │  │              │  │   ChromaDB)      │
    └────────┬─────────┘  └──────────────┘  └──────────────────┘
             │
    ┌────────┴─────────┐
    │  CognitiveSpace  │  ← The 8D manifold (THE novel contribution)
    │  + GravityField  │
    │  + KDTree index  │
    │  + CogProjection │
    └──────────────────┘

Quickstart

pip install -r requirements.txt
from spatial_memory import SpatialMemory

# Initialize with zero config (defaults: sentence-transformers + JSONL)
mem = SpatialMemory(data_dir="./my_memory")

# Store memories
mem.store("The user prefers dark mode interfaces", importance=0.8)
mem.store("Meeting with Alice scheduled Friday 3pm", importance=0.6)
mem.store("Project deadline is next Wednesday", importance=0.9)

# Query by gravity (not just similarity!)
results = mem.query("What's coming up this week?", k=5)
for r in results:
    print(f"  [{r['relevance']:.3f}] {r['content']}")

# Get formatted context for LLM injection
context = mem.get_context("Planning the week ahead")
print(context)

Key Concepts

8D Cognitive Projection (Johnson-Lindenstrauss)

Every text embedding (384D from sentence-transformers) is projected to 8D via a fixed random orthogonal matrix. This projection preserves pairwise distances within a constant factor, giving each concept a permanent "address" in cognitive space.

Gravity-Ranked Retrieval

Instead of cosine similarity, retrieval is ranked by gravitational pull:

Gravity = Temperature × Mass / Distance²
  • Temperature: Lorentzian cooling in pulse-time. Recently accessed = hot = strong pull.
  • Mass: Confidence (beliefs) or importance (memories). Intrinsic, not inflated by connections.
  • Distance: Euclidean distance in 8D space. Semantically similar concepts are geometrically close.

Dual-Space Architecture

Two independent 8D spaces share the same projection matrix:

  • Belief Space: ~1K points, high mass, slow change (semantic memory)
  • Memory Space: ~12K+ points, lower mass, fast accumulation (episodic memory)

A single attention center moves through both spaces, pulled by three forces:

  1. F_gravity: nearby massive concepts
  2. F_stability: pull toward identity center (core beliefs)
  3. F_stimulus: pull toward the current thought/query

Cognitive Trail

As attention moves through the manifold, it traces a path. Points sampled along this path produce peripheral flashes — brief fragments of whatever lies between the previous and current thought. This creates natural "association chains" without explicit graph traversal.

Custom Embedding Provider

from spatial_memory import SpatialMemory, EmbeddingProvider
import numpy as np

class OpenAIEmbedding(EmbeddingProvider):
    def __init__(self):
        from openai import OpenAI
        self.client = OpenAI()

    def embed_text(self, text: str) -> np.ndarray:
        response = self.client.embeddings.create(
            model="text-embedding-3-small",
            input=text
        )
        return np.array(response.data[0].embedding)

    @property
    def embedding_dim(self) -> int:
        return 1536

mem = SpatialMemory(
    embedding_provider=OpenAIEmbedding(),
    data_dir="./my_memory"
)

Storage Backends

from spatial_memory import SpatialMemory
from spatial_memory.memory import JSONLStore, SQLiteStore

# Default: JSONL (append-only, portable, git-friendly)
mem = SpatialMemory(storage_backend=JSONLStore("memories.jsonl"))

# SQLite (indexed, faster search on large datasets)
mem = SpatialMemory(storage_backend=SQLiteStore("memories.db"))

# ChromaDB (vector similarity search)
# pip install chromadb
from spatial_memory.memory import ChromaStore
mem = SpatialMemory(storage_backend=ChromaStore("./chroma_db"))

Belief System

The belief store manages categorized beliefs with a full lifecycle:

from spatial_memory.beliefs import BeliefStore

store = BeliefStore("./beliefs")

# Add a belief
store.add_belief(
    category="knowledge",
    belief_id="kno_20260523_001",
    content="Python is a dynamically typed language",
    confidence=0.9,
    mass=1.5,
)

# Cognitive mass equation: Mass = confidence + Ω_encoding × (1 - s_total) × (0.5 + stability)
mass = store.compute_cognitive_mass(store.get_belief("kno_20260523_001"))

# Nightly attrition: C = min(1.0, (Base + T + R + V) × (0.5 + S))
stats = store.recalculate_all_confidences()

Origins

This system was originally developed as part of the Helix AGI cognitive architecture. It has been extracted into a standalone, LLM-agnostic library for use in any project that needs intelligent, context-aware memory retrieval.

License

Open Source: AGPL-3.0 — free to use, modify, and distribute with copyleft obligations. If you deploy a modified version as a network service, you must share your source code.

Commercial: For proprietary use without AGPL obligations, commercial licenses are available. Contact helix.agi.email@gmail.com for details.

About

Spatial Memory replaces standard cosine-similarity RAG with physics-inspired 8D manifold where memories and beliefs have: Mass — derived from confidence and affective encoding ; Temperature — recency heat that cools over time (Lorentzian decay); and Gravity — `F = T × m / d²` — hot, massive, nearby concepts pull attention

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages