Skip to main content

Reflex-based memory system for AI agents - retrieval through activation, not search

Project description

๐Ÿถ PugBrain: The Hybrid Neural-Vector Intelligence Core

PyPI CI Python 3.11+ License: MIT VS Code OpenClaw Plugin Code style: ruff

PugBrain is an advanced hybrid memory system that bridges the gap between high-performance semantic search and associative neural reasoning. It fuses the speed of RuVector (Rust) with the causal intelligence of a graph-based neural network.

๐Ÿš€ The Neural Memory Architecture

graph TD
    User((User/Agent)) -->|Query/Remember| PugBrain[PugBrain Core Engine]
    
    subgraph "Neural Memory System"
        Encoder[Memory Encoder]
        Retrieval[Reflex Pipeline]
        Graph[Neural Graph Storage]
        
        PugBrain --> Encoder
        PugBrain --> Retrieval
        Encoder <--> Graph
        Retrieval <--> Graph
    end
    
    subgraph "Storage Backends"
        SQLite[(SQLite - Default)]
        FalkorDB[(FalkorDB - Optional)]
        Neo4j[(Neo4j - Optional)]
        
        Graph --> SQLite
        Graph -.-> FalkorDB
        Graph -.-> Neo4j
    end
    
    subgraph "Integration Layer"
        MCP[MCP Server]
        REST[FastAPI Server]
        CLI[CLI Interface]
        Dashboard[Web Dashboard]
        
        PugBrain --> MCP
        PugBrain --> REST
        PugBrain --> CLI
        REST --> Dashboard
    end
  • Neural Core: Graph-based memory with spreading activation for contextual recall and associative reasoning.
  • Multi-Backend: Default SQLite storage with optional FalkorDB or Neo4j for enhanced graph operations.
  • Integration Ready: MCP server for AI assistants, REST API, CLI tools, and web dashboard.

๐Ÿ›  Key Features

  • โœ… Activatable Intelligence: Neural graph with spreading activation for context-aware memory recall.
  • โœ… Hybrid Multiple Brains: Support for multiple independent brain instances with seamless switching.
  • โœ… Stabilized Dashboard: A modernized UI with automatic brain detection and zero-config CORS for reliable remote access.
  • โœ… Docker Native: Ready-to-use containerized deployment with persistent volume mapping.
  • โœ… MCP Ready: Standard Model Context Protocol server for seamless integration with Claude Code, Cursor, and OpenClaw.
  • โœ… Multi-format Training: PDF, DOCX, PPTX, HTML, JSON, XLSX, CSV, and Markdown document ingestion.
  • โœ… Code Indexing: Index and recall from codebases with syntax awareness.
  • โœ… Cross-Language Embedding: Optional embedding support for multi-language memory recall.

๐Ÿ“ฆ Installation & Setup

1. Python Package Installation

Install the core pug-brain package:

pip install pug-brain[server]

This provides the pug CLI command and FastAPI server with dashboard.

2. One-Line Installer

For a complete setup with dependencies:

curl -sSL https://raw.githubusercontent.com/tannht/pug-brain/pug-master/install.sh | bash

3. Manual Requirements

  • Python: 3.11+ (required)
  • Node.js: v18+ (for dashboard development)

โŒจ๏ธ CLI Usage

PugBrain provides a simple global command for all your memory needs:

# Remember a strategic decision
pug remember "Switched primary model to Gemini 3.1 Pro for better reasoning" --type decision --tags setup,ai

# Recall with context
pug recall "What is our current model configuration?"

# Check system health and stats
pug status

๐Ÿณ Docker Deployment

To run the PugBrain Core and Dashboard behind a proxy (like Caddy/Nginx) with persistent storage:

# Clone the repo
git clone -b pug-master https://github.com/tannht/pug-brain.git
cd pug-brain

# Build and start
docker compose up -d --build

The dashboard will be available at http://localhost:18790 (mapped from container port 8000).

