mcp-workflow-server-enhanced
Version:
Enhanced MCP Workflow Server with smart problem routing, comprehensive validation, guide compliance, and robust error handling. Intelligently routes to appropriate AI functions based on problem type.
1,179 lines (1,046 loc) • 37.8 kB
text/typescript
import {
CognitiveInputSchema,
FunctionOutput,
WorkflowContext,
ValidationError,
DomainError,
} from '../shared/types.js';
import { logWorkflowProgress } from '../shared/utils.js';
import { globalErrorHandler, withErrorHandling } from '../shared/error-handling.js';
/**
* Cognitive Analysis Function
*
* This function performs deep cognitive analysis on the research data and improved prompt.
* It synthesizes information, identifies patterns, generates insights, and creates
* comprehensive conclusions to guide the planning phase.
*/
export function createCognitiveFunction() {
return async (input: any, context: WorkflowContext): Promise<FunctionOutput> => {
return await withErrorHandling(async () => {
// Validate and sanitize input
const inputValidation = globalErrorHandler.validateInput(input, 'cognitive');
if (!inputValidation.valid) {
throw new ValidationError(
`Input validation failed: ${inputValidation.errors.join(', ')}`,
inputValidation.errors,
'cognitive'
);
}
const sanitizedInput = globalErrorHandler.sanitizeInput(input, 'cognitive');
// Validate input schema
let validatedInput;
try {
validatedInput = CognitiveInputSchema.parse(sanitizedInput);
} catch (error) {
throw new ValidationError(
'Schema validation failed',
error as any,
'cognitive'
);
}
const { researchData, improvedPrompt, analysisDepth } = validatedInput;
logWorkflowProgress(context, 'cognitive', 'Starting cognitive analysis and synthesis');
// Determine problem domain and route to appropriate analysis
let domainAnalysis;
try {
domainAnalysis = detectProblemDomain(improvedPrompt);
logWorkflowProgress(context, 'cognitive',
`Detected domain: ${domainAnalysis.domain} (confidence: ${domainAnalysis.confidence}%)`
);
} catch (error) {
throw new DomainError(
`Domain detection failed: ${error.message}`,
'unknown',
'detection'
);
}
let analysis;
try {
if (domainAnalysis.domain === 'generic' || domainAnalysis.confidence < 50) {
// Use generic problem analysis for unspecified or low-confidence domains
analysis = await analyzeGenericProblem(improvedPrompt, researchData, analysisDepth);
} else {
// Use domain-specific analysis with enhanced context
analysis = await performDomainSpecificAnalysis(
researchData,
improvedPrompt,
analysisDepth,
domainAnalysis
);
}
} catch (error) {
throw new DomainError(
`Domain analysis failed: ${error.message}`,
domainAnalysis.domain,
'analysis'
);
}
// Generate insights and patterns
const insights = generateInsights(researchData, analysis);
// Create comprehensive conclusions
const conclusions = generateConclusions(analysis, insights);
// Identify requirements and constraints
const requirements = extractRequirements(researchData, analysis);
const constraints = extractConstraints(researchData, analysis);
// Generate strategic recommendations
const recommendations = generateStrategicRecommendations(analysis, insights);
const result = {
analysisDepth,
cognitiveAnalysis: analysis,
insights,
conclusions,
requirements,
constraints,
recommendations,
riskAssessment: performRiskAssessment(analysis),
opportunityAnalysis: identifyOpportunities(insights),
decisionMatrix: createDecisionMatrix(analysis, insights),
confidenceScore: calculateConfidenceScore(analysis),
};
logWorkflowProgress(context, 'cognitive', 'Cognitive analysis completed successfully');
return {
success: true,
result,
nextStep: 'planner',
context,
metadata: {
analysisDepth,
insightsGenerated: insights.length,
confidenceScore: result.confidenceScore,
processingTime: Date.now(),
domainAnalysis: domainAnalysis,
errorHandlingApplied: true,
},
};
}, context, 'cognitive').catch(error => {
logWorkflowProgress(context, 'cognitive', `Error in cognitive analysis: ${error.message}`);
return {
success: false,
result: {
error: error.message,
errorType: error.constructor.name,
step: 'cognitive',
recoverable: error.recoverable !== false,
},
context,
metadata: {
errorOccurred: true,
errorTimestamp: new Date().toISOString(),
},
};
});
};
}
/**
* Perform cognitive analysis based on research data
*/
async function performCognitiveAnalysis(
researchData: any,
improvedPrompt: string,
depth: 'surface' | 'deep' | 'comprehensive'
): Promise<{
promptAnalysis: any;
researchSynthesis: any;
patternRecognition: any;
contextualUnderstanding: any;
complexityAssessment: any;
}> {
// Analyze the improved prompt
const promptAnalysis = analyzePromptCognitively(improvedPrompt);
// Synthesize research findings
const researchSynthesis = synthesizeResearchData(researchData);
// Recognize patterns across data
const patternRecognition = recognizePatterns(researchData, promptAnalysis);
// Develop contextual understanding
const contextualUnderstanding = buildContextualUnderstanding(
promptAnalysis,
researchSynthesis,
depth
);
// Assess complexity
const complexityAssessment = assessComplexity(
promptAnalysis,
researchSynthesis,
patternRecognition
);
return {
promptAnalysis,
researchSynthesis,
patternRecognition,
contextualUnderstanding,
complexityAssessment,
};
}
/**
* Analyze the prompt from a cognitive perspective
*/
function analyzePromptCognitively(prompt: string): {
intent: string;
scope: string;
domain: string[];
complexity: number;
ambiguity: number;
feasibility: number;
innovation: number;
} {
const promptLower = prompt.toLowerCase();
// Determine intent
let intent = 'general';
if (promptLower.includes('create') || promptLower.includes('build')) intent = 'creation';
if (promptLower.includes('analyze') || promptLower.includes('research')) intent = 'analysis';
if (promptLower.includes('improve') || promptLower.includes('optimize')) intent = 'optimization';
if (promptLower.includes('solve') || promptLower.includes('fix')) intent = 'problem-solving';
// Determine scope
let scope = 'medium';
const wordCount = prompt.split(/\s+/).length;
if (wordCount < 20) scope = 'narrow';
if (wordCount > 100) scope = 'broad';
// Identify domains
const domains: string[] = [];
const domainKeywords = {
'software-development': ['code', 'programming', 'development', 'software'],
'ai-ml': ['ai', 'machine learning', 'neural', 'model'],
'web-development': ['web', 'frontend', 'backend', 'api'],
'data': ['data', 'database', 'analytics', 'visualization'],
'devops': ['deployment', 'docker', 'kubernetes', 'ci/cd'],
'testing': ['test', 'testing', 'qa', 'quality'],
};
for (const [domain, keywords] of Object.entries(domainKeywords)) {
if (keywords.some(keyword => promptLower.includes(keyword))) {
domains.push(domain);
}
}
// Calculate metrics (1-10 scale)
const complexity = calculateComplexityScore(prompt);
const ambiguity = calculateAmbiguityScore(prompt);
const feasibility = calculateFeasibilityScore(prompt);
const innovation = calculateInnovationScore(prompt);
return {
intent,
scope,
domain: domains,
complexity,
ambiguity,
feasibility,
innovation,
};
}
/**
* Synthesize research data into coherent insights
*/
function synthesizeResearchData(researchData: any): {
keyThemes: string[];
technologyLandscape: any;
bestPracticesMap: any;
toolEcosystem: any;
trendsAnalysis: any;
} {
const keyThemes: string[] = [];
const technologyLandscape = {};
const bestPracticesMap = {};
const toolEcosystem = {};
const trendsAnalysis = {};
if (researchData?.topicResults) {
// Extract key themes
researchData.topicResults.forEach((result: any) => {
keyThemes.push(result.topic);
// Map technologies
if (result.tools) {
technologyLandscape[result.topic] = result.tools;
}
// Map best practices
if (result.bestPractices) {
bestPracticesMap[result.topic] = result.bestPractices;
}
// Analyze trends
if (result.currentTrends) {
trendsAnalysis[result.topic] = result.currentTrends;
}
});
}
if (researchData?.toolsAndTechnologies) {
toolEcosystem.build = researchData.toolsAndTechnologies.buildTools;
toolEcosystem.testing = researchData.toolsAndTechnologies.testingFrameworks;
toolEcosystem.development = researchData.toolsAndTechnologies.developmentTools;
toolEcosystem.deployment = researchData.toolsAndTechnologies.deploymentTools;
}
return {
keyThemes,
technologyLandscape,
bestPracticesMap,
toolEcosystem,
trendsAnalysis,
};
}
/**
* Recognize patterns across the analyzed data
*/
function recognizePatterns(researchData: any, promptAnalysis: any): {
architecturalPatterns: string[];
designPatterns: string[];
workflowPatterns: string[];
integrationPatterns: string[];
} {
const architecturalPatterns: string[] = [];
const designPatterns: string[] = [];
const workflowPatterns: string[] = [];
const integrationPatterns: string[] = [];
// Analyze based on prompt intent and research findings
if (promptAnalysis.intent === 'creation') {
architecturalPatterns.push('Modular architecture');
designPatterns.push('Factory pattern');
workflowPatterns.push('Sequential processing');
}
if (promptAnalysis.domain.includes('software-development')) {
architecturalPatterns.push('Layered architecture');
designPatterns.push('Repository pattern');
integrationPatterns.push('API-first design');
}
if (researchData?.codeAnalysis) {
architecturalPatterns.push(...researchData.codeAnalysis.suggestedArchitecture);
designPatterns.push(...researchData.codeAnalysis.designPatterns);
}
return {
architecturalPatterns,
designPatterns,
workflowPatterns,
integrationPatterns,
};
}
/**
* Build contextual understanding
*/
function buildContextualUnderstanding(
promptAnalysis: any,
researchSynthesis: any,
depth: string
): {
businessContext: string;
technicalContext: string;
userContext: string;
environmentalContext: string;
} {
const businessContext = `Project intent: ${promptAnalysis.intent}, Scope: ${promptAnalysis.scope}`;
const technicalContext = `Domains: ${promptAnalysis.domain.join(', ')}, Complexity: ${promptAnalysis.complexity}/10`;
const userContext = `Target users: Developers and technical stakeholders`;
const environmentalContext = `Technology landscape: ${Object.keys(researchSynthesis.technologyLandscape).join(', ')}`;
return {
businessContext,
technicalContext,
userContext,
environmentalContext,
};
}
/**
* Assess overall complexity
*/
function assessComplexity(promptAnalysis: any, researchSynthesis: any, patterns: any): {
technicalComplexity: number;
implementationComplexity: number;
integrationComplexity: number;
overallComplexity: number;
} {
const technicalComplexity = promptAnalysis.complexity;
const implementationComplexity = Math.min(10, patterns.architecturalPatterns.length * 2);
const integrationComplexity = Math.min(10, Object.keys(researchSynthesis.toolEcosystem).length);
const overallComplexity = Math.round((technicalComplexity + implementationComplexity + integrationComplexity) / 3);
return {
technicalComplexity,
implementationComplexity,
integrationComplexity,
overallComplexity,
};
}
/**
* Generate insights from the analysis
*/
function generateInsights(researchData: any, analysis: any): string[] {
const insights: string[] = [];
insights.push(`Project complexity is ${analysis.complexityAssessment.overallComplexity}/10`);
insights.push(`Primary intent is ${analysis.promptAnalysis.intent}`);
insights.push(`Key domains involved: ${analysis.promptAnalysis.domain.join(', ')}`);
if (analysis.researchSynthesis.keyThemes.length > 0) {
insights.push(`Research identified ${analysis.researchSynthesis.keyThemes.length} key themes`);
}
if (analysis.patternRecognition.architecturalPatterns.length > 0) {
insights.push(`Recommended architectural patterns: ${analysis.patternRecognition.architecturalPatterns.slice(0, 2).join(', ')}`);
}
return insights;
}
/**
* Generate comprehensive conclusions
*/
function generateConclusions(analysis: any, insights: string[]): string[] {
const conclusions: string[] = [];
conclusions.push('Based on the cognitive analysis, the following conclusions have been reached:');
conclusions.push(`The project has ${analysis.complexityAssessment.overallComplexity > 7 ? 'high' : analysis.complexityAssessment.overallComplexity > 4 ? 'medium' : 'low'} complexity`);
conclusions.push(`The approach should focus on ${analysis.promptAnalysis.intent}`);
conclusions.push('A structured implementation plan is recommended');
conclusions.push('Regular testing and validation should be incorporated');
return conclusions;
}
/**
* Extract requirements from analysis
*/
function extractRequirements(researchData: any, analysis: any): string[] {
const requirements: string[] = [];
requirements.push('Implement core functionality as specified');
requirements.push('Follow identified best practices');
requirements.push('Use recommended tools and technologies');
requirements.push('Ensure proper error handling and validation');
requirements.push('Include comprehensive testing');
return requirements;
}
/**
* Extract constraints from analysis
*/
function extractConstraints(researchData: any, analysis: any): string[] {
const constraints: string[] = [];
constraints.push('Must maintain code quality standards');
constraints.push('Should follow architectural patterns');
constraints.push('Must be maintainable and extensible');
if (analysis.complexityAssessment.overallComplexity > 7) {
constraints.push('High complexity requires careful planning');
}
return constraints;
}
/**
* Generate strategic recommendations
*/
function generateStrategicRecommendations(analysis: any, insights: string[]): string[] {
const recommendations: string[] = [];
recommendations.push('Proceed with structured implementation approach');
recommendations.push('Prioritize core functionality first');
recommendations.push('Implement comprehensive testing strategy');
recommendations.push('Plan for iterative development and feedback');
return recommendations;
}
/**
* Perform risk assessment
*/
function performRiskAssessment(analysis: any): { risk: string; mitigation: string }[] {
const risks = [];
if (analysis.complexityAssessment.overallComplexity > 7) {
risks.push({
risk: 'High complexity may lead to implementation challenges',
mitigation: 'Break down into smaller, manageable tasks'
});
}
if (analysis.promptAnalysis.ambiguity > 6) {
risks.push({
risk: 'Ambiguous requirements may cause scope creep',
mitigation: 'Clarify requirements before implementation'
});
}
return risks;
}
/**
* Identify opportunities
*/
function identifyOpportunities(insights: string[]): string[] {
return [
'Opportunity to implement best practices',
'Potential for reusable components',
'Chance to create comprehensive documentation',
'Possibility for future enhancements'
];
}
/**
* Create decision matrix
*/
function createDecisionMatrix(analysis: any, insights: string[]): any {
return {
approach: 'Structured implementation',
priority: 'High',
timeline: 'Medium-term',
resources: 'Standard development resources',
riskLevel: analysis.complexityAssessment.overallComplexity > 7 ? 'High' : 'Medium'
};
}
/**
* Calculate confidence score
*/
function calculateConfidenceScore(analysis: any): number {
const factors = [
10 - analysis.promptAnalysis.ambiguity,
analysis.promptAnalysis.feasibility,
Math.min(10, Object.keys(analysis.researchSynthesis.technologyLandscape).length * 2)
];
return Math.round(factors.reduce((sum, factor) => sum + factor, 0) / factors.length);
}
// Helper functions for scoring
function calculateComplexityScore(prompt: string): number {
const factors = [
prompt.split(/\s+/).length / 10, // Word count factor
(prompt.match(/[,;]/g) || []).length, // Punctuation complexity
prompt.toLowerCase().includes('multiple') ? 2 : 0,
prompt.toLowerCase().includes('integrate') ? 2 : 0,
];
return Math.min(10, Math.max(1, Math.round(factors.reduce((sum, f) => sum + f, 0))));
}
function calculateAmbiguityScore(prompt: string): number {
const ambiguousWords = ['maybe', 'perhaps', 'might', 'could', 'something', 'anything'];
const count = ambiguousWords.filter(word => prompt.toLowerCase().includes(word)).length;
return Math.min(10, count * 2 + 1);
}
function calculateFeasibilityScore(prompt: string): number {
const feasibleIndicators = ['create', 'build', 'implement', 'develop', 'use'];
const count = feasibleIndicators.filter(word => prompt.toLowerCase().includes(word)).length;
return Math.min(10, count * 2 + 3);
}
function calculateInnovationScore(prompt: string): number {
const innovativeWords = ['new', 'novel', 'innovative', 'creative', 'unique'];
const count = innovativeWords.filter(word => prompt.toLowerCase().includes(word)).length;
return Math.min(10, count * 2 + 2);
}
/**
* Enhanced domain detection with multi-factor analysis
*/
function detectProblemDomain(prompt: string): {
domain: string;
confidence: number;
indicators: string[];
subdomains: string[];
} {
const promptLower = prompt.toLowerCase();
const indicators: string[] = [];
const subdomains: string[] = [];
// Domain detection patterns with confidence scoring
const domainPatterns = [
{
domain: 'vscode-extension',
patterns: [
{ keywords: ['vscode', 'visual studio code'], weight: 10 },
{ keywords: ['extension', 'plugin'], weight: 8 },
{ keywords: ['webview', 'postmessage'], weight: 9 },
{ keywords: ['command palette', 'tree view'], weight: 7 },
{ keywords: ['typescript', 'manifest.json'], weight: 6 },
],
subdomains: ['webview-communication', 'command-handling', 'ui-components', 'file-system-access'],
},
{
domain: 'web-development',
patterns: [
{ keywords: ['react', 'vue', 'angular'], weight: 9 },
{ keywords: ['frontend', 'ui', 'interface'], weight: 7 },
{ keywords: ['javascript', 'typescript', 'html', 'css'], weight: 6 },
{ keywords: ['component', 'state management'], weight: 8 },
{ keywords: ['responsive', 'mobile-first'], weight: 7 },
],
subdomains: ['spa-development', 'responsive-design', 'state-management', 'performance-optimization'],
},
{
domain: 'api-backend',
patterns: [
{ keywords: ['api', 'rest', 'graphql'], weight: 9 },
{ keywords: ['server', 'backend', 'microservice'], weight: 8 },
{ keywords: ['database', 'sql', 'nosql'], weight: 7 },
{ keywords: ['authentication', 'authorization'], weight: 8 },
{ keywords: ['node.js', 'express', 'fastify'], weight: 7 },
],
subdomains: ['rest-api', 'database-design', 'authentication', 'scalability'],
},
{
domain: 'mobile-development',
patterns: [
{ keywords: ['mobile', 'ios', 'android'], weight: 10 },
{ keywords: ['react native', 'flutter', 'xamarin'], weight: 9 },
{ keywords: ['app store', 'play store'], weight: 8 },
{ keywords: ['native', 'hybrid'], weight: 7 },
],
subdomains: ['cross-platform', 'native-development', 'app-distribution'],
},
{
domain: 'data-ml',
patterns: [
{ keywords: ['machine learning', 'ai', 'artificial intelligence'], weight: 10 },
{ keywords: ['data science', 'analytics'], weight: 9 },
{ keywords: ['neural network', 'deep learning'], weight: 9 },
{ keywords: ['python', 'tensorflow', 'pytorch'], weight: 7 },
],
subdomains: ['supervised-learning', 'data-preprocessing', 'model-deployment'],
},
{
domain: 'devops-infrastructure',
patterns: [
{ keywords: ['docker', 'kubernetes', 'container'], weight: 9 },
{ keywords: ['ci/cd', 'pipeline', 'deployment'], weight: 8 },
{ keywords: ['aws', 'azure', 'gcp', 'cloud'], weight: 7 },
{ keywords: ['monitoring', 'logging'], weight: 6 },
],
subdomains: ['containerization', 'orchestration', 'monitoring', 'cloud-deployment'],
},
];
let bestMatch = { domain: 'generic', confidence: 0, indicators: [], subdomains: [] };
for (const domainPattern of domainPatterns) {
let score = 0;
const matchedIndicators: string[] = [];
const matchedSubdomains: string[] = [];
for (const pattern of domainPattern.patterns) {
for (const keyword of pattern.keywords) {
if (promptLower.includes(keyword)) {
score += pattern.weight;
matchedIndicators.push(keyword);
}
}
}
// Check for subdomain indicators
for (const subdomain of domainPattern.subdomains) {
const subdomainKeywords = subdomain.split('-');
if (subdomainKeywords.some(keyword => promptLower.includes(keyword))) {
matchedSubdomains.push(subdomain);
score += 2; // Bonus for subdomain match
}
}
// Calculate confidence (0-100)
const maxPossibleScore = domainPattern.patterns.reduce((sum, p) => sum + p.weight, 0);
const confidence = Math.min(100, (score / maxPossibleScore) * 100);
if (confidence > bestMatch.confidence) {
bestMatch = {
domain: domainPattern.domain,
confidence,
indicators: matchedIndicators,
subdomains: matchedSubdomains,
};
}
}
// If confidence is too low, mark as generic
if (bestMatch.confidence < 30) {
bestMatch.domain = 'generic';
}
return bestMatch;
}
/**
* Perform domain-specific analysis with enhanced context
*/
async function performDomainSpecificAnalysis(
researchData: any,
improvedPrompt: string,
analysisDepth: 'surface' | 'deep' | 'comprehensive',
domainAnalysis: { domain: string; confidence: number; indicators: string[]; subdomains: string[] }
): Promise<{
promptAnalysis: any;
researchSynthesis: any;
patternRecognition: any;
contextualUnderstanding: any;
complexityAssessment: any;
domainSpecificAnalysis: any;
}> {
// Perform standard cognitive analysis
const standardAnalysis = await performCognitiveAnalysis(researchData, improvedPrompt, analysisDepth);
// Add domain-specific analysis
const domainSpecificAnalysis = {
detectedDomain: domainAnalysis.domain,
domainConfidence: domainAnalysis.confidence,
domainIndicators: domainAnalysis.indicators,
relevantSubdomains: domainAnalysis.subdomains,
domainSpecificPatterns: analyzeDomainPatterns(improvedPrompt, domainAnalysis.domain),
domainBestPractices: getDomainBestPractices(domainAnalysis.domain),
domainSpecificRisks: getDomainSpecificRisks(domainAnalysis.domain),
domainToolsAndFrameworks: getDomainToolsAndFrameworks(domainAnalysis.domain),
implementationGuidance: getDomainImplementationGuidance(domainAnalysis.domain, improvedPrompt),
};
return {
...standardAnalysis,
domainSpecificAnalysis,
};
}
/**
* Analyze generic problems with comprehensive approach
*/
async function analyzeGenericProblem(
userPrompt: string,
researchData: any,
analysisDepth: 'surface' | 'deep' | 'comprehensive'
): Promise<{
promptAnalysis: any;
researchSynthesis: any;
patternRecognition: any;
contextualUnderstanding: any;
complexityAssessment: any;
problemSpecificAnalysis: any;
}> {
// Perform standard cognitive analysis
const standardAnalysis = await performCognitiveAnalysis(researchData, userPrompt, analysisDepth);
// Add problem-specific analysis
const problemSpecificAnalysis = {
problemType: classifyProblemType(userPrompt),
solutionApproach: determineSolutionApproach(userPrompt),
implementationStrategy: generateImplementationStrategy(userPrompt),
riskFactors: identifyRiskFactors(userPrompt),
successCriteria: defineSuccessCriteria(userPrompt),
resourceRequirements: assessResourceRequirements(userPrompt),
};
return {
...standardAnalysis,
problemSpecificAnalysis,
};
}
/**
* Classify the type of problem being addressed
*/
function classifyProblemType(prompt: string): string {
const promptLower = prompt.toLowerCase();
if (promptLower.includes('fix') || promptLower.includes('error') || promptLower.includes('bug')) {
return 'bug-fix';
}
if (promptLower.includes('improve') || promptLower.includes('enhance') || promptLower.includes('optimize')) {
return 'enhancement';
}
if (promptLower.includes('create') || promptLower.includes('build') || promptLower.includes('develop')) {
return 'development';
}
if (promptLower.includes('analyze') || promptLower.includes('research') || promptLower.includes('investigate')) {
return 'analysis';
}
return 'general';
}
/**
* Determine the solution approach based on problem characteristics
*/
function determineSolutionApproach(prompt: string): string {
const problemType = classifyProblemType(prompt);
switch (problemType) {
case 'bug-fix':
return 'diagnostic-and-repair';
case 'enhancement':
return 'iterative-improvement';
case 'development':
return 'systematic-construction';
case 'analysis':
return 'investigative-research';
default:
return 'adaptive-methodology';
}
}
/**
* Generate implementation strategy based on problem analysis
*/
function generateImplementationStrategy(prompt: string): {
approach: string;
phases: string[];
methodology: string;
validation: string[];
} {
const problemType = classifyProblemType(prompt);
const solutionApproach = determineSolutionApproach(prompt);
const baseStrategy = {
approach: solutionApproach,
phases: ['analysis', 'planning', 'implementation', 'validation'],
methodology: 'agile-iterative',
validation: ['unit-testing', 'integration-testing', 'user-acceptance'],
};
// Customize based on problem type
switch (problemType) {
case 'bug-fix':
baseStrategy.phases = ['diagnosis', 'root-cause-analysis', 'fix-implementation', 'regression-testing'];
baseStrategy.validation = ['error-reproduction', 'fix-verification', 'regression-testing'];
break;
case 'enhancement':
baseStrategy.phases = ['current-state-analysis', 'improvement-design', 'incremental-implementation', 'performance-validation'];
baseStrategy.validation = ['performance-testing', 'user-experience-validation', 'backward-compatibility'];
break;
case 'development':
baseStrategy.phases = ['requirements-analysis', 'architecture-design', 'development', 'testing'];
baseStrategy.validation = ['unit-testing', 'integration-testing', 'system-testing', 'user-acceptance'];
break;
}
return baseStrategy;
}
/**
* Identify risk factors in the problem domain
*/
function identifyRiskFactors(prompt: string): string[] {
const risks: string[] = [];
const promptLower = prompt.toLowerCase();
if (promptLower.includes('complex') || promptLower.includes('multiple')) {
risks.push('complexity-risk');
}
if (promptLower.includes('integration') || promptLower.includes('api')) {
risks.push('integration-risk');
}
if (promptLower.includes('performance') || promptLower.includes('scale')) {
risks.push('performance-risk');
}
if (promptLower.includes('security') || promptLower.includes('auth')) {
risks.push('security-risk');
}
if (promptLower.includes('legacy') || promptLower.includes('existing')) {
risks.push('compatibility-risk');
}
return risks.length > 0 ? risks : ['general-implementation-risk'];
}
/**
* Define success criteria for the problem solution
*/
function defineSuccessCriteria(prompt: string): string[] {
const criteria: string[] = [];
const problemType = classifyProblemType(prompt);
// Base criteria for all problems
criteria.push('solution-addresses-core-problem');
criteria.push('implementation-is-maintainable');
criteria.push('solution-is-testable');
// Problem-specific criteria
switch (problemType) {
case 'bug-fix':
criteria.push('error-is-eliminated');
criteria.push('no-regression-introduced');
break;
case 'enhancement':
criteria.push('performance-improvement-measurable');
criteria.push('user-experience-enhanced');
break;
case 'development':
criteria.push('requirements-fully-implemented');
criteria.push('code-quality-standards-met');
break;
case 'analysis':
criteria.push('insights-are-actionable');
criteria.push('findings-are-comprehensive');
break;
}
return criteria;
}
/**
* Assess resource requirements for problem solution
*/
function assessResourceRequirements(prompt: string): {
timeEstimate: string;
skillsRequired: string[];
toolsNeeded: string[];
complexity: 'low' | 'medium' | 'high';
} {
const promptLower = prompt.toLowerCase();
const problemType = classifyProblemType(prompt);
let complexity: 'low' | 'medium' | 'high' = 'medium';
let timeEstimate = '1-3 days';
const skillsRequired: string[] = [];
const toolsNeeded: string[] = [];
// Assess complexity
if (promptLower.includes('simple') || promptLower.includes('basic')) {
complexity = 'low';
timeEstimate = '1-2 hours';
} else if (promptLower.includes('complex') || promptLower.includes('advanced') || promptLower.includes('multiple')) {
complexity = 'high';
timeEstimate = '1-2 weeks';
}
// Determine skills based on domain
if (promptLower.includes('javascript') || promptLower.includes('typescript')) {
skillsRequired.push('javascript-development');
}
if (promptLower.includes('react') || promptLower.includes('frontend')) {
skillsRequired.push('frontend-development');
}
if (promptLower.includes('api') || promptLower.includes('backend')) {
skillsRequired.push('backend-development');
}
if (promptLower.includes('database') || promptLower.includes('sql')) {
skillsRequired.push('database-management');
}
// Default skills if none specified
if (skillsRequired.length === 0) {
skillsRequired.push('general-programming');
}
// Determine tools
if (promptLower.includes('vscode') || promptLower.includes('extension')) {
toolsNeeded.push('vscode-extension-api');
}
if (promptLower.includes('test') || problemType === 'bug-fix') {
toolsNeeded.push('testing-framework');
}
return {
timeEstimate,
skillsRequired,
toolsNeeded,
complexity,
};
}
/**
* Analyze domain-specific patterns
*/
function analyzeDomainPatterns(prompt: string, domain: string): string[] {
const patterns: string[] = [];
const promptLower = prompt.toLowerCase();
switch (domain) {
case 'vscode-extension':
if (promptLower.includes('webview')) patterns.push('webview-communication-pattern');
if (promptLower.includes('command')) patterns.push('command-registration-pattern');
if (promptLower.includes('tree')) patterns.push('tree-view-pattern');
if (promptLower.includes('provider')) patterns.push('provider-pattern');
break;
case 'web-development':
if (promptLower.includes('component')) patterns.push('component-composition-pattern');
if (promptLower.includes('state')) patterns.push('state-management-pattern');
if (promptLower.includes('hook')) patterns.push('hooks-pattern');
if (promptLower.includes('responsive')) patterns.push('responsive-design-pattern');
break;
case 'api-backend':
if (promptLower.includes('rest')) patterns.push('rest-api-pattern');
if (promptLower.includes('middleware')) patterns.push('middleware-pattern');
if (promptLower.includes('auth')) patterns.push('authentication-pattern');
if (promptLower.includes('database')) patterns.push('repository-pattern');
break;
}
return patterns;
}
/**
* Get domain-specific best practices
*/
function getDomainBestPractices(domain: string): string[] {
const practices: { [key: string]: string[] } = {
'vscode-extension': [
'Use TypeScript for type safety',
'Implement proper error handling for webview communication',
'Follow VS Code extension guidelines',
'Use activation events efficiently',
'Implement proper disposal patterns',
],
'web-development': [
'Use semantic HTML',
'Implement responsive design',
'Optimize for performance',
'Follow accessibility guidelines',
'Use modern CSS features',
],
'api-backend': [
'Implement proper error handling',
'Use input validation',
'Follow REST principles',
'Implement rate limiting',
'Use proper HTTP status codes',
],
'generic': [
'Write clean, maintainable code',
'Implement comprehensive testing',
'Follow SOLID principles',
'Use version control effectively',
'Document your code',
],
};
return practices[domain] || practices['generic'];
}
/**
* Get domain-specific risks
*/
function getDomainSpecificRisks(domain: string): string[] {
const risks: { [key: string]: string[] } = {
'vscode-extension': [
'Webview security vulnerabilities',
'Extension activation performance',
'API compatibility issues',
'Memory leaks in long-running processes',
],
'web-development': [
'Cross-browser compatibility',
'Performance on mobile devices',
'Security vulnerabilities (XSS, CSRF)',
'Bundle size optimization',
],
'api-backend': [
'Security vulnerabilities',
'Scalability bottlenecks',
'Database performance issues',
'Third-party service dependencies',
],
'generic': [
'Technical debt accumulation',
'Maintenance complexity',
'Performance degradation',
'Security vulnerabilities',
],
};
return risks[domain] || risks['generic'];
}
/**
* Get domain-specific tools and frameworks
*/
function getDomainToolsAndFrameworks(domain: string): string[] {
const tools: { [key: string]: string[] } = {
'vscode-extension': [
'VS Code Extension API',
'TypeScript',
'Webpack',
'ESLint',
'Jest for testing',
],
'web-development': [
'React/Vue/Angular',
'Webpack/Vite',
'CSS frameworks (Tailwind, Bootstrap)',
'Testing libraries (Jest, Cypress)',
'Build tools (npm, yarn)',
],
'api-backend': [
'Express.js/Fastify',
'Database ORMs (Prisma, TypeORM)',
'Authentication libraries',
'Testing frameworks (Jest, Supertest)',
'Monitoring tools',
],
'generic': [
'Version control (Git)',
'Code editors/IDEs',
'Testing frameworks',
'Documentation tools',
'CI/CD platforms',
],
};
return tools[domain] || tools['generic'];
}
/**
* Get domain-specific implementation guidance
*/
function getDomainImplementationGuidance(domain: string, prompt: string): {
approach: string;
keyConsiderations: string[];
recommendedArchitecture: string;
testingStrategy: string;
} {
const guidance: { [key: string]: any } = {
'vscode-extension': {
approach: 'Extension-based development with proper lifecycle management',
keyConsiderations: [
'Webview security and communication',
'Extension activation performance',
'Proper resource disposal',
'User experience consistency',
],
recommendedArchitecture: 'MVC pattern with clear separation of concerns',
testingStrategy: 'Unit tests for logic, integration tests for VS Code API',
},
'web-development': {
approach: 'Component-based development with modern frameworks',
keyConsiderations: [
'Responsive design',
'Performance optimization',
'Accessibility compliance',
'SEO considerations',
],
recommendedArchitecture: 'Component-based architecture with state management',
testingStrategy: 'Unit tests, integration tests, and E2E testing',
},
'api-backend': {
approach: 'RESTful API development with proper error handling',
keyConsiderations: [
'Security implementation',
'Database optimization',
'Scalability planning',
'API documentation',
],
recommendedArchitecture: 'Layered architecture with clear separation',
testingStrategy: 'Unit tests, integration tests, and API testing',
},
'generic': {
approach: 'Systematic development with best practices',
keyConsiderations: [
'Code maintainability',
'Performance considerations',
'Security awareness',
'Documentation quality',
],
recommendedArchitecture: 'Clean architecture with SOLID principles',
testingStrategy: 'Comprehensive testing at all levels',
},
};
return guidance[domain] || guidance['generic'];
}