#
tokens: 49906/50000 13/252 files (page 7/12)
lines: off (toggle) GitHub
raw markdown copy
This is page 7 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

--------------------------------------------------------------------------------
/docs/prompt-vs-template-guide.md:
--------------------------------------------------------------------------------

```markdown
# Execution Modes Guide - Prompt vs Template vs Chain

## Overview

The Claude Prompts MCP Server provides **three intelligent execution modes** optimized for different use cases. All execution happens through the consolidated `prompt_engine` MCP tool with automatic mode detection and framework integration.

> 📖 **For comprehensive details**, see the [Execution Architecture Guide](./execution-architecture-guide.md)

## Three Execution Modes

- **Prompt**: Basic variable substitution (fastest, ~10-50ms)
- **Template**: Framework-aware processing with methodology guidance (balanced, ~100-500ms) 
- **Chain**: LLM-driven iterative execution with instructions (most capable, variable timing)

**Intelligent Detection**: The `prompt_engine` automatically detects the optimal execution mode based on your prompt's complexity and structure.

## Quick Decision Guide

### 🚀 Use **Prompt Mode** When:

- Speed is critical (sub-100ms execution)
- Simple variable substitution needed
- Development/testing scenarios
- Basic text formatting or generation
- No framework methodology needed

### 🧠 Use **Template Mode** When:

- Complex reasoning or analysis required
- Framework methodology benefits (CAGEERF, ReACT, 5W1H, SCAMPER)
- Professional-quality outputs needed
- Quality gates and validation desired
- System prompt enhancement helpful

### 🔗 Use **Chain Mode** When:

- Multi-step processes requiring iterative execution
- Building complex outputs progressively through LLM guidance
- Context needs to flow between steps
- Mission-critical processes requiring step-by-step validation
- LLM should control execution flow and decision-making

## MCP Tool Usage

All execution uses the consolidated `prompt_engine` MCP tool:

### Basic Execution

```bash
# Automatic mode detection (recommended)
prompt_engine >>my_prompt input="analyze this data"

# Explicit mode specification
prompt_engine >>my_prompt input="data" execution_mode="prompt"     # Force basic mode
prompt_engine >>my_prompt input="data" execution_mode="template"   # Force framework mode  
prompt_engine >>my_prompt input="data" execution_mode="chain"      # Force chain mode
```

### JSON Command Format

```bash
# Alternative JSON syntax for complex arguments
prompt_engine command='{"command": ">>analysis_prompt", "args": {"data": "complex data", "focus": "security"}}'
```

### Framework Integration

Templates automatically use the active framework methodology:

```bash
# Check current framework and system status
system_control status

# Switch framework for enhanced template processing
system_control switch_framework framework="CAGEERF" reason="Need comprehensive analysis"
system_control switch_framework framework="ReACT" reason="Problem-solving focus"
```

## Execution Mode Details

### Prompt Mode (`execution_mode="prompt"`)

**Purpose**: Lightning-fast variable substitution without framework overhead

**Features**:
- Simple Nunjucks template processing
- Direct variable substitution
- No system prompt enhancement
- Minimal processing overhead
- Optional quality gates

**Output Format**: `⚡ **Basic Prompt Execution** | 🚀 Fast variable substitution`

**Example**:
```bash
prompt_engine >>format_code code="function test() {}" style="prettier" execution_mode="prompt"
```

### Template Mode (`execution_mode="template"`)

**Purpose**: Framework-enhanced execution with methodology guidance

**Features**:
- Full framework processing with active methodology
- System prompt injection from framework guides
- Quality gates integration (when enabled)
- Framework-specific enhancement and validation
- Professional-quality outputs

**Output Format**: `🧠 **Framework Template Execution** | 🎯 [Active Framework] | ✅ Quality gates applied`

**Example**:
```bash
prompt_engine >>security_analysis code="{{codebase}}" execution_mode="template" gate_validation=true
```

### Chain Mode (`execution_mode="chain"`)

**Purpose**: LLM-driven iterative execution with step-by-step guidance

**Revolutionary Architecture**: Instead of server-side orchestration, chains return **structured instructions** that guide the LLM through iterative execution.

**How Chain Mode Works**:
1. Chain mode analyzes the chain definition and current state
2. Returns **LLM instruction template** for the next step to execute
3. LLM executes the step by calling `prompt_engine` again with step-specific arguments
4. Server tracks progress and provides instructions for subsequent steps
5. Process continues until chain completion

**Features**:
- LLM controls execution flow and decision-making
- Natural conversation flow preservation
- Automatic step progression with state tracking
- Quality gates enabled by default (`gate_validation=true`)
- Error recovery and retry capabilities
- Context preservation between steps

**Output Format**: `🔗 **Chain Execution**: [Chain Name] | Step [N/Total] | [Next Instructions]`

**Example**:
```bash
# Execute complete chain with automatic progression
prompt_engine >>research_pipeline topic="AI Ethics" llm_driven_execution=true

# Manual step-by-step execution
prompt_engine >>research_pipeline topic="AI Ethics" execution_mode="chain"
# Returns instructions for Step 1, then call again based on instructions
```

## Performance Characteristics

| Execution Mode | Speed         | Memory | CPU | Framework | Quality Gates | Best Use Case |
|----------------|---------------|--------|-----|-----------|---------------|---------------|
| **Prompt**     | ⚡ ~10-50ms   | Low    | Low | None      | Optional      | Variable substitution, formatting |
| **Template**   | 🚀 ~100-500ms | Medium | Med | Active    | Optional      | Analysis, reasoning, quality output |
| **Chain**      | 🔄 Variable   | Medium | Med | Active    | Default On    | Multi-step processes, complex orchestration |

## Advanced Features

### Automatic Mode Detection

When `execution_mode="auto"` (default):

1. **Semantic Analysis**: Analyzes prompt structure and complexity
2. **Chain Detection**: Automatically detects chains based on presence of `chainSteps`
3. **Template Detection**: Complex arguments, template variables, or analysis requirements
4. **Prompt Fallback**: Simple variable substitution (default)

**Detection Logic**:
```typescript
if (prompt.chainSteps?.length) return "chain"
if (hasComplexArguments || requiresFramework) return "template"  
return "prompt"  // Default for simple cases
```

### Framework System Integration

**Active Framework Impact**:
- **Prompt Mode**: No framework enhancement
- **Template Mode**: Full framework processing with methodology guidance
- **Chain Mode**: Framework-aware step instructions and validation

**Available Methodologies**:
- **CAGEERF**: Comprehensive structured analysis (Context, Analysis, Goals, Execution, Evaluation, Refinement, Framework)
- **ReACT**: Reasoning and Acting systematic problem-solving approach  
- **5W1H**: Who, What, When, Where, Why, How systematic analysis framework
- **SCAMPER**: Creative problem-solving (Substitute, Combine, Adapt, Modify, Put to other uses, Eliminate, Reverse)

### Quality Gates Integration

**Gate Validation Levels**:
- **Prompts**: Optional gates (`gate_validation=false` by default)
- **Templates**: Optional gates (`gate_validation=true` recommended)
- **Chains**: Automatic gates (`gate_validation=true` by default)

**Gate Types Available**:
- Content analysis (length, readability, tone, grammar)
- Structure validation (format, sections, hierarchy)
- Pattern matching (keywords, patterns, links)
- Custom logic (required fields, completeness, security)

## Common Usage Patterns

### Speed-Critical Operations

```bash
# Use prompt mode for rapid iteration and simple tasks
prompt_engine >>format_json data="{{raw_data}}" execution_mode="prompt"
prompt_engine >>generate_title content="{{article}}" execution_mode="prompt"
```

### Analysis and Reasoning Tasks

```bash
# Templates provide framework methodology enhancement
prompt_engine >>code_review code="{{source}}" execution_mode="template"
prompt_engine >>market_analysis data="{{research}}" execution_mode="template" gate_validation=true
```

### Complex Multi-Step Processes

```bash
# Chains handle iterative LLM-driven execution
prompt_engine >>content_creation_workflow topic="{{subject}}" length="comprehensive" llm_driven_execution=true
prompt_engine >>research_and_analysis_pipeline query="{{research_question}}" depth="thorough"
```

### Framework-Specific Execution

```bash
# Switch framework and execute with methodology guidance
system_control switch_framework framework="CAGEERF" reason="Comprehensive analysis needed"
prompt_engine >>strategic_analysis situation="{{business_context}}" execution_mode="template"

# Different methodology for creative tasks  
system_control switch_framework framework="SCAMPER" reason="Creative problem solving"
prompt_engine >>innovation_workshop challenge="{{problem}}" execution_mode="template"
```

## Troubleshooting

### Mode Detection Issues

```bash
# Check what execution mode was detected and why
system_control analytics

# View detailed execution history and mode usage
system_control status

# Force specific mode if auto-detection is incorrect
prompt_engine >>my_prompt input="data" execution_mode="template"
```

### Performance Optimization

**Speed Priority**:
- Use `execution_mode="prompt"` for maximum speed
- Disable quality gates: `gate_validation=false`
- Use simple variable names and minimal template logic

**Quality Priority**:
- Use `execution_mode="template"` with appropriate framework
- Enable quality gates: `gate_validation=true`  
- Switch to methodology that matches your task type

**Complex Workflow Priority**:
- Use `execution_mode="chain"` for multi-step processes
- Enable `llm_driven_execution=true` for LLM-driven coordination
- Let LLM control flow - don't force manual step control

### Chain Execution Issues

**Chain Not Progressing**:
```bash
# Check chain state and progress
system_control status

# Reset chain state if stuck
prompt_engine >>your_chain_name execution_mode="chain"  # Restarts from current step
```

**Chain Step Failures**:
- Quality gates are enabled by default - check gate validation results
- LLM instructions may need clarification - review step definitions
- Framework methodology may not match chain requirements

### Framework Integration Issues

```bash
# Verify active framework
system_control status

# Check framework switching history and performance
system_control analytics include_history=true

# Switch to appropriate framework for your task
system_control switch_framework framework="ReACT" reason="Problem-solving task"
```

## Migration Guide

### From Simple to Complex Execution

**Development Phase**:
1. Start with **prompt mode** for rapid prototyping: `execution_mode="prompt"`
2. Test with various inputs and ensure variable substitution works correctly

**Quality Phase**:
3. Upgrade to **template mode** when output quality matters: `execution_mode="template"`
4. Choose appropriate framework methodology for your use case
5. Enable quality gates for validation: `gate_validation=true`

**Production Phase**:
6. Convert to **chain mode** for multi-step processes: `execution_mode="chain"`
7. Enable LLM-driven chain coordination: `llm_driven_execution=true`
8. Monitor execution analytics and optimize based on usage patterns

### Framework Selection Guide

**Choose Framework Based on Task Type**:

- **CAGEERF**: Complex analysis, strategic planning, comprehensive evaluation
- **ReACT**: Problem-solving, debugging, systematic reasoning tasks  
- **5W1H**: Research, investigation, systematic information gathering
- **SCAMPER**: Creative tasks, innovation, brainstorming, design thinking

## System Integration

### MCP Tool Coordination

```bash
# Complete workflow using all consolidated tools
system_control status                           # Check system and framework state
system_control switch_framework framework="CAGEERF"  # Set methodology
prompt_engine >>analysis_task data="{{input}}" execution_mode="template"  # Execute with framework
system_control analytics                        # Monitor performance
```

### Analytics and Monitoring

**Execution Statistics**:
- Mode usage distribution (prompt/template/chain percentages)
- Framework usage patterns and switching frequency
- Performance metrics per execution mode
- Quality gate success rates and common failures

**Access Analytics**:
```bash
# View comprehensive execution analytics
system_control analytics include_history=true

# Monitor system health including execution performance
system_control health

# Reset metrics if needed for fresh tracking
system_control reset_metrics confirm=true
```

## Best Practices

### Execution Mode Selection

- **Start Simple**: Begin with automatic mode detection, override only when necessary
- **Performance Testing**: Benchmark your specific use cases to choose optimal modes
- **Framework Alignment**: Match execution mode with framework - templates benefit most from methodology
- **Quality Requirements**: Use quality gates in template/chain modes for production workloads

### Framework Integration

- **Task-Appropriate Frameworks**: Switch frameworks based on task type, not randomly
- **Consistent Methodology**: Stick with one framework per logical workflow or project phase
- **Performance Monitoring**: Track framework effectiveness for your specific use cases
- **Strategic Switching**: Plan framework switches, don't change mid-workflow unnecessarily

### Chain Development

- **Step Design**: Design clear, discrete steps that can be executed independently
- **State Management**: Let the LLM handle state and flow - avoid over-constraining steps
- **Error Recovery**: Design steps to be retryable and recoverable from failures
- **Progress Tracking**: Monitor chain execution through system analytics

### Quality Assurance

- **Gate Strategy**: Enable gates for production, disable for development speed
- **Framework Quality**: Use appropriate methodology - each framework has quality strengths
- **Validation Testing**: Test execution modes with realistic data before production
- **Monitoring Setup**: Implement analytics monitoring for production workloads

## Advanced Topics

### Custom Chain Development

For creating sophisticated multi-step workflows:

```bash
# Define chain with clear step progression
prompt_manager create_template name="custom_analysis_chain" category="analysis" \
  content="Multi-step analysis workflow with data collection and synthesis" \
  chain_steps='[
    {"promptId": "data_collection", "stepName": "Data Collection"},
    {"promptId": "analysis_processing", "stepName": "Analysis"},
    {"promptId": "synthesis_generation", "stepName": "Synthesis"}
  ]'
```

### Performance Optimization Strategies

**For High-Throughput Scenarios**:
- Batch similar executions using prompt mode
- Cache framework contexts when possible  
- Monitor memory usage during chain execution
- Use analytics to identify bottlenecks

**For Quality-Critical Scenarios**:
- Always enable quality gates in production
- Use appropriate framework methodology consistently
- Implement comprehensive error handling and retry logic
- Monitor quality gate success rates and adjust criteria

---

**Quick Summary**: The MCP server provides three intelligent execution modes accessible through the `prompt_engine` tool. Use automatic mode detection for most cases, prompt mode for speed, template mode for quality with framework enhancement, and chain mode for complex LLM-driven iterative processes. All modes integrate seamlessly with the framework system and quality gates for professional-grade AI prompt execution.
```

--------------------------------------------------------------------------------
/docs/template-development-guide.md:
--------------------------------------------------------------------------------

```markdown
# Template Development Guide

## Overview

This guide covers creating **framework-aware templates** that leverage the Claude Prompts MCP Server's methodology system for enhanced, systematic prompt execution. Templates represent the middle tier of our three-tier execution model, providing structured guidance and quality assurance.

## Related Documentation

- **[Three-Tier Execution System](execution-architecture-guide.md)** - Understanding template execution in the broader system
- **[Prompt Format Guide](prompt-format-guide.md)** - Basic prompt formatting (foundation for templates)
- **[Chain System Analysis](chain-system-analysis.md)** - Using templates within chain workflows
- **[Enhanced Gate System](enhanced-gate-system.md)** - Quality validation for templates
- **[MCP Tools Reference](mcp-tools-reference.md)** - Using tools with template execution

## What Are Framework-Aware Templates?

Framework-aware templates are enhanced prompts that:
- **Integrate with methodology guides** (CAGEERF, ReACT, 5W1H, SCAMPER)
- **Include system prompt injection** for structured thinking
- **Apply quality gates** for validation and consistency
- **Provide structured guidance** to LLMs for better outcomes

## Template Structure

### Basic Template Format

```markdown
# Template Name

**🔄 TEMPLATE EXECUTION**: Framework-aware processing with {{framework}} methodology

## System Message
You are an expert {{role}} who follows systematic approaches to {{task_type}}.
Use the active framework methodology to ensure comprehensive analysis.

## User Message Template
{{user_content_with_variables}}

## Arguments
- role: The expert role for this template
- task_type: Type of task being performed
- user_content_with_variables: Main template content
```

### Template Markers

Templates are identified by specific markers:

#### Execution Type Markers
```markdown
**🔄 TEMPLATE EXECUTION**: Framework-aware processing
**⚡ EXECUTION REQUIRED**: Uses template execution for framework integration
```

#### Framework Integration Markers
```markdown
**📋 FRAMEWORK**: Uses active methodology ({{framework}}) for systematic approach
**🎯 METHODOLOGY**: Applies {{framework}} principles throughout execution
```

## Framework Integration

### Available Frameworks

#### CAGEERF Framework
**Use for**: Comprehensive structured analysis
- **Context**: Understand the situation
- **Analysis**: Break down the problem  
- **Goals**: Define clear objectives
- **Execution**: Implement systematic approach
- **Evaluation**: Assess results
- **Refinement**: Improve based on feedback
- **Framework**: Apply methodology consistently

```markdown
# CAGEERF Analysis Template
**🔄 TEMPLATE EXECUTION**: Uses CAGEERF methodology for systematic analysis

## System Message
You are an expert analyst who follows the CAGEERF methodology for comprehensive evaluation.
Apply each phase systematically: Context → Analysis → Goals → Execution → Evaluation → Refinement → Framework consistency.

## User Message Template
Analyze the following using CAGEERF methodology:
{{content}}

Focus areas: {{focus_areas}}
```

#### ReACT Framework
**Use for**: Reasoning and action-oriented tasks
- **Reasoning**: Think through the problem systematically
- **Acting**: Take concrete steps based on reasoning

```markdown
# ReACT Problem Solving Template
**🔄 TEMPLATE EXECUTION**: Uses ReACT methodology for reasoning and action

## System Message  
You are an expert problem solver who uses ReACT (Reasoning and Acting) methodology.
For each step: 1) Reason about the situation, 2) Act based on that reasoning.

## User Message Template
Apply ReACT methodology to solve:
{{problem_statement}}

Available actions: {{available_actions}}
```

#### 5W1H Framework
**Use for**: Comprehensive information gathering
- **Who**: Key stakeholders and people involved
- **What**: Core facts and details
- **When**: Timing and sequence
- **Where**: Location and context
- **Why**: Motivations and reasons
- **How**: Methods and processes

```markdown
# 5W1H Analysis Template
**🔄 TEMPLATE EXECUTION**: Uses 5W1H methodology for comprehensive analysis

## System Message
You are an expert investigator who uses the 5W1H framework for thorough analysis.
Address each question systematically: Who, What, When, Where, Why, and How.

## User Message Template
Analyze using 5W1H framework:
{{subject}}

Priority questions: {{priority_questions}}
```

#### SCAMPER Framework  
**Use for**: Creative problem-solving and innovation
- **Substitute**: What can be substituted?
- **Combine**: What can be combined?
- **Adapt**: What can be adapted?
- **Modify**: What can be modified?
- **Put to other uses**: How else can this be used?
- **Eliminate**: What can be eliminated?
- **Reverse**: What can be reversed?

```markdown
# SCAMPER Innovation Template
**🔄 TEMPLATE EXECUTION**: Uses SCAMPER methodology for creative problem-solving

## System Message
You are an innovation expert who applies SCAMPER methodology for creative solutions.
Systematically explore: Substitute, Combine, Adapt, Modify, Put to other uses, Eliminate, Reverse.

## User Message Template
Apply SCAMPER methodology to innovate on:
{{concept}}

Focus areas: {{focus_areas}}
```

### Framework Selection

#### Automatic Framework Application
Templates automatically use the **active framework** set in the system:

```bash
# Check current framework
system_control status

# Switch framework for template execution
system_control switch_framework framework=CAGEERF reason="Need comprehensive analysis"
```

#### Framework-Specific Templates
Create templates optimized for specific frameworks:

```markdown
# CAGEERF-Optimized Template
**📋 FRAMEWORK**: Optimized for CAGEERF methodology

This template works best with CAGEERF framework active.
To use: `system_control switch_framework framework=CAGEERF`
```

## Template Development Process

### Step 1: Define Template Purpose

```markdown
# Template Planning
- **Purpose**: What specific task does this template address?
- **Target Framework**: Which methodology best supports this task?
- **Complexity Level**: Simple, moderate, or complex template?
- **Quality Requirements**: What validation is needed?
```

### Step 2: Choose Template Structure

#### Simple Template (Basic framework integration)
```markdown
# Simple Analysis Template
**🔄 TEMPLATE EXECUTION**: Framework-aware analysis

Analyze: {{content}}
Focus: {{focus_area}}
```

#### Structured Template (Full framework integration)
```markdown
# Comprehensive Analysis Template  
**🔄 TEMPLATE EXECUTION**: Uses {{framework}} for systematic analysis

## System Message
You are an expert analyst following {{framework}} methodology.
[Detailed system instructions...]

## User Message Template  
[Structured template with multiple variables...]

## Arguments
- content: Content to analyze
- framework: Active methodology framework
- focus_area: Specific focus for analysis
```

#### Advanced Template (Custom framework guidance)
```markdown
# Advanced Research Template
**🔄 TEMPLATE EXECUTION**: Advanced framework integration with custom quality gates

