UNPKG

@nova-mcp/mcp-nova

Version:

AI Memory System for Claude & Cursor - Stop losing context. Start saving tokens.

105 lines 371 kB
var ua=Object.defineProperty;var u=(T,e)=>ua(T,"name",{value:e,configurable:!0});var g=(T,e)=>()=>(e||T((e={exports:{}}).exports,e),e.exports);var Ee=g((El,ji)=>{var ge=require("sqlite3").verbose(),pa=require("fs-extra"),ya=require("path"),_e=class _e{constructor(e){this.db=null,this.dbPath=e,this.preparedStatements={}}addMissingColumnsSync(){process.env.NOVA_MCP_MODE||console.error("\u{1F527} Running auto-recovery: Checking and updating database schema..."),this.db.serialize(()=>{this.db.all("PRAGMA table_info(entities)",(e,t)=>{if(!e&&t&&t.length>0){let s=t.map(n=>n.name),i=0;s.includes("last_updated")||(i++,this.db.run("ALTER TABLE entities ADD COLUMN last_updated TEXT DEFAULT (datetime('now'))",n=>{n&&!n.message.includes("duplicate column")?console.error("Error adding last_updated column:",n):n||console.error("\u2705 Added missing column: entities.last_updated")})),s.includes("updated_at")||(i++,this.db.run("ALTER TABLE entities ADD COLUMN updated_at TEXT DEFAULT (datetime('now'))",n=>{n&&!n.message.includes("duplicate column")?console.error("Error adding updated_at column:",n):n||console.error("\u2705 Added missing column: entities.updated_at")})),s.includes("mention_count")||(i++,this.db.run("ALTER TABLE entities ADD COLUMN mention_count INTEGER DEFAULT 1",n=>{n&&!n.message.includes("duplicate column")?console.error("Error adding mention_count column:",n):n||console.error("\u2705 Added missing column: entities.mention_count")})),s.includes("metadata")||(i++,this.db.run("ALTER TABLE entities ADD COLUMN metadata TEXT DEFAULT '{}'",n=>{n&&!n.message.includes("duplicate column")?console.error("Error adding metadata column:",n):n||console.error("\u2705 Added missing column: entities.metadata")})),i===0&&(process.env.NOVA_MCP_MODE||console.error("\u2705 Entities table schema is up to date"))}}),this.db.all("PRAGMA table_info(relationships)",(e,t)=>{if(!e&&t&&t.length>0){let s=t.map(n=>n.name),i=0;s.includes("timestamp")||(i++,this.db.run("ALTER TABLE relationships ADD COLUMN timestamp TEXT DEFAULT (datetime('now'))",n=>{n&&!n.message.includes("duplicate column")?console.error("Error adding timestamp column:",n):n||console.error("\u2705 Added missing column: relationships.timestamp")})),s.includes("metadata")||(i++,this.db.run("ALTER TABLE relationships ADD COLUMN metadata TEXT DEFAULT '{}'",n=>{n&&!n.message.includes("duplicate column")?console.error("Error adding metadata column:",n):n||console.error("\u2705 Added missing column: relationships.metadata")})),i===0&&(process.env.NOVA_MCP_MODE||console.error("\u2705 Relationships table schema is up to date"))}}),this.db.all("PRAGMA table_info(memory_entity_links)",(e,t)=>{if(!e&&t&&t.length>0){let s=t.map(n=>n.name),i=0;s.includes("confidence")||(i++,this.db.run("ALTER TABLE memory_entity_links ADD COLUMN confidence FLOAT DEFAULT 1.0",n=>{n&&!n.message.includes("duplicate column")?console.error("Error adding confidence column to memory_entity_links:",n):n||console.error("\u2705 Added missing column: memory_entity_links.confidence")})),s.includes("timestamp")||(i++,this.db.run("ALTER TABLE memory_entity_links ADD COLUMN timestamp DATETIME DEFAULT CURRENT_TIMESTAMP",n=>{n&&!n.message.includes("duplicate column")?console.error("Error adding timestamp column to memory_entity_links:",n):n||console.error("\u2705 Added missing column: memory_entity_links.timestamp")})),i===0&&(process.env.NOVA_MCP_MODE||console.error("\u2705 Memory_entity_links table schema is up to date"))}}),this.db.all("PRAGMA table_info(memory_entries)",(e,t)=>{if(!e&&t&&t.length>0){let s=t.map(n=>n.name),i=0;s.includes("entity_key")||(i++,this.db.run("ALTER TABLE memory_entries ADD COLUMN entity_key TEXT",n=>{n&&!n.message.includes("duplicate column")?console.error("Error adding entity_key column:",n):n||console.error("\u2705 Added missing column: memory_entries.entity_key")})),s.includes("version")||(i++,this.db.run("ALTER TABLE memory_entries ADD COLUMN version INTEGER DEFAULT 1",n=>{n&&!n.message.includes("duplicate column")?console.error("Error adding version column:",n):n||console.error("\u2705 Added missing column: memory_entries.version")})),s.includes("previous_id")||(i++,this.db.run("ALTER TABLE memory_entries ADD COLUMN previous_id INTEGER",n=>{n&&!n.message.includes("duplicate column")?console.error("Error adding previous_id column:",n):n||console.error("\u2705 Added missing column: memory_entries.previous_id")})),s.includes("is_latest")||(i++,this.db.run("ALTER TABLE memory_entries ADD COLUMN is_latest INTEGER DEFAULT 1",n=>{n&&!n.message.includes("duplicate column")?console.error("Error adding is_latest column:",n):n||console.error("\u2705 Added missing column: memory_entries.is_latest")})),i===0&&(process.env.NOVA_MCP_MODE||console.error("\u2705 Memory entries table schema is up to date"))}})})}initDatabase(){try{pa.ensureDirSync(ya.dirname(this.dbPath)),this.db=new ge.Database(this.dbPath,ge.OPEN_READWRITE|ge.OPEN_CREATE),this.setupAutoRecovery(),this.db.run("PRAGMA journal_mode = WAL"),this.db.run("PRAGMA synchronous = NORMAL"),this.db.run("PRAGMA cache_size = 50000"),this.db.run("PRAGMA temp_store = MEMORY"),this.db.run("PRAGMA mmap_size = 268435456"),this.db.run("PRAGMA page_size = 4096"),this.db.run("PRAGMA locking_mode = NORMAL"),this.db.run("PRAGMA busy_timeout = 30000"),this.db.run("PRAGMA wal_autocheckpoint = 1000"),this.createSchemaBlocking(),this.prepareStatements(),process.env.NOVA_MCP_MODE||console.error("\u2705 Database schema initialized with performance optimizations and auto-recovery")}catch(e){throw console.error(`\u274C Failed to initialize database: ${e.message}`),e}}dbRun(e,t=[],s=3){return new Promise((i,n)=>{let r=u(o=>{this.db.run(e,t,function(a){a?a.code==="SQLITE_BUSY"&&o>0?setTimeout(()=>r(o-1),100*(4-o)):n(a):i({lastID:this.lastID,changes:this.changes})})},"attempt");r(s)})}dbGet(e,t=[],s=3){return new Promise((i,n)=>{let r=u(o=>{this.db.get(e,t,(a,c)=>{a?a.code==="SQLITE_BUSY"&&o>0?setTimeout(()=>r(o-1),100*(4-o)):n(a):i(c)})},"attempt");r(s)})}dbAll(e,t=[],s=3){return new Promise((i,n)=>{let r=u(o=>{this.db.all(e,t,(a,c)=>{a?a.code==="SQLITE_BUSY"&&o>0?setTimeout(()=>r(o-1),100*(4-o)):n(a):i(c)})},"attempt");r(s)})}createSchemaBlocking(){this.db.serialize(()=>{this.db.run("SELECT 1",e=>{e||this.addMissingColumnsSync()}),this.db.run(` CREATE TABLE IF NOT EXISTS memory_entries ( id INTEGER PRIMARY KEY AUTOINCREMENT, content TEXT NOT NULL, memory_type TEXT DEFAULT 'general', session_id TEXT, timestamp TEXT DEFAULT (datetime('now')), tags TEXT DEFAULT '[]', tool_used TEXT, confidence_score REAL DEFAULT 1.0, metadata TEXT DEFAULT '{}', embedding TEXT ) `),this.db.run(` CREATE TABLE IF NOT EXISTS entities ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL UNIQUE, type TEXT DEFAULT 'unknown', confidence REAL DEFAULT 1.0, created_at TEXT DEFAULT (datetime('now')), updated_at TEXT DEFAULT (datetime('now')), last_updated TEXT DEFAULT (datetime('now')), mention_count INTEGER DEFAULT 1, metadata TEXT DEFAULT '{}' ) `),this.db.run(` CREATE TABLE IF NOT EXISTS relationships ( id INTEGER PRIMARY KEY AUTOINCREMENT, entity1 TEXT NOT NULL, entity2 TEXT NOT NULL, relation TEXT NOT NULL, confidence REAL DEFAULT 1.0, entity1_type TEXT DEFAULT 'unknown', entity2_type TEXT DEFAULT 'unknown', relation_type TEXT DEFAULT 'general', created_at TEXT DEFAULT (datetime('now')), updated_at TEXT DEFAULT (datetime('now')), timestamp TEXT DEFAULT (datetime('now')), metadata TEXT DEFAULT '{}' ) `),this.db.run(` CREATE TABLE IF NOT EXISTS memory_entity_links ( id INTEGER PRIMARY KEY AUTOINCREMENT, memory_id INTEGER, entity_id INTEGER, confidence FLOAT DEFAULT 1.0, timestamp DATETIME DEFAULT CURRENT_TIMESTAMP, created_at TEXT DEFAULT (datetime('now')), FOREIGN KEY(memory_id) REFERENCES memory_entries(id), FOREIGN KEY(entity_id) REFERENCES entities(id), UNIQUE(memory_id, entity_id) ) `),this.db.run(` CREATE TABLE IF NOT EXISTS analysis_cache ( memory_id TEXT PRIMARY KEY, analysis_version TEXT, analyzed_at INTEGER, cluster_id TEXT, cluster_theme TEXT, features_extracted INTEGER DEFAULT 0, last_modified INTEGER, metadata TEXT ) `),this.db.run("CREATE INDEX IF NOT EXISTS idx_memory_timestamp ON memory_entries(timestamp)"),this.db.run("CREATE INDEX IF NOT EXISTS idx_memory_type ON memory_entries(memory_type)"),this.db.run("CREATE INDEX IF NOT EXISTS idx_memory_session ON memory_entries(session_id)"),this.db.run("CREATE INDEX IF NOT EXISTS idx_memory_content ON memory_entries(content)"),this.db.run("CREATE INDEX IF NOT EXISTS idx_entities_name ON entities(name)"),this.db.run("CREATE INDEX IF NOT EXISTS idx_entities_type ON entities(type)"),this.db.run("CREATE INDEX IF NOT EXISTS idx_entities_last_updated ON entities(last_updated)"),this.db.run("CREATE INDEX IF NOT EXISTS idx_relationships_entity1 ON relationships(entity1)"),this.db.run("CREATE INDEX IF NOT EXISTS idx_relationships_entity2 ON relationships(entity2)"),this.db.run("CREATE INDEX IF NOT EXISTS idx_relationships_relation ON relationships(relation)"),this.db.run("CREATE INDEX IF NOT EXISTS idx_relationships_timestamp ON relationships(timestamp)"),this.db.run("CREATE INDEX IF NOT EXISTS idx_memory_entity_links_memory ON memory_entity_links(memory_id)"),this.db.run("CREATE INDEX IF NOT EXISTS idx_memory_entity_links_entity ON memory_entity_links(entity_id)"),this.db.run("CREATE INDEX IF NOT EXISTS idx_analysis_cache_cluster ON analysis_cache(cluster_id)"),this.db.run("CREATE INDEX IF NOT EXISTS idx_analysis_cache_version ON analysis_cache(analysis_version)"),this.db.run(` CREATE VIRTUAL TABLE IF NOT EXISTS memory_fts USING fts5( content, tags, memory_type, content='memory_entries', content_rowid='id' ) `),this.db.run(` CREATE TRIGGER IF NOT EXISTS memory_fts_insert AFTER INSERT ON memory_entries BEGIN INSERT INTO memory_fts(rowid, content, tags, memory_type) VALUES (new.id, new.content, new.tags, new.memory_type); END `),this.db.run(` CREATE TRIGGER IF NOT EXISTS memory_fts_delete AFTER DELETE ON memory_entries BEGIN INSERT INTO memory_fts(memory_fts, rowid, content, tags, memory_type) VALUES('delete', old.id, old.content, old.tags, old.memory_type); END `),this.db.run(` CREATE TRIGGER IF NOT EXISTS memory_fts_update AFTER UPDATE ON memory_entries BEGIN INSERT INTO memory_fts(memory_fts, rowid, content, tags, memory_type) VALUES('delete', old.id, old.content, old.tags, old.memory_type); INSERT INTO memory_fts(rowid, content, tags, memory_type) VALUES (new.id, new.content, new.tags, new.memory_type); END `)})}prepareStatements(){process.env.NOVA_MCP_MODE||console.error("\u2705 Prepared statements initialized for performance optimization")}setupAutoRecovery(){let e=this.dbRun.bind(this);this.dbRun=async(t,s=[],i=3)=>{try{return await e(t,s,i)}catch(n){if(n.message&&n.message.includes("no such column"))return console.error(`\u{1F527} Auto-recovery triggered: ${n.message}`),await new Promise(r=>{this.addMissingColumnsSync(),setTimeout(r,100)}),console.error("\u{1F504} Retrying operation after auto-recovery..."),await e(t,s,i);if(n.message&&n.message.includes("no such table"))return console.error(`\u{1F527} Auto-recovery triggered for missing table: ${n.message}`),await new Promise(r=>{this.createSchemaBlocking(),setTimeout(r,100)}),console.error("\u{1F504} Retrying operation after table creation..."),await e(t,s,i);throw n}}}async close(){return new Promise((e,t)=>{this.db?this.db.close(s=>{s?t(s):(console.error("\u2705 Memory system database closed"),e())}):e()})}};u(_e,"DatabaseOperations");var fe=_e;ji.exports={DatabaseOperations:fe}});var Wi=g((wl,Bi)=>{var W=require("fs-extra"),P=require("path"),Ui=require("yaml"),we=class we{constructor(){this.defaultConfig=this._getDefaultConfig()}loadConfig(e=null){if(!e)return this.defaultConfig;if(typeof e=="string")return this._loadConfigFile(e);if(typeof e=="object")return this._mergeConfigs(this.defaultConfig,e);throw new Error("Invalid config type. Expected object, string, or null")}expandPath(e){if(!e)throw new Error("File path is required");if(e.startsWith("~")&&(e=P.join(require("os").homedir(),e.slice(2))),process.env.NODE_ENV==="test"||process.env.NOVA_UNIQUE_DB){let t=P.parse(e),s=Date.now(),i=process.pid,n=Math.random().toString(36).substring(2,8);e=P.join(t.dir,`${t.name}-${i}-${s}-${n}${t.ext}`)}return e}validateConfig(e){if(!e||typeof e!="object")throw new Error("Configuration must be an object");if(!e.storage||!e.storage.path)throw new Error("Configuration must include storage.path");if(e.search){let t=["tfidf","bm25","hybrid"];if(e.search.algorithm&&!t.includes(e.search.algorithm))throw new Error(`Invalid search algorithm. Must be one of: ${t.join(", ")}`)}if(e.performance){let t=e.performance;if(t.batch_size&&(typeof t.batch_size!="number"||t.batch_size<1))throw new Error("performance.batch_size must be a positive number");if(t.cache_timeout&&(typeof t.cache_timeout!="number"||t.cache_timeout<0))throw new Error("performance.cache_timeout must be a non-negative number")}return!0}getSystemInfo(){return{nodeVersion:process.version,platform:process.platform,arch:process.arch,pid:process.pid,env:process.env.NODE_ENV||"development",memory:process.memoryUsage(),uptime:process.uptime()}}_getDefaultConfig(){return{storage:{type:"sqlite",path:"~/data/nova-memory/memory.db",backup_enabled:!0,backup_interval:86400,max_backups:7},search:{algorithm:"hybrid",max_results:100,similarity_threshold:.1,optimizations:{enable_caching:!0,enable_indexing:!0,enable_parallel_search:!1,enable_result_reranking:!0}},performance:{batch_size:50,cache_timeout:3e5,max_cache_size:100,connection_timeout:3e4,retry_attempts:3,enable_wal_mode:!0,enable_memory_mapping:!0},entity_extraction:{enabled:!0,confidence_threshold:.8,max_entities_per_memory:20,entity_types:["PERSON","ORG","GPE","TECHNOLOGY","CONCEPT"]},clustering:{algorithm:"dbscan",min_samples:3,eps:.3,max_clusters:50,enable_quality_metrics:!0},query:{default_limit:20,max_limit:1e3,timeout:5e3},retention:{archive_old:!0,days:30,max_entries:1e4,cleanup_enabled:!0},logging:{level:"info",file_enabled:!1,file_path:"~/data/nova-memory/logs/memory.log",console_enabled:!0}}}_loadConfigFile(e){try{let t=this.expandPath(e);if(!W.existsSync(t))return console.warn(`Configuration file not found: ${t}, using defaults`),this.defaultConfig;let s=W.readFileSync(t,"utf8"),i=P.extname(t).toLowerCase(),n;if(i===".yaml"||i===".yml")n=Ui.parse(s);else if(i===".json")n=JSON.parse(s);else throw new Error(`Unsupported configuration file format: ${i}`);return this._mergeConfigs(this.defaultConfig,n)}catch(t){return console.error(`Failed to load configuration from ${e}: ${t.message}`),console.warn("Using default configuration"),this.defaultConfig}}_mergeConfigs(e,t){let s={...e};for(let[i,n]of Object.entries(t))n!=null&&(typeof n=="object"&&!Array.isArray(n)&&typeof s[i]=="object"&&!Array.isArray(s[i])?s[i]=this._mergeConfigs(s[i],n):s[i]=n);return s}saveConfig(e,t,s="yaml"){try{this.validateConfig(e);let i=this.expandPath(t);W.ensureDirSync(P.dirname(i));let n;if(s==="yaml"||s==="yml")n=Ui.stringify(e,{indent:2});else if(s==="json")n=JSON.stringify(e,null,2);else throw new Error(`Unsupported format: ${s}`);W.writeFileSync(i,n,"utf8"),console.log(`Configuration saved to: ${i}`)}catch(i){throw console.error(`Failed to save configuration: ${i.message}`),i}}loadConfigFromLoader(e){try{let t=e.memoryConfig||{},s={storage:{path:e.databasePath,type:"sqlite",backup_enabled:!0,backup_interval:86400,max_backups:7},project:{path:e.projectPath,name:e.projectName||P.basename(e.projectPath)},memory:{globalMaxMemories:t.globalMaxMemories||this.defaultConfig.retention.max_entries,typeRetention:t.typeRetention||{},versioning:t.versioning||{enabled:!1}}};return this._mergeConfigs(this.defaultConfig,s)}catch(t){return console.warn(`Failed to load ConfigLoader format: ${t.message}, using defaults`),this.defaultConfig}}createTemplate(e,t="yaml"){try{let s=this.expandPath(e);if(W.existsSync(s))throw new Error(`Template file already exists: ${s}`);this.saveConfig(this.defaultConfig,s,t),console.log(`Configuration template created: ${s}`)}catch(s){throw console.error(`Failed to create configuration template: ${s.message}`),s}}};u(we,"ConfigurationManager");var be=we;Bi.exports={ConfigurationManager:be}});var K=g((Sl,Te)=>{var{ConfigurationManager:Hi}=Wi();Te.exports={ConfigurationManager:Hi};Te.exports.ConfigurationManager=Hi});var G=g((Cl,Gi)=>{var{v4:ga}=require("uuid"),Ce=class Ce{constructor({id:e=null,content:t="",memory_type:s="general",session_id:i=null,timestamp:n=null,tags:r=[],tool_used:o=null,confidence_score:a=1,metadata:c={},embedding:l=null,structured:h=null}={}){this.id=e,this.content=t,this.memory_type=s,this.session_id=i,this.timestamp=n||new Date,this.tags=Array.isArray(r)?r:[],this.tool_used=o,this.confidence_score=a,this.metadata=c||{},this.embedding=l,this.structured=h}toJSON(){return{id:this.id,content:this.content,memory_type:this.memory_type,session_id:this.session_id,timestamp:this.timestamp.toISOString(),tags:this.tags,tool_used:this.tool_used,confidence_score:this.confidence_score,metadata:this.metadata,embedding:this.embedding}}};u(Ce,"MemoryEntry");var H=Ce,ve=class ve{constructor(e,t){var s,i,n;this.db=e,this.config=t,this.stats={total_entries:0,last_cleanup:null,cleanup_count:0,cache_hits:0,cache_misses:0},this.queryCache=new Map,this.maxCacheSize=((s=t.performance)==null?void 0:s.max_cache_size)||100,this.cacheTimeout=((i=t.performance)==null?void 0:i.cache_timeout)||3e5,this.batchQueue=[],this.batchSize=((n=t.performance)==null?void 0:n.batch_size)||50,this.batchTimeout=null}async store(e){try{let t=process.hrtime.bigint();e instanceof H||(e=new H(e)),e.id||(e.id=ga()),this._validateEntry(e);let i=(await this.db.dbRun(` INSERT INTO memory_entries ( content, memory_type, session_id, timestamp, tags, tool_used, confidence_score, metadata, embedding ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) `,[e.content,e.memory_type,e.session_id,e.timestamp.toISOString(),JSON.stringify(e.tags),e.tool_used,e.confidence_score,JSON.stringify(e.metadata),e.embedding?JSON.stringify(e.embedding):null])).lastID;this.stats.total_entries++,this._clearCache();let n=process.hrtime.bigint(),r=Number(n-t)/1e6;return console.log(`\u2705 Memory entry stored with ID: ${i} (${r.toFixed(2)}ms)`),i}catch(t){throw console.error(`\u274C Failed to store memory entry: ${t.message}`),t}}async query(e={},t=null){var s;try{let i=process.hrtime.bigint();t=t||((s=this.config.search)==null?void 0:s.max_results)||100;let n=`query_${JSON.stringify(e)}_${t}`,r=this._getFromCache(n);if(r){this.stats.cache_hits++;let m=process.hrtime.bigint(),p=Number(m-i)/1e6;return console.log(`\u{1F680} Query served from cache (${p.toFixed(2)}ms)`),r}this.stats.cache_misses++;let o="SELECT * FROM memory_entries WHERE 1=1",a=[];e.memory_type&&(o+=" AND memory_type = ?",a.push(e.memory_type)),e.session_id&&(o+=" AND session_id = ?",a.push(e.session_id)),e.tool_used&&(o+=" AND tool_used = ?",a.push(e.tool_used)),e.min_confidence&&(o+=" AND confidence_score >= ?",a.push(e.min_confidence)),e.tags&&e.tags.length>0&&(o+=" AND tags LIKE ?",a.push(`%${e.tags[0]}%`)),e.content_search&&(o+=" AND content LIKE ?",a.push(`%${e.content_search}%`)),e.start_date&&(o+=" AND timestamp >= ?",a.push(e.start_date)),e.end_date&&(o+=" AND timestamp <= ?",a.push(e.end_date)),o+=" ORDER BY timestamp DESC",t&&(o+=" LIMIT ?",a.push(t));let l=(await this.db.dbAll(o,a)).map(m=>({...m,timestamp:new Date(m.timestamp),tags:JSON.parse(m.tags||"[]"),metadata:JSON.parse(m.metadata||"{}"),embedding:m.embedding?JSON.parse(m.embedding):null}));this._setCache(n,l);let h=process.hrtime.bigint(),d=Number(h-i)/1e6;return d>10&&console.warn(`\u26A0\uFE0F Slow query operation: ${d.toFixed(2)}ms (target: <10ms)`),console.log(`\u2705 Query executed (${d.toFixed(2)}ms) - ${l.length} results`),l}catch(i){throw console.error(`\u274C Failed to query memories: ${i.message}`),i}}async update(e,t){try{let s=process.hrtime.bigint(),i=[],n=[];for(let[l,h]of Object.entries(t))l==="tags"||l==="metadata"?(i.push(`${l} = ?`),n.push(JSON.stringify(h))):l==="embedding"?(i.push(`${l} = ?`),n.push(h?JSON.stringify(h):null)):l==="timestamp"?(i.push(`${l} = ?`),n.push(h instanceof Date?h.toISOString():h)):(i.push(`${l} = ?`),n.push(h));if(i.length===0)throw new Error("No valid fields to update");n.push(e);let r=`UPDATE memory_entries SET ${i.join(", ")} WHERE id = ?`;if((await this.db.dbRun(r,n)).changes===0)throw new Error(`Memory entry not found: ${e}`);this._clearCache();let a=process.hrtime.bigint(),c=Number(a-s)/1e6;return console.log(`\u2705 Memory entry updated: ${e} (${c.toFixed(2)}ms)`),!0}catch(s){throw console.error(`\u274C Failed to update memory entry: ${s.message}`),s}}async delete(e){try{let t=process.hrtime.bigint();if((await this.db.dbRun("DELETE FROM memory_entries WHERE id = ?",[e])).changes===0)throw new Error(`Memory entry not found: ${e}`);await this.db.dbRun("DELETE FROM memory_entity_links WHERE memory_id = ?",[e]),this.stats.total_entries--,this._clearCache();let i=process.hrtime.bigint(),n=Number(i-t)/1e6;return console.log(`\u2705 Memory entry deleted: ${e} (${n.toFixed(2)}ms)`),!0}catch(t){throw console.error(`\u274C Failed to delete memory entry: ${t.message}`),t}}async getStats(){try{let e=await this.db.dbGet("SELECT COUNT(*) as count FROM memory_entries");this.stats.total_entries=e.count;let t=await this.db.dbAll(` SELECT memory_type, COUNT(*) as count FROM memory_entries GROUP BY memory_type `),s=await this.db.dbAll(` SELECT session_id, COUNT(*) as count FROM memory_entries WHERE session_id IS NOT NULL GROUP BY session_id ORDER BY count DESC LIMIT 10 `);return{...this.stats,type_distribution:t,top_sessions:s,cache_hit_rate:this.stats.cache_hits/(this.stats.cache_hits+this.stats.cache_misses)||0}}catch(e){throw console.error(`\u274C Failed to get memory statistics: ${e.message}`),e}}_validateEntry(e){if(!e.content||typeof e.content!="string")throw new Error("Memory entry must have non-empty content");if(e.content.length>1e4)throw new Error("Memory content too long (max 10000 characters)");if(e.confidence_score<0||e.confidence_score>1)throw new Error("Confidence score must be between 0 and 1");if(!Array.isArray(e.tags))throw new Error("Tags must be an array");if(typeof e.metadata!="object")throw new Error("Metadata must be an object")}_getFromCache(e){let t=this.queryCache.get(e);return t&&Date.now()-t.timestamp<this.cacheTimeout?t.data:(t&&this.queryCache.delete(e),null)}_setCache(e,t){if(this.queryCache.size>=this.maxCacheSize){let s=this.queryCache.keys().next().value;this.queryCache.delete(s)}this.queryCache.set(e,{data:t,timestamp:Date.now()})}_clearCache(){this.queryCache.clear()}};u(ve,"MemoryStorage");var Se=ve;Gi.exports={MemoryEntry:H,MemoryStorage:Se}});var Ne=g((Al,Vi)=>{var Me=class Me{constructor(e={}){this.maxFeatures=e.maxFeatures||1e3,this.minTermFreq=e.minTermFreq||1,this.stopWords=new Set(["the","a","an","and","or","but","in","on","at","to","for","of","with","by","from","up","about","into","through","during","before","after","above","below","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","could","should","may","might","must","can","shall","this","that"])}extractFeatures(e){let t=process.hrtime.bigint(),s=this.buildVocabulary(e),i=e.map(o=>this.memoryToVector(o,s)),n=process.hrtime.bigint(),r=Number(n-t)/1e6;return{vectors:i,vocabulary:s,dimensions:s.size,duration:r}}buildVocabulary(e){let t=new Map;e.forEach(n=>{let r=this.tokenize(n.content);new Set(r).forEach(a=>{t.set(a,(t.get(a)||0)+1)})});let s=new Map,i=0;return Array.from(t.entries()).filter(([n,r])=>r>=this.minTermFreq).sort((n,r)=>r[1]-n[1]).slice(0,this.maxFeatures).forEach(([n,r])=>{s.set(n,i++)}),s}memoryToVector(e,t){let s=new Array(t.size).fill(0),i=this.tokenize(e.content),n=new Map;i.forEach(o=>{t.has(o)&&n.set(o,(n.get(o)||0)+1)}),n.forEach((o,a)=>{let c=t.get(a);s[c]=o/i.length});let r=this.extractMetadataFeatures(e);return{id:e.id,features:s,metadata:r,content:e.content,memory_type:e.memory_type,tags:e.tags||[],timestamp:e.timestamp,confidence_score:e.confidence_score||1}}extractMetadataFeatures(e){return{contentLength:e.content.length,tagCount:(e.tags||[]).length,confidenceScore:e.confidence_score||1,memoryType:e.memory_type,dayOfWeek:new Date(e.timestamp).getDay(),hourOfDay:new Date(e.timestamp).getHours()}}tokenize(e){return!e||typeof e!="string"?[]:e.toLowerCase().replace(/[^\w\s]/g," ").split(/\s+/).filter(t=>t.length>2&&!this.stopWords.has(t)).filter(Boolean)}cosineDistance(e,t){if(e.length!==t.length)throw new Error("Vectors must have same dimensions");let s=0,i=0,n=0;for(let a=0;a<e.length;a++)s+=e[a]*t[a],i+=e[a]*e[a],n+=t[a]*t[a];let r=Math.sqrt(i)*Math.sqrt(n);return r===0?1:1-s/r}euclideanDistance(e,t){if(e.length!==t.length)throw new Error("Vectors must have same dimensions");let s=0;for(let i=0;i<e.length;i++){let n=e[i]-t[i];s+=n*n}return Math.sqrt(s)}};u(Me,"MemoryFeatureExtractor");var N=Me,Re=class Re{constructor(e=.5,t=3,s="cosine",i=null){this.epsilon=e,this.minPoints=t,this.distanceMetric=s,this.featureExtractor=i||new N}cluster(e){let t=process.hrtime.bigint(),s=e.map((c,l)=>({index:l,features:c.features,memory:c,cluster:null,visited:!1,isNoise:!1})),i=0,n=[];for(let c of s){if(c.visited)continue;c.visited=!0;let l=this.regionQuery(c,s);if(l.length<this.minPoints)c.isNoise=!0;else{let h=this.expandCluster(c,l,i,s);h.length>0&&(n.push({id:i,size:h.length,members:h,centroid:this.calculateCentroid(h)}),i++)}}let r=s.filter(c=>c.isNoise).map(c=>c.memory),o=process.hrtime.bigint(),a=Number(o-t)/1e6;return{clusters:n,noise:r,stats:{clusterCount:n.length,noiseCount:r.length,totalPoints:s.length,avgClusterSize:n.length>0?n.reduce((c,l)=>c+l.size,0)/n.length:0},parameters:{epsilon:this.epsilon,minPoints:this.minPoints,distanceMetric:this.distanceMetric},duration:a}}regionQuery(e,t){let s=[];if(e._processedNeighbors)return e._processedNeighbors;for(let i of t){if(e===i)continue;this.calculateDistance(e.features,i.features)<=this.epsilon&&s.push(i)}return e._processedNeighbors=s,s}expandCluster(e,t,s,i){let n=[e.memory];e.cluster=s;let r=0;for(;r<t.length;){let o=t[r];if(!o.visited){o.visited=!0;let a=this.regionQuery(o,i);a.length>=this.minPoints&&t.push(...a)}o.cluster===null&&(o.cluster=s,n.push(o.memory)),r++}return n}calculateDistance(e,t){if(this.distanceMetric==="cosine")return this.featureExtractor.cosineDistance(e,t);if(this.distanceMetric==="euclidean")return this.featureExtractor.euclideanDistance(e,t);throw new Error(`Unknown distance metric: ${this.distanceMetric}`)}calculateCentroid(e){if(e.length===0)return null;let t=e[0].features.length,s=new Array(t).fill(0);e.forEach(i=>{for(let n=0;n<t;n++)s[n]+=i.features[n]});for(let i=0;i<t;i++)s[i]/=e.length;return s}};u(Re,"DBSCANClusterer");var Z=Re,ke=class ke{constructor(e=3,t=100,s=1e-4,i="euclidean",n=null){this.k=e,this.maxIterations=t,this.tolerance=s,this.distanceMetric=i,this.featureExtractor=n||new N}cluster(e){let t=process.hrtime.bigint();if(e.length<this.k)throw new Error(`Cannot create ${this.k} clusters from ${e.length} data points`);let s=e.map(l=>({features:l.features,memory:l,cluster:null})),i=this.initializeCentroids(s),n=0,r=!1;for(;n<this.maxIterations&&!r;){this.assignPointsToClusters(s,i);let l=this.updateCentroids(s);r=this.hasConverged(i,l),i=l,n++}let o=this.createClusters(s,i),a=process.hrtime.bigint(),c=Number(a-t)/1e6;return{clusters:o,stats:{clusterCount:o.length,totalPoints:s.length,avgClusterSize:o.reduce((l,h)=>l+h.size,0)/o.length,inertia:this.calculateInertia(s,i)},parameters:{k:this.k,iterations:n,converged:r,distanceMetric:this.distanceMetric},duration:c}}initializeCentroids(e){let t=[],s=e[0].features.length,i=e[Math.floor(Math.random()*e.length)].features.slice();t.push(i);for(let n=1;n<this.k;n++){let r=e.map(l=>{let h=1/0;for(let d of t){let m=this.calculateDistance(l.features,d);h=Math.min(h,m)}return h*h}),o=r.reduce((l,h)=>l+h,0),a=Math.random()*o,c=0;for(let l=0;l<e.length;l++)if(c+=r[l],c>=a){t.push(e[l].features.slice());break}}return t}assignPointsToClusters(e,t){e.forEach(s=>{let i=1/0,n=0;t.forEach((r,o)=>{let a=this.calculateDistance(s.features,r);a<i&&(i=a,n=o)}),s.cluster=n})}updateCentroids(e){let t=e[0].features.length,s=[];for(let i=0;i<this.k;i++){let n=e.filter(o=>o.cluster===i);if(n.length===0){s.push(new Array(t).fill(0));continue}let r=new Array(t).fill(0);n.forEach(o=>{for(let a=0;a<t;a++)r[a]+=o.features[a]});for(let o=0;o<t;o++)r[o]/=n.length;s.push(r)}return s}hasConverged(e,t){for(let s=0;s<e.length;s++)if(this.calculateDistance(e[s],t[s])>this.tolerance)return!1;return!0}createClusters(e,t){let s=[];for(let i=0;i<this.k;i++){let n=e.filter(r=>r.cluster===i);n.length>0&&s.push({id:i,size:n.length,members:n.map(r=>r.memory),centroid:t[i]})}return s}calculateInertia(e,t){let s=0;return e.forEach(i=>{let n=t[i.cluster],r=this.calculateDistance(i.features,n);s+=r*r}),s}calculateDistance(e,t){if(this.distanceMetric==="cosine")return this.featureExtractor.cosineDistance(e,t);if(this.distanceMetric==="euclidean")return this.featureExtractor.euclideanDistance(e,t);throw new Error(`Unknown distance metric: ${this.distanceMetric}`)}};u(ke,"KMeansClusterer");var ee=ke,xe=class xe{static calculateSilhouetteScore(e,t,s=null){if(t.length<2)return 0;let i=s||new N,n=new Map;t.forEach((a,c)=>{a.members.forEach(l=>{n.set(l.id,c)})});let r=0,o=0;return e.forEach(a=>{let c=n.get(a.id);if(c===void 0)return;let l=t[c];if(l.size<2)return;let h=0,d=0;l.members.forEach(_=>{if(_.id!==a.id){let E=e.find(b=>b.id===_.id);E&&(h+=i.euclideanDistance(a.features,E.features),d++)}});let m=d>0?h/d:0,p=1/0;t.forEach((_,E)=>{if(E===c)return;let b=0,w=0;if(_.members.forEach(S=>{let v=e.find(C=>C.id===S.id);v&&(b+=i.euclideanDistance(a.features,v.features),w++)}),w>0){let S=b/w;p=Math.min(p,S)}});let y=p===1/0?0:p,f=Math.max(m,y)===0?0:(y-m)/Math.max(m,y);r+=f,o++}),o>0?r/o:0}static calculateDaviesBouldinIndex(e,t,s=null){if(t.length<2)return 0;let i=s||new N,n=t.map(a=>a.centroid),r=t.map((a,c)=>{let l=0;return a.members.forEach(h=>{let d=e.find(m=>m.id===h.id);d&&(l+=i.euclideanDistance(d.features,n[c]))}),a.size>0?l/a.size:0}),o=0;return t.forEach((a,c)=>{let l=0;t.forEach((h,d)=>{if(c===d)return;let m=i.euclideanDistance(n[c],n[d]);if(m>0){let p=(r[c]+r[d])/m;l=Math.max(l,p)}}),o+=l}),o/t.length}};u(xe,"ClusteringEvaluator");var L=xe,Oe=class Oe{constructor(e={}){this.featureExtractor=new N(e.features)}async clusterWithDBSCAN(e,t={}){if(e.length===0)return{clusters:[],noise:[],stats:{clusterCount:0,noiseCount:0,totalPoints:0,avgClusterSize:0},parameters:{epsilon:t.epsilon||.3,minPoints:t.minPoints||3,distanceMetric:t.distanceMetric||"cosine"},quality:{silhouetteScore:0,daviesBouldinIndex:0},algorithm:"DBSCAN",duration:0};let s=e.length,i=300;console.log(`\u{1F527} MCP SERVER DEBUG: DBSCAN analyzing ${s} memories - OPTIMIZATION ACTIVE!`);let n=e;if(s>i){console.log(`\u{1F4CA} DBSCAN optimization: ${s} \u2192 ${i} memories (avoiding ${Math.pow(s,2).toLocaleString()} distance calculations)`);let h=Math.floor(i*.5),d=i-h,m=e.slice(0,h),y=e.slice(h).sort(()=>.5-Math.random()).slice(0,d);n=[...m,...y],console.log(`\u{1F680} Complexity reduced: O(${Math.pow(n.length,2).toLocaleString()}) vs O(${Math.pow(s,2).toLocaleString()}) operations`)}let{vectors:r}=this.featureExtractor.extractFeatures(n),a=new Z(t.epsilon||.3,t.minPoints||3,t.distanceMetric||"cosine",this.featureExtractor).cluster(r),c=L.calculateSilhouetteScore(r,a.clusters,this.featureExtractor),l=L.calculateDaviesBouldinIndex(r,a.clusters,this.featureExtractor);return{...a,quality:{silhouetteScore:c,daviesBouldinIndex:l},algorithm:"DBSCAN"}}async clusterWithKMeans(e,t={}){if(e.length===0)return{clusters:[],stats:{clusterCount:0,totalPoints:0,avgClusterSize:0,inertia:0},parameters:{k:t.k||0,iterations:0,converged:!0,distanceMetric:t.distanceMetric||"euclidean"},quality:{silhouetteScore:0,daviesBouldinIndex:0},algorithm:"K-Means",duration:0};let{vectors:s}=this.featureExtractor.extractFeatures(e),i=t.k||Math.min(Math.ceil(Math.sqrt(e.length/2)),10),r=new ee(i,t.maxIterations||100,t.tolerance||1e-4,t.distanceMetric||"euclidean",this.featureExtractor).cluster(s),o=L.calculateSilhouetteScore(s,r.clusters,this.featureExtractor),a=L.calculateDaviesBouldinIndex(s,r.clusters,this.featureExtractor);return{...r,quality:{silhouetteScore:o,daviesBouldinIndex:a},algorithm:"K-Means"}}async autoClustering(e,t={}){let s=process.hrtime.bigint();if(e.length===0){let c={clusters:[],noise:[],stats:{clusterCount:0,noiseCount:0,totalPoints:0,avgClusterSize:0,inertia:0},parameters:{epsilon:t.epsilon||.3,minPoints:t.minPoints||3,k:t.k||0,iterations:0,converged:!0,distanceMetric:"euclidean"},quality:{silhouetteScore:0,daviesBouldinIndex:0},algorithm:"None",duration:0};return{bestResult:c,dbscanResult:c,kmeansResult:c,comparison:{dbscanSilhouette:0,kmeansSilhouette:0,selectedAlgorithm:"None",totalDuration:0}}}let i=await this.clusterWithDBSCAN(e,{epsilon:t.epsilon||.3,minPoints:t.minPoints||3,distanceMetric:"cosine"}),n=await this.clusterWithKMeans(e,{k:t.k||Math.min(Math.ceil(Math.sqrt(e.length/2)),8),distanceMetric:"euclidean"}),r=i.quality.silhouetteScore>n.quality.silhouetteScore?i:n,o=process.hrtime.bigint(),a=Number(o-s)/1e6;return{bestResult:r,dbscanResult:i,kmeansResult:n,comparison:{dbscanSilhouette:i.quality.silhouetteScore,kmeansSilhouette:n.quality.silhouetteScore,selectedAlgorithm:r.algorithm,totalDuration:a}}}};u(Oe,"ClusteringEngine");var Ae=Oe;Vi.exports={MemoryFeatureExtractor:N,DBSCANClusterer:Z,KMeansClusterer:ee,ClusteringEvaluator:L,ClusteringEngine:Ae}});var Yi=g((Rl,Xi)=>{var De=class De{constructor(e={}){this.batchSize=e.batchSize||20,this.maxTokensPerBatch=e.maxTokensPerBatch||15e3,this.progressCallback=e.progressCallback||null,this.analysisCache=e.analysisCache||null}async analyzeBatches(e,t={}){let s=Date.now(),i={batches:[],summary:{totalMemories:e.length,processedMemories:0,cachedMemories:0,batchesProcessed:0,clusters:new Map,errors:[]},progress:[]},n=e;if(this.analysisCache){let a=await this.analysisCache.filterUnanalyzedMemories(e);n=a.unanalyzed,i.summary.cachedMemories=a.alreadyAnalyzed,this.reportProgress({phase:"cache_check",cached:a.alreadyAnalyzed,toProcess:n.length,total:e.length})}let r=this.createTokenSafeBatches(n);for(let a=0;a<r.length;a++){let c=r[a];try{this.reportProgress({phase:"batch_start",batchNumber:a+1,totalBatches:r.length,batchSize:c.length,estimatedTokens:c.estimatedTokens});let l=await this.analyzeSingleBatch(c.memories,{...t,batchId:`batch_${a+1}`});i.batches.push({batchId:`batch_${a+1}`,size:c.length,result:l,duration:l.duration}),i.summary.processedMemories+=c.length,i.summary.batchesProcessed++,this.analysisCache&&l.clusterAssignments&&await this.analysisCache.markAsAnalyzed(c.memories,l.clusterAssignments,t.analysisVersion||"1.0"),this.reportProgress({phase:"batch_complete",batchNumber:a+1,processedSoFar:i.summary.processedMemories,totalToProcess:n.length,percentComplete:Math.round(i.summary.processedMemories/n.length*100)})}catch(l){i.summary.errors.push({batch:a+1,error:l.message}),this.reportProgress({phase:"batch_error",batchNumber:a+1,error:l.message})}a<r.length-1&&await this.delay(100)}let o=this.mergeBatchResults(i.batches);return i.finalAnalysis={...o,summary:{...i.summary,duration:Date.now()-s,averageBatchTime:i.batches.reduce((a,c)=>a+(c.duration||0),0)/i.batches.length}},this.reportProgress({phase:"complete",totalProcessed:i.summary.processedMemories,totalCached:i.summary.cachedMemories,totalBatches:i.summary.batchesProcessed,duration:Date.now()-s}),i}createTokenSafeBatches(e){let t=[],s=[],i=0;for(let n of e){let r=this.estimateTokens(n);s.length>0&&(i+r>this.maxTokensPerBatch||s.length>=this.batchSize)?(t.push({memories:s,estimatedTokens:i,length:s.length}),s=[n],i=r):(s.push(n),i+=r)}return s.length>0&&t.push({memories:s,estimatedTokens:i,length:s.length}),t}async analyzeSingleBatch(e,t={}){let{ClusteringEngine:s}=Ne(),i=new s,n=Date.now(),r=await i.clusterWithDBSCAN(e,{epsilon:t.epsilon||.3,minPoints:Math.min(3,Math.floor(e.length/4)),...t}),o=new Map;return r.clusters&&r.clusters.forEach((a,c)=>{let l=`${t.batchId}_cluster_${c}`,h=a.theme||`Cluster ${c+1}`;a.memories&&Array.isArray(a.memories)&&a.memories.forEach(d=>{o.set(d.id,{id:l,theme:h})})}),{...r,clusterAssignments:o,batchId:t.batchId,duration:Date.now()-n}}mergeBatchResults(e){let t={totalClusters:0,clusters:[],noise:[],stats:{totalMemories:0,clusteredMemories:0,noiseMemories:0}};for(let s of e)s.result.clusters&&t.clusters.push(...s.result.clusters.map(i=>({...i,batchId:s.batchId}))),s.result.noise&&t.noise.push(...s.result.noise),t.stats.totalMemories+=s.size;return t.totalClusters=t.clusters.length,t.stats.clusteredMemories=t.stats.totalMemories-t.noise.length,t.stats.noiseMemories=t.noise.length,t}estimateTokens(e){let t=0;return e.content&&(t+=e.content.length),e.tags&&(t+=JSON.stringify(e.tags).length),e.metadata&&(t+=JSON.stringify(e.metadata).length),Math.ceil(t/4)}reportProgress(e){this.progressCallback&&this.progressCallback(e)}delay(e){return new Promise(t=>setTimeout(t,e))}async*analyzeIncremental(e,t={}){var n,r;let s=this.createTokenSafeBatches(e),i={processedBatches:0,totalBatches:s.length,clusters:[],summary:{}};for(let o=0;o<s.length;o++){let a=s[o];yield{type:"progress",batchNumber:o+1,totalBatches:s.length,processing:a.length};let c=await this.analyzeSingleBatch(a.memories,{...t,batchId:`batch_${o+1}`});i.processedBatches++,i.clusters.push(...c.clusters||[]),yield{type:"batch_complete",batchNumber:o+1,result:{clusters:((n=c.clusters)==null?void 0:n.length)||0,noise:((r=c.noise)==null?void 0:r.length)||0,duration:c.duration},cumulativeProgress:{processedBatches:i.processedBatches,totalClusters:i.clusters.length}}}yield{type:"complete",finalResults:i}}};u(De,"BatchAnalysisEngine");var Ie=De;Xi.exports={BatchAnalysisEngine:Ie}});var Qi=g((xl,Ji)=>{var Fe=class Fe{constructor(){this.nodes=new Map,this.edges=new Map,this.edgeWeights=new Map}addNode(e,t){this.nodes.set(e,{id:e,...t,pagerank:1,community:null,degree:0}),this.edges.has(e)||this.edges.set(e,new Set)}addEdge(e,t,s=1){if(!this.nodes.has(e)||!this.nodes.has(t))throw new Error(`Both nodes must exist before adding edge: ${e} -> ${t}`);this.edges.get(e).add(t),this.edges.get(t).add(e),this.edgeWeights.set(`${e}-${t}`,s),this.edgeWeights.set(`${t}-${e}`,s),this.nodes.get(e).degree++,this.nodes.get(t).degree++}getNeighbors(e){return Array.from(this.edges.get(e)||new Set)}getEdgeWeight(e,t){return this.edgeWeights.get(`${e}-${t}`)||0}getAllNodes(){return Array.from(this.nodes.values())}getNode(e){return this.nodes.get(e)}getStats(){let e=this.nodes.size,t=Array.from(this.edges.values()).reduce((r,o)=>r+o.size,0)/2,s=Array.from(this.nodes.values()).map(r=>r.degree),i=s.reduce((r,o)=>r+o,0)/e||0,n=Math.max(...s,0);return{nodes:e,edges:t,averageDegree:i,maxDegree:n,density:e>1?2*t/(e*(e-1)):0}}};u(Fe,"MemoryGraph");var te=Fe,$e=class $e{constructor(e=.85,t=100,s=1e-6){this.dampingFactor=e,this.maxIterations=t,this.tolerance=s}calculatePageRank(e){let t=process.hrtime.bigint(),s=e.getAllNodes();if(s.length===0)return{rankings:[],iterations:0,converged:!0,duration:0};let n=new Map,r=new Map;s.forEach(d=>{n.set(d.id,1),r.set(d.id,0)});let o=0,a=!1;for(;o<this.maxIterations&&!a;){s.forEach(p=>r.set(p.id,0)),s.forEach(p=>{let y=e.getNeighbors(p.id),f=y.length;if(f>0){let _=n.get(p.id)/f;y.forEach(E=>{let b=e.getEdgeWeight(p.id,E),w=_*b;r.set(E,r.get(E)+w)})}});let d=1-this.dampingFactor;s.forEach(p=>{let y=this.dampingFactor*r.get(p.id)+d;r.set(p.id,y)});let m=0;s.forEach(p=>{let y=Math.abs(r.get(p.id)-n.get(p.id));m=Math.max(m,y)}),a=m<this.tolerance,s.forEach(p=>{n.set(p.id,r.get(p.id)),e.getNode(p.id).pagerank=r.get(p.id)}),o++}let c=s.map(d=>({id:d.id,pagerank:n.get(d.id),content:d.content,memory_type:d.memory_type,degree:d.degree})).sort((d,m)=>m.pagerank-d.pagerank),l=process.hrtime.bigint(),h=Number(l-t)/1e6;return{rankings:c,iterations:o,converged:a,duration:h,dampingFactor:this.dampingFactor,tolerance:this.tolerance}}};u($e,"PageRankAnalyzer");var se=$e,Pe=class Pe{constructor(e=100,t=null){this.maxIterations=e,this.randomSeed=t}detectCommunities(e){let t=process.hrtime.bigint(),s=e.getAllNodes();if(s.length===0)return{communities:[],stats:{communityCount:0,modularity:0},iterations:0,duration:0};let n=new Map;s.forEach((m,p)=>{n.set(m.id,p),m.community=p});let r=0,o=!0;for(;r<this.maxIterations&&o;)o=!1,[...s].sort(()=>Math.random()-.5).forEach(p=>{let y=e.getNeighbors(p.id);if(y.length===0)return;let f=new Map;y.forEach(b=>{let w=n.get(b),S=e.getEdgeWeight(p.id,b);f.set(w,(f.get(w)||0)+S)});let _=0,E=n.get(p.id);f.forEach((b,w)=>{b>_&&(_=b,E=w)}),E!==n.get(p.id)&&(n.set(p.id,E),p.community=E,o=!0)}),r++;let a=new Map;s.forEach(m=>{let p=n.get(m.id);a.has(p)||a.set(p,[]),a.get(p).push({id:m.id,content:m.content,memory_type:m.memory_type,pagerank:m.pagerank})});let c=Array.from(a.entries()).map(([m,p])=>({id:m,size:p.length,members:p,avgPageRank:p.reduce((y,f)=>y+f.pagerank,0)/p.length})).sort((m,p)=>p.size-m.size),l=this.calculateModularity(e,n),h=process.hrtime.bigint(),d=Number(h-t)/1e6;return{communities:c,stats:{communityCount:c.length,modularity:l,largestCommunitySize:c.length>0?c[0].size:0,smallestCommunitySize:c.length>0?c[c.length-1].size:0},iterations:r,duration:d}}calculateModularity(e,t){let s=e.getAllNodes(),i=e.getStats().edges*2;if(i===0)return 0;let n=0;return s.forEach(r=>{s.forEach(o=>{if(r.id<=o.id)return;let a=e.getEdgeWeight(r.id,o.id),c=r.degree*o.degree/i,l=t.get(r.id)===t.get(o.id)?1:0;n+=(a-c)*l})}),n/i}};u(Pe,"CommunityDetector");var ie=Pe,ze=class ze{constructor(e={}){this.similarityThreshold=e.similarityThreshold||.1,this.temporalWindowHours=e.temporalWindowHours||24,this.tagWeightMultiplier=e.tagWeightMultiplier||2,this.typeWeightMultiplier=e.typeWeightMultiplier||1.5}buildGraph(e){let t=process.hrtime.bigint(),s=new te;e.forEach(a=>{s.addNode(a.id,{content:a.content,memory_type:a.memory_type,timestamp:new Date(a.timestamp),tags:a.tags||[],confidence_score:a.confidence_score||1})});let n=e.sort((a,c)=>new Date(c.timestamp)-new Date(a.timestamp)).slice(0,200);for(let a=0;a<n.length;a++){let c=Math.min(20,n.length-a-1);for(let l=a+1;l<=a+c&&!(l>=n.length);l++){let h=n[a],d=n[l],m=this.calculateSimilarity(h,d);m>this.similarityThreshold&&s.addEdge(h.id,d.id,m)}}let r=process.hrtime.bigint(),o=Number(r-t)/1e6;return{graph:s,buildStats:{nodeCount:s.nodes.size,edgeCount:s.getStats().edges,duration:o,similarityThreshold:this.similarityThreshold}}}calculateSimilarity(e,t){let s=0,i=this.calculateContentSimilarity(e.content,t.content);s+=i*.4;let n=this.calculateTagSimilarity(e.tags||[],t.tags||[]);s+=n*.3*this.tagWeightMultiplier;let r=e.memory_type===t.memory_type?1:0;s+=r*.2*this.typeWeightMultiplier;let o=this.calculateTemporalSimilarity(new Date(e.timestamp),new Date(t.timestamp));return s+=o*.1,Math.min(s,1)}calculateContentSimilarity(e,t){let s=new Set(e.toLowerCase().split(/\s+/).filter(o=>o.length>2)),i=new Set(t.toLowerCase().split(/\s+/).filter(o=>o.length>2)),n=new Set([...s].filter(o=>i.has(o))),r=new Set([...s,...i]);return r.size>0?n.size/r.size:0}calculateTagSimilarity(e,t){let s=new Set(e),i=new Set(t),n=new Set([...s].filter(o=>i.has(o))),r=new Set([...s,...i]);return r.size>0?n.size/r.size:0}calculateTemporalSimilarity(e,t){let s=Math.abs(e-t)/36e5;return s>this.temporalWindowHours?0:1-s/this.temporalWindowHours}};u(ze,"MemoryRelationshipAnalyzer");var ne=ze,qe=class qe{constructor(e={}){var t,s,i,n,r;this.relationshipAnalyzer=new ne(e.relationship||{}),this.pageRankAnalyzer=new se((t=e.pagerank)==null?void 0:t.dampingFactor,(s=e.pagerank)==null?void 0:s.maxIterations,(i=e.pagerank)==null?void 0:i.tolerance),this.communityDetector=new ie((n=e.community)==null?void 0:n.maxIterations,(r=e.community)==null?void 0:r.randomSeed)}async analyzeMemories(e,t={}){let s=process.hrtime.bigint(),i=e.length,n=1e4;console.log(`\u{1F527} MCP SERVER DEBUG: Graph analysis analyzing ${i} memories - OPTIMIZATION ACTIVE!`);let r=e;if(i>n){console.log(`\u{1F4CA} Graph analysis optimization: ${i} \u2192 ${n} memories (avoiding ${Math.pow(i,2).toLocaleString()} graph operations)`);let p=Math.floor(n*.4),y=Math.floor(n*.3),f=n-p-y,_=e.slice(0,p),E=e.filter(S=>S.confidence_score>.8).slice(0,y),w=e.slice(p).sort(()=>.5-Math.random()).slice(0,f);r=[..._,...E,...w],console.log(`\u{1F680} Graph complexity reduced: O(${Math.pow(r.length,2).toLocaleString()}) vs O(${Math.pow(i,2).toLocaleString()}) operations`)}let{graph:o,buildStats:a}=this.relationshipAnalyzer.buildGraph(r),c=this.pageRankAnalyzer.calculatePageRank(o),l=this.communityDetector.detectCommunities(o),h=o.getStats(),d=process.hrtime.bigint(),m=Number(d-s)/1e6;return{graph:{nodes:o.getAllNodes(),stats:h,buildStats:a},pagerank:c,communities:l,analysis:{totalDuration:m,memoryCount:e.length,relationshipCount:h.edges,communityCount:l.stats.communityCount,topMemoriesByImportance:c.rankings.slice(0,10),largestCommunities:l.communities.slice(0,5)}}}};u(qe,"GraphAnalysisEngine");var Le=qe;Ji.exports={MemoryGraph:te,PageRankAnalyzer:se,CommunityDetector:ie,MemoryRelationshipAnalyzer:ne,GraphAnalysisEngine:Le}});var z=g((Nl,Ki)=>{var Ue=class Ue{constructor(){this.stopWords=new Set(["the","a","an","and","or","but","in","on","at","to","for","of","with","by","from","up","about","into","through","during","before","after","above","below","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","could","should","may","might","must","can","shall","this","that","these","those","i","me","my","myself","we","our","ours","ourselves","you","your","yours","yourself","yourselves","he","him","his","himself","she","her","hers","herself","it","its","itself","they","them","their","theirs","themselves"])}tokenize(e){return!e||typeof e!="string"?[]:e.toLowerCase().replace(/[^\w\s]/g," ").split(/\s+/).filter(t=>t.length>2&&!this.stopWords.has(t)).filter(Boolean)}calculateTermFrequency(e){let t={},s=e.length;for(let i of e)t[i]=(t[i]||0)+1;for(let i in t)t[i]=t[i]/s;return t}getAllTerms(e){let t=new Set;for(let s of e){let i=this.tokenize(s.content);for(let n of i)t.add(n)}return Array.from(t)}};u(Ue,"TextProcessor");var I=Ue,Be=class Be{constructor(){this.textProcessor=new I,this.idfCache=new Map}calculateIDF(e,t){let s=`${e}_${t.length}`;if(this.idfCache.has(s))return this.idfCache.get(s);let i=t.filter(r=>this.textProcessor.tokenize(r.content).includes(e)).length;if(i===0)return this.idfCache.set(s,0),0;let n=Math.log((t.length+1)/(i+1));return this.idfCache.set(s,n),n}calculateTFIDF(e,t,s){let i=this.textProcessor.tokenize(e),n=this.textProcessor.tokenize(t.content),r=this.textProcessor.calculateTermFrequency(n),o=0,a=0;for(let c of i){let l=r[c]||0;if(l>0){a++;let h=this.calculateIDF(c,s),d=h>0?l*h:l*.1;o+=d}}return a>0?o/Math.sqrt(i.length):0}rank(e,t){let s=process.hrtime.bigint();if(!e||e.trim()==="")return{results:[],algorithm:"precise",duration:0,totalDocuments:t.length,rankedDocuments:0};let i=t,n=!1;if(t.length>1e3){let h=Math.min(500,Math.floor(t.length*.1)),d=[],m=Math.floor(t.length/h);for(let y=0;y<t.length;y+=m)d.push(t[y]);let p=this.textProcessor.tokenize(e);for(let y of p)this.calculateIDF(y,d);n=!0,console.log(`\u26A1 TF-IDF: Using sampling strategy (${h} samples from ${t.length} docs)`)}let r=[],o=this.textProcessor.tokenize(e);for(let h=0;h<t.length;h++){let d=t[h],m=d.content.toLowerCase();if(!o.some(f=>m.includes(f)))continue;let y=this.calculateTFIDF(e,d,n?[]:t);if(y>0&&r.push({...d,tfidf_score:y}),r.length>100&&h>t.length*.3){console.log(`\u26A1 TF-IDF: Early termination at ${h}/${t.length} docs`);break}}let a=r.sort((h,d)=>d.tfidf_score-h.tfidf_score),c=process.hrtime.bigint(),l=Number(c-s)/1e6;return{results:a,algorithm:"precise",duration:l,totalDocuments:t.length,rankedDocuments:a.length,sampled:n}}};u(Be,"TFIDFRanker");var V=Be,We=class We{constructor(e=1.2,t=.75){this.k1=e,this.b=t,this.textProcessor=new I,this.avgDocLength=0,this.documentLengths=new Map,this.termDocumentFrequency=new Map}preprocessDocuments(e,t=null){let s=t&&e.length>1e3?e.filter(n=>{let r=n.content.toLowerCase();return t.some(o=>r.includes(o))}):e;s.length<e.length&&console.log(`\u26A1 BM25: Processing ${s.length}/${e.length} relevant docs`),this.documentLengths.clear(),this.termDocumentFrequency.clear();let i=0;for(let n of s){let r=this.textProcessor.tokenize(n.content),o=r.length;this.documentLengths.set(n.id,o),i+=o;let a=t&&e.length>1e3?r.filter(l=>t.includes(l)):r,c=new Set(a);for(let l of c)this.termDocumentFrequency.set(l,(this.termDocumentFrequency.get(l)||0)+1)}this.avgDocLength=i/Math.max(s.length,1),this.totalDocCount=e.length}calculateBM25(e,t,s){let i=this.textProcessor.tokenize(e),n=this.textProcessor.tokenize(t.content),r=this.documentLengths.get(t.id)||n.length,o={};for(let c of n)o[c]=(o[c]||0)+1;let a=0;for(let c of i){let l=o[c]||0;if(l===0)continue;let h=this.termDocumentFrequency.get(c)||0;if(h===0)conti