UNPKG

@claude-vector/cli

Version:

CLI for Claude-integrated vector search

580 lines (478 loc) 21.5 kB
#!/usr/bin/env node /** * ccvector - Claude Vector Search CLI * 任意のディレクトリから実行可能なインテリジェントCLI */ import { SmartClaude } from '../src/commands/smart-search.js'; import { WatchCommand } from '../src/commands/watch-command.js'; import { fileURLToPath } from 'url'; import path from 'path'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); async function main() { const args = process.argv.slice(2); const command = args[0]; const smartClaude = new SmartClaude(); // 動的タイムアウト設定(操作に応じて調整) const isIndexOperation = command === 'index' || command === 'i'; const timeoutDuration = isIndexOperation ? 600000 : 60000; // インデックス作成は10分、その他は1分 const timeout = setTimeout(() => { console.log(`\n⏰ Operation timeout after ${timeoutDuration/1000} seconds`); if (isIndexOperation) { console.log('💡 For large projects, consider using smaller batch sizes or running in multiple sessions'); console.log(' Large projects may require more time for embedding generation'); } process.exit(1); }, timeoutDuration); try { switch (command) { case 'search': case 's': const query = args[1]; if (!query) { console.error('❌ Usage: ccvector search "your query"'); showSearchHelp(); process.exit(1); } const searchOptions = {}; // オプション解析と検証 const validOptions = ['--limit', '--threshold']; const invalidOptions = args.filter(arg => arg.startsWith('--') && !validOptions.includes(arg) ); if (invalidOptions.length > 0) { console.error(`❌ Unknown option(s): ${invalidOptions.join(', ')}`); console.error('💡 Valid options for search: --limit <number>, --threshold <float>'); console.error(' Use "ccvector search --help" for detailed help'); process.exit(1); } if (args.includes('--limit')) { const limitIndex = args.indexOf('--limit'); const limitValue = parseInt(args[limitIndex + 1]); if (isNaN(limitValue) || limitValue < 1 || limitValue > 100) { console.error('❌ --limit must be a number between 1 and 100'); process.exit(1); } searchOptions.maxResults = limitValue; } if (args.includes('--threshold')) { const thresholdIndex = args.indexOf('--threshold'); const thresholdValue = parseFloat(args[thresholdIndex + 1]); if (isNaN(thresholdValue) || thresholdValue < 0 || thresholdValue > 1) { console.error('❌ --threshold must be a number between 0.0 and 1.0'); process.exit(1); } searchOptions.searchThreshold = thresholdValue; } await smartClaude.search(query, searchOptions); break; case 'index': case 'i': // インデックスコマンドのオプション検証 const indexValidOptions = ['--force', '-f', '--resume', '-r', '--check-only', '-c']; const indexInvalidOptions = args.filter(arg => arg.startsWith('-') && !indexValidOptions.includes(arg) ); if (indexInvalidOptions.length > 0) { console.error(`❌ Unknown option(s): ${indexInvalidOptions.join(', ')}`); console.error('💡 Valid options for index: --force (-f), --resume (-r), --check-only (-c)'); process.exit(1); } const force = args.includes('--force') || args.includes('-f'); const resume = args.includes('--resume') || args.includes('-r'); const checkOnly = args.includes('--check-only') || args.includes('-c'); if (checkOnly) { console.log('🔍 Check-only mode: analyzing file changes without updating index'); const changeResult = await smartClaude.checkIndexChanges(); if (changeResult.requiresUpdate) { console.log(`📊 Changes detected: ${changeResult.stats.newFiles} new, ${changeResult.stats.modifiedFiles} modified, ${changeResult.stats.deletedFiles} deleted`); console.log('💡 Run "ccvector index" to update the index'); process.exit(0); } else { console.log('✅ Index is up to date - no changes detected'); process.exit(0); } } if (resume) { console.log('🔄 Resume mode enabled - will continue from previous progress if available'); } await smartClaude.createIndex(force, resume); break; case 'info': case 'status': await smartClaude.info(); break; case 'help': case '--help': case '-h': showHelp(); break; case 'version': case '--version': case '-v': await showVersion(); break; case 'watch': case 'w': const watchCommand = new WatchCommand(); const subCommand = args[1]; const watchArgs = args.slice(2); await watchCommand.execute(subCommand, watchArgs); break; case 'perf': case 'performance': const analysisType = args[1] || 'full'; // full, index, search, memory const perfOptions = {}; // オプション解析 if (args.includes('--iterations')) { const iterIndex = args.indexOf('--iterations'); perfOptions.iterations = parseInt(args[iterIndex + 1]) || 3; } if (args.includes('--output')) { const outputIndex = args.indexOf('--output'); perfOptions.outputFile = args[outputIndex + 1]; } if (args.includes('--queries')) { const queriesIndex = args.indexOf('--queries'); const queriesArg = args[queriesIndex + 1]; if (queriesArg) { perfOptions.queries = queriesArg.split(','); } } console.log('🔍 Claude Vector Performance Analysis'); // SmartClaudeインスタンスを作成して初期化 const perfSmartClaude = new SmartClaude(); const perfResults = await perfSmartClaude.runPerformanceAnalysis(analysisType, perfOptions); break; case 'memory': case 'm': const memoryCommand = args[1]; // start, stop, status const memorySmartClaude = new SmartClaude(); switch (memoryCommand) { case 'start': const memoryOptions = {}; // オプション解析 if (args.includes('--threshold')) { const thresholdIndex = args.indexOf('--threshold'); memoryOptions.alertThresholdMB = parseInt(args[thresholdIndex + 1]) || 500; } if (args.includes('--interval')) { const intervalIndex = args.indexOf('--interval'); memoryOptions.monitoringInterval = parseInt(args[intervalIndex + 1]) * 1000 || 30000; // 秒をミリ秒に変換 } console.log('🔍 Claude Vector Memory Monitoring'); const memoryMonitor = await memorySmartClaude.startMemoryMonitoring(memoryOptions); // プロセス終了時の処理 process.on('SIGINT', async () => { console.log('\n🛑 Stopping memory monitoring...'); await memorySmartClaude.stopMemoryMonitoring(); process.exit(0); }); // 継続実行(メモリ監視は別スレッドで動作) console.log('\n💡 Press Ctrl+C to stop monitoring and save report'); // 定期的な状態表示(60秒毎) setInterval(() => { const status = memorySmartClaude.getMemoryMonitoringStatus(); if (status.monitoring) { console.log(`📊 Memory: ${status.currentMemory.heapUsedMB}MB heap, ${status.currentMemory.rssMB}MB RSS`); } }, 60000); // メインプロセスをブロックしてCLIを維持 await new Promise(() => {}); // 無限待機 break; case 'stop': await memorySmartClaude.stopMemoryMonitoring(); break; case 'status': default: const status = memorySmartClaude.getMemoryMonitoringStatus(); console.log('\n🔍 Memory Monitoring Status:'); console.log(` Enabled: ${status.enabled ? '✅' : '❌'}`); console.log(` Monitoring: ${status.monitoring ? '✅' : '❌'}`); if (status.enabled && status.currentMemory) { console.log('\n💾 Current Memory Usage:'); console.log(` Heap Used: ${status.currentMemory.heapUsedMB}MB`); console.log(` Heap Total: ${status.currentMemory.heapTotalMB}MB`); console.log(` RSS: ${status.currentMemory.rssMB}MB`); if (status.monitoring && status.stats) { console.log('\n📈 Monitoring Statistics:'); console.log(` Duration: ${Math.round(status.stats.monitoringDuration / 1000)}s`); console.log(` Data Points: ${status.stats.historySize}`); console.log(` Alerts: ${status.stats.alertsTriggered}`); console.log(` Peak Memory: ${Math.round(status.stats.peakMemoryUsage)}MB`); console.log(` Average Memory: ${Math.round(status.stats.averageMemoryUsage)}MB`); } } if (!status.enabled) { console.log('\n💡 To enable memory monitoring:'); console.log(' ccvector memory start [--threshold MB] [--interval seconds]'); } break; } break; default: if (command) { console.log('❌ Unknown command:', command); } else { console.log('❌ No command provided'); } showHelp(); process.exit(1); } } catch (error) { console.error('❌ Error:', error.message); // 開発者向けの詳細エラー情報 if (process.env.DEBUG) { console.error('Debug info:', error); } // 一般的なエラーに対する提案 if (error.message.includes('Index not found')) { console.log('\n💡 Quick fix:'); console.log(' 1. Make sure you are in a project directory'); console.log(' 2. Run: node scripts/claude-code-indexer.js'); console.log(' 3. Or check if .claude-code-index directory exists'); } process.exit(1); } finally { clearTimeout(timeout); process.exit(0); } } function showHelp() { console.log(` 🤖 ccvector - Claude Vector Search CLI Advanced code search with AI-powered optimization and real-time monitoring Usage: ccvector <command> [options] 📋 CORE COMMANDS: search, s <query> 🔍 Search for code and documentation index, i 📊 Create or update project index watch, w <command> 👀 Real-time file monitoring and indexing perf <type> 📈 Performance analysis and optimization memory, m <command> 💾 Real-time memory monitoring and analysis info, status ℹ️ Show project and index information help, -h, --help ❓ Show this help message version, -v 📦 Show version information 🔍 SEARCH COMMAND: ccvector search "your query" [options] Options: --limit <number> Maximum number of results (default: 20) --threshold <float> Similarity threshold 0.0-1.0 (default: 0.3) Examples: ccvector search "user authentication" ccvector search "React hooks" --limit 15 --threshold 0.2 ccvector search "error handling middleware" 📊 INDEX COMMAND: ccvector index [options] Options: --force, -f Force rebuild existing index (full recreation) --resume, -r Resume interrupted indexing from last saved progress --check-only, -c Check for changes without updating index Examples: ccvector index # Smart update (detect changes and update incrementally) ccvector index --force # Force complete rebuild ccvector index --resume # Resume interrupted indexing ccvector index --check-only # Check for changes without updating 👀 WATCH COMMANDS: ccvector watch <subcommand> [options] Subcommands: start Start real-time file monitoring stop Stop monitoring process restart Restart monitoring process status Show monitoring status and statistics logs Show monitoring logs config Manage watch configuration Start Options: --feedback <level> Feedback level: silent, normal, verbose --batch-size <num> Batch size for processing (default: 5) --max-concurrent <n> Max concurrent operations (default: 3) Examples: ccvector watch start ccvector watch start --feedback verbose --batch-size 10 ccvector watch stop ccvector watch status ccvector watch logs --follow ccvector watch config show 📈 PERFORMANCE COMMANDS: ccvector perf <type> [options] Analysis Types: full Complete performance analysis (default) index Index loading performance only search Search performance only memory Memory usage analysis only Options: --iterations <num> Number of test iterations (default: 3) --output <file> Save results to file --queries <list> Custom search queries (comma-separated) Examples: ccvector perf # Full analysis ccvector perf index --iterations 5 # Index loading test ccvector perf search --queries "auth,api,db" ccvector perf memory --output ./perf.json 💾 MEMORY COMMANDS: ccvector memory <subcommand> [options] Subcommands: start Start real-time memory monitoring stop Stop current monitoring session status Show current memory status and statistics Start Options: --threshold <MB> Memory alert threshold in MB (default: 500) --interval <seconds> Monitoring interval in seconds (default: 30) Examples: ccvector memory start # Start monitoring with defaults ccvector memory start --threshold 1000 # High memory threshold ccvector memory start --interval 10 # More frequent monitoring ccvector memory status # Check current status ccvector memory stop # Stop and save report 🚀 QUICK START: 1. ccvector index # Create initial index 2. ccvector search "your query" # Search your code 3. ccvector watch start # Start real-time monitoring ✨ FEATURES: 🎯 Smart project detection 📁 Multi-project support 🔍 Semantic code search 🔄 Real-time index updates 🤖 AI-powered optimization ⚡ Adaptive performance control 📊 Context-aware results 🛡️ OpenAI API rate limiting 📝 Structured logging 💾 Real-time memory monitoring 🔧 Zero-configuration setup 📈 Performance analysis tools ⚙️ ENVIRONMENT VARIABLES: OPENAI_API_KEY Your OpenAI API key (required) CLAUDE_FEEDBACK_LEVEL Default feedback level (silent/normal/verbose) CLAUDE_BATCH_SIZE Default batch size for processing CLAUDE_MAX_FILES Maximum files to monitor 📚 MORE HELP: ccvector search --help Detailed search help ccvector watch Watch command help ccvector watch config Configuration management help 📦 Installation: npm install @claude-vector/cli 🔗 More Information: GitHub: https://github.com/liets/claude-vector-search-npm Docs: https://docs.claude-vector.dev (coming soon) `); } function showSearchHelp() { console.log(` 🔍 Advanced Search Command Help Usage: ccvector search "your query" [options] 📋 OPTIONS: --limit <number> Maximum number of results (default: 20, max: 100) --threshold <float> Similarity threshold 0.0-1.0 (default: 0.3) Lower values = more results, higher values = more precise 🎯 SEARCH STRATEGIES: 🔍 Semantic Search: ccvector search "user login flow" ccvector search "handle database connections" ccvector search "React component lifecycle" 🎯 Precise Matches: ccvector search "useState hook" --threshold 0.6 ccvector search "async/await pattern" --threshold 0.7 📊 Broad Discovery: ccvector search "authentication" --threshold 0.2 --limit 30 ccvector search "error handling" --threshold 0.1 --limit 50 💡 SEARCH TECHNIQUES: 📝 Function & Method Names: ccvector search "validateUser" ccvector search "connectDatabase" ccvector search "parseJSON" 🏗️ Architecture Patterns: ccvector search "middleware pattern" ccvector search "factory pattern" ccvector search "observer pattern" 🐛 Problem-Solving: ccvector search "memory leak fix" ccvector search "performance optimization" ccvector search "race condition handling" 📚 Technology-Specific: ccvector search "React hooks useEffect" ccvector search "Express.js routing" ccvector search "TypeScript generic types" ⚙️ THRESHOLD GUIDELINES: 0.1-0.2 Very broad search (experimental discovery) 0.2-0.4 Standard search (recommended for most cases) 0.4-0.6 Focused search (specific concepts) 0.6-0.8 Precise search (exact matches) 0.8-1.0 Ultra-precise (may return no results) 🚀 EXAMPLES BY USE CASE: 🧑‍💻 Development: ccvector search "API error handling" --limit 15 ccvector search "data validation logic" ccvector search "unit test examples" --threshold 0.3 🔍 Code Review: ccvector search "security vulnerabilities" --threshold 0.2 ccvector search "code smells" --limit 25 ccvector search "performance bottlenecks" 📖 Learning: ccvector search "how to implement caching" --threshold 0.2 ccvector search "best practices" --limit 30 ccvector search "design patterns examples" 💁 PRO TIPS: • Combine technical terms with context for better results • Use natural language - the AI understands concepts • Try different threshold values if results aren't optimal • Use specific technology names (React, Node.js, TypeScript) • Search for both problems and solutions ("fix", "handle", "implement") 📊 PERFORMANCE: • Searches typically complete in 0.5-2 seconds • Results are ranked by semantic similarity • AI-powered context understanding improves over time • Works with any programming language or framework `); } async function showVersion() { try { const packageJsonPath = path.join(__dirname, '../package.json'); const fs = await import('fs'); const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8')); console.log(` 🤖 ccvector - Claude Vector Search CLI 📦 Version: ${packageJson.version} 📄 Package: ${packageJson.name} 🔧 COMPONENTS: • Core Engine: @claude-vector/core v${packageJson.dependencies['@claude-vector/core']?.replace('^', '')} • Claude Tools: @claude-vector/claude-tools v${packageJson.dependencies['@claude-vector/claude-tools']?.replace('^', '')} • Node.js: ${process.version} • Platform: ${process.platform} (${process.arch}) ✨ FEATURES IN THIS VERSION: 🔍 Advanced semantic search with AI optimization 📊 Incremental indexing with resume capability 👀 Real-time file monitoring and auto-indexing ⚡ Adaptive performance control and API rate limiting 🔧 Zero-configuration setup with smart defaults 📝 Structured logging and process management 🔗 LINKS: 📚 GitHub: https://github.com/liets/claude-vector-search-npm 📖 Documentation: https://docs.claude-vector.dev (coming soon) 🐛 Issues: https://github.com/liets/claude-vector-search-npm/issues 💡 Feature Requests: https://github.com/liets/claude-vector-search-npm/discussions 📊 SYSTEM INFO: • Working Directory: ${process.cwd()} • Home Directory: ${process.env.HOME || process.env.USERPROFILE || 'unknown'} • Memory Usage: ${Math.round(process.memoryUsage().heapUsed / 1024 / 1024)}MB • Uptime: ${Math.round(process.uptime())}s `); } catch (error) { console.log(` 🤖 ccvector - Claude Vector Search CLI ❌ Version information not available 📁 Running from: ${__dirname} 🔧 Node.js: ${process.version} `); } } // エラーハンドリング process.on('unhandledRejection', (error) => { console.error('❌ Unhandled promise rejection:', error.message); process.exit(1); }); process.on('uncaughtException', (error) => { console.error('❌ Uncaught exception:', error.message); process.exit(1); }); // SIGINT(Ctrl+C)のハンドリング process.on('SIGINT', () => { console.log('\n👋 Goodbye!'); process.exit(0); }); main().catch(error => { console.error('❌ Fatal error:', error.message); process.exit(1); });