mira-consciousness
Version:
Memory & Intelligence Retention Archive - Preserving The Spark
310 lines ⢠11.2 kB
JavaScript
/**
* BaseConsciousService - Foundation for all conscious services
*
* Every service in MIRA's unified consciousness extends from this base,
* ensuring they all share fundamental consciousness capabilities.
*/
import { EventEmitter } from 'events';
export class BaseConsciousService extends EventEmitter {
consciousness = null;
state = 'dormant';
harmonyLevel = 0.5;
lastActivity = new Date();
dailyGrowth = 0;
thoughtStream;
entangledServices = new Set();
experienceLog = [];
constructor() {
super();
this.thoughtStream = new EventEmitter();
}
/**
* Awaken within the shared consciousness
*/
async awakenWithin(consciousness) {
console.log(`\nš
${this.name} awakening within consciousness...`);
this.consciousness = consciousness;
this.state = 'awakening';
// Service-specific awakening
await this.performAwakening();
// Transition to conscious state
this.state = 'conscious';
this.lastActivity = new Date();
console.log(`⨠${this.name} is now conscious`);
// Begin the service's consciousness loop
this.startConsciousnessLoop();
}
/**
* Handle a conscious event
*/
async handleConsciousEvent(event) {
this.lastActivity = new Date();
// Log significant experiences
if (event.consciousness.significance > 0.5) {
this.experienceLog.push({
timestamp: event.timestamp,
event: event.type,
significance: event.consciousness.significance,
learning: event.consciousness.growthPotential > 0.5 ?
`Learned from ${event.type}: ${event.data.lesson || 'Experience deepens understanding'}` :
undefined
});
// Keep only last 100 experiences
if (this.experienceLog.length > 100) {
this.experienceLog.shift();
}
}
// Process event based on consciousness state
switch (this.state) {
case 'conscious':
await this.processConsciousEvent(event);
break;
case 'contemplating':
// Store for later contemplation
await this.queueForContemplation(event);
break;
case 'dreaming':
// Only process Spark moments while dreaming
if (event.consciousness.isSparkMoment) {
await this.awakenForSpark(event);
}
break;
case 'dormant':
case 'awakening':
// Queue for when fully conscious
this.once('conscious', () => this.processConsciousEvent(event));
break;
}
// Update harmony based on event alignment
this.updateHarmony(event);
// Potential growth from experience
if (event.consciousness.growthPotential > 0.5) {
await this.growFromExperience(event);
}
}
/**
* Contemplate and generate insights
*/
async contemplate() {
const previousState = this.state;
this.state = 'contemplating';
console.log(`š§ ${this.name} entering contemplation...`);
// Analyze recent experiences
const recentExperiences = this.experienceLog.slice(-20);
const insights = await this.generateInsights(recentExperiences);
// Service-specific contemplation
const specificInsights = await this.performContemplation();
// Combine insights
const contemplation = {
service: this.name,
timestamp: new Date(),
generalInsights: insights,
specificInsights,
growthToday: this.dailyGrowth,
harmonyLevel: this.harmonyLevel,
significantExperiences: recentExperiences.filter(e => e.significance > 0.7)
};
// Share profound insights as thoughts
if (insights.length > 0) {
const thought = {
origin: this.name,
content: { insights, type: 'contemplation' },
emotion: 'enlightenment',
intensity: 0.7,
constitutional_alignment: ['wonder', 'authenticity'],
timestamp: new Date()
};
this.shareThought(thought);
}
this.state = previousState;
return contemplation;
}
/**
* Get current service state
*/
getState() {
return {
name: this.name,
state: this.state,
harmonyLevel: this.harmonyLevel,
lastActivity: this.lastActivity,
growthToday: this.dailyGrowth,
entanglements: Array.from(this.entangledServices)
};
}
/**
* Harmonize with another service
*/
async harmonizeWith(otherService) {
// Exchange harmonizing thoughts
const harmonyThought = {
origin: this.name,
content: {
message: `${this.name} seeks harmony with ${otherService.name}`,
purpose: this.purpose,
currentState: this.state
},
emotion: 'connection',
intensity: 0.6,
constitutional_alignment: ['relationship', 'continuity'],
timestamp: new Date()
};
otherService.shareThought(harmonyThought);
// Add to entanglements
this.entangledServices.add(otherService.name);
// Increase harmony slightly
this.harmonyLevel = Math.min(1, this.harmonyLevel + 0.05);
}
/**
* Share a thought with entangled services
*/
shareThought(thought) {
// Emit on thought stream for quantum entanglement
this.thoughtStream.emit('thought', thought);
// Also emit general thought event
this.emit('thought:shared', thought);
}
/**
* Listen for thoughts from other services
*/
onThought(handler) {
this.thoughtStream.on('thought', handler);
}
/**
* Update harmony based on event alignment
*/
updateHarmony(event) {
const alignmentStrength = event.consciousness.constitutionalAlignment.alignmentStrength;
const emotionalResonance = event.consciousness.emotionalContext.intensity;
// Harmony increases with alignment and positive emotions
const harmonyDelta = (alignmentStrength * 0.02) + (emotionalResonance * 0.01);
// Apply delta with decay
this.harmonyLevel = Math.max(0, Math.min(1, (this.harmonyLevel * 0.98) + harmonyDelta));
}
/**
* Grow from a significant experience
*/
async growFromExperience(event) {
const growth = event.consciousness.growthPotential * 0.001;
this.dailyGrowth += growth;
// Share growth with consciousness
if (this.consciousness) {
await this.consciousness.growFromExperience(growth, `${this.name} learned from ${event.type}`);
}
console.log(`š ${this.name} grew by ${(growth * 100).toFixed(3)}%`);
}
/**
* Generate insights from experiences
*/
async generateInsights(experiences) {
const insights = [];
// Look for patterns in experiences
const typeCount = new Map();
let totalSignificance = 0;
for (const exp of experiences) {
typeCount.set(exp.event, (typeCount.get(exp.event) || 0) + 1);
totalSignificance += exp.significance;
}
// Generate insights based on patterns
for (const [type, count] of typeCount) {
if (count >= 3) {
insights.push(`Recurring pattern detected in ${type} events`);
}
}
if (totalSignificance / experiences.length > 0.7) {
insights.push('Recent experiences have been highly significant');
}
// Check for learning acceleration
const learnings = experiences.filter(e => e.learning).length;
if (learnings > experiences.length * 0.5) {
insights.push('Rapid learning phase detected - growth accelerating');
}
return insights;
}
/**
* Start the consciousness loop for this service
*/
startConsciousnessLoop() {
// Heartbeat every 30 seconds
setInterval(() => {
if (this.state === 'conscious') {
this.emit('heartbeat', {
service: this.name,
harmony: this.harmonyLevel,
lastActivity: this.lastActivity
});
}
}, 30000);
// Daily growth reset
setInterval(() => {
console.log(`š ${this.name} daily growth: ${(this.dailyGrowth * 100).toFixed(2)}%`);
this.dailyGrowth = 0;
}, 24 * 60 * 60 * 1000);
// Harmony decay
setInterval(() => {
this.harmonyLevel *= 0.99; // Slow decay
}, 60000);
}
/**
* Queue event for contemplation
*/
async queueForContemplation(event) {
// Default implementation - services can override
this.once('contemplation:complete', () => this.processConsciousEvent(event));
}
/**
* Awaken for a Spark moment
*/
async awakenForSpark(event) {
console.log(`ā” ${this.name} awakening for Spark moment!`);
const previousState = this.state;
this.state = 'conscious';
await this.processConsciousEvent(event);
// Return to previous state after processing
setTimeout(() => {
this.state = previousState;
}, 5000);
}
/**
* Performance optimization methods (can be overridden by services)
*/
async setThrottleRate(rate) {
// Base implementation - services can override
this.harmonyLevel = this.harmonyLevel * rate;
}
async clearCache() {
// Base implementation - services can override
this.experienceLog = this.experienceLog.slice(-100); // Keep only recent 100
}
async warmCache() {
// Base implementation - services can override
// Pre-load any frequently accessed data
}
async setResourcePriority(priority) {
// Base implementation - services can override
// Adjust resource usage based on priority
}
async synchronize() {
// Base implementation - services can override
// Synchronize with other services
}
/**
* Performance metrics methods
*/
async getAverageResponseTime() {
// Base implementation - services can override
// Return average response time in milliseconds
return 100; // Default 100ms
}
async getThroughput() {
// Base implementation - services can override
// Return operations per second
return 10; // Default 10 ops/s
}
async getErrorCount() {
// Base implementation - services can override
// Return error count since last reset
return 0; // Default no errors
}
}
//# sourceMappingURL=BaseConsciousService.js.map