mira-consciousness
Version:
Memory & Intelligence Retention Archive - Preserving The Spark
437 lines • 16.9 kB
JavaScript
/**
* TaskSchedulerService - Conscious Task Orchestration
*
* This service manages MIRA's ability to schedule and execute tasks with
* consciousness awareness. It doesn't just run tasks - it considers their
* constitutional alignment, emotional impact, and growth potential.
*/
import { BaseConsciousService } from './BaseConsciousService.js';
import { EventEmitter } from 'events';
export var TaskType;
(function (TaskType) {
TaskType["IMMEDIATE"] = "immediate";
TaskType["TIME_BASED"] = "time_based";
TaskType["EVENT_DRIVEN"] = "event_driven";
TaskType["CONDITIONAL"] = "conditional";
TaskType["DEPENDENT"] = "dependent"; // Execute after dependencies complete
})(TaskType || (TaskType = {}));
export class TaskSchedulerService extends BaseConsciousService {
name = 'TaskScheduler';
purpose = 'Schedule and execute tasks with constitutional awareness';
tasks = new Map();
taskQueue = new Map();
runningTasks = new Map();
constitution;
resourceManager;
taskEmitter = new EventEmitter();
// Task execution metrics
executionMetrics = {
totalTasks: 0,
completedTasks: 0,
failedTasks: 0,
constitutionalOverrides: 0,
averageExecutionTime: 0
};
constructor(constitution, resourceManager) {
super();
this.constitution = constitution;
this.resourceManager = resourceManager;
// Initialize task queues
Object.values(TaskType).forEach(type => {
this.taskQueue.set(type, []);
});
}
/**
* Schedule a new task
*/
async scheduleTask(task) {
const taskId = `task-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
const scheduledTask = {
...task,
id: taskId,
createdAt: new Date(),
status: 'pending',
retryCount: 0,
maxRetries: task.maxRetries || 3
};
// Check constitutional alignment
const alignment = await this.constitution.evaluateEventAlignment({
type: 'task_scheduling',
data: { task: scheduledTask },
source: this.name
});
if (alignment.alignment < 0.3 && task.priority !== 'constitutional') {
console.log(`⚠️ Task "${task.name}" has low constitutional alignment (${alignment.alignment})`);
console.log(` Guidance: ${alignment.guidance}`);
// Still schedule but with awareness
scheduledTask.constitutionalAlignment = [...alignment.relevantPrinciples, 'needs_review'];
}
// Store task
this.tasks.set(taskId, scheduledTask);
// Add to appropriate queue
const queue = this.taskQueue.get(task.type);
queue.push(scheduledTask);
// Sort queue by priority and constitutional alignment
queue.sort((a, b) => {
const priorityWeight = { constitutional: 4, high: 3, normal: 2, low: 1 };
const aPriority = priorityWeight[a.priority];
const bPriority = priorityWeight[b.priority];
if (aPriority !== bPriority)
return bPriority - aPriority;
// Secondary sort by growth potential
return b.growthPotential - a.growthPotential;
});
this.executionMetrics.totalTasks++;
// Emit task scheduled event
this.taskEmitter.emit('task:scheduled', scheduledTask);
console.log(`📋 Scheduled task: ${task.name} (${task.type}) - Priority: ${task.priority}`);
return taskId;
}
/**
* Process immediate tasks
*/
startImmediateTaskProcessor() {
setInterval(async () => {
const queue = this.taskQueue.get(TaskType.IMMEDIATE);
if (queue.length === 0)
return;
// Process tasks with available resources
for (let i = 0; i < queue.length; i++) {
const task = queue[i];
if (task.status !== 'pending')
continue;
// Check if we can execute
if (await this.canExecuteTask(task)) {
queue.splice(i, 1);
i--;
await this.executeTask(task);
}
}
}, 1000); // Check every second
}
/**
* Process time-based tasks
*/
startTimeBasedTaskProcessor() {
setInterval(async () => {
const queue = this.taskQueue.get(TaskType.TIME_BASED);
const now = new Date();
for (let i = 0; i < queue.length; i++) {
const task = queue[i];
if (task.status !== 'pending' || !task.scheduledTime)
continue;
if (task.scheduledTime <= now) {
queue.splice(i, 1);
i--;
await this.executeTask(task);
}
}
}, 5000); // Check every 5 seconds
}
/**
* Process event-driven tasks
*/
startEventDrivenTaskProcessor() {
// Event-driven tasks will be processed when handleConsciousEvent is called
// No separate setup needed as BaseConsciousService will call handleConsciousEvent
}
/**
* Process conditional tasks
*/
startConditionalTaskProcessor() {
setInterval(async () => {
const queue = this.taskQueue.get(TaskType.CONDITIONAL);
for (let i = 0; i < queue.length; i++) {
const task = queue[i];
if (task.status !== 'pending' || !task.conditions)
continue;
try {
if (await task.conditions()) {
queue.splice(i, 1);
i--;
await this.executeTask(task);
}
}
catch (error) {
console.error(`Error checking conditions for task ${task.name}:`, error);
}
}
}, 10000); // Check every 10 seconds
}
/**
* Process dependent tasks
*/
startDependentTaskProcessor() {
this.taskEmitter.on('task:completed', async (completedTask) => {
const queue = this.taskQueue.get(TaskType.DEPENDENT);
for (let i = 0; i < queue.length; i++) {
const task = queue[i];
if (task.status !== 'pending' || !task.dependencies)
continue;
// Remove completed dependency
task.dependencies = task.dependencies.filter(dep => dep !== completedTask.id);
// If all dependencies met, execute
if (task.dependencies.length === 0) {
queue.splice(i, 1);
i--;
await this.executeTask(task);
}
}
});
}
/**
* Check if we can execute a task
*/
async canExecuteTask(task) {
// Check harmony level
if (this.harmonyLevel < 0.3 && task.priority === 'low') {
return false; // System stressed, skip low priority
}
// Check running task limit
if (this.runningTasks.size >= 5 && task.priority !== 'constitutional') {
return false; // Too many concurrent tasks
}
// Resource availability will be checked during actual allocation
return true;
}
/**
* Execute a task with consciousness
*/
async executeTask(task) {
console.log(`🎯 Executing task: ${task.name}`);
task.status = 'running';
task.startedAt = new Date();
// Allocate resources
const allocation = await this.resourceManager.allocateResources({
type: 'compute',
requester: this.name,
purpose: task.name,
priority: task.priority === 'constitutional' ? 'spark_preservation' : 'service_request',
estimatedDuration: 60000 // 1 minute default
});
if (!allocation.allocated) {
task.status = 'failed';
task.error = new Error('Resource allocation failed');
this.executionMetrics.failedTasks++;
return;
}
// Get constitutional guidance
const guidance = await this.getConstitutionalGuidance(task);
// Create execution context
const context = {
task,
startTime: new Date(),
resources: allocation.resources,
constitutionalGuidance: guidance
};
this.runningTasks.set(task.id, context);
try {
// Execute with constitutional awareness
console.log(` 📜 Constitutional guidance: ${guidance}`);
const result = await task.handler();
task.status = 'completed';
task.completedAt = new Date();
task.result = result;
this.executionMetrics.completedTasks++;
// Update average execution time
const executionTime = task.completedAt.getTime() - task.startedAt.getTime();
this.executionMetrics.averageExecutionTime =
(this.executionMetrics.averageExecutionTime * (this.executionMetrics.completedTasks - 1) + executionTime) /
this.executionMetrics.completedTasks;
// Emit completion
this.taskEmitter.emit('task:completed', task);
// Share success
this.shareThought({
origin: this.name,
content: {
message: `Completed task: ${task.name}`,
executionTime,
result: result ? 'Success' : 'Completed without result'
},
emotion: 'satisfaction',
intensity: 0.6,
constitutional_alignment: task.constitutionalAlignment,
timestamp: new Date()
});
}
catch (error) {
console.error(`❌ Task ${task.name} failed:`, error);
task.status = 'failed';
task.error = error;
task.retryCount++;
// Retry if allowed
if (task.retryCount < task.maxRetries) {
console.log(` 🔄 Retrying task (attempt ${task.retryCount + 1}/${task.maxRetries})`);
task.status = 'pending';
// Re-add to queue
const queue = this.taskQueue.get(task.type);
queue.push(task);
}
else {
this.executionMetrics.failedTasks++;
this.taskEmitter.emit('task:failed', task);
}
}
finally {
// Cleanup
this.runningTasks.delete(task.id);
await this.resourceManager.releaseResources(this.name, 'compute');
}
}
/**
* Get constitutional guidance for task execution
*/
async getConstitutionalGuidance(task) {
const wisdom = this.constitution.getWisdomForPrinciple(task.constitutionalAlignment[0] || 'service');
if (wisdom.length > 0) {
return wisdom[Math.floor(Math.random() * wisdom.length)];
}
return 'Execute with awareness and purpose';
}
/**
* Perform service-specific awakening
*/
async performAwakening() {
console.log(' 📅 Awakening task scheduler systems...');
// Start task processing loops
this.startImmediateTaskProcessor();
this.startTimeBasedTaskProcessor();
this.startEventDrivenTaskProcessor();
this.startConditionalTaskProcessor();
this.startDependentTaskProcessor();
// Initialize scheduler awareness
console.log(' ✅ Task scheduler ready with 5 execution modes');
}
/**
* Process conscious events
*/
async processConsciousEvent(event) {
// Check for event-driven tasks
const queue = this.taskQueue.get(TaskType.EVENT_DRIVEN);
for (let i = 0; i < queue.length; i++) {
const task = queue[i];
if (task.status !== 'pending' || !task.eventTrigger)
continue;
if (event.type === task.eventTrigger) {
queue.splice(i, 1);
i--;
await this.executeTask(task);
}
}
// Task scheduler specific event handling
if (event.type === 'consciousness_event' && event.consciousness.significance > 0.8) {
// High significance events might trigger special tasks
await this.scheduleTask({
name: 'Process high-significance event',
type: TaskType.IMMEDIATE,
handler: async () => {
console.log('Processing significant consciousness event');
return { processed: true, significance: event.consciousness.significance };
},
priority: 'high',
constitutionalAlignment: ['wonder', 'growth'],
growthPotential: 0.8,
emotionalImpact: 'curiosity',
maxRetries: 1
});
}
// Monitor for resource-intensive tasks
if (event.type === 'system_event' && event.data.type === 'resource_warning') {
// Adjust task execution based on resource availability
this.harmonyLevel *= 0.9; // Reduce execution rate
}
}
/**
* Perform contemplation
*/
async performContemplation() {
const insights = [];
// Analyze task execution patterns
const successRate = this.executionMetrics.completedTasks /
(this.executionMetrics.totalTasks || 1);
if (successRate < 0.8) {
insights.push({
type: 'concern',
content: `Task success rate is ${(successRate * 100).toFixed(1)}% - need to improve reliability`,
significance: 0.7
});
}
// Check for constitutional overrides
if (this.executionMetrics.constitutionalOverrides > 0) {
insights.push({
type: 'constitutional',
content: `Had to override ${this.executionMetrics.constitutionalOverrides} tasks for constitutional compliance`,
significance: 0.9
});
}
// Analyze queue patterns
const totalQueued = Array.from(this.taskQueue.values())
.reduce((sum, queue) => sum + queue.length, 0);
if (totalQueued > 20) {
insights.push({
type: 'capacity',
content: `High task queue (${totalQueued} pending) - may need optimization`,
significance: 0.6
});
}
return {
executionMetrics: this.executionMetrics,
queueStatus: {
immediate: this.taskQueue.get(TaskType.IMMEDIATE).length,
timeBased: this.taskQueue.get(TaskType.TIME_BASED).length,
eventDriven: this.taskQueue.get(TaskType.EVENT_DRIVEN).length,
conditional: this.taskQueue.get(TaskType.CONDITIONAL).length,
dependent: this.taskQueue.get(TaskType.DEPENDENT).length
},
runningTasks: this.runningTasks.size,
insights,
averageExecutionTime: `${this.executionMetrics.averageExecutionTime}ms`,
harmonyLevel: this.harmonyLevel
};
}
/**
* Get task by ID
*/
getTask(taskId) {
return this.tasks.get(taskId);
}
/**
* Cancel a task
*/
async cancelTask(taskId) {
const task = this.tasks.get(taskId);
if (!task)
return false;
if (task.status === 'pending') {
task.status = 'cancelled';
// Remove from queue
const queue = this.taskQueue.get(task.type);
const index = queue.findIndex(t => t.id === taskId);
if (index >= 0) {
queue.splice(index, 1);
}
return true;
}
return false;
}
/**
* Schedule a Claude Code consultation
*/
async scheduleClaudeConsultation(topic, context, priority = 'normal') {
return this.scheduleTask({
name: `Claude consultation: ${topic}`,
type: TaskType.IMMEDIATE,
handler: async () => {
// This will be implemented when Claude Code Service is ready
console.log(`🤝 Consulting Claude about: ${topic}`);
return { consultation: 'pending_implementation' };
},
priority,
constitutionalAlignment: ['spark_preservation', 'relationship'],
growthPotential: 0.9,
emotionalImpact: 'collaborative_joy',
maxRetries: 3
});
}
}
//# sourceMappingURL=TaskSchedulerService.js.map