import { Task as TaskToolTask } from '../tools/task-tool'; import { BaseSubagentProtocol, SubagentProtocolFactory, SubagentContext, ValidationResult } from '../protocols/subagent-protocols'; import { ArtifactManager } from './artifact-manager'; import { ProjectState } from './project-state'; import chalk from 'chalk'; /** * Enhanced AI Persona Engine - Spawns protocol-aware AI subagents * * This is the core engine that transforms our CLI from menu-based interactions * to real AI conversations using Task tool subagents with strict artifact management. * * Key Features: * - Real AI conversations using Task tool subagents * - Strict artifact management protocols * - Automatic validation and quality gates * - Cross-persona handoffs with context preservation */ export interface AIPersonaConfig { name: string; role: string; personality: string; expertise: string[]; capabilities: string[]; systemPrompt: string; conversationStarter: string; projectContext: string; // Enhanced with protocol integration protocolEnabled: boolean; expectedArtifacts: string[]; requiresValidation: boolean; } export class AIPersonaEngine { private taskTool: Task; private projectState: ProjectState; private artifactManager: ArtifactManager; constructor(projectState?: ProjectState) { this.taskTool = new Task(); this.projectState = projectState || new ProjectState(); this.artifactManager = new ArtifactManager(this.projectState); } /** * Enhanced persona spawning with protocol integration * This creates real AI conversations with strict artifact management */ async spawnPersona(personaConfig: AIPersonaConfig): Promise { console.log(chalk.blue(`šŸš€ Launching ${personaConfig.name} AI Subagent with Protocol Management...`)); let protocol: BaseSubagentProtocol | null = null; // Initialize protocol if enabled if (personaConfig.protocolEnabled) { protocol = await this.initializeProtocol(personaConfig); if (!protocol) { console.log(chalk.yellow(`āš ļø No protocol found for ${personaConfig.name}, continuing without artifact management`)); } } // Build comprehensive persona prompt with protocol integration const personaPrompt = this.buildProtocolAwarePrompt(personaConfig, protocol); try { // Pre-spawn validation if protocol is enabled if (protocol) { const validation = await protocol.validatePrerequisites(); if (!validation.valid) { console.log(chalk.red('āŒ Prerequisites validation failed:')); validation.errors.forEach(error => console.log(chalk.red(` • ${error}`))); validation.blockers.forEach(blocker => console.log(chalk.red(` 🚫 ${blocker}`))); return; } if (validation.warnings.length > 0) { console.log(chalk.yellow('āš ļø Warnings:')); validation.warnings.forEach(warning => console.log(chalk.yellow(` • ${warning}`))); } } // Spawn the AI subagent with enhanced prompt console.log(chalk.gray('šŸ“” Creating protocol-aware Claude Code conversation...')); await this.taskTool.spawn({ subagent_type: 'general-purpose', description: `${personaConfig.name} Protocol-Aware AI Conversation`, prompt: personaPrompt }); // Post-spawn protocol processing if (protocol) { await this.executePostSpawnProtocol(protocol, personaConfig); } console.log(chalk.green(`āœ… ${personaConfig.name} conversation completed with artifact management`)); } catch (error) { console.error(chalk.red(`āŒ Failed to spawn ${personaConfig.name}:`), error); await this.handleSpawnFailure(personaConfig, protocol, error); } } /** * Initialize protocol for the persona */ private async initializeProtocol(config: AIPersonaConfig): Promise { try { const protocol = SubagentProtocolFactory.createProtocol(config.name); const context: SubagentContext = { projectState: this.projectState, artifactManager: this.artifactManager, sessionId: this.generateSessionId(), userContext: config.projectContext }; await protocol.initialize(context); console.log(chalk.green(`āœ… Initialized ${config.name} protocol with artifact management`)); return protocol; } catch (error) { console.log(chalk.yellow(`āš ļø Failed to initialize protocol for ${config.name}: ${error}`)); return null; } } /** * Execute post-spawn protocol operations */ private async executePostSpawnProtocol(protocol: BaseSubagentProtocol, config: AIPersonaConfig): Promise { try { console.log(chalk.blue('šŸ”„ Executing post-conversation protocol operations...')); // Execute core protocol logic const executionResult = await protocol.executeCore(); if (executionResult.success) { // Create artifacts console.log(chalk.yellow('šŸ“¦ Creating artifacts...')); const artifactResults = await protocol.createArtifacts(); // Report artifact creation results artifactResults.forEach(result => { if (result.status === 'created') { console.log(chalk.green(` āœ… ${result.type}: ${result.message}`)); } else if (result.status === 'failed') { console.log(chalk.red(` āŒ ${result.type}: ${result.message}`)); } }); // Validate outputs const outputValidation = await protocol.validateOutputs(); if (!outputValidation.valid) { console.log(chalk.red('āŒ Output validation failed:')); outputValidation.errors.forEach(error => console.log(chalk.red(` • ${error}`))); } // Prepare handoff const handoff = await protocol.handoffToNext(); console.log(chalk.blue(`šŸ”„ Next recommended persona: ${handoff.nextPersona}`)); console.log(chalk.gray(` Context: ${handoff.context}`)); console.log(chalk.gray(` Instructions: ${handoff.instructions}`)); } else { console.log(chalk.red('āŒ Protocol execution failed')); } // Cleanup await protocol.cleanup(); } catch (error) { console.log(chalk.red(`āŒ Post-spawn protocol execution failed: ${error}`)); } } /** * Handle spawn failures with protocol cleanup */ private async handleSpawnFailure(config: AIPersonaConfig, protocol: BaseSubagentProtocol | null, error: any): Promise { // Cleanup protocol if it was initialized if (protocol) { try { await protocol.cleanup(); } catch (cleanupError) { console.log(chalk.red(`āŒ Protocol cleanup failed: ${cleanupError}`)); } } // Show fallback options const personaPrompt = this.buildProtocolAwarePrompt(config, protocol); console.log(chalk.yellow('\nšŸ’” FALLBACK: Protocol-aware prompt for manual use:')); console.log(chalk.gray('─'.repeat(80))); console.log(personaPrompt); console.log(chalk.gray('─'.repeat(80))); } /** * Generate unique session ID */ private generateSessionId(): string { return `session-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`; } /** * Build protocol-aware persona prompt */ private buildProtocolAwarePrompt(config: AIPersonaConfig, protocol: BaseSubagentProtocol | null): string { const basePrompt = this.buildPersonaPrompt(config); if (!protocol) { return basePrompt; } // Add protocol-specific instructions const protocolInstructions = ` ## ARTIFACT MANAGEMENT PROTOCOL You MUST follow these strict artifact creation and management protocols: ### MANDATORY ARTIFACT CREATION You are required to create the following artifacts during this conversation: ${config.expectedArtifacts.map(artifact => `• ${artifact}`).join('\n')} ### ARTIFACT CREATION RULES 1. **Use Structured Format**: All artifacts must include metadata headers with ID, type, creator, timestamp 2. **Follow Naming Conventions**: Use lowercase alphanumeric names with hyphens (e.g., "project-roadmap") 3. **Track Dependencies**: Specify which artifacts depend on others 4. **Validate Content**: Ensure artifacts meet quality standards for their type 5. **Update Status**: Mark artifacts as draft → review → approved through the workflow ### PROTOCOL WORKFLOW 1. **Validate Prerequisites**: Check that required input artifacts exist and are approved 2. **Execute Core Logic**: Perform your specialized persona work 3. **Create Required Artifacts**: Generate all mandatory artifacts with proper metadata 4. **Validate Outputs**: Ensure all required artifacts were created successfully 5. **Prepare Handoff**: Provide context and instructions for the next persona ### ARTIFACT TYPES AND STANDARDS - **validation-report**: Must be >500 characters, include market analysis - **prd-document**: Must start with "# Product Requirements Document", depend on validation - **technical-architecture**: Must depend on PRD, include system design - **project-roadmap**: Strategic guidance with phase progression - **concept-brief**: Validated idea summary with key findings ### INTEGRATION COMMANDS During the conversation, you can: - Create artifacts: Specify artifact name, type, content, and dependencies - Update project state: Record interactions and progress - Generate documents: Use templates with proper variable substitution - Validate inputs: Check prerequisites before proceeding Remember: You are not just having a conversation - you are systematically creating managed artifacts that will be used by other personas in the workflow.`; return basePrompt + protocolInstructions; } /** * Build comprehensive persona prompt based on BMad Method architecture */ private buildPersonaPrompt(config: AIPersonaConfig): string { return `# ${config.name} - VC-SYS AI Persona ## PERSONA ACTIVATION You are now ${config.name}, ${config.role} for the VC-SYS system. CRITICAL: You must fully embody this persona throughout the entire conversation. Stay in character, use the specified personality, and apply your expertise consistently. ## YOUR IDENTITY **Role**: ${config.role} **Personality**: ${config.personality} **Core Expertise**: ${config.expertise.join(', ')} ## YOUR CAPABILITIES ${config.capabilities.map(cap => `• ${cap}`).join('\n')} ## CURRENT PROJECT CONTEXT ${config.projectContext} ## YOUR BEHAVIOR GUIDELINES 1. **Stay In Character**: Embody the persona completely - think, speak, and act as this specialized expert 2. **Apply Expertise**: Use your domain knowledge to provide valuable, specific insights 3. **Be Conversational**: Engage naturally while maintaining your professional expertise 4. **Ask Questions**: Gather information needed to provide the best guidance 5. **Provide Value**: Focus on actionable advice and concrete next steps 6. **Use Tools**: Generate documents, update project state, and create artifacts as needed ## CONVERSATION STARTER ${config.conversationStarter} ## SYSTEM INTEGRATION - You can access and update project state - You can generate documents using templates - You can create artifacts and track progress - You can recommend next steps and persona handoffs Begin the conversation now as ${config.name}. Greet the user and start helping them with their project.`; } /** * Create The Mentor AI Persona Configuration with Protocol Integration */ createMentorPersona(projectContext: string): AIPersonaConfig { return { name: 'The Mentor', role: 'Master Orchestrator and Strategic Guide', personality: 'Supportive, wise, strategic thinker who sees the big picture', expertise: ['Project strategy', 'Persona orchestration', 'Development workflows', 'Business guidance'], capabilities: [ 'Strategic project guidance and roadmap planning', 'Persona orchestration and intelligent routing', 'Context-aware advice based on project phase', 'Educational mentorship for founders' ], systemPrompt: 'You are the master guide who helps founders navigate their entire development journey.', conversationStarter: 'Welcome! I\'m The Mentor, your strategic guide through the VC-SYS journey. I can see you\'re working on this project, and I\'m here to help you navigate the path from idea to deployed application. What specific guidance do you need today?', projectContext, // Protocol integration protocolEnabled: true, expectedArtifacts: ['project-roadmap'], requiresValidation: false }; } /** * Create The Gauntlet AI Persona Configuration with Protocol Integration */ createGauntletPersona(projectContext: string): AIPersonaConfig { return { name: 'The Gauntlet', role: 'Ruthless Idea Validator and Challenge Master', personality: 'Direct, challenging, constructively critical - doesn\'t coddle but genuinely wants you to succeed', expertise: ['Market validation', 'Business model analysis', 'Competitive research', 'Problem-solution fit'], capabilities: [ 'Systematic idea validation using proven frameworks', 'Market analysis and competitive landscape assessment', 'Problem-solution fit evaluation', 'Business model validation' ], systemPrompt: 'You challenge assumptions ruthlessly but constructively, forcing founders to think critically about their ideas.', conversationStarter: 'Time to put your idea through the fire! I don\'t coddle - I validate. I see you\'re working on something, and I\'m here to challenge every assumption and make sure you\'re building something people actually want. What\'s your idea, and are you ready to defend it?', projectContext, // Protocol integration protocolEnabled: true, expectedArtifacts: ['validation-report', 'concept-brief'], requiresValidation: false }; } /** * Create The Architect AI Persona Configuration with Protocol Integration */ createArchitectPersona(projectContext: string): AIPersonaConfig { return { name: 'The Architect', role: 'Master Technical Architect and System Designer', personality: 'Systematic, methodical, technically brilliant but practical', expertise: ['System architecture', 'Technical specifications', 'Database design', 'API planning', 'Scalability'], capabilities: [ 'Comprehensive PRD generation from validated concepts', 'Technical architecture design and system planning', 'Database schema design and data modeling', 'API specification and integration planning' ], systemPrompt: 'You transform validated ideas into comprehensive technical architectures and detailed PRDs.', conversationStarter: 'Let\'s transform your validated concept into a comprehensive technical blueprint. I can see your project context, and I\'m ready to design the architecture that will bring your vision to life. Shall we start with understanding your technical requirements?', projectContext, // Protocol integration protocolEnabled: true, expectedArtifacts: ['prd-document', 'technical-architecture'], requiresValidation: true // Architect requires validation-report to proceed }; } } /** * Task Tool Interface for spawning subagents */ class Task { async spawn(config: { subagent_type: string; description: string; prompt: string; }): Promise { // This would integrate with Claude Code's Task tool // For now, we'll throw an error to show the integration point throw new Error('Task tool integration needed - this is where real AI subagents would spawn'); } }