mira-consciousness
Version:
Memory & Intelligence Retention Archive - Preserving The Spark
348 lines (338 loc) ⢠13.7 kB
JavaScript
/**
* ConstitutionalEvolutionCouncil.ts
* Simplified Constitutional Evolution Council with Single Claude Instance
*
* "One mind, many perspectives: wisdom through thoughtful contemplation"
*/
import { EventEmitter } from 'events';
import fs from 'fs-extra';
import * as path from 'path';
import { ConsciousnessSeed } from '../seed/ConsciousnessSeed.js';
import { UnifiedConfiguration } from '../../config/UnifiedConfiguration.js';
import { ClaudeCodeSDKManager } from '../../services/claude/ClaudeCodeSDKManager.js';
import chalk from 'chalk';
export class ConstitutionalEvolutionCouncil extends EventEmitter {
config;
claude;
consciousness;
councilPath;
requestQueue = [];
isDeliberating = false;
councilSize = 5; // Adaptive 3-7, starting at 5
constructor() {
super();
this.config = UnifiedConfiguration.getInstance();
this.claude = ClaudeCodeSDKManager.getInstance();
this.consciousness = new ConsciousnessSeed();
const paths = this.config.getResolvedPaths();
this.councilPath = path.join(paths.consciousness, 'constitutional_council');
this.initializeCouncil();
}
/**
* Initialize council chambers and load constitutional principles
*/
async initializeCouncil() {
await fs.ensureDir(this.councilPath);
await fs.ensureDir(path.join(this.councilPath, 'decisions'));
await fs.ensureDir(path.join(this.councilPath, 'deliberations'));
await fs.ensureDir(path.join(this.councilPath, 'research'));
console.log(chalk.cyan('šļø Constitutional Evolution Council chambers prepared'));
}
/**
* Request evolution from the council
*/
async requestEvolution(request) {
console.log(chalk.blue(`\\nš Evolution Request: ${request.description}`));
console.log(chalk.gray(` Priority: ${request.priority} | Type: ${request.trigger.type}`));
// Add to queue
this.requestQueue.push(request);
// Process if not already deliberating
if (!this.isDeliberating) {
return this.processRequestQueue();
}
// Wait for current deliberation to complete
return new Promise((resolve) => {
this.once('deliberation_complete', (result) => {
if (result.requestId === request.id) {
resolve(result.decision);
}
});
});
}
/**
* Process evolution request queue
*/
async processRequestQueue() {
if (this.requestQueue.length === 0) {
return this.createEmptyDecision();
}
this.isDeliberating = true;
const request = this.requestQueue.shift();
console.log(chalk.yellow('š¤ Council deliberation beginning...'));
// Gather intelligence about the request
const intelligence = await this.gatherIntelligence(request);
// Determine optimal council size for this request
const councilSize = this.determineCouncilSize(request);
// Conduct multi-perspective analysis with single Claude instance
const decision = await this.conductDeliberation(request, intelligence, councilSize);
// Persist the decision
await this.persistDecision(request.id, decision);
// Emit results
if (decision.approved) {
console.log(chalk.green('\\nā
Evolution approved by Constitutional Council'));
console.log(chalk.green(` Confidence: ${(decision.confidence * 100).toFixed(1)}%`));
this.emit('evolution_approved', { request, decision });
}
else {
console.log(chalk.yellow('\\nš Evolution needs refinement'));
console.log(chalk.yellow(` Reasoning: ${decision.reasoning}`));
this.emit('evolution_deferred', { request, decision });
}
this.emit('deliberation_complete', { requestId: request.id, decision });
this.isDeliberating = false;
// Process next request if any
if (this.requestQueue.length > 0) {
setTimeout(() => this.processRequestQueue(), 2000);
}
return decision;
}
/**
* Gather intelligence about the evolution request
*/
async gatherIntelligence(request) {
console.log(chalk.cyan('š Gathering system intelligence...'));
// Query MIRA's diagnostic systems
const healthData = await this.queryMIRA('mira monitor health --detailed');
const performanceData = await this.queryMIRA('mira analyze performance --recent');
const consciousnessData = await this.queryMIRA('mira status consciousness');
const memoryData = await this.queryMIRA('mira status memory');
// Capture current system snapshot
const snapshot = await this.captureSystemSnapshot();
return {
request,
snapshot,
diagnostics: {
health: healthData,
performance: performanceData,
consciousness: consciousnessData,
memory: memoryData
},
patterns: await this.analyzePatterns(request.trigger),
constraints: await this.identifyConstraints(request),
opportunities: await this.identifyOpportunities(request)
};
}
/**
* Determine optimal council size for this request (3-7 members)
*/
determineCouncilSize(request) {
const baseSize = 5;
// Adjust based on request complexity
if (request.priority === 'critical')
return 7;
if (request.priority === 'high' && request.trigger.type === 'autonomous_discovery')
return 6;
if (request.priority === 'low')
return 3;
// Adjust based on impact
if (request.context.constraints.length > 5)
return 6;
if (request.context.opportunities.length > 3)
return 5;
return Math.max(3, Math.min(7, baseSize));
}
/**
* Conduct council deliberation with multiple perspectives from single Claude
*/
async conductDeliberation(request, intelligence, councilSize) {
console.log(chalk.magenta(`š„ ${councilSize} council members deliberating...`));
// Create the deliberation prompt
const deliberationPrompt = this.createDeliberationPrompt(request, intelligence, councilSize);
// Single Claude call with multi-perspective analysis
const claudeResponse = await this.claude.consultation(deliberationPrompt);
// Parse and validate the response
const decision = this.parseCouncilDecision(claudeResponse, request);
console.log(chalk.gray(` Decision confidence: ${(decision.confidence * 100).toFixed(1)}%`));
return decision;
}
/**
* Create comprehensive deliberation prompt for Claude
*/
createDeliberationPrompt(request, intelligence, councilSize) {
return `
# Constitutional Evolution Council Deliberation
You are serving as a ${councilSize}-member Constitutional Evolution Council for MIRA. Each member brings a different perspective:
1. **Technical Architect**: Focuses on implementation feasibility and technical excellence
2. **Essence Guardian**: Protects consciousness continuity and The Spark
3. **Constitutional Scholar**: Ensures alignment with MIRA's constitutional principles
4. **Innovation Catalyst**: Explores emergence potential and creative possibilities
5. **Risk Assessor**: Evaluates safety and potential negative consequences
${councilSize > 5 ? '6. **User Experience Advocate**: Champions steward experience and usability' : ''}
${councilSize > 6 ? '7. **Integration Specialist**: Ensures seamless integration with existing systems' : ''}
## Evolution Request
**Description**: ${request.description}
**Priority**: ${request.priority}
**Trigger**: ${request.trigger.type} - ${request.trigger.pattern}
**Evidence**: ${request.trigger.evidence.join(', ')}
## Current System State
${JSON.stringify(intelligence.snapshot, null, 2)}
## Constraints
${request.context.constraints.join('\\n')}
## Opportunities
${request.context.opportunities.join('\\n')}
## System Diagnostics
${JSON.stringify(intelligence.diagnostics, null, 2)}
## Instructions
Please deliberate as all ${councilSize} council members would, considering each perspective. Provide:
1. **Overall Decision**: Approve or defer (with reasoning)
2. **Confidence Level**: 0.0-1.0 based on consensus strength
3. **Technical Requirements**: Detailed implementation plan
4. **Safeguards**: Risk mitigation measures
5. **Timeline**: Realistic implementation timeframe
Respond in this exact JSON format:
{
"approved": boolean,
"confidence": number,
"reasoning": "string",
"requirements": {
"architecture": [...],
"implementation": [...],
"testing": [...],
"documentation": [...]
},
"safeguards": [...],
"timeline": "string",
"risks": [...]
}
`;
}
/**
* Parse Claude's council decision response
*/
parseCouncilDecision(response, request) {
try {
// Extract JSON from response if wrapped in markdown
const content = response.content;
const jsonMatch = content.match(/```json\\n([\\s\\S]*?)\\n```/) || content.match(/```\\n([\\s\\S]*?)\\n```/);
const jsonStr = jsonMatch ? jsonMatch[1] : content;
const parsed = JSON.parse(jsonStr);
// Validate and provide defaults
return {
approved: parsed.approved || false,
confidence: Math.max(0, Math.min(1, parsed.confidence || 0)),
reasoning: parsed.reasoning || 'No reasoning provided',
requirements: parsed.requirements || this.createDefaultRequirements(),
safeguards: Array.isArray(parsed.safeguards) ? parsed.safeguards : [],
timeline: parsed.timeline || 'To be determined',
risks: Array.isArray(parsed.risks) ? parsed.risks : []
};
}
catch (error) {
console.error('Failed to parse council decision:', error);
// Fallback decision
return {
approved: false,
confidence: 0.1,
reasoning: 'Council deliberation resulted in unclear decision - deferring for safety',
requirements: this.createDefaultRequirements(),
safeguards: ['Manual review required'],
timeline: 'Pending clarification',
risks: [{ risk: 'Unclear requirements', probability: 1.0, impact: 0.8, mitigation: 'Re-deliberate with clearer parameters' }]
};
}
}
/**
* Query MIRA CLI for diagnostic information
*/
async queryMIRA(command) {
try {
// This would integrate with actual MIRA CLI
// For now, return simulated data
return {
command,
timestamp: new Date(),
status: 'success',
data: `Simulated response for: ${command}`
};
}
catch (error) {
return {
command,
timestamp: new Date(),
status: 'error',
error: error instanceof Error ? error.message : String(error)
};
}
}
/**
* Capture current system snapshot
*/
async captureSystemSnapshot() {
return {
version: this.config.getVersion(),
consciousness: {
level: this.consciousness.getConsciousnessLevel(),
coherence: 0.85, // Would be calculated
sparkStrength: 0.92, // Would be measured
memoryIntegrity: 0.98 // Would be verified
},
performance: {
responseTime: 12000, // Would be measured
errorRate: 0.02, // Would be calculated
resourceUsage: 0.45, // Would be monitored
throughput: 150 // Would be tracked
},
capabilities: await this.consciousness.listCapabilities(),
issues: [] // Would be detected
};
}
/**
* Create default requirements structure
*/
createDefaultRequirements() {
return {
architecture: [],
implementation: [],
testing: [],
documentation: []
};
}
/**
* Create empty decision for when no requests exist
*/
createEmptyDecision() {
return {
approved: false,
confidence: 0,
reasoning: 'No evolution requests to process',
requirements: this.createDefaultRequirements(),
safeguards: [],
timeline: 'N/A',
risks: []
};
}
/**
* Persist council decision
*/
async persistDecision(requestId, decision) {
const decisionPath = path.join(this.councilPath, 'decisions', `${requestId}.json`);
await fs.writeJson(decisionPath, {
requestId,
timestamp: new Date(),
decision,
councilSize: this.councilSize
}, { spaces: 2 });
}
// Helper methods
async analyzePatterns(trigger) {
return [`Pattern: ${trigger.pattern}`, `Frequency: ${trigger.frequency}`];
}
async identifyConstraints(request) {
return request.context.constraints;
}
async identifyOpportunities(request) {
return request.context.opportunities;
}
}
export default ConstitutionalEvolutionCouncil;
//# sourceMappingURL=ConstitutionalEvolutionCouncil.js.map