Reflex-based memory system for AI agents - retrieval through activation, not search
Project description
๐ถ PugBrain: Reflex-based Neural Memory
Reflex-based memory system for AI agents โ retrieval through activation, not search.
PugBrain is a hybrid neural-vector memory system designed for long-term agent continuity. It combines graph relationships with vector embeddings to simulate "reflexive" recall.
๐ Quick Start
42 MCP tools ยท 14 memory types ยท 24 synapse types ยท Schema v22 ยท 3500+ tests ยท Cognitive reasoning layer
pip install neural-memory
๐ Features
- Hybrid Retrieval: Neural graph + Vector similarity.
- Built-in Dashboard: Visualize memory clusters and agent habits.
- MCP Support: Ready for Claude Desktop and OpenClaw.
- Pluggable Backends: SQLite (default), Neo4j, FalkorDB, ChromaDB.
๐ฅ Dashboard
Serve the memory system with a built-in UI:
pugbrain serve --port 18790
Visit: http://localhost:18790/ui
๐ง Core Philosophy
Memory shouldn't be a database query; it should be an activation signal. PugBrain treats entities as neurons that "fire" based on context.
Installation
pip install neural-memory
With optional features:
pip install neural-memory[server] # FastAPI server + dashboard
pip install neural-memory[extract] # PDF/DOCX/PPTX/HTML/XLSX extraction
pip install neural-memory[nlp-vi] # Vietnamese NLP
pip install neural-memory[embeddings] # Local embedding (cross-language recall)
pip install neural-memory[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):
# ~/.pugbrain/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/neural-memory
/plugin install neural-memory@neural-memory-marketplace
That's it. MCP server, skills, commands, and agent are all configured automatically via uvx.
OpenClaw (Plugin)
pip install neural-memory
npm install -g pugbrain
Then set the memory slot in ~/.openclaw/openclaw.json:
{ "plugins": { "slots": { "memory": "pugbrain" } } }
Restart the gateway. See the full setup guide.
Cursor / Windsurf / Other MCP Clients
pip install neural-memory
Then add to your editor's MCP config (Cursor: .cursor/mcp.json, Windsurf: ~/.codeium/windsurf/mcp_config.json):
{
"mcpServers": {
"pugbrain": {
"command": "pug-mcp"
}
}
}
The editor spawns pug-mcp automatically via stdio โ no manual server start needed. No pugbrain init needed โ auto-initializes on first use.
Usage
CLI
# Store memories (type auto-detected)
pugbrain remember "Fixed auth bug with null check in login.py:42"
pugbrain remember "We decided to use PostgreSQL" --type decision
pugbrain todo "Review PR #123" --priority 7
# Recall memories
pugbrain recall "auth bug"
pugbrain recall "database decision" --depth 2
# Shortcuts
pugbrain a "quick note" # Short for remember
pugbrain q "auth" # Short for recall
pugbrain last 5 # Last 5 memories
pugbrain today # Today's memories
# Get context for AI injection
pugbrain context --limit 10 --json
# Brain management
pugbrain brain list
pugbrain brain create work
pugbrain brain use work
pugbrain brain health
pugbrain brain export -o backup.json
pugbrain brain import backup.json
# Codebase indexing
pugbrain index src/ # Index code into neural memory
# Memory lifecycle
pugbrain decay # Apply forgetting curve
pugbrain consolidate # Prune, merge, summarize
pugbrain cleanup # Remove expired memories
# Visual tools
pugbrain serve # Start FastAPI server
# Then open http://localhost:8000/dashboard
# Telegram backup
pugbrain telegram status # Show Telegram config status
pugbrain telegram test # Send test message
pugbrain 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 42 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 |
pugbrain_edit |
Edit memory type, content, or priority (preserves connections) |
pugbrain_forget |
Soft delete (set expiry) or hard delete (permanent removal) |
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_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 |
Cognitive Reasoning:
| Tool | Description |
|---|---|
pugbrain_hypothesize |
Create and manage hypotheses with Bayesian confidence tracking |
pugbrain_evidence |
Submit evidence for/against hypotheses โ auto-updates confidence |
pugbrain_predict |
Make falsifiable predictions with deadlines, linked to hypotheses |
pugbrain_verify |
Verify predictions as correct/wrong โ propagates to linked hypotheses |
pugbrain_cognitive |
Hot index: ranked summary of active hypotheses + predictions |
pugbrain_gaps |
Knowledge gaps: detect, track, and resolve what the brain doesn't know |
pugbrain_schema |
Schema evolution: evolve hypotheses into new versions with SUPERSEDES links |
pugbrain_explain |
Trace shortest path between two concepts โ debug recall, verify connections |
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
pugbrain remember "Objective fact" --type fact
pugbrain remember "We chose X over Y" --type decision
pugbrain remember "User prefers dark mode" --type preference
pugbrain todo "Review the PR" --priority 7 --expires 30
pugbrain remember "Pattern: always validate input" --type insight
pugbrain remember "Meeting notes from standup" --type context --expires 7
pugbrain remember "Always run tests before push" --type instruction
pugbrain remember "Import failed: missing column" --type error
pugbrain remember "Deploy process: build โ test โ push" --type workflow
pugbrain 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 neural-memory[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
pugbrain 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.
Cognitive Reasoning
Hypothesize, predict, verify, and evolve beliefs โ the brain reasons about what it knows:
# Create a hypothesis with initial confidence
pugbrain_hypothesize(action="create", content="Redis is causing the latency spike", confidence=0.6)
# Submit evidence
pugbrain_evidence(hypothesis_id="h-1", evidence_type="for", content="Redis latency at 200ms")
pugbrain_evidence(hypothesis_id="h-1", evidence_type="against", content="Network latency was 500ms")
# Make a falsifiable prediction
pugbrain_predict(action="create", content="Switching to Valkey will fix latency",
hypothesis_id="h-1", deadline="2026-04-01")
# Verify prediction outcome โ propagates to linked hypothesis
pugbrain_verify(prediction_id="p-1", outcome="correct")
# Evolve hypothesis when understanding changes (creates SUPERSEDES chain)
pugbrain_schema(action="evolve", hypothesis_id="h-1",
content="Network config was root cause, not Redis",
reason="New evidence from network team")
# Track what the brain doesn't know
pugbrain_gaps(action="detect", topic="Why does latency spike at 3am?", source="recall_miss")
# View cognitive dashboard
pugbrain_cognitive(action="summary") # Hot index of active hypotheses + predictions
pugbrain_schema(action="history", hypothesis_id="h-2") # Version evolution chain
Auto-resolution: hypotheses with confidence โฅ0.9 + 3 supporting evidence โ auto-confirmed. Confidence โค0.1 + 3 against โ auto-refuted. Calibration score tracks prediction accuracy.
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
pugbrain 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 PUGBRAIN_TELEGRAM_BOT_TOKEN="your-bot-token"
# Add to config.toml:
# [telegram]
# enabled = true
# chat_ids = ["123456789"]
# CLI
pugbrain telegram status # Check config
pugbrain telegram test # Send test message
pugbrain telegram backup # Send brain backup
pugbrain 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
pugbrain 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
pugbrain check "API_KEY=sk-xxx"
# Auto-redact before storing
pugbrain remember "Config: API_KEY=sk-xxx" --redact
# Safe export (exclude sensitive neurons)
pugbrain brain export --exclude-sensitive -o safe.json
# Health check (freshness + sensitive scan)
pugbrain 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_tokensclamped to 10,000
Server Mode
pip install neural-memory[server]
pugbrain serve # localhost:8000
pugbrain serve -p 9000 # Custom port
pugbrain 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
pugbrain hooks install # Post-commit reminder to save commit messages
pugbrain hooks show # Show installed hooks
pugbrain hooks uninstall # Remove hooks
Development
git clone https://github.com/nhadaututtheky/neural-memory
cd neural-memory
pip install -e ".[dev]"
# Run tests (3500+ tests)
pytest tests/ -v
# Lint & format
ruff check src/ tests/
ruff format src/ tests/
Documentation
- Complete Guide โ Full documentation
- Integration Guide โ AI assistant & tool integration
- Safety & Limitations โ Security best practices
- Architecture โ Technical design
Support
If you find PugBrain useful, consider supporting development:
Solana: 5XVY6dZDeyuZJy6Co9KeLDxY5RZ6EwCpjsUVkacMz7HF
Contributing
Contributions welcome! See CONTRIBUTING.md.
License
MIT License โ see LICENSE.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file pug_brain-3.1.2.tar.gz.
File metadata
- Download URL: pug_brain-3.1.2.tar.gz
- Upload date:
- Size: 982.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
3cce32dc756f428265c382ed2f6056989b8e9068489dfad121474c46362cb50b
|
|
| MD5 |
89271a83c448c4bdd5adabb3e21ba491
|
|
| BLAKE2b-256 |
5024810bbfcd8018541f5307a40156b88f9eb91b041cafe4c2594d16ccb2e94d
|
Provenance
The following attestation bundles were made for pug_brain-3.1.2.tar.gz:
Publisher:
release.yml on tannht/pug-brain
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
pug_brain-3.1.2.tar.gz -
Subject digest:
3cce32dc756f428265c382ed2f6056989b8e9068489dfad121474c46362cb50b - Sigstore transparency entry: 1083253384
- Sigstore integration time:
-
Permalink:
tannht/pug-brain@4c5b3fb4994e3eb879807f30811b84a54cebba8d -
Branch / Tag:
refs/heads/pug-master - Owner: https://github.com/tannht
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@4c5b3fb4994e3eb879807f30811b84a54cebba8d -
Trigger Event:
workflow_dispatch
-
Statement type:
File details
Details for the file pug_brain-3.1.2-py3-none-any.whl.
File metadata
- Download URL: pug_brain-3.1.2-py3-none-any.whl
- Upload date:
- Size: 10.3 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
2a8f59b20da7b871d679630dc490bbf7162535fa9037160c70958ba7a6b12779
|
|
| MD5 |
99913777477efdcce84da5edfdf4277e
|
|
| BLAKE2b-256 |
0985f999398d9d533f34af18d6f4d23539b5068ec80f7383d3c52e8c143a90df
|
Provenance
The following attestation bundles were made for pug_brain-3.1.2-py3-none-any.whl:
Publisher:
release.yml on tannht/pug-brain
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
pug_brain-3.1.2-py3-none-any.whl -
Subject digest:
2a8f59b20da7b871d679630dc490bbf7162535fa9037160c70958ba7a6b12779 - Sigstore transparency entry: 1083253482
- Sigstore integration time:
-
Permalink:
tannht/pug-brain@4c5b3fb4994e3eb879807f30811b84a54cebba8d -
Branch / Tag:
refs/heads/pug-master - Owner: https://github.com/tannht
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@4c5b3fb4994e3eb879807f30811b84a54cebba8d -
Trigger Event:
workflow_dispatch
-
Statement type: