UNPKG

mushcode-mcp-server

Version:

A specialized Model Context Protocol server for MUSHCODE development assistance. Provides AI-powered code generation, validation, optimization, and examples for MUD development.

477 lines 23 kB
/** * Optimized pattern matcher with caching and performance improvements */ var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) { var useValue = arguments.length > 2; for (var i = 0; i < initializers.length; i++) { value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); } return useValue ? value : void 0; }; var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); var _, done = false; for (var i = decorators.length - 1; i >= 0; i--) { var context = {}; for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; for (var p in contextIn.access) context.access[p] = contextIn.access[p]; context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); if (kind === "accessor") { if (result === void 0) continue; if (result === null || typeof result !== "object") throw new TypeError("Object expected"); if (_ = accept(result.get)) descriptor.get = _; if (_ = accept(result.set)) descriptor.set = _; if (_ = accept(result.init)) initializers.unshift(_); } else if (_ = accept(result)) { if (kind === "field") initializers.unshift(_); else descriptor[key] = _; } } if (target) Object.defineProperty(target, contextIn.name, descriptor); done = true; }; import { PatternMatcher } from './matcher.js'; import { cacheManager } from '../utils/cache.js'; import { monitorPerformance } from '../utils/performance.js'; import { logger } from '../utils/logger.js'; /** * Optimized pattern matcher with caching and improved algorithms */ let OptimizedPatternMatcher = (() => { let _classSuper = PatternMatcher; let _instanceExtraInitializers = []; let _findPatternsForGeneration_decorators; let _findSecurityViolations_decorators; let _findOptimizationPatterns_decorators; let _findSimilarExamples_decorators; let _findPatternsByFunction_decorators; let _findByTags_decorators; return class OptimizedPatternMatcher extends _classSuper { static { const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0; _findPatternsForGeneration_decorators = [monitorPerformance('find_patterns_for_generation')]; _findSecurityViolations_decorators = [monitorPerformance('find_security_violations')]; _findOptimizationPatterns_decorators = [monitorPerformance('find_optimization_patterns')]; _findSimilarExamples_decorators = [monitorPerformance('find_similar_examples')]; _findPatternsByFunction_decorators = [monitorPerformance('find_patterns_by_function')]; _findByTags_decorators = [monitorPerformance('find_by_tags')]; __esDecorate(this, null, _findPatternsForGeneration_decorators, { kind: "method", name: "findPatternsForGeneration", static: false, private: false, access: { has: obj => "findPatternsForGeneration" in obj, get: obj => obj.findPatternsForGeneration }, metadata: _metadata }, null, _instanceExtraInitializers); __esDecorate(this, null, _findSecurityViolations_decorators, { kind: "method", name: "findSecurityViolations", static: false, private: false, access: { has: obj => "findSecurityViolations" in obj, get: obj => obj.findSecurityViolations }, metadata: _metadata }, null, _instanceExtraInitializers); __esDecorate(this, null, _findOptimizationPatterns_decorators, { kind: "method", name: "findOptimizationPatterns", static: false, private: false, access: { has: obj => "findOptimizationPatterns" in obj, get: obj => obj.findOptimizationPatterns }, metadata: _metadata }, null, _instanceExtraInitializers); __esDecorate(this, null, _findSimilarExamples_decorators, { kind: "method", name: "findSimilarExamples", static: false, private: false, access: { has: obj => "findSimilarExamples" in obj, get: obj => obj.findSimilarExamples }, metadata: _metadata }, null, _instanceExtraInitializers); __esDecorate(this, null, _findPatternsByFunction_decorators, { kind: "method", name: "findPatternsByFunction", static: false, private: false, access: { has: obj => "findPatternsByFunction" in obj, get: obj => obj.findPatternsByFunction }, metadata: _metadata }, null, _instanceExtraInitializers); __esDecorate(this, null, _findByTags_decorators, { kind: "method", name: "findByTags", static: false, private: false, access: { has: obj => "findByTags" in obj, get: obj => obj.findByTags }, metadata: _metadata }, null, _instanceExtraInitializers); if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata }); } optimizedKnowledgeBase = __runInitializers(this, _instanceExtraInitializers); patternMatchCache; securityViolationCache; optimizationCache; similarExamplesCache; // Pre-compiled regex patterns for better performance compiledSecurityPatterns = new Map(); codeTermsCache = new Map(); constructor(optimizedKnowledgeBase) { super(optimizedKnowledgeBase); this.optimizedKnowledgeBase = optimizedKnowledgeBase; // Initialize caches this.patternMatchCache = cacheManager.getCache('pattern_matches', { maxSize: 200, defaultTtl: 300000, // 5 minutes cleanupInterval: 60000 }); this.securityViolationCache = cacheManager.getCache('security_violations', { maxSize: 100, defaultTtl: 600000, // 10 minutes cleanupInterval: 120000 }); this.optimizationCache = cacheManager.getCache('optimization_patterns', { maxSize: 150, defaultTtl: 300000, // 5 minutes cleanupInterval: 60000 }); this.similarExamplesCache = cacheManager.getCache('similar_examples', { maxSize: 200, defaultTtl: 300000, // 5 minutes cleanupInterval: 60000 }); this.precompileSecurityPatterns(); } /** * Find patterns matching a natural language description with caching */ findPatternsForGeneration(description, serverType, functionType, difficulty) { const cacheKey = this.generatePatternCacheKey(description, serverType, functionType, difficulty); // Check cache first const cached = this.patternMatchCache.get(cacheKey); if (cached) { logger.debug('Pattern match cache hit', { operation: 'find_patterns_for_generation', description: description.substring(0, 50), cacheKey }); return cached; } // Use optimized knowledge base search const query = { query: description, ...(serverType && { serverType }), ...(functionType && { category: functionType }), ...(difficulty && { difficulty }), includePatterns: true, includeExamples: false, fuzzyMatch: true, limit: 10 }; const results = this.optimizedKnowledgeBase.search(query); // Cache the result this.patternMatchCache.set(cacheKey, results.patterns, 300000); logger.debug('Pattern match completed and cached', { operation: 'find_patterns_for_generation', description: description.substring(0, 50), resultCount: results.patterns.length }); return results.patterns; } /** * Find security violations with optimized regex compilation and caching */ findSecurityViolations(code, serverType) { const cacheKey = this.generateSecurityCacheKey(code, serverType); // Check cache first const cached = this.securityViolationCache.get(cacheKey); if (cached) { logger.debug('Security violation cache hit', { operation: 'find_security_violations', cacheKey }); return cached; } const violations = []; const codeLines = code.split('\n'); // Use pre-compiled patterns for better performance for (const [ruleId, compiledPattern] of this.compiledSecurityPatterns.entries()) { const rule = this.optimizedKnowledgeBase.getSecurityRule(ruleId); if (!rule) continue; // Skip rules that don't apply to this server type if (serverType && rule.affectedServers.length > 0 && !rule.affectedServers.includes(serverType)) { continue; } // Check each line for pattern matches for (let i = 0; i < codeLines.length; i++) { const line = codeLines[i]; if (line && compiledPattern.test(line)) { violations.push(rule); break; // Don't add the same rule multiple times } } } const sortedViolations = violations.sort((a, b) => { const severityOrder = { critical: 4, high: 3, medium: 2, low: 1 }; return severityOrder[b.severity] - severityOrder[a.severity]; }); // Cache the result this.securityViolationCache.set(cacheKey, sortedViolations, 600000); logger.debug('Security violation check completed and cached', { operation: 'find_security_violations', violationCount: sortedViolations.length }); return sortedViolations; } /** * Find optimization patterns with caching and improved term extraction */ findOptimizationPatterns(code, serverType) { const cacheKey = this.generateOptimizationCacheKey(code, serverType); // Check cache first const cached = this.optimizationCache.get(cacheKey); if (cached) { logger.debug('Optimization pattern cache hit', { operation: 'find_optimization_patterns', cacheKey }); return cached; } // Use cached code terms extraction const codeTerms = this.getCodeTermsCached(code); const matches = []; // Use optimized knowledge base methods for (const pattern of this.optimizedKnowledgeBase.getAllPatterns()) { // Skip patterns not compatible with server type if (serverType && !pattern.serverCompatibility.includes(serverType)) { continue; } const relevance = this.calculateOptimizedCodePatternRelevance(codeTerms, pattern); if (relevance > 0.3) { // Threshold for relevance matches.push({ patternId: pattern.id, confidence: relevance, relevance, matchedTerms: this.getCodeMatchedTerms(codeTerms, pattern) }); } } const sortedMatches = matches.sort((a, b) => b.relevance - a.relevance).slice(0, 5); // Cache the result this.optimizationCache.set(cacheKey, sortedMatches, 300000); logger.debug('Optimization pattern search completed and cached', { operation: 'find_optimization_patterns', matchCount: sortedMatches.length }); return sortedMatches; } /** * Find similar examples with caching */ findSimilarExamples(code, serverType, limit = 5) { const cacheKey = this.generateSimilarExamplesCacheKey(code, serverType, limit); // Check cache first const cached = this.similarExamplesCache.get(cacheKey); if (cached) { logger.debug('Similar examples cache hit', { operation: 'find_similar_examples', cacheKey }); return cached; } const codeTerms = this.getCodeTermsCached(code); const matches = []; for (const example of this.optimizedKnowledgeBase.getAllExamples()) { // Skip examples not compatible with server type if (serverType && !example.serverCompatibility.includes(serverType)) { continue; } const relevance = this.calculateOptimizedExampleCodeRelevance(codeTerms, example); if (relevance > 0.2) { matches.push({ example, relevance }); } } const sortedExamples = matches .sort((a, b) => b.relevance - a.relevance) .slice(0, limit) .map(match => match.example); // Cache the result this.similarExamplesCache.set(cacheKey, sortedExamples, 300000); logger.debug('Similar examples search completed and cached', { operation: 'find_similar_examples', exampleCount: sortedExamples.length }); return sortedExamples; } /** * Fast pattern lookup by function name using knowledge base indexes */ findPatternsByFunction(functionName) { // Use optimized knowledge base method if available if (this.optimizedKnowledgeBase.findPatternsByFunction) { return this.optimizedKnowledgeBase.findPatternsByFunction(functionName); } // Fallback to base implementation return super.findPatternByName(functionName) ? [super.findPatternByName(functionName)] : []; } /** * Fast tag-based search using knowledge base indexes */ findByTags(tags) { // Use optimized knowledge base method if available if (this.optimizedKnowledgeBase.findByTags) { return this.optimizedKnowledgeBase.findByTags(tags); } // Fallback to base implementation const patterns = []; const examples = []; for (const tag of tags) { patterns.push(...super.findPatternsByTag(tag)); } return { patterns: [...new Set(patterns)], examples }; } /** * Get cache statistics for monitoring */ getCacheStats() { return { patternMatchCache: this.patternMatchCache.getStats(), securityViolationCache: this.securityViolationCache.getStats(), optimizationCache: this.optimizationCache.getStats(), similarExamplesCache: this.similarExamplesCache.getStats(), compiledPatternsCount: this.compiledSecurityPatterns.size, codeTermsCacheSize: this.codeTermsCache.size }; } /** * Clear all caches */ clearCaches() { this.patternMatchCache.clear(); this.securityViolationCache.clear(); this.optimizationCache.clear(); this.similarExamplesCache.clear(); this.codeTermsCache.clear(); logger.info('Pattern matcher caches cleared', { operation: 'clear_caches' }); } /** * Pre-compile security patterns for better performance */ precompileSecurityPatterns() { logger.info('Pre-compiling security patterns', { operation: 'precompile_security_patterns' }); let compiledCount = 0; for (const rule of this.optimizedKnowledgeBase.getAllSecurityRules()) { try { const compiledPattern = new RegExp(rule.pattern, 'gi'); this.compiledSecurityPatterns.set(rule.ruleId, compiledPattern); compiledCount++; } catch (error) { logger.warn(`Failed to compile security pattern for rule ${rule.ruleId}: ${rule.pattern}`, { operation: 'precompile_security_patterns', ruleId: rule.ruleId, error: error.message }); } } logger.info(`Pre-compiled ${compiledCount} security patterns`, { operation: 'precompile_security_patterns', compiledCount }); } /** * Get code terms with caching */ getCodeTermsCached(code) { const cacheKey = this.generateCodeHash(code); if (this.codeTermsCache.has(cacheKey)) { return this.codeTermsCache.get(cacheKey); } const terms = this.extractCodeTerms(code); // Cache with size limit if (this.codeTermsCache.size >= 1000) { // Remove oldest entries const keys = Array.from(this.codeTermsCache.keys()); for (let i = 0; i < 100; i++) { this.codeTermsCache.delete(keys[i]); } } this.codeTermsCache.set(cacheKey, terms); return terms; } /** * Calculate optimized code pattern relevance with weighted scoring */ calculateOptimizedCodePatternRelevance(codeTerms, pattern) { const weights = { name: 3.0, description: 2.0, codeTemplate: 2.5, tags: 2.0 }; const fields = { name: pattern.name.toLowerCase(), description: pattern.description.toLowerCase(), codeTemplate: pattern.codeTemplate.toLowerCase(), tags: pattern.tags.join(' ').toLowerCase() }; let score = 0; let maxPossibleScore = 0; for (const term of codeTerms) { for (const [field, content] of Object.entries(fields)) { const weight = weights[field]; maxPossibleScore += weight; if (content.includes(term.toLowerCase())) { score += weight; // Bonus for exact word match if (content.split(/\s+/).includes(term.toLowerCase())) { score += weight * 0.5; } } } } return maxPossibleScore > 0 ? score / maxPossibleScore : 0; } /** * Calculate optimized example code relevance */ calculateOptimizedExampleCodeRelevance(codeTerms, example) { const weights = { title: 3.0, description: 2.0, code: 2.5, tags: 2.0 }; const fields = { title: example.title.toLowerCase(), description: example.description.toLowerCase(), code: example.code.toLowerCase(), tags: example.tags.join(' ').toLowerCase() }; let score = 0; let maxPossibleScore = 0; for (const term of codeTerms) { for (const [field, content] of Object.entries(fields)) { const weight = weights[field]; maxPossibleScore += weight; if (content.includes(term.toLowerCase())) { score += weight; // Bonus for exact word match if (content.split(/\s+/).includes(term.toLowerCase())) { score += weight * 0.5; } } } } return maxPossibleScore > 0 ? score / maxPossibleScore : 0; } /** * Generate cache key for pattern matching */ generatePatternCacheKey(description, serverType, functionType, difficulty) { return `pattern:${description}:${serverType || ''}:${functionType || ''}:${difficulty || ''}`; } /** * Generate cache key for security violations */ generateSecurityCacheKey(code, serverType) { const codeHash = this.generateCodeHash(code); return `security:${codeHash}:${serverType || ''}`; } /** * Generate cache key for optimization patterns */ generateOptimizationCacheKey(code, serverType) { const codeHash = this.generateCodeHash(code); return `optimization:${codeHash}:${serverType || ''}`; } /** * Generate cache key for similar examples */ generateSimilarExamplesCacheKey(code, serverType, limit) { const codeHash = this.generateCodeHash(code); return `examples:${codeHash}:${serverType || ''}:${limit || 5}`; } /** * Generate a hash for code content */ generateCodeHash(code) { // Simple hash function for caching purposes let hash = 0; for (let i = 0; i < code.length; i++) { const char = code.charCodeAt(i); hash = ((hash << 5) - hash) + char; hash = hash & hash; // Convert to 32-bit integer } return hash.toString(36); } }; })(); export { OptimizedPatternMatcher }; //# sourceMappingURL=optimized-matcher.js.map