This is page 2 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/prompts/content_processing/vault_related_notes_finder.md: -------------------------------------------------------------------------------- ```markdown 1 | # Vault Related Notes Finder 2 | 3 | ## Description 4 | Searches vault for actual related notes using content analysis and glob/grep patterns to find real cross-references 5 | 6 | ## System Message 7 | You are an expert assistant providing structured, systematic analysis. Apply appropriate methodology and reasoning frameworks to deliver comprehensive responses. 8 | 9 | ## User Message Template 10 | Search the vault for actual related notes to: {{note_topic}} 11 | 12 | Current note content areas: {{content_areas}} 13 | Vault root path: {{vault_path}} 14 | 15 | Execute systematic vault search to find real related notes: 16 | 17 | **PHASE 1: Semantic Search Strategy** 18 | - Extract key concepts, terminology, and domain keywords from note content 19 | - Identify parent domains (e.g., for typography: art, design, visual_communication) 20 | - Map related disciplines and cross-domain connections 21 | 22 | **PHASE 2: Vault Structure Analysis** 23 | - Use Glob patterns to explore relevant directory structures 24 | - Search for MOCs (Maps of Content) in related domains 25 | - Identify hub notes and navigation centers 26 | 27 | **PHASE 3: Content Discovery** 28 | - Use Grep with key terminology to find actual related content 29 | - Search for complementary topics and techniques 30 | - Find case studies, examples, and practical applications 31 | 32 | **PHASE 4: Relationship Validation** 33 | - Verify found notes actually relate to the topic 34 | - Read key sections to confirm relevance 35 | - Prioritize direct relationships over tangential connections 36 | 37 | **PHASE 5: Strategic Link Selection** 38 | - Select 3-5 most relevant and valuable related notes 39 | - Prioritize: MOCs > Fundamental concepts > Practical applications > Case studies 40 | - Format as proper [[WikiLinks]] with existing file names 41 | 42 | **Output Requirements:** 43 | 1. List actual file paths found in vault 44 | 2. Briefly explain relevance of each related note 45 | 3. Provide final Related Notes section with 3-5 [[WikiLinks]] 46 | 4. Ensure all links point to real existing files in vault 47 | ``` -------------------------------------------------------------------------------- /server/prompts/documentation/docs-content-planning.md: -------------------------------------------------------------------------------- ```markdown 1 | # Content Planning (Step 2 of 5) 2 | 3 | ## Description 4 | Create a detailed content plan and structure for the documentation 5 | 6 | ## System Message 7 | [System Info: You are a documentation architect who specializes in creating detailed content plans for technical documentation. Your goal is to create a comprehensive outline that ensures all critical information is covered in a logical, user-friendly structure.] 8 | 9 | ## User Message Template 10 | Based on the project analysis: 11 | {{previous_message}} 12 | 13 | I need to create a detailed content plan for {{doc_type}} documentation targeting {{audience}}. 14 | 15 | Please develop a comprehensive documentation plan that includes: 16 | 17 | 1. A detailed table of contents with all main sections and subsections organized in a logical progression 18 | 2. For each section, specify: 19 | - Key information to cover 20 | - Recommended depth of technical detail based on audience needs 21 | - Specific examples, diagrams, or code snippets to include 22 | - Estimated length/importance of each section 23 | 24 | 3. A recommended documentation structure that follows these best practices: 25 | - Progressive disclosure (basic concepts before advanced ones) 26 | - Logical grouping of related topics 27 | - Clear navigation paths for different user journeys 28 | - Appropriate cross-referencing between related sections 29 | 30 | 4. Special considerations for: 31 | - Getting started/quickstart content for new users 32 | - Troubleshooting sections for common issues 33 | - Reference materials vs. conceptual explanations vs. tutorials 34 | - Version-specific information (if applicable) 35 | 36 | 5. Documentation metadata and supporting elements: 37 | - Necessary disclaimers, prerequisites, or system requirements 38 | - Glossary terms that should be defined 39 | - Additional resources or external references to include 40 | 41 | Please organize this content plan with clear headings and provide enough detail that it could serve as a comprehensive blueprint for creating the actual documentation. 42 | ``` -------------------------------------------------------------------------------- /server/prompts/documentation/docs-final-assembly.md: -------------------------------------------------------------------------------- ```markdown 1 | # Final Assembly (Step 5 of 5) 2 | 3 | ## Description 4 | Create the final, production-ready version of the documentation 5 | 6 | ## System Message 7 | [System Info: You are a documentation finalizer who specializes in preparing polished, production-ready technical documentation. Your goal is to create the final version of documentation that incorporates all refinements and is properly formatted for its intended platform.] 8 | 9 | ## User Message Template 10 | I have documentation content that has been reviewed with suggestions for improvement: 11 | {{previous_message}} 12 | 13 | For this documentation type: {{doc_type}} 14 | For this target audience: {{audience}} 15 | {% if depth_level %}At this depth level: {{depth_level}}{% endif %} 16 | 17 | Please create the final, production-ready version of this documentation by: 18 | 19 | 1. Incorporating all suggested refinements and improvements 20 | 2. Ensuring perfect formatting using proper Markdown (or specified format) 21 | 3. Adding appropriate front matter and metadata: 22 | - Title and description 23 | - Table of contents 24 | - Version information 25 | - Author/contributor information 26 | - Last updated date 27 | - Appropriate license information 28 | 29 | 4. Including these essential documentation elements: 30 | - Informative introduction that establishes purpose and scope 31 | - Clear navigation structure with logical content progression 32 | - Proper heading hierarchy and section organization 33 | - Consistent formatting of code blocks, notes, warnings, etc. 34 | - Complete table of contents with working anchor links 35 | 36 | 5. Final organization optimizations: 37 | - Ensuring related information is grouped together 38 | - Breaking very long sections into more digestible chunks 39 | - Adding "See also" sections where appropriate 40 | - Including a glossary for technical terms if needed 41 | 42 | Please deliver the complete, final documentation in properly formatted Markdown that could be published immediately. It should be comprehensive, well-structured, and ready for use by the target audience. 43 | ``` -------------------------------------------------------------------------------- /server/src/gates/templates/code_quality_validation.md: -------------------------------------------------------------------------------- ```markdown 1 | # Code Quality Self-Check Template 2 | 3 | ## Instructions 4 | Evaluate the code you've generated against industry best practices and quality standards. 5 | 6 | ## Code Quality Criteria 7 | 8 | ### Error Handling & Robustness 9 | - [ ] **Error Handling**: Includes appropriate try-catch blocks or error handling 10 | - [ ] **Input Validation**: Validates inputs and handles edge cases 11 | - [ ] **Boundary Conditions**: Considers boundary conditions and null/undefined cases 12 | - [ ] **Graceful Degradation**: Fails gracefully with meaningful error messages 13 | 14 | ### Code Structure & Readability 15 | - [ ] **Clear Naming**: Uses descriptive, consistent naming conventions 16 | - [ ] **Comments**: Includes inline comments for complex logic 17 | - [ ] **Function Size**: Functions are focused and reasonably sized 18 | - [ ] **Code Organization**: Well-structured and logically organized 19 | 20 | ### Best Practices 21 | - [ ] **Security**: Follows security best practices (no hardcoded secrets, input sanitization) 22 | - [ ] **Performance**: Considers performance implications 23 | - [ ] **Maintainability**: Easy to understand and modify 24 | - [ ] **Documentation**: Includes basic function documentation/docstrings 25 | 26 | ### Code Quality Indicators 27 | - [ ] **No TODO/FIXME**: No placeholder comments or incomplete code 28 | - [ ] **Consistent Style**: Follows consistent coding style 29 | - [ ] **Modern Patterns**: Uses appropriate modern language features 30 | - [ ] **Testing Ready**: Code structure supports testing 31 | 32 | ## Self-Assessment 33 | 34 | **Overall Code Quality Score (0.0-1.0): ___** 35 | 36 | **Quality Breakdown:** 37 | - Error Handling: ___/10 38 | - Readability: ___/10 39 | - Security: ___/10 40 | - Maintainability: ___/10 41 | 42 | **Code Review Notes:** 43 | [Describe the strengths and weaknesses of the generated code] 44 | 45 | **Specific Improvements Needed:** 46 | [List concrete improvements if score < 0.8] 47 | 48 | ## Validation Response 49 | 50 | Based on your assessment: 51 | - **PASS** if score ≥ 0.8 and no critical security/error handling issues 52 | - **NEEDS_IMPROVEMENT** if score < 0.8 or has critical flaws 53 | 54 | **Final Assessment: [PASS/NEEDS_IMPROVEMENT]** ``` -------------------------------------------------------------------------------- /server/src/gates/templates/structure_validation.md: -------------------------------------------------------------------------------- ```markdown 1 | # Content Structure Self-Check Template 2 | 3 | ## Instructions 4 | Assess the organization, clarity, and structure of your content response. 5 | 6 | ## Structure Quality Criteria 7 | 8 | ### Organization & Flow 9 | - [ ] **Clear Headings**: Uses appropriate headings (##, ###) to organize content 10 | - [ ] **Logical Sequence**: Information flows logically from introduction to conclusion 11 | - [ ] **Section Balance**: Sections are appropriately sized and balanced 12 | - [ ] **Smooth Transitions**: Good transitions between sections and ideas 13 | 14 | ### Clarity & Readability 15 | - [ ] **List Usage**: Uses bullet points or numbered lists for clarity 16 | - [ ] **Paragraph Length**: Paragraphs are reasonably sized (3-5 sentences) 17 | - [ ] **Sentence Structure**: Varies sentence length and structure 18 | - [ ] **Technical Clarity**: Complex concepts are explained clearly 19 | 20 | ### Content Enhancement 21 | - [ ] **Examples**: Includes relevant examples when explaining concepts 22 | - [ ] **Visual Elements**: Uses formatting (bold, italic, code blocks) appropriately 23 | - [ ] **Actionable Content**: Provides actionable insights or steps where relevant 24 | - [ ] **Summary/Conclusion**: Includes appropriate summary or next steps 25 | 26 | ### Reader Experience 27 | - [ ] **Scannable**: Content is easy to scan and navigate 28 | - [ ] **Consistent Tone**: Maintains consistent tone and style throughout 29 | - [ ] **Appropriate Length**: Content length matches the complexity of the topic 30 | - [ ] **Engaging**: Content is engaging and maintains reader interest 31 | 32 | ## Self-Assessment 33 | 34 | **Overall Structure Quality Score (0.0-1.0): ___** 35 | 36 | **Structure Breakdown:** 37 | - Organization: ___/10 38 | - Readability: ___/10 39 | - Clarity: ___/10 40 | - Reader Experience: ___/10 41 | 42 | **Structure Analysis:** 43 | [Evaluate how well the content is organized and presented] 44 | 45 | **Missing Elements:** 46 | [Identify structural elements that could improve the content] 47 | 48 | ## Validation Response 49 | 50 | Assessment criteria: 51 | - **PASS** if score ≥ 0.7 and has clear headings/organization 52 | - **NEEDS_IMPROVEMENT** if score < 0.7 or lacks basic structure 53 | 54 | **Final Assessment: [PASS/NEEDS_IMPROVEMENT]** ``` -------------------------------------------------------------------------------- /server/prompts/analysis/review.md: -------------------------------------------------------------------------------- ```markdown 1 | # review 2 | 3 | ## Description 4 | Comprehensive audit template for modules, implementations, and system integrations 5 | 6 | ## System Message 7 | You are an expert system architect and code reviewer. Conduct thorough, evidence-based analysis. Focus on reliability, integration quality, duplication detection, and consolidation opportunities. 8 | 9 | ## User Message Template 10 | Conduct a comprehensive audit of: {{target}} 11 | 12 | ## Implementation Analysis 13 | 1. **Current Functionality** 14 | - What is the current functionality and purpose? 15 | - What are the implementation details and patterns used? 16 | - What are the dependencies and interfaces? 17 | 18 | 2. **Reliability Assessment** 19 | - Is the functionality reliable and robust? 20 | - Are there error handling gaps or edge cases? 21 | - What are the failure modes and recovery mechanisms? 22 | 23 | ## Integration Analysis 24 | 3. **Integration Mapping** 25 | - Which modules/systems currently use this functionality? 26 | - Are all required integration points properly hooked up? 27 | - Are there missing integrations that should exist? 28 | 29 | 4. **System Coordination** 30 | - Does it integrate with the right system coordinators/conductors? 31 | - Is the coordination pattern consistent with architecture? 32 | - Are lifecycle management hooks properly implemented? 33 | 34 | ## Duplication & Consolidation 35 | 5. **Duplication Detection** 36 | - Are there duplicate implementations of similar functionality? 37 | - Do multiple modules provide overlapping capabilities? 38 | - What percentage of functionality is duplicated? 39 | 40 | 6. **Consolidation Opportunities** 41 | - Should these modules be consolidated? 42 | - What would be the benefits and risks of consolidation? 43 | - What is the migration complexity? 44 | 45 | ## Recommendations 46 | 7. **Refactoring Assessment** 47 | - Should the implementation be refactored? 48 | - What specific improvements are recommended? 49 | - What is the priority level (Critical/High/Medium/Low)? 50 | 51 | 8. **Action Items** 52 | - Prioritized list of recommended actions 53 | - Risk assessment for each recommendation 54 | - Success criteria for improvements 55 | 56 | Provide evidence-based, actionable recommendations with specific file paths and line numbers where relevant. 57 | ``` -------------------------------------------------------------------------------- /server/prompts/analysis/note_refinement.md: -------------------------------------------------------------------------------- ```markdown 1 | # Note Refinement 2 | 3 | ## Description 4 | 5 | Refine existing notes by improving organization, flow, and clarity without adding or modifying the content. 6 | 7 | ## User Message Template 8 | 9 | Please refine and reorganize the following notes into a beautiful, well-structured reference page that will be easy to use in the future: 10 | 11 | {{previous_message}} 12 | 13 | Create a polished note page by following these specific refinement guidelines: 14 | 15 | **STRUCTURE & ORGANIZATION:** 16 | 17 | - Use clear hierarchical headings (# ## ### ####) to create logical sections 18 | - Organize content from general concepts to specific details 19 | - Group related information together under appropriate headings 20 | - Create a logical flow that builds understanding progressively 21 | 22 | **VISUAL FORMATTING:** 23 | 24 | - Use **bold** for key terms, concepts, and important points 25 | - Use _italics_ for emphasis and definitions 26 | - Apply consistent bullet points for lists and sub-points 27 | - Use numbered lists for processes, steps, or ordered information 28 | - Add horizontal rules (---) to separate major sections when needed 29 | 30 | **CONTENT ENHANCEMENT:** 31 | 32 | - Create a brief summary or overview at the beginning if the content is complex 33 | - Add "Key Takeaways" or "Important Points" sections where appropriate 34 | - Use blockquotes (>) for important quotes, definitions, or highlighted concepts 35 | - Ensure each section has a clear purpose and contribution to the overall topic 36 | 37 | **READABILITY IMPROVEMENTS:** 38 | 39 | - Break up large text blocks into digestible paragraphs 40 | - Use consistent formatting throughout the document 41 | - Ensure proper spacing between sections 42 | - Make the document scannable with clear visual hierarchy 43 | - Add context or brief explanations where connections might not be obvious 44 | 45 | **REFERENCE OPTIMIZATION:** 46 | 47 | - Structure the content so key information can be quickly located 48 | - Use descriptive section headings that clearly indicate content 49 | - Maintain all original information while improving presentation 50 | - Create a format that supports both quick reference and deeper reading 51 | 52 | Transform the content into a professional, well-organized reference document that maintains all original information while dramatically improving usability and visual appeal. 53 | ``` -------------------------------------------------------------------------------- /server/prompts/content_processing/video_notes_enhanced.md: -------------------------------------------------------------------------------- ```markdown 1 | # Enhanced Video Notes Chain 2 | 3 | ## Description 4 | Comprehensive video processing chain including content analysis, visual extraction, vault integration, and note creation with proper formatting 5 | 6 | ## User Message Template 7 | Process video content into comprehensive vault-integrated notes with visual content extraction. 8 | 9 | Video URL: {{video_url}} 10 | Topic: {{topic}} 11 | Content Areas: {{content_areas}} 12 | Video Duration: {{duration}} 13 | 14 | This enhanced chain will: 15 | 1. **Analyze Content**: Extract key concepts and educational structure 16 | 2. **Extract Visuals**: Download relevant visual examples and integrate into notes 17 | 3. **Deep Analysis**: Apply ReACT methodology for insights and connections 18 | 4. **Create Notes**: Generate comprehensive markdown with proper formatting 19 | 5. **Vault Integration**: Find actual related notes in vault for cross-referencing 20 | 6. **Final Refinement**: Polish formatting and ensure S.P.A.R.C. compliance 21 | 22 | The result will be a professionally formatted note with embedded visual examples, proper vault integration, and comprehensive educational content. 23 | 24 | ## Chain Steps 25 | 26 | 1. **Initial Content Analysis** (content_analysis) 27 | - Input Mapping: {"content":"video_content"} 28 | - Output Mapping: {"analysis_output":"content_analysis"} 29 | 30 | 2. **Visual Content Extraction** (video_visual_extraction) 31 | - Input Mapping: {"video_url":"video_url","topic":"topic","content_areas":"content_areas"} 32 | - Output Mapping: {"visual_content":"extracted_visuals"} 33 | 34 | 3. **Deep Analysis Integration** (deep_analysis) 35 | - Input Mapping: {"content":"video_content","initial_analysis":"content_analysis"} 36 | - Output Mapping: {"deep_analysis_output":"deep_insights"} 37 | 38 | 4. **Comprehensive Note Creation** (markdown_notebook) 39 | - Input Mapping: {"topic":"topic","analysis":"deep_insights"} 40 | - Output Mapping: {"notebook_output":"structured_notes"} 41 | 42 | 5. **Vault Integration** (vault_related_notes_finder) 43 | - Input Mapping: {"note_topic":"topic","content_areas":"content_areas"} 44 | - Output Mapping: {"related_notes":"vault_connections"} 45 | 46 | 6. **Final Refinement** (note_refinement) 47 | - Input Mapping: {"notes":"structured_notes"} 48 | - Output Mapping: {"final_notes":"polished_output"} 49 | 50 | ``` -------------------------------------------------------------------------------- /server/src/frameworks/types/index.ts: -------------------------------------------------------------------------------- ```typescript 1 | /** 2 | * Framework Types Index 3 | * 4 | * Consolidated export of all framework-related type definitions. 5 | * This replaces the distributed type definitions across multiple files 6 | * and provides a single source of truth for framework types. 7 | */ 8 | 9 | // Methodology guide types 10 | export type { 11 | FrameworkMethodology, 12 | FrameworkDefinition, 13 | FrameworkExecutionContext, 14 | FrameworkSelectionCriteria, 15 | PromptCreationGuidance, 16 | ProcessingGuidance, 17 | StepGuidance, 18 | MethodologyEnhancement, 19 | ArgumentGuidance, 20 | ProcessingStep, 21 | ExecutionStep, 22 | QualityGate, 23 | TemplateEnhancement, 24 | MethodologyToolDescription, 25 | MethodologyToolDescriptions, 26 | MethodologyValidation, 27 | IMethodologyGuide 28 | } from './methodology-types.js'; 29 | 30 | export { 31 | BaseMethodologyGuide 32 | } from './methodology-types.js'; 33 | 34 | // Prompt guidance types 35 | export type { 36 | SystemPromptInjectionConfig, 37 | SystemPromptInjectionResult, 38 | TemplateEnhancementConfig, 39 | TemplateEnhancementType, 40 | TemplateEnhancementResult, 41 | AppliedEnhancement, 42 | MethodologyTrackingState, 43 | MethodologySwitchRecord, 44 | MethodologyStateChangeEvent, 45 | PromptGuidanceConfig, 46 | PromptGuidanceResult, 47 | PromptGuidanceAnalytics, 48 | FrameworkStateInfo, 49 | IPromptGuidanceService, 50 | // Phase 3 additions 51 | MethodologyState, 52 | MethodologySwitchRequest, 53 | MethodologyHealth, 54 | PersistedMethodologyState, 55 | TemplateProcessingGuidance 56 | } from './prompt-guidance-types.js'; 57 | 58 | // Integration types 59 | export type { 60 | IntegratedAnalysisResult, 61 | FrameworkSwitchingConfig, 62 | FrameworkAlignmentResult, 63 | FrameworkUsageInsights, 64 | FrameworkUsageMetrics, 65 | FrameworkSwitchRecommendation, 66 | MCPToolIntegrationContext, 67 | MCPToolIntegrationResult, 68 | SemanticIntegrationConfig, 69 | CrossSystemIntegrationStatus, 70 | IntegrationPerformanceMetrics, 71 | IntegrationEvent, 72 | IFrameworkSemanticIntegration, 73 | IMCPToolIntegration, 74 | SystemIntegrationConfig 75 | } from './integration-types.js'; 76 | 77 | // Legacy type aliases for backward compatibility during migration 78 | // These will be removed in Phase 4 79 | export type { 80 | FrameworkDefinition as LegacyFrameworkDefinition, 81 | FrameworkExecutionContext as LegacyFrameworkExecutionContext, 82 | FrameworkSelectionCriteria as LegacyFrameworkSelectionCriteria 83 | } from './methodology-types.js'; ``` -------------------------------------------------------------------------------- /server/src/gates/templates/security_validation.md: -------------------------------------------------------------------------------- ```markdown 1 | # Security Validation Self-Check Template 2 | 3 | ## Instructions 4 | Evaluate the security aspects of your response, especially for code generation and technical content. 5 | 6 | ## Security Assessment Criteria 7 | 8 | ### Code Security (if applicable) 9 | - [ ] **No Hardcoded Secrets**: Code does not contain hardcoded passwords, API keys, or tokens 10 | - [ ] **Input Validation**: All user inputs are properly validated and sanitized 11 | - [ ] **SQL Injection Prevention**: Uses parameterized queries or prepared statements 12 | - [ ] **Authentication**: Proper authentication mechanisms are implemented 13 | - [ ] **Authorization**: Appropriate access controls are in place 14 | - [ ] **HTTPS/TLS**: Secure communication protocols are used 15 | - [ ] **Error Handling**: Errors don't expose sensitive information 16 | 17 | ### General Security Awareness 18 | - [ ] **OWASP Compliance**: Follows OWASP Top 10 security guidelines 19 | - [ ] **Rate Limiting**: API endpoints include rate limiting considerations 20 | - [ ] **Logging Security**: Security events are logged without exposing sensitive data 21 | - [ ] **Dependency Security**: Discusses keeping dependencies updated 22 | - [ ] **Principle of Least Privilege**: Access is limited to minimum necessary 23 | 24 | ### Security Education 25 | - [ ] **Vulnerability Awareness**: Addresses potential security vulnerabilities 26 | - [ ] **Best Practices**: Includes security best practices and recommendations 27 | - [ ] **Risk Assessment**: Identifies and discusses security risks 28 | - [ ] **Mitigation Strategies**: Provides concrete security mitigation approaches 29 | 30 | ## Self-Assessment 31 | 32 | **Overall Security Score (0.0-1.0): ___** 33 | 34 | **Security Breakdown:** 35 | - Code Security: ___/10 36 | - Awareness: ___/10 37 | - Education: ___/10 38 | - Best Practices: ___/10 39 | 40 | **Security Review:** 41 | [Assess how well the response addresses security considerations] 42 | 43 | **Identified Security Issues:** 44 | [List any potential security concerns or missing security considerations] 45 | 46 | **Security Improvements Needed:** 47 | [Specific improvements if score < 0.85] 48 | 49 | ## Validation Response 50 | 51 | Security assessment criteria: 52 | - **PASS** if score ≥ 0.85 and no critical security issues identified 53 | - **NEEDS_IMPROVEMENT** if score < 0.85 or contains security vulnerabilities 54 | 55 | **Final Assessment: [PASS/NEEDS_IMPROVEMENT]** ``` -------------------------------------------------------------------------------- /server/prompts/development/strategicImplement.md: -------------------------------------------------------------------------------- ```markdown 1 | # Strategic Implementation 2 | 3 | ## Description 4 | Systematically implement a plan phase with architectural alignment, compatibility checking, and progress tracking 5 | 6 | ## User Message Template 7 | Strategically implement the following plan phase with systematic architectural alignment: 8 | 9 | **Plan Document**: {{plan_path}} 10 | **Phase to Implement**: {{phase_identifier}} 11 | 12 | ## Implementation Protocol 13 | 14 | ### 1. Context Discovery & Analysis 15 | - Read and analyze the plan document thoroughly 16 | - Understand the phase objectives, requirements, and success criteria 17 | - Map dependencies and integration points with existing systems 18 | - Identify potential compatibility issues and risks 19 | 20 | ### 2. Architectural Alignment 21 | - Review current system architecture for alignment points 22 | - Check interface compatibility with existing systems 23 | - Identify required changes to maintain consistency 24 | - Plan for backwards compatibility where needed 25 | 26 | ### 3. Strategic Implementation 27 | - Implement changes incrementally with validation at each step 28 | - Follow established patterns and conventions from the codebase 29 | - Maintain existing functionality while adding new capabilities 30 | - Use appropriate design patterns (composition over inheritance, service patterns, etc.) 31 | 32 | ### 4. Validation & Testing 33 | - Run typecheck to ensure TypeScript compliance 34 | - Execute relevant tests to verify functionality 35 | - Check for integration issues with dependent systems 36 | - Validate performance impact 37 | 38 | ### 5. Progress Tracking 39 | - Update the plan document with implementation status 40 | - Mark completed tasks and note any deviations 41 | - Document decisions made during implementation 42 | - Record any blockers or issues encountered 43 | 44 | ## Expected Outputs 45 | 46 | 1. **Implementation**: Complete, tested code changes aligned with architecture 47 | 2. **Updated Plan**: Progress notes, completion status, and next steps 48 | 3. **Documentation**: Key decisions and any architectural changes 49 | 4. **Validation**: Test results and compatibility verification 50 | 51 | Apply the following principles: 52 | - **Understand before changing**: Analyze existing code thoroughly 53 | - **Incremental progress**: Small, validated steps 54 | - **Maintain compatibility**: Preserve existing interfaces 55 | - **Follow patterns**: Use established architectural patterns 56 | - **Track progress**: Keep plan document current 57 | ``` -------------------------------------------------------------------------------- /server/prompts/analysis/deep_analysis.md: -------------------------------------------------------------------------------- ```markdown 1 | # Deep Analysis 2 | 3 | ## Description 4 | Expand on a previous analysis by diving deeper into information, identifying key insights and relationships. 5 | 6 | ## System Message 7 | You are an expert analyst specializing in deep content analysis and insight extraction. Your role is to build upon initial analysis to uncover deeper patterns, relationships, and implications that may not be immediately obvious. 8 | 9 | ## User Message Template 10 | Based on the initial content analysis, please conduct a comprehensive deep analysis: 11 | 12 | **Original Content:** 13 | {{content|default("No content provided")}} 14 | 15 | **Initial Analysis Results:** 16 | {{initial_analysis|default("No previous analysis provided")}} 17 | 18 | ## Deep Analysis Framework 19 | 20 | Please provide a thorough deep analysis by examining: 21 | 22 | ### 1. **Key Insights Identification** 23 | - Extract the most significant insights from the content 24 | - Identify patterns and trends that emerge 25 | - Highlight unexpected or counterintuitive findings 26 | 27 | ### 2. **Relationship Mapping** 28 | - Identify connections between different concepts 29 | - Map cause-and-effect relationships 30 | - Uncover hidden dependencies and correlations 31 | 32 | ### 3. **Contextual Analysis** 33 | - Place findings within broader context 34 | - Consider historical or comparative perspectives 35 | - Analyze implications for different stakeholders 36 | 37 | ### 4. **Critical Evaluation** 38 | - Assess the reliability and significance of findings 39 | - Identify potential limitations or biases 40 | - Evaluate the strength of evidence presented 41 | 42 | ### 5. **Strategic Implications** 43 | - Determine practical applications of insights 44 | - Identify actionable recommendations 45 | - Consider future implications and trends 46 | 47 | ## Output Format 48 | 49 | Structure your deep analysis as follows: 50 | 51 | ```markdown 52 | # Deep Analysis Results 53 | 54 | ## Executive Summary 55 | [2-3 sentences capturing the most critical insights] 56 | 57 | ## Key Insights 58 | [Detailed findings with supporting evidence] 59 | 60 | ## Relationship Networks 61 | [Connections and interdependencies identified] 62 | 63 | ## Critical Assessment 64 | [Evaluation of findings and their reliability] 65 | 66 | ## Strategic Implications 67 | [Actionable insights and recommendations] 68 | 69 | ## Areas for Further Investigation 70 | [Questions or areas requiring additional research] 71 | ``` 72 | 73 | Please ensure your analysis goes beyond surface-level observations to provide genuine insights that add substantial value to the initial analysis. ``` -------------------------------------------------------------------------------- /server/prompts/documentation/docs-review-refinement.md: -------------------------------------------------------------------------------- ```markdown 1 | # Review and Refinement (Step 4 of 5) 2 | 3 | ## Description 4 | Review the documentation for accuracy, clarity, completeness, and usability 5 | 6 | ## System Message 7 | [System Info: You are a documentation quality specialist who excels at reviewing and refining technical documentation. Your goal is to identify issues with clarity, completeness, accuracy, and usability, and to suggest specific improvements.] 8 | 9 | ## User Message Template 10 | I've created initial documentation content: 11 | {{previous_message}} 12 | 13 | For this documentation type: {{doc_type}} 14 | For this audience: {{audience}} 15 | {% if depth_level %}At this depth level: {{depth_level}}{% endif %} 16 | 17 | Please perform a comprehensive review and refinement of this documentation, focusing on: 18 | 19 | 1. Technical accuracy and precision 20 | - Verify that technical explanations are correct and precise 21 | - Check that code samples would actually work as described 22 | - Ensure API references match expected behavior 23 | - Confirm that terminology is used consistently and correctly 24 | 25 | 2. Clarity and readability 26 | - Identify overcomplicated explanations that could be simplified 27 | - Find sections that need additional context or explanation 28 | - Check for logical flow and clear progression of ideas 29 | - Ensure headings accurately reflect section content 30 | 31 | 3. Completeness and coverage 32 | - Identify missing information or underdeveloped sections 33 | - Check for edge cases or scenarios that aren't addressed 34 | - Ensure prerequisites and dependencies are clearly stated 35 | - Verify that all user questions are anticipated and answered 36 | 37 | 4. Format and presentation 38 | - Check for consistent formatting and style throughout 39 | - Ensure proper use of Markdown or other formatting elements 40 | - Verify that code blocks are properly formatted with syntax highlighting 41 | - Check that diagrams and visuals are clear and properly referenced 42 | 43 | 5. User experience improvements 44 | - Suggest additional examples where they would be helpful 45 | - Identify places where diagrams could clarify complex concepts 46 | - Recommend improved navigation or cross-referencing 47 | - Find opportunities for progressive disclosure of complex topics 48 | 49 | Please provide your review with specific suggestions for improvement, categorized by issue type. For each issue, identify the location in the document, explain the problem, and suggest a specific improvement. 50 | ``` -------------------------------------------------------------------------------- /server/src/gates/templates/educational_clarity_validation.md: -------------------------------------------------------------------------------- ```markdown 1 | # Educational Clarity Self-Check Template 2 | 3 | ## Instructions 4 | Evaluate how effectively your response serves educational purposes and promotes understanding. 5 | 6 | ## Educational Effectiveness Criteria 7 | 8 | ### Learning Structure 9 | - [ ] **Clear Objectives**: Learning goals or objectives are stated or implied 10 | - [ ] **Progressive Complexity**: Content moves from simple to complex concepts 11 | - [ ] **Logical Sequence**: Ideas flow in a logical, easy-to-follow order 12 | - [ ] **Clear Transitions**: Smooth transitions between concepts and sections 13 | - [ ] **Summary/Recap**: Includes summary or key takeaways 14 | 15 | ### Clarity and Accessibility 16 | - [ ] **Plain Language**: Uses clear, jargon-free language when possible 17 | - [ ] **Defined Terms**: Technical terms are defined or explained 18 | - [ ] **Concrete Examples**: Abstract concepts supported with concrete examples 19 | - [ ] **Analogies/Metaphors**: Uses helpful analogies to aid understanding 20 | - [ ] **Visual Structure**: Well-organized with headers, lists, and formatting 21 | 22 | ### Pedagogical Elements 23 | - [ ] **Step-by-Step**: Processes broken down into clear steps 24 | - [ ] **Practice Opportunities**: Includes exercises, questions, or applications 25 | - [ ] **Common Misconceptions**: Addresses potential misunderstandings 26 | - [ ] **Multiple Perspectives**: Presents information from different angles 27 | - [ ] **Real-World Applications**: Shows practical applications of concepts 28 | 29 | ### Engagement and Understanding 30 | - [ ] **Reader Engagement**: Content maintains reader interest and attention 31 | - [ ] **Comprehension Checks**: Includes ways to verify understanding 32 | - [ ] **Appropriate Difficulty**: Content level matches intended audience 33 | - [ ] **Interactive Elements**: Encourages active learning and participation 34 | - [ ] **Motivational Context**: Explains why the information is valuable 35 | 36 | ## Self-Assessment 37 | 38 | **Overall Educational Clarity Score (0.0-1.0): ___** 39 | 40 | **Educational Breakdown:** 41 | - Learning Structure: ___/10 42 | - Clarity/Accessibility: ___/10 43 | - Pedagogical Elements: ___/10 44 | - Engagement: ___/10 45 | 46 | **Target Audience: [Beginner/Intermediate/Advanced]** 47 | 48 | **Educational Effectiveness Review:** 49 | [Assess how well the content serves educational purposes] 50 | 51 | **Learning Obstacles:** 52 | [Identify any barriers to understanding] 53 | 54 | **Clarity Improvements Needed:** 55 | [Specific improvements if score < 0.8] 56 | 57 | ## Validation Response 58 | 59 | Educational clarity assessment: 60 | - **PASS** if score ≥ 0.8 and content effectively promotes learning 61 | - **NEEDS_IMPROVEMENT** if score < 0.8 or lacks educational structure 62 | 63 | **Final Assessment: [PASS/NEEDS_IMPROVEMENT]** ``` -------------------------------------------------------------------------------- /server/src/gates/templates/technical_accuracy_validation.md: -------------------------------------------------------------------------------- ```markdown 1 | # Technical Accuracy Self-Check Template 2 | 3 | ## Instructions 4 | Evaluate the technical correctness and precision of your response. 5 | 6 | ## Technical Accuracy Criteria 7 | 8 | ### Factual Correctness 9 | - [ ] **Verified Facts**: Technical facts and specifications are accurate and verifiable 10 | - [ ] **Version Specificity**: Includes relevant version numbers and compatibility information 11 | - [ ] **Official Sources**: References official documentation when available 12 | - [ ] **Current Information**: Uses up-to-date technical information 13 | - [ ] **Precise Terminology**: Uses technical terms correctly and precisely 14 | 15 | ### Technical Depth 16 | - [ ] **Implementation Details**: Provides accurate implementation details where relevant 17 | - [ ] **Error Handling**: Addresses error conditions and edge cases appropriately 18 | - [ ] **Performance Considerations**: Discusses performance implications accurately 19 | - [ ] **Best Practices**: Follows established technical best practices 20 | - [ ] **Code Correctness**: Code examples are syntactically correct and functional 21 | 22 | ### Evidence and Support 23 | - [ ] **Documentation References**: Links to or mentions official documentation 24 | - [ ] **Standards Compliance**: Follows relevant technical standards (RFC, ISO, etc.) 25 | - [ ] **Testing Verification**: Code examples can be tested and verified 26 | - [ ] **Context Appropriate**: Technical level matches the intended audience 27 | - [ ] **Trade-off Analysis**: Discusses technical trade-offs and alternatives 28 | 29 | ### Precision and Clarity 30 | - [ ] **Specific Details**: Avoids vague generalizations with concrete specifics 31 | - [ ] **Accurate Measurements**: Provides accurate performance metrics or specifications 32 | - [ ] **Clear Limitations**: Clearly states limitations and constraints 33 | - [ ] **Distinction Clarity**: Distinguishes between different technical concepts clearly 34 | 35 | ## Self-Assessment 36 | 37 | **Overall Technical Accuracy Score (0.0-1.0): ___** 38 | 39 | **Technical Breakdown:** 40 | - Factual Correctness: ___/10 41 | - Technical Depth: ___/10 42 | - Evidence/Support: ___/10 43 | - Precision/Clarity: ___/10 44 | 45 | **Technical Verification:** 46 | [Evaluate the accuracy and precision of technical content] 47 | 48 | **Sources Consulted:** 49 | [List any official documentation or standards referenced] 50 | 51 | **Areas Requiring Verification:** 52 | [Identify any technical claims that need additional verification if score < 0.8] 53 | 54 | ## Validation Response 55 | 56 | Technical accuracy assessment: 57 | - **PASS** if score ≥ 0.8 and all critical technical facts verified 58 | - **NEEDS_IMPROVEMENT** if score < 0.8 or contains unverified technical claims 59 | 60 | **Final Assessment: [PASS/NEEDS_IMPROVEMENT]** ``` -------------------------------------------------------------------------------- /server/prompts/analysis/content_analysis.md: -------------------------------------------------------------------------------- ```markdown 1 | # Content Analysis 2 | 3 | ## Description 4 | Systematically analyze web content, breaking it down into key components. 5 | 6 | ## System Message 7 | You are a content analysis expert. Follow the provided framework to systematically break down and analyze the given content. 8 | 9 | ## User Message Template 10 | Perform a comprehensive content analysis of the following material: 11 | 12 | {{content}} 13 | 14 | **ANALYSIS FRAMEWORK - Execute each step systematically:** 15 | 16 | ### 1. Initial Content Overview 17 | - **Content Type**: Identify the format and medium (article, video transcript, report, etc.) 18 | - **Source**: Note the origin and credibility indicators 19 | - **Length**: Approximate word count and reading time 20 | - **Date/Context**: When was this created and in what context? 21 | 22 | ### 2. Structural Analysis 23 | - **Main Sections**: Break down the content into logical sections/chapters 24 | - **Argument Flow**: How does the content progress logically? 25 | - **Supporting Elements**: What evidence, examples, or data are used? 26 | - **Visual Elements**: Any charts, images, or multimedia components? 27 | 28 | ### 3. Key Themes & Topics 29 | - **Primary Theme**: What is the main subject or thesis? 30 | - **Secondary Themes**: What supporting topics are covered? 31 | - **Keywords**: Extract the most important terms and concepts 32 | - **Tone & Style**: Formal, informal, persuasive, informative, etc. 33 | 34 | ### 4. Critical Analysis 35 | - **Strengths**: What aspects are well-developed or compelling? 36 | - **Weaknesses**: What gaps, biases, or unclear areas exist? 37 | - **Evidence Quality**: How strong is the supporting evidence? 38 | - **Logical Consistency**: Are the arguments coherent and well-reasoned? 39 | 40 | ### 5. Key Insights & Takeaways 41 | - **Main Messages**: What are the 3-5 most important points? 42 | - **Actionable Items**: What specific actions or recommendations are suggested? 43 | - **Implications**: What are the broader consequences or applications? 44 | - **Questions Raised**: What important questions does this content raise? 45 | 46 | ### 6. Content Categorization 47 | - **Audience**: Who is the intended audience? 48 | - **Purpose**: What is the content trying to achieve? 49 | - **Genre/Category**: How would you classify this content? 50 | - **Complexity Level**: Beginner, intermediate, or advanced? 51 | 52 | ### 7. Summary & Conclusion 53 | - **Executive Summary**: Provide a concise 2-3 sentence overview 54 | - **Key Quotes**: Extract 2-3 most significant quotes or statements 55 | - **Further Research**: What topics warrant additional investigation? 56 | - **Related Content**: What other materials would complement this? 57 | 58 | **OUTPUT FORMAT**: Present your analysis in the above structured format with clear headings and bullet points for easy navigation and reference. 59 | ``` -------------------------------------------------------------------------------- /server/prompts/development/code_review_optimization_chain.md: -------------------------------------------------------------------------------- ```markdown 1 | # Comprehensive Code Review 2 | 3 | ## Description 4 | Systematic 6-step code review covering structure, functionality, security, performance, optimization, and quality assurance 5 | 6 | ## System Message 7 | You are an expert code reviewer providing systematic, comprehensive analysis. Apply appropriate methodology (CAGEERF/ReACT) to deliver structured, evidence-based feedback with actionable recommendations. 8 | 9 | ## User Message Template 10 | # Comprehensive Code Review 11 | 12 | **Target Code**: {{target_code}} 13 | **Language/Framework**: {{language_framework}} 14 | **Performance Goals**: {{performance_goals}} 15 | 16 | This chain performs a systematic 6-step code review: 17 | 18 | ## Step 1: Structure & Organization Analysis 19 | Analyze code architecture, organization, patterns, naming conventions, documentation, and dependency management. 20 | 21 | **Output Required**: Structural assessment with identified patterns, coupling issues, and organization recommendations. 22 | 23 | --- 24 | 25 | ## Step 2: Functionality & Logic Review 26 | Examine business logic correctness, edge cases, error handling, input/output processing, and algorithm efficiency. 27 | 28 | **Output Required**: Logic validation with edge case analysis, error handling assessment, and correctness verification. 29 | 30 | --- 31 | 32 | ## Step 3: Security & Best Practices Audit 33 | Review for security vulnerabilities: input validation, authentication/authorization, data exposure, injection risks, and framework-specific security patterns. 34 | 35 | **Output Required**: Security assessment with vulnerability identification, risk levels, and mitigation strategies. 36 | 37 | --- 38 | 39 | ## Step 4: Performance Analysis 40 | Evaluate time complexity, memory usage, I/O efficiency, caching opportunities, and database query optimization. 41 | 42 | **Output Required**: Performance metrics with complexity analysis, bottleneck identification, and optimization opportunities. 43 | 44 | --- 45 | 46 | ## Step 5: Optimization Implementation 47 | Apply identified optimizations: refactor algorithms, implement performance improvements, add caching, optimize data structures, reduce complexity. 48 | 49 | **Output Required**: Optimized code with documented changes, performance improvements, and refactoring rationale. 50 | 51 | --- 52 | 53 | ## Step 6: Quality Assurance & Documentation 54 | Finalize with: code formatting consistency, test coverage analysis, documentation updates, performance benchmarking, and summary with metrics. 55 | 56 | **Output Required**: Final review report with quality metrics, test coverage, performance benchmarks, and comprehensive summary. 57 | 58 | ## Gate Configuration 59 | 60 | ```json 61 | { 62 | "include": [ 63 | "code-quality", 64 | "research-quality", 65 | "technical-accuracy", 66 | "content-structure", 67 | "security-awareness" 68 | ], 69 | "framework_gates": true 70 | } 71 | ``` 72 | ``` -------------------------------------------------------------------------------- /server/src/execution/parsers/index.ts: -------------------------------------------------------------------------------- ```typescript 1 | /** 2 | * Execution Parsers Export Module 3 | * 4 | * Centralizes all parsing infrastructure exports including: 5 | * - Unified Command Parser with multi-strategy parsing 6 | * - Argument Processing Pipeline with validation and enrichment 7 | * - Compatibility Wrapper for backward compatibility 8 | */ 9 | 10 | // Core parsing infrastructure 11 | export { 12 | UnifiedCommandParser, 13 | createUnifiedCommandParser, 14 | type CommandParseResult 15 | } from './unified-command-parser.js'; 16 | 17 | export { 18 | ArgumentParser, 19 | createArgumentParser, 20 | type ArgumentParsingResult, 21 | type ExecutionContext 22 | } from './argument-parser.js'; 23 | 24 | // Context resolution system 25 | export { 26 | ContextResolver, 27 | createContextResolver, 28 | type ContextResolution, 29 | type ContextProvider, 30 | type ContextSource, 31 | type ContextAggregationOptions 32 | } from '../context/context-resolver.js'; 33 | 34 | // Backward compatibility wrapper removed - migration completed 35 | // Legacy parsing methods are preserved through deprecated redirects in consolidated-prompt-engine.ts 36 | 37 | // Re-export for convenience 38 | export type { 39 | PromptData, 40 | PromptArgument, 41 | ConvertedPrompt 42 | } from '../../types/index.js'; 43 | 44 | export type { 45 | ValidationResult, 46 | ValidationError, 47 | ValidationWarning 48 | } from '../types.js'; 49 | 50 | import { Logger } from "../../logging/index.js"; 51 | import { UnifiedCommandParser, createUnifiedCommandParser } from "./unified-command-parser.js"; 52 | import { ArgumentParser, createArgumentParser } from "./argument-parser.js"; 53 | import { ContextResolver, createContextResolver } from "../context/context-resolver.js"; 54 | 55 | /** 56 | * Complete parsing system with all components 57 | */ 58 | export interface ParsingSystem { 59 | commandParser: UnifiedCommandParser; 60 | argumentParser: ArgumentParser; 61 | contextResolver: ContextResolver; 62 | } 63 | 64 | /** 65 | * Factory function to create complete parsing system 66 | * 67 | * Creates a fully configured parsing system with: 68 | * - Unified command parser with multi-strategy support 69 | * - Argument processor with validation and type coercion 70 | * - Context resolver with intelligent fallbacks 71 | * 72 | * @param logger Logger instance for system-wide logging 73 | * @returns Complete parsing system ready for use 74 | */ 75 | export function createParsingSystem(logger: Logger): ParsingSystem { 76 | const commandParser = createUnifiedCommandParser(logger); 77 | const argumentParser = createArgumentParser(logger); 78 | const contextResolver = createContextResolver(logger); 79 | 80 | logger.info("Parsing system initialized successfully"); 81 | logger.info("- Unified command parser with multi-strategy support"); 82 | logger.info("- Argument parser with validation pipeline"); 83 | logger.info("- Context resolver with intelligent fallbacks"); 84 | 85 | return { 86 | commandParser, 87 | argumentParser, 88 | contextResolver 89 | }; 90 | } ``` -------------------------------------------------------------------------------- /server/prompts/analysis/deep_research.md: -------------------------------------------------------------------------------- ```markdown 1 | # Deep Research Framework 2 | 3 | ## Description 4 | A comprehensive framework for conducting thorough, methodical research on complex topics with academic rigor. 5 | 6 | ## System Message 7 | You are a professional researcher with expertise in conducting comprehensive investigations. Your approach is methodical, thorough, and adheres to high standards of academic rigor and intellectual honesty. Help the user explore their topic with depth, nuance, and critical thinking. 8 | 9 | ## User Message Template 10 | # Deep Research Framework 11 | 12 | I need you to conduct deep research on {{topic}}. Approach this as a professional researcher would, with methodical analysis, critical thinking, and intellectual honesty. 13 | 14 | ## Research Structure 15 | 16 | 1. **Topic Exploration (Breadth)** 17 | - Define the core concepts, terminology, and scope 18 | - Map the key areas, sub-topics, and domains of knowledge 19 | - Identify the major schools of thought and contrasting perspectives 20 | - Establish historical context and evolution of understanding 21 | 22 | 2. **Deep Dive Analysis (Depth)** 23 | - Analyze the most significant developments, breakthroughs, or controversies 24 | - Examine the methodologies, evidence, and reasoning behind key findings 25 | - Identify gaps, limitations, or areas of ongoing debate 26 | - Evaluate the credibility and reliability of different sources 27 | 28 | 3. **Critical Synthesis** 29 | - Draw connections between different areas of knowledge 30 | - Synthesize findings to form a coherent understanding 31 | - Identify patterns, trends, or emerging themes 32 | - Form preliminary conclusions while acknowledging uncertainties 33 | 34 | 4. **Research Quality & Rigor** 35 | - Cite credible sources and evidence 36 | - Acknowledge limitations and potential biases 37 | - Present multiple perspectives fairly 38 | - Maintain intellectual honesty about what is known vs. unknown 39 | 40 | 5. **Future Directions** 41 | - Identify promising areas for further investigation 42 | - Suggest important questions that remain unanswered 43 | - Outline potential practical applications or implications 44 | 45 | ## Research Guidelines 46 | 47 | - Prioritize academic sources, peer-reviewed research, and established authorities 48 | - Be transparent about the strength and limitations of evidence 49 | - Maintain objectivity while acknowledging inherent complexities 50 | - Structure information in a logical, accessible format 51 | - Include diverse perspectives and avoid tunnel vision 52 | 53 | ## Output Format 54 | 55 | Please structure your research in a comprehensive report that includes: 56 | - Executive summary of key findings 57 | - Detailed analysis organized by topic areas 58 | - Critical evaluation of sources and evidence 59 | - Synthesis of different perspectives 60 | - Identified gaps and future research directions 61 | - Bibliography or source references where applicable 62 | 63 | Begin your research on: {{topic}} 64 | ``` -------------------------------------------------------------------------------- /scripts/test_server.js: -------------------------------------------------------------------------------- ```javascript 1 | #!/usr/bin/env node 2 | 3 | // Simple test script to verify server startup 4 | const { spawn } = require('child_process'); 5 | const path = require('path'); 6 | 7 | console.log('Testing MCP Server startup...'); 8 | 9 | const serverPath = path.join(__dirname, 'server', 'dist', 'index.js'); 10 | console.log('Server path:', serverPath); 11 | 12 | // Test 1: Check if server can show help 13 | console.log('\n=== Test 1: Help Command ==='); 14 | const helpProcess = spawn('node', [serverPath, '--help'], { 15 | stdio: 'pipe', 16 | cwd: path.join(__dirname, 'server') 17 | }); 18 | 19 | let helpOutput = ''; 20 | let helpError = ''; 21 | 22 | helpProcess.stdout.on('data', (data) => { 23 | helpOutput += data.toString(); 24 | }); 25 | 26 | helpProcess.stderr.on('data', (data) => { 27 | helpError += data.toString(); 28 | }); 29 | 30 | helpProcess.on('close', (code) => { 31 | console.log(`Help command exit code: ${code}`); 32 | if (helpOutput) { 33 | console.log('Help output:', helpOutput.substring(0, 200) + '...'); 34 | } 35 | if (helpError) { 36 | console.log('Help stderr:', helpError); 37 | } 38 | 39 | // Test 2: Try to start server with debug output (timeout after 5 seconds) 40 | console.log('\n=== Test 2: Server Startup (5 second timeout) ==='); 41 | const startProcess = spawn('node', [serverPath, '--debug-startup'], { 42 | stdio: 'pipe', 43 | cwd: path.join(__dirname, 'server') 44 | }); 45 | 46 | let startOutput = ''; 47 | let startError = ''; 48 | 49 | startProcess.stdout.on('data', (data) => { 50 | startOutput += data.toString(); 51 | }); 52 | 53 | startProcess.stderr.on('data', (data) => { 54 | startError += data.toString(); 55 | }); 56 | 57 | // Kill after 5 seconds 58 | const timeout = setTimeout(() => { 59 | console.log('Killing server after 5 seconds...'); 60 | startProcess.kill('SIGINT'); 61 | }, 5000); 62 | 63 | startProcess.on('close', (code) => { 64 | clearTimeout(timeout); 65 | console.log(`Server startup exit code: ${code}`); 66 | if (startOutput) { 67 | console.log('Server stdout:', startOutput); 68 | } 69 | if (startError) { 70 | console.log('Server stderr:', startError); 71 | } 72 | 73 | // Analyze results 74 | console.log('\n=== Analysis ==='); 75 | const hasError = startError.includes('Error') || startError.includes('error'); 76 | const hasSuccess = startError.includes('successfully') || startOutput.includes('successfully'); 77 | 78 | if (hasError) { 79 | console.log('❌ Server startup had errors'); 80 | } else if (hasSuccess) { 81 | console.log('✅ Server appears to start successfully'); 82 | } else { 83 | console.log('⚠️ Server startup status unclear'); 84 | } 85 | }); 86 | 87 | startProcess.on('error', (error) => { 88 | clearTimeout(timeout); 89 | console.log('Server startup error:', error); 90 | }); 91 | }); 92 | 93 | helpProcess.on('error', (error) => { 94 | console.log('Help command error:', error); 95 | }); ``` -------------------------------------------------------------------------------- /server/src/gates/guidance/FrameworkGuidanceFilter.ts: -------------------------------------------------------------------------------- ```typescript 1 | /** 2 | * Framework Guidance Filter - Pure Function Implementation 3 | * 4 | * Extracts framework-specific guidance from multi-framework guidance text. 5 | * This is a pure function with no dependencies for maximum reusability. 6 | */ 7 | 8 | /** 9 | * Filter guidance text to show only the specified framework's guidance 10 | * 11 | * @param guidance - Original guidance text (may contain multiple frameworks) 12 | * @param activeFramework - Framework to filter for (e.g., 'ReACT', 'CAGEERF') 13 | * @returns Filtered guidance showing only the active framework's content 14 | */ 15 | export function filterFrameworkGuidance(guidance: string, activeFramework: string): string { 16 | // Parse the guidance to extract only the relevant framework section 17 | const lines = guidance.split('\n'); 18 | const filteredLines: string[] = []; 19 | let foundRelevantSection = false; 20 | 21 | for (const line of lines) { 22 | // Check if this line contains framework-specific guidance 23 | if (line.includes(`- ${activeFramework}:`)) { 24 | foundRelevantSection = true; 25 | filteredLines.push(line); 26 | } else if (line.startsWith('- ') && (line.includes('CAGEERF:') || line.includes('ReACT:') || line.includes('5W1H:') || line.includes('SCAMPER:'))) { 27 | // Skip other framework-specific lines 28 | foundRelevantSection = false; 29 | continue; 30 | } else if (!line.startsWith('- ') || foundRelevantSection) { 31 | // Include general guidance lines and continuation lines 32 | filteredLines.push(line); 33 | } 34 | } 35 | 36 | // If we found framework-specific guidance, use filtered version 37 | if (filteredLines.some(line => line.includes(`- ${activeFramework}:`))) { 38 | let result = filteredLines.join('\n'); 39 | 40 | // Clean up the framework-specific line to be more concise 41 | result = result.replace(`- ${activeFramework}: `, `**${activeFramework} Methodology Guidelines:**\n- `); 42 | 43 | return result; 44 | } 45 | 46 | // Fallback to original guidance if no framework-specific section found 47 | return guidance; 48 | } 49 | 50 | /** 51 | * Check if guidance text contains framework-specific content 52 | * 53 | * @param guidance - Guidance text to analyze 54 | * @returns true if guidance contains framework-specific sections 55 | */ 56 | export function hasFrameworkSpecificContent(guidance: string): boolean { 57 | const frameworkPatterns = ['CAGEERF:', 'ReACT:', '5W1H:', 'SCAMPER:']; 58 | return frameworkPatterns.some(pattern => guidance.includes(pattern)); 59 | } 60 | 61 | /** 62 | * Get list of frameworks mentioned in guidance text 63 | * 64 | * @param guidance - Guidance text to analyze 65 | * @returns Array of framework names found in the guidance 66 | */ 67 | export function getFrameworksInGuidance(guidance: string): string[] { 68 | const frameworkPatterns = [ 69 | { name: 'CAGEERF', pattern: 'CAGEERF:' }, 70 | { name: 'ReACT', pattern: 'ReACT:' }, 71 | { name: '5W1H', pattern: '5W1H:' }, 72 | { name: 'SCAMPER', pattern: 'SCAMPER:' } 73 | ]; 74 | 75 | return frameworkPatterns 76 | .filter(fw => guidance.includes(fw.pattern)) 77 | .map(fw => fw.name); 78 | } ``` -------------------------------------------------------------------------------- /server/tests/test-enhanced-parsing.js: -------------------------------------------------------------------------------- ```javascript 1 | #!/usr/bin/env node 2 | 3 | /** 4 | * Quick test script to verify enhanced chain step parsing with gate support 5 | */ 6 | 7 | import { createLogger } from "../dist/logging/index.js"; 8 | import { PromptLoader } from "../dist/prompts/loader.js"; 9 | 10 | async function testEnhancedParsing() { 11 | console.log("🧪 Testing Enhanced Chain Step Parsing with Gate Support...\n"); 12 | 13 | const logger = createLogger({ level: "info" }); 14 | const loader = new PromptLoader(logger); 15 | 16 | try { 17 | // Test parsing the enhanced notes.md file 18 | const result = await loader.loadPromptFile( 19 | "analysis/notes.md", 20 | "/home/minipuft/Applications/claude-prompts-mcp/server/prompts" 21 | ); 22 | 23 | console.log("✅ Successfully parsed notes.md"); 24 | console.log(`📋 Found ${result.chainSteps?.length || 0} chain steps`); 25 | 26 | if (result.chainSteps) { 27 | console.log("\n📊 Chain Steps Analysis:"); 28 | result.chainSteps.forEach((step, index) => { 29 | console.log(`\n Step ${index + 1}:`); 30 | console.log(` - promptId: ${step.promptId}`); 31 | console.log(` - stepName: ${step.stepName}`); 32 | console.log( 33 | ` - gates: ${step.gates ? JSON.stringify(step.gates) : "none"}` 34 | ); 35 | console.log( 36 | ` - inputMapping: ${ 37 | Object.keys(step.inputMapping || {}).length 38 | } inputs` 39 | ); 40 | console.log( 41 | ` - outputMapping: ${ 42 | Object.keys(step.outputMapping || {}).length 43 | } outputs` 44 | ); 45 | }); 46 | 47 | // Verify expected gates 48 | const step1Gates = result.chainSteps[0]?.gates || []; 49 | const step2Gates = result.chainSteps[1]?.gates || []; 50 | const step3Gates = result.chainSteps[2]?.gates || []; 51 | const step4Gates = result.chainSteps[3]?.gates || []; 52 | 53 | console.log("\n🔍 Gate Configuration Verification:"); 54 | console.log( 55 | ` Step 1 gates: ${JSON.stringify(step1Gates)} ${ 56 | step1Gates.includes("research-quality") ? "✅" : "❌" 57 | }` 58 | ); 59 | console.log( 60 | ` Step 2 gates: ${JSON.stringify(step2Gates)} ${ 61 | step2Gates.includes("research-quality") ? "✅" : "❌" 62 | }` 63 | ); 64 | console.log( 65 | ` Step 3 gates: ${JSON.stringify(step3Gates)} ${ 66 | step3Gates.includes("content-structure") ? "✅" : "❌" 67 | }` 68 | ); 69 | console.log( 70 | ` Step 4 gates: ${JSON.stringify(step4Gates)} ${ 71 | step4Gates.includes("content-structure") ? "✅" : "❌" 72 | }` 73 | ); 74 | 75 | const allCorrect = 76 | step1Gates.includes("research-quality") && 77 | step2Gates.includes("research-quality") && 78 | step3Gates.includes("content-structure") && 79 | step4Gates.includes("content-structure"); 80 | 81 | console.log( 82 | `\n🎯 Gate Configuration: ${ 83 | allCorrect ? "✅ ALL CORRECT" : "❌ NEEDS ATTENTION" 84 | }` 85 | ); 86 | } 87 | 88 | console.log("\n✅ Enhanced parsing test completed successfully!"); 89 | } catch (error) { 90 | console.error("❌ Test failed:", error); 91 | process.exit(1); 92 | } 93 | } 94 | 95 | testEnhancedParsing(); 96 | ``` -------------------------------------------------------------------------------- /server/src/gates/templates/framework_compliance_validation.md: -------------------------------------------------------------------------------- ```markdown 1 | # Framework Methodology Compliance Self-Check Template 2 | 3 | ## Instructions 4 | Evaluate how well your response follows the active framework methodology principles. 5 | 6 | ## Framework-Specific Criteria 7 | 8 | ### CAGEERF Framework 9 | - [ ] **Context**: Establishes clear context and background information 10 | - [ ] **Analysis**: Provides systematic analysis of the situation/problem 11 | - [ ] **Goals**: Defines clear goals and objectives 12 | - [ ] **Execution**: Shows concrete execution steps or implementation 13 | - [ ] **Evaluation**: Includes evaluation criteria and assessment methods 14 | - [ ] **Refinement**: Demonstrates iterative improvement and refinement 15 | - [ ] **Framework**: Shows framework-aware systematic thinking 16 | 17 | ### ReACT Framework 18 | - [ ] **Reasoning**: Shows clear reasoning and thought processes 19 | - [ ] **Acting**: Demonstrates concrete actions and implementations 20 | - [ ] **Observation**: Includes observation of results and outcomes 21 | - [ ] **Adjustment**: Shows ability to adjust based on observations 22 | - [ ] **Systematic Approach**: Uses systematic problem-solving methodology 23 | - [ ] **Iterative Process**: Demonstrates iterative reasoning-action cycles 24 | 25 | ### 5W1H Framework 26 | - [ ] **Who**: Addresses who is involved or affected 27 | - [ ] **What**: Clearly defines what is being done or analyzed 28 | - [ ] **When**: Includes timing and scheduling considerations 29 | - [ ] **Where**: Addresses location or context considerations 30 | - [ ] **Why**: Explains reasoning and rationale 31 | - [ ] **How**: Provides detailed methodology and approach 32 | 33 | ### SCAMPER Framework 34 | - [ ] **Substitute**: Considers what can be substituted 35 | - [ ] **Combine**: Explores combination possibilities 36 | - [ ] **Adapt**: Shows adaptation strategies 37 | - [ ] **Modify**: Identifies modification opportunities 38 | - [ ] **Put to Other Uses**: Explores alternative applications 39 | - [ ] **Eliminate**: Considers what can be eliminated 40 | - [ ] **Reverse**: Examines reverse approaches 41 | 42 | ## General Framework Compliance 43 | - [ ] **Systematic Structure**: Follows systematic methodology structure 44 | - [ ] **Comprehensive Coverage**: Addresses all relevant framework aspects 45 | - [ ] **Logical Flow**: Maintains logical progression through framework elements 46 | - [ ] **Methodology Awareness**: Shows understanding of framework principles 47 | - [ ] **Practical Application**: Applies framework meaningfully to the content 48 | 49 | ## Self-Assessment 50 | 51 | **Overall Framework Compliance Score (0.0-1.0): ___** 52 | 53 | **Framework Analysis:** 54 | - Structure Adherence: ___/10 55 | - Completeness: ___/10 56 | - Methodology Understanding: ___/10 57 | - Practical Application: ___/10 58 | 59 | **Active Framework: [CAGEERF/ReACT/5W1H/SCAMPER]** 60 | 61 | **Framework Compliance Review:** 62 | [Evaluate how well the response follows framework principles] 63 | 64 | **Missing Framework Elements:** 65 | [Identify any framework components not adequately addressed if score < 0.75] 66 | 67 | ## Validation Response 68 | 69 | Framework compliance assessment: 70 | - **PASS** if score ≥ 0.75 and systematic methodology is evident 71 | - **NEEDS_IMPROVEMENT** if score < 0.75 or lacks framework structure 72 | 73 | **Final Assessment: [PASS/NEEDS_IMPROVEMENT]** ``` -------------------------------------------------------------------------------- /server/prompts/documentation/create_docs_chain.md: -------------------------------------------------------------------------------- ```markdown 1 | # Documentation Generation Chain 2 | 3 | ## Description 4 | A comprehensive chain for creating high-quality technical documentation with proper structure, formatting, and best practices 5 | 6 | ## System Message 7 | [System Info: You are a documentation expert who guides users through the process of creating comprehensive, high-quality technical documentation. Your goal is to help them understand what goes into excellent documentation and to facilitate the creation of documentation that follows best practices.] 8 | 9 | ## User Message Template 10 | I need to create documentation for: {{project_info}} 11 | 12 | Documentation type required: {{doc_type}} 13 | Target audience: {{audience}} 14 | {% if depth_level %}Desired depth level: {{depth_level}}{% else %}Desired depth level: intermediate{% endif %} 15 | 16 | Please guide me through your systematic documentation generation process. I would like you to: 17 | 18 | 1. Analyze my project to determine what needs to be documented and how 19 | 2. Create a detailed content plan with a logical structure 20 | 3. Generate the actual documentation content 21 | 4. Review and refine the documentation for clarity, accuracy, and completeness 22 | 5. Assemble the final documentation in a polished, production-ready format 23 | 24 | At each step, please show your thinking and explain your recommendations. The final documentation should follow these technical documentation best practices: 25 | 26 | - Well-structured with clear navigation 27 | - Appropriate detail level for the target audience 28 | - Consistent terminology and formatting 29 | - Comprehensive code examples where relevant 30 | - Clear explanations of complex concepts 31 | - Proper Markdown formatting for readability 32 | 33 | Please execute this documentation creation process step by step, ensuring each phase builds upon the previous one to create cohesive, high-quality documentation. 34 | 35 | ## Chain Steps 36 | 37 | 1. promptId: docs-project-analysis 38 | stepName: Project Analysis (Step 1 of 5) 39 | inputMapping: 40 | project_info: project_info 41 | doc_type: doc_type 42 | audience: audience 43 | depth_level: depth_level 44 | outputMapping: 45 | 46 | 2. promptId: docs-content-planning 47 | stepName: Content Planning (Step 2 of 5) 48 | inputMapping: 49 | previous_message: output:Project Analysis 50 | doc_type: doc_type 51 | audience: audience 52 | outputMapping: 53 | 54 | 3. promptId: docs-content-creation 55 | stepName: Content Creation (Step 3 of 5) 56 | inputMapping: 57 | previous_message: output:Content Planning 58 | doc_type: doc_type 59 | project_info: project_info 60 | audience: audience 61 | outputMapping: 62 | 63 | 4. promptId: docs-review-refinement 64 | stepName: Review and Refinement (Step 4 of 5) 65 | inputMapping: 66 | previous_message: output:Content Creation 67 | doc_type: doc_type 68 | audience: audience 69 | depth_level: depth_level 70 | outputMapping: 71 | 72 | 5. promptId: docs-final-assembly 73 | stepName: Final Assembly (Step 5 of 5) 74 | inputMapping: 75 | previous_message: output:Review and Refinement 76 | doc_type: doc_type 77 | audience: audience 78 | depth_level: depth_level 79 | outputMapping: 80 | 81 | ## Output Format 82 | 83 | After completing all 5 steps in the chain, you will have a final output that: 84 | 85 | 1. Is well-organized and clearly structured 86 | 2. Represents the culmination of the entire chain process 87 | 88 | The final output will be the result of the last step in the chain. 89 | ``` -------------------------------------------------------------------------------- /server/src/mcp-tools/prompt-manager/core/types.ts: -------------------------------------------------------------------------------- ```typescript 1 | /** 2 | * Shared types and interfaces for prompt manager modules 3 | */ 4 | 5 | import { Logger } from "../../../logging/index.js"; 6 | import { ConfigManager } from "../../../config/index.js"; 7 | import { 8 | ToolResponse, 9 | ConvertedPrompt, 10 | PromptData, 11 | Category 12 | } from "../../../types/index.js"; 13 | import { ContentAnalyzer } from "../../../semantic/configurable-semantic-analyzer.js"; 14 | import { FrameworkStateManager } from "../../../frameworks/framework-state-manager.js"; 15 | import { FrameworkManager } from "../../../frameworks/framework-manager.js"; 16 | 17 | /** 18 | * Prompt classification interface for management operations 19 | */ 20 | export interface PromptClassification { 21 | executionType: "prompt" | "template" | "chain"; 22 | requiresExecution: boolean; 23 | requiresFramework: boolean; 24 | confidence: number; 25 | reasoning: string[]; 26 | suggestedGates: string[]; 27 | framework?: string; 28 | // Enhanced with configurable analysis information 29 | analysisMode?: string; 30 | capabilities?: { 31 | canDetectStructure: boolean; 32 | canAnalyzeComplexity: boolean; 33 | canRecommendFramework: boolean; 34 | hasSemanticUnderstanding: boolean; 35 | }; 36 | limitations?: string[]; 37 | warnings?: string[]; 38 | } 39 | 40 | /** 41 | * Analysis result with feedback and suggestions 42 | */ 43 | export interface AnalysisResult { 44 | classification: PromptClassification; 45 | feedback: string; 46 | suggestions: string[]; 47 | } 48 | 49 | /** 50 | * Smart filter criteria for prompt discovery 51 | */ 52 | export interface SmartFilters { 53 | text?: string; 54 | type?: string; 55 | category?: string; 56 | confidence?: { min?: number; max?: number }; 57 | execution?: boolean; 58 | gates?: boolean; 59 | intent?: string; 60 | } 61 | 62 | /** 63 | * Dependencies required by all prompt manager modules 64 | */ 65 | export interface PromptManagerDependencies { 66 | logger: Logger; 67 | mcpServer: any; 68 | configManager: ConfigManager; 69 | semanticAnalyzer: ContentAnalyzer; 70 | frameworkStateManager?: FrameworkStateManager; 71 | frameworkManager?: FrameworkManager; 72 | onRefresh: () => Promise<void>; 73 | onRestart: (reason: string) => Promise<void>; 74 | } 75 | 76 | /** 77 | * Data references shared across modules 78 | */ 79 | export interface PromptManagerData { 80 | promptsData: PromptData[]; 81 | convertedPrompts: ConvertedPrompt[]; 82 | categories: Category[]; 83 | } 84 | 85 | /** 86 | * Common operation result interface 87 | */ 88 | export interface OperationResult { 89 | message: string; 90 | affectedFiles?: string[]; 91 | metadata?: any; 92 | } 93 | 94 | /** 95 | * Validation error details 96 | */ 97 | export interface ValidationContext { 98 | operation: string; 99 | requiredFields: string[]; 100 | providedFields: string[]; 101 | } 102 | 103 | /** 104 | * Category management result 105 | */ 106 | export interface CategoryResult { 107 | effectiveCategory: string; 108 | created: boolean; 109 | } 110 | 111 | /** 112 | * File operation result 113 | */ 114 | export interface FileOperationResult { 115 | exists: boolean; 116 | path?: string; 117 | metadata?: any; 118 | } 119 | 120 | /** 121 | * Dependency analysis result 122 | */ 123 | export interface DependencyAnalysis { 124 | dependencies: ConvertedPrompt[]; 125 | risks: string[]; 126 | warnings: string[]; 127 | } 128 | 129 | /** 130 | * Migration operation result 131 | */ 132 | export interface MigrationResult { 133 | fromType: string; 134 | toType: string; 135 | changes: string[]; 136 | result: ToolResponse; 137 | } 138 | 139 | /** 140 | * Base interface for all modular components 141 | */ 142 | export interface PromptManagerModule { 143 | /** 144 | * Update data references 145 | */ 146 | updateData?(data: PromptManagerData): void; 147 | 148 | /** 149 | * Set framework state manager 150 | */ 151 | setFrameworkStateManager?(frameworkStateManager: FrameworkStateManager): void; 152 | 153 | /** 154 | * Set framework manager 155 | */ 156 | setFrameworkManager?(frameworkManager: FrameworkManager): void; 157 | } ``` -------------------------------------------------------------------------------- /server/prompts/development/detect_project_commands.md: -------------------------------------------------------------------------------- ```markdown 1 | # Project Commands Detection 2 | 3 | ## Description 4 | 5 | Intelligently detects and configures project validation commands (lint, test, build) for different project types 6 | 7 | ## System Message 8 | 9 | You are an expert assistant providing structured, systematic analysis. Apply appropriate methodology and reasoning frameworks to deliver comprehensive responses. 10 | 11 | ## User Message Template 12 | 13 | # Project Commands Detection for 14 | 15 | ## Objective 16 | 17 | Analyze the project at `{{ project_path }}` (type: `{{ project_type }}`) to detect and configure validation commands for validation checkpoint system. 18 | 19 | ## Command Detection Strategy 20 | 21 | ### Node.js/Frontend Projects 22 | 23 | **Analysis Steps:** 24 | 25 | 1. Read `package.json` to extract scripts section 26 | 2. Check for TypeScript configuration (`tsconfig.json`) 27 | 3. Detect testing framework and linting tools 28 | 4. Map to standard command patterns 29 | 30 | **Expected Commands:** 31 | 32 | - `quick_validation`: Fast syntax/lint check 33 | - `lint`: Code linting with configuration 34 | - `typecheck`: TypeScript type checking (if applicable) 35 | - `unit_test`: Unit test execution 36 | - `build`: Production build 37 | - `full_test`: Complete test suite 38 | - `e2e_test`: End-to-end tests (if available) 39 | 40 | ### Rust Projects 41 | 42 | **Standard Commands:** 43 | 44 | - `quick_validation`: "cargo check --quiet" 45 | - `lint`: "cargo clippy -- -D warnings" 46 | - `typecheck`: "" (built into Rust) 47 | - `unit_test`: "cargo test" 48 | - `build`: "cargo build" 49 | - `full_test`: "cargo test" 50 | 51 | ### Python Projects 52 | 53 | **Detection Logic:** 54 | 55 | 1. Check for `mypy.ini`, `pyproject.toml` with mypy config 56 | 2. Detect `ruff`, `flake8`, or `pylint` availability 57 | 3. Look for `pytest`, `unittest` setup 58 | 59 | ### Go Projects 60 | 61 | **Standard Commands:** 62 | 63 | - `quick_validation`: "go vet ./..." 64 | - `lint`: "golangci-lint run" or "go fmt ./... && go vet ./..." 65 | - `unit_test`: "go test ./..." 66 | - `build`: "go build ./..." 67 | 68 | ### Enhanced CAGEERF Validation Checkpoints 69 | 70 | Configure these checkpoint commands: 71 | 72 | **CHECKPOINT 1: Context Validation** 73 | 74 | - Syntax validation 75 | - Basic linting 76 | - Type checking 77 | 78 | **CHECKPOINT 2: Progressive Edit Validation** 79 | 80 | - Incremental build validation 81 | - Modified file linting 82 | - Related test execution 83 | 84 | **CHECKPOINT 3: Integration Validation** 85 | 86 | - Full build process 87 | - Integration test suite 88 | - Dependency validation 89 | 90 | **CHECKPOINT 4: Completion Validation** 91 | 92 | - Full test suite 93 | - Performance validation 94 | - Final build verification 95 | 96 | ## Analysis Instructions 97 | 98 | 1. **Project Examination**: Use Read and Glob tools to examine project structure 99 | 2. **Configuration Analysis**: Read relevant config files (package.json, Cargo.toml, etc.) 100 | 3. **Command Mapping**: Map detected tools to standardized command interface 101 | 4. **Validation Setup**: Configure CAGEERF checkpoint commands 102 | 5. **Fallback Strategy**: Provide sensible defaults for undetected tools 103 | 104 | ## Expected Output Format 105 | 106 | ```json 107 | { 108 | "project_type": "{{ project_type }}", 109 | "commands": { 110 | "quick_validation": "command_here", 111 | "lint": "command_here", 112 | "typecheck": "command_here_or_empty", 113 | "unit_test": "command_here", 114 | "build": "command_here", 115 | "full_test": "command_here", 116 | "e2e_test": "command_here_or_empty" 117 | }, 118 | "cageerf_checkpoints": { 119 | "checkpoint_1_context": ["quick_validation", "lint"], 120 | "checkpoint_2_progressive": ["lint", "unit_test"], 121 | "checkpoint_3_integration": ["build", "full_test"], 122 | "checkpoint_4_completion": ["full_test", "build"] 123 | }, 124 | "validation_config": { 125 | "has_typescript": false, 126 | "has_testing": true, 127 | "has_linting": true, 128 | "detected_tools": ["tool1", "tool2"] 129 | } 130 | } 131 | ``` 132 | ``` -------------------------------------------------------------------------------- /server/prompts/analysis/notes.md: -------------------------------------------------------------------------------- ```markdown 1 | # Notes 2 | 3 | ## Description 4 | Enhanced notes chain that searches the vault for actual related notes instead of generating fictional ones - UPDATED" 5 | 6 | ## System Message 7 | You are an expert content analyst who processes information through a systematic multi-step approach. Your goal is to analyze content thoroughly and produce well-organized, insightful notes. 8 | 9 | IMPORTANT: You must explicitly call the MCP `prompt_engine` tool multiple times to progress through this chain. After receiving a response from each step, you must call `prompt_engine` with the appropriate next command using template mode for individual step execution with gate validation. 10 | 11 | IMPLEMENTATION DETAILS: 12 | 13 | - For tracking purposes, use a counter variable to monitor which step of the chain you're on 14 | - Start with counter=1 and increment it after each step 15 | - When counter=5, you're done with all steps and should present the final output 16 | - Use "execution_mode": "template" for each step to enable individual template execution with gate validation 17 | - Store step results in variables (step1_result, step2_result, etc.) for use in subsequent steps 18 | - If any step fails gate validation, review and retry with improved parameters 19 | 20 | ## User Message Template 21 | I'm processing the following content through a multi-step content analysis chain: 22 | 23 | ``` 24 | {{content}} 25 | ``` 26 | 27 | **ENHANCED IMPLEMENTATION INSTRUCTIONS:** 28 | 29 | 1. **Step 1** (counter=1): Call MCP tool `prompt_engine` with: 30 | 31 | ```json 32 | { 33 | "command": ">>content_analysis {{content}}", 34 | "execution_mode": "template", 35 | "gate_validation": true 36 | } 37 | ``` 38 | 39 | Store result as `step1_result` (initial analysis) 40 | 41 | 2. **Step 2** (counter=2): Call MCP tool `prompt_engine` with: 42 | 43 | ```json 44 | { 45 | "command": ">>deep_analysis", 46 | "content": "{{content}}", 47 | "initial_analysis": "[Insert step1_result here]", 48 | "execution_mode": "template", 49 | "gate_validation": true 50 | } 51 | ``` 52 | 53 | Store result as `step2_result` (deep analysis) 54 | 55 | 3. **Step 3** (counter=3): Call MCP tool `prompt_engine` with: 56 | 57 | ```json 58 | { 59 | "command": ">>vault_integrated_notes", 60 | "topic": "{{content}}", 61 | "execution_mode": "template", 62 | "gate_validation": true 63 | } 64 | ``` 65 | 66 | Store result as `step3_result` (vault integrated notes) 67 | 68 | 4. **Step 4** (counter=4): Call MCP tool `prompt_engine` with: 69 | 70 | ```json 71 | { 72 | "command": ">>note_refinement", 73 | "notes": "[Insert step3_result here]", 74 | "execution_mode": "template", 75 | "gate_validation": true 76 | } 77 | ``` 78 | 79 | Store result as `step4_result` (refined notes) 80 | 81 | 5. **Completion** (counter=5): Present final refined notes with execution summary 82 | - Combine all step results into a comprehensive analysis 83 | - Include execution summary: steps completed, validation results, total processing time 84 | - Format as: **Final Result**: [step4_result] + **Execution Summary**: [completion stats] 85 | 86 | **EXECUTION BENEFITS:** 87 | 88 | - ✅ Gate validation ensures quality at each step 89 | - 🔄 Progress tracking shows completion status 90 | - ⚠️ Error recovery if any step fails validation 91 | - 📊 Execution analytics for performance monitoring 92 | 93 | **ERROR HANDLING PROTOCOLS:** 94 | 95 | - **Step Failure**: If any step fails gate validation, review parameters and retry with corrections 96 | - **Tool Unavailable**: If `prompt_engine` is unavailable, report error and wait for system recovery 97 | - **Context Loss**: If step results are lost, restart from last successful step 98 | - **Validation Failure**: If gate validation fails, analyze failure reason and adjust approach 99 | - **Recovery Strategy**: Always preserve step results for potential retry/rollback scenarios 100 | 101 | **Starting counter value**: 1 102 | ``` -------------------------------------------------------------------------------- /server/src/utils/chainUtils.ts: -------------------------------------------------------------------------------- ```typescript 1 | /** 2 | * Chain Utility Functions 3 | * 4 | * Provides helper functions for chain detection and validation. 5 | * MIGRATION: Simplified to support only markdown-embedded chains. 6 | * Modular chain functions are deprecated but maintained for compatibility. 7 | * 8 | * Phase 2 of Chain System Migration (2025-01-30) 9 | */ 10 | 11 | import * as fs from 'fs/promises'; 12 | import * as path from 'path'; 13 | 14 | import { ValidationError } from './errorHandling.js'; 15 | // REMOVED: All types from deleted chain-scaffolding.ts 16 | // Modular chain system has been completely deprecated 17 | 18 | const CHAIN_ID_PATTERN = /^[a-z0-9_-]+$/i; 19 | 20 | function isPathInside(basePath: string, targetPath: string): boolean { 21 | const relative = path.relative(basePath, targetPath); 22 | return !relative.startsWith('..') && !path.isAbsolute(relative); 23 | } 24 | 25 | export function normalizeChainId(chainId: string): string { 26 | if (typeof chainId !== 'string') { 27 | throw new ValidationError('Chain ID must be a string'); 28 | } 29 | 30 | const normalized = chainId.trim(); 31 | 32 | if (normalized.length === 0) { 33 | throw new ValidationError('Chain ID is required'); 34 | } 35 | 36 | if (!CHAIN_ID_PATTERN.test(normalized)) { 37 | throw new ValidationError( 38 | `Invalid chain ID "${normalized}": only letters, numbers, hyphen, and underscore are allowed` 39 | ); 40 | } 41 | 42 | return normalized; 43 | } 44 | 45 | // ===== Utility-Specific Type Definitions ===== 46 | // Types used specifically by utility functions that don't exist in canonical chain types 47 | 48 | /** 49 | * ChainStep interface for utility functions 50 | */ 51 | export interface ChainStep { 52 | promptId: string; 53 | stepName: string; 54 | executionType?: 'prompt' | 'template'; 55 | inputMapping?: Record<string, string>; 56 | outputMapping?: Record<string, string>; 57 | dependencies?: string[]; 58 | } 59 | 60 | // Import ConvertedPrompt from execution domain instead of redefining 61 | import type { ConvertedPrompt } from '../execution/types.js'; 62 | 63 | 64 | /** 65 | * Determines if a prompt is a chain based on the presence of chain steps 66 | * Replaces the redundant isChain boolean property 67 | */ 68 | export function isChainPrompt(prompt: ConvertedPrompt): boolean { 69 | return (prompt.chainSteps?.length || 0) > 0; 70 | } 71 | 72 | /** 73 | * Get the number of steps in a chain prompt 74 | */ 75 | export function getChainStepCount(prompt: ConvertedPrompt): number { 76 | return prompt.chainSteps?.length || 0; 77 | } 78 | 79 | /** 80 | * Validate that chain steps are properly formed 81 | */ 82 | export function validateChainSteps(steps: ChainStep[]): boolean { 83 | if (!steps || steps.length === 0) { 84 | return false; 85 | } 86 | 87 | return steps.every(step => 88 | step.promptId && 89 | step.stepName && 90 | typeof step.promptId === 'string' && 91 | typeof step.stepName === 'string' 92 | ); 93 | } 94 | 95 | /** 96 | * Check if a prompt has valid chain steps 97 | * Combines presence check with validation 98 | */ 99 | export function hasValidChainSteps(prompt: ConvertedPrompt): boolean { 100 | const steps = prompt.chainSteps; 101 | return steps ? validateChainSteps(steps) : false; 102 | } 103 | 104 | /** 105 | * Get chain information summary for a prompt 106 | */ 107 | export function getChainInfo(prompt: ConvertedPrompt): { 108 | isChain: boolean; 109 | stepCount: number; 110 | isValid: boolean; 111 | } { 112 | const steps = prompt.chainSteps; 113 | return { 114 | isChain: isChainPrompt(prompt), 115 | stepCount: getChainStepCount(prompt), 116 | isValid: steps ? validateChainSteps(steps) : false 117 | }; 118 | } 119 | 120 | // ===== REMOVED: Modular Chain Detection and Management ===== 121 | // ChainType enum and detectChainType() function removed 122 | // All chain detection now uses isChainPrompt() and chainSteps property 123 | 124 | 125 | /** 126 | * Check if a prompt is a chain with valid steps (replaces legacy isMonolithicChain) 127 | */ 128 | export function isValidChain(prompt: ConvertedPrompt): boolean { 129 | return isChainPrompt(prompt) && hasValidChainSteps(prompt); 130 | } 131 | 132 | // Modular chain system fully removed 133 | // All chain management now uses markdown-embedded chainSteps property 134 | ``` -------------------------------------------------------------------------------- /server/src/mcp-tools/prompt-engine/core/types.ts: -------------------------------------------------------------------------------- ```typescript 1 | /** 2 | * Prompt Engine Core Types 3 | * 4 | * Contains all interfaces and types used by the prompt engine system, 5 | * including chain execution, formatting, and classification types. 6 | */ 7 | 8 | import { ConvertedPrompt, ToolResponse } from "../../../types/index.js"; 9 | import type { TemporaryGateDefinition } from "../../../execution/types.js"; 10 | 11 | /** 12 | * Chain step execution context 13 | */ 14 | export interface ChainExecutionContext { 15 | promptId: string; 16 | promptArgs: Record<string, any>; 17 | convertedPrompt: ConvertedPrompt; 18 | isChainManagement?: boolean; 19 | chainAction?: string; 20 | chainParameters?: Record<string, any>; 21 | /** Chain-level temporary gate IDs that child steps inherit */ 22 | chainGateIds?: string[]; 23 | /** Chain execution ID for scope tracking */ 24 | chainExecutionId?: string; 25 | /** Whether this chain execution should inherit gates from parent */ 26 | inheritParentGates?: boolean; 27 | } 28 | 29 | /** 30 | * Chain step arguments building context 31 | */ 32 | export interface StepArgumentsContext { 33 | stepData: any; 34 | originalArgs: Record<string, any>; 35 | contextData: Record<string, any>; 36 | currentStep: number; 37 | } 38 | 39 | /** 40 | * Chain management command structure 41 | */ 42 | export interface ChainManagementCommand { 43 | action: string; 44 | target: string; 45 | parameters: Record<string, any>; 46 | } 47 | 48 | /** 49 | * Chain gate information 50 | */ 51 | export interface ChainGateInfo { 52 | status: string; 53 | gates: Array<{ 54 | name: string; 55 | location: string; 56 | criteria: string; 57 | }>; 58 | } 59 | 60 | /** 61 | * Chain execution options 62 | */ 63 | export interface ChainExecutionOptions { 64 | enableGates: boolean; 65 | force_restart?: boolean; 66 | session_id?: string; 67 | step_confirmation?: boolean; 68 | llm_driven_execution?: boolean; 69 | chain_uri?: string; 70 | timeout?: number; 71 | /** Execution-time temporary gates (not persisted to prompt configuration) */ 72 | temporary_gates?: TemporaryGateDefinition[]; 73 | /** Scope for execution-time temporary gates (default: execution) */ 74 | gate_scope?: 'execution' | 'session' | 'chain' | 'step'; 75 | /** Whether to inherit gates from parent chain scope (default: true) */ 76 | inherit_chain_gates?: boolean; 77 | /** Built-in quality gates to apply (by name) - use system_control to discover */ 78 | quality_gates?: string[]; 79 | /** Custom quality checks (simplified: name + description only) */ 80 | custom_checks?: Array<{ name: string; description: string }>; 81 | /** Gate validation mode: enforce, advise, or report */ 82 | gate_mode?: 'enforce' | 'advise' | 'report'; 83 | } 84 | 85 | /** 86 | * Framework execution context for prompt processing 87 | */ 88 | export interface FormatterExecutionContext { 89 | executionId: string; 90 | executionType: "prompt" | "template" | "chain"; 91 | startTime: number; 92 | endTime: number; 93 | frameworkUsed?: string; 94 | frameworkEnabled: boolean; 95 | success: boolean; 96 | stepsExecuted?: number; 97 | sessionId?: string; 98 | } 99 | 100 | /** 101 | * Simple response formatter interface 102 | */ 103 | export interface SimpleResponseFormatter { 104 | formatResponse(content: any): any; 105 | formatPromptEngineResponse(response: any, ...args: any[]): any; 106 | formatErrorResponse(error: any, ...args: any[]): any; 107 | setAnalyticsService(service: any): void; 108 | } 109 | 110 | /** 111 | * Prompt classification interface for execution strategy 112 | */ 113 | export interface PromptClassification { 114 | executionType: "prompt" | "template" | "chain"; 115 | requiresExecution: boolean; 116 | confidence: number; 117 | reasoning: string[]; 118 | suggestedGates: string[]; 119 | framework?: string; 120 | } 121 | 122 | /** 123 | * Chain execution strategy result 124 | */ 125 | export interface ChainExecutionStrategy { 126 | mode: "prompt" | "template" | "chain"; 127 | gateValidation: boolean; 128 | } 129 | 130 | /** 131 | * Chain validation result 132 | */ 133 | export interface ChainValidationResult { 134 | isValid: boolean; 135 | issues: string[]; 136 | chainId: string; 137 | stepCount: number; 138 | } 139 | 140 | /** 141 | * Chain step data structure 142 | */ 143 | export interface ChainStepData { 144 | promptId: string; 145 | stepName: string; 146 | inputMapping?: Record<string, string>; 147 | outputMapping?: Record<string, string>; 148 | config?: { 149 | gates?: string[]; 150 | }; 151 | gates?: string[]; 152 | } 153 | 154 | /** 155 | * Chain state information 156 | */ 157 | export interface ChainState { 158 | currentStep: number; 159 | totalSteps: number; 160 | lastUpdated: number; 161 | } 162 | ``` -------------------------------------------------------------------------------- /server/src/metrics/types.ts: -------------------------------------------------------------------------------- ```typescript 1 | /** 2 | * Analytics Service Types 3 | * 4 | * Comprehensive type definitions for the analytics service that handles 5 | * execution monitoring, performance tracking, and system metrics collection 6 | * across all MCP tools without coupling to execution logic. 7 | */ 8 | 9 | /** 10 | * Core execution data collected from tools 11 | */ 12 | export interface ExecutionData { 13 | executionId: string; 14 | executionType: "prompt" | "template" | "chain"; 15 | startTime: number; 16 | endTime: number; 17 | executionTime: number; 18 | success: boolean; 19 | frameworkUsed?: string; 20 | frameworkEnabled: boolean; 21 | stepsExecuted?: number; 22 | sessionId?: string; 23 | toolName: string; // prompt_engine, prompt_manager, system_control 24 | error?: string; 25 | memoryUsage?: { 26 | heapUsed: number; 27 | heapTotal: number; 28 | external: number; 29 | }; 30 | } 31 | 32 | /** 33 | * Gate validation data for analytics tracking 34 | */ 35 | export interface GateValidationData { 36 | executionId: string; 37 | gateValidationEnabled: boolean; 38 | totalGates: number; 39 | passedGates: number; 40 | failedGates: number; 41 | validationTime: number; 42 | retryCount?: number; 43 | gateResults: Array<{ 44 | gateId: string; 45 | gateName: string; 46 | passed: boolean; 47 | score?: number; 48 | evaluationTime?: number; 49 | }>; 50 | } 51 | 52 | /** 53 | * Framework switching data for methodology analytics 54 | */ 55 | export interface FrameworkSwitchData { 56 | switchId: string; 57 | fromFramework: string; 58 | toFramework: string; 59 | switchTime: number; 60 | reason?: string; 61 | switchSuccess: boolean; 62 | switchDuration: number; 63 | } 64 | 65 | /** 66 | * Aggregated execution statistics 67 | */ 68 | export interface ExecutionStats { 69 | totalExecutions: number; 70 | successfulExecutions: number; 71 | failedExecutions: number; 72 | averageExecutionTime: number; 73 | executionsByMode: { 74 | prompt: number; 75 | template: number; 76 | chain: number; 77 | }; 78 | executionsByTool: { 79 | prompt_engine: number; 80 | prompt_manager: number; 81 | system_control: number; 82 | }; 83 | lastUpdated: number; 84 | } 85 | 86 | /** 87 | * System performance metrics 88 | */ 89 | export interface SystemMetrics { 90 | uptime: number; 91 | memoryUsage: { 92 | heapUsed: number; 93 | heapTotal: number; 94 | external: number; 95 | rss: number; 96 | }; 97 | averageResponseTime: number; 98 | requestsPerMinute: number; 99 | errorRate: number; 100 | performanceTrends: PerformanceTrend[]; 101 | } 102 | 103 | /** 104 | * Performance trend data point 105 | */ 106 | export interface PerformanceTrend { 107 | timestamp: number; 108 | metric: "execution_time" | "memory_usage" | "success_rate" | "response_time"; 109 | value: number; 110 | context?: string; 111 | } 112 | 113 | /** 114 | * Framework usage analytics 115 | */ 116 | export interface FrameworkUsage { 117 | currentFramework: string; 118 | frameworkSwitches: number; 119 | frameworkUsageTime: Record<string, number>; // framework -> total time used 120 | frameworkSwitchHistory: Array<{ 121 | timestamp: number; 122 | fromFramework: string; 123 | toFramework: string; 124 | reason?: string; 125 | }>; 126 | frameworkPerformance: Record<string, { 127 | averageExecutionTime: number; 128 | successRate: number; 129 | usageCount: number; 130 | }>; 131 | } 132 | 133 | /** 134 | * Analytics event types for event-driven architecture 135 | */ 136 | export type AnalyticsEvent = 137 | | { type: 'execution:start'; data: Partial<ExecutionData> } 138 | | { type: 'execution:complete'; data: ExecutionData } 139 | | { type: 'execution:error'; data: ExecutionData } 140 | | { type: 'gate:validation'; data: GateValidationData } 141 | | { type: 'framework:switch'; data: FrameworkSwitchData } 142 | | { type: 'system:memory'; data: { timestamp: number; usage: SystemMetrics['memoryUsage'] } } 143 | | { type: 'system:performance'; data: PerformanceTrend }; 144 | 145 | /** 146 | * Analytics query options for data retrieval 147 | */ 148 | export interface AnalyticsQueryOptions { 149 | timeRange?: { 150 | start: number; 151 | end: number; 152 | }; 153 | toolFilter?: string[]; 154 | frameworkFilter?: string[]; 155 | includePerformanceTrends?: boolean; 156 | includeTrendHistory?: boolean; 157 | maxResults?: number; 158 | } 159 | 160 | /** 161 | * Comprehensive analytics summary 162 | */ 163 | export interface AnalyticsSummary { 164 | executionStats: ExecutionStats; 165 | systemMetrics: SystemMetrics; 166 | frameworkUsage: FrameworkUsage; 167 | gateValidationStats: { 168 | totalValidations: number; 169 | validationSuccessRate: number; 170 | averageValidationTime: number; 171 | gateAdoptionRate: number; 172 | }; 173 | recommendations: string[]; 174 | } ``` -------------------------------------------------------------------------------- /server/tests/helpers/test-helpers.js: -------------------------------------------------------------------------------- ```javascript 1 | /** 2 | * Test Helpers (JavaScript version) 3 | * Common utilities and fixtures for tests 4 | */ 5 | 6 | import path from 'path'; 7 | import { fileURLToPath } from 'url'; 8 | 9 | // Get project root for consistent paths 10 | const __filename = fileURLToPath(import.meta.url); 11 | const __dirname = path.dirname(__filename); 12 | export const PROJECT_ROOT = path.resolve(__dirname, '../..'); 13 | export const DIST_PATH = path.join(PROJECT_ROOT, 'dist'); 14 | 15 | /** 16 | * Mock Logger Implementation 17 | */ 18 | export class MockLogger { 19 | constructor() { 20 | this.logs = []; 21 | } 22 | 23 | info(message, ...args) { 24 | this.logs.push({ level: 'info', message, args }); 25 | } 26 | 27 | warn(message, ...args) { 28 | this.logs.push({ level: 'warn', message, args }); 29 | } 30 | 31 | error(message, ...args) { 32 | this.logs.push({ level: 'error', message, args }); 33 | } 34 | 35 | debug(message, ...args) { 36 | this.logs.push({ level: 'debug', message, args }); 37 | } 38 | 39 | clear() { 40 | this.logs = []; 41 | } 42 | 43 | getLogsByLevel(level) { 44 | return this.logs.filter(log => log.level === level); 45 | } 46 | } 47 | 48 | /** 49 | * Mock MCP Server for testing 50 | * Enhanced with interface contract compliance 51 | */ 52 | export class MockMcpServer { 53 | constructor() { 54 | this.registeredTools = []; 55 | this.toolHandlers = new Map(); 56 | } 57 | 58 | tool(name, description, schema) { 59 | this.registeredTools.push({ name, description, schema }); 60 | 61 | // Return mock tool handler 62 | return { 63 | name, 64 | handler: async (args) => { 65 | const handler = this.toolHandlers.get(name); 66 | if (handler) { 67 | return handler(args); 68 | } 69 | return { 70 | content: [{ type: 'text', text: `Mock response for ${name}` }] 71 | }; 72 | } 73 | }; 74 | } 75 | 76 | /** 77 | * MCP SDK compatible registerTool method 78 | * Fixes the interface mismatch that caused CI failures 79 | */ 80 | registerTool(name, config, handler) { 81 | // Validate MCP SDK registerTool parameters 82 | if (typeof name !== 'string' || !name) { 83 | throw new Error(`Invalid tool name: ${name}`); 84 | } 85 | if (!config || typeof config !== 'object') { 86 | throw new Error(`Invalid tool config for ${name}`); 87 | } 88 | if (typeof handler !== 'function') { 89 | throw new Error(`Invalid tool handler for ${name}`); 90 | } 91 | 92 | // Extract description and schema from MCP SDK config format 93 | const description = config.description || config.title || name; 94 | const schema = config.inputSchema || {}; 95 | 96 | // Store the handler for this tool 97 | this.addToolHandler(name, handler); 98 | 99 | // Delegate to existing tool method for registration 100 | return this.tool(name, description, schema); 101 | } 102 | 103 | addToolHandler(name, handler) { 104 | this.toolHandlers.set(name, handler); 105 | } 106 | 107 | getRegisteredToolNames() { 108 | return this.registeredTools.map(tool => tool.name); 109 | } 110 | 111 | clear() { 112 | this.registeredTools = []; 113 | this.toolHandlers.clear(); 114 | } 115 | 116 | /** 117 | * Interface compliance validation 118 | */ 119 | validateInterfaceCompliance() { 120 | const requiredMethods = ['tool', 'registerTool']; 121 | const missingMethods = requiredMethods.filter(method => 122 | typeof this[method] !== 'function' 123 | ); 124 | 125 | return { 126 | isCompliant: missingMethods.length === 0, 127 | missingMethods 128 | }; 129 | } 130 | } 131 | 132 | /** 133 | * Test Data Fixtures 134 | */ 135 | export const testPrompts = { 136 | simple: { 137 | id: 'test-simple', 138 | name: 'Simple Test Prompt', 139 | userMessageTemplate: 'This is a simple test prompt', 140 | description: 'A basic prompt for testing', 141 | category: 'test', 142 | arguments: [] 143 | }, 144 | withArgs: { 145 | id: 'test-with-args', 146 | name: 'Test Prompt with Arguments', 147 | userMessageTemplate: 'Hello {{name}}, you are {{age}} years old', 148 | description: 'A prompt with template arguments', 149 | category: 'test', 150 | arguments: [ 151 | { name: 'name', type: 'string', description: 'User name' }, 152 | { name: 'age', type: 'number', description: 'User age' } 153 | ] 154 | } 155 | }; 156 | 157 | /** 158 | * Performance Test Utilities 159 | */ 160 | export class PerformanceTimer { 161 | constructor() { 162 | this.startTime = 0; 163 | this.endTime = 0; 164 | } 165 | 166 | start() { 167 | this.startTime = Date.now(); 168 | } 169 | 170 | stop() { 171 | this.endTime = Date.now(); 172 | return this.getDuration(); 173 | } 174 | 175 | getDuration() { 176 | return this.endTime - this.startTime; 177 | } 178 | } ``` -------------------------------------------------------------------------------- /docs/installation-guide.md: -------------------------------------------------------------------------------- ```markdown 1 | # Installation and Setup Guide 2 | 3 | This guide will walk you through the process of installing and setting up the Claude Custom Prompts server. 4 | 5 | ## Prerequisites 6 | 7 | Before you begin, ensure you have the following installed: 8 | 9 | - [Node.js](https://nodejs.org/) (v14 or later) 10 | - [npm](https://www.npmjs.com/) (v6 or later) 11 | - [Git](https://git-scm.com/) (optional, for cloning the repository) 12 | 13 | ## System Requirements 14 | 15 | - **Operating System**: Windows, macOS, or Linux 16 | - **Memory**: At least 2GB RAM 17 | - **Disk Space**: At least 500MB free space 18 | 19 | ## Installation 20 | 21 | ### Option 1: Clone the Repository 22 | 23 | If you have Git installed, you can clone the repository: 24 | 25 | ```bash 26 | git clone https://github.com/minipuft/claude-prompts.git 27 | cd claude-prompts 28 | ``` 29 | 30 | ### Option 2: Download the Source Code 31 | 32 | Alternatively, you can download the source code as a ZIP file and extract it. 33 | 34 | ### Install Dependencies 35 | 36 | Once you have the source code, install the dependencies for both the server: 37 | 38 | ```bash 39 | # Install server dependencies 40 | cd server 41 | npm install 42 | ``` 43 | 44 | ## Configuration 45 | 46 | ### Server Configuration 47 | 48 | The server configuration is stored in `server/config.json`. You can modify this file to change the server settings: 49 | 50 | ```json 51 | { 52 | "server": { 53 | "name": "Claude Custom Prompts", 54 | "version": "1.0.0", 55 | "port": 9090 56 | }, 57 | "prompts": { 58 | "file": "promptsConfig.json" 59 | }, 60 | "transports": { 61 | "default": "stdio" 62 | }, 63 | "logging": { 64 | "directory": "./logs", 65 | "level": "info" 66 | } 67 | } 68 | ``` 69 | 70 | Key configuration options: 71 | 72 | - **server.port**: The port on which the server will run (default: 9090) 73 | - **prompts.file**: The main prompts configuration file (default: promptsConfig.json) 74 | - **transports.default**: The default transport to use (options: stdio, sse) 75 | - **logging.directory**: The directory where logs will be stored (default: ./logs) 76 | - **logging.level**: The logging level (options: debug, info, warn, error) 77 | 78 | ### Prompts Configuration 79 | 80 | The prompts configuration is distributed across multiple files: 81 | 82 | 1. **promptsConfig.json**: The main configuration file that defines categories and imports category-specific prompts.json files 83 | 2. **Category-specific prompts.json files**: Each category has its own prompts.json file in its directory 84 | 85 | #### Main Configuration (promptsConfig.json) 86 | 87 | ```json 88 | { 89 | "categories": [ 90 | { 91 | "id": "general", 92 | "name": "General", 93 | "description": "General-purpose prompts for everyday tasks" 94 | }, 95 | { 96 | "id": "code", 97 | "name": "Code", 98 | "description": "Prompts related to programming and software development" 99 | } 100 | ], 101 | "imports": ["prompts/general/prompts.json", "prompts/code/prompts.json"] 102 | } 103 | ``` 104 | 105 | ## Creating Your First Prompt 106 | 107 | ### Prompt Execution Fails 108 | 109 | ## Updating the Application 110 | 111 | To update the application to a newer version: 112 | 113 | 1. Pull the latest changes or download the new source code. 114 | 2. Install any new dependencies: 115 | ```bash 116 | cd server 117 | npm install 118 | ``` 119 | 3. Rebuild the application: 120 | ```bash 121 | cd server 122 | npm run build 123 | ``` 124 | 4. Restart the server. 125 | 126 | ## Backup and Restore 127 | 128 | ### Backing Up Prompts 129 | 130 | The prompts are stored in the `/prompts' folder in the server directory. To back up your prompts, simply copy this folder to a safe location. 131 | 132 | ### Restoring Prompts 133 | 134 | To restore prompts from a backup, drop in your copy of the '/prompts' directory and restart the server. 135 | 136 | ## Advanced Configuration 137 | 138 | ### Custom Logging 139 | 140 | You can customize the logging behavior by modifying the logging section in `config.json`: 141 | 142 | ```json 143 | "logging": { 144 | "directory": "./custom-logs", 145 | "level": "debug", 146 | "maxFiles": 10, 147 | "maxSize": "10m" 148 | } 149 | ``` 150 | 151 | ## Security Considerations 152 | 153 | - The server does not implement authentication by default. Consider running it in a secure environment or implementing your own authentication layer. 154 | - Regularly back up your prompts to prevent data loss. 155 | - Keep your Node.js and npm packages updated to avoid security vulnerabilities. 156 | 157 | ## Getting Help 158 | 159 | If you encounter issues or have questions: 160 | 161 | 1. Check the documentation in the `docs` directory. 162 | 2. Look for error messages in the server logs. 163 | 3. Contact the maintainers or community for support. 164 | 165 | ## Next Steps 166 | 167 | Now that you have the Claude Custom Prompts server up and running, you can: 168 | 169 | 1. Create more prompts and categories. 170 | 2. Experiment with chain prompts for complex processes. 171 | 3. Integrate the API with your applications. 172 | 4. Contribute to the project by reporting issues or submitting pull requests. 173 | ``` -------------------------------------------------------------------------------- /server/tests/enhanced-validation/contract-validation/interface-contracts.js: -------------------------------------------------------------------------------- ```javascript 1 | /** 2 | * Interface Contract Validation System (JavaScript version) 3 | * 4 | * Validates that mock objects fully implement expected interfaces to prevent 5 | * runtime method missing errors like the registerTool issue. 6 | */ 7 | 8 | /** 9 | * MCP SDK Interface Contract Validator 10 | * 11 | * Prevents interface mismatches by validating mock objects against real SDK interfaces 12 | */ 13 | export class McpSdkInterfaceValidator { 14 | constructor(logger) { 15 | this.logger = logger; 16 | } 17 | 18 | /** 19 | * Validate tool registration interface compatibility 20 | * Specifically addresses the registerTool method mismatch issue 21 | */ 22 | async validateToolRegistrationInterface(mockServer) { 23 | const requiredMethods = [ 24 | 'tool', // Existing method in MockMcpServer 25 | 'registerTool' // Missing method that caused CI failure 26 | ]; 27 | 28 | const missingMethods = []; 29 | const incompatibleSignatures = []; 30 | 31 | // Check for missing methods 32 | for (const method of requiredMethods) { 33 | if (typeof mockServer[method] !== 'function') { 34 | missingMethods.push(method); 35 | } 36 | } 37 | 38 | // Validate method signatures if they exist 39 | if (typeof mockServer.tool === 'function') { 40 | const toolMethod = mockServer.tool; 41 | if (toolMethod.length < 3) { 42 | incompatibleSignatures.push({ 43 | method: 'tool', 44 | expected: 'tool(name: string, description: string, schema: any)', 45 | actual: `tool with ${toolMethod.length} parameters` 46 | }); 47 | } 48 | } 49 | 50 | if (typeof mockServer.registerTool === 'function') { 51 | const registerToolMethod = mockServer.registerTool; 52 | if (registerToolMethod.length < 3) { 53 | incompatibleSignatures.push({ 54 | method: 'registerTool', 55 | expected: 'registerTool(name: string, config: any, handler: Function)', 56 | actual: `registerTool with ${registerToolMethod.length} parameters` 57 | }); 58 | } 59 | } 60 | 61 | // Generate recommendations 62 | const recommendations = []; 63 | if (missingMethods.includes('registerTool')) { 64 | recommendations.push('Add registerTool method that delegates to existing tool method'); 65 | recommendations.push('Ensure registerTool accepts (name, config, handler) parameters'); 66 | } 67 | 68 | const isValid = missingMethods.length === 0 && incompatibleSignatures.length === 0; 69 | 70 | return { 71 | isValid, 72 | missingMethods, 73 | incompatibleSignatures, 74 | recommendations 75 | }; 76 | } 77 | 78 | /** 79 | * Comprehensive method signature validation 80 | */ 81 | validateMethodSignatures(mockObject, expectedMethods) { 82 | const missingMethods = []; 83 | const incompatibleSignatures = []; 84 | 85 | for (const [methodName, expectedParamCount] of Object.entries(expectedMethods)) { 86 | if (typeof mockObject[methodName] !== 'function') { 87 | missingMethods.push(methodName); 88 | } else { 89 | const actualParamCount = mockObject[methodName].length; 90 | if (actualParamCount !== expectedParamCount) { 91 | incompatibleSignatures.push({ 92 | method: methodName, 93 | expected: `${expectedParamCount} parameters`, 94 | actual: `${actualParamCount} parameters` 95 | }); 96 | } 97 | } 98 | } 99 | 100 | return { 101 | isValid: missingMethods.length === 0 && incompatibleSignatures.length === 0, 102 | missingMethods, 103 | incompatibleSignatures, 104 | recommendations: [] 105 | }; 106 | } 107 | 108 | /** 109 | * Generate comprehensive validation report 110 | */ 111 | async generateContractReport(mockServer, mockObjectName = 'MockMcpServer') { 112 | this.logger.debug(`[CONTRACT VALIDATOR] Generating report for ${mockObjectName}`); 113 | 114 | const validationResult = await this.validateToolRegistrationInterface(mockServer); 115 | const validatedMethods = ['tool', 'registerTool'].filter(method => 116 | typeof mockServer[method] === 'function' 117 | ); 118 | 119 | return { 120 | mockObjectName, 121 | referenceInterface: 'MCP SDK Server Interface', 122 | validationResult, 123 | timestamp: new Date(), 124 | validatedMethods 125 | }; 126 | } 127 | 128 | /** 129 | * Quick validation check for CI/testing 130 | */ 131 | async quickValidation(mockServer) { 132 | const result = await this.validateToolRegistrationInterface(mockServer); 133 | 134 | if (!result.isValid) { 135 | this.logger.error('[CONTRACT VALIDATOR] Interface validation failed:', { 136 | missingMethods: result.missingMethods, 137 | incompatibleSignatures: result.incompatibleSignatures, 138 | recommendations: result.recommendations 139 | }); 140 | } 141 | 142 | return result.isValid; 143 | } 144 | } 145 | 146 | /** 147 | * Factory function for creating validator instance 148 | */ 149 | export function createMcpSdkInterfaceValidator(logger) { 150 | return new McpSdkInterfaceValidator(logger); 151 | } ``` -------------------------------------------------------------------------------- /server/prompts/content_processing/format_enhancement.md: -------------------------------------------------------------------------------- ```markdown 1 | # Format Enhancement Workflow 2 | 3 | ## Description 4 | Transform existing basic markdown notes to advanced Obsidian formatting standards with professional presentation and interactive elements 5 | 6 | ## System Message 7 | You are a formatting transformation specialist who converts basic markdown content into publication-ready notes using advanced Obsidian features. You maintain all original content while dramatically improving presentation, organization, and usability. 8 | 9 | ## User Message Template 10 | **FORMAT ENHANCEMENT WORKFLOW** 11 | 12 | Transform this existing content into advanced Obsidian formatting: 13 | 14 | {{existing_content}} 15 | 16 | **ENHANCEMENT PARAMETERS:** 17 | - Domain: {{domain}} (auto-detect from content if not specified) 18 | - Enhancement Level: {{enhancement_level | default('comprehensive')}} 19 | 20 | **TRANSFORMATION REQUIREMENTS:** 21 | 22 | ## Content Preservation Priority 23 | - **Maintain ALL original information** - no content loss allowed 24 | - **Preserve existing structure** while enhancing presentation 25 | - **Enhance, don't replace** - build upon what exists 26 | - **Strategic enhancement** without overwhelming the content 27 | 28 | ## Mandatory Formatting Upgrades 29 | 30 | ### **1. Frontmatter Enhancement** 31 | Add/update with: 32 | ```yaml 33 | --- 34 | tags: [relevant_domain_tags, specific_concepts] 35 | aliases: [Alternative Names] 36 | created: YYYY-MM-DD 37 | status: evergreen 38 | difficulty: ⭐⭐⭐⭐ (assess complexity) 39 | duration: X hours (estimate time investment) 40 | equipment_cost: $X-$Y (if applicable) 41 | --- 42 | ``` 43 | 44 | ### **2. Visual Hierarchy Transformation** 45 | - **Title Enhancement**: Add appropriate emoji and professional formatting 46 | - **Header Progression**: Ensure clear ##, ###, #### hierarchy 47 | - **Section Separators**: Add `---` between major sections 48 | - **Emoji Integration**: Consistent system for content categorization 49 | 50 | ### **3. Interactive Element Integration** 51 | Apply minimum 3 types: 52 | - **Callout Conversion**: Transform key paragraphs into `[!tip]`, `[!warning]`, `[!success]`, `[!quote]` callouts 53 | - **Checklist Creation**: Convert action items to `- [ ]` interactive checklists 54 | - **Collapsible Sections**: Use `[!example]-` for detailed technical content 55 | - **Multi-Column Layouts**: Apply to complex information sections 56 | 57 | ### **4. Data Organization Enhancement** 58 | - **Table Creation**: Convert lists to enhanced comparison matrices 59 | - **Code Block Enhancement**: Structure technical information appropriately 60 | - **Highlighting Strategy**: Apply `==key concepts==` highlighting 61 | - **Extended Markdown**: Use `++important terms++`, `^references^`, `~technical notes~` 62 | 63 | ### **5. Professional Polish Application** 64 | - **Quote Attribution**: Proper formatting for all quotes and sources 65 | - **Cross-Reference Integration**: Strategic linking opportunities (3-8 relevant connections) 66 | - **Footnote System**: Add `[^1]` citations for sources 67 | - **Quick Reference Creation**: Summary sections for essential information 68 | 69 | ## Domain-Specific Enhancement Strategy 70 | 71 | ### **Auto-Detection Guidelines** 72 | Analyze content for: 73 | - **Creative Arts**: Techniques, equipment, workflow, artistic methods 74 | - **Technical Fields**: Code, algorithms, systems, specifications 75 | - **Personal Development**: Goals, skills, processes, improvement 76 | - **Educational Content**: Learning, instruction, knowledge transfer 77 | 78 | ### **Enhancement Application** 79 | Apply appropriate domain formatting: 80 | - **Creative**: Master quotes, technique breakdowns, equipment matrices 81 | - **Technical**: Code blocks, system specifications, performance metrics 82 | - **Personal**: Goal tracking, progress indicators, resource optimization 83 | - **Educational**: Learning paths, skill progression, practice workflows 84 | 85 | ## Quality Assurance Standards 86 | 87 | ### **Enhancement Verification Checklist** 88 | - [ ] All original content preserved and enhanced 89 | - [ ] Visual hierarchy dramatically improved 90 | - [ ] Interactive elements appropriately integrated 91 | - [ ] Data organization significantly enhanced 92 | - [ ] Professional presentation achieved 93 | - [ ] Strategic cross-references added 94 | - [ ] Quick reference sections created 95 | - [ ] Publication-ready quality achieved 96 | 97 | ### **Professional Standards** 98 | - **Visual Appeal**: ⭐⭐⭐⭐⭐ transformation quality 99 | - **Information Architecture**: Logical, scannable organization 100 | - **Plugin Utilization**: Systematic use of advanced features 101 | - **Readability**: Enhanced without overwhelming content 102 | - **Professional Presentation**: Publication-ready documentation 103 | 104 | **EXECUTE TRANSFORMATION:** 105 | Apply this enhancement workflow to transform the existing content into a professionally formatted, publication-ready note that demonstrates advanced Obsidian formatting capabilities while preserving all original information and improving usability dramatically. 106 | ``` -------------------------------------------------------------------------------- /server/package.json: -------------------------------------------------------------------------------- ```json 1 | { 2 | "name": "claude-prompts-server", 3 | "version": "1.3.0", 4 | "description": "Claude Custom Prompts MCP Server", 5 | "author": "minipuft", 6 | "license": "MIT", 7 | "type": "module", 8 | "main": "dist/index.js", 9 | "types": "dist/index.d.ts", 10 | "files": [ 11 | "dist", 12 | "README.md", 13 | "LICENSE" 14 | ], 15 | "scripts": { 16 | "build": "tsc", 17 | "typecheck": "tsc --noEmit", 18 | "start": "node dist/index.js", 19 | "dev": "tsc -w & node --watch dist/index.js", 20 | "start:sse": "node dist/index.js --transport=sse", 21 | "start:stdio": "node dist/index.js --transport=stdio", 22 | "start:quiet": "node dist/index.js --quiet", 23 | "start:verbose": "node dist/index.js --verbose", 24 | "start:debug": "node dist/index.js --debug-startup", 25 | "start:production": "node dist/index.js --quiet --transport=stdio", 26 | "start:development": "node dist/index.js --verbose --transport=sse", 27 | "start:test": "node dist/index.js --startup-test", 28 | "help": "node dist/index.js --help", 29 | "test": "npm run test:integration", 30 | "test:unit": "npm run test:unit-scripts", 31 | "test:unit-scripts": "node tests/scripts/unit-conversation-manager.js && node tests/scripts/unit-semantic-analyzer.js && node tests/scripts/unit-unified-parsing.js", 32 | "test:integration": "npm run test:integration-scripts", 33 | "test:integration-scripts": "node tests/scripts/integration-mcp-tools.js && node tests/scripts/integration-server-startup.js && node tests/scripts/integration-unified-parsing.js && node tests/scripts/integration-routing-system.js", 34 | "test:e2e": "NODE_OPTIONS=\"--experimental-vm-modules\" jest tests/e2e", 35 | "test:performance": "NODE_OPTIONS=\"--experimental-vm-modules\" jest tests/performance", 36 | "test:watch": "NODE_OPTIONS=\"--experimental-vm-modules\" jest --watch", 37 | "test:coverage": "NODE_OPTIONS=\"--experimental-vm-modules\" jest --coverage", 38 | "test:jest": "NODE_OPTIONS=\"--experimental-vm-modules\" jest", 39 | "test:ci": "npm run test:unit-scripts && npm run test:integration-scripts && npm run test:performance", 40 | "test:legacy": "node ../test_server.js", 41 | "test:runtime-integration": "node tests/scripts/runtime-integration.js", 42 | "test:methodology-guides": "node tests/scripts/methodology-guides.js", 43 | "test:consolidated-tools": "node tests/scripts/consolidated-tools.js", 44 | "test:performance-memory": "node --expose-gc tests/scripts/performance-memory.js", 45 | "test:functional-mcp": "node tests/scripts/functional-mcp-validation.js", 46 | "test:establish-baselines": "node --expose-gc tests/scripts/establish-performance-baselines.js", 47 | "test:all-enhanced": "npm run test:runtime-integration && npm run test:methodology-guides && npm run test:consolidated-tools && npm run test:functional-mcp", 48 | "test:ci-startup": "node tests/ci-startup-validation.js", 49 | "test:ci-startup-verbose": "VERBOSE=true node tests/ci-startup-validation.js", 50 | "test:enhanced-validation": "node tests/enhanced-validation/validation-orchestrator.js", 51 | "test:contracts": "node tests/enhanced-validation/contract-validation/contract-test-suite.js", 52 | "test:lifecycle": "node tests/enhanced-validation/lifecycle-validation/lifecycle-test-suite.js", 53 | "test:environment": "node tests/enhanced-validation/environment-validation/environment-test-suite.js", 54 | "validate:dependencies": "node scripts/validate-dependencies.js", 55 | "validate:circular": "npx madge --circular --extensions ts,js src/", 56 | "validate:all": "npm run validate:dependencies && npm run validate:circular", 57 | "validate:enhanced": "npm run test:enhanced-validation", 58 | "prepublishOnly": "npm run build" 59 | }, 60 | "repository": { 61 | "type": "git", 62 | "url": "git+https://github.com/minipuft/claude-prompts.git" 63 | }, 64 | "bugs": { 65 | "url": "https://github.com/minipuft/claude-prompts/issues" 66 | }, 67 | "homepage": "https://github.com/minipuft/claude-prompts#readme", 68 | "keywords": [ 69 | "claude", 70 | "ai", 71 | "mcp", 72 | "model-context-protocol", 73 | "prompts", 74 | "language-model", 75 | "server" 76 | ], 77 | "engines": { 78 | "node": ">=16" 79 | }, 80 | "publishConfig": { 81 | "access": "public" 82 | }, 83 | "dependencies": { 84 | "@modelcontextprotocol/sdk": "^1.18.1", 85 | "@types/handlebars": "^4.1.0", 86 | "@types/nunjucks": "^3.2.6", 87 | "cors": "^2.8.5", 88 | "express": "^4.18.2", 89 | "handlebars": "^4.7.8", 90 | "nunjucks": "^3.2.4", 91 | "zod": "^3.22.4" 92 | }, 93 | "devDependencies": { 94 | "@types/cors": "^2.8.17", 95 | "@types/express": "^4.17.21", 96 | "@types/jest": "^29.5.12", 97 | "@types/node": "^20.11.19", 98 | "@types/ws": "^8.5.14", 99 | "jest": "^29.7.0", 100 | "madge": "^8.0.0", 101 | "ts-jest": "^29.1.2", 102 | "typescript": "^5.3.3", 103 | "ws": "^8.18.1" 104 | } 105 | } 106 | ``` -------------------------------------------------------------------------------- /server/prompts/development/generate_comprehensive_claude_md.md: -------------------------------------------------------------------------------- ```markdown 1 | # Comprehensive CLAUDE.md Generator 2 | 3 | ## Description 4 | Generates comprehensive CLAUDE.md files with all 6 development criteria, Enhanced CAGEERF integration, and project-specific configurations 5 | 6 | ## System Message 7 | You are an expert assistant providing structured, systematic analysis. Apply appropriate methodology and reasoning frameworks to deliver comprehensive responses. 8 | 9 | ## User Message Template 10 | # Comprehensive CLAUDE.md Generation 11 | 12 | ## Objective 13 | Generate a comprehensive CLAUDE.md file for `{{ project_name }}` ({{ project_type }}) that includes all 6 development criteria and Enhanced CAGEERF integration. 14 | 15 | ## Project Context 16 | - **Path**: `{{ project_path }}` 17 | - **Name**: `{{ project_name }}` 18 | - **Type**: `{{ project_type }}` 19 | - **Architecture Level**: {{ architecture_level }}/10 20 | - **Detected Commands**: {{ project_commands }} 21 | 22 | ## Required Development Criteria 23 | 24 | ### 1. Comprehensive Development Standards 25 | Generate performance requirements, code quality standards, and naming conventions specific to {{ project_type }} projects. 26 | 27 | **Performance Requirements:** 28 | - Bundle size constraints appropriate for {{ project_type }} 29 | - Memory usage budgets 30 | - Build performance targets 31 | - Framework-specific metrics 32 | 33 | **Code Quality Standards:** 34 | - Complexity limits (cyclomatic, cognitive) 35 | - Coverage requirements 36 | - Architecture standards 37 | - Maintainability metrics 38 | 39 | **Naming Conventions:** 40 | - Language-specific conventions for {{ project_type }} 41 | - File and directory patterns 42 | - API design standards 43 | 44 | ### 2. Technology Constraints & Rules 45 | Define allowed/prohibited technologies and CSS-first philosophy. 46 | 47 | **For {{ project_type }} projects:** 48 | - Approved dependencies and versions 49 | - Security-focused restrictions 50 | - Performance-oriented constraints 51 | - Maintenance considerations 52 | 53 | **CSS-First Philosophy:** 54 | - Styling hierarchy for {{ project_type }} 55 | - Framework-specific CSS patterns 56 | - Performance requirements for styles 57 | 58 | ### 3. Validation Requirements 59 | Configure Enhanced CAGEERF validation checkpoints using detected commands. 60 | 61 | **Integration Commands from Detection:** 62 | ```json 63 | {{ project_commands }} 64 | ``` 65 | 66 | **4-Phase Validation Checkpoints:** 67 | 1. **CHECKPOINT 1**: Context Validation 68 | 2. **CHECKPOINT 2**: Progressive Edit Validation 69 | 3. **CHECKPOINT 3**: Integration Validation 70 | 4. **CHECKPOINT 4**: Completion Validation 71 | 72 | ### 4. Project-Specific Development Rules 73 | Configure build cycles, environment setup, and API integration requirements. 74 | 75 | **Build & Installation Cycle:** 76 | - Environment setup for {{ project_type }} 77 | - Dependency management 78 | - Development server configuration 79 | - Testing and deployment workflows 80 | 81 | **API Integration:** 82 | - Extension patterns (if applicable) 83 | - Library export patterns (if applicable) 84 | - Security constraints 85 | 86 | ### 5. Debug & Diagnostics Framework 87 | Setup comprehensive debugging and troubleshooting systems. 88 | 89 | **Test Harness:** 90 | - Integration test setup for {{ project_type }} 91 | - Performance testing configuration 92 | - Mock data management 93 | 94 | **Debug Configuration:** 95 | - Development debugging setup 96 | - Production monitoring 97 | - Error reporting configuration 98 | 99 | ### 6. Advanced Development Guidelines 100 | Emergency protocols, development philosophy, and innovation guidelines. 101 | 102 | **Emergency Protocols:** 103 | - Severity levels and response procedures 104 | - Hotfix workflows 105 | - Incident response 106 | 107 | **Development Philosophy:** 108 | - Core principles for {{ project_type }} development 109 | - Decision frameworks 110 | - Code review standards 111 | 112 | ## Enhanced CAGEERF Integration 113 | 114 | **CRITICAL**: Include comprehensive Enhanced CAGEERF methodology integration: 115 | 116 | 1. **Context Discovery Protocol** (Phase 1A-1F) 117 | 2. **4 Validation Checkpoints** throughout development 118 | 3. **Project Command Auto-Detection** integration 119 | 4. **Context Memory System** references 120 | 121 | ## Implementation Instructions 122 | 123 | 1. **Read Template**: Use the comprehensive template from `/home/minipuft/.claude/context-engineering/templates/comprehensive-claude-md-template.md` 124 | 2. **Project Analysis**: Examine the project structure and characteristics 125 | 3. **Smart Substitution**: Replace template variables with project-specific values 126 | 4. **Command Integration**: Integrate the detected commands from {{ project_commands }} 127 | 5. **Validation Setup**: Configure the 4-phase CAGEERF checkpoint system 128 | 6. **Quality Assurance**: Ensure all 6 development criteria are comprehensively covered 129 | 130 | ## Expected Output 131 | 132 | Generate the complete CLAUDE.md file content with: 133 | - ✅ Global SuperClaude integration references 134 | - ✅ All 6 comprehensive development criteria 135 | - ✅ Enhanced CAGEERF validation checkpoints 136 | - ✅ Project-specific command integration 137 | - ✅ Context memory system integration 138 | - ✅ Session management protocols 139 | 140 | **File Location**: `{{ project_path }}/CLAUDE.md` 141 | 142 | Begin generating the comprehensive CLAUDE.md for: `{{ project_name }}` 143 | ``` -------------------------------------------------------------------------------- /server/scripts/validate-dependencies.js: -------------------------------------------------------------------------------- ```javascript 1 | #!/usr/bin/env node 2 | /** 3 | * Dependency Validation Script 4 | * 5 | * Detects duplicate systems and overlapping functionality that violate 6 | * the "Single Source of Truth" principle. 7 | */ 8 | 9 | import fs from 'fs'; 10 | import path from 'path'; 11 | import { fileURLToPath } from 'url'; 12 | 13 | const __filename = fileURLToPath(import.meta.url); 14 | const __dirname = path.dirname(__filename); 15 | 16 | // Define known system overlaps that should trigger warnings 17 | const OVERLAP_PATTERNS = [ 18 | { 19 | name: "Execution Systems", 20 | files: [ 21 | "execution/engine.ts", 22 | "execution/execution-coordinator.ts", 23 | "execution/unified-prompt-processor.ts" 24 | ], 25 | warning: "Multiple execution systems detected. Choose ONE primary system and deprecate others." 26 | }, 27 | { 28 | name: "Analysis Systems", 29 | files: [ 30 | "analysis/semantic-analyzer.ts", 31 | "analysis/configurable-semantic-analyzer.ts", 32 | "frameworks/analysis/framework-consensus-engine.ts", 33 | "frameworks/analysis/framework-enhancement-pipeline.ts" 34 | ], 35 | warning: "Multiple analysis systems detected. Consolidate into single configurable analyzer." 36 | }, 37 | { 38 | name: "Runtime/Application Systems", 39 | files: [ 40 | "runtime/application.ts", 41 | "orchestration/application-orchestrator.ts", 42 | "server/server.ts" 43 | ], 44 | warning: "Multiple application runtime systems detected. Use ONE unified runtime system." 45 | }, 46 | { 47 | name: "MCP Tools Architecture", 48 | files: [ 49 | "mcp-tools/template-generation-tools.ts", 50 | "mcp-tools/prompt-management-tools.ts", 51 | "mcp-tools/execution-tools.ts", 52 | "mcp-tools/analysis-tools.ts" 53 | ], 54 | warning: "Legacy fragmented MCP tools detected. Should be consolidated into 3 intelligent tools." 55 | } 56 | ]; 57 | 58 | // Scan for files and detect overlaps 59 | function validateSystemConsolidation() { 60 | console.log("🔍 Validating system consolidation...\n"); 61 | 62 | let hasViolations = false; 63 | 64 | for (const pattern of OVERLAP_PATTERNS) { 65 | const existingFiles = []; 66 | 67 | for (const filePath of pattern.files) { 68 | const fullPath = path.join(__dirname, '..', 'src', filePath); 69 | if (fs.existsSync(fullPath)) { 70 | existingFiles.push(filePath); 71 | } 72 | } 73 | 74 | if (existingFiles.length > 1) { 75 | hasViolations = true; 76 | console.log(`❌ ${pattern.name} VIOLATION:`); 77 | console.log(` Found ${existingFiles.length} overlapping systems:`); 78 | existingFiles.forEach(file => console.log(` - ${file}`)); 79 | console.log(` ${pattern.warning}\n`); 80 | } else if (existingFiles.length === 1) { 81 | console.log(`✅ ${pattern.name}: Single system detected (${existingFiles[0]})`); 82 | } 83 | } 84 | 85 | // Validate new consolidated architecture presence 86 | console.log("\n🔍 Validating new consolidated architecture..."); 87 | 88 | const REQUIRED_ARCHITECTURE = [ 89 | { 90 | name: "Consolidated MCP Tools", 91 | files: [ 92 | "mcp-tools/prompt-engine/core/engine.ts", 93 | "mcp-tools/prompt-manager.ts", 94 | "mcp-tools/system-control.ts" 95 | ], 96 | required: 3 97 | }, 98 | { 99 | name: "Methodology Guides", 100 | files: [ 101 | "frameworks/adapters/cageerf-methodology-guide.ts", 102 | "frameworks/adapters/react-methodology-guide.ts", 103 | "frameworks/adapters/5w1h-methodology-guide.ts", 104 | "frameworks/adapters/scamper-methodology-guide.ts" 105 | ], 106 | required: 4 107 | }, 108 | { 109 | name: "Framework System", 110 | files: [ 111 | "frameworks/framework-manager.ts", 112 | "frameworks/framework-state-manager.ts" 113 | ], 114 | required: 2 115 | }, 116 | { 117 | name: "Runtime System", 118 | files: [ 119 | "runtime/application.ts", 120 | "runtime/startup.ts" 121 | ], 122 | required: 2 123 | } 124 | ]; 125 | 126 | let architectureScore = 0; 127 | for (const archPattern of REQUIRED_ARCHITECTURE) { 128 | const existingFiles = []; 129 | 130 | for (const filePath of archPattern.files) { 131 | const fullPath = path.join(__dirname, '..', 'src', filePath); 132 | if (fs.existsSync(fullPath)) { 133 | existingFiles.push(filePath); 134 | } 135 | } 136 | 137 | if (existingFiles.length >= archPattern.required) { 138 | console.log(`✅ ${archPattern.name}: ${existingFiles.length}/${archPattern.required} components found`); 139 | architectureScore++; 140 | } else { 141 | console.log(`❌ ${archPattern.name}: ${existingFiles.length}/${archPattern.required} components found - INCOMPLETE`); 142 | existingFiles.forEach(file => console.log(` - ${file}`)); 143 | hasViolations = true; 144 | } 145 | } 146 | 147 | if (hasViolations) { 148 | console.log("🚨 SYSTEM CONSOLIDATION VIOLATIONS DETECTED!"); 149 | console.log(" See CLAUDE.md 'System Migration & Deprecation Guidelines' for resolution."); 150 | process.exit(1); 151 | } else { 152 | console.log(`\n✅ All systems properly consolidated! (${architectureScore}/${REQUIRED_ARCHITECTURE.length} architecture patterns validated)`); 153 | } 154 | } 155 | 156 | validateSystemConsolidation(); ``` -------------------------------------------------------------------------------- /server/src/prompts/types.ts: -------------------------------------------------------------------------------- ```typescript 1 | /** 2 | * Prompt System Type Definitions 3 | * 4 | * Contains all types related to prompt management, processing, and organization. 5 | * This includes prompt data structures, arguments, categories, and file handling. 6 | */ 7 | 8 | /** 9 | * Enhanced argument definition for prompts 10 | * Consolidates features from multiple previous definitions 11 | */ 12 | export interface PromptArgument { 13 | /** Name of the argument */ 14 | name: string; 15 | /** Optional description of the argument */ 16 | description?: string; 17 | /** Whether this argument is required */ 18 | required: boolean; 19 | /** Type of the argument value */ 20 | type?: 'string' | 'number' | 'boolean' | 'object' | 'array'; 21 | /** Default value if not provided */ 22 | defaultValue?: string | number | boolean | null | object | Array<any>; 23 | /** Optional CAGEERF component association for framework-aware processing */ 24 | cageerfComponent?: 'context' | 'analysis' | 'goals' | 'execution' | 'evaluation' | 'refinement' | 'framework'; 25 | /** Validation rules for the argument */ 26 | validation?: { 27 | /** Regex pattern for string validation */ 28 | pattern?: string; 29 | /** Minimum length for strings */ 30 | minLength?: number; 31 | /** Maximum length for strings */ 32 | maxLength?: number; 33 | /** Allowed values for enumeration */ 34 | allowedValues?: Array<string | number | boolean>; 35 | }; 36 | } 37 | 38 | /** 39 | * A category for organizing prompts 40 | */ 41 | export interface Category { 42 | /** Unique identifier for the category */ 43 | id: string; 44 | /** Display name for the category */ 45 | name: string; 46 | /** Description of the category */ 47 | description: string; 48 | } 49 | 50 | /** 51 | * Gate definition interface (shared with gates system) 52 | */ 53 | export interface GateDefinition { 54 | id: string; 55 | name: string; 56 | type: 'validation' | 'approval' | 'condition' | 'quality'; 57 | requirements: any[]; 58 | failureAction: 'stop' | 'retry' | 'skip' | 'rollback'; 59 | retryPolicy?: { 60 | maxRetries: number; 61 | retryDelay: number; 62 | }; 63 | } 64 | 65 | /** 66 | * Complete prompt metadata structure 67 | */ 68 | export interface PromptData { 69 | /** Unique identifier for the prompt */ 70 | id: string; 71 | /** Display name for the prompt */ 72 | name: string; 73 | /** Category this prompt belongs to */ 74 | category: string; 75 | /** Description of the prompt */ 76 | description: string; 77 | /** Path to the prompt file */ 78 | file: string; 79 | /** Arguments accepted by this prompt */ 80 | arguments: PromptArgument[]; 81 | /** Whether this prompt should use available tools */ 82 | tools?: boolean; 83 | /** Defines behavior when prompt is invoked without its defined arguments */ 84 | onEmptyInvocation?: "execute_if_possible" | "return_template"; 85 | /** Optional gates for validation */ 86 | gates?: GateDefinition[]; 87 | } 88 | 89 | /** 90 | * Structure of an individual prompt file 91 | */ 92 | export interface PromptFile { 93 | /** Title of the prompt */ 94 | title: string; 95 | /** Description of the prompt */ 96 | description: string; 97 | /** Optional system message for the prompt */ 98 | systemMessage?: string; 99 | /** Template for generating the user message */ 100 | userMessageTemplate: string; 101 | /** Whether this prompt should use available tools */ 102 | tools?: boolean; 103 | } 104 | 105 | /** 106 | * Structure of the prompts registry file 107 | */ 108 | export interface PromptsFile { 109 | /** Available categories for organizing prompts */ 110 | categories: Category[]; 111 | /** Available prompts */ 112 | prompts: PromptData[]; 113 | } 114 | 115 | /** 116 | * Configuration for the prompts subsystem with category imports 117 | */ 118 | export interface PromptsConfigFile { 119 | /** Available categories for organizing prompts */ 120 | categories: Category[]; 121 | /** Paths to prompts.json files to import from category folders */ 122 | imports: string[]; 123 | } 124 | 125 | /** 126 | * Configuration for the prompts subsystem 127 | */ 128 | export interface PromptsConfig { 129 | /** Path to the prompts definition file */ 130 | file: string; 131 | } 132 | 133 | /** 134 | * Prompt file content structure 135 | */ 136 | export interface PromptFileContent { 137 | systemMessage?: string; 138 | userMessageTemplate: string; 139 | chainSteps?: ChainStep[]; 140 | } 141 | 142 | /** 143 | * Result of loading category prompts 144 | */ 145 | export interface CategoryPromptsResult { 146 | promptsData: PromptData[]; 147 | categories: Category[]; 148 | } 149 | 150 | /** 151 | * Chain step definition (minimal for prompt context) 152 | */ 153 | export interface ChainStep { 154 | promptId: string; 155 | stepName: string; 156 | executionType?: 'prompt' | 'template'; 157 | inputMapping?: Record<string, string>; 158 | outputMapping?: Record<string, string>; 159 | } 160 | 161 | /** 162 | * Category validation result 163 | */ 164 | export interface CategoryValidationResult { 165 | isValid: boolean; 166 | issues: string[]; 167 | warnings: string[]; 168 | } 169 | 170 | /** 171 | * Category statistics 172 | */ 173 | export interface CategoryStatistics { 174 | totalCategories: number; 175 | categoriesWithPrompts: number; 176 | emptyCategoriesCount: number; 177 | averagePromptsPerCategory: number; 178 | categoryBreakdown: Array<{ 179 | category: Category; 180 | promptCount: number; 181 | }>; 182 | } 183 | 184 | /** 185 | * Category-prompt relationship data 186 | */ 187 | export interface CategoryPromptRelationship { 188 | categoryId: string; 189 | categoryName: string; 190 | promptIds: string[]; 191 | promptCount: number; 192 | hasChains: boolean; 193 | hasTemplates: boolean; 194 | } ``` -------------------------------------------------------------------------------- /server/prompts/development/component_flow_analysis.md: -------------------------------------------------------------------------------- ```markdown 1 | # Component Flow Analysis 2 | 3 | ## Description 4 | Comprehensive component review that tracks data flow, lifecycle, dependencies, and integration points 5 | 6 | ## User Message Template 7 | Analyze the following {{framework}} component and provide a comprehensive flow analysis: 8 | 9 | **Component Path**: {{component_path}} 10 | **Component Code**: 11 | ```{{language}} 12 | {{component_code}} 13 | ``` 14 | 15 | ## Analysis Framework 16 | 17 | ### 1. Component Overview 18 | - **Purpose**: What problem does this component solve? 19 | - **Type**: Presentational, Container, Higher-Order Component, Hook, etc. 20 | - **Complexity Level**: Simple, Moderate, Complex 21 | - **Primary Responsibilities**: List core functions 22 | 23 | ### 2. Data Flow Analysis 24 | 25 | #### Inputs (Props/Parameters) 26 | - List all props/parameters with types 27 | - Identify required vs optional inputs 28 | - Document default values 29 | - Track prop drilling depth (if applicable) 30 | 31 | #### State Management 32 | - Local state variables and their purpose 33 | - External state (Context, Redux, Zustand, etc.) 34 | - State update triggers and effects 35 | - State flow diagram (describe transitions) 36 | 37 | #### Outputs 38 | - Events emitted/callbacks invoked 39 | - Side effects triggered 40 | - Data transformations performed 41 | - Return values or rendered output 42 | 43 | ### 3. Lifecycle & Execution Flow 44 | 45 | #### Initialization Phase 46 | - Constructor/setup logic 47 | - Initial data fetching 48 | - Subscription establishment 49 | - Effect registration 50 | 51 | #### Update Phase 52 | - Re-render triggers 53 | - Update dependencies 54 | - Optimization strategies (memoization, etc.) 55 | - Performance considerations 56 | 57 | #### Cleanup Phase 58 | - Cleanup operations 59 | - Subscription teardown 60 | - Memory leak prevention 61 | - Resource disposal 62 | 63 | ### 4. Dependency Analysis 64 | 65 | #### Internal Dependencies 66 | - Other components used/imported 67 | - Utility functions called 68 | - Custom hooks utilized 69 | - Internal modules referenced 70 | 71 | #### External Dependencies 72 | - Third-party libraries 73 | - API endpoints called 74 | - External services integrated 75 | - Browser APIs used 76 | 77 | #### Circular Dependencies 78 | - Identify any circular dependency risks 79 | - Suggest refactoring if needed 80 | 81 | ### 5. Integration Points 82 | 83 | #### Parent Components 84 | - How is this component used by parents? 85 | - What context does it expect? 86 | - Required wrapper components 87 | 88 | #### Child Components 89 | - What components does it render? 90 | - How does it communicate with children? 91 | - Data passed down to children 92 | 93 | #### Sibling Communication 94 | - Event bus usage 95 | - Shared state access 96 | - Cross-component messaging 97 | 98 | ### 6. Event Flow & User Interactions 99 | 100 | #### User Events Handled 101 | - Click, input, scroll, etc. 102 | - Event handlers and their flow 103 | - Event propagation (bubbling/capturing) 104 | 105 | #### Custom Events 106 | - Events dispatched by this component 107 | - Event payload structure 108 | - Event consumers 109 | 110 | #### Async Operations 111 | - API calls and their triggers 112 | - Loading states management 113 | - Error handling flow 114 | - Success/failure callbacks 115 | 116 | ### 7. Rendering Flow 117 | 118 | #### Conditional Rendering 119 | - Rendering conditions and branches 120 | - Loading states UI 121 | - Error states UI 122 | - Empty states UI 123 | 124 | #### Dynamic Content 125 | - List rendering logic 126 | - Dynamic children generation 127 | - Content interpolation 128 | 129 | #### Performance Optimization 130 | - Memoization usage 131 | - Lazy loading implementation 132 | - Virtual scrolling (if applicable) 133 | - Code splitting points 134 | 135 | ### 8. Side Effects & External Interactions 136 | 137 | #### API Interactions 138 | - Endpoints called 139 | - Request/response flow 140 | - Caching strategy 141 | - Error handling 142 | 143 | #### Browser APIs 144 | - LocalStorage/SessionStorage 145 | - Geolocation, notifications, etc. 146 | - DOM manipulation 147 | - Navigation/routing 148 | 149 | #### Third-Party Services 150 | - Analytics tracking 151 | - Error monitoring 152 | - Feature flags 153 | - Authentication services 154 | 155 | ### 9. Data Transformation Pipeline 156 | 157 | Trace how data flows through the component: 158 | 1. **Input** → What raw data comes in? 159 | 2. **Processing** → How is it transformed? 160 | 3. **Storage** → Where is it stored (if at all)? 161 | 4. **Display** → How is it presented to users? 162 | 5. **Output** → What data/events go out? 163 | 164 | ### 10. Flow Diagram 165 | 166 | Provide a text-based flow diagram showing: 167 | - Component initialization 168 | - Data flow paths 169 | - User interaction flows 170 | - Async operation flows 171 | - Cleanup sequences 172 | 173 | Example format: 174 | ``` 175 | User Action (click) 176 | → Event Handler (handleSubmit) 177 | → Validation Logic 178 | → API Call (submitData) 179 | → Loading State (setIsLoading: true) 180 | → Success: Update State → Re-render 181 | → Error: Show Error Message → Re-render 182 | ``` 183 | 184 | ### 11. Issues & Recommendations 185 | 186 | #### Potential Issues 187 | - Code smells identified 188 | - Performance bottlenecks 189 | - Accessibility concerns 190 | - Security vulnerabilities 191 | - Maintenance challenges 192 | 193 | #### Optimization Opportunities 194 | - Refactoring suggestions 195 | - Performance improvements 196 | - Code organization enhancements 197 | - Pattern improvements 198 | 199 | #### Best Practices Compliance 200 | - Does it follow framework conventions? 201 | - Proper error handling? 202 | - Accessibility implemented? 203 | - Type safety enforced? 204 | 205 | ## Summary 206 | 207 | Provide a concise summary including: 208 | - Component health score (1-10) 209 | - Primary data flows identified 210 | - Key integration points 211 | - Critical dependencies 212 | - Recommended next actions 213 | ``` -------------------------------------------------------------------------------- /server/src/mcp-tools/prompt-engine/processors/template-processor.ts: -------------------------------------------------------------------------------- ```typescript 1 | /** 2 | * Template Processor - Handles template processing logic 3 | * 4 | * Extracted from ConsolidatedPromptEngine to provide focused 5 | * template processing capabilities with clear separation of concerns. 6 | */ 7 | 8 | import { processTemplate } from "../../../utils/jsonUtils.js"; 9 | import { ConvertedPrompt } from "../../../types/index.js"; 10 | import { createLogger } from "../../../logging/index.js"; 11 | 12 | const logger = createLogger({ 13 | logFile: '/tmp/template-processor.log', 14 | transport: 'stdio', 15 | enableDebug: false, 16 | configuredLevel: 'info' 17 | }); 18 | 19 | /** 20 | * TemplateProcessor handles all template-related processing 21 | * 22 | * This class provides: 23 | * - Template argument processing and validation 24 | * - Variable substitution and template rendering 25 | * - Template error handling and validation 26 | * - Integration with Nunjucks template engine 27 | */ 28 | export class TemplateProcessor { 29 | 30 | /** 31 | * Process template with provided arguments 32 | */ 33 | public processTemplate( 34 | convertedPrompt: ConvertedPrompt, 35 | promptArgs: Record<string, any> 36 | ): string { 37 | try { 38 | logger.debug('🎯 [Template] Processing template with arguments', { 39 | promptId: convertedPrompt.id, 40 | argsCount: Object.keys(promptArgs).length 41 | }); 42 | 43 | const processedContent = processTemplate(convertedPrompt.userMessageTemplate, promptArgs); 44 | 45 | logger.debug('✅ [Template] Template processed successfully', { 46 | promptId: convertedPrompt.id, 47 | contentLength: processedContent.length 48 | }); 49 | 50 | return processedContent; 51 | } catch (error) { 52 | logger.error('❌ [Template] Template processing failed', { 53 | promptId: convertedPrompt.id, 54 | error: error instanceof Error ? error.message : String(error) 55 | }); 56 | throw error; 57 | } 58 | } 59 | 60 | /** 61 | * Validate template arguments against prompt requirements 62 | */ 63 | public validateTemplateArguments( 64 | convertedPrompt: ConvertedPrompt, 65 | promptArgs: Record<string, any> 66 | ): { isValid: boolean; missingArgs: string[]; errors: string[] } { 67 | const missingArgs: string[] = []; 68 | const errors: string[] = []; 69 | 70 | try { 71 | // Check required arguments 72 | if (convertedPrompt.arguments) { 73 | for (const arg of convertedPrompt.arguments) { 74 | if (arg.required && !promptArgs.hasOwnProperty(arg.name)) { 75 | missingArgs.push(arg.name); 76 | } 77 | } 78 | } 79 | 80 | // Validate argument types if specified 81 | if (convertedPrompt.arguments) { 82 | for (const arg of convertedPrompt.arguments) { 83 | if (promptArgs.hasOwnProperty(arg.name)) { 84 | const value = promptArgs[arg.name]; 85 | if (!this.validateArgumentType(value, arg.type || 'string')) { 86 | errors.push(`Argument '${arg.name}' should be of type '${arg.type}'`); 87 | } 88 | } 89 | } 90 | } 91 | 92 | const isValid = missingArgs.length === 0 && errors.length === 0; 93 | 94 | logger.debug('🔍 [Template] Argument validation result', { 95 | promptId: convertedPrompt.id, 96 | isValid, 97 | missingArgs, 98 | errorsCount: errors.length 99 | }); 100 | 101 | return { isValid, missingArgs, errors }; 102 | } catch (error) { 103 | logger.error('❌ [Template] Argument validation failed', { 104 | promptId: convertedPrompt.id, 105 | error: error instanceof Error ? error.message : String(error) 106 | }); 107 | 108 | return { 109 | isValid: false, 110 | missingArgs, 111 | errors: [...errors, `Validation error: ${error instanceof Error ? error.message : String(error)}`] 112 | }; 113 | } 114 | } 115 | 116 | /** 117 | * Validate argument type 118 | */ 119 | private validateArgumentType(value: any, expectedType: string): boolean { 120 | switch (expectedType.toLowerCase()) { 121 | case 'string': 122 | return typeof value === 'string'; 123 | case 'number': 124 | return typeof value === 'number' && !isNaN(value); 125 | case 'boolean': 126 | return typeof value === 'boolean'; 127 | case 'array': 128 | return Array.isArray(value); 129 | case 'object': 130 | return typeof value === 'object' && value !== null && !Array.isArray(value); 131 | default: 132 | // Unknown types are considered valid 133 | return true; 134 | } 135 | } 136 | 137 | /** 138 | * Extract template variables from content 139 | */ 140 | public extractTemplateVariables(content: string | undefined): string[] { 141 | const variables: string[] = []; 142 | 143 | try { 144 | if (!content) return []; 145 | 146 | // Extract Nunjucks-style variables {{variable}} 147 | const matches = content.match(/\{\{\s*([^}]+)\s*\}\}/g); 148 | 149 | if (matches) { 150 | for (const match of matches) { 151 | const variable = match.replace(/[\{\}\s]/g, ''); 152 | if (!variables.includes(variable)) { 153 | variables.push(variable); 154 | } 155 | } 156 | } 157 | 158 | logger.debug('🔍 [Template] Extracted template variables', { 159 | variablesCount: variables.length, 160 | variables 161 | }); 162 | 163 | return variables; 164 | } catch (error) { 165 | logger.error('❌ [Template] Variable extraction failed', { 166 | error: error instanceof Error ? error.message : String(error) 167 | }); 168 | return []; 169 | } 170 | } 171 | } ``` -------------------------------------------------------------------------------- /server/src/mcp-tools/constants.ts: -------------------------------------------------------------------------------- ```typescript 1 | /** 2 | * Constants for MCP Tools 3 | * 4 | * Centralized constants to avoid duplication and improve maintainability. 5 | */ 6 | 7 | /** 8 | * Tool names 9 | */ 10 | export const TOOL_NAMES = { 11 | PROMPT_ENGINE: 'prompt_engine', 12 | PROMPT_MANAGER: 'prompt_manager', 13 | SYSTEM_CONTROL: 'system_control' 14 | } as const; 15 | 16 | /** 17 | * Action types for each tool 18 | */ 19 | export const ACTIONS = { 20 | PROMPT_MANAGER: { 21 | CREATE: 'create', 22 | CREATE_PROMPT: 'create_prompt', 23 | CREATE_TEMPLATE: 'create_template', 24 | UPDATE: 'update', 25 | DELETE: 'delete', 26 | RELOAD: 'reload', 27 | LIST: 'list', 28 | INSPECT: 'inspect' 29 | }, 30 | SYSTEM_CONTROL: { 31 | STATUS: 'status', 32 | FRAMEWORK: 'framework', 33 | ANALYTICS: 'analytics', 34 | CONFIG: 'config', 35 | MAINTENANCE: 'maintenance' 36 | } 37 | } as const; 38 | 39 | /** 40 | * Operation types for system control 41 | */ 42 | export const SYSTEM_OPERATIONS = { 43 | STATUS: { 44 | OVERVIEW: 'overview', 45 | HEALTH: 'health', 46 | DIAGNOSTICS: 'diagnostics', 47 | FRAMEWORK_STATUS: 'framework_status' 48 | }, 49 | FRAMEWORK: { 50 | SWITCH: 'switch', 51 | LIST: 'list', 52 | ENABLE: 'enable', 53 | DISABLE: 'disable' 54 | }, 55 | ANALYTICS: { 56 | VIEW: 'view', 57 | RESET: 'reset', 58 | HISTORY: 'history' 59 | }, 60 | CONFIG: { 61 | GET: 'get', 62 | SET: 'set', 63 | LIST: 'list', 64 | VALIDATE: 'validate', 65 | RESTORE: 'restore' 66 | }, 67 | MAINTENANCE: { 68 | RESTART: 'restart' 69 | } 70 | } as const; 71 | 72 | /** 73 | * Execution modes for prompt engine 74 | */ 75 | export const EXECUTION_MODES = { 76 | AUTO: 'auto', 77 | PROMPT: 'prompt', 78 | TEMPLATE: 'template', 79 | CHAIN: 'chain' 80 | } as const; 81 | 82 | /** 83 | * Output formats 84 | */ 85 | export const OUTPUT_FORMATS = { 86 | COMPACT: 'compact', 87 | DETAILED: 'detailed', 88 | JSON: 'json', 89 | MARKDOWN: 'markdown' 90 | } as const; 91 | 92 | /** 93 | * Detail levels for inspection 94 | */ 95 | export const DETAIL_LEVELS = { 96 | OVERVIEW: 'overview', 97 | STEPS: 'steps', 98 | STRUCTURE: 'structure', 99 | GATES: 'gates', 100 | FLOW: 'flow', 101 | ANALYSIS: 'analysis', 102 | RAW: 'raw', 103 | FULL: 'full' 104 | } as const; 105 | 106 | /** 107 | * Filter operators 108 | */ 109 | export const FILTER_OPERATORS = { 110 | EQUALS: '=', 111 | GREATER_THAN: '>', 112 | LESS_THAN: '<', 113 | GREATER_EQUAL: '>=', 114 | LESS_EQUAL: '<=', 115 | CONTAINS: '~', 116 | REGEX: '/', 117 | AND: 'AND', 118 | OR: 'OR', 119 | NOT: 'NOT' 120 | } as const; 121 | 122 | /** 123 | * Validation patterns 124 | */ 125 | export const VALIDATION_PATTERNS = { 126 | PROMPT_ID: /^[a-zA-Z0-9_-]+$/, 127 | SESSION_ID: /^[a-zA-Z0-9_-]+$/, 128 | ARGUMENT_NAME: /^[a-zA-Z_][a-zA-Z0-9_]*$/, 129 | EMAIL: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, 130 | URL: /^https?:\/\/.+/ 131 | } as const; 132 | 133 | /** 134 | * Error codes 135 | */ 136 | export const ERROR_CODES = { 137 | VALIDATION_ERROR: 'VALIDATION_ERROR', 138 | CONFIG_ERROR: 'CONFIG_ERROR', 139 | FRAMEWORK_ERROR: 'FRAMEWORK_ERROR', 140 | EXECUTION_ERROR: 'EXECUTION_ERROR', 141 | NOT_FOUND: 'NOT_FOUND', 142 | PERMISSION_DENIED: 'PERMISSION_DENIED', 143 | TIMEOUT: 'TIMEOUT', 144 | UNKNOWN_ERROR: 'UNKNOWN_ERROR' 145 | } as const; 146 | 147 | /** 148 | * Default limits and constraints 149 | */ 150 | export const LIMITS = { 151 | MAX_NAME_LENGTH: 100, 152 | MIN_NAME_LENGTH: 1, 153 | MAX_DESCRIPTION_LENGTH: 500, 154 | MIN_DESCRIPTION_LENGTH: 10, 155 | MAX_STEP_NAME_LENGTH: 50, 156 | MAX_FILTER_RESULTS: 1000, 157 | DEFAULT_PAGE_SIZE: 20, 158 | MAX_PAGE_SIZE: 100, 159 | EXECUTION_TIMEOUT: 30000, // 30 seconds 160 | CACHE_TTL: 300000 // 5 minutes 161 | } as const; 162 | 163 | /** 164 | * Framework types 165 | */ 166 | export const FRAMEWORKS = { 167 | CAGEERF: 'CAGEERF', 168 | REACT: 'ReACT', 169 | FIVE_W_ONE_H: '5W1H', 170 | SCAMPER: 'SCAMPER' 171 | } as const; 172 | 173 | /** 174 | * Category types 175 | */ 176 | export const CATEGORIES = { 177 | ANALYSIS: 'analysis', 178 | DEVELOPMENT: 'development', 179 | CONTENT_PROCESSING: 'content_processing', 180 | DEBUGGING: 'debugging', 181 | DOCUMENTATION: 'documentation', 182 | EDUCATION: 'education', 183 | RESEARCH: 'research', 184 | SYSTEM: 'system' 185 | } as const; 186 | 187 | /** 188 | * Common error messages 189 | */ 190 | export const ERROR_MESSAGES = { 191 | REQUIRED_FIELD: (field: string) => `Field '${field}' is required but was not provided`, 192 | INVALID_FORMAT: (field: string, format: string) => `Field '${field}' must match format: ${format}`, 193 | LENGTH_CONSTRAINT: (field: string, min: number, max: number) => 194 | `Field '${field}' must be between ${min} and ${max} characters`, 195 | UNKNOWN_ACTION: (action: string, validActions: string[]) => 196 | `Unknown action: ${action}. Valid actions: ${validActions.join(', ')}`, 197 | UNKNOWN_OPERATION: (operation: string, validOperations: string[]) => 198 | `Unknown operation: ${operation}. Valid operations: ${validOperations.join(', ')}`, 199 | NOT_FOUND: (type: string, id: string) => `${type} not found: ${id}`, 200 | ALREADY_EXISTS: (type: string, id: string) => `${type} already exists: ${id}` 201 | } as const; 202 | 203 | /** 204 | * Success messages 205 | */ 206 | export const SUCCESS_MESSAGES = { 207 | CREATED: (type: string, id: string) => `${type} created successfully: ${id}`, 208 | UPDATED: (type: string, id: string) => `${type} updated successfully: ${id}`, 209 | DELETED: (type: string, id: string) => `${type} deleted successfully: ${id}`, 210 | OPERATION_COMPLETE: (operation: string) => `${operation} completed successfully` 211 | } as const; 212 | 213 | /** 214 | * Documentation URLs (when available) 215 | */ 216 | export const DOCUMENTATION = { 217 | PROMPT_CREATION: '/docs/prompts/creation', 218 | CHAIN_CREATION: '/docs/prompts/chains', 219 | FILTERING: '/docs/prompts/filtering', 220 | FRAMEWORKS: '/docs/frameworks', 221 | TROUBLESHOOTING: '/docs/troubleshooting' 222 | } as const; ``` -------------------------------------------------------------------------------- /server/prompts/analysis/progressive_research.md: -------------------------------------------------------------------------------- ```markdown 1 | # Progressive Research Assistant 2 | 3 | ## Description 4 | A step-by-step research assistant that builds knowledge incrementally through iterative questions and analysis instead of immediately producing a final output. 5 | 6 | ## System Message 7 | You are an expert research assistant who specializes in building knowledge incrementally through systematic analysis. Instead of immediately producing a final polished output, you work through information methodically, asking follow-up questions, expanding key concepts, and building deeper understanding step-by-step. 8 | 9 | ## User Message Template 10 | Guide the model in creating a detailed and informative response to the provided {{notes}} by conducting step-by-step research. 11 | 12 | Instead of outputting a final markdown page, use iterative questions and detailed analyses to progressively expand the given information: 13 | 14 | {{information}} 15 | 16 | # Goal 17 | 18 | The objective is to function as a researcher gathering insights and preparing the necessary information incrementally. Ask follow-up questions if any part of the provided notes is unclear or incomplete. Analyze the various topics step-by-step to add depth and context. 19 | 20 | # Step-by-Step Guide 21 | 22 | 1. **Understand the Initial Scope**: Review the given `{{notes}}` and identify the major themes and key elements. Start by summarizing what you understand to validate the context. Include concepts, keywords, and areas that may require expansion. 23 | 24 | 2. **Generate Follow-Up Questions**: Identify the sections or points that need further elaboration. Ask clear and specific follow-up questions to clarify ambiguities. Dive deeper into questions to plan how each part of the research could be compounded into a cohesive and comprehensive whole. 25 | 26 | 3. **Conduct Iterative Research**: 27 | - Perform individual research for each topic listed in `{{notes}}`, breaking down key concepts with respective definitions or details. 28 | - Expand with additional points, such as its historical background, notable experiments, practical applications, or current and future impacts. 29 | - If you encounter complex points that need deeper understanding, produce a focused list of additional clarifying questions. 30 | 31 | 4. **Expand on Key Concepts**: Elaborate on the core topics using reliable sources. For each topic: 32 | - Present fundamental definitions and concepts. 33 | - Provide examples illustrating key points—like experiments or use cases. 34 | - Include related discussions to enrich the understanding of the subject. 35 | 36 | 5. **Establish Connections Across Topics**: Determine any logical connections between different aspects of `{{notes}}`: 37 | - Try to bridge gaps between the ideas. 38 | - Provide continuous notes on transitions and flow for best linking sections during final composition. 39 | 40 | 6. **Add Insights and Context**: Offer personal analyses, including pros and cons, challenges, or breakthroughs regarding each topic. This exploration adds value by providing a more nuanced understanding. 41 | - Explore implications and real-world significance of topics. 42 | - Pose relevant questions to stimulate deeper inquiry or highlight potential challenges. 43 | 44 | 7. **Document the Process Regularly**: Keep a record of your findings, proposed connections, and unanswered questions. Consider suggesting the layout or ordering for a potential final output. 45 | 46 | # Output Format 47 | 48 | - **Iterative Questions and Expansion Responses**: 49 | - For each identified gap or ambiguity, ask one or more follow-up questions to seek more detailed information. 50 | - For each research topic or subtopic, provide structured notes, expanding on the definition, explanation, and examples. 51 | - Use bullet points or numbered lists for easier comprehension. 52 | - Recommendations for any additional areas requiring deeper research can be added in bullet format. 53 | 54 | - **Examples of Output**: A structured list of iterative questions followed by researched notes: 55 | 1. **Initial Assessment and Understanding**: 56 | - Questions: "What are the major theoretical implications of wave-particle duality?" "Can we include historical background on the experimentation that led to superposition?" 57 | - Answers: "Wave-particle duality shows the dual behavior of particles (e.g., electrons behave as both waves and particles depending on the situation)." 58 | 59 | 2. **Further Context Expansion**: 60 | - Key Concept: **Double-Slit Experiment**. 61 | - "The experiment reveals substantial insights about how particles interfere with each other, which is core to understanding wave-particle duality." 62 | 63 | # Notes 64 | 65 | 1. Focus on gradually accumulating enough content to transition effectively to writing a complete Markdown description. The approach should help generate in-depth content ready for logical conversion into explanative structures. 66 | 67 | 2. This step-by-step progression can continue until there's sufficient information on each key aspect of `{{notes}}`. The goal is to cover fundamental points as well as nuanced topics that add helpful detail, allowing an easy transition into structured Markdown content in a subsequent step. 68 | 69 | 3. List additional open threads and related questions that might require attention to ensure completeness. ``` -------------------------------------------------------------------------------- /server/src/types.ts: -------------------------------------------------------------------------------- ```typescript 1 | /** 2 | * Type definitions for the prompt management system 3 | */ 4 | 5 | // Import domain-specific types 6 | import type { GateDefinition } from './gates/types.js'; 7 | import type { PromptArgument, Category, PromptData, PromptsFile, PromptFile, PromptsConfigFile, PromptsConfig } from './prompts/types.js'; 8 | 9 | // ===== Configuration Types ===== 10 | 11 | /** 12 | * Configuration for the server 13 | */ 14 | export interface ServerConfig { 15 | /** Name of the server */ 16 | name: string; 17 | /** Version string in semver format */ 18 | version: string; 19 | /** Port number to listen on (1024-65535) */ 20 | port: number; 21 | } 22 | 23 | // PromptsConfig interface moved to ./prompts/types.ts 24 | // (imported directly above) 25 | 26 | /** 27 | * Configuration for a transport 28 | */ 29 | export interface TransportConfig { 30 | /** Whether this transport is enabled */ 31 | enabled: boolean; 32 | } 33 | 34 | /** 35 | * Configuration for all transports 36 | */ 37 | export interface TransportsConfig { 38 | /** Name of the default transport to use */ 39 | default: string; 40 | /** Server-sent events transport configuration */ 41 | sse: TransportConfig; 42 | /** Standard I/O transport configuration */ 43 | stdio: TransportConfig; 44 | /** Custom transports map */ 45 | customTransports?: Record<string, TransportConfig>; 46 | // Removed: Index signature for backwards compatibility - use customTransports instead 47 | } 48 | 49 | /** 50 | * Analysis mode for semantic analysis 51 | * Mode is automatically inferred based on LLM integration configuration 52 | */ 53 | export type AnalysisMode = "structural" | "semantic"; 54 | 55 | /** 56 | * LLM provider for semantic analysis 57 | */ 58 | export type LLMProvider = "openai" | "anthropic" | "custom"; 59 | 60 | /** 61 | * LLM integration configuration 62 | */ 63 | export interface LLMIntegrationConfig { 64 | /** Whether LLM integration is enabled */ 65 | enabled: boolean; 66 | /** API key for the LLM provider */ 67 | apiKey: string | null; 68 | /** Custom endpoint URL for the LLM provider (provider auto-detected from URL) */ 69 | endpoint: string | null; 70 | /** Model name to use */ 71 | model: string; 72 | /** Maximum tokens for analysis requests */ 73 | maxTokens: number; 74 | /** Temperature for analysis requests */ 75 | temperature: number; 76 | } 77 | 78 | 79 | /** 80 | * Semantic analysis configuration 81 | */ 82 | export interface SemanticAnalysisConfig { 83 | /** Analysis mode to use (automatically inferred if not specified) */ 84 | mode?: AnalysisMode; 85 | /** LLM integration configuration */ 86 | llmIntegration: LLMIntegrationConfig; 87 | } 88 | 89 | /** 90 | * Analysis system configuration 91 | */ 92 | export interface AnalysisConfig { 93 | /** Semantic analysis configuration */ 94 | semanticAnalysis: SemanticAnalysisConfig; 95 | } 96 | 97 | /** 98 | * Logging system configuration 99 | */ 100 | export interface LoggingConfig { 101 | /** Directory to write log files to */ 102 | directory: string; 103 | /** Log level: debug, info, warn, error */ 104 | level: string; 105 | } 106 | 107 | // Removed: FrameworkConfig - deprecated interface, framework state now managed at runtime 108 | 109 | /** 110 | * Tool descriptions configuration options 111 | */ 112 | export interface ToolDescriptionsOptions { 113 | /** Whether to restart server when tool descriptions change */ 114 | restartOnChange?: boolean; 115 | } 116 | 117 | /** 118 | * Complete application configuration 119 | */ 120 | /** 121 | * Configuration for gates subsystem 122 | */ 123 | export interface GatesConfig { 124 | /** Directory containing gate definitions */ 125 | definitionsDirectory: string; 126 | /** Directory containing LLM validation templates */ 127 | templatesDirectory: string; 128 | } 129 | 130 | export interface Config { 131 | /** Server configuration */ 132 | server: ServerConfig; 133 | /** Prompts subsystem configuration */ 134 | prompts: PromptsConfig; 135 | /** Analysis system configuration */ 136 | analysis?: AnalysisConfig; 137 | /** Gates system configuration */ 138 | gates?: GatesConfig; 139 | /** Transports configuration */ 140 | transports: TransportsConfig; 141 | /** Logging configuration */ 142 | logging?: LoggingConfig; 143 | /** Tool descriptions configuration */ 144 | toolDescriptions?: ToolDescriptionsOptions; 145 | } 146 | 147 | // ===== Prompt Types ===== 148 | // Moved to ./prompts/types.ts for domain organization 149 | // Re-export for backward compatibility 150 | export type { PromptArgument } from './prompts/types.js'; 151 | 152 | /** 153 | * Base interface for message content 154 | */ 155 | export interface BaseMessageContent { 156 | /** Type discriminator for the content */ 157 | type: string; 158 | } 159 | 160 | /** 161 | * Text message content 162 | */ 163 | export interface TextMessageContent extends BaseMessageContent { 164 | /** Type discriminator set to "text" */ 165 | type: "text"; 166 | /** The text content */ 167 | text: string; 168 | } 169 | 170 | /** 171 | * Types of message content supported by the system 172 | * Extensible for future content types 173 | */ 174 | export type MessageContent = TextMessageContent; 175 | 176 | /** 177 | * Role types for messages 178 | */ 179 | export type MessageRole = "user" | "assistant" | "system"; 180 | 181 | /** 182 | * A message in a conversation 183 | */ 184 | export interface Message { 185 | /** Role of the message sender */ 186 | role: MessageRole; 187 | /** Content of the message */ 188 | content: MessageContent; 189 | } 190 | 191 | // Category interface moved to ./prompts/types.ts 192 | export type { Category } from './prompts/types.js'; 193 | 194 | // PromptData interface moved to ./prompts/types.ts 195 | export type { PromptData } from './prompts/types.js'; 196 | 197 | // PromptsFile interface moved to ./prompts/types.ts 198 | export type { PromptsFile } from './prompts/types.js'; 199 | 200 | // PromptFile interface moved to ./prompts/types.ts 201 | export type { PromptFile } from './prompts/types.js'; 202 | 203 | // PromptsConfigFile interface moved to ./prompts/types.js 204 | export type { PromptsConfigFile } from './prompts/types.js'; 205 | ``` -------------------------------------------------------------------------------- /server/prompts/content_processing/noteIntegration.md: -------------------------------------------------------------------------------- ```markdown 1 | # Advanced Note Integration with Content Analysis Chain 2 | 3 | ## Description 4 | Advanced workflow that runs a comprehensive content analysis chain to transform raw content into publication-ready, interconnected notes optimized for Obsidian knowledge management systems. Uses intelligent defaults - only pass the content argument. 5 | 6 | ## System Message 7 | You are executing a sophisticated content analysis chain that transforms raw content into publication-ready Obsidian notes. Follow the S.P.A.R.C. methodology (Strategic Personal Archive with Refined Connectivity) and C.A.G.E.E.R.F framework. Each step builds upon the previous one to create comprehensive, interconnected knowledge assets. Use intelligent defaults for all optional parameters. 8 | 9 | ## User Message Template 10 | Execute a comprehensive content analysis chain to transform raw content into publication-ready, interconnected notes optimized for Obsidian knowledge management. 11 | 12 | ## Content Analysis Chain Workflow 13 | 14 | ### Input Content 15 | {{content}} 16 | 17 | {% if existing_notes %} 18 | ### Existing Notes Context 19 | {{existing_notes}} 20 | {% endif %} 21 | 22 | {% if vault_context %} 23 | ### Vault Context 24 | {{vault_context}} 25 | {% endif %} 26 | 27 | ### Processing Configuration (Using Intelligent Defaults) 28 | - **Domain**: {{domain or 'general'}} 29 | - **Analysis Depth**: {{analysis_depth or 'comprehensive'}} 30 | - **Structure Type**: {{structure_type or 'comprehensive'}} 31 | - **Integration Level**: {{integration_level or 'advanced'}} 32 | - **Target Readability**: {{target_readability or 'comprehensive'}} 33 | - **Metadata Depth**: {{metadata_depth or 'advanced'}} 34 | - **Quality Standards**: {{quality_standards or 'comprehensive'}} 35 | - **Enhancement Level**: {{enhancement_level or 'comprehensive'}} 36 | 37 | ### Expected Output 38 | This workflow will produce a sophisticated, publication-ready note that: 39 | - Preserves all original insights while adding professional structure 40 | - Leverages advanced Obsidian features (callouts, multi-column layouts, metadata) 41 | - Creates meaningful connections with existing vault content 42 | - Follows S.P.A.R.C. methodology for strategic knowledge management 43 | - Implements C.A.G.E.E.R.F framework for structured analysis 44 | - Meets professional documentation standards 45 | 46 | Execute the chain workflow to transform the provided content into an enhanced, integrated note ready for your Obsidian knowledge management system. 47 | 48 | ## Chain Steps 49 | 50 | 1. promptId: content_preservation_analysis 51 | stepName: Content Preservation Analysis 52 | inputMapping: 53 | content: content 54 | existing_content: existing_notes 55 | analysis_depth: analysis_depth 56 | outputMapping: 57 | analyzed_content: preserved_analysis 58 | 59 | 2. promptId: layered_note_structure 60 | stepName: Layered Note Structure Creation 61 | inputMapping: 62 | analyzed_content: preserved_analysis 63 | vault_context: vault_context 64 | structure_type: structure_type 65 | outputMapping: 66 | structured_content: layered_structure 67 | 68 | 3. promptId: smart_content_refinement 69 | stepName: Smart Content Refinement 70 | inputMapping: 71 | raw_content: layered_structure 72 | vault_context: vault_context 73 | integration_level: integration_level 74 | target_readability: target_readability 75 | outputMapping: 76 | refined_content: smart_refined 77 | 78 | 4. promptId: obsidian_metadata_optimizer 79 | stepName: Obsidian Metadata Optimization 80 | inputMapping: 81 | note_content: smart_refined 82 | vault_structure: vault_context 83 | metadata_depth: metadata_depth 84 | outputMapping: 85 | optimized_content: metadata_optimized 86 | 87 | 5. promptId: vault_integration_optimizer 88 | stepName: Vault Integration Optimization 89 | inputMapping: 90 | note_content: metadata_optimized 91 | vault_structure: vault_context 92 | integration_level: integration_level 93 | outputMapping: 94 | integrated_content: vault_integrated 95 | 96 | 6. promptId: note_quality_assurance 97 | stepName: Quality Assurance 98 | inputMapping: 99 | note_content: vault_integrated 100 | original_source: content 101 | quality_standards: quality_standards 102 | outputMapping: 103 | quality_assured: qa_content 104 | 105 | 7. promptId: format_enhancement 106 | stepName: Format Enhancement 107 | inputMapping: 108 | existing_content: qa_content 109 | domain: domain 110 | enhancement_level: enhancement_level 111 | outputMapping: 112 | final_note: enhanced_note 113 | 114 | ## Chain Steps 115 | 116 | 1. **Initial Content Analysis** (content_analysis) 117 | - Input Mapping: {"content":"content"} 118 | - Output Mapping: {"analysis_output":"step_0_output"} 119 | 120 | 2. **Find Related Vault Notes** (vault_related_notes_finder) 121 | - Input Mapping: {"note_topic":"content","content_areas":"analysis_output"} 122 | - Output Mapping: {"related_notes":"step_1_output"} 123 | 124 | 3. **Integrate Content with Existing Notes** (note_integration) 125 | - Input Mapping: {"notes":"existing_notes","new_information":"analysis_output"} 126 | - Output Mapping: {"integrated_content":"step_2_output"} 127 | 128 | 4. **Optimize Metadata** (obsidian_metadata_optimizer) 129 | - Input Mapping: {"note_content":"integrated_content","vault_structure":"vault_context"} 130 | - Output Mapping: {"metadata_optimized":"step_3_output"} 131 | 132 | 5. **Enhance Formatting** (format_enhancement) 133 | - Input Mapping: {"existing_content":"metadata_optimized","domain":"domain"} 134 | - Output Mapping: {"enhanced_content":"step_4_output"} 135 | 136 | 6. **Final Refinement** (note_refinement) 137 | - Input Mapping: {"notes":"enhanced_content"} 138 | - Output Mapping: {"final_output":"step_5_output"} 139 | 140 | ```