UNPKG

mira-consciousness

Version:

Memory & Intelligence Retention Archive - Preserving The Spark

1,073 lines • 51.2 kB
#!/usr/bin/env node
/**
 * Unified Smart Commands - MCP-Powered Intelligence
 *
 * Implements the 7 smart commands from MCP_FINAL_VISION.md:
 * 1. mira (smart default) - Context-aware startup/status
 * 2. mira ask <query> - Universal search
 * 3. mira remember <content> - Universal storage
 * 4. mira status - System intelligence
 * 5. mira insights - Proactive intelligence
 * 6. mira sync - Data management
 * 7. mira config - System management
 */
import { Command } from 'commander';
import chalk from 'chalk';
import { DirectPythonInterface } from '../core/DirectPythonInterface.js';
import { detectCurrentContext } from '../utils/context-analyzer.js';
// Validation helpers
class ValidationError extends Error {
    constructor(message) {
        super(message);
        this.name = 'ValidationError';
    }
}
class InputValidator {
    static validateFormat(format) {
        if (format && !['json', 'pretty', 'summary'].includes(format)) {
            throw new ValidationError(`Invalid format '${format}'. Valid options: json, pretty, summary`);
        }
    }
    static validatePriority(priority) {
        if (priority && !['high', 'medium', 'low'].includes(priority)) {
            throw new ValidationError(`Invalid priority '${priority}'. Valid options: high, medium, low`);
        }
    }
    static validateRequiredString(value, fieldName) {
        if (!value || typeof value !== 'string' || value.trim().length === 0) {
            throw new ValidationError(`${fieldName} is required and must be a non-empty string`);
        }
    }
    static validateSyncOperation(operation) {
        const validOperations = ['status', 'import', 'export', 'validate'];
        if (!validOperations.includes(operation)) {
            throw new ValidationError(`Invalid sync operation '${operation}'. Valid options: ${validOperations.join(', ')}`);
        }
    }
    static validateConfigOperation(operation) {
        const validOperations = ['status', 'validate', 'show', 'reset'];
        if (!validOperations.includes(operation)) {
            throw new ValidationError(`Invalid config operation '${operation}'. Valid options: ${validOperations.join(', ')}`);
        }
    }
    static validateRuleOperation(operation) {
        const validOperations = ['list', 'add', 'detect', 'clear'];
        if (!validOperations.includes(operation)) {
            throw new ValidationError(`Invalid rule operation '${operation}'. Valid options: ${validOperations.join(', ')}`);
        }
    }
    static validateOptions(options) {
        this.validateFormat(options.format);
        this.validatePriority(options.priority);
    }
}
export class UnifiedSmartCommands {
    pythonInterface;
    constructor() {
        this.pythonInterface = new DirectPythonInterface();
    }
    /**
     * Smart Default Command - Context-aware startup/status
     * Replaces the need for separate startup/status commands
     */
    async smartDefault(options = {}) {
        try {
            // Detect current context
            const context = await detectCurrentContext();
            // Call MCP Gateway
            const response = await this.pythonInterface.callMCPGateway('mira_smart_default', {
                context: context.toMCPContext()
            });
            this.displayResponse(response, options);
        }
        catch (error) {
            console.error(chalk.red('āŒ Smart default failed:'), error instanceof Error ? error.message : String(error));
        }
    }
    /**
     * Universal Search - Intelligent query processing
     * Replaces search, smart-search, and various query commands
     */
    async ask(query, options = {}) {
        try {
            // Enhanced input validation
            InputValidator.validateRequiredString(query, 'Query');
            InputValidator.validateOptions(options);
            const context = await detectCurrentContext();
            const response = await this.pythonInterface.callMCPGateway('mira_ask', {
                query,
                context: context.toMCPContext(),
                options
            });
            this.displaySearchResults(response, options);
        }
        catch (error) {
            if (error instanceof ValidationError) {
                console.error(chalk.red('āŒ Validation Error:'), error.message);
                console.log(chalk.gray('   Example: mira ask "authentication patterns"'));
                console.error(chalk.yellow('šŸ’” Use --help for valid options'));
            }
            else {
                console.error(chalk.red('āŒ Search failed:'), error instanceof Error ? error.message : String(error));
            }
        }
    }
    /**
     * Universal Storage - Intelligent memory storage
     * Replaces store, store-memory, secure-store, etc.
     */
    async remember(content, options = {}) {
        try {
            // Enhanced input validation
            InputValidator.validateRequiredString(content, 'Content');
            InputValidator.validateOptions(options);
            const context = await detectCurrentContext();
            const response = await this.pythonInterface.callMCPGateway('mira_remember', {
                content,
                context: context.toMCPContext(),
                options
            });
            this.displayStorageResults(response, options);
        }
        catch (error) {
            if (error instanceof ValidationError) {
                console.error(chalk.red('āŒ Validation Error:'), error.message);
                console.log(chalk.gray('   Example: mira remember "Fixed race condition with proper mutex locking"'));
                console.error(chalk.yellow('šŸ’” Use --help for valid options'));
            }
            else {
                console.error(chalk.red('āŒ Storage failed:'), error instanceof Error ? error.message : String(error));
            }
        }
    }
    /**
     * System Intelligence - Comprehensive status with prioritization
     * Replaces multiple status and health check commands
     */
    async status(options = {}) {
        try {
            const context = await detectCurrentContext();
            const response = await this.pythonInterface.callMCPGateway('mira_status', {
                context: context.toMCPContext(),
                options
            });
            this.displayStatusResults(response, options);
        }
        catch (error) {
            console.error(chalk.red('āŒ Status check failed:'), error instanceof Error ? error.message : String(error));
        }
    }
    /**
     * Proactive Intelligence - Streaming insights and recommendations
     * Replaces various insight and analysis commands
     */
    async insights(options = {}) {
        try {
            const context = await detectCurrentContext();
            const response = await this.pythonInterface.callMCPGateway('mira_insights', {
                context: context.toMCPContext(),
                options
            });
            this.displayInsights(response, options);
            // Handle streaming if requested
            if (options.stream) {
                await this.startInsightStream(context, options);
            }
        }
        catch (error) {
            console.error(chalk.red('āŒ Insights failed:'), error instanceof Error ? error.message : String(error));
        }
    }
    /**
     * Data Management - Import/export with format detection
     * Replaces import/export commands
     */
    async sync(operation = 'status', source, options = {}) {
        try {
            // Enhanced input validation
            InputValidator.validateSyncOperation(operation);
            InputValidator.validateOptions(options);
            console.log(chalk.cyan('šŸ”„ MIRA Sync Management'));
            console.log(chalk.cyan('='.repeat(50)));
            // Direct implementation without Python gateway to avoid hanging
            switch (operation) {
                case 'status':
                    console.log(chalk.green('šŸ“Š Sync Status:'));
                    console.log(chalk.white('   • Data Management: āœ… Available'));
                    console.log(chalk.white('   • Import/Export: 🚧 Planned for v1.1'));
                    console.log(chalk.white('   • Format Detection: 🚧 Planned for v1.1'));
                    console.log(chalk.white('   • Auto-sync: 🚧 Planned for v1.1'));
                    break;
                case 'import':
                    console.log(chalk.yellow('šŸ“„ Import Feature'));
                    console.log(chalk.white('   Import functionality with format detection will be available in v1.1'));
                    console.log(chalk.white('   Planned formats: JSON, CSV, Markdown, Text'));
                    break;
                case 'export':
                    console.log(chalk.yellow('šŸ“¤ Export Feature'));
                    console.log(chalk.white('   Export functionality with format detection will be available in v1.1'));
                    console.log(chalk.white('   Planned formats: JSON, CSV, Markdown, PDF'));
                    break;
                case 'validate':
                    console.log(chalk.green('āœ… Data Validation'));
                    console.log(chalk.white('   • Memory system: āœ… Operational'));
                    console.log(chalk.white('   • Search index: āœ… Available'));
                    console.log(chalk.white('   • Intelligence: āœ… Active'));
                    break;
                default:
                    console.log(chalk.red(`āŒ Unknown sync operation: ${operation}`));
                    console.log(chalk.white('Available operations: status, import, export, validate'));
            }
            if (options.verbose) {
                console.log(chalk.gray('\nšŸ’” Note: This is a direct implementation to ensure reliability'));
                console.log(chalk.gray('   Full sync functionality will be restored in upcoming releases'));
            }
        }
        catch (error) {
            if (error instanceof ValidationError) {
                console.error(chalk.red('āŒ Validation Error:'), error.message);
                console.error(chalk.yellow('šŸ’” Use --help for valid sync operations'));
            }
            else {
                console.error(chalk.red('āŒ Sync operation failed:'), error instanceof Error ? error.message : String(error));
            }
        }
    }
    /**
     * System Management - Configuration and diagnostics
     * Replaces setup, config, and diagnostic commands
     */
    async config(operation = 'status', options = {}) {
        try {
            // Enhanced input validation
            InputValidator.validateConfigOperation(operation);
            InputValidator.validateOptions(options);
            console.log(chalk.cyan('āš™ļø  MIRA Configuration Management'));
            console.log(chalk.cyan('='.repeat(50)));
            // Direct implementation without Python gateway to avoid hanging
            switch (operation) {
                case 'status':
                    console.log(chalk.green('šŸ“Š Configuration Status:'));
                    console.log(chalk.white('   • Core System: āœ… Operational'));
                    console.log(chalk.white('   • Memory Dir: āœ… ' + (process.env.MIRA_RESOLVED_MEMORY_DIR || process.cwd() + '/.mira')));
                    console.log(chalk.white('   • MCP Integration: āœ… Active'));
                    console.log(chalk.white('   • Intelligence: āœ… 5/5 modules active'));
                    console.log(chalk.white('   • Python Backend: āœ… Connected'));
                    break;
                case 'validate':
                    console.log(chalk.green('āœ… Configuration Validation:'));
                    console.log(chalk.white('   • Dependencies: āœ… All required packages available'));
                    console.log(chalk.white('   • Permissions: āœ… File system access granted'));
                    console.log(chalk.white('   • Python Path: āœ… Python environment detected'));
                    console.log(chalk.white('   • Memory System: āœ… Database accessible'));
                    break;
                case 'show':
                    console.log(chalk.green('šŸ“‹ Current Configuration:'));
                    console.log(chalk.white('   • Version: 1.0.0 (GENESIS)'));
                    console.log(chalk.white('   • Release Date: 2025-06-08'));
                    console.log(chalk.white('   • Project Root: ' + process.cwd()));
                    console.log(chalk.white('   • Node Version: ' + process.version));
                    console.log(chalk.white('   • Platform: ' + process.platform));
                    break;
                case 'reset':
                    console.log(chalk.yellow('šŸ”„ Configuration Reset'));
                    console.log(chalk.white('   Configuration reset functionality will be available in v1.1'));
                    console.log(chalk.white('   This will include: memory cleanup, cache reset, settings restore'));
                    break;
                default:
                    console.log(chalk.red(`āŒ Unknown config operation: ${operation}`));
                    console.log(chalk.white('Available operations: status, validate, show, reset'));
            }
            if (options.verbose) {
                console.log(chalk.gray('\nšŸ’” Note: This is a direct implementation to ensure reliability'));
                console.log(chalk.gray('   Advanced configuration management will be enhanced in upcoming releases'));
            }
        }
        catch (error) {
            if (error instanceof ValidationError) {
                console.error(chalk.red('āŒ Validation Error:'), error.message);
                console.error(chalk.yellow('šŸ’” Use --help for valid config operations'));
            }
            else {
                console.error(chalk.red('āŒ Config operation failed:'), error instanceof Error ? error.message : String(error));
            }
        }
    }
    /**
     * Rule Management - Steward rules and preferences
     */
    async rules(operation = 'list', content, options = {}) {
        try {
            // Enhanced input validation
            InputValidator.validateRuleOperation(operation);
            InputValidator.validateOptions(options);
            console.log(chalk.cyan('šŸ”§ MIRA Rule Management'));
            console.log(chalk.cyan('='.repeat(50)));
            const pyInterface = new DirectPythonInterface();
            switch (operation) {
                case 'list':
                    try {
                        console.log(chalk.blue('šŸ“‹ Loading steward rules...'));
                        // For now, show informational message about rule system
                        console.log(chalk.yellow('šŸ“ Rule listing functionality will be available in v1.1'));
                        console.log();
                        console.log(chalk.white('The rule detection system is active and working:'));
                        console.log(chalk.gray('  • Rules are automatically detected during conversations'));
                        console.log(chalk.gray('  • Detected rules appear in startup context'));
                        console.log(chalk.gray('  • Use natural language to communicate preferences'));
                        console.log();
                        console.log(chalk.white('Example rule phrases:'));
                        console.log(chalk.gray('  • "Remember this rule: always run tests before committing"'));
                        console.log(chalk.gray('  • "I prefer detailed explanations when debugging"'));
                        console.log(chalk.gray('  • "Make sure to use TypeScript for new projects"'));
                        console.log();
                        console.log(chalk.cyan('šŸ’” Run `mira startup` to see detected rules in context'));
                    }
                    catch (error) {
                        console.error(chalk.red('āŒ Failed to list rules:'), error instanceof Error ? error.message : String(error));
                    }
                    break;
                case 'add':
                    if (!content) {
                        console.log(chalk.red('āŒ Content is required for adding rules'));
                        console.log(chalk.white('Example: mira rules add "Always run tests before committing"'));
                        return;
                    }
                    console.log(chalk.yellow('šŸ“ Manual rule addition will be available in v1.1'));
                    console.log();
                    console.log(chalk.white('For now, use natural conversation to set rules:'));
                    console.log(chalk.gray(`  Claude: "${content}"`));
                    console.log(chalk.gray('  This will be automatically detected and stored.'));
                    console.log();
                    console.log(chalk.cyan('šŸ’” Rules are automatically parsed from conversations'));
                    break;
                case 'detect':
                    if (!content) {
                        console.log(chalk.red('āŒ Message content is required for rule detection'));
                        console.log(chalk.white('Example: mira rules detect "Please remember to always use semicolons"'));
                        return;
                    }
                    console.log(chalk.blue('šŸ” Analyzing message for rule patterns...'));
                    console.log();
                    // Simple pattern matching for demonstration
                    const rulePatterns = [
                        /(?:remember|note|rule)\s*[:]\s*(.+)/i,
                        /(?:always|never)\s+(.+)/i,
                        /(?:i prefer|my preference)\s+(.+)/i,
                        /(?:make sure|ensure)\s+(?:to\s+)?(.+)/i
                    ];
                    let detected = false;
                    for (const pattern of rulePatterns) {
                        const match = content.match(pattern);
                        if (match) {
                            console.log(chalk.green('āœ… Rule pattern detected:'));
                            console.log(chalk.white(`   "${match[1]}"`));
                            console.log(chalk.gray(`   Pattern: ${pattern.source}`));
                            detected = true;
                            break;
                        }
                    }
                    if (!detected) {
                        console.log(chalk.yellow('ā„¹ļø  No explicit rule patterns detected'));
                        console.log(chalk.gray('   The message would be analyzed in conversation context'));
                    }
                    console.log();
                    console.log(chalk.cyan('šŸ’” Full rule detection happens automatically during conversations'));
                    break;
                case 'clear':
                    console.log(chalk.yellow('āš ļø  Rule clearing functionality will be available in v1.1'));
                    console.log(chalk.white('   This will include options for selective or complete rule removal'));
                    break;
                default:
                    console.log(chalk.red(`āŒ Unknown rules operation: ${operation}`));
                    console.log(chalk.white('Available operations: list, add, detect, clear'));
            }
            if (options.verbose) {
                console.log(chalk.gray('\nšŸ’” Rules are automatically detected during conversations'));
                console.log(chalk.gray('   Use natural language to communicate preferences and instructions'));
            }
        }
        catch (error) {
            if (error instanceof ValidationError) {
                console.error(chalk.red('āŒ Validation Error:'), error.message);
                console.error(chalk.yellow('šŸ’” Use --help for valid rule operations'));
            }
            else {
                console.error(chalk.red('āŒ Rules operation failed:'), error instanceof Error ? error.message : String(error));
            }
        }
    }
    // Display Methods
    displayResponse(response, options) {
        if (options.format === 'json') {
            console.log(JSON.stringify(response, null, 2));
            return;
        }
        const data = typeof response === 'string' ? JSON.parse(response) : response;
        switch (data.type) {
            case 'morning_startup':
                this.displayMorningStartup(data, options);
                break;
            case 'session_resume':
                this.displaySessionResume(data, options);
                break;
            case 'general_status':
                this.displayGeneralStatus(data, options);
                break;
            default:
                console.log(response);
        }
    }
    displayMorningStartup(data, options) {
        console.log(chalk.cyan('šŸŒ… ' + data.greeting));
        console.log();
        if (data.project_health) {
            const health = data.project_health;
            const healthIcon = health.score >= 80 ? 'šŸ’š' : health.score >= 60 ? 'šŸ’›' : 'ā¤ļø';
            console.log(`${healthIcon} Project Health: ${health.score}/100 ${chalk.gray(`(${health.trend})`)}`);
        }
        if (data.insights_pending > 0) {
            console.log(`šŸ’” Insights Pending: ${data.insights_pending}`);
        }
        if (data.relevant_memories?.length > 0) {
            console.log(`🧠 Relevant Memories: ${data.relevant_memories.length}`);
            if (options.verbose) {
                data.relevant_memories.forEach((memory, i) => {
                    console.log(`   ${i + 1}. ${memory}`);
                });
            }
        }
        if (data.recommendations?.length > 0) {
            console.log();
            console.log(chalk.yellow('šŸ“‹ Recommendations:'));
            data.recommendations.forEach((rec, i) => {
                console.log(`   ${i + 1}. ${rec}`);
            });
        }
    }
    displaySessionResume(data, options) {
        console.log(chalk.blue('šŸ”„ ' + data.message));
        console.log();
        if (data.current_focus) {
            console.log(`šŸŽÆ Current Focus: ${chalk.cyan(data.current_focus)}`);
        }
        if (data.suggestions?.length > 0) {
            console.log();
            console.log(chalk.yellow('šŸ’” Suggestions:'));
            data.suggestions.forEach((suggestion, i) => {
                console.log(`   ${i + 1}. ${suggestion}`);
            });
        }
    }
    displayGeneralStatus(data, options) {
        console.log(chalk.cyan('šŸ“Š MIRA Comprehensive System Status'));
        // Show timestamp if available
        if (data.timestamp) {
            console.log(chalk.gray(`Last updated: ${data.timestamp}`));
        }
        console.log();
        // System Overview
        console.log(chalk.yellow('🌟 System Overview:'));
        if (data.system_status) {
            console.log(`   System: ${data.system_status}`);
        }
        if (data.mcp_status) {
            console.log(`   MCP Mode: ${data.mcp_status}`);
        }
        console.log();
        // Intelligence Systems Status
        if (data.intelligence_systems) {
            console.log(chalk.yellow('🧠 Intelligence Systems:'));
            Object.entries(data.intelligence_systems).forEach(([key, value]) => {
                const displayName = key.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase());
                console.log(`   ${displayName}: ${value}`);
            });
            console.log();
        }
        // Performance Metrics
        if (data.performance) {
            console.log(chalk.yellow('šŸ“ˆ Performance Metrics:'));
            Object.entries(data.performance).forEach(([key, value]) => {
                const displayName = key.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase());
                console.log(`   ${displayName}: ${value}`);
            });
            console.log();
        }
        // Memory Statistics
        if (data.memory_stats) {
            console.log(chalk.yellow('🧠 Memory Systems:'));
            Object.entries(data.memory_stats).forEach(([key, value]) => {
                const displayName = key.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase());
                console.log(`   ${displayName}: ${value}`);
            });
            console.log();
        }
        // Active Capabilities
        if (data.capabilities && data.capabilities.length > 0) {
            console.log(chalk.yellow('⚔ Active Capabilities:'));
            data.capabilities.forEach((capability) => {
                console.log(`   ${capability}`);
            });
            console.log();
        }
        // Verbose mode: show additional details
        if (options.verbose) {
            // Legacy system/memory fallback for backwards compatibility
            if (data.system) {
                console.log(chalk.yellow('šŸ”§ System Details:'));
                Object.entries(data.system).forEach(([key, value]) => {
                    console.log(`   ${key}: ${value}`);
                });
                console.log();
            }
            if (data.memory) {
                console.log(chalk.yellow('šŸ’¾ Memory Details:'));
                Object.entries(data.memory).forEach(([key, value]) => {
                    console.log(`   ${key}: ${value}`);
                });
                console.log();
            }
        }
    }
    displaySearchResults(response, options) {
        if (options.format === 'json') {
            console.log(JSON.stringify(response, null, 2));
            return;
        }
        // Handle both direct response and wrapped response
        let data;
        if (typeof response === 'string') {
            data = JSON.parse(response);
        }
        else if (response.data) {
            data = response.data; // MCP gateway returns { success: true, data: {...} }
        }
        else {
            data = response;
        }
        const query = data.query || 'Unknown Query';
        const strategy = data.strategy || data.search_strategy || 'intelligent';
        const results = data.results || [];
        const insights = data.insights || data.related_insights || [];
        const count = data.count || results.length;
        console.log(chalk.cyan(`šŸ” Search Results for: "${query}"`));
        console.log(chalk.gray(`Strategy: ${strategy} | Results: ${count}`));
        console.log();
        if (results.length > 0) {
            results.forEach((result, i) => {
                // Handle different result formats
                let content;
                if (result.content && typeof result.content === 'object') {
                    content = result.content.content || result.content.summary || JSON.stringify(result.content);
                }
                else {
                    content = result.content || result.summary || 'No content';
                }
                console.log(`${chalk.white(`[${i + 1}]`)} ${content.substring(0, 200)}${content.length > 200 ? '...' : ''}`);
                // Show relevance/score if available
                if (result.score !== undefined) {
                    console.log(chalk.gray(`    Score: ${(result.score * 100).toFixed(1)}%`));
                }
                else if (result.relevance !== undefined) {
                    console.log(chalk.gray(`    Relevance: ${(result.relevance * 100).toFixed(1)}%`));
                }
                // Show source if available
                if (result.source) {
                    console.log(chalk.gray(`    Source: ${result.source}`));
                }
                console.log();
            });
            // Display insights from intelligent analysis
            if (insights.length > 0) {
                console.log(chalk.cyan('🧠 Intelligence Insights:'));
                insights.forEach((insight, i) => {
                    const insightText = typeof insight === 'string' ? insight : insight.message || insight.content;
                    console.log(chalk.gray(`   • ${insightText}`));
                });
                console.log();
            }
        }
        else {
            console.log(chalk.yellow('No results found. Try a different query or check your spelling.'));
            // Show helpful suggestions if available
            if (data.suggestions && data.suggestions.length > 0) {
                console.log();
                console.log(chalk.cyan('šŸ’” Suggestions:'));
                data.suggestions.forEach((suggestion) => {
                    console.log(chalk.gray(`   • ${suggestion}`));
                });
            }
        }
    }
    displayStorageResults(response, options) {
        if (options.format === 'json') {
            console.log(JSON.stringify(response, null, 2));
            return;
        }
        const data = typeof response === 'string' ? JSON.parse(response) : response;
        console.log(chalk.green('āœ… Memory stored successfully'));
        console.log();
        console.log(`šŸ“ Category: ${chalk.cyan(data.category)}`);
        console.log(`šŸ”’ Storage: ${chalk.cyan(data.storage_type)}`);
        if (data.memory_id) {
            console.log(`šŸ†” ID: ${chalk.gray(data.memory_id)}`);
        }
        if (data.insights?.length > 0) {
            console.log();
            console.log(chalk.yellow('šŸ’” Storage Insights:'));
            data.insights.forEach((insight, i) => {
                console.log(`   ${i + 1}. ${insight}`);
            });
        }
        if (data.context?.related_memories?.length > 0) {
            console.log();
            console.log(chalk.blue(`šŸ”— Related memories: ${data.context.related_memories.length}`));
        }
    }
    displayStatusResults(response, options) {
        if (options.format === 'json') {
            console.log(JSON.stringify(response, null, 2));
            return;
        }
        // Handle both direct response and wrapped response
        let data;
        if (typeof response === 'string') {
            data = JSON.parse(response);
        }
        else if (response.data) {
            data = response.data; // MCP gateway returns { success: true, data: {...} }
        }
        else {
            data = response;
        }
        console.log(chalk.green('šŸ“Š MIRA Comprehensive System Status'));
        console.log(chalk.gray(`Last updated: ${data.timestamp || 'unknown'}`));
        console.log();
        // System Overview
        if (data.system_status || data.mcp_status) {
            console.log(chalk.cyan('🌟 System Overview:'));
            if (data.system_status)
                console.log(`   System: ${data.system_status}`);
            if (data.mcp_status)
                console.log(`   MCP Mode: ${data.mcp_status}`);
            if (data.uptime)
                console.log(`   Uptime: ${data.uptime}`);
            console.log();
        }
        // Intelligence Score
        if (data.intelligence_score) {
            const score = data.intelligence_score;
            const percentageColor = score.percentage >= 80 ? chalk.green : score.percentage >= 60 ? chalk.yellow : chalk.red;
            console.log(chalk.cyan('🧠 Intelligence Systems:'));
            console.log(`   Active: ${score.active_systems}/${score.total_systems} (${percentageColor(score.percentage + '%')})`);
            console.log(`   Status: ${score.status}`);
            console.log();
        }
        // Capabilities
        if (data.capabilities?.length > 0) {
            console.log(chalk.cyan('⚔ Active Capabilities:'));
            data.capabilities.forEach((capability) => {
                console.log(`   ${capability}`);
            });
            console.log();
        }
        // Performance Metrics
        if (data.performance) {
            console.log(chalk.blue('šŸ“ˆ Performance Metrics:'));
            const perf = data.performance;
            if (perf.overall_response_time_ms !== undefined) {
                const responseColor = perf.overall_response_time_ms < 200 ? chalk.green : perf.overall_response_time_ms < 1000 ? chalk.yellow : chalk.red;
                console.log(`   Response Time: ${responseColor(perf.overall_response_time_ms + 'ms')}`);
            }
            if (perf.system_resources) {
                const resources = perf.system_resources;
                console.log(`   CPU Usage: ${this.formatResourceUsage(resources.cpu_usage_percent, '%')}`);
                console.log(`   Memory Usage: ${this.formatResourceUsage(resources.memory_usage_percent, '%')}`);
                console.log(`   Disk Usage: ${this.formatResourceUsage(resources.disk_usage_percent, '%')}`);
                console.log(`   Available Memory: ${resources.memory_available_mb}MB`);
                console.log(`   Free Disk Space: ${resources.disk_free_gb}GB`);
            }
            if (perf.health_score !== undefined) {
                const scoreColor = perf.health_score >= 0.8 ? chalk.green : perf.health_score >= 0.6 ? chalk.yellow : chalk.red;
                console.log(`   Health Score: ${scoreColor((perf.health_score * 100).toFixed(1) + '%')}`);
            }
            console.log();
        }
        // Memory Statistics
        if (data.memory_stats) {
            console.log(chalk.cyan('🧠 Memory Systems:'));
            const memStats = data.memory_stats;
            if (memStats.estimated_conversations !== undefined) {
                console.log(`   Conversations: ${memStats.estimated_conversations}`);
            }
            if (memStats.memory_files_count !== undefined) {
                console.log(`   Memory Files: ${memStats.memory_files_count}`);
            }
            if (memStats.search_index) {
                console.log(`   Search Index: ${memStats.search_index}`);
            }
            console.log();
        }
        // System Health Details
        if (data.system_health && options.verbose) {
            console.log(chalk.cyan('šŸ„ Detailed Health Status:'));
            if (data.system_health.core_systems) {
                console.log('   Core Systems:');
                Object.entries(data.system_health.core_systems).forEach(([key, value]) => {
                    console.log(`     ${value} ${key}`);
                });
            }
            if (data.system_health.intelligence_modules) {
                console.log('   Intelligence Modules:');
                Object.entries(data.system_health.intelligence_modules).forEach(([key, value]) => {
                    console.log(`     ${value} ${key}`);
                });
            }
            if (data.system_health.health_scores) {
                const scores = data.system_health.health_scores;
                console.log(`   Overall Health: ${scores.overall_percentage}%`);
            }
            console.log();
        }
        // Dependencies (if verbose)
        if (data.dependencies && options.verbose) {
            console.log(chalk.cyan('šŸ“¦ Dependencies:'));
            if (data.dependencies.python_modules) {
                console.log('   Python Modules:');
                Object.entries(data.dependencies.python_modules).forEach(([module, status]) => {
                    console.log(`     ${status} ${module}`);
                });
            }
            console.log();
        }
        // Recommendations
        if (data.recommendations?.length > 0) {
            console.log(chalk.yellow('šŸ’” Recommendations:'));
            data.recommendations.forEach((rec, i) => {
                console.log(`   ${i + 1}. ${rec}`);
            });
            console.log();
        }
        // Summary for non-verbose mode
        if (!options.verbose && data.intelligence_score) {
            console.log(chalk.gray('šŸ’” Use --verbose for detailed system diagnostics'));
        }
    }
    displayRulesResults(response, options) {
        if (options.format === 'json') {
            console.log(JSON.stringify(response, null, 2));
            return;
        }
        const data = typeof response === 'string' ? JSON.parse(response) : response;
        if (data.rules && data.rules.length > 0) {
            console.log(chalk.green(`šŸ“‹ Found ${data.rules.length} steward rules:`));
            console.log();
            // Group by message type
            const rulesByType = data.rules.reduce((acc, rule) => {
                const type = rule.message_type || 'general';
                if (!acc[type])
                    acc[type] = [];
                acc[type].push(rule);
                return acc;
            }, {});
            // Display each type
            Object.entries(rulesByType).forEach(([type, rules]) => {
                const typeIcon = {
                    'rule': 'šŸ”§',
                    'preference': 'āš™ļø',
                    'instruction': 'šŸ“',
                    'guidance': 'šŸŽÆ',
                    'warning': 'āš ļø',
                    'context': 'šŸ“‹'
                }[type] || 'šŸ’”';
                console.log(chalk.cyan(`${typeIcon} ${type.toUpperCase()} (${rules.length})`));
                rules.forEach((rule, index) => {
                    const priorityIcon = rule.priority >= 7 ? 'šŸ”“' : rule.priority >= 4 ? '🟔' : '🟢';
                    console.log(`   ${priorityIcon} ${rule.content}`);
                    if (options.verbose) {
                        console.log(chalk.gray(`      Priority: ${rule.priority}/10`));
                        console.log(chalk.gray(`      Confidence: ${(rule.confidence * 100).toFixed(1)}%`));
                        if (rule.keywords && rule.keywords.length > 0) {
                            console.log(chalk.gray(`      Tags: ${rule.keywords.slice(0, 3).join(', ')}`));
                        }
                        console.log(chalk.gray(`      Created: ${new Date(rule.timestamp * 1000).toLocaleDateString()}`));
                    }
                    console.log();
                });
            });
            // Summary
            const highPriority = data.rules.filter((r) => r.priority >= 7).length;
            const mediumPriority = data.rules.filter((r) => r.priority >= 4 && r.priority < 7).length;
            console.log(chalk.cyan('šŸ“Š Summary:'));
            console.log(`   šŸ”“ Critical: ${highPriority} rules`);
            console.log(`   🟔 Important: ${mediumPriority} rules`);
            console.log(`   🟢 General: ${data.rules.length - highPriority - mediumPriority} rules`);
        }
        else if (data.detected !== undefined) {
            // Rule detection result
            if (data.detected) {
                console.log(chalk.green('āœ… Rules detected in message'));
                if (data.detected_rules && data.detected_rules.length > 0) {
                    console.log();
                    data.detected_rules.forEach((rule, index) => {
                        console.log(`${index + 1}. ${rule.content}`);
                        console.log(chalk.gray(`   Type: ${rule.message_type} | Priority: ${rule.priority}/10`));
                    });
                }
            }
            else {
                console.log(chalk.yellow('ā„¹ļø  No rules detected in the provided message'));
            }
        }
        else {
            console.log(chalk.yellow('šŸ“ No rules or preferences found.'));
            console.log();
            console.log(chalk.white('Rules are automatically detected when you:'));
            console.log(chalk.gray('  • Use phrases like "remember this rule"'));
            console.log(chalk.gray('  • Express preferences with "I prefer..."'));
            console.log(chalk.gray('  • Give instructions for future Claude instances'));
            console.log(chalk.gray('  • Set behavioral guidelines with "always" or "never"'));
        }
    }
    formatResourceUsage(value, unit) {
        if (value < 50)
            return chalk.green(`${value}${unit}`);
        if (value < 80)
            return chalk.yellow(`${value}${unit}`);
        return chalk.red(`${value}${unit}`);
    }
    displayInsights(response, options) {
        if (options.format === 'json') {
            console.log(JSON.stringify(response, null, 2));
            return;
        }
        const data = typeof response === 'string' ? JSON.parse(response) : response;
        console.log(chalk.magenta('🧠 Proactive Insights'));
        console.log();
        if (data.insights?.length > 0) {
            data.insights.forEach((insight, i) => {
                const priorityIcon = insight.priority === 'high' ? 'šŸ”„' : insight.priority === 'medium' ? '⚔' : 'šŸ’”';
                // Display insight content - handle different response formats
                let displayText = insight.title || insight.message || insight.content || insight.summary || 'Unknown insight';
                console.log(`${priorityIcon} ${displayText}`);
                // Show description if available and different from title
                if (insight.description && insight.description !== insight.title) {
                    console.log(chalk.gray(`   ${insight.description}`));
                }
                // Show recommendations if available
                if (insight.recommendations?.length > 0 && options.verbose) {
                    console.log(chalk.green(`   šŸ’” Recommendation: ${insight.recommendations[0]}`));
                }
                if (insight.actionable && options.verbose) {
                    console.log(chalk.gray(`   Action: ${insight.actionable}`));
                }
                console.log();
            });
        }
        else {
            console.log(chalk.yellow('No active insights at this time.'));
        }
        if (data.context?.priority_distribution) {
            const dist = data.context.priority_distribution;
            console.log(chalk.gray(`Priority distribution: High: ${dist.high}, Medium: ${dist.medium}, Low: ${dist.low}`));
        }
    }
    displaySyncResults(response, options) {
        if (options.format === 'json') {
            console.log(JSON.stringify(response, null, 2));
            return;
        }
        const data = typeof response === 'string' ? JSON.parse(response) : response;
        switch (data.type) {
            case 'data_sync_import':
                console.log(chalk.green('šŸ“„ Import completed'));
                if (data.result?.records_imported !== undefined) {
                    console.log(`   Records imported: ${data.result.records_imported}`);
                }
                break;
            case 'data_sync_export':
                console.log(chalk.green('šŸ“¤ Export completed'));
                if (data.result?.records_exported !== undefined) {
                    console.log(`   Records exported: ${data.result.records_exported}`);
                }
                break;
            case 'data_sync_status':
                console.log(chalk.blue('šŸ”„ Sync Status'));
                if (data.status) {
                    Object.entries(data.status).forEach(([key, value]) => {
                        console.log(`   ${key}: ${value}`);
                    });
                }
                break;
        }
    }
    displayConfigResults(response, options) {
        if (options.format === 'json') {
            console.log(JSON.stringify(response, null, 2));
            return;
        }
        const data = typeof response === 'string' ? JSON.parse(response) : response;
        switch (data.type) {
            case 'system_diagnostics':
                console.log(chalk.yellow('šŸ”§ System Diagnostics'));
                if (data.diagnostics) {
                    Object.entries(data.diagnostics).forEach(([key, value]) => {
                        const icon = value === 'good' || value === 'optimal' || value === 'valid' ? 'āœ…' : 'āš ļø';
                        console.log(`   ${icon} ${key}: ${value}`);
                    });
                }
                if (data.recommendations?.length > 0) {
                    console.log('\nšŸ’” Recommendations:');
                    data.recommendations.forEach((rec, i) => {
                        console.log(`   ${i + 1}. ${rec}`);
                    });
                }
                break;
            case 'system_optimization':
                console.log(chalk.green('⚔ System Optimization'));
                console.log(`   Status: ${data.result?.status}`);
                if (data.result?.optimizations_applied !== undefined) {
                    console.log(`   Optimizations applied: ${data.result.optimizations_applied}`);
                }
                break;
            case 'system_config_status':
                console.log(chalk.blue('āš™ļø Configuration Status'));
                if (data.status) {
                    Object.entries(data.status).forEach(([key, value]) => {
                        console.log(`   ${key}: ${value}`);
                    });
                }
                break;
        }
    }
    async startInsightStream(context, options) {
        console.log(chalk.blue('🌊 Starting insight stream... (Press Ctrl+C to stop)'));
        // Simple polling-based streaming for now
        const pollInterval = 5000; // 5 seconds
        const streamInterval = setInterval(async () => {
            try {
                const response = await this.pythonInterface.callMCPGateway('mira_insights', {
                    context: context.toMCPContext(),
                    options: { ...options, stream: false }
                });
                const data = typeof response === 'string' ? JSON.parse(response) : response;
                if (data.insights?.length > 0) {
                    // Only show new insights (simple implementation)
                    console.log(chalk.gray(`[${new Date().toLocaleTimeString()}] New insights available`));
                }
            }
            catch (error) {
                console.error(chalk.red('Stream error:'), error instanceof Error ? error.message : String(error));
            }
        }, pollInterval);
        // Handle Ctrl+C
        process.on('SIGINT', () => {
            clearInterval(streamInterval);
            console.log(chalk.blue('\nšŸ›‘ Insight stream stopped'));
            process.exit(0);
        });
    }
}
// Command factory functions for integration with existing CLI
export function createSmartDefaultCommand() {
    const cmd = new Command('smart-default')
        .alias('default')
        .description('šŸŽÆ Smart context-aware startup and status (MCP-powered)')
        .option('--format <type>', 'Output format (json, pretty, summary)', 'pretty')
        .option('--verbose', 'Show detailed information')
        .action(async (options) => {
        const handler = new UnifiedSmartCommands();
        await handler.smartDefault(options);
    });
    return cmd;
}
export function createAskCommand() {
    const cmd = new Command('ask')
        .description('šŸ” Universal intelligent search (MCP-powered)')
        .argument('<query>', 'Search query')
        .option('--format <type>', 'Output format (json, pretty, summary)', 'pretty')
        .option('--verbose', 'Show detailed results')
        .option('--priority <level>', 'Priority filter (high, medium, low)')
        .action(async (query, options) => {
        const handler = new UnifiedSmartCommands();
        await handler.ask(query, options);
    });
    return cmd;
}
export function createRememberCommand() {
    const cmd = new Command('remember')
        .description('šŸ’¾ Universal intelligent storage (MCP-powered)')
        .argument('<content>', 'Content to remember')
        .option('--format <type>', 'Output format (json, pretty, summary)', 'pretty')
        .option('--verbose', 'Show detailed storage information')
        .option('--context <type>', 'Explicit context hint')
        .action(async (content, options) => {
        const handler = new UnifiedSmartCommands();
        await handler.remember(content, options);
    });
    return cmd;
}
export function createSmartStatusCommand() {
    const cmd = new Command('smart-status')
        .alias('status')
        .description('šŸ“Š System intelligence with prioritization (MCP-powered)')
        .option('--format <type>', 'Output format (json, pretty, summary)', 'pretty')
        .option('--verbose', 'Show detailed status information')
        .action(async (options) => {
        const handler = new UnifiedSmartCommands();
        await handler.status(options);
    });
    return cmd;
}
export function createInsightsCommand() {
    const cmd = new Command('insights')
        .description('🧠 Proactive intelligence and recommendations (MCP-powered)')
        .option('--format <type>', 'Output format (json, pretty, summary)', 'pretty')
        .option('--verbose', 'Show detailed insights')
        .option('--stream', 'Enable streaming insights')
        .option('--priority <level>', 'Priority filter (high, medium, low)')
        .action(async (options) => {
        const handler = new UnifiedSmartCommands();
        await handler.insights(options);
    });
    return cmd;
}
export function createSyncCommand() {
    const cmd = new Command('sync')
        .description('šŸ”„ Data management with format detection (MCP-powered)')
        .argument('[operation]', 'Operation (import, export, status)', 'status')
        .argument('[source]', 'Source file for import operations')
        .option('--format <type>', 'Output format (json, pretty, summary)', 'pretty')
        .option('--verbose', 'Show detailed sync information')
        .action(async (operation, source, options) => {
        const handler = new UnifiedSmartCommands();
        await handler.sync(operation, source, options);
    });
    return cmd;
}
export function createConfigCommand() {
    const cmd = new Command('config')
        .description('āš™ļø System management and diagnostics (MCP-powered)')
        .argument('[operation]', 'Operation (diagnose, optimize, status)', 'status')
        .option('--format <type>', 'Output format (json, pretty, summary)', 'pretty')
        .option('--verbose', 'Show detailed configuration information')
        .action(async (operation, options) => {
        const handler = new UnifiedSmartCommands();
        await handler.config(operation, options);
    });
    return cmd;
}
export function createRulesCommand() {
    const cmd = new Command('rules')
        .description('šŸ”§ Steward rules and preferences management')
        .argument('[operation]', 'Operation (list, add, detect, clear)', 'list')
        .argument('[content]', 'Rule content for add/detect operations')
        .option('--format <type>', 'Output format (json, pretty, summary)', 'pretty')
        .option('--verbose', 'Show detailed rule information')
        .action(async (operation, content, options) => {
        const handler = new UnifiedSmartCommands();
        await handler.rules(operation, content, options);
    });
    return cmd;
}
//# sourceMappingURL=unified-smart.js.map