UNPKG

@pytt0n/self-improving-memory-mcp

Version:

๐Ÿง  Self-improving memory system for Claude Code CLI with automatic learning, zero context loss, and advanced analytics

842 lines (695 loc) โ€ข 28.1 kB
# ๐Ÿ—๏ธ Arquitectura del Sistema Diseรฑo tรฉcnico completo del sistema de memoria auto-evolutivo. --- ## ๐Ÿ“‹ Contenidos 1. [Visiรณn General](#visiรณn-general) 2. [Arquitectura de 3 Capas](#arquitectura-de-3-capas) 3. [Flujo de Datos](#flujo-de-datos) 4. [Componentes Principales](#componentes-principales) 5. [Sistema de Entidades y Relaciones](#sistema-de-entidades-y-relaciones) 6. [Decisiones de Diseรฑo](#decisiones-de-diseรฑo) --- ## Visiรณn General ### Principios Arquitectรณnicos **SOLID Principles:** - โœ… **Single Responsibility:** Cada componente tiene una responsabilidad clara - โœ… **Open/Closed:** Extensible mediante agentes y plugins sin modificar core - โœ… **Liskov Substitution:** VectorStore puede intercambiarse por otras implementaciones - โœ… **Interface Segregation:** Interfaces pequeรฑas y especรญficas - โœ… **Dependency Inversion:** KnowledgeStore depende de abstracciรณn, no implementaciรณn **Otros Principios:** - ๐Ÿ”„ **Separation of Concerns:** API, lรณgica, persistencia separadas - ๐Ÿ“ฆ **Modular Design:** Componentes independientes y reutilizables - ๐ŸŽฏ **Single Source of Truth:** LanceDB es la รบnica fuente de datos - ๐Ÿ”Œ **Plugin Architecture:** Agentes como plugins auto-contenidos --- ## Arquitectura de 3 Capas ``` โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ CAPA 1: INTERFACES โ”‚ โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ โ”‚ โ”‚ MCP Tools โ”‚ โ”‚ Slash โ”‚ โ”‚ CLI (terminal) โ”‚ โ”‚ โ”‚ โ”‚ (Claude) โ”‚ โ”‚ Commands โ”‚ โ”‚ memory-cli stats โ”‚ โ”‚ โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ”‚ โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ–ผ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ CAPA 2: Lร“GICA DE NEGOCIO โ”‚ โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ โ”‚ โ”‚ MCP Server (index.js) โ”‚ โ”‚ โ”‚ โ”‚ โ€ข Transport Layer (StdioServerTransport) โ”‚ โ”‚ โ”‚ โ”‚ โ€ข Tool Registration & Routing โ”‚ โ”‚ โ”‚ โ”‚ โ€ข Request Validation (Zod schemas) โ”‚ โ”‚ โ”‚ โ”‚ โ€ข Error Handling โ”‚ โ”‚ โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ โ”‚ โ”‚ KnowledgeStore (class) โ”‚ โ”‚ โ”‚ โ”‚ โ€ข Entity Management (CRUD) โ”‚ โ”‚ โ”‚ โ”‚ โ€ข Relation Management โ”‚ โ”‚ โ”‚ โ”‚ โ€ข Confidence System โ”‚ โ”‚ โ”‚ โ”‚ โ€ข Search & Retrieval โ”‚ โ”‚ โ”‚ โ”‚ โ€ข Stats & Analytics โ”‚ โ”‚ โ”‚ โ”‚ โ€ข Export Functionality โ”‚ โ”‚ โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ–ผ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ CAPA 3: PERSISTENCIA โ”‚ โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ โ”‚ โ”‚ VectorStore (vector-store.js) โ”‚ โ”‚ โ”‚ โ”‚ โ€ข Embedding Generation (Transformers.js) โ”‚ โ”‚ โ”‚ โ”‚ โ€ข Vector Operations (add, search, update, delete) โ”‚ โ”‚ โ”‚ โ”‚ โ€ข LanceDB Abstraction โ”‚ โ”‚ โ”‚ โ”‚ โ€ข Schema Management โ”‚ โ”‚ โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ โ”‚ โ”‚ LanceDB Storage โ”‚ โ”‚ โ”‚ โ”‚ โ€ข Vector Database (.claude-memory/vectors/lancedb/) โ”‚ โ”‚ โ”‚ โ”‚ โ€ข Persistent Storage โ”‚ โ”‚ โ”‚ โ”‚ โ€ข Efficient Vector Search โ”‚ โ”‚ โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ ``` --- ## Flujo de Datos ### 1. User Request โ†’ Knowledge Capture ``` โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ Usuario โ”‚ "Guarda decisiรณn: Usar PostgreSQL" โ””โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ–ผ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ MCP Tool Call โ”‚ save_knowledge({type: "decision", content: "..."}) โ””โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ–ผ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ Input Validation โ”‚ Zod schema validation โ””โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ–ผ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ KnowledgeStore โ”‚ addEntry({...}) โ”‚ โ€ข Generate UUID โ”‚ โ”‚ โ€ข Set metadata โ”‚ โ”‚ โ€ข Prepare for store โ”‚ โ””โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ–ผ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ VectorStore โ”‚ add({...}) โ”‚ โ€ข Generate embeddingโ”‚ Transformers.js (384D vector) โ”‚ โ€ข Serialize arrays โ”‚ tags โ†’ JSON string โ”‚ โ€ข Insert to LanceDB โ”‚ โ””โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ–ผ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ LanceDB โ”‚ Persistent storage โ”‚ โ€ข Write to disk โ”‚ โ”‚ โ€ข Index vector โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ ``` ### 2. Knowledge Search ``` โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ Usuario โ”‚ "Busca decisiones sobre database" โ””โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ–ผ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ MCP Tool Call โ”‚ search_knowledge({query: "database"}) โ””โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ–ผ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ KnowledgeStore โ”‚ search("database", {type: "decision"}) โ””โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ–ผ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ VectorStore โ”‚ search("database", limit: 10) โ”‚ โ€ข Generate embeddingโ”‚ Query โ†’ 384D vector โ”‚ โ€ข Vector search โ”‚ Cosine similarity โ”‚ โ€ข Filter results โ”‚ By type, confidence โ””โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ–ผ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ LanceDB โ”‚ Vector similarity search โ”‚ โ€ข ANN search โ”‚ Approximate Nearest Neighbors โ”‚ โ€ข Return top K โ”‚ โ””โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ–ผ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ Post-Processing โ”‚ โ”‚ โ€ข Deserialize arraysโ”‚ JSON string โ†’ array โ”‚ โ€ข Update metadata โ”‚ accessCount++, lastAccessed โ”‚ โ€ข Format response โ”‚ โ””โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ–ผ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ Results โ”‚ [{id, type, content, confidence, ...}, ...] โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ ``` ### 3. Agent Workflow ``` โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ Trigger โ”‚ Error occurs, task starts, etc. โ””โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ–ผ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ Claude detects โ”‚ Matches trigger condition in CLAUDE.md โ”‚ trigger โ”‚ โ””โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ–ผ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ Task tool call โ”‚ Launch agent (subagent_type: "general-purpose") โ””โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ–ผ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ Agent executes โ”‚ โ”‚ 1. Search memory โ”‚ mcp__memory__search_nodes โ”‚ 2. Analyze findings โ”‚ โ”‚ 3. Create entities โ”‚ mcp__memory__create_entities โ”‚ 4. Create relations โ”‚ mcp__memory__create_relations โ””โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ–ผ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ Knowledge stored โ”‚ Entities + Relations in LanceDB โ””โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ–ผ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ Report โ”‚ Brief confirmation to Claude โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ ``` --- ## Componentes Principales ### 1. MCP Server (`index.js`) **Responsabilidad:** API Layer y Transport **Componentes:** ```javascript // Server initialization const server = new Server({ name: 'self-improving-memory', version: '2.0.0' }, { capabilities: { tools: {} // Expose MCP tools } }); // Transport (stdio para Claude Desktop) const transport = new StdioServerTransport(); // Tool registration server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: [ { name: 'create_entities', ... }, { name: 'search_nodes', ... }, ... ] })); // Tool execution server.setRequestHandler(CallToolRequestSchema, async (request) => { // Route to KnowledgeStore }); ``` **Herramientas Expuestas:** 1. `create_entities` - Crear entidades 2. `create_relations` - Crear relaciones 3. `add_observations` - Agregar observaciones 4. `search_nodes` - Buscar conocimiento 5. `open_nodes` - Abrir entidades especรญficas 6. `read_graph` - Leer grafo completo 7. `delete_entities` - Eliminar entidades 8. `delete_observations` - Eliminar observaciones **Patterns Utilizados:** - **Factory Pattern:** Para crear entidades - **Strategy Pattern:** Routing de tools - **Facade Pattern:** Simplifica acceso a KnowledgeStore --- ### 2. KnowledgeStore (clase en `index.js`) **Responsabilidad:** Business Logic **Mรฉtodos Principales:** ```javascript class KnowledgeStore { constructor(projectPath) { this.vectorStore = new VectorStore(projectPath); } // Entity Management async addEntry({ type, content, context, confidence, ... }) { const id = crypto.randomUUID(); const entry = { id, type, content, context, confidence, verified: false, tags: [], timestamp: new Date().toISOString(), accessCount: 0, lastAccessed: null, relatedIds: [] }; await this.vectorStore.add(entry); return id; } // Search with filters async search(query, { type, minConfidence, limit } = {}) { const results = await this.vectorStore.search(query, limit); // Filter by type if (type) { results = results.filter(r => r.type === type); } // Filter by confidence if (minConfidence) { results = results.filter(r => r.confidence >= minConfidence); } // Update access metadata for (const result of results) { await this.updateMetadata(result.id, { accessCount: result.accessCount + 1, lastAccessed: new Date().toISOString() }); } return results; } // Relation Management async linkEntries(fromId, toId, relationType) { const from = await this.getById(fromId); if (!from.relatedIds.includes(toId)) { from.relatedIds.push(toId); await this.updateEntry(fromId, { relatedIds: from.relatedIds }); } } // Analytics async getStats() { const allEntries = await this.vectorStore.getAll(); return { totalEntries: allEntries.length, byType: this.groupBy(allEntries, 'type'), byConfidence: this.groupByConfidence(allEntries), verified: allEntries.filter(e => e.verified).length, mostAccessedId: this.findMostAccessed(allEntries)?.id }; } // Export async exportMarkdown() { const entries = await this.vectorStore.getAll(); const grouped = this.groupBy(entries, 'type'); let md = '# Knowledge Base Export\n\n'; for (const [type, items] of Object.entries(grouped)) { md += `## ${type}\n\n`; for (const item of items) { md += `### ${item.content}\n`; md += `- Confidence: ${item.confidence}\n`; md += `- Tags: ${item.tags.join(', ')}\n\n`; } } return md; } } ``` **Patterns Utilizados:** - **Repository Pattern:** Abstrae acceso a datos - **Builder Pattern:** Construcciรณn de queries complejas - **Template Method:** Export en diferentes formatos --- ### 3. VectorStore (`vector-store.js`) **Responsabilidad:** Vector Operations & LanceDB Abstraction **Componentes:** ```javascript class VectorStore { constructor(projectPath) { this.dbPath = path.join(projectPath, '.claude-memory', 'vectors', 'lancedb'); this.db = null; this.table = null; this.model = null; // Transformers.js model } // Initialization async initialize() { this.db = await lancedb.connect(this.dbPath); // Check if table exists const tableNames = await this.db.tableNames(); if (tableNames.includes('knowledge')) { this.table = await this.db.openTable('knowledge'); } else { // Create table with schema this.table = await this.db.createTable('knowledge', SCHEMA); } // Warm-up embeddings model in background this.warmupModel(); } // Embedding generation async generateEmbedding(text) { if (!this.model) { const { pipeline } = await import('@xenova/transformers'); this.model = await pipeline( 'feature-extraction', 'Xenova/all-MiniLM-L6-v2' ); } const output = await this.model(text, { pooling: 'mean', normalize: true }); return Array.from(output.data); // 384D vector } // Add entry async add(entry) { const embedding = await this.generateEmbedding( `${entry.type} ${entry.content} ${entry.context || ''}` ); const record = { id: entry.id, vector: embedding, text: entry.content, type: entry.type, content: entry.content, context: entry.context || '', confidence: entry.confidence, verified: entry.verified, tags: JSON.stringify(entry.tags), // Serialize timestamp: entry.timestamp, accessCount: entry.accessCount, lastAccessed: entry.lastAccessed || '', relatedIds: JSON.stringify(entry.relatedIds), // Serialize indexed_at: new Date().toISOString() }; await this.table.add([record]); } // Vector search async search(query, limit = 10) { const queryEmbedding = await this.generateEmbedding(query); const results = await this.table .search(queryEmbedding) .limit(limit) .execute(); // Deserialize arrays return results.map(r => ({ ...r, tags: JSON.parse(r.tags || '[]'), relatedIds: JSON.parse(r.relatedIds || '[]') })); } // Update (delete + add pattern) async update(id, updates) { const existing = await this.getById(id); const merged = { ...existing, ...updates }; await this.delete(id); await this.add(merged); } // Metadata-only update (no re-embed) async updateMetadata(id, metadata) { // Direct SQL update for efficiency (no vector change) const sql = `UPDATE knowledge SET ${Object.keys(metadata).map(k => `${k} = ?`).join(', ')} WHERE id = ?`; await this.table.execute(sql, [...Object.values(metadata), id]); } } ``` **Patterns Utilizados:** - **Singleton Pattern:** Model instance reutilizada - **Lazy Loading:** Model se carga en primer uso - **Adapter Pattern:** Abstrae LanceDB specifics --- ### 4. CLI Tool (`memory-cli.js`) **Responsabilidad:** Terminal Interface **Comandos:** ```javascript const commands = { init: async () => { // Initialize .claude-memory directory }, stats: async () => { const store = new VectorStore(process.cwd()); const stats = await store.getStats(); console.log(formatStats(stats)); }, list: async (type) => { const entries = await store.getAll(); const filtered = type ? entries.filter(e => e.type === type) : entries; console.table(filtered.map(formatEntry)); }, search: async (query) => { const results = await store.search(query); console.log(formatResults(results)); }, show: async (id) => { const entry = await store.getById(id); console.log(formatDetail(entry)); }, export: async (format = 'md') => { if (format === 'md') { const md = await store.exportMarkdown(); fs.writeFileSync('knowledge-export.md', md); } }, analyze: async () => { // Quality analysis const entries = await store.getAll(); const lowConfidence = entries.filter(e => e.confidence < 0.5); const unverified = entries.filter(e => !e.verified); const unused = entries.filter(e => e.accessCount === 0); console.log(`Low confidence: ${lowConfidence.length}`); console.log(`Unverified: ${unverified.length}`); console.log(`Unused: ${unused.length}`); } }; ``` **Features:** - Acceso directo a VectorStore (no usa MCP) - Formateo con colores ANSI - Instalable globalmente (`npm link`) --- ## Sistema de Entidades y Relaciones ### Entity Schema ```typescript interface Entity { // Identity id: string; // UUID v4 name: string; // Human-readable name entityType: string; // Tipo de entidad (17 tipos) // Content observations: string[]; // Array de observaciones // Metadata (implicit) confidence?: number; // 0-1 (stored in observations) tags?: string[]; // (stored in observations) timestamp?: string; // ISO8601 verified?: boolean; // (stored in observations) } ``` ### Relation Schema ```typescript interface Relation { from: string; // Entity name (source) to: string; // Entity name (target) relationType: string; // Tipo de relaciรณn } ``` ### Entity Types (17 tipos) **Categorรญa: Proyecto & Cรณdigo** - `project` - Informaciรณn del proyecto - `component` - Componente/mรณdulo de cรณdigo - `dependency` - Librerรญa/herramienta externa **Categorรญa: Aprendizaje** - `error` - Error encontrado - `solution` - Soluciรณn exitosa - `pattern` - Patrรณn reutilizable - `insight` - Aprendizaje importante - `decision` - Decisiรณn tรฉcnica **Categorรญa: Usuario** - `user-intent` - Quรฉ quiere lograr el usuario - `user-preference` - Preferencias del usuario - `requirement` - Requisito o constraint **Categorรญa: Estilo** - `style-rule` - Regla de estilo de cรณdigo - `architectural-pattern` - Patrรณn arquitectรณnico - `tool-preference` - Herramienta/library preferida **Categorรญa: Sesiones** - `session-snapshot` - Estado completo de sesiรณn - `continuation-point` - Punto de continuaciรณn - `work-in-progress` - Trabajo incompleto ### Relation Types (ejemplos) ``` uses, depends on, fixes, implements, supersedes, applies to, guided by, causes, prevents, enhances, similar to, contradicts, requires, validates, extends ``` ### Knowledge Graph Structure ``` โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ PROJECT โ”‚ โ”‚ my-web-app โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ uses โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ โ”‚ โ”‚ โ–ผ โ–ผ โ–ผ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚COMPONENT โ”‚ โ”‚COMPONENT โ”‚ โ”‚DEPENDENCYโ”‚ โ”‚ Auth โ”‚ โ”‚ API โ”‚ โ”‚PostgreSQLโ”‚ โ””โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ”‚ โ”‚ โ”‚ implements โ”‚ applies to โ”‚ used in โ–ผ โ–ผ โ–ผ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ DECISION โ”‚ โ”‚ ERROR โ”‚ โ”‚DECISION โ”‚ โ”‚ Use JWT โ”‚ โ”‚ CORS failโ”‚ โ”‚ Use PG โ”‚ โ””โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ”‚ fixed by โ”‚ guided by โ–ผ โ–ผ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ SOLUTION โ”‚ โ”‚USER-PREF โ”‚ โ”‚Enable โ”‚ โ”‚Secure โ”‚ โ”‚CORS โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ ``` --- ## Decisiones de Diseรฑo ### 1. ยฟPor quรฉ LanceDB? **Alternativas consideradas:** - Pinecone (cloud-only, caro) - Weaviate (overhead alto) - ChromaDB (mรกs lento) - JSON + manual search (no escala) **Razones para LanceDB:** - โœ… Persistencia local (no depende de cloud) - โœ… Vector search nativo y rรกpido - โœ… Bajo overhead (embedded database) - โœ… Escalable (hasta millones de vectores) - โœ… Integraciรณn fรกcil con Node.js ### 2. ยฟPor quรฉ Transformers.js? **Alternativas:** - OpenAI Embeddings API (requiere API key, costo) - Python sentence-transformers (requiere Python) - Manual TF-IDF (menos semรกntico) **Razones para Transformers.js:** - โœ… 100% JavaScript (no Python dependency) - โœ… Funciona offline (modelo local) - โœ… Gratis y open-source - โœ… Modelo pequeรฑo pero efectivo (90MB) - โœ… Rรกpido despuรฉs de warm-up ### 3. ยฟPor quรฉ Modelo all-MiniLM-L6-v2? **Specs:** - Tamaรฑo: ~90MB - Dimensiones: 384 - Performance: 0.68 semantic similarity (benchmark) **Trade-offs:** - โœ… Pequeรฑo y rรกpido - โœ… Buena precisiรณn para mayorรญa de casos - โŒ No tan preciso como modelos grandes (768D) **Conclusiรณn:** Sweet spot entre tamaรฑo/velocidad/precisiรณn. ### 4. ยฟPor quรฉ 3 Capas? **Separation of Concerns:** - **Layer 1 (Interfaces):** Mรบltiples formas de interactuar - **Layer 2 (Logic):** Business rules independientes de storage - **Layer 3 (Persistence):** Fรกcil cambiar implementaciรณn **Benefits:** - Testeable (mock layers independientemente) - Mantenible (cambios localizados) - Extensible (agregar interfaces fรกcilmente) ### 5. ยฟPor quรฉ MCP Protocol? **Alternativas:** - REST API (overhead de servidor) - GraphQL (complejidad innecesaria) - Direct function calls (no portable) **Razones para MCP:** - โœ… Standard de Anthropic para Claude integrations - โœ… Stdio transport (simple, sin networking) - โœ… Schema validation built-in - โœ… Auto-discovery de tools ### 6. ยฟPor quรฉ No JSON Storage? **Problemas con JSON:** - โŒ No search semรกntica (solo text match) - โŒ O(n) para bรบsquedas - โŒ No escala bien (>10k entries) - โŒ Require cargar todo en memoria **Benefits de Vector DB:** - โœ… O(log n) bรบsqueda con ANN - โœ… Semantic search (encuentra conceptos similares) - โœ… Escalable sin lรญmite prรกctico - โœ… Lazy loading (no todo en RAM) --- ## Performance Considerations ### Latency Breakdown ``` Total search time: ~300-500ms 1. Query embedding generation: ~100-200ms (primera vez) ~10-20ms (warm model) 2. Vector search (LanceDB): ~50-100ms (10k entries) ~200-300ms (100k entries) 3. Post-processing: ~10-20ms 4. Metadata update: ~20-50ms ``` ### Memory Usage ``` Base: ~50MB (Node.js runtime) Transformers.js: ~90MB (model in memory) LanceDB: ~20MB + (vectors * 384 * 4 bytes) Example for 10k entries: 10,000 * 384 * 4 = ~15MB Total: ~175MB (10k entries) ~265MB (100k entries) ``` ### Scalability Targets | Entries | DB Size | Search Latency | Memory | |---------|---------|----------------|---------| | 1k | ~5MB | <100ms | ~165MB | | 10k | ~50MB | <200ms | ~175MB | | 100k | ~500MB | <500ms | ~265MB | | 1M | ~5GB | <1s | ~500MB | --- ## Security Considerations ### Data Privacy - โœ… **Local-first:** Todo almacenado localmente - โœ… **No cloud:** No envรญa datos a servicios externos - โœ… **No tracking:** No telemetrรญa - โœ… **User control:** Usuario controla sus datos ### Input Validation ```javascript // Zod schemas para validaciรณn const EntitySchema = z.object({ name: z.string().min(1).max(200), entityType: z.enum([...17 entity types]), observations: z.array(z.string()).min(1) }); // Sanitizaciรณn function sanitize(input) { return input .trim() .replace(/[<>]/g, '') // Remove HTML tags .slice(0, 10000); // Limit length } ``` ### Error Handling ```javascript try { await vectorStore.add(entity); } catch (error) { logger.error('Failed to add entity', { error: error.message, stack: error.stack, entity: sanitizeForLog(entity) }); throw new MCPError('Entity creation failed'); } ``` --- **Documentaciรณn relacionada:** - [Agentes](AGENTS.md) - [API Reference](API.md) - [ROADMAP](../ROADMAP.md)