diff --git a/.claude-flow/sessions/pair/pair_1755097338012.json b/.claude-flow/sessions/pair/pair_1755097338012.json new file mode 100644 index 0000000000..0f91f078e6 --- /dev/null +++ b/.claude-flow/sessions/pair/pair_1755097338012.json @@ -0,0 +1,11 @@ +{ + "id": "pair_1755097338012", + "guidanceMode": "beginner", + "autoFix": true, + "threshold": 0.9, + "startTime": "2025-08-13T15:02:18.012Z", + "status": "active", + "verificationScores": [], + "fixHistory": [], + "iterations": 0 +} \ No newline at end of file diff --git a/.claude/checkpoints/1755097287.json b/.claude/checkpoints/1755097287.json new file mode 100644 index 0000000000..878bfe6af8 --- /dev/null +++ b/.claude/checkpoints/1755097287.json @@ -0,0 +1 @@ +{"branch": "checkpoint/pre-edit-20250813-150127", "file": "/workspaces/claude-code-flow/src/cli/simple-commands/pair-working.js", "timestamp": "2025-08-13T15:01:27Z", "type": "pre-edit", "original_branch": "alpha-89"} diff --git a/.claude/checkpoints/1755097289.json b/.claude/checkpoints/1755097289.json new file mode 100644 index 0000000000..6dd3514261 --- /dev/null +++ b/.claude/checkpoints/1755097289.json @@ -0,0 +1 @@ +{"tag": "checkpoint-20250813-150129", "file": "/workspaces/claude-code-flow/src/cli/simple-commands/pair-working.js", "timestamp": "2025-08-13T15:01:29Z", "type": "post-edit", "branch": "alpha-89", "diff_summary": " .claude-flow/metrics/performance.json | 2 +- .claude-flow/metrics/system-metrics.json | 108 ++++ .claude-flow/metrics/task-metrics.json | 6 +- .claude/checkpoints/task-1755097018.json | 1 + claude-flow-wiki | 0 src/cli/simple-commands/pair-working.js | 839 +++++++++++++++++++++++++++++++ 6 files changed, 952 insertions(+), 4 deletions(-) "} diff --git a/src/cli/simple-commands/pair-enhanced.backup.js b/src/cli/simple-commands/pair-enhanced.backup.js new file mode 100644 index 0000000000..dee871371c --- /dev/null +++ b/src/cli/simple-commands/pair-enhanced.backup.js @@ -0,0 +1,1066 @@ +/** + * Enhanced Pair Programming with Advanced Guidance Options + * Includes recursive auto-fix, intelligent suggestions, and multiple guidance modes + */ + +import fs from 'fs/promises'; +import path from 'path'; +import { spawn, exec } from 'child_process'; +import { promisify } from 'util'; +import readline from 'readline'; + +const execAsync = promisify(exec); + +// Guidance modes for different expertise levels and preferences +const GUIDANCE_MODES = { + beginner: { + name: 'Beginner', + description: 'Detailed explanations and step-by-step guidance', + verbosity: 'high', + suggestions: 'frequent', + explanations: 'detailed', + examples: true, + autoFix: true, + threshold: 0.90 + }, + intermediate: { + name: 'Intermediate', + description: 'Balanced guidance with helpful suggestions', + verbosity: 'medium', + suggestions: 'moderate', + explanations: 'concise', + examples: false, + autoFix: true, + threshold: 0.95 + }, + expert: { + name: 'Expert', + description: 'Minimal guidance, focus on efficiency', + verbosity: 'low', + suggestions: 'on-demand', + explanations: 'minimal', + examples: false, + autoFix: false, + threshold: 0.98 + }, + mentor: { + name: 'Mentor', + description: 'Teaching mode with best practices and patterns', + verbosity: 'high', + suggestions: 'educational', + explanations: 'teaching', + examples: true, + autoFix: false, + threshold: 0.95 + }, + strict: { + name: 'Strict', + description: 'Enforces best practices and high standards', + verbosity: 'medium', + suggestions: 'critical', + explanations: 'rules-based', + examples: false, + autoFix: true, + threshold: 0.98 + } +}; + +// Suggestion categories +const SUGGESTIONS = { + performance: [ + 'Consider using memoization for expensive computations', + 'Use lazy loading for better initial load times', + 'Implement virtualization for large lists', + 'Consider using Web Workers for CPU-intensive tasks', + 'Optimize bundle size with code splitting' + ], + security: [ + 'Sanitize user input to prevent XSS attacks', + 'Use parameterized queries to prevent SQL injection', + 'Implement proper authentication and authorization', + 'Store sensitive data in environment variables', + 'Enable CORS only for trusted domains' + ], + testing: [ + 'Add unit tests for critical business logic', + 'Include edge cases in your test suite', + 'Aim for at least 80% code coverage', + 'Write integration tests for API endpoints', + 'Add E2E tests for critical user flows' + ], + architecture: [ + 'Consider using dependency injection for better testability', + 'Implement the Repository pattern for data access', + 'Use event-driven architecture for loose coupling', + 'Apply SOLID principles to your class design', + 'Consider microservices for independent scaling' + ], + codeQuality: [ + 'Extract complex logic into well-named functions', + 'Use descriptive variable names', + 'Add JSDoc comments for public APIs', + 'Reduce cyclomatic complexity', + 'Follow consistent naming conventions' + ] +}; + +class EnhancedPairSession { + constructor(options = {}) { + this.sessionId = `pair_${Date.now()}`; + this.guidanceMode = options.guidance || 'intermediate'; + this.guidance = GUIDANCE_MODES[this.guidanceMode]; + this.verify = options.verify !== false; + this.autoFix = options.autoFix ?? this.guidance.autoFix; + this.threshold = options.threshold || this.guidance.threshold; + this.maxIterations = options.maxIterations || 5; + this.suggestions = options.suggestions !== false; + this.patterns = options.patterns !== false; + this.bestPractices = options.bestPractices !== false; + this.realtime = options.realtime !== false; + this.startTime = new Date(); + this.status = 'active'; + this.verificationScores = []; + this.fixHistory = []; + this.suggestionHistory = []; + this.currentIteration = 0; + this.rl = null; + } + + async start() { + await this.saveSession(); + this.showWelcome(); + + // Show initial guidance based on mode + this.showGuidance(); + + if (this.verify && this.autoFix) { + console.log('\n๐Ÿ”„ Auto-Fix Mode Enabled'); + await this.recursiveFixLoop(); + } else if (this.verify) { + await this.runVerification(); + } + + // Start real-time monitoring if enabled + if (this.realtime) { + this.startRealtimeMonitoring(); + } + + await this.startInteractiveMode(); + } + + showWelcome() { + console.log('\n๐Ÿš€ Enhanced Pair Programming Session'); + console.log('โ”'.repeat(50)); + console.log(`Session ID: ${this.sessionId}`); + console.log(`Guidance Mode: ${this.guidance.name}`); + console.log(`Description: ${this.guidance.description}`); + console.log(`Verification: ${this.verify ? 'โœ… Enabled' : 'โŒ Disabled'}`); + console.log(`Auto-Fix: ${this.autoFix ? 'โœ… Enabled' : 'โŒ Disabled'}`); + console.log(`Target Threshold: ${this.threshold}`); + console.log('โ”'.repeat(50)); + } + + showGuidance() { + console.log('\n๐Ÿ“š Guidance Settings:'); + console.log(` โ€ข Mode: ${this.guidance.name}`); + console.log(` โ€ข Verbosity: ${this.guidance.verbosity}`); + console.log(` โ€ข Suggestions: ${this.guidance.suggestions}`); + console.log(` โ€ข Explanations: ${this.guidance.explanations}`); + + if (this.guidanceMode === 'beginner') { + console.log('\n๐Ÿ’ก Beginner Tips:'); + console.log(' โ€ข Use /explain for detailed explanations'); + console.log(' โ€ข Use /pattern to see design patterns'); + console.log(' โ€ข Use /best for best practices'); + console.log(' โ€ข Use /why to understand decisions'); + } else if (this.guidanceMode === 'mentor') { + console.log('\n๐Ÿ‘จโ€๐Ÿซ Mentor Mode Active:'); + console.log(' โ€ข Focus on learning and understanding'); + console.log(' โ€ข Detailed explanations for each decision'); + console.log(' โ€ข Best practices and patterns highlighted'); + console.log(' โ€ข Interactive Q&A available'); + } + } + + /** + * Provide intelligent suggestions based on current context + */ + async provideSuggestions(category = 'all') { + console.log('\n๐Ÿ’ก Intelligent Suggestions:'); + console.log('โ”'.repeat(40)); + + // Analyze current code context + const context = await this.analyzeContext(); + + if (category === 'all' || category === 'immediate') { + console.log('\n๐ŸŽฏ Immediate Actions:'); + const immediateSuggestions = await this.getImmediateSuggestions(context); + immediateSuggestions.forEach((s, i) => { + console.log(` ${i + 1}. ${s}`); + }); + } + + if (category === 'all' || category === 'improvements') { + console.log('\n๐Ÿ“ˆ Improvement Opportunities:'); + const improvements = this.getImprovementSuggestions(context); + improvements.forEach((s, i) => { + console.log(` ${i + 1}. ${s}`); + }); + } + + if (category === 'all' || category === 'patterns') { + console.log('\n๐Ÿ—๏ธ Pattern Suggestions:'); + const patterns = this.getPatternSuggestions(context); + patterns.forEach((s, i) => { + console.log(` ${i + 1}. ${s}`); + }); + } + + // Record suggestions in history + this.suggestionHistory.push({ + timestamp: new Date(), + category, + count: context.suggestions?.length || 0 + }); + } + + /** + * Analyze current code context + */ + async analyzeContext() { + const context = { + hasTypeErrors: false, + hasLintErrors: false, + hasBuildErrors: false, + hasTestFailures: false, + coverage: 0, + complexity: 0, + suggestions: [] + }; + + try { + // Check for various issues + const { stdout: typeCheck } = await execAsync('npm run typecheck 2>&1 || true'); + context.hasTypeErrors = typeCheck.toLowerCase().includes('error'); + + const { stdout: lintCheck } = await execAsync('npm run lint 2>&1 || true'); + context.hasLintErrors = lintCheck.toLowerCase().includes('error'); + + // Analyze complexity (simplified) + context.complexity = this.estimateComplexity(); + + } catch (error) { + console.log(' โš ๏ธ Context analysis partial:', error.message); + } + + return context; + } + + /** + * Get immediate action suggestions based on context + */ + async getImmediateSuggestions(context) { + const suggestions = []; + + if (context.hasTypeErrors) { + suggestions.push('Fix TypeScript errors - Run: npm run typecheck'); + } + + if (context.hasLintErrors) { + suggestions.push('Fix linting issues - Run: npm run lint --fix'); + } + + if (context.coverage < 80) { + suggestions.push('Increase test coverage - Add unit tests for uncovered code'); + } + + if (context.complexity > 10) { + suggestions.push('Reduce complexity - Extract functions and simplify logic'); + } + + if (suggestions.length === 0) { + suggestions.push('Code looks good! Consider adding documentation or tests'); + } + + return suggestions; + } + + /** + * Get improvement suggestions + */ + getImprovementSuggestions(context) { + const suggestions = []; + + // Based on guidance mode, provide different suggestions + if (this.guidanceMode === 'beginner') { + suggestions.push(...SUGGESTIONS.codeQuality.slice(0, 3)); + } else if (this.guidanceMode === 'mentor') { + suggestions.push(...SUGGESTIONS.architecture.slice(0, 2)); + suggestions.push(...SUGGESTIONS.testing.slice(0, 2)); + } else if (this.guidanceMode === 'strict') { + suggestions.push(...SUGGESTIONS.security.slice(0, 2)); + suggestions.push(...SUGGESTIONS.performance.slice(0, 2)); + } else { + // Mix of suggestions for intermediate/expert + suggestions.push(SUGGESTIONS.performance[0]); + suggestions.push(SUGGESTIONS.testing[0]); + } + + return suggestions; + } + + /** + * Get pattern suggestions + */ + getPatternSuggestions(context) { + const patterns = []; + + if (context.complexity > 10) { + patterns.push('Consider Strategy pattern for complex conditional logic'); + patterns.push('Use Factory pattern for object creation'); + } + + if (context.hasTypeErrors) { + patterns.push('Implement Builder pattern for complex object construction'); + } + + patterns.push('Apply Dependency Injection for better testability'); + + return patterns.slice(0, 3); + } + + /** + * Estimate code complexity (simplified) + */ + estimateComplexity() { + // In a real implementation, this would analyze actual code + return Math.floor(Math.random() * 15) + 5; + } + + /** + * Explain a concept or decision + */ + explainConcept(topic) { + const explanations = { + 'auto-fix': ` +๐Ÿ”„ Auto-Fix Explanation: +The auto-fix system uses recursive stream-chaining to: +1. Identify issues through verification +2. Create targeted fix chains for each issue type +3. Apply fixes automatically using npm scripts and Claude AI +4. Re-verify until the threshold is met +5. Provide a complete audit trail of changes`, + + 'verification': ` +๐Ÿ” Verification Explanation: +Verification runs three weighted checks: +1. TypeScript (40%) - Type safety and compilation +2. Linting (30%) - Code style and potential bugs +3. Build (30%) - Production build success +Scores are calculated based on error/warning counts.`, + + 'patterns': ` +๐Ÿ—๏ธ Design Patterns Explanation: +Design patterns are reusable solutions to common problems: +โ€ข Strategy: Encapsulate algorithms +โ€ข Factory: Centralize object creation +โ€ข Observer: Event-driven communication +โ€ข Repository: Abstract data access +โ€ข Dependency Injection: Loose coupling`, + + 'testing': ` +๐Ÿงช Testing Best Practices: +โ€ข Unit tests: Test individual functions +โ€ข Integration tests: Test component interactions +โ€ข E2E tests: Test complete user flows +โ€ข Coverage: Aim for 80%+ code coverage +โ€ข TDD: Write tests before implementation` + }; + + console.log(explanations[topic] || `\n๐Ÿ“– No explanation available for: ${topic}`); + } + + /** + * Show best practices for current context + */ + showBestPractices(area = 'general') { + console.log(`\nโœจ Best Practices - ${area}:`); + console.log('โ”'.repeat(40)); + + const practices = { + general: [ + 'โ€ข Follow SOLID principles', + 'โ€ข Write self-documenting code', + 'โ€ข Keep functions small and focused', + 'โ€ข Use meaningful variable names', + 'โ€ข Handle errors gracefully' + ], + typescript: [ + 'โ€ข Use strict mode', + 'โ€ข Avoid any type', + 'โ€ข Define interfaces for contracts', + 'โ€ข Use generics for reusability', + 'โ€ข Enable strict null checks' + ], + react: [ + 'โ€ข Use functional components', + 'โ€ข Implement proper key props', + 'โ€ข Memoize expensive computations', + 'โ€ข Handle loading and error states', + 'โ€ข Use custom hooks for logic' + ], + testing: [ + 'โ€ข Test behavior, not implementation', + 'โ€ข Use descriptive test names', + 'โ€ข Follow AAA pattern (Arrange, Act, Assert)', + 'โ€ข Mock external dependencies', + 'โ€ข Test edge cases' + ], + security: [ + 'โ€ข Never trust user input', + 'โ€ข Use environment variables for secrets', + 'โ€ข Implement proper authentication', + 'โ€ข Enable HTTPS everywhere', + 'โ€ข Regular dependency updates' + ] + }; + + const selectedPractices = practices[area] || practices.general; + selectedPractices.forEach(practice => console.log(practice)); + } + + /** + * Interactive Q&A for learning + */ + async askQuestion(question) { + console.log('\nโ“ Question:', question); + + // Simulate AI response based on guidance mode + if (this.guidanceMode === 'beginner' || this.guidanceMode === 'mentor') { + console.log('\n๐Ÿ“š Detailed Answer:'); + console.log('โ”'.repeat(40)); + + // Provide detailed, educational answer + if (question.toLowerCase().includes('why')) { + console.log('This is important because:'); + console.log('1. It improves code maintainability'); + console.log('2. It reduces potential bugs'); + console.log('3. It follows industry best practices'); + console.log('\nExample implementation:'); + console.log('```javascript'); + console.log('// Example code here'); + console.log('```'); + } + } else { + console.log('\n๐Ÿ’ก Quick Answer:'); + console.log('Consider checking the documentation or using /explain for details.'); + } + } + + /** + * Start real-time monitoring + */ + startRealtimeMonitoring() { + console.log('\n๐Ÿ‘๏ธ Real-time Monitoring Active'); + console.log(' โ€ข File changes will trigger suggestions'); + console.log(' โ€ข Continuous quality tracking'); + console.log(' โ€ข Automatic issue detection'); + + // In production, this would use file watchers + // For demo, we'll simulate periodic checks + this.monitoringInterval = setInterval(async () => { + if (this.status === 'active') { + const context = await this.analyzeContext(); + if (context.hasTypeErrors || context.hasLintErrors) { + console.log('\nโš ๏ธ Issues detected! Use /suggest for recommendations'); + } + } + }, 60000); // Check every minute + } + + /** + * Enhanced recursive fix loop with guidance + */ + async recursiveFixLoop() { + console.log('\n๐Ÿš€ Starting Intelligent Auto-Fix Loop...'); + console.log('โ”'.repeat(50)); + + let score = 0; + this.currentIteration = 0; + + while (score < this.threshold && this.currentIteration < this.maxIterations) { + this.currentIteration++; + console.log(`\n๐Ÿ“ Iteration ${this.currentIteration}/${this.maxIterations}`); + + // Provide guidance based on mode + if (this.guidanceMode === 'beginner' || this.guidanceMode === 'mentor') { + console.log('๐Ÿ’ก Analyzing code quality and searching for improvements...'); + } + + // Run verification + const verificationResult = await this.runVerification(); + score = verificationResult.score; + + if (score >= this.threshold) { + console.log(`\nโœจ Success! Target threshold achieved: ${score.toFixed(2)}`); + if (this.guidanceMode === 'mentor') { + console.log('๐Ÿ“š Learning Point: Consistent quality checks ensure maintainable code'); + } + break; + } + + // Identify and fix issues + const issues = this.identifyIssues(verificationResult); + + if (this.guidanceMode === 'beginner') { + console.log('\n๐Ÿ“– Understanding the issues:'); + issues.forEach(issue => { + console.log(` โ€ข ${issue.type}: ${this.explainIssueType(issue.type)}`); + }); + } + + if (issues.length > 0) { + console.log('\n๐Ÿ”— Creating intelligent fix chain...'); + await this.createFixChain(issues); + } + + // Provide encouragement based on progress + if (this.currentIteration > 1 && score > verificationResult.previousScore) { + console.log('๐Ÿ“ˆ Good progress! Score improved by ' + + ((score - verificationResult.previousScore) * 100).toFixed(1) + '%'); + } + + await new Promise(resolve => setTimeout(resolve, 2000)); + } + + this.showFixSummary(); + } + + /** + * Explain issue types for learning + */ + explainIssueType(type) { + const explanations = { + 'lint': 'Code style and potential bug issues', + 'typecheck': 'Type safety and compilation errors', + 'build': 'Production build configuration problems', + 'test': 'Failing tests or insufficient coverage' + }; + return explanations[type] || 'General code quality issue'; + } + + /** + * Show comprehensive fix summary + */ + showFixSummary() { + console.log('\n๐Ÿ“Š Auto-Fix Summary:'); + console.log('โ”'.repeat(50)); + console.log(` Total Iterations: ${this.currentIteration}`); + console.log(` Fixes Applied: ${this.fixHistory.length}`); + + if (this.verificationScores.length > 1) { + const initial = this.verificationScores[0].score; + const final = this.verificationScores[this.verificationScores.length - 1].score; + console.log(` Initial Score: ${initial.toFixed(2)}`); + console.log(` Final Score: ${final.toFixed(2)}`); + console.log(` Improvement: +${((final - initial) * 100).toFixed(1)}%`); + } + + if (this.guidanceMode === 'mentor' || this.guidanceMode === 'beginner') { + console.log('\n๐Ÿ“š Key Learnings:'); + console.log(' โ€ข Automated tools can fix many common issues'); + console.log(' โ€ข Regular verification prevents technical debt'); + console.log(' โ€ข Consistent standards improve team productivity'); + } + } + + async startInteractiveMode() { + this.rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, + prompt: '\n๐Ÿ’ป pair> ' + }); + + console.log('\n๐Ÿ’ก Interactive mode active. Type /help for commands.\n'); + + this.showCommands(); + this.rl.prompt(); + + this.rl.on('line', async (line) => { + const input = line.trim(); + + if (input.startsWith('/')) { + await this.handleCommand(input); + } else if (input.startsWith('?')) { + // Quick question format + await this.askQuestion(input.substring(1).trim()); + } else if (input) { + console.log('๐Ÿค– AI: Processing your input...'); + // Provide contextual response based on guidance mode + if (this.guidanceMode === 'beginner') { + console.log('๐Ÿ’ก Tip: Use /help to see available commands'); + } + } + + this.rl.prompt(); + }); + + this.rl.on('close', () => { + this.end(); + }); + } + + showCommands() { + console.log('\n๐Ÿ“ Session Commands:'); + console.log(' /help - Show all commands'); + console.log(' /verify - Run verification'); + console.log(' /autofix - Start auto-fix loop'); + console.log(' /suggest - Get suggestions'); + console.log(' /explain - Explain concept'); + console.log(' /best - Show best practices'); + console.log(' /pattern - Pattern suggestions'); + console.log(' /why - Explain decisions'); + console.log(' /status - Session status'); + console.log(' /metrics - Quality metrics'); + console.log(' /guidance - Change guidance mode'); + console.log(' /test - Run tests'); + console.log(' /commit - Commit with verification'); + console.log(' /end - End session'); + console.log('\n๐Ÿ’ก Quick tips:'); + console.log(' โ€ข Type ? followed by question for Q&A'); + console.log(' โ€ข Use Tab for command completion'); + } + + async handleCommand(command) { + const [cmd, ...args] = command.split(' '); + const arg = args.join(' '); + + switch (cmd) { + case '/help': + this.showCommands(); + break; + + case '/verify': + await this.runVerification(); + break; + + case '/autofix': + await this.recursiveFixLoop(); + break; + + case '/suggest': + await this.provideSuggestions(arg || 'all'); + break; + + case '/explain': + this.explainConcept(arg || 'auto-fix'); + break; + + case '/best': + this.showBestPractices(arg || 'general'); + break; + + case '/pattern': + const context = await this.analyzeContext(); + const patterns = this.getPatternSuggestions(context); + console.log('\n๐Ÿ—๏ธ Pattern Recommendations:'); + patterns.forEach((p, i) => console.log(` ${i + 1}. ${p}`)); + break; + + case '/why': + console.log('\n๐Ÿ“– Understanding the "Why":'); + console.log('Every suggestion is based on:'); + console.log(' โ€ข Industry best practices'); + console.log(' โ€ข Code maintainability'); + console.log(' โ€ข Team productivity'); + console.log(' โ€ข Bug prevention'); + break; + + case '/guidance': + await this.changeGuidanceMode(arg); + break; + + case '/status': + await this.showStatus(); + break; + + case '/metrics': + this.showMetrics(); + break; + + case '/test': + await this.runTests(); + break; + + case '/commit': + await this.commitWithVerification(); + break; + + case '/end': + case '/exit': + await this.end(); + process.exit(0); + break; + + default: + console.log(`โŒ Unknown command: ${cmd}`); + console.log('๐Ÿ’ก Type /help for available commands'); + } + } + + async changeGuidanceMode(newMode) { + if (!newMode) { + console.log('\n๐Ÿ“š Available Guidance Modes:'); + Object.entries(GUIDANCE_MODES).forEach(([key, mode]) => { + console.log(` โ€ข ${key}: ${mode.description}`); + }); + return; + } + + if (GUIDANCE_MODES[newMode]) { + this.guidanceMode = newMode; + this.guidance = GUIDANCE_MODES[newMode]; + console.log(`\nโœ… Guidance mode changed to: ${this.guidance.name}`); + this.showGuidance(); + } else { + console.log(`โŒ Unknown mode: ${newMode}`); + } + } + + async showStatus() { + const duration = Math.floor((Date.now() - this.startTime) / 1000 / 60); + + console.log('\n๐Ÿ“Š Session Status'); + console.log('โ”'.repeat(40)); + console.log(`Session ID: ${this.sessionId}`); + console.log(`Duration: ${duration} minutes`); + console.log(`Guidance Mode: ${this.guidance.name}`); + console.log(`Auto-Fix: ${this.autoFix ? 'Enabled' : 'Disabled'}`); + console.log(`Iterations: ${this.currentIteration}`); + console.log(`Fixes Applied: ${this.fixHistory.length}`); + console.log(`Suggestions Given: ${this.suggestionHistory.length}`); + + if (this.verificationScores.length > 0) { + const latest = this.verificationScores[this.verificationScores.length - 1]; + console.log(`Latest Score: ${latest.score.toFixed(2)}`); + } + } + + showMetrics() { + console.log('\n๐Ÿ“ˆ Quality Metrics'); + console.log('โ”'.repeat(40)); + + if (this.verificationScores.length > 0) { + console.log('\nScore Progression:'); + this.verificationScores.forEach((v, i) => { + const bar = 'โ–ˆ'.repeat(Math.floor(v.score * 20)); + console.log(` ${i + 1}. ${bar} ${v.score.toFixed(2)}`); + }); + + if (this.verificationScores.length > 1) { + const first = this.verificationScores[0].score; + const last = this.verificationScores[this.verificationScores.length - 1].score; + const improvement = ((last - first) * 100).toFixed(1); + console.log(`\n Total Improvement: +${improvement}%`); + } + } + + if (this.suggestionHistory.length > 0) { + console.log(`\n๐Ÿ“ Suggestions Provided: ${this.suggestionHistory.length}`); + } + } + + // Include all the auto-fix methods from the previous implementation + async runVerification() { + console.log('\n๐Ÿ” Running verification check...'); + + const checks = [ + { + name: 'Type Check', + command: 'npm run typecheck 2>&1 || true', + weight: 0.4 + }, + { + name: 'Linting', + command: 'npm run lint 2>&1 || true', + weight: 0.3 + }, + { + name: 'Build', + command: 'npm run build 2>&1 || true', + weight: 0.3 + } + ]; + + const results = []; + let totalScore = 0; + let totalWeight = 0; + + for (const check of checks) { + try { + const { stdout, stderr } = await execAsync(check.command); + const output = stdout + stderr; + + let score = 1.0; + if (output.toLowerCase().includes('error')) { + const errorCount = (output.match(/error/gi) || []).length; + score = Math.max(0.2, 1.0 - (errorCount * 0.1)); + } else if (output.toLowerCase().includes('warning')) { + const warningCount = (output.match(/warning/gi) || []).length; + score = Math.max(0.7, 1.0 - (warningCount * 0.05)); + } + + totalScore += score * check.weight; + totalWeight += check.weight; + + const icon = score >= 0.8 ? 'โœ…' : score >= 0.5 ? 'โš ๏ธ' : 'โŒ'; + console.log(` ${icon} ${check.name}: ${score.toFixed(2)}`); + + results.push({ + name: check.name, + score, + output: output.slice(0, 200) + }); + } catch (error) { + console.log(` โŒ ${check.name}: 0.00 (failed)`); + results.push({ name: check.name, score: 0, error: error.message }); + totalWeight += check.weight; + } + } + + const averageScore = totalWeight > 0 ? totalScore / totalWeight : 0; + + console.log(`\n๐Ÿ“Š Verification Score: ${averageScore.toFixed(2)}/${this.threshold}`); + + const verificationResult = { + score: averageScore, + results, + timestamp: new Date(), + iteration: this.currentIteration, + previousScore: this.verificationScores.length > 0 + ? this.verificationScores[this.verificationScores.length - 1].score + : 0 + }; + + this.verificationScores.push(verificationResult); + + // Provide guidance based on score and mode + if (averageScore < this.threshold) { + if (this.guidanceMode === 'beginner') { + console.log('\n๐Ÿ’ก Don\'t worry! Use /autofix to automatically improve the score'); + } else if (this.guidanceMode === 'mentor') { + console.log('\n๐Ÿ“š Learning opportunity: Each issue fixed improves code quality'); + } + } + + return verificationResult; + } + + // Include other methods from previous implementation... + identifyIssues(verificationResult) { + const issues = []; + + if (verificationResult.results) { + for (const check of verificationResult.results) { + if (check.score < 0.8) { + issues.push({ + type: check.name.toLowerCase().replace(' check', '').replace(' ', ''), + description: `Score: ${check.score.toFixed(2)}`, + severity: check.score < 0.5 ? 'high' : 'medium' + }); + } + } + } + + return issues; + } + + async createFixChain(issues) { + // Implementation from previous version + console.log(' ๐Ÿ”ง Creating fix chains for identified issues...'); + // ... rest of implementation + } + + async runTests() { + console.log('\n๐Ÿงช Running tests...'); + try { + const { stdout } = await execAsync('npm test 2>&1 || true'); + const passed = stdout.includes('PASS'); + console.log(` ${passed ? 'โœ…' : 'โŒ'} Tests ${passed ? 'passed' : 'failed'}`); + + if (this.guidanceMode === 'beginner' && !passed) { + console.log(' ๐Ÿ’ก Tip: Check test output for specific failures'); + } + + return passed; + } catch (error) { + console.log(' โŒ Test execution failed:', error.message); + return false; + } + } + + async commitWithVerification() { + const result = await this.runVerification(); + + if (result.score >= this.threshold) { + console.log('โœ… Verification passed! Ready to commit.'); + console.log('\n๐Ÿ“ Suggested commit message:'); + console.log(' "feat: improved code quality to ' + result.score.toFixed(2) + ' threshold"'); + } else { + console.log('โŒ Verification failed!'); + if (this.autoFix) { + console.log('๐Ÿ’ก Run /autofix to automatically fix issues'); + } else { + console.log('๐Ÿ’ก Run /suggest for improvement recommendations'); + } + } + } + + async end() { + console.log('\n๐Ÿ›‘ Ending enhanced pair programming session...'); + + if (this.rl) this.rl.close(); + if (this.monitoringInterval) clearInterval(this.monitoringInterval); + + this.status = 'completed'; + await this.saveSession(); + + const duration = Math.floor((Date.now() - this.startTime) / 1000 / 60); + console.log('\nโœจ Session Complete!'); + console.log('โ”'.repeat(40)); + console.log(`Duration: ${duration} minutes`); + console.log(`Guidance Mode: ${this.guidance.name}`); + console.log(`Total Fixes: ${this.fixHistory.length}`); + console.log(`Suggestions Given: ${this.suggestionHistory.length}`); + + if (this.verificationScores.length > 0) { + const final = this.verificationScores[this.verificationScores.length - 1]; + console.log(`Final Score: ${final.score.toFixed(2)}`); + } + + if (this.guidanceMode === 'mentor' || this.guidanceMode === 'beginner') { + console.log('\n๐Ÿ“š Session Summary:'); + console.log(' โ€ข Key concepts covered'); + console.log(' โ€ข Best practices applied'); + console.log(' โ€ข Improvements achieved'); + console.log('\n๐Ÿ’ก Keep learning and improving!'); + } + + console.log('\n๐Ÿ‘‹ Thanks for using enhanced pair programming!\n'); + } + + async saveSession() { + const sessionPath = '.claude-flow/sessions/pair'; + await fs.mkdir(sessionPath, { recursive: true }); + + const sessionData = { + id: this.sessionId, + guidanceMode: this.guidanceMode, + verify: this.verify, + autoFix: this.autoFix, + threshold: this.threshold, + startTime: this.startTime.toISOString(), + status: this.status, + verificationScores: this.verificationScores, + fixHistory: this.fixHistory, + suggestionHistory: this.suggestionHistory, + iterations: this.currentIteration + }; + + await fs.writeFile( + path.join(sessionPath, `${this.sessionId}.json`), + JSON.stringify(sessionData, null, 2) + ); + } +} + +async function pairCommand(args = [], flags = {}) { + console.log('\n๐Ÿ‘ฅ Enhanced Pair Programming'); + console.log('โ”'.repeat(50)); + + if (flags.help || args.includes('--help')) { + showHelp(); + return; + } + + if (flags.start) { + const session = new EnhancedPairSession({ + guidance: flags.guidance || flags.mode || 'intermediate', + verify: flags.verify !== false, + autoFix: flags.autofix || flags.fix || false, + threshold: parseFloat(flags.threshold) || undefined, + maxIterations: parseInt(flags.iterations) || 5, + suggestions: flags.suggestions !== false, + patterns: flags.patterns !== false, + bestPractices: flags.best !== false, + realtime: flags.realtime || false + }); + + return await session.start(); + } + + showHelp(); +} + +function showHelp() { + console.log(` +๐Ÿ“š USAGE: + claude-flow pair [options] + +โš™๏ธ OPTIONS: + --start Start enhanced pair session + --guidance Guidance mode (beginner|intermediate|expert|mentor|strict) + --verify Enable verification + --autofix Enable recursive auto-fix + --threshold Target threshold (default varies by mode) + --iterations Max fix iterations (default: 5) + --realtime Enable real-time monitoring + --suggestions Enable intelligent suggestions + --patterns Show design pattern recommendations + --best Show best practices + --help Show this help + +๐ŸŽฏ GUIDANCE MODES: + beginner - Detailed explanations, step-by-step guidance + intermediate - Balanced guidance with helpful suggestions + expert - Minimal guidance, focus on efficiency + mentor - Teaching mode with best practices + strict - Enforces high standards and best practices + +๐Ÿ’ก FEATURES: + โ€ข Intelligent suggestions based on context + โ€ข Recursive auto-fix with stream chaining + โ€ข Best practices and design patterns + โ€ข Interactive Q&A (type ? followed by question) + โ€ข Real-time monitoring and feedback + โ€ข Multiple guidance modes for all skill levels + โ€ข Comprehensive metrics and history + +๐Ÿ“ EXAMPLES: + # Beginner mode with auto-fix + claude-flow pair --start --guidance beginner --autofix + + # Mentor mode for learning + claude-flow pair --start --guidance mentor --verify + + # Strict mode for production + claude-flow pair --start --guidance strict --autofix --threshold 0.98 + + # Expert mode with minimal guidance + claude-flow pair --start --guidance expert --verify + +๐ŸŽ“ INTERACTIVE COMMANDS: + /suggest - Get contextual suggestions + /explain - Explain concepts + /best - Show best practices + /pattern - Design pattern recommendations + /why - Understand decisions + /guidance - Change guidance mode + ? - Ask questions + +๐Ÿ“š Documentation: + .claude/commands/pair/README.md +`); +} + +export default pairCommand; \ No newline at end of file diff --git a/src/cli/simple-commands/pair.js b/src/cli/simple-commands/pair.js index dee871371c..fa7542fb90 100644 --- a/src/cli/simple-commands/pair.js +++ b/src/cli/simple-commands/pair.js @@ -1,6 +1,6 @@ /** - * Enhanced Pair Programming with Advanced Guidance Options - * Includes recursive auto-fix, intelligent suggestions, and multiple guidance modes + * Enhanced Pair Programming with Working Auto-Fix + * This version actually applies fixes using real commands */ import fs from 'fs/promises'; @@ -11,117 +11,63 @@ import readline from 'readline'; const execAsync = promisify(exec); -// Guidance modes for different expertise levels and preferences +// Guidance mode configurations const GUIDANCE_MODES = { beginner: { - name: 'Beginner', - description: 'Detailed explanations and step-by-step guidance', verbosity: 'high', suggestions: 'frequent', explanations: 'detailed', - examples: true, autoFix: true, - threshold: 0.90 + threshold: 0.9, + description: 'Detailed explanations and step-by-step guidance' }, intermediate: { - name: 'Intermediate', - description: 'Balanced guidance with helpful suggestions', verbosity: 'medium', - suggestions: 'moderate', + suggestions: 'balanced', explanations: 'concise', - examples: false, autoFix: true, - threshold: 0.95 + threshold: 0.95, + description: 'Balanced guidance with key explanations' }, expert: { - name: 'Expert', - description: 'Minimal guidance, focus on efficiency', verbosity: 'low', - suggestions: 'on-demand', - explanations: 'minimal', - examples: false, - autoFix: false, - threshold: 0.98 + suggestions: 'minimal', + explanations: 'brief', + autoFix: true, + threshold: 0.98, + description: 'Minimal guidance, maximum efficiency' }, mentor: { - name: 'Mentor', - description: 'Teaching mode with best practices and patterns', verbosity: 'high', suggestions: 'educational', explanations: 'teaching', - examples: true, autoFix: false, - threshold: 0.95 + threshold: 0.9, + description: 'Educational focus with learning opportunities' }, strict: { - name: 'Strict', - description: 'Enforces best practices and high standards', verbosity: 'medium', - suggestions: 'critical', - explanations: 'rules-based', - examples: false, + suggestions: 'quality-focused', + explanations: 'standards', autoFix: true, - threshold: 0.98 + threshold: 0.99, + description: 'Enforces highest code quality standards' } }; -// Suggestion categories -const SUGGESTIONS = { - performance: [ - 'Consider using memoization for expensive computations', - 'Use lazy loading for better initial load times', - 'Implement virtualization for large lists', - 'Consider using Web Workers for CPU-intensive tasks', - 'Optimize bundle size with code splitting' - ], - security: [ - 'Sanitize user input to prevent XSS attacks', - 'Use parameterized queries to prevent SQL injection', - 'Implement proper authentication and authorization', - 'Store sensitive data in environment variables', - 'Enable CORS only for trusted domains' - ], - testing: [ - 'Add unit tests for critical business logic', - 'Include edge cases in your test suite', - 'Aim for at least 80% code coverage', - 'Write integration tests for API endpoints', - 'Add E2E tests for critical user flows' - ], - architecture: [ - 'Consider using dependency injection for better testability', - 'Implement the Repository pattern for data access', - 'Use event-driven architecture for loose coupling', - 'Apply SOLID principles to your class design', - 'Consider microservices for independent scaling' - ], - codeQuality: [ - 'Extract complex logic into well-named functions', - 'Use descriptive variable names', - 'Add JSDoc comments for public APIs', - 'Reduce cyclomatic complexity', - 'Follow consistent naming conventions' - ] -}; - -class EnhancedPairSession { +class WorkingPairSession { constructor(options = {}) { this.sessionId = `pair_${Date.now()}`; this.guidanceMode = options.guidance || 'intermediate'; this.guidance = GUIDANCE_MODES[this.guidanceMode]; - this.verify = options.verify !== false; this.autoFix = options.autoFix ?? this.guidance.autoFix; this.threshold = options.threshold || this.guidance.threshold; this.maxIterations = options.maxIterations || 5; - this.suggestions = options.suggestions !== false; - this.patterns = options.patterns !== false; - this.bestPractices = options.bestPractices !== false; - this.realtime = options.realtime !== false; + this.verify = options.verify || false; this.startTime = new Date(); this.status = 'active'; this.verificationScores = []; this.fixHistory = []; - this.suggestionHistory = []; this.currentIteration = 0; this.rl = null; } @@ -130,359 +76,25 @@ class EnhancedPairSession { await this.saveSession(); this.showWelcome(); - // Show initial guidance based on mode - this.showGuidance(); - if (this.verify && this.autoFix) { console.log('\n๐Ÿ”„ Auto-Fix Mode Enabled'); + console.log(' โ€ข Will automatically fix issues until threshold is met'); + console.log(` โ€ข Maximum iterations: ${this.maxIterations}`); + console.log(` โ€ข Target threshold: ${this.threshold}`); + await this.recursiveFixLoop(); } else if (this.verify) { await this.runVerification(); } - // Start real-time monitoring if enabled - if (this.realtime) { - this.startRealtimeMonitoring(); - } - await this.startInteractiveMode(); } - showWelcome() { - console.log('\n๐Ÿš€ Enhanced Pair Programming Session'); - console.log('โ”'.repeat(50)); - console.log(`Session ID: ${this.sessionId}`); - console.log(`Guidance Mode: ${this.guidance.name}`); - console.log(`Description: ${this.guidance.description}`); - console.log(`Verification: ${this.verify ? 'โœ… Enabled' : 'โŒ Disabled'}`); - console.log(`Auto-Fix: ${this.autoFix ? 'โœ… Enabled' : 'โŒ Disabled'}`); - console.log(`Target Threshold: ${this.threshold}`); - console.log('โ”'.repeat(50)); - } - - showGuidance() { - console.log('\n๐Ÿ“š Guidance Settings:'); - console.log(` โ€ข Mode: ${this.guidance.name}`); - console.log(` โ€ข Verbosity: ${this.guidance.verbosity}`); - console.log(` โ€ข Suggestions: ${this.guidance.suggestions}`); - console.log(` โ€ข Explanations: ${this.guidance.explanations}`); - - if (this.guidanceMode === 'beginner') { - console.log('\n๐Ÿ’ก Beginner Tips:'); - console.log(' โ€ข Use /explain for detailed explanations'); - console.log(' โ€ข Use /pattern to see design patterns'); - console.log(' โ€ข Use /best for best practices'); - console.log(' โ€ข Use /why to understand decisions'); - } else if (this.guidanceMode === 'mentor') { - console.log('\n๐Ÿ‘จโ€๐Ÿซ Mentor Mode Active:'); - console.log(' โ€ข Focus on learning and understanding'); - console.log(' โ€ข Detailed explanations for each decision'); - console.log(' โ€ข Best practices and patterns highlighted'); - console.log(' โ€ข Interactive Q&A available'); - } - } - /** - * Provide intelligent suggestions based on current context - */ - async provideSuggestions(category = 'all') { - console.log('\n๐Ÿ’ก Intelligent Suggestions:'); - console.log('โ”'.repeat(40)); - - // Analyze current code context - const context = await this.analyzeContext(); - - if (category === 'all' || category === 'immediate') { - console.log('\n๐ŸŽฏ Immediate Actions:'); - const immediateSuggestions = await this.getImmediateSuggestions(context); - immediateSuggestions.forEach((s, i) => { - console.log(` ${i + 1}. ${s}`); - }); - } - - if (category === 'all' || category === 'improvements') { - console.log('\n๐Ÿ“ˆ Improvement Opportunities:'); - const improvements = this.getImprovementSuggestions(context); - improvements.forEach((s, i) => { - console.log(` ${i + 1}. ${s}`); - }); - } - - if (category === 'all' || category === 'patterns') { - console.log('\n๐Ÿ—๏ธ Pattern Suggestions:'); - const patterns = this.getPatternSuggestions(context); - patterns.forEach((s, i) => { - console.log(` ${i + 1}. ${s}`); - }); - } - - // Record suggestions in history - this.suggestionHistory.push({ - timestamp: new Date(), - category, - count: context.suggestions?.length || 0 - }); - } - - /** - * Analyze current code context - */ - async analyzeContext() { - const context = { - hasTypeErrors: false, - hasLintErrors: false, - hasBuildErrors: false, - hasTestFailures: false, - coverage: 0, - complexity: 0, - suggestions: [] - }; - - try { - // Check for various issues - const { stdout: typeCheck } = await execAsync('npm run typecheck 2>&1 || true'); - context.hasTypeErrors = typeCheck.toLowerCase().includes('error'); - - const { stdout: lintCheck } = await execAsync('npm run lint 2>&1 || true'); - context.hasLintErrors = lintCheck.toLowerCase().includes('error'); - - // Analyze complexity (simplified) - context.complexity = this.estimateComplexity(); - - } catch (error) { - console.log(' โš ๏ธ Context analysis partial:', error.message); - } - - return context; - } - - /** - * Get immediate action suggestions based on context - */ - async getImmediateSuggestions(context) { - const suggestions = []; - - if (context.hasTypeErrors) { - suggestions.push('Fix TypeScript errors - Run: npm run typecheck'); - } - - if (context.hasLintErrors) { - suggestions.push('Fix linting issues - Run: npm run lint --fix'); - } - - if (context.coverage < 80) { - suggestions.push('Increase test coverage - Add unit tests for uncovered code'); - } - - if (context.complexity > 10) { - suggestions.push('Reduce complexity - Extract functions and simplify logic'); - } - - if (suggestions.length === 0) { - suggestions.push('Code looks good! Consider adding documentation or tests'); - } - - return suggestions; - } - - /** - * Get improvement suggestions - */ - getImprovementSuggestions(context) { - const suggestions = []; - - // Based on guidance mode, provide different suggestions - if (this.guidanceMode === 'beginner') { - suggestions.push(...SUGGESTIONS.codeQuality.slice(0, 3)); - } else if (this.guidanceMode === 'mentor') { - suggestions.push(...SUGGESTIONS.architecture.slice(0, 2)); - suggestions.push(...SUGGESTIONS.testing.slice(0, 2)); - } else if (this.guidanceMode === 'strict') { - suggestions.push(...SUGGESTIONS.security.slice(0, 2)); - suggestions.push(...SUGGESTIONS.performance.slice(0, 2)); - } else { - // Mix of suggestions for intermediate/expert - suggestions.push(SUGGESTIONS.performance[0]); - suggestions.push(SUGGESTIONS.testing[0]); - } - - return suggestions; - } - - /** - * Get pattern suggestions - */ - getPatternSuggestions(context) { - const patterns = []; - - if (context.complexity > 10) { - patterns.push('Consider Strategy pattern for complex conditional logic'); - patterns.push('Use Factory pattern for object creation'); - } - - if (context.hasTypeErrors) { - patterns.push('Implement Builder pattern for complex object construction'); - } - - patterns.push('Apply Dependency Injection for better testability'); - - return patterns.slice(0, 3); - } - - /** - * Estimate code complexity (simplified) - */ - estimateComplexity() { - // In a real implementation, this would analyze actual code - return Math.floor(Math.random() * 15) + 5; - } - - /** - * Explain a concept or decision - */ - explainConcept(topic) { - const explanations = { - 'auto-fix': ` -๐Ÿ”„ Auto-Fix Explanation: -The auto-fix system uses recursive stream-chaining to: -1. Identify issues through verification -2. Create targeted fix chains for each issue type -3. Apply fixes automatically using npm scripts and Claude AI -4. Re-verify until the threshold is met -5. Provide a complete audit trail of changes`, - - 'verification': ` -๐Ÿ” Verification Explanation: -Verification runs three weighted checks: -1. TypeScript (40%) - Type safety and compilation -2. Linting (30%) - Code style and potential bugs -3. Build (30%) - Production build success -Scores are calculated based on error/warning counts.`, - - 'patterns': ` -๐Ÿ—๏ธ Design Patterns Explanation: -Design patterns are reusable solutions to common problems: -โ€ข Strategy: Encapsulate algorithms -โ€ข Factory: Centralize object creation -โ€ข Observer: Event-driven communication -โ€ข Repository: Abstract data access -โ€ข Dependency Injection: Loose coupling`, - - 'testing': ` -๐Ÿงช Testing Best Practices: -โ€ข Unit tests: Test individual functions -โ€ข Integration tests: Test component interactions -โ€ข E2E tests: Test complete user flows -โ€ข Coverage: Aim for 80%+ code coverage -โ€ข TDD: Write tests before implementation` - }; - - console.log(explanations[topic] || `\n๐Ÿ“– No explanation available for: ${topic}`); - } - - /** - * Show best practices for current context - */ - showBestPractices(area = 'general') { - console.log(`\nโœจ Best Practices - ${area}:`); - console.log('โ”'.repeat(40)); - - const practices = { - general: [ - 'โ€ข Follow SOLID principles', - 'โ€ข Write self-documenting code', - 'โ€ข Keep functions small and focused', - 'โ€ข Use meaningful variable names', - 'โ€ข Handle errors gracefully' - ], - typescript: [ - 'โ€ข Use strict mode', - 'โ€ข Avoid any type', - 'โ€ข Define interfaces for contracts', - 'โ€ข Use generics for reusability', - 'โ€ข Enable strict null checks' - ], - react: [ - 'โ€ข Use functional components', - 'โ€ข Implement proper key props', - 'โ€ข Memoize expensive computations', - 'โ€ข Handle loading and error states', - 'โ€ข Use custom hooks for logic' - ], - testing: [ - 'โ€ข Test behavior, not implementation', - 'โ€ข Use descriptive test names', - 'โ€ข Follow AAA pattern (Arrange, Act, Assert)', - 'โ€ข Mock external dependencies', - 'โ€ข Test edge cases' - ], - security: [ - 'โ€ข Never trust user input', - 'โ€ข Use environment variables for secrets', - 'โ€ข Implement proper authentication', - 'โ€ข Enable HTTPS everywhere', - 'โ€ข Regular dependency updates' - ] - }; - - const selectedPractices = practices[area] || practices.general; - selectedPractices.forEach(practice => console.log(practice)); - } - - /** - * Interactive Q&A for learning - */ - async askQuestion(question) { - console.log('\nโ“ Question:', question); - - // Simulate AI response based on guidance mode - if (this.guidanceMode === 'beginner' || this.guidanceMode === 'mentor') { - console.log('\n๐Ÿ“š Detailed Answer:'); - console.log('โ”'.repeat(40)); - - // Provide detailed, educational answer - if (question.toLowerCase().includes('why')) { - console.log('This is important because:'); - console.log('1. It improves code maintainability'); - console.log('2. It reduces potential bugs'); - console.log('3. It follows industry best practices'); - console.log('\nExample implementation:'); - console.log('```javascript'); - console.log('// Example code here'); - console.log('```'); - } - } else { - console.log('\n๐Ÿ’ก Quick Answer:'); - console.log('Consider checking the documentation or using /explain for details.'); - } - } - - /** - * Start real-time monitoring - */ - startRealtimeMonitoring() { - console.log('\n๐Ÿ‘๏ธ Real-time Monitoring Active'); - console.log(' โ€ข File changes will trigger suggestions'); - console.log(' โ€ข Continuous quality tracking'); - console.log(' โ€ข Automatic issue detection'); - - // In production, this would use file watchers - // For demo, we'll simulate periodic checks - this.monitoringInterval = setInterval(async () => { - if (this.status === 'active') { - const context = await this.analyzeContext(); - if (context.hasTypeErrors || context.hasLintErrors) { - console.log('\nโš ๏ธ Issues detected! Use /suggest for recommendations'); - } - } - }, 60000); // Check every minute - } - - /** - * Enhanced recursive fix loop with guidance + * Working recursive fix loop that actually applies fixes */ async recursiveFixLoop() { - console.log('\n๐Ÿš€ Starting Intelligent Auto-Fix Loop...'); + console.log('\n๐Ÿš€ Starting Auto-Fix Loop with Real Fixes...'); console.log('โ”'.repeat(50)); let score = 0; @@ -492,44 +104,29 @@ Design patterns are reusable solutions to common problems: this.currentIteration++; console.log(`\n๐Ÿ“ Iteration ${this.currentIteration}/${this.maxIterations}`); - // Provide guidance based on mode - if (this.guidanceMode === 'beginner' || this.guidanceMode === 'mentor') { - console.log('๐Ÿ’ก Analyzing code quality and searching for improvements...'); - } - - // Run verification + // Step 1: Run verification const verificationResult = await this.runVerification(); score = verificationResult.score; if (score >= this.threshold) { - console.log(`\nโœจ Success! Target threshold achieved: ${score.toFixed(2)}`); - if (this.guidanceMode === 'mentor') { - console.log('๐Ÿ“š Learning Point: Consistent quality checks ensure maintainable code'); - } + console.log(`\nโœจ Threshold met! Score: ${score.toFixed(2)} >= ${this.threshold}`); break; } - // Identify and fix issues - const issues = this.identifyIssues(verificationResult); + // Step 2: Apply actual fixes + console.log('\n๐Ÿ”ง Applying fixes...'); + const fixResults = await this.applyRealFixes(verificationResult); - if (this.guidanceMode === 'beginner') { - console.log('\n๐Ÿ“– Understanding the issues:'); - issues.forEach(issue => { - console.log(` โ€ข ${issue.type}: ${this.explainIssueType(issue.type)}`); + if (fixResults.applied > 0) { + console.log(` โœ… Applied ${fixResults.applied} fixes`); + this.fixHistory.push({ + iteration: this.currentIteration, + fixes: fixResults.fixes, + timestamp: new Date() }); } - if (issues.length > 0) { - console.log('\n๐Ÿ”— Creating intelligent fix chain...'); - await this.createFixChain(issues); - } - - // Provide encouragement based on progress - if (this.currentIteration > 1 && score > verificationResult.previousScore) { - console.log('๐Ÿ“ˆ Good progress! Score improved by ' + - ((score - verificationResult.previousScore) * 100).toFixed(1) + '%'); - } - + // Wait before next iteration await new Promise(resolve => setTimeout(resolve, 2000)); } @@ -537,40 +134,268 @@ Design patterns are reusable solutions to common problems: } /** - * Explain issue types for learning + * Apply real fixes to the codebase */ - explainIssueType(type) { - const explanations = { - 'lint': 'Code style and potential bug issues', - 'typecheck': 'Type safety and compilation errors', - 'build': 'Production build configuration problems', - 'test': 'Failing tests or insufficient coverage' + async applyRealFixes(verificationResult) { + const fixResults = { + applied: 0, + fixes: [] }; - return explanations[type] || 'General code quality issue'; + + // Fix linting issues + if (verificationResult.lintScore < 0.8) { + console.log(' ๐Ÿ”ง Fixing linting issues...'); + try { + // First try auto-fix + const { stdout, stderr } = await execAsync('npm run lint -- --fix 2>&1 || true'); + + // Check if fixes were applied + const afterLint = await execAsync('npm run lint 2>&1 || true'); + const stillHasErrors = afterLint.stdout.toLowerCase().includes('error'); + + if (!stillHasErrors || afterLint.stdout.match(/error/gi)?.length < + stdout.match(/error/gi)?.length) { + console.log(' โœ… Applied ESLint auto-fixes'); + fixResults.applied++; + fixResults.fixes.push('ESLint auto-fix'); + } + + // If still has errors, try prettier + if (stillHasErrors) { + await execAsync('npx prettier --write "src/**/*.{js,ts,jsx,tsx}" 2>&1 || true'); + console.log(' โœ… Applied Prettier formatting'); + fixResults.applied++; + fixResults.fixes.push('Prettier formatting'); + } + } catch (error) { + console.log(' โš ๏ธ Some linting issues require manual fixes'); + } + } + + // Fix TypeScript issues + if (verificationResult.typeScore < 0.8) { + console.log(' ๐Ÿ”ง Analyzing TypeScript errors...'); + try { + const { stdout: tsErrors } = await execAsync('npm run typecheck 2>&1 || true'); + + // Common auto-fixable TypeScript issues + if (tsErrors.includes('Could not find a declaration file')) { + console.log(' ๐Ÿ“ฆ Installing missing type definitions...'); + const missingTypes = this.extractMissingTypes(tsErrors); + for (const pkg of missingTypes) { + try { + await execAsync(`npm install --save-dev @types/${pkg} 2>&1 || true`); + console.log(` โœ… Installed @types/${pkg}`); + fixResults.applied++; + fixResults.fixes.push(`Installed @types/${pkg}`); + } catch (e) { + // Type package might not exist + } + } + } + + // Add basic type annotations for 'any' types + if (tsErrors.includes("implicitly has an 'any' type")) { + console.log(' ๐Ÿ“ Adding type annotations for implicit any...'); + // This would need more complex AST manipulation in production + // For now, we'll just report it + console.log(' โ„น๏ธ Manual type annotations needed'); + } + } catch (error) { + console.log(' โš ๏ธ TypeScript fixes require manual intervention'); + } + } + + // Fix build issues + if (verificationResult.buildScore < 0.8) { + console.log(' ๐Ÿ”ง Fixing build configuration...'); + try { + // Clear cache and rebuild + await execAsync('rm -rf dist 2>&1 || true'); + await execAsync('npm run build 2>&1 || true'); + console.log(' โœ… Cleared cache and rebuilt'); + fixResults.applied++; + fixResults.fixes.push('Cache clear and rebuild'); + } catch (error) { + console.log(' โš ๏ธ Build issues may require configuration changes'); + } + } + + // Fix package issues + console.log(' ๐Ÿ”ง Checking for dependency issues...'); + try { + // Audit and fix vulnerabilities + const { stdout: auditOutput } = await execAsync('npm audit --json 2>&1 || true'); + const audit = JSON.parse(auditOutput); + + if (audit.metadata?.vulnerabilities?.total > 0) { + console.log(' ๐Ÿ›ก๏ธ Fixing security vulnerabilities...'); + await execAsync('npm audit fix 2>&1 || true'); + console.log(' โœ… Applied security fixes'); + fixResults.applied++; + fixResults.fixes.push('Security vulnerability fixes'); + } + + // Update outdated packages (only patch/minor) + await execAsync('npm update 2>&1 || true'); + console.log(' โœ… Updated dependencies'); + fixResults.applied++; + fixResults.fixes.push('Dependency updates'); + } catch (error) { + // Audit might fail, that's okay + } + + return fixResults; } /** - * Show comprehensive fix summary + * Extract missing type packages from TypeScript errors */ - showFixSummary() { - console.log('\n๐Ÿ“Š Auto-Fix Summary:'); - console.log('โ”'.repeat(50)); - console.log(` Total Iterations: ${this.currentIteration}`); - console.log(` Fixes Applied: ${this.fixHistory.length}`); + extractMissingTypes(tsErrors) { + const packages = new Set(); + const regex = /Could not find a declaration file for module '([^']+)'/g; + let match; - if (this.verificationScores.length > 1) { - const initial = this.verificationScores[0].score; - const final = this.verificationScores[this.verificationScores.length - 1].score; - console.log(` Initial Score: ${initial.toFixed(2)}`); - console.log(` Final Score: ${final.toFixed(2)}`); - console.log(` Improvement: +${((final - initial) * 100).toFixed(1)}%`); + while ((match = regex.exec(tsErrors)) !== null) { + const pkg = match[1]; + // Clean package name (remove @org/ prefix if present) + const cleanPkg = pkg.replace(/^@[^/]+\//, ''); + packages.add(cleanPkg); } - if (this.guidanceMode === 'mentor' || this.guidanceMode === 'beginner') { - console.log('\n๐Ÿ“š Key Learnings:'); - console.log(' โ€ข Automated tools can fix many common issues'); - console.log(' โ€ข Regular verification prevents technical debt'); - console.log(' โ€ข Consistent standards improve team productivity'); + return Array.from(packages); + } + + /** + * Run verification with detailed scoring + */ + async runVerification() { + console.log('\n๐Ÿ” Running verification check...'); + + const checks = [ + { + name: 'Type Check', + command: '(npm run typecheck) 2>&1 || true', + weight: 0.4, + scoreKey: 'typeScore' + }, + { + name: 'Linting', + command: '(npm run lint) 2>&1 || true', + weight: 0.3, + scoreKey: 'lintScore' + }, + { + name: 'Build', + command: '(npm run build) 2>&1 || true', + weight: 0.3, + scoreKey: 'buildScore' + } + ]; + + const results = {}; + let totalScore = 0; + let totalWeight = 0; + + for (const check of checks) { + try { + const { stdout, stderr } = await execAsync(check.command); + const output = stdout + stderr; + + // Calculate score based on actual errors/warnings + let score = 1.0; + const errorCount = (output.match(/error/gi) || []).length; + const warningCount = (output.match(/warning/gi) || []).length; + + if (errorCount > 0) { + score = Math.max(0.2, 1.0 - (errorCount * 0.1)); + } else if (warningCount > 0) { + score = Math.max(0.7, 1.0 - (warningCount * 0.05)); + } + + results[check.scoreKey] = score; + totalScore += score * check.weight; + totalWeight += check.weight; + + const icon = score >= 0.8 ? 'โœ…' : score >= 0.5 ? 'โš ๏ธ' : 'โŒ'; + console.log(` ${icon} ${check.name}: ${score.toFixed(2)}`); + } catch (error) { + console.log(` โŒ ${check.name}: 0.00 (failed)`); + results[check.scoreKey] = 0; + totalWeight += check.weight; + } + } + + const averageScore = totalWeight > 0 ? totalScore / totalWeight : 0; + console.log(`\n๐Ÿ“Š Verification Score: ${averageScore.toFixed(2)}/${this.threshold}`); + + if (this.guidanceMode === 'beginner' && averageScore < this.threshold) { + console.log('\n๐Ÿ’ก Don\'t worry! Use /autofix to automatically improve the score'); + } + + const verificationResult = { + score: averageScore, + ...results, + timestamp: new Date(), + iteration: this.currentIteration + }; + + this.verificationScores.push(verificationResult); + return verificationResult; + } + + showWelcome() { + console.log('\n๐Ÿš€ Enhanced Pair Programming Session'); + console.log('โ”'.repeat(50)); + console.log(`Session ID: ${this.sessionId}`); + console.log(`Guidance Mode: ${this.guidanceMode.charAt(0).toUpperCase() + this.guidanceMode.slice(1)}`); + console.log(`Description: ${this.guidance.description}`); + console.log(`Verification: ${this.verify ? 'โœ… Enabled' : 'โŒ Disabled'}`); + console.log(`Auto-Fix: ${this.autoFix ? 'โœ… Enabled' : 'โŒ Disabled'}`); + console.log(`Target Threshold: ${this.threshold}`); + console.log('โ”'.repeat(50)); + + if (this.guidanceMode === 'beginner') { + console.log('\n๐Ÿ“š Guidance Settings:'); + console.log(` โ€ข Mode: ${this.guidanceMode.charAt(0).toUpperCase() + this.guidanceMode.slice(1)}`); + console.log(` โ€ข Verbosity: ${this.guidance.verbosity}`); + console.log(` โ€ข Suggestions: ${this.guidance.suggestions}`); + console.log(` โ€ข Explanations: ${this.guidance.explanations}`); + + console.log('\n๐Ÿ’ก Beginner Tips:'); + console.log(' โ€ข Use /explain for detailed explanations'); + console.log(' โ€ข Use /pattern to see design patterns'); + console.log(' โ€ข Use /best for best practices'); + console.log(' โ€ข Use /why to understand decisions'); + } + } + + showFixSummary() { + if (this.fixHistory.length > 0) { + console.log('\n๐Ÿ“‹ Fix Summary:'); + console.log('โ”'.repeat(50)); + + let totalFixes = 0; + for (const entry of this.fixHistory) { + console.log(`\nIteration ${entry.iteration}:`); + for (const fix of entry.fixes) { + console.log(` โœ… ${fix}`); + totalFixes++; + } + } + + console.log('โ”'.repeat(50)); + console.log(`Total fixes applied: ${totalFixes}`); + console.log(`Iterations completed: ${this.currentIteration}`); + + if (this.verificationScores.length > 1) { + const first = this.verificationScores[0].score; + const last = this.verificationScores[this.verificationScores.length - 1].score; + const improvement = ((last - first) * 100).toFixed(1); + if (improvement > 0) { + console.log(`Score improvement: +${improvement}%`); + } + } } } @@ -592,14 +417,9 @@ Design patterns are reusable solutions to common problems: if (input.startsWith('/')) { await this.handleCommand(input); } else if (input.startsWith('?')) { - // Quick question format - await this.askQuestion(input.substring(1).trim()); + await this.askQuestion(input.slice(1).trim()); } else if (input) { - console.log('๐Ÿค– AI: Processing your input...'); - // Provide contextual response based on guidance mode - if (this.guidanceMode === 'beginner') { - console.log('๐Ÿ’ก Tip: Use /help to see available commands'); - } + console.log('๐Ÿค– Processing your input...'); } this.rl.prompt(); @@ -626,14 +446,16 @@ Design patterns are reusable solutions to common problems: console.log(' /test - Run tests'); console.log(' /commit - Commit with verification'); console.log(' /end - End session'); - console.log('\n๐Ÿ’ก Quick tips:'); - console.log(' โ€ข Type ? followed by question for Q&A'); - console.log(' โ€ข Use Tab for command completion'); + + if (this.guidanceMode === 'beginner') { + console.log('\n๐Ÿ’ก Quick tips:'); + console.log(' โ€ข Type ? followed by question for Q&A'); + console.log(' โ€ข Use Tab for command completion'); + } } async handleCommand(command) { const [cmd, ...args] = command.split(' '); - const arg = args.join(' '); switch (cmd) { case '/help': @@ -649,35 +471,23 @@ Design patterns are reusable solutions to common problems: break; case '/suggest': - await this.provideSuggestions(arg || 'all'); + await this.showSuggestions(); break; case '/explain': - this.explainConcept(arg || 'auto-fix'); + await this.explainConcept(args.join(' ')); break; case '/best': - this.showBestPractices(arg || 'general'); + this.showBestPractices(args[0] || 'general'); break; case '/pattern': - const context = await this.analyzeContext(); - const patterns = this.getPatternSuggestions(context); - console.log('\n๐Ÿ—๏ธ Pattern Recommendations:'); - patterns.forEach((p, i) => console.log(` ${i + 1}. ${p}`)); + this.showPatternSuggestions(); break; case '/why': - console.log('\n๐Ÿ“– Understanding the "Why":'); - console.log('Every suggestion is based on:'); - console.log(' โ€ข Industry best practices'); - console.log(' โ€ข Code maintainability'); - console.log(' โ€ข Team productivity'); - console.log(' โ€ข Bug prevention'); - break; - - case '/guidance': - await this.changeGuidanceMode(arg); + this.explainDecisions(); break; case '/status': @@ -688,6 +498,10 @@ Design patterns are reusable solutions to common problems: this.showMetrics(); break; + case '/guidance': + await this.changeGuidanceMode(args[0]); + break; + case '/test': await this.runTests(); break; @@ -708,25 +522,105 @@ Design patterns are reusable solutions to common problems: } } - async changeGuidanceMode(newMode) { - if (!newMode) { - console.log('\n๐Ÿ“š Available Guidance Modes:'); - Object.entries(GUIDANCE_MODES).forEach(([key, mode]) => { - console.log(` โ€ข ${key}: ${mode.description}`); - }); + async showSuggestions() { + console.log('\n๐Ÿ’ก Analyzing for suggestions...'); + + // Get latest verification scores + let latestScore = null; + if (this.verificationScores.length > 0) { + latestScore = this.verificationScores[this.verificationScores.length - 1]; + } else { + latestScore = await this.runVerification(); + } + + console.log('\n๐Ÿ“ Immediate Actions:'); + if (latestScore.lintScore < 0.8) { + console.log(' 1. Fix linting issues: Run /autofix or npm run lint --fix'); + } + if (latestScore.typeScore < 0.8) { + console.log(' 2. Fix TypeScript errors: Check npm run typecheck output'); + } + if (latestScore.buildScore < 0.8) { + console.log(' 3. Fix build issues: Clear cache and rebuild'); + } + + if (latestScore.score >= this.threshold) { + console.log(' โœจ Code quality meets threshold! Consider adding tests or documentation.'); + } + } + + async explainConcept(topic) { + if (!topic) { + console.log('Usage: /explain '); return; } - if (GUIDANCE_MODES[newMode]) { - this.guidanceMode = newMode; - this.guidance = GUIDANCE_MODES[newMode]; - console.log(`\nโœ… Guidance mode changed to: ${this.guidance.name}`); - this.showGuidance(); + console.log(`\n๐Ÿ“š Explaining: ${topic}`); + console.log('โ”'.repeat(40)); + + // Provide explanations based on common topics + const explanations = { + 'typescript': 'TypeScript adds static typing to JavaScript, catching errors at compile time.', + 'linting': 'Linting analyzes code for potential errors and style issues.', + 'testing': 'Tests verify your code works as expected and prevent regressions.', + 'async': 'Async/await provides cleaner syntax for handling promises.', + 'hooks': 'React hooks allow using state in functional components.' + }; + + const explanation = explanations[topic.toLowerCase()]; + if (explanation) { + console.log(explanation); } else { - console.log(`โŒ Unknown mode: ${newMode}`); + console.log('Topic not found. Try: typescript, linting, testing, async, hooks'); } } + showBestPractices(area) { + console.log(`\n๐Ÿ“š Best Practices for ${area}:`); + console.log('โ”'.repeat(40)); + + const practices = { + general: [ + 'โ€ข Write self-documenting code', + 'โ€ข Keep functions small and focused', + 'โ€ข Use meaningful variable names', + 'โ€ข Handle errors properly', + 'โ€ข Write tests for critical paths' + ], + testing: [ + 'โ€ข Test behavior, not implementation', + 'โ€ข Use descriptive test names', + 'โ€ข Follow AAA pattern', + 'โ€ข Mock external dependencies', + 'โ€ข Test edge cases' + ] + }; + + const selected = practices[area] || practices.general; + selected.forEach(p => console.log(p)); + } + + showPatternSuggestions() { + console.log('\n๐Ÿ—๏ธ Recommended Design Patterns:'); + console.log('โ”'.repeat(40)); + console.log('โ€ข Singleton - One instance throughout app'); + console.log('โ€ข Factory - Create objects without specifying class'); + console.log('โ€ข Observer - Subscribe to and notify changes'); + console.log('โ€ข Strategy - Encapsulate algorithms'); + console.log('โ€ข Decorator - Add functionality to objects'); + } + + explainDecisions() { + console.log('\n๐Ÿค” Decision Rationale:'); + console.log('โ”'.repeat(40)); + console.log('Auto-fix decisions are based on:'); + console.log('โ€ข Industry best practices'); + console.log('โ€ข Code maintainability'); + console.log('โ€ข Performance optimization'); + console.log('โ€ข Security considerations'); + console.log('โ€ข Team consistency'); + } + async showStatus() { const duration = Math.floor((Date.now() - this.startTime) / 1000 / 60); @@ -734,11 +628,10 @@ Design patterns are reusable solutions to common problems: console.log('โ”'.repeat(40)); console.log(`Session ID: ${this.sessionId}`); console.log(`Duration: ${duration} minutes`); - console.log(`Guidance Mode: ${this.guidance.name}`); + console.log(`Guidance Mode: ${this.guidanceMode}`); console.log(`Auto-Fix: ${this.autoFix ? 'Enabled' : 'Disabled'}`); - console.log(`Iterations: ${this.currentIteration}`); - console.log(`Fixes Applied: ${this.fixHistory.length}`); - console.log(`Suggestions Given: ${this.suggestionHistory.length}`); + console.log(`Fix Iterations: ${this.currentIteration}`); + console.log(`Total Fixes Applied: ${this.fixHistory.reduce((sum, h) => sum + h.fixes.length, 0)}`); if (this.verificationScores.length > 0) { const latest = this.verificationScores[this.verificationScores.length - 1]; @@ -761,137 +654,46 @@ Design patterns are reusable solutions to common problems: const first = this.verificationScores[0].score; const last = this.verificationScores[this.verificationScores.length - 1].score; const improvement = ((last - first) * 100).toFixed(1); - console.log(`\n Total Improvement: +${improvement}%`); - } - } - - if (this.suggestionHistory.length > 0) { - console.log(`\n๐Ÿ“ Suggestions Provided: ${this.suggestionHistory.length}`); - } - } - - // Include all the auto-fix methods from the previous implementation - async runVerification() { - console.log('\n๐Ÿ” Running verification check...'); - - const checks = [ - { - name: 'Type Check', - command: 'npm run typecheck 2>&1 || true', - weight: 0.4 - }, - { - name: 'Linting', - command: 'npm run lint 2>&1 || true', - weight: 0.3 - }, - { - name: 'Build', - command: 'npm run build 2>&1 || true', - weight: 0.3 - } - ]; - - const results = []; - let totalScore = 0; - let totalWeight = 0; - - for (const check of checks) { - try { - const { stdout, stderr } = await execAsync(check.command); - const output = stdout + stderr; - - let score = 1.0; - if (output.toLowerCase().includes('error')) { - const errorCount = (output.match(/error/gi) || []).length; - score = Math.max(0.2, 1.0 - (errorCount * 0.1)); - } else if (output.toLowerCase().includes('warning')) { - const warningCount = (output.match(/warning/gi) || []).length; - score = Math.max(0.7, 1.0 - (warningCount * 0.05)); - } - - totalScore += score * check.weight; - totalWeight += check.weight; - - const icon = score >= 0.8 ? 'โœ…' : score >= 0.5 ? 'โš ๏ธ' : 'โŒ'; - console.log(` ${icon} ${check.name}: ${score.toFixed(2)}`); - - results.push({ - name: check.name, - score, - output: output.slice(0, 200) - }); - } catch (error) { - console.log(` โŒ ${check.name}: 0.00 (failed)`); - results.push({ name: check.name, score: 0, error: error.message }); - totalWeight += check.weight; - } - } - - const averageScore = totalWeight > 0 ? totalScore / totalWeight : 0; - - console.log(`\n๐Ÿ“Š Verification Score: ${averageScore.toFixed(2)}/${this.threshold}`); - - const verificationResult = { - score: averageScore, - results, - timestamp: new Date(), - iteration: this.currentIteration, - previousScore: this.verificationScores.length > 0 - ? this.verificationScores[this.verificationScores.length - 1].score - : 0 - }; - - this.verificationScores.push(verificationResult); - - // Provide guidance based on score and mode - if (averageScore < this.threshold) { - if (this.guidanceMode === 'beginner') { - console.log('\n๐Ÿ’ก Don\'t worry! Use /autofix to automatically improve the score'); - } else if (this.guidanceMode === 'mentor') { - console.log('\n๐Ÿ“š Learning opportunity: Each issue fixed improves code quality'); - } - } - - return verificationResult; - } - - // Include other methods from previous implementation... - identifyIssues(verificationResult) { - const issues = []; - - if (verificationResult.results) { - for (const check of verificationResult.results) { - if (check.score < 0.8) { - issues.push({ - type: check.name.toLowerCase().replace(' check', '').replace(' ', ''), - description: `Score: ${check.score.toFixed(2)}`, - severity: check.score < 0.5 ? 'high' : 'medium' - }); + if (improvement > 0) { + console.log(`\n Improvement: +${improvement}%`); } } } - - return issues; } - async createFixChain(issues) { - // Implementation from previous version - console.log(' ๐Ÿ”ง Creating fix chains for identified issues...'); - // ... rest of implementation + async changeGuidanceMode(newMode) { + if (!newMode || !GUIDANCE_MODES[newMode]) { + console.log('Available modes: beginner, intermediate, expert, mentor, strict'); + return; + } + + this.guidanceMode = newMode; + this.guidance = GUIDANCE_MODES[newMode]; + console.log(`โœ… Guidance mode changed to: ${newMode}`); + console.log(`Description: ${this.guidance.description}`); + } + + async askQuestion(question) { + console.log('\nโ“ Question:', question); + console.log('\n๐Ÿ“š Answer:'); + console.log('โ”'.repeat(40)); + + // Provide contextual answers + if (question.toLowerCase().includes('why')) { + console.log('This is important for code quality and maintainability.'); + } else if (question.toLowerCase().includes('how')) { + console.log('You can achieve this by following the suggested approach.'); + } else { + console.log('That\'s a great question! Consider exploring the documentation.'); + } } async runTests() { console.log('\n๐Ÿงช Running tests...'); try { const { stdout } = await execAsync('npm test 2>&1 || true'); - const passed = stdout.includes('PASS'); + const passed = !stdout.toLowerCase().includes('fail'); console.log(` ${passed ? 'โœ…' : 'โŒ'} Tests ${passed ? 'passed' : 'failed'}`); - - if (this.guidanceMode === 'beginner' && !passed) { - console.log(' ๐Ÿ’ก Tip: Check test output for specific failures'); - } - return passed; } catch (error) { console.log(' โŒ Test execution failed:', error.message); @@ -905,22 +707,17 @@ Design patterns are reusable solutions to common problems: if (result.score >= this.threshold) { console.log('โœ… Verification passed! Ready to commit.'); console.log('\n๐Ÿ“ Suggested commit message:'); - console.log(' "feat: improved code quality to ' + result.score.toFixed(2) + ' threshold"'); + console.log(` "feat: improved code quality to ${result.score.toFixed(2)} threshold"`); } else { console.log('โŒ Verification failed!'); - if (this.autoFix) { - console.log('๐Ÿ’ก Run /autofix to automatically fix issues'); - } else { - console.log('๐Ÿ’ก Run /suggest for improvement recommendations'); - } + console.log('๐Ÿ’ก Run /autofix to automatically fix issues'); } } async end() { - console.log('\n๐Ÿ›‘ Ending enhanced pair programming session...'); + console.log('\n๐Ÿ›‘ Ending pair programming session...'); if (this.rl) this.rl.close(); - if (this.monitoringInterval) clearInterval(this.monitoringInterval); this.status = 'completed'; await this.saveSession(); @@ -929,24 +726,15 @@ Design patterns are reusable solutions to common problems: console.log('\nโœจ Session Complete!'); console.log('โ”'.repeat(40)); console.log(`Duration: ${duration} minutes`); - console.log(`Guidance Mode: ${this.guidance.name}`); - console.log(`Total Fixes: ${this.fixHistory.length}`); - console.log(`Suggestions Given: ${this.suggestionHistory.length}`); + console.log(`Total Fixes Applied: ${this.fixHistory.reduce((sum, h) => sum + h.fixes.length, 0)}`); + console.log(`Final Iterations: ${this.currentIteration}`); if (this.verificationScores.length > 0) { const final = this.verificationScores[this.verificationScores.length - 1]; console.log(`Final Score: ${final.score.toFixed(2)}`); } - if (this.guidanceMode === 'mentor' || this.guidanceMode === 'beginner') { - console.log('\n๐Ÿ“š Session Summary:'); - console.log(' โ€ข Key concepts covered'); - console.log(' โ€ข Best practices applied'); - console.log(' โ€ข Improvements achieved'); - console.log('\n๐Ÿ’ก Keep learning and improving!'); - } - - console.log('\n๐Ÿ‘‹ Thanks for using enhanced pair programming!\n'); + console.log('\n๐Ÿ‘‹ Thanks for pair programming!\n'); } async saveSession() { @@ -956,14 +744,12 @@ Design patterns are reusable solutions to common problems: const sessionData = { id: this.sessionId, guidanceMode: this.guidanceMode, - verify: this.verify, autoFix: this.autoFix, threshold: this.threshold, startTime: this.startTime.toISOString(), status: this.status, verificationScores: this.verificationScores, fixHistory: this.fixHistory, - suggestionHistory: this.suggestionHistory, iterations: this.currentIteration }; @@ -984,16 +770,12 @@ async function pairCommand(args = [], flags = {}) { } if (flags.start) { - const session = new EnhancedPairSession({ - guidance: flags.guidance || flags.mode || 'intermediate', - verify: flags.verify !== false, + const session = new WorkingPairSession({ + guidance: flags.guidance || 'intermediate', + verify: flags.verify || false, autoFix: flags.autofix || flags.fix || false, threshold: parseFloat(flags.threshold) || undefined, - maxIterations: parseInt(flags.iterations) || 5, - suggestions: flags.suggestions !== false, - patterns: flags.patterns !== false, - bestPractices: flags.best !== false, - realtime: flags.realtime || false + maxIterations: parseInt(flags.iterations) || 5 }); return await session.start(); @@ -1008,57 +790,48 @@ function showHelp() { claude-flow pair [options] โš™๏ธ OPTIONS: - --start Start enhanced pair session - --guidance Guidance mode (beginner|intermediate|expert|mentor|strict) + --start Start a new pair programming session + --guidance Set guidance mode (beginner, intermediate, expert, mentor, strict) --verify Enable verification - --autofix Enable recursive auto-fix - --threshold Target threshold (default varies by mode) - --iterations Max fix iterations (default: 5) - --realtime Enable real-time monitoring - --suggestions Enable intelligent suggestions - --patterns Show design pattern recommendations - --best Show best practices - --help Show this help + --autofix, --fix Enable auto-fix with real fixes + --threshold Target verification threshold + --iterations Max fix iterations + --help Show this help message ๐ŸŽฏ GUIDANCE MODES: - beginner - Detailed explanations, step-by-step guidance - intermediate - Balanced guidance with helpful suggestions - expert - Minimal guidance, focus on efficiency - mentor - Teaching mode with best practices - strict - Enforces high standards and best practices + beginner - Detailed explanations and step-by-step guidance + intermediate - Balanced guidance with key explanations + expert - Minimal guidance, maximum efficiency + mentor - Educational focus with learning opportunities + strict - Enforces highest code quality standards -๐Ÿ’ก FEATURES: - โ€ข Intelligent suggestions based on context - โ€ข Recursive auto-fix with stream chaining - โ€ข Best practices and design patterns - โ€ข Interactive Q&A (type ? followed by question) - โ€ข Real-time monitoring and feedback - โ€ข Multiple guidance modes for all skill levels - โ€ข Comprehensive metrics and history +๐Ÿ”„ AUTO-FIX FEATURES: + โ€ข Real ESLint auto-fixes + โ€ข Prettier formatting + โ€ข Missing type definitions installation + โ€ข Security vulnerability fixes + โ€ข Dependency updates + โ€ข Cache clearing and rebuilding -๐Ÿ“ EXAMPLES: +๐Ÿ’ก EXAMPLES: # Beginner mode with auto-fix - claude-flow pair --start --guidance beginner --autofix + claude-flow pair --start --guidance beginner --verify --autofix - # Mentor mode for learning + # Expert mode with high threshold + claude-flow pair --start --guidance expert --verify --autofix --threshold 0.98 + + # Mentor mode (educational, no auto-fix) claude-flow pair --start --guidance mentor --verify - - # Strict mode for production - claude-flow pair --start --guidance strict --autofix --threshold 0.98 - - # Expert mode with minimal guidance - claude-flow pair --start --guidance expert --verify -๐ŸŽ“ INTERACTIVE COMMANDS: - /suggest - Get contextual suggestions - /explain - Explain concepts - /best - Show best practices - /pattern - Design pattern recommendations - /why - Understand decisions - /guidance - Change guidance mode - ? - Ask questions +๐Ÿ“Š DURING SESSION: + /verify - Manual verification + /autofix - Start auto-fix loop + /suggest - Get improvement suggestions + /guidance - Change guidance mode + /metrics - Show quality metrics + /status - Current session status -๐Ÿ“š Documentation: +๐Ÿ“š For detailed documentation, see: .claude/commands/pair/README.md `); }