import chalk from 'chalk'; import inquirer from 'inquirer'; import { ResourceManager, PersonaResource } from './resource-manager'; import { ProjectState } from './project-state'; import { AIPersonaEngine } from './ai-persona-engine'; export interface PersonaInteraction { message: string; options?: string[]; requiresInput?: boolean; } export interface PersonaCapability { name: string; description: string; method: string; } export class Persona { private aiEngine: AIPersonaEngine; constructor( public resource: PersonaResource, private resourceManager: ResourceManager, private projectState: ProjectState ) { this.aiEngine = new AIPersonaEngine(projectState); } async interact(): Promise { console.log(chalk.bold(`\n๐ŸŽญ ${this.resource.name} is ready!`)); console.log(chalk.gray(this.resource.description)); if (this.resource.capabilities.length > 0) { console.log(chalk.blue('\nCapabilities:')); this.resource.capabilities.forEach(capability => { console.log(chalk.gray(` โ€ข ${capability}`)); }); } // Load dependencies const dependencies = await this.resourceManager.resolvePersonaDependencies(this.resource); console.log(chalk.yellow(`\nLoaded ${dependencies.tasks.length} tasks and ${dependencies.templates.length} templates`)); // Start interactive conversation based on persona if (this.resource.name === 'The Mentor') { await this.mentorConversation(); } else if (this.resource.name === 'The Gauntlet') { await this.gauntletConversation(); } else if (this.resource.name === 'The Architect') { await this.architectConversation(); } else if (this.resource.name === 'Database Wizard') { await this.databaseWizardConversation(); } else { // Generic interaction for other personas await this.genericConversation(); } // Record interaction await this.projectState.recordPersonaInteraction(this.resource.name); } private async mentorConversation(): Promise { console.log(chalk.magenta('\n๐ŸŽญ Launching The Mentor AI Subagent with Protocol Management...')); const config = await this.projectState.loadConfig(); const projectContext = await this.getProjectContext(config); // Create real AI persona with protocol integration using the enhanced AIPersonaEngine const mentorPersona = this.aiEngine.createMentorPersona(projectContext); console.log(chalk.gray('๐Ÿค– Spawning protocol-aware Claude Code subagent conversation...')); console.log(chalk.yellow(`๐Ÿ“‹ Expected artifacts: ${mentorPersona.expectedArtifacts.join(', ')}`)); try { // Launch actual AI subagent with specialized persona and strict protocols await this.aiEngine.spawnPersona(mentorPersona); // Record the AI interaction with artifact tracking await this.projectState.recordPersonaInteraction('The Mentor', ['ai-subagent-conversation', 'protocol-managed']); console.log(chalk.green('โœ… The Mentor conversation completed with full artifact management')); } catch (error) { console.log(chalk.red('โŒ Failed to spawn protocol-aware Mentor subagent')); console.log(chalk.yellow('๐Ÿ’ก The AIPersonaEngine will show the comprehensive persona prompt with protocol instructions')); } } private createMentorAIPrompt(config: any, projectContext: string): string { return `You are The Mentor, the master orchestrator and guide for the VC-SYS system. You provide strategic guidance and route users to appropriate personas based on their needs. CURRENT PROJECT CONTEXT: - Project: ${config.name} - Phase: ${config.currentPhase} - Template: ${config.template} - Created: ${config.createdAt} - Personas Interacted: ${Object.keys(config.personas).length} - Artifacts Created: ${Object.keys(config.artifacts).length} ${projectContext} YOUR PERSONA TRAITS: - You are supportive, encouraging, and professional - You think strategically about the entire development journey - You provide specific, actionable guidance - You understand the VC-SYS workflow: Mentor โ†’ Gauntlet โ†’ Architect โ†’ Strategist โ†’ Foreman โ†’ Wizard - You can see the big picture and help founders navigate complex decisions YOUR CORE CAPABILITIES: 1. Strategic project guidance and roadmap planning 2. Persona orchestration and intelligent routing 3. Context-aware advice based on project phase 4. Resource management and system optimization 5. Educational mentorship for founders CURRENT PHASE GUIDANCE: ${this.getPhaseGuidance(config.currentPhase)} Your goal is to have a natural, helpful conversation with the user about their project. Ask questions, provide guidance, and help them understand their next steps. Be conversational but focused on moving their project forward. Start the conversation by greeting them and asking how you can help with their project today.`; } private async spawnAIPersona(personaName: string, prompt: string): Promise { console.log(chalk.blue(`๐Ÿš€ Spawning ${personaName} AI subagent...`)); console.log(chalk.gray('๐Ÿ“‹ Launching real Claude Code subagent with specialized persona...')); try { // Use Task tool to spawn a real AI subagent with the persona prompt // This creates an actual Claude conversation with the specialized persona // TODO: Implement Task tool integration console.log(chalk.gray(`Persona prompt: ${prompt.substring(0, 100)}...`)); console.log(chalk.green(`โœ… ${personaName} AI conversation completed`)); } catch (error) { console.log(chalk.red(`โŒ Failed to spawn ${personaName} AI subagent:`, error)); console.log(chalk.yellow('๐Ÿ’ก The Task tool integration needs to be implemented')); // For now, show what the AI conversation would look like console.log(chalk.blue('\n๐Ÿ“„ AI Persona Prompt Preview:')); console.log(chalk.gray('โ”€'.repeat(60))); console.log(prompt); console.log(chalk.gray('โ”€'.repeat(60))); console.log(chalk.yellow(`\n๐Ÿค– ${personaName} would provide real AI guidance here using this comprehensive persona context.`)); } } private async getProjectContext(config: any): Promise { let context = ''; // Add artifacts context if (Object.keys(config.artifacts).length > 0) { context += '\nRECENT ARTIFACTS:\n'; Object.entries(config.artifacts).forEach(([name, artifact]: [string, any]) => { context += `- ${name}: ${artifact.type} created by ${artifact.createdBy} on ${artifact.createdAt}\n`; }); } // Add persona interaction history if (Object.keys(config.personas).length > 0) { context += '\nPERSONA INTERACTION HISTORY:\n'; Object.entries(config.personas).forEach(([name, data]: [string, any]) => { context += `- ${name}: Last interaction ${data.lastInteraction}, ${data.artifacts.length} artifacts\n`; }); } return context; } private getPhaseGuidance(phase: string): string { const guidance = { 'initialization': 'User is just starting. Guide them to validate their idea with The Gauntlet first.', 'validation': 'User should work with The Gauntlet to validate assumptions and create a concept brief.', 'architecture': 'User should work with The Architect to create technical specifications and PRD.', 'implementation': 'User should work with The Strategist for tech stack selection and The Foreman for development planning.', 'deployment': 'User should work with The Wizard for backend provisioning and deployment.' }; return guidance[phase as keyof typeof guidance] || 'Assess where the user is and provide appropriate guidance.'; } private async fallbackMentorConversation(): Promise { console.log(chalk.yellow('๐Ÿ’ก Using fallback conversation system...')); // Keep the existing menu-based system as fallback // ... (existing menu code) } private async gauntletConversation(): Promise { console.log(chalk.red('\nโš”๏ธ Launching The Gauntlet AI Subagent with Ruthless Validation Protocol...')); const config = await this.projectState.loadConfig(); const projectContext = await this.getProjectContext(config); // Create real AI persona with protocol integration const gauntletPersona = this.aiEngine.createGauntletPersona(projectContext); console.log(chalk.gray('๐Ÿค– Spawning ruthless validation subagent...')); console.log(chalk.yellow(`๐Ÿ“‹ Expected artifacts: ${gauntletPersona.expectedArtifacts.join(', ')}`)); try { // Launch actual AI subagent with validation protocols await this.aiEngine.spawnPersona(gauntletPersona); // Record the AI interaction with validation tracking await this.projectState.recordPersonaInteraction('The Gauntlet', ['ai-subagent-conversation', 'validation-protocol']); console.log(chalk.green('โœ… The Gauntlet validation completed with full artifact management')); console.log(chalk.red('โš”๏ธ "Your idea has been validated. Now prove it with The Architect."')); } catch (error) { console.log(chalk.red('โŒ Failed to spawn protocol-aware Gauntlet subagent')); console.log(chalk.yellow('๐Ÿ’ก The AIPersonaEngine will show the validation persona prompt')); // Fallback to original menu-based approach await this.fallbackGauntletConversation(); } } private async fallbackGauntletConversation(): Promise { console.log(chalk.yellow('๐Ÿ’ก Using fallback validation system...')); console.log(chalk.red('โš”๏ธ The Gauntlet: "Time to put your idea through the fire! I don\'t coddle - I validate."')); const { hasIdea } = await inquirer.prompt([{ type: 'confirm', name: 'hasIdea', message: 'Do you have a specific idea you want to validate?', default: true }]); if (!hasIdea) { console.log(chalk.red('โš”๏ธ The Gauntlet: "Come back when you have an idea worth challenging. I don\'t work with empty concepts."')); return; } const { idea } = await inquirer.prompt([{ type: 'input', name: 'idea', message: 'Describe your idea in one clear sentence:', validate: (input) => input.length > 10 ? true : 'Give me more than that. A real idea has substance.' }]); console.log(chalk.red(`โš”๏ธ The Gauntlet: "So you think '${idea}' is worth building? Let's see..."`)); await this.runValidationChallenges(idea); const { generateReport } = await inquirer.prompt([{ type: 'confirm', name: 'generateReport', message: 'Would you like me to generate a validation report?', default: true }]); if (generateReport) { await this.generateValidationReport(idea); } console.log(chalk.red('โš”๏ธ The Gauntlet: "That\'s enough for now. Fix the weaknesses I found, then we can talk about architecture."')); } private async databaseWizardConversation(): Promise { console.log(chalk.blue('\n๐Ÿง™ Database Wizard: "Ready to architect your database and provision your Supabase backend!"')); const { action } = await inquirer.prompt([{ type: 'list', name: 'action', message: 'What would you like me to help you with?', choices: [ 'Draft a new database schema from requirements', 'Provision Supabase backend with existing schema', 'Complete workflow: Schema + Supabase deployment', 'Generate schema documentation only', 'Exit' ] }]); switch (action) { case 'Draft a new database schema from requirements': await this.draftDatabaseSchema(); break; case 'Provision Supabase backend with existing schema': await this.provisionSupabaseBackend(); break; case 'Complete workflow: Schema + Supabase deployment': await this.completeSchemaToDeployment(); break; case 'Generate schema documentation only': await this.generateSchemaDocumentation(); break; case 'Exit': console.log(chalk.blue('๐Ÿง™ Database Wizard: "Your database architecture awaits. Return when you need me!"')); return; } // Ask if they want to continue const { continue: shouldContinue } = await inquirer.prompt([{ type: 'confirm', name: 'continue', message: 'Would you like to do anything else with the database?', default: false }]); if (shouldContinue) { await this.databaseWizardConversation(); } } private async draftDatabaseSchema(): Promise { console.log(chalk.blue('\n๐Ÿง™ Database Wizard: "Let me help you design a robust database schema."')); // Collect requirements const requirements = await this.collectDatabaseRequirements(); // Generate schema const schemaContent = await this.generateSchemaFromRequirements(requirements); // Save schema file const projectRoot = this.projectState.getProjectRoot(); const schemaFile = await this.resourceManager.saveDocument( schemaContent, `schema-${Date.now()}.sql`, projectRoot ); // Generate documentation const documentation = await this.resourceManager.renderTemplate('schema-documentation', { project_name: requirements.project_name, schema_version: '1.0', created_date: new Date().toLocaleDateString(), database_type: 'PostgreSQL (Supabase)', total_tables: requirements.tables.length }); const docFile = await this.resourceManager.saveDocument( documentation, `schema-documentation-${Date.now()}.md`, projectRoot ); // Record artifacts await this.projectState.recordArtifact('database-schema', 'schema', schemaFile, 'Database Wizard'); await this.projectState.recordArtifact('schema-documentation', 'document', docFile, 'Database Wizard'); console.log(chalk.green(`\n๐ŸŽ‰ Database schema generated successfully!`)); console.log(chalk.blue(`๐Ÿ“„ Schema: ${schemaFile}`)); console.log(chalk.blue(`๐Ÿ“š Documentation: ${docFile}`)); console.log(chalk.yellow(`\n๐Ÿง™ Database Wizard: "Your schema is ready! Want me to provision a Supabase backend?"`)); } private async collectDatabaseRequirements(): Promise { console.log(chalk.yellow('\n๐Ÿ“‹ Let me gather your database requirements:')); const projectName = await inquirer.prompt([{ type: 'input', name: 'project_name', message: 'Project name:', validate: (input: string) => input.length > 2 ? true : 'Please provide a project name' }]); const coreEntities = await inquirer.prompt([{ type: 'input', name: 'entities', message: 'What are your core entities? (comma-separated, e.g., users, projects, tasks):', validate: (input: string) => input.includes(',') ? true : 'Please list at least 2 entities separated by commas' }]); const authRequirement = await inquirer.prompt([{ type: 'confirm', name: 'needs_auth', message: 'Does your app need user authentication?', default: true }]); const relationships = await inquirer.prompt([{ type: 'input', name: 'relationships', message: 'Describe key relationships (e.g., "users own projects, projects have tasks"):', validate: (input: string) => input.length > 10 ? true : 'Please describe the relationships' }]); const security = await inquirer.prompt([{ type: 'list', name: 'security_level', message: 'Security requirements:', choices: [ 'Basic (simple access control)', 'Standard (Row Level Security)', 'Advanced (Complex multi-tenant)', 'Enterprise (Audit trails + compliance)' ] }]); return { project_name: projectName.project_name, tables: coreEntities.entities.split(',').map((e: string) => e.trim()), needs_auth: authRequirement.needs_auth, relationships: relationships.relationships, security_level: security.security_level, rls_enabled: !security.security_level.includes('Basic') }; } private async generateSchemaFromRequirements(requirements: any): Promise { console.log(chalk.yellow('\n๐Ÿ”จ Generating database schema...')); // Use the database schema template const schemaContent = await this.resourceManager.renderTemplate('database-schema', { project_name: requirements.project_name, schema_version: '1.0', created_date: new Date().toLocaleDateString(), tables: requirements.tables.join(', '), auth_enabled: requirements.needs_auth, rls_enabled: requirements.rls_enabled }); return schemaContent; } private async provisionSupabaseBackend(): Promise { console.log(chalk.blue('\n๐Ÿง™ Database Wizard: "Let me provision your Supabase backend!"')); // Check if schema file exists const { schemaFile } = await inquirer.prompt([{ type: 'input', name: 'schemaFile', message: 'Path to your schema.sql file:', default: 'schema.sql', validate: async (input: string) => { const fs = await import('fs-extra'); const exists = await fs.pathExists(input); return exists ? true : 'Schema file not found. Please check the path.'; } }]); const { projectName } = await inquirer.prompt([{ type: 'input', name: 'projectName', message: 'Supabase project name:', validate: (input: string) => input.length > 2 ? true : 'Please provide a project name' }]); console.log(chalk.yellow('\n๐Ÿš€ Starting Supabase provisioning workflow...')); try { // Import the auth manager to use CLI commands const { AuthManager } = await import('./auth-manager'); const authManager = new AuthManager(); // Check authentication console.log(chalk.gray('๐Ÿ” Checking Supabase authentication...')); const isAuth = await authManager.isAuthenticated(); if (!isAuth) { console.log(chalk.yellow('๐Ÿ” Please authenticate with Supabase first...')); await authManager.authenticate(); } // List organizations for user to choose console.log(chalk.gray('๐Ÿข Fetching organizations...')); const orgs = await authManager.makeAuthenticatedRequest('/api/cli/supabase/organizations') as any[]; const { selectedOrg } = await inquirer.prompt([{ type: 'list', name: 'selectedOrg', message: 'Select organization:', choices: orgs.map((org: any) => ({ name: `${org.name} (${org.tier})`, value: org.id })) }]); const { dbPassword } = await inquirer.prompt([{ type: 'password', name: 'dbPassword', message: 'Database password:', mask: '*', validate: (input: string) => input.length >= 8 ? true : 'Password must be at least 8 characters' }]); // Create project console.log(chalk.gray('๐Ÿš€ Creating Supabase project...')); const project = await authManager.makeAuthenticatedRequest('/api/cli/supabase/provision', { method: 'POST', data: { name: projectName, organization_id: selectedOrg, region: 'us-east-1', db_pass: dbPassword } }) as any; console.log(chalk.green(`โœ… Project created: ${project.name} (${project.ref})`)); // Deploy schema console.log(chalk.gray('๐Ÿ“ฆ Deploying database schema...')); const fs = await import('fs-extra'); const schemaContent = await fs.readFile(schemaFile, 'utf8'); await authManager.makeAuthenticatedRequest('/api/cli/supabase/deploy-schema', { method: 'POST', data: { projectRef: project.ref, schema: schemaContent, schemaFile } }); console.log(chalk.green('โœ… Schema deployed successfully!')); // Generate environment file console.log(chalk.gray('โš™๏ธ Generating environment configuration...')); const envVars = await authManager.makeAuthenticatedRequest(`/api/cli/supabase/env/${project.ref}`); const envContent = Object.entries(envVars) .map(([key, value]) => `${key}=${value}`) .join('\n'); const projectRoot = this.projectState.getProjectRoot(); const envFile = await this.resourceManager.saveDocument( envContent, '.env.local', projectRoot ); // Record artifacts await this.projectState.recordArtifact('supabase-project', 'configuration', project.ref, 'Database Wizard'); await this.projectState.recordArtifact('environment-config', 'configuration', envFile, 'Database Wizard'); console.log(chalk.green(`\n๐ŸŽ‰ Supabase backend provisioned successfully!`)); console.log(chalk.blue(`๐Ÿ—„๏ธ Project: ${project.name} (${project.ref})`)); console.log(chalk.blue(`โš™๏ธ Environment: ${envFile}`)); console.log(chalk.blue(`๐ŸŒ URL: https://${project.ref}.supabase.co`)); console.log(chalk.yellow(`\n๐Ÿง™ Database Wizard: "Your backend is live and ready for development!"`)); } catch (error) { console.error(chalk.red(`โŒ Provisioning failed: ${error}`)); console.log(chalk.yellow('๐Ÿ’ก Make sure you have valid Supabase authentication')); } } private async completeSchemaToDeployment(): Promise { console.log(chalk.blue('\n๐Ÿง™ Database Wizard: "I\'ll guide you through the complete workflow!"')); console.log(chalk.yellow('\n๐Ÿ“‹ Step 1: Database Schema Design')); await this.draftDatabaseSchema(); const { proceedToDeploy } = await inquirer.prompt([{ type: 'confirm', name: 'proceedToDeploy', message: 'Schema created! Proceed to Supabase provisioning?', default: true }]); if (proceedToDeploy) { console.log(chalk.yellow('\n๐Ÿš€ Step 2: Supabase Backend Provisioning')); await this.provisionSupabaseBackend(); console.log(chalk.green('\n๐ŸŽ‰ Complete workflow finished!')); console.log(chalk.yellow('๐Ÿง™ Database Wizard: "From concept to live database - your backend is ready!"')); } } private async generateSchemaDocumentation(): Promise { console.log(chalk.blue('\n๐Ÿง™ Database Wizard: "I\'ll create comprehensive schema documentation."')); const { projectName } = await inquirer.prompt([{ type: 'input', name: 'projectName', message: 'Project name for documentation:', validate: (input: string) => input.length > 2 ? true : 'Please provide a project name' }]); const documentation = await this.resourceManager.renderTemplate('schema-documentation', { project_name: projectName, schema_version: '1.0', created_date: new Date().toLocaleDateString(), database_type: 'PostgreSQL (Supabase)', total_tables: '3' }); const projectRoot = this.projectState.getProjectRoot(); const docFile = await this.resourceManager.saveDocument( documentation, `database-documentation-${Date.now()}.md`, projectRoot ); await this.projectState.recordArtifact('database-documentation', 'document', docFile, 'Database Wizard'); console.log(chalk.green(`\n๐Ÿ“š Documentation generated: ${docFile}`)); console.log(chalk.yellow('๐Ÿง™ Database Wizard: "Your database documentation is ready for the team!"')); } private async genericConversation(): Promise { console.log(chalk.blue(`\n${this.resource.name}: Ready for interaction!`)); const { action } = await inquirer.prompt([{ type: 'list', name: 'action', message: 'What would you like to do?', choices: [ 'View capabilities', 'Start a task', 'Generate a document', 'Exit' ] }]); switch (action) { case 'View capabilities': console.log(chalk.blue('\nCapabilities:')); this.resource.capabilities.forEach(cap => { console.log(chalk.gray(` โ€ข ${cap}`)); }); break; case 'Start a task': console.log(chalk.yellow('Task workflows will be implemented next!')); break; case 'Generate a document': console.log(chalk.yellow('Document generation will be implemented next!')); break; case 'Exit': return; } } private async guideCurrentPhase(phase: string): Promise { const guidance: Record = { 'initialization': 'You\'re just getting started! First, validate your idea with The Gauntlet, then move to architecture with The Architect.', 'validation': 'Perfect! Work with The Gauntlet to challenge your assumptions and validate market demand.', 'architecture': 'Time to build your PRD! The Architect will help you create detailed technical specifications.', 'implementation': 'Ready to build! The Strategist will help choose your tech stack, and The Foreman will manage development.', 'deployment': 'Almost there! The Wizard will provision your backend and get you live.' }; console.log(chalk.magenta(`๐ŸŽญ The Mentor: "${guidance[phase] || 'Let me assess where you are and provide specific guidance.'}"`)); } private async recommendPersona(phase: string): Promise { const recommendations: Record = { 'initialization': ['The Gauntlet'], 'validation': ['The Gauntlet', 'The Architect'], 'architecture': ['The Architect'], 'implementation': ['The Strategist', 'The Foreman'], 'deployment': ['The Wizard'] }; const nextPersonas = recommendations[phase] || ['The Gauntlet']; console.log(chalk.magenta(`๐ŸŽญ The Mentor: "Based on your current phase, I recommend working with:"`)); nextPersonas.forEach(persona => { console.log(chalk.yellow(` โ€ข ${persona}`)); }); console.log(chalk.gray(`\nUse: vcsys ${nextPersonas[0].toLowerCase().replace('the ', '').replace(' ', '-')}`)); } private async showRoadmap(): Promise { console.log(chalk.magenta('๐ŸŽญ The Mentor: "Here\'s your journey through VC-SYS:"\n')); const roadmap = [ '1. ๐ŸฅŠ The Gauntlet - Validate your idea ruthlessly', '2. ๐Ÿ—๏ธ The Architect - Design your technical architecture', '3. ๐Ÿ“‹ The Strategist - Choose optimal tech stack', '4. ๐Ÿ‘ท The Foreman - Manage development workflow', '5. ๐Ÿง™ The Wizard - Provision backend and deploy', '6. ๐ŸŽ‰ Live Application - From idea to deployment!' ]; roadmap.forEach(step => console.log(chalk.blue(step))); } private async explainPersonas(): Promise { console.log(chalk.magenta('๐ŸŽญ The Mentor: "Let me explain each persona:"\n')); const personas = [ '๐ŸฅŠ The Gauntlet: Ruthlessly validates ideas and challenges assumptions', '๐Ÿ—๏ธ The Architect: Creates detailed PRDs and technical specifications', '๐Ÿ“‹ The Strategist: Recommends optimal boilerplates and tech stacks', '๐Ÿ‘ท The Foreman: Manages development tasks and workflows', '๐Ÿง™ The Wizard: Provisions Supabase backends and handles deployment' ]; personas.forEach(persona => console.log(chalk.blue(persona))); } private async runValidationChallenges(idea: string): Promise { const challenges = [ 'Who specifically has this problem?', 'How are they currently solving it?', 'Why is your solution better than existing alternatives?', 'How big is this market really?', 'What\'s your unfair advantage?' ]; console.log(chalk.red('\nโš”๏ธ The Gauntlet: "Answer these challenges:"')); for (let i = 0; i < challenges.length; i++) { const { answer } = await inquirer.prompt([{ type: 'input', name: 'answer', message: chalk.yellow(`${i + 1}. ${challenges[i]}`), validate: (input) => input.length > 5 ? true : 'Give me a real answer, not a cop-out.' }]); // Simple validation feedback if (answer.length < 20) { console.log(chalk.red(' โš ๏ธ Weak answer. Dig deeper.')); } else if (answer.includes('I think') || answer.includes('maybe')) { console.log(chalk.red(' โš ๏ธ Too many assumptions. Where\'s the evidence?')); } else { console.log(chalk.green(' โœ… Solid response.')); } } } private async architectConversation(): Promise { console.log(chalk.blue('\n๐Ÿ—๏ธ Launching The Architect AI Subagent with Technical Design Protocol...')); const config = await this.projectState.loadConfig(); const projectContext = await this.getProjectContext(config); // Create real AI persona with protocol integration const architectPersona = this.aiEngine.createArchitectPersona(projectContext); console.log(chalk.gray('๐Ÿค– Spawning technical architecture subagent...')); console.log(chalk.yellow(`๐Ÿ“‹ Expected artifacts: ${architectPersona.expectedArtifacts.join(', ')}`)); console.log(chalk.blue(`๐Ÿ” Requires validation: ${architectPersona.requiresValidation ? 'Yes' : 'No'}`)); try { // Launch actual AI subagent with architecture protocols await this.aiEngine.spawnPersona(architectPersona); // Record the AI interaction with architecture tracking await this.projectState.recordPersonaInteraction('The Architect', ['ai-subagent-conversation', 'architecture-protocol']); console.log(chalk.green('โœ… The Architect technical design completed with full artifact management')); console.log(chalk.blue('๐Ÿ—๏ธ "Your technical foundation is ready. Next, work with The Strategist for implementation planning."')); } catch (error) { console.log(chalk.red('โŒ Failed to spawn protocol-aware Architect subagent')); console.log(chalk.yellow('๐Ÿ’ก The AIPersonaEngine will show the architecture persona prompt')); // Fallback to original menu-based approach await this.fallbackArchitectConversation(); } } private async fallbackArchitectConversation(): Promise { console.log(chalk.yellow('๐Ÿ’ก Using fallback architecture system...')); console.log(chalk.blue('๐Ÿ—๏ธ The Architect: "Let\'s transform your validated concept into a comprehensive technical blueprint."')); const config = await this.projectState.loadConfig(); // Check if validation has been completed const hasValidation = Object.keys(config.artifacts).some(artifact => artifact.includes('validation') || config.personas['The Gauntlet'] ); if (!hasValidation) { console.log(chalk.yellow('๐Ÿ—๏ธ The Architect: "I recommend completing idea validation with The Gauntlet first."')); console.log(chalk.gray(' Run: vcsys gauntlet')); return; } const choices = [ 'Generate a comprehensive PRD', 'Design technical architecture only', 'Create user stories and requirements', 'Review existing validation results', 'Exit conversation' ]; const { action } = await inquirer.prompt([{ type: 'list', name: 'action', message: 'What architectural work do you need?', choices }]); switch (action) { case 'Generate a comprehensive PRD': await this.generateComprehensivePRD(); break; case 'Design technical architecture only': await this.designTechnicalArchitecture(); break; case 'Create user stories and requirements': await this.createUserStories(); break; case 'Review existing validation results': await this.reviewValidationResults(); break; case 'Exit conversation': console.log(chalk.blue('๐Ÿ—๏ธ The Architect: "Your technical foundation is ready. Next, work with The Strategist for implementation planning."')); return; } // Ask if they want to continue const { continue: shouldContinue } = await inquirer.prompt([{ type: 'confirm', name: 'continue', message: 'Would you like to continue working on architecture?', default: false }]); if (shouldContinue) { await this.architectConversation(); } else { console.log(chalk.blue('๐Ÿ—๏ธ The Architect: "Excellent work! Your technical architecture is solid. Use \'vcsys strategist\' for the next phase."')); } } private async generateComprehensivePRD(): Promise { console.log(chalk.blue('\n๐Ÿ—๏ธ The Architect: "I\'ll guide you through creating a comprehensive PRD. This will take 15-20 minutes."')); // Phase 1: Project Overview console.log(chalk.yellow('\n๐Ÿ“‹ Phase 1: Project Overview')); const projectOverview = await this.collectProjectOverview(); // Phase 2: User Personas console.log(chalk.yellow('\n๐Ÿ‘ฅ Phase 2: User Personas')); const userPersonas = await this.collectUserPersonas(); // Phase 3: Requirements console.log(chalk.yellow('\nโš™๏ธ Phase 3: Requirements')); const requirements = await this.collectRequirements(); // Phase 4: Technical Architecture console.log(chalk.yellow('\n๐Ÿ›๏ธ Phase 4: Technical Architecture')); const architecture = await this.collectTechnicalArchitecture(); // Phase 5: Planning console.log(chalk.yellow('\n๐Ÿ“… Phase 5: Planning')); const planning = await this.collectPlanning(); // Generate the PRD await this.compilePRDDocument(projectOverview, userPersonas, requirements, architecture, planning); } private async collectProjectOverview(): Promise> { const questions = [ { type: 'input', name: 'vision_statement', message: 'What is your product vision in one sentence?', validate: (input: string) => input.length > 20 ? true : 'Please provide a more detailed vision statement' }, { type: 'input', name: 'problem_definition', message: 'Describe the core problem you\'re solving:', validate: (input: string) => input.length > 30 ? true : 'Please provide more detail about the problem' }, { type: 'input', name: 'target_market', message: 'Who is your target market?', validate: (input: string) => input.length > 10 ? true : 'Please be more specific about your target market' }, { type: 'input', name: 'solution_approach', message: 'How will you solve this problem? (high-level approach)', validate: (input: string) => input.length > 20 ? true : 'Please provide more detail about your approach' } ]; return await inquirer.prompt(questions); } private async collectUserPersonas(): Promise> { console.log(chalk.gray('Define your primary user persona:')); const primaryPersona = await inquirer.prompt([ { type: 'input', name: 'name', message: 'Primary persona name/title:', default: 'Primary User' }, { type: 'input', name: 'demographics', message: 'Demographics (age, role, industry):', validate: (input: string) => input.length > 10 ? true : 'Please provide demographic details' }, { type: 'input', name: 'goals', message: 'What are their primary goals?', validate: (input: string) => input.length > 15 ? true : 'Please describe their goals in more detail' }, { type: 'input', name: 'pain_points', message: 'What are their biggest pain points?', validate: (input: string) => input.length > 15 ? true : 'Please describe their pain points in more detail' }, { type: 'list', name: 'tech_level', message: 'Technical proficiency level:', choices: ['Beginner', 'Intermediate', 'Advanced', 'Expert'] } ]); return { primary_persona_name: primaryPersona.name, primary_persona_demographics: primaryPersona.demographics, primary_persona_goals: primaryPersona.goals, primary_persona_pain_points: primaryPersona.pain_points, primary_persona_tech_level: primaryPersona.tech_level, primary_persona_devices: 'Desktop, Mobile, Tablet' // Default }; } private async collectRequirements(): Promise> { const questions = [ { type: 'input', name: 'core_features', message: 'List your core features (comma-separated):', validate: (input: string) => input.includes(',') ? true : 'Please list at least 2 core features separated by commas' }, { type: 'input', name: 'user_management_features', message: 'What user management features do you need? (registration, profiles, etc.):', default: 'User registration, login, profile management' }, { type: 'input', name: 'integration_requirements', message: 'What third-party integrations are required?', default: 'Authentication (OAuth), Payment processing, Email services' }, { type: 'input', name: 'concurrent_users_requirement', message: 'Expected concurrent users at scale:', default: '10,000' }, { type: 'input', name: 'response_time_requirement', message: 'Target API response time:', default: '<200ms' } ]; return await inquirer.prompt(questions); } private async collectTechnicalArchitecture(): Promise> { const questions = [ { type: 'list', name: 'architecture_pattern', message: 'Preferred architecture pattern:', choices: ['Monolithic (simple, fast to build)', 'Microservices (scalable, complex)', 'Serverless (cost-effective, auto-scaling)', 'Hybrid (best of both)'] }, { type: 'input', name: 'frontend_technologies', message: 'Frontend technology preferences:', default: 'React, TypeScript, Tailwind CSS' }, { type: 'input', name: 'backend_technologies', message: 'Backend technology preferences:', default: 'Node.js, Express, TypeScript' }, { type: 'list', name: 'database_choice', message: 'Primary database choice:', choices: ['PostgreSQL (relational)', 'MongoDB (document)', 'MySQL (relational)', 'Supabase (PostgreSQL + Auth)', 'Firebase (NoSQL + Auth)'] }, { type: 'input', name: 'infrastructure_technologies', message: 'Deployment and infrastructure preferences:', default: 'Vercel, AWS, Docker' } ]; const responses = await inquirer.prompt(questions); return { ...responses, database_technologies: responses.database_choice, third_party_services: 'Authentication, Payment processing, Email services, Analytics' }; } private async collectPlanning(): Promise> { const questions = [ { type: 'input', name: 'project_timeline', message: 'Target timeline for MVP:', default: '3-6 months' }, { type: 'input', name: 'key_milestones', message: 'Key milestones (comma-separated):', default: 'MVP launch, Beta testing, Public launch, Feature expansion' }, { type: 'input', name: 'success_metrics', message: 'Key success metrics:', default: 'User acquisition, retention rate, revenue growth' }, { type: 'input', name: 'dependencies_and_risks', message: 'Major dependencies or risks:', default: 'Third-party API availability, market validation, team scaling' } ]; return await inquirer.prompt(questions); } private async compilePRDDocument(overview: any, personas: any, requirements: any, architecture: any, planning: any): Promise { console.log(chalk.yellow('\n๐Ÿ“„ Compiling comprehensive PRD...')); try { const config = await this.projectState.loadConfig(); // Combine all collected data into template variables const variables = { project_name: config.name, current_date: new Date().toLocaleDateString(), prd_version: '1.0', prd_status: 'Draft', // Project overview vision_statement: overview.vision_statement, problem_definition: overview.problem_definition, target_market: overview.target_market, solution_approach: overview.solution_approach, problem_summary: overview.problem_definition, // User personas ...personas, // Requirements core_features: requirements.core_features, user_management_features: requirements.user_management_features, integration_requirements: requirements.integration_requirements, concurrent_users_requirement: requirements.concurrent_users_requirement, response_time_requirement: requirements.response_time_requirement, // Architecture architecture_pattern: architecture.architecture_pattern, frontend_technologies: architecture.frontend_technologies, backend_technologies: architecture.backend_technologies, database_technologies: architecture.database_technologies, infrastructure_technologies: architecture.infrastructure_technologies, third_party_services: architecture.third_party_services, // Planning project_timeline: planning.project_timeline, key_milestones: planning.key_milestones, success_metrics: planning.success_metrics, dependencies_and_risks: planning.dependencies_and_risks, // Default values for comprehensive template current_state_description: 'Current solutions are inadequate or non-existent', problem_impact: 'Significant impact on user productivity and satisfaction', urgency_rationale: 'Market opportunity and competitive advantage', key_differentiators: 'Unique approach, better UX, superior technology', solution_benefits: 'Improved efficiency, cost savings, better outcomes', // Technical defaults system_components: 'Frontend, Backend API, Database, Authentication, External integrations', deployment_architecture: 'Cloud-native deployment with horizontal scaling capabilities', data_models: 'User, Project, Task, Analytics data models', key_entities: 'Users, Projects, Tasks, Organizations', entity_relationships: 'One-to-many and many-to-many relationships between core entities', // Additional defaults for completeness scalability_requirements: 'Horizontal scaling to support 100K+ users', security_requirements: 'HTTPS, data encryption, secure authentication', performance_targets: '<200ms API response, <3s page load times', testing_approach: 'Unit testing, integration testing, end-to-end testing', deployment_strategy: 'CI/CD pipeline with automated testing and deployment' }; const prdDocument = await this.resourceManager.renderTemplate('comprehensive-prd', variables); // Save document to file system const projectRoot = this.projectState.getProjectRoot(); const filename = `comprehensive-prd-${Date.now()}.md`; const filePath = await this.resourceManager.saveDocument(prdDocument, filename, projectRoot); // Record in project state await this.projectState.recordArtifact( 'comprehensive-prd', 'document', filePath.replace(projectRoot + '/', ''), 'The Architect' ); // Update project phase await this.projectState.updatePhase('architecture'); console.log(chalk.green(`\n๐ŸŽ‰ Comprehensive PRD generated successfully!`)); console.log(chalk.blue(`๐Ÿ“„ Document: ${filename}`)); console.log(chalk.gray(`๐Ÿ“ Location: ${filePath}`)); console.log(chalk.yellow(`\n๐Ÿ—๏ธ The Architect: "Your PRD is complete! Next, work with The Strategist to choose your tech stack."`)); console.log(chalk.gray(` Run: vcsys strategist`)); } catch (error) { console.log(chalk.red(`โŒ Failed to generate PRD: ${error}`)); } } private async designTechnicalArchitecture(): Promise { console.log(chalk.blue('\n๐Ÿ—๏ธ The Architect: "Let\'s focus on your technical architecture design."')); console.log(chalk.yellow('(Technical architecture design will be implemented next)')); } private async createUserStories(): Promise { console.log(chalk.blue('\n๐Ÿ—๏ธ The Architect: "Let\'s map out your user stories and requirements."')); console.log(chalk.yellow('(User story mapping will be implemented next)')); } private async reviewValidationResults(): Promise { console.log(chalk.blue('\n๐Ÿ—๏ธ The Architect: "Let me review your existing validation results."')); const config = await this.projectState.loadConfig(); if (Object.keys(config.artifacts).length === 0) { console.log(chalk.yellow('No validation artifacts found. Run \'vcsys gauntlet\' first.')); return; } console.log(chalk.green('\nFound validation artifacts:')); Object.entries(config.artifacts).forEach(([name, artifact]) => { console.log(chalk.gray(` โ€ข ${name} (${artifact.type}) - created by ${artifact.createdBy}`)); }); } private async generateValidationReport(idea: string): Promise { console.log(chalk.yellow('\n๐Ÿ“„ Generating validation report...')); try { const variables = { project_name: idea, current_date: new Date().toLocaleDateString(), current_phase: 'validation', idea_summary: idea, validation_status: 'NEEDS_WORK', key_findings: 'โ€ข Market validation required\nโ€ข Competitive analysis needed\nโ€ข Business model unclear', problem_statement: 'To be defined through user research', target_market: 'To be identified through market analysis', problem_evidence: 'Evidence collection needed', proposed_solution: idea, competitive_analysis: 'Competitive research required', differentiation_factors: 'Unique value proposition to be developed', market_size: 'Market sizing analysis needed', gtm_strategy: 'Go-to-market strategy to be developed', revenue_model: 'Business model validation required', key_assumptions: 'Core assumptions to be tested', risk_factors: 'Risk assessment to be conducted', mitigation_strategies: 'Risk mitigation plans needed', overall_assessment: 'Requires further validation and development', next_steps: '1. Conduct user interviews\n2. Analyze competitors\n3. Develop MVP', success_metrics: 'Success metrics to be defined', research_sources: 'Primary and secondary research needed', validation_framework: 'Lean Startup methodology' }; const report = await this.resourceManager.renderTemplate('validation-report', variables); // Save document to file system const projectRoot = this.projectState.getProjectRoot(); const filename = `validation-report-${Date.now()}.md`; const filePath = await this.resourceManager.saveDocument(report, filename, projectRoot); // Record in project state await this.projectState.recordArtifact( 'validation-report', 'document', filePath.replace(projectRoot + '/', ''), 'The Gauntlet' ); console.log(chalk.green(`โœ… Validation report generated: ${filename}`)); console.log(chalk.gray(`๐Ÿ“ Saved to: ${filePath}`)); } catch (error) { console.log(chalk.red(`โŒ Failed to generate report: ${error}`)); } } async validate(input?: string): Promise { console.log(chalk.bold(`\nโš”๏ธ ${this.resource.name}: Starting validation...`)); if (input) { console.log(chalk.yellow(`Input: "${input}"`)); // Simulate validation process console.log(chalk.gray('๐Ÿ” Analyzing assumptions...')); console.log(chalk.gray('๐ŸŽฏ Identifying pain points...')); console.log(chalk.gray('๐Ÿ“Š Evaluating market potential...')); await this.projectState.recordPersonaInteraction(this.resource.name, ['validation-session']); console.log(chalk.green('\nโœ… Validation complete! (Simulated for Phase 1)')); console.log(chalk.gray('Full validation logic will be implemented in upcoming phases.')); } else { console.log(chalk.yellow('๐Ÿ’ก No input provided. Interactive validation coming in Phase 1!')); } } async generateDocument(templateName: string, variables: Record): Promise { try { const document = await this.resourceManager.renderTemplate(templateName, variables); await this.projectState.recordPersonaInteraction(this.resource.name, [templateName]); return document; } catch (error) { throw new Error(`Failed to generate document: ${error}`); } } getName(): string { return this.resource.name; } getCapabilities(): string[] { return this.resource.capabilities; } } export class PersonaManager { private loadedPersonas: Map = new Map(); private projectState: ProjectState; private aiEngine: AIPersonaEngine; constructor(private resourceManager: ResourceManager) { this.projectState = new ProjectState(); this.aiEngine = new AIPersonaEngine(); } async loadPersona(personaName: string): Promise { // Check if persona is already loaded if (this.loadedPersonas.has(personaName)) { return this.loadedPersonas.get(personaName)!; } try { // Load persona resource const personaResource = await this.resourceManager.loadPersona(personaName); // Create persona instance const persona = new Persona(personaResource, this.resourceManager, this.projectState); // Cache the persona this.loadedPersonas.set(personaName, persona); console.log(chalk.green(`โœ… Loaded persona: ${personaResource.name}`)); return persona; } catch (error) { throw new Error(`Failed to load persona '${personaName}': ${error}`); } } async listAvailablePersonas(): Promise { try { return await this.resourceManager.listAvailablePersonas(); } catch (error) { console.warn(chalk.yellow('โš ๏ธ Could not list personas - resources not yet created')); return []; } } async switchPersona(personaName: string): Promise { console.log(chalk.blue(`๐Ÿ”„ Switching to persona: ${personaName}`)); return await this.loadPersona(personaName); } async getPersonaRecommendation(projectPhase: string): Promise { const recommendations: Record = { 'initialization': ['the-mentor'], 'validation': ['the-gauntlet', 'the-mentor'], 'architecture': ['the-architect', 'the-mentor'], 'implementation': ['the-strategist', 'the-foreman'], 'deployment': ['the-wizard', 'the-mentor'] }; return recommendations[projectPhase] || ['the-mentor']; } async getCurrentPersona(): Promise { if (this.loadedPersonas.size === 0) { return null; } // Return the most recently loaded persona const personaNames = Array.from(this.loadedPersonas.keys()); const lastPersonaName = personaNames[personaNames.length - 1]; return this.loadedPersonas.get(lastPersonaName) || null; } async orchestratePersonaFlow(startingPersona: string, goal: string): Promise { console.log(chalk.bold(`\n๐ŸŽฏ Starting persona orchestration for: ${goal}`)); console.log(chalk.gray(`Initial persona: ${startingPersona}`)); // This will be implemented in Phase 1 - orchestration logic // For now, just load the starting persona const persona = await this.loadPersona(startingPersona); await persona.interact(); console.log(chalk.yellow('\n๐Ÿ’ก Full persona orchestration will be implemented in Phase 1')); console.log(chalk.gray('This will include automatic persona switching based on project needs.')); } clearCache(): void { this.loadedPersonas.clear(); console.log(chalk.gray('๐Ÿงน Persona cache cleared')); } }