mega-minds
Version:
Enhanced multi-agent workflow system for Claude Code projects with automated handoff management and Claude Code hooks integration
818 lines (697 loc) ⢠35.7 kB
JavaScript
const fs = require('fs-extra');
const path = require('path');
const inquirer = require('inquirer').default;
const { execSync } = require('child_process');
// MEGA-MINDS 2.0: Variable-Driven Agent System components
const { ProjectContextAnalyzer } = require('./project-context-analyzer');
const { TemplateAdapter } = require('./template-adapter');
const { StackProfileManager } = require('./stack-profile-manager');
async function ensurePackageJson() {
const packageJsonPath = path.join(process.cwd(), 'package.json');
if (!await fs.pathExists(packageJsonPath)) {
console.log('š¦ No package.json found. Initializing npm project...');
try {
execSync('npm init -y', { stdio: 'pipe' });
console.log('ā
Created package.json\n');
} catch (error) {
console.error('ā Failed to initialize npm project:', error.message);
process.exit(1);
}
}
}
async function ensureMegaMindsDependency() {
const packageJsonPath = path.join(process.cwd(), 'package.json');
const packageJson = await fs.readJson(packageJsonPath);
const hasDependency =
(packageJson.dependencies && packageJson.dependencies['mega-minds']) ||
(packageJson.devDependencies && packageJson.devDependencies['mega-minds']);
if (!hasDependency) {
console.log('š¦ Adding mega-minds to project dependencies...');
if (!packageJson.dependencies) {
packageJson.dependencies = {};
}
// Get the current version from our package.json
const ourPackageJson = await fs.readJson(path.join(__dirname, '..', 'package.json'));
packageJson.dependencies['mega-minds'] = `^${ourPackageJson.version}`;
await fs.writeJson(packageJsonPath, packageJson, { spaces: 2 });
console.log('ā
Added mega-minds to dependencies\n');
console.log('š„ Installing dependencies...');
try {
execSync('npm install', { stdio: 'inherit' });
console.log('ā
Dependencies installed\n');
} catch (error) {
console.log('ā ļø Could not auto-install. Please run "npm install" manually.\n');
}
} else {
console.log('ā
mega-minds already in dependencies\n');
}
}
async function run() {
console.log('š¤ Welcome to Mega Minds Installer!');
console.log('Installing Claude Code sub-agents for multi-agent development workflow...\n');
// First check if we're in a valid npm project
await ensurePackageJson();
// Ask user configuration questions
const answers = await inquirer.prompt([
{
type: 'input',
name: 'projectName',
message: 'What is your project name?',
default: path.basename(process.cwd())
},
{
type: 'confirm',
name: 'installAll',
message: 'Install all agents and workflows?',
default: true
},
{
type: 'list',
name: 'agentStructure',
message: 'How would you like to organize your agents?',
choices: [
{
name: 'Flat structure (Recommended - guaranteed compatibility)',
value: 'flat'
},
{
name: 'Categorized subdirectories (Experimental)',
value: 'categorized'
}
],
default: 'flat'
},
{
type: 'confirm',
name: 'overwriteExisting',
message: 'Overwrite existing .claude directory if it exists?',
default: false,
when: () => fs.existsSync(path.join(process.cwd(), '.claude'))
}
]);
try {
// Ensure mega-minds is in dependencies
await ensureMegaMindsDependency();
// MEGA-MINDS 2.0: Initialize Variable-Driven Agent System
console.log('\nš Initializing Variable-Driven Agent System...');
const variableSystemInit = await initializeVariableSystem(answers);
if (!variableSystemInit.success) {
console.log('ā ļø Variable System initialization failed, falling back to static templates');
} else {
console.log(`ā
Tech Stack Detected: ${variableSystemInit.techStack}`);
console.log(`ā
Variable Engine Active: ${variableSystemInit.variableCount} variables generated`);
}
// Setup directory structure
await setupDirectoryStructure(answers);
// Copy template files based on structure choice with Variable System integration
if (answers.agentStructure === 'flat') {
await installFlatStructure(answers, variableSystemInit);
} else {
await installCategorizedStructure(answers, variableSystemInit);
}
// MEGA-MINDS 2.1: Initialize Claude Code Integration (Phase 1 Enhancements)
await initializeClaudeIntegration(answers, variableSystemInit);
// Success message with instructions
displaySuccessMessage(answers, variableSystemInit);
// Run verification
console.log('\n' + '='.repeat(50));
console.log('\nš Running installation verification...');
const { verifyInstallation } = require('./verify-installation');
const verified = verifyInstallation();
if (!verified) {
console.log('\nā ļø Some issues were detected. Please review and fix them.');
}
} catch (error) {
console.error('ā Installation failed:', error.message);
console.error('Please check permissions and try again.');
process.exit(1);
}
}
async function setupDirectoryStructure(answers) {
const claudeDir = path.join(process.cwd(), '.claude');
// Check if .claude exists and handle overwrite
if (fs.existsSync(claudeDir)) {
if (answers.overwriteExisting) {
console.log('šļø Removing existing .claude directory...');
await fs.remove(claudeDir);
} else {
console.log('ā ļø .claude directory exists. Skipping installation.');
console.log('Run with --force flag or choose overwrite option to replace existing installation.');
process.exit(0);
}
}
// Create main .claude directory structure
console.log('š Creating .claude directory structure...');
await fs.ensureDir(claudeDir);
await fs.ensureDir(path.join(claudeDir, 'agents'));
await fs.ensureDir(path.join(claudeDir, 'workflows'));
await fs.ensureDir(path.join(claudeDir, 'workflows', 'logs'));
}
async function installFlatStructure(answers, variableSystemInit) {
console.log('š¦ Installing agents in flat structure...');
const templatesDir = path.join(__dirname, '..', 'templates');
const claudeDir = path.join(process.cwd(), '.claude');
// Agent categories and their files
const agentCategories = [
'businessops',
'development',
'devops',
'maintenance',
'planning',
'prototyping',
'qa',
'saas'
];
// Copy all agent files to flat .claude/agents/ structure with Variable System processing
for (const category of agentCategories) {
const categoryPath = path.join(templatesDir, category);
if (await fs.pathExists(categoryPath)) {
const files = await fs.readdir(categoryPath);
const agentFiles = files.filter(file => file.endsWith('-agent.md'));
for (const agentFile of agentFiles) {
const sourcePath = path.join(categoryPath, agentFile);
const destPath = path.join(claudeDir, 'agents', agentFile);
// MEGA-MINDS 2.0: Process templates with Variable System
if (variableSystemInit.success && variableSystemInit.templateAdapter) {
try {
const templateContent = await fs.readFile(sourcePath, 'utf8');
const adaptedContent = await variableSystemInit.templateAdapter.adaptAgentTemplate(
agentFile.replace('.md', ''),
templateContent
);
await fs.writeFile(destPath, adaptedContent);
console.log(`ā
Installed (Variable-Adapted): ${agentFile}`);
} catch (error) {
// Fallback to static copy
await fs.copy(sourcePath, destPath);
console.log(`ā
Installed (Static): ${agentFile}`);
}
} else {
// Fallback to static copy
await fs.copy(sourcePath, destPath);
console.log(`ā
Installed: ${agentFile}`);
}
}
}
}
// Copy workflow files
await copyWorkflowFiles(templatesDir, claudeDir);
// Copy main claude.md file with Variable System context
await copyMainConfigFile(templatesDir, claudeDir, answers, variableSystemInit);
}
async function installCategorizedStructure(answers, variableSystemInit) {
console.log('š¦ Installing agents in categorized structure...');
console.log('ā ļø Note: This is experimental - Claude Code may not recognize subdirectories');
const templatesDir = path.join(__dirname, '..', 'templates');
const claudeDir = path.join(process.cwd(), '.claude');
// Agent categories mapping
const categoryMapping = {
'planning': ['project-orchestrator-agent.md', 'requirements-analysis-agent.md', 'market-research-agent.md', 'risk-assessment-agent.md', 'technical-architecture-agent.md'],
'development': ['frontend-development-agent.md', 'backend-development-agent.md', 'database-agent.md', 'authentication-agent.md'],
'prototyping': ['ux-ui-design-agent.md', 'api-design-agent.md', 'database-schema-agent.md', 'security-architecture-agent.md'],
'qa': ['testing-agent.md', 'code-review-agent.md', 'security-testing-agent.md', 'performance-testing-agent.md'],
'devops': ['ci-cd-pipeline-agent.md', 'infrastructure-agent.md', 'monitoring-agent.md', 'backup-recovery-agent.md'],
'maintenance': ['bug-tracker-agent.md', 'performance-optimizer-agent.md', 'feature-manager-agent.md', 'ab-tester-agent.md'],
'businessops': ['analytics-agent.md', 'customer-support-agent.md', 'marketing-automation-agent.md', 'documentation-agent.md'],
'saas': ['multi-tenancy-agent.md', 'onboarding-agent.md', 'subscription-management-agent.md', 'usage-tracking-agent.md']
};
// Create category subdirectories and copy files with Variable System processing
for (const [category, agentFiles] of Object.entries(categoryMapping)) {
const categoryDir = path.join(claudeDir, 'agents', category);
await fs.ensureDir(categoryDir);
const sourceCategoryDir = path.join(templatesDir, category);
if (await fs.pathExists(sourceCategoryDir)) {
for (const agentFile of agentFiles) {
const sourcePath = path.join(sourceCategoryDir, agentFile);
const destPath = path.join(categoryDir, agentFile);
if (await fs.pathExists(sourcePath)) {
// MEGA-MINDS 2.0: Process templates with Variable System
if (variableSystemInit.success && variableSystemInit.templateAdapter) {
try {
const templateContent = await fs.readFile(sourcePath, 'utf8');
const adaptedContent = await variableSystemInit.templateAdapter.adaptAgentTemplate(
agentFile.replace('.md', ''),
templateContent
);
await fs.writeFile(destPath, adaptedContent);
console.log(`ā
Installed (Variable-Adapted): ${category}/${agentFile}`);
} catch (error) {
// Fallback to static copy
await fs.copy(sourcePath, destPath);
console.log(`ā
Installed (Static): ${category}/${agentFile}`);
}
} else {
// Fallback to static copy
await fs.copy(sourcePath, destPath);
console.log(`ā
Installed: ${category}/${agentFile}`);
}
}
}
}
}
// Copy workflow files
await copyWorkflowFiles(templatesDir, claudeDir);
// Copy main claude.md file with Variable System context
await copyMainConfigFile(templatesDir, claudeDir, answers, variableSystemInit);
}
async function copyWorkflowFiles(templatesDir, claudeDir) {
console.log('š Installing workflow files...');
const workflowsSourceDir = path.join(templatesDir, 'workflows');
const workflowsDestDir = path.join(claudeDir, 'workflows');
if (await fs.pathExists(workflowsSourceDir)) {
// Copy all workflow files
const workflowFiles = await fs.readdir(workflowsSourceDir, { withFileTypes: true });
for (const item of workflowFiles) {
const sourcePath = path.join(workflowsSourceDir, item.name);
const destPath = path.join(workflowsDestDir, item.name);
if (item.isDirectory()) {
await fs.copy(sourcePath, destPath);
console.log(`ā
Installed workflow directory: ${item.name}/`);
} else {
await fs.copy(sourcePath, destPath);
console.log(`ā
Installed workflow: ${item.name}`);
}
}
}
}
async function copyMainConfigFile(templatesDir, claudeDir, answers, variableSystemInit) {
console.log('āļø Installing main configuration...');
const destClaudeFile = path.join(claudeDir, 'claude.md');
// Generate dynamic CLAUDE.md content based on project analysis
const claudeContent = generateDynamicClaudeContent(answers, variableSystemInit);
await fs.writeFile(destClaudeFile, claudeContent);
console.log('ā
Installed: claude.md');
}
function generateDynamicClaudeContent(answers, variableSystemInit) {
const projectMode = variableSystemInit?.analysis?.projectMode || {
mode: 'unknown',
confidence: 'low',
description: 'Project mode could not be determined',
instructions: 'Please specify your project type.',
quickStart: '@project-orchestrator-agent "Help me get started with this project"',
examples: []
};
const techStack = variableSystemInit?.analysis?.techStack || { languages: [], confidence: 'unknown' };
const stackDisplay = techStack.languages.length > 0 ?
techStack.languages.join(', ') : 'Not yet determined';
const confidenceEmoji = {
'high': 'ā
',
'medium': 'ā ļø',
'low': 'ā',
'unknown': 'ā'
}[projectMode.confidence] || 'ā';
return `# ${answers.projectName}
*Powered by Mega-Minds AI Development System*
## š Project Analysis
**Detected**: ${projectMode.mode.toUpperCase().replace('-', ' ')} ${confidenceEmoji} (${projectMode.confidence} confidence)
**Tech Stack**: ${stackDisplay}
**Description**: ${projectMode.description}
## š Quick Start
${projectMode.instructions}
### Recommended First Command:
\`\`\`
${projectMode.quickStart}
\`\`\`
### Examples:
${projectMode.examples && projectMode.examples.length > 0 ?
projectMode.examples.map(example => `- @project-orchestrator-agent "${example}"`).join('\n') :
'- @project-orchestrator-agent "Help me understand this project structure"\n- @project-orchestrator-agent "Set up a development workflow for this stack"'}
### Alternative Commands:
- **New Project**: \`@project-orchestrator-agent "I want to build [your idea]"\`
- **Existing Project**: \`@project-orchestrator-agent "Analyze this codebase and continue"\`
- **Override Detection**: \`@project-orchestrator-agent "This is actually a [new/existing] project"\`
## š¤ Agent Coordination
The @project-orchestrator-agent will automatically coordinate all specialist agents based on your project needs:
- **Frontend Development**: React, Vue, Angular specialists
- **Backend Development**: Node.js, Python, Go, Java specialists
- **Database**: PostgreSQL, MongoDB, Supabase specialists
- **Testing**: Unit, integration, E2E testing specialists
- **DevOps**: CI/CD, deployment, infrastructure specialists
## š Quick Commands
- \`mega-minds memory-status\` - Check memory health
- \`mega-minds agent-status\` - See active agents
- \`mega-minds variable-status\` - View tech stack variables
- \`mega-minds save-session\` - Save your progress
## š§ Variable-Driven System
${variableSystemInit?.success ?
`ā
**Active** - Templates adapted for ${variableSystemInit.techStack}` :
'ā ļø **Static Mode** - Using generic templates'
}
---
š” **Pro tip**: Always start with the @project-orchestrator-agent for best coordination between all specialist agents!
*Generated by Mega-Minds v2.0 with Variable-Driven Agent System*
`;
}
function displaySuccessMessage(answers, variableSystemInit) {
console.log('\nš Success! Your mega-minds agents are installed!\n');
// MEGA-MINDS 2.0: Show Variable System status
if (variableSystemInit && variableSystemInit.success) {
console.log('š§ Variable-Driven Agent System: ā
ACTIVE');
console.log(` š Tech Stack: ${variableSystemInit.techStack}`);
console.log(` š¢ Variables Generated: ${variableSystemInit.variableCount}`);
console.log(` šÆ Templates: Adapted for your tech stack`);
console.log('');
} else {
console.log('ā ļø Variable-Driven Agent System: Static mode (tech stack not detected)');
console.log('');
}
console.log('š Installed structure:');
console.log('āāā .claude/');
console.log('ā āāā agents/ (Claude Code sub-agents)');
if (answers.agentStructure === 'categorized') {
console.log('ā ā āāā planning/');
console.log('ā ā āāā development/');
console.log('ā ā āāā qa/');
console.log('ā ā āāā ... (other categories)');
} else {
console.log('ā ā āāā project-orchestrator-agent.md');
console.log('ā ā āāā frontend-development-agent.md');
console.log('ā ā āāā ... (all agents)');
}
console.log('ā āāā workflows/ (Communication protocols & quality gates)');
console.log('ā āāā claude.md (Main configuration)');
console.log('āāā node_modules/');
console.log('ā āāā mega-minds/ (Core AI team functionality)');
console.log('ā āāā lib/');
console.log('ā āāā core/ (SessionManager, AIDevTeam, etc.)');
console.log('ā āāā memory/ (TokenManager, MemoryManager, etc.)');
console.log('ā āāā variable-driven/ (Variable System, Stack Detection, etc.)');
console.log('');
console.log('ā
IMPORTANT: Dependencies Configuration');
console.log(' mega-minds has been added to your package.json');
console.log(' Core functionality remains in node_modules/mega-minds/');
console.log('');
console.log('š To activate your agents:');
console.log('1. Start Claude Code in your project directory');
console.log('2. Claude Code will automatically read .claude/claude.md');
console.log('3. Verify agents are loaded with: "/agents"');
console.log('4. Start building: "@project-orchestrator I want to build <your idea here>"');
console.log('');
console.log('š§ Memory Management Commands (use with npx):');
console.log(' npx mega-minds memory-status - Check memory health');
console.log(' npx mega-minds save-session - Save development session');
console.log(' npx mega-minds compress-context - Optimize for Claude Code');
console.log('');
if (answers.agentStructure === 'categorized') {
console.log('ā ļø Note: You chose categorized structure (experimental)');
console.log(' If Claude Code doesn\'t recognize your agents, try:');
console.log(' - Use "/agents" to check if they\'re detected');
console.log(' - Flatten the structure by moving all .md files to .claude/agents/');
console.log(' - Or reinstall with flat structure option');
console.log('');
}
console.log('š¤ Your agents will coordinate the entire development process!');
console.log('š Check .claude/workflows/ for communication protocols and quality gates.');
console.log('');
console.log('ā” NEW: Claude Code Integration Features');
console.log(' - Quick slash commands: All 31+ agents available (e.g., /orchestrator, /frontend, /backend)');
console.log(' - Real-time statusline: Shows agents, memory, and performance');
console.log(' - Optimal settings: Auto-configured for your project');
console.log(' - Utility commands: /mega-status, /handoff, /memory-check');
console.log('');
console.log('š” Pro tip: Always start with @project-orchestrator-agent for best results!');
}
// MEGA-MINDS 2.0: Variable-Driven Agent System initialization
async function initializeVariableSystem(answers) {
try {
const projectPath = process.cwd();
// Initialize components
const projectAnalyzer = new ProjectContextAnalyzer(projectPath);
const templateAdapter = new TemplateAdapter(projectPath);
const stackProfileManager = new StackProfileManager();
// Analyze project and detect tech stack
console.log(' š Detecting project technology stack...');
const analysis = await projectAnalyzer.analyzeProject();
// Get stack profile or use detected stack
let stackProfile = null;
if (analysis.techStack && analysis.techStack.confidence === 'high') {
stackProfile = stackProfileManager.findBestProfile(analysis.techStack);
}
if (!stackProfile) {
console.log(' ā ļø Could not auto-detect stack, using fallback profile');
// Use the first available profile as fallback
const availableProfiles = stackProfileManager.getAvailableProfiles();
if (availableProfiles.length > 0) {
stackProfile = availableProfiles[0];
} else {
// Create minimal fallback if no profiles available
stackProfile = {
name: 'Generic Full Stack',
description: 'Generic full-stack development profile',
variables: {
'{{LANGUAGE_PRIMARY}}': 'JavaScript',
'{{FRONTEND_FRAMEWORK}}': 'React',
'{{BACKEND_FRAMEWORK}}': 'Node.js',
'{{TESTING_FRAMEWORK}}': 'Jest',
'{{FILE_EXTENSION}}': '.js'
}
};
}
}
// Initialize template adapter with detected stack
templateAdapter.setStackProfile(stackProfile);
return {
success: true,
techStack: stackProfile ? stackProfile.name : 'Generic Full Stack',
stackProfile: stackProfile,
templateAdapter: templateAdapter,
projectAnalyzer: projectAnalyzer,
variableCount: Object.keys(stackProfile?.variables || {}).length,
analysis: analysis
};
} catch (error) {
console.error(' ā Variable System initialization error:', error.message);
return {
success: false,
error: error.message,
templateAdapter: null,
stackProfile: null
};
}
}
// MEGA-MINDS 2.1: Claude Code Integration Initialization
async function initializeClaudeIntegration(answers, variableSystemInit) {
console.log('\nš Initializing Claude Code Integration...');
console.log('ā” Phase 1: Quick Wins (Slash Commands, Statusline, Settings)');
try {
const { initializeClaudeIntegration } = require('./claude-integration');
// Prepare agent data for slash commands
const agentData = await prepareAgentData(answers);
// Prepare project analysis for optimization
const projectAnalysis = await prepareProjectAnalysis(variableSystemInit);
// Initialize all Claude integrations
const integrationResults = await initializeClaudeIntegration(
process.cwd(),
{ ...projectAnalysis, agents: agentData },
null // AIDevTeam will be initialized during runtime
);
// Report results
if (integrationResults.slashCommands && integrationResults.slashCommands.totalGenerated > 0) {
console.log(`ā
Generated ${integrationResults.slashCommands.totalGenerated} slash commands`);
}
if (integrationResults.statusline && integrationResults.statusline.path) {
console.log('ā
Created statusline script for real-time monitoring');
}
if (integrationResults.settings && integrationResults.settings.path) {
console.log('ā
Generated optimal Claude Code settings');
}
// Report any errors
if (integrationResults.errors.length > 0) {
console.log('ā ļø Some integration features had issues:');
integrationResults.errors.forEach(error => console.log(` - ${error}`));
}
console.log('š Claude Code integration ready!');
console.log(' Use /mega-status to check system status');
console.log(' Use /handoff to manage agent transitions');
} catch (error) {
console.log('ā ļø Claude integration initialization failed:', error.message);
console.log(' Basic mega-minds functionality will still work');
}
}
async function prepareAgentData(answers) {
// Dynamically discover ALL available agents from templates directory
const templatesDir = path.join(__dirname, '..', 'templates');
const allAgents = [];
try {
// Get all agent categories
const agentCategories = [
'planning', 'development', 'qa', 'devops',
'businessops', 'maintenance', 'prototyping', 'saas'
];
// Scan each category for agent files
for (const category of agentCategories) {
const categoryPath = path.join(templatesDir, category);
if (await fs.pathExists(categoryPath)) {
const categoryFiles = await fs.readdir(categoryPath);
const agentFiles = categoryFiles.filter(file =>
file.endsWith('-agent.md') || file.endsWith('-agent.markdown')
);
// Parse each agent file to extract metadata
for (const agentFile of agentFiles) {
const agentPath = path.join(categoryPath, agentFile);
const agentName = path.basename(agentFile, path.extname(agentFile));
try {
const agentContent = await fs.readFile(agentPath, 'utf8');
const description = extractAgentDescription(agentContent, agentName);
const specialty = getCategorySpecialty(category, agentName);
allAgents.push({
name: agentName,
description: description,
specialty: specialty,
category: category
});
} catch (error) {
console.warn(`ā ļø Could not parse agent ${agentName}:`, error.message);
}
}
}
}
console.log(`š Discovered ${allAgents.length} agents for slash command generation`);
return allAgents;
} catch (error) {
console.warn('ā ļø Could not scan agents directory, using fallback set:', error.message);
// Fallback to essential agents if scanning fails
return [
{
name: 'project-orchestrator-agent',
description: 'Coordinates all agents and manages project workflow',
specialty: 'multi-agent coordination',
category: 'planning'
},
{
name: 'frontend-development-agent',
description: 'Builds user interfaces and client-side functionality',
specialty: 'frontend development',
category: 'development'
},
{
name: 'backend-development-agent',
description: 'Develops server-side logic and APIs',
specialty: 'backend development',
category: 'development'
},
{
name: 'testing-agent',
description: 'Ensures code quality through comprehensive testing',
specialty: 'quality assurance',
category: 'qa'
},
{
name: 'database-agent',
description: 'Designs and optimizes database structures and queries',
specialty: 'database management',
category: 'development'
}
];
}
}
// Helper function to extract agent description from markdown content
function extractAgentDescription(content, agentName) {
// Try to extract from frontmatter description
const frontmatterMatch = content.match(/^---\n([\s\S]*?)\n---/);
if (frontmatterMatch) {
const descriptionMatch = frontmatterMatch[1].match(/description:\s*(.+)/);
if (descriptionMatch) {
return descriptionMatch[1].trim().replace(/^["']|["']$/g, '');
}
}
// Try to extract from first heading or paragraph
const headingMatch = content.match(/^#+\s*(.+)/m);
if (headingMatch && !headingMatch[1].includes('agent')) {
return headingMatch[1].trim();
}
// Generate description from agent name
return generateDescriptionFromName(agentName);
}
// Helper function to generate description from agent name
function generateDescriptionFromName(agentName) {
const nameMap = {
'project-orchestrator-agent': 'Coordinates all agents and manages project workflow',
'frontend-development-agent': 'Builds user interfaces and client-side functionality',
'backend-development-agent': 'Develops server-side logic and APIs',
'database-agent': 'Designs and optimizes database structures and queries',
'testing-agent': 'Ensures code quality through comprehensive testing',
'authentication-agent': 'Handles user authentication and authorization systems',
'api-design-agent': 'Designs and documents RESTful and GraphQL APIs',
'security-testing-agent': 'Performs security analysis and vulnerability testing',
'performance-testing-agent': 'Optimizes application performance and load testing',
'code-review-agent': 'Reviews code quality, standards, and best practices',
'ci-cd-pipeline-agent': 'Sets up continuous integration and deployment',
'infrastructure-agent': 'Manages cloud infrastructure and deployment',
'monitoring-agent': 'Implements logging, monitoring, and alerting systems',
'backup-recovery-agent': 'Handles data backup and disaster recovery',
'analytics-agent': 'Implements user analytics and business intelligence',
'customer-support-agent': 'Develops customer support and help systems',
'marketing-automation-agent': 'Creates marketing automation and campaigns',
'ux-ui-design-agent': 'Designs user experience and interface components',
'technical-architecture-agent': 'Designs system architecture and technical decisions',
'risk-assessment-agent': 'Analyzes project risks and mitigation strategies',
'market-research-agent': 'Conducts market analysis and competitive research',
'database-schema-agent': 'Designs optimal database schemas and relationships',
'security-architecture-agent': 'Architects secure system designs and protocols',
'ab-tester-agent': 'Implements A/B testing and experimentation',
'bug-tracker-agent': 'Manages bug tracking and issue resolution',
'feature-manager-agent': 'Plans and manages feature development lifecycle',
'performance-optimizer-agent': 'Optimizes system and application performance',
'multi-tenancy-agent': 'Implements multi-tenant architecture patterns',
'onboarding-agent': 'Designs user onboarding and activation flows',
'subscription-management-agent': 'Handles subscription billing and management',
'usage-tracking-agent': 'Implements usage analytics and tracking systems'
};
return nameMap[agentName] || `Specialized agent for ${agentName.replace(/-/g, ' ').replace(' agent', '')}`;
}
// Helper function to get category specialty
function getCategorySpecialty(category, agentName) {
const categoryMap = {
'planning': 'project planning and strategy',
'development': 'software development',
'qa': 'quality assurance and testing',
'devops': 'infrastructure and operations',
'businessops': 'business operations',
'maintenance': 'system maintenance and optimization',
'prototyping': 'design and prototyping',
'saas': 'SaaS platform features'
};
return categoryMap[category] || 'specialized development';
}
async function prepareProjectAnalysis(variableSystemInit) {
// Extract project information for settings optimization
const analysis = {
projectType: 'development',
complexity: variableSystemInit.success ? 'medium' : 'low',
hasPackageJson: fs.existsSync('package.json'),
hasGit: fs.existsSync('.git'),
needsBash: true,
needsNetwork: false,
hasDatabase: false,
hasAPI: true,
needsSecurity: true,
techStack: {
languages: ['JavaScript'],
frameworks: []
}
};
// Enhanced analysis if Variable System is available
if (variableSystemInit.success && variableSystemInit.analysis) {
analysis.techStack = variableSystemInit.analysis.techStack || analysis.techStack;
analysis.complexity = variableSystemInit.analysis.complexity || analysis.complexity;
analysis.hasDatabase = variableSystemInit.analysis.hasDatabase || false;
analysis.projectType = variableSystemInit.analysis.projectType || 'development';
}
return analysis;
}
// Handle CLI execution
if (require.main === module) {
run().catch(error => {
console.error('Fatal error:', error);
process.exit(1);
});
}
module.exports = {
run,
generateDynamicClaudeContent,
initializeVariableSystem,
initializeClaudeIntegration,
prepareAgentData,
prepareProjectAnalysis
};