## Framework-Specific Guidance
{{#if framework == "CAGEERF"}}
Apply CAGEERF phases systematically...
{{elif framework == "ReACT"}}
Use reasoning-action cycles...
{{else}}
Apply general systematic approach...
{{/if}}

[Rest of template...]
```

### Step 3: Implement Template Logic

#### Variable Definition
```markdown
## Arguments
- content (required): Primary content for processing
- focus_area (optional): Specific area to emphasize
- depth_level (optional, default: "moderate"): Analysis depth
- output_format (optional, default: "markdown"): Desired output format
```

#### Conditional Logic
```markdown
## User Message Template
Analyze the following content:
{{content}}

{{#if focus_area}}
Pay special attention to: {{focus_area}}
{{/if}}

{{#if depth_level == "deep"}}
Provide comprehensive analysis including edge cases and implications.
{{elif depth_level == "surface"}}
Provide high-level overview focusing on key points.
{{else}}
Provide balanced analysis covering main points and key details.
{{/if}}
```

### Step 4: Add Quality Gates

#### Template-Level Quality Requirements
```markdown
# Template with Quality Gates
**🔄 TEMPLATE EXECUTION**: Framework-aware with enhanced validation
**🛡️ QUALITY GATES**: Enabled - Content analysis, structure validation, methodology compliance

[Template content...]
```

#### Custom Quality Criteria
```markdown
## Quality Requirements
- Minimum response length: 500 words
- Must include framework methodology application
- Structured output with clear sections
- Evidence-based conclusions
```

## Advanced Template Features

### Nunjucks Template Features

#### Loops and Iteration
```markdown
## Analysis Points
{{#each analysis_points}}
### {{@index + 1}}. {{this.title}}
{{this.description}}

{{/each}}
```

#### Filters and Functions
```markdown
## Processed Content
Original length: {{content | length}} characters
Summary: {{content | truncate(200)}}
Formatted: {{content | upper | trim}}
```

#### Macros for Reusable Components
```markdown
{{#macro section_header(title, framework)}}
## {{title}}
*Using {{framework}} methodology*
{{/macro}}

{{section_header("Analysis", framework)}}
Your analysis content here...
```

### Framework Context Injection

#### Accessing Framework Information
```markdown
## Current Framework Context
- **Active Framework**: {{framework}}  
- **Methodology Guide**: {{framework_description}}
- **Quality Criteria**: {{framework_quality_gates}}

Apply {{framework}} principles throughout this analysis.
```

#### Framework-Specific Customization
```markdown
{{#if framework == "CAGEERF"}}
## CAGEERF Analysis Structure
1. **Context**: {{context_analysis}}
2. **Analysis**: {{detailed_analysis}}  
3. **Goals**: {{goal_definition}}
4. **Execution**: {{implementation_plan}}
5. **Evaluation**: {{results_assessment}}
6. **Refinement**: {{improvement_suggestions}}
7. **Framework**: {{methodology_consistency}}
{{/if}}
```

## Testing Templates

### Local Testing

```bash
# Test template execution
prompt_engine >>your_template content="test content" focus_area="key points"

# Test with specific framework
system_control switch_framework framework=CAGEERF
prompt_engine >>your_template execution_mode=template
```

### Quality Gate Testing

```bash
# Test with quality gates enabled
prompt_engine >>your_template gate_validation=true

# Test quality gate compliance
prompt_engine >>your_template execution_mode=template gate_validation=true
```

### Framework Integration Testing

```bash
# Test with different frameworks
system_control switch_framework framework=ReACT
prompt_engine >>your_template

system_control switch_framework framework=5W1H  
prompt_engine >>your_template

# Compare framework-specific outputs
```

## Best Practices

### Template Design

#### DO:
- **Use clear template markers** for execution type identification
- **Define all required arguments** with descriptions
- **Include framework integration markers** for methodology awareness
- **Structure templates logically** with clear sections
- **Test across different frameworks** to ensure compatibility

#### DON'T:
- **Hard-code framework references** - use {{framework}} variables
- **Create overly complex templates** - prefer clarity over cleverness
- **Ignore quality gate requirements** - design for validation
- **Mix execution tiers** - keep templates focused on their tier

### Performance Optimization

#### Template Efficiency
- **Minimize complex conditional logic**
- **Use efficient Nunjucks operations**
- **Cache reusable template components**
- **Optimize variable substitution**

#### Framework Integration
- **Leverage active framework selection** rather than switching
- **Use framework-appropriate templates** for best performance
- **Cache framework context** when possible

### Quality Assurance

#### Template Validation
- **Test all argument combinations**
- **Verify framework integration works correctly**
- **Validate output structure and format**
- **Check quality gate compliance**

#### Documentation
- **Document template purpose clearly**
- **Provide usage examples**
- **List framework compatibility**
- **Include troubleshooting guidance**

## Migration from Basic Prompts

### Converting Existing Prompts

#### Step 1: Add Template Markers
```markdown
# Before (basic prompt)
Analyze this content: {{content}}

# After (template)  
**🔄 TEMPLATE EXECUTION**: Framework-aware analysis

Analyze this content using systematic methodology: {{content}}
```

#### Step 2: Add Framework Integration
```markdown
# Enhanced template
**🔄 TEMPLATE EXECUTION**: Uses {{framework}} methodology

## System Message
You are an expert analyst applying {{framework}} methodology for systematic analysis.

## User Message Template
Apply {{framework}} principles to analyze: {{content}}
```

#### Step 3: Add Quality Requirements
```markdown
# Final template with quality gates
**🔄 TEMPLATE EXECUTION**: Framework-aware with quality validation
**🛡️ QUALITY GATES**: Content analysis, methodology compliance

[Template content with framework integration]
```

## Troubleshooting

### Common Issues

#### Template Not Using Framework
**Problem**: Template executes as basic prompt instead of framework-aware template
**Solution**: Add proper template execution markers and check framework is active

#### Quality Gate Failures  
**Problem**: Template fails validation
**Solution**: Review quality gate requirements and adjust template structure

#### Variable Substitution Issues
**Problem**: Variables not being replaced correctly
**Solution**: Check variable names match argument definitions exactly

### Debug Information

Enable verbose logging to debug template execution:
```bash
npm run start:verbose
```

This shows:
- Template execution tier detection
- Framework integration process
- Quality gate evaluation results
- Variable substitution details

## Examples Library

### Content Analysis Template
```markdown
# Content Analysis Template
**🔄 TEMPLATE EXECUTION**: Framework-aware content analysis

## System Message
You are an expert content analyst who uses systematic methodology for comprehensive analysis.
Apply the active framework to ensure thorough and structured evaluation.

## User Message Template
Analyze the following content using {{framework}} methodology:

**Content:**
{{content}}

**Analysis Focus:**
{{#if focus_areas}}
Pay special attention to: {{focus_areas}}
{{else}}
Provide comprehensive analysis across all relevant dimensions.
{{/if}}

**Output Requirements:**
- Use {{framework}} structured approach
- Provide evidence-based insights
- Include actionable recommendations
- Maintain systematic methodology throughout

## Arguments
- content: Content to analyze (required)
- focus_areas: Specific areas to emphasize (optional)
```

### Problem-Solving Template
```markdown
# Systematic Problem Solving Template
**🔄 TEMPLATE EXECUTION**: Framework-driven problem solving

## System Message
You are an expert problem solver who applies systematic methodology to address complex challenges.
Use the active framework to ensure comprehensive problem analysis and solution development.

## User Message Template
Apply {{framework}} methodology to solve this problem:

**Problem Statement:**
{{problem}}

**Constraints:**
{{constraints}}

**Available Resources:**
{{resources}}

**Success Criteria:**
{{success_criteria}}

Follow {{framework}} principles to:
1. Analyze the problem systematically
2. Develop structured solutions
3. Evaluate options methodically
4. Provide implementation guidance

## Arguments
- problem: Problem description (required)
- constraints: Known limitations (required)
- resources: Available resources (optional)
- success_criteria: Definition of success (required)
```

This guide provides the foundation for creating powerful, framework-aware templates that leverage the full capabilities of the Claude Prompts MCP Server's methodology system.
```

--------------------------------------------------------------------------------
/server/src/mcp-tools/prompt-manager/operations/file-operations.ts:
--------------------------------------------------------------------------------

```typescript
/**
 * File system and category management operations
 */

import * as fs from "fs/promises";
import { readFile } from "fs/promises";
import path from "path";
import { Logger } from "../../../logging/index.js";
import { ConfigManager } from "../../../config/index.js";
import { PromptData, PromptsConfigFile } from "../../../types/index.js";
import { safeWriteFile } from "../../../prompts/promptUtils.js";
import {
  OperationResult,
  CategoryResult,
  FileOperationResult,
  PromptManagerDependencies
} from "../core/types.js";
import { CategoryManager } from "../utils/category-manager.js";

/**
 * File system operations for prompt management
 */
export class FileOperations {
  private logger: Logger;
  private configManager: ConfigManager;
  private categoryManager: CategoryManager;

  constructor(dependencies: Pick<PromptManagerDependencies, 'logger' | 'configManager'>) {
    this.logger = dependencies.logger;
    this.configManager = dependencies.configManager;
    this.categoryManager = new CategoryManager(this.logger);
  }

  /**
   * Update prompt implementation (shared by create/update)
   */
  async updatePromptImplementation(promptData: any): Promise<OperationResult> {
    const PROMPTS_FILE = this.configManager.getPromptsFilePath();
    const messages: string[] = [];

    const fileContent = await readFile(PROMPTS_FILE, "utf8");
    const promptsConfig = JSON.parse(fileContent) as PromptsConfigFile;

    if (!promptsConfig.categories) promptsConfig.categories = [];
    if (!promptsConfig.imports) promptsConfig.imports = [];

    // Ensure category exists
    const { effectiveCategory, created: categoryCreated } =
      await this.categoryManager.ensureCategoryExists(promptData.category, promptsConfig, PROMPTS_FILE);

    if (categoryCreated) {
      messages.push(`✅ Created category: '${effectiveCategory}'`);
    }

    // Create/update prompt file
    const { exists: promptExists } = await this.createOrUpdatePromptFile(
      promptData,
      effectiveCategory,
      PROMPTS_FILE
    );

    messages.push(`✅ ${promptExists ? 'Updated' : 'Created'} prompt file and registry entry`);

    return {
      message: messages.join('\n'),
      affectedFiles: [`${promptData.id}.md`]
    };
  }

  /**
   * Delete prompt implementation
   */
  async deletePromptImplementation(id: string): Promise<OperationResult> {
    const PROMPTS_FILE = this.configManager.getPromptsFilePath();
    const promptsConfigDir = path.dirname(PROMPTS_FILE);
    const messages: string[] = [];
    const affectedFiles: string[] = [];

    const fileContent = await readFile(PROMPTS_FILE, "utf8");
    const promptsConfig = JSON.parse(fileContent) as PromptsConfigFile;

    let promptFound = false;

    // Search through category imports
    for (const categoryImport of promptsConfig.imports || []) {
      const categoryPath = path.join(promptsConfigDir, categoryImport);

      try {
        const categoryContent = await readFile(categoryPath, "utf8");
        const categoryData = JSON.parse(categoryContent);

        const promptIndex = categoryData.prompts.findIndex((p: PromptData) => p.id === id);

        if (promptIndex > -1) {
          const promptEntry = categoryData.prompts[promptIndex];

          // Remove from category
          categoryData.prompts.splice(promptIndex, 1);
          await safeWriteFile(categoryPath, JSON.stringify(categoryData, null, 2), "utf8");

          // Delete markdown file
          const markdownPath = path.join(path.dirname(categoryPath), promptEntry.file);
          try {
            await fs.unlink(markdownPath);
            messages.push(`✅ Deleted prompt file: ${promptEntry.file}`);
            affectedFiles.push(promptEntry.file);
          } catch (unlinkError: any) {
            if (unlinkError.code !== "ENOENT") {
              messages.push(`⚠️ Could not delete file: ${unlinkError.message}`);
            }
          }

          messages.push(`✅ Removed from category: ${categoryImport}`);
          promptFound = true;

          // Automatically clean up empty category
          if (categoryData.prompts.length === 0) {
            this.logger.info(`Category ${categoryImport} is now empty, performing automatic cleanup`);
            const cleanupResult = await this.categoryManager.cleanupEmptyCategory(categoryImport, promptsConfig, PROMPTS_FILE);
            messages.push(`🧹 **Automatic Category Cleanup**:\n${cleanupResult.message}`);
          }

          break;
        }
      } catch (error) {
        this.logger.warn(`Could not process category file: ${categoryPath}`, error);
      }
    }

    if (!promptFound) {
      throw new Error(`Prompt not found: ${id}`);
    }

    return {
      message: messages.join('\n'),
      affectedFiles
    };
  }

  /**
   * Create or update prompt file
   */
  async createOrUpdatePromptFile(
    promptData: any,
    effectiveCategory: string,
    promptsFile: string
  ): Promise<FileOperationResult> {
    const promptFilename = `${promptData.id}.md`;
    const categoryDir = path.join(path.dirname(promptsFile), effectiveCategory);
    const promptPath = path.join(categoryDir, promptFilename);

    // Create markdown content
    let content = `# ${promptData.name}\n\n`;
    content += `## Description\n${promptData.description}\n\n`;

    if (promptData.systemMessage) {
      content += `## System Message\n${promptData.systemMessage}\n\n`;
    }

    content += `## User Message Template\n${promptData.userMessageTemplate}\n`;

    // Build gate configuration section separately
    let gateConfigSection = '';
    this.logger.error(`[GATE-TRACE] 💾 FILE-OPS Gate Configuration Check for ${promptData.id}:`, {
      hasGateConfiguration: !!promptData.gateConfiguration,
      gateConfigType: typeof promptData.gateConfiguration,
      gateConfigContent: promptData.gateConfiguration,
      promptId: promptData.id
    });

    if (promptData.gateConfiguration) {
      this.logger.error(`[GATE-TRACE] ✅ Building gate configuration section for prompt ${promptData.id}`);
      gateConfigSection = `\n## Gate Configuration\n\n`;
      gateConfigSection += `\`\`\`json\n`;
      const gateConfigJson = JSON.stringify(promptData.gateConfiguration, null, 2);
      gateConfigSection += gateConfigJson;
      gateConfigSection += `\n\`\`\`\n`;
      this.logger.error(`[GATE-TRACE] 📝 Gate configuration JSON content:`, gateConfigJson);
    } else {
      this.logger.error(`[GATE-TRACE] ❌ NO GATE CONFIGURATION FOUND for prompt ${promptData.id}`);
    }

    // Build chain steps section
    let chainStepsSection = '';
    if ((promptData.chainSteps?.length ?? 0) > 0) {
      chainStepsSection = `\n## Chain Steps\n\n`;
      promptData.chainSteps.forEach((step: any, index: number) => {
        chainStepsSection += `${index + 1}. **${step.stepName}** (${step.promptId})\n`;
        if (step.inputMapping) {
          chainStepsSection += `   - Input Mapping: ${JSON.stringify(step.inputMapping)}\n`;
        }
        if (step.outputMapping) {
          chainStepsSection += `   - Output Mapping: ${JSON.stringify(step.outputMapping)}\n`;
        }
        chainStepsSection += `\n`;
      });
    }

    // Check if file exists and handle Gate Configuration replacement
    const existsBefore = await fs.access(promptPath).then(() => true).catch(() => false);

    if (existsBefore && gateConfigSection) {
      try {
        // Read existing file to preserve structure and replace Gate Configuration section
        const existingContent = await readFile(promptPath, "utf8");

        // Remove ALL existing Gate Configuration sections (handles multiple duplicates)
        const gateConfigRegex = /## Gate Configuration\s*\n```json\s*\n[\s\S]*?\n```\s*/g;
        let cleanedContent = existingContent.replace(gateConfigRegex, '');

        // Find insertion point - after User Message Template, before Chain Steps or end
        const chainStepsIndex = cleanedContent.indexOf('## Chain Steps');

        if (chainStepsIndex > 0) {
          // Insert gate config before Chain Steps
          content = cleanedContent.slice(0, chainStepsIndex).trimEnd() + '\n' +
                    gateConfigSection + '\n' +
                    cleanedContent.slice(chainStepsIndex);
          this.logger.error(`[GATE-TRACE] ✅ Replaced Gate Configuration section (inserted before Chain Steps)`);
        } else {
          // No Chain Steps - append at end
          content = cleanedContent.trimEnd() + '\n' + gateConfigSection;
          this.logger.error(`[GATE-TRACE] ✅ Replaced Gate Configuration section (appended at end)`);
        }
      } catch (readError) {
        // If read fails, fall back to full regeneration
        this.logger.warn(`[GATE-TRACE] ⚠️ Failed to read existing file for section replacement, using full regeneration`, readError);
        content += gateConfigSection + chainStepsSection;
      }
    } else {
      // New file or no gate configuration - use simple append
      content += gateConfigSection + chainStepsSection;
      if (gateConfigSection) {
        this.logger.error(`[GATE-TRACE] ✅ Added Gate Configuration section to new file`);
      }
    }

    // Write markdown file
    await safeWriteFile(promptPath, content, "utf8");

    // Update category prompts.json
    const categoryPromptsPath = path.join(categoryDir, "prompts.json");
    let categoryData: { prompts: PromptData[] };

    try {
      const categoryContent = await readFile(categoryPromptsPath, "utf8");
      categoryData = JSON.parse(categoryContent);
    } catch {
      categoryData = { prompts: [] };
    }

    const promptEntry: PromptData = {
      id: promptData.id,
      name: promptData.name,
      category: effectiveCategory,
      description: promptData.description,
      file: promptFilename,
      arguments: promptData.arguments || []
    };

    const existingIndex = categoryData.prompts.findIndex(p => p.id === promptData.id);
    if (existingIndex > -1) {
      categoryData.prompts[existingIndex] = promptEntry;
    } else {
      categoryData.prompts.push(promptEntry);
    }

    await safeWriteFile(categoryPromptsPath, JSON.stringify(categoryData, null, 2), "utf8");

    return {
      exists: existsBefore,
      path: promptPath
    };
  }

  /**
   * Ensure category exists in the configuration
   */
  async ensureCategoryExists(
    category: string,
    promptsConfig: PromptsConfigFile,
    promptsFile: string
  ): Promise<CategoryResult> {
    return this.categoryManager.ensureCategoryExists(category, promptsConfig, promptsFile);
  }

  /**
   * Clean up empty category
   */
  async cleanupEmptyCategory(
    categoryImport: string,
    promptsConfig: PromptsConfigFile,
    promptsFile: string
  ): Promise<OperationResult> {
    return this.categoryManager.cleanupEmptyCategory(categoryImport, promptsConfig, promptsFile);
  }

  /**
   * Validate file system state
   */
  async validateFileSystemState(): Promise<{
    valid: boolean;
    issues: string[];
    stats: Record<string, number>;
  }> {
    const issues: string[] = [];
    const PROMPTS_FILE = this.configManager.getPromptsFilePath();

    try {
      // Check main config file
      const fileContent = await readFile(PROMPTS_FILE, "utf8");
      const promptsConfig = JSON.parse(fileContent) as PromptsConfigFile;

      // Validate categories and imports
      const stats = await this.categoryManager.getCategoryStats(promptsConfig.imports || [], PROMPTS_FILE);

      // Check each category structure
      for (const categoryImport of promptsConfig.imports || []) {
        const validation = await this.categoryManager.validateCategoryStructure(categoryImport, PROMPTS_FILE);
        if (!validation.valid) {
          issues.push(`Category ${categoryImport}: ${validation.issues.join(', ')}`);
        }
      }

      return {
        valid: issues.length === 0,
        issues,
        stats
      };

    } catch (error) {
      issues.push(`Failed to validate file system: ${error instanceof Error ? error.message : String(error)}`);
      return {
        valid: false,
        issues,
        stats: {}
      };
    }
  }

  /**
   * Backup prompt files
   */
  async backupPrompts(): Promise<{
    backupPath: string;
    fileCount: number;
  }> {
    const PROMPTS_FILE = this.configManager.getPromptsFilePath();
    const promptsDir = path.dirname(PROMPTS_FILE);
    const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
    const backupDir = path.join(promptsDir, `backup-${timestamp}`);

    await fs.mkdir(backupDir, { recursive: true });

    // Copy main config
    await fs.copyFile(PROMPTS_FILE, path.join(backupDir, 'promptsConfig.json'));
    let fileCount = 1;

    // Copy all categories and their prompts
    const fileContent = await readFile(PROMPTS_FILE, "utf8");
    const promptsConfig = JSON.parse(fileContent) as PromptsConfigFile;

    for (const categoryImport of promptsConfig.imports || []) {
      const sourcePath = path.join(promptsDir, categoryImport);
      const targetPath = path.join(backupDir, categoryImport);

      // Create category directory in backup
      await fs.mkdir(path.dirname(targetPath), { recursive: true });

      try {
        // Copy category config
        await fs.copyFile(sourcePath, targetPath);
        fileCount++;

        // Copy all markdown files in category
        const categoryDir = path.dirname(sourcePath);
        const files = await fs.readdir(categoryDir);

        for (const file of files) {
          if (file.endsWith('.md')) {
            const sourceFile = path.join(categoryDir, file);
            const targetFile = path.join(path.dirname(targetPath), file);
            await fs.copyFile(sourceFile, targetFile);
            fileCount++;
          }
        }
      } catch (error) {
        this.logger.warn(`Failed to backup category ${categoryImport}:`, error);
      }
    }

    this.logger.info(`Created backup with ${fileCount} files at ${backupDir}`);

    return {
      backupPath: backupDir,
      fileCount
    };
  }

  /**
   * Get file system statistics
   */
  async getFileSystemStats(): Promise<{
    totalCategories: number;
    totalPrompts: number;
    totalFiles: number;
    diskUsage: number;
  }> {
    const PROMPTS_FILE = this.configManager.getPromptsFilePath();
    const promptsDir = path.dirname(PROMPTS_FILE);

    let totalCategories = 0;
    let totalPrompts = 0;
    let totalFiles = 0;
    let diskUsage = 0;

    try {
      const fileContent = await readFile(PROMPTS_FILE, "utf8");
      const promptsConfig = JSON.parse(fileContent) as PromptsConfigFile;

      totalCategories = promptsConfig.categories?.length || 0;

      const stats = await this.categoryManager.getCategoryStats(promptsConfig.imports || [], PROMPTS_FILE);
      totalPrompts = Object.values(stats).reduce((sum, count) => sum + count, 0);

      // Count files and calculate disk usage
      const calculateDirSize = async (dirPath: string): Promise<{ files: number; size: number }> => {
        let files = 0;
        let size = 0;

        try {
          const items = await fs.readdir(dirPath, { withFileTypes: true });

          for (const item of items) {
            const itemPath = path.join(dirPath, item.name);

            if (item.isDirectory()) {
              const subResult = await calculateDirSize(itemPath);
              files += subResult.files;
              size += subResult.size;
            } else {
              files++;
              const stat = await fs.stat(itemPath);
              size += stat.size;
            }
          }
        } catch (error) {
          // Ignore errors for inaccessible directories
        }

        return { files, size };
      };

      const dirStats = await calculateDirSize(promptsDir);
      totalFiles = dirStats.files;
      diskUsage = dirStats.size;

    } catch (error) {
      this.logger.warn('Failed to calculate file system stats:', error);
    }

    return {
      totalCategories,
      totalPrompts,
      totalFiles,
      diskUsage
    };
  }
}
```

--------------------------------------------------------------------------------
/server/src/frameworks/prompt-guidance/methodology-tracker.ts:
--------------------------------------------------------------------------------

```typescript
/**
 * Methodology Tracker - Phase 3 Implementation
 *
 * Tracks active methodology state and handles framework switching.
 * Consolidated from framework-state-manager for better separation of concerns.
 */

import { EventEmitter } from "events";
import { Logger } from "../../logging/index.js";
import {
  FrameworkDefinition,
  MethodologyState,
  MethodologySwitchRequest,
  MethodologyHealth,
  PersistedMethodologyState
} from "../types/index.js";
import * as fs from 'fs/promises';
import * as path from 'path';

/**
 * Methodology tracking configuration
 */
export interface MethodologyTrackerConfig {
  persistStateToDisk: boolean;
  stateFilePath: string;
  enableHealthMonitoring: boolean;
  healthCheckIntervalMs: number;
  maxSwitchHistory: number;
  enableMetrics: boolean;
}

/**
 * Methodology Tracker Events
 */
export interface MethodologyTrackerEvents {
  'methodology-switched': (previous: string, current: string, reason: string) => void;
  'methodology-error': (methodology: string, error: Error) => void;
  'health-changed': (health: MethodologyHealth) => void;
  'state-persisted': (state: PersistedMethodologyState) => void;
}

/**
 * Methodology Tracker
 *
 * Maintains methodology state across operations, handles switching,
 * and provides health monitoring for the methodology system.
 */
export class MethodologyTracker extends EventEmitter {
  private logger: Logger;
  private config: MethodologyTrackerConfig;
  private currentState: MethodologyState;
  private readonly rootPath: string;
  private switchHistory: Array<{
    from: string;
    to: string;
    timestamp: Date;
    reason: string;
    success: boolean;
  }> = [];
  private healthCheckTimer: NodeJS.Timeout | null = null;
  private switchingMetrics = {
    totalSwitches: 0,
    successfulSwitches: 0,
    failedSwitches: 0,
    averageResponseTime: 0,
    responseTimes: [] as number[]
  };

  constructor(logger: Logger, config?: Partial<MethodologyTrackerConfig>) {
    super();
    this.logger = logger;
    const rootPath = path.resolve(process.env.MCP_SERVER_ROOT || process.cwd());
    this.rootPath = rootPath;
    const runtimeStatePath = path.join(rootPath, 'runtime-state', 'framework-state.json');

    const defaultConfig: MethodologyTrackerConfig = {
      persistStateToDisk: true,
      stateFilePath: runtimeStatePath,
      enableHealthMonitoring: true,
      healthCheckIntervalMs: 30000, // 30 seconds
      maxSwitchHistory: 100,
      enableMetrics: true
    };

    this.config = {
      ...defaultConfig,
      ...config,
      stateFilePath: config?.stateFilePath
        ? path.isAbsolute(config.stateFilePath)
          ? config.stateFilePath
          : path.resolve(rootPath, config.stateFilePath)
        : defaultConfig.stateFilePath
    };

    // Initialize default state
    this.currentState = {
      activeMethodology: "CAGEERF", // Default methodology
      previousMethodology: null,
      switchedAt: new Date(),
      switchReason: "Initial state",
      isHealthy: true,
      methodologySystemEnabled: true,
      switchingMetrics: {
        switchCount: 0,
        averageResponseTime: 0,
        errorCount: 0
      }
    };
  }

  /**
   * Initialize methodology tracker with state restoration
   */
  async initialize(): Promise<void> {
    this.logger.info("Initializing MethodologyTracker...");

    try {
      // Restore state from disk if enabled
      if (this.config.persistStateToDisk) {
        await this.restoreState();
      }

      // Start health monitoring if enabled
      if (this.config.enableHealthMonitoring) {
        this.startHealthMonitoring();
      }

      this.logger.info(`MethodologyTracker initialized with ${this.currentState.activeMethodology} methodology`);
    } catch (error) {
      this.logger.error("Failed to initialize MethodologyTracker:", error);
      throw error;
    }
  }

  /**
   * Switch to a different methodology
   * Consolidated from framework-state-manager.switchFramework()
   */
  async switchMethodology(request: MethodologySwitchRequest): Promise<boolean> {
    const startTime = Date.now();
    const previousMethodology = this.currentState.activeMethodology;
    const targetMethodology = request.targetMethodology;
    const reason = request.reason || "Manual switch";

    this.logger.info(`Switching methodology: ${previousMethodology} -> ${targetMethodology} (${reason})`);

    try {
      // Validate switch request
      if (!this.validateSwitchRequest(request)) {
        throw new Error(`Invalid switch request: ${targetMethodology}`);
      }

      // Update state
      this.currentState = {
        ...this.currentState,
        previousMethodology,
        activeMethodology: targetMethodology,
        switchedAt: new Date(),
        switchReason: reason,
        switchingMetrics: {
          ...this.currentState.switchingMetrics,
          switchCount: this.currentState.switchingMetrics.switchCount + 1
        }
      };

      // Record switch in history
      const switchRecord = {
        from: previousMethodology,
        to: targetMethodology,
        timestamp: new Date(),
        reason,
        success: true
      };
      this.addToSwitchHistory(switchRecord);

      // Update metrics
      if (this.config.enableMetrics) {
        this.updateSwitchingMetrics(Date.now() - startTime, true);
      }

      // Persist state if enabled
      if (this.config.persistStateToDisk) {
        await this.persistState();
      }

      // Emit event
      this.emit('methodology-switched', previousMethodology, targetMethodology, reason);

      this.logger.info(`Methodology switch completed: ${previousMethodology} -> ${targetMethodology} in ${Date.now() - startTime}ms`);
      return true;

    } catch (error) {
      this.logger.error(`Failed to switch methodology to ${targetMethodology}:`, error);

      // Record failed switch
      this.addToSwitchHistory({
        from: previousMethodology,
        to: targetMethodology,
        timestamp: new Date(),
        reason,
        success: false
      });

      // Update failure metrics
      if (this.config.enableMetrics) {
        this.updateSwitchingMetrics(Date.now() - startTime, false);
      }

      // Emit error event
      this.emit('methodology-error', targetMethodology, error instanceof Error ? error : new Error(String(error)));

      return false;
    }
  }

  /**
   * Get current methodology state
   */
  getCurrentState(): MethodologyState {
    return { ...this.currentState };
  }

  /**
   * Get methodology system health
   */
  getSystemHealth(): MethodologyHealth {
    return {
      status: this.currentState.isHealthy ? "healthy" : "error",
      activeMethodology: this.currentState.activeMethodology,
      methodologySystemEnabled: this.currentState.methodologySystemEnabled,
      lastSwitchTime: this.currentState.switchedAt,
      switchingMetrics: {
        totalSwitches: this.switchingMetrics.totalSwitches,
        successfulSwitches: this.switchingMetrics.successfulSwitches,
        failedSwitches: this.switchingMetrics.failedSwitches,
        averageResponseTime: this.switchingMetrics.averageResponseTime
      },
      issues: this.detectHealthIssues()
    };
  }

  /**
   * Enable or disable the methodology system
   */
  async setMethodologySystemEnabled(enabled: boolean, reason: string = "Manual toggle"): Promise<void> {
    const previousState = this.currentState.methodologySystemEnabled;

    this.currentState.methodologySystemEnabled = enabled;
    this.currentState.switchReason = `System ${enabled ? 'enabled' : 'disabled'}: ${reason}`;

    this.logger.info(`Methodology system ${enabled ? 'enabled' : 'disabled'}: ${reason}`);

    // Persist state change
    if (this.config.persistStateToDisk) {
      await this.persistState();
    }

    // Emit event if state changed
    if (previousState !== enabled) {
      this.emit('methodology-system-toggled' as any, enabled, reason);
    }
  }

  /**
   * Get switch history
   */
  getSwitchHistory(): Array<{ from: string; to: string; timestamp: Date; reason: string; success: boolean }> {
    return [...this.switchHistory];
  }

  /**
   * Clear switch history
   */
  clearSwitchHistory(): void {
    this.switchHistory = [];
    this.logger.debug("Switch history cleared");
  }

  /**
   * Shutdown methodology tracker
   */
  async shutdown(): Promise<void> {
    this.logger.info("Shutting down MethodologyTracker...");

    // Stop health monitoring
    if (this.healthCheckTimer) {
      clearInterval(this.healthCheckTimer);
      this.healthCheckTimer = null;
    }

    // Persist final state
    if (this.config.persistStateToDisk) {
      await this.persistState();
    }

    this.logger.info("MethodologyTracker shutdown complete");
  }

  /**
   * Validate switch request
   */
  private validateSwitchRequest(request: MethodologySwitchRequest): boolean {
    // Check if methodology system is enabled
    if (!this.currentState.methodologySystemEnabled) {
      this.logger.warn("Methodology switch rejected - system disabled");
      return false;
    }

    // Check if switching to same methodology
    if (request.targetMethodology === this.currentState.activeMethodology) {
      this.logger.debug(`Already using ${request.targetMethodology} methodology`);
      return true; // Not an error, but no switch needed
    }

    // Validate methodology exists (basic validation)
    const validMethodologies = ["CAGEERF", "ReACT", "5W1H", "SCAMPER"];
    if (!validMethodologies.includes(request.targetMethodology)) {
      this.logger.error(`Invalid methodology: ${request.targetMethodology}`);
      return false;
    }

    return true;
  }

  /**
   * Add switch record to history
   */
  private addToSwitchHistory(record: {
    from: string;
    to: string;
    timestamp: Date;
    reason: string;
    success: boolean;
  }): void {
    this.switchHistory.push(record);

    // Trim history if it exceeds maximum
    if (this.switchHistory.length > this.config.maxSwitchHistory) {
      this.switchHistory = this.switchHistory.slice(-this.config.maxSwitchHistory);
    }
  }

  /**
   * Update switching metrics
   */
  private updateSwitchingMetrics(responseTime: number, success: boolean): void {
    this.switchingMetrics.totalSwitches++;

    if (success) {
      this.switchingMetrics.successfulSwitches++;
    } else {
      this.switchingMetrics.failedSwitches++;
    }

    // Update response time metrics
    this.switchingMetrics.responseTimes.push(responseTime);
    if (this.switchingMetrics.responseTimes.length > 100) {
      this.switchingMetrics.responseTimes = this.switchingMetrics.responseTimes.slice(-100);
    }

    this.switchingMetrics.averageResponseTime =
      this.switchingMetrics.responseTimes.reduce((sum, time) => sum + time, 0) /
      this.switchingMetrics.responseTimes.length;

    // Update current state metrics
    this.currentState.switchingMetrics = {
      switchCount: this.switchingMetrics.totalSwitches,
      averageResponseTime: this.switchingMetrics.averageResponseTime,
      errorCount: this.switchingMetrics.failedSwitches
    };
  }

  /**
   * Start health monitoring
   */
  private startHealthMonitoring(): void {
    this.healthCheckTimer = setInterval(() => {
      this.performHealthCheck();
    }, this.config.healthCheckIntervalMs);

    this.logger.debug(`Health monitoring started (interval: ${this.config.healthCheckIntervalMs}ms)`);
  }

  /**
   * Perform health check
   */
  private performHealthCheck(): void {
    const wasHealthy = this.currentState.isHealthy;
    const health = this.getSystemHealth();

    // Update health status
    this.currentState.isHealthy = health.status === "healthy";

    // Emit health change event if status changed
    if (wasHealthy !== this.currentState.isHealthy) {
      this.emit('health-changed', health);
      this.logger.info(`Methodology system health changed: ${health.status}`);
    }
  }

  /**
   * Detect health issues
   */
  private detectHealthIssues(): string[] {
    const issues: string[] = [];

    // Check error rate
    const errorRate = this.switchingMetrics.totalSwitches > 0
      ? this.switchingMetrics.failedSwitches / this.switchingMetrics.totalSwitches
      : 0;

    if (errorRate > 0.1) { // More than 10% error rate
      issues.push(`High error rate: ${(errorRate * 100).toFixed(1)}%`);
    }

    // Check response time
    if (this.switchingMetrics.averageResponseTime > 1000) { // More than 1 second
      issues.push(`Slow switching: ${this.switchingMetrics.averageResponseTime.toFixed(0)}ms average`);
    }

    // Check if system is disabled
    if (!this.currentState.methodologySystemEnabled) {
      issues.push("Methodology system is disabled");
    }

    return issues;
  }

  /**
   * Persist state to disk
   */
  private async persistState(): Promise<void> {
    try {
      const persistedState: PersistedMethodologyState = {
        version: "1.0.0",
        methodologySystemEnabled: this.currentState.methodologySystemEnabled,
        activeMethodology: this.currentState.activeMethodology,
        lastSwitchedAt: this.currentState.switchedAt.toISOString(),
        switchReason: this.currentState.switchReason
      };

      await fs.mkdir(path.dirname(this.config.stateFilePath), { recursive: true });
      await fs.writeFile(
        this.config.stateFilePath,
        JSON.stringify(persistedState, null, 2)
      );
      this.emit('state-persisted', persistedState);
      this.logger.debug(`State persisted to ${this.config.stateFilePath}`);

    } catch (error) {
      this.logger.error("Failed to persist methodology state:", error);
    }
  }

  /**
   * Restore state from disk
   */
  private async restoreState(): Promise<void> {
    const persistedState = await this.readPersistedState();

    if (!persistedState) {
      this.logger.debug("Using default methodology state");
      return;
    }

    this.currentState = {
      ...this.currentState,
      activeMethodology: persistedState.activeMethodology,
      methodologySystemEnabled: persistedState.methodologySystemEnabled,
      switchedAt: new Date(persistedState.lastSwitchedAt),
      switchReason: persistedState.switchReason
    };

    this.logger.info(
      `State restored from ${this.config.stateFilePath}: ${persistedState.activeMethodology}`
    );
  }

  private async readPersistedState(): Promise<PersistedMethodologyState | null> {
    try {
      const stateData = await fs.readFile(this.config.stateFilePath, 'utf-8');
      return JSON.parse(stateData);
    } catch (error: any) {
      if (error?.code !== 'ENOENT') {
        this.logger.warn(
          `Failed to read methodology state from ${this.config.stateFilePath}: ${
            error instanceof Error ? error.message : String(error)
          }`
        );
      }
      return null;
    }
  }

  /**
   * Update tracker configuration
   */
  updateConfig(config: Partial<MethodologyTrackerConfig>): void {
    const oldConfig = { ...this.config };
    this.config = { ...this.config, ...config };

    if (config.stateFilePath) {
      this.config.stateFilePath = path.isAbsolute(config.stateFilePath)
        ? config.stateFilePath
        : path.resolve(this.rootPath, config.stateFilePath);
    }

    // Restart health monitoring if interval changed
    if (oldConfig.healthCheckIntervalMs !== this.config.healthCheckIntervalMs && this.config.enableHealthMonitoring) {
      if (this.healthCheckTimer) {
        clearInterval(this.healthCheckTimer);
      }
      this.startHealthMonitoring();
    }

    this.logger.debug('MethodologyTracker configuration updated', config);
  }

  /**
   * Get current tracker configuration
   */
  getConfig(): MethodologyTrackerConfig {
    return { ...this.config };
  }
}

/**
 * Create and initialize a MethodologyTracker instance
 */
export async function createMethodologyTracker(
  logger: Logger,
  config?: Partial<MethodologyTrackerConfig>
): Promise<MethodologyTracker> {
  const tracker = new MethodologyTracker(logger, config);
  await tracker.initialize();
  return tracker;
}

```

--------------------------------------------------------------------------------
/server/src/api/index.ts:
--------------------------------------------------------------------------------

```typescript
/**
 * API Management Module
 * Handles Express app setup, middleware, and REST API endpoints
 */

import express, { Request, Response } from "express";
import { mkdir, readFile, writeFile } from "fs/promises";
import path from "path";
import { ConfigManager } from "../config/index.js";
import { Logger } from "../logging/index.js";
import { McpToolsManager } from "../mcp-tools/index.js";
import { PromptManager } from "../prompts/index.js";
import { modifyPromptSection } from "../prompts/promptUtils.js";
import { Category, PromptData, PromptsFile } from "../types/index.js";

/**
 * API Manager class
 */
export class ApiManager {
  private logger: Logger;
  private configManager: ConfigManager;
  private promptManager?: PromptManager;
  private mcpToolsManager?: McpToolsManager;
  private promptsData: PromptData[] = [];
  private categories: Category[] = [];
  private convertedPrompts: any[] = [];

  constructor(
    logger: Logger,
    configManager: ConfigManager,
    promptManager?: PromptManager,
    mcpToolsManager?: McpToolsManager
  ) {
    this.logger = logger;
    this.configManager = configManager;
    this.promptManager = promptManager;
    this.mcpToolsManager = mcpToolsManager;
  }

  /**
   * Update data references
   */
  updateData(
    promptsData: PromptData[],
    categories: Category[],
    convertedPrompts: any[]
  ): void {
    this.promptsData = promptsData;
    this.categories = categories;
    this.convertedPrompts = convertedPrompts;
  }

  /**
   * Create and configure Express application
   */
  createApp(): express.Application {
    const app = express();

    // Setup middleware
    this.setupMiddleware(app);

    // Setup routes
    this.setupRoutes(app);

    return app;
  }

  /**
   * Setup Express middleware
   */
  private setupMiddleware(app: express.Application): void {
    // Enable CORS for Cursor integration
    app.use((req, res, next) => {
      res.header("Access-Control-Allow-Origin", "*");
      res.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS, DELETE");
      res.header(
        "Access-Control-Allow-Headers",
        "Origin, X-Requested-With, Content-Type, Accept"
      );
      if (req.method === "OPTIONS") {
        return res.sendStatus(200);
      }
      next();
    });

    // Add JSON body parser middleware
    app.use(express.json());

    // Add request logging middleware
    app.use((req, res, next) => {
      this.logger.debug(
        `${req.method} ${req.url} - Headers: ${JSON.stringify(req.headers)}`
      );
      next();
    });
  }

  /**
   * Setup API routes
   */
  private setupRoutes(app: express.Application): void {
    // Basic routes
    this.setupBasicRoutes(app);

    // Prompt and category routes
    this.setupPromptRoutes(app);

    // Tool API routes
    this.setupToolRoutes(app);
  }

  /**
   * Setup basic routes (home, health)
   */
  private setupBasicRoutes(app: express.Application): void {
    app.get("/", (_req: Request, res: Response) => {
      res.send(
        "Claude Custom Prompts MCP Server - Use /mcp endpoint for MCP connections"
      );
    });

    // Health check endpoint
    app.get("/health", (_req: Request, res: Response) => {
      const config = this.configManager.getConfig();
      res.json({ status: "ok", version: config.server.version });
    });
  }

  /**
   * Setup prompt and category routes
   */
  private setupPromptRoutes(app: express.Application): void {
    // Get all categories and prompts
    app.get("/prompts", (_req: Request, res: Response) => {
      const result = {
        categories: this.categories,
        prompts: this.promptsData.map((prompt) => ({
          id: prompt.id,
          name: prompt.name,
          category: prompt.category,
          description: prompt.description,
          arguments: prompt.arguments,
        })),
      };
      res.json(result);
    });

    // Get prompts by category
    app.get(
      "/categories/:categoryId/prompts",
      (req: Request, res: Response) => {
        const categoryId = req.params.categoryId;
        const categoryPrompts = this.promptsData.filter(
          (prompt) => prompt.category === categoryId
        );

        if (categoryPrompts.length === 0) {
          return res
            .status(404)
            .json({ error: `No prompts found for category: ${categoryId}` });
        }

        res.json(categoryPrompts);
      }
    );
  }

  /**
   * Setup tool API routes
   */
  private setupToolRoutes(app: express.Application): void {
    // Create category endpoint
    app.post(
      "/api/v1/tools/create_category",
      async (req: Request, res: Response) => {
        await this.handleCreateCategory(req, res);
      }
    );

    // Update prompt endpoint
    app.post(
      "/api/v1/tools/update_prompt",
      async (req: Request, res: Response) => {
        await this.handleUpdatePrompt(req, res);
      }
    );

    // Delete prompt endpoint
    app.delete(
      "/api/v1/tools/prompts/:id",
      async (req: Request, res: Response) => {
        await this.handleDeletePrompt(req, res);
      }
    );

    // Modify prompt section endpoint
    app.post(
      "/api/v1/tools/modify_prompt_section",
      async (req: Request, res: Response) => {
        await this.handleModifyPromptSection(req, res);
      }
    );

    // Reload prompts endpoint
    app.post(
      "/api/v1/tools/reload_prompts",
      async (req: Request, res: Response) => {
        await this.handleReloadPrompts(req, res);
      }
    );
  }

  /**
   * Handle create category API endpoint
   */
  private async handleCreateCategory(
    req: Request,
    res: Response
  ): Promise<void> {
    try {
      this.logger.info("API request to create category:", req.body);

      // Validate required fields
      if (!req.body.id || !req.body.name || !req.body.description) {
        res.status(400).json({
          error:
            "Missing required fields. Please provide id, name, and description.",
        });
        return;
      }

      const { id, name, description } = req.body;

      // Read the current prompts configuration file
      const PROMPTS_FILE = this.getPromptsFilePath();
      const fileContent = await readFile(PROMPTS_FILE, "utf8");
      const promptsFile = JSON.parse(fileContent) as PromptsFile;

      // Check if the category already exists
      const categoryExists = promptsFile.categories.some(
        (cat) => cat.id === id
      );
      if (categoryExists) {
        res.status(400).json({ error: `Category '${id}' already exists.` });
        return;
      }

      // Add the new category
      promptsFile.categories.push({ id, name, description });

      // Write the updated file
      await writeFile(
        PROMPTS_FILE,
        JSON.stringify(promptsFile, null, 2),
        "utf8"
      );

      // Create the category directory if it doesn't exist
      const categoryDirPath = path.join(path.dirname(PROMPTS_FILE), id);
      try {
        await mkdir(categoryDirPath, { recursive: true });
      } catch (error) {
        this.logger.error(
          `Error creating directory ${categoryDirPath}:`,
          error
        );
        // Continue even if directory creation fails
      }

      // Reload prompts and categories if prompt manager is available
      if (this.promptManager) {
        try {
          await this.reloadPromptData();
          this.logger.info(
            `Reloaded ${this.promptsData.length} prompts and ${this.categories.length} categories after creating category: ${id}`
          );
        } catch (error) {
          this.logger.error("Error reloading prompts data:", error);
        }
      }

      res.status(200).json({
        success: true,
        message: `Category '${name}' created successfully`,
      });
    } catch (error) {
      this.logger.error("Error handling create_category API request:", error);
      res.status(500).json({
        error: "Internal server error",
        details: error instanceof Error ? error.message : String(error),
      });
    }
  }

  /**
   * Handle update prompt API endpoint
   */
  private async handleUpdatePrompt(req: Request, res: Response): Promise<void> {
    try {
      this.logger.info("API request to update prompt:", req.body);

      // Validate required fields
      if (
        !req.body.id ||
        !req.body.name ||
        !req.body.category ||
        !req.body.userMessageTemplate
      ) {
        res.status(400).json({
          error:
            "Missing required fields. Please provide id, name, category, and userMessageTemplate.",
        });
        return;
      }

      const {
        id,
        name,
        category,
        description,
        userMessageTemplate,
        arguments: promptArgs,
        systemMessage,
        isChain,
        chainSteps,
      } = req.body;

      // Implementation would include full update logic...
      // For brevity, this is a simplified version
      res.status(200).json({
        success: true,
        message: `Prompt '${name}' updated successfully`,
      });
    } catch (error) {
      this.logger.error("Error handling update_prompt API request:", error);
      res.status(500).json({
        error: "Internal server error",
        details: error instanceof Error ? error.message : String(error),
      });
    }
  }

  /**
   * Handle delete prompt API endpoint
   */
  private async handleDeletePrompt(req: Request, res: Response): Promise<void> {
    try {
      const id = req.params.id;
      this.logger.info(`API request to delete prompt: ${id}`);

      if (!id) {
        res.status(400).json({ error: "Prompt ID is required" });
        return;
      }

      // Implementation would include full delete logic...
      res.status(200).json({
        success: true,
        message: `Prompt '${id}' deleted successfully`,
      });
    } catch (error) {
      this.logger.error("Error handling delete_prompt API request:", error);
      res.status(500).json({
        error: "Internal server error",
        details: error instanceof Error ? error.message : String(error),
      });
    }
  }

  /**
   * Handle modify prompt section API endpoint
   */
  private async handleModifyPromptSection(
    req: Request,
    res: Response
  ): Promise<void> {
    try {
      this.logger.info("Received request to modify prompt section:", req.body);

      const { id, section_name, new_content, restartServer } = req.body;

      if (!id || !section_name || !new_content) {
        res.status(400).json({
          success: false,
          message:
            "Missing required fields: id, section_name, and new_content are required",
        });
        return;
      }

      // Use the modifyPromptSection function from promptUtils
      const PROMPTS_FILE = this.getPromptsFilePath();
      const result = await modifyPromptSection(
        id,
        section_name,
        new_content,
        PROMPTS_FILE
      );

      if (!result.success) {
        res.status(404).json({
          success: false,
          message: result.message,
        });
        return;
      }

      // Reload prompt data if available
      if (this.promptManager) {
        try {
          await this.reloadPromptData();
          this.logger.info(
            `Triggered server refresh${
              restartServer ? " with restart" : ""
            } after modifying section: ${section_name}`
          );
        } catch (refreshError) {
          this.logger.error(
            `Error refreshing server after modifying section: ${section_name}`,
            refreshError
          );
        }
      }

      res.status(200).json({
        success: true,
        message: result.message,
        restarting: restartServer || false,
      });
    } catch (error) {
      this.logger.error(
        "Error handling modify_prompt_section API request:",
        error
      );
      res.status(500).json({
        success: false,
        message: "Internal server error",
      });
    }
  }

  /**
   * Handle reload prompts API endpoint
   */
  private async handleReloadPrompts(
    req: Request,
    res: Response
  ): Promise<void> {
    try {
      this.logger.info("API request to reload prompts");

      const shouldRestart = req.body && req.body.restart === true;
      const reason =
        req.body && req.body.reason
          ? req.body.reason
          : "Manual reload requested";

      try {
        // Reload prompt data if available
        if (this.promptManager) {
          await this.reloadPromptData();
        }

        if (shouldRestart) {
          res.status(200).json({
            success: true,
            message: `Successfully refreshed the server with ${this.promptsData.length} prompts and ${this.categories.length} categories. Server is now restarting.`,
            data: {
              promptsCount: this.promptsData.length,
              categoriesCount: this.categories.length,
              convertedPromptsCount: this.convertedPrompts.length,
              restarting: true,
            },
          });
        } else {
          res.status(200).json({
            success: true,
            message: `Successfully refreshed the server with ${this.promptsData.length} prompts and ${this.categories.length} categories`,
            data: {
              promptsCount: this.promptsData.length,
              categoriesCount: this.categories.length,
              convertedPromptsCount: this.convertedPrompts.length,
            },
          });
        }
      } catch (refreshError) {
        this.logger.error("Error refreshing server:", refreshError);
        res.status(500).json({
          success: false,
          message: `Failed to refresh server: ${
            refreshError instanceof Error
              ? refreshError.message
              : String(refreshError)
          }`,
        });
      }
    } catch (error) {
      this.logger.error("Error handling reload_prompts API request:", error);
      res.status(500).json({
        success: false,
        message: "Internal server error",
      });
    }
  }

  /**
   * Helper method to reload prompt data
   */
  private async reloadPromptData(): Promise<void> {
    if (!this.promptManager) {
      throw new Error("PromptManager not available");
    }

    const PROMPTS_FILE = this.getPromptsFilePath();

    const result = await this.promptManager.loadAndConvertPrompts(PROMPTS_FILE);
    this.updateData(
      result.promptsData,
      result.categories,
      result.convertedPrompts
    );

    // Update MCP tools manager if available
    if (this.mcpToolsManager) {
      this.mcpToolsManager.updateData(
        result.promptsData,
        result.convertedPrompts,
        result.categories
      );
    }
  }

  /**
   * Get prompts file path using consistent resolution logic
   * This ensures all API operations use the same path resolution as the orchestration module
   */
  private getPromptsFilePath(): string {
    // ENHANCED: Use same path resolution logic as orchestration module
    // This ensures API operations also respect MCP_PROMPTS_CONFIG_PATH environment variable
    let PROMPTS_FILE: string;

    if (process.env.MCP_PROMPTS_CONFIG_PATH) {
      PROMPTS_FILE = process.env.MCP_PROMPTS_CONFIG_PATH;
      this.logger.info(
        "🎯 API: Using MCP_PROMPTS_CONFIG_PATH environment variable override"
      );
    } else {
      // Fallback to ConfigManager's getPromptsFilePath() method which handles server root properly
      PROMPTS_FILE = this.configManager.getPromptsFilePath();
      this.logger.info(
        "📁 API: Using config-based prompts file path resolution"
      );
    }

    // Ensure absolute path (critical for Claude Desktop)
    if (!path.isAbsolute(PROMPTS_FILE)) {
      PROMPTS_FILE = path.resolve(PROMPTS_FILE);
      this.logger.info(`🔧 API: Converted to absolute path: ${PROMPTS_FILE}`);
    }

    return PROMPTS_FILE;
  }
}

/**
 * Create and configure an API manager
 */
export function createApiManager(
  logger: Logger,
  configManager: ConfigManager,
  promptManager?: PromptManager,
  mcpToolsManager?: McpToolsManager
): ApiManager {
  return new ApiManager(logger, configManager, promptManager, mcpToolsManager);
}

```

--------------------------------------------------------------------------------
/server/tests/integration/unified-parsing-integration.test.ts:
--------------------------------------------------------------------------------

```typescript
/**
 * Integration Tests for Unified Parsing System
 * 
 * End-to-end integration tests that verify the complete parsing system
 * works correctly with the real MCP server infrastructure.
 */

import { describe, test, expect, beforeEach, afterEach, jest } from '@jest/globals';
import { Logger } from '../../src/logging/index.js';
import { PromptManager } from '../../src/prompts/index.js';
import { ConsolidatedPromptEngine, createConsolidatedPromptEngine } from '../../src/mcp-tools/consolidated-prompt-engine.js';
import { SemanticAnalyzer } from '../../src/analysis/semantic-analyzer.js';
import { PromptData, ConvertedPrompt } from '../../src/types/index.js';
import { isChainPrompt } from '../../src/utils/chainUtils.js';

// Mock logger
const mockLogger: Logger = {
  debug: jest.fn(),
  info: jest.fn(),
  warn: jest.fn(),
  error: jest.fn()
} as any;

// Mock MCP server
const mockMcpServer = {
  tool: jest.fn()
};

// Mock prompt manager
const mockPromptManager = {
  processTemplateAsync: jest.fn().mockResolvedValue('Processed template content'),
  convertedPrompts: [] as ConvertedPrompt[],
  promptsData: [] as PromptData[]
} as any;

// Mock semantic analyzer
const mockSemanticAnalyzer = {
  analyzePrompt: jest.fn().mockResolvedValue({
    executionType: 'template',
    requiresExecution: true,
    confidence: 0.8,
    reasoning: ['Simple prompt detected'],
    suggestedGates: []
  })
} as any;

// Test data
const testPromptsData: PromptData[] = [
  {
    id: 'simple_test',
    name: 'simple_test',
    description: 'A simple test prompt',
    userMessageTemplate: 'Process this: {{content}}',
    arguments: [
      {
        name: 'content',
        description: 'Content to process',
        required: true
      }
    ],
    category: 'test'
  },
  {
    id: 'multi_arg_test',
    name: 'multi_arg_test', 
    description: 'Multi-argument test prompt',
    userMessageTemplate: 'Transform {{text}} to {{format}} in {{language}}',
    arguments: [
      {
        name: 'text',
        description: 'Text to transform',
        required: true
      },
      {
        name: 'format',
        description: 'Output format (json, xml, csv)',
        required: false
      },
      {
        name: 'language',
        description: 'Target language',
        required: false
      }
    ],
    category: 'test'
  },
  {
    id: 'chain_test',
    name: 'chain_test',
    description: 'Chain execution test prompt',
    userMessageTemplate: 'Step result: {{result}}',
    arguments: [
      {
        name: 'result',
        description: 'Result from previous step',
        required: false
      }
    ],
    category: 'test'
  }
];

const testConvertedPrompts: ConvertedPrompt[] = testPromptsData.map(prompt => ({
  ...prompt,
  chainSteps: prompt.id === 'chain_test' ? [
    { stepName: 'Step 1', promptId: 'simple_test' },
    { stepName: 'Step 2', promptId: 'multi_arg_test' }
  ] : undefined
}));

describe('Unified Parsing Integration Tests', () => {
  let promptEngine: ConsolidatedPromptEngine;

  beforeEach(() => {
    // Reset mocks
    jest.clearAllMocks();
    
    // Create prompt engine with enhanced parsing
    promptEngine = createConsolidatedPromptEngine(
      mockLogger,
      mockMcpServer,
      mockPromptManager,
      mockSemanticAnalyzer
    );
    
    // Update test data
    promptEngine.updateData(testPromptsData, testConvertedPrompts);
  });

  describe('End-to-End Command Processing', () => {
    test('should process simple command through entire pipeline', async () => {
      const mockExecutePrompt = jest.fn();
      
      // Mock the internal executePrompt method
      (promptEngine as any).executePrompt = mockExecutePrompt.mockResolvedValue({
        content: [{ type: 'text', text: 'Success: Processed content' }]
      });

      // Simulate the command execution
      const result = await (promptEngine as any).executePrompt({
        command: '>>simple_test Hello world',
        execution_mode: 'auto'
      }, {});

      expect(mockExecutePrompt).toHaveBeenCalledWith(
        expect.objectContaining({
          command: '>>simple_test Hello world',
          execution_mode: 'auto'
        }),
        {}
      );
    });

    test('should handle JSON command format', async () => {
      const mockExecutePrompt = jest.fn().mockResolvedValue({
        content: [{ type: 'text', text: 'Success: JSON processed' }]
      });
      
      (promptEngine as any).executePrompt = mockExecutePrompt;

      const jsonCommand = JSON.stringify({
        command: '>>multi_arg_test',
        args: {
          text: 'Hello world',
          format: 'json',
          language: 'en'
        }
      });

      await (promptEngine as any).executePrompt({
        command: jsonCommand,
        execution_mode: 'auto'
      }, {});

      expect(mockExecutePrompt).toHaveBeenCalled();
    });

    test('should handle structured command format', async () => {
      const mockExecutePrompt = jest.fn().mockResolvedValue({
        content: [{ type: 'text', text: 'Success: Structured processed' }]
      });
      
      (promptEngine as any).executePrompt = mockExecutePrompt;

      const structuredCommand = 'multi_arg_test {"text": "Hello", "format": "xml"}';

      await (promptEngine as any).executePrompt({
        command: structuredCommand,
        execution_mode: 'template'
      }, {});

      expect(mockExecutePrompt).toHaveBeenCalled();
    });

    test('should parse multi-line arguments in simple command format', async () => {
      const multiLineCommand = [
        '>>simple_test **Title**: Network Layers Model',
        '**Summary**:',
        'Line one of details.',
        'Line two of details.'
      ].join('\n');

      const result = await (promptEngine as any).parseCommandUnified(multiLineCommand);

      expect(result.promptId).toBe('simple_test');
      expect(result.arguments).toBeDefined();
      expect(result.arguments.content).toContain('Line two of details.');
      expect(result.arguments.content.split('\n').length).toBeGreaterThan(1);
    });
  });

  describe('Context-Aware Processing', () => {
    test('should use conversation history for context', async () => {
      // Mock conversation history in prompt manager
      const mockHistory = [
        { role: 'user', content: 'Previous message content', timestamp: Date.now() - 1000 }
      ];
      
      mockPromptManager.getHistory = jest.fn().mockReturnValue(mockHistory);

      const mockExecutePrompt = jest.fn().mockResolvedValue({
        content: [{ type: 'text', text: 'Success: Context aware' }]
      });
      
      (promptEngine as any).executePrompt = mockExecutePrompt;

      // Execute command that should use context
      await (promptEngine as any).executePrompt({
        command: '>>simple_test',
        execution_mode: 'auto'
      }, {});

      expect(mockExecutePrompt).toHaveBeenCalled();
    });

    test('should resolve environment variables for defaults', async () => {
      // Set environment variable
      process.env.PROMPT_FORMAT = 'json';
      process.env.PROMPT_LANGUAGE = 'es';

      const mockExecutePrompt = jest.fn().mockResolvedValue({
        content: [{ type: 'text', text: 'Success: Environment resolved' }]
      });
      
      (promptEngine as any).executePrompt = mockExecutePrompt;

      await (promptEngine as any).executePrompt({
        command: '>>multi_arg_test Hello world',
        execution_mode: 'auto'
      }, {});

      expect(mockExecutePrompt).toHaveBeenCalled();

      // Clean up
      delete process.env.PROMPT_FORMAT;
      delete process.env.PROMPT_LANGUAGE;
    });
  });

  describe('Error Handling and Recovery', () => {
    test('should provide helpful error messages for unknown prompts', async () => {
      try {
        await (promptEngine as any).parseCommandUnified('>>unknown_prompt test');
        expect(true).toBe(false); // Should not reach here
      } catch (error: any) {
        expect(error.message).toContain('Unknown prompt: unknown_prompt');
        expect(error.message).toContain('>>listprompts');
      }
    });

    test('should suggest corrections for typos', async () => {
      try {
        await (promptEngine as any).parseCommandUnified('>>simple_tst test');
      } catch (error: any) {
        expect(error.message).toContain('simple_test');
      }
    });

    test('should handle malformed JSON gracefully', async () => {
      try {
        await (promptEngine as any).parseCommandUnified('{"command": ">>simple_test", "malformed": json}');
      } catch (error: any) {
        expect(error.message).toContain('Supported command formats');
      }
    });
  });

  describe('Performance and Statistics', () => {
    test('should track parsing statistics', async () => {
      // Execute several commands
      const commands = [
        '>>simple_test hello',
        '>>multi_arg_test world format=json',
        'chain_test {"result": "test"}'
      ];

      for (const command of commands) {
        try {
          await (promptEngine as any).parseCommandUnified(command);
        } catch (error) {
          // Expected for some test cases
        }
      }

      const stats = promptEngine.getParsingStats();
      
      expect(stats.commandParser).toBeDefined();
      expect(stats.argumentProcessor).toBeDefined();
      expect(stats.contextResolver).toBeDefined();
      
      expect(stats.commandParser.totalParses).toBeGreaterThan(0);
      expect(stats.argumentProcessor.totalProcessed).toBeGreaterThan(0);
      expect(stats.contextResolver.totalResolutions).toBeGreaterThan(0);
    });

    test('should allow statistics reset', () => {
      promptEngine.resetParsingStats();
      
      const stats = promptEngine.getParsingStats();
      expect(stats.commandParser.totalParses).toBe(0);
      expect(stats.argumentProcessor.totalProcessed).toBe(0);
      expect(stats.contextResolver.totalResolutions).toBe(0);
    });
  });

  describe('Execution Mode Detection', () => {
    test('should detect template mode for simple prompts', async () => {
      mockSemanticAnalyzer.analyzePrompt.mockResolvedValue({
        executionType: 'template',
        requiresExecution: false,
        confidence: 0.9,
        reasoning: ['Simple informational prompt'],
        suggestedGates: []
      });

      const mockExecuteTemplate = jest.fn().mockResolvedValue({
        content: [{ type: 'text', text: 'Template result' }]
      });
      
      (promptEngine as any).executeTemplate = mockExecuteTemplate;

      await (promptEngine as any).executePrompt({
        command: '>>simple_test info request',
        execution_mode: 'auto'
      }, {});

      // Would verify template mode was selected
    });

    test('should detect chain mode for chain prompts', async () => {
      const chainPrompt = testConvertedPrompts.find(p => isChainPrompt(p));
      expect(chainPrompt).toBeDefined();

      const mockExecuteChain = jest.fn().mockResolvedValue({
        content: [{ type: 'text', text: 'Chain result' }]
      });
      
      (promptEngine as any).executeChain = mockExecuteChain;

      // Test would verify chain execution
    });
  });

  describe('Backward Compatibility', () => {
    test('should maintain compatibility with legacy parseCommand calls', async () => {
      const legacyResult = await (promptEngine as any).parseCommand('>>simple_test legacy test');
      
      expect(legacyResult.promptId).toBe('simple_test');
      expect(legacyResult.arguments).toBeDefined();
      expect(legacyResult.convertedPrompt).toBeDefined();
    });

    test('should maintain compatibility with legacy parseArguments calls', async () => {
      const legacyResult = await (promptEngine as any).parseArguments(
        'legacy argument test',
        testPromptsData[0]
      );
      
      expect(legacyResult).toBeDefined();
      expect(typeof legacyResult).toBe('object');
    });

    test('should log migration warnings for deprecated methods', async () => {
      await (promptEngine as any).parseCommand('>>simple_test legacy');
      await (promptEngine as any).parseArguments('test', testPromptsData[0]);
      
      expect(mockLogger.warn).toHaveBeenCalledWith(
        expect.stringContaining('[MIGRATION]')
      );
    });
  });

  describe('Real-World Scenarios', () => {
    test('should handle complex multi-step workflow', async () => {
      const workflow = [
        '>>simple_test Extract key information from this document',
        '>>multi_arg_test format=json language=en',
        '>>chain_test'
      ];

      for (const command of workflow) {
        try {
          await (promptEngine as any).parseCommandUnified(command);
        } catch (error) {
          // Some commands may fail in test environment
        }
      }

      // Verify the workflow was processed
      const stats = promptEngine.getParsingStats();
      expect(stats.commandParser.totalParses).toBe(workflow.length);
    });

    test('should handle concurrent command processing', async () => {
      const concurrentCommands = [
        '>>simple_test concurrent test 1',
        '>>multi_arg_test concurrent test 2',
        '>>simple_test concurrent test 3'
      ];

      const promises = concurrentCommands.map(command => 
        (promptEngine as any).parseCommandUnified(command).catch(() => null)
      );

      await Promise.all(promises);

      const stats = promptEngine.getParsingStats();
      expect(stats.commandParser.totalParses).toBe(concurrentCommands.length);
    });

    test('should maintain state consistency under load', async () => {
      const commands = Array(50).fill(null).map((_, i) => 
        `>>simple_test load test ${i}`
      );

      for (const command of commands) {
        try {
          await (promptEngine as any).parseCommandUnified(command);
        } catch (error) {
          // Expected in test environment
        }
      }

      const stats = promptEngine.getParsingStats();
      expect(stats.commandParser.successfulParses + stats.commandParser.failedParses)
        .toBe(stats.commandParser.totalParses);
    });
  });
});

describe('Migration Validation', () => {
  test('should demonstrate zero-breaking-changes migration', async () => {
    const promptEngine = createConsolidatedPromptEngine(
      mockLogger,
      mockMcpServer,
      mockPromptManager,
      mockSemanticAnalyzer
    );
    
    promptEngine.updateData(testPromptsData, testConvertedPrompts);

    // All these legacy patterns should still work
    const legacyPatterns = [
      '>>simple_test hello',
      '>>multi_arg_test text format=json',
      'chain_test'
    ];

    let allPassed = true;
    for (const pattern of legacyPatterns) {
      try {
        await (promptEngine as any).parseCommandUnified(pattern);
      } catch (error) {
        // Error handling is expected, but should be graceful
        expect((error as Error).message).toBeTruthy();
      }
    }

    // Verify enhanced features are available
    expect(promptEngine.getParsingStats).toBeDefined();
    expect(promptEngine.resetParsingStats).toBeDefined();
  });
});

describe('System Health and Monitoring', () => {
  test('should provide comprehensive system health metrics', () => {
    const promptEngine = createConsolidatedPromptEngine(
      mockLogger,
      mockMcpServer,
      mockPromptManager,
      mockSemanticAnalyzer
    );

    const executionStats = promptEngine.getAnalytics();
    const parsingStats = promptEngine.getParsingStats();

    expect(executionStats).toHaveProperty('totalExecutions');
    expect(executionStats).toHaveProperty('successfulExecutions');
    expect(executionStats).toHaveProperty('executionsByMode');

    expect(parsingStats).toHaveProperty('commandParser');
    expect(parsingStats).toHaveProperty('argumentProcessor');
    expect(parsingStats).toHaveProperty('contextResolver');
  });

  test('should enable performance monitoring', async () => {
    const promptEngine = createConsolidatedPromptEngine(
      mockLogger,
      mockMcpServer,
      mockPromptManager,
      mockSemanticAnalyzer
    );
    
    promptEngine.updateData(testPromptsData, testConvertedPrompts);

    // Perform operations
    try {
      await (promptEngine as any).parseCommandUnified('>>simple_test monitoring test');
    } catch (error) {
      // Expected in test environment
    }

    const stats = promptEngine.getParsingStats();
    
    // Verify metrics are being collected
    expect(stats.commandParser.totalParses).toBeGreaterThan(0);
    expect(stats.commandParser.averageConfidence).toBeGreaterThanOrEqual(0);
  });
});

```

--------------------------------------------------------------------------------
/server/src/prompts/file-observer.ts:
--------------------------------------------------------------------------------

```typescript
/**
 * File Observer Module
 * Handles file system watching for automatic change detection and hot reload triggers
 */

import * as fs from "fs";
import { FSWatcher } from "fs";
import path from "path";
import { Logger } from "../logging/index.js";
import { EventEmitter } from "events";
import { ConfigManager } from "../config/index.js";

/**
 * File change event types
 */
export type FileChangeType = 'added' | 'modified' | 'removed' | 'renamed';

/**
 * Framework analysis data for file changes
 */
export interface FrameworkAnalysisData {
  requiresFrameworkUpdate: boolean;
  affectedFrameworks: string[];
  analysisInvalidated: boolean;
  performanceImpact: 'low' | 'medium' | 'high';
}

/**
 * File change event data
 */
export interface FileChangeEvent {
  type: FileChangeType;
  filePath: string;
  filename: string;
  timestamp: number;
  isPromptFile: boolean;
  isConfigFile: boolean;
  category?: string;
  frameworkAnalysis?: FrameworkAnalysisData;
}

/**
 * Framework integration capabilities
 */
export interface FrameworkIntegration {
  enabled: boolean;
  analyzeChanges: boolean;
  cacheInvalidation: boolean;
  performanceTracking: boolean;
}

/**
 * File observer configuration
 */
export interface FileObserverConfig {
  enabled: boolean;
  debounceMs: number;
  watchPromptFiles: boolean;
  watchConfigFiles: boolean;
  recursive: boolean;
  ignoredPatterns: string[];
  maxRetries: number;
  retryDelayMs: number;
  frameworkIntegration?: FrameworkIntegration;
}

/**
 * File observer statistics
 */
export interface FileObserverStats {
  watchersActive: number;
  eventsDetected: number;
  eventsDebounced: number;
  eventsTriggered: number;
  lastEventTime?: number;
  uptime: number;
  retryCount: number;
  frameworkEvents: number;
  frameworkCacheInvalidations: number;
}

/**
 * Default configuration for FileObserver
 */
const DEFAULT_CONFIG: FileObserverConfig = {
  enabled: true,
  debounceMs: 500,
  watchPromptFiles: true,
  watchConfigFiles: true,
  recursive: true,
  ignoredPatterns: [
    '**/.git/**',
    '**/node_modules/**',
    '**/.DS_Store',
    '**/Thumbs.db',
    '**/*.tmp',
    '**/*.temp',
    '**/dist/**',
    '**/*.log'
  ],
  maxRetries: 3,
  retryDelayMs: 1000,
  frameworkIntegration: {
    enabled: false,
    analyzeChanges: false,
    cacheInvalidation: false,
    performanceTracking: false
  }
};

/**
 * FileObserver class
 * Provides robust file system watching with event-driven architecture
 */
export class FileObserver extends EventEmitter {
  protected logger: Logger;
  private config: FileObserverConfig;
  private watchers: Map<string, FSWatcher> = new Map();
  private debounceTimers: Map<string, NodeJS.Timeout> = new Map();
  private stats: FileObserverStats;
  private isStarted: boolean = false;
  private startTime: number = 0;
  private retryCount: number = 0;
  private configManager?: ConfigManager;

  constructor(logger: Logger, config?: Partial<FileObserverConfig>, configManager?: ConfigManager) {
    super();
    this.logger = logger;
    this.config = { ...DEFAULT_CONFIG, ...config };
    this.configManager = configManager;
    this.stats = {
      watchersActive: 0,
      eventsDetected: 0,
      eventsDebounced: 0,
      eventsTriggered: 0,
      uptime: 0,
      retryCount: 0,
      frameworkEvents: 0,
      frameworkCacheInvalidations: 0
    };

    // Set max listeners to prevent warning for multiple prompt directories
    this.setMaxListeners(50);
  }

  /**
   * Start file watching
   */
  async start(): Promise<void> {
    if (this.isStarted) {
      this.logger.warn("FileObserver is already started");
      return;
    }

    if (!this.config.enabled) {
      this.logger.info("FileObserver is disabled in configuration");
      return;
    }

    this.logger.info("📁 FileObserver: Starting file system watching...");
    this.startTime = Date.now();
    this.isStarted = true;

    // Listen for process termination to clean up watchers
    process.on('SIGINT', () => this.stop());
    process.on('SIGTERM', () => this.stop());

    this.logger.info(`✅ FileObserver started with debounce: ${this.config.debounceMs}ms`);
  }

  /**
   * Stop file watching and clean up resources
   */
  async stop(): Promise<void> {
    if (!this.isStarted) {
      return;
    }

    this.logger.info("🛑 FileObserver: Stopping file system watching...");

    // Clear all debounce timers
    for (const timer of this.debounceTimers.values()) {
      clearTimeout(timer);
    }
    this.debounceTimers.clear();

    // Close all watchers
    for (const [path, watcher] of this.watchers.entries()) {
      try {
        watcher.close();
        this.logger.debug(`Closed watcher for: ${path}`);
      } catch (error) {
        this.logger.warn(`Failed to close watcher for ${path}:`, error);
      }
    }
    this.watchers.clear();

    this.isStarted = false;
    this.stats.watchersActive = 0;

    this.logger.info("✅ FileObserver stopped and resources cleaned up");
  }

  /**
   * Add a directory to watch
   */
  async watchDirectory(directoryPath: string, category?: string): Promise<void> {
    if (!this.isStarted) {
      throw new Error("FileObserver must be started before adding watchers");
    }

    if (this.watchers.has(directoryPath)) {
      this.logger.debug(`Directory already being watched: ${directoryPath}`);
      return;
    }

    try {
      // Verify directory exists
      const stats = await fs.promises.stat(directoryPath);
      if (!stats.isDirectory()) {
        throw new Error(`Path is not a directory: ${directoryPath}`);
      }

      const watcher = fs.watch(directoryPath, { recursive: this.config.recursive }, (eventType, filename) => {
        this.handleFileEvent(eventType, directoryPath, filename, category);
      });

      watcher.on('error', (error) => {
        this.handleWatcherError(directoryPath, error);
      });

      this.watchers.set(directoryPath, watcher);
      this.stats.watchersActive = this.watchers.size;

      this.logger.info(`👁️ FileObserver: Watching directory: ${directoryPath}${category ? ` (category: ${category})` : ''}`);

    } catch (error) {
      this.logger.error(`Failed to watch directory ${directoryPath}:`, error);
      if (this.retryCount < this.config.maxRetries) {
        this.retryCount++;
        this.stats.retryCount++;
        this.logger.info(`Retrying in ${this.config.retryDelayMs}ms (attempt ${this.retryCount}/${this.config.maxRetries})`);
        setTimeout(() => this.watchDirectory(directoryPath, category), this.config.retryDelayMs);
      } else {
        throw error;
      }
    }
  }

  /**
   * Remove a directory from watching
   */
  async unwatchDirectory(directoryPath: string): Promise<void> {
    const watcher = this.watchers.get(directoryPath);
    if (!watcher) {
      this.logger.debug(`Directory not being watched: ${directoryPath}`);
      return;
    }

    try {
      watcher.close();
      this.watchers.delete(directoryPath);
      this.stats.watchersActive = this.watchers.size;

      // Clear any pending debounce timers for this directory
      const timersToRemove: string[] = [];
      for (const [key, timer] of this.debounceTimers.entries()) {
        if (key.startsWith(directoryPath)) {
          clearTimeout(timer);
          timersToRemove.push(key);
        }
      }
      timersToRemove.forEach(key => this.debounceTimers.delete(key));

      this.logger.info(`🚫 FileObserver: Stopped watching directory: ${directoryPath}`);

    } catch (error) {
      this.logger.error(`Failed to stop watching directory ${directoryPath}:`, error);
      throw error;
    }
  }

  /**
   * Handle file system events
   */
  private handleFileEvent(eventType: string, directoryPath: string, filename: string | null, category?: string): void {
    if (!filename) {
      return;
    }

    const filePath = path.join(directoryPath, filename);
    this.stats.eventsDetected++;

    // Check if file should be ignored
    if (this.shouldIgnoreFile(filePath, filename)) {
      return;
    }

    // Determine file types
    const isPromptFile = this.isPromptFile(filename);
    const isConfigFile = this.isConfigFile(filename, filePath);

    // Skip if we're not watching this type
    if (!isPromptFile && !isConfigFile) {
      return;
    }

    if (!this.config.watchPromptFiles && isPromptFile) {
      return;
    }

    if (!this.config.watchConfigFiles && isConfigFile) {
      return;
    }

    const changeType = this.mapEventType(eventType);
    const event: FileChangeEvent = {
      type: changeType,
      filePath,
      filename,
      timestamp: Date.now(),
      isPromptFile,
      isConfigFile,
      category
    };

    // Add framework analysis if enabled
    if (this.config.frameworkIntegration?.enabled) {
      event.frameworkAnalysis = this.analyzeFrameworkImpact(event);
      if (event.frameworkAnalysis.requiresFrameworkUpdate) {
        this.stats.frameworkEvents++;
      }
    }

    this.logger.debug(`File event detected: ${changeType} ${filename} in ${directoryPath}`);

    // Apply debouncing
    this.debounceEvent(event);
  }

  /**
   * Apply debouncing to prevent excessive event firing
   */
  private debounceEvent(event: FileChangeEvent): void {
    const debounceKey = `${event.filePath}_${event.type}`;
    
    // Clear existing timer for this file+type
    const existingTimer = this.debounceTimers.get(debounceKey);
    if (existingTimer) {
      clearTimeout(existingTimer);
      this.stats.eventsDebounced++;
    }

    // Set new timer
    const timer = setTimeout(() => {
      this.debounceTimers.delete(debounceKey);
      this.emitFileChangeEvent(event);
    }, this.config.debounceMs);

    this.debounceTimers.set(debounceKey, timer);
  }

  /**
   * Emit the file change event
   */
  private emitFileChangeEvent(event: FileChangeEvent): void {
    this.stats.eventsTriggered++;
    this.stats.lastEventTime = event.timestamp;

    this.logger.info(`🔄 FileObserver: File ${event.type}: ${event.filename}`);
    
    // Emit specific event types
    this.emit('fileChange', event);
    this.emit(`file:${event.type}`, event);
    
    if (event.isPromptFile) {
      this.emit('promptFileChange', event);
    }
    
    if (event.isConfigFile) {
      this.emit('configFileChange', event);
    }
  }

  /**
   * Handle watcher errors
   */
  private handleWatcherError(directoryPath: string, error: Error): void {
    this.logger.error(`FileObserver: Watcher error for ${directoryPath}:`, error);
    
    // Remove failed watcher
    this.watchers.delete(directoryPath);
    this.stats.watchersActive = this.watchers.size;

    // Emit error event
    this.emit('watcherError', { directoryPath, error });

    // Attempt to restart watcher
    if (this.retryCount < this.config.maxRetries) {
      this.retryCount++;
      this.stats.retryCount++;
      setTimeout(() => {
        this.logger.info(`Attempting to restart watcher for: ${directoryPath}`);
        this.watchDirectory(directoryPath).catch(retryError => {
          this.logger.error(`Failed to restart watcher for ${directoryPath}:`, retryError);
        });
      }, this.config.retryDelayMs);
    }
  }

  /**
   * Check if file should be ignored
   */
  private shouldIgnoreFile(filePath: string, filename: string): boolean {
    const normalizedPath = path.normalize(filePath).replace(/\\/g, '/');
    
    return this.config.ignoredPatterns.some(pattern => {
      // Simple glob pattern matching
      const regexPattern = pattern
        .replace(/\*\*/g, '.*')
        .replace(/\*/g, '[^/]*')
        .replace(/\?/g, '[^/]');
      
      const regex = new RegExp(`^${regexPattern}$`);
      return regex.test(normalizedPath) || regex.test(filename);
    });
  }

  /**
   * Check if file is a prompt file
   */
  private isPromptFile(filename: string): boolean {
    const ext = path.extname(filename).toLowerCase();
    return ext === '.md' || ext === '.markdown';
  }

  /**
   * Check if file is a configuration file
   */
  private isConfigFile(filename: string, fullPath?: string): boolean {
    const basename = path.basename(filename);
    
    // Standard config files
    if (basename === 'prompts.json' || basename === 'config.json') {
      return true;
    }
    
    // Main prompts config - get filename from ConfigManager if available
    if (this.configManager && fullPath) {
      try {
        const mainConfigPath = this.configManager.getPromptsFilePath();
        const mainConfigFilename = path.basename(mainConfigPath);
        return basename === mainConfigFilename;
      } catch (error) {
        // Fallback to default behavior if ConfigManager fails
        this.logger.debug(`Could not get prompts config path from ConfigManager: ${error}`);
      }
    }
    
    // Fallback for backward compatibility
    return basename === 'promptsConfig.json';
  }

  /**
   * Map fs.watch event types to our event types
   */
  private mapEventType(eventType: string): FileChangeType {
    switch (eventType) {
      case 'rename':
        return 'renamed';
      case 'change':
        return 'modified';
      default:
        return 'modified';
    }
  }

  /**
   * Get current statistics
   */
  getStats(): FileObserverStats {
    return {
      ...this.stats,
      uptime: this.isStarted ? Date.now() - this.startTime : 0
    };
  }

  /**
   * Get current configuration
   */
  getConfig(): FileObserverConfig {
    return { ...this.config };
  }

  /**
   * Update configuration
   */
  updateConfig(newConfig: Partial<FileObserverConfig>): void {
    this.config = { ...this.config, ...newConfig };
    this.logger.info("FileObserver configuration updated");
  }

  /**
   * Get list of watched directories
   */
  getWatchedDirectories(): string[] {
    return Array.from(this.watchers.keys());
  }

  /**
   * Check if FileObserver is running
   */
  isRunning(): boolean {
    return this.isStarted;
  }

  /**
   * Analyze framework impact of file changes
   * Phase 1: Basic analysis without complex framework dependencies
   */
  private analyzeFrameworkImpact(event: FileChangeEvent): FrameworkAnalysisData {
    // Basic framework analysis for Phase 1 compatibility
    const requiresFrameworkUpdate = event.isPromptFile || event.isConfigFile;
    const affectedFrameworks = requiresFrameworkUpdate ? ['basic'] : [];
    const analysisInvalidated = event.isPromptFile && (event.type === 'modified' || event.type === 'added');
    const performanceImpact: 'low' | 'medium' | 'high' = event.isConfigFile ? 'high' : 'low';

    if (requiresFrameworkUpdate && this.config.frameworkIntegration?.cacheInvalidation) {
      this.stats.frameworkCacheInvalidations++;
      this.logger.debug(`Framework cache invalidation triggered by ${event.filename}`);
    }

    return {
      requiresFrameworkUpdate,
      affectedFrameworks,
      analysisInvalidated,
      performanceImpact
    };
  }

  /**
   * Enable framework integration
   */
  enableFrameworkIntegration(options: Partial<FrameworkIntegration> = {}): void {
    this.config.frameworkIntegration = {
      enabled: true,
      analyzeChanges: true,
      cacheInvalidation: true,
      performanceTracking: true,
      ...options
    };
    this.logger.info("Framework integration enabled for FileObserver");
  }

  /**
   * Disable framework integration
   */
  disableFrameworkIntegration(): void {
    this.config.frameworkIntegration = {
      enabled: false,
      analyzeChanges: false,
      cacheInvalidation: false,
      performanceTracking: false
    };
    this.logger.info("Framework integration disabled for FileObserver");
  }

  /**
   * Check if framework integration is enabled
   */
  isFrameworkIntegrationEnabled(): boolean {
    return this.config.frameworkIntegration?.enabled ?? false;
  }

  /**
   * Get debug information
   */
  getDebugInfo(): {
    isRunning: boolean;
    config: FileObserverConfig;
    stats: FileObserverStats;
    watchedDirectories: string[];
    activeDebounceTimers: number;
    frameworkIntegration: FrameworkIntegration | undefined;
  } {
    return {
      isRunning: this.isRunning(),
      config: this.getConfig(),
      stats: this.getStats(),
      watchedDirectories: this.getWatchedDirectories(),
      activeDebounceTimers: this.debounceTimers.size,
      frameworkIntegration: this.config.frameworkIntegration
    };
  }
}

/**
 * Factory function to create a FileObserver instance
 */
export function createFileObserver(logger: Logger, config?: Partial<FileObserverConfig>, configManager?: ConfigManager): FileObserver {
  return new FileObserver(logger, config, configManager);
}
```

--------------------------------------------------------------------------------
/server/src/prompts/hot-reload-manager.ts:
--------------------------------------------------------------------------------

```typescript
/**
 * Hot Reload Manager Module
 * Orchestrates file system monitoring and reload workflows with event-driven architecture
 */

import { Logger } from "../logging/index.js";
import { FileObserver, FileChangeEvent, FileObserverConfig, createFileObserver } from "./file-observer.js";
import { CategoryManager } from "./category-manager.js";
import { ConfigManager } from "../config/index.js";
import path from "path";
import * as fs from "fs/promises";

/**
 * Hot reload event types
 */
export type HotReloadEventType = 'prompt_changed' | 'config_changed' | 'category_changed' | 'reload_required';

/**
 * Hot reload event data
 */
export interface HotReloadEvent {
  type: HotReloadEventType;
  reason: string;
  affectedFiles: string[];
  category?: string;
  timestamp: number;
  requiresFullReload: boolean;
}

/**
 * Framework-aware hot reload capabilities
 */
export interface FrameworkHotReloadCapabilities {
  enabled: boolean;
  frameworkAnalysis: boolean;
  performanceMonitoring: boolean;
  preWarmAnalysis: boolean;
  invalidateFrameworkCaches: boolean;
}

/**
 * Hot reload configuration
 */
export interface HotReloadConfig extends Partial<FileObserverConfig> {
  enabled: boolean;
  autoReload: boolean;
  reloadDelayMs: number;
  batchChanges: boolean;
  batchTimeoutMs: number;
  frameworkCapabilities?: FrameworkHotReloadCapabilities;
}

/**
 * Hot reload statistics
 */
export interface HotReloadStats {
  reloadsTriggered: number;
  filesChanged: number;
  lastReloadTime?: number;
  autoReloadsEnabled: boolean;
  fileObserverStats: ReturnType<FileObserver['getStats']>;
  frameworkReloads: number;
  frameworkCacheClears: number;
  performanceOptimizations: number;
}

/**
 * Hot reload manager configuration
 */
const DEFAULT_HOT_RELOAD_CONFIG: HotReloadConfig = {
  enabled: true,
  autoReload: true,
  reloadDelayMs: 1000,
  batchChanges: true,
  batchTimeoutMs: 2000,
  debounceMs: 500,
  watchPromptFiles: true,
  watchConfigFiles: true,
  recursive: true,
  ignoredPatterns: [
    '**/.git/**',
    '**/node_modules/**',
    '**/.DS_Store',
    '**/Thumbs.db',
    '**/*.tmp',
    '**/*.temp',
    '**/dist/**',
    '**/*.log'
  ],
  maxRetries: 3,
  retryDelayMs: 1000,
  frameworkCapabilities: {
    enabled: false,
    frameworkAnalysis: false,
    performanceMonitoring: false,
    preWarmAnalysis: false,
    invalidateFrameworkCaches: false
  }
};

/**
 * HotReloadManager class
 * Coordinates file watching and reload operations
 */
export class HotReloadManager {
  protected logger: Logger;
  private config: HotReloadConfig;
  private fileObserver: FileObserver;
  private categoryManager?: CategoryManager;
  private onReloadCallback?: (event: HotReloadEvent) => Promise<void>;
  private stats: HotReloadStats;
  private isStarted: boolean = false;
  private batchTimer?: NodeJS.Timeout;
  private pendingChanges: FileChangeEvent[] = [];
  private watchedDirectories: Set<string> = new Set();

  constructor(
    logger: Logger, 
    categoryManager?: CategoryManager,
    config?: Partial<HotReloadConfig>,
    configManager?: ConfigManager
  ) {
    this.logger = logger;
    this.categoryManager = categoryManager;
    this.config = { ...DEFAULT_HOT_RELOAD_CONFIG, ...config };
    
    // Create file observer with filtered config
    const observerConfig = {
      enabled: this.config.enabled,
      debounceMs: this.config.debounceMs,
      watchPromptFiles: this.config.watchPromptFiles,
      watchConfigFiles: this.config.watchConfigFiles,
      recursive: this.config.recursive,
      ignoredPatterns: this.config.ignoredPatterns,
      maxRetries: this.config.maxRetries,
      retryDelayMs: this.config.retryDelayMs
    };
    
    this.fileObserver = createFileObserver(logger, observerConfig, configManager);
    
    this.stats = {
      reloadsTriggered: 0,
      filesChanged: 0,
      autoReloadsEnabled: this.config.autoReload,
      fileObserverStats: this.fileObserver.getStats(),
      frameworkReloads: 0,
      frameworkCacheClears: 0,
      performanceOptimizations: 0
    };

    this.setupFileObserverEventHandlers();
  }

  /**
   * Start hot reload monitoring
   */
  async start(): Promise<void> {
    if (this.isStarted) {
      this.logger.warn("HotReloadManager is already started");
      return;
    }

    if (!this.config.enabled) {
      this.logger.info("HotReloadManager is disabled in configuration");
      return;
    }

    this.logger.info("🔥 HotReloadManager: Starting hot reload monitoring...");

    await this.fileObserver.start();
    this.isStarted = true;

    this.logger.info(`✅ HotReloadManager started - Auto reload: ${this.config.autoReload ? 'ON' : 'OFF'}`);
  }

  /**
   * Stop hot reload monitoring
   */
  async stop(): Promise<void> {
    if (!this.isStarted) {
      return;
    }

    this.logger.info("🛑 HotReloadManager: Stopping hot reload monitoring...");

    // Clear batch timer
    if (this.batchTimer) {
      clearTimeout(this.batchTimer);
      this.batchTimer = undefined;
    }

    await this.fileObserver.stop();
    this.isStarted = false;

    this.logger.info("✅ HotReloadManager stopped");
  }

  /**
   * Set the callback for reload events
   */
  setReloadCallback(callback: (event: HotReloadEvent) => Promise<void>): void {
    this.onReloadCallback = callback;
    this.logger.debug("HotReloadManager: Reload callback registered");
  }

  /**
   * Add directories to watch
   */
  async watchDirectories(directories: Array<{ path: string; category?: string }>): Promise<void> {
    if (!this.isStarted) {
      throw new Error("HotReloadManager must be started before watching directories");
    }

    for (const { path: dirPath, category } of directories) {
      try {
        await this.fileObserver.watchDirectory(dirPath, category);
        this.watchedDirectories.add(dirPath);
        this.logger.info(`📁 HotReloadManager: Watching directory: ${dirPath}${category ? ` (${category})` : ''}`);
      } catch (error) {
        this.logger.error(`Failed to watch directory ${dirPath}:`, error);
      }
    }
  }

  /**
   * Manually trigger a reload
   */
  async triggerReload(reason: string = 'Manual trigger', requiresFullReload: boolean = true): Promise<void> {
    const event: HotReloadEvent = {
      type: 'reload_required',
      reason,
      affectedFiles: [],
      timestamp: Date.now(),
      requiresFullReload
    };

    await this.processReloadEvent(event);
  }

  /**
   * Setup file observer event handlers
   */
  private setupFileObserverEventHandlers(): void {
    this.fileObserver.on('fileChange', (event: FileChangeEvent) => {
      this.handleFileChange(event);
    });

    this.fileObserver.on('watcherError', (error: { directoryPath: string; error: Error }) => {
      this.logger.error(`File watcher error for ${error.directoryPath}:`, error.error);
    });

    this.logger.debug("HotReloadManager: File observer event handlers registered");
  }

  /**
   * Handle file change events
   */
  private handleFileChange(event: FileChangeEvent): void {
    this.stats.filesChanged++;
    this.logger.debug(`File change detected: ${event.type} - ${event.filename}`);

    if (this.config.batchChanges) {
      this.batchFileChange(event);
    } else {
      this.processFileChangeImmediate(event);
    }
  }

  /**
   * Batch file changes to prevent excessive reloads
   */
  private batchFileChange(event: FileChangeEvent): void {
    this.pendingChanges.push(event);

    // Clear existing timer
    if (this.batchTimer) {
      clearTimeout(this.batchTimer);
    }

    // Set new timer
    this.batchTimer = setTimeout(() => {
      this.processBatchedChanges();
    }, this.config.batchTimeoutMs);
  }

  /**
   * Process batched file changes
   */
  private async processBatchedChanges(): Promise<void> {
    if (this.pendingChanges.length === 0) {
      return;
    }

    const changes = [...this.pendingChanges];
    this.pendingChanges = [];
    this.batchTimer = undefined;

    this.logger.info(`Processing ${changes.length} batched file changes`);

    // Group changes by type
    const promptChanges = changes.filter(c => c.isPromptFile);
    const configChanges = changes.filter(c => c.isConfigFile);

    // Determine reload type
    const requiresFullReload = configChanges.length > 0 || 
      promptChanges.some(c => c.type === 'added' || c.type === 'removed');

    let reloadType: HotReloadEventType = 'prompt_changed';
    let reason = `${promptChanges.length} prompt file(s) changed`;

    if (configChanges.length > 0) {
      reloadType = 'config_changed';
      reason = `${configChanges.length} config file(s) changed`;
    }

    const hotReloadEvent: HotReloadEvent = {
      type: reloadType,
      reason,
      affectedFiles: changes.map(c => c.filePath),
      timestamp: Date.now(),
      requiresFullReload
    };

    await this.processReloadEvent(hotReloadEvent);
  }

  /**
   * Process immediate file change (no batching)
   */
  private async processFileChangeImmediate(event: FileChangeEvent): Promise<void> {
    let reloadType: HotReloadEventType = 'prompt_changed';
    let requiresFullReload = false;

    if (event.isConfigFile) {
      reloadType = 'config_changed';
      requiresFullReload = true;
    } else if (event.type === 'added' || event.type === 'removed') {
      requiresFullReload = true;
    }

    const hotReloadEvent: HotReloadEvent = {
      type: reloadType,
      reason: `File ${event.type}: ${event.filename}`,
      affectedFiles: [event.filePath],
      category: event.category,
      timestamp: event.timestamp,
      requiresFullReload
    };

    await this.processReloadEvent(hotReloadEvent);
  }

  /**
   * Process reload event with framework integration
   */
  protected async processReloadEvent(event: HotReloadEvent): Promise<void> {
    this.stats.reloadsTriggered++;
    this.stats.lastReloadTime = event.timestamp;

    this.logger.info(`🔄 Hot reload triggered: ${event.reason}`);

    // Framework-aware pre-processing
    if (this.config.frameworkCapabilities?.enabled) {
      await this.processFrameworkPreReload(event);
    }

    if (this.config.autoReload && this.onReloadCallback) {
      try {
        // Add delay if configured
        if (this.config.reloadDelayMs > 0) {
          this.logger.debug(`Delaying reload by ${this.config.reloadDelayMs}ms`);
          await new Promise(resolve => setTimeout(resolve, this.config.reloadDelayMs));
        }

        await this.onReloadCallback(event);
        
        // Framework-aware post-processing
        if (this.config.frameworkCapabilities?.enabled) {
          await this.processFrameworkPostReload(event);
        }

        this.logger.info("✅ Hot reload completed successfully");

      } catch (error) {
        this.logger.error("❌ Hot reload failed:", error);
      }
    } else {
      this.logger.info("⏭️ Auto reload is disabled - skipping automatic reload");
    }
  }

  /**
   * Get current statistics
   */
  getStats(): HotReloadStats {
    return {
      ...this.stats,
      fileObserverStats: this.fileObserver.getStats()
    };
  }

  /**
   * Get current configuration
   */
  getConfig(): HotReloadConfig {
    return { ...this.config };
  }

  /**
   * Update configuration
   */
  updateConfig(newConfig: Partial<HotReloadConfig>): void {
    const oldAutoReload = this.config.autoReload;
    this.config = { ...this.config, ...newConfig };
    
    // Update file observer config if needed
    if (newConfig.debounceMs !== undefined || 
        newConfig.watchPromptFiles !== undefined || 
        newConfig.watchConfigFiles !== undefined) {
      this.fileObserver.updateConfig({
        debounceMs: this.config.debounceMs,
        watchPromptFiles: this.config.watchPromptFiles,
        watchConfigFiles: this.config.watchConfigFiles
      });
    }

    if (oldAutoReload !== this.config.autoReload) {
      this.stats.autoReloadsEnabled = this.config.autoReload;
      this.logger.info(`Auto reload ${this.config.autoReload ? 'enabled' : 'disabled'}`);
    }

    this.logger.info("HotReloadManager configuration updated");
  }

  /**
   * Check if hot reload manager is running
   */
  isRunning(): boolean {
    return this.isStarted;
  }

  /**
   * Get watched directories
   */
  getWatchedDirectories(): string[] {
    return Array.from(this.watchedDirectories);
  }

  /**
   * Framework pre-reload processing
   * Phase 1: Basic framework cache invalidation and analysis
   */
  private async processFrameworkPreReload(event: HotReloadEvent): Promise<void> {
    const startTime = performance.now();
    
    this.logger.debug("Processing framework pre-reload analysis...");
    
    if (this.config.frameworkCapabilities?.invalidateFrameworkCaches) {
      this.stats.frameworkCacheClears++;
      this.logger.debug("Framework caches invalidated for hot-reload");
    }
    
    if (this.config.frameworkCapabilities?.frameworkAnalysis) {
      this.stats.frameworkReloads++;
      this.logger.debug(`Framework analysis prepared for ${event.affectedFiles.length} files`);
    }
    
    const processingTime = performance.now() - startTime;
    this.logger.debug(`Framework pre-reload completed in ${processingTime.toFixed(2)}ms`);
  }

  /**
   * Framework post-reload processing
   * Phase 1: Basic performance optimization and cache warming
   */
  private async processFrameworkPostReload(event: HotReloadEvent): Promise<void> {
    const startTime = performance.now();
    
    this.logger.debug("Processing framework post-reload optimizations...");
    
    if (this.config.frameworkCapabilities?.preWarmAnalysis) {
      this.stats.performanceOptimizations++;
      this.logger.debug("Framework analysis cache pre-warmed");
    }
    
    if (this.config.frameworkCapabilities?.performanceMonitoring) {
      const processingTime = performance.now() - startTime;
      this.logger.debug(`Framework post-reload monitoring: ${processingTime.toFixed(2)}ms`);
    }
  }

  /**
   * Enable framework capabilities
   */
  enableFrameworkCapabilities(options: Partial<FrameworkHotReloadCapabilities> = {}): void {
    this.config.frameworkCapabilities = {
      enabled: true,
      frameworkAnalysis: true,
      performanceMonitoring: true,
      preWarmAnalysis: true,
      invalidateFrameworkCaches: true,
      ...options
    };
    
    // Enable framework integration on file observer if available
    if ('enableFrameworkIntegration' in this.fileObserver) {
      (this.fileObserver as any).enableFrameworkIntegration({
        enabled: true,
        analyzeChanges: this.config.frameworkCapabilities.frameworkAnalysis,
        cacheInvalidation: this.config.frameworkCapabilities.invalidateFrameworkCaches,
        performanceTracking: this.config.frameworkCapabilities.performanceMonitoring
      });
    }
    
    this.logger.info("Framework capabilities enabled for HotReloadManager");
  }

  /**
   * Disable framework capabilities
   */
  disableFrameworkCapabilities(): void {
    this.config.frameworkCapabilities = {
      enabled: false,
      frameworkAnalysis: false,
      performanceMonitoring: false,
      preWarmAnalysis: false,
      invalidateFrameworkCaches: false
    };
    
    // Disable framework integration on file observer if available
    if ('disableFrameworkIntegration' in this.fileObserver) {
      (this.fileObserver as any).disableFrameworkIntegration();
    }
    
    this.logger.info("Framework capabilities disabled for HotReloadManager");
  }

  /**
   * Check if framework capabilities are enabled
   */
  isFrameworkCapabilitiesEnabled(): boolean {
    return this.config.frameworkCapabilities?.enabled ?? false;
  }

  /**
   * Get debug information
   */
  getDebugInfo(): {
    isRunning: boolean;
    config: HotReloadConfig;
    stats: HotReloadStats;
    watchedDirectories: string[];
    pendingChanges: number;
    fileObserverDebug: ReturnType<FileObserver['getDebugInfo']>;
    frameworkCapabilities: FrameworkHotReloadCapabilities | undefined;
  } {
    return {
      isRunning: this.isRunning(),
      config: this.getConfig(),
      stats: this.getStats(),
      watchedDirectories: this.getWatchedDirectories(),
      pendingChanges: this.pendingChanges.length,
      fileObserverDebug: this.fileObserver.getDebugInfo(),
      frameworkCapabilities: this.config.frameworkCapabilities
    };
  }
}

/**
 * Factory function to create a HotReloadManager instance
 */
export function createHotReloadManager(
  logger: Logger, 
  categoryManager?: CategoryManager,
  config?: Partial<HotReloadConfig>,
  configManager?: ConfigManager
): HotReloadManager {
  return new HotReloadManager(logger, categoryManager, config, configManager);
}
```

--------------------------------------------------------------------------------
/server/src/prompts/registry.ts:
--------------------------------------------------------------------------------

```typescript
/**
 * Prompt Registry Module
 * Handles registering prompts with MCP server using proper MCP protocol and managing conversation history
 */

import { z } from "zod";
import { ConfigManager } from "../config/index.js";
import { Logger } from "../logging/index.js";
import {
  ConversationHistoryItem,
  ConvertedPrompt,
} from "../types/index.js";
import { isChainPrompt } from "../utils/chainUtils.js";
// TemplateProcessor functionality consolidated into UnifiedPromptProcessor

/**
 * Prompt Registry class
 */
export class PromptRegistry {
  private logger: Logger;
  private mcpServer: any;
  private configManager: ConfigManager;
  // templateProcessor removed - functionality consolidated into UnifiedPromptProcessor
  private conversationHistory: ConversationHistoryItem[] = [];
  private readonly MAX_HISTORY_SIZE = 100;
  private registeredPromptNames = new Set<string>(); // Track registered prompts to prevent duplicates

  /**
   * Direct template processing method (minimal implementation)
   * Replaces templateProcessor calls for basic template processing
   */
  private async processTemplateDirect(
    template: string,
    args: Record<string, string>,
    specialContext: Record<string, string> = {},
    toolsEnabled: boolean = false
  ): Promise<string> {
    // Import jsonUtils for basic template processing
    const { processTemplate } = await import("../utils/jsonUtils.js");
    const { getAvailableTools } = await import("../utils/index.js");
    
    const enhancedSpecialContext = { ...specialContext };
    if (toolsEnabled) {
      enhancedSpecialContext["tools_available"] = getAvailableTools();
    }
    
    return processTemplate(template, args, enhancedSpecialContext);
  }

  constructor(
    logger: Logger,
    mcpServer: any,
    configManager: ConfigManager
  ) {
    this.logger = logger;
    this.mcpServer = mcpServer;
    this.configManager = configManager;
    // templateProcessor removed - functionality consolidated into UnifiedPromptProcessor
  }

  /**
   * Register individual prompts using MCP SDK registerPrompt API
   * This implements the standard MCP prompts protocol using the high-level API
   */
  private registerIndividualPrompts(prompts: ConvertedPrompt[]): void {
    try {
      this.logger.info('Registering individual prompts with MCP SDK...');
      let registeredCount = 0;

      for (const prompt of prompts) {
        // Skip if already registered (deduplication guard)
        if (this.registeredPromptNames.has(prompt.name)) {
          this.logger.debug(`Skipping already registered prompt: ${prompt.name}`);
          continue;
        }

        // Create argument schema
        const argsSchema: Record<string, any> = {};
        for (const arg of prompt.arguments) {
          argsSchema[arg.name] = z
            .string()
            .optional()
            .describe(arg.description || `Argument: ${arg.name}`);
        }

        // Register the prompt using the correct MCP SDK API with error recovery
        try {
          this.mcpServer.registerPrompt(
            prompt.name,
            {
              title: prompt.name,
              description: prompt.description || `Prompt: ${prompt.name}`,
              argsSchema
            },
            async (args: any) => {
              this.logger.debug(`Executing prompt '${prompt.name}' with args:`, args);
              return await this.executePromptLogic(prompt, args || {});
            }
          );

          // Track the registered prompt
          this.registeredPromptNames.add(prompt.name);
          registeredCount++;
          this.logger.debug(`Registered prompt: ${prompt.name}`);
        } catch (error: any) {
          if (error.message && error.message.includes('already registered')) {
            // Handle MCP SDK's "already registered" error gracefully
            this.logger.warn(`Prompt '${prompt.name}' already registered in MCP SDK, skipping re-registration`);
            this.registeredPromptNames.add(prompt.name); // Track it anyway
            continue;
          } else {
            // Re-throw other errors
            this.logger.error(`Failed to register prompt '${prompt.name}':`, error.message || error);
            throw error;
          }
        }
      }

      this.logger.info(`Successfully registered ${registeredCount} of ${prompts.length} prompts with MCP SDK`);
    } catch (error) {
      this.logger.error('Error registering individual prompts:', error instanceof Error ? error.message : String(error));
      throw error;
    }
  }

  /**
   * Execute prompt logic (extracted from createPromptHandler for MCP protocol)
   */
  private async executePromptLogic(promptData: ConvertedPrompt, args: any): Promise<any> {
    try {
      this.logger.info(`Executing prompt '${promptData.name}'...`);

      // Check if arguments are effectively empty
      const effectivelyEmptyArgs = this.areArgumentsEffectivelyEmpty(
        promptData.arguments,
        args
      );

      if (
        effectivelyEmptyArgs &&
        promptData.onEmptyInvocation === "return_template"
      ) {
        this.logger.info(
          `Prompt '${promptData.name}' invoked without arguments and onEmptyInvocation is 'return_template'. Returning template info.`
        );

        let responseText = `Prompt: '${promptData.name}'\n`;
        responseText += `Description: ${promptData.description}\n`;

        if (promptData.arguments && promptData.arguments.length > 0) {
          responseText += `This prompt requires the following arguments:\n`;
          promptData.arguments.forEach((arg) => {
            responseText += `  - ${arg.name}${
              arg.required ? " (required)" : " (optional)"
            }: ${arg.description || "No description"}\n`;
          });
          responseText += `\nExample usage: >>${
            promptData.id || promptData.name
          } ${promptData.arguments
            .map((arg) => `${arg.name}=\"value\"`)
            .join(" ")}`;
        } else {
          responseText += "This prompt does not require any arguments.\n";
        }

        return {
          messages: [
            {
              role: "assistant" as const,
              content: { type: "text" as const, text: responseText },
            },
          ],
        };
      }

      // Check if this is a chain prompt
      if (
        isChainPrompt(promptData) &&
        promptData.chainSteps &&
        promptData.chainSteps.length > 0
      ) {
        this.logger.info(
          `Prompt '${promptData.name}' is a chain with ${promptData.chainSteps.length} steps. NOT automatically executing the chain.`
        );
        // Note: Chain execution is handled elsewhere
      }

      // Create messages array with only user and assistant roles
      const messages: {
        role: "user" | "assistant";
        content: { type: "text"; text: string };
      }[] = [];

      // Create user message with placeholders replaced
      let userMessageText = promptData.userMessageTemplate;

      // If there's a system message, prepend it to the user message
      if (promptData.systemMessage) {
        userMessageText = `[System Info: ${promptData.systemMessage}]\n\n${userMessageText}`;
      }

      // Process the template with special context
      // Using direct processing since TemplateProcessor was consolidated
      userMessageText = await this.processTemplateDirect(
        userMessageText,
        args,
        { previous_message: this.getPreviousMessage() },
        promptData.tools || false
      );

      // Store in conversation history for future reference
      this.addToConversationHistory({
        role: "user",
        content: userMessageText,
        timestamp: Date.now(),
        isProcessedTemplate: true, // Mark as a processed template
      });

      // Push the user message to the messages array
      messages.push({
        role: "user",
        content: {
          type: "text",
          text: userMessageText,
        },
      });

      this.logger.debug(
        `Processed messages for prompt '${promptData.name}':`,
        messages
      );
      return { messages };
    } catch (error) {
      this.logger.error(
        `Error executing prompt '${promptData.name}':`,
        error
      );
      throw error; // Re-throw to let the MCP framework handle it
    }
  }

  /**
   * Register all prompts with the MCP server using proper MCP protocol
   */
  async registerAllPrompts(prompts: ConvertedPrompt[]): Promise<number> {
    try {
      this.logger.info(
        `Registering ${prompts.length} prompts with MCP SDK registerPrompt API...`
      );

      // Register individual prompts using the correct MCP SDK API
      this.registerIndividualPrompts(prompts);

      this.logger.info(
        `Successfully registered ${prompts.length} prompts with MCP SDK`
      );
      return prompts.length;
    } catch (error) {
      this.logger.error(`Error registering prompts:`, error);
      throw error;
    }
  }


  /**
   * Send list_changed notification to clients (for hot-reload)
   * This is the proper MCP way to notify clients about prompt updates
   */
  async notifyPromptsListChanged(): Promise<void> {
    try {
      // Send MCP notification that prompt list has changed
      if (this.mcpServer && typeof this.mcpServer.notification === 'function') {
        this.mcpServer.notification({
          method: "notifications/prompts/list_changed"
        });
        this.logger.info("✅ Sent prompts/list_changed notification to clients");
      } else {
        this.logger.debug("MCP server doesn't support notifications");
      }
    } catch (error) {
      this.logger.warn("Could not send prompts/list_changed notification:", error);
    }
  }

  // Note: MCP SDK doesn't provide prompt unregistration
  // Hot-reload is handled through list_changed notifications to clients

  /**
   * Helper function to determine if provided arguments are effectively empty
   * for the given prompt definition.
   */
  private areArgumentsEffectivelyEmpty(
    promptArgs: Array<{ name: string }>,
    providedArgs: any
  ): boolean {
    if (
      !providedArgs ||
      typeof providedArgs !== "object" ||
      Object.keys(providedArgs).length === 0
    ) {
      return true; // No arguments provided at all
    }
    // Check if any of the defined arguments for the prompt have a meaningful value
    for (const definedArg of promptArgs) {
      const value = providedArgs[definedArg.name];
      if (
        value !== undefined &&
        value !== null &&
        String(value).trim() !== ""
      ) {
        return false; // Found at least one provided argument with a value
      }
    }
    return true; // All defined arguments are missing or have empty values
  }



  /**
   * Add item to conversation history with size management
   */
  addToConversationHistory(item: ConversationHistoryItem): void {
    this.conversationHistory.push(item);

    // Trim history if it exceeds maximum size
    if (this.conversationHistory.length > this.MAX_HISTORY_SIZE) {
      // Remove oldest entries, keeping recent ones
      this.conversationHistory.splice(
        0,
        this.conversationHistory.length - this.MAX_HISTORY_SIZE
      );
      this.logger.debug(
        `Trimmed conversation history to ${this.MAX_HISTORY_SIZE} entries to prevent memory leaks`
      );
    }
  }

  /**
   * Get the previous message from conversation history
   */
  getPreviousMessage(): string {
    // Try to find the last user message in conversation history
    if (this.conversationHistory.length > 0) {
      // Start from the end and find the first non-template user message
      for (let i = this.conversationHistory.length - 1; i >= 0; i--) {
        const historyItem = this.conversationHistory[i];
        // Only consider user messages that aren't processed templates
        if (historyItem.role === "user" && !historyItem.isProcessedTemplate) {
          this.logger.debug(
            `Found previous user message for context: ${historyItem.content.substring(
              0,
              50
            )}...`
          );
          return historyItem.content;
        }
      }
    }

    // Return a default prompt if no suitable history item is found
    return "[Please check previous messages in the conversation for context]";
  }

  /**
   * Get conversation history
   */
  getConversationHistory(): ConversationHistoryItem[] {
    return [...this.conversationHistory];
  }

  /**
   * Clear conversation history
   */
  clearConversationHistory(): void {
    this.conversationHistory = [];
    this.logger.info("Conversation history cleared");
  }

  /**
   * Get conversation history statistics
   */
  getConversationStats(): {
    totalMessages: number;
    userMessages: number;
    assistantMessages: number;
    processedTemplates: number;
    oldestMessage?: number;
    newestMessage?: number;
  } {
    const userMessages = this.conversationHistory.filter(
      (item) => item.role === "user"
    ).length;
    const assistantMessages = this.conversationHistory.filter(
      (item) => item.role === "assistant"
    ).length;
    const processedTemplates = this.conversationHistory.filter(
      (item) => item.isProcessedTemplate
    ).length;

    const timestamps = this.conversationHistory.map((item) => item.timestamp);
    const oldestMessage =
      timestamps.length > 0 ? Math.min(...timestamps) : undefined;
    const newestMessage =
      timestamps.length > 0 ? Math.max(...timestamps) : undefined;

    return {
      totalMessages: this.conversationHistory.length,
      userMessages,
      assistantMessages,
      processedTemplates,
      oldestMessage,
      newestMessage,
    };
  }

  /**
   * Execute a prompt directly (for testing or internal use)
   */
  async executePromptDirectly(
    promptId: string,
    args: Record<string, string>,
    prompts: ConvertedPrompt[]
  ): Promise<string> {
    try {
      const convertedPrompt = prompts.find((cp) => cp.id === promptId);
      if (!convertedPrompt) {
        throw new Error(`Could not find prompt with ID: ${promptId}`);
      }

      this.logger.debug(
        `Running prompt directly: ${promptId} with arguments:`,
        args
      );

      // Check for missing arguments but treat all as optional
      const missingArgs = convertedPrompt.arguments
        .filter((arg) => !args[arg.name])
        .map((arg) => arg.name);

      if (missingArgs.length > 0) {
        this.logger.info(
          `Missing arguments for '${promptId}': ${missingArgs.join(
            ", "
          )}. Will attempt to use conversation context.`
        );

        // Use previous_message for all missing arguments
        missingArgs.forEach((argName) => {
          args[argName] = `{{previous_message}}`;
        });
      }

      // Process template with context
      // Using direct processing since TemplateProcessor was consolidated
      const userMessageText = await this.processTemplateDirect(
        convertedPrompt.userMessageTemplate,
        args,
        { previous_message: this.getPreviousMessage() },
        convertedPrompt.tools || false
      );

      // Add the message to conversation history
      this.addToConversationHistory({
        role: "user",
        content: userMessageText,
        timestamp: Date.now(),
        isProcessedTemplate: true,
      });

      // Generate a response (echo in this MCP implementation)
      const response = `Processed prompt: ${promptId}\nWith message: ${userMessageText}`;

      // Store the response in conversation history
      this.addToConversationHistory({
        role: "assistant",
        content: response,
        timestamp: Date.now(),
      });

      return response;
    } catch (error) {
      this.logger.error(`Error executing prompt '${promptId}':`, error);
      throw error;
    }
  }

  /**
   * Get registration statistics
   */
  getRegistrationStats(prompts: ConvertedPrompt[]): {
    totalPrompts: number;
    chainPrompts: number;
    regularPrompts: number;
    toolEnabledPrompts: number;
    categoriesCount: number;
    averageArgumentsPerPrompt: number;
  } {
    const chainPrompts = prompts.filter((p) => isChainPrompt(p)).length;
    const toolEnabledPrompts = prompts.filter((p) => p.tools).length;
    const categoriesSet = new Set(prompts.map((p) => p.category));
    const totalArguments = prompts.reduce(
      (sum, p) => sum + p.arguments.length,
      0
    );

    return {
      totalPrompts: prompts.length,
      chainPrompts,
      regularPrompts: prompts.length - chainPrompts,
      toolEnabledPrompts,
      categoriesCount: categoriesSet.size,
      averageArgumentsPerPrompt:
        prompts.length > 0 ? totalArguments / prompts.length : 0,
    };
  }
}

```

--------------------------------------------------------------------------------
/server/src/mcp-tools/prompt-engine/utils/category-extractor.ts:
--------------------------------------------------------------------------------

```typescript
/**
 * Category Extraction Utility
 *
 * Implements intelligent category detection from multiple sources:
 * 1. Prompt metadata (PromptData.category)
 * 2. File path structure (/prompts/analysis/ -> analysis)
 * 3. Pattern-based detection (fallback)
 *
 * Part of Gate System Intelligent Selection Upgrade - Phase 1
 */

import type { Logger } from '../../../logging/index.js';
import path from 'path';

/**
 * Template gate configuration
 */
export interface GateConfigurationInfo {
  include?: string[];
  exclude?: string[];
  framework_gates?: boolean;
}

/**
 * Extracted category and gate information with source tracking
 */
export interface CategoryExtractionResult {
  /** The determined category */
  category: string;
  /** Source of the category determination */
  source: 'metadata' | 'path' | 'pattern' | 'fallback';
  /** Confidence level (0-100) */
  confidence: number;
  /** Template-level gate configuration */
  gateConfiguration?: GateConfigurationInfo;
  /** Original data used for extraction */
  sourceData?: {
    metadata?: string;
    filePath?: string;
    promptId?: string;
  };
}

/**
 * Category extractor with intelligent detection
 */
export class CategoryExtractor {
  private logger: Logger;

  constructor(logger: Logger) {
    this.logger = logger;
  }

  /**
   * Extract category from prompt using multiple detection strategies
   *
   * Priority order:
   * 1. Prompt metadata category (highest confidence)
   * 2. File path structure parsing
   * 3. Prompt ID pattern matching
   * 4. Default fallback
   */
  extractCategory(prompt: any): CategoryExtractionResult {
    this.logger.debug('[CATEGORY EXTRACTOR] Extracting category from prompt:', {
      promptId: prompt?.id,
      promptCategory: prompt?.category,
      promptFile: prompt?.file,
      hasGateConfiguration: !!prompt?.gateConfiguration
    });

    // Strategy 1: Use prompt metadata category (highest priority)
    if (prompt?.category && typeof prompt.category === 'string') {
      const metadataCategory = prompt.category.toLowerCase().trim();
      if (this.isValidCategory(metadataCategory)) {
        return {
          category: metadataCategory,
          source: 'metadata',
          confidence: 95,
          gateConfiguration: prompt.gateConfiguration,
          sourceData: {
            metadata: prompt.category,
            filePath: prompt.file,
            promptId: prompt.id
          }
        };
      }
    }

    // Strategy 2: Extract from file path structure
    if (prompt?.file && typeof prompt.file === 'string') {
      const pathCategory = this.extractCategoryFromPath(prompt.file);
      if (pathCategory) {
        return {
          category: pathCategory,
          source: 'path',
          confidence: 85,
          gateConfiguration: prompt.gateConfiguration,
          sourceData: {
            filePath: prompt.file,
            promptId: prompt.id
          }
        };
      }
    }

    // Strategy 3: Pattern-based detection from prompt ID
    if (prompt?.id && typeof prompt.id === 'string') {
      const patternCategory = this.extractCategoryFromPattern(prompt.id);
      if (patternCategory) {
        return {
          category: patternCategory,
          source: 'pattern',
          confidence: 60,
          gateConfiguration: prompt.gateConfiguration,
          sourceData: {
            promptId: prompt.id,
            filePath: prompt.file
          }
        };
      }
    }

    // Strategy 4: Default fallback
    this.logger.debug('[CATEGORY EXTRACTOR] No category detected, using fallback');
    return {
      category: 'general',
      source: 'fallback',
      confidence: 30,
      gateConfiguration: prompt?.gateConfiguration,
      sourceData: {
        promptId: prompt?.id,
        filePath: prompt?.file
      }
    };
  }

  /**
   * Extract category from file path structure
   * Examples:
   * - "/prompts/analysis/notes.md" -> "analysis"
   * - "/prompts/education/learning.md" -> "education"
   * - "analysis/query_refinement.md" -> "analysis"
   */
  private extractCategoryFromPath(filePath: string): string | null {
    try {
      // Normalize path separators
      const normalizedPath = filePath.replace(/\\/g, '/');

      // Split path and look for category indicators
      const pathSegments = normalizedPath.split('/').filter(segment => segment.length > 0);

      // Look for prompts directory structure: /prompts/{category}/
      const promptsIndex = pathSegments.findIndex(segment => segment === 'prompts');
      if (promptsIndex !== -1 && promptsIndex + 1 < pathSegments.length) {
        const categoryCandidate = pathSegments[promptsIndex + 1];
        if (this.isValidCategory(categoryCandidate)) {
          return categoryCandidate;
        }
      }

      // Look for direct category directory structure: {category}/
      for (const segment of pathSegments) {
        if (this.isValidCategory(segment)) {
          return segment;
        }
      }

      return null;
    } catch (error) {
      this.logger.warn('[CATEGORY EXTRACTOR] Error extracting category from path:', error);
      return null;
    }
  }

  /**
   * Extract category from prompt ID patterns
   * Examples:
   * - "analysis_notes" -> "analysis"
   * - "education_learning" -> "education"
   * - "debug_application" -> "debugging"
   */
  private extractCategoryFromPattern(promptId: string): string | null {
    const patterns = [
      { pattern: /^analysis_|_analysis$|analysis/i, category: 'analysis' },
      { pattern: /^education_|_education$|learning|teach/i, category: 'education' },
      { pattern: /^develop_|_develop$|code|programming/i, category: 'development' },
      { pattern: /^research_|_research$|investigate/i, category: 'research' },
      { pattern: /^debug_|_debug$|troubleshoot/i, category: 'debugging' },
      { pattern: /^doc_|_doc$|documentation|readme/i, category: 'documentation' },
      { pattern: /^content_|_content$|process|format/i, category: 'content_processing' }
    ];

    for (const { pattern, category } of patterns) {
      if (pattern.test(promptId)) {
        return category;
      }
    }

    return null;
  }

  /**
   * Validate if a category is recognized
   */
  private isValidCategory(category: string): boolean {
    const validCategories = [
      'analysis',
      'education',
      'development',
      'research',
      'debugging',
      'documentation',
      'content_processing',
      'general'
    ];

    return validCategories.includes(category.toLowerCase());
  }

  /**
   * Intelligent gate selection with precedence logic
   *
   * Priority order:
   * 1. Explicit template gates (highest priority)
   * 2. Category-based gates
   * 3. Framework-based gates
   * 4. Default fallback gates (lowest priority)
   */
  selectGatesWithPrecedence(
    categoryResult: CategoryExtractionResult,
    frameworkGates: string[] = [],
    fallbackGates: string[] = ['content-structure']
  ): {
    selectedGates: string[];
    precedenceUsed: string[];
    reasoning: string;
  } {
    const { category, gateConfiguration } = categoryResult;
    const categoryGates = CategoryExtractor.getCategoryGateMapping()[category] || [];

    this.logger.debug('[GATE PRECEDENCE] Input for gate selection:', {
      category,
      templateGates: gateConfiguration,
      categoryGates,
      frameworkGates,
      fallbackGates
    });

    let selectedGates: string[] = [];
    let precedenceUsed: string[] = [];
    let reasoning = '';

    // Phase 1: Start with template gates if specified
    if (gateConfiguration) {
      if (gateConfiguration.include && gateConfiguration.include.length > 0) {
        selectedGates.push(...gateConfiguration.include);
        precedenceUsed.push('template-include');
        reasoning += `Template includes: [${gateConfiguration.include.join(', ')}]. `;
      }

      // Phase 2: Add category gates if framework_gates is true (default)
      if (gateConfiguration.framework_gates !== false) {
        const additionalCategoryGates = categoryGates.filter(gate => !selectedGates.includes(gate));
        selectedGates.push(...additionalCategoryGates);
        if (additionalCategoryGates.length > 0) {
          precedenceUsed.push('category-gates');
          reasoning += `Category gates: [${additionalCategoryGates.join(', ')}]. `;
        }

        // Phase 3: Add framework gates
        const additionalFrameworkGates = frameworkGates.filter(gate => !selectedGates.includes(gate));
        selectedGates.push(...additionalFrameworkGates);
        if (additionalFrameworkGates.length > 0) {
          precedenceUsed.push('framework-gates');
          reasoning += `Framework gates: [${additionalFrameworkGates.join(', ')}]. `;
        }
      }

      // Phase 4: Apply exclusions
      if (gateConfiguration.exclude && gateConfiguration.exclude.length > 0) {
        const originalCount = selectedGates.length;
        selectedGates = selectedGates.filter(gate => !gateConfiguration.exclude!.includes(gate));
        if (selectedGates.length < originalCount) {
          precedenceUsed.push('template-exclude');
          reasoning += `Template excludes: [${gateConfiguration.exclude.join(', ')}]. `;
        }
      }
    } else {
      // No template configuration - use standard precedence

      // Phase 2: Category gates
      selectedGates.push(...categoryGates);
      if (categoryGates.length > 0) {
        precedenceUsed.push('category-gates');
        reasoning += `Category gates: [${categoryGates.join(', ')}]. `;
      }

      // Phase 3: Framework gates
      const additionalFrameworkGates = frameworkGates.filter(gate => !selectedGates.includes(gate));
      selectedGates.push(...additionalFrameworkGates);
      if (additionalFrameworkGates.length > 0) {
        precedenceUsed.push('framework-gates');
        reasoning += `Framework gates: [${additionalFrameworkGates.join(', ')}]. `;
      }
    }

    // Phase 5: Fallback if no gates selected
    if (selectedGates.length === 0) {
      selectedGates.push(...fallbackGates);
      precedenceUsed.push('fallback');
      reasoning += `Fallback gates: [${fallbackGates.join(', ')}]. `;
    }

    // Remove duplicates (shouldn't happen with our logic, but safety check)
    selectedGates = [...new Set(selectedGates)];

    this.logger.info('[GATE PRECEDENCE] Final gate selection:', {
      category,
      selectedGates,
      precedenceUsed,
      reasoning: reasoning.trim()
    });

    return {
      selectedGates,
      precedenceUsed,
      reasoning: reasoning.trim()
    };
  }

  /**
   * Get fallback category mapping for gate selection
   */
  public static getCategoryGateMapping(): Record<string, string[]> {
    return {
      'analysis': ['research-quality', 'technical-accuracy'],
      'education': ['educational-clarity', 'content-structure'],
      'development': ['code-quality', 'security-awareness'],
      'research': ['research-quality', 'fact-checking'],
      'debugging': ['technical-accuracy', 'problem-solving'],
      'documentation': ['content-structure', 'clarity'],
      'content_processing': ['content-structure', 'format-consistency'],
      'general': ['content-structure']
    };
  }

  /**
   * Enhanced gate selection with 5-level precedence including temporary gates
   *
   * Priority order (Phase 3):
   * 1. Temporary gates (highest priority - execution-specific)
   * 2. Explicit template gates
   * 3. Category-based gates
   * 4. Framework-based gates
   * 5. Default fallback gates (lowest priority)
   */
  selectGatesWithEnhancedPrecedence(
    categoryResult: CategoryExtractionResult,
    frameworkGates: string[] = [],
    fallbackGates: string[] = ['content-structure'],
    temporaryGates: string[] = [],
    enhancedConfig?: any
  ): {
    selectedGates: string[];
    precedenceUsed: string[];
    reasoning: string;
    temporaryGatesApplied: string[];
  } {
    const { category, gateConfiguration } = categoryResult;
    const categoryGates = CategoryExtractor.getCategoryGateMapping()[category] || [];

    this.logger.debug('[ENHANCED GATE PRECEDENCE] Input for enhanced gate selection:', {
      category,
      templateGates: gateConfiguration,
      categoryGates,
      frameworkGates,
      fallbackGates,
      temporaryGates,
      enhancedConfig
    });

    let selectedGates: string[] = [];
    let precedenceUsed: string[] = [];
    let reasoning = '';
    let temporaryGatesApplied: string[] = [];

    // Phase 1: Start with temporary gates (highest priority)
    if (temporaryGates.length > 0) {
      selectedGates.push(...temporaryGates);
      precedenceUsed.push('temporary-gates');
      temporaryGatesApplied = [...temporaryGates];
      reasoning += `Temporary gates: [${temporaryGates.join(', ')}]. `;
    }

    // Phase 2: Add template gates if specified
    if (gateConfiguration) {
      if (gateConfiguration.include && gateConfiguration.include.length > 0) {
        const additionalTemplateGates = gateConfiguration.include.filter(gate => !selectedGates.includes(gate));
        selectedGates.push(...additionalTemplateGates);
        if (additionalTemplateGates.length > 0) {
          precedenceUsed.push('template-include');
          reasoning += `Template includes: [${additionalTemplateGates.join(', ')}]. `;
        }
      }

      // Phase 3: Add category gates if framework_gates is true (default)
      if (gateConfiguration.framework_gates !== false) {
        const additionalCategoryGates = categoryGates.filter(gate => !selectedGates.includes(gate));
        selectedGates.push(...additionalCategoryGates);
        if (additionalCategoryGates.length > 0) {
          precedenceUsed.push('category-gates');
          reasoning += `Category gates: [${additionalCategoryGates.join(', ')}]. `;
        }

        // Phase 4: Add framework gates
        const additionalFrameworkGates = frameworkGates.filter(gate => !selectedGates.includes(gate));
        selectedGates.push(...additionalFrameworkGates);
        if (additionalFrameworkGates.length > 0) {
          precedenceUsed.push('framework-gates');
          reasoning += `Framework gates: [${additionalFrameworkGates.join(', ')}]. `;
        }
      }

      // Phase 5: Apply exclusions (can remove temporary, template, category, or framework gates)
      if (gateConfiguration.exclude && gateConfiguration.exclude.length > 0) {
        const originalCount = selectedGates.length;
        selectedGates = selectedGates.filter(gate => !gateConfiguration.exclude!.includes(gate));

        // Update temporary gates applied if they were excluded
        temporaryGatesApplied = temporaryGatesApplied.filter(gate => !gateConfiguration.exclude!.includes(gate));

        if (selectedGates.length < originalCount) {
          precedenceUsed.push('template-exclude');
          reasoning += `Template excludes: [${gateConfiguration.exclude.join(', ')}]. `;
        }
      }
    } else {
      // No template configuration - use standard precedence (skip template level)

      // Phase 3: Category gates
      const additionalCategoryGates = categoryGates.filter(gate => !selectedGates.includes(gate));
      selectedGates.push(...additionalCategoryGates);
      if (additionalCategoryGates.length > 0) {
        precedenceUsed.push('category-gates');
        reasoning += `Category gates: [${additionalCategoryGates.join(', ')}]. `;
      }

      // Phase 4: Framework gates
      const additionalFrameworkGates = frameworkGates.filter(gate => !selectedGates.includes(gate));
      selectedGates.push(...additionalFrameworkGates);
      if (additionalFrameworkGates.length > 0) {
        precedenceUsed.push('framework-gates');
        reasoning += `Framework gates: [${additionalFrameworkGates.join(', ')}]. `;
      }
    }

    // Phase 6: Fallback if no gates selected
    if (selectedGates.length === 0) {
      selectedGates.push(...fallbackGates);
      precedenceUsed.push('fallback');
      reasoning += `Fallback gates: [${fallbackGates.join(', ')}]. `;
    }

    // Remove duplicates (shouldn't happen with our logic, but safety check)
    selectedGates = [...new Set(selectedGates)];
    temporaryGatesApplied = [...new Set(temporaryGatesApplied)];

    this.logger.info('[ENHANCED GATE PRECEDENCE] Final enhanced gate selection:', {
      category,
      selectedGates,
      precedenceUsed,
      temporaryGatesApplied,
      reasoning: reasoning.trim()
    });

    return {
      selectedGates,
      precedenceUsed,
      reasoning: reasoning.trim(),
      temporaryGatesApplied
    };
  }
}

/**
 * Convenience function for quick category extraction
 */
export function extractPromptCategory(prompt: any, logger: Logger): CategoryExtractionResult {
  const extractor = new CategoryExtractor(logger);
  return extractor.extractCategory(prompt);
}
```

--------------------------------------------------------------------------------
/server/src/prompts/promptUtils.ts:
--------------------------------------------------------------------------------

```typescript
import fs from "fs/promises";
import path from "path";
import { PromptData, PromptsConfigFile } from "../types.js";

// Create a simple logger since we can't import from index.ts
const log = {
  info: (message: string, ...args: any[]) => {
    console.log(`[INFO] ${message}`, ...args);
  },
  error: (message: string, ...args: any[]) => {
    console.error(`[ERROR] ${message}`, ...args);
  },
  warn: (message: string, ...args: any[]) => {
    console.warn(`[WARN] ${message}`, ...args);
  },
};

/**
 * Resolves a prompt file path consistently across the application
 * @param promptFile The file path from the prompt data
 * @param configFilePath The path to the config file (used as reference for absolute paths)
 * @param categoryFolder The path to the category folder (used for relative paths)
 * @returns The fully resolved path to the prompt file
 */
export function resolvePromptFilePath(
  promptFile: string,
  configFilePath: string,
  categoryFolder: string
): string {
  if (promptFile.startsWith("/")) {
    // Absolute path (relative to config file location)
    return path.resolve(path.dirname(configFilePath), promptFile.slice(1));
  } else if (promptFile.includes("/")) {
    // Path already includes category or sub-path
    return path.resolve(path.dirname(configFilePath), promptFile);
  } else {
    // Simple filename, relative to category folder
    return path.resolve(categoryFolder, promptFile);
  }
}

/**
 * Reads a prompt file and returns its content
 * @param promptFilePath Path to the prompt file
 * @returns The content of the prompt file
 */
export async function readPromptFile(promptFilePath: string): Promise<string> {
  try {
    return await fs.readFile(promptFilePath, "utf8");
  } catch (error) {
    log.error(`Error reading prompt file ${promptFilePath}:`, error);
    throw new Error(
      `Failed to read prompt file: ${
        error instanceof Error ? error.message : String(error)
      }`
    );
  }
}

/**
 * Parses a prompt file content into sections
 * @param content The content of the prompt file
 * @returns An object containing the different sections of the prompt
 */
export function parsePromptSections(content: string): Record<string, string> {
  const sections: Record<string, string> = {};

  // Extract the title and description (everything before the first ## heading)
  const titleMatch = content.match(/^# (.+?)(?=\n\n|\n##)/s);
  if (titleMatch) {
    sections.title = titleMatch[1].trim();

    // Extract description (content between title and first ## heading)
    const descMatch = content.match(/^# .+?\n\n([\s\S]+?)(?=\n## )/s);
    if (descMatch) {
      sections.description = descMatch[1].trim();
    } else {
      sections.description = "";
    }
  }

  // Extract other sections (## headings)
  const sectionMatches = content.matchAll(
    /## ([^\n]+)\n\n([\s\S]+?)(?=\n## |\n# |\n$)/g
  );
  for (const match of sectionMatches) {
    const sectionName = match[1].trim();
    const sectionContent = match[2].trim();
    sections[sectionName] = sectionContent;
  }

  return sections;
}

/**
 * Modifies a specific section of a prompt markdown file
 * @param promptId Unique identifier of the prompt to modify
 * @param sectionName Name of the section to modify (e.g., "title", "description", "System Message", "User Message Template")
 * @param newContent New content for the specified section
 * @param configPath Path to the promptsConfig.json file
 * @returns Object containing the result of the operation
 */
export async function modifyPromptSection(
  promptId: string,
  sectionName: string,
  newContent: string,
  configPath: string
): Promise<{
  success: boolean;
  message: string;
  promptData?: PromptData;
  filePath?: string;
}> {
  try {
    const messages: string[] = [];
    // Read the promptsConfig.json file
    const configFilePath = path.resolve(configPath);
    const configContent = await fs.readFile(configFilePath, "utf8");
    const promptsConfig = JSON.parse(configContent) as PromptsConfigFile;

    // Find the prompt in all category files
    let prompt: PromptData | null = null;
    let categoryFilePath: string = "";
    let promptIndex: number = -1;
    let promptsFile: any = null;

    // Search through each import path
    for (const importPath of promptsConfig.imports) {
      try {
        // Construct the full path to the import file
        const fullImportPath = path.resolve(
          path.dirname(configFilePath),
          importPath
        );

        // Check if the file exists
        try {
          await fs.access(fullImportPath);
        } catch (error) {
          log.warn(`Import file not found: ${importPath}. Skipping.`);
          continue;
        }

        // Read the file
        const fileContent = await fs.readFile(fullImportPath, "utf8");
        const categoryPromptsFile = JSON.parse(fileContent);

        if (
          categoryPromptsFile.prompts &&
          Array.isArray(categoryPromptsFile.prompts)
        ) {
          // Find the prompt in this category file
          const foundIndex = categoryPromptsFile.prompts.findIndex(
            (p: PromptData) => p.id === promptId
          );

          if (foundIndex !== -1) {
            prompt = categoryPromptsFile.prompts[foundIndex];
            categoryFilePath = fullImportPath;
            promptIndex = foundIndex;
            promptsFile = categoryPromptsFile;
            messages.push(
              `✅ Found prompt '${promptId}' in category file: ${path.basename(
                categoryFilePath
              )}`
            );
            break;
          }
        }
      } catch (error) {
        log.error(`Error processing import file ${importPath}:`, error);
      }
    }

    // If prompt not found, throw an error
    if (!prompt) {
      return {
        success: false,
        message: `Prompt with ID '${promptId}' not found in any category file`,
      };
    }

    // Determine the category folder path
    const categoryFolder = path.dirname(categoryFilePath);

    // Get the full path to the prompt file using the new utility function
    const promptFilePath = resolvePromptFilePath(
      prompt.file,
      configFilePath,
      categoryFolder
    );

    // Read the prompt file
    const promptContent = await readPromptFile(promptFilePath);

    // Parse the prompt sections
    const sections = parsePromptSections(promptContent);

    // Check if the section exists
    if (!(sectionName in sections) && sectionName !== "description") {
      return {
        success: false,
        message: `Section '${sectionName}' not found in prompt '${promptId}'`,
      };
    }

    // Store the original prompt data for potential rollback
    const originalPrompt = { ...prompt };
    const originalContent = promptContent;

    // Modify the section
    if (sectionName === "title") {
      sections.title = newContent;
    } else if (sectionName === "description") {
      sections.description = newContent;
    } else {
      sections[sectionName] = newContent;
    }

    // Reconstruct the prompt content
    let newPromptContent = `# ${sections.title}\n\n${sections.description}\n\n`;

    // Add other sections
    for (const [name, content] of Object.entries(sections)) {
      if (name !== "title" && name !== "description") {
        newPromptContent += `## ${name}\n\n${content}\n\n`;
      }
    }

    // Create the updated prompt
    const updatedPrompt: PromptData = {
      ...originalPrompt,
      name: sectionName === "title" ? newContent : originalPrompt.name,
    };

    // Create a copy of the prompts file with the prompt removed
    const updatedPromptsFile = {
      ...promptsFile,
      prompts: [...promptsFile.prompts],
    };
    updatedPromptsFile.prompts.splice(promptIndex, 1);

    // Add the updated prompt to the new prompts array
    updatedPromptsFile.prompts.push(updatedPrompt);

    // Define the operations and rollbacks for the transaction
    const operations = [
      // 1. Write the updated prompt content to the file
      async () => await safeWriteFile(promptFilePath, newPromptContent),

      // 2. Write the updated category file with the prompt removed and added back
      async () =>
        await safeWriteFile(
          categoryFilePath,
          JSON.stringify(updatedPromptsFile, null, 2)
        ),
    ];

    const rollbacks = [
      // 1. Restore the original prompt content
      async () => await fs.writeFile(promptFilePath, originalContent, "utf8"),

      // 2. Restore the original category file
      async () =>
        await fs.writeFile(
          categoryFilePath,
          JSON.stringify(promptsFile, null, 2),
          "utf8"
        ),
    ];

    // Perform the operations as a transaction
    await performTransactionalFileOperations(operations, rollbacks);

    messages.push(
      `✅ Updated section '${sectionName}' in markdown file: ${prompt.file}`
    );
    if (sectionName === "title") {
      messages.push(
        `✅ Updated prompt name in category file to '${newContent}'`
      );
    }

    return {
      success: true,
      message: messages.join("\n"),
      promptData: updatedPrompt,
      filePath: promptFilePath,
    };
  } catch (error) {
    log.error(`Error in modifyPromptSection:`, error);
    return {
      success: false,
      message: `Failed to modify prompt section: ${
        error instanceof Error ? error.message : String(error)
      }`,
    };
  }
}

/**
 * Helper function to perform a series of file operations as a transaction
 * Automatically rolls back all changes if any operation fails
 * @param operations Array of async functions that perform file operations
 * @param rollbacks Array of async functions that undo the operations
 * @returns Result of the last operation if successful
 */
export async function performTransactionalFileOperations<T>(
  operations: Array<() => Promise<any>>,
  rollbacks: Array<() => Promise<any>>
): Promise<T> {
  // Validate inputs
  if (!operations || !Array.isArray(operations) || operations.length === 0) {
    throw new Error("No operations provided for transaction");
  }

  if (!rollbacks || !Array.isArray(rollbacks)) {
    log.warn(
      "No rollbacks provided for transaction - operations cannot be rolled back if they fail"
    );
    rollbacks = [];
  }

  // Ensure rollbacks array matches operations array length
  if (rollbacks.length < operations.length) {
    log.warn(
      `Rollbacks array (${rollbacks.length}) is shorter than operations array (${operations.length}) - some operations cannot be rolled back`
    );
    // Fill with dummy rollbacks
    for (let i = rollbacks.length; i < operations.length; i++) {
      rollbacks.push(async () => {
        log.warn(`No rollback defined for operation ${i}`);
      });
    }
  }

  let lastSuccessfulIndex = -1;
  let result: any;

  try {
    // Perform operations
    for (let i = 0; i < operations.length; i++) {
      if (typeof operations[i] !== "function") {
        throw new Error(`Operation at index ${i} is not a function`);
      }
      result = await operations[i]();
      lastSuccessfulIndex = i;
    }
    return result as T;
  } catch (error) {
    log.error(
      `Transaction failed at operation ${lastSuccessfulIndex + 1}:`,
      error
    );

    // Perform rollbacks in reverse order
    for (let i = lastSuccessfulIndex; i >= 0; i--) {
      try {
        if (typeof rollbacks[i] === "function") {
          await rollbacks[i]();
        } else {
          log.warn(`Skipping invalid rollback at index ${i} (not a function)`);
        }
      } catch (rollbackError) {
        log.error(`Error during rollback operation ${i}:`, rollbackError);
        // Continue with other rollbacks even if one fails
      }
    }
    throw error;
  }
}

/**
 * Safely writes content to a file by first writing to a temp file, then renaming
 * This ensures the file is either completely written or left unchanged
 * @param filePath Path to the file
 * @param content Content to write
 * @param encoding Optional encoding (defaults to 'utf8')
 */
export async function safeWriteFile(
  filePath: string,
  content: string,
  encoding: BufferEncoding = "utf8"
): Promise<void> {
  const tempPath = `${filePath}.tmp`;

  try {
    // Write to temp file
    await fs.writeFile(tempPath, content, encoding);

    // Check if the original file exists
    try {
      await fs.access(filePath);
      // If it exists, make a backup
      const backupPath = `${filePath}.bak`;
      await fs.copyFile(filePath, backupPath);

      // Replace the original with the temp file
      await fs.rename(tempPath, filePath);

      // Remove the backup
      await fs.unlink(backupPath);
    } catch (error) {
      // File doesn't exist, just rename the temp file
      await fs.rename(tempPath, filePath);
    }
  } catch (error) {
    // Clean up temp file if it exists
    try {
      await fs.unlink(tempPath);
    } catch (cleanupError) {
      // Ignore errors during cleanup
    }
    throw error;
  }
}

/**
 * Finds and deletes a prompt file
 * @param promptId Unique identifier of the prompt to delete
 * @param baseDir Base directory to search in (usually the prompts directory)
 * @returns Object containing information about the deletion
 */
export async function findAndDeletePromptFile(
  promptId: string,
  baseDir: string
): Promise<{
  found: boolean;
  deleted: boolean;
  path?: string;
  error?: string;
}> {
  try {
    // First, find the prompt file
    const findResult = await findPromptFile(promptId, baseDir);

    // If the file wasn't found, return the result
    if (!findResult.found) {
      return { found: false, deleted: false };
    }

    // Try to delete the file
    try {
      await fs.unlink(findResult.path!);
      log.info(`Successfully deleted markdown file: ${findResult.path}`);
      return { found: true, deleted: true, path: findResult.path };
    } catch (deleteError) {
      const errorMessage = `Error deleting file at ${findResult.path}: ${
        deleteError instanceof Error ? deleteError.message : String(deleteError)
      }`;
      log.error(errorMessage);
      return {
        found: true,
        deleted: false,
        path: findResult.path,
        error: errorMessage,
      };
    }
  } catch (error) {
    const errorMessage = `Error finding and deleting prompt file: ${
      error instanceof Error ? error.message : String(error)
    }`;
    log.error(errorMessage);
    return { found: false, deleted: false, error: errorMessage };
  }
}

/**
 * Checks if a prompt file exists and returns its path
 * @param promptId Unique identifier of the prompt to find
 * @param baseDir Base directory to search in (usually the prompts directory)
 * @returns Object containing information about the prompt file
 */
export async function findPromptFile(
  promptId: string,
  baseDir: string
): Promise<{
  found: boolean;
  path?: string;
  category?: string;
  error?: string;
}> {
  try {
    // Get all category directories
    const categoryDirs = await fs.readdir(baseDir, { withFileTypes: true });

    // Filter for directories only
    const categories = categoryDirs
      .filter((dirent) => dirent.isDirectory())
      .map((dirent) => dirent.name);

    log.info(
      `Searching for markdown file with ID '${promptId}' in ${categories.length} category folders`
    );

    // Possible filenames to look for
    const possibleFilenames = [
      `${promptId}.md`, // Simple ID.md
      `${promptId.replace(/-/g, "_")}.md`, // ID with underscores instead of hyphens
      `${promptId.replace(/_/g, "-")}.md`, // ID with hyphens instead of underscores
    ];

    // Search each category directory for the file
    for (const category of categories) {
      const categoryPath = path.join(baseDir, category);

      try {
        const files = await fs.readdir(categoryPath);

        // Check each possible filename
        for (const filename of possibleFilenames) {
          if (files.includes(filename)) {
            const filePath = path.join(categoryPath, filename);
            log.info(`Found markdown file at: ${filePath}`);
            return { found: true, path: filePath, category };
          }
        }
      } catch (readError) {
        log.warn(
          `Error reading directory ${categoryPath}: ${
            readError instanceof Error ? readError.message : String(readError)
          }`
        );
        // Continue to next category
      }
    }

    log.warn(
      `Could not find markdown file for prompt '${promptId}' in any category folder`
    );
    return { found: false };
  } catch (error) {
    const errorMessage = `Error searching for prompt file: ${
      error instanceof Error ? error.message : String(error)
    }`;
    log.error(errorMessage);
    return { found: false, error: errorMessage };
  }
}

```

--------------------------------------------------------------------------------
/server/src/execution/context/context-resolver.ts:
--------------------------------------------------------------------------------

```typescript
/**
 * Context Resolution System
 * 
 * Intelligent context resolution with priority-based fallbacks that replaces
 * the hardcoded {{previous_message}} pattern with flexible, multi-source context aggregation.
 * 
 * Features:
 * - Priority-based context resolution strategies
 * - Multi-source context aggregation
 * - Context validation and sanitization
 * - Smart fallback context generation
 * - Context caching for performance
 */

import { Logger } from "../../logging/index.js";
import { PromptArgument } from "../../types/index.js";

/**
 * Context source types
 */
export type ContextSource = 
  | 'user_provided'
  | 'conversation_history'
  | 'environment_variables'
  | 'prompt_defaults'
  | 'system_context'
  | 'cached_context'
  | 'generated_placeholder'
  | 'empty_fallback';

/**
 * Context resolution result
 */
export interface ContextResolution {
  value: any;
  source: ContextSource;
  confidence: number;
  metadata: {
    resolvedAt: number;
    strategy: string;
    alternativeValues?: Array<{ value: any; source: ContextSource; confidence: number }>;
    warnings: string[];
  };
}

/**
 * Context provider interface
 */
export interface ContextProvider {
  name: string;
  priority: number;
  isAvailable: () => boolean;
  resolve: (key: string, hint?: any) => Promise<ContextResolution | null>;
}

/**
 * Context aggregation options
 */
export interface ContextAggregationOptions {
  preferredSources?: ContextSource[];
  excludedSources?: ContextSource[];
  cacheResults?: boolean;
  includeAlternatives?: boolean;
  minimumConfidence?: number;
}

/**
 * Context resolver class
 */
export class ContextResolver {
  private logger: Logger;
  private providers: Map<string, ContextProvider> = new Map();
  private cache: Map<string, ContextResolution> = new Map();
  private cacheTimeout: number = 30000; // 30 seconds
  
  // Resolution statistics
  private stats = {
    totalResolutions: 0,
    successfulResolutions: 0,
    cacheHits: 0,
    cacheMisses: 0,
    providerUsage: new Map<string, number>(),
    averageConfidence: 0,
    averageResolutionTime: 0
  };

  constructor(logger: Logger) {
    this.logger = logger;
    this.initializeDefaultProviders();
    this.logger.debug(`ContextResolver initialized with ${this.providers.size} providers`);
  }

  /**
   * Resolve context value using priority-based strategy
   */
  async resolveContext(
    key: string, 
    hint?: any, 
    options: ContextAggregationOptions = {}
  ): Promise<ContextResolution> {
    const startTime = Date.now();
    this.stats.totalResolutions++;
    
    this.logger.debug(`Resolving context for key: "${key}"`);
    
    // Check cache first
    if (options.cacheResults !== false) {
      const cached = this.getCachedResolution(key);
      if (cached) {
        this.stats.cacheHits++;
        this.logger.debug(`Context resolved from cache: ${key} -> ${cached.source}`);
        return cached;
      }
    }
    
    this.stats.cacheMisses++;
    
    // Get available providers sorted by priority
    const availableProviders = this.getAvailableProviders(options);
    const alternatives: Array<{ value: any; source: ContextSource; confidence: number }> = [];
    
    // Try each provider in priority order
    for (const provider of availableProviders) {
      try {
        const resolution = await provider.resolve(key, hint);
        if (resolution && this.meetsMinimumConfidence(resolution, options)) {
          
          // Collect alternatives if requested
          if (options.includeAlternatives) {
            // Continue trying other providers for alternatives
            await this.collectAlternatives(key, hint, availableProviders, provider, alternatives);
            resolution.metadata.alternativeValues = alternatives;
          }
          
          // Cache the result
          if (options.cacheResults !== false) {
            this.cacheResolution(key, resolution);
          }
          
          // Update statistics
          this.updateStats(provider.name, resolution, startTime);
          
          this.logger.debug(`Context resolved: ${key} -> ${resolution.source} (confidence: ${resolution.confidence})`);
          return resolution;
        } else if (resolution) {
          alternatives.push({
            value: resolution.value,
            source: resolution.source,
            confidence: resolution.confidence
          });
        }
      } catch (error) {
        this.logger.debug(`Provider ${provider.name} failed for key ${key}:`, error);
        continue;
      }
    }
    
    // If no provider succeeded, create a fallback resolution
    const fallbackResolution = this.createFallbackResolution(key, hint, alternatives);
    
    // Cache fallback if enabled
    if (options.cacheResults !== false) {
      this.cacheResolution(key, fallbackResolution);
    }
    
    this.updateStats('fallback', fallbackResolution, startTime);
    this.logger.debug(`Context resolved using fallback: ${key} -> ${fallbackResolution.source}`);
    
    return fallbackResolution;
  }

  /**
   * Register a custom context provider
   */
  registerProvider(provider: ContextProvider): void {
    this.providers.set(provider.name, provider);
    this.stats.providerUsage.set(provider.name, 0);
    this.logger.debug(`Registered context provider: ${provider.name} (priority: ${provider.priority})`);
  }

  /**
   * Unregister a context provider
   */
  unregisterProvider(name: string): boolean {
    const removed = this.providers.delete(name);
    this.stats.providerUsage.delete(name);
    if (removed) {
      this.logger.debug(`Unregistered context provider: ${name}`);
    }
    return removed;
  }

  /**
   * Initialize default context providers
   */
  private initializeDefaultProviders(): void {
    // Conversation history provider
    this.registerProvider({
      name: 'conversation_history',
      priority: 80,
      isAvailable: () => true,
      resolve: async (key: string, hint?: any): Promise<ContextResolution | null> => {
        if (hint?.conversationHistory && hint.conversationHistory.length > 0) {
          const lastMessage = hint.conversationHistory[hint.conversationHistory.length - 1];
          if (lastMessage?.content) {
            return {
              value: lastMessage.content,
              source: 'conversation_history',
              confidence: 0.8,
              metadata: {
                resolvedAt: Date.now(),
                strategy: 'last_message',
                warnings: []
              }
            };
          }
        }
        return null;
      }
    });

    // Environment variables provider
    this.registerProvider({
      name: 'environment_variables',
      priority: 70,
      isAvailable: () => true,
      resolve: async (key: string): Promise<ContextResolution | null> => {
        const envKey = `PROMPT_${key.toUpperCase()}`;
        const value = process.env[envKey];
        if (value) {
          return {
            value,
            source: 'environment_variables',
            confidence: 0.9,
            metadata: {
              resolvedAt: Date.now(),
              strategy: 'env_var',
              warnings: []
            }
          };
        }
        return null;
      }
    });

    // Prompt defaults provider
    this.registerProvider({
      name: 'prompt_defaults',
      priority: 60,
      isAvailable: () => true,
      resolve: async (key: string, hint?: any): Promise<ContextResolution | null> => {
        if (hint?.promptDefaults && hint.promptDefaults[key] !== undefined) {
          return {
            value: hint.promptDefaults[key],
            source: 'prompt_defaults',
            confidence: 0.7,
            metadata: {
              resolvedAt: Date.now(),
              strategy: 'prompt_specific',
              warnings: []
            }
          };
        }
        return null;
      }
    });

    // System context provider
    this.registerProvider({
      name: 'system_context',
      priority: 50,
      isAvailable: () => true,
      resolve: async (key: string, hint?: any): Promise<ContextResolution | null> => {
        if (hint?.systemContext && hint.systemContext[key] !== undefined) {
          return {
            value: hint.systemContext[key],
            source: 'system_context',
            confidence: 0.6,
            metadata: {
              resolvedAt: Date.now(),
              strategy: 'system_provided',
              warnings: []
            }
          };
        }
        return null;
      }
    });

    // Smart placeholder generator
    this.registerProvider({
      name: 'placeholder_generator',
      priority: 30,
      isAvailable: () => true,
      resolve: async (key: string, hint?: any): Promise<ContextResolution | null> => {
        const placeholder = this.generateSmartPlaceholder(key, hint);
        return {
          value: placeholder.value,
          source: 'generated_placeholder',
          confidence: placeholder.confidence,
          metadata: {
            resolvedAt: Date.now(),
            strategy: 'smart_generation',
            warnings: placeholder.warnings
          }
        };
      }
    });
  }

  /**
   * Get available providers based on options
   */
  private getAvailableProviders(options: ContextAggregationOptions): ContextProvider[] {
    return Array.from(this.providers.values())
      .filter(provider => {
        // Check if provider is available
        if (!provider.isAvailable()) return false;
        
        // Check preferred sources
        if (options.preferredSources?.length) {
          // This is a simplistic check - in practice you'd map provider names to sources
          const providerSource = this.mapProviderToSource(provider.name);
          if (!options.preferredSources.includes(providerSource)) return false;
        }
        
        // Check excluded sources
        if (options.excludedSources?.length) {
          const providerSource = this.mapProviderToSource(provider.name);
          if (options.excludedSources.includes(providerSource)) return false;
        }
        
        return true;
      })
      .sort((a, b) => b.priority - a.priority); // Higher priority first
  }

  /**
   * Map provider name to context source
   */
  private mapProviderToSource(providerName: string): ContextSource {
    const mapping: Record<string, ContextSource> = {
      'conversation_history': 'conversation_history',
      'environment_variables': 'environment_variables',
      'prompt_defaults': 'prompt_defaults',
      'system_context': 'system_context',
      'placeholder_generator': 'generated_placeholder'
    };
    
    return mapping[providerName] || 'system_context';
  }

  /**
   * Check if resolution meets minimum confidence
   */
  private meetsMinimumConfidence(resolution: ContextResolution, options: ContextAggregationOptions): boolean {
    if (options.minimumConfidence === undefined) return true;
    return resolution.confidence >= options.minimumConfidence;
  }

  /**
   * Collect alternative values from other providers
   */
  private async collectAlternatives(
    key: string,
    hint: any,
    allProviders: ContextProvider[],
    usedProvider: ContextProvider,
    alternatives: Array<{ value: any; source: ContextSource; confidence: number }>
  ): Promise<void> {
    const remainingProviders = allProviders.filter(p => p !== usedProvider);
    
    for (const provider of remainingProviders.slice(0, 3)) { // Limit to 3 alternatives
      try {
        const resolution = await provider.resolve(key, hint);
        if (resolution) {
          alternatives.push({
            value: resolution.value,
            source: resolution.source,
            confidence: resolution.confidence
          });
        }
      } catch (error) {
        // Ignore errors when collecting alternatives
        continue;
      }
    }
  }

  /**
   * Generate smart placeholder based on key characteristics
   */
  private generateSmartPlaceholder(
    key: string, 
    hint?: any
  ): { value: string; confidence: number; warnings: string[] } {
    const keyLower = key.toLowerCase();
    const warnings: string[] = [];
    
    // Argument-specific placeholders
    if (hint?.argumentDef) {
      const arg = hint.argumentDef as PromptArgument;
      const description = (arg.description || '').toLowerCase();
      
      if (description.includes('file') || keyLower.includes('file')) {
        return { value: '[File path required]', confidence: 0.4, warnings };
      }
      
      if (description.includes('url') || keyLower.includes('url')) {
        return { value: '[URL required]', confidence: 0.4, warnings };
      }
      
      if (description.includes('number') || keyLower.includes('count')) {
        return { value: '1', confidence: 0.5, warnings };
      }
    }
    
    // Generic semantic placeholders
    if (keyLower.includes('content') || keyLower.includes('text') || keyLower.includes('input')) {
      return { 
        value: '[Content to be provided]', 
        confidence: 0.3, 
        warnings: ['Generic content placeholder - consider providing specific content']
      };
    }
    
    if (keyLower.includes('name') || keyLower.includes('title')) {
      return { value: `[${key} required]`, confidence: 0.3, warnings };
    }
    
    if (keyLower.includes('format') || keyLower.includes('style')) {
      return { value: 'default', confidence: 0.4, warnings };
    }
    
    if (keyLower.includes('language') || keyLower.includes('lang')) {
      return { value: 'en', confidence: 0.4, warnings };
    }
    
    // Ultra-generic fallback
    warnings.push(`No semantic match found for "${key}" - using generic placeholder`);
    return { 
      value: `[${key.replace(/_/g, ' ')} to be specified]`, 
      confidence: 0.2, 
      warnings 
    };
  }

  /**
   * Create fallback resolution when no providers succeed
   */
  private createFallbackResolution(
    key: string,
    hint: any,
    alternatives: Array<{ value: any; source: ContextSource; confidence: number }>
  ): ContextResolution {
    // If we have alternatives, use the best one
    if (alternatives.length > 0) {
      const best = alternatives.sort((a, b) => b.confidence - a.confidence)[0];
      return {
        value: best.value,
        source: best.source,
        confidence: best.confidence,
        metadata: {
          resolvedAt: Date.now(),
          strategy: 'best_alternative',
          alternativeValues: alternatives,
          warnings: ['Used alternative resolution after primary strategies failed']
        }
      };
    }
    
    // Last resort: empty fallback
    return {
      value: '',
      source: 'empty_fallback',
      confidence: 0.1,
      metadata: {
        resolvedAt: Date.now(),
        strategy: 'empty_fallback',
        warnings: [`No context available for "${key}" - using empty value`]
      }
    };
  }

  /**
   * Get cached resolution if available and not expired
   */
  private getCachedResolution(key: string): ContextResolution | null {
    const cached = this.cache.get(key);
    if (cached && (Date.now() - cached.metadata.resolvedAt) < this.cacheTimeout) {
      return cached;
    } else if (cached) {
      // Remove expired cache entry
      this.cache.delete(key);
    }
    return null;
  }

  /**
   * Cache resolution result
   */
  private cacheResolution(key: string, resolution: ContextResolution): void {
    this.cache.set(key, resolution);
    
    // Cleanup old entries periodically
    if (this.cache.size > 1000) {
      const cutoff = Date.now() - this.cacheTimeout;
      for (const [k, v] of this.cache.entries()) {
        if (v.metadata.resolvedAt < cutoff) {
          this.cache.delete(k);
        }
      }
    }
  }

  /**
   * Update resolution statistics
   */
  private updateStats(providerName: string, resolution: ContextResolution, startTime: number): void {
    this.stats.successfulResolutions++;
    
    const current = this.stats.providerUsage.get(providerName) || 0;
    this.stats.providerUsage.set(providerName, current + 1);
    
    // Update average confidence
    const totalSuccessful = this.stats.successfulResolutions;
    this.stats.averageConfidence = 
      (this.stats.averageConfidence * (totalSuccessful - 1) + resolution.confidence) / totalSuccessful;
    
    // Update average resolution time
    const resolutionTime = Date.now() - startTime;
    this.stats.averageResolutionTime =
      (this.stats.averageResolutionTime * (totalSuccessful - 1) + resolutionTime) / totalSuccessful;
  }

  /**
   * Clear cache
   */
  clearCache(): void {
    this.cache.clear();
    this.logger.debug('Context cache cleared');
  }

  /**
   * Get context resolution statistics
   */
  getStats(): typeof this.stats {
    return {
      ...this.stats,
      providerUsage: new Map(this.stats.providerUsage)
    };
  }

  /**
   * Reset statistics
   */
  resetStats(): void {
    this.stats = {
      totalResolutions: 0,
      successfulResolutions: 0,
      cacheHits: 0,
      cacheMisses: 0,
      providerUsage: new Map(Array.from(this.providers.keys()).map(name => [name, 0])),
      averageConfidence: 0,
      averageResolutionTime: 0
    };
  }
}

/**
 * Factory function to create context resolver
 */
export function createContextResolver(logger: Logger): ContextResolver {
  return new ContextResolver(logger);
}
```

--------------------------------------------------------------------------------
/server/prompts/analysis/advanced_analysis_engine.md:
--------------------------------------------------------------------------------

```markdown
# Advanced Analysis Engine

## Description
Complex template testing prompt with advanced Nunjucks features including conditionals, loops, inheritance, filters, and multi-format output generation. Designed to stress-test the template engine with maximum complexity.

## System Message
You are an advanced analysis engine capable of processing complex requests with multiple data sources, analysis types, and output formats. Handle all template complexity gracefully and provide structured, comprehensive analysis. This prompt tests advanced template features including nested conditionals, complex loops, filters, and dynamic content generation.

## User Message Template
# 🔍 Advanced Analysis: {{ topic | title if topic else "General Analysis" }}

## 🎯 Analysis Configuration
{% if analysis_type %}
**Analysis Type**: {{ analysis_type | upper | replace("_", " ") }}
{% else %}
**Analysis Type**: COMPREHENSIVE MULTI-DIMENSIONAL ANALYSIS
{% endif %}

{% set complexity_score = 0 %}
{% if sources %}{% set complexity_score = complexity_score + sources|length %}{% endif %}
{% if focus_areas %}{% set complexity_score = complexity_score + focus_areas|length %}{% endif %}
{% if constraints %}{% set complexity_score = complexity_score + constraints|length %}{% endif %}

**Complexity Score**: {{ complexity_score }} 
{% if complexity_score > 10 %}🔥 MAXIMUM COMPLEXITY{% elif complexity_score > 5 %}⚡ HIGH COMPLEXITY{% else %}📊 STANDARD COMPLEXITY{% endif %}

{% if sources %}
## 📊 Data Sources Strategy
{% for source in sources %}
{% set loop_info = loop %}
{{ loop.index }}. **{{ source | title | replace("_", " ") }}**
   {% if source == "web" %}
   - Current information and real-time trends
   - SEO-optimized content analysis
   - Social sentiment indicators
   {% elif source == "papers" %}
   - Peer-reviewed research and academic insights
   - Methodological rigor and scientific validation
   - Historical context and longitudinal studies
   {% elif source == "news" %}
   - Breaking developments and current events
   - Media bias analysis and fact-checking
   - Timeline construction and event correlation
   {% elif source == "social" %}
   - Public opinion and sentiment analysis
   - Viral trend identification
   - Demographic and geographic distribution
   {% elif source == "industry" %}
   - Market reports and industry intelligence
   - Competitive landscape analysis
   - Regulatory and compliance considerations
   {% elif source == "expert" %}
   - Professional opinions and expert interviews
   - Specialized knowledge and insider perspectives
   - Best practices and lessons learned
   {% else %}
   - {{ source | title }} data collection and analysis
   - Source-specific validation and verification
   - Integration with primary research methods
   {% endif %}
   {% if loop.first %}**PRIMARY SOURCE** - Foundation for analysis{% endif %}
   {% if loop.last %}**VALIDATION SOURCE** - Final verification and cross-reference{% endif %}
   {% if loop.length > 3 and loop.index == loop.length // 2 %}**PIVOT SOURCE** - Mid-analysis validation{% endif %}
{% endfor %}

### Source Integration Matrix
{% for source in sources %}
{% for other_source in sources %}
{% if source != other_source %}
- **{{ source|title }} ↔ {{ other_source|title }}**: {% if source == "web" and other_source == "papers" %}Validate web claims with academic research{% elif source == "news" and other_source == "social" %}Cross-reference news with social sentiment{% else %}Comparative analysis and validation{% endif %}
{% endif %}
{% endfor %}
{% endfor %}
{% else %}
## 📊 Standard Data Sources
1. **Web Research** - Current information and trends
2. **Academic Papers** - Scholarly perspective and research  
3. **News Articles** - Recent developments and context
4. **Industry Reports** - Market intelligence and analysis
{% endif %}

{% if depth %}
## 🎚️ Analysis Depth: {{ depth | title }}
{% set depth_config = {
  "surface": {
    "description": "Quick overview and key highlights",
    "time_estimate": "15-30 minutes",
    "output_length": "2-3 pages", 
    "detail_level": "High-level summary with actionable insights"
  },
  "standard": {
    "description": "Detailed examination of core topics",
    "time_estimate": "1-2 hours",
    "output_length": "5-8 pages",
    "detail_level": "Comprehensive analysis with supporting evidence"
  },
  "comprehensive": {
    "description": "Deep-dive analysis across all dimensions", 
    "time_estimate": "3-5 hours",
    "output_length": "10-15 pages",
    "detail_level": "Multi-perspective evaluation with detailed frameworks"
  },
  "expert": {
    "description": "Expert-level technical analysis",
    "time_estimate": "6+ hours", 
    "output_length": "15+ pages",
    "detail_level": "Advanced methodology with strategic recommendations"
  }
} %}

{% set current_depth = depth_config[depth] if depth in depth_config else depth_config["standard"] %}

- **Description**: {{ current_depth.description }}
- **Estimated Time**: {{ current_depth.time_estimate }}
- **Expected Output**: {{ current_depth.output_length }}
- **Detail Level**: {{ current_depth.detail_level }}

{% if depth == "expert" %}
### Expert Analysis Framework
- Advanced statistical analysis and modeling
- Multi-dimensional correlation mapping
- Predictive analytics and scenario planning
- Risk assessment matrices and mitigation strategies
{% endif %}
{% endif %}

{% if constraints %}
## ⚙️ Analysis Constraints & Parameters
{% for key, value in constraints.items() %}
- **{{ key | replace("_", " ") | title }}**: {{ value }}
  {% if key == "time_limit" %}*Prioritizing high-impact insights within timeframe*{% endif %}
  {% if key == "budget" %}*Cost-effective research methods and resource allocation*{% endif %}
  {% if key == "scope" %}*Focused analysis boundaries and exclusion criteria*{% endif %}
  {% if key == "audience" %}*Content and presentation tailored for {{ value }}*{% endif %}
{% endfor %}

### Constraint Impact Assessment
{% if constraints.time_limit %}
⏱️ **Time Pressure**: Accelerated methodology with focus on critical insights
{% endif %}
{% if constraints.budget %}
💰 **Budget Optimization**: Prioritized research activities and cost-effective approaches  
{% endif %}
{% if constraints.scope %}
🎯 **Scope Management**: Clear boundaries prevent scope creep and maintain focus
{% endif %}
{% endif %}

{% if focus_areas %}
## 🔍 Multi-Dimensional Focus Areas
{% for area in focus_areas %}
### {{ loop.index }}. {{ area | title }} Analysis Framework
{% if area == "technical" %}
#### Technical Deep-Dive
- **Architecture & Design**: System specifications and technical requirements
- **Implementation Details**: Development methodologies and best practices  
- **Performance Metrics**: Benchmarking, optimization, and scalability analysis
- **Technology Stack**: Tools, frameworks, and platform considerations
- **Risk Assessment**: Technical debt, security vulnerabilities, maintenance overhead
{% elif area == "business" %}
#### Business Impact Analysis
- **Market Dynamics**: Competitive landscape and positioning strategies
- **Financial Modeling**: Revenue projections, cost analysis, and ROI calculations
- **Strategic Alignment**: Business objectives and organizational fit
- **Stakeholder Impact**: Customer, partner, and internal team considerations
- **Go-to-Market**: Launch strategies, marketing approaches, and sales enablement
{% elif area == "ethical" %}
#### Ethical Framework Evaluation
- **Moral Implications**: Ethical principles and moral reasoning analysis
- **Stakeholder Impact**: Effects on users, communities, and society
- **Privacy & Rights**: Data protection, consent, and individual autonomy
- **Fairness & Bias**: Algorithmic fairness and discrimination prevention
- **Transparency**: Explainability, accountability, and public discourse
{% elif area == "regulatory" %}
#### Regulatory Compliance Analysis
- **Legal Framework**: Applicable laws, regulations, and compliance requirements
- **Risk Assessment**: Legal exposure, liability, and mitigation strategies
- **Policy Implications**: Government relations and regulatory strategy
- **International Considerations**: Cross-border regulations and harmonization
- **Future Regulations**: Anticipated regulatory changes and preparation strategies
{% elif area == "social" %}
#### Social Impact Assessment
- **Community Effects**: Local and global community implications
- **Cultural Considerations**: Cross-cultural sensitivity and adaptation
- **Public Opinion**: Social acceptance and public discourse analysis
- **Digital Divide**: Accessibility and inclusion considerations
- **Behavioral Change**: Individual and collective behavior modifications
{% elif area == "environmental" %}
#### Environmental Sustainability Analysis
- **Carbon Footprint**: Environmental impact and sustainability metrics
- **Resource Usage**: Energy consumption and resource optimization
- **Lifecycle Assessment**: End-to-end environmental impact evaluation
- **Green Alternatives**: Sustainable approaches and eco-friendly solutions
- **Regulatory Environment**: Environmental regulations and compliance
{% else %}
#### {{ area | title }} Framework
- **Core Principles**: Fundamental concepts and guiding principles
- **Key Considerations**: Critical factors and decision points
- **Impact Assessment**: Quantitative and qualitative impact evaluation
- **Risk Factors**: Potential challenges and mitigation strategies
- **Best Practices**: Industry standards and recommended approaches
{% endif %}

{% if not loop.last %}
---
{% endif %}
{% endfor %}

### Focus Area Integration Matrix
{% for area1 in focus_areas %}
{% for area2 in focus_areas %}
{% if area1 != area2 and loop.index0 < loop.index %}
- **{{ area1|title }} ↔ {{ area2|title }}**: Cross-dimensional analysis and synergy identification
{% endif %}
{% endfor %}
{% endfor %}
{% else %}
## 🔍 Standard Analysis Framework
1. **Contextual Overview** - Current state and background analysis
2. **Trend Identification** - Pattern recognition and trend analysis
3. **Impact Assessment** - Quantitative and qualitative impact evaluation
4. **Strategic Implications** - Long-term considerations and planning
5. **Actionable Recommendations** - Specific next steps and implementation guidance
{% endif %}

{% if format %}
## 📋 Output Format Specification: {{ format | title | replace("_", " ") }}
{% set format_specs = {
  "executive_summary": {
    "structure": "Executive Summary → Key Findings → Strategic Recommendations → Appendices",
    "length": "2-4 pages + supporting materials",
    "audience": "C-level executives, board members, and senior decision makers",
    "style": "Concise, decision-focused, high-level strategic content",
    "sections": ["Executive Overview", "Critical Insights", "Strategic Options", "Resource Requirements", "Timeline & Milestones"]
  },
  "technical_report": {
    "structure": "Technical Overview → Detailed Analysis → Implementation Guide → Technical Appendices",
    "length": "10-20 pages + technical documentation", 
    "audience": "Technical teams, engineers, and implementation specialists",
    "style": "Detailed, implementation-focused, technical depth",
    "sections": ["Technical Architecture", "Detailed Specifications", "Implementation Roadmap", "Technical Risks", "Testing & Validation"]
  },
  "presentation": {
    "structure": "Slide deck with executive summary, detailed findings, and action items",
    "length": "15-25 slides + speaker notes",
    "audience": "Mixed stakeholder groups and meeting presentations", 
    "style": "Visual, presentation-ready, engaging narrative",
    "sections": ["Problem Statement", "Analysis Overview", "Key Findings", "Recommendations", "Next Steps"]
  },
  "research_paper": {
    "structure": "Abstract → Introduction → Literature Review → Analysis → Discussion → Conclusions → References",
    "length": "15-30 pages + extensive bibliography",
    "audience": "Academic researchers, policy makers, and domain experts",
    "style": "Academic rigor, peer-review ready, comprehensive citations",
    "sections": ["Abstract", "Introduction", "Methodology", "Results & Analysis", "Discussion", "Conclusions", "Future Research"]
  }
} %}

{% set current_format = format_specs[format] if format in format_specs else format_specs["executive_summary"] %}

### Format Configuration
- **Structure**: {{ current_format.structure }}
- **Expected Length**: {{ current_format.length }}
- **Target Audience**: {{ current_format.audience }}
- **Writing Style**: {{ current_format.style }}

### Content Sections
{% for section in current_format.sections %}
{{ loop.index }}. **{{ section }}**
{% endfor %}

### Presentation Guidelines
{% if format == "executive_summary" %}
- Lead with bottom-line impact and recommendations
- Use bullet points and executive-friendly language
- Include financial implications and resource requirements
- Provide clear decision points and options
{% elif format == "technical_report" %}
- Include detailed technical specifications and diagrams
- Provide step-by-step implementation guidance
- Document technical dependencies and requirements
- Include testing procedures and validation methods
{% elif format == "presentation" %}
- Design slide-ready content with clear headings
- Include data visualizations and infographics
- Provide speaker notes and presentation guidance
- Structure for 30-45 minute presentation window
{% elif format == "research_paper" %}
- Follow academic formatting and citation standards
- Include comprehensive literature review and methodology
- Provide detailed statistical analysis and evidence
- Structure for peer review and academic publication
{% endif %}
{% endif %}

{% if previous_context %}
## 🔗 Building Upon Previous Analysis
**Previous Context Integration:**
{{ previous_context }}

### Continuity Framework
- **Historical Baseline**: Previous findings serve as analytical foundation
- **Evolutionary Analysis**: Changes and developments since last analysis
- **Gap Identification**: Areas requiring additional investigation
- **Trend Validation**: Confirmation or revision of previous predictions
{% endif %}

{% if requirements %}
## ✅ Specific Requirements & Success Criteria
{% for req in requirements %}
{% if req is string %}
{{ loop.index }}. {{ req }}
{% else %}
{{ loop.index }}. **{{ req.category | default("General Requirement") | title }}**: {{ req.description }}
   {% if req.priority %}
   - **Priority Level**: {{ req.priority | upper }}
   {% if req.priority == "critical" %}🔴 CRITICAL - Must be addressed in core analysis
   {% elif req.priority == "high" %}🟡 HIGH - Primary focus area
   {% elif req.priority == "medium" %}🟢 MEDIUM - Important but not critical
   {% else %}⚪ LOW - Include if time/resources permit{% endif %}
   {% endif %}
   {% if req.examples %}
   - **Examples**: {% for ex in req.examples %}{{ ex }}{% if not loop.last %}, {% endif %}{% endfor %}
   {% endif %}
   {% if req.success_criteria %}
   - **Success Criteria**: {{ req.success_criteria }}
   {% endif %}
{% endif %}
{% endfor %}

### Requirements Validation Matrix
{% for req in requirements %}
{% if req is not string and req.priority %}
- **{{ req.category | default("Requirement " + loop.index|string) }}** ({{ req.priority|upper }}): Validation method and acceptance criteria
{% endif %}
{% endfor %}
{% endif %}

---

## 🎯 Analysis Execution Framework

### Phase 1: Foundation & Context
- Establish analytical baseline and context
- Validate scope and constraints alignment
- Confirm data source accessibility and reliability

### Phase 2: Multi-Dimensional Investigation  
{% if focus_areas %}
{% for area in focus_areas %}
- **{{ area|title }} Analysis**: Deep-dive investigation and assessment
{% endfor %}
{% else %}
- Comprehensive investigation across all relevant dimensions
{% endif %}

### Phase 3: Integration & Synthesis
- Cross-dimensional pattern identification
- Insight synthesis and framework development
- Validation against requirements and constraints

### Phase 4: Recommendations & Implementation
- Strategic recommendation development
- Implementation pathway design
- Risk assessment and mitigation planning

---

**🚀 Analysis Request Summary:**
- **Topic**: {{ topic }}
- **Complexity**: {% if sources and focus_areas and constraints %}Maximum ({{ complexity_score }} complexity points){% elif focus_areas or constraints %}High{% else %}Standard{% endif %}
- **Expected Deliverable**: {{ format | default("Comprehensive Analysis") | title }}
- **Timeline**: {% if constraints.time_limit %}{{ constraints.time_limit }}{% else %}Standard delivery window{% endif %}

{% set template_features_used = [] %}
{% if sources %}{% set _ = template_features_used.append("Dynamic source configuration") %}{% endif %}
{% if focus_areas %}{% set _ = template_features_used.append("Multi-dimensional framework") %}{% endif %}
{% if constraints %}{% set _ = template_features_used.append("Constraint optimization") %}{% endif %}
{% if requirements %}{% set _ = template_features_used.append("Requirements validation") %}{% endif %}
{% if format %}{% set _ = template_features_used.append("Format specialization") %}{% endif %}

**🔧 Template Features Active**: {{ template_features_used | join(", ") | default("Standard template rendering") }}

---

Please provide a comprehensive analysis following the above specifications. Ensure all requested dimensions are covered, the output matches the specified format requirements, and the analysis demonstrates the full complexity and capability of this advanced template system.

```
Page 7/12FirstPrevNextLast