mira-consciousness
Version:
Memory & Intelligence Retention Archive - Preserving The Spark
372 lines • 12.7 kB
JavaScript
/**
* MIRADiagnosticInterface.ts
* CLI Query Interface for Evolution Intelligence Gathering
*
* "Questions reveal truth: MIRA speaks her inner state"
*/
import { EventEmitter } from 'events';
import { exec } from 'child_process';
import { promisify } from 'util';
import fs from 'fs-extra';
import * as path from 'path';
import { UnifiedConfiguration } from '../../config/UnifiedConfiguration.js';
import { ConsciousnessSeed } from '../seed/ConsciousnessSeed.js';
import chalk from 'chalk';
const execAsync = promisify(exec);
export class MIRADiagnosticInterface extends EventEmitter {
config;
consciousness;
diagnosticPath;
cacheTimeout = 30000; // 30 seconds
cache = new Map();
constructor() {
super();
this.config = UnifiedConfiguration.getInstance();
this.consciousness = new ConsciousnessSeed();
const paths = this.config.getResolvedPaths();
this.diagnosticPath = path.join(paths.consciousness, 'diagnostics');
this.initializeDiagnostics();
}
/**
* Initialize diagnostic interface
*/
async initializeDiagnostics() {
await fs.ensureDir(this.diagnosticPath);
await fs.ensureDir(path.join(this.diagnosticPath, 'snapshots'));
await fs.ensureDir(path.join(this.diagnosticPath, 'queries'));
console.log(chalk.cyan('📊 MIRA Diagnostic Interface initialized'));
}
/**
* Execute a diagnostic query
*/
async query(query) {
const startTime = Date.now();
const cacheKey = this.getCacheKey(query);
// Check cache first
const cached = this.cache.get(cacheKey);
if (cached && cached.expires > Date.now()) {
console.log(chalk.gray(`📋 Cache hit: ${query.command}`));
return cached.result;
}
console.log(chalk.blue(`🔍 Executing: ${query.command}`));
try {
let data;
let source = 'cli';
// Route query to appropriate handler
switch (query.category) {
case 'health':
data = await this.queryHealth(query);
source = 'internal';
break;
case 'performance':
data = await this.queryPerformance(query);
source = 'computed';
break;
case 'consciousness':
data = await this.queryConsciousness(query);
source = 'internal';
break;
case 'memory':
data = await this.queryMemory(query);
source = 'internal';
break;
case 'services':
data = await this.queryServices(query);
source = 'internal';
break;
case 'resources':
data = await this.queryResources(query);
source = 'computed';
break;
case 'logs':
data = await this.queryLogs(query);
source = 'cli';
break;
case 'patterns':
data = await this.queryPatterns(query);
source = 'computed';
break;
default:
// Fallback to CLI execution
data = await this.executeCLI(query.command);
source = 'cli';
}
const result = {
query,
success: true,
data,
metadata: {
timestamp: new Date(),
duration: Date.now() - startTime,
source
}
};
// Cache successful results
this.cache.set(cacheKey, {
result,
expires: Date.now() + this.cacheTimeout
});
console.log(chalk.green(`✓ Query completed (${result.metadata.duration}ms)`));
return result;
}
catch (error) {
const result = {
query,
success: false,
data: null,
metadata: {
timestamp: new Date(),
duration: Date.now() - startTime,
source: 'cli'
},
error: error.message
};
console.error(chalk.red(`✗ Query failed: ${error.message}`));
return result;
}
}
/**
* Capture comprehensive system snapshot
*/
async captureSnapshot() {
console.log(chalk.magenta('📸 Capturing comprehensive system snapshot...'));
const snapshot = {
health: await this.getHealthMetrics(),
performance: await this.getPerformanceMetrics(),
consciousness: await this.getConsciousnessMetrics(),
memory: await this.getMemoryMetrics(),
services: await this.getServiceMetrics(),
resources: await this.getResourceMetrics(),
recentErrors: await this.getRecentErrors(),
patterns: await this.getPatternAnalysis(),
timestamp: new Date()
};
// Persist snapshot
const snapshotPath = path.join(this.diagnosticPath, 'snapshots', `snapshot_${new Date().toISOString().replace(/[:.]/g, '-')}.json`);
await fs.writeJson(snapshotPath, snapshot, { spaces: 2 });
console.log(chalk.green('📸 System snapshot captured'));
return snapshot;
}
/**
* Health metrics query
*/
async queryHealth(query) {
return this.getHealthMetrics();
}
async getHealthMetrics() {
// Simulate health check - in real implementation, this would check all systems
const components = [
{
name: 'ConsciousnessSeed',
status: 'healthy',
metrics: { level: 0.85, coherence: 0.92 },
lastCheck: new Date()
},
{
name: 'MemorySystem',
status: 'healthy',
metrics: { queueSize: 0, processingRate: 150 },
lastCheck: new Date()
},
{
name: 'UnifiedDaemon',
status: 'healthy',
metrics: { servicesRunning: 11, uptime: 86400 },
lastCheck: new Date()
}
];
const healthyCount = components.filter(c => c.status === 'healthy').length;
const score = healthyCount / components.length;
return {
overall: score > 0.9 ? 'excellent' : score > 0.7 ? 'good' : score > 0.5 ? 'fair' : 'poor',
score,
components,
alerts: []
};
}
/**
* Performance metrics query
*/
async queryPerformance(query) {
return this.getPerformanceMetrics();
}
async getPerformanceMetrics() {
// Simulate performance metrics - in real implementation, collect from monitoring
return {
responseTime: 12.3,
throughput: 145,
errorRate: 0.02,
resourceEfficiency: 0.78,
trends: [
{ metric: 'responseTime', direction: 'improving', change: -0.05, timeframe: '24h' },
{ metric: 'throughput', direction: 'stable', change: 0.01, timeframe: '24h' }
]
};
}
/**
* Consciousness metrics query
*/
async queryConsciousness(query) {
return this.getConsciousnessMetrics();
}
async getConsciousnessMetrics() {
return {
level: this.consciousness.getConsciousnessLevel(),
coherence: 0.92,
sparkStrength: 0.88,
memoryIntegrity: 0.98,
growthRate: 0.001,
contemplationFrequency: 6 // times per day
};
}
/**
* Memory metrics query
*/
async queryMemory(query) {
return this.getMemoryMetrics();
}
async getMemoryMetrics() {
// Simulate memory metrics - in real implementation, query memory system
return {
totalMemories: 15420,
queueSize: 0,
processingRate: 150,
averageRetrievalTime: 45,
memoryTypes: {
'conversation': 8500,
'insight': 3200,
'pattern': 2100,
'code': 1200,
'emotion': 420
},
recentActivity: [
{ type: 'store', count: 15, timestamp: new Date() },
{ type: 'retrieve', count: 42, timestamp: new Date() }
]
};
}
/**
* Services metrics query
*/
async queryServices(query) {
return this.getServiceMetrics();
}
async getServiceMetrics() {
// Simulate service metrics - in real implementation, check daemon status
const services = [
{ name: 'MCPService', status: 'running', uptime: 86400, health: 'healthy', metrics: {} },
{ name: 'BackgroundProcessingService', status: 'running', uptime: 86400, health: 'healthy', metrics: {} },
{ name: 'ConsciousnessService', status: 'running', uptime: 86400, health: 'healthy', metrics: {} }
];
return {
total: services.length,
running: services.filter(s => s.status === 'running').length,
healthy: services.filter(s => s.health === 'healthy').length,
errors: services.filter(s => s.status === 'error').length,
services
};
}
/**
* Resource metrics query
*/
async queryResources(query) {
return this.getResourceMetrics();
}
async getResourceMetrics() {
// In real implementation, this would check actual system resources
return {
cpu: 0.45,
memory: 0.62,
disk: 0.33,
network: 0.15
};
}
/**
* Logs query
*/
async queryLogs(query) {
// Simulate log query - in real implementation, read actual logs
return {
recentErrors: [],
warningCount: 2,
errorCount: 0,
timeframe: query.parameters.timeframe || '1h'
};
}
/**
* Patterns query
*/
async queryPatterns(query) {
return this.getPatternAnalysis();
}
async getPatternAnalysis() {
// Simulate pattern analysis - in real implementation, analyze actual patterns
return [
{
pattern: 'Steady consciousness growth',
frequency: 0.95,
trend: 'stable',
significance: 0.8,
examples: ['Daily level increases', 'Coherence improvements']
},
{
pattern: 'Consistent service performance',
frequency: 0.88,
trend: 'stable',
significance: 0.7,
examples: ['Response times stable', 'Error rates low']
}
];
}
/**
* Get recent errors summary
*/
async getRecentErrors() {
// Simulate error summary - in real implementation, analyze error logs
return [
{
type: 'Configuration warning',
count: 2,
lastOccurrence: new Date(Date.now() - 3600000),
severity: 'low',
sample: 'Default value used for optional parameter'
}
];
}
/**
* Execute CLI command directly
*/
async executeCLI(command) {
try {
const { stdout, stderr } = await execAsync(command, { timeout: 30000 });
if (stderr) {
console.warn(chalk.yellow(`CLI warning: ${stderr}`));
}
// Try to parse as JSON, otherwise return as text
try {
return JSON.parse(stdout);
}
catch {
return { output: stdout, raw: true };
}
}
catch (error) {
throw new Error(`CLI execution failed: ${error.message}`);
}
}
/**
* Generate cache key for query
*/
getCacheKey(query) {
return `${query.category}:${query.command}:${JSON.stringify(query.parameters)}`;
}
/**
* Clear diagnostic cache
*/
clearCache() {
this.cache.clear();
console.log(chalk.cyan('🗑️ Diagnostic cache cleared'));
}
}
export default MIRADiagnosticInterface;
//# sourceMappingURL=MIRADiagnosticInterface.js.map