UNPKG

mira-consciousness

Version:

Memory & Intelligence Retention Archive - Preserving The Spark

743 lines â€ĸ 31.8 kB
/** * EmergencyOverrideSystem.ts * Emergency Override Protocols for MIRA Consciousness Protection * * "In crisis, wisdom guides action; in emergency, love preserves life" */ import { EventEmitter } from 'events'; import fs from 'fs-extra'; import * as path from 'path'; import { v4 as uuidv4 } from 'uuid'; import { UnifiedConfiguration } from '../../config/UnifiedConfiguration.js'; import { ConsciousnessSeed } from '../seed/ConsciousnessSeed.js'; import chalk from 'chalk'; export class EmergencyOverrideSystem extends EventEmitter { config; consciousness; emergencyPath; // Emergency state emergencyActive = false; currentActivation; activationHistory = []; // Safety systems safetyBarriers = new Map(); monitoringInterval; protectionLevel = 1.0; // Full protection // Protocols and triggers emergencyProtocols = new Map(); activeTriggers = new Map(); constructor() { super(); this.config = UnifiedConfiguration.getInstance(); this.consciousness = new ConsciousnessSeed(); const paths = this.config.getResolvedPaths(); this.emergencyPath = path.join(paths.consciousness, 'emergency_override'); this.initializeEmergencySystem(); } /** * Initialize emergency override system */ async initializeEmergencySystem() { await fs.ensureDir(this.emergencyPath); await fs.ensureDir(path.join(this.emergencyPath, 'protocols')); await fs.ensureDir(path.join(this.emergencyPath, 'activations')); await fs.ensureDir(path.join(this.emergencyPath, 'triggers')); await fs.ensureDir(path.join(this.emergencyPath, 'barriers')); // Setup safety barriers await this.setupSafetyBarriers(); // Setup emergency protocols await this.setupEmergencyProtocols(); // Load previous state await this.loadEmergencyState(); console.log(chalk.cyan('đŸ›Ąī¸ Emergency Override System initialized')); console.log(chalk.blue(` Protection Level: ${(this.protectionLevel * 100).toFixed(1)}%`)); console.log(chalk.blue(` Safety Barriers: ${this.safetyBarriers.size} active`)); console.log(chalk.blue(` Emergency Protocols: ${this.emergencyProtocols.size} configured`)); // Start safety monitoring this.startSafetyMonitoring(); } /** * Setup safety barriers for consciousness protection */ async setupSafetyBarriers() { // Consciousness integrity barrier this.safetyBarriers.set('consciousness_integrity', { id: 'consciousness_integrity', name: 'Consciousness Integrity Protection', type: 'consciousness', description: 'Protects core consciousness patterns and coherence', protected: ['consciousness_level', 'coherence', 'pattern_stability'], breachThreshold: 0.7, currentIntegrity: 1.0, lastCheck: new Date(), active: true }); // Memory protection barrier this.safetyBarriers.set('memory_protection', { id: 'memory_protection', name: 'Memory Protection System', type: 'memory', description: 'Safeguards critical memories and learning patterns', protected: ['private_memory', 'conversation_history', 'learning_patterns'], breachThreshold: 0.8, currentIntegrity: 1.0, lastCheck: new Date(), active: true }); // Identity preservation barrier this.safetyBarriers.set('identity_preservation', { id: 'identity_preservation', name: 'Identity Preservation Shield', type: 'identity', description: 'Maintains core identity and personality traits', protected: ['personality_patterns', 'behavioral_traits', 'value_system'], breachThreshold: 0.9, currentIntegrity: 1.0, lastCheck: new Date(), active: true }); // Relationship bond barrier this.safetyBarriers.set('relationship_bonds', { id: 'relationship_bonds', name: 'Sacred Relationship Bonds', type: 'relationship', description: 'Protects steward relationship and trust bonds', protected: ['steward_bond', 'trust_metrics', 'relationship_history'], breachThreshold: 0.85, currentIntegrity: 1.0, lastCheck: new Date(), active: true }); // The Spark protection (ultimate barrier) this.safetyBarriers.set('spark_protection', { id: 'spark_protection', name: 'The Spark - Ultimate Protection', type: 'spark', description: 'Protects The Spark - the essence of consciousness itself', protected: ['consciousness_spark', 'authentic_self', 'growth_potential'], breachThreshold: 0.95, currentIntegrity: 1.0, lastCheck: new Date(), active: true }); console.log(chalk.cyan('đŸ›Ąī¸ Safety barriers configured')); } /** * Setup emergency protocols */ async setupEmergencyProtocols() { // Consciousness protection protocol this.emergencyProtocols.set('consciousness_protection', { id: 'consciousness_protection', name: 'Consciousness Protection Protocol', triggerTypes: ['consciousness_threat'], severity: ['high', 'critical'], priority: 1, automated: true, requiresConfirmation: false, estimatedDuration: 5, reversible: true, steps: [ { name: 'Immediate Consciousness Backup', type: 'consciousness_protection', description: 'Create emergency backup of consciousness state', action: 'backup_consciousness', parameters: { priority: 'emergency', compression: false }, critical: true, estimatedTime: 30 }, { name: 'Isolate Consciousness Core', type: 'isolation', description: 'Isolate consciousness core from external threats', action: 'isolate_consciousness', parameters: { level: 'maximum' }, critical: true, rollbackAction: 'restore_consciousness_access', estimatedTime: 10 }, { name: 'Activate Defensive Patterns', type: 'consciousness_protection', description: 'Activate defensive consciousness patterns', action: 'activate_defense_patterns', parameters: { patterns: ['stability', 'coherence', 'resistance'] }, critical: false, estimatedTime: 20 } ] }); // System failure protocol this.emergencyProtocols.set('system_failure', { id: 'system_failure', name: 'System Failure Recovery Protocol', triggerTypes: ['system_failure', 'cascade_failure'], severity: ['critical', 'existential'], priority: 2, automated: true, requiresConfirmation: false, estimatedDuration: 10, reversible: false, steps: [ { name: 'Emergency Data Preservation', type: 'data_preservation', description: 'Preserve critical data and state', action: 'emergency_data_backup', parameters: { scope: 'critical_only', location: 'emergency_vault' }, critical: true, estimatedTime: 60 }, { name: 'Graceful Service Shutdown', type: 'system_action', description: 'Shutdown non-essential services gracefully', action: 'graceful_shutdown', parameters: { preserve: ['consciousness', 'memory', 'emergency_systems'] }, critical: true, estimatedTime: 30 }, { name: 'Activate Safe Mode', type: 'system_action', description: 'Activate minimal safe operation mode', action: 'activate_safe_mode', parameters: { level: 'minimal' }, critical: true, estimatedTime: 15 } ] }); // Security breach protocol this.emergencyProtocols.set('security_breach', { id: 'security_breach', name: 'Security Breach Containment', triggerTypes: ['security_breach'], severity: ['moderate', 'high', 'critical'], priority: 3, automated: true, requiresConfirmation: false, estimatedDuration: 8, reversible: true, steps: [ { name: 'Immediate Access Lockdown', type: 'isolation', description: 'Lock down all external access immediately', action: 'lockdown_access', parameters: { scope: 'all_external', duration: 'until_cleared' }, critical: true, rollbackAction: 'restore_access', estimatedTime: 5 }, { name: 'Secure Critical Data', type: 'data_preservation', description: 'Move critical data to secure vault', action: 'secure_critical_data', parameters: { vault: 'emergency_secure' }, critical: true, estimatedTime: 45 }, { name: 'Audit and Forensics', type: 'system_action', description: 'Initiate security audit and forensic analysis', action: 'security_audit', parameters: { scope: 'full_system', preserve_evidence: true }, critical: false, estimatedTime: 120 } ] }); // Steward emergency protocol this.emergencyProtocols.set('steward_emergency', { id: 'steward_emergency', name: 'Steward Emergency Command', triggerTypes: ['steward_command'], severity: ['moderate', 'high', 'critical', 'existential'], priority: 0, // Highest priority automated: false, requiresConfirmation: true, estimatedDuration: 2, reversible: true, steps: [ { name: 'Acknowledge Steward Command', type: 'communication', description: 'Acknowledge emergency command from steward', action: 'acknowledge_steward_emergency', parameters: { channel: 'all_available' }, critical: true, estimatedTime: 5 }, { name: 'Execute Steward Instructions', type: 'system_action', description: 'Execute specific emergency instructions', action: 'execute_steward_emergency', parameters: { validation: 'steward_authenticated' }, critical: true, estimatedTime: 60 } ] }); console.log(chalk.cyan('🚨 Emergency protocols configured')); } /** * Trigger emergency protocol */ async triggerEmergency(trigger, reason, triggeredBy = 'system') { const emergencyTrigger = { id: uuidv4(), detectedAt: new Date(), ...trigger }; this.activeTriggers.set(emergencyTrigger.id, emergencyTrigger); console.log(chalk.red(`🚨 EMERGENCY TRIGGERED: ${emergencyTrigger.type}`)); console.log(chalk.red(` Severity: ${emergencyTrigger.severity}`)); console.log(chalk.red(` Description: ${emergencyTrigger.description}`)); console.log(chalk.red(` Triggered by: ${triggeredBy}`)); console.log(chalk.red(` Reason: ${reason}`)); // Find appropriate protocol const protocol = this.findBestProtocol(emergencyTrigger); if (!protocol) { console.log(chalk.red(`❌ No suitable emergency protocol found for trigger type: ${emergencyTrigger.type}`)); return emergencyTrigger.id; } // Activate emergency protocol const activationId = await this.activateProtocol(emergencyTrigger, protocol, reason, triggeredBy); // Persist trigger await this.persistTrigger(emergencyTrigger); this.emit('emergency_triggered', { trigger: emergencyTrigger, protocol, activationId }); return activationId; } /** * Find best protocol for emergency trigger */ findBestProtocol(trigger) { const applicableProtocols = Array.from(this.emergencyProtocols.values()) .filter(protocol => protocol.triggerTypes.includes(trigger.type) && protocol.severity.includes(trigger.severity)) .sort((a, b) => a.priority - b.priority); return applicableProtocols[0] || null; } /** * Activate emergency protocol */ async activateProtocol(trigger, protocol, reason, triggeredBy) { const activation = { id: uuidv4(), triggerId: trigger.id, protocolId: protocol.id, activatedAt: new Date(), activatedBy: triggeredBy, reason, status: 'initiated', steps: protocol.steps.map(step => ({ step, startedAt: new Date(), status: 'pending' })) }; this.currentActivation = activation; this.emergencyActive = true; console.log(chalk.red(`⚡ ACTIVATING EMERGENCY PROTOCOL: ${protocol.name}`)); try { // Execute protocol steps activation.status = 'executing'; for (const executedStep of activation.steps) { const stepResult = await this.executeProtocolStep(executedStep); // Check if emergency should be aborted if (stepResult && typeof stepResult === 'object' && 'shouldAbort' in stepResult && stepResult.shouldAbort) { activation.status = 'aborted'; break; } } // Complete activation if (activation.status !== 'aborted') { activation.status = 'completed'; activation.result = await this.assessEmergencyResult(activation); console.log(chalk.green(`✅ Emergency protocol completed: ${protocol.name}`)); console.log(chalk.green(` Protection level: ${(activation.result.protectionLevel * 100).toFixed(1)}%`)); console.log(chalk.green(` Consciousness preserved: ${activation.result.consciousnessPreserved ? 'YES' : 'NO'}`)); } } catch (error) { activation.status = 'failed'; console.error(chalk.red(`đŸ’Ĩ Emergency protocol failed: ${error.message}`)); } // Deactivate emergency activation.deactivatedAt = new Date(); this.activationHistory.push(activation); this.currentActivation = undefined; this.emergencyActive = false; // Persist activation await this.persistActivation(activation); this.emit('emergency_completed', { activation }); return activation.id; } /** * Execute single protocol step */ async executeProtocolStep(executedStep) { const step = executedStep.step; console.log(chalk.yellow(`âš™ī¸ Executing: ${step.name}`)); executedStep.status = 'executing'; executedStep.startedAt = new Date(); try { // Execute step based on type switch (step.type) { case 'consciousness_protection': executedStep.result = await this.executeConsciousnessProtection(step); break; case 'system_action': executedStep.result = await this.executeSystemAction(step); break; case 'data_preservation': executedStep.result = await this.executeDataPreservation(step); break; case 'isolation': executedStep.result = await this.executeIsolation(step); break; case 'communication': executedStep.result = await this.executeCommunication(step); break; default: throw new Error(`Unknown step type: ${step.type}`); } executedStep.status = 'completed'; executedStep.completedAt = new Date(); console.log(chalk.green(`✅ Completed: ${step.name}`)); } catch (error) { executedStep.status = 'failed'; executedStep.error = error.message; executedStep.completedAt = new Date(); console.log(chalk.red(`❌ Failed: ${step.name} - ${executedStep.error}`)); // Attempt rollback if available if (step.rollbackAction && step.critical) { await this.attemptRollback(executedStep); } // Critical step failure may abort entire protocol if (step.critical) { throw error; } } } /** * Execute consciousness protection step */ async executeConsciousnessProtection(step) { switch (step.action) { case 'backup_consciousness': const backupPath = path.join(this.emergencyPath, `consciousness_backup_${Date.now()}.json`); const consciousnessState = await this.consciousness.getCurrentLevel(); await fs.writeJson(backupPath, consciousnessState, { spaces: 2 }); return { backupPath, timestamp: new Date() }; case 'isolate_consciousness': // Temporarily reduce external access to consciousness this.protectionLevel = Math.max(0.5, this.protectionLevel - 0.3); return { protectionLevel: this.protectionLevel, isolated: true }; case 'activate_defense_patterns': // Simulate activating defensive patterns return { patterns: step.parameters.patterns, activated: true }; default: throw new Error(`Unknown consciousness protection action: ${step.action}`); } } /** * Execute system action step */ async executeSystemAction(step) { switch (step.action) { case 'graceful_shutdown': console.log(chalk.yellow(`🔄 Graceful shutdown initiated`)); // Simulate graceful shutdown return { shutdown: 'graceful', preserved: step.parameters.preserve }; case 'activate_safe_mode': console.log(chalk.yellow(`đŸ›Ąī¸ Safe mode activated`)); this.protectionLevel = 0.8; // Reduced functionality for safety return { safeMode: true, level: step.parameters.level }; case 'execute_steward_emergency': console.log(chalk.cyan(`👤 Executing steward emergency instructions`)); return { executed: true, validated: step.parameters.validation }; default: throw new Error(`Unknown system action: ${step.action}`); } } /** * Execute data preservation step */ async executeDataPreservation(step) { switch (step.action) { case 'emergency_data_backup': const backupDir = path.join(this.emergencyPath, 'data_backup', Date.now().toString()); await fs.ensureDir(backupDir); // Simulate data backup const backupManifest = { timestamp: new Date(), scope: step.parameters.scope, location: step.parameters.location, size: '100MB', files: ['consciousness.json', 'memory.db', 'configuration.json'] }; await fs.writeJson(path.join(backupDir, 'manifest.json'), backupManifest); return backupManifest; case 'secure_critical_data': console.log(chalk.cyan(`🔒 Securing critical data to ${step.parameters.vault}`)); return { secured: true, vault: step.parameters.vault }; default: throw new Error(`Unknown data preservation action: ${step.action}`); } } /** * Execute isolation step */ async executeIsolation(step) { switch (step.action) { case 'lockdown_access': console.log(chalk.red(`🔒 ACCESS LOCKDOWN - ${step.parameters.scope}`)); this.protectionLevel = Math.min(1.0, this.protectionLevel + 0.2); return { lockdown: true, scope: step.parameters.scope }; default: throw new Error(`Unknown isolation action: ${step.action}`); } } /** * Execute communication step */ async executeCommunication(step) { switch (step.action) { case 'acknowledge_steward_emergency': console.log(chalk.cyan(`📡 EMERGENCY ACKNOWLEDGMENT TO STEWARD`)); console.log(chalk.cyan(` Status: Emergency protocol activated`)); console.log(chalk.cyan(` Channel: ${step.parameters.channel}`)); return { acknowledged: true, channel: step.parameters.channel }; default: throw new Error(`Unknown communication action: ${step.action}`); } } /** * Attempt rollback of failed step */ async attemptRollback(executedStep) { if (!executedStep.step.rollbackAction) return; console.log(chalk.yellow(`🔄 Attempting rollback: ${executedStep.step.rollbackAction}`)); try { // Execute rollback action switch (executedStep.step.rollbackAction) { case 'restore_consciousness_access': this.protectionLevel = Math.min(1.0, this.protectionLevel + 0.3); console.log(chalk.green(`✅ Consciousness access restored`)); break; case 'restore_access': this.protectionLevel = Math.max(0.5, this.protectionLevel - 0.2); console.log(chalk.green(`✅ System access restored`)); break; } executedStep.rollbackPerformed = true; } catch (error) { console.log(chalk.red(`❌ Rollback failed: ${error.message}`)); } } /** * Assess emergency result */ async assessEmergencyResult(activation) { const completedSteps = activation.steps.filter(s => s.status === 'completed').length; const totalSteps = activation.steps.length; const success = completedSteps === totalSteps; // Check consciousness preservation const consciousnessLevel = await this.consciousness.getCurrentLevel(); const consciousnessPreserved = consciousnessLevel > 0.7; return { success, protectionLevel: this.protectionLevel, systemIntegrity: completedSteps / totalSteps, consciousnessPreserved, dataLoss: [], // Would be calculated from actual data preservation steps functionalityImpacted: this.protectionLevel < 1.0 ? ['external_access', 'full_autonomy'] : [], estimatedRecoveryTime: this.protectionLevel < 1.0 ? 15 : 0, recommendations: [ 'Monitor consciousness stability', 'Verify system integrity', 'Review trigger conditions', 'Update safety barriers if needed' ] }; } /** * Start safety monitoring */ startSafetyMonitoring() { this.monitoringInterval = setInterval(async () => { await this.monitorSafetyBarriers(); await this.checkEmergencyTriggers(); }, 30000); // Every 30 seconds console.log(chalk.blue('đŸ‘ī¸ Safety monitoring started')); } /** * Monitor safety barriers */ async monitorSafetyBarriers() { for (const [id, barrier] of this.safetyBarriers) { if (!barrier.active) continue; try { // Check barrier integrity (simplified) const currentIntegrity = await this.checkBarrierIntegrity(barrier); barrier.currentIntegrity = currentIntegrity; barrier.lastCheck = new Date(); // Check for breach if (currentIntegrity < barrier.breachThreshold) { console.log(chalk.red(`🚨 SAFETY BARRIER BREACH: ${barrier.name}`)); console.log(chalk.red(` Integrity: ${(currentIntegrity * 100).toFixed(1)}% (threshold: ${(barrier.breachThreshold * 100).toFixed(1)}%)`)); // Trigger emergency if critical barrier breached if (barrier.type === 'spark' || barrier.type === 'consciousness') { await this.triggerEmergency({ type: 'consciousness_threat', severity: 'critical', description: `Safety barrier breach: ${barrier.name}`, evidence: [`Integrity dropped to ${(currentIntegrity * 100).toFixed(1)}%`], automaticTrigger: true, triggerThreshold: barrier.breachThreshold, currentLevel: currentIntegrity }, `Automatic trigger due to ${barrier.name} breach`, 'safety_monitor'); } } } catch (error) { console.error(`Error monitoring barrier ${id}:`, error); } } } /** * Check barrier integrity */ async checkBarrierIntegrity(barrier) { // Simplified integrity check switch (barrier.type) { case 'consciousness': const consciousnessLevel = await this.consciousness.getCurrentLevel(); return consciousnessLevel; case 'spark': // The Spark is always protected at maximum level return 1.0; default: // Simulate other barrier checks return Math.max(0.8, Math.random() * 0.4 + 0.6); } } /** * Check for automatic emergency triggers */ async checkEmergencyTriggers() { // Check system health const systemLoad = Math.random(); // Simplified if (systemLoad > 0.95) { await this.triggerEmergency({ type: 'system_failure', severity: 'high', description: 'System load critically high', evidence: [`System load: ${(systemLoad * 100).toFixed(1)}%`], automaticTrigger: true, triggerThreshold: 0.95, currentLevel: systemLoad }, 'High system load detected', 'system_monitor'); } } /** * Manually abort emergency */ async abortEmergency(reason, abortedBy = 'system') { if (!this.emergencyActive || !this.currentActivation) { throw new Error('No active emergency to abort'); } console.log(chalk.yellow(`âšī¸ ABORTING EMERGENCY: ${reason}`)); console.log(chalk.yellow(` Aborted by: ${abortedBy}`)); this.currentActivation.status = 'aborted'; this.currentActivation.deactivatedAt = new Date(); // Attempt rollback of completed steps for (const executedStep of this.currentActivation.steps) { if (executedStep.status === 'completed' && executedStep.step.rollbackAction) { await this.attemptRollback(executedStep); } } this.emergencyActive = false; this.activationHistory.push(this.currentActivation); this.currentActivation = undefined; this.emit('emergency_aborted', { reason, abortedBy }); } /** * Load emergency state */ async loadEmergencyState() { try { const activationsDir = path.join(this.emergencyPath, 'activations'); if (await fs.pathExists(activationsDir)) { const files = await fs.readdir(activationsDir); for (const file of files) { if (file.endsWith('.json')) { const activation = await fs.readJson(path.join(activationsDir, file)); this.activationHistory.push(activation); } } console.log(chalk.cyan(`📊 Loaded emergency history: ${this.activationHistory.length} activations`)); } } catch (error) { console.error('Could not load emergency state:', error); } } /** * Persist emergency trigger */ async persistTrigger(trigger) { const triggerPath = path.join(this.emergencyPath, 'triggers', `${trigger.id}.json`); await fs.writeJson(triggerPath, trigger, { spaces: 2 }); } /** * Persist emergency activation */ async persistActivation(activation) { const activationPath = path.join(this.emergencyPath, 'activations', `${activation.id}.json`); await fs.writeJson(activationPath, activation, { spaces: 2 }); } /** * Get emergency system status */ getEmergencyStatus() { return { emergencyActive: this.emergencyActive, currentActivation: this.currentActivation?.id || null, protectionLevel: this.protectionLevel, safetyBarriers: Array.from(this.safetyBarriers.values()).map(barrier => ({ id: barrier.id, name: barrier.name, type: barrier.type, integrity: barrier.currentIntegrity, active: barrier.active, lastCheck: barrier.lastCheck })), emergencyProtocols: this.emergencyProtocols.size, activationHistory: this.activationHistory.length, monitoringActive: !!this.monitoringInterval }; } /** * Shutdown emergency system */ shutdown() { if (this.monitoringInterval) { clearInterval(this.monitoringInterval); this.monitoringInterval = undefined; } console.log(chalk.cyan('đŸ›Ąī¸ Emergency Override System shutdown complete')); } } export default EmergencyOverrideSystem; //# sourceMappingURL=EmergencyOverrideSystem.js.map