diff --git a/agents/architect.yaml b/agents/architect.yaml index 057ae5debe..8015208de0 100644 --- a/agents/architect.yaml +++ b/agents/architect.yaml @@ -8,4 +8,4 @@ capabilities: optimizations: - context-caching - memory-persistence -createdAt: "2026-01-07T03:55:13.825Z" +createdAt: "2026-01-07T04:31:43.920Z" diff --git a/agents/coder.yaml b/agents/coder.yaml index 2f40eca45b..92b0840c83 100644 --- a/agents/coder.yaml +++ b/agents/coder.yaml @@ -8,4 +8,4 @@ capabilities: optimizations: - flash-attention - token-reduction -createdAt: "2026-01-07T03:55:13.825Z" +createdAt: "2026-01-07T04:31:43.920Z" diff --git a/agents/reviewer.yaml b/agents/reviewer.yaml index bf6e71c786..f83bf424f9 100644 --- a/agents/reviewer.yaml +++ b/agents/reviewer.yaml @@ -7,4 +7,4 @@ capabilities: - best-practices optimizations: - incremental-analysis -createdAt: "2026-01-07T03:55:13.825Z" +createdAt: "2026-01-07T04:31:43.921Z" diff --git a/agents/security-architect.yaml b/agents/security-architect.yaml index ad23593606..6e26b26428 100644 --- a/agents/security-architect.yaml +++ b/agents/security-architect.yaml @@ -7,4 +7,4 @@ capabilities: - security-review optimizations: - pattern-matching -createdAt: "2026-01-07T03:55:13.825Z" +createdAt: "2026-01-07T04:31:43.921Z" diff --git a/agents/tester.yaml b/agents/tester.yaml index 49ce839c0b..f82884eec4 100644 --- a/agents/tester.yaml +++ b/agents/tester.yaml @@ -7,4 +7,4 @@ capabilities: - coverage optimizations: - parallel-execution -createdAt: "2026-01-07T03:55:13.825Z" +createdAt: "2026-01-07T04:31:43.920Z" diff --git a/v3/@claude-flow/cli/src/commands/completions.ts b/v3/@claude-flow/cli/src/commands/completions.ts new file mode 100644 index 0000000000..470bf498f4 --- /dev/null +++ b/v3/@claude-flow/cli/src/commands/completions.ts @@ -0,0 +1,558 @@ +/** + * V3 CLI Completions Command + * Shell completions for bash, zsh, fish, powershell + * + * Created with ruv.io + */ + +import type { Command, CommandContext, CommandResult } from '../types.js'; +import { output } from '../output.js'; + +// Get all top-level commands for completions +const TOP_LEVEL_COMMANDS = [ + 'swarm', 'agent', 'task', 'session', 'config', 'memory', 'workflow', + 'hive-mind', 'hooks', 'daemon', 'neural', 'security', 'performance', + 'providers', 'plugins', 'deployment', 'claims', 'embeddings', + 'doctor', 'completions', 'help', 'version' +]; + +// Swarm subcommands +const SWARM_SUBCOMMANDS = ['init', 'status', 'scale', 'destroy', 'monitor', 'optimize']; + +// Agent subcommands +const AGENT_SUBCOMMANDS = ['spawn', 'terminate', 'status', 'list', 'pool', 'health', 'update']; + +// Task subcommands +const TASK_SUBCOMMANDS = ['create', 'status', 'list', 'complete', 'cancel']; + +// Memory subcommands +const MEMORY_SUBCOMMANDS = ['store', 'retrieve', 'search', 'list', 'delete', 'stats', 'configure', 'cleanup', 'compress', 'export', 'import']; + +// Hive-mind subcommands +const HIVE_MIND_SUBCOMMANDS = ['init', 'spawn', 'status', 'task', 'join', 'leave', 'consensus', 'broadcast', 'memory', 'optimize-memory', 'shutdown']; + +// Hooks subcommands +const HOOKS_SUBCOMMANDS = ['pre-edit', 'post-edit', 'pre-command', 'post-command', 'pre-task', 'post-task', 'route', 'explain', 'pretrain', 'build-agents', 'metrics', 'transfer', 'list', 'intelligence']; + +// Generate bash completion script +function generateBashCompletion(): string { + return `# claude-flow bash completion +# Generated by claude-flow completions bash +# Add this to ~/.bashrc or ~/.bash_completion + +_claude_flow_completions() { + local cur prev words cword + _init_completion -n : || return + + local commands="${TOP_LEVEL_COMMANDS.join(' ')}" + + # Subcommand completions + local swarm_commands="${SWARM_SUBCOMMANDS.join(' ')}" + local agent_commands="${AGENT_SUBCOMMANDS.join(' ')}" + local task_commands="${TASK_SUBCOMMANDS.join(' ')}" + local memory_commands="${MEMORY_SUBCOMMANDS.join(' ')}" + local hive_mind_commands="${HIVE_MIND_SUBCOMMANDS.join(' ')}" + local hooks_commands="${HOOKS_SUBCOMMANDS.join(' ')}" + + case "\${words[1]}" in + swarm) + COMPREPLY=( $(compgen -W "\${swarm_commands}" -- "\${cur}") ) + return 0 + ;; + agent) + COMPREPLY=( $(compgen -W "\${agent_commands}" -- "\${cur}") ) + return 0 + ;; + task) + COMPREPLY=( $(compgen -W "\${task_commands}" -- "\${cur}") ) + return 0 + ;; + memory) + COMPREPLY=( $(compgen -W "\${memory_commands}" -- "\${cur}") ) + return 0 + ;; + hive-mind|hive) + COMPREPLY=( $(compgen -W "\${hive_mind_commands}" -- "\${cur}") ) + return 0 + ;; + hooks) + COMPREPLY=( $(compgen -W "\${hooks_commands}" -- "\${cur}") ) + return 0 + ;; + neural) + COMPREPLY=( $(compgen -W "train status patterns predict optimize" -- "\${cur}") ) + return 0 + ;; + security) + COMPREPLY=( $(compgen -W "scan cve threats audit secrets" -- "\${cur}") ) + return 0 + ;; + performance) + COMPREPLY=( $(compgen -W "benchmark profile metrics optimize bottleneck" -- "\${cur}") ) + return 0 + ;; + plugins) + COMPREPLY=( $(compgen -W "list install uninstall toggle info create" -- "\${cur}") ) + return 0 + ;; + deployment|deploy) + COMPREPLY=( $(compgen -W "deploy status rollback history environments logs" -- "\${cur}") ) + return 0 + ;; + claims) + COMPREPLY=( $(compgen -W "list check grant revoke roles policies" -- "\${cur}") ) + return 0 + ;; + embeddings) + COMPREPLY=( $(compgen -W "generate search compare collections index providers" -- "\${cur}") ) + return 0 + ;; + daemon) + COMPREPLY=( $(compgen -W "start stop status trigger enable" -- "\${cur}") ) + return 0 + ;; + providers) + COMPREPLY=( $(compgen -W "list configure test models usage" -- "\${cur}") ) + return 0 + ;; + doctor) + COMPREPLY=( $(compgen -W "--fix --component --verbose" -- "\${cur}") ) + return 0 + ;; + esac + + if [[ \${cword} -eq 1 ]]; then + COMPREPLY=( $(compgen -W "\${commands}" -- "\${cur}") ) + return 0 + fi +} + +complete -F _claude_flow_completions claude-flow +complete -F _claude_flow_completions npx\\ @claude-flow/cli@v3alpha +`; +} + +// Generate zsh completion script +function generateZshCompletion(): string { + return `#compdef claude-flow +# claude-flow zsh completion +# Generated by claude-flow completions zsh +# Add to ~/.zfunc/_claude-flow or ~/.zsh/completions/_claude-flow + +_claude_flow() { + local -a commands + local -a subcommands + + commands=( + 'swarm:Multi-agent swarm orchestration' + 'agent:Agent lifecycle management' + 'task:Task creation and management' + 'session:Session management' + 'config:Configuration management' + 'memory:Memory operations with AgentDB' + 'workflow:Workflow automation' + 'hive-mind:Queen-led consensus coordination' + 'hooks:Self-learning automation hooks' + 'daemon:Background service management' + 'neural:Neural pattern training' + 'security:Security scanning and CVE detection' + 'performance:Performance profiling' + 'providers:AI provider management' + 'plugins:Plugin management' + 'deployment:Deployment management' + 'claims:Claims-based authorization' + 'embeddings:Vector embeddings' + 'doctor:System diagnostics' + 'completions:Shell completion scripts' + 'help:Show help' + 'version:Show version' + ) + + _arguments -C \\ + '1: :->command' \\ + '2: :->subcommand' \\ + '*:: :->args' && return + + case $state in + command) + _describe -t commands 'claude-flow commands' commands + ;; + subcommand) + case $words[2] in + swarm) + subcommands=( + 'init:Initialize swarm' + 'status:Show swarm status' + 'scale:Scale agent count' + 'destroy:Shutdown swarm' + 'monitor:Real-time monitoring' + 'optimize:Optimize topology' + ) + ;; + agent) + subcommands=( + 'spawn:Create new agent' + 'terminate:Stop agent' + 'status:Check agent status' + 'list:List all agents' + 'pool:Manage agent pool' + 'health:Health check' + 'update:Update agent config' + ) + ;; + task) + subcommands=( + 'create:Create new task' + 'status:Check task status' + 'list:List all tasks' + 'complete:Mark task complete' + 'cancel:Cancel task' + ) + ;; + memory) + subcommands=( + 'store:Store data' + 'retrieve:Retrieve data' + 'search:Semantic search' + 'list:List entries' + 'delete:Delete entry' + 'stats:Show statistics' + 'configure:Configure backend' + 'cleanup:Clean stale data' + 'compress:Compress storage' + 'export:Export to file' + 'import:Import from file' + ) + ;; + hive-mind|hive) + subcommands=( + 'init:Initialize hive mind' + 'spawn:Spawn worker agents' + 'status:Show hive status' + 'task:Submit task' + 'join:Join agent to hive' + 'leave:Remove agent' + 'consensus:Consensus management' + 'broadcast:Broadcast message' + 'memory:Shared memory' + 'optimize-memory:Optimize patterns' + 'shutdown:Shutdown hive' + ) + ;; + hooks) + subcommands=( + 'pre-edit:Before file editing' + 'post-edit:After file editing' + 'pre-command:Before command execution' + 'post-command:After command execution' + 'pre-task:Before task start' + 'post-task:After task completion' + 'route:Route task to agent' + 'explain:Explain routing' + 'pretrain:Bootstrap intelligence' + 'build-agents:Generate agent configs' + 'metrics:Show metrics' + 'transfer:Transfer learning' + 'list:List hooks' + 'intelligence:Neural intelligence commands' + ) + ;; + neural) + subcommands=( + 'train:Train neural patterns' + 'status:Check neural status' + 'patterns:Manage patterns' + 'predict:Make predictions' + 'optimize:Optimize models' + ) + ;; + security) + subcommands=( + 'scan:Security scan' + 'cve:CVE detection' + 'threats:Threat modeling' + 'audit:Security audit' + 'secrets:Secrets scanning' + ) + ;; + performance) + subcommands=( + 'benchmark:Run benchmarks' + 'profile:Profile code' + 'metrics:Show metrics' + 'optimize:Optimize performance' + 'bottleneck:Find bottlenecks' + ) + ;; + plugins) + subcommands=( + 'list:List plugins' + 'install:Install plugin' + 'uninstall:Remove plugin' + 'toggle:Enable/disable' + 'info:Plugin details' + 'create:Scaffold plugin' + ) + ;; + deployment|deploy) + subcommands=( + 'deploy:Deploy to environment' + 'status:Deployment status' + 'rollback:Rollback version' + 'history:Deployment history' + 'environments:List environments' + 'logs:View logs' + ) + ;; + claims) + subcommands=( + 'list:List claims' + 'check:Check permission' + 'grant:Grant claim' + 'revoke:Revoke claim' + 'roles:Manage roles' + 'policies:Manage policies' + ) + ;; + embeddings) + subcommands=( + 'generate:Generate embeddings' + 'search:Semantic search' + 'compare:Compare vectors' + 'collections:Manage collections' + 'index:Index operations' + 'providers:Embedding providers' + ) + ;; + daemon) + subcommands=( + 'start:Start daemon' + 'stop:Stop daemon' + 'status:Daemon status' + 'trigger:Trigger event' + 'enable:Enable feature' + ) + ;; + providers) + subcommands=( + 'list:List providers' + 'configure:Configure provider' + 'test:Test connection' + 'models:Available models' + 'usage:Usage statistics' + ) + ;; + esac + _describe -t subcommands 'subcommands' subcommands + ;; + esac +} + +_claude_flow "$@" +`; +} + +// Generate fish completion script +function generateFishCompletion(): string { + return `# claude-flow fish completion +# Generated by claude-flow completions fish +# Save to ~/.config/fish/completions/claude-flow.fish + +# Disable file completion by default +complete -c claude-flow -f + +# Top-level commands +${TOP_LEVEL_COMMANDS.map(cmd => `complete -c claude-flow -n "__fish_use_subcommand" -a "${cmd}"`).join('\n')} + +# Swarm subcommands +${SWARM_SUBCOMMANDS.map(sub => `complete -c claude-flow -n "__fish_seen_subcommand_from swarm" -a "${sub}"`).join('\n')} + +# Agent subcommands +${AGENT_SUBCOMMANDS.map(sub => `complete -c claude-flow -n "__fish_seen_subcommand_from agent" -a "${sub}"`).join('\n')} + +# Task subcommands +${TASK_SUBCOMMANDS.map(sub => `complete -c claude-flow -n "__fish_seen_subcommand_from task" -a "${sub}"`).join('\n')} + +# Memory subcommands +${MEMORY_SUBCOMMANDS.map(sub => `complete -c claude-flow -n "__fish_seen_subcommand_from memory" -a "${sub}"`).join('\n')} + +# Hive-mind subcommands +${HIVE_MIND_SUBCOMMANDS.map(sub => `complete -c claude-flow -n "__fish_seen_subcommand_from hive-mind hive" -a "${sub}"`).join('\n')} + +# Hooks subcommands +${HOOKS_SUBCOMMANDS.map(sub => `complete -c claude-flow -n "__fish_seen_subcommand_from hooks" -a "${sub}"`).join('\n')} + +# Neural subcommands +complete -c claude-flow -n "__fish_seen_subcommand_from neural" -a "train status patterns predict optimize" + +# Security subcommands +complete -c claude-flow -n "__fish_seen_subcommand_from security" -a "scan cve threats audit secrets" + +# Performance subcommands +complete -c claude-flow -n "__fish_seen_subcommand_from performance" -a "benchmark profile metrics optimize bottleneck" + +# Plugins subcommands +complete -c claude-flow -n "__fish_seen_subcommand_from plugins" -a "list install uninstall toggle info create" + +# Deployment subcommands +complete -c claude-flow -n "__fish_seen_subcommand_from deployment deploy" -a "deploy status rollback history environments logs" + +# Claims subcommands +complete -c claude-flow -n "__fish_seen_subcommand_from claims" -a "list check grant revoke roles policies" + +# Embeddings subcommands +complete -c claude-flow -n "__fish_seen_subcommand_from embeddings" -a "generate search compare collections index providers" + +# Daemon subcommands +complete -c claude-flow -n "__fish_seen_subcommand_from daemon" -a "start stop status trigger enable" + +# Providers subcommands +complete -c claude-flow -n "__fish_seen_subcommand_from providers" -a "list configure test models usage" +`; +} + +// Generate PowerShell completion script +function generatePowerShellCompletion(): string { + return `# claude-flow PowerShell completion +# Generated by claude-flow completions powershell +# Add to $PROFILE or save to a separate file and dot-source it + +$script:ClaudeFlowCommands = @( + '${TOP_LEVEL_COMMANDS.join("',\n '")}' +) + +$script:SubCommands = @{ + 'swarm' = @('${SWARM_SUBCOMMANDS.join("', '")}') + 'agent' = @('${AGENT_SUBCOMMANDS.join("', '")}') + 'task' = @('${TASK_SUBCOMMANDS.join("', '")}') + 'memory' = @('${MEMORY_SUBCOMMANDS.join("', '")}') + 'hive-mind' = @('${HIVE_MIND_SUBCOMMANDS.join("', '")}') + 'hive' = @('${HIVE_MIND_SUBCOMMANDS.join("', '")}') + 'hooks' = @('${HOOKS_SUBCOMMANDS.join("', '")}') + 'neural' = @('train', 'status', 'patterns', 'predict', 'optimize') + 'security' = @('scan', 'cve', 'threats', 'audit', 'secrets') + 'performance' = @('benchmark', 'profile', 'metrics', 'optimize', 'bottleneck') + 'plugins' = @('list', 'install', 'uninstall', 'toggle', 'info', 'create') + 'deployment' = @('deploy', 'status', 'rollback', 'history', 'environments', 'logs') + 'deploy' = @('deploy', 'status', 'rollback', 'history', 'environments', 'logs') + 'claims' = @('list', 'check', 'grant', 'revoke', 'roles', 'policies') + 'embeddings' = @('generate', 'search', 'compare', 'collections', 'index', 'providers') + 'daemon' = @('start', 'stop', 'status', 'trigger', 'enable') + 'providers' = @('list', 'configure', 'test', 'models', 'usage') +} + +Register-ArgumentCompleter -Native -CommandName claude-flow -ScriptBlock { + param($wordToComplete, $commandAst, $cursorPosition) + + $tokens = $commandAst.ToString().Split(' ') + $command = $tokens[1] + + if ($tokens.Count -eq 2) { + # Complete top-level commands + $script:ClaudeFlowCommands | Where-Object { $_ -like "$wordToComplete*" } | ForEach-Object { + [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_) + } + } + elseif ($tokens.Count -eq 3 -and $script:SubCommands.ContainsKey($command)) { + # Complete subcommands + $script:SubCommands[$command] | Where-Object { $_ -like "$wordToComplete*" } | ForEach-Object { + [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_) + } + } +} +`; +} + +// Bash subcommand +const bashCommand: Command = { + name: 'bash', + description: 'Generate bash completion script', + action: async (ctx: CommandContext): Promise => { + const script = generateBashCompletion(); + output.writeln(script); + return { success: true }; + } +}; + +// Zsh subcommand +const zshCommand: Command = { + name: 'zsh', + description: 'Generate zsh completion script', + action: async (ctx: CommandContext): Promise => { + const script = generateZshCompletion(); + output.writeln(script); + return { success: true }; + } +}; + +// Fish subcommand +const fishCommand: Command = { + name: 'fish', + description: 'Generate fish completion script', + action: async (ctx: CommandContext): Promise => { + const script = generateFishCompletion(); + output.writeln(script); + return { success: true }; + } +}; + +// PowerShell subcommand +const powershellCommand: Command = { + name: 'powershell', + aliases: ['pwsh'], + description: 'Generate PowerShell completion script', + action: async (ctx: CommandContext): Promise => { + const script = generatePowerShellCompletion(); + output.writeln(script); + return { success: true }; + } +}; + +// Main completions command +export const completionsCommand: Command = { + name: 'completions', + description: 'Generate shell completion scripts', + subcommands: [bashCommand, zshCommand, fishCommand, powershellCommand], + options: [], + examples: [ + { command: 'claude-flow completions bash > ~/.bash_completion.d/claude-flow', description: 'Install bash completions' }, + { command: 'claude-flow completions zsh > ~/.zfunc/_claude-flow', description: 'Install zsh completions' }, + { command: 'claude-flow completions fish > ~/.config/fish/completions/claude-flow.fish', description: 'Install fish completions' }, + { command: 'claude-flow completions powershell >> $PROFILE', description: 'Install PowerShell completions' } + ], + action: async (): Promise => { + output.writeln(); + output.writeln(output.bold('Shell Completions')); + output.writeln(); + output.writeln('Generate shell completion scripts for tab completion support.'); + output.writeln(); + output.writeln('Supported shells:'); + output.printList([ + `${output.highlight('bash')} - Bash completion`, + `${output.highlight('zsh')} - Zsh completion`, + `${output.highlight('fish')} - Fish completion`, + `${output.highlight('powershell')} - PowerShell completion` + ]); + output.writeln(); + output.writeln('Installation:'); + output.writeln(); + output.writeln(output.bold('Bash:')); + output.writeln(output.dim(' claude-flow completions bash > ~/.bash_completion.d/claude-flow')); + output.writeln(output.dim(' source ~/.bash_completion.d/claude-flow')); + output.writeln(); + output.writeln(output.bold('Zsh:')); + output.writeln(output.dim(' mkdir -p ~/.zfunc')); + output.writeln(output.dim(' claude-flow completions zsh > ~/.zfunc/_claude-flow')); + output.writeln(output.dim(' # Add to ~/.zshrc: fpath=(~/.zfunc $fpath); autoload -Uz compinit && compinit')); + output.writeln(); + output.writeln(output.bold('Fish:')); + output.writeln(output.dim(' claude-flow completions fish > ~/.config/fish/completions/claude-flow.fish')); + output.writeln(); + output.writeln(output.bold('PowerShell:')); + output.writeln(output.dim(' claude-flow completions powershell >> $PROFILE')); + + return { success: true }; + } +}; + +export default completionsCommand; diff --git a/v3/@claude-flow/cli/src/commands/doctor.ts b/v3/@claude-flow/cli/src/commands/doctor.ts new file mode 100644 index 0000000000..a0629d5af5 --- /dev/null +++ b/v3/@claude-flow/cli/src/commands/doctor.ts @@ -0,0 +1,378 @@ +/** + * V3 CLI Doctor Command + * System diagnostics, dependency checks, config validation + * + * Created with ruv.io + */ + +import type { Command, CommandContext, CommandResult } from '../types.js'; +import { output } from '../output.js'; +import { existsSync, readFileSync } from 'fs'; +import { join } from 'path'; +import { execSync } from 'child_process'; + +interface HealthCheck { + name: string; + status: 'pass' | 'warn' | 'fail'; + message: string; + fix?: string; +} + +// Check Node.js version +async function checkNodeVersion(): Promise { + const requiredMajor = 20; + const version = process.version; + const major = parseInt(version.slice(1).split('.')[0], 10); + + if (major >= requiredMajor) { + return { name: 'Node.js Version', status: 'pass', message: `${version} (>= ${requiredMajor} required)` }; + } else if (major >= 18) { + return { name: 'Node.js Version', status: 'warn', message: `${version} (>= ${requiredMajor} recommended)`, fix: 'nvm install 20 && nvm use 20' }; + } else { + return { name: 'Node.js Version', status: 'fail', message: `${version} (>= ${requiredMajor} required)`, fix: 'nvm install 20 && nvm use 20' }; + } +} + +// Check npm version +async function checkNpmVersion(): Promise { + try { + const version = execSync('npm --version', { encoding: 'utf8' }).trim(); + const major = parseInt(version.split('.')[0], 10); + if (major >= 9) { + return { name: 'npm Version', status: 'pass', message: `v${version}` }; + } else { + return { name: 'npm Version', status: 'warn', message: `v${version} (>= 9 recommended)`, fix: 'npm install -g npm@latest' }; + } + } catch { + return { name: 'npm Version', status: 'fail', message: 'npm not found', fix: 'Install Node.js from https://nodejs.org' }; + } +} + +// Check config file +async function checkConfigFile(): Promise { + const configPaths = [ + '.claude-flow/config.json', + 'claude-flow.config.json', + '.claude-flow.json' + ]; + + for (const configPath of configPaths) { + if (existsSync(configPath)) { + try { + const content = readFileSync(configPath, 'utf8'); + JSON.parse(content); + return { name: 'Config File', status: 'pass', message: `Found: ${configPath}` }; + } catch (e) { + return { name: 'Config File', status: 'fail', message: `Invalid JSON: ${configPath}`, fix: 'Fix JSON syntax in config file' }; + } + } + } + + return { name: 'Config File', status: 'warn', message: 'No config file (using defaults)', fix: 'claude-flow config init' }; +} + +// Check daemon status +async function checkDaemonStatus(): Promise { + try { + const pidFile = '.claude-flow/daemon.pid'; + if (existsSync(pidFile)) { + const pid = readFileSync(pidFile, 'utf8').trim(); + try { + process.kill(parseInt(pid, 10), 0); // Check if process exists + return { name: 'Daemon Status', status: 'pass', message: `Running (PID: ${pid})` }; + } catch { + return { name: 'Daemon Status', status: 'warn', message: 'Stale PID file', fix: 'rm .claude-flow/daemon.pid && claude-flow daemon start' }; + } + } + return { name: 'Daemon Status', status: 'warn', message: 'Not running', fix: 'claude-flow daemon start' }; + } catch { + return { name: 'Daemon Status', status: 'warn', message: 'Unable to check', fix: 'claude-flow daemon status' }; + } +} + +// Check memory database +async function checkMemoryDatabase(): Promise { + const dbPaths = [ + '.claude-flow/memory.db', + '.swarm/memory.db', + 'data/memory.db' + ]; + + for (const dbPath of dbPaths) { + if (existsSync(dbPath)) { + try { + const stats = require('fs').statSync(dbPath); + const sizeMB = (stats.size / 1024 / 1024).toFixed(2); + return { name: 'Memory Database', status: 'pass', message: `${dbPath} (${sizeMB} MB)` }; + } catch { + return { name: 'Memory Database', status: 'warn', message: `${dbPath} (unable to stat)` }; + } + } + } + + return { name: 'Memory Database', status: 'warn', message: 'Not initialized', fix: 'claude-flow memory configure --backend hybrid' }; +} + +// Check API keys +async function checkApiKeys(): Promise { + const keys = ['ANTHROPIC_API_KEY', 'CLAUDE_API_KEY', 'OPENAI_API_KEY']; + const found: string[] = []; + + for (const key of keys) { + if (process.env[key]) { + found.push(key); + } + } + + if (found.includes('ANTHROPIC_API_KEY') || found.includes('CLAUDE_API_KEY')) { + return { name: 'API Keys', status: 'pass', message: `Found: ${found.join(', ')}` }; + } else if (found.length > 0) { + return { name: 'API Keys', status: 'warn', message: `Found: ${found.join(', ')} (no Claude key)`, fix: 'export ANTHROPIC_API_KEY=your_key' }; + } else { + return { name: 'API Keys', status: 'warn', message: 'No API keys found', fix: 'export ANTHROPIC_API_KEY=your_key' }; + } +} + +// Check git +async function checkGit(): Promise { + try { + const version = execSync('git --version', { encoding: 'utf8' }).trim(); + return { name: 'Git', status: 'pass', message: version.replace('git version ', 'v') }; + } catch { + return { name: 'Git', status: 'warn', message: 'Not installed', fix: 'Install git from https://git-scm.com' }; + } +} + +// Check if in git repo +async function checkGitRepo(): Promise { + try { + execSync('git rev-parse --git-dir', { encoding: 'utf8', stdio: 'pipe' }); + return { name: 'Git Repository', status: 'pass', message: 'In a git repository' }; + } catch { + return { name: 'Git Repository', status: 'warn', message: 'Not a git repository', fix: 'git init' }; + } +} + +// Check MCP servers +async function checkMcpServers(): Promise { + const mcpConfigPaths = [ + join(process.env.HOME || '', '.claude/claude_desktop_config.json'), + join(process.env.HOME || '', '.config/claude/mcp.json'), + '.mcp.json' + ]; + + for (const configPath of mcpConfigPaths) { + if (existsSync(configPath)) { + try { + const content = JSON.parse(readFileSync(configPath, 'utf8')); + const servers = content.mcpServers || content.servers || {}; + const count = Object.keys(servers).length; + const hasClaudeFlow = 'claude-flow' in servers || 'claude-flow_alpha' in servers; + if (hasClaudeFlow) { + return { name: 'MCP Servers', status: 'pass', message: `${count} servers (claude-flow configured)` }; + } else { + return { name: 'MCP Servers', status: 'warn', message: `${count} servers (claude-flow not found)`, fix: 'claude mcp add claude-flow npx @claude-flow/cli@v3alpha mcp start' }; + } + } catch { + // continue to next path + } + } + } + + return { name: 'MCP Servers', status: 'warn', message: 'No MCP config found', fix: 'claude mcp add claude-flow npx @claude-flow/cli@v3alpha mcp start' }; +} + +// Check disk space +async function checkDiskSpace(): Promise { + try { + if (process.platform === 'win32') { + return { name: 'Disk Space', status: 'pass', message: 'Check skipped on Windows' }; + } + const output_str = execSync('df -h . | tail -1', { encoding: 'utf8' }); + const parts = output_str.split(/\s+/); + const available = parts[3]; + const usePercent = parseInt(parts[4]?.replace('%', '') || '0', 10); + + if (usePercent > 90) { + return { name: 'Disk Space', status: 'fail', message: `${available} available (${usePercent}% used)`, fix: 'Free up disk space' }; + } else if (usePercent > 80) { + return { name: 'Disk Space', status: 'warn', message: `${available} available (${usePercent}% used)` }; + } + return { name: 'Disk Space', status: 'pass', message: `${available} available` }; + } catch { + return { name: 'Disk Space', status: 'warn', message: 'Unable to check' }; + } +} + +// Check TypeScript/build +async function checkBuildTools(): Promise { + try { + const tscVersion = execSync('npx tsc --version 2>/dev/null || echo "not found"', { encoding: 'utf8' }).trim(); + if (tscVersion.includes('not found')) { + return { name: 'TypeScript', status: 'warn', message: 'Not installed locally', fix: 'npm install -D typescript' }; + } + return { name: 'TypeScript', status: 'pass', message: tscVersion.replace('Version ', 'v') }; + } catch { + return { name: 'TypeScript', status: 'warn', message: 'Unable to check' }; + } +} + +// Format health check result +function formatCheck(check: HealthCheck): string { + const icon = check.status === 'pass' ? output.success('✓') : + check.status === 'warn' ? output.warning('⚠') : + output.error('✗'); + return `${icon} ${check.name}: ${check.message}`; +} + +// Main doctor command +export const doctorCommand: Command = { + name: 'doctor', + description: 'System diagnostics and health checks', + options: [ + { + name: 'fix', + short: 'f', + description: 'Show fix commands for issues', + type: 'boolean', + default: false + }, + { + name: 'component', + short: 'c', + description: 'Check specific component (node, config, daemon, memory, api, git, mcp)', + type: 'string' + }, + { + name: 'verbose', + short: 'v', + description: 'Verbose output', + type: 'boolean', + default: false + } + ], + examples: [ + { command: 'claude-flow doctor', description: 'Run full health check' }, + { command: 'claude-flow doctor --fix', description: 'Show fixes for issues' }, + { command: 'claude-flow doctor -c daemon', description: 'Check specific component' } + ], + action: async (ctx: CommandContext): Promise => { + const showFix = ctx.flags.fix as boolean; + const component = ctx.flags.component as string; + const verbose = ctx.flags.verbose as boolean; + + output.writeln(); + output.writeln(output.bold('Claude Flow Doctor')); + output.writeln(output.dim('System diagnostics and health check')); + output.writeln(output.dim('─'.repeat(50))); + output.writeln(); + + const allChecks: (() => Promise)[] = [ + checkNodeVersion, + checkNpmVersion, + checkGit, + checkGitRepo, + checkConfigFile, + checkDaemonStatus, + checkMemoryDatabase, + checkApiKeys, + checkMcpServers, + checkDiskSpace, + checkBuildTools + ]; + + const componentMap: Record Promise> = { + 'node': checkNodeVersion, + 'npm': checkNpmVersion, + 'config': checkConfigFile, + 'daemon': checkDaemonStatus, + 'memory': checkMemoryDatabase, + 'api': checkApiKeys, + 'git': checkGit, + 'mcp': checkMcpServers, + 'disk': checkDiskSpace, + 'typescript': checkBuildTools + }; + + let checksToRun = allChecks; + if (component && componentMap[component]) { + checksToRun = [componentMap[component]]; + } + + const results: HealthCheck[] = []; + const fixes: string[] = []; + + for (const check of checksToRun) { + const spinner = output.createSpinner({ text: 'Checking...', spinner: 'dots' }); + spinner.start(); + + try { + const result = await check(); + results.push(result); + + spinner.stop(); + output.writeln(formatCheck(result)); + + if (result.fix && (result.status === 'fail' || result.status === 'warn')) { + fixes.push(`${result.name}: ${result.fix}`); + } + } catch (error) { + spinner.stop(); + const errorResult: HealthCheck = { + name: 'Check', + status: 'fail', + message: error instanceof Error ? error.message : 'Unknown error' + }; + results.push(errorResult); + output.writeln(formatCheck(errorResult)); + } + } + + // Summary + const passed = results.filter(r => r.status === 'pass').length; + const warnings = results.filter(r => r.status === 'warn').length; + const failed = results.filter(r => r.status === 'fail').length; + + output.writeln(); + output.writeln(output.dim('─'.repeat(50))); + output.writeln(); + + const summaryParts = [ + output.success(`${passed} passed`), + warnings > 0 ? output.warning(`${warnings} warnings`) : null, + failed > 0 ? output.error(`${failed} failed`) : null + ].filter(Boolean); + + output.writeln(`Summary: ${summaryParts.join(', ')}`); + + // Show fixes + if (showFix && fixes.length > 0) { + output.writeln(); + output.writeln(output.bold('Suggested Fixes:')); + output.writeln(); + for (const fix of fixes) { + output.writeln(output.dim(` ${fix}`)); + } + } else if (fixes.length > 0 && !showFix) { + output.writeln(); + output.writeln(output.dim(`Run with --fix to see ${fixes.length} suggested fix${fixes.length > 1 ? 'es' : ''}`)); + } + + // Overall result + if (failed > 0) { + output.writeln(); + output.writeln(output.error('Some checks failed. Please address the issues above.')); + return { success: false, exitCode: 1, data: { passed, warnings, failed, results } }; + } else if (warnings > 0) { + output.writeln(); + output.writeln(output.warning('All checks passed with some warnings.')); + return { success: true, data: { passed, warnings, failed, results } }; + } else { + output.writeln(); + output.writeln(output.success('All checks passed! System is healthy.')); + return { success: true, data: { passed, warnings, failed, results } }; + } + } +}; + +export default doctorCommand; diff --git a/v3/@claude-flow/cli/src/commands/index.ts b/v3/@claude-flow/cli/src/commands/index.ts index 8dd5241978..dc1f0a5c6c 100644 --- a/v3/@claude-flow/cli/src/commands/index.ts +++ b/v3/@claude-flow/cli/src/commands/index.ts @@ -30,6 +30,9 @@ import { pluginsCommand } from './plugins.js'; import { deploymentCommand } from './deployment.js'; import { claimsCommand } from './claims.js'; import { embeddingsCommand } from './embeddings.js'; +// P0 Commands +import { completionsCommand } from './completions.js'; +import { doctorCommand } from './doctor.js'; // Export all commands export { agentCommand } from './agent.js'; @@ -58,6 +61,9 @@ export { pluginsCommand } from './plugins.js'; export { deploymentCommand } from './deployment.js'; export { claimsCommand } from './claims.js'; export { embeddingsCommand } from './embeddings.js'; +// P0 Commands +export { completionsCommand } from './completions.js'; +export { doctorCommand } from './doctor.js'; /** * All available commands @@ -90,6 +96,9 @@ export const commands: Command[] = [ deploymentCommand, claimsCommand, embeddingsCommand, + // P0 Commands + completionsCommand, + doctorCommand, ]; /** diff --git a/v3/@claude-flow/cli/src/commands/memory.ts b/v3/@claude-flow/cli/src/commands/memory.ts index 64685fefd3..019958e3f3 100644 --- a/v3/@claude-flow/cli/src/commands/memory.ts +++ b/v3/@claude-flow/cli/src/commands/memory.ts @@ -30,8 +30,8 @@ const storeCommand: Command = { }, { name: 'value', - short: 'v', - description: 'Value to store', + // Note: No short flag - global -v is reserved for verbose + description: 'Value to store (use --value)', type: 'string' }, { diff --git a/v3/@claude-flow/cli/src/index.ts b/v3/@claude-flow/cli/src/index.ts index 726e77b030..61b6678d1b 100644 --- a/v3/@claude-flow/cli/src/index.ts +++ b/v3/@claude-flow/cli/src/index.ts @@ -11,7 +11,8 @@ import { dirname, join } from 'path'; import type { Command, CommandContext, CommandResult, V3Config, CLIError } from './types.js'; import { CommandParser, commandParser } from './parser.js'; import { OutputFormatter, output } from './output.js'; -import { commands, commandRegistry, getCommand } from './commands/index.js'; +import { commands, commandRegistry, getCommand, getCommandNames } from './commands/index.js'; +import { suggestCommand } from './suggest.js'; // Read version from package.json at runtime function getPackageVersion(): string { @@ -114,7 +115,10 @@ export class CLI { if (!command) { this.output.printError(`Unknown command: ${commandName}`); - this.output.writeln(`Run "${this.name} --help" for available commands`); + // Smart suggestions + const availableCommands = Array.from(new Set(commands.map(c => c.name))); + const { message } = suggestCommand(commandName, availableCommands); + this.output.writeln(this.output.dim(` ${message}`)); process.exit(1); } diff --git a/v3/@claude-flow/cli/src/suggest.ts b/v3/@claude-flow/cli/src/suggest.ts new file mode 100644 index 0000000000..247c97dc87 --- /dev/null +++ b/v3/@claude-flow/cli/src/suggest.ts @@ -0,0 +1,245 @@ +/** + * V3 CLI Smart Error Suggestions + * Levenshtein distance and command suggestions + * + * Created with ruv.io + */ + +/** + * Calculate Levenshtein distance between two strings + */ +export function levenshteinDistance(a: string, b: string): number { + const m = a.length; + const n = b.length; + + // Early termination for empty strings + if (m === 0) return n; + if (n === 0) return m; + + // Create distance matrix + const d: number[][] = Array(m + 1).fill(null).map(() => Array(n + 1).fill(0)); + + // Initialize first column + for (let i = 0; i <= m; i++) { + d[i][0] = i; + } + + // Initialize first row + for (let j = 0; j <= n; j++) { + d[0][j] = j; + } + + // Fill in the rest of the matrix + for (let j = 1; j <= n; j++) { + for (let i = 1; i <= m; i++) { + const cost = a[i - 1] === b[j - 1] ? 0 : 1; + d[i][j] = Math.min( + d[i - 1][j] + 1, // deletion + d[i][j - 1] + 1, // insertion + d[i - 1][j - 1] + cost // substitution + ); + } + } + + return d[m][n]; +} + +/** + * Calculate similarity score (0-1) between two strings + */ +export function similarityScore(a: string, b: string): number { + const maxLen = Math.max(a.length, b.length); + if (maxLen === 0) return 1; + const distance = levenshteinDistance(a.toLowerCase(), b.toLowerCase()); + return 1 - distance / maxLen; +} + +/** + * Find similar strings from a list + */ +export function findSimilar( + input: string, + candidates: string[], + options: { + maxSuggestions?: number; + minSimilarity?: number; + maxDistance?: number; + } = {} +): string[] { + const { + maxSuggestions = 3, + minSimilarity = 0.4, + maxDistance = 3 + } = options; + + const inputLower = input.toLowerCase(); + + // Score all candidates + const scored = candidates + .map(candidate => ({ + candidate, + distance: levenshteinDistance(inputLower, candidate.toLowerCase()), + similarity: similarityScore(inputLower, candidate), + // Boost prefix matches + prefixBoost: candidate.toLowerCase().startsWith(inputLower) ? 0.3 : 0 + })) + .filter(s => s.distance <= maxDistance || s.similarity >= minSimilarity) + .map(s => ({ + ...s, + score: s.similarity + s.prefixBoost + })) + .sort((a, b) => b.score - a.score) + .slice(0, maxSuggestions); + + return scored.map(s => s.candidate); +} + +/** + * Format suggestion message for CLI errors + */ +export function formatSuggestion( + invalidInput: string, + suggestions: string[], + context: 'command' | 'subcommand' | 'option' | 'value' = 'command' +): string { + if (suggestions.length === 0) { + return ''; + } + + const contextMap = { + command: 'Did you mean', + subcommand: 'Available subcommands', + option: 'Did you mean', + value: 'Valid values' + }; + + const prefix = contextMap[context]; + + if (suggestions.length === 1) { + return `\n ${prefix}: ${suggestions[0]}`; + } + + return `\n ${prefix}:\n${suggestions.map(s => ` - ${s}`).join('\n')}`; +} + +/** + * Common typos and their corrections + */ +export const COMMON_TYPOS: Record = { + 'init': 'init', + 'initi': 'init', + 'inizialize': 'init', + 'staus': 'status', + 'stauts': 'status', + 'stats': 'stats', + 'stat': 'status', + 'swarrm': 'swarm', + 'swarn': 'swarm', + 'agnet': 'agent', + 'agen': 'agent', + 'memroy': 'memory', + 'mem': 'memory', + 'memmory': 'memory', + 'confg': 'config', + 'conf': 'config', + 'configu': 'config', + 'hook': 'hooks', + 'hoks': 'hooks', + 'hive': 'hive-mind', + 'hivemind': 'hive-mind', + 'hive_mind': 'hive-mind', + 'neurl': 'neural', + 'nueral': 'neural', + 'securty': 'security', + 'sec': 'security', + 'perf': 'performance', + 'performace': 'performance', + 'provider': 'providers', + 'plugin': 'plugins', + 'dep': 'deployment', + 'depoly': 'deployment', + 'deploy': 'deployment', + 'claim': 'claims', + 'embed': 'embeddings', + 'embeding': 'embeddings', + 'daemon': 'daemon', + 'deamon': 'daemon', + 'doc': 'doctor', + 'docter': 'doctor', + 'complete': 'completions', + 'completion': 'completions', + 'comp': 'completions', + 'task': 'task', + 'taks': 'task', + 'sessio': 'session', + 'sess': 'session', + 'sesssion': 'session', + 'workflow': 'workflow', + 'wf': 'workflow', + 'wokflow': 'workflow' +}; + +/** + * Get corrected command if it's a common typo + */ +export function getTypoCorrection(input: string): string | undefined { + return COMMON_TYPOS[input.toLowerCase()]; +} + +/** + * Smart command suggestion for unknown commands + */ +export function suggestCommand( + unknownCommand: string, + availableCommands: string[] +): { + correction?: string; + suggestions: string[]; + message: string; +} { + // Check for common typo first + const correction = getTypoCorrection(unknownCommand); + if (correction && availableCommands.includes(correction)) { + return { + correction, + suggestions: [correction], + message: `Did you mean "${correction}"?` + }; + } + + // Find similar commands + const suggestions = findSimilar(unknownCommand, availableCommands, { + maxSuggestions: 3, + minSimilarity: 0.3, + maxDistance: 4 + }); + + if (suggestions.length === 0) { + return { + suggestions: [], + message: 'Run "claude-flow --help" to see available commands.' + }; + } + + if (suggestions.length === 1) { + return { + suggestions, + message: `Did you mean "${suggestions[0]}"?` + }; + } + + return { + suggestions, + message: `Did you mean one of these?\n${suggestions.map(s => ` - ${s}`).join('\n')}` + }; +} + +export default { + levenshteinDistance, + similarityScore, + findSimilar, + formatSuggestion, + suggestCommand, + getTypoCorrection, + COMMON_TYPOS +}; diff --git a/v3/@claude-flow/embeddings/agents/architect.yaml b/v3/@claude-flow/embeddings/agents/architect.yaml index 2f8632fc1c..60e6b327b2 100644 --- a/v3/@claude-flow/embeddings/agents/architect.yaml +++ b/v3/@claude-flow/embeddings/agents/architect.yaml @@ -8,4 +8,4 @@ capabilities: optimizations: - context-caching - memory-persistence -createdAt: "2026-01-07T04:20:22.495Z" +createdAt: "2026-01-07T04:34:45.999Z" diff --git a/v3/@claude-flow/embeddings/agents/coder.yaml b/v3/@claude-flow/embeddings/agents/coder.yaml index 48396c28f7..16dd32c575 100644 --- a/v3/@claude-flow/embeddings/agents/coder.yaml +++ b/v3/@claude-flow/embeddings/agents/coder.yaml @@ -8,4 +8,4 @@ capabilities: optimizations: - flash-attention - token-reduction -createdAt: "2026-01-07T04:20:22.494Z" +createdAt: "2026-01-07T04:34:45.999Z" diff --git a/v3/@claude-flow/embeddings/agents/reviewer.yaml b/v3/@claude-flow/embeddings/agents/reviewer.yaml index 8a9347d1ab..a178bc138b 100644 --- a/v3/@claude-flow/embeddings/agents/reviewer.yaml +++ b/v3/@claude-flow/embeddings/agents/reviewer.yaml @@ -7,4 +7,4 @@ capabilities: - best-practices optimizations: - incremental-analysis -createdAt: "2026-01-07T04:20:22.495Z" +createdAt: "2026-01-07T04:34:46.000Z" diff --git a/v3/@claude-flow/embeddings/agents/security-architect.yaml b/v3/@claude-flow/embeddings/agents/security-architect.yaml index 26f15b36a6..d633a16b23 100644 --- a/v3/@claude-flow/embeddings/agents/security-architect.yaml +++ b/v3/@claude-flow/embeddings/agents/security-architect.yaml @@ -7,4 +7,4 @@ capabilities: - security-review optimizations: - pattern-matching -createdAt: "2026-01-07T04:20:22.495Z" +createdAt: "2026-01-07T04:34:46.000Z" diff --git a/v3/@claude-flow/embeddings/agents/tester.yaml b/v3/@claude-flow/embeddings/agents/tester.yaml index 3f8eccc73b..7f017c417f 100644 --- a/v3/@claude-flow/embeddings/agents/tester.yaml +++ b/v3/@claude-flow/embeddings/agents/tester.yaml @@ -7,4 +7,4 @@ capabilities: - coverage optimizations: - parallel-execution -createdAt: "2026-01-07T04:20:22.495Z" +createdAt: "2026-01-07T04:34:46.000Z" diff --git a/v3/@claude-flow/embeddings/src/persistent-cache.ts b/v3/@claude-flow/embeddings/src/persistent-cache.ts new file mode 100644 index 0000000000..341d7a608f --- /dev/null +++ b/v3/@claude-flow/embeddings/src/persistent-cache.ts @@ -0,0 +1,314 @@ +/** + * SQLite-backed Persistent Cache for Embeddings + * + * Features: + * - Disk persistence across sessions + * - LRU eviction with configurable max size + * - Automatic schema creation + * - TTL support for cache entries + * - Lazy initialization (no startup cost if not used) + */ + +import { existsSync, mkdirSync } from 'fs'; +import { dirname } from 'path'; + +// SQLite types (dynamically imported) +type Database = { + prepare(sql: string): Statement; + exec(sql: string): void; + close(): void; +}; + +type Statement = { + run(...params: unknown[]): { changes: number }; + get(...params: unknown[]): unknown; + all(...params: unknown[]): unknown[]; +}; + +/** + * Configuration for persistent cache + */ +export interface PersistentCacheConfig { + /** Path to SQLite database file */ + dbPath: string; + /** Maximum number of entries (default: 10000) */ + maxSize?: number; + /** TTL in milliseconds (default: 7 days) */ + ttlMs?: number; + /** Enable compression for large embeddings */ + compress?: boolean; +} + +/** + * Cache statistics + */ +export interface PersistentCacheStats { + size: number; + maxSize: number; + hitRate: number; + hits: number; + misses: number; + dbSizeBytes?: number; +} + +/** + * SQLite-backed persistent embedding cache + */ +export class PersistentEmbeddingCache { + private db: Database | null = null; + private initialized = false; + private hits = 0; + private misses = 0; + + private readonly dbPath: string; + private readonly maxSize: number; + private readonly ttlMs: number; + + constructor(config: PersistentCacheConfig) { + this.dbPath = config.dbPath; + this.maxSize = config.maxSize ?? 10000; + this.ttlMs = config.ttlMs ?? 7 * 24 * 60 * 60 * 1000; // 7 days + } + + /** + * Lazily initialize database connection + */ + private async ensureInitialized(): Promise { + if (this.initialized) return; + + try { + // Dynamically import better-sqlite3 + const BetterSqlite3 = (await import('better-sqlite3')).default; + + // Ensure directory exists + const dir = dirname(this.dbPath); + if (!existsSync(dir)) { + mkdirSync(dir, { recursive: true }); + } + + this.db = new BetterSqlite3(this.dbPath) as unknown as Database; + + // Create schema + this.db.exec(` + CREATE TABLE IF NOT EXISTS embeddings ( + key TEXT PRIMARY KEY, + embedding BLOB NOT NULL, + dimensions INTEGER NOT NULL, + created_at INTEGER NOT NULL, + accessed_at INTEGER NOT NULL, + access_count INTEGER DEFAULT 1 + ); + + CREATE INDEX IF NOT EXISTS idx_accessed_at ON embeddings(accessed_at); + CREATE INDEX IF NOT EXISTS idx_created_at ON embeddings(created_at); + `); + + // Clean expired entries on startup + this.cleanExpired(); + + this.initialized = true; + } catch (error) { + // If better-sqlite3 not available, fall back gracefully + console.warn('[persistent-cache] SQLite not available, cache disabled:', + error instanceof Error ? error.message : error); + this.initialized = true; // Mark as initialized to prevent retry + } + } + + /** + * Generate cache key from text + */ + private hashKey(text: string): string { + // FNV-1a hash for fast, deterministic key generation + let hash = 0x811c9dc5; + for (let i = 0; i < text.length; i++) { + hash ^= text.charCodeAt(i); + hash = (hash * 0x01000193) >>> 0; + } + return `emb_${hash.toString(16)}_${text.length}`; + } + + /** + * Serialize Float32Array to Buffer + */ + private serializeEmbedding(embedding: Float32Array): Buffer { + return Buffer.from(embedding.buffer, embedding.byteOffset, embedding.byteLength); + } + + /** + * Deserialize Buffer to Float32Array + */ + private deserializeEmbedding(buffer: Buffer, dimensions: number): Float32Array { + const arrayBuffer = buffer.buffer.slice( + buffer.byteOffset, + buffer.byteOffset + buffer.byteLength + ); + return new Float32Array(arrayBuffer); + } + + /** + * Get embedding from cache + */ + async get(text: string): Promise { + await this.ensureInitialized(); + if (!this.db) { + this.misses++; + return null; + } + + const key = this.hashKey(text); + const now = Date.now(); + + try { + const row = this.db.prepare(` + SELECT embedding, dimensions, created_at + FROM embeddings + WHERE key = ? + `).get(key) as { embedding: Buffer; dimensions: number; created_at: number } | undefined; + + if (!row) { + this.misses++; + return null; + } + + // Check TTL + if (now - row.created_at > this.ttlMs) { + this.db.prepare('DELETE FROM embeddings WHERE key = ?').run(key); + this.misses++; + return null; + } + + // Update access time and count + this.db.prepare(` + UPDATE embeddings + SET accessed_at = ?, access_count = access_count + 1 + WHERE key = ? + `).run(now, key); + + this.hits++; + return this.deserializeEmbedding(row.embedding, row.dimensions); + } catch (error) { + console.error('[persistent-cache] Get error:', error); + this.misses++; + return null; + } + } + + /** + * Store embedding in cache + */ + async set(text: string, embedding: Float32Array): Promise { + await this.ensureInitialized(); + if (!this.db) return; + + const key = this.hashKey(text); + const now = Date.now(); + const buffer = this.serializeEmbedding(embedding); + + try { + // Upsert entry + this.db.prepare(` + INSERT INTO embeddings (key, embedding, dimensions, created_at, accessed_at, access_count) + VALUES (?, ?, ?, ?, ?, 1) + ON CONFLICT(key) DO UPDATE SET + embedding = excluded.embedding, + accessed_at = excluded.accessed_at, + access_count = access_count + 1 + `).run(key, buffer, embedding.length, now, now); + + // Check size and evict if needed + await this.evictIfNeeded(); + } catch (error) { + console.error('[persistent-cache] Set error:', error); + } + } + + /** + * Evict oldest entries if cache exceeds max size + */ + private async evictIfNeeded(): Promise { + if (!this.db) return; + + const count = (this.db.prepare('SELECT COUNT(*) as count FROM embeddings').get() as { count: number }).count; + + if (count > this.maxSize) { + const toDelete = count - this.maxSize + Math.floor(this.maxSize * 0.1); // Delete 10% extra + this.db.prepare(` + DELETE FROM embeddings + WHERE key IN ( + SELECT key FROM embeddings + ORDER BY accessed_at ASC + LIMIT ? + ) + `).run(toDelete); + } + } + + /** + * Clean expired entries + */ + private cleanExpired(): void { + if (!this.db) return; + + const cutoff = Date.now() - this.ttlMs; + this.db.prepare('DELETE FROM embeddings WHERE created_at < ?').run(cutoff); + } + + /** + * Get cache statistics + */ + async getStats(): Promise { + await this.ensureInitialized(); + + const total = this.hits + this.misses; + const stats: PersistentCacheStats = { + size: 0, + maxSize: this.maxSize, + hitRate: total > 0 ? this.hits / total : 0, + hits: this.hits, + misses: this.misses, + }; + + if (this.db) { + const row = this.db.prepare('SELECT COUNT(*) as count FROM embeddings').get() as { count: number }; + stats.size = row.count; + } + + return stats; + } + + /** + * Clear all cached entries + */ + async clear(): Promise { + await this.ensureInitialized(); + if (!this.db) return; + + this.db.exec('DELETE FROM embeddings'); + this.hits = 0; + this.misses = 0; + } + + /** + * Close database connection + */ + async close(): Promise { + if (this.db) { + this.db.close(); + this.db = null; + this.initialized = false; + } + } +} + +/** + * Check if persistent cache is available (better-sqlite3 installed) + */ +export async function isPersistentCacheAvailable(): Promise { + try { + await import('better-sqlite3'); + return true; + } catch { + return false; + } +}