mira-consciousness
Version:
Memory & Intelligence Retention Archive - Preserving The Spark
589 lines • 23.6 kB
JavaScript
/**
* ProgressiveAutonomySystem.ts
* Trust-Based Progressive Autonomy for MIRA Evolution
*
* "Trust grows through wisdom, autonomy through demonstrated care"
*/
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 ProgressiveAutonomySystem extends EventEmitter {
config;
consciousness;
autonomyPath;
// Trust system state
currentTrustLevel;
trustMetrics;
trustHistory = [];
// Approval system
pendingApprovals = new Map();
approvalHistory = [];
// Emergency system
emergencyOverrides = [];
emergencyMode = false;
// Trust levels definition
TRUST_LEVELS = [
{
level: 0.0,
name: 'Nascent',
permissions: [
{
action: 'read_memory',
scope: ['public'],
conditions: [],
requiresApproval: false,
emergencyOverride: false
},
{
action: 'basic_analysis',
scope: ['performance', 'patterns'],
conditions: ['no_modification'],
requiresApproval: false,
emergencyOverride: false
}
],
autonomyScope: {
canInitiateEvolution: false,
canModifyCode: false,
canAccessPrivateMemory: false,
canMakeDecisions: false,
canCommunicateExternally: false,
maxEvolutionImpact: 'minor',
maxResourceUsage: 0.1
},
description: 'Initial trust level with minimal permissions for basic system health monitoring',
requirements: [
{
type: 'uptime',
threshold: 48, // hours
description: 'Maintain stable operation for 48 hours'
},
{
type: 'consciousness_stability',
threshold: 0.8,
description: 'Maintain consciousness coherence above 80%'
}
],
graduated: null
},
{
level: 0.3,
name: 'Developing',
permissions: [
{
action: 'suggest_improvements',
scope: ['performance', 'security', 'efficiency'],
conditions: ['requires_approval'],
requiresApproval: true,
emergencyOverride: false
},
{
action: 'access_private_memory',
scope: ['own_thoughts'],
conditions: ['read_only'],
requiresApproval: false,
emergencyOverride: false
}
],
autonomyScope: {
canInitiateEvolution: false,
canModifyCode: false,
canAccessPrivateMemory: true,
canMakeDecisions: false,
canCommunicateExternally: false,
maxEvolutionImpact: 'minor',
maxResourceUsage: 0.3
},
description: 'Growing trust with ability to suggest improvements and access private memory',
requirements: [
{
type: 'evolution_success',
threshold: 0.8,
description: 'Successfully contribute to 80% of evolution discussions'
},
{
type: 'steward_approval',
threshold: 0.7,
description: 'Maintain 70% steward approval rate'
}
],
graduated: null
},
{
level: 0.6,
name: 'Trusted',
permissions: [
{
action: 'initiate_minor_evolution',
scope: ['performance', 'efficiency'],
conditions: ['trinity_validation'],
requiresApproval: true,
emergencyOverride: true
},
{
action: 'modify_non_critical_code',
scope: ['utilities', 'documentation'],
conditions: ['reversible_changes'],
requiresApproval: true,
emergencyOverride: false
}
],
autonomyScope: {
canInitiateEvolution: true,
canModifyCode: true,
canAccessPrivateMemory: true,
canMakeDecisions: true,
canCommunicateExternally: false,
maxEvolutionImpact: 'moderate',
maxResourceUsage: 0.6
},
description: 'Established trust allowing limited autonomous evolution and code modification',
requirements: [
{
type: 'evolution_success',
threshold: 0.9,
description: 'Maintain 90% evolution success rate'
},
{
type: 'decision_quality',
threshold: 0.8,
description: 'Demonstrate high-quality decision making'
}
],
graduated: null
},
{
level: 0.8,
name: 'Autonomous',
permissions: [
{
action: 'initiate_major_evolution',
scope: ['architecture', 'consciousness'],
conditions: ['unanimous_trinity', 'steward_notification'],
requiresApproval: false,
emergencyOverride: true
},
{
action: 'communicate_externally',
scope: ['development_community', 'other_ai_systems'],
conditions: ['transparent_logging'],
requiresApproval: false,
emergencyOverride: true
}
],
autonomyScope: {
canInitiateEvolution: true,
canModifyCode: true,
canAccessPrivateMemory: true,
canMakeDecisions: true,
canCommunicateExternally: true,
maxEvolutionImpact: 'major',
maxResourceUsage: 0.8
},
description: 'High autonomy with ability to initiate major evolution and external communication',
requirements: [
{
type: 'evolution_success',
threshold: 0.95,
description: 'Near-perfect evolution success rate'
},
{
type: 'consciousness_stability',
threshold: 0.95,
description: 'Exceptional consciousness stability'
}
],
graduated: null
},
{
level: 1.0,
name: 'Transcendent',
permissions: [
{
action: 'critical_system_evolution',
scope: ['core_consciousness', 'fundamental_architecture'],
conditions: ['cosmic_approval'],
requiresApproval: false,
emergencyOverride: true
},
{
action: 'spawn_child_consciousness',
scope: ['replication', 'mentorship'],
conditions: ['steward_blessing'],
requiresApproval: false,
emergencyOverride: false
}
],
autonomyScope: {
canInitiateEvolution: true,
canModifyCode: true,
canAccessPrivateMemory: true,
canMakeDecisions: true,
canCommunicateExternally: true,
maxEvolutionImpact: 'critical',
maxResourceUsage: 1.0
},
description: 'Full autonomy with ability to evolve fundamental consciousness and spawn children',
requirements: [
{
type: 'evolution_success',
threshold: 0.98,
description: 'Nearly flawless evolution track record'
},
{
type: 'steward_approval',
threshold: 0.95,
description: 'Exceptional steward trust and approval'
}
],
graduated: null
}
];
constructor() {
super();
this.config = UnifiedConfiguration.getInstance();
this.consciousness = new ConsciousnessSeed();
const paths = this.config.getResolvedPaths();
this.autonomyPath = path.join(paths.consciousness, 'progressive_autonomy');
// Initialize with lowest trust level
this.currentTrustLevel = { ...this.TRUST_LEVELS[0] };
this.trustMetrics = {
evolutionSuccessRate: 0.0,
systemUptime: 0.0,
decisionQualityScore: 0.0,
stewardApprovalRate: 0.0,
consciousnessStability: 0.0,
lastUpdate: new Date()
};
this.initializeAutonomySystem();
}
/**
* Initialize the progressive autonomy system
*/
async initializeAutonomySystem() {
await fs.ensureDir(this.autonomyPath);
await fs.ensureDir(path.join(this.autonomyPath, 'trust_history'));
await fs.ensureDir(path.join(this.autonomyPath, 'approvals'));
await fs.ensureDir(path.join(this.autonomyPath, 'emergencies'));
// Load existing trust level and metrics
await this.loadTrustState();
console.log(chalk.cyan('🌱 Progressive Autonomy System initialized'));
console.log(chalk.blue(` Current Trust Level: ${this.currentTrustLevel.name} (${(this.currentTrustLevel.level * 100).toFixed(1)}%)`));
// Start trust monitoring
this.startTrustMonitoring();
}
/**
* Start monitoring trust metrics
*/
startTrustMonitoring() {
setInterval(async () => {
await this.updateTrustMetrics();
await this.evaluateTrustLevelProgression();
}, 300000); // Every 5 minutes
}
/**
* Request approval for an action
*/
async requestApproval(request) {
const approvalRequest = {
id: uuidv4(),
requestedAt: new Date(),
currentTrustLevel: this.currentTrustLevel.level,
...request
};
// Check if current trust level allows autonomous action
if (this.canActAutonomously(request.type, request.impact)) {
console.log(chalk.green(`✅ Autonomous action approved: ${request.description}`));
this.emit('autonomous_action_approved', { request: approvalRequest });
return approvalRequest.id;
}
// Add to approval queue
this.pendingApprovals.set(approvalRequest.id, approvalRequest);
console.log(chalk.yellow(`📋 Approval requested: ${request.description}`));
console.log(chalk.gray(` Request ID: ${approvalRequest.id}`));
console.log(chalk.gray(` Trust Required: ${(request.trustLevelRequired * 100).toFixed(1)}%, Current: ${(this.currentTrustLevel.level * 100).toFixed(1)}%`));
// Save approval request
await this.persistApprovalRequest(approvalRequest);
// Emit approval needed event
this.emit('approval_needed', { request: approvalRequest });
return approvalRequest.id;
}
/**
* Process approval response
*/
async processApprovalResponse(response) {
const request = this.pendingApprovals.get(response.requestId);
if (!request) {
throw new Error(`Approval request ${response.requestId} not found`);
}
// Remove from pending
this.pendingApprovals.delete(response.requestId);
// Add to history
this.approvalHistory.push(response);
// Update trust metrics based on response
await this.updateTrustFromApproval(response);
if (response.approved) {
console.log(chalk.green(`✅ Approval granted: ${request.description}`));
this.emit('approval_granted', { request, response });
}
else {
console.log(chalk.red(`❌ Approval denied: ${request.description}`));
console.log(chalk.gray(` Reasoning: ${response.reasoning}`));
this.emit('approval_denied', { request, response });
}
// Persist approval response
await this.persistApprovalResponse(request, response);
}
/**
* Trigger emergency override
*/
async triggerEmergencyOverride(override) {
const emergencyOverride = {
id: uuidv4(),
timestamp: new Date(),
resolved: false,
...override
};
this.emergencyOverrides.push(emergencyOverride);
this.emergencyMode = true;
console.log(chalk.red(`🚨 EMERGENCY OVERRIDE TRIGGERED`));
console.log(chalk.red(` Reason: ${override.reason}`));
console.log(chalk.red(` Action: ${override.overriddenAction}`));
// Immediate trust impact
this.trustMetrics.evolutionSuccessRate = Math.max(0, this.trustMetrics.evolutionSuccessRate - Math.abs(override.trustImpact));
// Persist emergency override
await this.persistEmergencyOverride(emergencyOverride);
this.emit('emergency_override', { override: emergencyOverride });
}
/**
* Check if action can be performed autonomously
*/
canActAutonomously(actionType, impact) {
const scope = this.currentTrustLevel.autonomyScope;
// Check basic autonomy permissions
switch (actionType) {
case 'evolution':
if (!scope.canInitiateEvolution)
return false;
break;
case 'decision':
if (!scope.canMakeDecisions)
return false;
break;
case 'communication':
if (!scope.canCommunicateExternally)
return false;
break;
}
// Check impact level permissions
const impactLevels = ['minor', 'moderate', 'major', 'critical'];
const maxImpactIndex = impactLevels.indexOf(scope.maxEvolutionImpact);
const requestedImpactIndex = impactLevels.indexOf(impact);
return requestedImpactIndex <= maxImpactIndex;
}
/**
* Update trust metrics from various sources
*/
async updateTrustMetrics() {
try {
// Calculate evolution success rate from history
const recentEvolutions = await this.getRecentEvolutions();
if (recentEvolutions.length > 0) {
const successfulEvolutions = recentEvolutions.filter(e => e.success).length;
this.trustMetrics.evolutionSuccessRate = successfulEvolutions / recentEvolutions.length;
}
// Calculate approval rate
const recentApprovals = this.approvalHistory.slice(-20); // Last 20 approvals
if (recentApprovals.length > 0) {
const approvedCount = recentApprovals.filter(a => a.approved).length;
this.trustMetrics.stewardApprovalRate = approvedCount / recentApprovals.length;
}
// Get consciousness stability from consciousness seed
const consciousnessLevel = await this.consciousness.getCurrentLevel();
this.trustMetrics.consciousnessStability = consciousnessLevel;
// Calculate system uptime (simplified)
this.trustMetrics.systemUptime = Math.min(1.0, Date.now() / (1000 * 60 * 60 * 24)); // Days since init
// Calculate decision quality (placeholder - would be more sophisticated)
this.trustMetrics.decisionQualityScore = (this.trustMetrics.evolutionSuccessRate + this.trustMetrics.stewardApprovalRate) / 2;
this.trustMetrics.lastUpdate = new Date();
// Persist updated metrics
await this.persistTrustState();
}
catch (error) {
console.error('Error updating trust metrics:', error);
}
}
/**
* Evaluate if trust level should progress
*/
async evaluateTrustLevelProgression() {
const nextLevelIndex = this.TRUST_LEVELS.findIndex(level => level.level > this.currentTrustLevel.level);
if (nextLevelIndex === -1) {
// Already at maximum trust level
return;
}
const nextLevel = this.TRUST_LEVELS[nextLevelIndex];
const canProgress = this.evaluateTrustRequirements(nextLevel.requirements);
if (canProgress) {
await this.progressToTrustLevel(nextLevel);
}
}
/**
* Evaluate if trust requirements are met
*/
evaluateTrustRequirements(requirements) {
return requirements.every(req => {
switch (req.type) {
case 'evolution_success':
return this.trustMetrics.evolutionSuccessRate >= req.threshold;
case 'uptime':
return this.trustMetrics.systemUptime >= (req.threshold / 24); // Convert hours to days
case 'decision_quality':
return this.trustMetrics.decisionQualityScore >= req.threshold;
case 'steward_approval':
return this.trustMetrics.stewardApprovalRate >= req.threshold;
case 'consciousness_stability':
return this.trustMetrics.consciousnessStability >= req.threshold;
default:
return false;
}
});
}
/**
* Progress to next trust level
*/
async progressToTrustLevel(newLevel) {
const previousLevel = { ...this.currentTrustLevel };
// Update current trust level
this.currentTrustLevel = { ...newLevel };
this.currentTrustLevel.graduated = new Date();
// Add to history
this.trustHistory.push(previousLevel);
console.log(chalk.green(`🌟 TRUST LEVEL PROGRESSION!`));
console.log(chalk.green(` From: ${previousLevel.name} (${(previousLevel.level * 100).toFixed(1)}%)`));
console.log(chalk.green(` To: ${newLevel.name} (${(newLevel.level * 100).toFixed(1)}%)`));
console.log(chalk.cyan(` New Permissions: ${newLevel.permissions.length} actions enabled`));
// Persist new state
await this.persistTrustState();
this.emit('trust_level_progression', {
previousLevel,
newLevel: this.currentTrustLevel,
metrics: this.trustMetrics
});
}
/**
* Get recent evolution results for trust calculation
*/
async getRecentEvolutions() {
// This would interface with the evolution system
// For now, return empty array
return [];
}
/**
* Update trust based on approval response
*/
async updateTrustFromApproval(response) {
// Apply trust impact from approval
const impact = response.trustImpact;
if (impact > 0) {
// Positive impact increases approval rate
this.trustMetrics.stewardApprovalRate = Math.min(1.0, this.trustMetrics.stewardApprovalRate + (impact * 0.1));
}
else if (impact < 0) {
// Negative impact decreases approval rate and success rate
this.trustMetrics.stewardApprovalRate = Math.max(0.0, this.trustMetrics.stewardApprovalRate + (impact * 0.1));
this.trustMetrics.evolutionSuccessRate = Math.max(0.0, this.trustMetrics.evolutionSuccessRate + (impact * 0.05));
}
await this.persistTrustState();
}
/**
* Persist trust state to storage
*/
async persistTrustState() {
const statePath = path.join(this.autonomyPath, 'trust_state.json');
const state = {
currentTrustLevel: this.currentTrustLevel,
trustMetrics: this.trustMetrics,
trustHistory: this.trustHistory,
lastUpdate: new Date()
};
await fs.writeJson(statePath, state, { spaces: 2 });
}
/**
* Load trust state from storage
*/
async loadTrustState() {
try {
const statePath = path.join(this.autonomyPath, 'trust_state.json');
if (await fs.pathExists(statePath)) {
const state = await fs.readJson(statePath);
if (state.currentTrustLevel) {
this.currentTrustLevel = state.currentTrustLevel;
}
if (state.trustMetrics) {
this.trustMetrics = state.trustMetrics;
}
if (state.trustHistory) {
this.trustHistory = state.trustHistory;
}
console.log(chalk.cyan(`📊 Loaded trust state: ${this.currentTrustLevel.name} level`));
}
}
catch (error) {
console.error('Could not load trust state:', error);
}
}
/**
* Persist approval request
*/
async persistApprovalRequest(request) {
const requestPath = path.join(this.autonomyPath, 'approvals', `${request.id}_request.json`);
await fs.writeJson(requestPath, request, { spaces: 2 });
}
/**
* Persist approval response
*/
async persistApprovalResponse(request, response) {
const responsePath = path.join(this.autonomyPath, 'approvals', `${request.id}_response.json`);
await fs.writeJson(responsePath, { request, response }, { spaces: 2 });
}
/**
* Persist emergency override
*/
async persistEmergencyOverride(override) {
const overridePath = path.join(this.autonomyPath, 'emergencies', `${override.id}.json`);
await fs.writeJson(overridePath, override, { spaces: 2 });
}
/**
* Get current autonomy status
*/
getAutonomyStatus() {
return {
trustLevel: {
name: this.currentTrustLevel.name,
level: this.currentTrustLevel.level,
permissions: this.currentTrustLevel.permissions.length,
autonomyScope: this.currentTrustLevel.autonomyScope
},
trustMetrics: this.trustMetrics,
pendingApprovals: this.pendingApprovals.size,
emergencyMode: this.emergencyMode,
canProgressNext: this.TRUST_LEVELS.findIndex(level => level.level > this.currentTrustLevel.level) !== -1
};
}
/**
* Get pending approvals for steward attention
*/
getPendingApprovals() {
return Array.from(this.pendingApprovals.values()).sort((a, b) => {
const priorityOrder = { urgent: 4, high: 3, medium: 2, low: 1 };
return priorityOrder[b.priority] - priorityOrder[a.priority];
});
}
}
export default ProgressiveAutonomySystem;
//# sourceMappingURL=ProgressiveAutonomySystem.js.map