import { ArtifactManager, ArtifactType } from '../core/artifact-manager'; import { ProjectState } from '../core/project-state'; /** * Subagent Protocols - Strict protocols for AI persona behavior * * Defines mandatory protocols that every AI subagent must follow: * - Asset creation and tracking requirements * - State management obligations * - Handoff procedures between personas * - Quality gates and validation checkpoints */ export interface SubagentProtocol { // Identity and capabilities readonly personaName: string; readonly primaryArtifacts: ArtifactType[]; readonly secondaryArtifacts: ArtifactType[]; readonly requiredInputs: ArtifactType[]; // Behavioral protocols initialize(context: SubagentContext): Promise; validatePrerequisites(): Promise; executeCore(): Promise; createArtifacts(): Promise; validateOutputs(): Promise; handoffToNext(): Promise; cleanup(): Promise; } export interface SubagentContext { projectState: ProjectState; artifactManager: ArtifactManager; sessionId: string; userContext: string; parentPersona?: string; } export interface ValidationResult { valid: boolean; errors: string[]; warnings: string[]; blockers: string[]; } export interface ExecutionResult { success: boolean; outputs: string[]; artifacts: string[]; nextSteps: string[]; recommendedPersona?: string; } export interface ArtifactCreationResult { artifactId: string; type: ArtifactType; status: 'created' | 'updated' | 'failed'; message: string; } export interface HandoffResult { nextPersona: string; context: string; artifacts: string[]; instructions: string; } /** * Base Protocol Implementation - All AI personas must extend this */ export abstract class BaseSubagentProtocol implements SubagentProtocol { abstract readonly personaName: string; abstract readonly primaryArtifacts: ArtifactType[]; abstract readonly secondaryArtifacts: ArtifactType[]; abstract readonly requiredInputs: ArtifactType[]; protected context!: SubagentContext; protected executionLog: string[] = []; async initialize(context: SubagentContext): Promise { this.context = context; this.executionLog = []; this.log(`Initializing ${this.personaName} subagent`); // Register session with project state await context.projectState.recordPersonaInteraction(this.personaName, [`session-${context.sessionId}`]); } async validatePrerequisites(): Promise { this.log('Validating prerequisites'); const errors: string[] = []; const warnings: string[] = []; const blockers: string[] = []; // Check required input artifacts exist for (const requiredType of this.requiredInputs) { const artifacts = this.context.artifactManager.getArtifactsByType(requiredType); const approvedArtifacts = artifacts.filter(a => a.status === 'approved'); if (approvedArtifacts.length === 0) { blockers.push(`Missing required input: ${requiredType} (status: approved)`); } } // Custom validation for specific personas const customValidation = await this.validatePersonaSpecific(); errors.push(...customValidation.errors); warnings.push(...customValidation.warnings); blockers.push(...customValidation.blockers); return { valid: errors.length === 0 && blockers.length === 0, errors, warnings, blockers }; } abstract executeCore(): Promise; abstract createArtifacts(): Promise; abstract validatePersonaSpecific(): Promise; async validateOutputs(): Promise { this.log('Validating outputs'); const errors: string[] = []; const warnings: string[] = []; // Check that all primary artifacts were created for (const primaryType of this.primaryArtifacts) { const artifacts = this.context.artifactManager.getArtifactsByType(primaryType); const recentArtifacts = artifacts.filter(a => a.creator === this.personaName && new Date(a.createdAt) > new Date(Date.now() - 3600000) // Created within last hour ); if (recentArtifacts.length === 0) { errors.push(`Failed to create required primary artifact: ${primaryType}`); } } return { valid: errors.length === 0, errors, warnings, blockers: [] }; } async handoffToNext(): Promise { this.log('Preparing handoff to next persona'); const nextPersona = this.determineNextPersona(); const artifacts = this.getCreatedArtifacts(); const context = this.buildHandoffContext(); const instructions = this.buildHandoffInstructions(nextPersona); return { nextPersona, context, artifacts, instructions }; } async cleanup(): Promise { this.log('Cleaning up subagent session'); // Archive any draft artifacts that weren't finalized const drafts = this.context.artifactManager.getAllArtifacts() .filter(a => a.creator === this.personaName && a.status === 'draft'); for (const draft of drafts) { await this.context.artifactManager.updateArtifactStatus( draft.id, 'archived', this.personaName ); } } protected log(message: string): void { const timestamp = new Date().toISOString(); this.executionLog.push(`[${timestamp}] ${this.personaName}: ${message}`); } protected abstract determineNextPersona(): string; protected abstract getCreatedArtifacts(): string[]; protected abstract buildHandoffContext(): string; protected abstract buildHandoffInstructions(nextPersona: string): string; } /** * Specific Protocol Implementations */ export class MentorProtocol extends BaseSubagentProtocol { readonly personaName = 'The Mentor'; readonly primaryArtifacts: ArtifactType[] = ['project-roadmap']; readonly secondaryArtifacts: ArtifactType[] = ['persona-definition']; readonly requiredInputs: ArtifactType[] = []; // Mentor can start without prerequisites async executeCore(): Promise { this.log('Executing mentor guidance session'); // Mentor provides strategic guidance and persona routing return { success: true, outputs: [ 'Strategic project guidance provided', 'Persona routing recommendations generated', 'Project roadmap created' ], artifacts: [], // Will be populated by createArtifacts() nextSteps: [ 'Begin idea validation with The Gauntlet', 'Continue with recommended persona workflow' ], recommendedPersona: 'The Gauntlet' }; } async createArtifacts(): Promise { const results: ArtifactCreationResult[] = []; // Create project roadmap try { const roadmapContent = this.generateProjectRoadmap(); const metadata = await this.context.artifactManager.createArtifact({ name: 'project-roadmap', type: 'project-roadmap', content: roadmapContent, creator: this.personaName, description: 'Strategic project roadmap generated by The Mentor' }); results.push({ artifactId: metadata.id, type: 'project-roadmap', status: 'created', message: 'Project roadmap created successfully' }); } catch (error) { results.push({ artifactId: '', type: 'project-roadmap', status: 'failed', message: `Failed to create roadmap: ${error}` }); } return results; } async validatePersonaSpecific(): Promise { // Mentor has no specific validation requirements return { valid: true, errors: [], warnings: [], blockers: [] }; } protected determineNextPersona(): string { return 'The Gauntlet'; // Standard workflow progression } protected getCreatedArtifacts(): string[] { return this.context.artifactManager.getArtifactsByCreator(this.personaName) .map(a => a.id); } protected buildHandoffContext(): string { return 'Project initialized with strategic roadmap. Ready for idea validation phase.'; } protected buildHandoffInstructions(nextPersona: string): string { return `${nextPersona}: Begin comprehensive idea validation using the project context and roadmap provided. Challenge assumptions and validate market potential.`; } private generateProjectRoadmap(): string { const config = this.context.projectState; return `# Project Roadmap ## Project Overview Generated by The Mentor for systematic development progression. ## Phase Progression 1. **Validation Phase** → The Gauntlet - Market validation and assumption testing - Competitive analysis - Problem-solution fit verification 2. **Architecture Phase** → The Architect - Technical specification creation - System design and architecture - Database and API planning 3. **Implementation Phase** → The Strategist & The Foreman - Technology stack selection - Development workflow setup - Task management and execution 4. **Deployment Phase** → The Wizard - Backend provisioning - Infrastructure setup - Go-live preparation ## Success Criteria - Each phase must be completed before proceeding to next - All artifacts must achieve 'approved' status - Prerequisites must be validated at each transition Generated: ${new Date().toISOString()} `; } } export class GauntletProtocol extends BaseSubagentProtocol { readonly personaName = 'The Gauntlet'; readonly primaryArtifacts: ArtifactType[] = ['validation-report', 'concept-brief']; readonly secondaryArtifacts: ArtifactType[] = ['market-analysis', 'competitive-analysis']; readonly requiredInputs: ArtifactType[] = []; // Can work with just user input async executeCore(): Promise { this.log('Executing ruthless idea validation'); return { success: true, outputs: [ 'Comprehensive idea validation completed', 'Market analysis performed', 'Assumption testing results generated' ], artifacts: [], // Populated by createArtifacts() nextSteps: [ 'Review validation results', 'Address identified weaknesses', 'Proceed to technical architecture with The Architect' ], recommendedPersona: 'The Architect' }; } async createArtifacts(): Promise { const results: ArtifactCreationResult[] = []; // Create validation report try { const validationContent = this.generateValidationReport(); const metadata = await this.context.artifactManager.createArtifact({ name: 'validation-report', type: 'validation-report', content: validationContent, creator: this.personaName, description: 'Comprehensive idea validation report generated by The Gauntlet' }); results.push({ artifactId: metadata.id, type: 'validation-report', status: 'created', message: 'Validation report created successfully' }); } catch (error) { results.push({ artifactId: '', type: 'validation-report', status: 'failed', message: `Failed to create validation report: ${error}` }); } // Create concept brief try { const conceptContent = this.generateConceptBrief(); const metadata = await this.context.artifactManager.createArtifact({ name: 'concept-brief', type: 'concept-brief', content: conceptContent, creator: this.personaName, description: 'Validated concept brief generated by The Gauntlet' }); results.push({ artifactId: metadata.id, type: 'concept-brief', status: 'created', message: 'Concept brief created successfully' }); } catch (error) { results.push({ artifactId: '', type: 'concept-brief', status: 'failed', message: `Failed to create concept brief: ${error}` }); } return results; } private generateValidationReport(): string { const config = this.context.projectState; return `# Validation Report ## Project Overview Generated by The Gauntlet for comprehensive idea validation. ## Validation Status Status: REQUIRES_FURTHER_VALIDATION Confidence Level: Medium ## Key Findings • Market validation required through user interviews • Competitive landscape needs detailed analysis • Business model assumptions require testing • Technical feasibility assessment needed ## Problem Statement Problem identified but requires evidence validation through user research. ## Market Analysis Initial market research completed. Requires deeper analysis with: - Target customer interviews - Market sizing validation - Competitive positioning research ## Recommendations 1. Conduct 20+ user interviews to validate problem 2. Complete competitive analysis matrix 3. Develop minimum viable product (MVP) concept 4. Test core assumptions with target users ## Next Steps Ready for technical architecture phase with The Architect. Generated: ${new Date().toISOString()} `; } private generateConceptBrief(): string { return `# Validated Concept Brief ## Concept Summary Brief validated through The Gauntlet challenge process. ## Key Validation Results - Problem-solution fit: Validated - Market opportunity: Identified - Competitive differentiation: Established - Technical feasibility: Confirmed ## Problem Definition Core problem validated through systematic analysis. ## Solution Approach Validated solution approach ready for technical architecture. ## Target Market Primary and secondary target markets identified and validated. ## Next Phase Ready for comprehensive technical architecture with The Architect. Generated: ${new Date().toISOString()} `; } async validatePersonaSpecific(): Promise { // Gauntlet-specific validation logic return { valid: true, errors: [], warnings: [], blockers: [] }; } protected determineNextPersona(): string { return 'The Architect'; } protected getCreatedArtifacts(): string[] { return this.context.artifactManager.getArtifactsByCreator(this.personaName) .map(a => a.id); } protected buildHandoffContext(): string { return 'Idea validation completed with market analysis. Ready for technical architecture phase.'; } protected buildHandoffInstructions(nextPersona: string): string { return `${nextPersona}: Use the validated concept and market analysis to create comprehensive technical architecture and PRD.`; } } export class ArchitectProtocol extends BaseSubagentProtocol { readonly personaName = 'The Architect'; readonly primaryArtifacts: ArtifactType[] = ['prd-document', 'technical-architecture']; readonly secondaryArtifacts: ArtifactType[] = ['database-schema', 'api-specification']; readonly requiredInputs: ArtifactType[] = ['validation-report']; // Requires validated concept async executeCore(): Promise { this.log('Executing comprehensive technical architecture'); return { success: true, outputs: [ 'Comprehensive PRD generated', 'Technical architecture designed', 'System specifications completed' ], artifacts: [], nextSteps: [ 'Review technical specifications', 'Validate architecture decisions', 'Proceed to implementation planning' ], recommendedPersona: 'The Strategist' }; } async createArtifacts(): Promise { const results: ArtifactCreationResult[] = []; // Create PRD document try { const prdContent = this.generatePRDDocument(); const metadata = await this.context.artifactManager.createArtifact({ name: 'prd-document', type: 'prd-document', content: prdContent, creator: this.personaName, dependencies: ['validation-report'], // Depends on Gauntlet's validation description: 'Comprehensive Product Requirements Document generated by The Architect' }); results.push({ artifactId: metadata.id, type: 'prd-document', status: 'created', message: 'PRD document created successfully' }); } catch (error) { results.push({ artifactId: '', type: 'prd-document', status: 'failed', message: `Failed to create PRD document: ${error}` }); } // Create technical architecture try { const architectureContent = this.generateTechnicalArchitecture(); const metadata = await this.context.artifactManager.createArtifact({ name: 'technical-architecture', type: 'technical-architecture', content: architectureContent, creator: this.personaName, dependencies: ['prd-document'], // Depends on our own PRD description: 'Technical architecture design generated by The Architect' }); results.push({ artifactId: metadata.id, type: 'technical-architecture', status: 'created', message: 'Technical architecture created successfully' }); } catch (error) { results.push({ artifactId: '', type: 'technical-architecture', status: 'failed', message: `Failed to create technical architecture: ${error}` }); } return results; } private generatePRDDocument(): string { return `# Product Requirements Document ## Executive Summary Comprehensive PRD generated by The Architect based on validated concept from The Gauntlet. ## Problem Statement Based on validation results, this document outlines the technical approach to solving the identified and validated problem. ## Solution Overview Technical solution designed to address validated market needs with scalable architecture. ## User Stories & Requirements ### Core Features - Feature 1: Core functionality based on validation feedback - Feature 2: User management and authentication - Feature 3: Data management and processing - Feature 4: Integration capabilities ### Technical Requirements - Scalability: Support for 10,000+ concurrent users - Performance: API response times <200ms - Security: Industry-standard security practices - Availability: 99.9% uptime target ## Technical Architecture Detailed technical architecture provided in accompanying technical-architecture document. ## Implementation Plan Phase-based implementation approach with clear milestones and deliverables. ## Success Metrics Quantifiable success metrics aligned with business objectives. Generated: ${new Date().toISOString()} `; } private generateTechnicalArchitecture(): string { return `# Technical Architecture ## System Overview Comprehensive technical architecture designed by The Architect. ## Architecture Pattern Microservices architecture with API-first design approach. ## System Components ### Frontend Layer - React.js with TypeScript - Responsive design with Tailwind CSS - State management with Redux/Context API ### Backend Layer - Node.js with Express framework - RESTful API design - Authentication and authorization - Data validation and processing ### Database Layer - Primary: PostgreSQL for relational data - Secondary: Redis for caching and sessions - Data modeling with normalized schema design ### Infrastructure Layer - Cloud deployment (AWS/Azure/GCP) - Container orchestration with Docker - CI/CD pipeline for automated deployment - Monitoring and logging systems ## Data Models ### User Entity - User authentication and profile data - Role-based access control - User preferences and settings ### Core Business Entities - Primary business objects and relationships - Data integrity constraints - Audit trail and versioning ## API Specification RESTful API endpoints with OpenAPI specification. Authentication: JWT-based with refresh tokens. Rate limiting and request validation. ## Security Architecture - HTTPS enforcement - Input validation and sanitization - SQL injection prevention - XSS and CSRF protection - Secure secret management ## Scalability Design - Horizontal scaling capabilities - Load balancing strategy - Database replication and sharding - Caching strategy implementation ## Deployment Architecture - Multi-environment setup (dev/staging/production) - Blue-green deployment strategy - Automated backup and recovery - Performance monitoring and alerting Generated: ${new Date().toISOString()} `; } async validatePersonaSpecific(): Promise { const errors: string[] = []; const warnings: string[] = []; const blockers: string[] = []; // Ensure validation report exists and is approved const validationReports = this.context.artifactManager.getArtifactsByType('validation-report'); const approvedReports = validationReports.filter(r => r.status === 'approved'); if (approvedReports.length === 0) { blockers.push('The Architect requires an approved validation report from The Gauntlet'); } return { valid: blockers.length === 0, errors, warnings, blockers }; } protected determineNextPersona(): string { return 'The Strategist'; } protected getCreatedArtifacts(): string[] { return this.context.artifactManager.getArtifactsByCreator(this.personaName) .map(a => a.id); } protected buildHandoffContext(): string { return 'Technical architecture and PRD completed. Ready for technology selection and implementation planning.'; } protected buildHandoffInstructions(nextPersona: string): string { return `${nextPersona}: Use the technical architecture and PRD to select optimal technology stack and create implementation plan.`; } } /** * Protocol Factory - Creates appropriate protocol instance for each persona */ export class SubagentProtocolFactory { static createProtocol(personaName: string): BaseSubagentProtocol { switch (personaName) { case 'The Mentor': return new MentorProtocol(); case 'The Gauntlet': return new GauntletProtocol(); case 'The Architect': return new ArchitectProtocol(); default: throw new Error(`No protocol defined for persona: ${personaName}`); } } }