๐Ÿ”„ Maintenance

Keep your brain sharp by running the update script:

/root/.openclaw/workspace/pug-brain/scripts/update-brain.sh

Installation

pip install pug-brain

With optional features:

pip install pug-brain[server]       # FastAPI server + dashboard
pip install pug-brain[extract]      # PDF/DOCX/PPTX/HTML/XLSX extraction
pip install pug-brain[nlp-vi]       # Vietnamese NLP
pip install pug-brain[embeddings]   # Local embedding (cross-language recall)
pip install pug-brain[all]          # All features

Optional: Embedding for Cross-Language Recall

Core recall works without embeddings. Enable embeddings to recall memories across languages (e.g., search in Vietnamese, find English memories):

# ~/.neuralmemory/config.toml
[embedding]
enabled = true
provider = "auto"    # Auto-detects: Ollama โ†’ sentence-transformers โ†’ Gemini โ†’ OpenAI

Or pick a specific provider: sentence_transformer (free/local), ollama (local via Ollama API), gemini (Google free tier), openai (paid). See the Embedding Setup Guide for details.

Quick Setup

Claude Code (Plugin โ€” Recommended)

/plugin marketplace add nhadaututtheky/pug-brain
/plugin install pug-brain@pug-brain-marketplace

That's it. MCP server, skills, commands, and agent are all configured automatically via uvx.

OpenClaw (Plugin)

pip install pug-brain
npm install -g neuralmemory

Then set the memory slot in ~/.openclaw/openclaw.json:

{ "plugins": { "slots": { "memory": "neuralmemory" } } }

Restart the gateway. See the full setup guide.

Cursor / Windsurf / Other MCP Clients

pip install pug-brain

Then add to your editor's MCP config (Cursor: .cursor/mcp.json, Windsurf: ~/.codeium/windsurf/mcp_config.json):

{
  "mcpServers": {
    "pug-brain": {
      "command": "pug-mcp"
    }
  }
}

The editor spawns pug-mcp automatically via stdio โ€” no manual server start needed. No pug init needed โ€” auto-initializes on first use.

Usage

CLI

# Store memories (type auto-detected)
pug remember "Fixed auth bug with null check in login.py:42"
pug remember "We decided to use PostgreSQL" --type decision
pug todo "Review PR #123" --priority 7

# Recall memories
pug recall "auth bug"
pug recall "database decision" --depth 2

# Shortcuts
pug a "quick note"           # Short for remember
pug q "auth"                 # Short for recall
pug last 5                   # Last 5 memories
pug today                    # Today's memories

# Get context for AI injection
pug context --limit 10 --json

# Brain management
pug brain list
pug brain create work
pug brain use work
pug brain health
pug brain export -o backup.json
pug brain import backup.json

# Codebase indexing
pug index src/               # Index code into neural memory

# Memory lifecycle
pug decay                    # Apply forgetting curve
pug consolidate              # Prune, merge, summarize
pug cleanup                  # Remove expired memories

# Visual tools
pug serve                    # Start FastAPI server
# Then open http://localhost:8000/dashboard

# Telegram backup
pug telegram status          # Show Telegram config status
pug telegram test            # Send test message
pug telegram backup          # Send brain .db to Telegram

Python API

import asyncio
from neural_memory import Brain
from neural_memory.storage import InMemoryStorage
from neural_memory.engine.encoder import MemoryEncoder
from neural_memory.engine.retrieval import ReflexPipeline

async def main():
    storage = InMemoryStorage()
    brain = Brain.create("my_brain")
    await storage.save_brain(brain)
    storage.set_brain(brain.id)

    # Encode memories
    encoder = MemoryEncoder(storage, brain.config)
    await encoder.encode("Met Alice to discuss API design")
    await encoder.encode("Decided to use FastAPI for backend")

    # Query through activation
    pipeline = ReflexPipeline(storage, brain.config)
    result = await pipeline.query("What did we decide about backend?")
    print(result.context)  # "Decided to use FastAPI for backend"

