claude-flow 2.7.42 → 2.7.44

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/memory/swarm-memory.js"],"sourcesContent":["/**\n * SwarmMemory - MCP-specific memory persistence extending SharedMemory\n * Provides swarm-specific features like agent coordination, task tracking, and neural patterns\n *\n * @module swarm-memory\n */\n\nimport { SharedMemory } from './shared-memory.js';\nimport path from 'path';\n\n/**\n * Swarm-specific namespaces\n */\nconst SWARM_NAMESPACES = {\n AGENTS: 'swarm:agents',\n TASKS: 'swarm:tasks',\n COMMUNICATIONS: 'swarm:communications',\n CONSENSUS: 'swarm:consensus',\n PATTERNS: 'swarm:patterns',\n METRICS: 'swarm:metrics',\n COORDINATION: 'swarm:coordination',\n};\n\n/**\n * SwarmMemory class - Extends SharedMemory with MCP features\n */\nexport class SwarmMemory extends SharedMemory {\n constructor(options = {}) {\n // Default to .swarm directory for MCP\n super({\n directory: options.directory || '.swarm',\n filename: options.filename || 'swarm-memory.db',\n ...options,\n });\n\n this.swarmId = options.swarmId || 'default';\n this.mcpMode = options.mcpMode !== false;\n\n // Additional swarm-specific caches\n this.agentCache = new Map();\n this.taskCache = new Map();\n this.patternCache = new Map();\n }\n\n /**\n * Initialize with swarm-specific setup\n */\n async initialize() {\n await super.initialize();\n\n // Initialize swarm-specific namespaces\n await this._initializeSwarmNamespaces();\n\n // Load active agents and tasks into cache\n await this._loadSwarmState();\n\n this.emit('swarm:initialized', { swarmId: this.swarmId });\n }\n\n /**\n * Store agent information\n */\n async storeAgent(agentId, agentData) {\n const key = `agent:${agentId}`;\n const enrichedData = {\n ...agentData,\n swarmId: this.swarmId,\n lastUpdated: new Date().toISOString(),\n };\n\n await this.store(key, enrichedData, {\n namespace: SWARM_NAMESPACES.AGENTS,\n tags: ['agent', agentData.type, agentData.status],\n metadata: {\n swarmId: this.swarmId,\n agentType: agentData.type,\n },\n });\n\n // Update agent cache\n this.agentCache.set(agentId, enrichedData);\n\n this.emit('swarm:agentStored', { agentId, type: agentData.type });\n\n return { agentId, stored: true };\n }\n\n /**\n * Retrieve agent information\n */\n async getAgent(agentId) {\n // Check cache first\n if (this.agentCache.has(agentId)) {\n return this.agentCache.get(agentId);\n }\n\n const key = `agent:${agentId}`;\n const agent = await this.retrieve(key, SWARM_NAMESPACES.AGENTS);\n\n if (agent) {\n this.agentCache.set(agentId, agent);\n }\n\n return agent;\n }\n\n /**\n * List all agents in swarm\n */\n async listAgents(filter = {}) {\n const agents = await this.list(SWARM_NAMESPACES.AGENTS, {\n limit: filter.limit || 100,\n });\n\n return agents\n .map((entry) => entry.value)\n .filter((agent) => {\n if (filter.type && agent.type !== filter.type) return false;\n if (filter.status && agent.status !== filter.status) return false;\n if (filter.swarmId && agent.swarmId !== filter.swarmId) return false;\n return true;\n });\n }\n\n /**\n * Store task information\n */\n async storeTask(taskId, taskData) {\n const key = `task:${taskId}`;\n const enrichedData = {\n ...taskData,\n swarmId: this.swarmId,\n createdAt: taskData.createdAt || new Date().toISOString(),\n updatedAt: new Date().toISOString(),\n };\n\n await this.store(key, enrichedData, {\n namespace: SWARM_NAMESPACES.TASKS,\n tags: ['task', taskData.status, taskData.priority],\n metadata: {\n swarmId: this.swarmId,\n assignedAgents: taskData.assignedAgents || [],\n },\n });\n\n // Update task cache\n this.taskCache.set(taskId, enrichedData);\n\n this.emit('swarm:taskStored', { taskId, status: taskData.status });\n\n return { taskId, stored: true };\n }\n\n /**\n * Update task status\n */\n async updateTaskStatus(taskId, status, result = null) {\n const task = await this.getTask(taskId);\n if (!task) {\n throw new Error(`Task ${taskId} not found`);\n }\n\n task.status = status;\n task.updatedAt = new Date().toISOString();\n\n if (result) {\n task.result = result;\n }\n\n if (status === 'completed') {\n task.completedAt = new Date().toISOString();\n }\n\n await this.storeTask(taskId, task);\n\n this.emit('swarm:taskStatusUpdated', { taskId, status });\n\n return { taskId, status, updated: true };\n }\n\n /**\n * Get task information\n */\n async getTask(taskId) {\n // Check cache first\n if (this.taskCache.has(taskId)) {\n return this.taskCache.get(taskId);\n }\n\n const key = `task:${taskId}`;\n const task = await this.retrieve(key, SWARM_NAMESPACES.TASKS);\n\n if (task) {\n this.taskCache.set(taskId, task);\n }\n\n return task;\n }\n\n /**\n * Store inter-agent communication\n */\n async storeCommunication(fromAgent, toAgent, message) {\n const commId = `comm:${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;\n const communication = {\n id: commId,\n fromAgent,\n toAgent,\n message,\n swarmId: this.swarmId,\n timestamp: new Date().toISOString(),\n };\n\n await this.store(commId, communication, {\n namespace: SWARM_NAMESPACES.COMMUNICATIONS,\n ttl: 86400, // 24 hours\n tags: ['communication', message.type],\n metadata: {\n fromAgent,\n toAgent,\n messageType: message.type,\n },\n });\n\n this.emit('swarm:communication', { fromAgent, toAgent, type: message.type });\n\n return { id: commId, stored: true };\n }\n\n /**\n * Store consensus decision\n */\n async storeConsensus(consensusId, decision) {\n const key = `consensus:${consensusId}`;\n const consensusData = {\n ...decision,\n swarmId: this.swarmId,\n timestamp: new Date().toISOString(),\n };\n\n await this.store(key, consensusData, {\n namespace: SWARM_NAMESPACES.CONSENSUS,\n tags: ['consensus', decision.status],\n metadata: {\n swarmId: this.swarmId,\n taskId: decision.taskId,\n threshold: decision.threshold,\n },\n });\n\n this.emit('swarm:consensus', { consensusId, status: decision.status });\n\n return { consensusId, stored: true };\n }\n\n /**\n * Store neural pattern\n */\n async storePattern(patternId, pattern) {\n const key = `pattern:${patternId}`;\n const patternData = {\n ...pattern,\n swarmId: this.swarmId,\n createdAt: new Date().toISOString(),\n usageCount: 0,\n successRate: 0,\n };\n\n await this.store(key, patternData, {\n namespace: SWARM_NAMESPACES.PATTERNS,\n tags: ['pattern', pattern.type],\n metadata: {\n swarmId: this.swarmId,\n patternType: pattern.type,\n confidence: pattern.confidence || 0,\n },\n });\n\n // Cache frequently used patterns\n if (pattern.type === 'coordination' || pattern.type === 'optimization') {\n this.patternCache.set(patternId, patternData);\n }\n\n this.emit('swarm:patternStored', { patternId, type: pattern.type });\n\n return { patternId, stored: true };\n }\n\n /**\n * Update pattern usage and success metrics\n */\n async updatePatternMetrics(patternId, success = true) {\n const pattern = await this.getPattern(patternId);\n if (!pattern) {\n throw new Error(`Pattern ${patternId} not found`);\n }\n\n pattern.usageCount++;\n pattern.lastUsedAt = new Date().toISOString();\n\n // Update success rate with exponential moving average\n const alpha = 0.1; // Smoothing factor\n const currentSuccess = success ? 1 : 0;\n pattern.successRate = alpha * currentSuccess + (1 - alpha) * (pattern.successRate || 0);\n\n await this.storePattern(patternId, pattern);\n\n return { patternId, usageCount: pattern.usageCount, successRate: pattern.successRate };\n }\n\n /**\n * Get pattern\n */\n async getPattern(patternId) {\n // Check cache first\n if (this.patternCache.has(patternId)) {\n return this.patternCache.get(patternId);\n }\n\n const key = `pattern:${patternId}`;\n return await this.retrieve(key, SWARM_NAMESPACES.PATTERNS);\n }\n\n /**\n * Find best patterns for a given context\n */\n async findBestPatterns(context, limit = 5) {\n const patterns = await this.search({\n namespace: SWARM_NAMESPACES.PATTERNS,\n tags: context.tags,\n limit: 100,\n });\n\n // Score patterns based on success rate and relevance\n const scored = patterns.map((entry) => {\n const pattern = entry.value;\n const score =\n pattern.successRate * 0.7 +\n (pattern.confidence || 0) * 0.2 +\n (pattern.usageCount > 0 ? 0.1 : 0);\n\n return { ...pattern, score };\n });\n\n // Sort by score and return top patterns\n return scored.sort((a, b) => b.score - a.score).slice(0, limit);\n }\n\n /**\n * Store coordination state\n */\n async storeCoordination(key, state) {\n await this.store(key, state, {\n namespace: SWARM_NAMESPACES.COORDINATION,\n ttl: 3600, // 1 hour\n metadata: {\n swarmId: this.swarmId,\n timestamp: new Date().toISOString(),\n },\n });\n\n return { key, stored: true };\n }\n\n /**\n * Get coordination state\n */\n async getCoordination(key) {\n return await this.retrieve(key, SWARM_NAMESPACES.COORDINATION);\n }\n\n /**\n * Store performance metrics\n */\n async storeMetrics(metricsId, metrics) {\n const key = `metrics:${metricsId}`;\n await this.store(key, metrics, {\n namespace: SWARM_NAMESPACES.METRICS,\n ttl: 86400 * 7, // 7 days\n tags: ['metrics', metrics.type],\n metadata: {\n swarmId: this.swarmId,\n agentId: metrics.agentId,\n timestamp: new Date().toISOString(),\n },\n });\n\n this.emit('swarm:metricsStored', { metricsId, type: metrics.type });\n\n return { metricsId, stored: true };\n }\n\n /**\n * Get swarm statistics\n */\n async getSwarmStats() {\n const baseStats = await this.getStats();\n\n // Add swarm-specific stats\n const agentCount = await this._countNamespace(SWARM_NAMESPACES.AGENTS);\n const taskCount = await this._countNamespace(SWARM_NAMESPACES.TASKS);\n const patternCount = await this._countNamespace(SWARM_NAMESPACES.PATTERNS);\n\n // Get active agents\n const activeAgents = Array.from(this.agentCache.values()).filter(\n (agent) => agent.status === 'active' || agent.status === 'busy',\n ).length;\n\n // Get task statistics\n const tasks = Array.from(this.taskCache.values());\n const taskStats = {\n total: tasks.length,\n pending: tasks.filter((t) => t.status === 'pending').length,\n inProgress: tasks.filter((t) => t.status === 'in_progress').length,\n completed: tasks.filter((t) => t.status === 'completed').length,\n failed: tasks.filter((t) => t.status === 'failed').length,\n };\n\n return {\n ...baseStats,\n swarm: {\n swarmId: this.swarmId,\n agents: {\n total: agentCount,\n active: activeAgents,\n cached: this.agentCache.size,\n },\n tasks: taskStats,\n patterns: {\n total: patternCount,\n cached: this.patternCache.size,\n },\n namespaces: Object.values(SWARM_NAMESPACES),\n },\n };\n }\n\n /**\n * Clean up old swarm data\n */\n async cleanupSwarmData(options = {}) {\n const {\n maxAge = 86400 * 7, // 7 days\n keepPatterns = true,\n keepConsensus = true,\n } = options;\n\n const cutoffTime = Date.now() - maxAge * 1000;\n let cleaned = 0;\n\n // Clean old communications\n const comms = await this.list(SWARM_NAMESPACES.COMMUNICATIONS);\n for (const comm of comms) {\n if (new Date(comm.value.timestamp).getTime() < cutoffTime) {\n await this.delete(comm.key, SWARM_NAMESPACES.COMMUNICATIONS);\n cleaned++;\n }\n }\n\n // Clean completed tasks\n const tasks = await this.list(SWARM_NAMESPACES.TASKS);\n for (const task of tasks) {\n if (\n task.value.status === 'completed' &&\n new Date(task.value.completedAt).getTime() < cutoffTime\n ) {\n await this.delete(task.key, SWARM_NAMESPACES.TASKS);\n this.taskCache.delete(task.value.id);\n cleaned++;\n }\n }\n\n // Clean old metrics\n const metrics = await this.list(SWARM_NAMESPACES.METRICS);\n for (const metric of metrics) {\n if (new Date(metric.createdAt).getTime() < cutoffTime) {\n await this.delete(metric.key, SWARM_NAMESPACES.METRICS);\n cleaned++;\n }\n }\n\n this.emit('swarm:cleanup', { cleaned, maxAge });\n\n return { cleaned };\n }\n\n /**\n * Export swarm state\n */\n async exportSwarmState() {\n const agents = await this.listAgents();\n const tasks = Array.from(this.taskCache.values());\n const patterns = await this.list(SWARM_NAMESPACES.PATTERNS);\n\n return {\n swarmId: this.swarmId,\n exportedAt: new Date().toISOString(),\n agents: agents,\n tasks: tasks,\n patterns: patterns.map((p) => p.value),\n statistics: await this.getSwarmStats(),\n };\n }\n\n /**\n * Import swarm state\n */\n async importSwarmState(state) {\n let imported = {\n agents: 0,\n tasks: 0,\n patterns: 0,\n };\n\n // Import agents\n if (state.agents) {\n for (const agent of state.agents) {\n await this.storeAgent(agent.id, agent);\n imported.agents++;\n }\n }\n\n // Import tasks\n if (state.tasks) {\n for (const task of state.tasks) {\n await this.storeTask(task.id, task);\n imported.tasks++;\n }\n }\n\n // Import patterns\n if (state.patterns) {\n for (const pattern of state.patterns) {\n await this.storePattern(pattern.id, pattern);\n imported.patterns++;\n }\n }\n\n this.emit('swarm:imported', imported);\n\n return imported;\n }\n\n /**\n * Private helper methods\n */\n\n async _initializeSwarmNamespaces() {\n // Create swarm metadata\n await this.store(\n 'swarm:metadata',\n {\n swarmId: this.swarmId,\n createdAt: new Date().toISOString(),\n version: '1.0.0',\n namespaces: Object.values(SWARM_NAMESPACES),\n },\n {\n namespace: 'swarm:system',\n },\n );\n }\n\n async _loadSwarmState() {\n // Load active agents\n const agents = await this.list(SWARM_NAMESPACES.AGENTS, { limit: 100 });\n for (const entry of agents) {\n if (entry.value.status === 'active' || entry.value.status === 'busy') {\n this.agentCache.set(entry.value.id, entry.value);\n }\n }\n\n // Load in-progress tasks\n const tasks = await this.search({\n namespace: SWARM_NAMESPACES.TASKS,\n tags: ['in_progress'],\n limit: 100,\n });\n for (const entry of tasks) {\n this.taskCache.set(entry.value.id, entry.value);\n }\n\n // Load high-confidence patterns\n const patterns = await this.list(SWARM_NAMESPACES.PATTERNS, { limit: 50 });\n for (const entry of patterns) {\n if (entry.value.confidence > 0.7 || entry.value.successRate > 0.8) {\n this.patternCache.set(entry.value.id, entry.value);\n }\n }\n }\n\n async _countNamespace(namespace) {\n const stats = await this.getStats();\n return stats.namespaces[namespace]?.count || 0;\n }\n}\n\n// Export factory function for easy creation\nexport function createSwarmMemory(options = {}) {\n return new SwarmMemory(options);\n}\n\n// Export for backwards compatibility\nexport default SwarmMemory;\n"],"names":["SharedMemory","SWARM_NAMESPACES","AGENTS","TASKS","COMMUNICATIONS","CONSENSUS","PATTERNS","METRICS","COORDINATION","SwarmMemory","options","directory","filename","swarmId","mcpMode","agentCache","Map","taskCache","patternCache","initialize","_initializeSwarmNamespaces","_loadSwarmState","emit","storeAgent","agentId","agentData","key","enrichedData","lastUpdated","Date","toISOString","store","namespace","tags","type","status","metadata","agentType","set","stored","getAgent","has","get","agent","retrieve","listAgents","filter","agents","list","limit","map","entry","value","storeTask","taskId","taskData","createdAt","updatedAt","priority","assignedAgents","updateTaskStatus","result","task","getTask","Error","completedAt","updated","storeCommunication","fromAgent","toAgent","message","commId","now","Math","random","toString","substr","communication","id","timestamp","ttl","messageType","storeConsensus","consensusId","decision","consensusData","threshold","storePattern","patternId","pattern","patternData","usageCount","successRate","patternType","confidence","updatePatternMetrics","success","getPattern","lastUsedAt","alpha","currentSuccess","findBestPatterns","context","patterns","search","scored","score","sort","a","b","slice","storeCoordination","state","getCoordination","storeMetrics","metricsId","metrics","getSwarmStats","baseStats","getStats","agentCount","_countNamespace","taskCount","patternCount","activeAgents","Array","from","values","length","tasks","taskStats","total","pending","t","inProgress","completed","failed","swarm","active","cached","size","namespaces","Object","cleanupSwarmData","maxAge","keepPatterns","keepConsensus","cutoffTime","cleaned","comms","comm","getTime","delete","metric","exportSwarmState","exportedAt","p","statistics","importSwarmState","imported","version","stats","count","createSwarmMemory"],"mappings":"AAOA,SAASA,YAAY,QAAQ,qBAAqB;AAMlD,MAAMC,mBAAmB;IACvBC,QAAQ;IACRC,OAAO;IACPC,gBAAgB;IAChBC,WAAW;IACXC,UAAU;IACVC,SAAS;IACTC,cAAc;AAChB;AAKA,OAAO,MAAMC,oBAAoBT;IAC/B,YAAYU,UAAU,CAAC,CAAC,CAAE;QAExB,KAAK,CAAC;YACJC,WAAWD,QAAQC,SAAS,IAAI;YAChCC,UAAUF,QAAQE,QAAQ,IAAI;YAC9B,GAAGF,OAAO;QACZ;QAEA,IAAI,CAACG,OAAO,GAAGH,QAAQG,OAAO,IAAI;QAClC,IAAI,CAACC,OAAO,GAAGJ,QAAQI,OAAO,KAAK;QAGnC,IAAI,CAACC,UAAU,GAAG,IAAIC;QACtB,IAAI,CAACC,SAAS,GAAG,IAAID;QACrB,IAAI,CAACE,YAAY,GAAG,IAAIF;IAC1B;IAKA,MAAMG,aAAa;QACjB,MAAM,KAAK,CAACA;QAGZ,MAAM,IAAI,CAACC,0BAA0B;QAGrC,MAAM,IAAI,CAACC,eAAe;QAE1B,IAAI,CAACC,IAAI,CAAC,qBAAqB;YAAET,SAAS,IAAI,CAACA,OAAO;QAAC;IACzD;IAKA,MAAMU,WAAWC,OAAO,EAAEC,SAAS,EAAE;QACnC,MAAMC,MAAM,CAAC,MAAM,EAAEF,SAAS;QAC9B,MAAMG,eAAe;YACnB,GAAGF,SAAS;YACZZ,SAAS,IAAI,CAACA,OAAO;YACrBe,aAAa,IAAIC,OAAOC,WAAW;QACrC;QAEA,MAAM,IAAI,CAAC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,MAAMpB,UAAU,CAAC7G,UAAU,EAAEkI,SAAS;IAC/C;AACF;AAGA,OAAO,SAASC,kBAAkBzJ,UAAU,CAAC,CAAC;IAC5C,OAAO,IAAID,YAAYC;AACzB;AAGA,eAAeD,YAAY"}
1
+ {"version":3,"sources":["../../../src/memory/swarm-memory.ts"],"sourcesContent":["import { EventEmitter } from 'node:events';\nimport { Logger } from '../core/logger.js';\nimport { MemoryManager } from './manager.js';\nimport { EventBus } from '../core/event-bus.js';\nimport { generateId } from '../utils/helpers.js';\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\n\nexport interface SwarmMemoryEntry {\n id: string;\n agentId: string;\n type: 'knowledge' | 'result' | 'state' | 'communication' | 'error';\n content: any;\n timestamp: Date;\n metadata: {\n taskId?: string;\n objectiveId?: string;\n tags?: string[];\n priority?: number;\n shareLevel?: 'private' | 'team' | 'public';\n };\n}\n\nexport interface SwarmMemoryQuery {\n agentId?: string;\n type?: SwarmMemoryEntry['type'];\n taskId?: string;\n objectiveId?: string;\n tags?: string[];\n since?: Date;\n before?: Date;\n limit?: number;\n shareLevel?: SwarmMemoryEntry['metadata']['shareLevel'];\n}\n\nexport interface SwarmKnowledgeBase {\n id: string;\n name: string;\n description: string;\n entries: SwarmMemoryEntry[];\n metadata: {\n domain: string;\n expertise: string[];\n contributors: string[];\n lastUpdated: Date;\n };\n}\n\nexport interface SwarmMemoryConfig {\n namespace: string;\n enableDistribution: boolean;\n enableReplication: boolean;\n syncInterval: number;\n maxEntries: number;\n compressionThreshold: number;\n enableKnowledgeBase: boolean;\n enableCrossAgentSharing: boolean;\n persistencePath: string;\n}\n\nexport class SwarmMemoryManager extends EventEmitter {\n private logger: Logger;\n private config: SwarmMemoryConfig;\n private baseMemory: MemoryManager;\n private entries: Map<string, SwarmMemoryEntry>;\n private knowledgeBases: Map<string, SwarmKnowledgeBase>;\n private agentMemories: Map<string, Set<string>>; // agentId -> set of entry IDs\n private syncTimer?: NodeJS.Timeout;\n private isInitialized: boolean = false;\n\n constructor(config: Partial<SwarmMemoryConfig> = {}) {\n super();\n this.logger = new Logger('SwarmMemoryManager');\n this.config = {\n namespace: 'swarm',\n enableDistribution: true,\n enableReplication: true,\n syncInterval: 10000, // 10 seconds\n maxEntries: 10000,\n compressionThreshold: 1000,\n enableKnowledgeBase: true,\n enableCrossAgentSharing: true,\n persistencePath: './swarm-memory',\n ...config,\n };\n\n this.entries = new Map();\n this.knowledgeBases = new Map();\n this.agentMemories = new Map();\n\n const eventBus = EventBus.getInstance();\n this.baseMemory = new MemoryManager(\n {\n backend: 'sqlite',\n namespace: this.config.namespace,\n cacheSizeMB: 50,\n syncOnExit: true,\n maxEntries: this.config.maxEntries,\n ttlMinutes: 60,\n },\n eventBus,\n this.logger,\n );\n }\n\n async initialize(): Promise<void> {\n if (this.isInitialized) return;\n\n this.logger.info('Initializing swarm memory manager...');\n\n // Initialize base memory\n await this.baseMemory.initialize();\n\n // Create persistence directory\n await fs.mkdir(this.config.persistencePath, { recursive: true });\n\n // Load existing memory\n await this.loadMemoryState();\n\n // Start sync timer\n if (this.config.syncInterval > 0) {\n this.syncTimer = setInterval(() => {\n this.syncMemoryState();\n }, this.config.syncInterval);\n }\n\n this.isInitialized = true;\n this.emit('memory:initialized');\n }\n\n async shutdown(): Promise<void> {\n if (!this.isInitialized) return;\n\n this.logger.info('Shutting down swarm memory manager...');\n\n // Stop sync timer\n if (this.syncTimer) {\n clearInterval(this.syncTimer);\n this.syncTimer = undefined;\n }\n\n // Save final state\n await this.saveMemoryState();\n\n this.isInitialized = false;\n this.emit('memory:shutdown');\n }\n\n async remember(\n agentId: string,\n type: SwarmMemoryEntry['type'],\n content: any,\n metadata: Partial<SwarmMemoryEntry['metadata']> = {},\n ): Promise<string> {\n const entryId = generateId('mem');\n const entry: SwarmMemoryEntry = {\n id: entryId,\n agentId,\n type,\n content,\n timestamp: new Date(),\n metadata: {\n shareLevel: 'team',\n priority: 1,\n ...metadata,\n },\n };\n\n this.entries.set(entryId, entry);\n\n // Associate with agent\n if (!this.agentMemories.has(agentId)) {\n this.agentMemories.set(agentId, new Set());\n }\n this.agentMemories.get(agentId)!.add(entryId);\n\n // Store in base memory for persistence\n await this.baseMemory.remember({\n namespace: this.config.namespace,\n key: `entry:${entryId}`,\n content: JSON.stringify(entry),\n metadata: {\n type: 'swarm-memory',\n agentId,\n entryType: type,\n shareLevel: entry.metadata.shareLevel,\n },\n });\n\n this.logger.debug(`Agent ${agentId} remembered: ${type} - ${entryId}`);\n this.emit('memory:added', entry);\n\n // Update knowledge base if applicable\n if (type === 'knowledge' && this.config.enableKnowledgeBase) {\n await this.updateKnowledgeBase(entry);\n }\n\n // Check for memory limits\n await this.enforceMemoryLimits();\n\n return entryId;\n }\n\n async recall(query: SwarmMemoryQuery): Promise<SwarmMemoryEntry[]> {\n let results = Array.from(this.entries.values());\n\n // Apply filters\n if (query.agentId) {\n results = results.filter((e) => e.agentId === query.agentId);\n }\n\n if (query.type) {\n results = results.filter((e) => e.type === query.type);\n }\n\n if (query.taskId) {\n results = results.filter((e) => e.metadata.taskId === query.taskId);\n }\n\n if (query.objectiveId) {\n results = results.filter((e) => e.metadata.objectiveId === query.objectiveId);\n }\n\n if (query.tags && query.tags.length > 0) {\n results = results.filter(\n (e) => e.metadata.tags && query.tags!.some((tag) => e.metadata.tags!.includes(tag)),\n );\n }\n\n if (query.since) {\n results = results.filter((e) => e.timestamp >= query.since!);\n }\n\n if (query.before) {\n results = results.filter((e) => e.timestamp <= query.before!);\n }\n\n if (query.shareLevel) {\n results = results.filter((e) => e.metadata.shareLevel === query.shareLevel);\n }\n\n // Sort by timestamp (newest first)\n results.sort((a, b) => b.timestamp.getTime() - a.timestamp.getTime());\n\n // Apply limit\n if (query.limit) {\n results = results.slice(0, query.limit);\n }\n\n this.logger.debug(`Recalled ${results.length} memories for query`);\n return results;\n }\n\n async shareMemory(entryId: string, targetAgentId: string): Promise<void> {\n const entry = this.entries.get(entryId);\n if (!entry) {\n throw new Error('Memory entry not found');\n }\n\n if (!this.config.enableCrossAgentSharing) {\n throw new Error('Cross-agent sharing is disabled');\n }\n\n // Check share level permissions\n if (entry.metadata.shareLevel === 'private') {\n throw new Error('Memory entry is private and cannot be shared');\n }\n\n // Create a shared copy for the target agent\n const sharedEntry: SwarmMemoryEntry = {\n ...entry,\n id: generateId('mem'),\n metadata: {\n ...entry.metadata,\n originalId: entryId,\n sharedFrom: entry.agentId,\n sharedTo: targetAgentId,\n sharedAt: new Date(),\n },\n };\n\n this.entries.set(sharedEntry.id, sharedEntry);\n\n // Associate with target agent\n if (!this.agentMemories.has(targetAgentId)) {\n this.agentMemories.set(targetAgentId, new Set());\n }\n this.agentMemories.get(targetAgentId)!.add(sharedEntry.id);\n\n this.logger.info(`Shared memory ${entryId} from ${entry.agentId} to ${targetAgentId}`);\n this.emit('memory:shared', { original: entry, shared: sharedEntry });\n }\n\n async broadcastMemory(entryId: string, agentIds?: string[]): Promise<void> {\n const entry = this.entries.get(entryId);\n if (!entry) {\n throw new Error('Memory entry not found');\n }\n\n if (entry.metadata.shareLevel === 'private') {\n throw new Error('Cannot broadcast private memory');\n }\n\n const targets =\n agentIds || Array.from(this.agentMemories.keys()).filter((id) => id !== entry.agentId);\n\n for (const targetId of targets) {\n try {\n await this.shareMemory(entryId, targetId);\n } catch (error) {\n this.logger.warn(`Failed to share memory to ${targetId}:`, error);\n }\n }\n\n this.logger.info(`Broadcasted memory ${entryId} to ${targets.length} agents`);\n }\n\n async createKnowledgeBase(\n name: string,\n description: string,\n domain: string,\n expertise: string[],\n ): Promise<string> {\n const kbId = generateId('kb');\n const knowledgeBase: SwarmKnowledgeBase = {\n id: kbId,\n name,\n description,\n entries: [],\n metadata: {\n domain,\n expertise,\n contributors: [],\n lastUpdated: new Date(),\n },\n };\n\n this.knowledgeBases.set(kbId, knowledgeBase);\n\n this.logger.info(`Created knowledge base: ${name} (${kbId})`);\n this.emit('knowledgebase:created', knowledgeBase);\n\n return kbId;\n }\n\n async updateKnowledgeBase(entry: SwarmMemoryEntry): Promise<void> {\n if (!this.config.enableKnowledgeBase) return;\n\n // Find relevant knowledge bases\n const relevantKBs = Array.from(this.knowledgeBases.values()).filter((kb) => {\n // Simple matching based on tags and content\n const tags = entry.metadata.tags || [];\n return tags.some((tag) =>\n kb.metadata.expertise.some(\n (exp) =>\n exp.toLowerCase().includes(tag.toLowerCase()) ||\n tag.toLowerCase().includes(exp.toLowerCase()),\n ),\n );\n });\n\n for (const kb of relevantKBs) {\n // Add entry to knowledge base\n kb.entries.push(entry);\n kb.metadata.lastUpdated = new Date();\n\n // Add contributor\n if (!kb.metadata.contributors.includes(entry.agentId)) {\n kb.metadata.contributors.push(entry.agentId);\n }\n\n this.logger.debug(`Updated knowledge base ${kb.id} with entry ${entry.id}`);\n }\n }\n\n async searchKnowledge(\n query: string,\n domain?: string,\n expertise?: string[],\n ): Promise<SwarmMemoryEntry[]> {\n const allEntries: SwarmMemoryEntry[] = [];\n\n // Search in knowledge bases\n for (const kb of this.knowledgeBases.values()) {\n if (domain && kb.metadata.domain !== domain) continue;\n\n if (expertise && !expertise.some((exp) => kb.metadata.expertise.includes(exp))) {\n continue;\n }\n\n allEntries.push(...kb.entries);\n }\n\n // Simple text search (in real implementation, use better search)\n const queryLower = query.toLowerCase();\n const results = allEntries.filter((entry) => {\n const contentStr = JSON.stringify(entry.content).toLowerCase();\n return contentStr.includes(queryLower);\n });\n\n return results.slice(0, 50); // Limit results\n }\n\n async getAgentMemorySnapshot(agentId: string): Promise<{\n totalEntries: number;\n recentEntries: SwarmMemoryEntry[];\n knowledgeContributions: number;\n sharedEntries: number;\n }> {\n const agentEntryIds = this.agentMemories.get(agentId) || new Set();\n const agentEntries = Array.from(agentEntryIds)\n .map((id) => this.entries.get(id))\n .filter(Boolean) as SwarmMemoryEntry[];\n\n const recentEntries = agentEntries\n .sort((a, b) => b.timestamp.getTime() - a.timestamp.getTime())\n .slice(0, 10);\n\n const knowledgeContributions = agentEntries.filter((e) => e.type === 'knowledge').length;\n\n const sharedEntries = agentEntries.filter(\n (e) => e.metadata.shareLevel === 'public' || e.metadata.shareLevel === 'team',\n ).length;\n\n return {\n totalEntries: agentEntries.length,\n recentEntries,\n knowledgeContributions,\n sharedEntries,\n };\n }\n\n private async loadMemoryState(): Promise<void> {\n try {\n // Load entries\n const entriesFile = path.join(this.config.persistencePath, 'entries.json');\n try {\n const entriesData = await fs.readFile(entriesFile, 'utf-8');\n const entriesArray = JSON.parse(entriesData);\n\n for (const entry of entriesArray) {\n this.entries.set(entry.id, {\n ...entry,\n timestamp: new Date(entry.timestamp),\n });\n\n // Rebuild agent memory associations\n if (!this.agentMemories.has(entry.agentId)) {\n this.agentMemories.set(entry.agentId, new Set());\n }\n this.agentMemories.get(entry.agentId)!.add(entry.id);\n }\n\n this.logger.info(`Loaded ${entriesArray.length} memory entries`);\n } catch (error) {\n this.logger.warn('No existing memory entries found');\n }\n\n // Load knowledge bases\n const kbFile = path.join(this.config.persistencePath, 'knowledge-bases.json');\n try {\n const kbData = await fs.readFile(kbFile, 'utf-8');\n const kbArray = JSON.parse(kbData);\n\n for (const kb of kbArray) {\n this.knowledgeBases.set(kb.id, {\n ...kb,\n metadata: {\n ...kb.metadata,\n lastUpdated: new Date(kb.metadata.lastUpdated),\n },\n entries: kb.entries.map((e: any) => ({\n ...e,\n timestamp: new Date(e.timestamp),\n })),\n });\n }\n\n this.logger.info(`Loaded ${kbArray.length} knowledge bases`);\n } catch (error) {\n this.logger.warn('No existing knowledge bases found');\n }\n } catch (error) {\n this.logger.error('Error loading memory state:', error);\n }\n }\n\n private async saveMemoryState(): Promise<void> {\n try {\n // Save entries\n const entriesArray = Array.from(this.entries.values());\n const entriesFile = path.join(this.config.persistencePath, 'entries.json');\n await fs.writeFile(entriesFile, JSON.stringify(entriesArray, null, 2));\n\n // Save knowledge bases\n const kbArray = Array.from(this.knowledgeBases.values());\n const kbFile = path.join(this.config.persistencePath, 'knowledge-bases.json');\n await fs.writeFile(kbFile, JSON.stringify(kbArray, null, 2));\n\n this.logger.debug('Saved memory state to disk');\n } catch (error) {\n this.logger.error('Error saving memory state:', error);\n }\n }\n\n private async syncMemoryState(): Promise<void> {\n try {\n await this.saveMemoryState();\n this.emit('memory:synced');\n } catch (error) {\n this.logger.error('Error syncing memory state:', error);\n }\n }\n\n private async enforceMemoryLimits(): Promise<void> {\n if (this.entries.size <= this.config.maxEntries) return;\n\n this.logger.info('Enforcing memory limits...');\n\n // Remove oldest entries that are not marked as important\n const entries = Array.from(this.entries.values())\n .filter((e) => (e.metadata.priority || 1) <= 1) // Only remove low priority\n .sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime());\n\n const toRemove = entries.slice(0, this.entries.size - this.config.maxEntries);\n\n for (const entry of toRemove) {\n this.entries.delete(entry.id);\n\n // Remove from agent memory\n const agentEntries = this.agentMemories.get(entry.agentId);\n if (agentEntries) {\n agentEntries.delete(entry.id);\n }\n\n this.logger.debug(`Removed old memory entry: ${entry.id}`);\n }\n\n this.emit('memory:cleaned', toRemove.length);\n }\n\n // Public API methods\n getMemoryStats(): {\n totalEntries: number;\n entriesByType: Record<string, number>;\n entriesByAgent: Record<string, number>;\n knowledgeBases: number;\n memoryUsage: number;\n } {\n const entries = Array.from(this.entries.values());\n const entriesByType: Record<string, number> = {};\n const entriesByAgent: Record<string, number> = {};\n\n for (const entry of entries) {\n entriesByType[entry.type] = (entriesByType[entry.type] || 0) + 1;\n entriesByAgent[entry.agentId] = (entriesByAgent[entry.agentId] || 0) + 1;\n }\n\n // Rough memory usage calculation\n const memoryUsage = JSON.stringify(entries).length;\n\n return {\n totalEntries: entries.length,\n entriesByType,\n entriesByAgent,\n knowledgeBases: this.knowledgeBases.size,\n memoryUsage,\n };\n }\n\n async exportMemory(agentId?: string): Promise<any> {\n const entries = agentId ? await this.recall({ agentId }) : Array.from(this.entries.values());\n\n return {\n entries,\n knowledgeBases: agentId\n ? Array.from(this.knowledgeBases.values()).filter((kb) =>\n kb.metadata.contributors.includes(agentId),\n )\n : Array.from(this.knowledgeBases.values()),\n exportedAt: new Date(),\n stats: this.getMemoryStats(),\n };\n }\n\n async clearMemory(agentId?: string): Promise<void> {\n if (agentId) {\n // Clear specific agent's memory\n const entryIds = this.agentMemories.get(agentId) || new Set();\n for (const entryId of entryIds) {\n this.entries.delete(entryId);\n }\n this.agentMemories.delete(agentId);\n this.logger.info(`Cleared memory for agent ${agentId}`);\n } else {\n // Clear all memory\n this.entries.clear();\n this.agentMemories.clear();\n this.knowledgeBases.clear();\n this.logger.info('Cleared all swarm memory');\n }\n\n this.emit('memory:cleared', { agentId });\n }\n\n // Compatibility methods for hive.ts\n async store(key: string, value: any): Promise<void> {\n // Extract namespace and actual key from the path\n const parts = key.split('/');\n const type = (parts[0] as SwarmMemoryEntry['type']) || 'state';\n const agentId = parts[1] || 'system';\n\n await this.remember(agentId, type, value, {\n tags: [parts[0], parts[1]].filter(Boolean),\n shareLevel: 'team',\n });\n }\n\n async search(pattern: string, limit: number = 10): Promise<any[]> {\n // Simple pattern matching on stored keys/content\n const results: any[] = [];\n\n for (const entry of this.entries.values()) {\n const entryString = JSON.stringify(entry);\n if (entryString.includes(pattern.replace('*', ''))) {\n results.push(entry.content);\n if (results.length >= limit) break;\n }\n }\n\n return results;\n }\n}\n"],"names":["EventEmitter","Logger","MemoryManager","EventBus","generateId","fs","path","SwarmMemoryManager","logger","config","baseMemory","entries","knowledgeBases","agentMemories","syncTimer","isInitialized","namespace","enableDistribution","enableReplication","syncInterval","maxEntries","compressionThreshold","enableKnowledgeBase","enableCrossAgentSharing","persistencePath","Map","eventBus","getInstance","backend","cacheSizeMB","syncOnExit","ttlMinutes","initialize","info","mkdir","recursive","loadMemoryState","setInterval","syncMemoryState","emit","shutdown","clearInterval","undefined","saveMemoryState","remember","agentId","type","content","metadata","entryId","entry","id","timestamp","Date","shareLevel","priority","set","has","Set","get","add","key","JSON","stringify","entryType","debug","updateKnowledgeBase","enforceMemoryLimits","recall","query","results","Array","from","values","filter","e","taskId","objectiveId","tags","length","some","tag","includes","since","before","sort","a","b","getTime","limit","slice","shareMemory","targetAgentId","Error","sharedEntry","originalId","sharedFrom","sharedTo","sharedAt","original","shared","broadcastMemory","agentIds","targets","keys","targetId","error","warn","createKnowledgeBase","name","description","domain","expertise","kbId","knowledgeBase","contributors","lastUpdated","relevantKBs","kb","exp","toLowerCase","push","searchKnowledge","allEntries","queryLower","contentStr","getAgentMemorySnapshot","agentEntryIds","agentEntries","map","Boolean","recentEntries","knowledgeContributions","sharedEntries","totalEntries","entriesFile","join","entriesData","readFile","entriesArray","parse","kbFile","kbData","kbArray","writeFile","size","toRemove","delete","getMemoryStats","entriesByType","entriesByAgent","memoryUsage","exportMemory","exportedAt","stats","clearMemory","entryIds","clear","store","value","parts","split","search","pattern","entryString","replace"],"mappings":"AAAA,SAASA,YAAY,QAAQ,cAAc;AAC3C,SAASC,MAAM,QAAQ,oBAAoB;AAC3C,SAASC,aAAa,QAAQ,eAAe;AAC7C,SAASC,QAAQ,QAAQ,uBAAuB;AAChD,SAASC,UAAU,QAAQ,sBAAsB;AACjD,YAAYC,QAAQ,mBAAmB;AACvC,YAAYC,UAAU,YAAY;AAsDlC,OAAO,MAAMC,2BAA2BP;IAC9BQ,OAAe;IACfC,OAA0B;IAC1BC,WAA0B;IAC1BC,QAAuC;IACvCC,eAAgD;IAChDC,cAAwC;IACxCC,UAA2B;IAC3BC,gBAAyB,MAAM;IAEvC,YAAYN,SAAqC,CAAC,CAAC,CAAE;QACnD,KAAK;QACL,IAAI,CAACD,MAAM,GAAG,IAAIP,OAAO;QACzB,IAAI,CAACQ,MAAM,GAAG;YACZO,WAAW;YACXC,oBAAoB;YACpBC,mBAAmB;YACnBC,cAAc;YACdC,YAAY;YACZC,sBAAsB;YACtBC,qBAAqB;YACrBC,yBAAyB;YACzBC,iBAAiB;YACjB,GAAGf,MAAM;QACX;QAEA,IAAI,CAACE,OAAO,GAAG,IAAIc;QACnB,IAAI,CAACb,cAAc,GAAG,IAAIa;QAC1B,IAAI,CAACZ,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AAEkG,KAAU,EAAiB;QAElD,MAAMC,QAAQnG,IAAIoG,KAAK,CAAC;QACxB,MAAMnH,OAAO,AAACkH,KAAK,CAAC,EAAE,IAAiC;QACvD,MAAMnH,UAAUmH,KAAK,CAAC,EAAE,IAAI;QAE5B,MAAM,IAAI,CAACpH,QAAQ,CAACC,SAASC,MAAMiH,OAAO;YACxCjF,MAAM;gBAACkF,KAAK,CAAC,EAAE;gBAAEA,KAAK,CAAC,EAAE;aAAC,CAACtF,MAAM,CAACwD;YAClC5E,YAAY;QACd;IACF;IAEA,MAAM4G,OAAOC,OAAe,EAAE1E,QAAgB,EAAE,EAAkB;QAEhE,MAAMnB,UAAiB,EAAE;QAEzB,KAAK,MAAMpB,SAAS,IAAI,CAACvC,OAAO,CAAC8D,MAAM,GAAI;YACzC,MAAM2F,cAActG,KAAKC,SAAS,CAACb;YACnC,IAAIkH,YAAYlF,QAAQ,CAACiF,QAAQE,OAAO,CAAC,KAAK,MAAM;gBAClD/F,QAAQmD,IAAI,CAACvE,MAAMH,OAAO;gBAC1B,IAAIuB,QAAQS,MAAM,IAAIU,OAAO;YAC/B;QACF;QAEA,OAAOnB;IACT;AACF"}
@@ -6,6 +6,33 @@ export function isNpmCacheError(error) {
6
6
  const errorStr = error?.message || String(error);
7
7
  return errorStr.includes('ENOTEMPTY') && (errorStr.includes('npm') || errorStr.includes('npx') || errorStr.includes('_npx')) || errorStr.includes('better-sqlite3');
8
8
  }
9
+ export function isNativeModuleVersionError(error) {
10
+ const errorStr = error?.message || String(error);
11
+ return errorStr.includes('NODE_MODULE_VERSION') || errorStr.includes('was compiled against a different Node.js version') || errorStr.includes('re-compiling or re-installing the module');
12
+ }
13
+ export function getNativeModuleRecoveryMessage(error) {
14
+ const errorStr = error?.message || String(error);
15
+ const compiledMatch = errorStr.match(/NODE_MODULE_VERSION (\d+)/);
16
+ const requiredMatch = errorStr.match(/requires\s+NODE_MODULE_VERSION (\d+)/);
17
+ let message = '⚠️ Native module version mismatch detected.\n';
18
+ if (compiledMatch && requiredMatch) {
19
+ const nodeVersionMap = {
20
+ '108': '18.x',
21
+ '115': '20.x',
22
+ '120': '21.x',
23
+ '127': '22.x',
24
+ '131': '23.x'
25
+ };
26
+ const compiled = nodeVersionMap[compiledMatch[1]] || `ABI ${compiledMatch[1]}`;
27
+ const required = nodeVersionMap[requiredMatch[1]] || `ABI ${requiredMatch[1]}`;
28
+ message += ` Module was compiled for Node.js ${compiled}, but running Node.js ${required}.\n`;
29
+ }
30
+ message += '\n To fix this, try one of:\n';
31
+ message += ' 1. npm rebuild better-sqlite3\n';
32
+ message += ' 2. rm -rf node_modules && npm install\n';
33
+ message += ' 3. npx cache: rm -rf ~/.npm/_npx/ && run command again\n';
34
+ return message;
35
+ }
9
36
  export function isWSL() {
10
37
  if (process.platform !== 'linux') {
11
38
  return false;
@@ -203,6 +230,8 @@ export async function recoverInitErrors(error) {
203
230
  }
204
231
  export const errorRecovery = {
205
232
  isNpmCacheError,
233
+ isNativeModuleVersionError,
234
+ getNativeModuleRecoveryMessage,
206
235
  isWSL,
207
236
  cleanNpmCache,
208
237
  retryWithRecovery,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/utils/error-recovery.ts"],"sourcesContent":["/**\n * Error Recovery Utilities\n * Automatic error detection and recovery for common installation issues\n */\n\nimport { execSync } from 'child_process';\nimport * as fs from 'fs-extra';\nimport * as path from 'path';\nimport * as os from 'os';\n\nexport interface RecoveryResult {\n success: boolean;\n action: string;\n message: string;\n recovered: boolean;\n}\n\nexport interface RetryOptions {\n maxRetries?: number;\n delay?: number;\n onRetry?: (attempt: number, error: Error) => void;\n cleanupFn?: () => Promise<void>;\n}\n\n/**\n * Detect if an error is the ENOTEMPTY npm cache error\n */\nexport function isNpmCacheError(error: any): boolean {\n const errorStr = error?.message || String(error);\n return (\n errorStr.includes('ENOTEMPTY') &&\n (errorStr.includes('npm') || errorStr.includes('npx') || errorStr.includes('_npx'))\n ) || errorStr.includes('better-sqlite3');\n}\n\n/**\n * Detect if running on WSL (Windows Subsystem for Linux)\n */\nexport function isWSL(): boolean {\n if (process.platform !== 'linux') {\n return false;\n }\n\n try {\n const release = fs.readFileSync('/proc/version', 'utf8').toLowerCase();\n return release.includes('microsoft') || release.includes('wsl');\n } catch {\n return false;\n }\n}\n\n/**\n * Clean npm and npx cache directories\n */\nexport async function cleanNpmCache(): Promise<RecoveryResult> {\n const homeDir = os.homedir();\n const npxCacheDir = path.join(homeDir, '.npm', '_npx');\n\n try {\n console.log('🧹 Cleaning npm cache...');\n\n // Clean npm cache\n try {\n execSync('npm cache clean --force', { stdio: 'pipe' });\n console.log('✅ npm cache cleaned');\n } catch (error) {\n console.warn('⚠️ npm cache clean failed, continuing...');\n }\n\n // Remove npx cache directory\n if (await fs.pathExists(npxCacheDir)) {\n console.log(`🗑️ Removing npx cache: ${npxCacheDir}`);\n await fs.remove(npxCacheDir);\n console.log('✅ npx cache removed');\n }\n\n // Fix permissions on WSL\n if (isWSL()) {\n const npmDir = path.join(homeDir, '.npm');\n if (await fs.pathExists(npmDir)) {\n try {\n execSync(`chmod -R 755 \"${npmDir}\"`, { stdio: 'pipe' });\n console.log('✅ npm directory permissions fixed');\n } catch (error) {\n console.warn('⚠️ Permission fix failed, continuing...');\n }\n }\n }\n\n return {\n success: true,\n action: 'cache-cleanup',\n message: 'npm/npx cache cleaned successfully',\n recovered: true\n };\n } catch (error) {\n return {\n success: false,\n action: 'cache-cleanup',\n message: `Failed to clean cache: ${error instanceof Error ? error.message : String(error)}`,\n recovered: false\n };\n }\n}\n\n/**\n * Automatic retry with exponential backoff and error recovery\n */\nexport async function retryWithRecovery<T>(\n fn: () => Promise<T>,\n options: RetryOptions = {}\n): Promise<T> {\n const {\n maxRetries = 3,\n delay = 1000,\n onRetry,\n cleanupFn\n } = options;\n\n let lastError: Error | undefined;\n\n for (let attempt = 1; attempt <= maxRetries; attempt++) {\n try {\n return await fn();\n } catch (error) {\n lastError = error as Error;\n\n // Check if it's a recoverable error\n if (isNpmCacheError(error)) {\n console.log(`\\n⚠️ Detected npm cache error (attempt ${attempt}/${maxRetries})`);\n\n // Attempt automatic recovery\n const recovery = await cleanNpmCache();\n if (recovery.success) {\n console.log('✅ Cache cleaned, retrying...\\n');\n\n // Run custom cleanup if provided\n if (cleanupFn) {\n await cleanupFn();\n }\n\n // Exponential backoff\n const backoffDelay = delay * Math.pow(2, attempt - 1);\n await new Promise(resolve => setTimeout(resolve, backoffDelay));\n\n continue; // Retry\n } else {\n console.error('❌ Cache cleanup failed:', recovery.message);\n }\n }\n\n // Call retry callback\n if (onRetry && attempt < maxRetries) {\n onRetry(attempt, lastError);\n await new Promise(resolve => setTimeout(resolve, delay));\n continue;\n }\n\n // Last attempt failed\n if (attempt === maxRetries) {\n break;\n }\n }\n }\n\n // All retries exhausted\n throw new Error(\n `Operation failed after ${maxRetries} attempts. ` +\n `Last error: ${lastError?.message || 'Unknown error'}`\n );\n}\n\n/**\n * WSL-specific error recovery\n */\nexport async function recoverWSLErrors(): Promise<RecoveryResult> {\n if (!isWSL()) {\n return {\n success: true,\n action: 'wsl-check',\n message: 'Not running on WSL, no recovery needed',\n recovered: false\n };\n }\n\n console.log('🔍 Detected WSL environment, applying fixes...');\n\n try {\n const homeDir = os.homedir();\n\n // Check if running from Windows mount\n const cwd = process.cwd();\n if (cwd.startsWith('/mnt/')) {\n console.warn('⚠️ WARNING: Running from Windows filesystem (/mnt/)');\n console.warn(' For best results, run from WSL filesystem (e.g., ~/projects/)');\n }\n\n // Ensure build tools are available\n try {\n execSync('which gcc', { stdio: 'pipe' });\n } catch {\n console.warn('⚠️ build-essential not found. Install with:');\n console.warn(' sudo apt-get update && sudo apt-get install -y build-essential python3');\n }\n\n // Clean cache with WSL-specific handling\n return await cleanNpmCache();\n } catch (error) {\n return {\n success: false,\n action: 'wsl-recovery',\n message: `WSL recovery failed: ${error instanceof Error ? error.message : String(error)}`,\n recovered: false\n };\n }\n}\n\n/**\n * Verify better-sqlite3 installation\n */\nexport async function verifyBetterSqlite3(): Promise<boolean> {\n try {\n require.resolve('better-sqlite3');\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Install better-sqlite3 with retry and error recovery\n */\nexport async function installBetterSqlite3WithRecovery(): Promise<RecoveryResult> {\n console.log('📦 Installing better-sqlite3...');\n\n return retryWithRecovery(\n async () => {\n execSync('npm install better-sqlite3 --no-save', {\n stdio: 'inherit',\n cwd: process.cwd()\n });\n\n // Verify installation\n if (await verifyBetterSqlite3()) {\n return {\n success: true,\n action: 'install-sqlite',\n message: 'better-sqlite3 installed successfully',\n recovered: true\n };\n } else {\n throw new Error('Installation completed but module not found');\n }\n },\n {\n maxRetries: 3,\n delay: 2000,\n onRetry: (attempt, error) => {\n console.log(`⚠️ Install attempt ${attempt} failed: ${error.message}`);\n console.log('🔄 Cleaning cache and retrying...');\n }\n }\n );\n}\n\n/**\n * Comprehensive error recovery for initialization\n */\nexport async function recoverInitErrors(error: any): Promise<RecoveryResult> {\n console.log('\\n🚨 Error detected during initialization');\n console.log(` Error: ${error?.message || String(error)}\\n`);\n\n // WSL-specific recovery\n if (isWSL()) {\n console.log('🔧 Applying WSL-specific fixes...');\n const wslRecovery = await recoverWSLErrors();\n if (!wslRecovery.success) {\n return wslRecovery;\n }\n }\n\n // npm cache error recovery\n if (isNpmCacheError(error)) {\n console.log('🔧 Detected npm cache error, attempting recovery...');\n const cacheRecovery = await cleanNpmCache();\n if (!cacheRecovery.success) {\n return cacheRecovery;\n }\n\n // Try to reinstall better-sqlite3\n if (!await verifyBetterSqlite3()) {\n console.log('🔧 better-sqlite3 missing, attempting reinstall...');\n return await installBetterSqlite3WithRecovery();\n }\n\n return {\n success: true,\n action: 'error-recovery',\n message: 'Cache cleaned and dependencies verified',\n recovered: true\n };\n }\n\n // Generic error handling\n return {\n success: false,\n action: 'error-recovery',\n message: `Unable to automatically recover from error: ${error?.message || String(error)}`,\n recovered: false\n };\n}\n\n/**\n * Export utility functions\n */\nexport const errorRecovery = {\n isNpmCacheError,\n isWSL,\n cleanNpmCache,\n retryWithRecovery,\n recoverWSLErrors,\n verifyBetterSqlite3,\n installBetterSqlite3WithRecovery,\n recoverInitErrors\n};\n"],"names":["execSync","fs","path","os","isNpmCacheError","error","errorStr","message","String","includes","isWSL","process","platform","release","readFileSync","toLowerCase","cleanNpmCache","homeDir","homedir","npxCacheDir","join","console","log","stdio","warn","pathExists","remove","npmDir","success","action","recovered","Error","retryWithRecovery","fn","options","maxRetries","delay","onRetry","cleanupFn","lastError","attempt","recovery","backoffDelay","Math","pow","Promise","resolve","setTimeout","recoverWSLErrors","cwd","startsWith","verifyBetterSqlite3","require","installBetterSqlite3WithRecovery","recoverInitErrors","wslRecovery","cacheRecovery","errorRecovery"],"mappings":"AAKA,SAASA,QAAQ,QAAQ,gBAAgB;AACzC,YAAYC,QAAQ,WAAW;AAC/B,YAAYC,UAAU,OAAO;AAC7B,YAAYC,QAAQ,KAAK;AAmBzB,OAAO,SAASC,gBAAgBC,KAAU;IACxC,MAAMC,WAAWD,OAAOE,WAAWC,OAAOH;IAC1C,OAAO,AACLC,SAASG,QAAQ,CAAC,gBACjBH,CAAAA,SAASG,QAAQ,CAAC,UAAUH,SAASG,QAAQ,CAAC,UAAUH,SAASG,QAAQ,CAAC,OAAM,KAC9EH,SAASG,QAAQ,CAAC;AACzB;AAKA,OAAO,SAASC;IACd,IAAIC,QAAQC,QAAQ,KAAK,SAAS;QAChC,OAAO;IACT;IAEA,IAAI;QACF,MAAMC,UAAUZ,GAAGa,YAAY,CAAC,iBAAiB,QAAQC,WAAW;QACpE,OAAOF,QAAQJ,QAAQ,CAAC,gBAAgBI,QAAQJ,QAAQ,CAAC;IAC3D,EAAE,OAAM;QACN,OAAO;IACT;AACF;AAKA,OAAO,eAAeO;IACpB,MAAMC,UAAUd,GAAGe,OAAO;IAC1B,MAAMC,cAAcjB,KAAKkB,IAAI,CAACH,SAAS,QAAQ;IAE/C,IAAI;QACFI,QAAQC,GAAG,CAAC;QAGZ,IAAI;YACFtB,SAA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TuB,WAAW;QACb;IACF;IAGA,OAAO;QACLF,SAAS;QACTC,QAAQ;QACRtB,SAAS,CAAC,4CAA4C,EAAEF,OAAOE,WAAWC,OAAOH,QAAQ;QACzFyB,WAAW;IACb;AACF;AAKA,OAAO,MAAM2B,gBAAgB;IAC3BrD;IACAM;IACAM;IACAgB;IACAgB;IACAG;IACAE;IACAC;AACF,EAAE"}
1
+ {"version":3,"sources":["../../../src/utils/error-recovery.ts"],"sourcesContent":["/**\n * Error Recovery Utilities\n * Automatic error detection and recovery for common installation issues\n */\n\nimport { execSync } from 'child_process';\nimport * as fs from 'fs-extra';\nimport * as path from 'path';\nimport * as os from 'os';\n\nexport interface RecoveryResult {\n success: boolean;\n action: string;\n message: string;\n recovered: boolean;\n}\n\nexport interface RetryOptions {\n maxRetries?: number;\n delay?: number;\n onRetry?: (attempt: number, error: Error) => void;\n cleanupFn?: () => Promise<void>;\n}\n\n/**\n * Detect if an error is the ENOTEMPTY npm cache error\n */\nexport function isNpmCacheError(error: any): boolean {\n const errorStr = error?.message || String(error);\n return (\n errorStr.includes('ENOTEMPTY') &&\n (errorStr.includes('npm') || errorStr.includes('npx') || errorStr.includes('_npx'))\n ) || errorStr.includes('better-sqlite3');\n}\n\n/**\n * Detect if an error is a native module version mismatch (NODE_MODULE_VERSION)\n * This happens when native modules are compiled for a different Node.js version\n */\nexport function isNativeModuleVersionError(error: any): boolean {\n const errorStr = error?.message || String(error);\n return (\n errorStr.includes('NODE_MODULE_VERSION') ||\n errorStr.includes('was compiled against a different Node.js version') ||\n errorStr.includes('re-compiling or re-installing the module')\n );\n}\n\n/**\n * Get helpful message for native module version mismatch\n */\nexport function getNativeModuleRecoveryMessage(error: any): string {\n const errorStr = error?.message || String(error);\n\n // Extract version numbers if available\n const compiledMatch = errorStr.match(/NODE_MODULE_VERSION (\\d+)/);\n const requiredMatch = errorStr.match(/requires\\s+NODE_MODULE_VERSION (\\d+)/);\n\n let message = '⚠️ Native module version mismatch detected.\\n';\n\n if (compiledMatch && requiredMatch) {\n const nodeVersionMap: Record<string, string> = {\n '108': '18.x',\n '115': '20.x',\n '120': '21.x',\n '127': '22.x',\n '131': '23.x'\n };\n const compiled = nodeVersionMap[compiledMatch[1]] || `ABI ${compiledMatch[1]}`;\n const required = nodeVersionMap[requiredMatch[1]] || `ABI ${requiredMatch[1]}`;\n message += ` Module was compiled for Node.js ${compiled}, but running Node.js ${required}.\\n`;\n }\n\n message += '\\n To fix this, try one of:\\n';\n message += ' 1. npm rebuild better-sqlite3\\n';\n message += ' 2. rm -rf node_modules && npm install\\n';\n message += ' 3. npx cache: rm -rf ~/.npm/_npx/ && run command again\\n';\n\n return message;\n}\n\n/**\n * Detect if running on WSL (Windows Subsystem for Linux)\n */\nexport function isWSL(): boolean {\n if (process.platform !== 'linux') {\n return false;\n }\n\n try {\n const release = fs.readFileSync('/proc/version', 'utf8').toLowerCase();\n return release.includes('microsoft') || release.includes('wsl');\n } catch {\n return false;\n }\n}\n\n/**\n * Clean npm and npx cache directories\n */\nexport async function cleanNpmCache(): Promise<RecoveryResult> {\n const homeDir = os.homedir();\n const npxCacheDir = path.join(homeDir, '.npm', '_npx');\n\n try {\n console.log('🧹 Cleaning npm cache...');\n\n // Clean npm cache\n try {\n execSync('npm cache clean --force', { stdio: 'pipe' });\n console.log('✅ npm cache cleaned');\n } catch (error) {\n console.warn('⚠️ npm cache clean failed, continuing...');\n }\n\n // Remove npx cache directory\n if (await fs.pathExists(npxCacheDir)) {\n console.log(`🗑️ Removing npx cache: ${npxCacheDir}`);\n await fs.remove(npxCacheDir);\n console.log('✅ npx cache removed');\n }\n\n // Fix permissions on WSL\n if (isWSL()) {\n const npmDir = path.join(homeDir, '.npm');\n if (await fs.pathExists(npmDir)) {\n try {\n execSync(`chmod -R 755 \"${npmDir}\"`, { stdio: 'pipe' });\n console.log('✅ npm directory permissions fixed');\n } catch (error) {\n console.warn('⚠️ Permission fix failed, continuing...');\n }\n }\n }\n\n return {\n success: true,\n action: 'cache-cleanup',\n message: 'npm/npx cache cleaned successfully',\n recovered: true\n };\n } catch (error) {\n return {\n success: false,\n action: 'cache-cleanup',\n message: `Failed to clean cache: ${error instanceof Error ? error.message : String(error)}`,\n recovered: false\n };\n }\n}\n\n/**\n * Automatic retry with exponential backoff and error recovery\n */\nexport async function retryWithRecovery<T>(\n fn: () => Promise<T>,\n options: RetryOptions = {}\n): Promise<T> {\n const {\n maxRetries = 3,\n delay = 1000,\n onRetry,\n cleanupFn\n } = options;\n\n let lastError: Error | undefined;\n\n for (let attempt = 1; attempt <= maxRetries; attempt++) {\n try {\n return await fn();\n } catch (error) {\n lastError = error as Error;\n\n // Check if it's a recoverable error\n if (isNpmCacheError(error)) {\n console.log(`\\n⚠️ Detected npm cache error (attempt ${attempt}/${maxRetries})`);\n\n // Attempt automatic recovery\n const recovery = await cleanNpmCache();\n if (recovery.success) {\n console.log('✅ Cache cleaned, retrying...\\n');\n\n // Run custom cleanup if provided\n if (cleanupFn) {\n await cleanupFn();\n }\n\n // Exponential backoff\n const backoffDelay = delay * Math.pow(2, attempt - 1);\n await new Promise(resolve => setTimeout(resolve, backoffDelay));\n\n continue; // Retry\n } else {\n console.error('❌ Cache cleanup failed:', recovery.message);\n }\n }\n\n // Call retry callback\n if (onRetry && attempt < maxRetries) {\n onRetry(attempt, lastError);\n await new Promise(resolve => setTimeout(resolve, delay));\n continue;\n }\n\n // Last attempt failed\n if (attempt === maxRetries) {\n break;\n }\n }\n }\n\n // All retries exhausted\n throw new Error(\n `Operation failed after ${maxRetries} attempts. ` +\n `Last error: ${lastError?.message || 'Unknown error'}`\n );\n}\n\n/**\n * WSL-specific error recovery\n */\nexport async function recoverWSLErrors(): Promise<RecoveryResult> {\n if (!isWSL()) {\n return {\n success: true,\n action: 'wsl-check',\n message: 'Not running on WSL, no recovery needed',\n recovered: false\n };\n }\n\n console.log('🔍 Detected WSL environment, applying fixes...');\n\n try {\n const homeDir = os.homedir();\n\n // Check if running from Windows mount\n const cwd = process.cwd();\n if (cwd.startsWith('/mnt/')) {\n console.warn('⚠️ WARNING: Running from Windows filesystem (/mnt/)');\n console.warn(' For best results, run from WSL filesystem (e.g., ~/projects/)');\n }\n\n // Ensure build tools are available\n try {\n execSync('which gcc', { stdio: 'pipe' });\n } catch {\n console.warn('⚠️ build-essential not found. Install with:');\n console.warn(' sudo apt-get update && sudo apt-get install -y build-essential python3');\n }\n\n // Clean cache with WSL-specific handling\n return await cleanNpmCache();\n } catch (error) {\n return {\n success: false,\n action: 'wsl-recovery',\n message: `WSL recovery failed: ${error instanceof Error ? error.message : String(error)}`,\n recovered: false\n };\n }\n}\n\n/**\n * Verify better-sqlite3 installation\n */\nexport async function verifyBetterSqlite3(): Promise<boolean> {\n try {\n require.resolve('better-sqlite3');\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Install better-sqlite3 with retry and error recovery\n */\nexport async function installBetterSqlite3WithRecovery(): Promise<RecoveryResult> {\n console.log('📦 Installing better-sqlite3...');\n\n return retryWithRecovery(\n async () => {\n execSync('npm install better-sqlite3 --no-save', {\n stdio: 'inherit',\n cwd: process.cwd()\n });\n\n // Verify installation\n if (await verifyBetterSqlite3()) {\n return {\n success: true,\n action: 'install-sqlite',\n message: 'better-sqlite3 installed successfully',\n recovered: true\n };\n } else {\n throw new Error('Installation completed but module not found');\n }\n },\n {\n maxRetries: 3,\n delay: 2000,\n onRetry: (attempt, error) => {\n console.log(`⚠️ Install attempt ${attempt} failed: ${error.message}`);\n console.log('🔄 Cleaning cache and retrying...');\n }\n }\n );\n}\n\n/**\n * Comprehensive error recovery for initialization\n */\nexport async function recoverInitErrors(error: any): Promise<RecoveryResult> {\n console.log('\\n🚨 Error detected during initialization');\n console.log(` Error: ${error?.message || String(error)}\\n`);\n\n // WSL-specific recovery\n if (isWSL()) {\n console.log('🔧 Applying WSL-specific fixes...');\n const wslRecovery = await recoverWSLErrors();\n if (!wslRecovery.success) {\n return wslRecovery;\n }\n }\n\n // npm cache error recovery\n if (isNpmCacheError(error)) {\n console.log('🔧 Detected npm cache error, attempting recovery...');\n const cacheRecovery = await cleanNpmCache();\n if (!cacheRecovery.success) {\n return cacheRecovery;\n }\n\n // Try to reinstall better-sqlite3\n if (!await verifyBetterSqlite3()) {\n console.log('🔧 better-sqlite3 missing, attempting reinstall...');\n return await installBetterSqlite3WithRecovery();\n }\n\n return {\n success: true,\n action: 'error-recovery',\n message: 'Cache cleaned and dependencies verified',\n recovered: true\n };\n }\n\n // Generic error handling\n return {\n success: false,\n action: 'error-recovery',\n message: `Unable to automatically recover from error: ${error?.message || String(error)}`,\n recovered: false\n };\n}\n\n/**\n * Export utility functions\n */\nexport const errorRecovery = {\n isNpmCacheError,\n isNativeModuleVersionError,\n getNativeModuleRecoveryMessage,\n isWSL,\n cleanNpmCache,\n retryWithRecovery,\n recoverWSLErrors,\n verifyBetterSqlite3,\n installBetterSqlite3WithRecovery,\n recoverInitErrors\n};\n"],"names":["execSync","fs","path","os","isNpmCacheError","error","errorStr","message","String","includes","isNativeModuleVersionError","getNativeModuleRecoveryMessage","compiledMatch","match","requiredMatch","nodeVersionMap","compiled","required","isWSL","process","platform","release","readFileSync","toLowerCase","cleanNpmCache","homeDir","homedir","npxCacheDir","join","console","log","stdio","warn","pathExists","remove","npmDir","success","action","recovered","Error","retryWithRecovery","fn","options","maxRetries","delay","onRetry","cleanupFn","lastError","attempt","recovery","backoffDelay","Math","pow","Promise","resolve","setTimeout","recoverWSLErrors","cwd","startsWith","verifyBetterSqlite3","require","installBetterSqlite3WithRecovery","recoverInitErrors","wslRecovery","cacheRecovery","errorRecovery"],"mappings":"AAKA,SAASA,QAAQ,QAAQ,gBAAgB;AACzC,YAAYC,QAAQ,WAAW;AAC/B,YAAYC,UAAU,OAAO;AAC7B,YAAYC,QAAQ,KAAK;AAmBzB,OAAO,SAASC,gBAAgBC,KAAU;IACxC,MAAMC,WAAWD,OAAOE,WAAWC,OAAOH;IAC1C,OAAO,AACLC,SAASG,QAAQ,CAAC,gBACjBH,CAAAA,SAASG,QA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,MAAML,uBAAuB;YAChC9B,QAAQC,GAAG,CAAC;YACZ,OAAO,MAAM+B;QACf;QAEA,OAAO;YACLzB,SAAS;YACTC,QAAQ;YACR9B,SAAS;YACT+B,WAAW;QACb;IACF;IAGA,OAAO;QACLF,SAAS;QACTC,QAAQ;QACR9B,SAAS,CAAC,4CAA4C,EAAEF,OAAOE,WAAWC,OAAOH,QAAQ;QACzFiC,WAAW;IACb;AACF;AAKA,OAAO,MAAM2B,gBAAgB;IAC3B7D;IACAM;IACAC;IACAO;IACAM;IACAgB;IACAgB;IACAG;IACAE;IACAC;AACF,EAAE"}
@@ -166,14 +166,4 @@ export class MetricsReader {
166
166
  }
167
167
  }
168
168
 
169
- //# sourceMappingURL=metrics-reader.js.map processCount: 0,
170
- orchestratorRunning: false,
171
- port: null,
172
- connections: 0
173
- };
174
- }
175
- }
176
- };
177
- export { MetricsReader };
178
-
179
169
  //# sourceMappingURL=metrics-reader.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-flow",
3
- "version": "2.7.42",
3
+ "version": "2.7.44",
4
4
  "description": "Enterprise-grade AI agent orchestration with WASM-powered ReasoningBank memory and AgentDB vector database (always uses latest agentic-flow)",
5
5
  "mcpName": "io.github.ruvnet/claude-flow",
6
6
  "main": "cli.mjs",
@@ -6,15 +6,45 @@ import {
6
6
  checkRuvSwarmAvailable,
7
7
  } from '../utils.js';
8
8
  import { SqliteMemoryStore } from '../../memory/sqlite-store.js';
9
+ import { InMemoryStore } from '../../memory/in-memory-store.js';
9
10
 
10
11
  // Initialize memory store
11
12
  let memoryStore = null;
13
+ let storeInitFailed = false;
12
14
 
13
15
  async function getMemoryStore() {
14
- if (!memoryStore) {
16
+ if (memoryStore) return memoryStore;
17
+
18
+ // If we already failed, return a working in-memory store
19
+ if (storeInitFailed) {
20
+ if (!memoryStore) {
21
+ memoryStore = new InMemoryStore();
22
+ await memoryStore.initialize();
23
+ }
24
+ return memoryStore;
25
+ }
26
+
27
+ try {
15
28
  memoryStore = new SqliteMemoryStore();
16
29
  await memoryStore.initialize();
30
+ } catch (err) {
31
+ // Check if it's a native module error (NODE_MODULE_VERSION mismatch)
32
+ const isNativeModuleError =
33
+ err.message?.includes('NODE_MODULE_VERSION') ||
34
+ err.message?.includes('was compiled against a different Node.js version') ||
35
+ err.message?.includes('better-sqlite3') ||
36
+ err.message?.includes('SQLite is not available');
37
+
38
+ if (isNativeModuleError) {
39
+ printWarning(`SQLite unavailable, using in-memory storage for hooks (data won't persist)`);
40
+ storeInitFailed = true;
41
+ memoryStore = new InMemoryStore();
42
+ await memoryStore.initialize();
43
+ } else {
44
+ throw err;
45
+ }
17
46
  }
47
+
18
48
  return memoryStore;
19
49
  }
20
50
 
@@ -6,6 +6,21 @@
6
6
  import * as fs from 'fs-extra';
7
7
  import * as path from 'path';
8
8
  import { IDatabaseProvider } from '../types/interfaces.js';
9
+ import { isNativeModuleVersionError, getNativeModuleRecoveryMessage } from '../utils/error-recovery.js';
10
+
11
+ /**
12
+ * Custom error class for native module issues
13
+ */
14
+ export class NativeModuleError extends Error {
15
+ public readonly originalError: Error;
16
+ public readonly isNativeModuleError = true;
17
+
18
+ constructor(message: string, originalError: Error) {
19
+ super(message);
20
+ this.name = 'NativeModuleError';
21
+ this.originalError = originalError;
22
+ }
23
+ }
9
24
 
10
25
  export class DatabaseManager implements IDatabaseProvider {
11
26
  private provider: IDatabaseProvider;
@@ -36,12 +51,17 @@ export class DatabaseManager implements IDatabaseProvider {
36
51
  } catch (error) {
37
52
  const errorMsg = error instanceof Error ? error.message : String(error);
38
53
 
54
+ // Check for native module version mismatch (NODE_MODULE_VERSION error)
55
+ if (error instanceof NativeModuleError || isNativeModuleVersionError(error)) {
56
+ console.warn('\n' + (error instanceof NativeModuleError ? error.message : getNativeModuleRecoveryMessage(error)));
57
+ console.warn(' Falling back to JSON storage (no data loss, just slower).\n');
58
+ }
39
59
  // Check if it's an npm cache error
40
- if (errorMsg.includes('ENOTEMPTY') || errorMsg.includes('better-sqlite3')) {
60
+ else if (errorMsg.includes('ENOTEMPTY') || errorMsg.includes('better-sqlite3')) {
41
61
  console.warn('⚠️ SQLite initialization failed due to npm cache error');
42
62
  console.warn(' Will attempt automatic recovery during initialize()');
43
63
  } else {
44
- console.warn('SQLite not available, falling back to JSON storage:', error);
64
+ console.warn('SQLite not available, falling back to JSON storage:', errorMsg);
45
65
  }
46
66
 
47
67
  // Fallback to JSON for now
@@ -177,6 +197,11 @@ class SQLiteProvider implements IDatabaseProvider {
177
197
  const Database = require('better-sqlite3');
178
198
  this.db = new Database(dbPath);
179
199
  } catch (error) {
200
+ // Check for native module version mismatch (NODE_MODULE_VERSION error)
201
+ if (isNativeModuleVersionError(error)) {
202
+ const recoveryMsg = getNativeModuleRecoveryMessage(error);
203
+ throw new NativeModuleError(recoveryMsg, error as Error);
204
+ }
180
205
  throw new Error('better-sqlite3 not available. Install with: npm install better-sqlite3');
181
206
  }
182
207
  }
@@ -20,11 +20,13 @@ class InMemoryStore {
20
20
  this.data.set('default', new Map());
21
21
 
22
22
  // Start cleanup interval for expired entries
23
+ // Use unref() so the interval doesn't prevent process exit
23
24
  this.cleanupInterval = setInterval(() => {
24
25
  this.cleanup().catch((err) =>
25
26
  console.error(`[${new Date().toISOString()}] ERROR [in-memory-store] Cleanup failed:`, err),
26
27
  );
27
28
  }, 60000); // Run cleanup every minute
29
+ this.cleanupInterval.unref(); // Don't keep process alive just for cleanup
28
30
 
29
31
  this.isInitialized = true;
30
32
  console.error(
@@ -33,35 +33,79 @@ async function tryLoadSQLite() {
33
33
  return true;
34
34
  } catch (importErr) {
35
35
  loadError = importErr;
36
-
37
- // Check for specific Windows errors
38
- if (requireErr.message.includes('was compiled against a different Node.js version') ||
39
- requireErr.message.includes('Could not locate the bindings file') ||
40
- requireErr.message.includes('The specified module could not be found') ||
36
+
37
+ // Check for NODE_MODULE_VERSION mismatch (different Node.js ABI)
38
+ const isVersionMismatch =
39
+ requireErr.message?.includes('NODE_MODULE_VERSION') ||
40
+ importErr.message?.includes('NODE_MODULE_VERSION') ||
41
+ requireErr.message?.includes('was compiled against a different Node.js version') ||
42
+ importErr.message?.includes('was compiled against a different Node.js version');
43
+
44
+ if (isVersionMismatch) {
45
+ // Extract version info for helpful message
46
+ const errorMsg = requireErr.message || importErr.message || '';
47
+ const compiledMatch = errorMsg.match(/NODE_MODULE_VERSION (\d+)/);
48
+ const requiredMatch = errorMsg.match(/requires\s+NODE_MODULE_VERSION (\d+)/);
49
+
50
+ const nodeVersionMap = {
51
+ '108': '18.x', '115': '20.x', '120': '21.x', '127': '22.x', '131': '23.x'
52
+ };
53
+
54
+ let versionInfo = '';
55
+ if (compiledMatch && requiredMatch) {
56
+ const compiled = nodeVersionMap[compiledMatch[1]] || `ABI ${compiledMatch[1]}`;
57
+ const required = nodeVersionMap[requiredMatch[1]] || `ABI ${requiredMatch[1]}`;
58
+ versionInfo = `\n║ Module compiled for Node.js ${compiled}, running Node.js ${required}`.padEnd(79) + '║';
59
+ }
60
+
61
+ console.warn(`
62
+ ╔══════════════════════════════════════════════════════════════════════════════╗
63
+ ║ Native Module Version Mismatch (NODE_MODULE_VERSION) ║
64
+ ╠══════════════════════════════════════════════════════════════════════════════╣
65
+ ║ ║
66
+ ║ The better-sqlite3 module was compiled for a different Node.js version. ║${versionInfo}
67
+ ║ ║
68
+ ║ Claude Flow will continue with JSON fallback storage (still works fine). ║
69
+ ║ ║
70
+ ║ To fix this and use SQLite: ║
71
+ ║ ║
72
+ ║ Option 1 - Rebuild the module: ║
73
+ ║ > npm rebuild better-sqlite3 ║
74
+ ║ ║
75
+ ║ Option 2 - Clear npx cache (if using npx): ║
76
+ ║ > rm -rf ~/.npm/_npx/ && npx claude-flow@alpha ... ║
77
+ ║ ║
78
+ ║ Option 3 - Reinstall dependencies: ║
79
+ ║ > rm -rf node_modules && npm install ║
80
+ ║ ║
81
+ ╚══════════════════════════════════════════════════════════════════════════════╝
82
+ `);
83
+ return false;
84
+ }
85
+
86
+ // Check for other Windows/installation errors
87
+ if (requireErr.message?.includes('Could not locate the bindings file') ||
88
+ requireErr.message?.includes('The specified module could not be found') ||
41
89
  requireErr.code === 'MODULE_NOT_FOUND') {
42
-
90
+
43
91
  console.warn(`
44
92
  ╔══════════════════════════════════════════════════════════════════════════════╗
45
- Windows SQLite Installation Issue
93
+ ║ SQLite Native Module Installation Issue
46
94
  ╠══════════════════════════════════════════════════════════════════════════════╣
47
95
  ║ ║
48
96
  ║ The native SQLite module failed to load. This is common on Windows when ║
49
- ║ using 'npx' or when node-gyp build tools are not available.
50
- ║ ║
51
- ║ Claude Flow will continue with in-memory storage (non-persistent). ║
97
+ ║ using 'npx' or when node-gyp build tools are not available.
52
98
  ║ ║
53
- To enable persistent storage on Windows:
99
+ Claude Flow will continue with JSON fallback storage (still works fine).
54
100
  ║ ║
55
- Option 1 - Install Windows Build Tools:
56
- ║ > npm install --global windows-build-tools ║
57
- ║ > npm install claude-flow@alpha ║
101
+ To enable SQLite storage:
58
102
  ║ ║
59
- ║ Option 2 - Use Pre-built Binaries:
60
- ║ > npm config set python python3
61
- ║ > npm install claude-flow@alpha --build-from-source=false
103
+ ║ Option 1 - Install Build Tools (Windows):
104
+ ║ > npm install --global windows-build-tools
105
+ ║ > npm install claude-flow@alpha
62
106
  ║ ║
63
- ║ Option 3 - Use WSL (Windows Subsystem for Linux):
64
- ║ Install WSL and run Claude Flow inside a Linux environment
107
+ ║ Option 2 - Use WSL (Windows Subsystem for Linux):
108
+ ║ Install WSL and run Claude Flow inside a Linux environment
65
109
  ║ ║
66
110
  ╚══════════════════════════════════════════════════════════════════════════════╝
67
111
  `);
@@ -33,6 +33,52 @@ export function isNpmCacheError(error: any): boolean {
33
33
  ) || errorStr.includes('better-sqlite3');
34
34
  }
35
35
 
36
+ /**
37
+ * Detect if an error is a native module version mismatch (NODE_MODULE_VERSION)
38
+ * This happens when native modules are compiled for a different Node.js version
39
+ */
40
+ export function isNativeModuleVersionError(error: any): boolean {
41
+ const errorStr = error?.message || String(error);
42
+ return (
43
+ errorStr.includes('NODE_MODULE_VERSION') ||
44
+ errorStr.includes('was compiled against a different Node.js version') ||
45
+ errorStr.includes('re-compiling or re-installing the module')
46
+ );
47
+ }
48
+
49
+ /**
50
+ * Get helpful message for native module version mismatch
51
+ */
52
+ export function getNativeModuleRecoveryMessage(error: any): string {
53
+ const errorStr = error?.message || String(error);
54
+
55
+ // Extract version numbers if available
56
+ const compiledMatch = errorStr.match(/NODE_MODULE_VERSION (\d+)/);
57
+ const requiredMatch = errorStr.match(/requires\s+NODE_MODULE_VERSION (\d+)/);
58
+
59
+ let message = '⚠️ Native module version mismatch detected.\n';
60
+
61
+ if (compiledMatch && requiredMatch) {
62
+ const nodeVersionMap: Record<string, string> = {
63
+ '108': '18.x',
64
+ '115': '20.x',
65
+ '120': '21.x',
66
+ '127': '22.x',
67
+ '131': '23.x'
68
+ };
69
+ const compiled = nodeVersionMap[compiledMatch[1]] || `ABI ${compiledMatch[1]}`;
70
+ const required = nodeVersionMap[requiredMatch[1]] || `ABI ${requiredMatch[1]}`;
71
+ message += ` Module was compiled for Node.js ${compiled}, but running Node.js ${required}.\n`;
72
+ }
73
+
74
+ message += '\n To fix this, try one of:\n';
75
+ message += ' 1. npm rebuild better-sqlite3\n';
76
+ message += ' 2. rm -rf node_modules && npm install\n';
77
+ message += ' 3. npx cache: rm -rf ~/.npm/_npx/ && run command again\n';
78
+
79
+ return message;
80
+ }
81
+
36
82
  /**
37
83
  * Detect if running on WSL (Windows Subsystem for Linux)
38
84
  */
@@ -315,6 +361,8 @@ export async function recoverInitErrors(error: any): Promise<RecoveryResult> {
315
361
  */
316
362
  export const errorRecovery = {
317
363
  isNpmCacheError,
364
+ isNativeModuleVersionError,
365
+ getNativeModuleRecoveryMessage,
318
366
  isWSL,
319
367
  cleanNpmCache,
320
368
  retryWithRecovery,