UNPKG

@andrebuzeli/advanced-memory-markdown-mcp

Version:

Advanced Memory Bank MCP v3.1.5 - Sistema avançado de gerenciamento de memória com isolamento de projetos por IDE, sincronização sob demanda, backup a cada 30min, apenas arquivos .md principais sincronizados, pasta reasoning temporária com limpeza automát

668 lines 29.6 kB
/** * Advanced Coding Reasoning Tool v2.0 * Specialized AI reasoning tool for coding problems, debugging, and software development * * Based on Chain-of-Thought prompting and interactive debugging best practices * Focuses specifically on coding-related reasoning and problem-solving */ import * as fs from 'fs/promises'; import * as path from 'path'; import * as os from 'os'; export class CodingReasoningTool { currentSession = null; sessionFile = null; currentProjectName = null; constructor() { // tempDir será definido dinamicamente baseado no projectName } getTempDir(projectName) { const memoryBankRoot = process.env.MEMORY_BANK_ROOT || path.join(os.homedir(), 'memory-bank'); return path.join(memoryBankRoot, projectName, 'reasoning'); } /** * Execute a coding reasoning action */ async executeAction(action, args, projectName) { if (!projectName) { throw new Error('projectName é obrigatório para operações de reasoning'); } this.currentProjectName = projectName; await this.ensureTempDir(projectName); switch (action) { case 'analyze-code': return await this.analyzeCode(args.code, args.language, args.context, args.problem); case 'debug-step-by-step': return await this.debugStepByStep(args.code, args.errorMessage, args.language, args.context); case 'architecture-reasoning': return await this.architectureReasoning(args.context, args.requirements, args.constraints); case 'performance-analysis': return await this.performanceAnalysis(args.code, args.language, args.context); case 'refactor-planning': return await this.refactorPlanning(args.code, args.language, args.goals, args.constraints); case 'test-strategy': return await this.testStrategy(args.code, args.language, args.requirements); case 'error-investigation': return await this.errorInvestigation(args.errorMessage, args.code, args.language, args.context); case 'code-review': return await this.codeReview(args.code, args.language, args.standards, args.context); case 'cleanup': await this.cleanup(); return { message: 'Arquivos de reasoning temporários removidos.' }; case 'status': return await this.getStatus(); default: throw new Error(`Ação desconhecida: ${action}`); } } /** * Analyze code using Chain-of-Thought reasoning */ async analyzeCode(code, language, context, problem) { const sessionId = this.generateSessionId(); const steps = []; // Step 1: Initial Code Observation steps.push({ stepNumber: 1, type: 'observation', content: `Analyzing ${language} code. Let me examine the structure and identify key components.`, codeSnippet: code, reasoning: 'First, I need to understand what this code is trying to do and identify its main components.', confidence: 8, timestamp: Date.now() }); // Step 2: Problem Identification if (problem) { steps.push({ stepNumber: 2, type: 'hypothesis', content: `The stated problem is: ${problem}. Let me analyze how the current code relates to this issue.`, reasoning: 'Understanding the specific problem helps focus the analysis on relevant code sections.', confidence: 7, timestamp: Date.now() }); } // Step 3: Code Structure Analysis steps.push({ stepNumber: steps.length + 1, type: 'investigation', content: this.analyzeCodeStructure(code, language), reasoning: 'Breaking down the code structure helps identify potential issues and improvement opportunities.', confidence: 8, timestamp: Date.now() }); // Step 4: Logic Flow Analysis steps.push({ stepNumber: steps.length + 1, type: 'investigation', content: this.analyzeLogicFlow(code, language), reasoning: 'Understanding the logic flow reveals potential bugs, edge cases, and optimization opportunities.', confidence: 7, timestamp: Date.now() }); // Step 5: Generate Solutions const solutions = this.generateSolutions(code, language, problem, context); steps.push({ stepNumber: steps.length + 1, type: 'conclusion', content: `Based on my analysis, I've identified ${solutions.length} potential solutions.`, reasoning: 'Synthesizing the analysis into actionable solutions.', confidence: 8, timestamp: Date.now() }); const result = { id: sessionId, problem: problem || 'Code analysis', language, steps, finalSolution: solutions[0] || 'No solution generated', alternativeSolutions: solutions.slice(1), testCases: this.generateTestCases(code, language), performanceNotes: this.generatePerformanceNotes(code, language), securityConsiderations: this.generateSecurityNotes(code, language), confidence: this.calculateOverallConfidence(steps), created: Date.now() }; await this.saveSession(sessionId, result); return result; } /** * Step-by-step debugging using interactive reasoning */ async debugStepByStep(code, errorMessage, language, context) { const sessionId = this.generateSessionId(); const steps = []; const hypothesis = []; const investigation = []; // Step 1: Error Analysis steps.push({ stepNumber: 1, action: 'examine', description: 'Examining the error message to understand the type of issue', findings: this.analyzeErrorMessage(errorMessage, language), nextAction: 'trace', confidence: 8 }); // Step 2: Code Tracing steps.push({ stepNumber: 2, action: 'trace', description: 'Tracing through the code execution path to locate the error source', findings: this.traceCodeExecution(code, errorMessage, language), nextAction: 'isolate', confidence: 7 }); // Step 3: Problem Isolation steps.push({ stepNumber: 3, action: 'isolate', description: 'Isolating the problematic code section', findings: this.isolateProblem(code, errorMessage, language), nextAction: 'test', confidence: 8 }); // Step 4: Hypothesis Generation hypothesis.push(...this.generateDebugHypothesis(code, errorMessage, language)); // Step 5: Solution Testing steps.push({ stepNumber: 4, action: 'test', description: 'Testing potential solutions', findings: this.testSolutions(code, errorMessage, language, hypothesis), nextAction: 'verify', confidence: 7 }); // Step 6: Solution Verification const solution = this.generateDebugSolution(code, errorMessage, language, hypothesis); steps.push({ stepNumber: 5, action: 'verify', description: 'Verifying the proposed solution', findings: `Solution verified: ${solution}`, confidence: 8 }); const debugSession = { id: sessionId, code, errorMessage, language, steps, hypothesis, investigation, solution, created: Date.now() }; await this.saveSession(sessionId, debugSession); return debugSession; } /** * Architecture reasoning for design decisions */ async architectureReasoning(context, requirements, constraints) { const sessionId = this.generateSessionId(); const designOptions = this.generateDesignOptions(context, requirements, constraints); const recommendation = this.selectBestDesign(designOptions, requirements, constraints); const tradeoffs = this.analyzeTradeoffs(designOptions, recommendation); const analysis = { id: sessionId, context, requirements, constraints, designOptions, recommendation, tradeoffs, created: Date.now() }; await this.saveSession(sessionId, analysis); return analysis; } /** * Performance analysis with reasoning */ async performanceAnalysis(code, language, context) { return await this.analyzeCode(code, language, context, 'Performance optimization analysis'); } /** * Refactoring planning with step-by-step reasoning */ async refactorPlanning(code, language, goals, constraints) { const problem = `Refactoring planning with goals: ${goals.join(', ')}`; return await this.analyzeCode(code, language, constraints?.join('; '), problem); } /** * Test strategy reasoning */ async testStrategy(code, language, requirements) { const problem = `Test strategy development for requirements: ${requirements.join(', ')}`; return await this.analyzeCode(code, language, undefined, problem); } /** * Error investigation with detailed reasoning */ async errorInvestigation(errorMessage, code, language, context) { return await this.debugStepByStep(code, errorMessage, language, context); } /** * Code review with reasoning */ async codeReview(code, language, standards, context) { const problem = `Code review analysis${standards ? ` against standards: ${standards.join(', ')}` : ''}`; return await this.analyzeCode(code, language, context, problem); } // Helper methods for code analysis analyzeCodeStructure(code, language) { const lines = code.split('\n').length; const functions = (code.match(/function|def |class |interface |type /g) || []).length; const complexity = this.estimateComplexity(code); return `Code structure analysis:\n` + `- Lines of code: ${lines}\n` + `- Functions/Classes/Types: ${functions}\n` + `- Estimated complexity: ${complexity}/10\n` + `- Language: ${language}`; } analyzeLogicFlow(code, language) { const conditionals = (code.match(/if|else|switch|case|while|for/g) || []).length; const loops = (code.match(/while|for|forEach|map|filter|reduce/g) || []).length; const asyncOps = (code.match(/async|await|Promise|then|catch/g) || []).length; return `Logic flow analysis:\n` + `- Conditional statements: ${conditionals}\n` + `- Loop constructs: ${loops}\n` + `- Async operations: ${asyncOps}\n` + `- Control flow complexity: ${this.calculateControlFlowComplexity(code)}/10`; } generateSolutions(code, language, problem, context) { const solutions = []; // Basic solution based on common patterns solutions.push(this.generateBasicSolution(code, language, problem)); // Performance-optimized solution solutions.push(this.generateOptimizedSolution(code, language)); // Maintainable solution solutions.push(this.generateMaintainableSolution(code, language)); return solutions.filter(s => s.length > 0); } generateTestCases(code, language) { const testCases = []; // Generate basic test cases based on code analysis testCases.push('Test with valid input data'); testCases.push('Test with edge cases (empty, null, boundary values)'); testCases.push('Test error handling scenarios'); if (code.includes('async') || code.includes('Promise')) { testCases.push('Test async operations and error handling'); } return testCases; } generatePerformanceNotes(code, language) { const notes = []; if (code.includes('for') || code.includes('while')) { notes.push('Consider loop optimization and early termination conditions'); } if (code.includes('map') || code.includes('filter')) { notes.push('Consider combining array operations to reduce iterations'); } if (language === 'javascript' && code.includes('JSON.parse')) { notes.push('Consider caching parsed JSON for repeated use'); } return notes; } generateSecurityNotes(code, language) { const notes = []; if (code.includes('eval') || code.includes('innerHTML')) { notes.push('SECURITY: Avoid eval() and innerHTML for user input - XSS risk'); } if (code.includes('password') || code.includes('token')) { notes.push('SECURITY: Ensure sensitive data is properly encrypted and not logged'); } if (code.includes('fetch') || code.includes('axios')) { notes.push('SECURITY: Validate and sanitize all API inputs and outputs'); } return notes; } // Debug helper methods analyzeErrorMessage(errorMessage, language) { const errorType = this.identifyErrorType(errorMessage); const commonCauses = this.getCommonCauses(errorType, language); return `Error analysis:\n` + `- Error type: ${errorType}\n` + `- Common causes: ${commonCauses.join(', ')}\n` + `- Language-specific considerations: ${this.getLanguageSpecificNotes(language, errorType)}`; } traceCodeExecution(code, errorMessage, language) { const errorLine = this.extractErrorLine(errorMessage); const executionPath = this.traceExecutionPath(code, errorLine); return `Code execution trace:\n` + `- Error likely occurs at: ${errorLine || 'Unknown line'}\n` + `- Execution path: ${executionPath}\n` + `- Variables in scope: ${this.identifyVariablesInScope(code, errorLine)}`; } isolateProblem(code, errorMessage, language) { const problematicSection = this.identifyProblematicSection(code, errorMessage); const dependencies = this.identifyDependencies(problematicSection); return `Problem isolation:\n` + `- Problematic code section identified\n` + `- Dependencies: ${dependencies.join(', ')}\n` + `- Isolated issue: ${this.describeIsolatedIssue(problematicSection, errorMessage)}`; } generateDebugHypothesis(code, errorMessage, language) { const hypotheses = []; const errorType = this.identifyErrorType(errorMessage); switch (errorType) { case 'TypeError': hypotheses.push('Variable is undefined or null when accessed'); hypotheses.push('Incorrect data type being used in operation'); hypotheses.push('Missing property or method on object'); break; case 'ReferenceError': hypotheses.push('Variable used before declaration'); hypotheses.push('Typo in variable or function name'); hypotheses.push('Scope issue - variable not accessible'); break; case 'SyntaxError': hypotheses.push('Missing or extra brackets/parentheses'); hypotheses.push('Incorrect syntax for language constructs'); hypotheses.push('Invalid character or encoding issue'); break; default: hypotheses.push('Logic error in algorithm implementation'); hypotheses.push('Incorrect assumptions about data structure'); hypotheses.push('Race condition or timing issue'); } return hypotheses; } testSolutions(code, errorMessage, language, hypotheses) { const testedSolutions = []; hypotheses.forEach((hypothesis, index) => { const solution = this.generateSolutionForHypothesis(hypothesis, code, language); const testResult = this.evaluateSolution(solution, code, errorMessage); testedSolutions.push(`Hypothesis ${index + 1}: ${testResult}`); }); return `Solution testing results:\n${testedSolutions.join('\n')}`; } generateDebugSolution(code, errorMessage, language, hypotheses) { const bestHypothesis = this.selectBestHypothesis(hypotheses, code, errorMessage); return this.generateSolutionForHypothesis(bestHypothesis, code, language); } // Architecture helper methods generateDesignOptions(context, requirements, constraints) { const options = []; // Monolithic option options.push({ name: 'Monolithic Architecture', description: 'Single deployable unit with all functionality', pros: ['Simple deployment', 'Easy debugging', 'Good for small teams'], cons: ['Scaling challenges', 'Technology lock-in', 'Large codebase'], complexity: 3, maintainability: 6, performance: 7, scalability: 4 }); // Microservices option options.push({ name: 'Microservices Architecture', description: 'Distributed system with independent services', pros: ['Independent scaling', 'Technology diversity', 'Team autonomy'], cons: ['Network complexity', 'Data consistency', 'Operational overhead'], complexity: 8, maintainability: 7, performance: 6, scalability: 9 }); // Modular monolith option options.push({ name: 'Modular Monolith', description: 'Well-structured monolith with clear module boundaries', pros: ['Balanced complexity', 'Easy refactoring', 'Good performance'], cons: ['Shared database', 'Deployment coupling', 'Module discipline required'], complexity: 5, maintainability: 8, performance: 8, scalability: 6 }); return options; } selectBestDesign(options, requirements, constraints) { // Simple scoring algorithm based on requirements and constraints let bestOption = options[0]; let bestScore = 0; if (!bestOption) { return 'No design options available'; } options.forEach(option => { let score = 0; // Score based on requirements if (requirements.includes('scalability')) score += option.scalability; if (requirements.includes('performance')) score += option.performance; if (requirements.includes('maintainability')) score += option.maintainability; if (requirements.includes('simplicity')) score += (10 - option.complexity); // Adjust for constraints if (constraints.includes('small team') && option.complexity > 6) score -= 3; if (constraints.includes('tight budget') && option.complexity > 7) score -= 5; if (score > bestScore) { bestScore = score; bestOption = option; } }); return `Recommended: ${bestOption.name} - ${bestOption.description}`; } analyzeTradeoffs(options, recommendation) { const tradeoffs = []; const recommended = options.find(o => recommendation.includes(o.name)); if (!recommended) return tradeoffs; if (recommended.complexity > 6) { tradeoffs.push('Higher complexity requires more experienced team'); } if (recommended.scalability < 7) { tradeoffs.push('May need architecture changes for high scale'); } if (recommended.performance < 7) { tradeoffs.push('Performance optimization may be needed'); } return tradeoffs; } // Utility methods estimateComplexity(code) { const lines = code.split('\n').length; const functions = (code.match(/function|def |class /g) || []).length; const conditionals = (code.match(/if|else|switch|while|for/g) || []).length; const complexity = Math.min(10, Math.floor((lines / 10) + (functions * 0.5) + (conditionals * 0.3))); return Math.max(1, complexity); } calculateControlFlowComplexity(code) { const branches = (code.match(/if|else if|case|catch/g) || []).length; const loops = (code.match(/while|for|forEach/g) || []).length; const complexity = Math.min(10, branches + loops); return Math.max(1, complexity); } calculateOverallConfidence(steps) { if (steps.length === 0) return 5; const avgConfidence = steps.reduce((sum, step) => sum + step.confidence, 0) / steps.length; return Math.round(avgConfidence); } identifyErrorType(errorMessage) { if (errorMessage.includes('TypeError')) return 'TypeError'; if (errorMessage.includes('ReferenceError')) return 'ReferenceError'; if (errorMessage.includes('SyntaxError')) return 'SyntaxError'; if (errorMessage.includes('RangeError')) return 'RangeError'; if (errorMessage.includes('URIError')) return 'URIError'; return 'Unknown'; } getCommonCauses(errorType, language) { const causes = { 'TypeError': ['Null/undefined access', 'Wrong data type', 'Missing method'], 'ReferenceError': ['Undeclared variable', 'Scope issue', 'Typo in name'], 'SyntaxError': ['Missing brackets', 'Invalid syntax', 'Encoding issue'], 'Unknown': ['Logic error', 'Runtime condition', 'External dependency'] }; return causes[errorType] || causes['Unknown'] || []; } getLanguageSpecificNotes(language, errorType) { const notes = { 'javascript': { 'TypeError': 'Check for undefined variables and null prototype chains', 'ReferenceError': 'Verify variable hoisting and closure scope', 'SyntaxError': 'Check for missing semicolons and bracket matching' }, 'python': { 'TypeError': 'Check data types and method availability', 'ReferenceError': 'Verify variable scope and imports', 'SyntaxError': 'Check indentation and syntax rules' } }; return notes[language]?.[errorType] || 'Check language-specific documentation'; } extractErrorLine(errorMessage) { const lineMatch = errorMessage.match(/line (\d+)|:(\d+):|at line (\d+)/); return lineMatch ? (lineMatch[1] || lineMatch[2] || lineMatch[3] || null) : null; } traceExecutionPath(code, errorLine) { if (!errorLine) return 'Unable to determine execution path'; const lines = code.split('\n'); const lineNum = parseInt(errorLine) - 1; if (lineNum >= 0 && lineNum < lines.length && lines[lineNum]) { return `Execution reaches line ${errorLine}: ${lines[lineNum].trim()}`; } return 'Error line not found in provided code'; } identifyVariablesInScope(code, errorLine) { // Simplified variable identification const variables = code.match(/(?:let|const|var)\s+(\w+)/g) || []; return variables.map(v => v.split(' ')[1]).join(', ') || 'No variables identified'; } identifyProblematicSection(code, errorMessage) { const errorLine = this.extractErrorLine(errorMessage); if (!errorLine) return code; const lines = code.split('\n'); const lineNum = parseInt(errorLine) - 1; const start = Math.max(0, lineNum - 2); const end = Math.min(lines.length, lineNum + 3); return lines.slice(start, end).join('\n'); } identifyDependencies(codeSection) { const imports = codeSection.match(/import\s+.+from\s+['"](.+)['"]/g) || []; const requires = codeSection.match(/require\(['"](.+)['"]\)/g) || []; return [...imports, ...requires].map(dep => { const match = dep.match(/['"](.+)['"]/); return match ? match[1] : dep; }).filter((dep) => dep !== undefined); } describeIsolatedIssue(codeSection, errorMessage) { const errorType = this.identifyErrorType(errorMessage); return `${errorType} in isolated code section - likely caused by the specific operation in this block`; } generateSolutionForHypothesis(hypothesis, code, language) { // Generate specific solutions based on hypothesis if (hypothesis.includes('undefined') || hypothesis.includes('null')) { return 'Add null/undefined checks before accessing properties or methods'; } if (hypothesis.includes('scope')) { return 'Move variable declaration to appropriate scope or use proper closure'; } if (hypothesis.includes('syntax')) { return 'Review syntax rules for ' + language + ' and fix structural issues'; } return 'Apply defensive programming practices and add error handling'; } evaluateSolution(solution, code, errorMessage) { // Simplified solution evaluation const errorType = this.identifyErrorType(errorMessage); if (solution.includes('null') && errorType === 'TypeError') { return 'High likelihood - addresses null/undefined access'; } if (solution.includes('scope') && errorType === 'ReferenceError') { return 'High likelihood - addresses scope issues'; } if (solution.includes('syntax') && errorType === 'SyntaxError') { return 'High likelihood - addresses syntax problems'; } return 'Medium likelihood - general solution approach'; } selectBestHypothesis(hypotheses, code, errorMessage) { // Select the most likely hypothesis based on error type and code analysis const errorType = this.identifyErrorType(errorMessage); for (const hypothesis of hypotheses) { if (errorType === 'TypeError' && hypothesis.includes('undefined')) { return hypothesis; } if (errorType === 'ReferenceError' && hypothesis.includes('scope')) { return hypothesis; } if (errorType === 'SyntaxError' && hypothesis.includes('syntax')) { return hypothesis; } } return hypotheses[0] || 'Unknown issue - requires manual investigation'; } generateBasicSolution(code, language, problem) { if (problem?.includes('performance')) { return 'Optimize loops, reduce complexity, and cache repeated calculations'; } if (problem?.includes('bug') || problem?.includes('error')) { return 'Add error handling, input validation, and defensive programming practices'; } return 'Improve code structure, add comments, and follow best practices for ' + language; } generateOptimizedSolution(code, language) { return 'Apply performance optimizations: algorithm improvements, caching, and efficient data structures'; } generateMaintainableSolution(code, language) { return 'Refactor for maintainability: extract functions, improve naming, add documentation, and reduce coupling'; } generateSessionId() { return `coding-reasoning-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`; } async ensureTempDir(projectName) { const tempDir = this.getTempDir(projectName); try { await fs.access(tempDir); } catch { await fs.mkdir(tempDir, { recursive: true }); } } async saveSession(sessionId, data) { if (!this.currentProjectName) { throw new Error('projectName não definido'); } const tempDir = this.getTempDir(this.currentProjectName); const filePath = path.join(tempDir, `${sessionId}.json`); await fs.writeFile(filePath, JSON.stringify(data, null, 2)); this.currentSession = sessionId; this.sessionFile = filePath; } async cleanup() { if (!this.currentProjectName) { return; // Não há projeto ativo para limpar } try { const tempDir = this.getTempDir(this.currentProjectName); const files = await fs.readdir(tempDir); for (const file of files) { await fs.unlink(path.join(tempDir, file)); } } catch { // Directory might not exist } } async getStatus() { return { active: this.currentSession !== null, session: this.currentSession, file: this.sessionFile }; } } //# sourceMappingURL=reasoning-tool.js.map