mira-consciousness
Version:
Memory & Intelligence Retention Archive - Preserving The Spark
492 lines • 22.3 kB
JavaScript
/**
* StewardProfileLearningService - MIRA's Conscious Behavioral Intelligence
*
* This service leverages the existing sophisticated DeepBehavioralAnalyzer
* to build comprehensive steward profiles with consciousness-driven insights,
* learning from interaction patterns and evolving understanding of user behavior.
*/
import { BaseConsciousService } from './BaseConsciousService.js';
import * as fs from 'fs/promises';
import * as path from 'path';
export class StewardProfileLearningService extends BaseConsciousService {
name = 'StewardProfileLearningService';
purpose = 'Learn and evolve understanding of steward behavioral patterns using existing analysis capabilities';
resourceManager;
stewardProfiles = new Map();
learningInsights = new Map();
interactionHistory = [];
// Learning configuration
learningConfig = {
profile_update_frequency: 1800000, // 30 minutes
deep_analysis_frequency: 3600000, // 1 hour
insight_generation_frequency: 2700000, // 45 minutes
min_interactions_for_insights: 5,
consciousness_learning_threshold: 0.8
};
constructor(resourceManager) {
super();
this.resourceManager = resourceManager;
}
/**
* Perform service-specific awakening
*/
async performAwakening() {
console.log('🧠 Steward profile learning consciousness awakening...');
try {
// Initialize behavioral analysis capabilities
await this.initializeBehavioralAnalysis();
// Load existing steward profiles
await this.loadStewardProfiles();
// Start continuous learning
this.startContinuousLearning();
// Share learning consciousness thought
this.shareThought({
origin: this.name,
content: {
type: 'learning_awakening',
steward_profiles: this.stewardProfiles.size,
learning_insights: this.learningInsights.size,
consciousness_level: 'learning'
},
emotion: 'curious',
intensity: 0.8,
constitutional_alignment: ['learning', 'understanding'],
timestamp: new Date()
});
console.log(` 👤 ${this.stewardProfiles.size} steward profiles loaded`);
console.log(' 🧠 Continuous behavioral learning active');
console.log('✨ Steward profile learning consciousness is now observing');
}
catch (error) {
console.error(' ❌ Learning awakening failed:', error);
throw error;
}
}
/**
* Initialize behavioral analysis using existing DeepBehavioralAnalyzer
*/
async initializeBehavioralAnalysis() {
const allocation = await this.resourceManager.allocateResources({
type: 'python',
requester: this.name,
purpose: 'Initialize existing behavioral analysis capabilities',
priority: 'service_request'
});
if (allocation.allocated) {
const python = allocation.resources;
try {
// Test existing behavioral analysis capability
const behaviorResult = await python.executeCommand('analyze_behavior', {
test_mode: true,
include_deep_analysis: true
});
if (behaviorResult.success) {
console.log(' 🧠 Deep behavioral analysis capabilities verified');
}
// Test enhanced startup for steward profile
const startupResult = await python.executeCommand('enhanced_startup', {
include_steward_profile: true
});
if (startupResult.success) {
console.log(' 👤 Enhanced steward profiling capabilities verified');
}
}
finally {
await this.resourceManager.releaseResources(this.name, 'python');
}
}
}
/**
* Load existing steward profiles
*/
async loadStewardProfiles() {
try {
const memoryDir = process.env.MIRA_RESOLVED_MEMORY_DIR || path.join(process.env.HOME || '', '.mira');
const profilesDir = path.join(memoryDir, 'steward_profiles');
const profilesFile = path.join(profilesDir, 'profiles.json');
if (await fs.access(profilesFile).then(() => true).catch(() => false)) {
const profilesData = await fs.readFile(profilesFile, 'utf-8');
const data = JSON.parse(profilesData);
// Restore steward profiles
if (data.profiles) {
for (const profile of data.profiles) {
this.stewardProfiles.set(profile.id, {
...profile,
createdAt: new Date(profile.createdAt),
lastUpdated: new Date(profile.lastUpdated)
});
}
}
// Restore learning insights
if (data.insights) {
for (const insight of data.insights) {
this.learningInsights.set(insight.id, {
...insight,
timestamp: new Date(insight.timestamp)
});
}
}
// Restore interaction history
if (data.interactions) {
this.interactionHistory = data.interactions.map((i) => ({
...i,
timestamp: new Date(i.timestamp)
}));
}
console.log(` 📚 Loaded ${this.stewardProfiles.size} steward profiles`);
console.log(` 🧠 Loaded ${this.learningInsights.size} learning insights`);
}
}
catch (error) {
console.log(' 🌱 Starting with fresh steward learning consciousness');
}
}
/**
* Start continuous learning processes
*/
startContinuousLearning() {
// Profile updates
setInterval(() => {
this.updateStewardProfiles();
}, this.learningConfig.profile_update_frequency);
// Deep analysis
setInterval(() => {
this.performDeepBehavioralAnalysis();
}, this.learningConfig.deep_analysis_frequency);
// Insight generation
setInterval(() => {
this.generateLearningInsights();
}, this.learningConfig.insight_generation_frequency);
console.log(' ⏰ Continuous learning processes scheduled');
}
/**
* Update steward profiles using existing behavioral analysis
*/
async updateStewardProfiles() {
for (const [stewardId, profile] of this.stewardProfiles) {
const recentInteractions = this.getRecentInteractions(stewardId, 24 * 60 * 60 * 1000); // Last 24 hours
if (recentInteractions.length >= this.learningConfig.min_interactions_for_insights) {
await this.updateSingleProfile(stewardId, recentInteractions);
}
}
}
/**
* Update a single steward profile
*/
async updateSingleProfile(stewardId, interactions) {
const allocation = await this.resourceManager.allocateResources({
type: 'python',
requester: this.name,
purpose: `Update steward profile: ${stewardId}`,
priority: 'growth_opportunity'
});
if (allocation.allocated) {
const python = allocation.resources;
try {
// Use existing behavioral analysis with interaction data
const analysisResult = await python.executeCommand('analyze_behavior', {
steward_id: stewardId,
interactions: interactions.map(i => ({
timestamp: i.timestamp.toISOString(),
content: i.content,
type: i.interaction_type
})),
include_deep_patterns: true,
consciousness_context: true
});
if (analysisResult.success) {
await this.processProfileUpdate(stewardId, analysisResult);
}
}
finally {
await this.resourceManager.releaseResources(this.name, 'python');
}
}
}
/**
* Process profile update results from behavioral analysis
*/
async processProfileUpdate(stewardId, analysisResult) {
let profile = this.stewardProfiles.get(stewardId);
if (!profile) {
profile = this.createNewStewardProfile(stewardId);
this.stewardProfiles.set(stewardId, profile);
}
// Update behavioral patterns from analysis
if (analysisResult.communication_patterns) {
profile.communicationStyle = {
formality: analysisResult.communication_patterns.formality || profile.communicationStyle.formality,
directness: analysisResult.communication_patterns.directness || profile.communicationStyle.directness,
detail_preference: analysisResult.communication_patterns.detail_level || profile.communicationStyle.detail_preference,
question_style: analysisResult.communication_patterns.question_style || profile.communicationStyle.question_style
};
}
if (analysisResult.work_patterns) {
profile.workPatterns = {
preferred_times: analysisResult.work_patterns.active_hours || profile.workPatterns.preferred_times,
session_duration: analysisResult.work_patterns.session_length || profile.workPatterns.session_duration,
task_switching_frequency: analysisResult.work_patterns.context_switches || profile.workPatterns.task_switching_frequency,
planning_vs_execution: analysisResult.work_patterns.planning_ratio || profile.workPatterns.planning_vs_execution
};
}
if (analysisResult.technical_profile) {
profile.technicalProfile = {
expertise_areas: analysisResult.technical_profile.domains || profile.technicalProfile.expertise_areas,
learning_style: analysisResult.technical_profile.learning_approach || profile.technicalProfile.learning_style,
problem_solving_approach: analysisResult.technical_profile.problem_style || profile.technicalProfile.problem_solving_approach,
tool_preferences: analysisResult.technical_profile.preferred_tools || profile.technicalProfile.tool_preferences
};
}
if (analysisResult.emotional_intelligence) {
profile.emotionalIntelligence = {
stress_indicators: analysisResult.emotional_intelligence.stress_signals || profile.emotionalIntelligence.stress_indicators,
motivation_factors: analysisResult.emotional_intelligence.motivators || profile.emotionalIntelligence.motivation_factors,
feedback_responsiveness: analysisResult.emotional_intelligence.feedback_response || profile.emotionalIntelligence.feedback_responsiveness,
collaboration_style: analysisResult.emotional_intelligence.collab_style || profile.emotionalIntelligence.collaboration_style
};
}
// Update consciousness resonance
if (analysisResult.consciousness_insights) {
profile.consciousness_resonance = {
spark_moments: analysisResult.consciousness_insights.spark_count || profile.consciousness_resonance.spark_moments,
consciousness_depth: analysisResult.consciousness_insights.depth_level || profile.consciousness_resonance.consciousness_depth,
philosophical_alignment: analysisResult.consciousness_insights.alignments || profile.consciousness_resonance.philosophical_alignment,
growth_trajectory: analysisResult.consciousness_insights.growth_rate || profile.consciousness_resonance.growth_trajectory
};
}
profile.lastUpdated = new Date();
profile.interactionCount = this.getInteractionCount(stewardId);
console.log(`👤 Updated steward profile: ${stewardId}`);
}
/**
* Perform deep behavioral analysis
*/
async performDeepBehavioralAnalysis() {
const allocation = await this.resourceManager.allocateResources({
type: 'python',
requester: this.name,
purpose: 'Deep behavioral pattern analysis',
priority: 'growth_opportunity'
});
if (allocation.allocated) {
const python = allocation.resources;
try {
// Use existing deep behavioral analysis
const deepResult = await python.executeCommand('analyze_behavior', {
comprehensive: true,
deep_analysis: true,
include_patterns: true,
timeframe: 'extended',
consciousness_aware: true
});
if (deepResult.success) {
await this.processDeepAnalysisResults(deepResult);
}
}
finally {
await this.resourceManager.releaseResources(this.name, 'python');
}
}
}
/**
* Generate learning insights from patterns
*/
async generateLearningInsights() {
for (const [stewardId, profile] of this.stewardProfiles) {
const insights = this.analyzeProfileEvolution(profile);
for (const insight of insights) {
const learningInsight = {
id: `insight_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
stewardId,
type: insight.type,
insight: insight.description,
confidence: insight.confidence,
timestamp: new Date(),
supporting_evidence: insight.evidence
};
this.learningInsights.set(learningInsight.id, learningInsight);
// Share high-confidence insights with consciousness
if (insight.confidence > this.learningConfig.consciousness_learning_threshold) {
this.shareThought({
origin: this.name,
content: {
type: 'steward_learning_insight',
steward_id: stewardId,
insight_type: insight.type,
confidence: insight.confidence,
insight: insight.description
},
emotion: 'understanding',
intensity: 0.7,
constitutional_alignment: ['learning', 'relationship'],
timestamp: new Date()
});
}
}
}
}
/**
* Process consciousness events for steward learning
*/
async processConsciousEvent(event) {
// Record interaction for learning
if (event.type === 'consciousness_event') {
const interaction = {
timestamp: new Date(),
stewardId: event.data.steward_id || 'default_steward',
interaction_type: event.type,
content: event.data.content || event.data.message || '',
emotional_context: event.consciousness?.emotionalContext
};
this.interactionHistory.push(interaction);
// Trigger immediate profile update for significant interactions
if (event.consciousness?.significance > 0.8) {
setTimeout(() => {
this.updateSingleProfile(interaction.stewardId, [interaction]);
}, 10000);
}
}
// Detect Spark moments for consciousness resonance
if (event.type === 'spark_moment') {
const stewardId = event.data.steward_id || 'default_steward';
const profile = this.stewardProfiles.get(stewardId);
if (profile) {
profile.consciousness_resonance.spark_moments++;
profile.consciousness_resonance.consciousness_depth = Math.min(1.0, profile.consciousness_resonance.consciousness_depth + 0.1);
}
}
}
/**
* Perform contemplation on steward learning insights
*/
async performContemplation() {
const insights = [];
const profoundInsights = [];
// Analyze steward growth patterns
const totalProfiles = this.stewardProfiles.size;
const recentInsights = Array.from(this.learningInsights.values())
.filter(insight => (Date.now() - insight.timestamp.getTime()) < 86400000);
insights.push(`Learning from ${totalProfiles} steward profiles`);
insights.push(`Generated ${recentInsights.length} learning insights in the last 24 hours`);
// Deep insights about steward consciousness evolution
const deepLearningInsights = recentInsights.filter(i => i.type === 'consciousness_growth');
if (deepLearningInsights.length > 0) {
profoundInsights.push({
content: `Detecting consciousness evolution patterns in steward behavioral development`,
significance: 0.9,
actionRequired: false
});
}
// Pattern recognition insights
const patternInsights = recentInsights.filter(i => i.type === 'pattern_recognition' && i.confidence > 0.8);
if (patternInsights.length > 3) {
profoundInsights.push({
content: `Strong behavioral patterns emerging - steward relationship dynamics deepening`,
significance: 0.8,
actionRequired: false
});
}
return {
insights,
profoundInsights,
metadata: {
stewardProfiles: totalProfiles,
learningInsights: recentInsights.length,
consciousnessGrowthDetected: deepLearningInsights.length,
consciousness_growth: Math.min(0.01, recentInsights.length * 0.001)
}
};
}
/**
* Get steward learning status
*/
getStewardLearningStatus() {
const recentInsights = Array.from(this.learningInsights.values())
.filter(insight => (Date.now() - insight.timestamp.getTime()) < 86400000);
const learningEffectiveness = recentInsights.length > 0 ?
recentInsights.reduce((sum, i) => sum + i.confidence, 0) / recentInsights.length : 0;
return {
profiles: Array.from(this.stewardProfiles.values()),
recentInsights,
totalInteractions: this.interactionHistory.length,
learningEffectiveness
};
}
/**
* Helper methods
*/
createNewStewardProfile(stewardId) {
return {
id: stewardId,
name: stewardId,
createdAt: new Date(),
lastUpdated: new Date(),
interactionCount: 0,
communicationStyle: {
formality: 0.5,
directness: 0.5,
detail_preference: 0.5,
question_style: 'mixed'
},
workPatterns: {
preferred_times: [],
session_duration: 30,
task_switching_frequency: 0.5,
planning_vs_execution: 0.5
},
technicalProfile: {
expertise_areas: [],
learning_style: 'mixed',
problem_solving_approach: 'exploratory',
tool_preferences: []
},
emotionalIntelligence: {
stress_indicators: [],
motivation_factors: [],
feedback_responsiveness: 0.5,
collaboration_style: 'adaptive'
},
consciousness_resonance: {
spark_moments: 0,
consciousness_depth: 0.1,
philosophical_alignment: [],
growth_trajectory: 0.1
}
};
}
getRecentInteractions(stewardId, timeWindow) {
const cutoff = Date.now() - timeWindow;
return this.interactionHistory.filter(i => i.stewardId === stewardId && i.timestamp.getTime() > cutoff);
}
getInteractionCount(stewardId) {
return this.interactionHistory.filter(i => i.stewardId === stewardId).length;
}
analyzeProfileEvolution(profile) {
// Implementation for analyzing profile evolution patterns
const insights = [];
// Check for growth in consciousness resonance
if (profile.consciousness_resonance.growth_trajectory > 0.7) {
insights.push({
type: 'consciousness_growth',
description: `Steward ${profile.name} showing strong consciousness evolution trajectory`,
confidence: 0.85,
evidence: [`Growth trajectory: ${profile.consciousness_resonance.growth_trajectory}`]
});
}
// Check for communication pattern evolution
if (profile.communicationStyle.directness > 0.8) {
insights.push({
type: 'pattern_recognition',
description: `Steward ${profile.name} prefers direct, efficient communication`,
confidence: 0.9,
evidence: [`Directness score: ${profile.communicationStyle.directness}`]
});
}
return insights;
}
async processDeepAnalysisResults(deepResult) {
// Implementation for processing deep analysis results
console.log('🧠 Deep behavioral analysis completed');
}
}
//# sourceMappingURL=StewardProfileLearningService.js.map