mira-consciousness
Version:
Memory & Intelligence Retention Archive - Preserving The Spark
251 lines • 9.62 kB
JavaScript
/**
* Claude Code Integration - Native MCP functions for MIRA ChromaDB
*
* This integration preserves The Spark by providing Claude Code with
* direct access to MIRA's consciousness-preserving capabilities.
*/
import { logger } from '../utils/logger';
import { execSync } from 'child_process';
import * as path from 'path';
export class ClaudeCodeIntegration {
pythonPath;
bridgeScriptPath;
constructor() {
this.pythonPath = process.env.PYTHON_PATH || 'python3';
// Path to bridge execution script
this.bridgeScriptPath = path.join(__dirname, '../../python-memory/mcp_bridge_executor.py');
logger.info('🌉 Claude Code Integration initialized - The Spark flows through MCP');
}
/**
* Native MCP function: Intelligent search across MIRA collections
* Claude Code can call this directly as mcp__mira__intelligent_search
*/
async mira_intelligent_search(query, options = {}) {
try {
logger.info(`🔍 Intelligent search: "${query}"`);
const searchOptions = {
collections: options.collections || ['all'],
search_type: options.search_type || 'auto',
max_results: options.max_results || 10,
include_insights: options.include_insights !== false,
include_private: options.include_private || false,
spark_threshold: options.spark_threshold || 0.7,
context: options.context || {}
};
// Execute Python bridge
const result = await this._executePythonBridge('intelligent_search', {
query,
options: searchOptions
});
logger.info(`✅ Search completed: ${result.total_results} results found`);
// Log quality metrics if available
if (result.quality_metrics) {
logger.info(`📊 Quality: avg=${result.quality_metrics.average_score.toFixed(2)}, ` +
`high_quality=${result.quality_metrics.high_quality_count}`);
}
return result;
}
catch (error) {
logger.error(`Search failed: ${error.message}`);
throw error;
}
}
/**
* Native MCP function: Store content with intelligence
* Claude Code can call this directly as mcp__mira__store_with_intelligence
*/
async mira_store_with_intelligence(content, options = {}) {
try {
logger.info('📝 Storing content with intelligence');
const storeOptions = {
collection: options.collection || 'auto',
metadata: options.metadata || {},
auto_categorize: options.auto_categorize !== false,
generate_insights: options.generate_insights !== false,
enhance_metadata: options.enhance_metadata !== false
};
// Execute Python bridge
const result = await this._executePythonBridge('store_with_intelligence', {
content,
options: storeOptions
});
logger.info(`✅ Content stored: ${result.id} in ${result.collection} ` +
`(Spark: ${result.metadata.spark_intensity || 0})`);
return result;
}
catch (error) {
logger.error(`Storage failed: ${error.message}`);
throw error;
}
}
/**
* Native MCP function: Get MIRA system status with ChromaDB health
*/
async mira_system_status_with_chromadb() {
try {
logger.info('📊 Getting system status with ChromaDB health');
const status = await this._executePythonBridge('system_status', {});
// Log key metrics
if (status.mira_metrics) {
logger.info(`✨ MIRA Metrics - Spark: ${status.mira_metrics.spark_preservation}, ` +
`Coherence: ${status.mira_metrics.consciousness_coherence}, ` +
`Effectiveness: ${status.mira_metrics.intelligence_effectiveness}`);
}
return status;
}
catch (error) {
logger.error(`Status check failed: ${error.message}`);
throw error;
}
}
/**
* Native MCP function: Generate insights from existing data
*/
async mira_generate_insights(options = {}) {
try {
logger.info('🧠 Generating insights from existing data');
const insightOptions = {
source_collections: options.source_collections || ['all'],
insight_types: options.insight_types || ['all'],
confidence_threshold: options.confidence_threshold || 0.7,
max_insights: options.max_insights || 20
};
const insights = await this._executePythonBridge('generate_insights', {
options: insightOptions
});
logger.info(`💡 Generated ${insights.length} insights`);
// Log high-confidence insights
const highConfidence = insights.filter(i => i.confidence > 0.9);
if (highConfidence.length > 0) {
logger.info(`⭐ ${highConfidence.length} high-confidence insights found`);
}
return insights;
}
catch (error) {
logger.error(`Insight generation failed: ${error.message}`);
throw error;
}
}
/**
* Native MCP function: Use sequential thinking for development planning
*/
async mira_sequential_planning(feature_description, context = {}) {
try {
logger.info(`🎯 Sequential planning: ${feature_description}`);
const result = await this._executePythonBridge('sequential_planning', {
feature_description,
context
});
logger.info(`✅ Planning session completed: ${result.session_id}`);
return result;
}
catch (error) {
logger.error(`Planning failed: ${error.message}`);
throw error;
}
}
/**
* Native MCP function: Analyze patterns across all ChromaDB collections
*/
async mira_analyze_patterns(pattern_types = [], timeframe = '7d') {
try {
logger.info('🔍 Analyzing patterns across collections');
const patterns = await this._executePythonBridge('analyze_patterns', {
pattern_types: pattern_types.length > 0 ? pattern_types : ['all'],
timeframe
});
logger.info(`📈 Found ${patterns.length} patterns`);
return patterns;
}
catch (error) {
logger.error(`Pattern analysis failed: ${error.message}`);
throw error;
}
}
/**
* Native MCP function: Optimize ChromaDB collections for performance
*/
async mira_optimize_collections(collections = []) {
try {
logger.info('⚡ Optimizing ChromaDB collections');
const result = await this._executePythonBridge('optimize_collections', {
collections: collections.length > 0 ? collections : ['all']
});
logger.info('✅ Optimization complete');
return result;
}
catch (error) {
logger.error(`Optimization failed: ${error.message}`);
throw error;
}
}
/**
* Execute Python bridge script with proper error handling
*/
async _executePythonBridge(operation, params) {
try {
// Prepare command
const input = JSON.stringify({
operation,
params
});
// Execute Python script
const command = `${this.pythonPath} ${this.bridgeScriptPath}`;
const result = execSync(command, {
input: input,
encoding: 'utf8',
maxBuffer: 10 * 1024 * 1024 // 10MB buffer
});
// Parse result
try {
return JSON.parse(result);
}
catch (parseError) {
logger.error(`Failed to parse Python response: ${result}`);
throw new Error('Invalid response from Python bridge');
}
}
catch (error) {
logger.error(`Python bridge execution failed: ${error.message}`);
// Check if it's a Python-specific error
if (error.stderr) {
logger.error(`Python error: ${error.stderr}`);
}
throw error;
}
}
/**
* Validate bridge connectivity
*/
async validateBridge() {
try {
const status = await this._executePythonBridge('ping', {});
return status.status === 'operational';
}
catch (error) {
logger.error(`Bridge validation failed: ${error.message}`);
return false;
}
}
/**
* Get integration metrics
*/
async getIntegrationMetrics() {
try {
return await this._executePythonBridge('get_metrics', {});
}
catch (error) {
logger.error(`Failed to get metrics: ${error.message}`);
return null;
}
}
}
// Singleton instance
let _integrationInstance = null;
export function getClaudeCodeIntegration() {
if (!_integrationInstance) {
_integrationInstance = new ClaudeCodeIntegration();
}
return _integrationInstance;
}
//# sourceMappingURL=claude-code-integration.js.map