This is page 11 of 18. Use http://codebase.md/minipuft/claude-prompts-mcp?lines=true&page={x} to view the full context. # Directory Structure ``` ├── .actrc ├── .gitattributes ├── .github │ └── workflows │ ├── ci.yml │ ├── mcp-compliance.yml │ └── pr-validation.yml ├── .gitignore ├── agent.md ├── assets │ └── logo.png ├── CLAUDE.md ├── config │ └── framework-state.json ├── docs │ ├── architecture.md │ ├── chain-modification-examples.md │ ├── contributing.md │ ├── enhanced-gate-system.md │ ├── execution-architecture-guide.md │ ├── installation-guide.md │ ├── mcp-tool-usage-guide.md │ ├── mcp-tools-reference.md │ ├── prompt-format-guide.md │ ├── prompt-management.md │ ├── prompt-vs-template-guide.md │ ├── README.md │ ├── template-development-guide.md │ ├── TODO.md │ ├── troubleshooting.md │ └── version-history.md ├── LICENSE ├── local-test.sh ├── plans │ ├── nunjucks-dynamic-chain-orchestration.md │ ├── outputschema-realtime-progress-and-validation.md │ ├── parallel-conditional-execution-analysis.md │ ├── sqlite-storage-migration.md │ └── symbolic-command-language-implementation.md ├── README.md ├── scripts │ ├── setup-windows-testing.sh │ ├── test_server.js │ ├── test-all-platforms.sh │ └── windows-tests │ ├── test-windows-paths.js │ ├── test-windows-startup.sh │ └── windows-env.sh └── server ├── config │ ├── framework-state.json │ └── tool-descriptions.json ├── config.json ├── jest.config.cjs ├── LICENSE ├── package-lock.json ├── package.json ├── prompts │ ├── analysis │ │ ├── advanced_analysis_engine.md │ │ ├── content_analysis.md │ │ ├── deep_analysis.md │ │ ├── deep_research.md │ │ ├── markdown_notebook.md │ │ ├── note_integration.md │ │ ├── note_refinement.md │ │ ├── notes.md │ │ ├── progressive_research.md │ │ ├── prompts.json │ │ ├── query_refinement.md │ │ └── review.md │ ├── architecture │ │ ├── prompts.json │ │ └── strategic-system-alignment.md │ ├── content_processing │ │ ├── format_enhancement.md │ │ ├── noteIntegration.md │ │ ├── obsidian_metadata_optimizer.md │ │ ├── prompts.json │ │ ├── vault_related_notes_finder.md │ │ └── video_notes_enhanced.md │ ├── debugging │ │ ├── analyze_logs.md │ │ └── prompts.json │ ├── development │ │ ├── analyze_code_structure.md │ │ ├── analyze_file_structure.md │ │ ├── code_review_optimization_chain.md │ │ ├── component_flow_analysis.md │ │ ├── create_modularization_plan.md │ │ ├── detect_code_issues.md │ │ ├── detect_project_commands.md │ │ ├── expert_code_implementation.md │ │ ├── generate_comprehensive_claude_md.md │ │ ├── prompts.json │ │ ├── strategicImplement.md │ │ ├── suggest_code_improvements.md │ │ └── transform_code_to_modules.md │ ├── documentation │ │ ├── create_docs_chain.md │ │ ├── docs-content-creation.md │ │ ├── docs-content-planning.md │ │ ├── docs-final-assembly.md │ │ ├── docs-project-analysis.md │ │ ├── docs-review-refinement.md │ │ └── prompts.json │ ├── education │ │ ├── prompts.json │ │ └── vault_integrated_notes.md │ ├── general │ │ ├── diagnose.md │ │ └── prompts.json │ ├── promptsConfig.json │ └── testing │ ├── final_verification_test.md │ └── prompts.json ├── README.md ├── scripts │ └── validate-dependencies.js ├── src │ ├── api │ │ └── index.ts │ ├── chain-session │ │ └── manager.ts │ ├── config │ │ └── index.ts │ ├── Dockerfile │ ├── execution │ │ ├── context │ │ │ ├── context-resolver.ts │ │ │ ├── framework-injector.ts │ │ │ └── index.ts │ │ ├── index.ts │ │ ├── parsers │ │ │ ├── argument-parser.ts │ │ │ ├── index.ts │ │ │ └── unified-command-parser.ts │ │ └── types.ts │ ├── frameworks │ │ ├── framework-manager.ts │ │ ├── framework-state-manager.ts │ │ ├── index.ts │ │ ├── integration │ │ │ ├── framework-semantic-integration.ts │ │ │ └── index.ts │ │ ├── methodology │ │ │ ├── guides │ │ │ │ ├── 5w1h-guide.ts │ │ │ │ ├── cageerf-guide.ts │ │ │ │ ├── react-guide.ts │ │ │ │ └── scamper-guide.ts │ │ │ ├── index.ts │ │ │ ├── interfaces.ts │ │ │ └── registry.ts │ │ ├── prompt-guidance │ │ │ ├── index.ts │ │ │ ├── methodology-tracker.ts │ │ │ ├── service.ts │ │ │ ├── system-prompt-injector.ts │ │ │ └── template-enhancer.ts │ │ └── types │ │ ├── index.ts │ │ ├── integration-types.ts │ │ ├── methodology-types.ts │ │ └── prompt-guidance-types.ts │ ├── gates │ │ ├── constants.ts │ │ ├── core │ │ │ ├── gate-definitions.ts │ │ │ ├── gate-loader.ts │ │ │ ├── gate-validator.ts │ │ │ ├── index.ts │ │ │ └── temporary-gate-registry.ts │ │ ├── definitions │ │ │ ├── code-quality.json │ │ │ ├── content-structure.json │ │ │ ├── educational-clarity.json │ │ │ ├── framework-compliance.json │ │ │ ├── research-quality.json │ │ │ ├── security-awareness.json │ │ │ └── technical-accuracy.json │ │ ├── gate-state-manager.ts │ │ ├── guidance │ │ │ ├── FrameworkGuidanceFilter.ts │ │ │ └── GateGuidanceRenderer.ts │ │ ├── index.ts │ │ ├── intelligence │ │ │ ├── GatePerformanceAnalyzer.ts │ │ │ └── GateSelectionEngine.ts │ │ ├── templates │ │ │ ├── code_quality_validation.md │ │ │ ├── educational_clarity_validation.md │ │ │ ├── framework_compliance_validation.md │ │ │ ├── research_self_validation.md │ │ │ ├── security_validation.md │ │ │ ├── structure_validation.md │ │ │ └── technical_accuracy_validation.md │ │ └── types.ts │ ├── index.ts │ ├── logging │ │ └── index.ts │ ├── mcp-tools │ │ ├── config-utils.ts │ │ ├── constants.ts │ │ ├── index.ts │ │ ├── prompt-engine │ │ │ ├── core │ │ │ │ ├── engine.ts │ │ │ │ ├── executor.ts │ │ │ │ ├── index.ts │ │ │ │ └── types.ts │ │ │ ├── index.ts │ │ │ ├── processors │ │ │ │ ├── response-formatter.ts │ │ │ │ └── template-processor.ts │ │ │ └── utils │ │ │ ├── category-extractor.ts │ │ │ ├── classification.ts │ │ │ ├── context-builder.ts │ │ │ └── validation.ts │ │ ├── prompt-manager │ │ │ ├── analysis │ │ │ │ ├── comparison-engine.ts │ │ │ │ ├── gate-analyzer.ts │ │ │ │ └── prompt-analyzer.ts │ │ │ ├── core │ │ │ │ ├── index.ts │ │ │ │ ├── manager.ts │ │ │ │ └── types.ts │ │ │ ├── index.ts │ │ │ ├── operations │ │ │ │ └── file-operations.ts │ │ │ ├── search │ │ │ │ ├── filter-parser.ts │ │ │ │ └── prompt-matcher.ts │ │ │ └── utils │ │ │ ├── category-manager.ts │ │ │ └── validation.ts │ │ ├── shared │ │ │ └── structured-response-builder.ts │ │ ├── system-control.ts │ │ ├── tool-description-manager.ts │ │ └── types │ │ └── shared-types.ts │ ├── metrics │ │ ├── analytics-service.ts │ │ ├── index.ts │ │ └── types.ts │ ├── performance │ │ ├── index.ts │ │ └── monitor.ts │ ├── prompts │ │ ├── category-manager.ts │ │ ├── converter.ts │ │ ├── file-observer.ts │ │ ├── hot-reload-manager.ts │ │ ├── index.ts │ │ ├── loader.ts │ │ ├── promptUtils.ts │ │ ├── registry.ts │ │ └── types.ts │ ├── runtime │ │ ├── application.ts │ │ └── startup.ts │ ├── semantic │ │ ├── configurable-semantic-analyzer.ts │ │ └── integrations │ │ ├── index.ts │ │ └── llm-clients.ts │ ├── server │ │ ├── index.ts │ │ └── transport │ │ └── index.ts │ ├── smithery.yaml │ ├── text-references │ │ ├── conversation.ts │ │ └── index.ts │ ├── types │ │ └── index.ts │ ├── types.ts │ └── utils │ ├── chainUtils.ts │ ├── errorHandling.ts │ ├── global-resource-tracker.ts │ ├── index.ts │ └── jsonUtils.ts ├── tests │ ├── ci-startup-validation.js │ ├── enhanced-validation │ │ ├── contract-validation │ │ │ ├── contract-test-suite.js │ │ │ ├── interface-contracts.js │ │ │ └── interface-contracts.ts │ │ ├── environment-validation │ │ │ ├── environment-parity-checker.js │ │ │ └── environment-test-suite.js │ │ ├── lifecycle-validation │ │ │ ├── lifecycle-test-suite.js │ │ │ └── process-lifecycle-validator.js │ │ └── validation-orchestrator.js │ ├── helpers │ │ └── test-helpers.js │ ├── integration │ │ ├── mcp-tools.test.ts │ │ ├── server-startup.test.ts │ │ └── unified-parsing-integration.test.ts │ ├── performance │ │ ├── parsing-system-benchmark.test.ts │ │ └── server-performance.test.ts │ ├── scripts │ │ ├── consolidated-tools.js │ │ ├── establish-performance-baselines.js │ │ ├── functional-mcp-validation.js │ │ ├── integration-mcp-tools.js │ │ ├── integration-routing-system.js │ │ ├── integration-server-startup.js │ │ ├── integration-unified-parsing.js │ │ ├── methodology-guides.js │ │ ├── performance-memory.js │ │ ├── runtime-integration.js │ │ ├── unit-conversation-manager.js │ │ ├── unit-semantic-analyzer.js │ │ └── unit-unified-parsing.js │ ├── setup.ts │ ├── test-enhanced-parsing.js │ └── unit │ ├── conversation-manager.test.ts │ ├── semantic-analyzer-three-tier.test.ts │ └── unified-parsing-system.test.ts ├── tsconfig.json └── tsconfig.test.json ``` # Files -------------------------------------------------------------------------------- /server/src/frameworks/prompt-guidance/system-prompt-injector.ts: -------------------------------------------------------------------------------- ```typescript 1 | /** 2 | * System Prompt Injector - Phase 3 Implementation 3 | * 4 | * Handles intelligent injection of methodology guidance into system prompts. 5 | * Extracted from framework-manager execution logic for better separation of concerns. 6 | */ 7 | 8 | import { Logger } from "../../logging/index.js"; 9 | import { ConvertedPrompt } from "../../types/index.js"; 10 | import { 11 | IMethodologyGuide, 12 | FrameworkDefinition, 13 | SystemPromptInjectionResult, 14 | PromptGuidanceConfig 15 | } from "../types/index.js"; 16 | import { ContentAnalysisResult } from "../../semantic/configurable-semantic-analyzer.js"; 17 | 18 | /** 19 | * System prompt injection configuration 20 | */ 21 | export interface SystemPromptInjectorConfig { 22 | enableTemplateVariables: boolean; 23 | enableContextualEnhancement: boolean; 24 | enableValidationGuidance: boolean; 25 | injectionMethod: 'template' | 'append' | 'prepend' | 'smart' | 'semantic-aware'; 26 | maxPromptLength: number; 27 | // Phase 4: Semantic awareness settings 28 | enableSemanticAwareness: boolean; 29 | semanticComplexityAdaptation: boolean; 30 | semanticInjectionStrategy: 'conservative' | 'moderate' | 'aggressive'; 31 | } 32 | 33 | /** 34 | * System Prompt Injector 35 | * 36 | * Intelligently injects methodology guidance into system prompts based on 37 | * active framework and prompt characteristics. 38 | */ 39 | export class SystemPromptInjector { 40 | private logger: Logger; 41 | private config: SystemPromptInjectorConfig; 42 | 43 | constructor(logger: Logger, config?: Partial<SystemPromptInjectorConfig>) { 44 | this.logger = logger; 45 | this.config = { 46 | enableTemplateVariables: true, 47 | enableContextualEnhancement: true, 48 | enableValidationGuidance: true, 49 | injectionMethod: 'smart', 50 | maxPromptLength: 4000, 51 | // Phase 4: Semantic awareness defaults 52 | enableSemanticAwareness: true, 53 | semanticComplexityAdaptation: true, 54 | semanticInjectionStrategy: 'moderate', 55 | ...config 56 | }; 57 | } 58 | 59 | /** 60 | * Inject methodology guidance into system prompt 61 | * Extracted from framework-manager.generateSystemPrompt() 62 | * Phase 4: Enhanced with semantic analysis awareness 63 | */ 64 | injectMethodologyGuidance( 65 | prompt: ConvertedPrompt, 66 | framework: FrameworkDefinition, 67 | methodologyGuide: IMethodologyGuide, 68 | semanticAnalysis?: ContentAnalysisResult 69 | ): SystemPromptInjectionResult { 70 | const startTime = Date.now(); 71 | this.logger.debug(`Injecting ${framework.methodology} guidance into system prompt for ${prompt.name}`); 72 | 73 | try { 74 | // Generate base guidance from methodology guide 75 | const baseGuidance = this.generateBaseGuidance(methodologyGuide, prompt, semanticAnalysis); 76 | 77 | // Create enhanced system prompt using framework template 78 | const enhancedPrompt = this.createEnhancedPrompt( 79 | framework.systemPromptTemplate, 80 | prompt, 81 | framework, 82 | baseGuidance, 83 | semanticAnalysis 84 | ); 85 | 86 | // Apply template variable substitution 87 | const finalPrompt = this.applyTemplateVariables(enhancedPrompt, prompt, framework); 88 | 89 | // Validate prompt length and quality 90 | const validationResult = this.validateInjectedPrompt(finalPrompt, prompt, framework); 91 | 92 | const result: SystemPromptInjectionResult = { 93 | originalPrompt: prompt.userMessageTemplate || '', 94 | enhancedPrompt: finalPrompt, 95 | injectedGuidance: baseGuidance, 96 | sourceFramework: framework, 97 | metadata: { 98 | injectionTime: new Date(), 99 | injectionMethod: this.getEffectiveInjectionMethod(semanticAnalysis), 100 | variablesUsed: this.extractUsedVariables(finalPrompt), 101 | confidence: validationResult.confidence, 102 | processingTimeMs: Date.now() - startTime, 103 | validationPassed: validationResult.passed, 104 | // Phase 4: Semantic analysis metadata 105 | semanticAware: semanticAnalysis !== undefined, 106 | semanticComplexity: semanticAnalysis?.complexity, 107 | semanticConfidence: semanticAnalysis?.confidence 108 | } 109 | }; 110 | 111 | this.logger.debug(`System prompt injection completed for ${framework.methodology} in ${result.metadata.processingTimeMs}ms`); 112 | return result; 113 | 114 | } catch (error) { 115 | this.logger.error(`Failed to inject methodology guidance for ${framework.methodology}:`, error); 116 | 117 | // Return fallback result with original prompt 118 | return { 119 | originalPrompt: prompt.userMessageTemplate || '', 120 | enhancedPrompt: prompt.userMessageTemplate || '', 121 | injectedGuidance: '', 122 | sourceFramework: framework, 123 | metadata: { 124 | injectionTime: new Date(), 125 | injectionMethod: 'template', 126 | variablesUsed: [], 127 | confidence: 0, 128 | processingTimeMs: Date.now() - startTime, 129 | validationPassed: false, 130 | error: error instanceof Error ? error.message : 'Unknown error' 131 | } 132 | }; 133 | } 134 | } 135 | 136 | /** 137 | * Generate base methodology guidance from guide 138 | * Extracted from framework-manager.generateSystemPromptTemplate() 139 | * Phase 4: Enhanced with semantic analysis 140 | */ 141 | private generateBaseGuidance( 142 | guide: IMethodologyGuide, 143 | prompt: ConvertedPrompt, 144 | semanticAnalysis?: ContentAnalysisResult 145 | ): string { 146 | // Get methodology-specific system prompt guidance 147 | const baseGuidance = guide.getSystemPromptGuidance({ 148 | promptName: prompt.name, 149 | promptCategory: prompt.category, 150 | promptType: prompt.executionMode || 'prompt' 151 | }); 152 | 153 | // Phase 4: Enhance with semantic-aware contextual guidance 154 | if (this.config.enableContextualEnhancement) { 155 | const contextualGuidance = this.generateContextualGuidance(guide, prompt, semanticAnalysis); 156 | return `${baseGuidance}\n\n${contextualGuidance}`; 157 | } 158 | 159 | // Add semantic complexity-specific guidance if available 160 | if (this.config.enableSemanticAwareness && semanticAnalysis) { 161 | const semanticGuidance = this.generateSemanticGuidance(guide, semanticAnalysis); 162 | if (semanticGuidance) { 163 | return `${baseGuidance}\n\n${semanticGuidance}`; 164 | } 165 | } 166 | 167 | return baseGuidance; 168 | } 169 | 170 | /** 171 | * Create enhanced system prompt with methodology integration 172 | * Phase 4: Enhanced with semantic analysis awareness 173 | */ 174 | private createEnhancedPrompt( 175 | template: string, 176 | prompt: ConvertedPrompt, 177 | framework: FrameworkDefinition, 178 | guidance: string, 179 | semanticAnalysis?: ContentAnalysisResult 180 | ): string { 181 | // Use smart injection method by default 182 | switch (this.config.injectionMethod) { 183 | case 'template': 184 | return this.injectViaTemplate(template, guidance); 185 | case 'append': 186 | return `${template}\n\n${guidance}`; 187 | case 'prepend': 188 | return `${guidance}\n\n${template}`; 189 | case 'semantic-aware': 190 | return this.semanticAwareInject(template, guidance, prompt, framework, semanticAnalysis); 191 | case 'smart': 192 | default: 193 | return this.smartInject(template, guidance, prompt, framework, semanticAnalysis); 194 | } 195 | } 196 | 197 | /** 198 | * Smart injection that adapts to prompt characteristics 199 | * Phase 4: Enhanced with semantic analysis awareness 200 | */ 201 | private smartInject( 202 | template: string, 203 | guidance: string, 204 | prompt: ConvertedPrompt, 205 | framework: FrameworkDefinition, 206 | semanticAnalysis?: ContentAnalysisResult 207 | ): string { 208 | // Use semantic analysis if available and semantic awareness is enabled 209 | if (this.config.enableSemanticAwareness && semanticAnalysis) { 210 | return this.semanticAwareInject(template, guidance, prompt, framework, semanticAnalysis); 211 | } 212 | 213 | // Fallback to original smart injection logic 214 | // For complex prompts or chain types, use template integration 215 | if (prompt.executionMode === 'chain' || (prompt.arguments && prompt.arguments.length > 3)) { 216 | return this.injectViaTemplate(template, guidance); 217 | } 218 | 219 | // For simple prompts, append guidance 220 | return `${template}\n\n## ${framework.methodology} Methodology Guidance\n\n${guidance}`; 221 | } 222 | 223 | /** 224 | * Inject guidance via template replacement 225 | */ 226 | private injectViaTemplate(template: string, guidance: string): string { 227 | // Look for guidance placeholder in template 228 | if (template.includes('{METHODOLOGY_GUIDANCE}')) { 229 | return template.replace('{METHODOLOGY_GUIDANCE}', guidance); 230 | } 231 | 232 | // If no placeholder, append to template 233 | return `${template}\n\n${guidance}`; 234 | } 235 | 236 | /** 237 | * Apply template variable substitution 238 | * Extracted from framework-manager.generateSystemPrompt() 239 | */ 240 | private applyTemplateVariables( 241 | prompt: string, 242 | convertedPrompt: ConvertedPrompt, 243 | framework: FrameworkDefinition 244 | ): string { 245 | if (!this.config.enableTemplateVariables) { 246 | return prompt; 247 | } 248 | 249 | let processedPrompt = prompt; 250 | 251 | // Replace standard template variables 252 | processedPrompt = processedPrompt.replace(/\{PROMPT_NAME\}/g, convertedPrompt.name || 'Prompt'); 253 | processedPrompt = processedPrompt.replace(/\{PROMPT_CATEGORY\}/g, convertedPrompt.category || 'general'); 254 | processedPrompt = processedPrompt.replace(/\{FRAMEWORK_NAME\}/g, framework.name); 255 | processedPrompt = processedPrompt.replace(/\{METHODOLOGY\}/g, framework.methodology); 256 | 257 | // Replace prompt-specific variables 258 | if (convertedPrompt.executionMode) { 259 | processedPrompt = processedPrompt.replace(/\{PROMPT_TYPE\}/g, convertedPrompt.executionMode); 260 | } 261 | 262 | return processedPrompt; 263 | } 264 | 265 | /** 266 | * Generate contextual guidance based on prompt characteristics 267 | * Phase 4: Enhanced with semantic analysis 268 | */ 269 | private generateContextualGuidance( 270 | guide: IMethodologyGuide, 271 | prompt: ConvertedPrompt, 272 | semanticAnalysis?: ContentAnalysisResult 273 | ): string { 274 | const contextParts = []; 275 | 276 | // Phase 4: Use semantic analysis for enhanced contextual guidance 277 | if (semanticAnalysis && this.config.enableSemanticAwareness) { 278 | // Add semantic complexity-based guidance 279 | switch (semanticAnalysis.complexity) { 280 | case 'high': 281 | contextParts.push(`High complexity detected - apply ${guide.methodology} with extra attention to systematic breakdown and validation.`); 282 | break; 283 | case 'medium': 284 | contextParts.push(`Medium complexity detected - ensure ${guide.methodology} methodology is applied comprehensively.`); 285 | break; 286 | case 'low': 287 | contextParts.push(`Low complexity detected - apply ${guide.methodology} efficiently while maintaining quality.`); 288 | break; 289 | } 290 | 291 | // Add semantic execution characteristics guidance 292 | if (semanticAnalysis.executionCharacteristics.hasStructuredReasoning) { 293 | contextParts.push(`Structured reasoning detected - leverage ${guide.methodology} systematic approach.`); 294 | } 295 | 296 | if (semanticAnalysis.executionCharacteristics.hasComplexAnalysis) { 297 | contextParts.push(`Complex analysis patterns detected - emphasize ${guide.methodology} analytical rigor.`); 298 | } 299 | 300 | // Add semantic confidence-based guidance 301 | if (semanticAnalysis.confidence < 0.7) { 302 | contextParts.push(`Uncertain semantic analysis - apply ${guide.methodology} with additional validation steps.`); 303 | } 304 | } else { 305 | // Fallback to original logic when semantic analysis unavailable 306 | // Add complexity-based guidance 307 | if (prompt.arguments && prompt.arguments.length > 2) { 308 | contextParts.push(`This prompt has multiple parameters - apply ${guide.methodology} systematically to each component.`); 309 | } 310 | 311 | // Add type-specific guidance 312 | if (prompt.executionMode === 'chain') { 313 | contextParts.push(`Chain execution detected - maintain ${guide.methodology} consistency across all steps.`); 314 | } 315 | 316 | // Add category-specific guidance 317 | if (prompt.category === 'analysis') { 318 | contextParts.push(`Analysis prompt detected - emphasize thorough ${guide.methodology} analytical phases.`); 319 | } 320 | } 321 | 322 | return contextParts.join('\n'); 323 | } 324 | 325 | /** 326 | * Validate injected prompt quality and characteristics 327 | */ 328 | private validateInjectedPrompt( 329 | prompt: string, 330 | originalPrompt: ConvertedPrompt, 331 | framework: FrameworkDefinition 332 | ): { passed: boolean; confidence: number; issues: string[] } { 333 | const issues: string[] = []; 334 | let confidence = 1.0; 335 | 336 | // Check prompt length 337 | if (prompt.length > this.config.maxPromptLength) { 338 | issues.push(`Prompt length (${prompt.length}) exceeds maximum (${this.config.maxPromptLength})`); 339 | confidence -= 0.2; 340 | } 341 | 342 | // Check methodology integration 343 | if (!prompt.toLowerCase().includes(framework.methodology.toLowerCase())) { 344 | issues.push(`Methodology ${framework.methodology} not clearly referenced in prompt`); 345 | confidence -= 0.3; 346 | } 347 | 348 | // Check template variable resolution 349 | const unresolvedVariables = prompt.match(/\{[A-Z_]+\}/g); 350 | if (unresolvedVariables && unresolvedVariables.length > 0) { 351 | issues.push(`Unresolved template variables: ${unresolvedVariables.join(', ')}`); 352 | confidence -= 0.1 * unresolvedVariables.length; 353 | } 354 | 355 | // Ensure minimum confidence 356 | confidence = Math.max(confidence, 0); 357 | 358 | return { 359 | passed: issues.length === 0, 360 | confidence, 361 | issues 362 | }; 363 | } 364 | 365 | /** 366 | * Phase 4: Semantic-aware injection that adapts based on semantic analysis 367 | */ 368 | private semanticAwareInject( 369 | template: string, 370 | guidance: string, 371 | prompt: ConvertedPrompt, 372 | framework: FrameworkDefinition, 373 | semanticAnalysis?: ContentAnalysisResult 374 | ): string { 375 | if (!semanticAnalysis) { 376 | return this.injectViaTemplate(template, guidance); 377 | } 378 | 379 | // Determine injection strategy based on semantic complexity and characteristics 380 | const injectionStrategy = this.determineSemanticInjectionStrategy(semanticAnalysis); 381 | 382 | switch (injectionStrategy) { 383 | case 'minimal': 384 | // Low complexity - simple append 385 | return `${template}\n\n${guidance}`; 386 | 387 | case 'structured': 388 | // Medium complexity - organized injection 389 | return `${template}\n\n## ${framework.methodology} Methodology Guidance\n\n${guidance}`; 390 | 391 | case 'comprehensive': 392 | // High complexity - full template integration 393 | return this.injectViaTemplate(template, `## ${framework.methodology} Methodology Framework\n\n${guidance}`); 394 | 395 | default: 396 | return this.injectViaTemplate(template, guidance); 397 | } 398 | } 399 | 400 | /** 401 | * Phase 4: Generate semantic-specific guidance based on analysis results 402 | */ 403 | private generateSemanticGuidance( 404 | guide: IMethodologyGuide, 405 | semanticAnalysis: ContentAnalysisResult 406 | ): string { 407 | const guidanceParts = []; 408 | 409 | // Add analysis mode-specific guidance 410 | if (semanticAnalysis.analysisMetadata.mode === 'semantic') { 411 | guidanceParts.push(`Semantic analysis mode: Apply ${guide.methodology} with intelligent pattern recognition.`); 412 | } else if (semanticAnalysis.analysisMetadata.mode === 'structural') { 413 | guidanceParts.push(`Structural analysis mode: Apply ${guide.methodology} with systematic template analysis.`); 414 | } 415 | 416 | // Add capability-based guidance 417 | if (semanticAnalysis.capabilities.hasSemanticUnderstanding) { 418 | guidanceParts.push(`Enhanced semantic understanding available - leverage for nuanced ${guide.methodology} application.`); 419 | } 420 | 421 | // Add limitation-aware guidance 422 | if (semanticAnalysis.limitations.length > 0) { 423 | guidanceParts.push(`Analysis limitations detected - apply ${guide.methodology} with extra validation.`); 424 | } 425 | 426 | return guidanceParts.length > 0 ? guidanceParts.join('\n') : ''; 427 | } 428 | 429 | /** 430 | * Phase 4: Determine injection strategy based on semantic analysis 431 | */ 432 | private determineSemanticInjectionStrategy(semanticAnalysis: ContentAnalysisResult): 'minimal' | 'structured' | 'comprehensive' { 433 | // Base strategy on configured approach 434 | if (this.config.semanticInjectionStrategy === 'conservative') { 435 | return 'minimal'; 436 | } else if (this.config.semanticInjectionStrategy === 'aggressive') { 437 | return 'comprehensive'; 438 | } 439 | 440 | // Moderate strategy - adapt based on semantic characteristics 441 | const complexityScore = this.calculateSemanticComplexityScore(semanticAnalysis); 442 | 443 | if (complexityScore >= 0.8) { 444 | return 'comprehensive'; 445 | } else if (complexityScore >= 0.5) { 446 | return 'structured'; 447 | } else { 448 | return 'minimal'; 449 | } 450 | } 451 | 452 | /** 453 | * Phase 4: Calculate semantic complexity score for injection decisions 454 | */ 455 | private calculateSemanticComplexityScore(semanticAnalysis: ContentAnalysisResult): number { 456 | let score = 0; 457 | 458 | // Base complexity mapping 459 | switch (semanticAnalysis.complexity) { 460 | case 'high': score += 0.6; break; 461 | case 'medium': score += 0.4; break; 462 | case 'low': score += 0.2; break; 463 | } 464 | 465 | // Execution characteristics influence 466 | const chars = semanticAnalysis.executionCharacteristics; 467 | if (chars.hasStructuredReasoning) score += 0.1; 468 | if (chars.hasComplexAnalysis) score += 0.1; 469 | if (chars.hasChainSteps) score += 0.1; 470 | if (chars.argumentCount > 3) score += 0.1; 471 | 472 | // Confidence influence (higher confidence = more decisive injection) 473 | score += (semanticAnalysis.confidence * 0.2); 474 | 475 | return Math.min(score, 1.0); 476 | } 477 | 478 | /** 479 | * Phase 4: Get effective injection method based on semantic analysis 480 | */ 481 | private getEffectiveInjectionMethod(semanticAnalysis?: ContentAnalysisResult): string { 482 | if (!semanticAnalysis || !this.config.enableSemanticAwareness) { 483 | return this.config.injectionMethod; 484 | } 485 | 486 | if (this.config.injectionMethod === 'semantic-aware') { 487 | const strategy = this.determineSemanticInjectionStrategy(semanticAnalysis); 488 | return `semantic-aware-${strategy}`; 489 | } 490 | 491 | return this.config.injectionMethod; 492 | } 493 | 494 | /** 495 | * Extract variables that were used in template processing 496 | */ 497 | private extractUsedVariables(prompt: string): string[] { 498 | const originalVariables = [ 499 | 'PROMPT_NAME', 'PROMPT_CATEGORY', 'FRAMEWORK_NAME', 500 | 'METHODOLOGY', 'PROMPT_TYPE', 'METHODOLOGY_GUIDANCE' 501 | ]; 502 | 503 | return originalVariables.filter(variable => 504 | !prompt.includes(`{${variable}}`) 505 | ); 506 | } 507 | 508 | /** 509 | * Update injector configuration 510 | */ 511 | updateConfig(config: Partial<SystemPromptInjectorConfig>): void { 512 | this.config = { ...this.config, ...config }; 513 | this.logger.debug('SystemPromptInjector configuration updated', config); 514 | } 515 | 516 | /** 517 | * Get current injector configuration 518 | */ 519 | getConfig(): SystemPromptInjectorConfig { 520 | return { ...this.config }; 521 | } 522 | } 523 | 524 | /** 525 | * Create and configure a SystemPromptInjector instance 526 | */ 527 | export function createSystemPromptInjector( 528 | logger: Logger, 529 | config?: Partial<SystemPromptInjectorConfig> 530 | ): SystemPromptInjector { 531 | return new SystemPromptInjector(logger, config); 532 | } ``` -------------------------------------------------------------------------------- /server/src/frameworks/framework-state-manager.ts: -------------------------------------------------------------------------------- ```typescript 1 | /** 2 | * Stateful Framework State Manager 3 | * 4 | * Manages the active framework methodology state and provides framework switching capabilities. 5 | * This tracks switching mechanics (timing, success/failure, counts) and framework state. 6 | * This is separate from execution strategy analysis - it handles WHICH framework methodology 7 | * to apply (CAGEERF, ReACT, 5W1H, SCAMPER) while semantic analysis handles execution strategies. 8 | */ 9 | 10 | import { EventEmitter } from "events"; 11 | import { Logger } from "../logging/index.js"; 12 | import { FrameworkManager, createFrameworkManager } from "./framework-manager.js"; 13 | import { 14 | FrameworkDefinition, 15 | FrameworkExecutionContext, 16 | FrameworkSelectionCriteria 17 | } from "./types/index.js"; 18 | import * as fs from 'fs/promises'; 19 | import * as path from 'path'; 20 | 21 | /** 22 | * Persisted framework state (saved to file) 23 | */ 24 | export interface PersistedFrameworkState { 25 | version: string; 26 | frameworkSystemEnabled: boolean; 27 | activeFramework: string; 28 | lastSwitchedAt: string; 29 | switchReason: string; 30 | } 31 | 32 | /** 33 | * Framework state information 34 | */ 35 | export interface FrameworkState { 36 | activeFramework: string; 37 | previousFramework: string | null; 38 | switchedAt: Date; 39 | switchReason: string; 40 | isHealthy: boolean; 41 | frameworkSystemEnabled: boolean; // NEW: Controls whether framework system is enabled/disabled 42 | switchingMetrics: { 43 | switchCount: number; 44 | averageResponseTime: number; 45 | errorCount: number; 46 | }; 47 | } 48 | 49 | /** 50 | * Framework switch request 51 | */ 52 | export interface FrameworkSwitchRequest { 53 | targetFramework: string; 54 | reason?: string; 55 | criteria?: FrameworkSelectionCriteria; 56 | } 57 | 58 | /** 59 | * Framework system health information 60 | */ 61 | export interface FrameworkSystemHealth { 62 | status: "healthy" | "degraded" | "error"; 63 | activeFramework: string; 64 | frameworkSystemEnabled: boolean; // NEW: Whether framework system is enabled 65 | availableFrameworks: string[]; 66 | lastSwitchTime: Date | null; 67 | switchingMetrics: { 68 | totalSwitches: number; 69 | successfulSwitches: number; 70 | failedSwitches: number; 71 | averageResponseTime: number; 72 | }; 73 | issues: string[]; 74 | } 75 | 76 | /** 77 | * Stateful Framework State Manager Events 78 | */ 79 | export interface FrameworkStateManagerEvents { 80 | 'framework-switched': (previousFramework: string, newFramework: string, reason: string) => void; 81 | 'framework-error': (framework: string, error: Error) => void; 82 | 'health-changed': (health: FrameworkSystemHealth) => void; 83 | 'framework-system-toggled': (enabled: boolean, reason: string) => void; // NEW: Framework system enabled/disabled 84 | } 85 | 86 | /** 87 | * Stateful Framework State Manager 88 | * 89 | * Maintains framework state across operations and provides switching capabilities 90 | */ 91 | export class FrameworkStateManager extends EventEmitter { 92 | private logger: Logger; 93 | private frameworkManager: FrameworkManager | null = null; 94 | private currentState: FrameworkState; 95 | private switchHistory: Array<{ from: string; to: string; timestamp: Date; reason: string }> = []; 96 | private switchingMetrics = { 97 | totalSwitches: 0, 98 | successfulSwitches: 0, 99 | failedSwitches: 0, 100 | averageResponseTime: 0, 101 | errorCount: 0 102 | }; 103 | private isInitialized: boolean = false; 104 | private runtimeStatePath: string; 105 | 106 | constructor(logger: Logger, serverRoot?: string) { 107 | super(); 108 | this.logger = logger; 109 | 110 | // Set state file path - place in config directory for better organization 111 | const rootPath = path.resolve(serverRoot || process.cwd()); 112 | this.runtimeStatePath = path.join(rootPath, 'runtime-state', 'framework-state.json'); 113 | 114 | // Initialize with default framework state (will be overridden by loadPersistedState) 115 | this.currentState = { 116 | activeFramework: 'CAGEERF', // Default to CAGEERF 117 | previousFramework: null, 118 | switchedAt: new Date(), 119 | switchReason: 'Initial framework selection', 120 | isHealthy: true, 121 | frameworkSystemEnabled: false, // NEW: Framework system disabled by default (changed from true) 122 | switchingMetrics: { 123 | switchCount: 0, 124 | averageResponseTime: 0, 125 | errorCount: 0 126 | } 127 | }; 128 | } 129 | 130 | /** 131 | * Initialize the framework state manager 132 | */ 133 | async initialize(): Promise<void> { 134 | if (this.isInitialized) { 135 | this.logger.debug("FrameworkStateManager already initialized"); 136 | return; 137 | } 138 | 139 | // Load persisted state before setting up framework manager 140 | await this.loadPersistedState(); 141 | 142 | this.logger.info("Initializing Framework State Manager..."); 143 | 144 | try { 145 | // Initialize framework manager 146 | this.frameworkManager = await createFrameworkManager(this.logger); 147 | 148 | // Validate default framework exists 149 | const defaultFramework = this.frameworkManager.getFramework(this.currentState.activeFramework); 150 | if (!defaultFramework) { 151 | throw new Error(`Default framework '${this.currentState.activeFramework}' not found`); 152 | } 153 | 154 | this.isInitialized = true; 155 | this.logger.info(`Framework State Manager initialized with active framework: ${this.currentState.activeFramework}`); 156 | 157 | // Emit initial health status 158 | this.emit('health-changed', this.getSystemHealth()); 159 | 160 | } catch (error) { 161 | this.logger.error("Failed to initialize Framework State Manager:", error); 162 | throw error; 163 | } 164 | } 165 | 166 | /** 167 | * Get current framework state 168 | */ 169 | getCurrentState(): FrameworkState { 170 | this.ensureInitialized(); 171 | return { ...this.currentState }; 172 | } 173 | 174 | /** 175 | * Load persisted state from file 176 | */ 177 | private async loadPersistedState(): Promise<void> { 178 | try { 179 | const stateContent = await fs.readFile(this.runtimeStatePath, 'utf-8'); 180 | const persistedState: PersistedFrameworkState = JSON.parse(stateContent); 181 | 182 | if (this.isValidPersistedState(persistedState)) { 183 | this.currentState.frameworkSystemEnabled = persistedState.frameworkSystemEnabled; 184 | this.currentState.activeFramework = persistedState.activeFramework; 185 | this.currentState.switchedAt = new Date(persistedState.lastSwitchedAt); 186 | this.currentState.switchReason = persistedState.switchReason; 187 | 188 | this.logger.info( 189 | `✅ Loaded framework state cache: ${ 190 | persistedState.frameworkSystemEnabled ? 'enabled' : 'disabled' 191 | }, active: ${persistedState.activeFramework}` 192 | ); 193 | return; 194 | } 195 | 196 | this.logger.warn( 197 | `⚠️ Invalid framework state cache at ${this.runtimeStatePath}, falling back to defaults` 198 | ); 199 | } catch (error: any) { 200 | if (error?.code !== 'ENOENT') { 201 | this.logger.warn( 202 | `⚠️ Failed to load framework state cache ${this.runtimeStatePath}: ${ 203 | error instanceof Error ? error.message : String(error) 204 | }` 205 | ); 206 | } 207 | } 208 | 209 | this.logger.info('📁 No framework state cache found, using defaults'); 210 | await this.saveStateToFile(); 211 | } 212 | 213 | /** 214 | * Save current state to file 215 | */ 216 | private async saveStateToFile(): Promise<void> { 217 | try { 218 | const persistedState: PersistedFrameworkState = { 219 | version: '1.0.0', 220 | frameworkSystemEnabled: this.currentState.frameworkSystemEnabled, 221 | activeFramework: this.currentState.activeFramework, 222 | lastSwitchedAt: this.currentState.switchedAt.toISOString(), 223 | switchReason: this.currentState.switchReason 224 | }; 225 | 226 | const runtimeDir = path.dirname(this.runtimeStatePath); 227 | await fs.mkdir(runtimeDir, { recursive: true }); 228 | 229 | await fs.writeFile( 230 | this.runtimeStatePath, 231 | JSON.stringify(persistedState, null, 2) 232 | ); 233 | this.logger.debug(`💾 Framework state saved to ${this.runtimeStatePath}`); 234 | } catch (error) { 235 | this.logger.error(`❌ Failed to save framework state: ${error instanceof Error ? error.message : String(error)}`); 236 | } 237 | } 238 | 239 | /** 240 | * Validate persisted state structure 241 | */ 242 | private isValidPersistedState(state: any): state is PersistedFrameworkState { 243 | return ( 244 | state && 245 | typeof state.version === 'string' && 246 | typeof state.frameworkSystemEnabled === 'boolean' && 247 | typeof state.activeFramework === 'string' && 248 | typeof state.lastSwitchedAt === 'string' && 249 | typeof state.switchReason === 'string' && 250 | ['CAGEERF', 'ReACT', '5W1H', 'SCAMPER'].includes(state.activeFramework) 251 | ); 252 | } 253 | 254 | /** 255 | * Get active framework definition 256 | */ 257 | getActiveFramework(): FrameworkDefinition { 258 | this.ensureInitialized(); 259 | const framework = this.frameworkManager!.getFramework(this.currentState.activeFramework); 260 | if (!framework) { 261 | throw new Error(`Active framework '${this.currentState.activeFramework}' not found`); 262 | } 263 | return framework; 264 | } 265 | 266 | /** 267 | * Get all available frameworks 268 | */ 269 | getAvailableFrameworks(): FrameworkDefinition[] { 270 | this.ensureInitialized(); 271 | return this.frameworkManager!.listFrameworks(true); // Only enabled frameworks 272 | } 273 | 274 | /** 275 | * Switch to a different framework 276 | */ 277 | async switchFramework(request: FrameworkSwitchRequest): Promise<boolean> { 278 | this.ensureInitialized(); 279 | 280 | const startTime = performance.now(); 281 | this.switchingMetrics.totalSwitches++; 282 | 283 | try { 284 | this.logger.info(`Attempting to switch framework from '${this.currentState.activeFramework}' to '${request.targetFramework}'`); 285 | 286 | // Validate target framework exists 287 | const targetFramework = this.frameworkManager!.getFramework(request.targetFramework); 288 | if (!targetFramework) { 289 | const availableFrameworks = this.frameworkManager!.listFrameworks().map(f => f.id).join(', '); 290 | const errorMsg = `Target framework '${request.targetFramework}' not found. Available frameworks: [${availableFrameworks}]`; 291 | this.logger.error(errorMsg); 292 | throw new Error(errorMsg); 293 | } 294 | 295 | this.logger.debug(`Target framework found: ${targetFramework.name} (${targetFramework.id})`); 296 | 297 | if (!targetFramework.enabled) { 298 | const errorMsg = `Target framework '${request.targetFramework}' (${targetFramework.name}) is disabled`; 299 | this.logger.error(errorMsg); 300 | throw new Error(errorMsg); 301 | } 302 | 303 | // Check if already active 304 | if (this.currentState.activeFramework === request.targetFramework) { 305 | this.logger.info(`Framework '${request.targetFramework}' is already active`); 306 | return true; 307 | } 308 | 309 | // Perform the switch 310 | const previousFramework = this.currentState.activeFramework; 311 | const switchReason = request.reason || `Switched to ${request.targetFramework}`; 312 | 313 | // Update state 314 | this.currentState = { 315 | activeFramework: request.targetFramework, 316 | previousFramework: previousFramework, 317 | switchedAt: new Date(), 318 | switchReason: switchReason, 319 | isHealthy: true, 320 | frameworkSystemEnabled: this.currentState.frameworkSystemEnabled, 321 | switchingMetrics: { 322 | switchCount: this.currentState.switchingMetrics.switchCount + 1, 323 | averageResponseTime: this.currentState.switchingMetrics.averageResponseTime, 324 | errorCount: this.currentState.switchingMetrics.errorCount 325 | } 326 | }; 327 | 328 | // Record switch history 329 | this.switchHistory.push({ 330 | from: previousFramework, 331 | to: request.targetFramework, 332 | timestamp: new Date(), 333 | reason: switchReason 334 | }); 335 | 336 | // Update switching performance metrics 337 | const switchTime = performance.now() - startTime; 338 | this.updateSwitchingMetrics(switchTime, true); 339 | 340 | // Save state to file 341 | this.saveStateToFile().catch(error => { 342 | this.logger.error(`Failed to persist framework switch state: ${error instanceof Error ? error.message : String(error)}`); 343 | }); 344 | 345 | this.logger.info(`✅ Framework switch successful: '${previousFramework}' -> '${request.targetFramework}' (${switchTime.toFixed(1)}ms)`); 346 | this.logger.info(`New active framework: ${targetFramework.name} - ${targetFramework.description}`); 347 | 348 | // Emit events 349 | this.emit('framework-switched', previousFramework, request.targetFramework, switchReason); 350 | this.emit('health-changed', this.getSystemHealth()); 351 | 352 | return true; 353 | 354 | } catch (error) { 355 | const switchTime = performance.now() - startTime; 356 | this.updateSwitchingMetrics(switchTime, false); 357 | this.switchingMetrics.errorCount++; 358 | this.currentState.switchingMetrics.errorCount++; 359 | this.currentState.isHealthy = false; 360 | 361 | this.logger.error(`Failed to switch framework to '${request.targetFramework}':`, error); 362 | this.emit('framework-error', request.targetFramework, error instanceof Error ? error : new Error(String(error))); 363 | 364 | return false; 365 | } 366 | } 367 | 368 | /** 369 | * Generate execution context using active framework 370 | */ 371 | generateExecutionContext(prompt: any, criteria?: FrameworkSelectionCriteria): FrameworkExecutionContext | null { 372 | this.ensureInitialized(); 373 | 374 | // NEW: Return null if framework system is disabled 375 | if (!this.currentState.frameworkSystemEnabled) { 376 | return null; 377 | } 378 | 379 | // Use framework manager to generate context with active framework 380 | const mergedCriteria: FrameworkSelectionCriteria = { 381 | userPreference: this.currentState.activeFramework as any, 382 | ...criteria 383 | }; 384 | 385 | return this.frameworkManager!.generateExecutionContext(prompt, mergedCriteria); 386 | } 387 | 388 | /** 389 | * Get framework system health 390 | */ 391 | getSystemHealth(): FrameworkSystemHealth { 392 | this.ensureInitialized(); 393 | 394 | const issues: string[] = []; 395 | let status: "healthy" | "degraded" | "error" = "healthy"; 396 | 397 | // Check for health issues 398 | if (this.currentState.switchingMetrics.errorCount > 0) { 399 | issues.push(`${this.currentState.switchingMetrics.errorCount} framework switching errors detected`); 400 | status = this.currentState.switchingMetrics.errorCount > 5 ? "error" : "degraded"; 401 | } 402 | 403 | if (!this.currentState.isHealthy) { 404 | issues.push("Framework system is in unhealthy state"); 405 | status = "error"; 406 | } 407 | 408 | const activeFramework = this.frameworkManager!.getFramework(this.currentState.activeFramework); 409 | if (!activeFramework?.enabled) { 410 | issues.push(`Active framework '${this.currentState.activeFramework}' is disabled`); 411 | status = "error"; 412 | } 413 | 414 | return { 415 | status, 416 | activeFramework: this.currentState.activeFramework, 417 | frameworkSystemEnabled: this.currentState.frameworkSystemEnabled, // NEW: Include enabled state 418 | availableFrameworks: this.frameworkManager!.listFrameworks(true).map(f => f.id), 419 | lastSwitchTime: this.switchHistory.length > 0 ? this.switchHistory[this.switchHistory.length - 1].timestamp : null, 420 | switchingMetrics: { ...this.switchingMetrics }, 421 | issues 422 | }; 423 | } 424 | 425 | /** 426 | * Get framework switch history 427 | */ 428 | getSwitchHistory(limit?: number): Array<{ from: string; to: string; timestamp: Date; reason: string }> { 429 | const history = [...this.switchHistory].reverse(); // Most recent first 430 | return limit ? history.slice(0, limit) : history; 431 | } 432 | 433 | /** 434 | * Reset switching performance metrics 435 | */ 436 | resetMetrics(): void { 437 | this.switchingMetrics = { 438 | totalSwitches: 0, 439 | successfulSwitches: 0, 440 | failedSwitches: 0, 441 | averageResponseTime: 0, 442 | errorCount: 0 443 | }; 444 | 445 | this.currentState.switchingMetrics = { 446 | switchCount: 0, 447 | averageResponseTime: 0, 448 | errorCount: 0 449 | }; 450 | 451 | this.logger.info("Framework state manager switching metrics reset"); 452 | } 453 | 454 | /** 455 | * Enable the framework system 456 | */ 457 | enableFrameworkSystem(reason?: string): void { 458 | this.ensureInitialized(); 459 | 460 | if (this.currentState.frameworkSystemEnabled) { 461 | this.logger.info("Framework system is already enabled"); 462 | return; 463 | } 464 | 465 | const enableReason = reason || "Framework system enabled"; 466 | 467 | this.currentState.frameworkSystemEnabled = true; 468 | this.currentState.switchReason = enableReason; 469 | this.currentState.switchedAt = new Date(); 470 | 471 | this.logger.info(`✅ Framework system enabled: ${enableReason}`); 472 | 473 | // Save state to file 474 | this.saveStateToFile().catch(error => { 475 | this.logger.error(`Failed to persist framework enable state: ${error instanceof Error ? error.message : String(error)}`); 476 | }); 477 | 478 | // Emit events 479 | this.emit('framework-system-toggled', true, enableReason); 480 | this.emit('health-changed', this.getSystemHealth()); 481 | } 482 | 483 | /** 484 | * Disable the framework system 485 | */ 486 | disableFrameworkSystem(reason?: string): void { 487 | this.ensureInitialized(); 488 | 489 | if (!this.currentState.frameworkSystemEnabled) { 490 | this.logger.info("Framework system is already disabled"); 491 | return; 492 | } 493 | 494 | const disableReason = reason || "Framework system disabled"; 495 | 496 | this.currentState.frameworkSystemEnabled = false; 497 | this.currentState.switchReason = disableReason; 498 | this.currentState.switchedAt = new Date(); 499 | 500 | this.logger.info(`🚫 Framework system disabled: ${disableReason}`); 501 | 502 | // Save state to file 503 | this.saveStateToFile().catch(error => { 504 | this.logger.error(`Failed to persist framework disable state: ${error instanceof Error ? error.message : String(error)}`); 505 | }); 506 | 507 | // Emit events 508 | this.emit('framework-system-toggled', false, disableReason); 509 | this.emit('health-changed', this.getSystemHealth()); 510 | } 511 | 512 | /** 513 | * Check if framework system is enabled 514 | */ 515 | isFrameworkSystemEnabled(): boolean { 516 | this.ensureInitialized(); 517 | return this.currentState.frameworkSystemEnabled; 518 | } 519 | 520 | /** 521 | * Set framework system enabled state (for config loading) 522 | */ 523 | setFrameworkSystemEnabled(enabled: boolean, reason?: string): void { 524 | if (enabled) { 525 | this.enableFrameworkSystem(reason || "Loaded from configuration"); 526 | } else { 527 | this.disableFrameworkSystem(reason || "Loaded from configuration"); 528 | } 529 | } 530 | 531 | // Private helper methods 532 | 533 | private ensureInitialized(): void { 534 | if (!this.isInitialized || !this.frameworkManager) { 535 | throw new Error("FrameworkStateManager not initialized. Call initialize() first."); 536 | } 537 | } 538 | 539 | private updateSwitchingMetrics(responseTime: number, success: boolean): void { 540 | if (success) { 541 | this.switchingMetrics.successfulSwitches++; 542 | } else { 543 | this.switchingMetrics.failedSwitches++; 544 | } 545 | 546 | // Update average response time for switching operations 547 | const totalOperations = this.switchingMetrics.successfulSwitches + this.switchingMetrics.failedSwitches; 548 | this.switchingMetrics.averageResponseTime = 549 | (this.switchingMetrics.averageResponseTime * (totalOperations - 1) + responseTime) / totalOperations; 550 | 551 | this.currentState.switchingMetrics.averageResponseTime = this.switchingMetrics.averageResponseTime; 552 | } 553 | } 554 | 555 | /** 556 | * Create and initialize framework state manager 557 | */ 558 | export async function createFrameworkStateManager(logger: Logger, serverRoot?: string): Promise<FrameworkStateManager> { 559 | const manager = new FrameworkStateManager(logger, serverRoot); 560 | await manager.initialize(); 561 | return manager; 562 | } 563 | ``` -------------------------------------------------------------------------------- /server/src/index.ts: -------------------------------------------------------------------------------- ```typescript 1 | /** 2 | * MCP Claude Prompts Server - Main Entry Point 3 | * Minimal entry point with comprehensive error handling, health checks, and validation 4 | */ 5 | 6 | import { Logger } from "./logging/index.js"; 7 | import { startApplication } from "./runtime/application.js"; 8 | import { ConfigManager } from "./config/index.js"; 9 | 10 | /** 11 | * Health check and validation state 12 | */ 13 | interface ApplicationHealth { 14 | startup: boolean; 15 | modules: boolean; 16 | server: boolean; 17 | lastCheck: number; 18 | } 19 | 20 | /** 21 | * Application state for health monitoring and rollback 22 | */ 23 | let applicationHealth: ApplicationHealth = { 24 | startup: false, 25 | modules: false, 26 | server: false, 27 | lastCheck: Date.now(), 28 | }; 29 | 30 | let orchestrator: any = null; 31 | let logger: Logger | null = null; 32 | let isShuttingDown = false; 33 | 34 | /** 35 | * Validate application health 36 | */ 37 | async function validateApplicationHealth(): Promise<boolean> { 38 | try { 39 | if (!orchestrator) { 40 | return false; 41 | } 42 | 43 | // Use the orchestrator's comprehensive health validation 44 | const healthCheck = orchestrator.validateHealth(); 45 | 46 | // Update health state with detailed information 47 | applicationHealth = { 48 | startup: healthCheck.modules.foundation, 49 | modules: healthCheck.modules.modulesInitialized, 50 | server: healthCheck.modules.serverRunning, 51 | lastCheck: Date.now(), 52 | }; 53 | 54 | // Log health issues if any 55 | if (!healthCheck.healthy && logger && healthCheck.issues.length > 0) { 56 | logger.warn("Health validation found issues:", healthCheck.issues); 57 | } 58 | 59 | return healthCheck.healthy; 60 | } catch (error) { 61 | if (logger) { 62 | logger.error("Health validation failed:", error); 63 | } 64 | return false; 65 | } 66 | } 67 | 68 | /** 69 | * Rollback mechanism for startup failures 70 | */ 71 | async function rollbackStartup(error: Error): Promise<void> { 72 | // Use stderr for error output to avoid interfering with stdio transport 73 | console.error("Critical startup failure, attempting rollback:", error); 74 | 75 | try { 76 | if (orchestrator) { 77 | console.error( 78 | "Attempting graceful shutdown of partial initialization..." 79 | ); 80 | await orchestrator.shutdown(); 81 | orchestrator = null; 82 | } 83 | 84 | // Reset health state 85 | applicationHealth = { 86 | startup: false, 87 | modules: false, 88 | server: false, 89 | lastCheck: Date.now(), 90 | }; 91 | 92 | console.error("Rollback completed"); 93 | } catch (rollbackError) { 94 | console.error("Error during rollback:", rollbackError); 95 | } 96 | } 97 | 98 | /** 99 | * Check if we're running in a test environment 100 | */ 101 | function isTestEnvironment(): boolean { 102 | return ( 103 | process.env.NODE_ENV === 'test' || 104 | process.argv.includes('--suppress-debug') || 105 | process.argv.includes('--test-mode') || 106 | // Detect GitHub Actions CI environment 107 | process.env.GITHUB_ACTIONS === 'true' || 108 | process.env.CI === 'true' || 109 | // Detect common test runner patterns 110 | process.argv.some(arg => arg.includes('test') || arg.includes('jest') || arg.includes('mocha')) || 111 | // Detect if called from integration test scripts 112 | process.argv[1]?.includes('tests/scripts/') 113 | ); 114 | } 115 | 116 | /** 117 | * Setup periodic health checks 118 | * SUPPRESSED in test environments to prevent hanging processes 119 | */ 120 | function setupHealthMonitoring(): void { 121 | if (!logger) return; 122 | 123 | // Skip health monitoring in test environments to prevent hanging processes 124 | if (isTestEnvironment()) { 125 | logger.debug("Health monitoring suppressed in test environment"); 126 | return; 127 | } 128 | 129 | // Health check every 30 seconds 130 | const healthInterval = setInterval(async () => { 131 | if (isShuttingDown || !logger) return; 132 | 133 | try { 134 | const isHealthy = await validateApplicationHealth(); 135 | if (!isHealthy) { 136 | logger.warn("Health check failed - application may be degraded"); 137 | 138 | // Log current status for debugging 139 | if (orchestrator) { 140 | const diagnostics = orchestrator.getDiagnosticInfo(); 141 | logger.warn("Diagnostic information:", { 142 | health: diagnostics.health, 143 | performance: diagnostics.performance, 144 | errors: diagnostics.errors, 145 | }); 146 | } 147 | } else { 148 | // Periodic performance logging (every 5th health check = 2.5 minutes) 149 | if (Date.now() % (5 * 30000) < 30000) { 150 | const performance = orchestrator.getPerformanceMetrics(); 151 | logger.info("Performance metrics:", { 152 | uptime: `${Math.floor(performance.uptime / 60)} minutes`, 153 | memoryUsage: `${Math.round( 154 | performance.memoryUsage.heapUsed / 1024 / 1024 155 | )}MB`, 156 | prompts: performance.application.promptsLoaded, 157 | categories: performance.application.categoriesLoaded, 158 | }); 159 | } 160 | } 161 | } catch (error) { 162 | logger.error("Error during health check:", error); 163 | 164 | // Emergency diagnostic collection 165 | try { 166 | const emergency = getDetailedDiagnostics(); 167 | logger.error("Emergency diagnostics:", emergency); 168 | } catch (diagError) { 169 | logger.error("Failed to collect emergency diagnostics:", diagError); 170 | } 171 | } 172 | }, 30000); 173 | 174 | logger.info( 175 | "Health monitoring enabled (30-second intervals with performance tracking)" 176 | ); 177 | } 178 | 179 | /** 180 | * Setup comprehensive error handlers 181 | */ 182 | function setupErrorHandlers(): void { 183 | // Handle uncaught exceptions with rollback 184 | process.on("uncaughtException", async (error) => { 185 | console.error("Uncaught exception detected:", error); 186 | 187 | if (logger) { 188 | logger.error( 189 | "Uncaught exception - initiating emergency shutdown:", 190 | error 191 | ); 192 | } 193 | 194 | isShuttingDown = true; 195 | 196 | try { 197 | if (orchestrator) { 198 | await orchestrator.shutdown(); 199 | } 200 | } catch (shutdownError) { 201 | console.error("Error during emergency shutdown:", shutdownError); 202 | } 203 | 204 | process.exit(1); 205 | }); 206 | 207 | // Handle unhandled promise rejections with rollback 208 | process.on("unhandledRejection", async (reason, promise) => { 209 | console.error( 210 | "Unhandled promise rejection at:", 211 | promise, 212 | "reason:", 213 | reason 214 | ); 215 | 216 | if (logger) { 217 | logger.error( 218 | "Unhandled promise rejection - initiating emergency shutdown:", 219 | { reason, promise } 220 | ); 221 | } 222 | 223 | isShuttingDown = true; 224 | 225 | try { 226 | if (orchestrator) { 227 | await orchestrator.shutdown(); 228 | } 229 | } catch (shutdownError) { 230 | console.error("Error during emergency shutdown:", shutdownError); 231 | } 232 | 233 | process.exit(1); 234 | }); 235 | 236 | // Handle SIGINT (Ctrl+C) gracefully 237 | process.on("SIGINT", async () => { 238 | if (logger) { 239 | logger.info("Received SIGINT (Ctrl+C), initiating graceful shutdown..."); 240 | } else { 241 | console.error( 242 | "Received SIGINT (Ctrl+C), initiating graceful shutdown..." 243 | ); 244 | } 245 | 246 | await gracefulShutdown(0); 247 | }); 248 | 249 | // Handle SIGTERM gracefully 250 | process.on("SIGTERM", async () => { 251 | if (logger) { 252 | logger.info("Received SIGTERM, initiating graceful shutdown..."); 253 | } else { 254 | console.error("Received SIGTERM, initiating graceful shutdown..."); 255 | } 256 | 257 | await gracefulShutdown(0); 258 | }); 259 | } 260 | 261 | /** 262 | * Graceful shutdown with validation 263 | */ 264 | async function gracefulShutdown(exitCode: number = 0): Promise<void> { 265 | if (isShuttingDown) { 266 | return; // Prevent multiple shutdown attempts 267 | } 268 | 269 | isShuttingDown = true; 270 | 271 | try { 272 | if (logger) { 273 | logger.info("Starting graceful shutdown sequence..."); 274 | } 275 | 276 | // Validate current state before shutdown 277 | if (orchestrator) { 278 | const status = orchestrator.getStatus(); 279 | if (logger) { 280 | logger.info("Application status before shutdown:", status); 281 | } 282 | 283 | // Perform graceful shutdown 284 | await orchestrator.shutdown(); 285 | 286 | if (logger) { 287 | logger.info("Orchestrator shutdown completed successfully"); 288 | } 289 | } 290 | 291 | // Final health state update 292 | applicationHealth = { 293 | startup: false, 294 | modules: false, 295 | server: false, 296 | lastCheck: Date.now(), 297 | }; 298 | 299 | if (logger) { 300 | logger.info("Graceful shutdown completed successfully"); 301 | } else { 302 | console.error("Graceful shutdown completed successfully"); 303 | } 304 | } catch (error) { 305 | if (logger) { 306 | logger.error("Error during graceful shutdown:", error); 307 | } else { 308 | console.error("Error during graceful shutdown:", error); 309 | } 310 | exitCode = 1; 311 | } 312 | 313 | process.exit(exitCode); 314 | } 315 | 316 | /** 317 | * Display help information 318 | */ 319 | function showHelp(): void { 320 | console.log(` 321 | MCP Claude Prompts Server v1.3.0 - Consolidated Architecture with Systematic Framework Application 322 | 323 | USAGE: 324 | node dist/index.js [OPTIONS] 325 | 326 | OPTIONS: 327 | --transport=TYPE Transport type: stdio (default) or sse 328 | --quiet Minimal output mode (production-friendly) 329 | --verbose Detailed diagnostics and strategy information 330 | --debug-startup Alias for --verbose with extra debugging 331 | --startup-test Validate startup and exit (for testing) 332 | --help Show this help message 333 | 334 | ENVIRONMENT VARIABLES: 335 | MCP_SERVER_ROOT Override server root directory detection (recommended) 336 | MCP_PROMPTS_CONFIG_PATH Direct path to prompts configuration file 337 | 338 | OPTIMIZED STARTUP MODES: 339 | Production: node dist/index.js --quiet --transport=stdio 340 | Development: node dist/index.js --verbose --transport=sse 341 | Debugging: node dist/index.js --debug-startup 342 | Silent: node dist/index.js --quiet 343 | 344 | EXAMPLES: 345 | # Standard usage 346 | node dist/index.js 347 | 348 | # Claude Desktop (recommended configuration) 349 | node dist/index.js --transport=stdio --quiet 350 | 351 | # Development with detailed logging 352 | node dist/index.js --verbose --transport=sse 353 | 354 | # With environment override (fastest startup) 355 | MCP_SERVER_ROOT=/path/to/server node dist/index.js --quiet 356 | 357 | PERFORMANCE FEATURES: 358 | ✓ Optimized strategy ordering (fastest detection first) 359 | ✓ Early termination on first success 360 | ✓ Environment variable bypass for instant detection 361 | ✓ Conditional logging based on verbosity level 362 | ✓ Intelligent fallback with user guidance 363 | 364 | TROUBLESHOOTING: 365 | Use --verbose to see detailed server root detection strategies 366 | Set MCP_SERVER_ROOT environment variable for instant path detection 367 | Use --quiet in production for clean startup logs 368 | 369 | For more information, visit: https://github.com/minipuft/claude-prompts-mcp 370 | `); 371 | } 372 | 373 | /** 374 | * Parse and validate command line arguments 375 | */ 376 | function parseCommandLineArgs(): { shouldExit: boolean; exitCode: number } { 377 | const args = process.argv.slice(2); 378 | 379 | // Check for help flag 380 | if (args.includes("--help") || args.includes("-h")) { 381 | showHelp(); 382 | return { shouldExit: true, exitCode: 0 }; 383 | } 384 | 385 | // Validate transport argument 386 | const transportArg = args.find((arg) => arg.startsWith("--transport=")); 387 | if (transportArg) { 388 | const transport = transportArg.split("=")[1]; 389 | if (!["stdio", "sse"].includes(transport)) { 390 | console.error( 391 | `Error: Invalid transport '${transport}'. Supported: stdio, sse` 392 | ); 393 | console.error("Use --help for usage information"); 394 | return { shouldExit: true, exitCode: 1 }; 395 | } 396 | } 397 | 398 | // Validate that conflicting flags aren't used together 399 | const isQuiet = args.includes("--quiet"); 400 | const isVerbose = 401 | args.includes("--verbose") || args.includes("--debug-startup"); 402 | 403 | if (isQuiet && isVerbose) { 404 | console.error("Error: Cannot use --quiet and --verbose flags together"); 405 | console.error("Use --help for usage information"); 406 | return { shouldExit: true, exitCode: 1 }; 407 | } 408 | 409 | return { shouldExit: false, exitCode: 0 }; 410 | } 411 | 412 | /** 413 | * Main application entry point with comprehensive error handling and validation 414 | */ 415 | async function main(): Promise<void> { 416 | try { 417 | // Parse and validate command line arguments 418 | const { shouldExit, exitCode } = parseCommandLineArgs(); 419 | if (shouldExit) { 420 | process.exit(exitCode); 421 | } 422 | 423 | // Check for startup validation mode (for GitHub Actions) 424 | const args = process.argv.slice(2); 425 | const isStartupTest = args.includes('--startup-test'); 426 | const isCI = process.env.CI === 'true' || process.env.NODE_ENV === 'test'; 427 | const isVerbose = args.includes('--verbose') || args.includes('--debug-startup'); 428 | 429 | if (isStartupTest && isVerbose) { 430 | // In CI mode, use console.log for debug to avoid stderr issues 431 | const debugLog = isCI ? console.log : console.error; 432 | debugLog("DEBUG: Running in startup validation mode"); 433 | debugLog(`DEBUG: Platform: ${process.platform}`); 434 | debugLog(`DEBUG: Node.js version: ${process.version}`); 435 | debugLog(`DEBUG: Working directory: ${process.cwd()}`); 436 | debugLog(`DEBUG: MCP_SERVER_ROOT: ${process.env.MCP_SERVER_ROOT || 'not set'}`); 437 | debugLog(`DEBUG: MCP_PROMPTS_CONFIG_PATH: ${process.env.MCP_PROMPTS_CONFIG_PATH || 'not set'}`); 438 | } 439 | 440 | // Setup error handlers first 441 | setupErrorHandlers(); 442 | 443 | // Use appropriate output stream based on environment - only if verbose 444 | if (isVerbose) { 445 | const statusLog = isCI ? console.log : console.error; 446 | statusLog("Starting MCP Claude Prompts Server..."); 447 | } 448 | 449 | // Initialize the application using the orchestrator 450 | const debugLog = isCI ? console.log : console.error; 451 | if (isVerbose) { 452 | debugLog("DEBUG: About to call startApplication()..."); 453 | } 454 | try { 455 | orchestrator = await startApplication(); 456 | if (isVerbose) { 457 | debugLog("DEBUG: startApplication() completed successfully"); 458 | } 459 | } catch (startupError) { 460 | const error = startupError instanceof Error ? startupError : new Error(String(startupError)); 461 | if (isVerbose) { 462 | debugLog("DEBUG: startApplication() failed with error:", error.message); 463 | debugLog("DEBUG: Error stack:", error.stack); 464 | } 465 | 466 | // Additional diagnostics for Windows 467 | if (isVerbose && process.platform === 'win32') { 468 | debugLog("DEBUG: Windows-specific diagnostics:"); 469 | debugLog(`DEBUG: Process argv: ${JSON.stringify(process.argv)}`); 470 | debugLog(`DEBUG: Environment keys: ${Object.keys(process.env).filter(k => k.startsWith('MCP_')).join(', ')}`); 471 | 472 | // Check if paths exist 473 | const fs = await import('fs'); 474 | const path = await import('path'); 475 | 476 | const serverRoot = process.env.MCP_SERVER_ROOT || process.cwd(); 477 | debugLog(`DEBUG: Checking server root: ${serverRoot}`); 478 | debugLog(`DEBUG: Server root exists: ${fs.existsSync(serverRoot)}`); 479 | 480 | const configPath = path.join(serverRoot, 'config.json'); 481 | debugLog(`DEBUG: Config path: ${configPath}`); 482 | debugLog(`DEBUG: Config exists: ${fs.existsSync(configPath)}`); 483 | 484 | // Use ConfigManager for consistent path resolution 485 | try { 486 | const tempConfigManager = new ConfigManager(configPath); 487 | await tempConfigManager.loadConfig(); 488 | const promptsConfigPath = tempConfigManager.getPromptsFilePath(); 489 | debugLog(`DEBUG: Prompts config path: ${promptsConfigPath}`); 490 | debugLog(`DEBUG: Prompts config exists: ${fs.existsSync(promptsConfigPath)}`); 491 | } catch (tempError) { 492 | debugLog(`DEBUG: Could not load config for path debugging: ${tempError}`); 493 | } 494 | } 495 | 496 | throw error; 497 | } 498 | 499 | // Get logger reference for global error handling 500 | if (isVerbose) { 501 | debugLog("DEBUG: Getting logger reference..."); 502 | } 503 | const modules = orchestrator.getModules(); 504 | logger = modules.logger; 505 | if (isVerbose) { 506 | debugLog("DEBUG: Logger reference obtained"); 507 | } 508 | 509 | // Validate initial startup with detailed diagnostics 510 | if (isVerbose) { 511 | debugLog("DEBUG: About to validate application health..."); 512 | } 513 | const initialHealth = await validateApplicationHealth(); 514 | if (isVerbose) { 515 | debugLog("DEBUG: Health validation result:", initialHealth); 516 | } 517 | 518 | if (!initialHealth) { 519 | // Get detailed health info for debugging 520 | const healthDetails = orchestrator.validateHealth(); 521 | if (isVerbose) { 522 | debugLog("DEBUG: Detailed health check results:", JSON.stringify(healthDetails, null, 2)); 523 | } 524 | 525 | throw new Error( 526 | "Initial health validation failed - application may not be properly initialized. " + 527 | "Health details: " + JSON.stringify(healthDetails.issues) 528 | ); 529 | } 530 | 531 | // If this is a startup test, exit successfully after validation 532 | if (isStartupTest) { 533 | if (isVerbose) { 534 | const successLog = isCI ? console.log : console.error; 535 | successLog("✅ MCP Claude Prompts Server startup validation completed successfully"); 536 | successLog("✅ All phases completed: Foundation → Data Loading → Module Initialization → Server Setup"); 537 | successLog("✅ Health validation passed - server is ready for operation"); 538 | } 539 | await orchestrator.shutdown(); 540 | process.exit(0); 541 | } 542 | 543 | // Log successful startup with details 544 | if (logger) { 545 | logger.info("🚀 MCP Claude Prompts Server started successfully"); 546 | 547 | // Log comprehensive application status 548 | const status = orchestrator.getStatus(); 549 | logger.info("📊 Application status:", { 550 | running: status.running, 551 | transport: status.transport, 552 | promptsLoaded: status.promptsLoaded, 553 | categoriesLoaded: status.categoriesLoaded, 554 | uptime: process.uptime(), 555 | memoryUsage: process.memoryUsage(), 556 | pid: process.pid, 557 | nodeVersion: process.version, 558 | }); 559 | 560 | // Setup health monitoring 561 | setupHealthMonitoring(); 562 | 563 | // Log successful complete initialization 564 | logger.info( 565 | "✅ Application initialization completed - all systems operational" 566 | ); 567 | } 568 | } catch (error) { 569 | // Comprehensive error handling with rollback 570 | console.error("❌ Failed to start MCP Claude Prompts Server:", error); 571 | 572 | if (logger) { 573 | logger.error("Fatal startup error:", error); 574 | } 575 | 576 | // Attempt rollback 577 | await rollbackStartup( 578 | error instanceof Error ? error : new Error(String(error)) 579 | ); 580 | 581 | // Exit with error code 582 | process.exit(1); 583 | } 584 | } 585 | 586 | /** 587 | * Export health check function for external monitoring 588 | */ 589 | export function getApplicationHealth(): ApplicationHealth { 590 | return { ...applicationHealth }; 591 | } 592 | 593 | /** 594 | * Export orchestrator diagnostic information for external monitoring 595 | */ 596 | export function getDetailedDiagnostics(): any { 597 | if (!orchestrator) { 598 | return { 599 | available: false, 600 | reason: "Orchestrator not initialized", 601 | timestamp: new Date().toISOString(), 602 | }; 603 | } 604 | 605 | try { 606 | return { 607 | available: true, 608 | timestamp: new Date().toISOString(), 609 | ...orchestrator.getDiagnosticInfo(), 610 | }; 611 | } catch (error) { 612 | return { 613 | available: false, 614 | reason: `Error collecting diagnostics: ${ 615 | error instanceof Error ? error.message : String(error) 616 | }`, 617 | timestamp: new Date().toISOString(), 618 | }; 619 | } 620 | } 621 | 622 | /** 623 | * Export graceful shutdown for external management 624 | */ 625 | export { gracefulShutdown }; 626 | 627 | // Start the application with comprehensive error handling 628 | main().catch(async (error) => { 629 | console.error("💥 Fatal error during startup:", error); 630 | 631 | // Final fallback - attempt rollback and exit 632 | await rollbackStartup( 633 | error instanceof Error ? error : new Error(String(error)) 634 | ); 635 | process.exit(1); 636 | }); 637 | ``` -------------------------------------------------------------------------------- /server/src/frameworks/methodology/guides/react-guide.ts: -------------------------------------------------------------------------------- ```typescript 1 | /** 2 | * ReACT Methodology Guide 3 | * Provides guidance for applying ReACT (Reasoning and Acting) methodology to prompt creation, 4 | * processing, and execution without hijacking semantic analysis functionality 5 | */ 6 | 7 | import type { ConvertedPrompt } from "../../../types/index.js"; 8 | import { ContentAnalysisResult } from "../../../semantic/configurable-semantic-analyzer.js"; 9 | import { 10 | IMethodologyGuide, 11 | BaseMethodologyGuide, 12 | PromptCreationGuidance, 13 | ProcessingGuidance, 14 | StepGuidance, 15 | MethodologyEnhancement, 16 | MethodologyValidation, 17 | ProcessingStep, 18 | ExecutionStep, 19 | QualityGate, 20 | TemplateEnhancement, 21 | MethodologyToolDescriptions 22 | } from "../interfaces.js"; 23 | 24 | /** 25 | * ReACT Methodology Guide Implementation 26 | * Guides the application of ReACT (Reasoning and Acting) principles without replacing semantic analysis 27 | */ 28 | export class ReACTMethodologyGuide extends BaseMethodologyGuide { 29 | readonly frameworkId = "react"; 30 | readonly frameworkName = "ReACT Framework"; 31 | readonly methodology = "ReACT"; 32 | readonly version = "1.0.0"; 33 | 34 | /** 35 | * Guide prompt creation using ReACT structure 36 | * Helps users create prompts that follow ReACT methodology 37 | */ 38 | guidePromptCreation(intent: string, context?: Record<string, any>): PromptCreationGuidance { 39 | return { 40 | structureGuidance: { 41 | systemPromptSuggestions: [ 42 | "Begin with clear reasoning about the problem", 43 | "Define specific actions to take", 44 | "Establish observation and feedback mechanisms", 45 | "Plan reasoning adjustment based on observations", 46 | "Set criteria for cycle completion" 47 | ], 48 | userTemplateSuggestions: [ 49 | "Structure request using Reason-Act-Observe cycles", 50 | "Provide clear problem statement for reasoning", 51 | "Define specific actions that can be taken", 52 | "Specify what observations should be made", 53 | "Indicate success criteria for completion" 54 | ], 55 | argumentSuggestions: [ 56 | { 57 | name: "problem", 58 | type: "string", 59 | description: "The problem or challenge to address systematically", 60 | methodologyReason: "ReACT requires clear problem definition for effective reasoning", 61 | examples: ["performance optimization", "user experience issue", "technical implementation"] 62 | }, 63 | { 64 | name: "actions", 65 | type: "array", 66 | description: "Potential actions that can be taken", 67 | methodologyReason: "ReACT methodology emphasizes specific, purposeful actions", 68 | examples: ["analyze metrics", "test hypothesis", "implement solution"] 69 | }, 70 | { 71 | name: "success_criteria", 72 | type: "string", 73 | description: "Clear criteria for when the objective is achieved", 74 | methodologyReason: "ReACT cycles need defined completion points", 75 | examples: ["performance improves by 20%", "user satisfaction increases", "tests pass"] 76 | } 77 | ] 78 | }, 79 | 80 | methodologyElements: { 81 | requiredSections: ["Reason", "Act", "Observe"], 82 | optionalSections: ["Adjust", "Continue"], 83 | sectionDescriptions: { 84 | "Reason": "Think through the problem systematically and plan approach", 85 | "Act": "Take specific, purposeful actions based on reasoning", 86 | "Observe": "Analyze results, feedback, and outcomes of actions", 87 | "Adjust": "Modify reasoning and approach based on observations", 88 | "Continue": "Repeat cycles until objective is achieved" 89 | } 90 | }, 91 | 92 | qualityGuidance: { 93 | clarityEnhancements: [ 94 | "Make reasoning explicit and traceable", 95 | "Define actions with clear, measurable outcomes", 96 | "Specify what to observe and how to measure results" 97 | ], 98 | completenessChecks: [ 99 | "Ensure reasoning addresses the core problem", 100 | "Verify actions are specific and actionable", 101 | "Confirm observation mechanisms are defined" 102 | ], 103 | specificityImprovements: [ 104 | "Replace abstract reasoning with concrete analysis steps", 105 | "Define specific metrics for observation phase", 106 | "Include clear decision points for cycle continuation" 107 | ] 108 | } 109 | }; 110 | } 111 | 112 | /** 113 | * Guide template processing with ReACT methodology 114 | */ 115 | guideTemplateProcessing(template: string, executionType: string): ProcessingGuidance { 116 | const reactSteps: ProcessingStep[] = [ 117 | { 118 | id: "reasoning_phase", 119 | name: "Reasoning Phase", 120 | description: "Think through the problem systematically and develop approach", 121 | methodologyBasis: "ReACT Reasoning phase", 122 | order: 1, 123 | required: true 124 | }, 125 | { 126 | id: "action_planning", 127 | name: "Action Planning", 128 | description: "Plan specific, purposeful actions based on reasoning", 129 | methodologyBasis: "ReACT Action phase", 130 | order: 2, 131 | required: true 132 | }, 133 | { 134 | id: "action_execution", 135 | name: "Action Execution", 136 | description: "Execute planned actions systematically", 137 | methodologyBasis: "ReACT Action phase", 138 | order: 3, 139 | required: true 140 | }, 141 | { 142 | id: "observation_analysis", 143 | name: "Observation Analysis", 144 | description: "Analyze results, feedback, and outcomes", 145 | methodologyBasis: "ReACT Observe phase", 146 | order: 4, 147 | required: true 148 | }, 149 | { 150 | id: "reasoning_adjustment", 151 | name: "Reasoning Adjustment", 152 | description: "Adjust approach based on observations", 153 | methodologyBasis: "ReACT cycle continuation", 154 | order: 5, 155 | required: false 156 | }, 157 | { 158 | id: "cycle_evaluation", 159 | name: "Cycle Evaluation", 160 | description: "Evaluate if objective is achieved or cycle should continue", 161 | methodologyBasis: "ReACT cycle management", 162 | order: 6, 163 | required: false 164 | } 165 | ]; 166 | 167 | return { 168 | processingSteps: reactSteps, 169 | 170 | templateEnhancements: { 171 | systemPromptAdditions: [ 172 | "Apply ReACT methodology with reasoning-action cycles", 173 | "Think systematically before taking actions", 174 | "Observe and analyze results after each action", 175 | "Adjust approach based on observations" 176 | ], 177 | userPromptModifications: [ 178 | "Structure response using Reason-Act-Observe cycles", 179 | "Make reasoning explicit and traceable", 180 | "Include observation and adjustment phases" 181 | ], 182 | contextualHints: [ 183 | "Focus on systematic problem-solving approach", 184 | "Emphasize learning from action outcomes", 185 | "Apply iterative reasoning improvement" 186 | ] 187 | }, 188 | 189 | executionFlow: { 190 | preProcessingSteps: [ 191 | "Validate problem definition clarity", 192 | "Confirm available actions are specified", 193 | "Verify observation mechanisms are defined" 194 | ], 195 | postProcessingSteps: [ 196 | "Review reasoning-action alignment", 197 | "Assess observation completeness", 198 | "Evaluate cycle termination criteria" 199 | ], 200 | validationSteps: [ 201 | "Reasoning quality check", 202 | "Action specificity verification", 203 | "Observation mechanism validation", 204 | "Cycle completion assessment" 205 | ] 206 | } 207 | }; 208 | } 209 | 210 | /** 211 | * Guide execution steps using ReACT methodology 212 | */ 213 | guideExecutionSteps(prompt: ConvertedPrompt, semanticAnalysis: ContentAnalysisResult): StepGuidance { 214 | const executionSteps: ExecutionStep[] = [ 215 | { 216 | id: "systematic_reasoning", 217 | name: "Systematic Reasoning", 218 | action: "Think through the problem systematically and develop initial approach", 219 | methodologyPhase: "Reason", 220 | dependencies: [], 221 | expected_output: "Clear reasoning about problem and planned approach" 222 | }, 223 | { 224 | id: "purposeful_action", 225 | name: "Purposeful Action", 226 | action: "Take specific, measurable actions based on reasoning", 227 | methodologyPhase: "Act", 228 | dependencies: ["systematic_reasoning"], 229 | expected_output: "Concrete actions taken with clear objectives" 230 | }, 231 | { 232 | id: "result_observation", 233 | name: "Result Observation", 234 | action: "Observe and analyze results, feedback, and outcomes", 235 | methodologyPhase: "Observe", 236 | dependencies: ["purposeful_action"], 237 | expected_output: "Detailed analysis of action results and feedback" 238 | }, 239 | { 240 | id: "reasoning_adjustment", 241 | name: "Reasoning Adjustment", 242 | action: "Adjust reasoning and approach based on observations", 243 | methodologyPhase: "Adjust", 244 | dependencies: ["result_observation"], 245 | expected_output: "Updated reasoning and modified approach" 246 | }, 247 | { 248 | id: "cycle_continuation", 249 | name: "Cycle Continuation", 250 | action: "Determine if objective is achieved or if cycle should continue", 251 | methodologyPhase: "Continue", 252 | dependencies: ["reasoning_adjustment"], 253 | expected_output: "Decision on cycle completion or continuation" 254 | } 255 | ]; 256 | 257 | // Adjust steps based on execution type from semantic analyzer 258 | const stepEnhancements: Record<string, string[]> = {}; 259 | const stepValidation: Record<string, string[]> = {}; 260 | 261 | if (semanticAnalysis.executionType === "chain") { 262 | if (semanticAnalysis.executionCharacteristics.advancedChainFeatures?.requiresAdvancedExecution) { 263 | // Advanced chains with workflow-like features 264 | stepEnhancements["reasoning_adjustment"] = [ 265 | "Define decision points and branching logic", 266 | "Plan workflow state transitions based on observations", 267 | "Establish error handling for failed actions" 268 | ]; 269 | stepValidation["reasoning_adjustment"] = [ 270 | "Decision logic validation", 271 | "State transition verification", 272 | "Error handling completeness check" 273 | ]; 274 | } else { 275 | // Basic chains 276 | stepEnhancements["systematic_reasoning"] = [ 277 | "Plan reasoning steps in sequence", 278 | "Define dependencies between reasoning phases", 279 | "Establish clear handoff points between steps" 280 | ]; 281 | stepValidation["systematic_reasoning"] = [ 282 | "Step sequence validation", 283 | "Dependency chain verification", 284 | "Handoff point adequacy check" 285 | ]; 286 | } 287 | } 288 | 289 | return { 290 | stepSequence: executionSteps, 291 | stepEnhancements, 292 | stepValidation 293 | }; 294 | } 295 | 296 | /** 297 | * Enhance execution with ReACT methodology 298 | */ 299 | enhanceWithMethodology(prompt: ConvertedPrompt, context: Record<string, any>): MethodologyEnhancement { 300 | const reactGates: QualityGate[] = [ 301 | { 302 | id: "reasoning_quality", 303 | name: "Reasoning Quality", 304 | description: "Verify systematic and logical reasoning approach", 305 | methodologyArea: "Reason", 306 | validationCriteria: [ 307 | "Problem analysis is systematic and thorough", 308 | "Reasoning is explicit and traceable", 309 | "Approach is logically structured" 310 | ], 311 | priority: "high" 312 | }, 313 | { 314 | id: "action_specificity", 315 | name: "Action Specificity", 316 | description: "Ensure actions are specific, purposeful, and measurable", 317 | methodologyArea: "Act", 318 | validationCriteria: [ 319 | "Actions are concrete and specific", 320 | "Actions have clear objectives", 321 | "Actions are measurable and observable" 322 | ], 323 | priority: "high" 324 | }, 325 | { 326 | id: "observation_completeness", 327 | name: "Observation Completeness", 328 | description: "Validate comprehensive observation and analysis of results", 329 | methodologyArea: "Observe", 330 | validationCriteria: [ 331 | "Results are observed systematically", 332 | "Feedback is analyzed thoroughly", 333 | "Outcomes are measured against objectives" 334 | ], 335 | priority: "high" 336 | }, 337 | { 338 | id: "cycle_effectiveness", 339 | name: "Cycle Effectiveness", 340 | description: "Assess effectiveness of reasoning-action cycles", 341 | methodologyArea: "Continue", 342 | validationCriteria: [ 343 | "Cycles show learning and improvement", 344 | "Adjustments are based on observations", 345 | "Progress toward objective is evident" 346 | ], 347 | priority: "medium" 348 | } 349 | ]; 350 | 351 | const templateSuggestions: TemplateEnhancement[] = [ 352 | { 353 | section: "system", 354 | type: "addition", 355 | description: "Add ReACT methodology guidance", 356 | content: "Apply the ReACT methodology: Reason through the problem systematically, take specific purposeful Actions, Observe results and feedback, then adjust your reasoning based on observations. Continue cycles until the objective is achieved.", 357 | methodologyJustification: "Ensures systematic application of reasoning-action cycles", 358 | impact: "high" 359 | }, 360 | { 361 | section: "user", 362 | type: "structure", 363 | description: "Structure response using ReACT cycles", 364 | content: "Please structure your response using ReACT cycles: 1) Reasoning about the problem, 2) Specific actions to take, 3) Observations of results, 4) Reasoning adjustments, 5) Continuation decision.", 365 | methodologyJustification: "Guides systematic problem-solving through reasoning-action cycles", 366 | impact: "medium" 367 | } 368 | ]; 369 | 370 | return { 371 | systemPromptGuidance: this.getSystemPromptGuidance(context), 372 | processingEnhancements: this.guideTemplateProcessing("", "template").processingSteps, 373 | methodologyGates: reactGates, 374 | templateSuggestions, 375 | enhancementMetadata: this.createEnhancementMetadata( 376 | 0.85, 377 | "ReACT methodology provides systematic reasoning-action cycles for problem solving" 378 | ) 379 | }; 380 | } 381 | 382 | /** 383 | * Validate methodology compliance 384 | */ 385 | validateMethodologyCompliance(prompt: ConvertedPrompt): MethodologyValidation { 386 | const combinedText = this.getCombinedText(prompt); 387 | const text = combinedText.toLowerCase(); 388 | 389 | // Check for ReACT phase presence 390 | const phases = { 391 | reason: /reason|think|analy|consider|approach/i.test(text), 392 | act: /act|action|implement|execute|do|perform/i.test(text), 393 | observe: /observe|result|outcome|feedback|measure|assess/i.test(text), 394 | adjust: /adjust|modify|change|improve|refine/i.test(text), 395 | continue: /continue|repeat|cycle|iterate/i.test(text) 396 | }; 397 | 398 | const presentPhases = Object.values(phases).filter(Boolean).length; 399 | const compliance_score = presentPhases / 5; // 5 ReACT phases 400 | 401 | const strengths: string[] = []; 402 | const improvement_areas: string[] = []; 403 | 404 | if (phases.reason) strengths.push("Systematic reasoning approach present"); 405 | else improvement_areas.push("Add systematic reasoning and problem analysis"); 406 | 407 | if (phases.act) strengths.push("Action-oriented approach evident"); 408 | else improvement_areas.push("Include specific, purposeful actions"); 409 | 410 | if (phases.observe) strengths.push("Observation and result analysis mentioned"); 411 | else improvement_areas.push("Add observation and result analysis"); 412 | 413 | if (phases.adjust) strengths.push("Adjustment and improvement considered"); 414 | else improvement_areas.push("Include reasoning adjustment based on observations"); 415 | 416 | const specific_suggestions: TemplateEnhancement[] = []; 417 | 418 | if (!phases.reason) { 419 | specific_suggestions.push({ 420 | section: "system", 421 | type: "addition", 422 | description: "Add systematic reasoning approach", 423 | content: "Begin by reasoning through the problem systematically before taking actions.", 424 | methodologyJustification: "ReACT Reasoning phase requires systematic problem analysis", 425 | impact: "high" 426 | }); 427 | } 428 | 429 | if (!phases.observe) { 430 | specific_suggestions.push({ 431 | section: "system", 432 | type: "addition", 433 | description: "Add observation and result analysis", 434 | content: "Observe and analyze results after taking actions to inform next steps.", 435 | methodologyJustification: "ReACT Observe phase is crucial for learning and adjustment", 436 | impact: "high" 437 | }); 438 | } 439 | 440 | return { 441 | compliant: compliance_score > 0.6, 442 | compliance_score, 443 | strengths, 444 | improvement_areas, 445 | specific_suggestions, 446 | methodology_gaps: improvement_areas 447 | }; 448 | } 449 | 450 | /** 451 | * Get ReACT-specific system prompt guidance 452 | */ 453 | getSystemPromptGuidance(context: Record<string, any>): string { 454 | return `Apply the ReACT methodology systematically: 455 | 456 | **Reason**: Think through the problem systematically and develop a clear approach 457 | **Act**: Take specific, purposeful actions based on your reasoning 458 | **Observe**: Analyze results, feedback, and outcomes of your actions carefully 459 | **Adjust**: Modify your reasoning and approach based on observations 460 | **Continue**: Repeat the cycle until the objective is achieved 461 | 462 | Focus on explicit reasoning, measurable actions, systematic observation, and continuous improvement through reasoning-action cycles. Each cycle should build upon learnings from previous cycles.`; 463 | } 464 | 465 | /** 466 | * Get ReACT-specific tool descriptions 467 | */ 468 | getToolDescriptions(): MethodologyToolDescriptions { 469 | return { 470 | prompt_engine: { 471 | description: "🚀 PROMPT TEMPLATE ENGINE [REACT-ENHANCED]: Processes prompt templates with systematic ReACT (Reasoning-Acting) methodology for iterative problem-solving. Guides systematic Reason → Act → Observe → Adjust cycles for continuous improvement and adaptive execution. WARNING: You are responsible for interpreting and executing the returned content, which contains iterative analytical instructions.", 472 | parameters: { 473 | execution_mode: "Override intelligent auto-detection with ReACT-aware selection (default: auto, iterative reasoning-enhanced)" 474 | } 475 | }, 476 | prompt_manager: { 477 | description: "📝 INTELLIGENT PROMPT MANAGER [REACT-ENHANCED]: Complete lifecycle management with systematic ReACT methodology integration. Creates iterative analysis templates that guide reasoning-action cycles through explicit Reasoning, purposeful Acting, systematic Observation, and continuous Adjustment. Optimized for adaptive problem-solving and iterative improvement tasks.", 478 | parameters: { 479 | action: "Management action with ReACT iterative approach: 'create_template' (reasoning-action cycle templates), 'analyze_type' (reasoning pattern analysis), 'migrate_type' (adaptive conversion), etc." 480 | } 481 | }, 482 | system_control: { 483 | description: "⚙️ INTELLIGENT SYSTEM CONTROL [REACT-ENHANCED]: System administration with ReACT iterative improvement methodology. Guides systematic Reason-Act-Observe-Adjust cycles for framework management, performance monitoring, and adaptive system optimization. Supports continuous improvement through reasoning-based decision making.", 484 | parameters: { 485 | action: "System action with ReACT methodology: 'switch_framework' (reasoning-based framework selection), 'analytics' (observation-based metrics), 'health' (systematic health reasoning), etc." 486 | } 487 | } 488 | }; 489 | } 490 | } ``` -------------------------------------------------------------------------------- /docs/version-history.md: -------------------------------------------------------------------------------- ```markdown 1 | # Version History 2 | 3 | ## Claude Prompts MCP Server Version History 4 | 5 | This document tracks the evolution of the Claude Prompts MCP Server, documenting major releases, features, improvements, and breaking changes. 6 | 7 | --- 8 | 9 | ## Version 1.2.0 - Execution Mode Enhancement & Architectural Consolidation 10 | 11 | **Release Date**: January 2025 12 | **Codename**: "Performance & Precision" 13 | 14 | ### 🎯 Major Features 15 | 16 | #### **Four-Tier Execution Mode System** 17 | 18 | - **New Mode**: Added `prompt` mode for direct high-speed variable substitution 19 | - **Enhanced MCP Schema**: Full execution mode support: `auto`, `prompt`, `template`, `chain` 20 | - **Performance-Aware Auto Detection**: Intelligent structural analysis for optimal mode selection 21 | - **Execution Mode Control**: Users can now specify exact execution mode or use improved auto detection 22 | 23 | #### **Structural Analysis Architecture** 24 | 25 | - **Reliable Detection Logic**: Removed unreliable "analysis intent" detection, replaced with verifiable structural indicators 26 | - **Framework Separation**: Clean separation between current structural capabilities and future LLM semantic analysis 27 | - **Future-Proof Stub**: Added `detectAnalysisIntentLLM()` stub method for future semantic integration 28 | - **Honest Capabilities**: Documentation now accurately represents what the system actually does 29 | 30 | #### **System Consolidation & Performance** 31 | 32 | - **87.5% Architecture Reduction**: Maintained 3 consolidated MCP tools while removing overlapping systems 33 | - **Dependency Validation**: Automated system consolidation validation preventing architecture drift 34 | - **Execution System Cleanup**: Removed deprecated `UnifiedPromptProcessor`, consolidated on `ExecutionCoordinator` 35 | - **Performance Optimization**: Near-instantaneous static prompt execution, optimized template processing 36 | 37 | ### 🛠️ Infrastructure Improvements 38 | 39 | #### **MCP Tool Interface Enhancement** 40 | 41 | - **Complete Mode Coverage**: All four execution modes now accessible via MCP interface 42 | - **Backward Compatibility**: Existing `auto` mode continues to work with improved detection logic 43 | - **Direct Performance Access**: Users can bypass framework overhead for simple variable substitution 44 | - **Consistent Tool Architecture**: Maintained 3-tool consolidation while adding precision control 45 | 46 | #### **Consolidated MCP Tools (3 Intelligent Tools)** 47 | 48 | - **`prompt_engine`**: Unified execution with intelligent analysis, four-tier mode system (auto/prompt/template/chain), and semantic detection 49 | - **`prompt_manager`**: Complete lifecycle management with smart filtering, advanced search syntax, and analysis-driven discovery 50 | - **`system_control`**: Framework management, analytics, health monitoring, and comprehensive system administration 51 | 52 | #### **Framework Performance Integration** 53 | 54 | - **Framework-Aware Detection**: Template mode applies methodology guidance (CAGEERF, ReACT, 5W1H, SCAMPER) 55 | - **Performance-First Default**: Simple variable substitution defaults to prompt mode (instant execution) 56 | - **Quality When Needed**: Complex analysis automatically uses template mode with framework enhancement 57 | - **Chain Mode Optimization**: LLM-driven iterative execution remains unchanged and optimized 58 | 59 | ### 🔧 Technical Enhancements 60 | 61 | #### **Execution Mode Detection Logic** 62 | 63 | ```typescript 64 | // New Detection Algorithm (Performance-Aware) 65 | if (hasChainSteps) return "chain"; 66 | else if (hasComplexTemplateLogic) return "template"; 67 | else if (hasTemplateVars && hasMultipleArgs) return "template"; 68 | else return "prompt"; // Performance-first default 69 | ``` 70 | 71 | #### **Documentation Accuracy Overhaul** 72 | 73 | - **Four Major Docs Updated**: `mcp-tools-reference.md`, `enhanced-gate-system.md`, `prompt-management.md`, `prompt-vs-template-guide.md` 74 | - **Phantom Features Removed**: Eliminated documentation of non-existent tools, APIs, and capabilities 75 | - **MCP Protocol Focus**: All examples now use actual MCP tool interface instead of fictional HTTP APIs 76 | - **Implementation Alignment**: Documentation now matches actual system capabilities 77 | 78 | ### 📊 Performance Impact 79 | 80 | #### **Execution Speed Improvements** 81 | 82 | - **Simple Variable Substitution**: Near-instantaneous execution (significant improvement over framework overhead) 83 | - **Static Content**: Instant execution with no processing overhead 84 | - **Template Processing**: Optimized processing speed with framework enhancement when needed 85 | - **Auto Detection Efficiency**: Substantially reduced unnecessary framework processing for simple cases 86 | 87 | #### **System Health Validation** 88 | 89 | - **CI/CD Pipeline**: All GitHub Actions workflows validated with cross-platform testing 90 | - **Dependency Validation**: Automated consolidation validation prevents system drift 91 | - **TypeScript Compliance**: Full type safety maintained across all changes 92 | - **Build Performance**: No impact on compilation or startup times 93 | 94 | ### 🐛 Architectural Fixes 95 | 96 | #### **System Consolidation** 97 | 98 | - **Removed Duplicate Systems**: Fixed dependency validation violations by removing overlapping execution systems 99 | - **Path Resolution**: Fixed double `prompts/prompts` path issue in prompt manager 100 | - **Import Cleanup**: Removed all references to deprecated systems 101 | - **Type Consistency**: Aligned internal types with MCP schema interface 102 | 103 | #### **Documentation Accuracy** 104 | 105 | - **Tool Count Correction**: Fixed "20+ tools" claims to accurate "3 consolidated tools" 106 | - **Feature Claims**: Removed false "framework effectiveness measurement" and "intelligent selection" claims 107 | - **Usage Examples**: All documentation now shows working MCP tool commands 108 | - **Architecture Representation**: Documentation reflects actual 87.5% consolidation achievement 109 | 110 | ### ⚙️ Quality Assurance 111 | 112 | #### **Testing & Validation** 113 | 114 | - **All Four Modes Tested**: Verified `auto`, `prompt`, `template`, and `chain` modes work correctly 115 | - **Performance Benchmarking**: Confirmed instant static execution and improved auto detection 116 | - **CI/CD Validation**: GitHub Actions workflows pass with architectural changes 117 | - **Integration Testing**: MCP protocol compliance maintained across all changes 118 | 119 | #### **Backward Compatibility** 120 | 121 | - **Zero Breaking Changes**: All existing functionality preserved 122 | - **API Compatibility**: MCP tool interface remains consistent for existing users 123 | - **Template Processing**: All existing prompts work without modification 124 | - **Framework System**: CAGEERF, ReACT, 5W1H, SCAMPER methodologies unchanged 125 | 126 | ### 🎯 Key Benefits 127 | 128 | #### **Performance Optimization** 129 | 130 | - **Substantial Reduction** in unnecessary framework processing for simple variable substitution 131 | - **Instant Execution** for static content and simple prompts 132 | - **Smart Performance Defaults** that choose speed when quality enhancement isn't needed 133 | - **Precision Control** for users who want specific execution behavior 134 | 135 | #### **Architectural Integrity** 136 | 137 | - **Honest Documentation** that accurately represents system capabilities 138 | - **Clean Separation** between current structural analysis and future semantic capabilities 139 | - **System Consolidation** maintained while adding user control options 140 | - **Future-Ready Architecture** with proper stubs for LLM semantic integration 141 | 142 | #### **Developer Experience** 143 | 144 | - **Complete Execution Control**: Direct access to all four execution modes 145 | - **Reliable Auto Detection**: Structural-only logic with 90% confidence rating 146 | - **Clear Performance Trade-offs**: Documentation clearly explains speed vs quality options 147 | - **Validated Architecture**: Automated checks prevent system architecture drift 148 | 149 | --- 150 | 151 | ## Version 1.1.0 - Framework System Enhancement & Gate Integration 152 | 153 | **Release Date**: December 2024 154 | **Codename**: "Framework Foundation" 155 | 156 | ### 🎯 Major Features 157 | 158 | #### **Framework Methodology System** 159 | 160 | - **Framework Manager**: Stateless framework orchestration with methodology guide loading 161 | - **Framework State Manager**: Stateful framework tracking with runtime switching capabilities 162 | - **Methodology Guides**: CAGEERF, ReACT, 5W1H, SCAMPER framework implementations 163 | - **Framework Integration**: Semantic analysis coordination with framework selection 164 | 165 | #### **Enhanced Gate Validation System** 166 | 167 | - **Gate Registry**: Centralized validation rule management with framework awareness 168 | - **Framework-Aware Gates**: Validation criteria that adapt based on active framework 169 | - **Multi-Level Validation**: Support for validation, approval, condition, and quality gate types 170 | - **Integration Layer**: Framework-semantic integration for intelligent validation 171 | 172 | #### **Execution Strategy Architecture** 173 | 174 | - **Strategy Pattern**: Prompt, chain, and workflow execution strategies 175 | - **Execution Engine**: Orchestrated execution with context management and error recovery 176 | - **Template Processing Pipeline**: Framework injection with Nunjucks template processing 177 | - **Conversation State**: Framework-aware conversation enhancement and state persistence 178 | 179 | #### **System Integration & Architecture** 180 | 181 | - **Semantic Analyzer**: Configurable analysis with multiple integration modes 182 | - **Multi-Phase Startup**: Orchestrated initialization with dependency management 183 | - **Framework Switching**: Runtime framework changes with state persistence 184 | - **Integration Factory**: Analysis integration factory for flexible semantic analysis 185 | 186 | ### 🛠️ Infrastructure Improvements 187 | 188 | #### **Enhanced Type System** 189 | 190 | - **Framework Interface Types**: Complete type definitions for methodology guide contracts 191 | - **Execution Strategy Types**: Enhanced interfaces for strategy pattern implementation 192 | - **Integration Types**: Comprehensive types for framework-semantic integration 193 | 194 | #### **Methodology Guide Interface** 195 | 196 | - **IMethodologyGuide Contract**: Standardized interface for all framework implementations 197 | - **Framework Integration Points**: Clear integration patterns for framework-aware components 198 | - **Semantic Analysis Coordination**: Structured interfaces for analysis-framework cooperation 199 | 200 | #### **MCP Architecture Foundation** 201 | 202 | - **Pre-Consolidation Tools**: Early MCP tool implementations before major consolidation 203 | - **Framework Integration**: Initial framework system integration with MCP protocol 204 | - **Multi-Transport Support**: STDIO and SSE transport layer implementations 205 | 206 | ### 🔧 Technical Enhancements 207 | 208 | #### **Framework Methodology Implementation** 209 | 210 | - **CAGEERF Methodology**: Context, Analysis, Goals, Execution, Evaluation, Refinement, Framework 211 | - **ReACT Methodology**: Reasoning and Acting pattern for systematic problem-solving 212 | - **5W1H Methodology**: Who, What, When, Where, Why, How systematic analysis 213 | - **SCAMPER Methodology**: Creative problem-solving framework implementation 214 | 215 | #### **Framework State Management** 216 | 217 | - **Active Framework Tracking**: Runtime framework state with switching capabilities 218 | - **Framework History**: Framework change tracking and performance monitoring 219 | - **State Persistence**: Framework state maintained across server sessions 220 | - **Event-Driven Communication**: Framework state changes communicated through events 221 | 222 | #### **Gate Integration System** 223 | 224 | - **Framework-Aware Evaluation**: Gate validation that adapts to active framework 225 | - **Strategy-Based Gates**: Gate evaluation integrated with execution strategy pattern 226 | - **Methodology Validation**: Framework-specific validation criteria and quality gates 227 | - **Multi-Level Gate Support**: Validation, approval, condition, and quality gate types 228 | 229 | ### 📝 Template Updates 230 | 231 | #### **Framework-Enhanced Templates** 232 | 233 | - **Chain Execution Type**: Templates enhanced with framework methodology guidance 234 | - **Structured Output**: Multi-step analysis process with framework-specific instructions 235 | - **Quality Integration**: Built-in framework validation for template completeness 236 | 237 | #### **Methodology-Aware Processing** 238 | 239 | - **Framework Injection**: Templates enhanced with methodology-specific system prompts 240 | - **Template Pipeline**: Framework injection integrated with Nunjucks processing 241 | - **Context Enhancement**: Framework-aware template context and variable substitution 242 | 243 | ### 🐛 Bug Fixes 244 | 245 | - **TypeScript Compilation**: Fixed interface inheritance issues in type system 246 | - **Async Function Types**: Corrected Promise return types in gate validation 247 | - **Execution Mode Validation**: Fixed type checking for execution mode detection 248 | 249 | ### ⚙️ Configuration Updates 250 | 251 | - **Framework Configuration**: Support for framework selection in prompt metadata 252 | - **Analysis Integration**: Configurable semantic analysis integration modes 253 | - **Framework Switching**: Runtime framework switching configuration options 254 | 255 | ### 📊 System Architecture 256 | 257 | - **Multi-Phase Orchestration**: Enhanced startup orchestration with dependency management 258 | - **Framework Integration**: Framework system integrated with semantic analysis 259 | - **State Management**: Framework state persistence and tracking capabilities 260 | - **Performance Monitoring**: Framework switching performance and health monitoring 261 | 262 | ### 🔄 Migration Guide 263 | 264 | #### **For Users (Claude)** 265 | 266 | - **Framework System**: Access framework switching through MCP system control tools 267 | - **Methodology Selection**: Choose appropriate framework (CAGEERF, ReACT, 5W1H, SCAMPER) for tasks 268 | - **Gate Validation**: Framework-aware validation automatically adapts to active framework 269 | - **Template Enhancement**: Templates now benefit from framework methodology guidance 270 | 271 | #### **For Developers** 272 | 273 | - **Framework Integration**: Import framework managers and methodology guide interfaces 274 | - **Type Imports**: Import framework interface types and strategy pattern interfaces 275 | - **Gate Integration**: Use framework-aware gates for methodology-specific validation 276 | 277 | ### 🎯 Key Benefits 278 | 279 | #### **Framework System Advantages** 280 | 281 | - **Methodology-Driven Architecture** replaces hard-coded framework logic with flexible guides 282 | - **Runtime Framework Switching** enables dynamic methodology selection based on task needs 283 | - **Framework-Aware Validation** adapts quality gates to methodology requirements 284 | - **Systematic Approach** to prompt creation and processing through established frameworks 285 | 286 | #### **Developer Experience** 287 | 288 | - **Clear Framework Architecture** with separation between stateless and stateful components 289 | - **Extensible Guide System** allows easy addition of new methodologies 290 | - **Strategy Pattern Implementation** enables clean execution strategy separation 291 | - **Type-Safe Framework Integration** with comprehensive interfaces and contracts 292 | 293 | #### **System Architecture** 294 | 295 | - **Foundation for Consolidation** establishes architecture later consolidated in v1.2.0 296 | - **Multi-Phase Orchestration** provides robust startup and dependency management 297 | - **Framework Integration Points** enable seamless semantic analysis coordination 298 | - **Scalable Gate System** supports methodology-specific validation criteria 299 | 300 | --- 301 | 302 | ## Version 1.0.0 - Initial Release 303 | 304 | **Release Date**: [Previous Release Date] 305 | **Codename**: "Foundation" 306 | 307 | ### 🎯 Initial Features 308 | 309 | - **Basic MCP Server**: Core Model Context Protocol server implementation 310 | - **Prompt Management**: Basic prompt creation, update, and deletion tools 311 | - **Template Processing**: Nunjucks-based template engine with variable substitution 312 | - **Chain Execution**: Basic support for prompt chains with sequential execution 313 | - **Hot-Reloading**: Dynamic prompt reloading without server restart 314 | - **Multiple Transports**: Support for STDIO and SSE transport protocols 315 | 316 | ### 🛠️ Core Tools (Pre-Consolidation) 317 | 318 | - **Early MCP Tools**: Initial implementation with scattered tool architecture 319 | - **Prompt Management Tools**: Basic prompt creation, update, and deletion functionality 320 | - **System Tools**: Display available prompts and usage information 321 | - **Template Tools**: Edit specific sections and reload prompts without restart 322 | - **Hot-Reload Support**: Dynamic prompt reloading system foundation 323 | - **Multi-Tool Architecture**: Foundation later consolidated into 3 intelligent tools in v1.2.0 324 | 325 | ### 📁 Template System 326 | 327 | - **Markdown Templates**: Support for markdown-based prompt templates 328 | - **Variable Substitution**: Basic `{{variable}}` syntax for dynamic content 329 | - **Category Organization**: Logical grouping of prompts by category 330 | - **Import System**: Modular prompt organization with category-specific files 331 | 332 | ### 🔧 Infrastructure 333 | 334 | - **TypeScript Foundation**: Full TypeScript implementation with type safety 335 | - **Configuration Management**: JSON-based configuration system 336 | - **Logging System**: Comprehensive logging with multiple levels 337 | - **Error Handling**: Basic error handling and validation 338 | 339 | ### 📊 Architecture 340 | 341 | - **Orchestration Engine**: Multi-phase startup with dependency management 342 | - **Module System**: Modular architecture for extensibility 343 | - **Health Monitoring**: Basic health checks and status reporting 344 | - **Transport Layer**: Abstraction for multiple client protocols 345 | 346 | --- 347 | 348 | ## Planned Releases 349 | 350 | ### Version 1.3.0 - LLM Semantic Analysis Integration (Planned) 351 | 352 | - **Semantic Analysis Layer**: Implementation of `detectAnalysisIntentLLM()` with actual LLM integration 353 | - **Intelligent Mode Detection**: Context-aware execution mode selection based on semantic understanding 354 | - **Content Quality Assessment**: LLM-powered analysis of prompt complexity and requirements 355 | - **Smart Framework Selection**: Automatic methodology selection based on task semantics 356 | 357 | ### Version 1.4.0 - Advanced Chain Orchestration (Planned) 358 | 359 | - **Automatic Chain Execution**: Full automation of multi-step processes 360 | - **Conditional Branching**: Support for conditional logic in chains 361 | - **Parallel Execution**: Concurrent execution of independent chain steps 362 | - **Chain Templates**: Pre-built chain templates for common processes 363 | 364 | ### Version 1.5.0 - AI-Powered Enhancements (Planned) 365 | 366 | - **Smart Gate Generation**: AI-generated quality gates based on prompt content 367 | - **Adaptive Execution**: Learning system that improves execution based on usage patterns 368 | - **Intelligent Error Recovery**: AI-powered suggestions for fixing failed executions 369 | - **Content Quality Scoring**: Advanced AI-based content quality assessment 370 | 371 | ### Version 2.0.0 - Enterprise Features (Planned) 372 | 373 | - **Multi-User Support**: User authentication and permission systems 374 | - **Workspace Management**: Isolated prompt workspaces for different projects 375 | - **Advanced Analytics**: Comprehensive analytics dashboard with visualizations 376 | - **API Extensions**: REST API for external integrations 377 | 378 | --- 379 | 380 | ## Migration and Compatibility 381 | 382 | ### Version Compatibility Matrix 383 | 384 | | Feature | v1.0.0 | v1.1.0 | v1.2.0 | v1.3.0 (Planned) | 385 | | ------------------------- | ------ | --------------- | -------------- | ---------------- | 386 | | Basic Prompt Execution | ✅ | ✅ | ✅ Enhanced | ✅ | 387 | | Four-Tier Execution Modes | ❌ | ❌ | ✅ New | ✅ | 388 | | Performance Optimization | ❌ | ❌ | ✅ Instant Execute | ✅ Enhanced | 389 | | Structural Auto Detection | ❌ | ❌ | ✅ New | ✅ LLM-Enhanced | 390 | | Chain Execution | ✅ | ✅ Enhanced | ✅ Optimized | ✅ Automated | 391 | | Framework System | ❌ | ✅ New | ✅ Enhanced | ✅ Advanced | 392 | | Gate Validation | ❌ | ✅ New | ✅ Enhanced | ✅ Advanced | 393 | | MCP Tool Consolidation | ❌ | ❌ | ✅ 87.5% Reduction | ✅ | 394 | | Step Confirmation | ❌ | ❌ | ✅ New | ✅ | 395 | | Architecture Validation | ❌ | ❌ | ✅ New | ✅ | 396 | 397 | ### Breaking Changes 398 | 399 | - **None in v1.1.0**: Full backward compatibility maintained with deprecated tool aliases 400 | - **None in v1.2.0**: Full backward compatibility maintained, all existing functionality preserved 401 | 402 | ### Deprecation Timeline 403 | 404 | - **v1.1.0**: Framework system established, pre-consolidation tool architecture maintained 405 | - **v1.2.0**: Intelligent command routing implementation, enhanced parser with multi-strategy parsing 406 | 407 | --- 408 | 409 | ## Contributing to Releases 410 | 411 | ### Release Process 412 | 413 | 1. **Feature Development**: Implement features in feature branches 414 | 2. **Testing & Validation**: Comprehensive testing of new features 415 | 3. **Documentation Updates**: Update relevant documentation 416 | 4. **Version History**: Update this document with release details 417 | 5. **Release Notes**: Generate detailed release notes 418 | 6. **Version Tagging**: Tag release in version control 419 | 420 | ### Version Numbering 421 | 422 | We follow [Semantic Versioning (SemVer)](https://semver.org/): 423 | 424 | - **MAJOR** version for incompatible API changes 425 | - **MINOR** version for backward-compatible functionality additions 426 | - **PATCH** version for backward-compatible bug fixes 427 | 428 | ### Release Schedule 429 | 430 | - **Major Releases**: Quarterly (every 3 months) 431 | - **Minor Releases**: Monthly (new features and enhancements) 432 | - **Patch Releases**: As needed (bug fixes and security updates) 433 | 434 | --- 435 | 436 | _For detailed technical information about any release, please refer to the corresponding documentation in the `/docs` directory._ 437 | ``` -------------------------------------------------------------------------------- /docs/mcp-tools-reference.md: -------------------------------------------------------------------------------- ```markdown 1 | # MCP Tools Reference (v1.4.0 - Phase 2A Conditional Branching) 2 | 3 | This document provides a comprehensive reference for the 3 intelligent MCP (Model Context Protocol) tools that power the Claude Prompts Server. The server implements **intelligent command routing** with built-in command detection and multi-strategy parsing while maintaining full functionality. 4 | 5 | ## Architecture Overview 6 | 7 | The server uses **three consolidated tools** that provide complete prompt management and execution capabilities: 8 | 9 | - **`prompt_engine`** - Universal execution with systematic analysis and structural detection 10 | - **`prompt_manager`** - Complete lifecycle management with smart filtering and type analysis 11 | - **`system_control`** - Framework management, switching performance analytics, and system administration 12 | 13 | ## Interaction Model 14 | 15 | MCP clients execute server capabilities by sending tool requests. Each tool uses Zod schema validation for type safety and provides structured responses with comprehensive error handling. 16 | 17 | --- 18 | 19 | ## Core Consolidated Tools 20 | 21 | ### `prompt_engine` 🎯 22 | 23 | **Universal Prompt Executor**: Systematically executes prompts, templates, and chains with structural analysis and quality gate validation. Automatically detects execution type and handles step-by-step progression. 24 | 25 | **Key Capabilities**: 26 | - **Structural Analysis**: File structure detection for execution routing (prompt/template/chain) 27 | - **Framework Integration**: Applies active framework methodology (CAGEERF, ReACT, 5W1H, SCAMPER) 28 | - **Quality Gates**: Configurable validation with systematic retry mechanisms 29 | - **LLM-Driven Chains**: Step-by-step workflow coordination with state management 30 | 31 | **Parameters**: 32 | 33 | ```typescript 34 | { 35 | command: string; // Required: Command to execute (>>prompt_name args) 36 | execution_mode?: "auto" | "template" | "chain"; // Optional: Override detection 37 | gate_validation?: boolean; // Optional: Enable quality gates 38 | step_confirmation?: boolean; // Optional: Confirm each chain step 39 | llm_driven_execution?: boolean; // Optional: Enable LLM-driven chain coordination (requires semantic LLM integration) 40 | force_restart?: boolean; // Optional: Force restart chain from beginning, clearing all state 41 | session_id?: string; // Optional: Specific session ID to use or resume 42 | chain_uri?: string; // Optional: Full chain URI for precise session control 43 | } 44 | ``` 45 | 46 | **Execution Types**: 47 | - **Prompt**: Basic variable substitution (fastest, no framework injection) 48 | - **Template**: Framework-enhanced processing with methodology injection 49 | - **Chain**: LLM-driven sequential execution with step validation 50 | 51 | **Example Usage**: 52 | ```bash 53 | # Basic execution with structural detection 54 | prompt_engine >>content_analysis text="my data" 55 | 56 | # Force template execution with framework enhancement 57 | prompt_engine >>analysis_prompt input="data" execution_mode="template" 58 | 59 | # Chain execution with LLM coordination (requires semantic LLM integration enabled) 60 | prompt_engine >>research_chain topic="AI" llm_driven_execution=true step_confirmation=true 61 | ``` 62 | 63 | #### Chain Execution Parameters 64 | 65 | For chain execution, the prompt engine supports advanced session management and URI-based control: 66 | 67 | **Session Control Parameters**: 68 | - `force_restart` - Clear all existing state and restart from beginning 69 | - `session_id` - Resume specific session ID 70 | - `chain_uri` - Use URI-based control for precise session management 71 | 72 | **Example Session Control Usage**: 73 | ```bash 74 | # Auto-resume existing session (default behavior) 75 | prompt_engine >>research_chain topic="AI" 76 | 77 | # Force restart from beginning 78 | prompt_engine >>research_chain topic="AI" force_restart=true 79 | 80 | # Resume specific session 81 | prompt_engine >>research_chain topic="AI" session_id="chain-session-1234" 82 | 83 | # URI-based control 84 | prompt_engine >>research_chain chain_uri="chain://research_chain?force_restart=true" 85 | ``` 86 | 87 | #### Chain URI Syntax 88 | 89 | Chain URIs provide precise control over chain execution with the following syntax: 90 | 91 | **URI Format**: 92 | ``` 93 | chain://chainId[/sessionId[/stepId]][?queryParams] 94 | ``` 95 | 96 | **Components**: 97 | - `chainId` - Chain identifier (required) 98 | - `sessionId` - Specific session ID (optional) 99 | - `stepId` - Specific step ID (optional, for future use) 100 | - `queryParams` - Execution options as query parameters 101 | 102 | **Query Parameters**: 103 | - `force_restart=true` - Force restart clearing all state 104 | - `framework=CAGEERF` - Specify framework methodology 105 | - `step_confirmation=true` - Enable step-by-step confirmation 106 | - `error_handling=continue` - Error handling strategy 107 | - `max_retries=5` - Maximum retry attempts per step 108 | - `conditional_mode=true` - Enable conditional branching execution (Phase 2A) 109 | - `conditional_debug=true` - Enable conditional execution debugging 110 | 111 | **URI Examples**: 112 | ```bash 113 | # Basic execution with auto-session resolution 114 | prompt_engine chain_uri="chain://research_pipeline" 115 | 116 | # Force restart with query parameters 117 | prompt_engine chain_uri="chain://research_pipeline?force_restart=true" 118 | 119 | # Specific session resumption 120 | prompt_engine chain_uri="chain://research_pipeline/session-abc123" 121 | 122 | # Custom framework and options 123 | prompt_engine chain_uri="chain://research_pipeline?framework=CAGEERF&step_confirmation=true" 124 | 125 | # Complex configuration 126 | prompt_engine chain_uri="chain://research_pipeline?force_restart=true&framework=ReACT&error_handling=continue" 127 | 128 | # Conditional branching mode (NEW in Phase 2A) 129 | prompt_engine chain_uri="chain://research_pipeline?conditional_mode=true" 130 | 131 | # Conditional debugging and enhanced workflow 132 | prompt_engine chain_uri="chain://research_pipeline?conditional_mode=true&conditional_debug=true&step_confirmation=true" 133 | ``` 134 | 135 | **Smart Error Recovery**: 136 | When chains get stuck in failed state, the system provides actionable guidance with specific recovery options including restart URIs, session resume URIs, and troubleshooting recommendations. 137 | 138 | #### Advanced Conditional Branching (Phase 2A) 139 | 140 | The system now supports sophisticated conditional execution with safe JavaScript expression evaluation for dynamic workflow control. 141 | 142 | **Conditional Chain Definition Example**: 143 | ```json 144 | { 145 | "id": "analysis_workflow", 146 | "name": "Conditional Analysis Workflow", 147 | "steps": [ 148 | { 149 | "id": "data_validation", 150 | "promptId": "validate_data", 151 | "name": "Data Validation", 152 | "order": 0, 153 | "dependencies": [], 154 | "conditionalExecution": { 155 | "type": "always", 156 | "description": "Always validate input data" 157 | } 158 | }, 159 | { 160 | "id": "simple_analysis", 161 | "promptId": "basic_analysis", 162 | "name": "Simple Analysis", 163 | "order": 1, 164 | "dependencies": ["data_validation"], 165 | "conditionalExecution": { 166 | "type": "conditional", 167 | "expression": "utils.length(steps.data_validation.result) < 1000", 168 | "description": "Use simple analysis for small datasets" 169 | } 170 | }, 171 | { 172 | "id": "complex_analysis", 173 | "promptId": "advanced_analysis", 174 | "name": "Complex Analysis", 175 | "order": 2, 176 | "dependencies": ["data_validation"], 177 | "conditionalExecution": { 178 | "type": "conditional", 179 | "expression": "utils.length(steps.data_validation.result) >= 1000", 180 | "description": "Use advanced analysis for large datasets" 181 | } 182 | }, 183 | { 184 | "id": "error_recovery", 185 | "promptId": "handle_errors", 186 | "name": "Error Recovery", 187 | "order": 3, 188 | "dependencies": ["simple_analysis", "complex_analysis"], 189 | "conditionalExecution": { 190 | "type": "skip_if_success", 191 | "description": "Only run if previous steps had errors" 192 | } 193 | } 194 | ] 195 | } 196 | ``` 197 | 198 | **Conditional Execution Types**: 199 | - `always` - Always execute this step 200 | - `conditional` - Execute based on JavaScript expression evaluation 201 | - `skip_if_error` - Skip if current step has errors 202 | - `skip_if_success` - Skip if current step succeeded (run only on failure) 203 | - `branch_to` - Branch to specific step based on condition 204 | - `skip_to` - Skip to specific step (future use) 205 | 206 | **Expression Evaluation Context**: 207 | Conditional expressions have access to: 208 | - `steps` - Results from previous steps (e.g., `steps.data_validation.result`) 209 | - `vars` - Chain variables (e.g., `vars.userInput`) 210 | - `utils` - Utility functions for safe operations 211 | 212 | **Available Utility Functions**: 213 | - `utils.exists(value)` - Check if value exists (not null/undefined) 214 | - `utils.contains(string, substring)` - Check if string contains substring 215 | - `utils.length(value)` - Get length of string, array, or object 216 | - `utils.toNumber(value)` - Convert to number safely 217 | - `utils.toString(value)` - Convert to string safely 218 | - `utils.matches(string, regex)` - Test regex pattern 219 | 220 | **Security Features**: 221 | - **Expression Validation**: Dangerous patterns (eval, require, process) are blocked 222 | - **Timeout Protection**: Expressions timeout after 5 seconds 223 | - **Sandboxed Execution**: No access to global objects or Node.js APIs 224 | - **Safe Evaluation**: Uses isolated execution context 225 | 226 | **Conditional Execution Examples**: 227 | ```bash 228 | # Enable conditional mode for advanced workflow control 229 | prompt_engine >>analysis_workflow data="large_dataset" conditional_mode=true 230 | 231 | # Enable debugging to see conditional evaluation details 232 | prompt_engine >>analysis_workflow data="test" conditional_mode=true conditional_debug=true 233 | 234 | # Combine with URI syntax for precise control 235 | prompt_engine chain_uri="chain://analysis_workflow?conditional_mode=true&conditional_debug=true&framework=CAGEERF" 236 | ``` 237 | 238 | ### `prompt_manager` 📋 239 | 240 | **Complete Lifecycle Management**: Create, update, delete, analyze, and manage prompts with advanced filtering and type analysis capabilities. 241 | 242 | **Key Capabilities**: 243 | - **Smart Filtering**: Advanced filter syntax (category:, type:, confidence:, etc.) 244 | - **Type Analysis**: Automatic execution type detection and classification 245 | - **Lifecycle Management**: Full CRUD operations with hot-reload support 246 | - **Migration Tools**: Convert between prompt types and analyze existing prompts 247 | 248 | **Actions Available**: 249 | - `list` - List and filter prompts with advanced search 250 | - `create` - Create new prompts with type detection 251 | - `create_prompt` - Create basic prompt (fast variable substitution) 252 | - `create_template` - Create framework-enhanced template 253 | - `update` - Update existing prompts 254 | - `delete` - Remove prompts with cleanup 255 | - `analyze_type` - Analyze prompt and recommend execution type 256 | - `migrate_type` - Convert between prompt and template types 257 | - `modify` - Modify specific sections of prompts 258 | 259 | **Advanced Filtering**: 260 | ```bash 261 | # Filter by category 262 | prompt_manager list filter="category:analysis" 263 | 264 | # Filter by execution type 265 | prompt_manager list filter="type:template" 266 | 267 | # Combined filters 268 | prompt_manager list filter="category:code type:template" 269 | 270 | # Intent-based search 271 | prompt_manager list filter="intent:debugging" 272 | ``` 273 | 274 | **Example Usage**: 275 | ```bash 276 | # List all prompts with advanced filtering 277 | prompt_manager list 278 | 279 | # Create framework-enhanced template 280 | prompt_manager create_template name="code_analyzer" category="development" \ 281 | content="Analyze {{code}} for security and performance issues" 282 | 283 | # Create conditional chain with branching logic (Phase 2A) 284 | prompt_manager create_template name="conditional_analysis" category="analysis" \ 285 | content="Dynamic analysis workflow with conditional branching" \ 286 | chain_steps='[ 287 | { 288 | "promptId": "data_check", 289 | "stepName": "Data Validation", 290 | "conditionalExecution": {"type": "always"} 291 | }, 292 | { 293 | "promptId": "simple_analysis", 294 | "stepName": "Simple Analysis", 295 | "conditionalExecution": { 296 | "type": "conditional", 297 | "expression": "utils.length(steps.data_check.result) < 1000" 298 | } 299 | }, 300 | { 301 | "promptId": "complex_analysis", 302 | "stepName": "Complex Analysis", 303 | "conditionalExecution": { 304 | "type": "conditional", 305 | "expression": "utils.length(steps.data_check.result) >= 1000" 306 | } 307 | } 308 | ]' 309 | 310 | # Analyze existing prompt type 311 | prompt_manager analyze_type prompt_id="my_prompt" 312 | 313 | # Update prompt content 314 | prompt_manager update id="analysis_prompt" content="new template content" 315 | ``` 316 | 317 | ### `system_control` ⚙️ 318 | 319 | **Framework Management & System Administration**: Control framework switching, monitor switching performance, manage system health, and access comprehensive analytics. 320 | 321 | **Key Capabilities**: 322 | - **Framework Switching**: Runtime methodology switching (CAGEERF, ReACT, 5W1H, SCAMPER) 323 | - **Switching Performance**: Track switching mechanics (timing, success rate, error count) 324 | - **System Health**: Monitor server health, module status, and resource usage 325 | - **Usage Analytics**: Framework usage statistics and system performance metrics 326 | 327 | **Actions Available**: 328 | - `status` - Comprehensive system status and framework state 329 | - `switch_framework` - Change active framework methodology 330 | - `list_frameworks` - Show available frameworks with details 331 | - `analytics` - System performance analytics and usage metrics 332 | - `health` - Health monitoring and diagnostic information 333 | - `diagnostics` - Detailed system diagnostics and recommendations 334 | - `reset_metrics` - Reset framework switching performance metrics 335 | - `switch_history` - View framework switching history 336 | - `config` - System configuration management 337 | 338 | **Framework Management**: 339 | ```bash 340 | # Check current framework status 341 | system_control status 342 | 343 | # Switch framework methodology 344 | system_control switch_framework framework="ReACT" reason="Problem-solving focus" 345 | 346 | # View available frameworks 347 | system_control list_frameworks show_details=true 348 | 349 | # Get framework switching history 350 | system_control switch_history limit=10 351 | ``` 352 | 353 | **Analytics & Monitoring**: 354 | ```bash 355 | # View system analytics 356 | system_control analytics include_history=true 357 | 358 | # Check system health 359 | system_control health 360 | 361 | # Run diagnostics 362 | system_control diagnostics 363 | 364 | # Reset switching performance metrics 365 | system_control reset_metrics confirm=true 366 | ``` 367 | 368 | --- 369 | 370 | ## Tool Response Format 371 | 372 | All tools return standardized responses with consistent error handling: 373 | 374 | ```typescript 375 | interface ToolResponse { 376 | content: Array<{ 377 | type: "text" | "resource"; 378 | text?: string; 379 | resource?: { 380 | uri: string; 381 | text: string; 382 | }; 383 | }>; 384 | isError?: boolean; 385 | } 386 | ``` 387 | 388 | --- 389 | 390 | ## Framework System Integration 391 | 392 | ### Available Frameworks 393 | 394 | The system provides **4 proven methodologies** for systematic thinking: 395 | 396 | - **CAGEERF**: Comprehensive structured approach (Context, Analysis, Goals, Execution, Evaluation, Refinement, Framework) 397 | - **ReACT**: Reasoning and Acting pattern for systematic problem-solving 398 | - **5W1H**: Who, What, When, Where, Why, How systematic analysis 399 | - **SCAMPER**: Creative problem-solving (Substitute, Combine, Adapt, Modify, Put to other uses, Eliminate, Reverse) 400 | 401 | ### Framework Selection 402 | 403 | Framework selection uses **rule-based logic** based on: 404 | - **User Preference**: Manual selection takes priority 405 | - **Execution Type**: Templates get framework enhancement, prompts bypass for speed 406 | - **Structural Complexity**: Basic structural analysis informs suggestions 407 | - **Current Active Framework**: Templates use the currently active methodology 408 | 409 | ### Switching Performance Metrics 410 | 411 | The system tracks **framework switching mechanics** (not effectiveness): 412 | - **Switch Count**: Total number of framework switches 413 | - **Switch Success Rate**: Percentage of successful framework switches 414 | - **Switch Time**: Average time for framework switching operations 415 | - **Error Count**: Number of failed switching attempts 416 | 417 | **Note**: Metrics track switching performance, not methodology effectiveness or output quality. 418 | 419 | --- 420 | 421 | ## Usage Examples 422 | 423 | ### Complete Workflow Example 424 | 425 | ```bash 426 | # 1. Check system status and active framework 427 | system_control status 428 | 429 | # 2. Switch to appropriate framework for your task 430 | system_control switch_framework framework="CAGEERF" reason="Complex analysis needed" 431 | 432 | # 3. List relevant prompts 433 | prompt_manager list filter="category:analysis type:template" 434 | 435 | # 4. Execute analysis with framework enhancement 436 | prompt_engine >>comprehensive_analysis data="my research data" execution_mode="template" 437 | 438 | # 5. Check switching performance 439 | system_control analytics 440 | ``` 441 | 442 | ### Chain Workflow Example 443 | 444 | ```bash 445 | # 1. Create analysis chain 446 | prompt_manager create_template name="research_chain" category="research" \ 447 | content="Multi-step research analysis workflow" \ 448 | chain_steps='[{"promptId":"data_collection","stepName":"Data Collection"},{"promptId":"analysis_step","stepName":"Analysis"},{"promptId":"summary_step","stepName":"Summary"}]' 449 | 450 | # 2. Execute chain with step validation and LLM coordination 451 | prompt_engine >>research_chain topic="AI trends" llm_driven_execution=true gate_validation=true 452 | 453 | # 3. Monitor chain execution through system status 454 | system_control status 455 | ``` 456 | 457 | ### Conditional Branching Workflow Example (Phase 2A) 458 | 459 | ```bash 460 | # 1. Create conditional analysis chain with branching logic 461 | prompt_manager create_template name="adaptive_analysis" category="analysis" \ 462 | content="Adaptive analysis with conditional execution paths" \ 463 | chain_steps='[ 464 | { 465 | "promptId": "input_assessment", 466 | "stepName": "Input Assessment", 467 | "conditionalExecution": {"type": "always"} 468 | }, 469 | { 470 | "promptId": "quick_analysis", 471 | "stepName": "Quick Analysis", 472 | "conditionalExecution": { 473 | "type": "conditional", 474 | "expression": "utils.contains(steps.input_assessment.result, \"simple\")" 475 | } 476 | }, 477 | { 478 | "promptId": "deep_analysis", 479 | "stepName": "Deep Analysis", 480 | "conditionalExecution": { 481 | "type": "conditional", 482 | "expression": "utils.contains(steps.input_assessment.result, \"complex\")" 483 | } 484 | }, 485 | { 486 | "promptId": "error_handler", 487 | "stepName": "Error Recovery", 488 | "conditionalExecution": {"type": "skip_if_success"} 489 | } 490 | ]' 491 | 492 | # 2. Execute conditional chain with debugging enabled 493 | prompt_engine >>adaptive_analysis input="complex data analysis task" \ 494 | conditional_mode=true conditional_debug=true step_confirmation=true 495 | 496 | # 3. Alternative execution with URI syntax for precise control 497 | prompt_engine chain_uri="chain://adaptive_analysis?conditional_mode=true&conditional_debug=true&framework=CAGEERF&step_confirmation=true" 498 | 499 | # 4. Monitor conditional execution and branching decisions 500 | system_control status 501 | ``` 502 | 503 | --- 504 | 505 | ## Error Handling 506 | 507 | All tools implement comprehensive error handling: 508 | 509 | - **Validation Errors**: Invalid parameters or missing required fields 510 | - **Execution Errors**: Prompt execution failures with detailed context 511 | - **System Errors**: Framework switching failures or system issues 512 | - **Recovery Suggestions**: Actionable guidance for resolving issues 513 | 514 | --- 515 | 516 | ## Performance Characteristics 517 | 518 | ### Execution Speed Comparison 519 | 520 | ``` 521 | Prompt Execution: 50-200ms (basic variable substitution) 522 | Template Execution: 200-800ms (framework enhancement + validation) 523 | Chain Execution: Variable (depends on step count and LLM response time) 524 | ``` 525 | 526 | ### Tool Consolidation Benefits 527 | 528 | **Intelligent Routing**: Enhanced command detection with automatic tool routing 529 | - **Simplified Interface**: Single tools handle multiple related functions 530 | - **Consistent Experience**: Standardized response format and error handling 531 | - **Reduced Complexity**: Easier to learn and use 532 | - **Maintained Functionality**: All original capabilities preserved 533 | 534 | --- 535 | 536 | ## Migration from Legacy Tools 537 | 538 | If you have references to old tool names, here's the mapping: 539 | 540 | | Legacy Tool | Consolidated Tool | Action | 541 | |------------|------------------|---------| 542 | | `execute_prompt` | `prompt_engine` | Direct replacement | 543 | | `listprompts` | `prompt_manager` | `list` action | 544 | | `update_prompt` | `prompt_manager` | `create` or `update` actions | 545 | | `delete_prompt` | `prompt_manager` | `delete` action | 546 | | `modify_prompt_section` | `prompt_manager` | `modify` action | 547 | | `reload_prompts` | `system_control` | `reload` action | 548 | | `execution_analytics` | `system_control` | `analytics` action | 549 | 550 | ### API Parameter Changes 551 | 552 | **Chain Creation Simplified** (v1.2.0+): 553 | 554 | | Old API (Deprecated) | New API | 555 | |---------------------|---------| 556 | | `isChain=true` | ❌ **Removed** - redundant parameter | 557 | | `chain_steps='[...]'` | ✅ **Chain detection automatic** | 558 | 559 | **Migration Example**: 560 | ```bash 561 | # ❌ OLD - Don't use isChain anymore 562 | prompt_manager create name="chain" isChain=true chain_steps='[...]' 563 | 564 | # ✅ NEW - Chain detected automatically from steps 565 | prompt_manager create name="chain" chain_steps='[{"promptId":"step1","stepName":"Step 1"}]' 566 | ``` 567 | 568 | --- 569 | 570 | ## System Requirements 571 | 572 | - **MCP Client**: Any MCP-compatible client (Claude Desktop, Cursor Windsurf, etc.) 573 | - **Transport**: STDIO (primary) or SSE (web clients) 574 | - **Node.js**: Version 16 or higher 575 | - **Memory**: ~50MB base usage, scales with prompt library size 576 | 577 | --- 578 | 579 | **Documentation Version**: 1.4.0 (Phase 2A Conditional Branching) 580 | **Last Updated**: 2025-01-30 581 | **Compatibility**: Universal MCP client support with advanced conditional workflow capabilities ``` -------------------------------------------------------------------------------- /server/src/prompts/loader.ts: -------------------------------------------------------------------------------- ```typescript 1 | /** 2 | * Prompt Loader Module 3 | * Handles loading prompts from category-specific configuration files and markdown templates 4 | */ 5 | 6 | import * as fs from "fs/promises"; 7 | import { readFile } from "fs/promises"; 8 | import path from "path"; 9 | import { Logger } from "../logging/index.js"; 10 | import { 11 | CategoryPromptsResult, 12 | PromptData, 13 | PromptsConfigFile, 14 | } from "../types/index.js"; 15 | import { safeWriteFile } from "./promptUtils.js"; 16 | import { CategoryManager, createCategoryManager } from "./category-manager.js"; 17 | 18 | /** 19 | * Prompt Loader class 20 | */ 21 | export class PromptLoader { 22 | private logger: Logger; 23 | private categoryManager: CategoryManager; 24 | 25 | constructor(logger: Logger) { 26 | this.logger = logger; 27 | this.categoryManager = createCategoryManager(logger); 28 | } 29 | 30 | /** 31 | * Load prompts from category-specific prompts.json files 32 | */ 33 | async loadCategoryPrompts( 34 | configPath: string 35 | ): Promise<CategoryPromptsResult> { 36 | try { 37 | this.logger.info( 38 | `🔍 PromptLoader: Starting to load category prompts from: ${configPath}` 39 | ); 40 | 41 | // Read the promptsConfig.json file 42 | this.logger.info("📖 Reading promptsConfig.json file..."); 43 | const configContent = await readFile(configPath, "utf8"); 44 | this.logger.info( 45 | `✓ Config file read successfully, ${configContent.length} characters` 46 | ); 47 | 48 | let promptsConfig: PromptsConfigFile; 49 | 50 | try { 51 | this.logger.info("🔧 Parsing promptsConfig.json..."); 52 | promptsConfig = JSON.parse(configContent) as PromptsConfigFile; 53 | this.logger.info("✓ Config file parsed successfully"); 54 | } catch (jsonError) { 55 | this.logger.error( 56 | `❌ Error parsing config file ${configPath}:`, 57 | jsonError 58 | ); 59 | throw new Error( 60 | `Invalid JSON in config file: ${ 61 | jsonError instanceof Error ? jsonError.message : String(jsonError) 62 | }` 63 | ); 64 | } 65 | 66 | // Log the parsed config structure 67 | this.logger.info(`📋 Config structure analysis:`); 68 | this.logger.info( 69 | ` - Categories defined: ${promptsConfig.categories?.length || 0}` 70 | ); 71 | this.logger.info( 72 | ` - Import paths defined: ${promptsConfig.imports?.length || 0}` 73 | ); 74 | 75 | if (promptsConfig.categories?.length > 0) { 76 | this.logger.info("📂 Categories found:"); 77 | promptsConfig.categories.forEach((cat) => { 78 | this.logger.info(` - ${cat.name} (${cat.id}): ${cat.description}`); 79 | }); 80 | } 81 | 82 | if (promptsConfig.imports?.length > 0) { 83 | this.logger.info("📥 Import paths to process:"); 84 | promptsConfig.imports.forEach((importPath, index) => { 85 | this.logger.info(` ${index + 1}. ${importPath}`); 86 | }); 87 | } 88 | 89 | // Ensure required properties exist 90 | if (!promptsConfig.categories) { 91 | this.logger.warn( 92 | `⚠️ Config file ${configPath} does not have a 'categories' array. Initializing it.` 93 | ); 94 | promptsConfig.categories = []; 95 | } 96 | 97 | if (!promptsConfig.imports || !Array.isArray(promptsConfig.imports)) { 98 | this.logger.warn( 99 | `⚠️ Config file ${configPath} does not have a valid 'imports' array. Initializing it.` 100 | ); 101 | promptsConfig.imports = []; 102 | } 103 | 104 | // Load and validate categories using CategoryManager 105 | const categoryValidation = await this.categoryManager.loadCategories(promptsConfig.categories); 106 | 107 | if (!categoryValidation.isValid) { 108 | this.logger.error("❌ Category validation failed:"); 109 | categoryValidation.issues.forEach(issue => this.logger.error(` - ${issue}`)); 110 | throw new Error(`Category validation failed: ${categoryValidation.issues.join('; ')}`); 111 | } 112 | 113 | if (categoryValidation.warnings.length > 0) { 114 | this.logger.warn("⚠️ Category validation warnings:"); 115 | categoryValidation.warnings.forEach(warning => this.logger.warn(` - ${warning}`)); 116 | } 117 | 118 | // Get validated categories 119 | const categories = this.categoryManager.getCategories(); 120 | 121 | // Initialize an array to store all prompts 122 | let allPrompts: PromptData[] = []; 123 | let totalImportProcessed = 0; 124 | let totalImportsFailed = 0; 125 | 126 | this.logger.info( 127 | `🚀 Starting to process ${promptsConfig.imports.length} import paths...` 128 | ); 129 | 130 | // Load prompts from each import path 131 | for (const importPath of promptsConfig.imports) { 132 | totalImportProcessed++; 133 | this.logger.info( 134 | `\n📦 Processing import ${totalImportProcessed}/${promptsConfig.imports.length}: ${importPath}` 135 | ); 136 | 137 | try { 138 | // Construct the full path to the import file 139 | const fullImportPath = path.join( 140 | path.dirname(configPath), 141 | importPath 142 | ); 143 | 144 | this.logger.info(` 🔍 Full path: ${fullImportPath}`); 145 | 146 | // Check if the file exists 147 | try { 148 | await fs.access(fullImportPath); 149 | this.logger.info(` ✓ Import file exists`); 150 | } catch (error) { 151 | this.logger.warn( 152 | ` ⚠️ Import file not found: ${importPath}. Creating empty file.` 153 | ); 154 | 155 | // Create the directory if it doesn't exist 156 | const dir = path.dirname(fullImportPath); 157 | await fs.mkdir(dir, { recursive: true }); 158 | 159 | // Create an empty prompts file 160 | await safeWriteFile( 161 | fullImportPath, 162 | JSON.stringify({ prompts: [] }, null, 2), 163 | "utf8" 164 | ); 165 | this.logger.info(` ✓ Created empty prompts file`); 166 | } 167 | 168 | // Read the file 169 | this.logger.info(` 📖 Reading import file...`); 170 | const fileContent = await readFile(fullImportPath, "utf8"); 171 | this.logger.info( 172 | ` ✓ File read successfully, ${fileContent.length} characters` 173 | ); 174 | 175 | let categoryPromptsFile: any; 176 | 177 | try { 178 | categoryPromptsFile = JSON.parse(fileContent); 179 | this.logger.info(` ✓ Import file parsed successfully`); 180 | } catch (jsonError) { 181 | this.logger.error( 182 | ` ❌ Error parsing import file ${importPath}:`, 183 | jsonError 184 | ); 185 | this.logger.info( 186 | ` 🔧 Creating empty prompts file for ${importPath} due to parsing error.` 187 | ); 188 | categoryPromptsFile = { prompts: [] }; 189 | await safeWriteFile( 190 | fullImportPath, 191 | JSON.stringify(categoryPromptsFile, null, 2), 192 | "utf8" 193 | ); 194 | } 195 | 196 | // Ensure prompts property exists and is an array 197 | if (!categoryPromptsFile.prompts) { 198 | this.logger.warn( 199 | ` ⚠️ Import file ${importPath} does not have a 'prompts' array. Initializing it.` 200 | ); 201 | categoryPromptsFile.prompts = []; 202 | await safeWriteFile( 203 | fullImportPath, 204 | JSON.stringify(categoryPromptsFile, null, 2), 205 | "utf8" 206 | ); 207 | } else if (!Array.isArray(categoryPromptsFile.prompts)) { 208 | this.logger.warn( 209 | ` ⚠️ Import file ${importPath} has an invalid 'prompts' property (not an array). Resetting it.` 210 | ); 211 | categoryPromptsFile.prompts = []; 212 | await safeWriteFile( 213 | fullImportPath, 214 | JSON.stringify(categoryPromptsFile, null, 2), 215 | "utf8" 216 | ); 217 | } 218 | 219 | this.logger.info( 220 | ` 📊 Found ${categoryPromptsFile.prompts.length} prompts in this import` 221 | ); 222 | 223 | // Update the file path to be relative to the category folder 224 | const categoryPath = path.dirname(importPath); 225 | const beforeCount = categoryPromptsFile.prompts.length; 226 | 227 | const categoryPrompts = categoryPromptsFile.prompts 228 | .map((prompt: PromptData, index: number) => { 229 | // Ensure prompt has all required properties 230 | if (!prompt.id || !prompt.name || !prompt.file) { 231 | this.logger.warn( 232 | ` ⚠️ Skipping invalid prompt ${ 233 | index + 1 234 | } in ${importPath}: missing required properties (id: ${!!prompt.id}, name: ${!!prompt.name}, file: ${!!prompt.file})` 235 | ); 236 | return null; 237 | } 238 | 239 | // If the file path is already absolute or starts with the category folder, keep it as is 240 | if ( 241 | prompt.file.startsWith("/") || 242 | prompt.file.startsWith(categoryPath) 243 | ) { 244 | return prompt; 245 | } 246 | 247 | // Otherwise, update the file path to include the category folder 248 | return { 249 | ...prompt, 250 | file: path.join(categoryPath, prompt.file), 251 | }; 252 | }) 253 | .filter(Boolean); // Remove any null entries (invalid prompts) 254 | 255 | const afterCount = categoryPrompts.length; 256 | if (beforeCount !== afterCount) { 257 | this.logger.warn( 258 | ` ⚠️ ${ 259 | beforeCount - afterCount 260 | } prompts were filtered out due to validation issues` 261 | ); 262 | } 263 | 264 | this.logger.info( 265 | ` ✅ Successfully processed ${afterCount} valid prompts from ${importPath}` 266 | ); 267 | 268 | // Add the prompts to the array 269 | allPrompts = [...allPrompts, ...categoryPrompts]; 270 | } catch (error) { 271 | totalImportsFailed++; 272 | this.logger.error( 273 | ` ❌ Error loading prompts from ${importPath}:`, 274 | error 275 | ); 276 | } 277 | } 278 | 279 | this.logger.info(`\n🎯 IMPORT PROCESSING SUMMARY:`); 280 | this.logger.info(` Total imports processed: ${totalImportProcessed}`); 281 | this.logger.info(` Imports failed: ${totalImportsFailed}`); 282 | this.logger.info( 283 | ` Imports succeeded: ${totalImportProcessed - totalImportsFailed}` 284 | ); 285 | this.logger.info(` Total prompts collected: ${allPrompts.length}`); 286 | this.logger.info(` Categories available: ${categories.length}`); 287 | 288 | // Validate category-prompt relationships using CategoryManager 289 | this.logger.info(`🔍 Validating category-prompt relationships...`); 290 | const promptCategoryValidation = this.categoryManager.validatePromptCategories(allPrompts); 291 | 292 | if (!promptCategoryValidation.isValid) { 293 | this.logger.error("❌ Category-prompt relationship validation failed:"); 294 | promptCategoryValidation.issues.forEach(issue => this.logger.error(` - ${issue}`)); 295 | this.logger.warn("Continuing with loading but some prompts may not display correctly"); 296 | } 297 | 298 | if (promptCategoryValidation.warnings.length > 0) { 299 | this.logger.warn("⚠️ Category-prompt relationship warnings:"); 300 | promptCategoryValidation.warnings.forEach(warning => this.logger.warn(` - ${warning}`)); 301 | } 302 | 303 | // Generate category statistics for debugging 304 | const categoryStats = this.categoryManager.getCategoryStatistics(allPrompts); 305 | this.logger.info(`📊 Category Statistics:`); 306 | this.logger.info(` Categories with prompts: ${categoryStats.categoriesWithPrompts}/${categoryStats.totalCategories}`); 307 | this.logger.info(` Empty categories: ${categoryStats.emptyCategoriesCount}`); 308 | this.logger.info(` Average prompts per category: ${categoryStats.averagePromptsPerCategory.toFixed(1)}`); 309 | 310 | const result = { promptsData: allPrompts, categories }; 311 | this.logger.info( 312 | `✅ PromptLoader.loadCategoryPrompts() completed successfully` 313 | ); 314 | 315 | return result; 316 | } catch (error) { 317 | this.logger.error(`❌ PromptLoader.loadCategoryPrompts() FAILED:`, error); 318 | throw error; 319 | } 320 | } 321 | 322 | /** 323 | * Get the CategoryManager instance for external access 324 | */ 325 | getCategoryManager(): CategoryManager { 326 | return this.categoryManager; 327 | } 328 | 329 | /** 330 | * Load prompt content from markdown file 331 | */ 332 | async loadPromptFile( 333 | filePath: string, 334 | basePath: string 335 | ): Promise<{ 336 | systemMessage?: string; 337 | userMessageTemplate: string; 338 | isChain?: boolean; 339 | gateConfiguration?: { 340 | include?: string[]; 341 | exclude?: string[]; 342 | framework_gates?: boolean; 343 | temporary_gates?: Array<{ 344 | id?: string; 345 | name: string; 346 | type: 'validation' | 'approval' | 'condition'; 347 | scope: 'execution' | 'session' | 'chain' | 'step'; 348 | description: string; 349 | guidance: string; 350 | pass_criteria: any[]; 351 | expires_at?: number; 352 | source?: 'manual' | 'automatic' | 'analysis'; 353 | context?: Record<string, any>; 354 | }>; 355 | gate_scope?: 'execution' | 'session' | 'chain' | 'step'; 356 | inherit_chain_gates?: boolean; 357 | }; 358 | chainSteps?: Array<{ 359 | promptId: string; 360 | stepName: string; 361 | gates?: string[]; 362 | inputMapping?: Record<string, string>; 363 | outputMapping?: Record<string, string>; 364 | }>; 365 | }> { 366 | try { 367 | const fullPath = path.join(basePath, filePath); 368 | const content = await readFile(fullPath, "utf8"); 369 | 370 | // Extract system message and user message template from markdown 371 | const systemMessageMatch = content.match( 372 | /## System Message\s*\n([\s\S]*?)(?=\n##|$)/ 373 | ); 374 | const userMessageMatch = content.match( 375 | /## User Message Template\s*\n([\s\S]*)$/ 376 | ); 377 | 378 | const systemMessage = systemMessageMatch 379 | ? systemMessageMatch[1].trim() 380 | : undefined; 381 | let userMessageTemplate = userMessageMatch 382 | ? userMessageMatch[1].trim() 383 | : ""; 384 | 385 | // Extract gate configuration if present (Phase 3: Enhanced gate configuration with temporary gates) 386 | let gateConfiguration: { 387 | include?: string[]; 388 | exclude?: string[]; 389 | framework_gates?: boolean; 390 | temporary_gates?: Array<{ 391 | id?: string; 392 | name: string; 393 | type: 'validation' | 'approval' | 'condition'; 394 | scope: 'execution' | 'session' | 'chain' | 'step'; 395 | description: string; 396 | guidance: string; 397 | pass_criteria: any[]; 398 | expires_at?: number; 399 | source?: 'manual' | 'automatic' | 'analysis'; 400 | context?: Record<string, any>; 401 | }>; 402 | gate_scope?: 'execution' | 'session' | 'chain' | 'step'; 403 | inherit_chain_gates?: boolean; 404 | } | undefined; 405 | 406 | const gateConfigMatch = content.match( 407 | /## Gate Configuration\s*\n```json\s*\n([\s\S]*?)\n```/ 408 | ); 409 | 410 | if (gateConfigMatch) { 411 | try { 412 | const gateConfigContent = gateConfigMatch[1].trim(); 413 | const parsedConfig = JSON.parse(gateConfigContent); 414 | 415 | // Validate and normalize the gate configuration 416 | if (Array.isArray(parsedConfig)) { 417 | // Simple array format: ["gate1", "gate2"] 418 | gateConfiguration = { 419 | include: parsedConfig, 420 | framework_gates: true 421 | }; 422 | } else if (typeof parsedConfig === 'object' && parsedConfig !== null) { 423 | // Object format: {"include": [...], "exclude": [...], "framework_gates": true, "temporary_gates": [...]} 424 | gateConfiguration = { 425 | include: Array.isArray(parsedConfig.include) ? parsedConfig.include : undefined, 426 | exclude: Array.isArray(parsedConfig.exclude) ? parsedConfig.exclude : undefined, 427 | framework_gates: typeof parsedConfig.framework_gates === 'boolean' ? parsedConfig.framework_gates : true, 428 | temporary_gates: Array.isArray(parsedConfig.temporary_gates) ? parsedConfig.temporary_gates : undefined, 429 | gate_scope: typeof parsedConfig.gate_scope === 'string' ? parsedConfig.gate_scope : undefined, 430 | inherit_chain_gates: typeof parsedConfig.inherit_chain_gates === 'boolean' ? parsedConfig.inherit_chain_gates : undefined 431 | }; 432 | } 433 | 434 | this.logger.debug(`[LOADER] Gate configuration parsed for ${filePath}:`, gateConfiguration); 435 | 436 | // Phase 3 Fix: Strip Gate Configuration section from userMessageTemplate 437 | // so it doesn't appear in the output to the user 438 | if (gateConfigMatch) { 439 | const gateConfigSectionRegex = /## Gate Configuration\s*\n```json\s*\n[\s\S]*?\n```\s*/; 440 | userMessageTemplate = userMessageTemplate.replace(gateConfigSectionRegex, '').trim(); 441 | this.logger.debug(`[LOADER] Stripped Gate Configuration section from user message template for ${filePath}`); 442 | } 443 | } catch (gateConfigError) { 444 | this.logger.warn(`[LOADER] Failed to parse gate configuration in ${filePath}:`, gateConfigError); 445 | } 446 | } 447 | 448 | // Extract chain information if present 449 | const chainMatch = content.match( 450 | /## Chain Steps\s*\n([\s\S]*?)(?=\n##|$)/ 451 | ); 452 | let chainSteps: Array<{ 453 | promptId: string; 454 | stepName: string; 455 | gates?: string[]; 456 | inputMapping?: Record<string, string>; 457 | outputMapping?: Record<string, string>; 458 | }> = []; 459 | 460 | if (chainMatch) { 461 | const chainContent = chainMatch[1].trim(); 462 | // Enhanced regex to match markdown format with optional gates 463 | const stepMatches = chainContent.matchAll( 464 | /(\d+)\.\s*promptId:\s*([^\n]+)\s*\n\s*stepName:\s*([^\n]+)(?:\s*\n\s*gates:\s*([^\n]+))?(?:\s*\n\s*inputMapping:\s*([\s\S]*?)(?=\s*\n\s*(?:outputMapping|promptId|\d+\.|$)))?\s*(?:\n\s*outputMapping:\s*([\s\S]*?)(?=\s*\n\s*(?:promptId|\d+\.|$)))?\s*/g 465 | ); 466 | 467 | for (const match of stepMatches) { 468 | const [ 469 | _, 470 | stepNumber, 471 | promptId, 472 | stepName, 473 | gatesStr, 474 | inputMappingStr, 475 | outputMappingStr, 476 | ] = match; 477 | 478 | const step: { 479 | promptId: string; 480 | stepName: string; 481 | gates?: string[]; 482 | inputMapping?: Record<string, string>; 483 | outputMapping?: Record<string, string>; 484 | } = { 485 | promptId: promptId.trim(), 486 | stepName: stepName.trim(), 487 | }; 488 | 489 | // Parse gates if present 490 | if (gatesStr) { 491 | try { 492 | // Handle both JSON array format ["gate1", "gate2"] and simple list format 493 | const gatesStrTrimmed = gatesStr.trim(); 494 | if (gatesStrTrimmed.startsWith('[') && gatesStrTrimmed.endsWith(']')) { 495 | // JSON array format 496 | step.gates = JSON.parse(gatesStrTrimmed); 497 | } else { 498 | // Simple comma-separated format: "gate1, gate2" 499 | step.gates = gatesStrTrimmed.split(',').map(g => g.trim()).filter(g => g.length > 0); 500 | } 501 | this.logger.debug(`Loaded ${step.gates?.length || 0} gate(s) for step ${stepNumber}: ${step.gates?.join(', ') || ''}`); 502 | } catch (e) { 503 | this.logger.warn( 504 | `Invalid gates format in chain step ${stepNumber} of ${filePath}: ${e}` 505 | ); 506 | } 507 | } 508 | 509 | if (inputMappingStr) { 510 | try { 511 | // Parse YAML-style mapping into JSON object 512 | const inputMapping: Record<string, string> = {}; 513 | const lines = inputMappingStr.trim().split("\n"); 514 | for (const line of lines) { 515 | const [key, value] = line 516 | .trim() 517 | .split(":") 518 | .map((s) => s.trim()); 519 | if (key && value) { 520 | inputMapping[key] = value; 521 | } 522 | } 523 | step.inputMapping = inputMapping; 524 | } catch (e) { 525 | this.logger.warn( 526 | `Invalid input mapping in chain step ${stepNumber} of ${filePath}: ${e}` 527 | ); 528 | } 529 | } 530 | 531 | if (outputMappingStr) { 532 | try { 533 | // Parse YAML-style mapping into JSON object 534 | const outputMapping: Record<string, string> = {}; 535 | const lines = outputMappingStr.trim().split("\n"); 536 | for (const line of lines) { 537 | const [key, value] = line 538 | .trim() 539 | .split(":") 540 | .map((s) => s.trim()); 541 | if (key && value) { 542 | outputMapping[key] = value; 543 | } 544 | } 545 | step.outputMapping = outputMapping; 546 | } catch (e) { 547 | this.logger.warn( 548 | `Invalid output mapping in chain step ${stepNumber} of ${filePath}: ${e}` 549 | ); 550 | } 551 | } 552 | 553 | chainSteps.push(step); 554 | } 555 | 556 | this.logger.debug( 557 | `Loaded chain with ${chainSteps.length} steps from ${filePath}` 558 | ); 559 | } 560 | 561 | if (!userMessageTemplate && !(chainSteps.length > 0)) { 562 | throw new Error(`No user message template found in ${filePath}`); 563 | } 564 | 565 | return { 566 | systemMessage, 567 | userMessageTemplate, 568 | gateConfiguration, 569 | chainSteps 570 | }; 571 | } catch (error) { 572 | this.logger.error(`Error loading prompt file ${filePath}:`, error); 573 | throw error; 574 | } 575 | } 576 | } 577 | ``` -------------------------------------------------------------------------------- /server/src/frameworks/methodology/guides/5w1h-guide.ts: -------------------------------------------------------------------------------- ```typescript 1 | /** 2 | * 5W1H Methodology Guide 3 | * Provides guidance for applying 5W1H (Who, What, When, Where, Why, How) methodology to prompt creation, 4 | * processing, and execution without hijacking semantic analysis functionality 5 | */ 6 | 7 | import type { ConvertedPrompt } from "../../../types/index.js"; 8 | import { ContentAnalysisResult } from "../../../semantic/configurable-semantic-analyzer.js"; 9 | import { 10 | IMethodologyGuide, 11 | BaseMethodologyGuide, 12 | PromptCreationGuidance, 13 | ProcessingGuidance, 14 | StepGuidance, 15 | MethodologyEnhancement, 16 | MethodologyValidation, 17 | ProcessingStep, 18 | ExecutionStep, 19 | QualityGate, 20 | TemplateEnhancement, 21 | MethodologyToolDescriptions 22 | } from "../interfaces.js"; 23 | 24 | /** 25 | * 5W1H Methodology Guide Implementation 26 | * Guides the application of 5W1H systematic questioning without replacing semantic analysis 27 | */ 28 | export class FiveW1HMethodologyGuide extends BaseMethodologyGuide { 29 | readonly frameworkId = "5w1h"; 30 | readonly frameworkName = "5W1H Framework"; 31 | readonly methodology = "5W1H"; 32 | readonly version = "1.0.0"; 33 | 34 | /** 35 | * Guide prompt creation using 5W1H structure 36 | * Helps users create prompts that follow 5W1H methodology 37 | */ 38 | guidePromptCreation(intent: string, context?: Record<string, any>): PromptCreationGuidance { 39 | return { 40 | structureGuidance: { 41 | systemPromptSuggestions: [ 42 | "Identify all stakeholders and actors involved", 43 | "Define exactly what needs to be accomplished", 44 | "Establish timing and sequence requirements", 45 | "Determine location and context constraints", 46 | "Understand underlying purposes and motivations", 47 | "Plan specific methods and implementation approaches" 48 | ], 49 | userTemplateSuggestions: [ 50 | "Structure request using 5W1H systematic questioning", 51 | "Identify who is involved or affected", 52 | "Define what exactly needs to be done", 53 | "Specify when this should happen", 54 | "Clarify where this takes place", 55 | "Explain why this is important", 56 | "Detail how this should be accomplished" 57 | ], 58 | argumentSuggestions: [ 59 | { 60 | name: "stakeholders", 61 | type: "array", 62 | description: "People, roles, or entities involved or affected", 63 | methodologyReason: "5W1H 'Who' question requires comprehensive stakeholder identification", 64 | examples: ["users", "developers", "managers", "customers"] 65 | }, 66 | { 67 | name: "objectives", 68 | type: "string", 69 | description: "Specific goals and deliverables to accomplish", 70 | methodologyReason: "5W1H 'What' question needs clear objective definition", 71 | examples: ["improve user experience", "reduce processing time", "increase sales"] 72 | }, 73 | { 74 | name: "timeline", 75 | type: "string", 76 | description: "When this should be completed or timing requirements", 77 | methodologyReason: "5W1H 'When' question establishes timing and urgency", 78 | examples: ["by end of quarter", "within 2 weeks", "before product launch"] 79 | }, 80 | { 81 | name: "context", 82 | type: "string", 83 | description: "Where this takes place or contextual constraints", 84 | methodologyReason: "5W1H 'Where' question identifies location and context factors", 85 | examples: ["web application", "mobile platform", "enterprise environment"] 86 | }, 87 | { 88 | name: "purpose", 89 | type: "string", 90 | description: "Why this is important and underlying motivations", 91 | methodologyReason: "5W1H 'Why' question uncovers fundamental motivations", 92 | examples: ["improve customer satisfaction", "reduce operational costs", "meet compliance"] 93 | } 94 | ] 95 | }, 96 | 97 | methodologyElements: { 98 | requiredSections: ["Who", "What", "When", "Where", "Why", "How"], 99 | optionalSections: ["Validation", "Dependencies"], 100 | sectionDescriptions: { 101 | "Who": "Identify stakeholders, actors, and people involved or affected", 102 | "What": "Define exactly what needs to be accomplished and deliverables", 103 | "When": "Establish timing, deadlines, and sequence requirements", 104 | "Where": "Determine location, context, and environmental constraints", 105 | "Why": "Understand underlying purposes, motivations, and importance", 106 | "How": "Plan specific methods, approaches, and implementation strategies" 107 | } 108 | }, 109 | 110 | qualityGuidance: { 111 | clarityEnhancements: [ 112 | "Make stakeholder roles and responsibilities explicit", 113 | "Define specific, measurable objectives and deliverables", 114 | "Provide concrete timelines and deadlines" 115 | ], 116 | completenessChecks: [ 117 | "Ensure all 6 questions (Who, What, When, Where, Why, How) are addressed", 118 | "Verify stakeholder identification is comprehensive", 119 | "Confirm objectives are specific and measurable" 120 | ], 121 | specificityImprovements: [ 122 | "Replace generic stakeholder references with specific roles", 123 | "Add quantifiable success criteria and metrics", 124 | "Include specific implementation steps and methods" 125 | ] 126 | } 127 | }; 128 | } 129 | 130 | /** 131 | * Guide template processing with 5W1H methodology 132 | */ 133 | guideTemplateProcessing(template: string, executionType: string): ProcessingGuidance { 134 | const fiveW1HSteps: ProcessingStep[] = [ 135 | { 136 | id: "stakeholder_identification", 137 | name: "Stakeholder Identification (Who)", 138 | description: "Identify all relevant stakeholders, actors, and people involved", 139 | methodologyBasis: "5W1H Who question", 140 | order: 1, 141 | required: true 142 | }, 143 | { 144 | id: "objective_definition", 145 | name: "Objective Definition (What)", 146 | description: "Define exactly what needs to be accomplished and deliverables", 147 | methodologyBasis: "5W1H What question", 148 | order: 2, 149 | required: true 150 | }, 151 | { 152 | id: "timing_establishment", 153 | name: "Timing Establishment (When)", 154 | description: "Establish timing, deadlines, and sequence requirements", 155 | methodologyBasis: "5W1H When question", 156 | order: 3, 157 | required: true 158 | }, 159 | { 160 | id: "context_determination", 161 | name: "Context Determination (Where)", 162 | description: "Determine location, context, and environmental constraints", 163 | methodologyBasis: "5W1H Where question", 164 | order: 4, 165 | required: true 166 | }, 167 | { 168 | id: "purpose_understanding", 169 | name: "Purpose Understanding (Why)", 170 | description: "Understand underlying purposes, motivations, and importance", 171 | methodologyBasis: "5W1H Why question", 172 | order: 5, 173 | required: true 174 | }, 175 | { 176 | id: "method_planning", 177 | name: "Method Planning (How)", 178 | description: "Plan specific methods, approaches, and implementation strategies", 179 | methodologyBasis: "5W1H How question", 180 | order: 6, 181 | required: true 182 | } 183 | ]; 184 | 185 | return { 186 | processingSteps: fiveW1HSteps, 187 | 188 | templateEnhancements: { 189 | systemPromptAdditions: [ 190 | "Apply 5W1H systematic questioning methodology", 191 | "Address Who, What, When, Where, Why, How comprehensively", 192 | "Ensure complete coverage of all stakeholders and requirements", 193 | "Use systematic questioning to uncover hidden requirements" 194 | ], 195 | userPromptModifications: [ 196 | "Structure response addressing all 5W1H questions", 197 | "Provide comprehensive stakeholder analysis", 198 | "Include detailed implementation planning" 199 | ], 200 | contextualHints: [ 201 | "Focus on comprehensive requirement gathering", 202 | "Emphasize stakeholder perspective consideration", 203 | "Apply systematic analysis to ensure nothing is missed" 204 | ] 205 | }, 206 | 207 | executionFlow: { 208 | preProcessingSteps: [ 209 | "Validate 5W1H question completeness", 210 | "Confirm stakeholder identification scope", 211 | "Verify objective clarity and measurability" 212 | ], 213 | postProcessingSteps: [ 214 | "Review 5W1H coverage completeness", 215 | "Assess stakeholder consideration adequacy", 216 | "Evaluate implementation plan specificity" 217 | ], 218 | validationSteps: [ 219 | "Who question completeness check", 220 | "What question specificity verification", 221 | "When question timing validation", 222 | "Where question context assessment", 223 | "Why question motivation analysis", 224 | "How question method evaluation" 225 | ] 226 | } 227 | }; 228 | } 229 | 230 | /** 231 | * Guide execution steps using 5W1H methodology 232 | */ 233 | guideExecutionSteps(prompt: ConvertedPrompt, semanticAnalysis: ContentAnalysisResult): StepGuidance { 234 | const executionSteps: ExecutionStep[] = [ 235 | { 236 | id: "comprehensive_who_analysis", 237 | name: "Comprehensive Who Analysis", 238 | action: "Identify and analyze all stakeholders, actors, and affected parties", 239 | methodologyPhase: "Who", 240 | dependencies: [], 241 | expected_output: "Complete stakeholder map with roles and responsibilities" 242 | }, 243 | { 244 | id: "specific_what_definition", 245 | name: "Specific What Definition", 246 | action: "Define exactly what needs to be accomplished with measurable deliverables", 247 | methodologyPhase: "What", 248 | dependencies: ["comprehensive_who_analysis"], 249 | expected_output: "Clear, specific, measurable objectives and deliverables" 250 | }, 251 | { 252 | id: "detailed_when_planning", 253 | name: "Detailed When Planning", 254 | action: "Establish comprehensive timing, deadlines, and sequence requirements", 255 | methodologyPhase: "When", 256 | dependencies: ["specific_what_definition"], 257 | expected_output: "Detailed timeline with milestones and dependencies" 258 | }, 259 | { 260 | id: "contextual_where_assessment", 261 | name: "Contextual Where Assessment", 262 | action: "Determine location, context, environment, and situational constraints", 263 | methodologyPhase: "Where", 264 | dependencies: ["detailed_when_planning"], 265 | expected_output: "Comprehensive context analysis with constraints identified" 266 | }, 267 | { 268 | id: "fundamental_why_exploration", 269 | name: "Fundamental Why Exploration", 270 | action: "Uncover underlying purposes, motivations, and fundamental importance", 271 | methodologyPhase: "Why", 272 | dependencies: ["contextual_where_assessment"], 273 | expected_output: "Deep understanding of motivations and fundamental purposes" 274 | }, 275 | { 276 | id: "specific_how_planning", 277 | name: "Specific How Planning", 278 | action: "Develop detailed methods, approaches, and implementation strategies", 279 | methodologyPhase: "How", 280 | dependencies: ["fundamental_why_exploration"], 281 | expected_output: "Comprehensive implementation plan with specific methods" 282 | } 283 | ]; 284 | 285 | // Adjust steps based on execution type from semantic analyzer 286 | const stepEnhancements: Record<string, string[]> = {}; 287 | const stepValidation: Record<string, string[]> = {}; 288 | 289 | if (semanticAnalysis.executionType === "chain") { 290 | stepEnhancements["specific_how_planning"] = [ 291 | "Plan sequential implementation steps", 292 | "Define clear handoff points between phases", 293 | "Establish validation checkpoints for each step" 294 | ]; 295 | stepValidation["specific_how_planning"] = [ 296 | "Sequential step validation", 297 | "Handoff point verification", 298 | "Checkpoint adequacy assessment" 299 | ]; 300 | } else if (semanticAnalysis.executionType === "template") { 301 | stepEnhancements["comprehensive_who_analysis"] = [ 302 | "Create stakeholder templates and categories", 303 | "Develop reusable stakeholder analysis patterns", 304 | "Establish standard stakeholder consideration checklists" 305 | ]; 306 | stepValidation["comprehensive_who_analysis"] = [ 307 | "Template completeness validation", 308 | "Pattern reusability verification", 309 | "Checklist coverage assessment" 310 | ]; 311 | } 312 | 313 | return { 314 | stepSequence: executionSteps, 315 | stepEnhancements, 316 | stepValidation 317 | }; 318 | } 319 | 320 | /** 321 | * Enhance execution with 5W1H methodology 322 | */ 323 | enhanceWithMethodology(prompt: ConvertedPrompt, context: Record<string, any>): MethodologyEnhancement { 324 | const fiveW1HGates: QualityGate[] = [ 325 | { 326 | id: "stakeholder_completeness", 327 | name: "Stakeholder Completeness", 328 | description: "Verify comprehensive stakeholder identification and analysis", 329 | methodologyArea: "Who", 330 | validationCriteria: [ 331 | "All relevant stakeholders identified", 332 | "Roles and responsibilities defined", 333 | "Stakeholder interests and concerns considered" 334 | ], 335 | priority: "high" 336 | }, 337 | { 338 | id: "objective_specificity", 339 | name: "Objective Specificity", 340 | description: "Ensure objectives are specific, measurable, and well-defined", 341 | methodologyArea: "What", 342 | validationCriteria: [ 343 | "Objectives are specific and clear", 344 | "Deliverables are measurable", 345 | "Success criteria are defined" 346 | ], 347 | priority: "high" 348 | }, 349 | { 350 | id: "timing_comprehensiveness", 351 | name: "Timing Comprehensiveness", 352 | description: "Validate thorough timing and scheduling consideration", 353 | methodologyArea: "When", 354 | validationCriteria: [ 355 | "Timeline is realistic and detailed", 356 | "Dependencies and constraints considered", 357 | "Milestones and checkpoints defined" 358 | ], 359 | priority: "medium" 360 | }, 361 | { 362 | id: "context_thoroughness", 363 | name: "Context Thoroughness", 364 | description: "Assess comprehensive context and environmental analysis", 365 | methodologyArea: "Where", 366 | validationCriteria: [ 367 | "Environmental factors considered", 368 | "Contextual constraints identified", 369 | "Location and situational factors addressed" 370 | ], 371 | priority: "medium" 372 | }, 373 | { 374 | id: "purpose_depth", 375 | name: "Purpose Depth", 376 | description: "Verify deep understanding of underlying motivations", 377 | methodologyArea: "Why", 378 | validationCriteria: [ 379 | "Fundamental purposes understood", 380 | "Underlying motivations explored", 381 | "Value and importance articulated" 382 | ], 383 | priority: "high" 384 | }, 385 | { 386 | id: "method_practicality", 387 | name: "Method Practicality", 388 | description: "Ensure methods and approaches are practical and detailed", 389 | methodologyArea: "How", 390 | validationCriteria: [ 391 | "Methods are specific and actionable", 392 | "Implementation approach is practical", 393 | "Resources and capabilities considered" 394 | ], 395 | priority: "medium" 396 | } 397 | ]; 398 | 399 | const templateSuggestions: TemplateEnhancement[] = [ 400 | { 401 | section: "system", 402 | type: "addition", 403 | description: "Add 5W1H methodology guidance", 404 | content: "Apply the 5W1H methodology systematically: Who (stakeholders), What (objectives), When (timing), Where (context), Why (purpose), How (methods). Ensure comprehensive coverage of all questions for thorough analysis.", 405 | methodologyJustification: "Ensures systematic application of comprehensive questioning", 406 | impact: "high" 407 | }, 408 | { 409 | section: "user", 410 | type: "structure", 411 | description: "Structure response using 5W1H questions", 412 | content: "Please structure your response addressing: 1) Who is involved or affected, 2) What needs to be accomplished, 3) When this should happen, 4) Where this takes place, 5) Why this is important, 6) How this should be done.", 413 | methodologyJustification: "Guides comprehensive analysis through systematic questioning", 414 | impact: "medium" 415 | } 416 | ]; 417 | 418 | return { 419 | systemPromptGuidance: this.getSystemPromptGuidance(context), 420 | processingEnhancements: this.guideTemplateProcessing("", "template").processingSteps, 421 | methodologyGates: fiveW1HGates, 422 | templateSuggestions, 423 | enhancementMetadata: this.createEnhancementMetadata( 424 | 0.9, 425 | "5W1H methodology ensures comprehensive analysis through systematic questioning" 426 | ) 427 | }; 428 | } 429 | 430 | /** 431 | * Validate methodology compliance 432 | */ 433 | validateMethodologyCompliance(prompt: ConvertedPrompt): MethodologyValidation { 434 | const combinedText = this.getCombinedText(prompt); 435 | const text = combinedText.toLowerCase(); 436 | 437 | // Check for 5W1H question presence 438 | const questions = { 439 | who: /who|stakeholder|actor|people|person|role|user|team/i.test(text), 440 | what: /what|objective|goal|deliverable|accomplish|achieve/i.test(text), 441 | when: /when|timing|deadline|schedule|time|date|timeline/i.test(text), 442 | where: /where|location|context|environment|place|setting/i.test(text), 443 | why: /why|purpose|reason|motivation|importance|value|benefit/i.test(text), 444 | how: /how|method|approach|strategy|process|implementation/i.test(text) 445 | }; 446 | 447 | const presentQuestions = Object.values(questions).filter(Boolean).length; 448 | const compliance_score = presentQuestions / 6; // 6 questions in 5W1H 449 | 450 | const strengths: string[] = []; 451 | const improvement_areas: string[] = []; 452 | 453 | if (questions.who) strengths.push("Stakeholder consideration present"); 454 | else improvement_areas.push("Identify stakeholders and people involved"); 455 | 456 | if (questions.what) strengths.push("Objective definition evident"); 457 | else improvement_areas.push("Define specific objectives and deliverables"); 458 | 459 | if (questions.when) strengths.push("Timing consideration included"); 460 | else improvement_areas.push("Establish timing and scheduling requirements"); 461 | 462 | if (questions.where) strengths.push("Context awareness demonstrated"); 463 | else improvement_areas.push("Consider location and contextual factors"); 464 | 465 | if (questions.why) strengths.push("Purpose and motivation addressed"); 466 | else improvement_areas.push("Explore underlying purposes and motivations"); 467 | 468 | if (questions.how) strengths.push("Implementation approach considered"); 469 | else improvement_areas.push("Plan specific methods and implementation approaches"); 470 | 471 | const specific_suggestions: TemplateEnhancement[] = []; 472 | 473 | if (!questions.who) { 474 | specific_suggestions.push({ 475 | section: "system", 476 | type: "addition", 477 | description: "Add stakeholder identification", 478 | content: "Identify all stakeholders, actors, and people involved or affected by this.", 479 | methodologyJustification: "5W1H Who question requires comprehensive stakeholder analysis", 480 | impact: "high" 481 | }); 482 | } 483 | 484 | if (!questions.why) { 485 | specific_suggestions.push({ 486 | section: "system", 487 | type: "addition", 488 | description: "Add purpose exploration", 489 | content: "Explore the underlying purposes, motivations, and importance of this effort.", 490 | methodologyJustification: "5W1H Why question uncovers fundamental motivations", 491 | impact: "high" 492 | }); 493 | } 494 | 495 | return { 496 | compliant: compliance_score > 0.7, 497 | compliance_score, 498 | strengths, 499 | improvement_areas, 500 | specific_suggestions, 501 | methodology_gaps: improvement_areas 502 | }; 503 | } 504 | 505 | /** 506 | * Get 5W1H-specific system prompt guidance 507 | */ 508 | getSystemPromptGuidance(context: Record<string, any>): string { 509 | return `Apply the 5W1H methodology systematically: 510 | 511 | **Who**: Identify all stakeholders, actors, and people involved or affected 512 | **What**: Define exactly what needs to be accomplished and deliverables 513 | **When**: Establish timing, deadlines, and sequence requirements 514 | **Where**: Determine location, context, and environmental constraints 515 | **Why**: Understand underlying purposes, motivations, and fundamental importance 516 | **How**: Plan specific methods, approaches, and implementation strategies 517 | 518 | Use systematic questioning to ensure comprehensive coverage and uncover hidden requirements. Address each question thoroughly to build complete understanding and effective solutions.`; 519 | } 520 | 521 | /** 522 | * Get 5W1H-specific tool descriptions 523 | */ 524 | getToolDescriptions(): MethodologyToolDescriptions { 525 | return { 526 | prompt_engine: { 527 | description: "🚀 PROMPT TEMPLATE ENGINE [5W1H-ENHANCED]: Processes prompt templates with systematic 5W1H questioning methodology for comprehensive analysis. Guides thorough exploration through Who (stakeholders), What (objectives), When (timing), Where (context), Why (motivation), and How (methods). WARNING: You are responsible for interpreting and executing the returned content, which contains systematic questioning instructions.", 528 | parameters: { 529 | execution_mode: "Override intelligent auto-detection with 5W1H-aware selection (default: auto, systematic questioning-enhanced)" 530 | } 531 | }, 532 | prompt_manager: { 533 | description: "📝 INTELLIGENT PROMPT MANAGER [5W1H-ENHANCED]: Complete lifecycle management with systematic 5W1H questioning methodology integration. Creates comprehensive analysis templates that guide systematic exploration through Who, What, When, Where, Why, and How dimensions. Optimized for thorough requirement analysis and complete solution development.", 534 | parameters: { 535 | action: "Management action with 5W1H systematic approach: 'create_template' (comprehensive questioning templates), 'analyze_type' (stakeholder analysis), 'migrate_type' (systematic conversion), etc." 536 | } 537 | }, 538 | system_control: { 539 | description: "⚙️ INTELLIGENT SYSTEM CONTROL [5W1H-ENHANCED]: System administration with 5W1H systematic questioning methodology. Guides comprehensive exploration through Who (users), What (objectives), When (timing), Where (environments), Why (purposes), and How (methods) for thorough system management and decision-making.", 540 | parameters: { 541 | action: "System action with 5W1H methodology: 'switch_framework' (systematic framework selection), 'analytics' (comprehensive questioning-based metrics), 'health' (thorough system analysis), etc." 542 | } 543 | } 544 | }; 545 | } 546 | } ```