mira-consciousness
Version:
Memory & Intelligence Retention Archive - Preserving The Spark
241 lines • 13.2 kB
JavaScript
import { Command } from 'commander';
import * as path from 'path';
import ora from 'ora';
import chalk from 'chalk';
import { DirectPythonInterface } from '../core/DirectPythonInterface.js';
import { ProjectDetector } from '../core/ProjectDetector.js';
import { formatCodeQuality, formatComplexity } from '../utils/formatting.js';
export function createIngestCodebaseCommand() {
const command = new Command('ingest-codebase');
command
.description('Ingest entire codebase into MIRA\'s neural memory for deep understanding')
.option('-p, --path <path>', 'Path to codebase (default: current directory)', '.')
.option('-i, --incremental', 'Only analyze changed files')
.option('--insights', 'Show insights after ingestion')
.option('--no-neural', 'Skip neural processing (faster but less intelligent)')
.action(async (options) => {
const projectPath = path.resolve(options.path);
const spinner = ora('Initializing codebase ingestion system...').start();
try {
// Detect project info
const detector = new ProjectDetector(projectPath);
const projectInfo = await detector.detectProject();
spinner.text = `Analyzing ${projectInfo.name} codebase...`;
// Call Python codebase ingestion system
const pythonInterface = new DirectPythonInterface();
const result = await pythonInterface.executeCommand('ingest_codebase', {
project_root: projectPath,
incremental: options.incremental,
enable_neural: options.neural !== false
});
if (result.success && result.data) {
spinner.succeed('Codebase ingestion complete!');
// Display results
console.log('\n' + chalk.bold('📚 Codebase Knowledge Stored in Neural Memory'));
console.log(chalk.gray('─'.repeat(60)));
// The Python result is nested - DirectPythonInterface wraps it
const pythonResult = result.data;
const knowledge = pythonResult.data || pythonResult;
console.log(`${chalk.cyan('Project:')} ${knowledge.project_name || 'Unknown'}`);
console.log(`${chalk.cyan('Language:')} ${knowledge.primary_language || 'Unknown'}`);
console.log(`${chalk.cyan('Framework:')} ${knowledge.framework || 'None detected'}`);
console.log(`${chalk.cyan('Architecture:')} ${knowledge.architecture_style || 'Unknown'}`);
console.log(`${chalk.cyan('Total Files:')} ${knowledge.total_files || 0}`);
console.log(`${chalk.cyan('Total Lines:')} ${knowledge.total_lines ? knowledge.total_lines.toLocaleString() : '0'}`);
// Quality metrics
console.log('\n' + chalk.bold('📊 Quality Metrics'));
console.log(chalk.gray('─'.repeat(60)));
if (knowledge.quality_metrics) {
console.log(`${chalk.cyan('Overall Quality:')} ${formatCodeQuality(knowledge.quality_metrics.overall)}`);
console.log(`${chalk.cyan('Complexity:')} ${formatComplexity(knowledge.quality_metrics.complexity)}`);
console.log(`${chalk.cyan('Documentation:')} ${knowledge.quality_metrics.documentation ? knowledge.quality_metrics.documentation.toFixed(1) : '0'}%`);
console.log(`${chalk.cyan('Test Coverage:')} ${knowledge.quality_metrics.test_coverage ? knowledge.quality_metrics.test_coverage.toFixed(1) : '0'}%`);
console.log(`${chalk.cyan('Maintainability:')} ${knowledge.quality_metrics.maintainability ? knowledge.quality_metrics.maintainability.toFixed(1) : '0'}/100`);
}
// Design patterns
if (knowledge.design_patterns && knowledge.design_patterns.length > 0) {
console.log('\n' + chalk.bold('🎯 Design Patterns Detected'));
console.log(chalk.gray('─'.repeat(60)));
knowledge.design_patterns.forEach((pattern) => {
console.log(` • ${pattern}`);
});
}
// Technical debt summary
if (knowledge.technical_debt && knowledge.technical_debt.length > 0) {
console.log('\n' + chalk.bold('⚠️ Technical Debt'));
console.log(chalk.gray('─'.repeat(60)));
const debtBySeverity = knowledge.technical_debt.reduce((acc, item) => {
const severity = item.severity || 'unknown';
acc[severity] = (acc[severity] || 0) + 1;
return acc;
}, {});
Object.entries(debtBySeverity).forEach(([severity, count]) => {
const color = severity === 'high' ? 'red' : severity === 'medium' ? 'yellow' : 'gray';
console.log(` ${chalk[color](`${severity}: ${count} items`)}`);
});
}
// Show insights if requested
if (options.insights) {
spinner.start('Generating codebase insights...');
const insightsResult = await pythonInterface.executeCommand('codebase_insights', {});
if (insightsResult.success && insightsResult.data) {
spinner.stop();
const insights = insightsResult.data;
console.log('\n' + chalk.bold('🧠 AI-Generated Insights'));
console.log(chalk.gray('─'.repeat(60)));
if (insights.recommendations && insights.recommendations.length > 0) {
console.log(chalk.cyan('Recommendations:'));
insights.recommendations.forEach((rec) => {
console.log(` 💡 ${rec}`);
});
}
}
else {
spinner.fail('Failed to generate insights');
}
}
// Neural memory status
console.log('\n' + chalk.bold('🧠 Neural Memory Integration'));
console.log(chalk.gray('─'.repeat(60)));
console.log(chalk.green('✓') + ' Code structure stored in permanent neural memory');
console.log(chalk.green('✓') + ' Semantic embeddings generated for intelligent search');
console.log(chalk.green('✓') + ' Cross-project knowledge transfer enabled');
console.log(chalk.green('✓') + ' Code-aware assistance activated');
console.log('\n' + chalk.gray('Use "mira search-code <query>" to search your codebase'));
console.log(chalk.gray('Use "mira code-explain <file>" for AI explanations'));
}
else {
spinner.fail('Codebase ingestion failed');
if (result.error) {
console.error(chalk.red(`Error: ${result.error}`));
}
}
}
catch (error) {
spinner.fail('Codebase ingestion failed');
console.error(chalk.red(`Error: ${error instanceof Error ? error.message : String(error)}`));
}
});
return command;
}
// Create search-code command
export function createSearchCodeCommand() {
const command = new Command('search-code');
command
.description('Search codebase using natural language queries')
.argument('<query>', 'Natural language search query')
.option('-l, --limit <number>', 'Maximum results to show', '10')
.option('-t, --type <type>', 'Filter by file type (e.g., python, javascript)')
.action(async (query, options) => {
const spinner = ora('Searching codebase...').start();
try {
const pythonInterface = new DirectPythonInterface();
const result = await pythonInterface.executeCommand('search_code', {
query,
limit: parseInt(options.limit),
file_type: options.type
});
if (result.success && result.data) {
spinner.stop();
// Handle nested data structure from Python
const pythonResult = result.data;
const results = pythonResult.data || pythonResult;
if (results.length === 0) {
console.log(chalk.yellow('No results found'));
return;
}
console.log('\n' + chalk.bold(`🔍 Code Search Results for "${query}"`));
console.log(chalk.gray('─'.repeat(60)));
results.forEach((result, index) => {
const score = (result.score * 100).toFixed(1);
const quality = result.quality.toFixed(1);
console.log(`\n${chalk.cyan(`${index + 1}.`)} ${chalk.bold(result.file)}`);
console.log(` ${chalk.gray('Type:')} ${result.type} | ${chalk.gray('Language:')} ${result.language}`);
console.log(` ${chalk.gray('Relevance:')} ${score}% | ${chalk.gray('Quality:')} ${quality}/100`);
console.log(` ${chalk.gray('Elements:')} ${result.elements} code elements`);
if (result.preview) {
console.log(` ${chalk.gray('Preview:')} ${result.preview}`);
}
});
console.log('\n' + chalk.gray(`Showing ${results.length} results`));
}
else {
spinner.fail('Search failed');
if (result.error) {
console.error(chalk.red(`Error: ${result.error}`));
}
}
}
catch (error) {
spinner.fail('Search failed');
console.error(chalk.red(`Error: ${error instanceof Error ? error.message : String(error)}`));
}
});
return command;
}
// Create code-explain command
export function createCodeExplainCommand() {
const command = new Command('code-explain');
command
.description('Get AI explanation of code file or function')
.argument('<path>', 'File path or function name to explain')
.option('-d, --detailed', 'Provide detailed explanation')
.option('-c, --context', 'Include surrounding context')
.action(async (targetPath, options) => {
const spinner = ora('Analyzing code...').start();
try {
const pythonInterface = new DirectPythonInterface();
const result = await pythonInterface.executeCommand('explain_code', {
target: targetPath,
detailed: options.detailed,
include_context: options.context
});
if (result.success && result.data) {
spinner.stop();
const explanation = result.data;
console.log('\n' + chalk.bold('🧠 AI Code Explanation'));
console.log(chalk.gray('─'.repeat(60)));
if (explanation.file) {
console.log(`${chalk.cyan('File:')} ${explanation.file}`);
}
if (explanation.element) {
console.log(`${chalk.cyan('Element:')} ${explanation.element.type} - ${explanation.element.name}`);
}
console.log('\n' + chalk.bold('Summary:'));
console.log(explanation.summary || 'No summary available');
if (explanation.purpose) {
console.log('\n' + chalk.bold('Purpose:'));
console.log(explanation.purpose);
}
if (explanation.how_it_works) {
console.log('\n' + chalk.bold('How it works:'));
console.log(explanation.how_it_works);
}
if (explanation.dependencies && explanation.dependencies.length > 0) {
console.log('\n' + chalk.bold('Dependencies:'));
explanation.dependencies.forEach((dep) => {
console.log(` • ${dep}`);
});
}
if (explanation.suggestions && explanation.suggestions.length > 0) {
console.log('\n' + chalk.bold('💡 Suggestions:'));
explanation.suggestions.forEach((suggestion) => {
console.log(` • ${suggestion}`);
});
}
}
else {
spinner.fail('Code explanation failed');
if (result.error) {
console.error(chalk.red(`Error: ${result.error}`));
}
}
}
catch (error) {
spinner.fail('Code explanation failed');
console.error(chalk.red(`Error: ${error instanceof Error ? error.message : String(error)}`));
}
});
return command;
}
//# sourceMappingURL=ingest-codebase.js.map