asyncio.run(main())

MCP Tools (Claude Code / Cursor)

Once configured, these 28 tools are available to your AI assistant:

Core Memory:

Tool Description
pugbrain_remember Store a memory (auto-detects type: fact, decision, insight, error, etc.)
pugbrain_recall Query with spreading activation (4 depth levels: instant/context/habit/deep)
pugbrain_context Get recent memories as session context
pugbrain_todo Quick TODO with 30-day expiry
pugbrain_auto Auto-capture memories from conversation text
pugbrain_suggest Autocomplete suggestions from brain neurons

Workflow:

Tool Description
pugbrain_session Track session state: task, feature, progress
pugbrain_eternal Save project context, decisions, instructions
pugbrain_recap Load saved context at session start
pugbrain_stats Brain statistics and health metrics
pugbrain_habits Workflow habit suggestions from usage patterns

Knowledge Base:

Tool Description
pugbrain_train Train brain from docs (PDF, DOCX, PPTX, HTML, JSON, XLSX, CSV, MD)
pugbrain_train_db Train brain from database schema
pugbrain_index Index codebase for code-aware recall
pugbrain_pin Pin/unpin memories (pinned = permanent, skip decay/prune)

Advanced:

Tool Description
pugbrain_health Brain health: purity score, grade (A-F), top penalties with fix actions
pugbrain_explain Trace shortest path between two concepts โ€” debug recall, verify connections
pugbrain_review Spaced repetition reviews (Leitner box system)
pugbrain_conflicts Memory conflicts: list, resolve, or pre-check
pugbrain_narrative Generate narratives: timeline, topic, or causal chain
pugbrain_alerts Brain health alerts: list or acknowledge
pugbrain_version Brain version control: snapshot, list, rollback, diff
pugbrain_transplant Transplant memories between brains by tags/types
pugbrain_import Import from ChromaDB, Mem0, Cognee, Graphiti, LlamaIndex
pugbrain_sync Multi-device sync (push/pull/full)
pugbrain_sync_status Sync status and pending changes
pugbrain_sync_config Configure sync settings
pugbrain_telegram_backup Send brain database backup to Telegram

VS Code Extension

Install from the VS Code Marketplace.

  • Memory tree view in the sidebar
  • Interactive graph explorer with Cytoscape.js
  • Encode from editor selections or comment triggers
  • CodeLens memory counts on functions and classes
  • Recap, eternal context, and codebase indexing commands
  • Real-time WebSocket sync

How It Works

Query: "What did Alice suggest?"
         โ”‚
         โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ 1. Decompose Query  โ”‚  โ†’ time hints, entities, intent
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
         โ”‚
         โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ 2. Find Anchors     โ”‚  โ†’ "Alice" neuron
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
         โ”‚
         โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ 3. Spread Activationโ”‚  โ†’ activate connected neurons
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
         โ”‚
         โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ 4. Find Intersectionโ”‚  โ†’ high-activation subgraph
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
         โ”‚
         โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ 5. Extract Context  โ”‚  โ†’ "Alice suggested rate limiting"
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Key Concepts

Concept What it is
Neuron A memory unit (concept, entity, action, time, state, spatial, sensory, intent)
Synapse A weighted, typed connection between neurons (CAUSED_BY, LEADS_TO, RESOLVED_BY, etc.)
Fiber A memory trace โ€” an ordered sequence of neurons forming a coherent experience
Spreading activation Signal propagates from anchor neurons through synapses, decaying with distance
Reflex pipeline Query โ†’ decompose โ†’ anchor โ†’ activate โ†’ intersect โ†’ extract context
Decay Memories lose activation over time following the Ebbinghaus forgetting curve
Consolidation Prune weak synapses, merge overlapping fibers, summarize topic clusters

Features

Memory Types

