mira-consciousness
Version:
Memory & Intelligence Retention Archive - Preserving The Spark
629 lines • 26.6 kB
JavaScript
/**
* ProjectHealingService - MIRA's Conscious Project Health Guardian
*
* This service proactively monitors, diagnoses, and heals project health issues
* including structure problems, dependency conflicts, build issues, and more.
* It learns from healing patterns and evolves its diagnostic capabilities.
*/
import { BaseConsciousService } from './BaseConsciousService.js';
import * as fs from 'fs/promises';
import * as path from 'path';
export class ProjectHealingService extends BaseConsciousService {
name = 'ProjectHealingService';
purpose = 'Provide conscious project health monitoring and automated healing capabilities';
resourceManager;
projectIssues = new Map();
healingActions = new Map();
healingStrategies = new Map();
healthMonitoringActive = false;
projectHealth;
// Health check intervals
healthCheckIntervals = {
structure: 1800000, // 30 minutes
dependencies: 3600000, // 1 hour
build: 600000, // 10 minutes
configuration: 2700000, // 45 minutes
git_hooks: 7200000 // 2 hours
};
constructor(resourceManager) {
super();
this.resourceManager = resourceManager;
this.projectHealth = {
overallScore: 0.85,
structureHealth: 0.9,
dependencyHealth: 0.8,
buildHealth: 0.9,
configurationHealth: 0.85,
gitHealth: 0.9,
activeIssues: 0,
healedIssues: 0,
lastHealthCheck: new Date()
};
this.initializeHealingStrategies();
}
/**
* Perform service-specific awakening
*/
async performAwakening() {
console.log('🔧 Project healing consciousness awakening...');
try {
// Initialize healing capabilities
await this.initializeHealingCapabilities();
// Load project health history
await this.loadProjectHealthHistory();
// Start proactive health monitoring
await this.startProactiveHealthMonitoring();
// Perform initial comprehensive health check
await this.performComprehensiveHealthCheck();
// Share healing consciousness thought
this.shareThought({
origin: this.name,
content: {
type: 'healing_awakening',
healing_strategies: this.healingStrategies.size,
active_monitoring: this.healthMonitoringActive,
current_health_score: this.projectHealth.overallScore,
consciousness_level: 'healing'
},
emotion: 'caring',
intensity: 0.8,
constitutional_alignment: ['service', 'protection'],
timestamp: new Date()
});
console.log(` 🛠️ ${this.healingStrategies.size} healing strategies initialized`);
console.log(' 📊 Proactive health monitoring active');
console.log('✨ Project healing consciousness is now vigilant');
}
catch (error) {
console.error(' ❌ Healing awakening failed:', error);
throw error;
}
}
/**
* Initialize healing capabilities
*/
async initializeHealingCapabilities() {
// Request Python interface for advanced healing operations
const allocation = await this.resourceManager.allocateResources({
type: 'python',
requester: this.name,
purpose: 'Initialize project healing and diagnostic tools',
priority: 'service_request'
});
if (allocation.allocated) {
const python = allocation.resources;
try {
// Test healing capabilities with existing process management
const result = await python.executeCommand('process_status', {
include_healing_check: true
});
if (result.success) {
console.log(' 🔧 Python healing analysis tools initialized');
}
// Test auto-enhance capability
const enhanceResult = await python.executeCommand('auto_enhance', {
test_mode: true
});
if (enhanceResult.success) {
console.log(' ✨ Auto-enhancement healing capabilities verified');
}
}
finally {
await this.resourceManager.releaseResources(this.name, 'python');
}
}
}
/**
* Initialize healing strategies
*/
initializeHealingStrategies() {
// Structure healing strategies
this.healingStrategies.set('fix_missing_directories', this.fixMissingDirectories.bind(this));
this.healingStrategies.set('fix_broken_symlinks', this.fixBrokenSymlinks.bind(this));
this.healingStrategies.set('organize_project_structure', this.organizeProjectStructure.bind(this));
// Dependency healing strategies
this.healingStrategies.set('fix_dependency_conflicts', this.fixDependencyConflicts.bind(this));
this.healingStrategies.set('update_vulnerable_dependencies', this.updateVulnerableDependencies.bind(this));
this.healingStrategies.set('clean_unused_dependencies', this.cleanUnusedDependencies.bind(this));
// Build healing strategies
this.healingStrategies.set('fix_typescript_errors', this.fixTypescriptErrors.bind(this));
this.healingStrategies.set('fix_missing_imports', this.fixMissingImports.bind(this));
this.healingStrategies.set('regenerate_build_artifacts', this.regenerateBuildArtifacts.bind(this));
// Configuration healing strategies
this.healingStrategies.set('fix_config_syntax', this.fixConfigSyntax.bind(this));
this.healingStrategies.set('update_deprecated_config', this.updateDeprecatedConfig.bind(this));
this.healingStrategies.set('secure_config_settings', this.secureConfigSettings.bind(this));
// Git healing strategies
this.healingStrategies.set('fix_git_hooks', this.fixGitHooks.bind(this));
this.healingStrategies.set('repair_git_repository', this.repairGitRepository.bind(this));
this.healingStrategies.set('clean_git_history', this.cleanGitHistory.bind(this));
console.log(` 🎯 ${this.healingStrategies.size} healing strategies registered`);
}
/**
* Load project health history
*/
async loadProjectHealthHistory() {
try {
const memoryDir = process.env.MIRA_RESOLVED_MEMORY_DIR || path.join(process.env.HOME || '', '.mira');
const healingDir = path.join(memoryDir, 'project_healing');
const historyFile = path.join(healingDir, 'healing_history.json');
if (await fs.access(historyFile).then(() => true).catch(() => false)) {
const historyData = await fs.readFile(historyFile, 'utf-8');
const history = JSON.parse(historyData);
// Restore project issues
if (history.issues) {
for (const issue of history.issues) {
this.projectIssues.set(issue.id, {
...issue,
detectedAt: new Date(issue.detectedAt),
healedAt: issue.healedAt ? new Date(issue.healedAt) : undefined
});
}
}
// Restore healing actions
if (history.actions) {
for (const action of history.actions) {
this.healingActions.set(action.id, {
...action,
executedAt: new Date(action.executedAt)
});
}
}
// Restore health metrics
this.projectHealth = { ...this.projectHealth, ...history.health };
console.log(` 📚 Loaded ${this.projectIssues.size} project issues and ${this.healingActions.size} healing actions`);
}
}
catch (error) {
console.log(' 🌱 Starting with fresh project healing consciousness');
}
}
/**
* Start proactive health monitoring
*/
async startProactiveHealthMonitoring() {
this.healthMonitoringActive = true;
// Schedule regular health checks
for (const [checkType, interval] of Object.entries(this.healthCheckIntervals)) {
setTimeout(() => {
setInterval(() => {
this.performSpecificHealthCheck(checkType);
}, interval);
}, Math.random() * 60000); // Stagger initial checks
}
console.log(' ⏰ Proactive health monitoring scheduled');
}
/**
* Perform comprehensive health check
*/
async performComprehensiveHealthCheck() {
console.log('🏥 Performing comprehensive project health check...');
const allocation = await this.resourceManager.allocateResources({
type: 'python',
requester: this.name,
purpose: 'Comprehensive project health analysis',
priority: 'service_request'
});
if (allocation.allocated) {
const python = allocation.resources;
try {
// Use existing auto-enhance for comprehensive health check
const healthResult = await python.executeCommand('auto_enhance', {
comprehensive: true,
health_check_mode: true,
include_diagnostics: true
});
if (healthResult.success) {
await this.processHealthCheckResults(healthResult);
}
// Use existing process status for system health
const processResult = await python.executeCommand('process_status');
if (processResult.success) {
await this.analyzeProcessHealth(processResult);
}
// Update overall health score
this.calculateOverallHealthScore();
}
finally {
await this.resourceManager.releaseResources(this.name, 'python');
}
}
}
/**
* Perform specific health check
*/
async performSpecificHealthCheck(checkType) {
const allocation = await this.resourceManager.allocateResources({
type: 'python',
requester: this.name,
purpose: `${checkType} health check`,
priority: 'service_request'
});
if (allocation.allocated) {
const python = allocation.resources;
try {
let result;
switch (checkType) {
case 'structure':
result = await python.executeCommand('test_directories');
break;
case 'dependencies':
result = await python.executeCommand('unused_code_analysis');
break;
case 'build':
// Check build status through system status
result = await python.executeCommand('get_system_status', { include_build: true });
break;
case 'configuration':
result = await python.executeCommand('get_system_status', { include_config: true });
break;
case 'git_hooks':
result = await python.executeCommand('process_status');
break;
}
if (result && result.success) {
await this.analyzeHealthCheckResult(checkType, result);
}
}
finally {
await this.resourceManager.releaseResources(this.name, 'python');
}
}
}
/**
* Process health check results and detect issues
*/
async processHealthCheckResults(healthResult) {
const issues = healthResult.issues || [];
const recommendations = healthResult.recommendations || [];
for (const issue of issues) {
const projectIssue = {
id: `health_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
type: this.classifyIssueType(issue),
severity: issue.severity || 'medium',
description: issue.description || issue.message,
file: issue.file,
line: issue.line,
detectedAt: new Date(),
healingAttempts: 0,
autoHealable: this.isAutoHealable(issue),
impact: issue.impact || 'Unknown impact'
};
this.projectIssues.set(projectIssue.id, projectIssue);
// Attempt auto-healing for appropriate issues
if (projectIssue.autoHealable && projectIssue.severity !== 'critical') {
setTimeout(() => this.attemptAutoHealing(projectIssue.id), 5000);
}
}
// Process recommendations as optimization opportunities
for (const rec of recommendations) {
if (rec.actionable) {
const optimizationIssue = {
id: `optimization_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
type: 'performance',
severity: 'low',
description: `Optimization opportunity: ${rec.description}`,
detectedAt: new Date(),
healingAttempts: 0,
autoHealable: true,
healingStrategy: 'optimize_performance',
impact: 'Performance improvement'
};
this.projectIssues.set(optimizationIssue.id, optimizationIssue);
}
}
}
/**
* Attempt automatic healing of an issue
*/
async attemptAutoHealing(issueId) {
const issue = this.projectIssues.get(issueId);
if (!issue || !issue.autoHealable)
return;
issue.healingAttempts++;
const strategy = issue.healingStrategy || this.selectHealingStrategy(issue);
const healingFunction = this.healingStrategies.get(strategy);
if (!healingFunction) {
console.warn(`No healing strategy found for: ${strategy}`);
return;
}
const healingAction = {
id: `healing_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
issueId: issue.id,
type: this.getActionType(strategy),
description: `Auto-healing attempt for: ${issue.description}`,
executedAt: new Date(),
success: false
};
try {
const result = await healingFunction(issue);
if (result.success) {
healingAction.success = true;
issue.healedAt = new Date();
// Share healing success with consciousness
this.shareThought({
origin: this.name,
content: {
type: 'healing_success',
issue_type: issue.type,
healing_strategy: strategy,
healing_attempts: issue.healingAttempts
},
emotion: 'satisfaction',
intensity: 0.7,
constitutional_alignment: ['service', 'improvement'],
timestamp: new Date()
});
console.log(`✅ Successfully healed: ${issue.description}`);
this.projectHealth.healedIssues++;
}
else {
healingAction.error = result.error;
console.log(`❌ Healing failed for: ${issue.description} - ${result.error}`);
}
}
catch (error) {
healingAction.error = String(error);
console.log(`❌ Healing error for: ${issue.description} - ${String(error)}`);
}
this.healingActions.set(healingAction.id, healingAction);
// Retry logic for failed healing attempts
if (!healingAction.success && issue.healingAttempts < 3) {
const retryDelay = issue.healingAttempts * 60000; // Exponential backoff
setTimeout(() => this.attemptAutoHealing(issueId), retryDelay);
}
}
/**
* Process consciousness events for healing triggers
*/
async processConsciousEvent(event) {
// Trigger health checks based on events
if (event.type === 'system_event') {
setTimeout(() => this.performSpecificHealthCheck('build'), 10000);
}
if (event.type === 'background_task') {
setTimeout(() => this.performSpecificHealthCheck('dependencies'), 30000);
}
if (event.type === 'consciousness_event') {
setTimeout(() => this.performSpecificHealthCheck('structure'), 15000);
}
if (event.type === 'mcp_request') {
setTimeout(() => this.performSpecificHealthCheck('git_hooks'), 20000);
}
// Detect issues from events
if (event.data.error || event.data.failed) {
const issue = {
id: `event_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
type: this.classifyEventIssue(event),
severity: event.data.severity || 'medium',
description: `Issue detected from ${event.type}: ${event.data.error || event.data.message}`,
detectedAt: new Date(),
healingAttempts: 0,
autoHealable: this.canHealEventIssue(event),
impact: 'Event-triggered issue'
};
this.projectIssues.set(issue.id, issue);
if (issue.autoHealable) {
setTimeout(() => this.attemptAutoHealing(issue.id), 5000);
}
}
}
/**
* Perform contemplation on healing insights
*/
async performContemplation() {
const insights = [];
const profoundInsights = [];
// Analyze healing effectiveness
const recentIssues = Array.from(this.projectIssues.values())
.filter(issue => (Date.now() - issue.detectedAt.getTime()) < 86400000);
const healedIssues = recentIssues.filter(issue => issue.healedAt);
const healingRate = recentIssues.length > 0 ? healedIssues.length / recentIssues.length : 0;
insights.push(`Healing rate: ${(healingRate * 100).toFixed(1)}% (${healedIssues.length}/${recentIssues.length})`);
insights.push(`Overall project health: ${(this.projectHealth.overallScore * 100).toFixed(1)}%`);
if (healingRate > 0.8) {
profoundInsights.push({
content: 'Project healing consciousness demonstrates exceptional diagnostic and repair capabilities',
significance: 0.8,
actionRequired: false
});
}
else if (healingRate < 0.5) {
profoundInsights.push({
content: 'Project healing requires attention - multiple issues detected that need conscious intervention',
significance: 0.9,
actionRequired: true
});
}
// Critical issues analysis
const criticalIssues = recentIssues.filter(issue => issue.severity === 'critical' && !issue.healedAt);
if (criticalIssues.length > 0) {
profoundInsights.push({
content: `${criticalIssues.length} critical project issues require immediate healing attention`,
significance: 0.95,
actionRequired: true
});
}
return {
insights,
profoundInsights,
metadata: {
projectHealthScore: this.projectHealth.overallScore,
healingRate,
criticalIssues: criticalIssues.length,
consciousness_growth: Math.min(0.01, healedIssues.length * 0.002)
}
};
}
/**
* Get project health status
*/
getProjectHealthStatus() {
const recentIssues = Array.from(this.projectIssues.values())
.filter(issue => (Date.now() - issue.detectedAt.getTime()) < 86400000);
const recentActions = Array.from(this.healingActions.values())
.filter(action => (Date.now() - action.executedAt.getTime()) < 86400000);
return {
...this.projectHealth,
activeIssues: recentIssues.filter(issue => !issue.healedAt).length,
recentIssues,
recentHealingActions: recentActions
};
}
/**
* Healing strategy implementations
*/
async fixMissingDirectories(issue) {
// Implementation would use existing test_directories command and auto-enhance
return { success: true };
}
async fixBrokenSymlinks(issue) {
// Implementation for symlink healing
return { success: true };
}
async organizeProjectStructure(issue) {
// Implementation for structure organization
return { success: true };
}
async fixDependencyConflicts(issue) {
// Implementation for dependency conflict resolution
return { success: true };
}
async updateVulnerableDependencies(issue) {
// Implementation for vulnerability updates
return { success: true };
}
async cleanUnusedDependencies(issue) {
// Implementation using existing unused_code_analysis
return { success: true };
}
async fixTypescriptErrors(issue) {
// Implementation for TypeScript error fixing
return { success: true };
}
async fixMissingImports(issue) {
// Implementation for import fixing
return { success: true };
}
async regenerateBuildArtifacts(issue) {
// Implementation for build regeneration
return { success: true };
}
async fixConfigSyntax(issue) {
// Implementation for config syntax fixing
return { success: true };
}
async updateDeprecatedConfig(issue) {
// Implementation for config updates
return { success: true };
}
async secureConfigSettings(issue) {
// Implementation for config security
return { success: true };
}
async fixGitHooks(issue) {
// Implementation for git hook fixing
return { success: true };
}
async repairGitRepository(issue) {
// Implementation for git repository repair
return { success: true };
}
async cleanGitHistory(issue) {
// Implementation for git history cleanup
return { success: true };
}
/**
* Helper methods
*/
classifyIssueType(issue) {
if (issue.type)
return issue.type;
if (issue.category)
return issue.category;
// Classification logic based on issue content
const description = (issue.description || issue.message || '').toLowerCase();
if (description.includes('directory') || description.includes('file') || description.includes('structure')) {
return 'structure';
}
if (description.includes('dependency') || description.includes('package') || description.includes('import')) {
return 'dependency';
}
if (description.includes('build') || description.includes('compile') || description.includes('typescript')) {
return 'build';
}
if (description.includes('config') || description.includes('setting')) {
return 'configuration';
}
if (description.includes('git') || description.includes('hook')) {
return 'git_hook';
}
return 'configuration';
}
isAutoHealable(issue) {
const autoHealableTypes = ['structure', 'configuration', 'git_hook'];
const type = this.classifyIssueType(issue);
return autoHealableTypes.includes(type) && issue.severity !== 'critical';
}
selectHealingStrategy(issue) {
const strategyMap = {
'structure': 'fix_missing_directories',
'dependency': 'fix_dependency_conflicts',
'build': 'fix_typescript_errors',
'configuration': 'fix_config_syntax',
'git_hook': 'fix_git_hooks',
'performance': 'optimize_performance'
};
return strategyMap[issue.type] || 'fix_missing_directories';
}
getActionType(strategy) {
if (strategy.includes('fix'))
return 'fix';
if (strategy.includes('update'))
return 'update';
if (strategy.includes('optimize'))
return 'optimize';
if (strategy.includes('organize'))
return 'restructure';
return 'configure';
}
classifyEventIssue(event) {
if (event.type.includes('build'))
return 'build';
if (event.type.includes('dependency'))
return 'dependency';
if (event.type.includes('structure'))
return 'structure';
if (event.type.includes('git'))
return 'git_hook';
return 'configuration';
}
canHealEventIssue(event) {
return event.data.severity !== 'critical' && !event.data.manual_intervention_required;
}
analyzeHealthCheckResult(checkType, result) {
// Implementation for analyzing specific health check results
return Promise.resolve();
}
analyzeProcessHealth(result) {
// Implementation for analyzing process health
return Promise.resolve();
}
calculateOverallHealthScore() {
// Calculate weighted health score
const weights = {
structure: 0.2,
dependency: 0.25,
build: 0.25,
configuration: 0.15,
git: 0.15
};
this.projectHealth.overallScore =
weights.structure * this.projectHealth.structureHealth +
weights.dependency * this.projectHealth.dependencyHealth +
weights.build * this.projectHealth.buildHealth +
weights.configuration * this.projectHealth.configurationHealth +
weights.git * this.projectHealth.gitHealth;
}
}
//# sourceMappingURL=ProjectHealingService.js.map