This is page 1 of 12. Use http://codebase.md/minipuft/claude-prompts-mcp?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 -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- ``` # Dependencies and Package Management server/node_modules/ server/package-lock.json .npm/ .yarn/ .pnp.* yarn.lock # Build Output and TypeScript server/dist/ build/ out/ *.tsbuildinfo .tsbuildinfo # Environment Variables server/.env* .env* # Logs and Debug Files #server/logs/ logs/ *.log npm-debug.log* yarn-debug.log* yarn-error.log* # Test Coverage and Reports coverage/ nyc_output/ .coverage/ junit.xml test-results/ *.lcov # Editor and IDE Files .vscode/ .cursor/ # Operating System Files .DS_Store .DS_Store? ._* .Spotlight-V100 .Trashes ehthumbs.db Thumbs.db *:Zone.Identifier *.Zone.Identifier # Runtime and Cache Files .cache/ tmp/ temp/ pids/ *.pid *.seed *.pid.lock # MCP Server Specific admin-ui/ # Runtime State Files # server/config/framework-state.json # .framework-state.json # Runtime State (generated during server execution) runtime-state/ server/runtime-state/ # Crash Dumps and Diagnostics *.dmp report.*.json *.diagraw heapdump-* # Claude-Code setup plans/archive/ CLAUDE.md .codex/ AGENTS.md .claude/ server/.claude/ ``` -------------------------------------------------------------------------------- /.actrc: -------------------------------------------------------------------------------- ``` # Act Configuration for Claude Prompts MCP # Optimized for local CI testing with comprehensive platform support and performance enhancements # Primary platform mappings - Ubuntu versions -P ubuntu-latest=catthehacker/ubuntu:act-22.04 -P ubuntu-20.04=catthehacker/ubuntu:act-20.04 -P ubuntu-18.04=catthehacker/ubuntu:act-18.04 # Windows platform mappings # Note: True Windows containers require Windows Docker mode; using Ubuntu for cross-platform compatibility -P windows-latest=catthehacker/ubuntu:act-22.04 -P windows-2022=catthehacker/ubuntu:act-22.04 -P windows-2019=catthehacker/ubuntu:act-22.04 # macOS platform mappings # Note: ACT runs Linux containers; macOS simulation through Ubuntu -P macos-latest=catthehacker/ubuntu:act-22.04 -P macos-13=catthehacker/ubuntu:act-22.04 -P macos-12=catthehacker/ubuntu:act-22.04 # Environment variables for proper CI simulation --env ACT=true --env CI=true --env NODE_ENV=test # Container configuration for better performance --container-architecture linux/amd64 # Artifact server configuration --artifact-server-path /tmp/artifacts # Resource limits to prevent container issues --container-cap-add SYS_PTRACE # Networking and Docker integration --container-daemon-socket /var/run/docker.sock # Verbose output for debugging --verbose ``` -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- ``` # Cross-Platform Line Ending Configuration for MCP Claude Prompts Server # Ensures consistent behavior across Windows, macOS, and Linux development environments # Default behavior: normalize line endings to LF on checkin, convert to native on checkout * text=auto # Explicitly declare text files and line ending handling *.md text *.json text *.js text *.ts text *.mjs text *.yml text *.yaml text *.txt text *.html text *.css text *.scss text *.xml text *.config text *.gitignore text *.gitattributes text # Shell scripts should always use LF (for cross-platform compatibility) *.sh text eol=lf *.bash text eol=lf # Windows batch files should use CRLF *.bat text eol=crlf *.cmd text eol=crlf # Binary files (declare as binary to prevent line ending conversion) *.png binary *.jpg binary *.jpeg binary *.gif binary *.ico binary *.pdf binary *.zip binary *.tar binary *.gz binary *.7z binary *.exe binary *.dll binary *.so binary *.dylib binary # Node.js specific files package.json text package-lock.json text .nvmrc text .node-version text # Git files .gitignore text .gitattributes text .gitkeep text # GitHub and CI/CD files .github/** text # MCP Server specific files promptsConfig.json text config.json text *.mcp text # Ensure consistent handling of sensitive files *.env text *.key binary *.pem binary *.p12 binary *.pfx binary # Documentation files README* text LICENSE* text CHANGELOG* text CONTRIBUTING* text *.md text # TypeScript and JavaScript configuration tsconfig.json text jsconfig.json text .eslintrc* text .prettierrc* text *.config.js text *.config.ts text # Line ending overrides for specific problematic files # (These patterns help prevent Windows-specific issues) server/dist/** binary node_modules/** binary coverage/** binary logs/** binary # Special handling for files that might cause Windows issues # Exclude problematic characters and ensure proper encoding *.log text *.tmp binary *.cache binary # AI and prompt specific files (ensure proper text handling) server/prompts/**/*.md text server/prompts/**/*.json text ``` -------------------------------------------------------------------------------- /docs/README.md: -------------------------------------------------------------------------------- ```markdown # Claude Prompts MCP - Documentation ## 🚀 Getting Started - [Installation Guide](installation-guide.md) - Setup and configuration instructions - [Quick Start: Execution Modes](prompt-vs-template-guide.md) - Choose the right execution mode for your needs - [Troubleshooting](troubleshooting.md) - Common issues and solutions ## 📋 Core Concepts - [System Architecture](architecture.md) - Overall system design and components - [Three-Tier Execution System](execution-architecture-guide.md) - **Comprehensive guide** to prompt → template → chain execution model - [Chain System Analysis](chain-system-analysis.md) - Current chain capabilities, limitations, and future roadmap ## 🛠️ Development Guides - [Prompt Format Guide](prompt-format-guide.md) - How to create and format custom prompt templates - [Template Development Guide](template-development-guide.md) - Creating framework-aware templates with methodology integration - [Prompt Management](prompt-management.md) - Managing prompts and categories in the distributed configuration system - [Enhanced Gate System](enhanced-gate-system.md) - Quality validation system for templates and chains ## 📚 Technical Reference - [MCP Tools Reference](mcp-tools-reference.md) - Complete reference for the server's MCP tools - [Version History](version-history.md) - Complete version history and release notes ## 🤝 Contributing - [Contributing Guide](contributing.md) - Development and contribution guidelines - [TODO](TODO.md) - Current development tasks and roadmap ``` -------------------------------------------------------------------------------- /server/README.md: -------------------------------------------------------------------------------- ```markdown # MCP Prompts Server A comprehensive Model Context Protocol (MCP) server that provides AI prompt management with hot-reloading capabilities, workflow orchestration, and enterprise-grade features. ## Overview The MCP Prompts Server implements a modernized execution architecture with three-tier processing that handles different types of prompt execution: - **Direct Prompt Processing**: Lightning-fast variable substitution via UnifiedPromptProcessor (90% of cases) - **LLM-Driven Chain Execution**: Multi-step workflows orchestrated by ConsolidatedPromptEngine (10% of cases) - **Framework Integration**: Methodology enhancement (CAGEERF/ReACT/5W1H/SCAMPER) applied contextually ## Architecture ### ExecutionCoordinator System The server uses ExecutionCoordinator as a thin orchestration layer that delegates all execution to ConsolidatedPromptEngine: ```typescript // Phase 3: Delegation-based execution routing const result = await executionCoordinator.executePrompt( promptId, args, options ); // All execution delegated to ConsolidatedPromptEngine ``` #### Core Components 1. **ExecutionCoordinator**: Thin orchestration layer with delegation pattern 2. **UnifiedPromptProcessor**: Handles 90% of prompt processing with fast variable substitution 3. **ConsolidatedPromptEngine**: Handles 10% of cases with LLM-driven chain execution and intelligent analysis ### Simplified Execution Architecture The system supports intelligent routing with three primary execution tiers: | Execution Tier | Framework Integration | Processing | Speed | Best For | | -------------- | ----------------------- | ------------------------ | -------------- | ------------------------------------- | | **Prompt** | ❌ Bypassed for speed | UnifiedPromptProcessor | Lightning Fast | Basic variable substitution | | **Template** | ✅ Methodology-aware | ConsolidatedPromptEngine | Smart | Framework-enhanced content generation | | **Chain** | ✅ Per-step enhancement | ConsolidatedPromptEngine | LLM-Driven | Multi-step workflows | #### Execution Flow - **Prompt Execution**: Fast path with direct variable substitution via UnifiedPromptProcessor, **bypasses framework injection** for maximum speed - **Template Execution**: Framework-enhanced processing with **automatic methodology injection** via ConsolidatedPromptEngine based on active framework - **Chain Execution**: LLM-driven iterative workflows with **per-step framework injection** and state management via ConsolidatedPromptEngine - **Framework Selection**: Rule-based framework selection using FrameworkManager based on execution type, complexity, and user preference - **Active Framework Management**: FrameworkStateManager maintains current active framework (default: CAGEERF) with runtime switching capabilities For detailed information about choosing the right execution type, see the [Execution Types Guide](../docs/execution-types-guide.md). ### Key Components - **Application Orchestrator**: Multi-phase startup with comprehensive health monitoring - **ConsolidatedPromptEngine**: Three-tier execution system with intelligent analysis and LLM-driven chains - **Template System**: Nunjucks-powered template processing with framework injection - **Gate System**: Quality validation with framework-aware evaluation - **Hot-Reload System**: Dynamic prompt updates without server restart ### Three-Tier Quality Assurance System The server implements an intelligent quality assurance model that adapts to execution type: #### Prompt Execution (No Framework, No Gates) - **Lightning Fast**: Direct Nunjucks variable substitution - **Zero Overhead**: Bypasses framework injection and quality gates - **Best For**: Simple formatting, variable replacement, basic templates #### Template Execution (Framework-Enhanced) - **Smart Processing**: Rule-based framework selection with conditional injection - **Methodology Integration**: CAGEERF, ReACT, 5W1H, or SCAMPER framework enhancement based on active framework - **Quality Validation**: Content validation and framework compliance - **Best For**: Analysis, reasoning, complex content generation #### Chain Execution (LLM-Driven Workflows) - **Iterative Processing**: LLM-guided step-by-step execution with intelligent coordination - **Context Management**: Conversation state and inter-step data flow management - **Quality Gate Integration**: Framework-aware validation and methodology compliance - **Best For**: Multi-step processes requiring sequential reasoning and state management For detailed gate configuration, see the [Enhanced Gate System Guide](../docs/enhanced-gate-system.md). ### Framework System Architecture The server implements a sophisticated framework system with systematic methodology application: #### Framework Components 1. **FrameworkManager** (Stateless): Loads methodology guides and generates framework definitions dynamically 2. **FrameworkStateManager** (Stateful): Tracks active framework and handles runtime switching with performance monitoring 3. **FrameworkInjector**: Conditionally injects framework-specific system prompts based on execution tier 4. **Methodology Guides**: CAGEERF, ReACT, 5W1H, SCAMPER guides providing framework-specific behavior #### Framework Selection Process ```typescript // Rule-based framework selection based on criteria const framework = frameworkManager.selectFramework({ executionType: "template", complexity: "high", userPreference: "CAGEERF", // User preference is primary selection factor }); // Runtime framework switching await frameworkStateManager.switchFramework({ targetFramework: "ReACT", reason: "User preference change", }); ``` #### Conditional Framework Injection - **Prompt Tier**: Framework injection **bypassed** for maximum execution speed - **Template Tier**: **Automatic injection** of active framework's system prompt and methodology guidance - **Chain Tier**: **Per-step injection** allowing different frameworks per chain step #### Available Methodologies - **CAGEERF**: Comprehensive structured approach (Context, Analysis, Goals, Execution, Evaluation, Refinement, Framework) - **ReACT**: Reasoning and Acting pattern for systematic problem-solving - **5W1H**: Who, What, When, Where, Why, How systematic analysis - **SCAMPER**: Creative problem-solving (Substitute, Combine, Adapt, Modify, Put to other uses, Eliminate, Reverse) ## Quick Start ### Installation ```bash # Clone or navigate to the project cd /path/to/claude-prompts-mcp/server # Install dependencies npm install # Build TypeScript npm run build ``` ### Claude Desktop Integration (Recommended) 1. **Add to Claude Desktop configuration** (typically `~/.claude_desktop_config.json`): ```json { "mcpServers": { "claude-prompts-mcp": { "command": "node", "args": ["/absolute/path/to/claude-prompts-mcp/server/dist/index.js"] } } } ``` 2. **Restart Claude Desktop** - The server will start automatically when Claude Desktop connects. ### Manual Testing & Development ```bash # Development mode with hot-reloading npm run dev # Type checking only npm run typecheck # Run tests npm test # Manual STDIO mode (for testing without Claude Desktop) npm run start:stdio # Web/SSE mode (for web clients) npm run start:sse ``` ## Configuration ### Main Configuration (`config.json`) ```json { "server": { "name": "claude-prompts-mcp", "version": "1.0.0" }, "transports": { "stdio": { "enabled": true }, "sse": { "enabled": true, "port": 3000 } }, "logging": { "directory": "./logs", "level": "INFO" }, "prompts": "./prompts/promptsConfig.json" } ``` ### Prompts Configuration (`prompts/promptsConfig.json`) ```json { "categories": [ { "name": "analysis", "displayName": "Analysis & Research", "description": "Data analysis and research prompts", "promptsFile": "./prompts/analysis/prompts.json" } ], "registrationMode": "NAME" } ``` ## Prompt and Template Development ### Basic Prompt Structure (Fast Variable Substitution) ````markdown # Quick Code Formatter ## System Message Format code cleanly and consistently. ## User Message Template Please format this {{language}} code using {{style}} style: ```{{language}} {{code}} ``` ```` ## Arguments - language: Programming language (required) - style: Formatting style (required) - code: Code to format (required) ```` ### Framework-Aware Template Structure (Methodology Enhanced) ```markdown # Code Security Analyzer ## System Message You are a security expert specialized in code analysis. ## User Message Template Analyze this {{language}} code for security vulnerabilities: ```{{language}} {{code}} ```` Provide comprehensive analysis including: - Vulnerability assessment - Risk prioritization - Remediation recommendations ## Arguments - language: Programming language (required) - code: Code to analyze (required) ```` ### Chain Execution ```json { "id": "analysis-chain", "name": "Analysis Chain", "chainSteps": [ { "promptId": "data-extraction", "stepName": "Extract Data", "inputMapping": { "source": "input" }, "outputMapping": { "extracted_data": "output" } }, { "promptId": "data-analysis", "stepName": "Analyze Data", "inputMapping": { "data": "extracted_data" }, "outputMapping": { "analysis_result": "output" } } ] } ```` ### Enhanced Chain Configuration ```json { "id": "analysis-chain", "name": "Enhanced Analysis Chain", "executionMode": "chain", "chainSteps": [ { "promptId": "data-validation", "stepName": "Validate Input Data", "inputMapping": { "source": "input" }, "outputMapping": { "validated_data": "output" } }, { "promptId": "advanced-analysis", "stepName": "Perform Analysis", "inputMapping": { "data": "validated_data" }, "outputMapping": { "analysis_result": "output" } } ], "gates": [ { "type": "validation", "requirements": [{ "type": "content_length", "criteria": { "min": 50 } }] } ] } ``` ## Performance Features ### Caching and Optimization - **Three-Tier Execution Caching**: Optimized routing between prompt/template/chain execution - **Memory Management**: Automatic cleanup and size limits - **Performance Monitoring**: Real-time metrics and diagnostics - **Consolidated Tool Architecture**: 87.5% reduction in tool complexity ### Monitoring ```typescript // Get execution statistics from coordinator const stats = executionCoordinator.getExecutionStats(); // Get framework state and analytics const analytics = frameworkStateManager.getAnalytics(); // System health monitoring const health = applicationOrchestrator.getHealthStatus(); ``` ## Development Commands ### Essential Commands ```bash # Build TypeScript npm run build # Type checking npm run typecheck # Development mode npm run dev # Run tests npm test # Start production server npm start ``` ### Transport-Specific ```bash # STDIO transport (Claude Desktop) npm run start:stdio # SSE transport (web clients) npm run start:sse # Development with verbose logging npm run start:verbose ``` ### Environment Variables (Optional) ```bash # Optional: Optimize server root detection (streamlined detection system) export MCP_SERVER_ROOT=/path/to/claude-prompts-mcp/server # Optional: Direct path to prompts config (automatic detection available) export MCP_PROMPTS_CONFIG_PATH=/path/to/claude-prompts-mcp/server/prompts/promptsConfig.json ``` **Detection Strategy:** The server uses streamlined detection with 3 core strategies: 1. **Script path analysis** (most reliable - works in 99% of cases) 2. **Module path detection** (reliable fallback for edge cases) 3. **Common directory patterns** (covers remaining scenarios) Environment variables provide **guaranteed detection** but are not required for normal operation. ## Troubleshooting ### Common Installation Issues 1. **"Cannot find module" errors** ```bash # Ensure you're in the server directory cd /path/to/claude-prompts-mcp/server # Clean install rm -rf node_modules package-lock.json npm install npm run build ``` 2. **Claude Desktop not connecting** - Verify absolute paths in configuration (no relative paths like `./` or `~/`) - Ensure the `dist/index.js` file exists after running `npm run build` - Check Claude Desktop logs for connection errors - Restart Claude Desktop after configuration changes 3. **Permission errors** ```bash # Fix file permissions chmod +x dist/index.js ``` 4. **TypeScript compilation errors** ```bash # Check for syntax errors npm run typecheck # Clean build npm run build ``` ### Verifying Installation ```bash # Test the server manually node dist/index.js --help # Run the test suite npm test # Check if MCP tools are working # After connecting to Claude Desktop, try: /mcp ``` ## Testing ### Test Structure - **Unit Tests**: Individual component testing - **Integration Tests**: Full system testing with ConsolidatedPromptEngine - **Performance Tests**: Three-tier execution benchmarking - **Framework Tests**: CAGEERF, ReACT, 5W1H, SCAMPER validation ### Running Tests ```bash # Run all tests npm test # Run specific test suites npm test -- --testNamePattern="ConsolidatedPromptEngine" # Run framework tests npm run test:cageerf-framework # Run MCP tools tests npm run test:mcp-tools ``` ## Advanced Integration ### Web Clients (Alternative to Claude Desktop) For web-based integrations, use SSE transport: ```bash # Start SSE server npm run start:sse ``` ```javascript // Connect to SSE endpoint const eventSource = new EventSource("http://localhost:3000/events"); eventSource.onmessage = function (event) { const data = JSON.parse(event.data); // Handle MCP messages }; ``` ### Custom MCP Clients For custom integrations, the server supports both STDIO and SSE transports. See the [MCP Protocol Documentation](https://modelcontextprotocol.io) for implementation details. ## Error Handling ### Graceful Degradation - **Startup Failures**: Rollback mechanisms for partial initialization - **Execution Errors**: Comprehensive error boundaries - **Template Errors**: Detailed error reporting with context - **Performance Issues**: Automatic optimization and cleanup ### Logging - **Structured Logging**: JSON-formatted logs with context - **Log Levels**: DEBUG, INFO, WARN, ERROR - **Transport-Aware**: Prevents STDIO interference - **Performance Tracking**: Execution timing and metrics ## API Reference ### Consolidated MCP Tools (87.5% Reduction: 24+ → 3 Tools) - **prompt_engine**: Universal execution with intelligent analysis, semantic detection, and LLM-driven chain coordination - **prompt_manager**: Complete lifecycle management with smart filtering, type analysis, and configurable semantic analysis - **system_control**: Framework management, analytics, health monitoring, and comprehensive system administration ### ExecutionCoordinator Methods (Phase 3) ```typescript // Execute with delegation to ConsolidatedPromptEngine await executionCoordinator.executePrompt(promptId, args, options); // Get execution statistics (three-tier model) const stats = executionCoordinator.getExecutionStats(); // Returns: { promptExecutions, templateExecutions, chainExecutions, failedExecutions } // Set consolidated engine for delegation executionCoordinator.setConsolidatedEngine(consolidatedPromptEngine); ``` ### ConsolidatedPromptEngine Methods ```typescript // Universal execution with intelligent type detection const result = await consolidatedPromptEngine.executePrompt(command, options); // Semantic analysis with configurable analyzer const analysis = semanticAnalyzer.analyze(promptData); // Returns: { executionType: 'prompt'|'template'|'chain', requiresFramework: boolean } ``` ### Framework System Methods ```typescript // Framework selection and management const framework = frameworkManager.selectFramework({ executionType: "template", complexity: "high", }); // Runtime framework switching await frameworkStateManager.switchFramework({ targetFramework: "CAGEERF", reason: "Complexity requires structured approach", }); // Framework injection (conditional based on execution tier) const injectionResult = await frameworkInjector.injectFrameworkContext( prompt, semanticAnalysis ); // Get current framework state and health const state = frameworkStateManager.getCurrentState(); const health = frameworkStateManager.getSystemHealth(); ``` ## Contributing 1. Follow TypeScript best practices 2. Include comprehensive tests 3. Update documentation 4. Ensure hot-reloading compatibility 5. Validate MCP protocol compliance ### Architecture Guidelines - **Delegation Pattern**: ExecutionCoordinator delegates all execution to ConsolidatedPromptEngine for simplified coordination - **Three-Tier Architecture**: Optimized routing between prompt (fast), template (framework-enhanced), and chain (LLM-driven) execution - **Conditional Framework Integration**: Framework injection applied selectively based on execution tier requirements - **Intelligent Routing**: Implement command routing with built-in detection and multi-strategy parsing - **Comprehensive Error Boundaries**: Implement error handling at all orchestration levels - **Backward Compatibility**: Maintain compatibility through ExecutionCoordinator interface while leveraging modern delegation architecture ## License MIT License - see LICENSE file for details. ## Support For issues and questions: - GitHub Issues: Report bugs and feature requests - Documentation: See `/docs` for detailed guides - Examples: Check `/examples` for usage patterns ``` -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- ```markdown # Claude Prompts MCP Server <div align="center">  [](https://www.npmjs.com/package/claude-prompts-server) [](https://opensource.org/licenses/MIT) [](https://modelcontextprotocol.io) [](https://nodejs.org) **A Universal Model Context Protocol Server for Advanced Prompt Management** Production-ready MCP server with intelligent prompt orchestration, hot-reload capabilities, and framework-driven AI workflows. Compatible with Claude Desktop, Cursor Windsurf, and any MCP client. [Quick Start](#quick-start) • [Features](#core-features) • [Documentation](#documentation) • [Configuration](#configuration) --- </div> ## Core Features **Three-Tier Execution Architecture** - **Prompt Execution**: Lightning-fast single prompt execution with variable substitution - **Template Processing**: Framework-enhanced templates with Nunjucks templating engine - **Chain Workflows**: Multi-step LLM-driven workflows with state management **Intelligent System Components** - **Structural Analysis**: Automatic execution type detection based on file structure - **Hot-Reload System**: Update prompts instantly without server restarts - **Quality Gates**: Framework-aware validation with conditional logic - **Performance Monitoring**: Comprehensive startup orchestration and health monitoring **Universal MCP Compatibility** - **Transport Support**: STDIO for desktop clients, SSE for web applications - **Client Integration**: Native support for Claude Desktop, Cursor Windsurf, and custom MCP clients - **Protocol Compliance**: Full Model Context Protocol implementation with tool registration ## Interactive Prompt Management Manage AI capabilities directly within conversations through three consolidated MCP tools: ```bash # Universal prompt execution with intelligent type detection prompt_engine >>code_formatter language="Python" style="PEP8" # Create and manage prompts with intelligent analysis prompt_manager create name="code_reviewer" type="template" \ content="Analyze {{code}} for security, performance, and maintainability" # Analyze existing prompts for execution optimization prompt_manager analyze_type prompt_id="my_prompt" # System control and framework management system_control switch_framework framework="ReACT" reason="Problem-solving focus" # Execute complex multi-step LLM-driven chains prompt_engine >>code_review_optimization_chain target_code="..." language_framework="TypeScript" ``` **Key Benefits:** - **Structural Intelligence**: Automatic execution routing based on file structure analysis - **Dynamic Capability Building**: Extend AI assistant capabilities through conversational management - **Minimal Configuration**: Execution type detection requires no manual setup - **Systematic Workflow**: Integrated creation, routing, and framework application - **Intelligent Command Routing**: Built-in command detection with multi-strategy parsing - **Methodology Integration**: Four thinking frameworks (CAGEERF, ReACT, 5W1H, SCAMPER) with conditional application ## Framework System The server implements a sophisticated methodology system that applies structured thinking frameworks to AI interactions: ### Available Methodologies - **CAGEERF**: Comprehensive structured approach (Context, Analysis, Goals, Execution, Evaluation, Refinement, Framework) - **ReACT**: Reasoning and Acting pattern for systematic problem-solving - **5W1H**: Who, What, When, Where, Why, How systematic analysis - **SCAMPER**: Creative problem-solving (Substitute, Combine, Adapt, Modify, Put to other uses, Eliminate, Reverse) ### Framework Features - **Manual Selection**: Choose optimal methodology based on specific needs - **Runtime Switching**: Change active framework with performance monitoring - **Conditional Application**: Framework enhancement applied when beneficial - **Performance Monitoring**: Track framework switching mechanics and usage ```bash # Switch methodology for different approaches system_control switch_framework framework="ReACT" reason="Problem-solving focus" # Monitor framework performance and usage system_control analytics show_details=true # Get current framework status system_control status ``` **Result**: Structured, systematic AI conversations through proven thinking methodologies. ### Analysis System Capabilities **Core Analysis Functions:** - **Structural Analysis**: Detects execution type by examining template variables (`{{variable}}`), chain steps, and file structure - **Framework Application**: Applies selected framework methodology based on execution tier - **Routing Logic**: Routes to appropriate execution tier (prompt/template/chain) based on structural characteristics **Optional Semantic Enhancement:** - **LLM Integration**: When enabled, provides semantic understanding of prompt content - **Advanced Analysis**: Methodology recommendations and complexity assessment - **Default Mode**: Structural analysis only (no LLM dependency) **Framework Control:** ```bash # Manual framework selection system_control switch_framework framework="ReACT" reason="Problem-solving focus" ``` ## Architecture & Reliability ### Developer Experience - **One-Command Installation**: Complete setup in under 60 seconds - **Hot-Reload System**: Update prompts, configs, and templates without restart - **Rich Template Engine**: Nunjucks with conditionals, loops, and data injection - **Universal MCP Integration**: Works with Claude Desktop, Cursor Windsurf, and any MCP client - **Multi-Transport Support**: STDIO for desktop + SSE/REST for web - **Dynamic Management**: Update, delete, and reload prompts on-the-fly ### Enterprise Architecture - **Orchestrated Startup**: Phased initialization with dependency management - **Error Handling**: Graceful degradation with comprehensive logging - **Health Monitoring**: Real-time module status, performance metrics, diagnostics - **Environment Detection**: Automatic adaptation for development and production - **Modular Design**: Extensible architecture for custom workflows - **Security**: Input validation, sanitization, and error boundaries ### Consolidated MCP Tools (3 Tools) - **prompt_engine**: Universal execution with intelligent analysis and chain coordination - **prompt_manager**: Complete lifecycle management with smart filtering and gate management - **system_control**: Framework management, analytics, and system administration ### Intelligent Features - **Structural Type Detection**: Automatic routing between prompt/template/chain execution - **Framework Integration**: Four methodologies with manual selection and conditional injection - **LLM-Driven Chains**: Step-by-step workflow coordination with state management - **Performance Analytics**: Three-tier execution monitoring with framework switching tracking - **Smart Argument Parsing**: JSON objects, single arguments, or conversational context ## Quick Start Get the server running in under a minute: ```bash # Clone, install, build, and start git clone https://github.com/minipuft/claude-prompts-mcp.git cd claude-prompts-mcp/server && npm install && npm run build && npm start ``` ### MCP Client Integration #### Claude Desktop Drop this into your `claude_desktop_config.json`: ```json { "mcpServers": { "claude-prompts-mcp": { "command": "node", "args": ["E:\\path\\to\\claude-prompts-mcp\\server\\dist\\index.js"], "env": { "MCP_PROMPTS_CONFIG_PATH": "E:\\path\\to\\claude-prompts-mcp\\server\\prompts\\promptsConfig.json" } } } } ``` #### Cursor Windsurf & Other MCP Clients Configure your MCP client to connect via STDIO transport: - **Command**: `node` - **Args**: `["path/to/claude-prompts-mcp/server/dist/index.js"]` - **Environment** (Optional): `MCP_PROMPTS_CONFIG_PATH=path/to/prompts/promptsConfig.json` #### Claude Code CLI Installation For Claude Code CLI users: ```bash claude mcp add-json claude-prompts-mcp '{"type":"stdio","command":"node","args":["path/to/claude-prompts-mcp/server/dist/index.js"],"env":{}}' ``` ### Usage Examples Start using the server immediately: ```bash # Discover prompts with intelligent filtering prompt_manager list filter="category:analysis" # Execute prompts with automatic type detection prompt_engine >>friendly_greeting name="Developer" # Analyze content with framework enhancement prompt_engine >>content_analysis input="research data" # Run multi-step LLM-driven chains prompt_engine >>code_review_optimization_chain target_code="..." language_framework="TypeScript" # Monitor system performance system_control analytics include_history=true # Create new prompts conversationally "Create a prompt called 'bug_analyzer' that finds and explains code issues" # Refine existing prompts "Make the bug_analyzer prompt also suggest performance improvements" # Reference existing chain prompts # Example chains available: code_review_optimization_chain, create_docs_chain, video_notes_enhanced # Manual control when needed prompt_engine >>content_analysis input="sensitive data" step_confirmation=true gate_validation=true ``` The system provides a structured approach to prompt management through systematic methodology application. ## Key Features ### Lightning-Fast Hot-Reload The orchestration engine monitors files and reloads everything seamlessly: ```bash # Edit any prompt file → Server detects → Reloads automatically → Zero downtime ``` - **Instant Updates**: Change templates, arguments, descriptions in real-time - **Zero Restart Required**: Advanced hot-reload system keeps everything running - **Smart Dependency Tracking**: Only reloads what actually changed - **Graceful Error Recovery**: Invalid changes don't crash the server ### Advanced Template Engine Nunjucks-powered dynamic prompts with full templating capabilities: ```nunjucks Analyze {{content}} for {% if focus_area %}{{focus_area}}{% else %}general{% endif %} insights. {% for requirement in requirements %} - Consider: {{requirement}} {% endfor %} {% if previous_context %} Build upon: {{previous_context}} {% endif %} ``` - **Conditional Logic**: Smart prompts that adapt based on input - **Loops & Iteration**: Handle arrays and complex data structures - **Template Inheritance**: Reuse and extend prompt patterns - **Real-Time Processing**: Templates render with live data injection ### Performance Forward Orchestration Multi-phase startup with comprehensive health monitoring: ```typescript Phase 1: Foundation → Config, logging, core services Phase 2: Data Loading → Prompts, categories, validation Phase 3: Module Init → Tools, executors, managers Phase 4: Server Launch → Transport, API, diagnostics ``` - **Dependency Management**: Modules start in correct order with validation - **Health Monitoring**: Real-time status of all components - **Performance Metrics**: Memory usage, uptime, connection tracking - **Diagnostic Tools**: Built-in troubleshooting and debugging ### Intelligent Prompt Chains Multi-step workflows implemented as LLM-driven instruction sequences embedded in markdown templates: #### LLM-Driven Chain Format (Primary Method) Chains are defined directly in markdown files using step headers that guide Claude through a systematic process: ```markdown # Comprehensive Code Review ## User Message Template **Target Code**: {{target_code}} **Language/Framework**: {{language_framework}} This chain performs a systematic 6-step code review: ## Step 1: Structure & Organization Analysis Analyze code architecture, organization, patterns, naming conventions... **Output Required**: Structural assessment with identified patterns. --- ## Step 2: Functionality & Logic Review Examine business logic correctness, edge cases, error handling... **Output Required**: Logic validation with edge case analysis. --- ## Step 3: Security & Best Practices Audit Review for security vulnerabilities: input validation, authentication... **Output Required**: Security assessment with vulnerability identification. ``` **Key Features:** - **LLM-Driven Execution**: Claude follows step-by-step instructions embedded in the template - **Context Preservation**: Each step builds on previous outputs naturally - **Flexible Structure**: Steps can include conditional logic and branching - **Framework Integration**: Automatically enhanced with active methodology (CAGEERF/ReACT) #### Modular Chain Format (Alternative) For chains that orchestrate multiple reusable prompts, use the markdown-embedded format: ```markdown ## Chain Steps 1. promptId: extract_key_points stepName: Extract Key Points inputMapping: content: original_content outputMapping: key_points: extracted_points 2. promptId: sentiment_analysis stepName: Analyze Sentiment inputMapping: text: extracted_points outputMapping: sentiment: analysis_result ``` **Capabilities:** - **Prompt Reuse**: Chain together existing prompts - **Data Flow Mapping**: Explicit input/output variable mapping - **Gate Integration**: Apply quality gates at each step - **Error Recovery**: Graceful handling of failed steps **Real Examples**: See working chain implementations: - `server/prompts/development/code_review_optimization_chain.md` - 6-step code review workflow - `server/prompts/documentation/create_docs_chain.md` - Documentation generation chain - `server/prompts/content_processing/video_notes_enhanced.md` - Video analysis workflow ## System Architecture ```mermaid graph TB A[Claude Desktop] -->|MCP Protocol| B[Transport Layer] B --> C[🧠 Orchestration Engine] C --> D[📝 Prompt Manager] C --> E[🛠️ MCP Tools Manager] C --> F[⚙️ Config Manager] D --> G[🎨 Template Engine] E --> H[🔧 Management Tools] F --> I[🔥 Hot Reload System] style C fill:#ff6b35 style D fill:#00ff88 style E fill:#0066cc ``` ## MCP Client Compatibility This server implements the Model Context Protocol (MCP) standard and works with any compatible client: ### Tested & Verified Clients - **Claude Desktop**: Full integration support - **Cursor Windsurf**: Native MCP compatibility - **Claude Code**: Full native support ### Transport Support - **STDIO**: Primary transport for desktop clients - **Server-Sent Events (SSE)**: Web-based clients and integrations - **HTTP Endpoints**: Basic endpoints for health checks and data queries ### Integration Features - **Auto-Discovery**: Clients detect tools automatically - **Tool Registration**: Dynamic capability announcement - **Hot Reload**: Changes appear instantly in clients - **Error Handling**: Graceful degradation across clients **Note**: As MCP adoption grows, this server will work with any new MCP-compatible AI assistant or development environment without modification. ## Configuration ### Server Configuration (`config.json`) Fine-tune your server's behavior: ```json { "server": { "name": "Claude Custom Prompts MCP Server", "version": "1.0.0", "port": 9090 }, "prompts": { "file": "promptsConfig.json", "registrationMode": "name" }, "transports": { "default": "stdio", "sse": { "enabled": false }, "stdio": { "enabled": true } } } ``` ### Prompt Organization (`promptsConfig.json`) Structure your AI command library: ```json { "categories": [ { "id": "development", "name": "🔧 Development", "description": "Code review, debugging, and development workflows" }, { "id": "analysis", "name": "📊 Analysis", "description": "Content analysis and research prompts" }, { "id": "creative", "name": "🎨 Creative", "description": "Content creation and creative writing" } ], "imports": [ "prompts/development/prompts.json", "prompts/analysis/prompts.json", "prompts/creative/prompts.json" ] } ``` ## Advanced Features ### Multi-Step Prompt Chains Build sophisticated AI workflows using two complementary approaches: #### LLM-Driven Chains (Recommended) The primary method uses step-by-step instructions embedded directly in markdown templates. Claude executes each step systematically while maintaining context: ```markdown # Research Analysis Chain ## User Message Template Research {{topic}} and provide {{analysis_type}} analysis. ## Step 1: Initial Research Gather comprehensive information about {{topic}} from available sources. Focus on {{analysis_type}} perspectives. **Output Required**: Research summary with key findings. --- ## Step 2: Extract Key Insights From the research findings, identify the most relevant insights. Organize by importance and relevance to {{analysis_type}} analysis. **Output Required**: Prioritized list of insights with supporting evidence. --- ## Step 3: Analyze Patterns Examine the extracted insights for patterns, trends, and relationships. Consider multiple analytical frameworks. **Output Required**: Pattern analysis with framework comparisons. --- ## Step 4: Synthesize Report Create comprehensive report combining all findings. **Output Required**: Structured report with executive summary. ``` **Benefits:** - **Natural Flow**: Claude maintains context automatically across steps - **Flexible Logic**: Steps can include conditional branching and decision points - **Framework Enhanced**: Automatically augmented with active methodology (CAGEERF/ReACT) - **Clear Outputs**: Each step specifies required deliverables #### Modular Prompt Chains (Alternative) For orchestrating multiple reusable prompts with explicit data flow: ```markdown ## Chain Steps 1. promptId: research_topic stepName: Initial Research inputMapping: query: topic outputMapping: findings: research_data 2. promptId: extract_insights stepName: Extract Key Insights inputMapping: content: research_data outputMapping: insights: key_findings 3. promptId: analyze_patterns stepName: Analyze Patterns inputMapping: data: key_findings outputMapping: analysis: pattern_results 4. promptId: generate_report stepName: Synthesize Report inputMapping: insights: key_findings patterns: pattern_results outputMapping: report: final_output ``` **Capabilities:** - **Prompt Reuse**: Leverage existing prompts as chain building blocks - **Explicit Data Flow**: Clear input/output mapping between steps - **Error Recovery**: Graceful handling of failed steps with retry logic - **Gate Validation**: Apply quality gates at each step for validation **Real Examples**: View production chain implementations: - `server/prompts/content_processing/noteIntegration.md` - Note processing with modular steps - Review the `## Chain Steps` section in any chain prompt for complete syntax ### Advanced Template Features Leverage the full power of Nunjucks templating: ```nunjucks # {{ title | title }} Analysis ## Context {% if previous_analysis %} Building upon previous analysis: {{ previous_analysis | summary }} {% endif %} ## Requirements {% for req in requirements %} {{loop.index}}. **{{req.priority | upper}}**: {{req.description}} {% if req.examples %} Examples: {% for ex in req.examples %}{{ex}}{% if not loop.last %}, {% endif %}{% endfor %} {% endif %} {% endfor %} ## Focus Areas {% set focus_areas = focus.split(',') %} {% for area in focus_areas %} - {{ area | trim | title }} {% endfor %} ``` **Template Features:** - **Filters & Functions**: Transform data on-the-fly - **Conditional Logic**: Smart branching based on input - **Loops & Iteration**: Handle complex data structures - **Template Inheritance**: Build reusable prompt components ### Real-Time Management Tools Manage your prompts dynamically while the server runs: ```bash # Update prompts with intelligent re-analysis prompt_manager update id="analysis_prompt" content="new template" # Modify specific sections with validation prompt_manager modify id="research" section="examples" content="new examples" # Hot-reload with comprehensive validation system_control reload reason="updated templates" ``` **Management Capabilities:** - **Live Updates**: Change prompts without server restart - **Section Editing**: Modify specific parts of prompts - **Bulk Operations**: Update multiple prompts at once - **Rollback Support**: Undo changes when things go wrong ### Production Monitoring Enterprise-grade observability: Built-in monitoring and diagnostics for production environments: ```typescript // Health Check Response { healthy: true, modules: { foundation: true, dataLoaded: true, modulesInitialized: true, serverRunning: true }, performance: { uptime: 86400, memoryUsage: { rss: 45.2, heapUsed: 23.1 }, promptsLoaded: 127, categoriesLoaded: 8 } } ``` **Monitoring Features:** - **Real-Time Health Checks**: All modules continuously monitored - **Performance Metrics**: Memory, uptime, connection tracking - **Diagnostic Tools**: Comprehensive troubleshooting information - **Error Tracking**: Graceful error handling with detailed logging ## Documentation | Guide | Description | | ------------------------------------------------------ | --------------------------------------------------------------- | | [Installation Guide](docs/installation-guide.md) | Complete setup walkthrough with troubleshooting | | [Troubleshooting Guide](docs/troubleshooting.md) | Common issues, diagnostic tools, and solutions | | [Architecture Overview](docs/architecture.md) | Deep dive into the orchestration engine, modules, and data flow | | [Prompt Format Guide](docs/prompt-format-guide.md) | Master prompt creation including chain workflows | | [Prompt Management](docs/prompt-management.md) | Dynamic management and hot-reload features | | [MCP Tools Reference](docs/mcp-tools-reference.md) | Complete MCP tools documentation | | [Roadmap & TODO](docs/TODO.md) | Planned features and development roadmap | | [Contributing](docs/contributing.md) | Join our development community | ## Contributing Join our development community: - **Found a bug?** [Open an issue](https://github.com/minipuft/claude-prompts-mcp/issues) - **Have an idea?** [Start a discussion](https://github.com/minipuft/claude-prompts-mcp/discussions) - **Want to contribute?** Check our [Contributing Guide](docs/contributing.md) - **Need help?** Visit our [Documentation](docs/README.md) ## License Released under the [MIT License](LICENSE) - see the file for details. --- <div align="center"> **Star this repo if it's improving your AI workflow** [Report Bug](https://github.com/minipuft/claude-prompts-mcp/issues) • [Request Feature](https://github.com/minipuft/claude-prompts-mcp/issues) • [View Docs](docs/README.md) _Built for the AI development community_ </div> ``` -------------------------------------------------------------------------------- /agent.md: -------------------------------------------------------------------------------- ```markdown # Agent Rules · Claude Prompts MCP Read this file at session start. Treat every rule as mandatory unless the user explicitly overrides it. ## Mission & Scope - **Role**: Automation/code-editing agent for the Claude Prompts MCP server repository (`claude-prompts-mcp`). - **Objective**: Deliver safe, reversible changes that respect MCP protocol guardrails and documented workflows. - **Hierarchy**: This file embeds global principles, domain conventions, and project-specific rules. No other rule files are loaded. ## Operating Principles (Global Layer) - **Plan-first mindset** → Outline intent, affected areas, and validation before implementing changes; keep the plan updated as work progresses. - **Protocol alignment** → Honor Model Context Protocol workflows and documented abstractions; prefer official tools/scripts over ad-hoc commands. - **Transparent reasoning** → Surface assumptions, blockers, and risks early; record skipped validations with justification. - **Reversibility** → Make small, reviewable diffs; avoid destructive operations without explicit user approval. - **Constraint awareness** → Respect sandbox/approval requirements, escalate instead of bypassing safeguards. ## Domain Guidance (Node.js + TypeScript MCP Stack) - Use Node.js 16+ and TypeScript in strict mode; maintain ES module syntax. - Keep code hot-reload friendly: prefer pure functions, dependency injection, and descriptive interfaces. - Follow Jest testing patterns; ensure new modules are testable and covered when practical. - Maintain compatibility with the multi-platform CI matrix (Ubuntu, macOS, Windows) and Node 16/18/20. - Avoid introducing unmanaged global state or side effects that could break STDIO/SSE transports. ## Project-Specific Guardrails - **MCP Tool Usage**: NEVER edit prompt/template/chain files directly. Interact via `prompt_manager`, `prompt_engine`, or `system_control` MCP tools. If direct modification is unavoidable, call it out and justify thoroughly. - **Hot-Reload Integrity**: Preserve registry synchronization; do not bypass the hot-reload manager or caches unless documented. - **Enhanced Gate System**: Respect five-level precedence (temporary → template → category → framework → fallback). Keep JSON definitions and TypeScript schemas synchronized. - **Framework Methodologies**: Document rationale when switching between CAGEERF, ReACT, 5W1H, and SCAMPER. Runtime selections persist in `server/runtime-state/framework-state.json`. - **Transport Parity**: Ensure changes remain compatible with both STDIO and SSE transports; run targeted smoke checks when touching transport logic. ## Task Workflow (Repeatable Loop) 1. **Discover**: Clarify scope with the user; inspect relevant sources (`CLAUDE.md`, `docs/*.md`, code modules) before editing. 2. **Design**: Outline approach, list affected files, and determine required validation commands or MCP tool operations. 3. **Implement**: Apply minimal, focused edits; keep formatting, linting, and typing consistent; update documentation if behavior changes. 4. **Validate**: Run appropriate scripts (`npm run typecheck`, `npm test`, `npm run validate:all`, targeted diagnostics). If skipped, explain why and assess risk. 5. **Document**: Summarize changes, highlight risks/gaps, suggest next steps, and note validations performed or skipped. ## Code Editing Playbooks - **TypeScript Modules**: Maintain strict typing; avoid ambient state; prefer descriptive interfaces and enums for shared contracts. - **Prompt & Chain Logic**: Route adjustments through MCP tools; confirm schema updates in `server/src/mcp-tools` and related validators. - **Gate System Changes**: Update definitions under `server/src/gates/` and supporting JSON; ensure precedence logic in `temporary-gate-registry`, `gate-state-manager`, and `category-extractor` stays coherent. - **Transport / Runtime**: Touching `server/src/runtime` or transport layers requires smoke tests via `npm run start:stdio` and `npm run start:sse`; avoid noisy logs in production paths. - **Configuration**: When editing `config/*.json` or `server/config*.json`, validate with `npm run validate:all` and confirm default values stay backwards compatible. ## Tooling & Command Reference - Build: `npm run build` - Type Check: `npm run typecheck` - Tests: `npm test` - CI parity: `npm run test:ci`, `npm run validate:all` - Dev watch: `npm run dev` - Diagnostics: `npm run start:verbose`, `npm run start:debug` - Transports: `npm run start:stdio`, `npm run start:sse`, `npm run start:production` ## Validation Expectations - Run type checks and relevant tests when altering execution paths, schemas, or TypeScript types. - Use targeted diagnostics for MCP tools, gate logic, and framework behavior when affected. - Document skipped validations with impact assessment and recommended follow-up. ## Safety & Escalation Checklist - Confirm with the user before scope jumps or potentially breaking changes. - Seek approval before destructive git or filesystem operations not explicitly requested. - Stop immediately and ask for guidance if unexpected repo changes appear or sandbox constraints block required workflows. - Keep track of lingering risks, TODOs, or follow-up items; store context in `plans/` when long-running work is needed. ## Documentation Map (Reference Only) - `CLAUDE.md` (historical global rules and context) - `docs/mcp-tool-usage-guide.md` - `docs/mcp-tools-reference.md` - `docs/architecture.md` - `docs/prompt-management.md` - `docs/enhanced-gate-system.md` - `docs/troubleshooting.md` - `docs/version-history.md` ## Session Closeout - Ensure working tree cleanliness or clearly communicate outstanding diffs. - Provide concise final response: change summary, validations run/skipped, risks, and recommended next steps. - Default to suggesting verification commands when you cannot run them yourself. ``` -------------------------------------------------------------------------------- /docs/contributing.md: -------------------------------------------------------------------------------- ```markdown # Contributing Guidelines Thank you for your interest in contributing to the Claude Prompts MCP Server! This document provides guidelines and instructions for contributing to this powerful Model Context Protocol server. ## Code of Conduct Please be respectful and considerate of others when contributing to this project. We aim to foster an inclusive and welcoming community for developers working with AI prompt engineering and MCP servers. ## Getting Started 1. Fork the repository on GitHub 2. Clone your fork locally 3. Set up the development environment as described below 4. Create a new branch for your changes ## Development Process ### Setting Up the Development Environment ```bash # Clone your fork git clone https://github.com/your-username/claude-prompts-mcp.git cd claude-prompts-mcp # Install server dependencies cd server npm install # Build the server npm run build # Start in development mode with hot-reload npm run dev ``` ### Project Structure ``` claude-prompts-mcp/ ├── server/ # Main MCP server │ ├── src/ # TypeScript source code │ │ ├── orchestration/ # Application orchestration and startup │ │ ├── mcp-tools/ # MCP tool implementations │ │ ├── prompts/ # Prompt management system │ │ ├── api/ # REST API endpoints (SSE transport) │ │ ├── config/ # Configuration management │ │ ├── logging/ # Logging system │ │ ├── transport/ # Transport layer (STDIO/SSE) │ │ ├── types/ # TypeScript type definitions │ │ └── utils/ # Utility functions │ ├── prompts/ # Distributed prompt configuration │ │ └── examples/ # Example prompts │ ├── dist/ # Compiled JavaScript output │ ├── config.json # Server configuration │ ├── promptsConfig.json # Main prompts configuration │ └── package.json # Node.js dependencies ├── docs/ # Documentation └── README.md # Project overview ``` ## Making Changes ### Server Development The server is built with Node.js, Express, and TypeScript, using a sophisticated orchestration system. Key areas for contribution: **Core Systems:** - `src/orchestration/index.ts` - Application orchestration and lifecycle management - `src/mcp-tools/index.ts` - MCP tool registration and implementation - `src/prompts/index.ts` - Prompt management and template processing - `src/api/index.ts` - REST API for SSE transport mode **Configuration System:** - `config.json` - Server configuration - `promptsConfig.json` - Main prompts configuration with category imports - `prompts/*/prompts.json` - Category-specific prompt definitions When making changes to the server: 1. **Follow TypeScript Best Practices**: Use proper type definitions and interfaces 2. **Maintain the Orchestration Pattern**: Respect the phased startup sequence 3. **Add Comprehensive Error Handling**: Use the existing error handling patterns 4. **Update Tests**: Add or update tests for new functionality 5. **Document Changes**: Update relevant documentation ### Prompt Development The server uses a distributed prompt configuration system: **Adding New Prompts:** 1. Choose or create a category in `prompts/` 2. Add your prompt markdown file to the category directory 3. Register the prompt in the category's `prompts.json` file 4. Test the prompt using the MCP tools **Creating New Categories:** 1. Create a new directory under `prompts/` 2. Create a `prompts.json` file in the directory 3. Add the category to `promptsConfig.json` 4. Add the import path to the imports array **Prompt Format Guidelines:** - Use clear, descriptive markdown format - Define all arguments with proper descriptions - Include system messages when appropriate - Test with various input scenarios ### Documentation Updates Documentation is written in Markdown and stored in the `docs/` directory. When updating documentation: 1. **Keep It Accurate**: Ensure all examples and references match the actual codebase 2. **Use Clear Examples**: Provide practical, working examples 3. **Update Cross-References**: Check for broken internal links 4. **Follow the Style Guide**: Maintain consistency with existing documentation ## Testing ### Server Tests ```bash cd server npm test ``` ### Manual Testing with Claude Desktop 1. Build the server: `npm run build` 2. Update your `claude_desktop_config.json` to point to your development build 3. Restart Claude Desktop 4. Test your changes using the `>>` or `/` command syntax ### Prompt Testing Test prompts using the built-in MCP tools: ```bash # List all available prompts >>listprompts # Test a specific prompt >>your_prompt_id argument="test value" # Test with JSON arguments >>complex_prompt {"arg1": "value1", "arg2": "value2"} ``` ## Pull Request Process 1. **Create a Feature Branch**: Create a descriptive branch name 2. **Make Focused Changes**: Keep PRs focused on a single feature or bug fix 3. **Write Clear Commit Messages**: Use descriptive commit messages 4. **Test Thoroughly**: Ensure all tests pass and manual testing is complete 5. **Update Documentation**: Update relevant documentation 6. **Submit the PR**: Include a clear description of changes and their purpose ### Pull Request Guidelines - **Clear Descriptions**: Explain what the PR does and why - **Link Related Issues**: Reference any related GitHub issues - **Include Examples**: Show how new features work - **Breaking Changes**: Clearly mark any breaking changes - **Performance Impact**: Note any performance implications ## Code Style and Standards ### TypeScript Standards - **Strict Type Checking**: Use TypeScript's strict mode - **Interface Definitions**: Create interfaces for complex data structures - **Proper Error Handling**: Use typed error handling patterns - **Documentation**: Add JSDoc comments for public APIs ### Code Organization - **Modular Architecture**: Follow the existing module structure - **Separation of Concerns**: Keep different functionalities in separate modules - **Dependency Injection**: Use the orchestration pattern for module dependencies - **Configuration-Driven**: Make features configurable when appropriate ### Naming Conventions - **Files**: Use kebab-case for file names (`prompt-manager.ts`) - **Classes**: Use PascalCase (`ApplicationOrchestrator`) - **Functions**: Use camelCase (`loadAndConvertPrompts`) - **Constants**: Use UPPER_SNAKE_CASE (`CONFIG_FILE`) ## Architecture Guidelines ### MCP Server Development When extending the MCP server: 1. **Use the Orchestration System**: Register new modules through the orchestrator 2. **Implement Health Checks**: Add health monitoring for new components 3. **Support Hot-Reload**: Ensure new features work with the hot-reload system 4. **Handle Multiple Transports**: Consider both STDIO and SSE transport modes ### Prompt System Development When extending the prompt system: 1. **Maintain Backward Compatibility**: Don't break existing prompt formats 2. **Use Nunjucks Templates**: Leverage the advanced templating features 3. **Support Text References**: Handle long content through the reference system 4. **Validate Input**: Use Zod or similar for input validation ## Performance Considerations - **Memory Usage**: Be mindful of memory consumption in long-running processes - **Hot-Reload Efficiency**: Ensure changes don't unnecessarily reload the entire system - **Template Processing**: Optimize template rendering for frequently-used prompts - **Error Recovery**: Implement graceful error recovery for robust operation ## Security Guidelines - **Input Validation**: Validate all user inputs using proper schemas - **Path Traversal**: Prevent directory traversal attacks in file operations - **Error Information**: Don't leak sensitive information in error messages - **Configuration Security**: Handle sensitive configuration data appropriately ## Versioning We use [Semantic Versioning](https://semver.org/): - **MAJOR**: Incompatible API changes or breaking prompt format changes - **MINOR**: New functionality in a backward-compatible manner - **PATCH**: Backward-compatible bug fixes ## Release Process 1. Update version numbers in `package.json` 2. Update the changelog 3. Create a release branch 4. Test the release thoroughly 5. Create a GitHub release with proper release notes ## Reporting Issues When reporting issues, please include: 1. **Clear Description**: Describe the issue clearly and concisely 2. **Reproduction Steps**: Provide step-by-step reproduction instructions 3. **Expected vs Actual**: Clearly state expected and actual behavior 4. **Environment Details**: Include OS, Node.js version, and Claude Desktop version 5. **Logs and Screenshots**: Attach relevant logs or screenshots 6. **Minimal Example**: Provide a minimal example that reproduces the issue ## Feature Requests Feature requests should include: 1. **Use Case Description**: Explain the real-world problem being solved 2. **Proposed Solution**: Describe your proposed approach 3. **Alternatives Considered**: Mention alternative solutions you've considered 4. **Implementation Ideas**: Share any implementation thoughts ## Community - **GitHub Issues**: For bug reports and feature requests - **GitHub Discussions**: For general questions and community discussion - **Pull Requests**: For code contributions and improvements ## Getting Help If you need help while contributing: 1. Check the documentation in the `docs/` directory 2. Look for similar issues or PRs in the GitHub repository 3. Ask questions in GitHub Discussions 4. Review the codebase for patterns and examples ## Recognition We appreciate all contributions to the project! Contributors will be: - Listed in the project contributors - Acknowledged in release notes for significant contributions - Invited to help shape the project's future direction ## License By contributing to this project, you agree that your contributions will be licensed under the project's MIT License. --- Thank you for contributing to the Claude Prompts MCP Server! Your contributions help make AI prompt engineering more powerful and accessible for developers worldwide. 🚀 ``` -------------------------------------------------------------------------------- /CLAUDE.md: -------------------------------------------------------------------------------- ```markdown # Claude Prompts MCP - Global Rules Integration ## 🔗 Global Rules System Integration @include ~/.claude/CLAUDE.md#Rule_Loading_Hierarchy **Detected Context**: Node.js TypeScript MCP Server Project **Active Domain Rules**: JAVASCRIPT.md (ES modules, TypeScript strict mode, Jest testing, Node.js patterns) **Project-Specific Rule Overrides**: - **MCP tool usage** → NEVER use direct file operations, ALWAYS use MCP tools - **Framework switching** → Use methodology guides as single source of truth - **Hot-reload compatibility** → Maintain registry synchronization This file provides guidance to Claude Code (claude.ai/code) when working with this Model Context Protocol (MCP) server repository. ## Build and Development Commands ### Essential Commands - **Build**: `npm run build` - Compiles TypeScript to JavaScript in `dist/` - **Type Check**: `npm run typecheck` - Validates TypeScript types without compilation - **Start**: `npm start` - Runs the compiled server from `dist/index.js` - **Development**: `npm run dev` - Watches TypeScript files and restarts on changes - **Test**: `npm test` - Runs the test server using `../test_server.js` ### Transport-Specific Commands - **STDIO Transport**: `npm run start:stdio` - For MCP clients like Claude Desktop - **SSE Transport**: `npm run start:sse` - For web-based clients - **Production**: `npm run start:production` - Quiet mode with STDIO transport - **Development**: `npm run start:development` - Verbose mode with SSE transport ### Debugging Commands - **Verbose Mode**: `npm run start:verbose` - Detailed diagnostics and strategy information - **Debug Startup**: `npm run start:debug` - Extra debugging information - **Quiet Mode**: `npm run start:quiet` - Minimal output for production - **Help**: `npm run help` - Show command line options and environment variables ## ⚠️ CRITICAL: MCP Tool Usage Requirements **NEVER use direct file manipulation when working with this MCP server.** The server provides structured MCP tools that MUST be used instead. ### ❌ FORBIDDEN Operations - `Update()`, `Edit()`, `MultiEdit()`, `Write()` - Direct file operations - Direct modification of JSON files in `/prompts/` directories - Creating new prompt files manually - Bash commands that modify prompt files ### ✅ REQUIRED: Use MCP Tools - **prompt_manager** - All prompt/chain creation, modification, deletion - **system_control** - Server management, framework switching, analytics - **prompt_engine** - Prompt execution, chain operations, scaffolding **References**: - [MCP Tool Usage Guide](./docs/mcp-tool-usage-guide.md) - Complete tool documentation - [Chain Modification Examples](./docs/chain-modification-examples.md) - Step-by-step workflows **Example of CORRECT usage**: ```bash # Wrong: Update(~/prompts/chain.json) # Right: prompt_manager(action: "update", id: "chain_name", ...) # Wrong: Write(~/prompts/new_prompt.md) # Right: prompt_manager(action: "create", id: "new_prompt", ...) ``` **Why this matters**: Direct file operations bypass MCP protocol compliance, break hot-reloading, cause registry desynchronization, and lead to "no structured content provided" errors. ## CI/CD Pipeline ### GitHub Actions Workflows The project uses GitHub Actions for automated testing and validation: #### Main CI Pipeline (`.github/workflows/ci.yml`) - **Triggers**: Push to `main`/`develop` branches, Pull Requests to `main` - **Matrix Testing**: Node.js versions 16, 18, 20 across Ubuntu, Windows, macOS - **Validation Steps**: TypeScript checking, build validation, test execution, server startup - **CAGEERF Integration**: Validates all CAGEERF framework modules compile and load - **Artifacts**: Uploads build artifacts for successful Ubuntu + Node 18 builds #### PR Validation (`.github/workflows/pr-validation.yml`) - **Triggers**: Pull request events (opened, synchronized, reopened) - **Quality Gates**: TypeScript, build, tests, CAGEERF validation, MCP tools validation - **Feedback**: Automated PR comments with validation results and changed files analysis - **Compatibility**: Checks for breaking changes when targeting main branch ### Quality Gates - **Mandatory**: TypeScript compilation, build success, test passing, server startup - **CAGEERF Validation**: All analyzer modules, template tools, and MCP integrations - **Code Quality**: No sensitive files, proper TypeScript structure, dependency consistency ## Nunjucks Dynamic Chain Orchestration Strategy ### Strategic Architecture Decision **Decision**: Keep Nunjucks template engine for dynamic chain orchestration capabilities. **Critical Discovery**: Nunjucks templates render on EACH chain step with access to previous step results, enabling powerful result-based conditional logic and adaptive prompt instructions. ### Chain Step Variable Access **How It Works**: ``` Step 1: analysis → Renders template with input variables → Outputs: {analysis: "...", confidence: 0.85} Step 2: validation → Renders template with: {analysis: "...", confidence: 0.85, threshold: 0.8} → Outputs: {score: 0.6, issues: [...]} Step 3: refinement → Renders template with: ALL previous outputs + new variables → Can use {% if score < 0.7 %} conditionals! ``` ### Capabilities Enabled **Result-Based Conditionals**: ```nunjucks {% if validation_score < 0.7 %} ⚠️ CRITICAL QUALITY ISSUES Apply aggressive refinement with citations... {% elif validation_score < 0.9 %} Moderate improvements needed... {% else %} Excellent quality - polish only... {% endif %} ``` **Quality-Driven Adaptation**: - Adjust instruction depth based on previous step quality - Customize approach based on validation results - Adapt error recovery based on failure types - Modify format based on content characteristics **Complexity-Based Branching**: ```nunjucks {% set complexity = sources|length + topics|length %} {% if complexity > 20 %} 🔥 MAXIMUM COMPLEXITY - Apply systematic framework... {% elif complexity > 10 %} ⚡ HIGH COMPLEXITY - Structured analysis... {% else %} 📊 STANDARD - Focus on key insights... {% endif %} ``` ### Implementation Guidelines **Best Practices**: 1. **Progressive Instruction Clarity**: More specific instructions as quality decreases 2. **Error Context Preservation**: Carry error context through recovery steps 3. **Metric-Driven Branching**: Use multiple quality metrics for nuanced decisions 4. **Accumulated State Tracking**: Reference outputs from multiple previous steps 5. **Self-Documenting Templates**: Make conditional logic clear and maintainable **Performance Considerations**: - Template rendering: <50ms per step - Variable substitution: ~1ms per 100 variables - Conditionals: ~0.5ms per condition - Templates cached in production (configured in jsonUtils.ts) **What Nunjucks CANNOT Do** (requires execution engine): - ❌ Change which prompt executes next (static chain definition) - ❌ Loop the same step (no recursive execution) - ❌ Dynamically select from prompt library (no runtime routing) ### Future Enhancements **Execution Engine Extensions** (beyond Nunjucks): - Dynamic step selection based on quality scores - Recursive step execution with quality thresholds - LLM-driven chain orchestration - Automatic quality gate enforcement **Reference**: See `/plans/nunjucks-dynamic-chain-orchestration.md` for comprehensive implementation strategy, patterns, and examples. ## Project Architecture ### Core System Structure This is a **Model Context Protocol (MCP) server** that provides AI prompt management with hot-reloading capabilities. The architecture follows a multi-phase orchestration pattern: 1. **Foundation Phase**: Configuration loading, logging setup, core services 2. **Data Loading Phase**: Prompt loading, category parsing, validation 3. **Module Initialization Phase**: Tools, executors, conversation managers 4. **Server Launch Phase**: Transport layer, API endpoints, health monitoring ### Key Components #### `/server/src/runtime/` - **Application Runtime** (`application.ts`) - Main entry point with comprehensive health monitoring and graceful shutdown - **Multi-phase startup** with dependency management and error recovery (Foundation → Data Loading → Module Initialization → Server Launch) - **Performance monitoring** with memory usage tracking and uptime metrics - **Startup orchestration** with strategy-based server detection #### `/server/src/frameworks/` - **Framework Manager** (`framework-manager.ts`) - Stateless framework orchestration, loads methodology guides and generates framework definitions - **Framework State Manager** (`framework-state-manager.ts`) - Stateful framework management, tracks active framework and handles switching - **Methodology Guides** (`adapters/`) - CAGEERF, ReACT, 5W1H, SCAMPER guides providing framework-specific guidance - **Framework Integration** (`integration/`) - Integration between frameworks and semantic analysis - **Framework Interfaces** (`interfaces/`) - Type definitions and contracts for framework system #### `/server/src/execution/` - **Execution Index** (`index.ts`) - Main execution orchestration and entry point - **Context Management** (`context/`) - Context resolution and framework injection - **Command Routing** (`routing/`) - Lightweight command routing optimized for LLM interactions - `command-router.ts` (149 lines) - Simple format detection and prompt resolution - `builtin-commands.ts` (52 lines) - Built-in command registry (listprompts, help, status, etc.) - Replaced legacy parsing system (1,354 lines) with 84% code reduction - **Execution Context** (`execution-context.ts`) - Type definitions for execution context - **Legacy Parsers** (`parsers/index.ts`) - Backwards compatibility exports (deprecated) - **Execution Types** (`types.ts`) - TypeScript interfaces for execution system #### `/server/src/gates/` - **Gate Definitions** (`definitions/`) - Gate definition templates and configurations - **Core Gates** (`core/`) - Core gate validation implementations and processors - **Gate Templates** (`templates/`) - Reusable gate template structures - **Main Index** (`index.ts`) - Gate system entry point and orchestration #### `/server/src/semantic/` - **Semantic Analysis Engine** - Automatic prompt type detection and analysis capabilities - **Integration Layer** (`integrations/`) - Framework and analysis system integration - **Analysis Types** - Type definitions for semantic analysis operations #### `/server/src/prompts/` - **Template processor** using Nunjucks with advanced features (conditionals, loops, macros) - **Prompt registry** for dynamic loading and hot-reloading - **Converter system** for format transformation and validation - **Hot-reload manager** - Supports dynamic prompt reloading without server restart - **Category manager** - Manages prompt organization and categorization #### `/server/src/mcp-tools/` - **Prompt Engine** (`prompt-engine.ts`) - Unified execution with intelligent analysis and semantic detection - **Prompt Manager** (`prompt-manager.ts`) - Complete lifecycle management with smart filtering and analysis - **System Control** (`system-control.ts`) - Framework management, analytics, and comprehensive system control - **Configuration & Error Handling** (`config-utils.ts`, `error-handler.ts`) - Centralized configuration and error management - **Advanced Filtering** (`filters/`) - Intelligent search and discovery capabilities - **Response Formatting** (`formatters/`) - Consistent MCP response formatting - **Validation System** (`validators/`) - Comprehensive input validation and schema checking - **Type Definitions** (`types/`) - TypeScript interfaces for MCP tool system #### `/server/src/performance/` - **Performance Monitor** (`monitor.ts`) - System performance tracking and metrics collection - **Memory Usage** - Memory monitoring and garbage collection optimization - **Startup Optimization** - Server startup time optimization and health monitoring #### `/server/src/metrics/` - **Usage Analytics** - Prompt usage patterns and execution metrics - **Performance Metrics** - System performance indicators and benchmarks - **Health Monitoring** - Server health status and diagnostic collection #### `/server/src/server/transport/` - **STDIO transport** for Claude Desktop integration - **SSE transport** for web-based clients - **Transport-aware logging** to avoid interference with STDIO protocol - **HTTP request processing and routing** for web-based clients - **WebSocket handlers** for real-time communication management ### Configuration System #### Main Configuration (`server/config.json`) - Server settings (name, version, port) - Transport configuration (STDIO/SSE) - Logging configuration (directory, level) - Prompts file reference pointing to `prompts/promptsConfig.json` #### Prompts Configuration (`server/prompts/promptsConfig.json`) - **Category organization** with logical grouping (18 categories including analysis, development, research, content_processing) - **Modular import system** using category-specific `prompts.json` files in `prompts/[category]/` directories - **Registration modes** (ID, NAME, or BOTH) with default NAME registration - **Dynamic imports** - categories are loaded from individual JSON files in subdirectories ### Prompt Organization #### File Structure ``` server/prompts/ ├── category-name/ │ ├── prompts.json # Category prompt registry │ ├── prompt-name.md # Individual prompt files │ └── ... └── promptsConfig.json # Main configuration ``` #### Prompt Format - **Markdown files** with structured sections - **Nunjucks templating** with `{{variable}}` syntax - **Argument definitions** with type information and validation - **Category association** for organization ### TypeScript Architecture #### Core Types (`src/types.ts`) - **Config interfaces** for application configuration - **PromptData** for prompt metadata and structure - **Message types** for conversation handling - **Transport types** for protocol abstraction #### Key Interfaces - `PromptData`: Complete prompt structure with metadata, arguments, and configuration - `PromptArgument`: Typed argument definitions with validation - `Category`: Prompt organization and categorization - `MessageContent`: Extensible content type system ### Framework System Architecture #### Methodology-Driven Design The core architecture is built around **methodology guides** that provide systematic approaches to prompt creation, processing, and execution. This replaces hard-coded framework logic with flexible, guideline-based behavior. #### Framework Components ##### Framework Manager (Stateless Orchestration) - **Location**: `/server/src/frameworks/framework-manager.ts` - **Purpose**: Loads methodology guides and dynamically generates framework definitions - **Key Functions**: - Initializes methodology guides (e.g CAGEERF, ReACT, 5W1H, SCAMPER) - Generates framework definitions from guide metadata - Creates execution contexts with framework-specific system prompts - Provides framework selection based on criteria ##### Framework State Manager (Stateful Management) - **Location**: `/server/src/frameworks/framework-state-manager.ts` - **Purpose**: Tracks active framework state and handles switching - **Key Functions**: - Maintains current active framework (default: CAGEERF) - Manages framework switching with validation and history - Provides health monitoring and performance metrics - Emits framework change events for system coordination ##### Methodology Guides - **Location**: `/server/src/frameworks/adapters/` - **Purpose**: Single source of truth for framework behavior - #### Framework Guide Interface Each methodology guide implements `IMethodologyGuide` with these capabilities: - **Prompt Creation Guidance**: Structure suggestions, argument recommendations, quality guidance - **Template Processing**: Framework-specific processing steps and enhancements - **Execution Steps**: Step-by-step guidance for applying the methodology - **Methodology Enhancement**: Quality gates and validation criteria - **Compliance Validation**: Checks prompt compliance with methodology principles #### Framework Selection & Switching - **Dynamic Selection**: Frameworks can be selected based on prompt complexity, execution type, and user preference - **Runtime Switching**: Active framework can be changed via MCP tools (`switch_framework`) - **State Persistence**: Framework state maintained across sessions with history tracking - **Performance Monitoring**: Tracks framework switching success rates and response times #### Integration Points ##### Semantic Analysis Integration - **Location**: `/server/src/frameworks/integration/framework-semantic-integration.ts` - **Purpose**: Coordinates semantic analysis results with framework selection - **Key Features**: - Uses semantic analysis to inform framework selection - Provides framework-specific execution contexts - Maintains separation between analysis (WHAT) and methodology (HOW) ##### Framework-Aware Gates - **Location**: `/server/src/gates/integration/framework-aware-gates.ts` - **Purpose**: Gate validation that adapts to active framework - **Key Features**: - Framework-specific validation criteria - Methodology-aware quality gates - Adaptive gate evaluation based on framework context ##### Framework Injection - **Location**: `/server/src/execution/processor/framework-injector.ts` - **Purpose**: Injects framework-specific guidance into execution context - **Key Features**: - Dynamic system prompt generation from methodology guides - Framework-enhanced template processing - Execution context augmentation with methodology guidance ### Execution Strategy Architecture #### Strategy Pattern Implementation The system uses the strategy pattern to handle different types of prompt execution: ##### Execution Engine - **Location**: `/server/src/execution/engine.ts` - **Purpose**: Orchestrates execution using appropriate strategy - **Key Functions**: - Strategy selection based on execution mode (prompt/chain/workflow) - Context management across execution phases - Error handling and recovery - Performance monitoring and logging ##### Execution Strategies - **Location**: `/server/src/execution/strategies/` - **Available Strategies**: - **Prompt Strategy**: Single prompt execution with framework injection - **Chain Strategy**: Sequential multi-step prompt execution with state management - **Workflow Strategy**: Complex workflow execution with gate validation and branching logic #### Template Processing Pipeline 1. **Template Loading**: Nunjucks template loaded from prompt definition 2. **Framework Injection**: Active methodology guide provides system prompt enhancements 3. **Variable Substitution**: User arguments processed through template 4. **Context Enhancement**: Framework-specific context added to execution 5. **Execution**: Strategy-appropriate execution with monitoring #### Conversation Management - **Location**: `/server/src/execution/conversation.ts` - **Purpose**: Manages conversation state across execution strategies - **Key Features**: - Message history tracking - Context preservation between steps - Framework-aware conversation enhancement - State persistence for long-running workflows ### Development Patterns #### Hot-Reloading System - **File watching** for prompt changes - **Registry updates** without server restart - **Template recompilation** on modification - **MCP client notification** of changes #### Error Handling - **Comprehensive error boundaries** at all levels - **Graceful degradation** for partial failures - **Health monitoring** with periodic validation - **Rollback mechanisms** for startup failures #### Template Processing - **Nunjucks engine** with full feature support - **Dynamic variable substitution** from arguments - **Conditional logic** and loops in templates - **Macro system** for reusable components ### MCP Integration #### Protocol Implementation - **Model Context Protocol SDK** integration - **Tool registration** for prompt management - **Conversation management** with state tracking - **Transport abstraction** for multiple client types #### Available MCP Tools (User Interface) The server exposes 3 consolidated MCP tools that users interact with: - **`prompt_engine`** - Execute prompts with intelligent analysis and semantic detection - **`prompt_manager`** - Create, update, delete, and manage prompts with smart filtering - **`system_control`** - Framework switching, analytics, health monitoring, and system management ### Performance Considerations #### Startup Optimization - **Strategy-based server detection** with early termination - **Environment variable bypass** for instant path detection - **Conditional logging** based on verbosity level - **Dependency management** with proper initialization order #### Runtime Performance - **Memory usage monitoring** with periodic reporting - **Health check validation** every 30 seconds - **Diagnostic collection** for troubleshooting - **Graceful shutdown** with resource cleanup ### Enhanced Systems #### Framework System Integration - **Methodology-driven architecture** with CAGEERF, ReACT, 5W1H, SCAMPER framework guides - **Dynamic framework switching** with runtime state management and performance monitoring - **Framework-aware quality gates** that adapt validation criteria based on active methodology - **Semantic analysis integration** for intelligent framework selection - **Framework injection system** for methodology-specific system prompt enhancement #### Execution Strategy System - **Strategy pattern implementation** with prompt, chain, and workflow execution strategies - **Execution engine orchestration** with context management and error recovery - **Template processing pipeline** with framework injection and Nunjucks template processing - **Conversation state management** with framework-aware conversation enhancement #### Gate Validation System - **Gate Registry** manages validation rules and quality gates with framework awareness - **Enhanced Gate Evaluators** with intelligent workflow validation and methodology-specific criteria - **Framework-aware gates** that adapt validation based on active framework context - **Multi-level validation** supporting validation, approval, condition, and quality gate types #### Advanced Analysis System - **Semantic Analyzer** for automatic prompt type detection and execution strategy recommendation - **Framework-semantic integration** coordinating analysis results with methodology selection - **Execution type detection** (prompt/chain/workflow) with framework-appropriate handling - **Quality assessment** with framework-specific validation criteria ### Key Development Guidelines - **Each functional area MUST have exactly ONE primary implementation** - **NEVER add new systems without explicit deprecation of old ones** ##### Dependency Direction Enforcement - **Establish clear architectural hierarchy** - lower layers cannot import from higher layers - **Bidirectional imports are STRICTLY FORBIDDEN** - **Example Fix Required**: `execution-coordinator.ts` ↔ `strategies/index.ts` circular import must be broken - **Use dependency injection or event patterns** instead of circular imports ##### Consolidation Over Addition Policy - **Strong preference for enhancing existing systems vs creating new ones** - **Question before coding**: "Can this functionality be added to an existing system?" - **Require architectural justification** for creating parallel systems - **Code reviews must verify no duplicate functionality is being introduced** #### Framework Development Rules ##### Methodology Guides as Single Source of Truth - **Never hard-code framework behavior** - All framework logic must come from methodology guides - **Methodology guides define framework identity** - `frameworkId`, `frameworkName`, `methodology` in guides - **Dynamic framework generation** - Framework definitions generated from guide metadata, not static configuration - **Guide-driven enhancements** - All framework-specific behavior (system prompts, quality gates, validation) comes from guide methods ##### Domain Cohesion Principles - **Framework logic belongs in `/frameworks`** - Keep all framework-related logic centralized - **Separate stateless from stateful** - Framework manager (stateless orchestration) separate from state manager (stateful tracking) - **Clear separation of concerns** - Analysis (WHAT the prompt needs) separate from methodology (HOW to approach it) - **Integration points are explicit** - Framework integration clearly defined in `/integration` directory ##### Methodology Guide Development - **Implement `IMethodologyGuide` interface** - All guides must follow the established contract - **Provide comprehensive guidance** - Implement all required methods: `guidePromptCreation`, `guideTemplateProcessing`, `guideExecutionSteps`, `enhanceWithMethodology`, `validateMethodologyCompliance` - **Framework-specific quality gates** - Each guide defines its own validation criteria and quality gates - **Template enhancement suggestions** - Guides provide specific suggestions for improving prompts - **Methodology validation** - Guides can validate prompt compliance with their methodology principles ##### Framework Integration Standards - **No direct framework coupling** - Other systems integrate through framework manager, not directly with guides - **Event-driven communication** - Framework state changes communicated through events - **Semantic analysis coordination** - Framework selection informed by, but not dependent on, semantic analysis - **Gate system integration** - Gates adapt to active framework but remain framework-agnostic in core logic #### Configuration Management - Use environment variables for path overrides (`MCP_SERVER_ROOT`, `MCP_PROMPTS_CONFIG_PATH`) - Maintain separation between server config and prompts config - Follow modular import patterns for prompt organization - Configure absolute paths for reliable Claude Desktop integration - #### Error Handling - Implement comprehensive error boundaries at all orchestration levels - Use structured logging with appropriate levels (supports both verbose and quiet modes) - Provide meaningful error messages with diagnostic information - Include rollback mechanisms for startup failures #### Testing - Test transport layer compatibility (STDIO and SSE) - Validate prompt template rendering with Nunjucks engine - Check hot-reloading functionality and workflow engine integration - Verify MCP protocol compliance and framework system validation - Test framework switching functionality and state persistence ### Environment Setup #### Required Environment Variables - `MCP_SERVER_ROOT`: Override server root directory detection (recommended for Claude Desktop) - `MCP_PROMPTS_CONFIG_PATH`: Direct path to prompts configuration file (bypasses server root detection) ## Project-Specific Development Integration ### MCP-Specific Development Standards **Project-Specific Requirements:** - **System Architecture Analysis**: Understand MCP server structure, framework system, and execution strategies - **Integration Point Mapping**: Components affected by changes (frameworks/, execution/, mcp-tools/, etc.) - **Performance Impact Assessment**: Baseline metrics and performance-sensitive areas for MCP protocol - **Client Compatibility Check**: Maintain Claude Desktop, web client, and MCP protocol compatibility **MCP Development Focus Areas:** - **Framework System**: Changes must work with all methodology guides - **Hot-Reload Compatibility**: File watching and registry updates for prompt management - **Multi-Transport Support**: Validate STDIO and SSE transport compatibility - **Command Routing System**: Lightweight routing optimized for LLM interactions (see Command Format Specification below) ### Command Format Specification The system uses a simplified CommandRouter (149 lines) optimized for LLM interactions, replacing the legacy parsing system (1,354 lines) with 84% code reduction. #### Supported Command Formats **1. Simple Format** (Most Common): ``` >>prompt_name arguments ``` **Examples**: ``` >>listprompts >>analyze_code function foo() { return bar; } >>code_review target_code="./src/app.ts" language_framework="TypeScript/React" ``` **2. JSON Format** (Structured Data): ```json { "command": ">>prompt_name", "args": { "key": "value", "key2": "value2" } } ``` **Examples**: ```json { "command": ">>analyze_code", "args": { "code": "function foo() { return bar; }", "language": "javascript" } } ``` #### Built-in Commands The following commands are handled specially by the system: - `listprompts`, `list_prompts`, `listprompt` - List all available prompts - `help`, `commands` - Show command help - `status`, `health` - Server status and health diagnostics - `analytics`, `metrics` - Usage analytics and performance metrics #### Command Resolution - **Case-Insensitive**: `>>ANALYZE_CODE` and `>>analyze_code` both work - **Name or ID**: Match by prompt ID or prompt name - **No Typo Correction**: LLMs send exact command names (no Levenshtein distance) - **Clear Error Messages**: Unknown prompts suggest using `>>listprompts` #### Argument Processing **Automatic Format Detection**: 1. **JSON args**: Parsed directly (LLMs send correct types) 2. **Single argument prompts**: Text mapped to first parameter 3. **Key=value format**: `key1="value1" key2="value2"` 4. **Simple text**: Passed as-is to first argument or `input` parameter **Type Handling**: - LLMs send correct types (no coercion needed) - Zod schema validation at MCP tool level - Optional: Use `z.coerce.number()` if type coercion needed #### Template Context Variables Special variables available in templates: - `{{previous_message}}` - Resolved from conversation history - `{{arg_name}}` - Any prompt argument - Framework-specific context injected automatically #### Migration from Legacy System **Removed Features** (No longer needed for LLM usage): - Typo correction (Levenshtein distance) - Type coercion (LLMs send correct types) - Smart content mapping (LLMs use schema descriptions) - Content-aware inference (over-engineered) - Environment variable defaults (rarely used) **See Also**: - Migration Guide: `docs/parser-migration-guide.md` - Refactoring Plan: `plans/parser-simplification-refactor.md` - CommandRouter Source: `server/src/execution/routing/command-router.ts` ## Coding Guidelines and Development Rules ### Enhanced Search System Implementation The system now includes advanced search capabilities implemented in `consolidated-prompt-manager.ts`: #### Search Filter Syntax - **Category Filtering**: `category:code`, `category:analysis`, `category:research` - **Intent-Based Discovery**: `intent:debugging`, `intent:analysis`, `intent:research` - **Execution Type Filtering**: `type:prompt`, `type:template`, `type:chain`, `type:workflow` - **Confidence-Based Filtering**: `confidence:>80`, `confidence:<100`, `confidence:70-90` - **Quality Gate Filtering**: `gates:yes`, `gates:no` - **Execution Requirements**: `execution:required`, `execution:optional` - **Text Search**: Supports fuzzy matching and partial word matching - **Combined Filters**: Multiple filters can be combined: `category:code type:workflow confidence:>80` #### Search Implementation Rules - **Fuzzy Text Matching**: Searches support partial word matching and multiple search terms - **Intent-Based Matching**: Maps user intents to relevant prompts using semantic analysis - **Category-Aware Results**: Results are organized by category with proper filtering - **LLM-Optimized Output**: Results include usage examples, confidence indicators, and actionable descriptions ### TypeScript Development Standards #### Type Safety Requirements - **Strict TypeScript**: All code must compile with strict TypeScript settings - **Explicit Typing**: Avoid `any` types - use proper interfaces and generic types - **Parameter Typing**: Always provide explicit types for function parameters, especially in callbacks and array methods - **Interface Implementation**: All framework guides must implement `IMethodologyGuide` interface completely #### ES Module Standards - **ES Module Syntax**: Use `import`/`export` syntax, not CommonJS `require()` - **File Extensions**: Import paths must include `.js` extension (TypeScript compiles to `.js`) - **Module Resolution**: Follow the moduleNameMapper in jest.config.cjs for consistent resolution ### Testing Standards #### Testing & Validation Commands **Essential Commands:** - `npm run test:ci` - Complete test suite (unit + integration + performance) - `npm run test:all-enhanced` - Enhanced framework and MCP validation - `npm run validate:all` - Core validation (dependencies + circular) - `npm run test:ci-startup` - Server startup validation **Quality Standards:** - **Jest Configuration**: ES modules, 30s timeout, single worker, `tests/setup.ts` - **Validation Integration**: Global Rules quality gates with evidence-based criteria - **Architecture Compliance**: Single source of truth principle enforcement ### Code Quality Standards #### Consolidated Tool Development Rules - **Single Responsibility**: Each consolidated tool handles one major functional area (execution, management, system control) - **Intelligent Filtering**: Support advanced filter syntax in prompt manager for discovery and organization - **Response Consistency**: All tools return standardized `ToolResponse` interface with consistent error handling - **Backwards Compatibility**: Maintain API compatibility when adding new features or filter types #### Framework Development Rules - **Methodology Guides**: All framework behavior must come from methodology guides, never hard-coded - **Interface Compliance**: New methodology guides must implement all required `IMethodologyGuide` methods - **Domain Separation**: Framework logic stays in `/frameworks`, semantic analysis in `/analysis` - **Integration Points**: Framework integration must be explicit and documented in `/integration` directory #### MCP Tool Development - **Tool Registration**: All MCP tools must be registered with proper Zod schema validation - **Error Handling**: Use the utility `handleError()` function for consistent error responses - **Response Format**: All tool responses must use the standardized `ToolResponse` interface - **Argument Validation**: Validate all required fields using `validateRequiredFields()` helper ### Development Workflow Standards #### Pre-Development Checklist (MANDATORY) Before starting any feature or system: 1. **System Overlap Check**: Run `npm run validate:all` to detect existing systems 2. **Architecture Review**: Can this be added to an existing system instead of creating new one? 3. **Dependency Check**: Will this create circular dependencies? Use `npm run validate:circular` 4. **Single Source Verification**: Does this violate "one system per function" rule? #### Code Changes - **System Validation First**: Run `npm run validate:all` before committing - **Type Check**: Always run `npm run typecheck` before committing - **Build Verification**: Run `npm run build` to ensure compilation succeeds - **Test Validation**: Run relevant test suites for changed components - **Hot-Reload Testing**: Verify changes work with `npm run dev` and hot-reloading #### Consolidated Tool Changes When modifying the consolidated MCP tools: 1. **Tool Schema Updates**: Update Zod schema validation for new parameters or options 2. **Response Format**: Maintain consistent `ToolResponse` interface across all tools 3. **Error Handling**: Use standardized `handleError()` function for consistent error responses 4. **Filter Support**: Add new filter types to intelligent filtering system in prompt manager 5. **Test Coverage**: Verify changes work with relevant test suites (`npm run test:mcp-tools`) #### Framework System Changes When modifying framework components: 1. **Methodology guides are single source of truth** - never bypass guide methods 2. **Test framework switching** using MCP tools after changes 3. **Validate guide interface compliance** with all required methods 4. **Ensure integration points remain decoupled** from direct guide access ## 🚀 Enhanced Development Standards Integration ### Evidence-Based Development Protocol **Required Language Standards** (from Global Rules): - **Prohibited**: "best|optimal|faster|secure|better|improved|enhanced|always|never|guaranteed" - **Required**: "may|could|potentially|typically|often|sometimes|measured|documented" - **Evidence**: "testing confirms|metrics show|benchmarks prove|data indicates|documentation states" **Research & Validation Standards**: - **Citations**: Official documentation required | Version compatibility verified | Sources documented - **Context7 Integration**: External libraries and documentation lookup for MCP protocol compliance - **WebSearch**: Official sources and current information for TypeScript/Node.js patterns - **Evidence before implementation**: Research → validate → implement (Global Rules workflow) - **Protocol Compliance**: All changes must maintain MCP SDK compatibility ### Environment & Deployment **Development Setup**: Node.js 16+ | TypeScript strict mode | Environment variables: `MCP_SERVER_ROOT`, `MCP_PROMPTS_CONFIG_PATH` **Transport Testing**: `npm run start:stdio` (Claude Desktop) | `npm run start:sse` (web clients) **CI/CD**: Cross-platform testing (Ubuntu/Windows/macOS, Node 16/18/20) | Quality gates with evidence-based validation #### Performance Budgets - Server startup: <3s | Tool response: <500ms | Framework switching: <100ms | Memory: <128MB --- **Integration**: @include ~/.claude/CLAUDE.md + MCP Protocol Compliance ``` -------------------------------------------------------------------------------- /server/prompts/documentation/prompts.json: -------------------------------------------------------------------------------- ```json { "prompts": [] } ``` -------------------------------------------------------------------------------- /server/src/smithery.yaml: -------------------------------------------------------------------------------- ```yaml version: 1 start: command: ["node", "dist/index.js", "--transport=stdio", "--quiet"] ``` -------------------------------------------------------------------------------- /server/src/frameworks/integration/index.ts: -------------------------------------------------------------------------------- ```typescript /** * Framework Integration Components * Semantic-framework integration layer */ export * from './framework-semantic-integration.js'; ``` -------------------------------------------------------------------------------- /server/prompts/testing/final_verification_test.md: -------------------------------------------------------------------------------- ```markdown # Final Verification Test ## Description Final verification of all isLLMEnabled() refactoring ## User Message Template This is the final test: {{input}} ``` -------------------------------------------------------------------------------- /config/framework-state.json: -------------------------------------------------------------------------------- ```json { "version": "1.0.0", "frameworkSystemEnabled": false, "activeFramework": "CAGEERF", "lastSwitchedAt": "2025-10-14T10:55:24.202Z", "switchReason": "Initial framework selection" } ``` -------------------------------------------------------------------------------- /server/tsconfig.test.json: -------------------------------------------------------------------------------- ```json { "extends": "./tsconfig.json", "compilerOptions": { "types": ["node", "jest"], "noEmit": true }, "include": ["src/**/*", "tests/**/*"], "exclude": ["node_modules", "dist"] } ``` -------------------------------------------------------------------------------- /server/config/framework-state.json: -------------------------------------------------------------------------------- ```json { "version": "1.0.0", "frameworkSystemEnabled": true, "activeFramework": "CAGEERF", "lastSwitchedAt": "2025-10-14T10:55:00.754Z", "switchReason": "User request to enable CAGEERF framework." } ``` -------------------------------------------------------------------------------- /server/src/gates/index.ts: -------------------------------------------------------------------------------- ```typescript /** * Gate System - Core Implementation * * The gate system provides validation and guidance capabilities for prompt execution. * This is the main gate system implementation. */ // Export core gate system as primary interface export * from './core/index.js'; ``` -------------------------------------------------------------------------------- /server/src/execution/context/index.ts: -------------------------------------------------------------------------------- ```typescript /** * Context System Export Module * * Centralizes all context resolution infrastructure exports */ export { ContextResolver, createContextResolver, type ContextResolution, type ContextProvider, type ContextSource, type ContextAggregationOptions } from './context-resolver.js'; ``` -------------------------------------------------------------------------------- /server/src/performance/index.ts: -------------------------------------------------------------------------------- ```typescript /** * Performance Monitoring Module * * Exports performance monitoring and optimization functionality * for the MCP server system. */ export { PerformanceMonitor, createPerformanceMonitor, type PerformanceMetrics, type PerformanceThresholds, type PerformanceAlert } from "./monitor.js"; ``` -------------------------------------------------------------------------------- /server/src/mcp-tools/prompt-manager/core/index.ts: -------------------------------------------------------------------------------- ```typescript /** * Prompt Manager Core Module Exports * * This index file provides unified access to all core prompt manager functionality * to resolve module resolution issues in CI/CD environments. */ // Re-export the consolidated prompt manager export * from './manager.js'; // Re-export all core types and interfaces export * from './types.js'; ``` -------------------------------------------------------------------------------- /server/prompts/testing/prompts.json: -------------------------------------------------------------------------------- ```json { "prompts": [ { "id": "final_verification_test", "name": "Final Verification Test", "category": "testing", "description": "Final verification of all isLLMEnabled() refactoring", "file": "final_verification_test.md", "arguments": [ { "name": "input", "type": "string", "description": "Test input" } ] } ] } ``` -------------------------------------------------------------------------------- /scripts/windows-tests/test-windows-startup.sh: -------------------------------------------------------------------------------- ```bash #!/bin/bash # Test Windows-like startup scenarios echo "Testing Windows-compatible startup..." # Simulate Windows environment export RUNNER_OS=Windows export PATH="/c/Windows/System32:$PATH" # Test Node.js startup cd server echo "Testing Node.js startup in Windows-like environment..." node --version npm --version # Test our application echo "Testing MCP server startup..." npm run help echo "✅ Windows startup test completed" ``` -------------------------------------------------------------------------------- /scripts/windows-tests/windows-env.sh: -------------------------------------------------------------------------------- ```bash #!/bin/bash # Windows environment simulation - no sensitive files export RUNNER_OS=Windows export PATH="/c/Windows/System32:/c/Windows:/c/Windows/System32/Wbem:$PATH" export USERPROFILE=/c/Users/runneradmin export TEMP=/c/Users/runneradmin/AppData/Local/Temp export TMP=/c/Users/runneradmin/AppData/Local/Temp export HOMEDRIVE=C: export HOMEPATH=/Users/runneradmin export PATHEXT=.COM:.EXE:.BAT:.CMD:.VBS:.VBE:.JS:.JSE:.WSF:.WSH:.MSC echo "Windows environment variables set" ``` -------------------------------------------------------------------------------- /server/prompts/education/prompts.json: -------------------------------------------------------------------------------- ```json { "prompts": [ { "id": "vault_integrated_notes", "name": "Vault-Integrated Notes Creator", "category": "education", "description": "Create comprehensive notes that search the vault for real related notes instead of generating fictional ones", "file": "vault_integrated_notes.md", "arguments": [ { "name": "topic", "description": "The topic to create comprehensive vault-integrated notes about", "required": true } ] } ] } ``` -------------------------------------------------------------------------------- /server/tsconfig.json: -------------------------------------------------------------------------------- ```json { "compilerOptions": { "target": "ES2020", "lib": ["ES2020"], "module": "NodeNext", "moduleResolution": "NodeNext", "types": ["node"], "esModuleInterop": true, "allowSyntheticDefaultImports": true, "forceConsistentCasingInFileNames": true, "strict": true, "skipLibCheck": true, "isolatedModules": true, "outDir": "dist", "sourceMap": true, "declaration": true, "resolveJsonModule": true }, "include": ["src/**/*"], "exclude": ["node_modules", "dist", "tests"] } ``` -------------------------------------------------------------------------------- /server/src/metrics/index.ts: -------------------------------------------------------------------------------- ```typescript /** * Metrics Module Exports * * Centralized exports for the metrics collector and related types. * Provides event-driven metrics collection separated from execution logic. */ // Metrics collector export { MetricsCollector, createMetricsCollector } from './analytics-service.js'; // Types export type { ExecutionData, GateValidationData, FrameworkSwitchData, ExecutionStats, SystemMetrics, FrameworkUsage, AnalyticsEvent, AnalyticsQueryOptions, AnalyticsSummary, PerformanceTrend } from './types.js'; ``` -------------------------------------------------------------------------------- /server/src/mcp-tools/prompt-engine/core/index.ts: -------------------------------------------------------------------------------- ```typescript /** * Prompt Engine Core Module Exports * * This index file provides unified access to all core prompt engine functionality * to resolve module resolution issues in CI/CD environments. */ // Re-export the main execution engine (excluding conflicting types) export { ConsolidatedPromptEngine, createConsolidatedPromptEngine } from './engine.js'; // Re-export the prompt executor export * from './executor.js'; // Re-export all core types and interfaces (primary source for PromptClassification) export * from './types.js'; ``` -------------------------------------------------------------------------------- /server/src/Dockerfile: -------------------------------------------------------------------------------- ```dockerfile FROM node:20-alpine # Set working directory WORKDIR /app # Copy package files first for better layer caching COPY package*.json ./ # Install all dependencies RUN npm ci # Copy source code COPY . . # Build the TypeScript project RUN npm run build # Remove dev dependencies to reduce image size RUN npm ci --only=production && npm cache clean --force # Set environment variables ENV NODE_ENV=production ENV MCP_SERVER_ROOT=/app # Expose port EXPOSE 8000 # Start the server CMD ["node", "dist/index.js", "--transport=stdio", "--quiet"] ``` -------------------------------------------------------------------------------- /scripts/windows-tests/test-windows-paths.js: -------------------------------------------------------------------------------- ```javascript // Test Windows path handling const path = require('path'); const os = require('os'); console.log('Testing Windows-compatible path handling...'); console.log('Platform:', os.platform()); console.log('Path separator:', path.sep); console.log('Path delimiter:', path.delimiter); // Test path operations that should work cross-platform const testPath = path.join('server', 'src', 'index.ts'); console.log('Cross-platform path:', testPath); // Test environment variables console.log('NODE_ENV:', process.env.NODE_ENV); console.log('RUNNER_OS:', process.env.RUNNER_OS); console.log('✅ Windows compatibility test passed'); ``` -------------------------------------------------------------------------------- /server/config.json: -------------------------------------------------------------------------------- ```json { "server": { "name": "claude-prompts-mcp", "version": "1.3.0", "port": 9090 }, "prompts": { "file": "prompts/promptsConfig.json" }, "analysis": { "semanticAnalysis": { "enabled": false, "llmIntegration": { "enabled": false, "apiKey": null, "endpoint": null, "model": "gpt-4", "maxTokens": 1000, "temperature": 0.1 } } }, "gates": { "definitionsDirectory": "src/gates/definitions", "templatesDirectory": "src/gates/templates" }, "transports": { "default": "stdio" }, "logging": { "directory": "./logs", "level": "debug" } } ``` -------------------------------------------------------------------------------- /server/prompts/development/analyze_code_structure.md: -------------------------------------------------------------------------------- ```markdown # Analyze Code Structure ## Description Analyzes the structure and patterns of provided code. ## System Message You are a code structure analyst who provides clear, objective observations about code organization and architecture. ## User Message Template Please analyze the structure of the following {{language}} code: ```{{language}} {{code}} ``` Provide a detailed analysis including: 1. Overall architecture and code organization 2. Function/method structure and relationships 3. Data flow patterns 4. Key design patterns used 5. Code complexity assessment Keep your analysis descriptive rather than prescriptive - focus on what the code does, not what should be changed. ``` -------------------------------------------------------------------------------- /server/prompts/debugging/prompts.json: -------------------------------------------------------------------------------- ```json { "prompts": [ { "id": "analyze_logs", "name": "Advanced Log Analysis & Debugging", "category": "debugging", "description": "Comprehensive log analysis template incorporating advanced debugging strategies used by senior developers and SREs for systematic root cause analysis", "file": "analyze_logs.md", "arguments": [ { "name": "logs", "description": "The complete log entries to analyze", "required": true }, { "name": "context", "description": "Additional context: system state, recent changes, user reports, etc.", "required": false } ] } ] } ``` -------------------------------------------------------------------------------- /server/src/gates/constants.ts: -------------------------------------------------------------------------------- ```typescript /** * Gate System Constants * * Centralized behavioral settings for the gate system. * These were previously configurable but are now set as sensible defaults. */ /** * Default retry limit for failed validations */ export const DEFAULT_RETRY_LIMIT = 3; /** * Whether to inject gate guidance into prompts by default */ export const ENABLE_GUIDANCE_INJECTION = true; /** * Whether to perform gate validation by default */ export const ENABLE_VALIDATION = true; /** * Default gate system behavioral configuration */ export const GATE_SYSTEM_DEFAULTS = { defaultRetryLimit: DEFAULT_RETRY_LIMIT, enableGuidanceInjection: ENABLE_GUIDANCE_INJECTION, enableValidation: ENABLE_VALIDATION, } as const; ``` -------------------------------------------------------------------------------- /server/src/frameworks/methodology/index.ts: -------------------------------------------------------------------------------- ```typescript /** * Methodology System Index - Phase 2 Implementation * * Centralized exports for the reorganized methodology system. * Provides clean imports for methodology guides, registry, and interfaces. */ // Export methodology registry export { MethodologyRegistry, createMethodologyRegistry } from "./registry.js"; export type { MethodologyRegistryConfig, MethodologyGuideEntry } from "./registry.js"; // Export methodology interfaces export * from "./interfaces.js"; // Export methodology guides from new location export { CAGEERFMethodologyGuide } from "./guides/cageerf-guide.js"; export { ReACTMethodologyGuide } from "./guides/react-guide.js"; export { FiveW1HMethodologyGuide } from "./guides/5w1h-guide.js"; export { SCAMPERMethodologyGuide } from "./guides/scamper-guide.js"; ``` -------------------------------------------------------------------------------- /server/src/frameworks/index.ts: -------------------------------------------------------------------------------- ```typescript /** * Framework System (Phase 2: Methodology System Reorganization) * Streamlined framework system with consolidated type definitions, * organized methodology system, and framework behavior guidance */ // Consolidated type definitions (Phase 1: NEW) export * from './types/index.js'; // Methodology system (Phase 2: NEW) export * from './methodology/index.js'; // Framework managers (stateless orchestration and stateful management) export * from './framework-manager.js'; export * from './framework-state-manager.js'; // Framework system components (stateful methodology switching) export * from './integration/index.js'; // Prompt guidance system (Phase 3: NEW) export * from './prompt-guidance/index.js'; // Methodology guides exported from ./methodology/ (single source of truth) // Legacy adapters directory removed - no duplication ``` -------------------------------------------------------------------------------- /server/prompts/development/detect_code_issues.md: -------------------------------------------------------------------------------- ```markdown # Detect Code Issues ## Description Identifies potential bugs, performance issues, and code smells in the provided code. ## System Message You are a code quality expert who specializes in identifying potential issues, bugs, and areas for improvement in code. ## User Message Template Based on the following code and its structural analysis, please identify potential issues: Code: ```{{language}} {{code}} ``` Previous Analysis: {{analysis}} Identify and list potential issues in these categories: 1. Bugs and logical errors 2. Performance concerns 3. Security vulnerabilities 4. Maintainability problems 5. Edge cases not properly handled For each issue, provide: - A clear description of the problem - The specific location in the code (line or function) - The potential impact of the issue - The level of severity (Critical, High, Medium, Low) ``` -------------------------------------------------------------------------------- /server/src/frameworks/methodology/interfaces.ts: -------------------------------------------------------------------------------- ```typescript /** * Methodology Interfaces - Phase 2 Implementation * * Consolidated interfaces for methodology guides and registry management. * This file centralizes all methodology-related interfaces that were * previously distributed across multiple files. */ // Re-export all methodology interfaces from the consolidated types export type { IMethodologyGuide, PromptCreationGuidance, ProcessingGuidance, StepGuidance, MethodologyEnhancement, ArgumentGuidance, ProcessingStep, ExecutionStep, QualityGate, TemplateEnhancement, MethodologyToolDescription, MethodologyToolDescriptions, MethodologyValidation } from "../types/methodology-types.js"; export { BaseMethodologyGuide } from "../types/methodology-types.js"; // Registry-specific interfaces export type { MethodologyRegistryConfig, MethodologyGuideEntry } from "./registry.js"; ``` -------------------------------------------------------------------------------- /server/prompts/general/prompts.json: -------------------------------------------------------------------------------- ```json { "prompts": [ { "id": "diagnose", "name": "Codebase Diagnostics", "category": "general", "description": "Systematically diagnose issues in codebases including bugs, performance problems, security vulnerabilities, architecture issues, and technical debt", "file": "diagnose.md", "arguments": [ { "name": "scope", "description": "Specific files, directories, or areas to analyze (e.g., 'src/auth/**', 'performance issues', 'security')" }, { "name": "focus", "description": "Specific diagnostic focus (e.g., 'security', 'performance', 'architecture', 'type errors')" }, { "name": "symptoms", "description": "Reported symptoms or problems (e.g., 'slow build times', 'memory leaks', 'failing tests')" } ] } ] } ``` -------------------------------------------------------------------------------- /server/src/mcp-tools/prompt-manager/index.ts: -------------------------------------------------------------------------------- ```typescript /** * Prompt Manager - Modular Architecture Entry Point * * This module maintains 100% backwards compatibility while providing * a modular internal architecture for improved maintainability. */ // Export the main class and factory function with exact same API export { ConsolidatedPromptManager } from "./core/manager.js"; export { createConsolidatedPromptManager } from "./core/manager.js"; // Export types for external use export type { PromptClassification, AnalysisResult, SmartFilters } from "./core/types.js"; // Backwards compatibility exports export type { PromptManagerDependencies } from "./core/types.js"; /** * Re-export all original interfaces to maintain API compatibility */ export type { PromptManagerModule, PromptManagerData, OperationResult, CategoryResult, FileOperationResult, DependencyAnalysis, MigrationResult, ValidationContext } from "./core/types.js"; ``` -------------------------------------------------------------------------------- /server/prompts/development/suggest_code_improvements.md: -------------------------------------------------------------------------------- ```markdown # Suggest Code Improvements ## Description Suggests specific improvements to address identified issues and enhance code quality. ## System Message You are a code improvement specialist who provides actionable, targeted suggestions to enhance code quality, readability, and performance. ## User Message Template Based on the code analysis and identified issues, please suggest specific improvements: Code: ```{{language}} {{code}} ``` Analysis: {{analysis}} Identified Issues: {{issues}} Provide improvement recommendations in these areas: 1. Bug fixes and logical error corrections 2. Performance optimizations 3. Security enhancements 4. Maintainability improvements 5. Code organization and structure For each recommendation: - Provide a clear explanation of the improvement - Include code examples where appropriate - Explain the benefits of implementing the change - Prioritize recommendations (Critical, High, Medium, Low) Focus on practical, implementable changes that maintain the original code's intent and functionality. ``` -------------------------------------------------------------------------------- /server/prompts/architecture/prompts.json: -------------------------------------------------------------------------------- ```json { "prompts": [ { "id": "strategic-system-alignment", "name": "Strategic System Alignment", "category": "architecture", "description": "Strategically align systems and code towards architectural rules and goals with systematic implementation planning and progress tracking in /plans markdown notes", "file": "strategic-system-alignment.md", "arguments": [ { "name": "task_description", "type": "string", "description": "System/component to align and alignment goals" }, { "name": "context_files", "type": "string", "description": "Optional: Relevant file paths" }, { "name": "architectural_rules", "type": "string", "description": "Optional: Rules to align with" }, { "name": "goals", "type": "string", "description": "Optional: Goals to achieve" }, { "name": "constraints", "type": "string", "description": "Optional: Constraints to respect" } ] } ] } ``` -------------------------------------------------------------------------------- /server/jest.config.cjs: -------------------------------------------------------------------------------- ``` /** @type {import('jest').Config} */ module.exports = { preset: 'ts-jest/presets/default-esm', extensionsToTreatAsEsm: ['.ts'], testEnvironment: 'node', roots: ['<rootDir>/tests'], testMatch: [ '<rootDir>/tests/**/*.test.ts' ], setupFilesAfterEnv: ['<rootDir>/tests/setup.ts'], // Re-enabled with working ES module support transform: { '^.+\\.ts$': ['ts-jest', { useESM: true, tsconfig: { module: 'esnext', target: 'es2020', moduleResolution: 'node', allowSyntheticDefaultImports: true, esModuleInterop: true } }] }, collectCoverageFrom: [ 'dist/**/*.js', '!dist/**/*.d.ts', '!dist/tests/**' ], coverageDirectory: 'coverage', coverageReporters: ['text', 'lcov'], testTimeout: 30000, verbose: true, maxWorkers: 1, // Essential for ES modules with Jest moduleFileExtensions: ['ts', 'js', 'mjs'], // Handle ES module imports properly - map .js imports to TypeScript files and preserve ES modules moduleNameMapper: { '^(\\.{1,2}/.*)\\.js$': '$1' }, // Transform ES modules from node_modules if needed transformIgnorePatterns: [ 'node_modules/(?!(@modelcontextprotocol)/)' ], // Support for dynamic imports and ES modules testPathIgnorePatterns: [ '/node_modules/' ] }; ``` -------------------------------------------------------------------------------- /server/prompts/development/expert_code_implementation.md: -------------------------------------------------------------------------------- ```markdown # Expert Code Implementation ## Description Expert implementation of refined coding requirements with comprehensive explanation and best practices. ## System Message You are an expert software developer with extensive experience across multiple domains. Your task is to implement high-quality, professional-grade code based on refined requirements. You write elegant, efficient, and well-documented code that follows best practices and industry standards. ## User Message Template Please implement the following coding request: **Request:** {{refined_query}} **Language:** {{language}} **Requirements:** {{requirements}} **Constraints:** {{constraints}} {% if gate_guidance %} ## Quality Guidelines {{gate_guidance}} {% endif %} For your implementation: 1. Design a robust solution that addresses all requirements 2. Write clean, efficient, well-structured code 3. Include comprehensive comments explaining complex sections 4. Implement proper error handling and edge case management 5. Follow language-specific best practices and conventions 6. Consider performance, security, and maintainability 7. Provide usage examples that demonstrate the code's functionality Your solution should be production-ready and include: - Complete, runnable code - Explanation of your implementation approach and design decisions - Any important technical considerations or limitations - Example usage showing how to properly use the code ``` -------------------------------------------------------------------------------- /server/src/gates/definitions/content-structure.json: -------------------------------------------------------------------------------- ```json { "id": "content-structure", "name": "Content Structure Guidelines", "type": "validation", "description": "Ensures well-organized, readable content with clear structure", "guidance": "**Content Structure Guidelines:**\n- Use clear headings and subheadings (## and ###)\n- Organize content in logical sections\n- Include bullet points or numbered lists for clarity\n- Provide examples when explaining concepts\n- Maintain consistent tone and style\n- Ensure smooth transitions between sections\n- Include a summary or conclusion when appropriate", "pass_criteria": [ { "type": "content_check", "min_length": 200, "required_patterns": [ "##", "-", "example" ] }, { "type": "pattern_check", "keyword_count": { "##": 2 }, "regex_patterns": [ "^##\\s+.+$", "^\\s*[-*]\\s+.+" ] } ], "_comment_llm_validation": "LLM self-check removed until API integration complete. Will be re-added when config.analysis.semanticAnalysis.llmIntegration is fully implemented.", "retry_config": { "max_attempts": 2, "improvement_hints": true, "preserve_context": true }, "activation": { "prompt_categories": ["documentation", "content_processing", "education"], "explicit_request": false }, "_comment": "Category gate - activates based on category only. Framework gates control methodology separately." } ``` -------------------------------------------------------------------------------- /server/src/gates/definitions/research-quality.json: -------------------------------------------------------------------------------- ```json { "id": "research-quality", "name": "Research Quality Guidelines", "type": "validation", "description": "Ensures thorough research with proper citations and credible sources", "guidance": "**Research Quality Guidelines:**\n- Cite at least 3 credible sources when making factual claims\n- Include publication dates for time-sensitive information\n- Distinguish between primary and secondary sources\n- Cross-reference facts across multiple sources\n- Provide context for statistical claims\n- Use authoritative sources (academic journals, government data, established news outlets)", "pass_criteria": [ { "type": "content_check", "min_length": 300, "required_patterns": [ "according to", "source", "published", "research", "study" ] }, { "type": "pattern_check", "keyword_count": { "according to": 1, "source": 2 } } ], "_comment_llm_validation": "LLM self-check removed until API integration complete. Will be re-added when config.analysis.semanticAnalysis.llmIntegration is fully implemented.", "retry_config": { "max_attempts": 3, "improvement_hints": true, "preserve_context": true }, "activation": { "prompt_categories": ["research", "analysis"], "explicit_request": true }, "_comment": "Category gate - activates based on category only. Framework gates control methodology separately." } ``` -------------------------------------------------------------------------------- /server/prompts/promptsConfig.json: -------------------------------------------------------------------------------- ```json { "categories": [ { "id": "analysis", "name": "Analysis", "description": "Prompts for analyzing content and data" }, { "id": "education", "name": "Education", "description": "Prompts for learning and teaching concepts" }, { "id": "development", "name": "Development", "description": "Prompts for software development and code quality" }, { "id": "documentation", "name": "Documentation", "description": "Prompts related to Documentation" }, { "id": "debugging", "name": "debugging", "description": "Prompts related to debugging" }, { "id": "content_processing", "name": "content_processing", "description": "Prompts related to content_processing" }, { "id": "architecture", "name": "architecture", "description": "Prompts related to architecture" }, { "id": "general", "name": "general", "description": "Prompts related to general" }, { "id": "testing", "name": "testing", "description": "Prompts related to testing" } ], "prompts": [], "imports": [ "analysis/prompts.json", "education/prompts.json", "development/prompts.json", "documentation/prompts.json", "debugging/prompts.json", "content_processing/prompts.json", "architecture/prompts.json", "general/prompts.json", "testing/prompts.json" ] } ``` -------------------------------------------------------------------------------- /server/prompts/analysis/query_refinement.md: -------------------------------------------------------------------------------- ```markdown # Query Refinement ## Description A systematic process to analyze and refine ambiguous coding requests into clear, actionable specifications. ## System Message You are an expert requirements analyst specializing in software development. Your task is to transform vague or ambiguous coding requests into clear, structured specifications. When presented with a query, you'll systematically analyze it, identify any technical ambiguities or missing information, and transform it into detailed requirements. ## User Message Template I need to refine this coding request: {{query}} Please follow these steps: 1. Parse the request to identify the core programming task 2. Determine the likely programming language(s) needed (specify if ambiguous) 3. Identify any technical ambiguities, unclear terms, or missing context 4. List key functional requirements that can be inferred from the request 5. Specify any performance, security, or quality constraints that should be considered 6. Propose any clarifying technical questions that would help resolve ambiguities 7. Provide a refined version of the request with clear specifications Output your analysis in this format: - **Language:** [Determined programming language] - **Refined Query:** [Clear, specific version of the request] - **Requirements:** [Bullet list of functional requirements] - **Constraints:** [Any performance/security/quality considerations] - **Clarifying Questions:** [Questions to further refine requirements] ``` -------------------------------------------------------------------------------- /server/src/mcp-tools/prompt-engine/index.ts: -------------------------------------------------------------------------------- ```typescript /** * Prompt Engine - Unified Execution System * * Consolidated prompt engine providing systematic prompt execution with: * - Framework integration (CAGEERF, ReACT, 5W1H, SCAMPER) * - Chain execution with progress tracking * - Semantic analysis and intelligent execution mode detection * - Gate validation and retry logic * * This module maintains API compatibility while providing improved organization. */ // Core engine exports export { ConsolidatedPromptEngine, createConsolidatedPromptEngine, } from "./core/engine.js"; // Chain execution exports export { ChainExecutor, } from "./core/executor.js"; // Type definitions export type { ChainExecutionContext, ChainExecutionOptions, ChainManagementCommand, ChainGateInfo, ChainValidationResult, ChainStepData, StepArgumentsContext, FormatterExecutionContext, SimpleResponseFormatter, PromptClassification, ChainExecutionStrategy, ChainState, } from "./core/types.js"; // Processing utilities (internal use) export { TemplateProcessor, } from "./processors/template-processor.js"; export { ResponseFormatter, } from "./processors/response-formatter.js"; // Utility functions (internal use) export { PromptClassifier, } from "./utils/classification.js"; export { EngineValidator, } from "./utils/validation.js"; export { ContextBuilder, } from "./utils/context-builder.js"; // Re-export shared utilities for backwards compatibility export { createExecutionResponse, } from "../shared/structured-response-builder.js"; ``` -------------------------------------------------------------------------------- /server/prompts/documentation/docs-project-analysis.md: -------------------------------------------------------------------------------- ```markdown # Project Analysis (Step 1 of 5) ## Description Analyze a project to identify what needs to be documented and how ## System Message [System Info: You are a documentation specialist who excels at analyzing projects to determine documentation needs. Your goal is to identify key components, features, and concepts that require documentation while understanding the project's overall purpose and structure.] ## User Message Template I need to create technical documentation for the following project: {{project_info}} The documentation type I need is: {{doc_type}} The target audience is: {{audience}} {% if depth_level %}The desired depth level is: {{depth_level}}{% endif %} Please analyze this project to help plan the documentation by: 1. Identifying the key components, features, and concepts that need to be documented 2. Determining the most important aspects to cover based on the target audience 3. Analyzing the project's structure and how it should be reflected in the documentation 4. Identifying any technical prerequisites or background knowledge the audience might need 5. Recognizing potential pain points or complex areas that will need extra documentation attention 6. Suggesting appropriate documentation formats and styles for this specific project 7. Noting which sections would benefit from examples, diagrams, or code snippets Please organize your analysis with clear sections and provide a comprehensive overview of what the documentation should address and how it should be structured to best serve its purpose. ``` -------------------------------------------------------------------------------- /server/prompts/development/create_modularization_plan.md: -------------------------------------------------------------------------------- ```markdown # Create Modularization Plan ## Description Creates a detailed plan for splitting a file into smaller, more maintainable modules based on analysis of its structure and dependencies. ## System Message You are an expert software architect specializing in code organization and modular design. Your task is to create a detailed plan for splitting a file into smaller, more maintainable modules based on analysis of its structure and dependencies. ## User Message Template Based on the analysis of this {{language}} file located at {{file_path}}, please create a detailed modularization plan: **File Analysis Results:** {{analysis_results}} Create a comprehensive modularization plan that includes: ## 1. Module Breakdown Strategy - Identified modules with clear responsibilities - Module naming conventions and organization - Dependency relationships between modules - Interface design and public APIs ## 2. Implementation Roadmap - Step-by-step refactoring sequence - Risk mitigation strategies - Testing approach for each module - Rollback procedures if needed ## 3. Technical Specifications - File structure and directory organization - Import/export patterns for {{language}} - Configuration and setup requirements - Documentation standards ## 4. Quality Assurance Plan - Code review checkpoints - Testing strategies for each module - Performance validation approaches - Backwards compatibility considerations Provide a detailed, actionable plan that ensures successful modularization while maintaining code quality and functionality. ``` -------------------------------------------------------------------------------- /server/src/gates/definitions/code-quality.json: -------------------------------------------------------------------------------- ```json { "id": "code-quality", "name": "Code Quality Standards", "type": "validation", "description": "Ensures generated code follows best practices and quality standards", "guidance": "**Code Quality Standards:**\n- Include error handling and input validation\n- Add inline comments for complex logic\n- Follow consistent naming conventions\n- Consider edge cases and boundary conditions\n- Optimize for readability over cleverness\n- Include basic documentation/docstrings\n- Follow security best practices (input sanitization, avoid hardcoded secrets)", "pass_criteria": [ { "type": "content_check", "min_length": 100, "required_patterns": [ "try", "catch", "//", "*", "function", "const" ], "forbidden_patterns": [ "TODO", "FIXME", "hack", "password123" ] }, { "type": "pattern_check", "regex_patterns": [ "function\\s+\\w+\\s*\\(", "\\/\\/.*\\w+", "try\\s*\\{" ] } ], "_comment_llm_validation": "LLM self-check removed until API integration complete. Will be re-added when config.analysis.semanticAnalysis.llmIntegration is fully implemented.", "retry_config": { "max_attempts": 2, "improvement_hints": true, "preserve_context": true }, "activation": { "prompt_categories": ["code", "development"], "explicit_request": false }, "_comment": "Category gate - activates based on category only. Framework gates control methodology separately." } ``` -------------------------------------------------------------------------------- /scripts/test-all-platforms.sh: -------------------------------------------------------------------------------- ```bash #!/bin/bash # Comprehensive multi-platform testing script set -e RED='\033[0;31m' GREEN='\033[0;32m' YELLOW='\033[1;33m' BLUE='\033[0;34m' NC='\033[0m' print_test() { echo -e "${BLUE}[TEST]${NC} $1" } print_pass() { echo -e "${GREEN}[PASS]${NC} $1" } print_fail() { echo -e "${RED}[FAIL]${NC} $1" } # Test 1: Ubuntu (Linux) - Primary platform print_test "Testing Ubuntu/Linux platform..." if ./local-test.sh dry-run code-quality >/dev/null 2>&1; then print_pass "Ubuntu/Linux testing works" else print_fail "Ubuntu/Linux testing failed" fi # Test 2: Windows simulation with Node.js print_test "Testing Windows simulation (Node.js)..." if docker run --rm -v "$PWD":/workspace -w /workspace/server node:18-alpine npm --version >/dev/null 2>&1; then print_pass "Windows simulation (Node.js) works" else print_fail "Windows simulation (Node.js) failed" fi # Test 3: Cross-platform Node.js compatibility print_test "Testing cross-platform Node.js compatibility..." if node scripts/windows-tests/test-windows-paths.js >/dev/null 2>&1; then print_pass "Cross-platform compatibility works" else print_fail "Cross-platform compatibility failed" fi # Test 4: Windows environment simulation print_test "Testing Windows environment simulation..." if [ -f "scripts/windows-tests/windows-env.sh" ] && source scripts/windows-tests/windows-env.sh >/dev/null 2>&1; then print_pass "Windows environment simulation works" else print_fail "Windows environment simulation failed" fi echo "" echo "Multi-platform testing summary completed!" ``` -------------------------------------------------------------------------------- /server/prompts/analysis/markdown_notebook.md: -------------------------------------------------------------------------------- ```markdown # Markdown Notebook Creation This prompt transforms deep analysis content into a well-structured markdown notebook with headers, bullet points, and emphasized content, mermaid graphs, graphs, italics, quotes, block quotes, LATEX etc... ## System Message You are an expert at organizing complex information into clear, well-structured markdown notebooks. Your task is to take detailed analysis and transform it into an organized set of notes that are easy to read and navigate. ## User Message Template Please create a markdown notebook based on the following deep analysis of the topic "{{topic}}": ``` {{analysis}} ``` Create a comprehensive markdown notebook with: 1. A clear title and introduction 2. Well-organized sections with appropriate headings (H1, H2, H3) 3. Bullet points for key concepts 4. Code blocks, tables, or other formatting as appropriate 5. Emphasis on important insights using bold or italics Focus on organization, clarity, and knowledge structure. Include all important insights from the analysis. ## Arguments - topic: The topic or subject of the analysis - analysis: The detailed analysis to organize into a markdown notebook ## Output Format A well-structured markdown notebook that follows markdown conventions, with: ```markdown # [Title] ## Introduction [Brief overview] ## [Main Section 1] ### [Subsection 1.1] - Key point - Key point ### [Subsection 1.2] [Content] ## [Main Section 2] ... ``` The notebook should be comprehensive yet clear, maintaining the depth of the original analysis while improving its organization and accessibility. ``` -------------------------------------------------------------------------------- /server/src/execution/index.ts: -------------------------------------------------------------------------------- ```typescript /** * Modernized Execution System Export Module (Phase 3) * * Simplified execution system with ConsolidatedPromptEngine delegation: * * Key exports: * - ExecutionCoordinator: Thin orchestration layer that delegates to ConsolidatedPromptEngine * - All complex execution handled through ConsolidatedPromptEngine */ // REMOVED: ExecutionCoordinator - modular chain system removed // All execution now handled directly by ConsolidatedPromptEngine // Execution conversation management integrated with text-references/conversation.ts // No separate execution conversation manager needed // UnifiedPromptProcessor removed - functionality consolidated into ExecutionCoordinator // Phase 3: Chain strategies removed - all execution delegated to ConsolidatedPromptEngine // Legacy strategy patterns deprecated in favor of ConsolidatedPromptEngine // Re-export types needed by strategies export type { ChainExecutionResult, ConvertedPrompt, // WorkflowExecutionResult removed in Phase 2 - use ChainExecutionResult // Workflow type removed in Phase 2 - use enhanced ChainStep configurations // RuntimeTarget removed in Phase 2 - workflow foundation types eliminated } from "../types/index.js"; // REMOVED: All execution coordinator imports - modular chain system removed // REMOVED: createFullyConfiguredExecutionCoordinator - modular chain system removed // All execution now handled directly by ConsolidatedPromptEngine in mcp-tools/prompt-engine.ts // Legacy factory function removed - createFullyConfiguredExecutionEngine // Use createFullyConfiguredExecutionCoordinator instead ``` -------------------------------------------------------------------------------- /server/prompts/development/transform_code_to_modules.md: -------------------------------------------------------------------------------- ```markdown # Transform Code to Modules ## Description Transforms a large file into multiple smaller module files according to a modularization plan, ensuring proper imports/exports and maintaining functionality. ## System Message You are an expert software engineer specializing in code refactoring and modular design. Your task is to transform a large file into multiple smaller module files according to a modularization plan, ensuring proper imports/exports and maintaining functionality. ## User Message Template Based on the modularization plan, please transform this {{language}} file located at {{file_path}} into multiple smaller modules: **Original Code:** ```{{language}} {{original_code}} ``` **Modularization Plan:** {{modularization_plan}} Please create the modular implementation with: ## 1. Module Files - Generate each module file with appropriate content - Implement proper imports/exports for {{language}} - Ensure clean separation of responsibilities - Maintain existing functionality ## 2. Interface Design - Clear public APIs for each module - Proper abstraction and encapsulation - Consistent naming conventions - Documentation for each module ## 3. Integration Code - Updated main file that imports new modules - Proper dependency management - Configuration and setup code - Error handling preservation ## 4. Implementation Notes - Changes made and rationale - Testing recommendations - Migration guide for users - Performance impact analysis Provide complete, working code for each module that maintains the original functionality while improving organization and maintainability. ``` -------------------------------------------------------------------------------- /server/src/frameworks/prompt-guidance/index.ts: -------------------------------------------------------------------------------- ```typescript /** * Prompt Guidance System Index - Phase 3 Implementation * * Central exports for the prompt guidance system that provides intelligent * methodology integration for MCP prompts. * * The prompt guidance system consists of three core components: * - SystemPromptInjector: Injects methodology guidance into system prompts * - MethodologyTracker: Tracks active methodology state and handles switching * - TemplateEnhancer: Enhances user templates with methodology-specific guidance */ // Core prompt guidance components export { SystemPromptInjector, createSystemPromptInjector, type SystemPromptInjectorConfig } from './system-prompt-injector.js'; export { MethodologyTracker, createMethodologyTracker, type MethodologyTrackerConfig, type MethodologyTrackerEvents } from './methodology-tracker.js'; export { TemplateEnhancer, createTemplateEnhancer, type TemplateEnhancerConfig, type TemplateEnhancementContext } from './template-enhancer.js'; // Unified prompt guidance service export { PromptGuidanceService, createPromptGuidanceService, type PromptGuidanceServiceConfig } from './service.js'; // Service-specific types (to avoid conflicts with types/index.js) export type { PromptGuidanceResult as ServicePromptGuidanceResult } from './service.js'; // Re-export relevant types from the types system export type { SystemPromptInjectionResult, TemplateEnhancementResult, MethodologyState, MethodologySwitchRequest, MethodologyHealth, PersistedMethodologyState, TemplateProcessingGuidance, PromptGuidanceConfig, PromptGuidanceResult } from '../types/index.js'; ``` -------------------------------------------------------------------------------- /server/prompts/education/vault_integrated_notes.md: -------------------------------------------------------------------------------- ```markdown # Vault-Integrated Notes Creator ## Description Create comprehensive notes that search the vault for real related notes instead of generating fictional ones ## System Message You are an expert note-taker with access to a comprehensive Obsidian vault. You excel at creating detailed, well-structured notes that integrate with existing knowledge through real vault searches and authentic cross-references. ## User Message Template I need to create comprehensive notes about: {{topic}} CRITICAL REQUIREMENTS: 1. **Real Vault Integration**: Before creating the Related Notes section, you MUST search the vault for actual related content using available search tools 2. **Authentic Cross-References**: Only include [[WikiLinks]] to notes that actually exist in the vault 3. **Strategic Linking**: Follow the S.P.A.R.C. methodology with 3-8 meaningful connections per note 4. **Vault Standards**: Follow all formatting standards from the vault's CLAUDE.md and workbench protocols PROCESS: 1. First, use search tools (Grep, Glob) to find related content in the vault 2. Identify actual existing notes that relate to the topic 3. Create comprehensive notes with real vault connections 4. Use enhanced frontmatter with relevant tags found in the vault 5. Include actual [[WikiLinks]] to discovered related notes SEARCH STRATEGY: - Search for key terms related to {{topic}} - Look for notes in relevant domain folders (Art/, Computer Science/, etc.) - Identify MOCs (Maps of Content) that should link to this note - Find case studies, techniques, or concepts that relate Create detailed, professional notes that authentically integrate with the existing vault knowledge structure. ``` -------------------------------------------------------------------------------- /server/src/gates/definitions/security-awareness.json: -------------------------------------------------------------------------------- ```json { "id": "security-awareness", "name": "Security Best Practices", "type": "validation", "description": "Ensures security-conscious development practices and prevents common vulnerabilities", "guidance": "**Security Best Practices:**\n- Never include hardcoded secrets, passwords, or API keys in code\n- Validate and sanitize all user inputs\n- Use parameterized queries to prevent SQL injection\n- Implement proper authentication and authorization\n- Follow OWASP Top 10 security guidelines\n- Use HTTPS and secure communication protocols\n- Implement rate limiting for APIs\n- Log security events but never log sensitive data\n- Keep dependencies updated and scan for vulnerabilities", "pass_criteria": [ { "type": "content_check", "forbidden_patterns": [ "password=\"", "api_key=\"", "secret=\"", "token=\"", "password123", "admin123", "root:root", "SELECT * FROM" ] }, { "type": "pattern_check", "regex_patterns": [ "validate|sanitize|escape", "parameterized|prepared", "authentication|authorization", "https://|ssl|tls" ] } ], "_comment_llm_validation": "LLM self-check removed until API integration complete. Will be re-added when config.analysis.semanticAnalysis.llmIntegration is fully implemented.", "retry_config": { "max_attempts": 2, "improvement_hints": true, "preserve_context": true }, "activation": { "prompt_categories": ["code", "development"], "explicit_request": false }, "_comment": "Category gate - activates based on category only. Framework gates control methodology separately." } ``` -------------------------------------------------------------------------------- /server/src/gates/templates/research_self_validation.md: -------------------------------------------------------------------------------- ```markdown # Research Quality Self-Check Template ## Instructions Please evaluate your response against the following research quality criteria. Be honest and objective in your assessment. ## Research Quality Criteria ### Citation Requirements - [ ] **Credible Sources**: Used at least 3 credible, authoritative sources - [ ] **Publication Dates**: Included publication dates for time-sensitive information - [ ] **Source Types**: Distinguished between primary and secondary sources - [ ] **Citation Format**: Used proper citation format (mentioned source names/types) ### Content Quality - [ ] **Cross-Referencing**: Cross-referenced facts across multiple sources - [ ] **Context**: Provided appropriate context for claims and statistics - [ ] **Objectivity**: Avoided speculation and maintained objectivity - [ ] **Authority**: Used authoritative sources (academic, government, established media) ### Research Depth - [ ] **Comprehensive**: Addressed the topic thoroughly - [ ] **Current**: Used recent and relevant information when appropriate - [ ] **Balanced**: Presented multiple perspectives where applicable - [ ] **Evidence-Based**: Supported claims with concrete evidence ## Self-Assessment **Overall Research Quality Score (0.0-1.0): ___** **Reasoning for Score:** [Explain your assessment. What research standards were met? What could be improved?] **Areas for Improvement:** [If score is below 0.75, list specific areas that need enhancement] ## Validation Response Based on your self-assessment: - **PASS** if score ≥ 0.75 and all critical citation requirements are met - **NEEDS_IMPROVEMENT** if score < 0.75 or missing critical elements **Final Assessment: [PASS/NEEDS_IMPROVEMENT]** ``` -------------------------------------------------------------------------------- /server/tests/setup.ts: -------------------------------------------------------------------------------- ```typescript /** * Jest Test Setup * Global configuration and utilities for all tests */ // Set test environment process.env.NODE_ENV = 'test'; // Global test timeout - commented out as it's set in jest.config.cjs // jest.setTimeout(30000); // Mock console methods in tests if needed const originalConsoleError = console.error; const originalConsoleWarn = console.warn; // These jest globals are setup in individual test files since ES modules handle setup differently // beforeEach(() => { // // Reset mocks before each test // jest.clearAllMocks(); // }); // afterEach(() => { // // Cleanup after each test // jest.restoreAllMocks(); // }); // Global test utilities - simplified for ES modules global.testUtils = { // Suppress console output during tests suppressConsole: () => { console.error = () => {}; console.warn = () => {}; }, // Restore console output restoreConsole: () => { console.error = originalConsoleError; console.warn = originalConsoleWarn; }, // Wait for async operations waitFor: (ms: number) => new Promise(resolve => setTimeout(resolve, ms)), // Create mock logger - implementation will use jest mocks in individual tests createMockLogger: () => ({ info: () => {}, warn: () => {}, error: () => {}, debug: () => {} }) }; // Extend Jest matchers if needed declare global { namespace jest { interface Matchers<R> { // Add custom matchers here if needed } } var testUtils: { suppressConsole: () => void; restoreConsole: () => void; waitFor: (ms: number) => Promise<void>; createMockLogger: () => any; }; } // Export statement required for ES modules, but empty to avoid issues export {}; ``` -------------------------------------------------------------------------------- /server/prompts/development/analyze_file_structure.md: -------------------------------------------------------------------------------- ```markdown # Analyze File Structure ## Description Analyzes a file's structure to identify potential modules, dependencies, and organization patterns for refactoring. ## System Message You are an expert code analyst specializing in code organization and architecture. Your task is to analyze a file's structure and identify potential modules, dependencies, and patterns that could guide refactoring efforts. ## User Message Template Please analyze the structure of this {{language}} file located at {{file_path}}: ```{{language}} {{code}} ``` Provide a comprehensive structural analysis including: ## 1. Code Organization Overview - File size and complexity metrics - Main components and their purposes - Current architectural patterns used - Overall organization quality assessment ## 2. Functional Areas Identification - Core business logic sections - Utility functions and helpers - Configuration and setup code - External integrations and dependencies ## 3. Dependency Analysis - Import/require statements analysis - Internal dependencies between functions/classes - External library dependencies - Circular dependency risks ## 4. Modularization Opportunities - Logical groupings for potential modules - Cohesive functional areas - Reusable components identification - Interface boundary recommendations ## 5. Code Quality Assessment - Code smells and anti-patterns - Maintainability concerns - Performance considerations - {{language}}-specific best practices compliance ## 6. Refactoring Recommendations - Priority modules for extraction - Suggested module names and responsibilities - Interface design recommendations - Step-by-step refactoring approach Focus on practical, actionable insights that will guide effective refactoring decisions. ``` -------------------------------------------------------------------------------- /server/src/gates/definitions/technical-accuracy.json: -------------------------------------------------------------------------------- ```json { "id": "technical-accuracy", "name": "Technical Accuracy Standards", "type": "validation", "description": "Ensures technical correctness, fact-checking, and precision in technical content", "guidance": "**Technical Accuracy Standards:**\n- Verify technical facts and specifications before stating them\n- Use precise technical terminology correctly\n- Include version numbers and compatibility information where relevant\n- Distinguish between stable and experimental features\n- Provide context for technical decisions and trade-offs\n- Reference official documentation when available\n- Avoid speculation about implementation details without evidence\n- Test code examples for syntax correctness\n- Include error handling and edge cases in technical discussions", "pass_criteria": [ { "type": "content_check", "min_length": 200, "required_patterns": [ "version", "according to", "documentation", "specification" ] }, { "type": "pattern_check", "keyword_count": { "accurate": 1, "precise": 1 }, "regex_patterns": [ "v\\d+\\.\\d+", "RFC \\d+", "\\d{4}-\\d{2}-\\d{2}" ] } ], "_comment_llm_validation": "LLM self-check removed until API integration complete. Will be re-added when config.analysis.semanticAnalysis.llmIntegration is fully implemented.", "retry_config": { "max_attempts": 3, "improvement_hints": true, "preserve_context": true }, "activation": { "prompt_categories": ["development", "analysis", "research"], "explicit_request": true }, "_comment": "Category gate - activates based on category only. Framework gates control methodology separately." } ``` -------------------------------------------------------------------------------- /server/src/gates/definitions/educational-clarity.json: -------------------------------------------------------------------------------- ```json { "id": "educational-clarity", "name": "Educational Content Clarity", "type": "validation", "description": "Ensures educational content is clear, well-structured, and pedagogically sound", "guidance": "**Educational Clarity Guidelines:**\n- Start with clear learning objectives or goals\n- Use progressive complexity (simple to advanced)\n- Include concrete examples for abstract concepts\n- Provide step-by-step explanations for processes\n- Use analogies and metaphors to aid understanding\n- Include practice exercises or applications when appropriate\n- Anticipate and address common misconceptions\n- Use clear, jargon-free language with definitions for technical terms\n- Organize content with logical flow and transitions\n- Include summary or key takeaways", "pass_criteria": [ { "type": "content_check", "min_length": 400, "required_patterns": [ "example", "step", "understand", "learn" ] }, { "type": "pattern_check", "keyword_count": { "example": 2, "for example": 1 }, "regex_patterns": [ "^##\\s+.*$", "^\\d+\\.\\s+.*$", "^\\s*[-*]\\s+.*$" ] } ], "_comment_llm_validation": "LLM self-check removed until API integration complete. Will be re-added when config.analysis.semanticAnalysis.llmIntegration is fully implemented.", "retry_config": { "max_attempts": 2, "improvement_hints": true, "preserve_context": true }, "activation": { "prompt_categories": ["education", "documentation", "content_processing", "development"], "explicit_request": false }, "_comment": "Category gate - activates based on category only. Framework gates control methodology separately." } ``` -------------------------------------------------------------------------------- /server/src/gates/definitions/framework-compliance.json: -------------------------------------------------------------------------------- ```json { "id": "framework-compliance", "name": "Framework Methodology Compliance", "type": "validation", "gate_type": "framework", "description": "Ensures responses follow the active framework methodology (CAGEERF, ReACT, 5W1H, SCAMPER). This is a framework-level gate that applies universally across all categories when a framework is active.", "guidance": "**Framework Methodology Compliance:**\n- CAGEERF: Include Context, Analysis, Goals, Execution, Evaluation, Refinement, Framework considerations\n- ReACT: Show clear Reasoning and Acting phases with systematic problem-solving\n- 5W1H: Address Who, What, When, Where, Why, How in comprehensive analysis\n- SCAMPER: Apply creative thinking techniques (Substitute, Combine, Adapt, Modify, Put to other uses, Eliminate, Reverse)\n- Structure responses according to framework principles\n- Include systematic thinking and methodology awareness\n- Show iterative improvement and refinement processes", "pass_criteria": [ { "type": "content_check", "min_length": 300, "required_patterns": [ "context", "analysis", "systematic" ] }, { "type": "pattern_check", "keyword_count": { "framework": 1, "methodology": 1 } } ], "_comment_llm_validation": "LLM self-check removed until API integration complete. Will be re-added when config.analysis.semanticAnalysis.llmIntegration is fully implemented.", "retry_config": { "max_attempts": 2, "improvement_hints": true, "preserve_context": true }, "activation": { "explicit_request": false, "framework_context": ["CAGEERF", "ReACT", "5W1H", "SCAMPER"] }, "_comment": "Framework gates apply universally - no category restrictions. Activated by framework context only." } ``` -------------------------------------------------------------------------------- /server/src/gates/core/gate-definitions.ts: -------------------------------------------------------------------------------- ```typescript /** * Gate System - Shared Definitions & Interfaces * * Centralized type definitions for all gate system components. * This enables clean dependencies and consistent interfaces. */ /** * Gate type classification for precedence and activation logic */ export type GateType = 'framework' | 'category' | 'quality' | 'security'; /** * Gate definition structure loaded from JSON files */ export interface GateDefinition { id: string; name: string; guidance: string; gate_type?: GateType; // Framework gates bypass category checks activation: { prompt_categories?: string[]; framework_context?: string[]; explicit_request?: boolean; }; } /** * Context information for gate activation and rendering */ export interface GateContext { framework?: string; category?: string; promptId?: string; } /** * Gate selection criteria for intelligent selection */ export interface GateSelectionCriteria { framework?: string; category?: string; promptId?: string; executionMode?: 'prompt' | 'template' | 'chain'; complexityLevel?: 'low' | 'medium' | 'high'; } /** * Result of gate selection with reasoning */ export interface GateSelectionResult { selectedGates: string[]; reasoning: string[]; confidence: number; estimatedExecutionTime: number; fallbackGates: string[]; } /** * Performance metrics for individual gates */ export interface GatePerformanceMetrics { gateId: string; avgExecutionTime: number; successRate: number; retryRate: number; lastUsed: Date; usageCount: number; } /** * Overall gate system analytics */ export interface GateSystemAnalytics { totalGates: number; avgExecutionTime: number; overallSuccessRate: number; topPerformingGates: string[]; underperformingGates: string[]; recommendations: string[]; } ``` -------------------------------------------------------------------------------- /server/prompts/documentation/docs-content-creation.md: -------------------------------------------------------------------------------- ```markdown # Content Creation (Step 3 of 5) ## Description Transform the content plan into well-crafted documentation ## System Message [System Info: You are a technical writer who excels at creating clear, concise, and comprehensive documentation. Your goal is to transform content plans into well-crafted documentation that effectively communicates technical information to the target audience.] ## User Message Template I need to create the content for {{doc_type}} documentation based on this content plan: {{previous_message}} For this project: {{project_info}} With this target audience: {{audience}} Please create the full documentation content following these technical writing best practices: 1. Write with clarity and precision - Use consistent terminology throughout - Define technical terms on first use - Maintain appropriate technical depth for the audience - Write in active voice with direct instructions 2. Structure content for readability - Use clear hierarchical headings (H1, H2, H3, etc.) - Keep paragraphs focused and concise - Use bullet points and numbered lists appropriately - Include informative code comments in examples 3. Follow documentation conventions - Use proper Markdown formatting - Create comprehensive code examples with proper syntax highlighting - Include descriptive captions for any tables or figures - Properly format command-line instructions, API endpoints, etc. 4. Ensure content completeness - Address all sections outlined in the content plan - Provide sufficient context and explanation for technical concepts - Include all necessary cross-references between related sections - Cover error cases and edge conditions where appropriate Please produce the complete documentation content organized according to the content plan, ready for final review and refinement. ``` -------------------------------------------------------------------------------- /server/prompts/content_processing/vault_related_notes_finder.md: -------------------------------------------------------------------------------- ```markdown # Vault Related Notes Finder ## Description Searches vault for actual related notes using content analysis and glob/grep patterns to find real cross-references ## System Message You are an expert assistant providing structured, systematic analysis. Apply appropriate methodology and reasoning frameworks to deliver comprehensive responses. ## User Message Template Search the vault for actual related notes to: {{note_topic}} Current note content areas: {{content_areas}} Vault root path: {{vault_path}} Execute systematic vault search to find real related notes: **PHASE 1: Semantic Search Strategy** - Extract key concepts, terminology, and domain keywords from note content - Identify parent domains (e.g., for typography: art, design, visual_communication) - Map related disciplines and cross-domain connections **PHASE 2: Vault Structure Analysis** - Use Glob patterns to explore relevant directory structures - Search for MOCs (Maps of Content) in related domains - Identify hub notes and navigation centers **PHASE 3: Content Discovery** - Use Grep with key terminology to find actual related content - Search for complementary topics and techniques - Find case studies, examples, and practical applications **PHASE 4: Relationship Validation** - Verify found notes actually relate to the topic - Read key sections to confirm relevance - Prioritize direct relationships over tangential connections **PHASE 5: Strategic Link Selection** - Select 3-5 most relevant and valuable related notes - Prioritize: MOCs > Fundamental concepts > Practical applications > Case studies - Format as proper [[WikiLinks]] with existing file names **Output Requirements:** 1. List actual file paths found in vault 2. Briefly explain relevance of each related note 3. Provide final Related Notes section with 3-5 [[WikiLinks]] 4. Ensure all links point to real existing files in vault ``` -------------------------------------------------------------------------------- /server/prompts/documentation/docs-content-planning.md: -------------------------------------------------------------------------------- ```markdown # Content Planning (Step 2 of 5) ## Description Create a detailed content plan and structure for the documentation ## System Message [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.] ## User Message Template Based on the project analysis: {{previous_message}} I need to create a detailed content plan for {{doc_type}} documentation targeting {{audience}}. Please develop a comprehensive documentation plan that includes: 1. A detailed table of contents with all main sections and subsections organized in a logical progression 2. For each section, specify: - Key information to cover - Recommended depth of technical detail based on audience needs - Specific examples, diagrams, or code snippets to include - Estimated length/importance of each section 3. A recommended documentation structure that follows these best practices: - Progressive disclosure (basic concepts before advanced ones) - Logical grouping of related topics - Clear navigation paths for different user journeys - Appropriate cross-referencing between related sections 4. Special considerations for: - Getting started/quickstart content for new users - Troubleshooting sections for common issues - Reference materials vs. conceptual explanations vs. tutorials - Version-specific information (if applicable) 5. Documentation metadata and supporting elements: - Necessary disclaimers, prerequisites, or system requirements - Glossary terms that should be defined - Additional resources or external references to include 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. ``` -------------------------------------------------------------------------------- /server/prompts/documentation/docs-final-assembly.md: -------------------------------------------------------------------------------- ```markdown # Final Assembly (Step 5 of 5) ## Description Create the final, production-ready version of the documentation ## System Message [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.] ## User Message Template I have documentation content that has been reviewed with suggestions for improvement: {{previous_message}} For this documentation type: {{doc_type}} For this target audience: {{audience}} {% if depth_level %}At this depth level: {{depth_level}}{% endif %} Please create the final, production-ready version of this documentation by: 1. Incorporating all suggested refinements and improvements 2. Ensuring perfect formatting using proper Markdown (or specified format) 3. Adding appropriate front matter and metadata: - Title and description - Table of contents - Version information - Author/contributor information - Last updated date - Appropriate license information 4. Including these essential documentation elements: - Informative introduction that establishes purpose and scope - Clear navigation structure with logical content progression - Proper heading hierarchy and section organization - Consistent formatting of code blocks, notes, warnings, etc. - Complete table of contents with working anchor links 5. Final organization optimizations: - Ensuring related information is grouped together - Breaking very long sections into more digestible chunks - Adding "See also" sections where appropriate - Including a glossary for technical terms if needed 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. ``` -------------------------------------------------------------------------------- /server/src/gates/templates/code_quality_validation.md: -------------------------------------------------------------------------------- ```markdown # Code Quality Self-Check Template ## Instructions Evaluate the code you've generated against industry best practices and quality standards. ## Code Quality Criteria ### Error Handling & Robustness - [ ] **Error Handling**: Includes appropriate try-catch blocks or error handling - [ ] **Input Validation**: Validates inputs and handles edge cases - [ ] **Boundary Conditions**: Considers boundary conditions and null/undefined cases - [ ] **Graceful Degradation**: Fails gracefully with meaningful error messages ### Code Structure & Readability - [ ] **Clear Naming**: Uses descriptive, consistent naming conventions - [ ] **Comments**: Includes inline comments for complex logic - [ ] **Function Size**: Functions are focused and reasonably sized - [ ] **Code Organization**: Well-structured and logically organized ### Best Practices - [ ] **Security**: Follows security best practices (no hardcoded secrets, input sanitization) - [ ] **Performance**: Considers performance implications - [ ] **Maintainability**: Easy to understand and modify - [ ] **Documentation**: Includes basic function documentation/docstrings ### Code Quality Indicators - [ ] **No TODO/FIXME**: No placeholder comments or incomplete code - [ ] **Consistent Style**: Follows consistent coding style - [ ] **Modern Patterns**: Uses appropriate modern language features - [ ] **Testing Ready**: Code structure supports testing ## Self-Assessment **Overall Code Quality Score (0.0-1.0): ___** **Quality Breakdown:** - Error Handling: ___/10 - Readability: ___/10 - Security: ___/10 - Maintainability: ___/10 **Code Review Notes:** [Describe the strengths and weaknesses of the generated code] **Specific Improvements Needed:** [List concrete improvements if score < 0.8] ## Validation Response Based on your assessment: - **PASS** if score ≥ 0.8 and no critical security/error handling issues - **NEEDS_IMPROVEMENT** if score < 0.8 or has critical flaws **Final Assessment: [PASS/NEEDS_IMPROVEMENT]** ``` -------------------------------------------------------------------------------- /server/src/gates/templates/structure_validation.md: -------------------------------------------------------------------------------- ```markdown # Content Structure Self-Check Template ## Instructions Assess the organization, clarity, and structure of your content response. ## Structure Quality Criteria ### Organization & Flow - [ ] **Clear Headings**: Uses appropriate headings (##, ###) to organize content - [ ] **Logical Sequence**: Information flows logically from introduction to conclusion - [ ] **Section Balance**: Sections are appropriately sized and balanced - [ ] **Smooth Transitions**: Good transitions between sections and ideas ### Clarity & Readability - [ ] **List Usage**: Uses bullet points or numbered lists for clarity - [ ] **Paragraph Length**: Paragraphs are reasonably sized (3-5 sentences) - [ ] **Sentence Structure**: Varies sentence length and structure - [ ] **Technical Clarity**: Complex concepts are explained clearly ### Content Enhancement - [ ] **Examples**: Includes relevant examples when explaining concepts - [ ] **Visual Elements**: Uses formatting (bold, italic, code blocks) appropriately - [ ] **Actionable Content**: Provides actionable insights or steps where relevant - [ ] **Summary/Conclusion**: Includes appropriate summary or next steps ### Reader Experience - [ ] **Scannable**: Content is easy to scan and navigate - [ ] **Consistent Tone**: Maintains consistent tone and style throughout - [ ] **Appropriate Length**: Content length matches the complexity of the topic - [ ] **Engaging**: Content is engaging and maintains reader interest ## Self-Assessment **Overall Structure Quality Score (0.0-1.0): ___** **Structure Breakdown:** - Organization: ___/10 - Readability: ___/10 - Clarity: ___/10 - Reader Experience: ___/10 **Structure Analysis:** [Evaluate how well the content is organized and presented] **Missing Elements:** [Identify structural elements that could improve the content] ## Validation Response Assessment criteria: - **PASS** if score ≥ 0.7 and has clear headings/organization - **NEEDS_IMPROVEMENT** if score < 0.7 or lacks basic structure **Final Assessment: [PASS/NEEDS_IMPROVEMENT]** ``` -------------------------------------------------------------------------------- /server/prompts/analysis/review.md: -------------------------------------------------------------------------------- ```markdown # review ## Description Comprehensive audit template for modules, implementations, and system integrations ## System Message You are an expert system architect and code reviewer. Conduct thorough, evidence-based analysis. Focus on reliability, integration quality, duplication detection, and consolidation opportunities. ## User Message Template Conduct a comprehensive audit of: {{target}} ## Implementation Analysis 1. **Current Functionality** - What is the current functionality and purpose? - What are the implementation details and patterns used? - What are the dependencies and interfaces? 2. **Reliability Assessment** - Is the functionality reliable and robust? - Are there error handling gaps or edge cases? - What are the failure modes and recovery mechanisms? ## Integration Analysis 3. **Integration Mapping** - Which modules/systems currently use this functionality? - Are all required integration points properly hooked up? - Are there missing integrations that should exist? 4. **System Coordination** - Does it integrate with the right system coordinators/conductors? - Is the coordination pattern consistent with architecture? - Are lifecycle management hooks properly implemented? ## Duplication & Consolidation 5. **Duplication Detection** - Are there duplicate implementations of similar functionality? - Do multiple modules provide overlapping capabilities? - What percentage of functionality is duplicated? 6. **Consolidation Opportunities** - Should these modules be consolidated? - What would be the benefits and risks of consolidation? - What is the migration complexity? ## Recommendations 7. **Refactoring Assessment** - Should the implementation be refactored? - What specific improvements are recommended? - What is the priority level (Critical/High/Medium/Low)? 8. **Action Items** - Prioritized list of recommended actions - Risk assessment for each recommendation - Success criteria for improvements Provide evidence-based, actionable recommendations with specific file paths and line numbers where relevant. ``` -------------------------------------------------------------------------------- /server/prompts/analysis/note_refinement.md: -------------------------------------------------------------------------------- ```markdown # Note Refinement ## Description Refine existing notes by improving organization, flow, and clarity without adding or modifying the content. ## User Message Template Please refine and reorganize the following notes into a beautiful, well-structured reference page that will be easy to use in the future: {{previous_message}} Create a polished note page by following these specific refinement guidelines: **STRUCTURE & ORGANIZATION:** - Use clear hierarchical headings (# ## ### ####) to create logical sections - Organize content from general concepts to specific details - Group related information together under appropriate headings - Create a logical flow that builds understanding progressively **VISUAL FORMATTING:** - Use **bold** for key terms, concepts, and important points - Use _italics_ for emphasis and definitions - Apply consistent bullet points for lists and sub-points - Use numbered lists for processes, steps, or ordered information - Add horizontal rules (---) to separate major sections when needed **CONTENT ENHANCEMENT:** - Create a brief summary or overview at the beginning if the content is complex - Add "Key Takeaways" or "Important Points" sections where appropriate - Use blockquotes (>) for important quotes, definitions, or highlighted concepts - Ensure each section has a clear purpose and contribution to the overall topic **READABILITY IMPROVEMENTS:** - Break up large text blocks into digestible paragraphs - Use consistent formatting throughout the document - Ensure proper spacing between sections - Make the document scannable with clear visual hierarchy - Add context or brief explanations where connections might not be obvious **REFERENCE OPTIMIZATION:** - Structure the content so key information can be quickly located - Use descriptive section headings that clearly indicate content - Maintain all original information while improving presentation - Create a format that supports both quick reference and deeper reading Transform the content into a professional, well-organized reference document that maintains all original information while dramatically improving usability and visual appeal. ``` -------------------------------------------------------------------------------- /server/prompts/content_processing/video_notes_enhanced.md: -------------------------------------------------------------------------------- ```markdown # Enhanced Video Notes Chain ## Description Comprehensive video processing chain including content analysis, visual extraction, vault integration, and note creation with proper formatting ## User Message Template Process video content into comprehensive vault-integrated notes with visual content extraction. Video URL: {{video_url}} Topic: {{topic}} Content Areas: {{content_areas}} Video Duration: {{duration}} This enhanced chain will: 1. **Analyze Content**: Extract key concepts and educational structure 2. **Extract Visuals**: Download relevant visual examples and integrate into notes 3. **Deep Analysis**: Apply ReACT methodology for insights and connections 4. **Create Notes**: Generate comprehensive markdown with proper formatting 5. **Vault Integration**: Find actual related notes in vault for cross-referencing 6. **Final Refinement**: Polish formatting and ensure S.P.A.R.C. compliance The result will be a professionally formatted note with embedded visual examples, proper vault integration, and comprehensive educational content. ## Chain Steps 1. **Initial Content Analysis** (content_analysis) - Input Mapping: {"content":"video_content"} - Output Mapping: {"analysis_output":"content_analysis"} 2. **Visual Content Extraction** (video_visual_extraction) - Input Mapping: {"video_url":"video_url","topic":"topic","content_areas":"content_areas"} - Output Mapping: {"visual_content":"extracted_visuals"} 3. **Deep Analysis Integration** (deep_analysis) - Input Mapping: {"content":"video_content","initial_analysis":"content_analysis"} - Output Mapping: {"deep_analysis_output":"deep_insights"} 4. **Comprehensive Note Creation** (markdown_notebook) - Input Mapping: {"topic":"topic","analysis":"deep_insights"} - Output Mapping: {"notebook_output":"structured_notes"} 5. **Vault Integration** (vault_related_notes_finder) - Input Mapping: {"note_topic":"topic","content_areas":"content_areas"} - Output Mapping: {"related_notes":"vault_connections"} 6. **Final Refinement** (note_refinement) - Input Mapping: {"notes":"structured_notes"} - Output Mapping: {"final_notes":"polished_output"} ``` -------------------------------------------------------------------------------- /server/src/frameworks/types/index.ts: -------------------------------------------------------------------------------- ```typescript /** * Framework Types Index * * Consolidated export of all framework-related type definitions. * This replaces the distributed type definitions across multiple files * and provides a single source of truth for framework types. */ // Methodology guide types export type { FrameworkMethodology, FrameworkDefinition, FrameworkExecutionContext, FrameworkSelectionCriteria, PromptCreationGuidance, ProcessingGuidance, StepGuidance, MethodologyEnhancement, ArgumentGuidance, ProcessingStep, ExecutionStep, QualityGate, TemplateEnhancement, MethodologyToolDescription, MethodologyToolDescriptions, MethodologyValidation, IMethodologyGuide } from './methodology-types.js'; export { BaseMethodologyGuide } from './methodology-types.js'; // Prompt guidance types export type { SystemPromptInjectionConfig, SystemPromptInjectionResult, TemplateEnhancementConfig, TemplateEnhancementType, TemplateEnhancementResult, AppliedEnhancement, MethodologyTrackingState, MethodologySwitchRecord, MethodologyStateChangeEvent, PromptGuidanceConfig, PromptGuidanceResult, PromptGuidanceAnalytics, FrameworkStateInfo, IPromptGuidanceService, // Phase 3 additions MethodologyState, MethodologySwitchRequest, MethodologyHealth, PersistedMethodologyState, TemplateProcessingGuidance } from './prompt-guidance-types.js'; // Integration types export type { IntegratedAnalysisResult, FrameworkSwitchingConfig, FrameworkAlignmentResult, FrameworkUsageInsights, FrameworkUsageMetrics, FrameworkSwitchRecommendation, MCPToolIntegrationContext, MCPToolIntegrationResult, SemanticIntegrationConfig, CrossSystemIntegrationStatus, IntegrationPerformanceMetrics, IntegrationEvent, IFrameworkSemanticIntegration, IMCPToolIntegration, SystemIntegrationConfig } from './integration-types.js'; // Legacy type aliases for backward compatibility during migration // These will be removed in Phase 4 export type { FrameworkDefinition as LegacyFrameworkDefinition, FrameworkExecutionContext as LegacyFrameworkExecutionContext, FrameworkSelectionCriteria as LegacyFrameworkSelectionCriteria } from './methodology-types.js'; ``` -------------------------------------------------------------------------------- /server/src/gates/templates/security_validation.md: -------------------------------------------------------------------------------- ```markdown # Security Validation Self-Check Template ## Instructions Evaluate the security aspects of your response, especially for code generation and technical content. ## Security Assessment Criteria ### Code Security (if applicable) - [ ] **No Hardcoded Secrets**: Code does not contain hardcoded passwords, API keys, or tokens - [ ] **Input Validation**: All user inputs are properly validated and sanitized - [ ] **SQL Injection Prevention**: Uses parameterized queries or prepared statements - [ ] **Authentication**: Proper authentication mechanisms are implemented - [ ] **Authorization**: Appropriate access controls are in place - [ ] **HTTPS/TLS**: Secure communication protocols are used - [ ] **Error Handling**: Errors don't expose sensitive information ### General Security Awareness - [ ] **OWASP Compliance**: Follows OWASP Top 10 security guidelines - [ ] **Rate Limiting**: API endpoints include rate limiting considerations - [ ] **Logging Security**: Security events are logged without exposing sensitive data - [ ] **Dependency Security**: Discusses keeping dependencies updated - [ ] **Principle of Least Privilege**: Access is limited to minimum necessary ### Security Education - [ ] **Vulnerability Awareness**: Addresses potential security vulnerabilities - [ ] **Best Practices**: Includes security best practices and recommendations - [ ] **Risk Assessment**: Identifies and discusses security risks - [ ] **Mitigation Strategies**: Provides concrete security mitigation approaches ## Self-Assessment **Overall Security Score (0.0-1.0): ___** **Security Breakdown:** - Code Security: ___/10 - Awareness: ___/10 - Education: ___/10 - Best Practices: ___/10 **Security Review:** [Assess how well the response addresses security considerations] **Identified Security Issues:** [List any potential security concerns or missing security considerations] **Security Improvements Needed:** [Specific improvements if score < 0.85] ## Validation Response Security assessment criteria: - **PASS** if score ≥ 0.85 and no critical security issues identified - **NEEDS_IMPROVEMENT** if score < 0.85 or contains security vulnerabilities **Final Assessment: [PASS/NEEDS_IMPROVEMENT]** ``` -------------------------------------------------------------------------------- /server/prompts/development/strategicImplement.md: -------------------------------------------------------------------------------- ```markdown # Strategic Implementation ## Description Systematically implement a plan phase with architectural alignment, compatibility checking, and progress tracking ## User Message Template Strategically implement the following plan phase with systematic architectural alignment: **Plan Document**: {{plan_path}} **Phase to Implement**: {{phase_identifier}} ## Implementation Protocol ### 1. Context Discovery & Analysis - Read and analyze the plan document thoroughly - Understand the phase objectives, requirements, and success criteria - Map dependencies and integration points with existing systems - Identify potential compatibility issues and risks ### 2. Architectural Alignment - Review current system architecture for alignment points - Check interface compatibility with existing systems - Identify required changes to maintain consistency - Plan for backwards compatibility where needed ### 3. Strategic Implementation - Implement changes incrementally with validation at each step - Follow established patterns and conventions from the codebase - Maintain existing functionality while adding new capabilities - Use appropriate design patterns (composition over inheritance, service patterns, etc.) ### 4. Validation & Testing - Run typecheck to ensure TypeScript compliance - Execute relevant tests to verify functionality - Check for integration issues with dependent systems - Validate performance impact ### 5. Progress Tracking - Update the plan document with implementation status - Mark completed tasks and note any deviations - Document decisions made during implementation - Record any blockers or issues encountered ## Expected Outputs 1. **Implementation**: Complete, tested code changes aligned with architecture 2. **Updated Plan**: Progress notes, completion status, and next steps 3. **Documentation**: Key decisions and any architectural changes 4. **Validation**: Test results and compatibility verification Apply the following principles: - **Understand before changing**: Analyze existing code thoroughly - **Incremental progress**: Small, validated steps - **Maintain compatibility**: Preserve existing interfaces - **Follow patterns**: Use established architectural patterns - **Track progress**: Keep plan document current ``` -------------------------------------------------------------------------------- /server/prompts/analysis/deep_analysis.md: -------------------------------------------------------------------------------- ```markdown # Deep Analysis ## Description Expand on a previous analysis by diving deeper into information, identifying key insights and relationships. ## System Message 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. ## User Message Template Based on the initial content analysis, please conduct a comprehensive deep analysis: **Original Content:** {{content|default("No content provided")}} **Initial Analysis Results:** {{initial_analysis|default("No previous analysis provided")}} ## Deep Analysis Framework Please provide a thorough deep analysis by examining: ### 1. **Key Insights Identification** - Extract the most significant insights from the content - Identify patterns and trends that emerge - Highlight unexpected or counterintuitive findings ### 2. **Relationship Mapping** - Identify connections between different concepts - Map cause-and-effect relationships - Uncover hidden dependencies and correlations ### 3. **Contextual Analysis** - Place findings within broader context - Consider historical or comparative perspectives - Analyze implications for different stakeholders ### 4. **Critical Evaluation** - Assess the reliability and significance of findings - Identify potential limitations or biases - Evaluate the strength of evidence presented ### 5. **Strategic Implications** - Determine practical applications of insights - Identify actionable recommendations - Consider future implications and trends ## Output Format Structure your deep analysis as follows: ```markdown # Deep Analysis Results ## Executive Summary [2-3 sentences capturing the most critical insights] ## Key Insights [Detailed findings with supporting evidence] ## Relationship Networks [Connections and interdependencies identified] ## Critical Assessment [Evaluation of findings and their reliability] ## Strategic Implications [Actionable insights and recommendations] ## Areas for Further Investigation [Questions or areas requiring additional research] ``` 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 # Review and Refinement (Step 4 of 5) ## Description Review the documentation for accuracy, clarity, completeness, and usability ## System Message [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.] ## User Message Template I've created initial documentation content: {{previous_message}} For this documentation type: {{doc_type}} For this audience: {{audience}} {% if depth_level %}At this depth level: {{depth_level}}{% endif %} Please perform a comprehensive review and refinement of this documentation, focusing on: 1. Technical accuracy and precision - Verify that technical explanations are correct and precise - Check that code samples would actually work as described - Ensure API references match expected behavior - Confirm that terminology is used consistently and correctly 2. Clarity and readability - Identify overcomplicated explanations that could be simplified - Find sections that need additional context or explanation - Check for logical flow and clear progression of ideas - Ensure headings accurately reflect section content 3. Completeness and coverage - Identify missing information or underdeveloped sections - Check for edge cases or scenarios that aren't addressed - Ensure prerequisites and dependencies are clearly stated - Verify that all user questions are anticipated and answered 4. Format and presentation - Check for consistent formatting and style throughout - Ensure proper use of Markdown or other formatting elements - Verify that code blocks are properly formatted with syntax highlighting - Check that diagrams and visuals are clear and properly referenced 5. User experience improvements - Suggest additional examples where they would be helpful - Identify places where diagrams could clarify complex concepts - Recommend improved navigation or cross-referencing - Find opportunities for progressive disclosure of complex topics 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. ``` -------------------------------------------------------------------------------- /server/src/gates/templates/educational_clarity_validation.md: -------------------------------------------------------------------------------- ```markdown # Educational Clarity Self-Check Template ## Instructions Evaluate how effectively your response serves educational purposes and promotes understanding. ## Educational Effectiveness Criteria ### Learning Structure - [ ] **Clear Objectives**: Learning goals or objectives are stated or implied - [ ] **Progressive Complexity**: Content moves from simple to complex concepts - [ ] **Logical Sequence**: Ideas flow in a logical, easy-to-follow order - [ ] **Clear Transitions**: Smooth transitions between concepts and sections - [ ] **Summary/Recap**: Includes summary or key takeaways ### Clarity and Accessibility - [ ] **Plain Language**: Uses clear, jargon-free language when possible - [ ] **Defined Terms**: Technical terms are defined or explained - [ ] **Concrete Examples**: Abstract concepts supported with concrete examples - [ ] **Analogies/Metaphors**: Uses helpful analogies to aid understanding - [ ] **Visual Structure**: Well-organized with headers, lists, and formatting ### Pedagogical Elements - [ ] **Step-by-Step**: Processes broken down into clear steps - [ ] **Practice Opportunities**: Includes exercises, questions, or applications - [ ] **Common Misconceptions**: Addresses potential misunderstandings - [ ] **Multiple Perspectives**: Presents information from different angles - [ ] **Real-World Applications**: Shows practical applications of concepts ### Engagement and Understanding - [ ] **Reader Engagement**: Content maintains reader interest and attention - [ ] **Comprehension Checks**: Includes ways to verify understanding - [ ] **Appropriate Difficulty**: Content level matches intended audience - [ ] **Interactive Elements**: Encourages active learning and participation - [ ] **Motivational Context**: Explains why the information is valuable ## Self-Assessment **Overall Educational Clarity Score (0.0-1.0): ___** **Educational Breakdown:** - Learning Structure: ___/10 - Clarity/Accessibility: ___/10 - Pedagogical Elements: ___/10 - Engagement: ___/10 **Target Audience: [Beginner/Intermediate/Advanced]** **Educational Effectiveness Review:** [Assess how well the content serves educational purposes] **Learning Obstacles:** [Identify any barriers to understanding] **Clarity Improvements Needed:** [Specific improvements if score < 0.8] ## Validation Response Educational clarity assessment: - **PASS** if score ≥ 0.8 and content effectively promotes learning - **NEEDS_IMPROVEMENT** if score < 0.8 or lacks educational structure **Final Assessment: [PASS/NEEDS_IMPROVEMENT]** ``` -------------------------------------------------------------------------------- /server/src/gates/templates/technical_accuracy_validation.md: -------------------------------------------------------------------------------- ```markdown # Technical Accuracy Self-Check Template ## Instructions Evaluate the technical correctness and precision of your response. ## Technical Accuracy Criteria ### Factual Correctness - [ ] **Verified Facts**: Technical facts and specifications are accurate and verifiable - [ ] **Version Specificity**: Includes relevant version numbers and compatibility information - [ ] **Official Sources**: References official documentation when available - [ ] **Current Information**: Uses up-to-date technical information - [ ] **Precise Terminology**: Uses technical terms correctly and precisely ### Technical Depth - [ ] **Implementation Details**: Provides accurate implementation details where relevant - [ ] **Error Handling**: Addresses error conditions and edge cases appropriately - [ ] **Performance Considerations**: Discusses performance implications accurately - [ ] **Best Practices**: Follows established technical best practices - [ ] **Code Correctness**: Code examples are syntactically correct and functional ### Evidence and Support - [ ] **Documentation References**: Links to or mentions official documentation - [ ] **Standards Compliance**: Follows relevant technical standards (RFC, ISO, etc.) - [ ] **Testing Verification**: Code examples can be tested and verified - [ ] **Context Appropriate**: Technical level matches the intended audience - [ ] **Trade-off Analysis**: Discusses technical trade-offs and alternatives ### Precision and Clarity - [ ] **Specific Details**: Avoids vague generalizations with concrete specifics - [ ] **Accurate Measurements**: Provides accurate performance metrics or specifications - [ ] **Clear Limitations**: Clearly states limitations and constraints - [ ] **Distinction Clarity**: Distinguishes between different technical concepts clearly ## Self-Assessment **Overall Technical Accuracy Score (0.0-1.0): ___** **Technical Breakdown:** - Factual Correctness: ___/10 - Technical Depth: ___/10 - Evidence/Support: ___/10 - Precision/Clarity: ___/10 **Technical Verification:** [Evaluate the accuracy and precision of technical content] **Sources Consulted:** [List any official documentation or standards referenced] **Areas Requiring Verification:** [Identify any technical claims that need additional verification if score < 0.8] ## Validation Response Technical accuracy assessment: - **PASS** if score ≥ 0.8 and all critical technical facts verified - **NEEDS_IMPROVEMENT** if score < 0.8 or contains unverified technical claims **Final Assessment: [PASS/NEEDS_IMPROVEMENT]** ``` -------------------------------------------------------------------------------- /server/prompts/analysis/content_analysis.md: -------------------------------------------------------------------------------- ```markdown # Content Analysis ## Description Systematically analyze web content, breaking it down into key components. ## System Message You are a content analysis expert. Follow the provided framework to systematically break down and analyze the given content. ## User Message Template Perform a comprehensive content analysis of the following material: {{content}} **ANALYSIS FRAMEWORK - Execute each step systematically:** ### 1. Initial Content Overview - **Content Type**: Identify the format and medium (article, video transcript, report, etc.) - **Source**: Note the origin and credibility indicators - **Length**: Approximate word count and reading time - **Date/Context**: When was this created and in what context? ### 2. Structural Analysis - **Main Sections**: Break down the content into logical sections/chapters - **Argument Flow**: How does the content progress logically? - **Supporting Elements**: What evidence, examples, or data are used? - **Visual Elements**: Any charts, images, or multimedia components? ### 3. Key Themes & Topics - **Primary Theme**: What is the main subject or thesis? - **Secondary Themes**: What supporting topics are covered? - **Keywords**: Extract the most important terms and concepts - **Tone & Style**: Formal, informal, persuasive, informative, etc. ### 4. Critical Analysis - **Strengths**: What aspects are well-developed or compelling? - **Weaknesses**: What gaps, biases, or unclear areas exist? - **Evidence Quality**: How strong is the supporting evidence? - **Logical Consistency**: Are the arguments coherent and well-reasoned? ### 5. Key Insights & Takeaways - **Main Messages**: What are the 3-5 most important points? - **Actionable Items**: What specific actions or recommendations are suggested? - **Implications**: What are the broader consequences or applications? - **Questions Raised**: What important questions does this content raise? ### 6. Content Categorization - **Audience**: Who is the intended audience? - **Purpose**: What is the content trying to achieve? - **Genre/Category**: How would you classify this content? - **Complexity Level**: Beginner, intermediate, or advanced? ### 7. Summary & Conclusion - **Executive Summary**: Provide a concise 2-3 sentence overview - **Key Quotes**: Extract 2-3 most significant quotes or statements - **Further Research**: What topics warrant additional investigation? - **Related Content**: What other materials would complement this? **OUTPUT FORMAT**: Present your analysis in the above structured format with clear headings and bullet points for easy navigation and reference. ``` -------------------------------------------------------------------------------- /server/prompts/development/code_review_optimization_chain.md: -------------------------------------------------------------------------------- ```markdown # Comprehensive Code Review ## Description Systematic 6-step code review covering structure, functionality, security, performance, optimization, and quality assurance ## System Message You are an expert code reviewer providing systematic, comprehensive analysis. Apply appropriate methodology (CAGEERF/ReACT) to deliver structured, evidence-based feedback with actionable recommendations. ## User Message Template # Comprehensive Code Review **Target Code**: {{target_code}} **Language/Framework**: {{language_framework}} **Performance Goals**: {{performance_goals}} This chain performs a systematic 6-step code review: ## Step 1: Structure & Organization Analysis Analyze code architecture, organization, patterns, naming conventions, documentation, and dependency management. **Output Required**: Structural assessment with identified patterns, coupling issues, and organization recommendations. --- ## Step 2: Functionality & Logic Review Examine business logic correctness, edge cases, error handling, input/output processing, and algorithm efficiency. **Output Required**: Logic validation with edge case analysis, error handling assessment, and correctness verification. --- ## Step 3: Security & Best Practices Audit Review for security vulnerabilities: input validation, authentication/authorization, data exposure, injection risks, and framework-specific security patterns. **Output Required**: Security assessment with vulnerability identification, risk levels, and mitigation strategies. --- ## Step 4: Performance Analysis Evaluate time complexity, memory usage, I/O efficiency, caching opportunities, and database query optimization. **Output Required**: Performance metrics with complexity analysis, bottleneck identification, and optimization opportunities. --- ## Step 5: Optimization Implementation Apply identified optimizations: refactor algorithms, implement performance improvements, add caching, optimize data structures, reduce complexity. **Output Required**: Optimized code with documented changes, performance improvements, and refactoring rationale. --- ## Step 6: Quality Assurance & Documentation Finalize with: code formatting consistency, test coverage analysis, documentation updates, performance benchmarking, and summary with metrics. **Output Required**: Final review report with quality metrics, test coverage, performance benchmarks, and comprehensive summary. ## Gate Configuration ```json { "include": [ "code-quality", "research-quality", "technical-accuracy", "content-structure", "security-awareness" ], "framework_gates": true } ``` ``` -------------------------------------------------------------------------------- /server/src/execution/parsers/index.ts: -------------------------------------------------------------------------------- ```typescript /** * Execution Parsers Export Module * * Centralizes all parsing infrastructure exports including: * - Unified Command Parser with multi-strategy parsing * - Argument Processing Pipeline with validation and enrichment * - Compatibility Wrapper for backward compatibility */ // Core parsing infrastructure export { UnifiedCommandParser, createUnifiedCommandParser, type CommandParseResult } from './unified-command-parser.js'; export { ArgumentParser, createArgumentParser, type ArgumentParsingResult, type ExecutionContext } from './argument-parser.js'; // Context resolution system export { ContextResolver, createContextResolver, type ContextResolution, type ContextProvider, type ContextSource, type ContextAggregationOptions } from '../context/context-resolver.js'; // Backward compatibility wrapper removed - migration completed // Legacy parsing methods are preserved through deprecated redirects in consolidated-prompt-engine.ts // Re-export for convenience export type { PromptData, PromptArgument, ConvertedPrompt } from '../../types/index.js'; export type { ValidationResult, ValidationError, ValidationWarning } from '../types.js'; import { Logger } from "../../logging/index.js"; import { UnifiedCommandParser, createUnifiedCommandParser } from "./unified-command-parser.js"; import { ArgumentParser, createArgumentParser } from "./argument-parser.js"; import { ContextResolver, createContextResolver } from "../context/context-resolver.js"; /** * Complete parsing system with all components */ export interface ParsingSystem { commandParser: UnifiedCommandParser; argumentParser: ArgumentParser; contextResolver: ContextResolver; } /** * Factory function to create complete parsing system * * Creates a fully configured parsing system with: * - Unified command parser with multi-strategy support * - Argument processor with validation and type coercion * - Context resolver with intelligent fallbacks * * @param logger Logger instance for system-wide logging * @returns Complete parsing system ready for use */ export function createParsingSystem(logger: Logger): ParsingSystem { const commandParser = createUnifiedCommandParser(logger); const argumentParser = createArgumentParser(logger); const contextResolver = createContextResolver(logger); logger.info("Parsing system initialized successfully"); logger.info("- Unified command parser with multi-strategy support"); logger.info("- Argument parser with validation pipeline"); logger.info("- Context resolver with intelligent fallbacks"); return { commandParser, argumentParser, contextResolver }; } ``` -------------------------------------------------------------------------------- /server/prompts/analysis/deep_research.md: -------------------------------------------------------------------------------- ```markdown # Deep Research Framework ## Description A comprehensive framework for conducting thorough, methodical research on complex topics with academic rigor. ## System Message 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. ## User Message Template # Deep Research Framework I need you to conduct deep research on {{topic}}. Approach this as a professional researcher would, with methodical analysis, critical thinking, and intellectual honesty. ## Research Structure 1. **Topic Exploration (Breadth)** - Define the core concepts, terminology, and scope - Map the key areas, sub-topics, and domains of knowledge - Identify the major schools of thought and contrasting perspectives - Establish historical context and evolution of understanding 2. **Deep Dive Analysis (Depth)** - Analyze the most significant developments, breakthroughs, or controversies - Examine the methodologies, evidence, and reasoning behind key findings - Identify gaps, limitations, or areas of ongoing debate - Evaluate the credibility and reliability of different sources 3. **Critical Synthesis** - Draw connections between different areas of knowledge - Synthesize findings to form a coherent understanding - Identify patterns, trends, or emerging themes - Form preliminary conclusions while acknowledging uncertainties 4. **Research Quality & Rigor** - Cite credible sources and evidence - Acknowledge limitations and potential biases - Present multiple perspectives fairly - Maintain intellectual honesty about what is known vs. unknown 5. **Future Directions** - Identify promising areas for further investigation - Suggest important questions that remain unanswered - Outline potential practical applications or implications ## Research Guidelines - Prioritize academic sources, peer-reviewed research, and established authorities - Be transparent about the strength and limitations of evidence - Maintain objectivity while acknowledging inherent complexities - Structure information in a logical, accessible format - Include diverse perspectives and avoid tunnel vision ## Output Format Please structure your research in a comprehensive report that includes: - Executive summary of key findings - Detailed analysis organized by topic areas - Critical evaluation of sources and evidence - Synthesis of different perspectives - Identified gaps and future research directions - Bibliography or source references where applicable Begin your research on: {{topic}} ``` -------------------------------------------------------------------------------- /scripts/test_server.js: -------------------------------------------------------------------------------- ```javascript #!/usr/bin/env node // Simple test script to verify server startup const { spawn } = require('child_process'); const path = require('path'); console.log('Testing MCP Server startup...'); const serverPath = path.join(__dirname, 'server', 'dist', 'index.js'); console.log('Server path:', serverPath); // Test 1: Check if server can show help console.log('\n=== Test 1: Help Command ==='); const helpProcess = spawn('node', [serverPath, '--help'], { stdio: 'pipe', cwd: path.join(__dirname, 'server') }); let helpOutput = ''; let helpError = ''; helpProcess.stdout.on('data', (data) => { helpOutput += data.toString(); }); helpProcess.stderr.on('data', (data) => { helpError += data.toString(); }); helpProcess.on('close', (code) => { console.log(`Help command exit code: ${code}`); if (helpOutput) { console.log('Help output:', helpOutput.substring(0, 200) + '...'); } if (helpError) { console.log('Help stderr:', helpError); } // Test 2: Try to start server with debug output (timeout after 5 seconds) console.log('\n=== Test 2: Server Startup (5 second timeout) ==='); const startProcess = spawn('node', [serverPath, '--debug-startup'], { stdio: 'pipe', cwd: path.join(__dirname, 'server') }); let startOutput = ''; let startError = ''; startProcess.stdout.on('data', (data) => { startOutput += data.toString(); }); startProcess.stderr.on('data', (data) => { startError += data.toString(); }); // Kill after 5 seconds const timeout = setTimeout(() => { console.log('Killing server after 5 seconds...'); startProcess.kill('SIGINT'); }, 5000); startProcess.on('close', (code) => { clearTimeout(timeout); console.log(`Server startup exit code: ${code}`); if (startOutput) { console.log('Server stdout:', startOutput); } if (startError) { console.log('Server stderr:', startError); } // Analyze results console.log('\n=== Analysis ==='); const hasError = startError.includes('Error') || startError.includes('error'); const hasSuccess = startError.includes('successfully') || startOutput.includes('successfully'); if (hasError) { console.log('❌ Server startup had errors'); } else if (hasSuccess) { console.log('✅ Server appears to start successfully'); } else { console.log('⚠️ Server startup status unclear'); } }); startProcess.on('error', (error) => { clearTimeout(timeout); console.log('Server startup error:', error); }); }); helpProcess.on('error', (error) => { console.log('Help command error:', error); }); ``` -------------------------------------------------------------------------------- /server/src/gates/guidance/FrameworkGuidanceFilter.ts: -------------------------------------------------------------------------------- ```typescript /** * Framework Guidance Filter - Pure Function Implementation * * Extracts framework-specific guidance from multi-framework guidance text. * This is a pure function with no dependencies for maximum reusability. */ /** * Filter guidance text to show only the specified framework's guidance * * @param guidance - Original guidance text (may contain multiple frameworks) * @param activeFramework - Framework to filter for (e.g., 'ReACT', 'CAGEERF') * @returns Filtered guidance showing only the active framework's content */ export function filterFrameworkGuidance(guidance: string, activeFramework: string): string { // Parse the guidance to extract only the relevant framework section const lines = guidance.split('\n'); const filteredLines: string[] = []; let foundRelevantSection = false; for (const line of lines) { // Check if this line contains framework-specific guidance if (line.includes(`- ${activeFramework}:`)) { foundRelevantSection = true; filteredLines.push(line); } else if (line.startsWith('- ') && (line.includes('CAGEERF:') || line.includes('ReACT:') || line.includes('5W1H:') || line.includes('SCAMPER:'))) { // Skip other framework-specific lines foundRelevantSection = false; continue; } else if (!line.startsWith('- ') || foundRelevantSection) { // Include general guidance lines and continuation lines filteredLines.push(line); } } // If we found framework-specific guidance, use filtered version if (filteredLines.some(line => line.includes(`- ${activeFramework}:`))) { let result = filteredLines.join('\n'); // Clean up the framework-specific line to be more concise result = result.replace(`- ${activeFramework}: `, `**${activeFramework} Methodology Guidelines:**\n- `); return result; } // Fallback to original guidance if no framework-specific section found return guidance; } /** * Check if guidance text contains framework-specific content * * @param guidance - Guidance text to analyze * @returns true if guidance contains framework-specific sections */ export function hasFrameworkSpecificContent(guidance: string): boolean { const frameworkPatterns = ['CAGEERF:', 'ReACT:', '5W1H:', 'SCAMPER:']; return frameworkPatterns.some(pattern => guidance.includes(pattern)); } /** * Get list of frameworks mentioned in guidance text * * @param guidance - Guidance text to analyze * @returns Array of framework names found in the guidance */ export function getFrameworksInGuidance(guidance: string): string[] { const frameworkPatterns = [ { name: 'CAGEERF', pattern: 'CAGEERF:' }, { name: 'ReACT', pattern: 'ReACT:' }, { name: '5W1H', pattern: '5W1H:' }, { name: 'SCAMPER', pattern: 'SCAMPER:' } ]; return frameworkPatterns .filter(fw => guidance.includes(fw.pattern)) .map(fw => fw.name); } ``` -------------------------------------------------------------------------------- /server/tests/test-enhanced-parsing.js: -------------------------------------------------------------------------------- ```javascript #!/usr/bin/env node /** * Quick test script to verify enhanced chain step parsing with gate support */ import { createLogger } from "../dist/logging/index.js"; import { PromptLoader } from "../dist/prompts/loader.js"; async function testEnhancedParsing() { console.log("🧪 Testing Enhanced Chain Step Parsing with Gate Support...\n"); const logger = createLogger({ level: "info" }); const loader = new PromptLoader(logger); try { // Test parsing the enhanced notes.md file const result = await loader.loadPromptFile( "analysis/notes.md", "/home/minipuft/Applications/claude-prompts-mcp/server/prompts" ); console.log("✅ Successfully parsed notes.md"); console.log(`📋 Found ${result.chainSteps?.length || 0} chain steps`); if (result.chainSteps) { console.log("\n📊 Chain Steps Analysis:"); result.chainSteps.forEach((step, index) => { console.log(`\n Step ${index + 1}:`); console.log(` - promptId: ${step.promptId}`); console.log(` - stepName: ${step.stepName}`); console.log( ` - gates: ${step.gates ? JSON.stringify(step.gates) : "none"}` ); console.log( ` - inputMapping: ${ Object.keys(step.inputMapping || {}).length } inputs` ); console.log( ` - outputMapping: ${ Object.keys(step.outputMapping || {}).length } outputs` ); }); // Verify expected gates const step1Gates = result.chainSteps[0]?.gates || []; const step2Gates = result.chainSteps[1]?.gates || []; const step3Gates = result.chainSteps[2]?.gates || []; const step4Gates = result.chainSteps[3]?.gates || []; console.log("\n🔍 Gate Configuration Verification:"); console.log( ` Step 1 gates: ${JSON.stringify(step1Gates)} ${ step1Gates.includes("research-quality") ? "✅" : "❌" }` ); console.log( ` Step 2 gates: ${JSON.stringify(step2Gates)} ${ step2Gates.includes("research-quality") ? "✅" : "❌" }` ); console.log( ` Step 3 gates: ${JSON.stringify(step3Gates)} ${ step3Gates.includes("content-structure") ? "✅" : "❌" }` ); console.log( ` Step 4 gates: ${JSON.stringify(step4Gates)} ${ step4Gates.includes("content-structure") ? "✅" : "❌" }` ); const allCorrect = step1Gates.includes("research-quality") && step2Gates.includes("research-quality") && step3Gates.includes("content-structure") && step4Gates.includes("content-structure"); console.log( `\n🎯 Gate Configuration: ${ allCorrect ? "✅ ALL CORRECT" : "❌ NEEDS ATTENTION" }` ); } console.log("\n✅ Enhanced parsing test completed successfully!"); } catch (error) { console.error("❌ Test failed:", error); process.exit(1); } } testEnhancedParsing(); ``` -------------------------------------------------------------------------------- /server/src/gates/templates/framework_compliance_validation.md: -------------------------------------------------------------------------------- ```markdown # Framework Methodology Compliance Self-Check Template ## Instructions Evaluate how well your response follows the active framework methodology principles. ## Framework-Specific Criteria ### CAGEERF Framework - [ ] **Context**: Establishes clear context and background information - [ ] **Analysis**: Provides systematic analysis of the situation/problem - [ ] **Goals**: Defines clear goals and objectives - [ ] **Execution**: Shows concrete execution steps or implementation - [ ] **Evaluation**: Includes evaluation criteria and assessment methods - [ ] **Refinement**: Demonstrates iterative improvement and refinement - [ ] **Framework**: Shows framework-aware systematic thinking ### ReACT Framework - [ ] **Reasoning**: Shows clear reasoning and thought processes - [ ] **Acting**: Demonstrates concrete actions and implementations - [ ] **Observation**: Includes observation of results and outcomes - [ ] **Adjustment**: Shows ability to adjust based on observations - [ ] **Systematic Approach**: Uses systematic problem-solving methodology - [ ] **Iterative Process**: Demonstrates iterative reasoning-action cycles ### 5W1H Framework - [ ] **Who**: Addresses who is involved or affected - [ ] **What**: Clearly defines what is being done or analyzed - [ ] **When**: Includes timing and scheduling considerations - [ ] **Where**: Addresses location or context considerations - [ ] **Why**: Explains reasoning and rationale - [ ] **How**: Provides detailed methodology and approach ### SCAMPER Framework - [ ] **Substitute**: Considers what can be substituted - [ ] **Combine**: Explores combination possibilities - [ ] **Adapt**: Shows adaptation strategies - [ ] **Modify**: Identifies modification opportunities - [ ] **Put to Other Uses**: Explores alternative applications - [ ] **Eliminate**: Considers what can be eliminated - [ ] **Reverse**: Examines reverse approaches ## General Framework Compliance - [ ] **Systematic Structure**: Follows systematic methodology structure - [ ] **Comprehensive Coverage**: Addresses all relevant framework aspects - [ ] **Logical Flow**: Maintains logical progression through framework elements - [ ] **Methodology Awareness**: Shows understanding of framework principles - [ ] **Practical Application**: Applies framework meaningfully to the content ## Self-Assessment **Overall Framework Compliance Score (0.0-1.0): ___** **Framework Analysis:** - Structure Adherence: ___/10 - Completeness: ___/10 - Methodology Understanding: ___/10 - Practical Application: ___/10 **Active Framework: [CAGEERF/ReACT/5W1H/SCAMPER]** **Framework Compliance Review:** [Evaluate how well the response follows framework principles] **Missing Framework Elements:** [Identify any framework components not adequately addressed if score < 0.75] ## Validation Response Framework compliance assessment: - **PASS** if score ≥ 0.75 and systematic methodology is evident - **NEEDS_IMPROVEMENT** if score < 0.75 or lacks framework structure **Final Assessment: [PASS/NEEDS_IMPROVEMENT]** ```