--- title: Hipocampo MCP emoji: π§ colorFrom: blue colorTo: purple sdk: docker pinned: false ---
<p align="center"> <img src="assets/logo.png" alt="Hipocampo" width="180"/> </p>
<h1 align="center">Hipocampo</h1> <h3 align="center">Dual-Memory System with Sparse Selective Caching</h3>
<p align="center"> Persistent memory for autonomous AI agents Β· PostgreSQL 17 + pgvector Β· Hybrid Search Β· MCP Server </p>
     
β οΈ Transport Note: SSE transport is deprecated since MCP spec 2025-03-26. Hipocampo now uses Streamable HTTP (single endpoint
/mcp) as the recommended remote transport. SSE (/sse) remains available for backward compatibility but will be removed in a future release.
π MCP Server β Live on Hugging Face
Hipocampo runs as a free MCP server on Hugging Face Spaces. Connect from any MCP client:
URL: https://alexbell1-hipocampo-mcp.hf.space/mcp
π§ͺ Interactive Playground: Try saving and searching memories from your browser at https://alexbell1-hipocampo-mcp.hf.space/ β no registration or MCP client needed.
β οΈ Important: The Hugging Face free tier is ephemeral β data is lost on restart/deploy. This instance is intended for testing only. For persistent storage, run Hipocampo locally (see Quick Start) or connect an external database (Neon, Supabase, etc.).
{
"mcpServers": {
"hipocampo": {
"url": "https://alexbell1-hipocampo-mcp.hf.space/mcp",
"type": "streamable-http"
}
}
}
Embedding model: sentence-transformers/all-MiniLM-L6-v2 (384 dims) via Hugging Face Inference API (free, no credit card required).
---
Hipocampo is an advanced dual-memory persistence architecture designed for autonomous AI agents. By maintaining both technical knowledge and user profiling data across sessions, Hipocampo provides a reliable, stateful context that enables agents to learn, adapt, and scale efficiently.
Built on top of PostgreSQL 17 with pgvector, it features BIRE v3.7 β a hybrid retrieval engine combining semantic embeddings (1024d), lexical expansion, and GIN trigram search with dynamic score fusion. Also includes Sparse Selective Caching (SSC) as an experimental pipeline.
---
π‘ Why Prompt Compression?
Hipocampo already reduces context through SSC (selective retrieval). But even the top-5 most relevant memories can consume 500-2000+ tokens when concatenated β a significant portion of any LLM's context window.
Hybrid compression adds a second reduction layer:
- Extractive phase: Removes redundant sentences (filtering by keyword relevance to your query). Reduces generic text by 30-50% instantly, with no API calls.
- LLM phase: Summarizes technical/code content using the same NVIDIA NIM endpoint already used for embeddings. Preserves all code, variable names, and syntax while dropping explanatory verbosity.
- Combined: 20-50% token reduction with near-zero quality loss. A 1500-token memory block becomes 750-1200 tokens β that's real savings on every LLM call.
Real impact: If you call compress_hipocampo before every search_hipocampo β LLM round-trip, you save 200-800 tokens per interaction. At scale (hundreds of queries), this translates to meaningful cost reduction and faster responses.
π Key Features
- Dual-Memory Architecture: Distinct storage layers for technical records (
memoria_vectorial) and user profile data (memory_items), each utilizing 1024-dimensional embeddings. - BIRE v3.7 (default): Hybrid search engine combining NVIDIA embeddings (1024d), query expansion, GIN trigram, and composite scoring β used by all MCP tools.
- SSC (experimental): Alternative four-phase progressive pipeline: Tag Router β pgvector Top-K β GIN Trigram β ILIKE Fallback.
- Logarithmic Checkpointing: Intelligently compresses historical memories based on time decay, shrinking 24-hour granular details into unified 90-day checkpoints.
- Automated Tagging Engine: A robust, Regex-based rule engine that autonomously categorizes and tags records upon persistence.
- Cross-System Vector Search: Unified semantic search across over 1,100 records for deep cross-referencing.
- Hybrid Prompt Compression (v4.0): Two-phase compression pipeline β extractive (sentence-level) for generic text and LLM summarization (via NVIDIA NIM) for technical/code content. Reduces prompt tokens by 20-50% while preserving critical information. Available as
compress_hipocampoMCP tool. - Memory Graph (v4.0): Directed graph of semantic relationships between memories. Link related records, navigate with BFS tree, find shortest paths. Available as
link_hipocampo,graph_hipocampo,path_hipocampoMCP tools. - Memory Hierarchy with Trigger-Based Prevention (v4.1): π§ π§ Three-level memory (episodic β semantic β automatic) inspired by human mnemonic consolidation. NEW: Tag memories with contextual triggers (
trigger:php,trigger:chartjs,trigger:tomcat) β when the agent starts working in that context, it searches for matchingautomaticarules and reactivates past errors before making the same mistake. This mirrors the biological hippocampus: a partial cue (project + language) triggers full memory retrieval of the error and its solution. Automatic rules are permanent β never compressed, never deleted.set_nivel_hipocampo(id, nivel)+consolidate_hipocampotools included. - Code Immune System β Regression Protection (v4.2): π‘οΈ Prevents agents from breaking code that was working. 3-step cycle: (1) Snapshot functional state before editing, (2) Verify after editing, (3) If something broke β create a permanent
automaticarule capturing the exact cause, symptom, and fix. Uses immune economy: pre-change snapshots are cheapepisodica(auto-compressed if no damage), post-break rules are permanentautomatica. Pre-loaded with fragile file catalog β header.php, conexion.php, utils.php, auth.php, etc. Agents searchtrigger:regression trigger:<file>before every edit to learn what other agents broke before. - Code RAG (v4.0): Index project source code (PHP, JS, TS, Python, SQL) as semantic embeddings. Search with
search_code(query, language)β returns real code snippets with file paths and line numbers, not just summaries. - Exponential Time Decay (v4.0):
final_score = relevance Γ exp(-Ξ» Γ days)with Ξ»=0.05 configurable and 20% floor. Recent knowledge naturally outranks old memories. - MMR Diversity Anti-Cluster (v4.3): Maximum Marginal Relevance post-fusion re-ranking prevents dense embedding clusters from monopolizing search results. Iteratively selects results that balance relevance with diversity:
diversity_lambda Γ relevance - (1-diversity_lambda) Γ max_similarity_to_selected. Configurable inhipocampo_hybrid_config.json. - Link Weight Decay (v4.3): Exponential weight decay on memory graph links (half-life 90 days). Links that aren't traversed lose strength over time; links <0.01 are pruned.
graph_hipocampo()andpath_hipocampo()auto-reinforce traversed links. Newdecay_hipocampo(dry_run)tool for graph maintenance. Columns:last_accessed,reinforced_at. - Session Memory & Auto-Summarization: Session-isolated save/search. After 20+ saves, Hipocampo auto-generates a consolidated session summary in the background.
- Proactive Context Preloading:
preload_context(project_path)extracts meaningful keywords from the project path, searches relevant memories, and returns a compressed summary β ideal for session start. - Context Budget Awareness:
compress_hipocampoauto-estimates token budget and adjusts k dynamically.budget_ratioparameter gives fine-grained control over output size. - Auto-Linking:
save_hipocampo(..., auto_link=True)auto-discovers semantically similar memories (>0.75 cosine) and createssimilaredges in the memory graph. - HNSW Auto-Recovery:
hipocampo_health()checks the HNSW index on startup and auto-creates it if missing β no more manualCREATE INDEXcommands. - Model Context Protocol (MCP): Native integration via a FastMCP server with 25 tools, exposing seamless read/write capabilities to modern MCP clients (e.g., Claude Desktop, OpenCode).
---
β‘ Why PostgreSQL + pgvector (Not SQLite)?
You might wonder why Hipocampo uses PostgreSQL 17 with pgvector instead of a lighter stack like SQLite. The answer: hybrid search requires more than vector similarity alone.
Hipocampo's retrieval pipeline combines pgvector (HNSW) for semantic search, pg_trgm (GIN) for lexical expansion, and ILIKE for fallback β fused into a single weighted score. SQLite extensions like sqlite-vec offer vector search, but lack:
- GIN trigram indexes for fuzzy/partial matching
- Full-text + vector hybrid fusion in a single query
- Production-grade HNSW indexing with concurrent writes
- pg_trgm-based query expansion when embeddings alone are insufficient
With ~1,100+ records across two memory tables and growing, Hipocampo needs a database that scales without sacrificing retrieval quality. PostgreSQL + pgvector isn't "heavy" for the sake of it β it's the minimum viable stack to deliver the hybrid accuracy that BIRE and SSC require.
---
π― Use Cases
Error β Learn β Never Repeat (AI Agent Learning Loop)
Hipocampo enables AI agents to learn from mistakes across sessions using a simple cycle:
ββ 1. SEARCH ββββββββββββββββββββββββββββββ
β Before executing a command, the agent β
β searches Hipocampo for similar errors: β
β search_hipocampo("error <context>") β
βββββββββββββββββββββ¬βββββββββββββββββββββββ
β
ββ 2. EXECUTE βββββββΌβββββββββββββββββββββββ
β If match found β apply known solution β
β If not β attempt new approach β
βββββββββββββββββββββ¬βββββββββββββββββββββββ
β
ββ 3. EVALUATE ββββββΌβββββββββββββββββββββββ
β Did it fail? Capture: β
β - error context & exit code β
β - what was attempted β
β - what happened β
βββββββββββββββββββββ¬βββββββββββββββββββββββ
β
ββ 4. PERSIST βββββββΌβββββββββββββββββββββββ
β save_hipocampo( β
β content="Error X: tried Y, result Z", β
β memory_type="decision", β
β code="error_<hash>", β
β categories=["bugfix", "<tool>"] β
β ) β
ββββββββββββββββββββββββββββββββββββββββββββ
Real example: An agent tries flatpak install npm and fails. It saves the error to Hipocampo: "npm is a Node.js package manager, not a Flatpak package. Use npm directly." Next time the same command is attempted, the agent finds this record and knows the solution immediately β without repeating the mistake.
Over time, the agent's error knowledge base grows organically. Each failure makes future sessions smarter. This turns Hipocampo from a simple archive into a continuous learning system for AI agents.
π§ Context-Aware Error Prevention (NEW v4.1) β Proactive, not Reactive
Going beyond reactive learning, Hipocampo v4.1 introduces trigger-based automatic rules that fire before the agent writes a single line of code:
ββ 1. DETECT CONTEXT ββββββββββββββββββββββββββββββββ
β Agent is about to edit a PHP file in SGV.pro: β
β File: analisis_visual.php β
β Library: Chart.js β
β Language: PHP β
ββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ
β
ββ 2. SEARCH TRIGGERS ββββΌββββββββββββββββββββββββββββ
β search_hipocampo("trigger:sgv trigger:chartjs β
β trigger:php trigger:json_encode")β
ββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ
β
ββ 3. REACTIVATE RULES ββΌβββββββββββββββββββββββββββββ
β REGLA AUTOMΓTICA FOUND (score 31.0): β
β "NUNCA usar variables JS (C.red, C.primary) β
β dentro de <?= json_encode() ?> en PHP. β
β PHP las evalΓΊa como constantes β Fatal Error." β
β SoluciΓ³n: usar literales #ef4444 / #408AEC β
ββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ
β
ββ 4. ACT WITH CONSTRAINT ββΌββββββββββββββββββββββββββ
β Agent generates code using color literals instead β
β of JS variables. Error avoided BEFORE it happens. β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
How to implement:
# 1. When saving an error, tag it with contextual triggers and elevate to automatica
save_hipocampo(
content="NUNCA usar variables JS en json_encode() PHP. Usar literales de color.",
memory_type="decision",
categories=["trigger:sgv", "trigger:chartjs", "trigger:php", "trigger:json_encode"],
nivel="automatica"
)
# 2. Before editing code in any project, search matching triggers
search_hipocampo("trigger:<project> trigger:<language> trigger:<tech>")
# 3. Automatic rules surface β agent applies them preventively
This mirrors the biological hippocampus: a partial cue triggers full memory retrieval β the brain doesn't wait for the error to happen before remembering it hurts.
π‘οΈ Regression Protection β Code Immune System (NEW v4.2)
Sometimes the agent breaks code that was working fine β not repeating an old error, but creating a new one. Hipocampo v4.2 implements a 3-step immune cycle that mirrors how the body generates antibodies:
ββ 1. SNAPSHOT βββββββββββββββββββββββββββββββββββ
β Before editing header.php, save what works: β
β "header.php depends on session_start(). β
β Verify: open dashboard.php, must load OK." β
β Cost: episodica (cheap, auto-compressed) β
βββββββββββββββββββββ¬ββββββββββββββββββββββββββββββ
β
ββ 2. VERIFY ββββββββΌββββββββββββββββββββββββββββββ
β After editing, run the snapshot verification: β
β - Dashboard loads OK β no cost, snapshot fades β
β - HTTP 500 on all pages β immune response! β
βββββββββββββββββββββ¬ββββββββββββββββββββββββββββββ
β
ββ 3. IMMUNIZE ββββββΌββββββββββββββββββββββββββββββ
β Save permanent automatica rule: β
β "Editing header.php: removed session_start(), β
β broke 40+ pages. Fix: restore session_start() β
β at top of file. NEVER touch this line." β
β Cost: automatica (permanent, never compressed) β
βββββββββββββββββββββββββββββββββββββββββββββββββββ
Fragile file catalog (pre-loaded): header.php, conexion.php, utils.php, auth.php, db_connection.php β these files have cascading dependencies. One wrong edit breaks dozens of pages. Hipocampo ships with fragile file rules so agents know what to handle with care.
Before every edit: search_hipocampo("trigger:regression trigger:<file> trigger:<project>") β learn what other agents broke on this file before you touch it.
βοΈ How to configure your agent
To enable this behavior, you need to instruct your agent to use the cycle above. This is done by adding instructions to the agent's configuration file, depending on the client:
| Agent | Configuration file | Example | |---|---|---| | OpenCode | AGENTS.md (project root) or ~/.opencode/AGENTS.md | See example | | Claude Code | CLAUDE.md or ~/.claude/CLAUDE.md | Similar approach | | Cursor | .cursorrules | Add instructions in plain text | | Windsurf | .windsurfrules | Same structure | | Cline | CLINE.md | Same structure |
Minimal example for AGENTS.md / CLAUDE.md:
## Error Learning Cycle
1. Before running any command, search: `search_hipocampo("error <command> <context>")`
2. If a similar error is found, apply the documented solution and skip the failing attempt
3. If the command fails (exit code != 0, timeout, "error"/"failed" in output):
- Save to Hipocampo: `save_hipocampo(content="Error: {stderr[:500]}. Attempt: {what was tried}. Result: {what happened}.", memory_type="decision", code="error_<hash>", categories=["bugfix", "<language/tool>"])`
π‘ Tip: For MCP-native agents (OpenCode, Claude Code), Hipocampo tools are available directly. For others, use the HTTP endpoint or CLI scripts.
π Want your agent to use ALL of Hipocampo? Append AGENTS_TEMPLATE.md sections into your AGENTS.md / CLAUDE.md / .cursorrules β safe to share, no credentials.
Other use cases
- Persistent user profile: Remember preferences, configs, and personal data across sessions
- Project state tracking: Keep context on ongoing projects, decisions made, and pending tasks
- Cross-session knowledge: Build on previous work without repeating context
---
π οΈ Quick Start
Prerequisites
- PostgreSQL 17+ (with
pgvectorandpg_trgmextensions enabled) - Python 3.13+
- NVIDIA API Key (for
nvidia/nv-embedqa-e5-v5embeddings) β or Hugging Face API Key forsentence-transformers/all-MiniLM-L6-v2(free via HF Inference API)
Installation
# 1. Clone the repository
git clone https://github.com/carrasquelalex1/hipocampo.git
cd hipocampo
# 2. Setup the PostgreSQL Database
createdb hipocampo_db
psql -d hipocampo_db -c "CREATE EXTENSION vector; CREATE EXTENSION pg_trgm;"
psql -d hipocampo_db -f esquema.sql
# 3. Initialize Python Environment
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
# 4. Environment Configuration
cp .env.example .env
# Edit .env with your DB_HOST, DB_USER, and NVIDIA_API_KEY
Basic Usage
Hipocampo provides specialized scripts to interact with the core engine:
# Perform a search using BIRE v3.7 (modern, recommended)
python3 scripts/hipocampo_search.py "query term"
# Perform a search using SSC v1.0 (experimental, legacy)
python3 scripts/hipocampo_ssc_search.py "query term"
# Compress older memories using Logarithmic Checkpointing
python3 scripts/hipocampo_checkpoint.py --dry-run
python3 scripts/hipocampo_checkpoint.py --force
# Hybrid prompt compression (extractive + LLM)
python3 scripts/hipocampo_compress.py "your query" --k 5 --method hybrid
python3 scripts/hipocampo_compress.py "your query" --method extractive # fastest, no API cost
---
π§ System Architecture
The core of Hipocampo is backed by a relational and vector hybrid design:
hipocampo_db (PostgreSQL 17 + pgvector + pg_trgm)
βββ memoria_vectorial (Technical Knowledge)
β βββ Columns: contenido (text), metadatos (jsonb), embedding (vector 1024d)
β βββ Indexes: HNSW (cosine similarity, 1024d), GIN (trigram)
βββ memory_items (User Profile & Events)
β βββ Columns: memory_type (profile|event|decision), summary, embedding, extra
β βββ Indexes: HNSW (cosine similarity, 1024d), GIN (trigram)
βββ memory_categories (Classification Taxonomy)
βββ category_items (M:N Mapping)
βββ resources (Referenced Assets & URLs)
BIRE v3.7 β Hybrid Search Engine
BIRE (BΓΊsqueda Integrada por Relevancia Expansiva) is the default search engine used by all MCP tools. It combines vector and lexical search with dynamic score fusion:
- Query Expansion β Expands terms using synonyms and stemming before search.
- Vector Search β NVIDIA embeddings (1024d) cosine similarity across both tables.
- GIN Trigram β Lexical expansion when vector confidence is low.
- Composite Scoring β Weighted fusion of vector + lexical scores with adaptive cutoff.
An SSC (Sparse Selective Caching) pipeline is also available as an experimental alternative:
- Phase 1: Tag Router β Classifies the query intent (profile vs. technical) and dynamically assigns weights.
- Phase 2: PGVector Top-K β Semantic search across both tables. Execution halts here if confidence β₯ 70%.
- Phase 3: GIN Trigram β Lexical expansion via Trigram indexing if semantic confidence is < 70%.
- Phase 4: ILIKE Scan β Final fallback full-table scan triggered only if confidence falls < 40%.
---
π MCP Server Integration
Hipocampo includes a fully functional FastMCP server, allowing LLM agents to autonomously read and write memories.
Available MCP Tools (25 tools)
Memory Operations:
search_hipocampo(query, session_id?): Unified semantic and lexical search (auto-records metrics). Optionally filter by session.quick_hipocampo_search(query): Shorthand alias for rapid queries.preload_context(project_path, k=8): Extract keywords from project path, search relevant memories, return compressed summary. Ideal for session initialization.compress_hipocampo(query, k=5, method="hybrid", budget_ratio=1.0, include_metadata=False): Search + hybrid compression with context budget awareness. Auto-estimates tokens and adjusts k dynamically. Three methods:"hybrid"(recommended),"extractive"(fastest, no API cost),"llm"(highest quality).save_hipocampo(content, memory_type, code, categories, session_id?, force?, auto_link=False, nivel="episodica"): Persist data intomemoria_vectorial. Supports session isolation, auto-dedup, auto-linking, and hierarchical memory levels.profile_hipocampo(summary, extra, categories): Store personal or event-driven user data (memory_items).
Memory Graph (v4.0):
link_hipocampo(source_id, target_id, relation_type, weight): Create a directed edge between two memories. Relation types:related,follow_up,part_of,references,similar,chain.unlink_hipocampo(id / source+target+type): Remove edge(s) from the memory graph.graph_hipocampo(node_id, depth=2): BFS tree traversal from a root node. Usenode_id=0for an overview of all connected nodes and edge counts.path_hipocampo(from_id, to_id, max_depth=5): Find the shortest BFS path between two memories.
Code RAG (v4.0):
index_project(project_path, force=False): Scan and index source code files as semantic embeddings. Incremental β only re-indexes changed files (by mtime). Supports PHP, JS, TS, Python, SQL, HTML, CSS, JSON, YAML.search_code(query, k=5, language=""): Vector search specifically in indexed code snippets. Returns real code with file paths, language, and line numbers.
CRUD Operations:
update_hipocampo(id, content?, memory_type?, code?, categories?): Update an existing memory. Regenerates embedding if content changes.delete_hipocampo(id): Permanently delete a memory by ID.set_nivel_hipocampo(id, nivel): Promote/demote a memory between hierarchical levels (episodica,semantica,automatica).consolidate_hipocampo(min_age_days=7, dry_run=True): Migrate old episodic memories to semantic level with optional content compression.
Self-Diagnosis & Auto-Repair:
hipocampo_health(): Full system health check (PostgreSQL, NVIDIA API, disk, extensions, HNSW index).hipocampo_auto_repair(): Automatically repairs detected issues (restart PostgreSQL, create missing tables, create HNSW index).
Performance Optimization (Fase 2):
hipocampo_stats(): Query performance metrics, latency analysis, and optimization recommendations.hipocampo_tune(): Auto-adjusts BIRE/SSC thresholds and hybrid weights based on real usage data.
Memory Maintenance (Fase 3):
hipocampo_dedup(merge): Detects and merges duplicate memories (exact + semantic via cosine similarity).hipocampo_checkpoint(dry_run): Logarithmic checkpointing to compress old memories.hipocampo_maintenance(): Full maintenance cycle (repair β dedup β checkpoint β tune).
Time Decay:
- Scores of memories >7 days old automatically decay ~5% per week (floor at 30%), keeping recent knowledge at the top.
Webhook Watches:
watch_hipocampo(pattern, webhook_url): Register a webhook that fires on save/update/delete events matching a text pattern.unwatch_hipocampo(id): Remove a registered webhook.list_watches(): List all registered webhooks and their targets.
Starting the Server
# Standard I/O mode (default for local desktop clients)
python3 scripts/hipocampo_mcp_server.py
# Streamable HTTP mode (recommended for remote clients)
python3 scripts/hipocampo_mcp_server.py --http 8001
# Legacy SSE mode (deprecated, only for backward compatibility)
python3 scripts/hipocampo_mcp_server.py --sse 8001
For advanced configuration, please refer to the MCP Server Guide.
Modular Architecture
DB connection, config loading, and embedding generation are centralized in the hipocampo package:
hipocampo/
βββ __init__.py # Package init (version 3.8)
βββ db.py # get_conn(), get_embedding(), load_config()
All scripts in scripts/ import from hipocampo.db instead of duplicating the boilerplate. The MCP server also imports search/health/stats/dedup/checkpoint functions directly β no subprocess calls.
Before: Each MCP search spawned subprocess.run() β fork Python interpreter β re-import everything β connect DB β generate embedding β run query β parse stdout. That's ~200β500ms of process + serialization overhead alone.
After: Direct function call within the same process. The DB connection pool, OpenAI client, and modules are already cached. Overhead drops to microseconds.
For individual searches the difference is marginal (~200ms), but for hipocampo_maintenance() it previously ran 4 serial subprocess forks β now it's one direct call per phase, saving ~1β2 seconds.
Async & Connection Pool (v3.8)
The MCP server now runs all 16 tools as async Python coroutines in HTTP mode, and uses a PostgreSQL connection pool instead of creating a new connection per call:
Before:
- Each MCP tool opened a new TCP + SSL connection to PostgreSQL β
connect()latency on every call - Sync tools blocked uvicorn's event loop β one slow
searchfroze the server for all concurrent clients - In HTTP mode with concurrent requests: risk of
too many connectionson the database
After:
init_pool(minconn=1, maxconn=10)creates aThreadedConnectionPoolat server startup β connections are reused across calls, handshake happens once- All 16 tools are
async defβ blocking I/O (DB queries, NVIDIA API) runs inasyncio.to_thread(), freeing the event loop for other requests - A thin
_PooledConnectionproxy transparently returns connections to the pool when.close()is called β zero caller-side changes
Impact: Concurrent requests no longer block each other; PostgreSQL connection overhead drops from ~10β50ms per call to near zero.
Integration Tests:
- 6 schema tests verify tool registration, annotations, parameters, and async signature β no database required, run in CI
- 3 live integration tests (marked
@pytest.mark.integration) start the server in stdio mode and verify tools/list, resources/list, and a real search call - 102 total tests, all passing
Config Validation, Rate Limiting & Granular Errors (v3.8)
Before:
- Missing
NVIDIA_API_KEYorDB_HOSTβ server started without errors, failed with crypticfe_sendauth/401on the first query - Any client could hammer the NVIDIA API (
$per embedding) and the free-tier PostgreSQL β no limits at all - Every error caught with
except Exception: logger.error("msg: %s", e)β no traceback, impossible to tell if it was a DB, network, or validation failure
After:
validate_config()runs at startup and logs clear warnings for each missing variable.init_pool()andget_conn()reject early with messages like "PostgreSQL connection incomplete: DB_HOST, DB_USER not configured in .env"- Three sliding-window rate limiters protect the system:
embedding_limiter(30/min β shields NVIDIA API cost),tool_limiter(60/min β shields PostgreSQL),watch_limiter(20/min). Clients get "β³ Too many requests. Limit: 30 per 60s. Wait 12s." _tool_err()helper differentiates by exception type:psycopg2.Errorβlogger.exception()with full traceback,ValueError/TypeErrorβlogger.warning()(client error), others βlogger.exception()._fire_webhookscatchesurllib.error.URLErrorseparately
Impact: Failures are caught before they reach the database, costs are capped, and logs are actionable β you know instantly if it's a misconfiguration, a network blip, or a code bug.
Retry with Backoff, Consistent CLI & Pre-commit Hooks (v3.8)
Before:
get_embedding()failed on the first NVIDIA API timeout or rate limit β no retry at all- All 12 scripts used manual
sys.argvparsing β no--help, no type validation, inconsistent interfaces - No pre-commit hooks β easy to push code with lint errors or broken tests
After:
get_embedding()usestenacitywithwait_exponential(mult=1, min=1, max=30), 5 attempts, retrying only onRateLimitError/APITimeoutError/APIConnectionError/InternalServerError. No retry onAuthenticationErrororBadRequestError. Each retry is logged atwarninglevel- All 12 scripts have
argparsewith--help, typed arguments, and consistent names:hipocampo_mcp_server.py --http 8001 .pre-commit-config.yamlwith ruff lint+format (pre-commit) and pytest (pre-push).pyproject.tomlconfigures ruff with line-length 120
Impact: The server tolerates transient API failures without the client seeing errors. CLI is self-documenting. Every commit is verified before reaching GitHub β no more broken tests on main.
---
Local Fixes, compress_hipocampo Tool, and symlink-based Structure (v3.9)
Before:
- Scripts in
scripts/were independent copies of the repo β eachgit pullrequired manual sync, and new files likehipocampo_compress.pywere missing - Local scripts (user-owned) lived in the same
scripts/directory β no separation from repo files - The
hipocampo/Python package was also a copy:load_config()looked for.envinproject_root/.envinstead of~/.hipocampo/.env, loading incorrect credentials (alex/hipocampo123) - If NVIDIA NIM API returned transient HTTP errors (403, 429, timeout),
compressoperations failed with a generic exception - The
query_statstable existed inesquema.sqlbut was never auto-created βhipocampo_healthreportedDEGRADED - 4 scripts called
register_vector(conn)on the_PooledConnectionfromget_conn()β psycopg2 rejected it withTypeError, breaking all vector operations - Integration tests sent raw JSON-RPC to FastMCP v1.27+ β missing the
initializehandshake, failing withInvalid request parameters
Now:
~/.hipocampo/is the canonical home:repo/(git clone),~/.hipocampo/scripts/βrepo/scripts/(symlink),~/.hipocampo/hipocampo/βrepo/hipocampo/(symlink). Local user scripts moved to~/.hipocampo/local_scripts/.git pullonrepo/auto-updates everything_find_env()indb.pyloads.envin deterministic order:ENV_PATHenv var β~/.hipocampo/.env(explicit user config) βproject_root/.env(Docker/Fly). No more wrong credentialsensure_stats_table()runs at module import time in the MCP server βquery_statstable auto-created on starthipocampo_compress.pywith explicit exception handling:RateLimitError,APITimeoutError,APIConnectionError,APIStatusErrorβ immediate fallback to extractive compression. All other errors β fallback with distinct warning levelregister_vector(conn)removed fromhipocampo_search.py,hipocampo_checkpoint.py,hipocampo_calibrate.py,mm_brain_tool.pyβget_conn()already registers the vector adapter on the real connection- Integration tests rewritten with
mcp[client]SDK (stdio_client+ClientSession+initialize()) β proper MCP 2025-03-26 handshake - 105 tests total, all passing
Impact: Zero-touch maintenance after git pull. Transient NVIDIA API errors degrade gracefully. Config loading is deterministic and secure. Vector operations work reliably. Tests follow the official MCP protocol.
---
β Support / Donaciones
If this project helps you, consider supporting its development:
 
- PayPal: paypal.me/carrasquealex
- USDT (TRC-20): (prΓ³ximamente)
- Cada grano de arena ayuda a mantener el proyecto vivo π§ β¨
---
β‘ Performance Optimizations (v3.9)
Optimizations applied in July 2026 to address latency and threshold drift:
Embedding Cache
get_embedding() now uses an LRU cache (128 entries) β repeated queries for identical text skip the NVIDIA API call entirely, saving ~450ms each. The OpenAI client is also reused across calls instead of being recreated.
SSC Search Acceleration
SSC_TOP_Kreduced from 20 β 15: fewer vector results per table means faster vector searchhnsw.ef_search = 20: lower HNSW breadth-of-search for approximate (faster) nearest neighbors (default was 40)CONFIANZA_ALTAlowered from 70 β 60: early exit from the SSC pipeline sooner when vector results are already good- Early exit: if β₯3 results already exceed the minimum threshold, trigram and ILIKE phases are skipped entirely
register_vectorcached per connection to avoid redundant SQL introspection
Threshold Reset & Sane Auto-Tune
alphareset from 0.6 β 0.5 (balanced 50% vector + 50% lexical),vectorial_confidence_minfrom 0.75 β 0.70- Auto-tune (
hipocampo_tune()) now capped: alpha stays within 0.4β0.6, confidence within 0.5β0.75 - Auto-tune can now decrease alpha too (if scores are high enough, reduces vector bias)
Health Check Improvements
- Reports PostgreSQL version and pgvector version for compatibility diagnostics
- Verifies
register_vector()and detects the pgvector/PG17indamincompatibility with a clear upgrade message
---
π§ͺ Testing
Hipocampo includes 105+ unit tests covering all core logic and MCP integration:
| Test file | What it covers | |-----------|---------------| | tests/test_search.py | Query expansion (stem map + synonyms), score fusion with dynamic alpha, temporal decay (5%/week), result formatting | | tests/test_autotag.py | All 17 tag rules, 16 category rules, memory_type auto-detection | | tests/test_dedup.py | Cosine similarity (including 1024-dim vectors), exact and semantic duplicate detection logic | | tests/test_checkpoint.py | Age scale classification, project grouping, summary generation | | tests/test_mcp_integration.py | 6 schema tests (tool registration, annotations, params, async signature) + 3 live integration tests (stdio server, mcp[client] SDK) | | tests/test_rate_limit.py | Sliding-window rate limiter: acquire/release, prune, stats, default limiters | | tests/test_db.py | Config validation: missing DB_HOST, NVIDIA_API_KEY, comprehensive coverage |
# Run all tests
python3 -m pytest tests/ -v
# Run with coverage
python3 -m pytest tests/ --cov=scripts --cov-report=term-missing
Tests run automatically on every push via GitHub Actions on Python 3.11β3.13.
π License
This project is licensed under the MIT License.
---
πͺπΈ VersiΓ³n en EspaΓ±ol
<p align="center"> <img src="assets/logo.png" alt="Hipocampo" width="160"/> </p>
<h1 align="center">Hipocampo</h1> <h3 align="center">Sistema de Memoria Dual con CachΓ© Selectivo (CS)</h3>
<p align="center"> Memoria persistente para agentes de IA autΓ³nomos Β· PostgreSQL 17 + pgvector Β· BΓΊsqueda HΓbrida Β· Servidor MCP </p>
  
β οΈ Nota de Transporte: SSE estΓ‘ deprecado desde spec MCP 2025-03-26. Hipocampo ahora usa Streamable HTTP (endpoint ΓΊnico
/mcp) como transporte remoto recomendado.
π Servidor MCP β Live en Hugging Face
Hipocampo corre como servidor MCP gratuito en Hugging Face Spaces. ConΓ©ctate desde cualquier cliente MCP:
{
"mcpServers": {
"hipocampo": {
"url": "https://alexbell1-hipocampo-mcp.hf.space/mcp",
"type": "streamable-http"
}
}
}
π§ͺ Playground interactivo: Prueba guardar y buscar recuerdos desde el navegador en https://alexbell1-hipocampo-mcp.hf.space/ β sin registro ni cliente MCP.
β οΈ Importante: El tier gratuito de Hugging Face es efΓmero β los datos se pierden al reiniciar/desplegar. Esta instancia es solo para pruebas. Para persistencia real, ejecuta Hipocampo localmente o conecta una base externa.
Hipocampo es una arquitectura avanzada de persistencia de memoria dual diseΓ±ada para agentes de Inteligencia Artificial. Al mantener tanto el conocimiento tΓ©cnico como los datos del perfil del usuario entre sesiones, Hipocampo proporciona un contexto con estado confiable que permite a los agentes aprender, adaptarse y escalar eficientemente.
Construido sobre PostgreSQL 17 y pgvector, utiliza BIRE v3.7 β un motor hΓbrido que combina embeddings semΓ‘nticos (1024d), expansiΓ³n lΓ©xica y bΓΊsqueda GIN trigram con fusiΓ³n dinΓ‘mica de puntuaciΓ³n. Incluye tambiΓ©n CachΓ© Selectivo (CS/SSC) como pipeline experimental.
---
π‘ ΒΏPor quΓ© CompresiΓ³n de Prompts?
Hipocampo ya reduce el contexto mediante SSC (bΓΊsqueda selectiva). Pero incluso las 5 memorias mΓ‘s relevantes pueden consumir 500-2000+ tokens al concatenarse β una porciΓ³n significativa de la ventana de contexto del LLM.
La compresiΓ³n hΓbrida aΓ±ade una segunda capa de reducciΓ³n:
- Fase extractiva: Elimina oraciones redundantes (filtrando por relevancia de keywords a la consulta). Reduce texto genΓ©rico entre 30-50% al instante, sin llamadas API.
- Fase LLM: Resume contenido tΓ©cnico/cΓ³digo usando el mismo endpoint NVIDIA NIM ya configurado para embeddings. Preserva todo el cΓ³digo, nombres de variables y sintaxis, eliminando verbosidad explicativa.
- Combinado: 20-50% de reducciΓ³n de tokens con pΓ©rdida de calidad casi nula. Un bloque de memoria de 1500 tokens se convierte en 750-1200 tokens β ahorro real en cada llamada al LLM.
Impacto real: Si usas compress_hipocampo antes de cada search_hipocampo β LLM, ahorras 200-800 tokens por interacciΓ³n. A escala (cientos de consultas), esto se traduce en reducciΓ³n significativa de costos y respuestas mΓ‘s rΓ‘pidas.
π CaracterΓsticas Principales
- Arquitectura de Memoria Dual: Capas de almacenamiento separadas para registros tΓ©cnicos (
memoria_vectorial) y datos de perfil (memory_items), ambas utilizando embeddings de 1024 dimensiones. - BIRE v3.7 (por defecto): BΓΊsqueda hΓbrida con embeddings NVIDIA (1024d), expansiΓ³n de consulta, GIN trigram y puntuaciΓ³n compuesta β usado por todas las tools MCP.
- CachΓ© Selectivo (CS/SSC, experimental): Pipeline alternativo de 4 fases: Tag Router β pgvector Top-K β GIN Trigram β ILIKE Fallback.
- Checkpointing LogarΓtmico: CompresiΓ³n inteligente basada en el decaimiento del tiempo, consolidando detalles granulares en un solo registro tras 90 dΓas.
- Auto-MeJORA MCP: AutodiagnΓ³stico (health check + auto-repair), optimizaciΓ³n dinΓ‘mica (stats + tune), y mantenimiento de memoria (dedup + checkpoint) β todo desde herramientas MCP.
- CompresiΓ³n HΓbrida de Prompts (v4.0): Pipeline de dos fases β compresiΓ³n extractiva (nivel de oraciones) para texto genΓ©rico y resumen LLM (vΓa NVIDIA NIM) para contenido tΓ©cnico/cΓ³digo. Reduce tokens del prompt entre 20-50% preservando informaciΓ³n crΓtica. Disponible como herramienta MCP
compress_hipocampo. - Grafo de Memoria (v4.0): Grafo dirigido de relaciones semΓ‘nticas entre recuerdos. Enlaza registros relacionados, navega con Γ‘rbol BFS, encuentra caminos mΓ‘s cortos. Tools:
link_hipocampo,graph_hipocampo,path_hipocampo. - JerarquΓa de Memoria con PrevenciΓ³n por Disparadores (v4.1): π§ π§ Tres niveles (episΓ³dica β semΓ‘ntica β automΓ‘tica) inspirado en consolidaciΓ³n mnΓ©mica humana. NOVEDAD: Etiqueta recuerdos con disparadores contextuales (
trigger:php,trigger:chartjs,trigger:tomcat) β cuando el agente comienza a trabajar en ese contexto, busca reglasautomaticacoincidentes y reactiva errores pasados antes de cometer el mismo error. Esto replica el hipocampo biolΓ³gico: una pista parcial (proyecto + lenguaje) dispara la recuperaciΓ³n completa del error y su soluciΓ³n. Las reglas automΓ‘ticas son permanentes β nunca se comprimen, nunca se eliminan. Tools:set_nivel_hipocampo(id, nivel)+consolidate_hipocampo. - Sistema InmunolΓ³gico de CΓ³digo β ProtecciΓ³n contra Regresiones (v4.2): π‘οΈ Evita que los agentes rompan cΓ³digo que funcionaba. Ciclo de 3 pasos: (1) Snapshot del estado funcional antes de editar, (2) Verificar despuΓ©s de editar, (3) Si algo se rompiΓ³ β crear regla
automaticapermanente que capture la causa exacta, el sΓntoma y la soluciΓ³n. Usa economΓa inmune: los snapshots pre-cambio sonepisodicabaratos (se autocomprimen si no hubo daΓ±o), las reglas post-rotura sonautomaticapermanentes. Precargado con catΓ‘logo de archivos frΓ‘giles β header.php, conexion.php, utils.php, auth.php, etc. El agente buscatrigger:regresion trigger:<archivo>antes de cada ediciΓ³n para aprender lo que otros agentes rompieron antes. - RAG de CΓ³digo (v4.0): Indexa cΓ³digo fuente de proyectos (PHP, JS, TS, Python, SQL) como embeddings semΓ‘nticos. Busca con
search_code(consulta, lenguaje)β devuelve cΓ³digo real con ruta de archivo y nΓΊmeros de lΓnea. - Decaimiento Temporal Exponencial (v4.0):
score_final = relevancia Γ exp(-Ξ» Γ dΓas)con Ξ»=0.05 configurable y piso 20%. El conocimiento reciente pesa naturalmente mΓ‘s. - Diversidad MMR Anti-Cluster (v4.3): Reordenamiento post-fusiΓ³n con Maximum Marginal Relevance para evitar que clusters densos monopolden los resultados. Selecciona iterativamente resultados balanceando relevancia con diversidad:
diversity_lambda Γ relevancia - (1-diversity_lambda) Γ max_similitud_a_seleccionados. Configurable enhipocampo_hybrid_config.json. - Decaimiento de Pesos en Enlaces (v4.3): Decaimiento exponencial en enlaces del grafo con half-life de 90 dΓas. Los enlaces no recorridos pierden fuerza; enlaces <0.01 se podan.
graph_hipocampo()ypath_hipocampo()refuerzan automΓ‘ticamente los enlaces atravesados. Nueva tooldecay_hipocampo(dry_run)para mantenimiento del grafo. Columnas:last_accessed,reinforced_at. - Memoria por SesiΓ³n y Auto-resumen: BΓΊsqueda/guardado aislado por sesiΓ³n. Cada 20 guardados, Hipocampo genera un resumen consolidado de fondo.
- Precarga Proactiva de Contexto:
preload_context(ruta_proyecto)extrae keywords del proyecto, busca memorias relevantes y devuelve resumen comprimido. Ideal al inicio de sesiΓ³n. - Presupuesto de Contexto Inteligente:
compress_hipocampoauto-estima tokens y ajusta k dinΓ‘micamente.budget_ratioda control fino sobre el tamaΓ±o de salida. - Auto-Enlace:
save_hipocampo(..., auto_link=True)descubre recuerdos semΓ‘nticamente similares (>0.75 cosine) y crea aristassimilaren el grafo. - RecuperaciΓ³n AutomΓ‘tica de HNSW:
hipocampo_health()verifica el Γndice HNSW al arrancar y lo crea si falta β sin comandosCREATE INDEXmanuales. - Protocolo MCP (Model Context Protocol): IntegraciΓ³n nativa mediante servidor FastMCP con 25 herramientas, otorgando capacidades directas de lectura/escritura y mantenimiento a clientes MCP como Claude Desktop y OpenCode.
---
β‘ ΒΏPor quΓ© PostgreSQL + pgvector (y no SQLite)?
QuizΓ‘s te preguntes por quΓ© Hipocampo usa PostgreSQL 17 con pgvector en lugar de algo mΓ‘s ligero como SQLite. La respuesta: la bΓΊsqueda hΓbrida necesita mΓ‘s que solo similitud vectorial.
El pipeline de recuperaciΓ³n combina pgvector (HNSW) para bΓΊsqueda semΓ‘ntica, pg_trgm (GIN) para expansiΓ³n lΓ©xica e ILIKE como fallback β todo fusionado en un solo score ponderado. Extensiones de SQLite como sqlite-vec ofrecen bΓΊsqueda vectorial, pero carecen de:
- Γndices GIN trigram para coincidencias difusas/parciales
- FusiΓ³n hΓbrida texto + vector en una sola consulta
- IndexaciΓ³n HNSW de nivel productivo con escrituras concurrentes
- ExpansiΓ³n por pg_trgm cuando los embeddings no bastan
Con mΓ‘s de 1,100 registros en dos tablas de memoria y creciendo, Hipocampo necesita una base de datos que escale sin sacrificar calidad de recuperaciΓ³n. PostgreSQL + pgvector no es "pesado" por capricho β es el stack mΓnimo viable para la precisiΓ³n hΓbrida que BIRE y SSC exigen.
---
π― Casos de Uso
Error β Aprender β No Repetir (Ciclo de Aprendizaje para Agentes IA)
Hipocampo permite que agentes de IA aprendan de sus errores entre sesiones con un ciclo simple:
ββ 1. BUSCAR ββββββββββββββββββββββββββββββ
β Antes de ejecutar, el agente busca β
β errores similares en Hipocampo: β
β search_hipocampo("error <contexto>") β
βββββββββββββββββββββ¬βββββββββββββββββββββββ
β
ββ 2. EJECUTAR ββββββΌβββββββββββββββββββββββ
β Si hay match β aplicar soluciΓ³n conocidaβ
β Si no β intentar nuevo enfoque β
βββββββββββββββββββββ¬βββββββββββββββββββββββ
β
ββ 3. EVALUAR βββββββΌβββββββββββββββββββββββ
β ΒΏFallΓ³? Capturar: β
β - contexto del error y exit code β
β - quΓ© se intentΓ³ β
β - quΓ© pasΓ³ β
βββββββββββββββββββββ¬βββββββββββββββββββββββ
β
ββ 4. PERSISTIR βββββΌβββββββββββββββββββββββ
β save_hipocampo( β
β content="Error X: intentΓ© Y, pasΓ³ Z",β
β memory_type="decision", β
β code="error_<hash>", β
β categories=["bugfix", "<herramienta>"]β
β ) β
ββββββββββββββββββββββββββββββββββββββββββββ
Ejemplo real: Un agente intenta flatpak install npm y falla. Guarda el error en Hipocampo: "npm es un gestor de paquetes de Node.js, no un paquete Flatpak. Usar npm directamente." La prΓ³xima vez que se intente el mismo comando, el agente encuentra este registro y aplica la soluciΓ³n de inmediato.
Con el tiempo, la base de conocimiento de errores crece orgΓ‘nicamente. Cada fallo hace mΓ‘s inteligentes las sesiones futuras. Esto convierte a Hipocampo de un simple archivo en un sistema de aprendizaje continuo para agentes de IA.
π§ PrevenciΓ³n de Errores por Disparadores Contextuales (NUEVO v4.1) β Proactivo, no Reactivo
MΓ‘s allΓ‘ del aprendizaje reactivo, Hipocampo v4.1 introduce reglas automΓ‘ticas con disparadores que se activan antes de que el agente escriba una sola lΓnea de cΓ³digo:
ββ 1. DETECTAR CONTEXTO ββββββββββββββββββββββββββββ
β El agente va a editar un archivo PHP en SGV.pro: β
β Archivo: analisis_visual.php β
β LibrerΓa: Chart.js β
β Lenguaje: PHP β
βββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ
β
ββ 2. BUSCAR DISPARADORES βββΌββββββββββββββββββββββββ
β search_hipocampo("trigger:sgv trigger:chartjs β
β trigger:php trigger:json_encode")β
βββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ
β
ββ 3. REACTIVAR REGLAS ββΌββββββββββββββββββββββββββββ
β REGLA AUTOMΓTICA ENCONTRADA (score 31.0): β
β "NUNCA usar variables JS (C.red, C.primary) β
β dentro de <?= json_encode() ?> en PHP. β
β PHP las evalΓΊa como constantes β Fatal Error." β
β SoluciΓ³n: usar literales #ef4444 / #408AEC β
βββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ
β
ββ 4. ACTUAR CON RESTRICCIΓN ββΌββββββββββββββββββββββ
β El agente genera cΓ³digo usando literales de β
β color. Error EVITADO antes de que ocurra. β
βββββββββββββββββββββββββββββββββββββββββββββββββββββ
CΓ³mo implementarlo:
# 1. Al guardar un error, etiquetarlo con triggers contextuales y elevar a automatica
save_hipocampo(
content="NUNCA usar variables JS en json_encode() PHP. Usar literales de color.",
memory_type="decision",
categories=["trigger:sgv", "trigger:chartjs", "trigger:php", "trigger:json_encode"],
nivel="automatica"
)
# 2. Antes de editar cΓ³digo en cualquier proyecto, buscar disparadores coincidentes
search_hipocampo("trigger:<proyecto> trigger:<lenguaje> trigger:<tecnologia>")
# 3. Las reglas automΓ‘ticas aparecen β el agente las aplica preventivamente
Esto replica el hipocampo biolΓ³gico: una pista parcial dispara la recuperaciΓ³n completa de la memoria β el cerebro no espera a que ocurra el error para recordar que duele.
π‘οΈ ProtecciΓ³n contra Regresiones β Sistema InmunolΓ³gico (NUEVO v4.2)
A veces el agente rompe cΓ³digo que funcionaba bien β no repite un error viejo, crea uno nuevo. Hipocampo v4.2 implementa un ciclo inmune de 3 pasos que replica cΓ³mo el cuerpo genera anticuerpos:
ββ 1. SNAPSHOT βββββββββββββββββββββββββββββββββββ
β Antes de editar header.php, guardar quΓ© sirve: β
β "header.php depende de session_start(). β
β Verificar: abrir dashboard.php, debe cargar." β
β Costo: episodica (barato, se autocomprime) β
βββββββββββββββββββββ¬ββββββββββββββββββββββββββββββ
β
ββ 2. VERIFICAR βββββΌββββββββββββββββββββββββββββββ
β DespuΓ©s de editar, verificar el snapshot: β
β - Dashboard carga OK β sin costo, se desvanece β
β - HTTP 500 en todas las pΓ‘ginas β Β‘respuesta! β
βββββββββββββββββββββ¬ββββββββββββββββββββββββββββββ
β
ββ 3. INMUNIZAR βββββΌββββββββββββββββββββββββββββββ
β Guardar regla automatica permanente: β
β "Editar header.php: quitΓ© session_start(), β
β rompiΓ³ 40+ pΓ‘ginas. SoluciΓ³n: restaurar β
β session_start() al inicio. NUNCA tocar esto." β
β Costo: automatica (permanente, inmutable) β
βββββββββββββββββββββββββββββββββββββββββββββββββββ
CatΓ‘logo de archivos frΓ‘giles (precargado): header.php, conexion.php, utils.php, auth.php, db_connection.php β estos archivos tienen dependencias en cascada. Una sola ediciΓ³n incorrecta rompe decenas de pΓ‘ginas. Hipocampo incluye reglas de fragilidad para que los agentes sepan quΓ© manejar con cuidado.
Antes de cada ediciΓ³n: search_hipocampo("trigger:regresion trigger:<archivo> trigger:<proyecto>") β aprende lo que otros agentes rompieron en este archivo antes de tocarlo.
βοΈ CΓ³mo configurar tu agente
Para activar este comportamiento, hay que instruir al agente. Se hace agregando reglas en su archivo de configuraciΓ³n:
| Agente | Archivo de configuraciΓ³n | |---|---| | OpenCode | AGENTS.md (raΓz del proyecto) o ~/.opencode/AGENTS.md | | Claude Code | CLAUDE.md o ~/.claude/CLAUDE.md | | Cursor | .cursorrules | | Windsurf | .windsurfrules | | Cline | CLINE.md |
Ejemplo mΓnimo para AGENTS.md / CLAUDE.md:
## Ciclo de Aprendizaje de Errores
1. Antes de ejecutar un comando, busca: `search_hipocampo("error <comando> <contexto>")`
2. Si hay error similar, aplica la soluciΓ³n documentada y omite el intento fallido
3. Si el comando falla (exit code != 0, timeout, "error"/"failed" en output):
- Guarda en Hipocampo: `save_hipocampo(content="Error: {stderr[:500]}. Intento: {quΓ© se probΓ³}. Resultado: {quΓ© pasΓ³}.", memory_type="decision", code="error_<hash>", categories=["bugfix", "<lenguaje/herramienta>"])`
π‘ Tip: Para agentes nativos MCP (OpenCode, Claude Code), las tools de Hipocampo estΓ‘n disponibles directamente. Para otros, usa el endpoint HTTP o los scripts CLI.
π ΒΏQuieres que tu agente use TODO Hipocampo? Agrega las secciones de AGENTS_TEMPLATE.md a tu AGENTS.md / CLAUDE.md / .cursorrules β seguro de compartir, sin credenciales.
Otros casos de uso
- Perfil de usuario persistente: Recordar preferencias, configuraciones y datos personales entre sesiones
- Seguimiento de proyectos: Mantener contexto de proyectos activos, decisiones tomadas y tareas pendientes
- Conocimiento entre sesiones: Continuar trabajos previos sin repetir contexto
---
π οΈ InstalaciΓ³n RΓ‘pida
# 1. Clonar y configurar BD
git clone https://github.com/carrasquelalex1/hipocampo.git
cd hipocampo
createdb hipocampo_db
psql -d hipocampo_db -c "CREATE EXTENSION vector; CREATE EXTENSION pg_trgm;"
psql -d hipocampo_db -f esquema.sql
# 2. Entorno Python y dependencias
python3 -m venv venv && source venv/bin/activate
pip install -r requirements.txt
# 3. Configurar variables de entorno
cp .env.example .env
# Editar .env con DB_HOST, DB_USER, NVIDIA_API_KEY
Para usar la bΓΊsqueda directamente desde la terminal: ``bash python3 scripts/hipocampo_search.py "tΓ©rmino de bΓΊsqueda" # BIRE v3.7 (recomendado) python3 scripts/hipocampo_ssc_search.py "tΓ©rmino de bΓΊsqueda" # SSC v1.0 (experimental) python3 scripts/hipocampo_compress.py "tΓ©rmino" --k 5 # BΓΊsqueda + compresiΓ³n hΓbrida ``
Para inicializar el servidor MCP: ``bash python3 scripts/hipocampo_mcp_server.py python3 scripts/hipocampo_mcp_server.py --http 8001 # Streamable HTTP (recomendado) python3 scripts/hipocampo_mcp_server.py --sse 8001 # legacy (deprecado) ``
Herramientas MCP Disponibles (22+ herramientas)
Operaciones de Memoria:
search_hipocampo(consulta, session_id?): BΓΊsqueda semΓ‘ntica + lΓ©xica hΓbrida (auto-registra mΓ©tricas). Filtro opcional por sesiΓ³n.quick_hipocampo_search(consulta): Alias rΓ‘pido para bΓΊsquedas.preload_context(ruta_proyecto, k=8): Extrae keywords del proyecto, busca memorias relevantes y devuelve resumen comprimido. Ideal para inicio de sesiΓ³n.compress_hipocampo(consulta, k=5, method="hybrid", budget_ratio=1.0, include_metadata=False): BΓΊsqueda + compresiΓ³n hΓbrida con presupuesto de contexto. Auto-estima tokens y ajusta k dinΓ‘micamente. Tres mΓ©todos:"hybrid"(recomendado),"extractive"(mΓ‘s rΓ‘pido, sin costo API),"llm"(mΓ‘xima calidad).save_hipocampo(contenido, tipo, codigo, categorias, session_id?, force?, auto_link=False, nivel="episodica"): Guarda datos tΓ©cnicos enmemoria_vectorial. Soporta auto-dedup, auto-enlace y niveles jerΓ‘rquicos.profile_hipocampo(resumen, extra, categorias): Guarda datos de perfil enmemory_items.
Grafo de Memoria (v4.0):
link_hipocampo(origen, destino, tipo_relacion, peso): Crea enlace dirigido entre recuerdos. Tipos:related,follow_up,part_of,references,similar,chain.unlink_hipocampo(id / origen+destino+tipo): Elimina enlaces del grafo.graph_hipocampo(nodo_id, profundidad=2): Γrbol BFS desde un nodo raΓz.nodo_id=0muestra vista general.path_hipocampo(origen, destino, max_depth=5): Camino mΓ‘s corto BFS entre dos recuerdos.
RAG de CΓ³digo (v4.0):
index_project(ruta_proyecto, force=False): Indexa archivos de cΓ³digo como embeddings semΓ‘nticos. Incremental β solo re-indexa archivos modificados. Soporta PHP, JS, TS, Python, SQL, HTML, CSS, JSON, YAML.search_code(consulta, k=5, lenguaje=""): BΓΊsqueda vectorial en cΓ³digo indexado. Devuelve cΓ³digo real con ruta, lenguaje y lΓneas.
Operaciones CRUD:
update_hipocampo(id, contenido?, tipo?, codigo?, categorias?): Actualiza un recuerdo existente. Regenera embedding si cambia el contenido.delete_hipocampo(id): Elimina un recuerdo permanentemente por ID.set_nivel_hipocampo(id, nivel): Promueve/degrada un recuerdo entre niveles jerΓ‘rquicos (episodica,semantica,automatica).consolidate_hipocampo(dias_min=7, seco=True): Migra recuerdos episΓ³dicos antiguos a nivel semΓ‘ntico con compresiΓ³n opcional.
AutodiagnΓ³stico y ReparaciΓ³n:
hipocampo_health(): Health check completo (PostgreSQL, API NVIDIA, disco, extensiones, Γndice HNSW).hipocampo_auto_repair(): Repara problemas automΓ‘ticamente (crea tablas, Γndice HNSW, reinicia PostgreSQL).
OptimizaciΓ³n de Rendimiento (Fase 2):
hipocampo_stats(): MΓ©tricas de rendimiento, latencia, y recomendaciones de optimizaciΓ³n.hipocampo_tune(): Ajusta thresholds BIRE/SSC y pesos hΓbridos segΓΊn uso real.
Mantenimiento de Memoria (Fase 3):
hipocampo_dedup(fusionar): Detecta y fusiona memorias duplicadas (exactas + semΓ‘nticas).hipocampo_checkpoint(seco): Checkpointing logarΓtmico para comprimir memorias antiguas.hipocampo_maintenance(): Ciclo completo de mantenimiento (reparar β dedup β checkpoint β tune).
Decaimiento Temporal:
- Scores de memorias >7 dΓas decaen ~5% por semana (piso 30%), priorizando conocimiento reciente.
Webhooks (Watch):
watch_hipocampo(patron, webhook_url): Registra un webhook que se dispara en eventos save/update/delete cuando el contenido coincide con un patrΓ³n.unwatch_hipocampo(id): Elimina un webhook registrado.list_watches(): Lista todos los webhooks activos.
Arquitectura Modular
La conexiΓ³n a BD, configuraciΓ³n y generaciΓ³n de embeddings estΓ‘n centralizadas en el paquete hipocampo:
hipocampo/
βββ __init__.py # InicializaciΓ³n del paquete (v3.8)
βββ db.py # get_conn(), get_embedding(), load_config()
Todos los scripts en scripts/ importan de hipocampo.db en lugar de duplicar el boilerplate. El servidor MCP importa las funciones de bΓΊsqueda/salud/estadΓsticas/dedup/checkpoint directamente β sin llamadas subprocess.
Antes: Cada bΓΊsqueda MCP ejecutaba subprocess.run() β fork del intΓ©rprete Python β re-importar todo β conectar DB β generar embedding β ejecutar query β parsear stdout. ~200β500ms solo de overhead de proceso y serializaciΓ³n.
Ahora: Llamada directa a funciΓ³n en el mismo proceso. La DB connection pool, OpenAI client y mΓ³dulos ya estΓ‘n cacheados. El overhead se reduce a microsegundos.
Para bΓΊsquedas individuales la diferencia es marginal (~200ms), pero para hipocampo_maintenance() antes ejecutaba 4 forks subprocess en serie β ahora es una llamada directa por fase, ahorrando ~1β2 segundos.
Async & Connection Pool (v3.8)
El servidor MCP ahora ejecuta las 16 herramientas como corutinas async en modo HTTP, y usa un pool de conexiones PostgreSQL en lugar de crear una conexiΓ³n nueva por cada llamada:
Antes:
- Cada herramienta abrΓa una conexiΓ³n TCP + SSL nueva a PostgreSQL β latencia de
connect()en cada llamada - Tools sincrΓ³nicas bloqueaban el event loop de uvicorn β una
searchlenta congelaba el servidor para todos los clientes concurrentes - En modo HTTP con requests concurrentes: riesgo de
too many connectionsen la BD
Ahora:
init_pool(minconn=1, maxconn=10)crea unThreadedConnectionPoolal arrancar β las conexiones se reΓΊsan, el handshake ocurre una sola vez- Las 16 herramientas son
async defβ I/O bloqueante (queries BD, API N