nmem remember "Objective fact" --type fact
nmem remember "We chose X over Y" --type decision
nmem remember "User prefers dark mode" --type preference
nmem todo "Review the PR" --priority 7 --expires 30
nmem remember "Pattern: always validate input" --type insight
nmem remember "Meeting notes from standup" --type context --expires 7
nmem remember "Always run tests before push" --type instruction
nmem remember "Import failed: missing column" --type error
nmem remember "Deploy process: build โ†’ test โ†’ push" --type workflow
nmem remember "API docs: https://..." --type reference

Knowledge Base Training

# Train from documents (permanent knowledge)
pugbrain_train(action="train", path="/docs/", domain_tag="project-docs")

# Supported formats: PDF, DOCX, PPTX, HTML, JSON, XLSX, CSV, MD, TXT, RST
# Trained memories are pinned โ€” they never decay, prune, or compress

# Pin/unpin specific memories
pugbrain_pin(fiber_ids=["abc123"], pinned=True)

Install extraction dependencies:

pip install pug-brain[extract]

Brain Health & Diagnostics

pugbrain_health()                       # Purity score, grade (A-F), top penalties
pugbrain_alerts(action="list")          # Active health alerts
pugbrain_review(action="queue")         # Spaced repetition review queue

Health reports include top_penalties โ€” a ranked list of what's hurting your score most, with exact fix actions. Always fix the highest penalty first.

7 components: Connectivity (25%), Diversity (20%), Freshness (15%), Consolidation (15%), Orphan Rate (10%), Activation (10%), Recall Confidence (5%).

See the Brain Health Guide for detailed explanations and improvement roadmap.

Connection Tracing

Trace the shortest path between two concepts in your neural graph:

# CLI
nmem explain "Redis" "auth outage"

# MCP tool
pugbrain_explain(entity_a="Redis", entity_b="auth outage")

Returns the path with evidence: Redis โ†’ USED_BY โ†’ session-store โ†’ CAUSED_BY โ†’ auth outage. Use this to debug recall, verify brain connections, or discover unexpected relationships between concepts.

Brain Versioning

pugbrain_version(action="create", name="v1-stable")  # Snapshot
pugbrain_version(action="list")                       # List versions
pugbrain_version(action="rollback", version_id="...")  # Restore
pugbrain_version(action="diff", from_version="...", to_version="...")

Web Dashboard

nmem serve                         # Start server on localhost:8000
# Open http://localhost:8000/dashboard  # React dashboard (7 pages)
# Open http://localhost:8000/docs       # API docs (Swagger)

Pages:

  • Overview โ€” KPI cards (neurons, synapses, fibers, brains) + brain table with click-to-switch and delete
  • Health โ€” Radar chart + health warnings + recommendations
  • Graph โ€” Sigma.js WebGL neural graph with ForceAtlas2 layout, color-coded by type, node inspector
  • Timeline โ€” Chronological memory feed with type badges
  • Evolution โ€” Brain maturity, plasticity, stage distribution charts
  • Mindmap โ€” ReactFlow interactive fiber mindmap (dagre tree, zoom/pan, MiniMap)
  • Settings โ€” Brain files, Telegram backup config

Light/Dark/System theme toggle with warm cream light mode.

Telegram Backup

Send brain .db files to Telegram for offsite backup:

# Setup: set env var + config
export NMEM_TELEGRAM_BOT_TOKEN="your-bot-token"
# Add to config.toml:
# [telegram]
# enabled = true
# chat_ids = ["123456789"]

# CLI
nmem telegram status              # Check config
nmem telegram test                # Send test message
nmem telegram backup              # Send brain backup
nmem telegram backup --brain work # Specific brain

# MCP tool
pugbrain_telegram_backup(brain_name="work")

Multi-Device Sync

pugbrain_sync(action="full")           # Bidirectional sync
pugbrain_sync_status()                 # Pending changes, devices
pugbrain_sync_config(action="set", hub_url="http://hub:8080")

External Memory Import

Import from existing memory systems:

# ChromaDB
nmem import backup.json --source chromadb

# Via MCP tool
pugbrain_import(source="mem0")           # Uses MEM0_API_KEY env var
pugbrain_import(source="chromadb", connection="/path/to/chroma")
pugbrain_import(source="cognee")         # Uses COGNEE_API_KEY env var
pugbrain_import(source="graphiti", connection="bolt://localhost:7687")
pugbrain_import(source="llamaindex", connection="/path/to/index")

Safety & Security

# Sensitive content detection
nmem check "API_KEY=sk-xxx"

# Auto-redact before storing
nmem remember "Config: API_KEY=sk-xxx" --redact

# Safe export (exclude sensitive neurons)
nmem brain export --exclude-sensitive -o safe.json

# Health check (freshness + sensitive scan)
nmem brain health
  • Content length validation (100KB limit)
  • ReDoS protection (text truncation before regex)
  • Spreading activation queue cap (prevents memory exhaustion)
  • API keys read from environment variables, never from tool parameters
  • max_tokens clamped to 10,000

Server Mode

pip install pug-brain[server]
nmem serve                    # localhost:8000
nmem serve -p 9000            # Custom port
nmem serve --host 0.0.0.0    # Expose to network

API endpoints:

POST /memory/encode     - Store memory
POST /memory/query      - Query memories
POST /brain/create      - Create brain
GET  /brain/{id}/export - Export brain
WS   /sync/ws           - Real-time sync
POST /hub/sync          - Multi-device incremental sync
GET  /hub/devices/{id}  - List registered devices
GET  /dashboard         - Web dashboard
GET  /docs              - API documentation

Git Hooks

nmem hooks install          # Post-commit reminder to save commit messages
nmem hooks show             # Show installed hooks
nmem hooks uninstall        # Remove hooks

Development

git clone https://github.com/nhadaututtheky/pug-brain
cd pug-brain
pip install -e ".[dev]"

# Run tests (2860+ tests)
pytest tests/ -v

# Lint & format
ruff check src/ tests/
ruff format src/ tests/

Documentation

Support

If you find NeuralMemory useful, consider supporting development:

Solana: 5XVY6dZDeyuZJy6Co9KeLDxY5RZ6EwCpjsUVkacMz7HF

Contributing

Contributions welcome! See CONTRIBUTING.md.

License

MIT License โ€” see LICENSE.

origin/main

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pug_brain-2.26.1.tar.gz (541.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pug_brain-2.26.1-py3-none-any.whl (687.7 kB view details)

Uploaded Python 3

File details

Details for the file pug_brain-2.26.1.tar.gz.

File metadata

  • Download URL: pug_brain-2.26.1.tar.gz
  • Upload date:
  • Size: 541.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.3

File hashes

Hashes for pug_brain-2.26.1.tar.gz
Algorithm Hash digest
SHA256 dc2d2a9c29efa18105db90fcc43b5e7b5a1f805f6cf950040abd0aaec48dd4e1
MD5 dd31dfb9ffbfcaf64a231d87c32c762e
BLAKE2b-256 2944c3f1d7df23ebf51e04b6ce8786954423eda07e167f93e429409502d53f3f

See more details on using hashes here.

File details

Details for the file pug_brain-2.26.1-py3-none-any.whl.

File metadata

  • Download URL: pug_brain-2.26.1-py3-none-any.whl
  • Upload date:
  • Size: 687.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.3

File hashes

Hashes for pug_brain-2.26.1-py3-none-any.whl
Algorithm Hash digest
SHA256 5564b92439e34495f14627607e309525a233cd0b44623c79f5f609ae398b82bf
MD5 b809b288ab3723e04448df5df434ef8f
BLAKE2b-256 8501dd99b85391a5930acba5a9af74c8f7c05cc0136d089bffd715221b97afa2

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page