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

--------------------------------------------------------------------------------
/server/src/mcp-tools/prompt-engine/core/engine.ts:
--------------------------------------------------------------------------------

```typescript
/**
 * Consolidated Prompt Engine - Unified Execution Tool
 *
 * Consolidates all prompt execution functionality into a single systematic tool:
 * - execute_prompt (from index.ts)
 * - Chain execution with progress tracking
 * - Structural execution mode detection
 * - Gate validation and retry logic
 */

import path from "path";
import { z } from "zod";
import { ConfigManager } from "../../../config/index.js";
import { Logger } from "../../../logging/index.js";
import { PromptManager } from "../../../prompts/index.js";
import {
  ChainExecutionProgress,
  ConvertedPrompt,
  ExecutionState,
  GateDefinition,
  PromptData,
  ToolResponse,
} from "../../../types/index.js";
// Import enhanced gate configuration from execution types
import {
  type EnhancedGateConfiguration,
} from "../../../execution/types.js";
// REMOVED: ModularChainDefinition from deleted chain-scaffolding.ts
import {
  PromptError,
  ValidationError,
  getAvailableTools,
  isChainPrompt,
  handleError as utilsHandleError,
} from "../../../utils/index.js";
import { processTemplate } from "../../../utils/jsonUtils.js";
// Gate evaluation removed - now using Framework methodology validation
import { FrameworkManager } from "../../../frameworks/framework-manager.js";
import { FrameworkExecutionContext } from "../../../frameworks/types/index.js";
import { FrameworkStateManager } from "../../../frameworks/framework-state-manager.js";
import { ContentAnalyzer } from "../../../semantic/configurable-semantic-analyzer.js";
import { ConversationManager } from "../../../text-references/conversation.js";
import { TextReferenceManager } from "../../../text-references/index.js";
import { ChainSessionManager, createChainSessionManager } from "../../../chain-session/manager.js";
import { createExecutionResponse } from "../../shared/structured-response-builder.js";
// Legacy gate system removed - using lightweight gates only
// NEW: Lightweight gate system
import {
  LightweightGateSystem,
  createLightweightGateSystem,
  type TemporaryGateRegistryDefinition as TemporaryGateDefinition,
} from "../../../gates/core/index.js";
// NEW: Role-based gate components (Phase 3)
import {
  GateGuidanceRenderer,
  createGateGuidanceRenderer,
} from "../../../gates/guidance/GateGuidanceRenderer.js";
// Gate validation integration
import {
  EngineValidator,
  GateValidationResult,
} from "../utils/validation.js";
// Phase 4: Clean architecture gate intelligence (replaced advanced orchestrator)
import {
  GateSelectionEngine,
  createGateSelectionEngine,
  ExtendedGateSelectionCriteria,
} from "../../../gates/intelligence/GateSelectionEngine.js";
import {
  GateSelectionResult,
} from "../../../gates/core/gate-definitions.js";
// Phase 1: Intelligent category detection
import {
  CategoryExtractor,
  extractPromptCategory,
  CategoryExtractionResult
} from "../utils/category-extractor.js";
// Phase 3: Prompt guidance system integration
import {
  PromptGuidanceService,
  createPromptGuidanceService,
  type ServicePromptGuidanceResult
} from "../../../frameworks/prompt-guidance/index.js";
// REMOVED: ChainOrchestrator and detectChainType/isModularChain - modular chain system completely removed
// REMOVED: Chain URI addressing system - deprecated with markdown-embedded chains
// New unified parsing system
import {
  createParsingSystem,
  type ExecutionContext,
  type ParsingSystem,
} from "../../../execution/parsers/index.js";
// REMOVED: Dynamic template discovery - scaffolding system deprecated
// Tool description manager
import { ToolDescriptionManager } from "../../tool-description-manager.js";
// Chain execution separation
import { ChainExecutor } from "./executor.js";
import { ChainExecutionContext, ChainExecutionOptions } from "./types.js";
// Enhanced tool dependencies removed (Phase 1.3) - Core implementations
// Simple core response handling without enhanced complexity
interface SimpleResponseFormatter {
  formatResponse(content: any): any;
  formatPromptEngineResponse(response: any, ...args: any[]): any; // Required
  formatErrorResponse(error: any, ...args: any[]): any; // Required
  setAnalyticsService(service: any): void; // Required
}

function createSimpleResponseFormatter(): SimpleResponseFormatter {
  return {
    formatResponse: (content: any) => content,
    formatPromptEngineResponse: (response: any, ...args: any[]) => {
      // Create proper ToolResponse with structuredContent using shared builder
      const executionContext = args[0] || {};
      const options = args[1] || {};

      // For template/prompt execution, return simple text so Claude Code can see instructions
      // For chain execution, keep structured content for state tracking
      const executionType = executionContext.executionType || "prompt";
      const includeStructuredContent = executionType === "chain";

      return createExecutionResponse(
        String(response),
        "execute",
        {
          executionType,
          executionTime: executionContext.executionTime,
          frameworkUsed: executionContext.frameworkUsed,
          stepsExecuted: executionContext.stepsExecuted,
          sessionId: executionContext.sessionId,
          gateResults: executionContext.gateResults
        },
        includeStructuredContent
      );
    },
    formatErrorResponse: (error: any, ...args: any[]) => {
      return createExecutionResponse(
        String(error),
        "error",
        {
          executionType: "prompt",
          executionTime: 0,
          frameworkUsed: undefined,
          stepsExecuted: 0,
          sessionId: undefined
        }
      );
    },
    setAnalyticsService: (service: any) => {}, // No-op for now
  };
}

// Simple output schema (minimal for Phase 1)
const promptEngineOutputSchema = {
  content: { type: "array" },
  isError: { type: "boolean", optional: true },
};

// Type aliases for compatibility
type ResponseFormatter = SimpleResponseFormatter;
const createResponseFormatter = createSimpleResponseFormatter;
type FormatterExecutionContext = {
  [key: string]: any; // Completely flexible for Phase 1
};
// Analytics service
import { ExecutionData, MetricsCollector } from "../../../metrics/index.js";

/**
 * Prompt classification interface for execution strategy
 */
export interface PromptClassification {
  executionType: "prompt" | "template" | "chain";
  requiresExecution: boolean;
  confidence: number;
  reasoning: string[];
  suggestedGates: string[];
  framework?: string;
}

/**
 * Tool routing detection result interface
 */
interface ToolRoutingResult {
  requiresRouting: boolean;
  targetTool?: string;
  translatedParams?: Record<string, any>;
  originalCommand?: string;
}

/**
 * Consolidated Prompt Engine Tool
 */
export class ConsolidatedPromptEngine {
  private logger: Logger;
  private mcpServer: any;
  private promptManager: PromptManager;
  private configManager: ConfigManager;
  private readonly serverRoot: string;
  private semanticAnalyzer: ContentAnalyzer;
  private conversationManager: ConversationManager;
  private textReferenceManager: TextReferenceManager;
  private chainSessionManager: ChainSessionManager;
  private frameworkStateManager?: FrameworkStateManager;
  private frameworkManager?: FrameworkManager;
  // Legacy gate system removed - using only lightweightGateSystem
  // NEW: Lightweight gate system (Phase 2 integration)
  private lightweightGateSystem: LightweightGateSystem;
  // NEW: Temporary gate registry access (Phase 3 enhancement)
  private get temporaryGateRegistry() {
    return this.lightweightGateSystem.getTemporaryGateRegistry?.();
  }
  // NEW: Role-based gate guidance renderer (Phase 3)
  private gateGuidanceRenderer: GateGuidanceRenderer;
  // Gate validation engine
  private engineValidator?: EngineValidator;
  // Phase 4: Clean architecture gate intelligence
  private gateSelectionEngine?: GateSelectionEngine;
  // Chain execution delegation
  private chainExecutor?: ChainExecutor;
  // REMOVED: chainOrchestrator - modular chain system removed
  // Chain URI addressing system
  // REMOVED: chainAddressingSystem - deprecated with markdown-embedded chains

  // MCP Tools Manager reference for analytics flow
  private mcpToolsManager?: any;

  // Analytics service for event-driven analytics collection
  private analyticsService?: MetricsCollector;

  // Response formatter for structured output
  private responseFormatter: ResponseFormatter;

  // New unified parsing system
  private parsingSystem: ParsingSystem;

  // Dynamic template discovery system
  // REMOVED: dynamicTemplateDiscovery - scaffolding system deprecated

  // Tool description manager
  private toolDescriptionManager?: ToolDescriptionManager;

  // Phase 3: Prompt guidance service
  private promptGuidanceService?: PromptGuidanceService;

  private activeGateRequest?: {
    gateIds: string[];
    gateMode: 'enforce' | 'advise' | 'report';
    qualityGates: string[];
    customChecks: Array<{ name: string; description: string }>;
    executionScopeId?: string;
  };

  // Data references
  private promptsData: PromptData[] = [];
  private convertedPrompts: ConvertedPrompt[] = [];

  // Execution state tracking
  private currentExecutionState: ExecutionState | null = null;
  private executionHistory: ExecutionState[] = [];
  private chainProgressState: ChainExecutionProgress | null = null;

  constructor(
    logger: Logger,
    mcpServer: any,
    promptManager: PromptManager,
    configManager: ConfigManager,
    semanticAnalyzer: ContentAnalyzer,
    conversationManager: ConversationManager,
    textReferenceManager: TextReferenceManager,
    // Legacy gateEvaluationService parameter removed - using lightweight system only
    mcpToolsManager?: any
    // Phase 3: Removed executionCoordinator parameter - no longer needed
  ) {
    this.logger = logger;
    this.mcpServer = mcpServer;
    this.promptManager = promptManager;
    this.configManager = configManager;
    this.semanticAnalyzer = semanticAnalyzer;
    this.conversationManager = conversationManager;
    this.textReferenceManager = textReferenceManager;

    // Initialize chain session manager with both conversation and text reference managers
    this.chainSessionManager = createChainSessionManager(logger, conversationManager, textReferenceManager);

    // Legacy gate evaluation service assignment removed
    this.mcpToolsManager = mcpToolsManager;
    // Phase 3: Removed executionCoordinator assignment - using LLM-driven chain model

    // Initialize lightweight gate system with temporary gates (Phase 3 enhancement)
    const config = configManager.getConfig();
    const gatesConfig = config.gates;
    const configRoot =
      typeof this.configManager.getServerRoot === 'function'
        ? this.configManager.getServerRoot()
        : path.dirname(this.configManager.getConfigPath?.() ?? path.join(process.cwd(), 'config.json'));
    this.serverRoot = configRoot;

    const gatesDirectory = gatesConfig?.definitionsDirectory
      ? path.isAbsolute(gatesConfig.definitionsDirectory)
        ? gatesConfig.definitionsDirectory
        : path.resolve(configRoot, gatesConfig.definitionsDirectory)
      : path.resolve(configRoot, 'src/gates/definitions');

    // Get LLM config for gate validator
    const llmConfig = config.analysis?.semanticAnalysis?.llmIntegration;

    this.lightweightGateSystem = createLightweightGateSystem(
      logger,
      gatesDirectory,
      undefined, // gateSystemManager - will be set later if needed
      {
        enableTemporaryGates: true,
        maxMemoryGates: 100, // Allow up to 100 temporary gates in memory
        defaultExpirationMs: 30 * 60 * 1000, // 30 minutes default expiration
        llmConfig // Pass LLM config to gate validator
      }
    );

    // NEW: Initialize role-based gate guidance renderer (Phase 3)
    // Phase 3 Enhancement: Pass temporary gate registry to renderer for temp gate support
    const temporaryGateRegistry = this.lightweightGateSystem.getTemporaryGateRegistry();
    this.gateGuidanceRenderer = createGateGuidanceRenderer(
      logger,
      gatesDirectory,
      temporaryGateRegistry
    );

    // Initialize EngineValidator with gate system (Phase 1.1 fix)
    this.engineValidator = new EngineValidator(this.lightweightGateSystem);

    // Phase 4: Initialize clean architecture gate intelligence
    this.gateSelectionEngine = createGateSelectionEngine(logger);

    // Note: Performance analytics now handled separately through system control
    // No need to connect gate selection engine to other components

    // Initialize new parsing system
    this.parsingSystem = createParsingSystem(logger);

    // Initialize dynamic template discovery
    // REMOVED: Dynamic template discovery initialization - scaffolding system deprecated

    // Initialize response formatter
    this.responseFormatter = createResponseFormatter();

    this.logger.info(
      "ConsolidatedPromptEngine initialized with new unified parsing system, dynamic template discovery, and response formatter"
    );
  }

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

  /**
   * Set framework state manager (called after initialization)
   */
  setFrameworkStateManager(frameworkStateManager: FrameworkStateManager): void {
    this.frameworkStateManager = frameworkStateManager;
    this.initializeChainExecutor();
  }

  /**
   * Set framework manager (called after initialization)
   */
  setFrameworkManager(frameworkManager: FrameworkManager): void {
    this.frameworkManager = frameworkManager;
    this.initializeChainExecutor();
    this.initializePromptGuidanceService();
  }

  /**
   * Initialize ChainExecutor once dependencies are available
   */
  private initializeChainExecutor(): void {
    if (this.frameworkManager && this.frameworkStateManager) {
      this.chainExecutor = new ChainExecutor(
        this.conversationManager,
        this.lightweightGateSystem,
        this.frameworkManager,
        this.frameworkStateManager,
        this.responseFormatter,
        this.chainSessionManager
      );
      this.logger.debug("ChainExecutor initialized successfully");
    }
  }

  /**
   * Initialize PromptGuidanceService once framework manager is available
   */
  private async initializePromptGuidanceService(): Promise<void> {
    if (this.frameworkManager && !this.promptGuidanceService) {
      try {
        const methodologyStatePath = path.join(
          this.serverRoot,
          'runtime-state',
          'framework-state.json'
        );

        this.promptGuidanceService = await createPromptGuidanceService(
          this.logger,
          {
            systemPromptInjection: {
              enabled: true,
              injectionMethod: 'smart',
              enableTemplateVariables: true,
              enableContextualEnhancement: true
            },
            templateEnhancement: {
              enabled: true,
              enhancementLevel: 'moderate',
              enableArgumentSuggestions: true,
              enableStructureOptimization: true
            },
            methodologyTracking: {
              enabled: true,
              persistStateToDisk: true,
              enableHealthMonitoring: true,
              stateFilePath: methodologyStatePath
            }
          },
          this.frameworkManager
        );
        this.logger.debug("PromptGuidanceService initialized successfully");
      } catch (error) {
        this.logger.warn("Failed to initialize PromptGuidanceService:", error);
        // Continue without guidance service - it's optional
      }
    }
  }

  /**
   * Set analytics service (called after initialization)
   */
  setAnalyticsService(analyticsService: MetricsCollector): void {
    this.analyticsService = analyticsService;
    this.responseFormatter.setAnalyticsService(analyticsService);
  }

  /**
   * Set tool description manager (called after initialization)
   */
  setToolDescriptionManager(manager: ToolDescriptionManager): void {
    this.toolDescriptionManager = manager;
  }

  /**
   * Get the prompts base path using ConfigManager for cross-platform compatibility
   */
  private getPromptsBasePath(): string {
    // Use environment variable override if available
    if (process.env.MCP_PROMPTS_PATH) {
      return process.env.MCP_PROMPTS_PATH;
    }

    // Use ConfigManager to get proper path resolution
    const promptsFilePath = this.configManager.getPromptsFilePath();
    // Get the directory containing the prompts config file
    return path.dirname(promptsFilePath);
  }

  // REMOVED: setChainOrchestrator method - modular chain system removed

  /**
   * Get lightweight gate system for external access
   */
  getLightweightGateSystem(): LightweightGateSystem {
    return this.lightweightGateSystem;
  }

  /**
   * Expose gate guidance renderer for discovery operations
   */
  getGateGuidanceRenderer(): GateGuidanceRenderer {
    return this.gateGuidanceRenderer;
  }

  /**
   * Set gate system manager for runtime gate management
   */
  setGateSystemManager(gateSystemManager: any): void {
    this.lightweightGateSystem.setGateSystemManager(gateSystemManager);
    this.logger.debug("Gate system manager configured for prompt engine");
  }

  /**
   * Get framework-enhanced system prompt injection
   */
  private async getFrameworkExecutionContext(
    prompt: ConvertedPrompt
  ): Promise<FrameworkExecutionContext | null> {
    this.logger.debug(`[ENGINE DEBUG] getFrameworkExecutionContext called for prompt: ${prompt.id}`);

    if (!this.frameworkManager || !this.frameworkStateManager) {
      this.logger.debug(`[ENGINE DEBUG] Missing dependencies - frameworkManager: ${!!this.frameworkManager}, frameworkStateManager: ${!!this.frameworkStateManager}`);
      return null;
    }

    // NEW: Check if framework system is enabled before generating context
    const isEnabled = this.frameworkStateManager.isFrameworkSystemEnabled();
    this.logger.debug(`[ENGINE DEBUG] Framework system enabled: ${isEnabled}`);
    if (!isEnabled) {
      return null;
    }

    try {
      // Get current active framework from state manager
      const activeFramework = this.frameworkStateManager.getActiveFramework();
      this.logger.debug(`[ENGINE DEBUG] Active framework:`, {
        methodology: activeFramework.methodology,
        name: activeFramework.name
      });

      // Generate execution context using the framework manager
      const context = this.frameworkManager.generateExecutionContext(prompt, {
        userPreference: activeFramework.methodology as any,
      });

      this.logger.debug(`[ENGINE DEBUG] Generated execution context:`, {
        hasContext: !!context,
        contextType: context ? typeof context : 'null',
        hasSystemPrompt: context?.systemPrompt ? true : false,
        systemPromptLength: context?.systemPrompt?.length || 0
      });

      return context;
    } catch (error) {
      this.logger.warn(
        "Failed to generate framework execution context:",
        error
      );
      return null;
    }
  }


  /**
   * Main prompt execution handler
   */
  public async executePromptCommand(
    args: {
      command: string;
      execution_mode?: "auto" | "prompt" | "template" | "chain";
      gate_validation?: boolean;
      step_confirmation?: boolean;
      llm_driven_execution?: boolean;
      force_restart?: boolean;
      session_id?: string;
      chain_uri?: string;
      timeout?: number;
      options?: Record<string, any>;
      temporary_gates?: TemporaryGateDefinition[];
      gate_scope?: 'execution' | 'session' | 'chain' | 'step';
      inherit_chain_gates?: boolean;
      quality_gates?: string[];
      custom_checks?: Array<{ name: string; description: string }>;
      gate_mode?: 'enforce' | 'advise' | 'report';
    },
    extra: any
  ): Promise<ToolResponse> {
    const {
      command,
      execution_mode = "auto",
      gate_validation,
      step_confirmation,
      llm_driven_execution,
      force_restart,
      session_id,
      chain_uri,
      timeout,
      options = {},
      temporary_gates,
      gate_scope = 'execution',
      inherit_chain_gates = true,
      quality_gates,
      custom_checks,
      gate_mode,
    } = args;

    const hasSimplifiedGates =
      (quality_gates?.length ?? 0) > 0 || (custom_checks?.length ?? 0) > 0;
    const resolvedGateMode: 'enforce' | 'advise' | 'report' =
      gate_mode ?? (hasSimplifiedGates ? 'enforce' : 'advise');

    const normalizedArgs = {
      ...args,
      gate_mode: resolvedGateMode,
      quality_gates,
      custom_checks,
    };

    this.logger.info(
      `🚀 [ENTRY] Prompt Engine: Executing "${command}" (mode: ${execution_mode})`
    );

    // Phase 1: Check if command should be routed to a different tool
    const routingResult = await this.detectToolRoutingCommand(command);
    this.logger.info(`🔍 [ROUTING DEBUG] Tool routing check:`, {
      command,
      requiresRouting: routingResult.requiresRouting,
      targetTool: routingResult.targetTool
    });

    if (routingResult.requiresRouting) {
      this.logger.info(`🔀 [ROUTING DEBUG] Command being routed to different tool: ${routingResult.targetTool}`);
      const routedResult = await this.routeToTool(
        routingResult.targetTool!,
        routingResult.translatedParams!,
        routingResult.originalCommand!
      );
      return routedResult;
    }

    // Parse command and extract execution context
    const executionContext = await this.parseAndPrepareExecution(command);

    // Handle chain management commands
    if (executionContext.isChainManagement && this.chainExecutor) {
      return await this.chainExecutor.executeChainManagement(
        executionContext.chainAction!,
        executionContext.chainParameters || {},
        options
      );
    }

    // Determine execution strategy
    const strategy = await this.determineExecutionStrategy(
      executionContext.convertedPrompt,
      execution_mode,
      {
        gate_validation,
        quality_gates,
        custom_checks,
      }
    );

    // Initialize execution state with session tracking
    this.initializeExecutionState(
      executionContext.convertedPrompt,
      strategy,
      session_id
    );

    // Execute using determined strategy
    return await this.executeWithStrategy(strategy, executionContext, {
      ...normalizedArgs,
      gate_validation,
      step_confirmation,
      llm_driven_execution,
      force_restart,
      session_id,
      chain_uri,
      timeout,
      options,
    });
  }

  /**
   * Parse command and prepare execution context
   */
  private async parseAndPrepareExecution(command: string) {
    const {
      promptId,
      arguments: promptArgs,
      convertedPrompt,
      isChainManagement,
      chainAction,
      chainParameters,
    } = await this.parseCommandUnified(command);

    // Apply prompt guidance if available and not a chain management command
    let enhancedPrompt = convertedPrompt;
    let guidanceResult: ServicePromptGuidanceResult | undefined;

    // FIXED: Re-enable PromptGuidanceService with system prompt injection only
    // This provides framework methodology reminder at the START of responses
    // Gate guidance (framework-compliance) provides quality criteria at the END
    if (!isChainManagement && this.promptGuidanceService && convertedPrompt) {
      try {
        this.logger.info(`🔧 [FRAMEWORK DEBUG] Calling PromptGuidanceService for ${convertedPrompt.id}`, {
          hasPromptGuidanceService: !!this.promptGuidanceService,
          isInitialized: this.promptGuidanceService.isInitialized(),
          originalSystemMessage: convertedPrompt.systemMessage?.substring(0, 100)
        });

        guidanceResult = await this.promptGuidanceService.applyGuidance(convertedPrompt, {
          includeSystemPromptInjection: true,   // ENABLED: Framework reminder at beginning
          includeTemplateEnhancement: false     // DISABLED: Prevent template duplication
        });

        this.logger.info(`🔧 [FRAMEWORK DEBUG] PromptGuidanceService result:`, {
          guidanceApplied: guidanceResult.guidanceApplied,
          hasEnhancedPrompt: !!guidanceResult.enhancedPrompt,
          enhancementsApplied: guidanceResult.metadata.enhancementsApplied,
          enhancedSystemMessage: guidanceResult.enhancedPrompt?.systemMessage?.substring(0, 200)
        });

        if (guidanceResult.guidanceApplied && guidanceResult.enhancedPrompt) {
          enhancedPrompt = guidanceResult.enhancedPrompt;
          this.logger.info(`✅ [FRAMEWORK DEBUG] Prompt guidance applied: ${guidanceResult.metadata.enhancementsApplied.join(', ')}`);
        } else {
          this.logger.warn(`⚠️ [FRAMEWORK DEBUG] Guidance not applied - guidanceApplied=${guidanceResult.guidanceApplied}, hasEnhancedPrompt=${!!guidanceResult.enhancedPrompt}`);
        }
      } catch (error) {
        this.logger.error("❌ [FRAMEWORK DEBUG] Prompt guidance failed:", error);
      }
    } else {
      this.logger.warn(`⚠️ [FRAMEWORK DEBUG] Skipping PromptGuidanceService:`, {
        isChainManagement,
        hasService: !!this.promptGuidanceService,
        hasPrompt: !!convertedPrompt
      });
    }

    return {
      promptId,
      promptArgs,
      convertedPrompt: enhancedPrompt,
      originalPrompt: convertedPrompt,
      guidanceResult,
      isChainManagement,
      chainAction,
      chainParameters,
    };
  }

  /**
   * Determine the execution strategy based on mode and prompt type
   */
  private async determineExecutionStrategy(
    convertedPrompt: any,
    execution_mode: string,
    overrides?: {
      gate_validation?: boolean;
      quality_gates?: string[];
      custom_checks?: Array<{ name: string; description: string }>;
    }
  ): Promise<{
    mode: "prompt" | "template" | "chain";
    gateValidation: boolean;
  }> {
    let effectiveExecutionMode: "prompt" | "template" | "chain";

    if (!execution_mode || execution_mode === "auto") {
      const detectedMode = await this.detectExecutionMode(convertedPrompt);
      effectiveExecutionMode = detectedMode as "prompt" | "template" | "chain";
    } else {
      effectiveExecutionMode = execution_mode as
        | "prompt"
        | "template"
        | "chain";
    }

    const hasSimplifiedGates =
      (overrides?.quality_gates?.length ?? 0) > 0 ||
      (overrides?.custom_checks?.length ?? 0) > 0;

    const effectiveGateValidation =
      overrides?.gate_validation ??
      (hasSimplifiedGates ? true : effectiveExecutionMode === "chain");

    this.logger.info(
      `🔍 EXECUTION MODE DEBUG: Effective settings: mode=${effectiveExecutionMode}, gates=${effectiveGateValidation}, prompt=${convertedPrompt.id}, simplifiedGates=${hasSimplifiedGates}`
    );

    return {
      mode: effectiveExecutionMode,
      gateValidation: effectiveGateValidation,
    };
  }

  /**
   * Initialize execution state tracking with session support
   */
  private initializeExecutionState(
    convertedPrompt: any,
    strategy: { mode: string; gateValidation: boolean },
    sessionId?: string
  ) {
    this.currentExecutionState = {
      type: isChainPrompt(convertedPrompt) ? "chain" : "single",
      promptId: convertedPrompt.id,
      status: "pending",
      gates: [],
      results: {},
      metadata: {
        startTime: Date.now(),
        executionMode: strategy.mode as "prompt" | "template" | "chain",
        gateValidation: strategy.gateValidation,
        sessionId, // Store session ID for step result capture
      },
    };
  }

  /**
   * Execute using the determined strategy
   */
  private async executeWithStrategy(
    strategy: {
      mode: "prompt" | "template" | "chain";
      gateValidation: boolean;
    },
    context: any,
    args: any
  ): Promise<ToolResponse> {
    const { convertedPrompt, promptArgs } = context;

    // Phase 3: Create execution scope for temporary gates
    const executionScopeId = this.createExecutionScope(convertedPrompt, strategy, args);

    try {

    switch (strategy.mode) {
      case "prompt":
        this.logger.info(
          `📍 EXECUTION PATH: Taking PROMPT path for ${convertedPrompt.id}`
        );
        const promptResult = await this.executePrompt(
          convertedPrompt,
          promptArgs,
          this.getExecutionContext(executionScopeId, 'execution')
        );
        return promptResult;

      case "template":
        this.logger.info(
          `📍 EXECUTION PATH: Taking TEMPLATE path for ${convertedPrompt.id}`
        );
        const templateResult = await this.executeTemplateWithFramework(
          convertedPrompt,
          promptArgs,
          strategy.gateValidation,
          this.getExecutionContext(executionScopeId, 'execution')
        );
        return templateResult;

      case "chain":
        this.logger.info(
          `📍 EXECUTION PATH: Taking CHAIN path for ${convertedPrompt.id}`
        );
        if (!this.chainExecutor) {
          return this.responseFormatter.formatErrorResponse(
            'ChainExecutor not initialized - framework managers required',
            'ConsolidatedPromptEngine',
            'executePromptCommand'
          );
        }

        // Ensure chain session exists
        const chainSessionId = await this.ensureChainSession(
          convertedPrompt,
          args.session_id,
          args.force_restart,
          promptArgs
        );

        return await this.chainExecutor.executeChainWithDualSupport(
          convertedPrompt,
          promptArgs,
          strategy.gateValidation,
          {
            enableGates: strategy.gateValidation,
            force_restart: args.force_restart,
            session_id: chainSessionId,
            step_confirmation: args.step_confirmation,
            llm_driven_execution: args.llm_driven_execution,
            chain_uri: args.chain_uri,
            timeout: args.timeout,
            temporary_gates: args.temporary_gates,
            gate_scope: args.gate_scope,
            inherit_chain_gates: args.inherit_chain_gates,
            ...args.options,
          }
        );

      default:
        throw new ValidationError(`Unknown execution mode: ${strategy.mode}`);
    }

    } finally {
      // Phase 3: Cleanup execution scope and temporary gates
      this.cleanupExecutionScope(executionScopeId);
    }
  }

  /**
   * Phase 3: Create execution scope for temporary gate lifecycle management
   * Phase 4: Enhanced with execution-time temporary gate support
   */
  private createExecutionScope(
    convertedPrompt: any,
    strategy: { mode: string; gateValidation: boolean },
    args: any
  ): string {
    const scopeId = `exec_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;

    this.logger.info(`🔧 [EXECUTION SCOPE] Created execution scope:`, {
      scopeId,
      promptId: convertedPrompt?.id,
      mode: strategy.mode,
      gateValidation: strategy.gateValidation,
      sessionId: args.session_id,
      hasExecutionTimeGates: !!args.temporary_gates,
      executionTimeGateCount: args.temporary_gates?.length || 0
    });

    // Create execution-time temporary gates if provided
    if (args.temporary_gates && args.temporary_gates.length > 0 && this.temporaryGateRegistry) {
      const gateScope = args.gate_scope || 'execution';
      this.logger.info(`🚀 [EXECUTION-TIME GATES] Creating ${args.temporary_gates.length} execution-time temporary gates`, {
        scope: gateScope,
        scopeId
      });

      for (const tempGate of args.temporary_gates) {
        try {
          const gateId = this.temporaryGateRegistry.createTemporaryGate(
            {
              name: tempGate.name,
              type: tempGate.type,
              scope: gateScope,
              description: tempGate.description,
              guidance: tempGate.guidance,
              pass_criteria: tempGate.pass_criteria,
              source: 'manual',
              context: { executionTimeGate: true, promptId: convertedPrompt?.id }
            },
            scopeId
          );

          this.logger.debug(`✅ [EXECUTION-TIME GATES] Created temporary gate: ${gateId} (${tempGate.name})`);
        } catch (error) {
          this.logger.error(`❌ [EXECUTION-TIME GATES] Failed to create temporary gate:`, {
            error: error instanceof Error ? error.message : String(error),
            gateName: tempGate.name
          });
        }
      }
    }

    const simplifiedGateIds = this.convertSimplifiedGates(
      args.quality_gates,
      args.custom_checks,
      scopeId
    );

    const hasSimplifiedGates =
      (args.quality_gates?.length ?? 0) > 0 ||
      (args.custom_checks?.length ?? 0) > 0;

    if (hasSimplifiedGates || args.gate_mode) {
      const gateMode = (args.gate_mode as 'enforce' | 'advise' | 'report') || 'advise';
      this.activeGateRequest = {
        gateIds: simplifiedGateIds,
        gateMode,
        qualityGates: args.quality_gates || [],
        customChecks: args.custom_checks || [],
        executionScopeId: scopeId,
      };
    } else {
      this.activeGateRequest = undefined;
    }

    return scopeId;
  }

  /**
   * Phase 3: Cleanup execution scope and associated temporary gates
   */
  private cleanupExecutionScope(scopeId: string): void {
    if (this.temporaryGateRegistry) {
      this.temporaryGateRegistry.cleanupScope(scopeId);
      this.logger.info(`🧹 [EXECUTION SCOPE] Cleaned up execution scope: ${scopeId}`);
    } else {
      this.logger.debug(`🧹 [EXECUTION SCOPE] No temporary gate registry available for cleanup: ${scopeId}`);
    }

    if (this.activeGateRequest?.executionScopeId === scopeId) {
      this.activeGateRequest = undefined;
    }
  }

  private convertSimplifiedGates(
    qualityGates?: string[],
    customChecks?: Array<{ name: string; description: string }>,
    executionScopeId?: string
  ): string[] {
    const gateIds: string[] = [];

    if (qualityGates && qualityGates.length > 0) {
      gateIds.push(...qualityGates);
    }

    if (customChecks && customChecks.length > 0) {
      if (!this.temporaryGateRegistry) {
        this.logger.warn(
          "Temporary gate registry unavailable; custom checks cannot be registered"
        );
      } else {
        for (const check of customChecks) {
          try {
            const gateId = this.temporaryGateRegistry.createTemporaryGate(
              {
                name: check.name,
                type: 'validation',
                scope: 'execution',
                description: check.description,
                guidance: `Ensure: ${check.description}`,
                pass_criteria: [],
                source: 'manual',
              },
              executionScopeId
            );

            gateIds.push(gateId);
          } catch (error) {
            this.logger.error(
              `Failed to create temporary gate for custom check ${check.name}:`,
              error
            );
          }
        }
      }
    }

    return gateIds;
  }

  private mergeRequestedGates(gates: string[]): string[] {
    const requested = this.activeGateRequest?.gateIds || [];
    if (!requested.length) {
      return gates;
    }

    const combined = [...requested, ...gates];
    return [...new Set(combined)];
  }

  private formatGateStatus(validation: GateValidationResult | null): string {
    if (!validation) {
      if (this.activeGateRequest?.gateMode === 'report') {
        return `\n\n---\nℹ️ **Quality Gates**: Validation not executed\n`;
      }
      return '';
    }

    const total = validation.results?.length ?? 0;

    if (validation.passed) {
      return `\n\n---\n✅ **Quality Gates**: All checks passed (${total} gates)\n`;
    }

    const failed = (validation.results || []).filter((result) => !result.passed);
    let message = `\n\n---\n⚠️ **Quality Gates**: ${failed.length} of ${total} failed\n\n`;

    for (const result of failed) {
      message += `❌ **${result.gate}**: ${result.message}\n`;
    }

    return message;
  }

  /**
   * Phase 3: Get execution context for temporary gates
   */
  private getExecutionContext(scopeId: string, scope: 'execution' | 'session' | 'chain' | 'step' = 'execution') {
    return {
      scopeId,
      scope
    };
  }

  /**
   * Phase 3: Extract temporary gates from prompt configuration
   */
  private getTemporaryGatesFromPrompt(prompt: ConvertedPrompt): Array<Omit<TemporaryGateDefinition, 'id' | 'created_at'>> | undefined {
    // Phase 3 Fix: Check enhancedGateConfiguration first, then fall back to gateConfiguration
    const gateConfig = (prompt.enhancedGateConfiguration || prompt.gateConfiguration) as EnhancedGateConfiguration | undefined;
    if (!gateConfig?.temporary_gates) {
      return undefined;
    }

    return gateConfig.temporary_gates.map((tempGate: any) => ({
      name: tempGate.name,
      type: tempGate.type,
      scope: tempGate.scope,
      description: tempGate.description,
      guidance: tempGate.guidance,
      pass_criteria: tempGate.pass_criteria,
      expires_at: tempGate.expires_at,
      source: tempGate.source || 'manual',
      context: tempGate.context
    }));
  }

  /**
   * Phase 1: Chain Management Command Detection
   */

  // REMOVED: detectChainManagementCommand - migrated to ChainExecutor

  // REMOVED: parseKeyValueParams - migrated to ChainExecutor

  // REMOVED: handleChainManagementCommand - migrated to ChainExecutor

  /**
   * Detect if command should be routed to a different tool
   */
  private async detectToolRoutingCommand(command: string): Promise<ToolRoutingResult> {
    const trimmedCommand = command.trim();

    // Built-in commands that route to prompt_manager
    if (/^(>>|\/)?listprompts?(\s.*)?$/i.test(trimmedCommand)) {
      const args = trimmedCommand.replace(/^(>>|\/)?listprompts?\s*/i, '').trim();
      return {
        requiresRouting: true,
        targetTool: 'prompt_manager',
        translatedParams: {
          action: 'list',
          ...(args && { search_query: args })
        },
        originalCommand: command
      };
    }

    // Help and status commands that route to system_control
    if (/^(>>|\/)?help$/i.test(trimmedCommand)) {
      return {
        requiresRouting: true,
        targetTool: 'system_control',
        translatedParams: {
          action: 'status',
          show_details: true
        },
        originalCommand: command
      };
    }

    if (/^(>>|\/)?status$/i.test(trimmedCommand)) {
      return {
        requiresRouting: true,
        targetTool: 'system_control',
        translatedParams: {
          action: 'status'
        },
        originalCommand: command
      };
    }

    // Framework switch commands
    const frameworkMatch = trimmedCommand.match(/^(>>|\/)?framework\s+(switch|change)\s+(.+)$/i);
    if (frameworkMatch) {
      return {
        requiresRouting: true,
        targetTool: 'system_control',
        translatedParams: {
          action: 'framework',
          operation: 'switch',
          framework: frameworkMatch[3].trim()
        },
        originalCommand: command
      };
    }

    // Analytics/metrics commands
    if (/^(>>|\/)?analytics?$/i.test(trimmedCommand)) {
      return {
        requiresRouting: true,
        targetTool: 'system_control',
        translatedParams: {
          action: 'analytics'
        },
        originalCommand: command
      };
    }

    // No routing needed - let existing parser handle it
    return {
      requiresRouting: false
    };
  }

  /**
   * Route command to appropriate tool with safe error handling
   */
  private async routeToTool(targetTool: string, params: Record<string, any>, originalCommand: string): Promise<ToolResponse> {
    this.logger.info(`🔀 Routing command "${originalCommand}" to ${targetTool}`);

    try {
      switch (targetTool) {
        case 'prompt_manager':
          if (this.mcpToolsManager?.promptManagerTool) {
            this.logger.debug(`Calling prompt_manager with params:`, params);
            return await this.mcpToolsManager.promptManagerTool.handleAction(params, {});
          } else {
            throw new Error('Prompt manager tool not available');
          }

        case 'system_control':
          if (this.mcpToolsManager?.systemControl) {
            this.logger.debug(`Calling system_control with params:`, params);
            return await this.mcpToolsManager.systemControl.handleAction(params, {});
          } else {
            throw new Error('System control tool not available');
          }

        default:
          throw new Error(`Unknown target tool: ${targetTool}`);
      }
    } catch (error) {
      this.logger.error(`Tool routing failed for ${targetTool}:`, error);

      // Return formatted error response
      return this.responseFormatter.formatErrorResponse(
        error instanceof Error
          ? `Tool routing failed: ${error.message}`
          : `Tool routing failed: ${String(error)}`,
        {
          tool: 'prompt_engine',
          operation: 'routeToTool',
          targetTool,
          originalCommand
        },
        {
          includeStructuredData: true
        }
      );
    }
  }

  /**
   * Parse command string using unified parsing system with chain management detection
   */
  private async parseCommandUnified(command: string): Promise<{
    promptId: string;
    arguments: Record<string, any>;
    convertedPrompt: ConvertedPrompt;
    isChainManagement?: boolean;
    chainAction?: string;
    chainParameters?: Record<string, any>;
  }> {
    // Phase 1: Smart chain management command detection
    if (this.chainExecutor) {
      const chainCommand = this.chainExecutor.detectChainManagementCommand(command);
      if (chainCommand.isChainManagement) {
        // Mark this as a chain management operation
        return {
          promptId: '',
          arguments: {},
          convertedPrompt: {} as ConvertedPrompt,
          isChainManagement: true,
          chainAction: chainCommand.action!,
          chainParameters: chainCommand.parameters!
        };
      }
    }
    // Use new unified command parser
    const parseResult = await this.parsingSystem.commandParser.parseCommand(
      command,
      this.promptsData
    );

    // Find the matching prompt data and converted prompt (case-insensitive lookup)
    const promptData = this.promptsData.find(
      (p) => p.id.toLowerCase() === parseResult.promptId.toLowerCase() || 
             (p.name && p.name.toLowerCase() === parseResult.promptId.toLowerCase())
    );
    if (!promptData) {
      throw new PromptError(
        `Unknown prompt: ${parseResult.promptId}. Use >>listprompts to see available prompts.`
      );
    }

    const convertedPrompt = this.convertedPrompts.find(
      (p) => p.id === promptData.id
    );
    if (!convertedPrompt) {
      throw new PromptError(
        `Converted prompt data not found for: ${parseResult.promptId}`
      );
    }

    // Process arguments using new argument processor
    const context: ExecutionContext = {
      conversationHistory: [], // Would be injected from conversation manager
      environmentVars: process.env as Record<string, string>,
      promptDefaults: {},
      systemContext: {},
    };

    const argResult = await this.parsingSystem.argumentParser.parseArguments(
      parseResult.rawArgs,
      promptData,
      context
    );

    // Log parsing details for monitoring
    this.logger.debug(`Command parsed successfully:`, {
      strategy: parseResult.metadata.parseStrategy,
      confidence: parseResult.confidence,
      argumentsProcessed: Object.keys(argResult.processedArgs).length,
      appliedDefaults: argResult.metadata.appliedDefaults.length,
      warnings: [
        ...parseResult.metadata.warnings,
        ...argResult.metadata.warnings,
      ],
    });

    return {
      promptId: promptData.id,
      arguments: argResult.processedArgs, // Pass typed arguments directly
      convertedPrompt,
    };
  }

  /**
   * Detect execution mode using semantic analysis - THREE-TIER MODEL
   * Returns appropriate execution strategy based on prompt characteristics
   */
  private async detectExecutionMode(
    convertedPrompt: ConvertedPrompt
  ): Promise<"prompt" | "template" | "chain"> {
    if (convertedPrompt.executionMode) {
      return convertedPrompt.executionMode;
    }

    const classification = await this.analyzePrompt(convertedPrompt);
    this.autoAssignQualityGates(convertedPrompt, classification);

    this.logger.debug(
      `Semantic analysis: ${classification.executionType} (${Math.round(
        classification.confidence * 100
      )}%)`
    );

    // Return the semantic analysis result directly - it now handles the three-tier distinction
    return classification.executionType;
  }

  /**
   * Create fallback analysis when semantic analysis is disabled
   */
  private createDisabledAnalysisFallback(
    prompt: ConvertedPrompt
  ): PromptClassification {
    const hasChainSteps = Boolean(prompt.chainSteps?.length);
    const argCount = prompt.arguments?.length || 0;
    const hasTemplateVars = /\{\{.*?\}\}/g.test(
      prompt.userMessageTemplate || ""
    );

    // Reliable structural detection: only use verifiable indicators
    const hasComplexTemplateLogic =
      /\{\{.*?\|.*?\}\}|\{%-.*?-%\}|\{%.*?if.*?%\}|\{%.*?for.*?%\}/g.test(
        prompt.userMessageTemplate || ""
      );
    const hasMultipleArgs = argCount > 1; // More than one argument suggests complexity

    // Three-tier detection based on structural indicators only
    let executionType: "prompt" | "template" | "chain" = "prompt";

    if (hasChainSteps) {
      executionType = "chain";
    } else if (hasComplexTemplateLogic) {
      // Complex Nunjucks logic always needs template mode
      executionType = "template";
    } else if (hasTemplateVars && hasMultipleArgs) {
      // Template variables with multiple args suggests framework benefit
      executionType = "template";
    }
    // Default to 'prompt' for simple cases (no vars, single arg, or static content)

    return {
      executionType,
      requiresExecution: true,
      confidence: 0.9, // High confidence in structural detection
      reasoning: [
        "Structural auto detection (semantic analysis disabled)",
        `Args: ${argCount}, Template vars: ${hasTemplateVars}, Complex logic: ${hasComplexTemplateLogic}`,
        `Selected ${executionType} mode based on verifiable structural indicators`,
      ],
      suggestedGates: ["basic_validation"],
      framework: "disabled",
    };
  }

  /**
   * Detect analysis intent using LLM semantic understanding (FUTURE IMPLEMENTATION)
   *
   * This method will be implemented when the LLM semantic layer is completed.
   * It will provide intelligent analysis intent detection by examining:
   * - Template content and complexity
   * - Argument semantics and naming patterns
   * - Task complexity indicators
   * - Context and domain-specific signals
   *
   * @param prompt - The prompt to analyze for analysis intent
   * @returns Promise<boolean> - True if prompt requires analytical framework processing
   *
   * @todo Implement when ContentAnalyzer LLM integration is enabled
   * @todo Design proper interface for semantic intent classification
   * @todo Add confidence scoring and reasoning for intent decisions
   */
  private async detectAnalysisIntentLLM(
    prompt: ConvertedPrompt
  ): Promise<boolean> {
    // STUB: Always return false until LLM semantic analysis is implemented
    // When implemented, this will use the LLM to intelligently detect:
    // - Analysis vs formatting tasks
    // - Complex reasoning requirements
    // - Domain-specific analytical patterns
    // - Context-dependent intent signals

    this.logger.debug(
      `LLM analysis intent detection not yet implemented for ${prompt.id}`
    );
    return false;
  }

  /**
   * Analyze prompt for execution strategy (configuration-aware)
   */
  private async analyzePrompt(
    prompt: ConvertedPrompt
  ): Promise<PromptClassification> {
    // Check if semantic analysis is enabled via the analyzer
    if (!this.semanticAnalyzer.isLLMEnabled()) {
      this.logger.debug(
        `Semantic analysis disabled for ${prompt.id} - using structural fallback`
      );
      return this.createDisabledAnalysisFallback(prompt);
    }

    try {
      const analysis = await this.semanticAnalyzer.analyzePrompt(prompt);
      return {
        executionType: analysis.executionType,
        requiresExecution: analysis.requiresExecution,
        confidence: analysis.confidence,
        reasoning: analysis.reasoning,
        suggestedGates: analysis.suggestedGates,
        framework: "semantic",
      };
    } catch (error) {
      this.logger.error(`Semantic analysis failed for ${prompt.id}:`, error);
      return {
        executionType: isChainPrompt(prompt) ? "chain" : "template",
        requiresExecution: true,
        confidence: 0.5,
        reasoning: [`Fallback analysis: ${error}`],
        suggestedGates: ["execution_validation"],
        framework: "fallback",
      };
    }
  }

  /**
   * Auto-assign quality gates based on classification
   */
  private autoAssignQualityGates(
    prompt: ConvertedPrompt,
    classification: PromptClassification
  ): void {
    const autoGates: GateDefinition[] = [];

    if (classification.requiresExecution && classification.confidence > 0.5) {
      autoGates.push({
        id: "content_length_validation",
        name: "Content Length Validation",
        type: "validation",
        requirements: [
          {
            type: "content_length",
            criteria: { min: 50 },
            required: true,
          },
        ],
        failureAction: "retry",
      });
    }

    if (autoGates.length > 0) {
      (prompt as any).autoAssignedGates = autoGates;
      this.logger.debug(
        `Auto-assigned ${autoGates.length} gates for ${prompt.id}`
      );
    }
  }

  /**
   * NEW: Execute basic prompt with simple variable substitution (fastest)
   * No framework processing, minimal overhead
   */
  private async executePrompt(
    prompt: ConvertedPrompt,
    args: Record<string, string>,
    executionContext?: {
      scopeId?: string;
      scope?: 'execution' | 'session' | 'chain' | 'step';
    }
  ): Promise<ToolResponse> {
    if (!this.currentExecutionState) {
      throw new PromptError("No execution state available");
    }

    this.currentExecutionState.status = "running";

    // Simple template processing without framework enhancement
    let content = prompt.userMessageTemplate;
    if (prompt.systemMessage) {
      content = `[System: ${prompt.systemMessage}]\n\n${content}`;
    }

    // Phase 4: Enhanced args without gate injection (gates now appended at end)
    const enhancedArgs = args;

    // Phase 3: Inject session context for step result interpolation
    const sessionEnhancedArgs = await this.injectSessionContext(enhancedArgs);

    // Fast variable substitution using modern template processor
    content = processTemplate(content, sessionEnhancedArgs, {});

    // Phase 4: Enhanced gate validation for basic prompts (only when framework system is enabled)
    let gateResults: GateValidationResult | null = null;
    const frameworkEnabled = this.frameworkStateManager?.isFrameworkSystemEnabled();
    const hasRequestedGates = (this.activeGateRequest?.gateIds?.length || 0) > 0;
    const shouldValidate = frameworkEnabled || hasRequestedGates;
    this.logger.info(
      `🔍 [DEBUG] Framework system enabled: ${frameworkEnabled}, requestedGates=${hasRequestedGates}`
    );

    if (shouldValidate) {
      const gateValidation = await this.validateContentWithGates(prompt, content, sessionEnhancedArgs, 'prompt');
      gateResults = gateValidation.validation;
      this.logger.info(`🔍 [DEBUG] Gate validation result:`, {
        hasGateResults: !!gateResults,
        gateResultsType: typeof gateResults,
        gateResultsValue: gateResults
      });

      if (gateResults && !gateResults.passed) {
        this.logger.debug(`Basic prompt gate validation failed for ${prompt.id}:`, gateResults.results);
        // For basic prompts, we just log and continue
      } else if (gateResults && gateResults.passed) {
        this.logger.debug(`Basic prompt gate validation passed for ${prompt.id}`);
      }
    }

    // Update state and analytics
    this.currentExecutionState.status = "completed";
    this.currentExecutionState.metadata.endTime = Date.now();
    // Store gate results in execution state for analytics
    if (gateResults) {
      (this.currentExecutionState.metadata as any).gateResults = gateResults;
    }

    // Capture step result if this is part of a chain session
    await this.captureStepResult(content, prompt);

    this.recordExecutionAnalytics();

    // Create execution context for response formatter
    const executionId = `exec_${Date.now()}_${Math.random()
      .toString(36)
      .substr(2, 9)}`;
    const activeFramework =
      this.frameworkStateManager?.getActiveFramework()?.name;
    const frameworkEnabledForContext =
      this.frameworkStateManager?.isFrameworkSystemEnabled() || false;

    const formatterContext: FormatterExecutionContext = {
      executionId,
      executionType: "prompt",
      startTime: this.currentExecutionState.metadata.startTime,
      endTime: this.currentExecutionState.metadata.endTime || Date.now(),
      frameworkUsed: activeFramework,
      frameworkEnabled: frameworkEnabledForContext,
      success: true,
    };

    // FIXED: Add supplemental gate guidance for prompt mode (same as template mode)
    let enhancedContent = content;
    this.logger.info(`🔍 [DEBUG] Gate conditional logic:`, {
      hasGateResults: !!gateResults,
      gateResultsValue: gateResults,
      willExecuteIfBranch: !!gateResults,
      willExecuteElseBranch: !gateResults
    });

    if (gateResults) {
      this.logger.info(`🔀 [DEBUG] Taking IF branch (gateResults exists)`);

      // Get selected gates from validation - basic prompts use 'prompt' mode gates
      const selectedGates = await this.getAdvancedGateSelection(prompt, 'prompt');
      const frameworkContext = await this.getFrameworkExecutionContext(prompt);

      if (selectedGates.length > 0) {
        const temporaryGates = this.getTemporaryGatesFromPrompt(prompt);
        const supplementalGuidance = await this.getSupplementalGateGuidance(
          selectedGates,
          frameworkContext,
          prompt,
          temporaryGates,
          executionContext
        );
        if (supplementalGuidance) {
          enhancedContent = content + supplementalGuidance;
        }
      }
    } else {
      this.logger.info(`🔀 [DEBUG] Taking ELSE branch (no gateResults) - this should call our gate guidance renderer`);
      // TEMP TEST: Force gate guidance even without validation results
      const testGates = ['framework-compliance', 'educational-clarity'];
      const frameworkContext = await this.getFrameworkExecutionContext(prompt);
      const temporaryGates = this.getTemporaryGatesFromPrompt(prompt);

      const supplementalGuidance = await this.getSupplementalGateGuidance(
        testGates,
        frameworkContext,
        prompt,
        temporaryGates,
        executionContext
      );
      if (supplementalGuidance) {
        enhancedContent = content + supplementalGuidance;
      } else {
        enhancedContent = content + "(Gate manager returned empty guidance)";
      }
    }

    if (this.activeGateRequest) {
      enhancedContent += this.formatGateStatus(gateResults);
    }

    // Format response with structured data
    const executionWarning = `⚠️ EXECUTION REQUIRED: The following content contains instructions that YOU must interpret and execute:\n\n`;

    return this.responseFormatter.formatPromptEngineResponse(
      executionWarning + enhancedContent,
      formatterContext,
      {
        includeAnalytics: true,
        includeMetadata: true,
      },
      gateResults // Include gate validation results for basic prompts too
    );
  }

  /**
   * Inject session context variables for template interpolation
   */
  private async injectSessionContext(args: Record<string, any>): Promise<Record<string, any>> {
    const sessionId = (this.currentExecutionState?.metadata as any)?.sessionId;

    if (!sessionId) {
      // No session context available
      return args;
    }

    try {
      // Get session context from chain session manager
      const sessionContext = this.chainSessionManager.getChainContext(sessionId);

      // Merge session context with existing args
      // Session context takes precedence for step result variables
      return {
        ...args,
        ...sessionContext
      };
    } catch (error) {
      this.logger.warn(`Failed to inject session context for session ${sessionId}:`, error);
      return args;
    }
  }

  /**
   * Ensure chain session exists for chain execution
   */
  private async ensureChainSession(
    convertedPrompt: ConvertedPrompt,
    providedSessionId?: string,
    forceRestart?: boolean,
    originalArgs?: Record<string, any>
  ): Promise<string> {
    // Generate session ID if not provided
    const sessionId = providedSessionId || `chain_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;

    // Check if session exists and force restart is requested
    if (forceRestart && this.chainSessionManager.hasActiveSession(sessionId)) {
      this.chainSessionManager.clearSession(sessionId);
      this.logger.debug(`Force restart: cleared existing session ${sessionId}`);
    }

    // Create session if it doesn't exist
    if (!this.chainSessionManager.hasActiveSession(sessionId)) {
      // Get step count from chain definition
      const stepCount = this.getChainStepCount(convertedPrompt);

      // Create new session
      this.chainSessionManager.createSession(
        sessionId,
        convertedPrompt.id,
        stepCount,
        originalArgs || {}
      );

      this.logger.info(
        `Created new chain session ${sessionId} for chain ${convertedPrompt.id} with ${stepCount} steps`
      );
    }

    return sessionId;
  }

  /**
   * Get the number of steps in a chain
   */
  private getChainStepCount(convertedPrompt: ConvertedPrompt): number {
    // For markdown-embedded chains, try to extract step count from chain definition
    if (convertedPrompt.chainSteps) {
      return convertedPrompt.chainSteps.length;
    }

    // Fallback: try to parse from userMessageTemplate
    if (convertedPrompt.userMessageTemplate) {
      const stepMatches = convertedPrompt.userMessageTemplate.match(/## Step \d+|### Step \d+/g);
      if (stepMatches) {
        return stepMatches.length;
      }
    }

    // Default to 1 if we can't determine step count
    this.logger.warn(`Could not determine step count for chain ${convertedPrompt.id}, defaulting to 1`);
    return 1;
  }

  /**
   * Capture step result for chain session management
   */
  private async captureStepResult(content: string, prompt: ConvertedPrompt): Promise<void> {
    const sessionId = (this.currentExecutionState?.metadata as any)?.sessionId;

    if (!sessionId) {
      // No session ID, this is not part of a chain execution
      return;
    }

    // Check if this session exists and should capture results
    if (!this.chainSessionManager.hasActiveSession(sessionId)) {
      this.logger.debug(`Session ${sessionId} not found or inactive, skipping result capture`);
      return;
    }

    try {
      // Get current session state to determine step number
      const session = this.chainSessionManager.getSession(sessionId);
      if (!session) {
        this.logger.warn(`Session ${sessionId} not found during result capture`);
        return;
      }

      // For LLM-driven chains, we need to determine the step number
      // This implementation assumes the step number is derived from current state
      const currentStepNumber = session.state.currentStep;

      // Store the step result
      const stepMetadata = {
        promptId: prompt.id,
        executionTime: Date.now() - (this.currentExecutionState?.metadata?.startTime || Date.now()),
        contentLength: content.length,
        timestamp: Date.now()
      };

      this.chainSessionManager.updateSessionState(
        sessionId,
        currentStepNumber,
        content,
        stepMetadata
      );

      this.logger.debug(
        `Captured step ${currentStepNumber} result for session ${sessionId} (${content.length} chars)`
      );
    } catch (error) {
      this.logger.error(`Failed to capture step result for session ${sessionId}:`, error);
    }
  }

  /**
   * Execute template with full framework processing and gates
   */
  private async executeTemplateWithFramework(
    prompt: ConvertedPrompt,
    args: Record<string, string>,
    enableGates: boolean,
    executionContext?: {
      scopeId?: string;
      scope?: 'execution' | 'session' | 'chain' | 'step';
    }
  ): Promise<ToolResponse> {
    if (!this.currentExecutionState) {
      throw new PromptError("No execution state available");
    }

    this.currentExecutionState.status = "running";

    // Process template with framework-enhanced system prompt injection
    let content = prompt.userMessageTemplate;

    // FIXED: Get framework execution context for enhanced system prompt
    const frameworkContext = await this.getFrameworkExecutionContext(prompt);
    this.logger.debug(`[ENGINE DEBUG] Framework context result:`, {
      hasFrameworkContext: !!frameworkContext,
      frameworkContextType: frameworkContext ? typeof frameworkContext : 'null',
      hasSystemPrompt: frameworkContext?.systemPrompt ? true : false,
      systemPromptLength: frameworkContext?.systemPrompt?.length || 0
    });

    if (prompt.systemMessage || frameworkContext) {
      let systemPrompt = prompt.systemMessage || "";

      // FIXED: Enhance with framework-specific system prompt if available
      if (frameworkContext) {
        const frameworkSystemPrompt = frameworkContext.systemPrompt;
        this.logger.debug(`[ENGINE DEBUG] Framework system prompt:`, {
          hasFrameworkSystemPrompt: !!frameworkSystemPrompt,
          frameworkSystemPromptLength: frameworkSystemPrompt?.length || 0,
          frameworkSystemPromptPreview: frameworkSystemPrompt?.substring(0, 100) + '...'
        });
        if (frameworkSystemPrompt) {
          systemPrompt = systemPrompt
            ? `${frameworkSystemPrompt}\n\n${systemPrompt}`
            : frameworkSystemPrompt;
        }
      }

      if (systemPrompt) {
        content = `[System: ${systemPrompt}]\n\n${content}`;
      }
    }

    // Phase 4: Enhanced args without gate injection (gates now appended at end)
    const enhancedArgs = args;

    // Template processing with special context and optional tools
    const specialContext: Record<string, string> = {
      previous_message: "{{previous_message}}",
    };
    if (prompt.tools) {
      specialContext["tools_available"] = getAvailableTools();
    }

    // Inject session context for step result interpolation
    const sessionEnhancedArgs = await this.injectSessionContext(enhancedArgs);

    content = processTemplate(content, sessionEnhancedArgs, specialContext);

    // Phase 1.2: Post-execution gate validation with retry logic (only for template mode when gates are enabled)
    let gateResults: GateValidationResult | null = null;
    let selectedGates: string[] = [];
    let retryAttempt = 0;
    const gateModeForExecution = this.activeGateRequest?.gateMode || (enableGates ? 'enforce' : 'advise');
    const maxRetries = gateModeForExecution === 'enforce' ? 2 : 0;

    if (enableGates) {
      do {
        const gateValidation = await this.validateContentWithGates(prompt, content, sessionEnhancedArgs, 'template');
        gateResults = gateValidation.validation;
        selectedGates = gateValidation.selectedGates;

      if (gateResults && !gateResults.passed && retryAttempt < maxRetries) {
          retryAttempt++;
          this.logger.warn(`Gate validation failed for ${prompt.id} (attempt ${retryAttempt}):`, gateResults.results);

          // Get retry hints from failed gates
          const retryHints = this.getRetryHintsFromValidation(gateResults);
          if (retryHints.length > 0) {
            this.logger.debug(`Applying retry hints: ${retryHints.join(', ')}`);

            // Enhance args with retry hints for content regeneration
            const retryEnhancedArgs = {
              ...sessionEnhancedArgs,
              retry_hints: retryHints.join('\n'),
              previous_attempt: content.substring(0, 200) + '...',
              improvement_focus: this.getImprovementFocus(gateResults)
            };

            // Regenerate content with improvement hints
            content = processTemplate(prompt.userMessageTemplate, retryEnhancedArgs, specialContext);
            this.logger.debug(`Content regenerated for retry attempt ${retryAttempt}`);
          } else {
            // No actionable hints available, break retry loop
            this.logger.debug(`No actionable retry hints available, accepting current result`);
            break;
          }
        } else if (gateResults && gateResults.passed) {
          this.logger.debug(`Gate validation passed for ${prompt.id}` + (retryAttempt > 0 ? ` after ${retryAttempt} retries` : ''));
          break;
        } else {
          // Max retries reached
          if (retryAttempt >= maxRetries) {
            this.logger.warn(`Max retries (${maxRetries}) reached for ${prompt.id}, proceeding with current content`);
          }
          break;
        }
      } while (retryAttempt <= maxRetries);
    }

    // Update state and analytics
    this.currentExecutionState.status = "completed";
    this.currentExecutionState.metadata.endTime = Date.now();
    // Store gate results in execution state for analytics
    if (gateResults) {
      (this.currentExecutionState.metadata as any).gateResults = gateResults;
    }
    this.recordExecutionAnalytics();

    // Create execution context for response formatter
    const executionId = `exec_${Date.now()}_${Math.random()
      .toString(36)
      .substr(2, 9)}`;
    const activeFramework =
      this.frameworkStateManager?.getActiveFramework()?.name;
    const frameworkEnabledForContext =
      this.frameworkStateManager?.isFrameworkSystemEnabled() || false;

    const formatterContext: FormatterExecutionContext = {
      executionId,
      executionType: "template",
      startTime: this.currentExecutionState.metadata.startTime,
      endTime: this.currentExecutionState.metadata.endTime || Date.now(),
      frameworkUsed: activeFramework,
      frameworkEnabled: frameworkEnabledForContext,
      success: true,
    };

    // Phase 4: Append supplemental gate guidance to content
    let enhancedContent = content;

    if (gateResults && selectedGates.length > 0) {
      const temporaryGates = this.getTemporaryGatesFromPrompt(prompt);
      const supplementalGuidance = await this.getSupplementalGateGuidance(
        selectedGates,
        frameworkContext,
        prompt,
        temporaryGates,
        executionContext
      );
      if (supplementalGuidance) {
        enhancedContent = content + supplementalGuidance;
      }
    } else {
      // TEMP TEST: Force gate guidance even without validation results (same as executePrompt)
      const testGates = ['framework-compliance', 'educational-clarity'];
      const temporaryGates = this.getTemporaryGatesFromPrompt(prompt);
      const supplementalGuidance = await this.getSupplementalGateGuidance(
        testGates,
        frameworkContext,
        prompt,
        temporaryGates,
        executionContext
      );
      if (supplementalGuidance) {
        enhancedContent = enhancedContent + supplementalGuidance;
      } else {
        enhancedContent = enhancedContent + `\n--- GATE MANAGER RETURNED EMPTY ---\n`;
      }
    }

    if (this.activeGateRequest) {
      enhancedContent += this.formatGateStatus(gateResults);
    }

    // Format response with structured data
    const executionWarning = `⚠️ EXECUTION REQUIRED: The following content contains instructions that YOU must interpret and execute:\n\n`;

    return this.responseFormatter.formatPromptEngineResponse(
      executionWarning + enhancedContent,
      formatterContext,
      {
        includeAnalytics: true,
        includeMetadata: true,
      },
      gateResults // Include gate validation results
    );
  }

  // REMOVED: getGateInfo - migrated to ChainExecutor

  // REMOVED: generateMetadataSection - migrated to ChainExecutor

  /**
   * Get supplemental gate guidance to append to responses (Phase 1 - Enhanced with intelligent category detection)
   */
  private async getSupplementalGateGuidance(
    selectedGates: string[],
    frameworkContext?: any,
    prompt?: any,
    temporaryGates?: Array<Omit<TemporaryGateDefinition, 'id' | 'created_at'>>,
    executionContext?: {
      scopeId?: string;
      scope?: 'execution' | 'session' | 'chain' | 'step';
    }
  ): Promise<string> {
    // Phase 1: Enhanced category detection
    let categoryExtractionResult: CategoryExtractionResult;
    if (prompt) {
      categoryExtractionResult = extractPromptCategory(prompt, this.logger);
      this.logger.info(`🏷️ [CATEGORY EXTRACTOR] Category detected:`, {
        category: categoryExtractionResult.category,
        source: categoryExtractionResult.source,
        confidence: categoryExtractionResult.confidence,
        promptId: prompt.id
      });
    } else {
      // Fallback when prompt not available
      categoryExtractionResult = {
        category: 'general',
        source: 'fallback',
        confidence: 20,
        sourceData: {}
      };
      this.logger.warn(`🏷️ [CATEGORY EXTRACTOR] No prompt provided, using fallback category`);
    }

    console.log(`🎯 [CONSOLE DEBUG] getSupplementalGateGuidance called:`, {
      selectedGatesCount: selectedGates.length,
      selectedGates,
      hasFrameworkContext: !!frameworkContext,
      frameworkMethodology: frameworkContext?.selectedFramework?.methodology,
      detectedCategory: categoryExtractionResult.category,
      categorySource: categoryExtractionResult.source,
      categoryConfidence: categoryExtractionResult.confidence
    });
    this.logger.info(`🎯 [GATE MANAGER] getSupplementalGateGuidance called:`, {
      selectedGatesCount: selectedGates.length,
      selectedGates,
      hasFrameworkContext: !!frameworkContext,
      frameworkMethodology: frameworkContext?.selectedFramework?.methodology,
      detectedCategory: categoryExtractionResult.category,
      categorySource: categoryExtractionResult.source
    });

    // Phase 3: Enhanced gate selection with 5-level precedence and temporary gates
    let finalSelectedGates = selectedGates;
    let temporaryGateIds: string[] = [];

    // Step 1: Create temporary gates if provided
    if (temporaryGates && temporaryGates.length > 0 && this.temporaryGateRegistry && executionContext) {
      for (const tempGate of temporaryGates) {
        try {
          const gateId = this.temporaryGateRegistry.createTemporaryGate(
            tempGate,
            executionContext.scopeId
          );
          temporaryGateIds.push(gateId);
          this.logger.info(`🚀 [TEMPORARY GATE] Created temporary gate:`, {
            gateId,
            name: tempGate.name,
            scope: tempGate.scope,
            scopeId: executionContext.scopeId
          });
        } catch (error) {
          this.logger.error(`❌ [TEMPORARY GATE] Failed to create temporary gate:`, {
            error: error instanceof Error ? error.message : String(error),
            gateName: tempGate.name
          });
        }
      }
    }

    // Step 2: Apply 5-level precedence selection
    if (prompt) {
      const extractor = new CategoryExtractor(this.logger);
      const frameworkGates = this.getFrameworkGates(frameworkContext);

      // Use enhanced precedence system with temporary gates
      const intelligentSelection = extractor.selectGatesWithEnhancedPrecedence(
        categoryExtractionResult,
        frameworkGates,
        selectedGates.length > 0 ? selectedGates : ['content-structure'], // fallback
        temporaryGateIds, // temporary gates have highest precedence
        categoryExtractionResult.gateConfiguration
      );

      finalSelectedGates = intelligentSelection.selectedGates;

      this.logger.info(`🎯 [5-LEVEL PRECEDENCE] Applied enhanced gate selection:`, {
        originalGates: selectedGates,
        temporaryGates: temporaryGateIds,
        finalGates: finalSelectedGates,
        precedenceUsed: intelligentSelection.precedenceUsed,
        reasoning: intelligentSelection.reasoning,
        temporaryGatesApplied: intelligentSelection.temporaryGatesApplied
      });
    } else if (temporaryGateIds.length > 0) {
      // No prompt context but we have temporary gates - include them
      finalSelectedGates = [...selectedGates, ...temporaryGateIds];
      this.logger.info(`🎯 [TEMPORARY GATES ONLY] Applied temporary gates without prompt context:`, {
        originalGates: selectedGates,
        temporaryGates: temporaryGateIds,
        finalGates: finalSelectedGates
      });
    }

    if (finalSelectedGates.length === 0) {
      this.logger.debug(`[GATE MANAGER] No gates selected after intelligent selection, returning empty guidance`);
      return '';
    }

    try {

      // NEW: Use role-based gate guidance renderer with intelligent category detection and gate selection (Phase 1 & 2)
      const supplementalGuidance = await this.gateGuidanceRenderer.renderGuidance(
        finalSelectedGates, // Use intelligently selected gates
        {
          framework: frameworkContext?.selectedFramework?.methodology || 'CAGEERF',
          category: categoryExtractionResult.category, // Dynamic category based on intelligent detection
          promptId: frameworkContext?.promptId
        }
      );

      this.logger.debug(`[GATE GUIDANCE RENDERER] Gate guidance renderer returned guidance:`, {
        guidanceLength: supplementalGuidance.length,
        hasContent: supplementalGuidance.length > 0
      });

      return supplementalGuidance;
    } catch (error) {
      this.logger.error("Failed to get supplemental gate guidance:", error);
      return '';
    }
  }

  /**
   * Get framework-specific gates for intelligent selection
   *
   * Returns the universal framework-compliance gate for all frameworks.
   * Future: Can add framework-specific quality gates alongside framework-compliance.
   */
  private getFrameworkGates(frameworkContext?: any): string[] {
    if (!frameworkContext?.selectedFramework?.methodology) {
      return [];
    }

    const methodology = frameworkContext.selectedFramework.methodology;

    // All frameworks get universal framework-compliance gate
    // Framework-specific gates can be added in future iterations
    switch (methodology) {
      case 'CAGEERF':
        return ['framework-compliance'];
      case 'ReACT':
        return ['framework-compliance'];
      case '5W1H':
        return ['framework-compliance'];
      case 'SCAMPER':
        return ['framework-compliance'];
      default:
        return ['framework-compliance'];
    }
  }

  /**
   * Extract gate title from guidance text
   */
  private extractGateTitle(guidanceText: string): string {
    const lines = guidanceText.split('\n');
    const titleLine = lines.find(line => line.includes('Guidelines') || line.includes(':'));
    if (titleLine) {
      return titleLine.replace(/\*\*/g, '').replace(/:/g, '').trim();
    }
    return 'Quality Guidelines';
  }

  /**
   * Simple prompt categorization for gate activation
   */
  private categorizePrompt(promptId: string): string {
    // Basic categorization based on prompt ID patterns
    if (promptId.includes("research") || promptId.includes("analysis")) {
      return "research";
    } else if (promptId.includes("code") || promptId.includes("development")) {
      return "code";
    } else if (
      promptId.includes("content") ||
      promptId.includes("documentation")
    ) {
      return "content_processing";
    }
    return "general";
  }

  /**
   * Get framework-specific gates for validation (Phase 4: Enhanced with advanced orchestration)
   */
  private async getAdvancedGateSelection(
    prompt: ConvertedPrompt,
    executionMode: 'prompt' | 'template' | 'chain',
    semanticAnalysis?: any
  ): Promise<string[]> {
    this.logger.debug(`[GATE DEBUG] getAdvancedGateSelection called:`, {
      promptId: prompt.id,
      executionMode,
      hasGateSelectionEngine: !!this.gateSelectionEngine,
      hasSemanticAnalysis: !!semanticAnalysis
    });

    if (!this.gateSelectionEngine) {
      this.logger.debug(`[GATE DEBUG] No gate selection engine, using fallback gates`);
      return this.mergeRequestedGates(this.getFallbackGates(prompt));
    }

    try {
      // Build gate selection criteria
      const criteria: ExtendedGateSelectionCriteria = {
        framework: this.frameworkStateManager?.getActiveFramework()?.methodology,
        category: prompt.category || 'general',
        promptId: prompt.id,
        executionMode,
        complexityLevel: this.assessPromptComplexity(prompt),
        semanticAnalysis,
        frameworkContext: this.frameworkStateManager?.isFrameworkSystemEnabled()
          ? this.frameworkStateManager.getActiveFramework()
          : undefined,
        userPreferences: {
          qualityFocus: 'balanced',
          performanceMode: false,
          strictValidation: true
        }
      };

      this.logger.debug(`[GATE DEBUG] Gate selection criteria:`, {
        hasFrameworkContext: !!criteria.frameworkContext,
        frameworkMethodology: criteria.frameworkContext?.methodology,
        executionMode: criteria.executionMode,
        complexityLevel: criteria.complexityLevel
      });

      // Use gate selection engine for intelligent gate selection
      const selection = await this.gateSelectionEngine.selectGates(criteria);

      this.logger.debug(`[GATE DEBUG] Advanced gate selection result:`, {
        promptId: prompt.id,
        selectedGates: selection.selectedGates,
        gateCount: selection.selectedGates.length,
        confidence: selection.confidence,
        reasoning: selection.reasoning,
        estimatedTime: selection.estimatedExecutionTime
      });

      return this.mergeRequestedGates(selection.selectedGates);

    } catch (error) {
      this.logger.error("Advanced gate selection failed, using fallback:", error);
      const fallbackGates = this.getFallbackGates(prompt);
      this.logger.debug(`[GATE DEBUG] Using fallback gates:`, { fallbackGates });
      return this.mergeRequestedGates(fallbackGates);
    }
  }

  /**
   * Fallback gate selection for when advanced orchestration is unavailable
   */
  private getFallbackGates(prompt: ConvertedPrompt): string[] {
    // TEMP DEBUG: Add comprehensive logging
    const isEnabled = this.frameworkStateManager?.isFrameworkSystemEnabled();
    this.logger.debug(`[FALLBACK GATES DEBUG] Framework system enabled: ${isEnabled}`);

    if (!isEnabled) {
      this.logger.debug(`[FALLBACK GATES DEBUG] Framework disabled, returning content-structure`);
      return ['content-structure'];
    }

    const activeFramework = this.frameworkStateManager?.getActiveFramework();
    this.logger.debug(`[FALLBACK GATES DEBUG] Active framework:`, {
      hasFramework: !!activeFramework,
      methodology: activeFramework?.methodology,
      frameworkObj: activeFramework
    });

    if (!activeFramework) {
      this.logger.debug(`[FALLBACK GATES DEBUG] No active framework, returning content-structure`);
      return ['content-structure'];
    }

    const gates: string[] = [];

    // Framework-specific gates based on methodology
    switch (activeFramework.methodology) {
      case 'CAGEERF':
        gates.push('framework-compliance', 'technical-accuracy', 'content-structure');
        break;
      case 'ReACT':
        gates.push('framework-compliance', 'educational-clarity');
        break;
      case '5W1H':
        gates.push('framework-compliance', 'research-quality');
        break;
      case 'SCAMPER':
        gates.push('framework-compliance', 'content-structure');
        break;
    }

    // Add category-specific gates
    const category = this.categorizePrompt(prompt.id);
    switch (category) {
      case 'code':
        gates.push('code-quality', 'security-awareness');
        break;
      case 'research':
        gates.push('research-quality', 'technical-accuracy');
        break;
      case 'content_processing':
        gates.push('content-structure', 'educational-clarity');
        break;
    }

    // Remove duplicates and return
    const finalGates = [...new Set(gates)];
    this.logger.debug(`[FALLBACK GATES DEBUG] Final gates returned:`, {
      gatesArray: finalGates,
      gateCount: finalGates.length
    });
    return finalGates;
  }

  /**
   * Assess prompt complexity for gate selection
   */
  private assessPromptComplexity(prompt: ConvertedPrompt): 'low' | 'medium' | 'high' {
    const argCount = prompt.arguments?.length || 0;
    const contentLength = prompt.userMessageTemplate?.length || 0;
    const hasSystemMessage = Boolean(prompt.systemMessage);

    if (argCount >= 5 || contentLength > 1000 || hasSystemMessage) return 'high';
    if (argCount >= 3 || contentLength > 500) return 'medium';
    return 'low';
  }

  /**
   * Validate content with framework-specific gates (Phase 4: Enhanced with advanced orchestration)
   */
  private async validateContentWithGates(
    prompt: ConvertedPrompt,
    content: string,
    promptArgs: Record<string, any>,
    executionMode: 'prompt' | 'template' | 'chain' = 'template',
    semanticAnalysis?: any
  ): Promise<{ validation: GateValidationResult | null; selectedGates: string[] }> {
    if (!this.engineValidator) {
      this.logger.debug("EngineValidator not available for gate validation");
      return { validation: null, selectedGates: [] };
    }

    // Get advanced gate selection (Phase 4)
    const suggestedGates = await this.getAdvancedGateSelection(prompt, executionMode, semanticAnalysis);

    if (suggestedGates.length === 0) {
      this.logger.debug("No gates suggested for validation");
      return { validation: { passed: true, results: [] }, selectedGates: [] };
    }

    try {
      const startTime = performance.now();
      this.logger.debug(`Validating content with advanced gate selection: ${suggestedGates.join(', ')}`);

      const validationResult = await this.engineValidator.validateWithGates(
        prompt,
        promptArgs,
        suggestedGates,
        content  // FIXED: Pass processed content for validation
      );

      const executionTime = performance.now() - startTime;

      // Performance metrics now handled separately by GatePerformanceAnalyzer in system control

      return { validation: validationResult, selectedGates: suggestedGates };
    } catch (error) {
      this.logger.error("Gate validation failed:", error);

      // Performance metrics for failed validation now handled by GatePerformanceAnalyzer

      return { validation: { passed: false, results: [{ gate: 'system', passed: false, message: `Validation error: ${error}` }] }, selectedGates: suggestedGates };
    }
  }

  /**
   * Extract retry hints from gate validation results (Phase 3 implementation)
   */
  private getRetryHintsFromValidation(gateResults: GateValidationResult): string[] {
    const hints: string[] = [];

    for (const result of gateResults.results) {
      if (!result.passed && result.message) {
        // Convert gate failure messages to actionable hints
        const hint = this.convertGateMessageToHint(result.gate, result.message);
        if (hint) {
          hints.push(hint);
        }
      }
    }

    return hints;
  }

  /**
   * Convert gate failure message to actionable retry hint
   */
  private convertGateMessageToHint(gateId: string, message: string): string | null {
    // Convert specific gate failures to actionable improvement hints
    switch (gateId) {
      case 'technical-accuracy':
        return 'Include specific version numbers, official documentation references, and technical specifications';
      case 'content-structure':
        return 'Organize content with clear headers, logical flow, and structured sections';
      case 'framework-compliance':
        return 'Follow the active methodology framework structure and include all required sections';
      case 'research-quality':
        return 'Include credible sources, evidence-based statements, and factual accuracy';
      case 'educational-clarity':
        return 'Use clear explanations, provide examples, and ensure concepts are well-explained';
      case 'code-quality':
        return 'Include proper syntax, error handling, and follow coding best practices';
      case 'security-awareness':
        return 'Address security considerations, validate inputs, and follow security best practices';
      default:
        // Generic hint based on message content
        if (message.toLowerCase().includes('length')) {
          return 'Provide more detailed and comprehensive content';
        } else if (message.toLowerCase().includes('structure')) {
          return 'Improve content organization and structure';
        } else if (message.toLowerCase().includes('quality')) {
          return 'Enhance content quality and accuracy';
        }
        return `Address validation concern: ${message}`;
    }
  }

  /**
   * Get improvement focus based on failed gates
   */
  private getImprovementFocus(gateResults: GateValidationResult): string {
    const failedGates = gateResults.results.filter(r => !r.passed).map(r => r.gate);

    if (failedGates.includes('technical-accuracy')) {
      return 'Technical accuracy and precision';
    } else if (failedGates.includes('framework-compliance')) {
      return 'Methodology framework compliance';
    } else if (failedGates.includes('content-structure')) {
      return 'Content organization and structure';
    } else if (failedGates.length > 1) {
      return 'Multiple quality aspects';
    } else {
      return 'Content quality improvement';
    }
  }

  /**
   * Record execution analytics using event-driven architecture
   */
  private recordExecutionAnalytics(): void {
    if (!this.currentExecutionState) {
      this.logger.debug(
        "RecordExecutionAnalytics called but currentExecutionState is null"
      );
      return;
    }

    if (!this.analyticsService) {
      this.logger.debug(
        "Analytics service not available - skipping analytics recording"
      );
      return;
    }

    const duration =
      (this.currentExecutionState.metadata.endTime || Date.now()) -
      this.currentExecutionState.metadata.startTime;

    const executionData: ExecutionData = {
      executionId: `exec_${Date.now()}_${Math.random()
        .toString(36)
        .substr(2, 9)}`,
      executionType: this.currentExecutionState.metadata.executionMode as
        | "prompt"
        | "template"
        | "chain",
      startTime: this.currentExecutionState.metadata.startTime,
      endTime: this.currentExecutionState.metadata.endTime || Date.now(),
      executionTime: duration,
      success: this.currentExecutionState.status === "completed",
      frameworkUsed: this.getActiveFrameworkId(),
      frameworkEnabled:
        this.frameworkStateManager?.isFrameworkSystemEnabled() || false,
      stepsExecuted: (this.currentExecutionState.metadata as any).stepsExecuted,
      sessionId: (this.currentExecutionState.metadata as any).sessionId,
      toolName: "prompt_engine",
      error:
        this.currentExecutionState.status === "failed"
          ? (this.currentExecutionState as any).error
          : undefined,
      memoryUsage: {
        heapUsed: process.memoryUsage().heapUsed,
        heapTotal: process.memoryUsage().heapTotal,
        external: process.memoryUsage().external,
      },
    };

    // Record execution analytics via event
    this.analyticsService.recordExecution(executionData);

    // Store in history for local access (keep limited history)
    this.executionHistory.push({ ...this.currentExecutionState });
    if (this.executionHistory.length > 100) {
      this.executionHistory.shift();
    }

    this.logger.debug(
      `Analytics recorded: ${executionData.executionType} execution (${duration}ms, success: ${executionData.success})`
    );
  }

  /**
   * Get active framework ID
   */
  private getActiveFrameworkId(): string | undefined {
    if (!this.frameworkStateManager?.isFrameworkSystemEnabled()) {
      return undefined;
    }
    return this.frameworkStateManager?.getCurrentState().activeFramework;
  }

  /**
   * Get execution analytics from analytics service
   */
  getAnalytics() {
    if (this.analyticsService) {
      return this.analyticsService.getExecutionStats();
    }

    // Fallback for backward compatibility
    return {
      totalExecutions: 0,
      successfulExecutions: 0,
      failedExecutions: 0,
      averageExecutionTime: 0,
      executionsByMode: {
        prompt: 0,
        template: 0,
        chain: 0,
      },
      executionsByTool: {
        prompt_engine: 0,
        prompt_manager: 0,
        system_control: 0,
      },
      lastUpdated: Date.now(),
    };
  }

  /**
   * Get parsing system statistics for monitoring
   */
  getParsingStats() {
    return {
      commandParser: this.parsingSystem.commandParser.getStats(),
      argumentParser: this.parsingSystem.argumentParser.getStats(),
      contextResolver: this.parsingSystem.contextResolver.getStats(),
    };
  }

  /**
   * Reset parsing statistics
   */
  resetParsingStats(): void {
    this.parsingSystem.commandParser.resetStats();
    this.parsingSystem.argumentParser.resetStats();
    this.parsingSystem.contextResolver.resetStats();
    this.logger.debug("Parsing system statistics reset");
  }

  /**
   * Error handling helper
   */
  private handleError(error: unknown, context: string): ToolResponse {
    utilsHandleError(error, context, this.logger);

    return this.responseFormatter.formatErrorResponse(
      error instanceof Error ? error : String(error),
      {
        tool: "prompt_engine",
        operation: context,
      },
      {
        includeStructuredData: true,
      }
    );
  }

  // REMOVED: executeChainWithDualSupport - migrated to ChainExecutor

  /**
   * MIGRATION: Chain management commands - deprecated scaffolding removed
   */
  // REMOVED: executeChainManagement - migrated to ChainExecutor
  // REMOVED: handleScaffoldCommand (~56 lines) - deprecated scaffolding functionality

  // REMOVED: handleConvertCommand (~42 lines) - deprecated chain conversion functionality

  /**
   * Handle validate command for markdown-embedded chains
   */
  // REMOVED: handleValidateCommand - migrated to ChainExecutor

  /**
   * Handle list chains command
   */
  // REMOVED: handleListChainsCommand - migrated to ChainExecutor

  // REMOVED: handleListTemplatesCommand (~55 lines) - scaffolding system deprecated
  // Migration: Use `prompt_manager action=list filter=category:analysis` for organized prompt discovery

  // REMOVED: handleDiscoverWorkflowsCommand (~50 lines) - scaffolding system deprecated
  // Migration: Use `prompt_manager action=list filter="intent:debugging category:development"` for intelligent discovery

  // REMOVED: handleScaffoldUsingCommand (~135 lines) - deprecated workflow scaffolding functionality
  // REMOVED: createChainDefinitionFromTemplate (~40 lines) - deprecated template creation functionality

  // REMOVED: handleChainEditCommand (~25 lines) - deprecated chain editing functionality
  // Migration: Chain editing is no longer needed with markdown-embedded chains
}

/**
 * Create consolidated prompt engine with enhanced parsing system
 */
export function createConsolidatedPromptEngine(
  logger: Logger,
  mcpServer: any,
  promptManager: PromptManager,
  configManager: ConfigManager,
  semanticAnalyzer: ContentAnalyzer,
  conversationManager: ConversationManager,
  textReferenceManager: TextReferenceManager,
  mcpToolsManager?: any
  // Phase 3: Removed executionCoordinator parameter - using LLM-driven chain model
): ConsolidatedPromptEngine {
  const engine = new ConsolidatedPromptEngine(
    logger,
    mcpServer,
    promptManager,
    configManager,
    semanticAnalyzer,
    conversationManager,
    textReferenceManager,
    // Phase 3: Legacy gateEvaluationService removed - using lightweight system only
    mcpToolsManager
    // Phase 3: Removed executionCoordinator parameter
  );

  logger.info("ConsolidatedPromptEngine created with enhanced features:");
  logger.info("- Unified multi-strategy command parsing");
  logger.info("- Advanced argument processing pipeline");
  logger.info(
    "- Optional gate evaluation service for template-driven verification"
  );
  logger.info("- Intelligent context resolution system");
  logger.info("- Backward compatibility with legacy parsing");

  return engine;
}

```

--------------------------------------------------------------------------------
/server/src/mcp-tools/system-control.ts:
--------------------------------------------------------------------------------

```typescript
/**
 * Consolidated System Control - Unified Framework & Analytics Management Tool
 *
 * Consolidates all system management functionality into a single intelligent tool:
 * - Framework switching and management (from system-status-tools.ts)
 * - System status and health monitoring
 * - Execution analytics and performance metrics
 * - Diagnostic reporting and maintenance
 * - Configuration management
 */

import { ConfigManager } from "../config/index.js";
import { FrameworkManager } from "../frameworks/framework-manager.js";
import {
  FrameworkStateManager,
  FrameworkSwitchRequest,
} from "../frameworks/framework-state-manager.js";
import { Logger } from "../logging/index.js";
import { ToolResponse } from "../types/index.js";
import { handleError as utilsHandleError } from "../utils/index.js";
import { SafeConfigWriter, createSafeConfigWriter } from "./config-utils.js";
import { createSystemResponse } from "./shared/structured-response-builder.js";
import { ToolDescriptionManager } from "./tool-description-manager.js";
// Phase 3: Prompt guidance system integration
import { PromptGuidanceService } from "../frameworks/prompt-guidance/index.js";
// Phase 4: Clean architecture gate performance analytics
import type { GatePerformanceAnalyzer } from "../gates/intelligence/GatePerformanceAnalyzer.js";
// Gates system management integration
import { GateSystemManager } from "../gates/gate-state-manager.js";
import type { GateGuidanceRenderer } from "../gates/guidance/GateGuidanceRenderer.js";
// Enhanced tool dependencies removed (Phase 1.3) - Core implementations
// Simple core response handling without enhanced complexity
interface SimpleResponseFormatter {
  formatResponse(content: any): any;
  formatSystemControlResponse(response: any, ...args: any[]): any; // Required
  formatErrorResponse(error: any, ...args: any[]): any; // Required
  setAnalyticsService(service: any): void; // Required
}

function createSimpleResponseFormatter(): SimpleResponseFormatter {
  return {
    formatResponse: (content: any) => content,
    formatSystemControlResponse: (response: any, ...args: any[]) => response, // Flexible args
    formatErrorResponse: (error: any, ...args: any[]) => ({
      content: [{ type: "text", text: String(error) }],
      isError: true,
      structuredContent: {
        executionMetadata: {
          executionId: `sc-error-${Date.now()}`,
          executionType: "prompt" as const,
          startTime: Date.now(),
          endTime: Date.now(),
          executionTime: 0,
          frameworkEnabled: false,
        },
      },
    }),
    setAnalyticsService: (service: any) => {}, // No-op for now
  };
}

// Simple output schema and response functions (minimal for Phase 1)
const systemControlOutputSchema = {
  content: { type: "array" },
  isError: { type: "boolean", optional: true },
};

function createStructuredResponse(
  content: any,
  isError: boolean | any = false,
  ...extraArgs: any[]
): any {
  // Handle flexible parameters for Phase 1 compatibility
  const actualIsError = typeof isError === "boolean" ? isError : false;
  const metadata = extraArgs.length > 0 ? extraArgs[0] : {};

  // Use shared response builder for consistency
  if (actualIsError) {
    // For errors, we might want to use createErrorResponse, but for compatibility, use createSystemResponse
    return createSystemResponse(
      Array.isArray(content)
        ? content[0]?.text || String(content)
        : String(content),
      "error",
      {
        systemHealth: metadata.systemHealth,
        analytics: metadata.analytics,
        configChanges: metadata.configChanges,
      }
    );
  }

  return createSystemResponse(
    Array.isArray(content)
      ? content[0]?.text || String(content)
      : String(content),
    metadata.operation || "system_action",
    {
      frameworkState: metadata.frameworkState,
      systemHealth: metadata.systemHealth,
      analytics: metadata.analytics,
      configChanges: metadata.configChanges,
    }
  );
}

// Type aliases for compatibility
type ResponseFormatter = SimpleResponseFormatter;
const createResponseFormatter = createSimpleResponseFormatter;
// Analytics service
import { MetricsCollector } from "../metrics/index.js";

/**
 * System analytics interface - optimized for API performance and rich historical context
 */
interface SystemAnalytics {
  // High-frequency API fields (kept for O(1) performance)
  totalExecutions: number;
  successfulExecutions: number;
  failedExecutions: number;
  averageExecutionTime: number; // Critical for dashboard APIs
  gateValidationCount: number;
  uptime: number;
  memoryUsage?: NodeJS.MemoryUsage;

  // Rich historical data with execution context
  performanceTrends: Array<{
    timestamp: number;
    metric:
      | "executionTime"
      | "memoryDelta"
      | "successRate"
      | "gateValidationTime";
    value: number;
    executionMode?: string; // Replaces executionsByMode aggregation
    framework?: string;
    success?: boolean;
  }>;
}

/**
 * Consolidated System Control Tool
 */
export class ConsolidatedSystemControl {
  private logger: Logger;
  private mcpServer: any;
  private configManager?: ConfigManager;
  private safeConfigWriter?: SafeConfigWriter;
  public frameworkStateManager?: FrameworkStateManager;
  private frameworkManager?: FrameworkManager;
  public gateSystemManager?: GateSystemManager;
  private onRestart?: (reason: string) => Promise<void>;
  private toolDescriptionManager?: ToolDescriptionManager;
  private mcpToolsManager?: any; // Reference to MCPToolsManager for tool updates
  private analyticsService?: MetricsCollector;
  private responseFormatter: ResponseFormatter;
  // Phase 3: Prompt guidance service
  private promptGuidanceService?: PromptGuidanceService;
  // Phase 4: Clean architecture gate performance analytics
  public gatePerformanceAnalyzer?: GatePerformanceAnalyzer;
  private gateGuidanceRenderer?: GateGuidanceRenderer;
  public startTime: number = Date.now();

  // Analytics data
  public systemAnalytics: SystemAnalytics = {
    totalExecutions: 0,
    successfulExecutions: 0,
    failedExecutions: 0,
    averageExecutionTime: 0,
    gateValidationCount: 0,
    uptime: 0,
    performanceTrends: [],
  };

  constructor(
    logger: Logger,
    mcpServer: any,
    onRestart?: (reason: string) => Promise<void>
  ) {
    this.logger = logger;
    this.mcpServer = mcpServer;
    this.onRestart = onRestart;
    this.responseFormatter = createResponseFormatter();
  }

  /**
   * Set framework state manager
   */
  setFrameworkStateManager(frameworkStateManager: FrameworkStateManager): void {
    this.frameworkStateManager = frameworkStateManager;
  }

  /**
   * Set framework manager
   */
  setFrameworkManager(frameworkManager: FrameworkManager): void {
    this.frameworkManager = frameworkManager;
  }

  /**
   * Set tool description manager
   */
  setToolDescriptionManager(manager: ToolDescriptionManager): void {
    this.toolDescriptionManager = manager;
  }

  /**
   * Set analytics service
   */
  setAnalyticsService(analyticsService: MetricsCollector): void {
    this.analyticsService = analyticsService;
    this.responseFormatter.setAnalyticsService(analyticsService);
  }

  /**
   * Set config manager for configuration operations
   */
  setConfigManager(configManager: ConfigManager): void {
    this.configManager = configManager;

    // Initialize SafeConfigWriter with the config file path
    try {
      // Get the config file path from the ConfigManager using proper getter method
      const configPath = configManager.getConfigPath();
      this.safeConfigWriter = createSafeConfigWriter(
        this.logger,
        configManager,
        configPath
      );
      this.logger.debug(
        "ConfigManager and SafeConfigWriter configured for system control"
      );
    } catch (error) {
      this.logger.warn("Failed to initialize SafeConfigWriter:", error);
      this.logger.debug(
        "ConfigManager configured for system control (read-only mode)"
      );
    }
  }

  /**
   * Set restart callback (for system restart functionality)
   */
  setRestartCallback(onRestart: (reason: string) => Promise<void>): void {
    this.onRestart = onRestart;
    this.logger.debug("Restart callback configured for system control");
  }

  /**
   * Set MCPToolsManager reference (for dynamic tool updates)
   */
  setMCPToolsManager(mcpToolsManager: any): void {
    this.mcpToolsManager = mcpToolsManager;
    this.logger.debug(
      "MCPToolsManager reference configured for dynamic tool updates"
    );
  }

  /**
   * Set gate performance analyzer (Phase 4 - Clean Architecture)
   */
  setGatePerformanceAnalyzer(analyzer: GatePerformanceAnalyzer): void {
    this.gatePerformanceAnalyzer = analyzer;
    this.logger.debug("Gate performance analyzer configured for analytics");
  }

  /**
   * Set gate system manager for runtime gate management
   */
  setGateSystemManager(gateSystemManager: GateSystemManager): void {
    this.gateSystemManager = gateSystemManager;
    this.logger.debug(
      "Gate system manager configured for runtime gate control"
    );
  }

  /**
   * Set gate guidance renderer for discovery operations
   */
  setGateGuidanceRenderer(renderer: GateGuidanceRenderer): void {
    this.gateGuidanceRenderer = renderer;
    this.logger.debug(
      "Gate guidance renderer configured for gate discovery"
    );
  }

  /**
   * Helper function for minimal outputSchema compliance
   */
  private createMinimalSystemResponse(
    text: string,
    action: string
  ): ToolResponse {
    return createStructuredResponse(text, false, {
      action,
      executionMetadata: {
        executionId: `sc-${action}-${Date.now()}`,
        executionType: "prompt" as const,
        startTime: Date.now(),
        endTime: Date.now(),
        executionTime: 0,
        frameworkEnabled: true,
      },
      systemState: {
        frameworkEnabled: true,
        activeFramework: "CAGEERF",
        availableFrameworks: ["CAGEERF", "ReACT", "5W1H", "SCAMPER"],
        uptime: 0,
        memoryUsage: {
          rss: 0,
          heapTotal: 0,
          heapUsed: 0,
          external: 0,
        },
        serverHealth: "healthy" as const,
      },
    });
  }

  /**
   * Derived calculation: Get execution mode distribution from performance trends
   */
  getExecutionsByMode(): Record<string, number> {
    return this.systemAnalytics.performanceTrends.reduce((acc, trend) => {
      if (trend.executionMode) {
        acc[trend.executionMode] = (acc[trend.executionMode] || 0) + 1;
      }
      return acc;
    }, {} as Record<string, number>);
  }

  /**
   * Update system analytics with rich execution data
   */
  updateAnalytics(
    analytics: Partial<SystemAnalytics> & { currentExecution?: any }
  ): void {
    // Update aggregate fields
    Object.assign(this.systemAnalytics, analytics);
    this.systemAnalytics.uptime = Date.now() - this.startTime;

    // Update memory usage
    this.systemAnalytics.memoryUsage = process.memoryUsage();

    // Record execution time trend with rich context
    if (analytics.currentExecution) {
      const currentExecution = analytics.currentExecution;
      this.systemAnalytics.performanceTrends.push({
        timestamp: Date.now(),
        metric: "executionTime",
        value: currentExecution.executionTime,
        executionMode: currentExecution.executionMode,
        framework: currentExecution.framework,
        success: currentExecution.success,
      });
    }

    // Add memory delta trend if significant change
    if (this.systemAnalytics.memoryUsage) {
      const memoryDelta = this.calculateMemoryDelta();
      if (Math.abs(memoryDelta) > 1024 * 1024) {
        // Only track changes > 1MB
        this.systemAnalytics.performanceTrends.push({
          timestamp: Date.now(),
          metric: "memoryDelta",
          value: memoryDelta,
        });
      }
    }

    // Add success rate trend periodically (every 10 executions)
    if (analytics.totalExecutions && analytics.totalExecutions % 10 === 0) {
      const successRate =
        analytics.totalExecutions > 0
          ? ((analytics.successfulExecutions || 0) /
              analytics.totalExecutions) *
            100
          : 0;
      this.systemAnalytics.performanceTrends.push({
        timestamp: Date.now(),
        metric: "successRate",
        value: successRate,
      });
    }

    // Keep only last 100 trend points
    if (this.systemAnalytics.performanceTrends.length > 100) {
      this.systemAnalytics.performanceTrends.shift();
    }
  }

  /**
   * Calculate memory usage delta from previous execution
   */
  private lastMemoryUsage: number = 0;
  private calculateMemoryDelta(): number {
    if (!this.systemAnalytics.memoryUsage) return 0;

    const currentMemory = this.systemAnalytics.memoryUsage.heapUsed;
    const delta = currentMemory - this.lastMemoryUsage;
    this.lastMemoryUsage = currentMemory;

    return delta;
  }

  /**
   * Main action handler
   */
  public async handleAction(
    args: {
      action: string;
      [key: string]: any;
    },
    extra: any
  ): Promise<ToolResponse> {
    const { action } = args;
    this.logger.info(`⚙️ System Control: Executing action "${action}"`);

    const actionHandler = this.getActionHandler(action);
    return await actionHandler.execute(args);
  }

  /**
   * Get the appropriate action handler based on action type
   */
  private getActionHandler(action: string): ActionHandler {
    switch (action) {
      case "status":
        return new StatusActionHandler(this);
      case "framework":
        return new FrameworkActionHandler(this);
      case "gates":
        return new GateActionHandler(this);
      case "analytics":
        return new AnalyticsActionHandler(this);
      case "config":
        return new ConfigActionHandler(this);
      case "maintenance":
        return new MaintenanceActionHandler(this);
      default:
        throw new Error(
          `Unknown action: ${action}. Valid actions: status, framework, gates, analytics, config, maintenance`
        );
    }
  }

  /**
   * Get comprehensive system status
   */
  public async getSystemStatus(args: {
    include_history?: boolean;
    include_metrics?: boolean;
  }): Promise<ToolResponse> {
    const { include_history = false, include_metrics = true } = args;

    if (!this.frameworkStateManager) {
      throw new Error("Framework state manager not initialized");
    }

    const health = this.frameworkStateManager.getSystemHealth();
    const statusIcon = health.status === "healthy" ? "✅" : "⚠️";

    // Check if framework system is enabled for injection
    const isFrameworkEnabled = health.frameworkSystemEnabled;
    const frameworkStatusIcon = isFrameworkEnabled ? "✅" : "🚫";
    const frameworkStatusText = isFrameworkEnabled
      ? `${frameworkStatusIcon} Enabled (${health.activeFramework})`
      : `${frameworkStatusIcon} Disabled (${health.activeFramework} selected)`;

    let response = `${statusIcon} **System Status Overview**\n\n`;
    response += `**Framework System**: ${frameworkStatusText}\n`;
    response += `**Status**: ${health.status}\n`;
    response += `**Uptime**: ${Math.floor(
      (Date.now() - this.startTime) / 1000 / 60
    )} minutes\n\n`;

    // Add warning message when framework is selected but system disabled
    if (!isFrameworkEnabled && health.activeFramework) {
      response += `⚠️ **Notice**: ${health.activeFramework} is selected but framework injection is disabled.\n`;
      response += `Prompts will execute without methodology guidance.\n`;
      response += `Use \`system_control framework enable\` to activate framework injection.\n\n`;
    }

    if (include_metrics) {
      response += `📊 **Performance Metrics**:\n`;
      response += `- Total Executions: ${this.systemAnalytics.totalExecutions}\n`;
      response += `- Success Rate: ${
        this.systemAnalytics.totalExecutions > 0
          ? Math.round(
              (this.systemAnalytics.successfulExecutions /
                this.systemAnalytics.totalExecutions) *
                100
            )
          : 0
      }%\n`;
      response += `- Average Execution Time: ${this.systemAnalytics.averageExecutionTime}ms\n\n`;
    }

    return this.createMinimalSystemResponse(response, "status");
  }

  // Framework management methods
  public async switchFramework(args: {
    framework?: "CAGEERF" | "ReACT" | "5W1H" | "SCAMPER";
    reason?: string;
  }): Promise<ToolResponse> {
    if (!this.frameworkStateManager) {
      throw new Error("Framework state manager not initialized");
    }

    if (!args.framework) {
      throw new Error("Framework parameter is required for switch operation");
    }

    const { framework, reason = `User requested switch to ${args.framework}` } =
      args;

    const currentState = this.frameworkStateManager.getCurrentState();

    // Check if already active
    if (currentState.activeFramework === framework) {
      return this.createMinimalSystemResponse(
        `ℹ️ Framework '${framework}' is already active. No change needed.`,
        "switch_framework"
      );
    }

    const request: FrameworkSwitchRequest = {
      targetFramework: framework,
      reason: reason,
    };

    const success = await this.frameworkStateManager.switchFramework(request);

    if (success) {
      const newState = this.frameworkStateManager.getCurrentState();
      const activeFramework = this.frameworkStateManager.getActiveFramework();

      let response = `🔄 **Framework Switch Successful**\n\n`;
      response += `**Previous**: ${currentState.activeFramework}\n`;
      response += `**Current**: ${newState.activeFramework}\n`;
      response += `**Switched At**: ${newState.switchedAt.toISOString()}\n`;
      response += `**Reason**: ${reason}\n\n`;
      response += `**New Framework Details**:\n`;
      response += `- **Name**: ${activeFramework.name}\n`;
      response += `- **Description**: ${activeFramework.description}\n`;
      response += `- **Methodology**: ${activeFramework.methodology}\n\n`;
      response += `**Guidelines**: ${activeFramework.executionGuidelines.join(
        " • "
      )}\n\n`;
      response += `✅ All future prompt executions will now use the ${framework} methodology.`;

      return this.createMinimalSystemResponse(response, "switch_framework");
    } else {
      throw new Error(
        `Failed to switch to framework '${framework}'. Please check framework availability and try again.`
      );
    }
  }

  public async listFrameworks(args: {
    show_details?: boolean;
  }): Promise<ToolResponse> {
    if (!this.frameworkManager) {
      throw new Error("Framework manager not initialized");
    }

    const frameworks = this.frameworkManager.listFrameworks();
    const currentState = this.frameworkStateManager?.getCurrentState();
    const activeFramework = currentState?.activeFramework || "CAGEERF";

    let response = `📋 **Available Frameworks**\n\n`;

    frameworks.forEach((framework: any) => {
      // Handle case variations by comparing uppercase versions
      const isActive =
        framework.id.toUpperCase() === activeFramework.toUpperCase();
      const status = isActive ? "🟢 ACTIVE" : "⚪ Available";

      response += `**${framework.name}** ${status}\n`;

      if (args.show_details) {
        response += `   📝 ${framework.description}\n`;
        response += `   🎯 Methodology: ${framework.methodology}\n`;
        if (
          framework.executionGuidelines &&
          framework.executionGuidelines.length > 0
        ) {
          response += `   📋 Guidelines: ${framework.executionGuidelines
            .slice(0, 2)
            .join(" • ")}\n`;
        }
        response += `\n`;
      }
    });

    if (!args.show_details) {
      response += `\n💡 Use 'show_details: true' for more information about each framework.\n`;
    }

    response += `\n🔄 Switch frameworks using: action="framework", operation="switch", framework="<name>"`;

    return this.createMinimalSystemResponse(response, "list_frameworks");
  }

  public async enableFrameworkSystem(args: {
    reason?: string;
  }): Promise<ToolResponse> {
    if (!this.frameworkStateManager) {
      throw new Error("Framework state manager not initialized");
    }

    const currentState = this.frameworkStateManager.getCurrentState();
    if (currentState.frameworkSystemEnabled) {
      return this.createMinimalSystemResponse(
        `ℹ️ Framework system is already enabled.`,
        "enable_framework_system"
      );
    }

    // Enable framework system (for now, just return success message since the method may not exist)
    try {
      await (this.frameworkStateManager as any).enableFrameworkSystem?.(
        args.reason || "User requested to enable framework system"
      );
    } catch (error) {
      // Method may not exist, that's ok for now
    }

    const response =
      `✅ **Framework System Enabled**\n\n` +
      `**Reason**: ${
        args.reason || "User requested to enable framework system"
      }\n` +
      `**Status**: Framework system is now active\n` +
      `**Active Framework**: ${currentState.activeFramework}\n\n` +
      `🎯 All prompt executions will now use framework-guided processing.`;

    return this.createMinimalSystemResponse(
      response,
      "enable_framework_system"
    );
  }

  public async disableFrameworkSystem(args: {
    reason?: string;
  }): Promise<ToolResponse> {
    if (!this.frameworkStateManager) {
      throw new Error("Framework state manager not initialized");
    }

    const currentState = this.frameworkStateManager.getCurrentState();
    if (!currentState.frameworkSystemEnabled) {
      return this.createMinimalSystemResponse(
        `ℹ️ Framework system is already disabled.`,
        "disable_framework_system"
      );
    }

    // Disable framework system (for now, just return success message since the method may not exist)
    try {
      await (this.frameworkStateManager as any).disableFrameworkSystem?.(
        args.reason || "User requested to disable framework system"
      );
    } catch (error) {
      // Method may not exist, that's ok for now
    }

    const response =
      `⚠️ **Framework System Disabled**\n\n` +
      `**Reason**: ${
        args.reason || "User requested to disable framework system"
      }\n` +
      `**Status**: Framework system is now inactive\n` +
      `**Previous Framework**: ${currentState.activeFramework}\n\n` +
      `📝 Prompt executions will now use basic processing without framework guidance.`;

    return this.createMinimalSystemResponse(
      response,
      "disable_framework_system"
    );
  }

  /**
   * Enable gate system
   */
  public async enableGateSystem(args: {
    reason?: string;
  }): Promise<ToolResponse> {
    if (!this.gateSystemManager) {
      throw new Error("Gate system manager not initialized");
    }

    const currentState = this.gateSystemManager.getCurrentState();
    if (currentState.enabled) {
      return this.createMinimalSystemResponse(
        `ℹ️ Gate system is already enabled.`,
        "enable_gate_system"
      );
    }

    await this.gateSystemManager.enableGateSystem(
      args.reason || "User requested to enable gate system"
    );

    const response =
      `✅ **Gate System Enabled**\n\n` +
      `**Reason**: ${args.reason || "User requested to enable gate system"}\n` +
      `**Status**: Gate system is now active\n` +
      `**Validation**: Quality gates will now be applied to prompt executions\n\n` +
      `🔍 All template and chain executions will now include gate validation and guidance.`;

    return this.createMinimalSystemResponse(response, "enable_gate_system");
  }

  /**
   * Disable gate system
   */
  public async disableGateSystem(args: {
    reason?: string;
  }): Promise<ToolResponse> {
    if (!this.gateSystemManager) {
      throw new Error("Gate system manager not initialized");
    }

    const currentState = this.gateSystemManager.getCurrentState();
    if (!currentState.enabled) {
      return this.createMinimalSystemResponse(
        `ℹ️ Gate system is already disabled.`,
        "disable_gate_system"
      );
    }

    await this.gateSystemManager.disableGateSystem(
      args.reason || "User requested to disable gate system"
    );

    const response =
      `⚠️ **Gate System Disabled**\n\n` +
      `**Reason**: ${
        args.reason || "User requested to disable gate system"
      }\n` +
      `**Status**: Gate system is now inactive\n` +
      `**Impact**: Gate validation and guidance will be skipped\n\n` +
      `📝 Prompt executions will now skip quality gate validation.`;

    return this.createMinimalSystemResponse(response, "disable_gate_system");
  }

  /**
   * Get gate system status
   */
  public async getGateSystemStatus(): Promise<ToolResponse> {
    if (!this.gateSystemManager) {
      return this.createMinimalSystemResponse(
        `❌ Gate system manager not available.`,
        "gate_system_status"
      );
    }

    const currentState = this.gateSystemManager.getCurrentState();
    const health = this.gateSystemManager.getSystemHealth();

    let response = `🚪 **Gate System Status**\n\n`;
    response += `**System State**: ${
      currentState.enabled ? "Enabled" : "Disabled"
    }\n`;
    response += `**Health Status**: ${health.status}\n`;
    response += `**Total Validations**: ${health.totalValidations}\n`;
    response += `**Success Rate**: ${health.successRate}%\n`;
    response += `**Average Validation Time**: ${health.averageValidationTime}ms\n`;

    if (health.lastValidationTime) {
      response += `**Last Validation**: ${health.lastValidationTime.toISOString()}\n`;
    }

    if (health.issues.length > 0) {
      response += `\n⚠️ **Issues**:\n`;
      health.issues.forEach((issue) => {
        response += `- ${issue}\n`;
      });
    }

    response += `\n🔧 Control gates using: action="gates", operation="enable/disable"`;

    return this.createMinimalSystemResponse(response, "gate_system_status");
  }

  /**
   * Get gate system health details
   */
  public async getGateSystemHealth(): Promise<ToolResponse> {
    if (!this.gateSystemManager) {
      return this.createMinimalSystemResponse(
        `❌ Gate system manager not available.`,
        "gate_system_health"
      );
    }

    const health = this.gateSystemManager.getSystemHealth();

    let response = `🏥 **Gate System Health Report**\n\n`;

    // Health status indicator
    const statusIcon =
      health.status === "healthy"
        ? "✅"
        : health.status === "degraded"
        ? "⚠️"
        : "❌";
    response += `**Overall Status**: ${statusIcon} ${health.status.toUpperCase()}\n\n`;

    // Core metrics
    response += `**Performance Metrics**:\n`;
    response += `- Enabled: ${health.enabled ? "Yes" : "No"}\n`;
    response += `- Total Validations: ${health.totalValidations}\n`;
    response += `- Success Rate: ${health.successRate}%\n`;
    response += `- Average Validation Time: ${health.averageValidationTime}ms\n`;

    if (health.lastValidationTime) {
      response += `- Last Validation: ${health.lastValidationTime.toISOString()}\n`;
    }

    // Health analysis
    if (health.status === "healthy") {
      response += "\n✅ System is performing optimally. No action required.\n";
    } else if (health.status === "degraded") {
      response += "\n⚠️ System performance is degraded. Monitor closely.\n";
      if (health.issues.length > 0) {
        response += "\n**Issues Detected**:\n";
        health.issues.forEach((issue) => {
          response += `- ${issue}\n`;
        });
      }
    } else if (health.status === "disabled") {
      response += "\n🚫 Gate system is currently disabled.\n";
      response += "Enable using: `action='gates', operation='enable'`\n";
    }

    return this.createMinimalSystemResponse(response, "gate_system_health");
  }

  /**
   * List all available quality gates
   */
  async listAvailableGates(): Promise<ToolResponse> {
    const gates =
      (await this.gateGuidanceRenderer?.getAvailableGates()) || [];

    const gateList = gates.length
      ? gates.map((gate) => `• ${gate}`).join("\n")
      : "• No quality gates discovered. Ensure gate configuration is available.";

    const exampleGate = gates[0] || "gate-name";

    const response = [
      "📋 **Available Quality Gates**",
      "",
      "Discover gates using: `system_control({ action: \"gates\", operation: \"list\" })`",
      "",
      gateList,
      "",
      "**Usage**: Specify gate names in prompt_engine's `quality_gates` parameter",
      `**Example**: \`{ \\\"quality_gates\\\": [\"${exampleGate}\"], \\\"gate_mode\\\": \"enforce\" }\``,
    ].join("\n");

    return this.createMinimalSystemResponse(response, "gate_list");
  }

  public async resetMetrics(args: any): Promise<ToolResponse> {
    throw new Error("resetMetrics method not yet implemented");
  }

  public async getSwitchHistory(args: any): Promise<ToolResponse> {
    throw new Error("getSwitchHistory method not yet implemented");
  }

  public async getAnalytics(args: any): Promise<ToolResponse> {
    throw new Error("getAnalytics method not yet implemented");
  }

  public async restoreConfig(args: any): Promise<ToolResponse> {
    throw new Error("restoreConfig method not yet implemented");
  }

  public async manageConfig(args: any): Promise<ToolResponse> {
    throw new Error("manageConfig method not yet implemented");
  }

  public async restartServer(args: any): Promise<ToolResponse> {
    throw new Error("restartServer method not yet implemented");
  }
}

/**
 * Base class for action handlers using command pattern
 */
abstract class ActionHandler {
  constructor(protected systemControl: ConsolidatedSystemControl) {}
  abstract execute(args: any): Promise<ToolResponse>;

  // Convenience getters for accessing system control properties
  protected get responseFormatter() {
    return this.systemControl["responseFormatter"];
  }
  protected get logger() {
    return this.systemControl["logger"];
  }
  protected get startTime() {
    return this.systemControl.startTime;
  }
  protected get frameworkManager() {
    return this.systemControl["frameworkManager"];
  }
  protected get mcpToolsManager() {
    return this.systemControl["mcpToolsManager"];
  }
  protected get configManager() {
    return this.systemControl["configManager"];
  }
  protected get safeConfigWriter() {
    return this.systemControl["safeConfigWriter"];
  }
  protected get onRestart() {
    return this.systemControl["onRestart"];
  }

  // Helper methods for system status and formatting
  protected createMinimalSystemResponse(
    text: string,
    action: string
  ): ToolResponse {
    return createStructuredResponse(text, false, {
      action,
      systemState: {
        uptime: Date.now() - this.startTime,
        framework:
          this.systemControl.frameworkStateManager?.getCurrentState()
            .activeFramework,
      },
    });
  }

  protected getExecutionsByMode(): Record<string, number> {
    // Extract execution mode data from performance trends
    const modeData: Record<string, number> = {};
    this.systemControl.systemAnalytics.performanceTrends.forEach((trend) => {
      if (trend.executionMode) {
        modeData[trend.executionMode] =
          (modeData[trend.executionMode] || 0) + 1;
      }
    });
    return modeData;
  }

  protected formatUptime(uptime: number): string {
    const seconds = Math.floor(uptime / 1000);
    const minutes = Math.floor(seconds / 60);
    const hours = Math.floor(minutes / 60);
    const days = Math.floor(hours / 24);

    if (days > 0) return `${days}d ${hours % 24}h ${minutes % 60}m`;
    if (hours > 0) return `${hours}h ${minutes % 60}m`;
    if (minutes > 0) return `${minutes}m ${seconds % 60}s`;
    return `${seconds}s`;
  }

  protected formatExecutionTime(time: number): string {
    return `${Math.round(time)}ms`;
  }

  protected formatBytes(bytes: number): string {
    const units = ["B", "KB", "MB", "GB"];
    let value = bytes;
    let unitIndex = 0;
    while (value >= 1024 && unitIndex < units.length - 1) {
      value /= 1024;
      unitIndex++;
    }
    return `${Math.round(value * 100) / 100}${units[unitIndex]}`;
  }

  protected getHealthIcon(status: string): string {
    switch (status) {
      case "healthy":
        return "✅";
      case "warning":
        return "⚠️";
      case "error":
        return "❌";
      case "critical":
        return "🚨";
      default:
        return "❓";
    }
  }

  protected getSuccessRate(): number {
    const total = this.systemControl.systemAnalytics.totalExecutions;
    if (total === 0) return 100;
    return Math.round(
      (this.systemControl.systemAnalytics.successfulExecutions / total) * 100
    );
  }

  protected formatTrendContext(trend: any): string {
    let context = "";
    if (trend.framework) context += ` [${trend.framework}]`;
    if (trend.executionMode) context += ` (${trend.executionMode})`;
    if (trend.success !== undefined) context += trend.success ? " ✓" : " ✗";
    return context;
  }

  protected formatTrendValue(metric: string, value: number): string {
    switch (metric) {
      case "executionTime":
        return `${Math.round(value)}ms`;
      case "memoryDelta":
        return `${value > 0 ? "+" : ""}${this.formatBytes(value)}`;
      case "successRate":
        return `${Math.round(value * 100)}%`;
      case "gateValidationTime":
        return `${Math.round(value)}ms validation`;
      default:
        return String(value);
    }
  }
}

/**
 * Handler for status-related operations
 */
class StatusActionHandler extends ActionHandler {
  async execute(args: any): Promise<ToolResponse> {
    const operation = args.operation || "default";

    switch (operation) {
      case "health":
        return await this.getSystemHealthStatus();
      case "diagnostics":
        return await this.getSystemDiagnostics();
      case "framework_status":
        return await this.getFrameworkStatus();
      case "overview":
      case "default":
      default:
        return await this.systemControl.getSystemStatus({
          include_history: args.include_history,
          include_metrics: args.include_metrics,
        });
    }
  }

  private async getSystemHealthStatus(): Promise<ToolResponse> {
    if (!this.systemControl.frameworkStateManager) {
      throw new Error("Framework state manager not initialized");
    }

    const health = this.systemControl.frameworkStateManager.getSystemHealth();
    const statusIcon = health.status === "healthy" ? "✅" : "⚠️";

    let response = `${statusIcon} **System Health Status**: ${health.status}\n\n`;
    response += `📊 **Metrics**:\n`;

    // Improved framework status display
    const isFrameworkEnabled = health.frameworkSystemEnabled;
    const injectionStatus = isFrameworkEnabled ? "Working" : "Inactive";
    const frameworkStatusText = isFrameworkEnabled
      ? `✅ Enabled - ${health.activeFramework} methodology active`
      : `🚫 Disabled - ${health.activeFramework} selected but not injecting`;

    response += `- Framework System: ${frameworkStatusText}\n`;
    response += `- Framework Injection: ${injectionStatus}\n`;
    response += `- Available Frameworks: ${health.availableFrameworks.join(
      ", "
    )}\n`;
    response += `- Total Framework Switches: ${health.switchingMetrics.totalSwitches}\n`;

    return this.createMinimalSystemResponse(response, "health");
  }

  private async getSystemDiagnostics(): Promise<ToolResponse> {
    let response = `🔧 **System Diagnostics**\n\n`;

    try {
      if (this.systemControl.frameworkStateManager) {
        const health =
          this.systemControl.frameworkStateManager.getSystemHealth();
        response += `Framework State: ${health.status}\n`;
        response += `Active Framework: ${health.activeFramework}\n`;
      }

      response += `Server Uptime: ${
        Date.now() - this.systemControl.startTime
      }ms\n`;
    } catch (error) {
      response += `❌ Error during diagnostics: ${error}\n`;
    }

    return this.createMinimalSystemResponse(response, "diagnostics");
  }

  private async getFrameworkStatus(): Promise<ToolResponse> {
    if (!this.systemControl.frameworkStateManager) {
      throw new Error("Framework state manager not initialized");
    }

    const health = this.systemControl.frameworkStateManager.getSystemHealth();

    let response = `🎯 **Framework System Status**\n\n`;

    // Enhanced status display
    const isFrameworkEnabled = health.frameworkSystemEnabled;
    const injectionStatusIcon = isFrameworkEnabled ? "✅" : "🚫";
    const injectionStatusText = isFrameworkEnabled
      ? "Active - Framework guidance being applied"
      : "Inactive - Framework guidance disabled";

    response += `**Selected Framework**: ${health.activeFramework}\n`;
    response += `**Injection Status**: ${injectionStatusIcon} ${injectionStatusText}\n`;
    response += `**System State**: ${
      health.frameworkSystemEnabled ? "Enabled" : "Disabled"
    }\n`;
    response += `**Health Status**: ${health.status}\n`;
    response += `**Available Frameworks**: ${health.availableFrameworks.join(
      ", "
    )}\n`;

    // Add warning for confused state
    if (!isFrameworkEnabled && health.activeFramework) {
      response += `\n⚠️ **Warning**: Framework system is disabled while ${health.activeFramework} is selected.\n`;
      response += `This means prompts will NOT receive framework methodology guidance.\n`;
      response += `To enable framework injection, use: \`system_control framework enable\`\n`;
    }

    return this.createMinimalSystemResponse(response, "framework_status");
  }
}

/**
 * Handler for framework-related operations
 */
class FrameworkActionHandler extends ActionHandler {
  async execute(args: any): Promise<ToolResponse> {
    const operation = args.operation || "default";

    switch (operation) {
      case "switch":
        return await this.systemControl.switchFramework({
          framework: args.framework,
          reason: args.reason,
        });
      case "list":
        return await this.systemControl.listFrameworks({
          show_details: args.show_details,
        });
      case "enable":
        return await this.systemControl.enableFrameworkSystem({
          reason: args.reason,
        });
      case "disable":
        return await this.systemControl.disableFrameworkSystem({
          reason: args.reason,
        });
      default:
        throw new Error(
          `Unknown framework operation: ${operation}. Valid operations: switch, list, enable, disable`
        );
    }
  }
}

/**
 * Handler for gates-related operations
 */
class GateActionHandler extends ActionHandler {
  async execute(args: any): Promise<ToolResponse> {
    const operation = args.operation || "status";

    switch (operation) {
      case "enable":
        return await this.systemControl.enableGateSystem({
          reason: args.reason,
        });
      case "disable":
        return await this.systemControl.disableGateSystem({
          reason: args.reason,
        });
      case "status":
        return await this.systemControl.getGateSystemStatus();
      case "health":
        return await this.systemControl.getGateSystemHealth();
      case "list":
        return await this.systemControl.listAvailableGates();
      default:
        throw new Error(
          `Unknown gates operation: ${operation}. Valid operations: enable, disable, status, health, list`
        );
    }
  }
}

/**
 * Handler for analytics-related operations
 */
class AnalyticsActionHandler extends ActionHandler {
  async execute(args: any): Promise<ToolResponse> {
    const operation = args.operation || "default";

    switch (operation) {
      case "reset":
        return await this.systemControl.resetMetrics({
          confirm: args.confirm,
        });
      case "history":
        return await this.systemControl.getSwitchHistory({
          limit: args.limit,
        });
      case "view":
      case "default":
      default:
        return await this.systemControl.getAnalytics({
          include_history: args.include_history,
          reset_analytics: args.reset_analytics,
        });
    }
  }
}

/**
 * Handler for config-related operations
 */
class ConfigActionHandler extends ActionHandler {
  async execute(args: any): Promise<ToolResponse> {
    const operation = args.operation || "default";

    switch (operation) {
      case "restore":
        return await this.systemControl.restoreConfig({
          backup_path: args.backup_path,
          confirm: args.confirm,
        });
      case "get":
      case "set":
      case "list":
      case "validate":
      case "default":
      default:
        return await this.systemControl.manageConfig({
          config: args.config,
        });
    }
  }
}

/**
 * Handler for maintenance-related operations
 */
class MaintenanceActionHandler extends ActionHandler {
  async execute(args: any): Promise<ToolResponse> {
    const operation = args.operation || "default";

    switch (operation) {
      case "restart":
      case "default":
      default:
        return await this.systemControl.restartServer({
          reason: args.reason,
          confirm: args.confirm,
        });
    }
  }

  /**
   * Get comprehensive system status
   */
  public async getSystemStatus(args: {
    include_history?: boolean;
    include_metrics?: boolean;
  }): Promise<ToolResponse> {
    const { include_history = false, include_metrics = true } = args;

    if (!this.systemControl.frameworkStateManager) {
      throw new Error("Framework state manager not initialized");
    }

    const currentState =
      this.systemControl.frameworkStateManager.getCurrentState();
    const systemHealth =
      this.systemControl.frameworkStateManager.getSystemHealth();
    const activeFramework =
      this.systemControl.frameworkStateManager.getActiveFramework();

    let response = "# ⚙️ System Status Report\n\n";

    // Framework Status
    response += "## 📋 Framework Status\n\n";
    response += `**Active Framework**: ${activeFramework.name} (${activeFramework.id})\n`;
    response += `**Description**: ${activeFramework.description}\n`;
    response += `**System Health**: ${this.getHealthIcon(
      systemHealth.status
    )} ${systemHealth.status.toUpperCase()}\n`;
    response += `**Last Switch**: ${currentState.switchedAt.toISOString()}\n`;
    response += `**Switch Reason**: ${currentState.switchReason}\n\n`;

    // Gate System Status
    if (this.systemControl.gateSystemManager) {
      const gateHealth = this.systemControl.gateSystemManager.getSystemHealth();
      response += "## 🚪 Gate System Status\n\n";
      response += `**System State**: ${
        gateHealth.enabled ? "Enabled" : "Disabled"
      }\n`;
      response += `**Health Status**: ${this.getHealthIcon(
        gateHealth.status
      )} ${gateHealth.status.toUpperCase()}\n`;
      response += `**Total Validations**: ${gateHealth.totalValidations}\n`;
      response += `**Success Rate**: ${gateHealth.successRate}%\n`;
      if (gateHealth.lastValidationTime) {
        response += `**Last Validation**: ${gateHealth.lastValidationTime.toISOString()}\n`;
      }
      response += `\n`;
    } else {
      response += "## 🚪 Gate System Status\n\n";
      response += `**System State**: Not Available\n`;
      response += `**Note**: Gate system manager not initialized\n\n`;
    }

    // System Metrics
    response += "## 📊 System Metrics\n\n";
    response += `**Uptime**: ${this.formatUptime(
      this.systemControl.systemAnalytics.uptime
    )}\n`;
    response += `**Total Executions**: ${this.systemControl.systemAnalytics.totalExecutions}\n`;
    response += `**Success Rate**: ${this.getSuccessRate()}%\n`;
    response += `**Average Execution Time**: ${this.formatExecutionTime(
      this.systemControl.systemAnalytics.averageExecutionTime
    )}\n`;

    if (this.systemControl.systemAnalytics.memoryUsage) {
      const mem = this.systemControl.systemAnalytics.memoryUsage;
      response += `**Memory Usage**: ${this.formatBytes(
        mem.heapUsed
      )}/${this.formatBytes(mem.heapTotal)}\n`;
    }

    response += `\n`;

    // Available Frameworks
    const availableFrameworks =
      this.systemControl.frameworkStateManager.getAvailableFrameworks();
    response += "## 🔄 Available Frameworks\n\n";
    availableFrameworks.forEach((framework) => {
      const isActive = framework.id === currentState.activeFramework;
      const icon = isActive ? "🟢" : "⚪";
      response += `${icon} **${framework.name}** - ${framework.description}\n`;
    });
    response += "\n";

    // Performance Metrics
    if (include_metrics) {
      response += "## 🎯 Performance Breakdown\n\n";
      const switchingMetrics = systemHealth.switchingMetrics;
      response += `**Framework Switches**: ${switchingMetrics.totalSwitches}\n`;
      response += `**Framework Switch Success Rate**: ${
        switchingMetrics.totalSwitches > 0
          ? Math.round(
              (switchingMetrics.successfulSwitches /
                switchingMetrics.totalSwitches) *
                100
            )
          : 100
      }%\n`;
      response += `**Framework Switch Time**: ${Math.round(
        switchingMetrics.averageResponseTime
      )}ms\n`;

      response += `\n**Execution Modes**:\n`;
      const executionsByMode = this.getExecutionsByMode();
      Object.entries(executionsByMode).forEach(([mode, count]) => {
        response += `- ${
          mode.charAt(0).toUpperCase() + mode.slice(1)
        }: ${count} executions\n`;
      });
      response += `\n`;
    }

    // System Health Issues
    if (systemHealth.issues.length > 0) {
      response += "## ⚠️ System Issues\n\n";
      systemHealth.issues.forEach((issue) => {
        response += `- ⚠️ ${issue}\n`;
      });
      response += "\n";
    }

    // Recent Activity
    if (
      include_history &&
      this.systemControl.systemAnalytics.performanceTrends.length > 0
    ) {
      response += "## 📈 Recent Performance Trends\n\n";
      const recentTrends =
        this.systemControl.systemAnalytics.performanceTrends.slice(-10);
      recentTrends.forEach((trend, index) => {
        const timestamp = new Date(trend.timestamp)
          .toISOString()
          .split("T")[1]
          .split(".")[0];
        const contextInfo = this.formatTrendContext(trend);
        response += `${index + 1}. ${timestamp}: ${this.formatTrendValue(
          trend.metric,
          trend.value
        )}${contextInfo}\n`;
      });
      response += "\n";
    }

    // Control Commands
    response += "## 🎛️ Available Commands\n\n";
    response += "- `switch_framework` - Change active framework methodology\n";
    response +=
      "- `gates` - Control gate system (enable, disable, status, health)\n";
    response += "- `analytics` - View detailed execution analytics\n";
    response += "- `health` - Check system health status\n";
    response += "- `diagnostics` - Run comprehensive system diagnostics\n";
    response +=
      "- `config` - Manage system configuration (get, set, list, validate)\n";
    response += "- `config_restore` - Restore configuration from backup\n";
    response += "- `reset_metrics` - Reset framework switching counters\n";
    response += "- `switch_history` - View framework change history\n";
    response += "- `restart` - Full server restart (requires confirmation)\n";

    return this.responseFormatter.formatSystemControlResponse(
      response,
      "status",
      {
        frameworkEnabled: currentState.frameworkSystemEnabled,
        activeFramework: activeFramework.name,
        availableFrameworks:
          this.frameworkManager?.listFrameworks().map((f: any) => f.name) || [],
        uptime: (Date.now() - this.startTime) / 1000,
        memoryUsage: process.memoryUsage ? process.memoryUsage() : undefined,
        serverHealth: systemHealth.status as
          | "healthy"
          | "warning"
          | "error"
          | "critical",
        lastFrameworkSwitch: currentState.switchedAt.toISOString(),
      },
      undefined,
      {
        includeStructuredData: true,
      }
    );
  }

  /**
   * Switch framework
   */
  public async switchFramework(args: {
    framework?: "CAGEERF" | "ReACT" | "5W1H" | "SCAMPER";
    reason?: string;
  }): Promise<ToolResponse> {
    if (!this.systemControl.frameworkStateManager) {
      throw new Error("Framework state manager not initialized");
    }

    if (!args.framework) {
      throw new Error("Framework parameter is required for switch operation");
    }

    const { framework, reason = `User requested switch to ${args.framework}` } =
      args;

    const currentState =
      this.systemControl.frameworkStateManager.getCurrentState();

    // Check if already active
    if (currentState.activeFramework === framework) {
      return this.createMinimalSystemResponse(
        `ℹ️ Framework '${framework}' is already active. No change needed.`,
        "switch_framework"
      );
    }

    const request: FrameworkSwitchRequest = {
      targetFramework: framework,
      reason: reason,
    };

    const success =
      await this.systemControl.frameworkStateManager.switchFramework(request);

    if (success) {
      const newState =
        this.systemControl.frameworkStateManager.getCurrentState();
      const activeFramework =
        this.systemControl.frameworkStateManager.getActiveFramework();

      let response = `🔄 **Framework Switch Successful**\n\n`;
      response += `**Previous**: ${currentState.activeFramework}\n`;
      response += `**Current**: ${newState.activeFramework}\n`;
      response += `**Switched At**: ${newState.switchedAt.toISOString()}\n`;
      response += `**Reason**: ${reason}\n\n`;
      response += `**New Framework Details**:\n`;
      response += `- **Name**: ${activeFramework.name}\n`;
      response += `- **Description**: ${activeFramework.description}\n`;
      response += `- **Methodology**: ${activeFramework.methodology}\n\n`;
      response += `**Guidelines**: ${activeFramework.executionGuidelines.join(
        " • "
      )}\n\n`;
      response += `✅ All future prompt executions will now use the ${framework} methodology.`;

      // Trigger dynamic tool description updates
      if (this.mcpToolsManager?.reregisterToolsWithUpdatedDescriptions) {
        try {
          await this.mcpToolsManager.reregisterToolsWithUpdatedDescriptions();
          response += `\n\n🔄 **Tool descriptions updated** - MCP clients will receive updated tool descriptions with ${framework} methodology guidance.`;
        } catch (error) {
          this.logger.error(
            `Failed to update tool descriptions after framework switch: ${
              error instanceof Error ? error.message : String(error)
            }`
          );
          response += `\n\n⚠️ **Note**: Tool descriptions may need manual refresh for some clients.`;
        }
      }

      return this.createMinimalSystemResponse(response, "switch_framework");
    } else {
      return this.createMinimalSystemResponse(
        `❌ Failed to switch to framework '${framework}'. Check system logs for details.`,
        "switch_framework"
      );
    }
  }

  /**
   * List available frameworks
   */
  public async listFrameworks(args: {
    show_details?: boolean;
  }): Promise<ToolResponse> {
    if (!this.systemControl.frameworkStateManager) {
      throw new Error("Framework state manager not initialized");
    }

    const { show_details = true } = args;

    const currentState =
      this.systemControl.frameworkStateManager.getCurrentState();
    const availableFrameworks =
      this.systemControl.frameworkStateManager.getAvailableFrameworks();

    let response = "# 📋 Available Framework Methodologies\n\n";
    response += `**Currently Active**: ${currentState.activeFramework}\n\n`;

    availableFrameworks.forEach((framework) => {
      const isActive = framework.id === currentState.activeFramework;
      const icon = isActive ? "🟢" : "⚪";
      const status = isActive ? " (ACTIVE)" : "";

      response += `## ${icon} ${framework.name}${status}\n\n`;
      response += `**ID**: ${framework.id}\n`;
      response += `**Methodology**: ${framework.methodology}\n`;
      response += `**Description**: ${framework.description}\n`;
      response += `**Priority**: ${framework.priority}\n`;
      response += `**Enabled**: ${framework.enabled ? "✅ Yes" : "❌ No"}\n`;
      response += `**Applicable Types**: ${
        framework.applicableTypes.join(", ") || "All"
      }\n`;

      if (show_details && framework.executionGuidelines) {
        response += `\n**Execution Guidelines**:\n`;
        framework.executionGuidelines.forEach((guideline, index) => {
          response += `${index + 1}. ${guideline}\n`;
        });
      }

      response += "\n";
    });

    response += "---\n\n";
    response +=
      "**Usage**: Use `switch_framework` action to change the active framework methodology.\n";
    response +=
      "**Note**: The framework methodology determines how prompts are processed systematically.";

    return this.createMinimalSystemResponse(response, "list_frameworks");
  }

  /**
   * Get execution analytics
   */
  public async getAnalytics(args: {
    include_history?: boolean;
    reset_analytics?: boolean;
  }): Promise<ToolResponse> {
    const { include_history = false, reset_analytics = false } = args;

    if (reset_analytics) {
      this.resetAnalyticsData();
      return this.createMinimalSystemResponse(
        "📊 Analytics have been reset to zero.",
        "analytics"
      );
    }

    const successRate = this.getSuccessRate();
    const avgTime = this.formatExecutionTime(
      this.systemControl.systemAnalytics.averageExecutionTime
    );

    let response = "# 📊 System Analytics Report\n\n";

    // Overall Performance
    response += "## 📈 Overall Performance\n\n";
    response += `**Total Executions**: ${this.systemControl.systemAnalytics.totalExecutions}\n`;
    response += `**Success Rate**: ${successRate}%\n`;
    response += `**Failed Executions**: ${this.systemControl.systemAnalytics.failedExecutions}\n`;
    response += `**Average Execution Time**: ${avgTime}\n`;
    response += `**System Uptime**: ${this.formatUptime(
      this.systemControl.systemAnalytics.uptime
    )}\n\n`;

    // Execution Modes
    response += "## 🎯 Execution Mode Distribution\n\n";
    const executionsByMode = this.getExecutionsByMode();
    const totalModeExecutions = Object.values(executionsByMode).reduce(
      (a, b) => a + b,
      0
    );
    Object.entries(executionsByMode).forEach(([mode, count]) => {
      const percentage =
        totalModeExecutions > 0
          ? Math.round((count / totalModeExecutions) * 100)
          : 0;
      response += `- **${
        mode.charAt(0).toUpperCase() + mode.slice(1)
      } Mode**: ${count} executions (${percentage}%)\n`;
    });
    response += "\n";

    // Quality Gates (Phase 4: Enhanced with advanced analytics)
    response += "## 🛡️ Quality Gate Analytics\n\n";
    response += `**Gate Validations**: ${this.systemControl.systemAnalytics.gateValidationCount}\n`;
    response += `**Gate Adoption Rate**: ${
      this.systemControl.systemAnalytics.totalExecutions > 0
        ? Math.round(
            (this.systemControl.systemAnalytics.gateValidationCount /
              this.systemControl.systemAnalytics.totalExecutions) *
              100
          )
        : 0
    }%\n`;

    // Phase 4: Clean architecture gate performance analytics
    if (this.systemControl.gatePerformanceAnalyzer) {
      try {
        const gateAnalytics =
          this.systemControl.gatePerformanceAnalyzer.getPerformanceAnalytics();
        response += `**Advanced Gate System**: Enabled\n`;
        response += `**Total Gates Tracked**: ${gateAnalytics.totalGates}\n`;
        response += `**Average Gate Execution Time**: ${Math.round(
          gateAnalytics.avgExecutionTime
        )}ms\n`;
        response += `**Overall Gate Success Rate**: ${Math.round(
          gateAnalytics.overallSuccessRate * 100
        )}%\n`;

        if (gateAnalytics.topPerformingGates.length > 0) {
          response += `**Top Performing Gates**: ${gateAnalytics.topPerformingGates.join(
            ", "
          )}\n`;
        }

        if (gateAnalytics.underperformingGates.length > 0) {
          response += `**Needs Optimization**: ${gateAnalytics.underperformingGates.join(
            ", "
          )}\n`;
        }

        if (gateAnalytics.recommendations.length > 0) {
          response += `\n**Optimization Recommendations**:\n`;
          gateAnalytics.recommendations.forEach(
            (rec: string, index: number) => {
              response += `${index + 1}. ${rec}\n`;
            }
          );
        }
      } catch (error) {
        response += `**Advanced Gate System**: Error retrieving analytics\n`;
      }
    } else {
      response += `**Advanced Gate System**: Not available\n`;
    }

    response += "\n";

    // System Resources
    if (this.systemControl.systemAnalytics.memoryUsage) {
      response += "## 💾 System Resources\n\n";
      const mem = this.systemControl.systemAnalytics.memoryUsage;
      response += `**Heap Used**: ${this.formatBytes(mem.heapUsed)}\n`;
      response += `**Heap Total**: ${this.formatBytes(mem.heapTotal)}\n`;
      response += `**RSS**: ${this.formatBytes(mem.rss)}\n`;
      response += `**External**: ${this.formatBytes(mem.external)}\n\n`;
    }

    // Performance Trends
    if (
      include_history &&
      this.systemControl.systemAnalytics.performanceTrends.length > 0
    ) {
      response += "## 📈 Performance Trends\n\n";

      // Group trends by metric type for better organization
      const trendsByMetric =
        this.systemControl.systemAnalytics.performanceTrends.reduce(
          (acc, trend) => {
            if (!acc[trend.metric]) acc[trend.metric] = [];
            acc[trend.metric].push(trend);
            return acc;
          },
          {} as Record<string, any[]>
        );

      Object.entries(trendsByMetric).forEach(([metric, trends]) => {
        const recentTrends = trends.slice(-10);
        response += `### ${
          metric.charAt(0).toUpperCase() + metric.slice(1)
        } Trends\n`;
        recentTrends.forEach((trend, index) => {
          const time = new Date(trend.timestamp)
            .toISOString()
            .split("T")[1]
            .split(".")[0];
          const contextInfo = this.formatTrendContext(trend);
          response += `${index + 1}. ${time}: ${this.formatTrendValue(
            trend.metric,
            trend.value
          )}${contextInfo}\n`;
        });
        response += "\n";
      });
    }

    response += `\n---\n*Generated at: ${new Date().toISOString()}*`;

    return this.createMinimalSystemResponse(response, "analytics");
  }

  /**
   * Get system health
   */
  public async getSystemHealth(args: any): Promise<ToolResponse> {
    if (!this.systemControl.frameworkStateManager) {
      throw new Error("Framework state manager not initialized");
    }

    const health = this.systemControl.frameworkStateManager.getSystemHealth();
    const statusIcon = this.getHealthIcon(health.status);

    let response = `# 🏥 System Health Report\n\n`;
    response += `**Overall Status**: ${statusIcon} ${health.status.toUpperCase()}\n`;
    response += `**Active Framework**: ${health.activeFramework}\n`;
    response += `**Available Frameworks**: ${health.availableFrameworks.length}\n`;
    response += `**System Uptime**: ${this.formatUptime(
      this.systemControl.systemAnalytics.uptime
    )}\n\n`;

    // Performance Health
    response += "## 📊 Performance Health\n\n";
    response += `**Framework Switches**: ${health.switchingMetrics.totalSwitches}\n`;
    response += `**Framework Switch Success Rate**: ${
      health.switchingMetrics.totalSwitches > 0
        ? Math.round(
            (health.switchingMetrics.successfulSwitches /
              health.switchingMetrics.totalSwitches) *
              100
          )
        : 100
    }%\n`;
    response += `**Framework Switch Time**: ${Math.round(
      health.switchingMetrics.averageResponseTime
    )}ms\n`;
    response += `**Execution Success Rate**: ${this.getSuccessRate()}%\n\n`;

    // Issues
    if (health.issues.length > 0) {
      response += "## ⚠️ Detected Issues\n\n";
      health.issues.forEach((issue, index) => {
        response += `${index + 1}. ⚠️ ${issue}\n`;
      });
      response += "\n";
    } else {
      response +=
        "## ✅ System Status\n\nNo issues detected. System is operating normally.\n\n";
    }

    // Health Recommendations
    response += "## 💡 Health Recommendations\n\n";

    if (health.status === "healthy") {
      response += "✅ System is healthy. No action required.\n";
      response += "- Continue monitoring performance metrics\n";
      response += "- Regular analytics reviews recommended\n";
    } else if (health.status === "degraded") {
      response += "⚠️ System performance is degraded. Monitor closely.\n";
      response += "- Review recent framework switches for patterns\n";
      response += "- Consider resetting metrics if issues are resolved\n";
      response += "- Check execution failure rates\n";
    } else {
      response += "❌ System requires immediate attention.\n";
      response += "- Check framework configuration\n";
      response += "- Review system logs for error patterns\n";
      response += "- Consider system restart if issues persist\n";
    }

    return this.createMinimalSystemResponse(response, "health");
  }

  /**
   * Run comprehensive diagnostics
   */
  public async runDiagnostics(args: any): Promise<ToolResponse> {
    let response = "# 🔧 System Diagnostics Report\n\n";

    // Framework System Check
    response += "## 🔄 Framework System\n\n";
    if (this.systemControl.frameworkStateManager) {
      const state = this.systemControl.frameworkStateManager.getCurrentState();
      const health = this.systemControl.frameworkStateManager.getSystemHealth();
      const frameworks =
        this.systemControl.frameworkStateManager.getAvailableFrameworks();

      response += `✅ **Framework Manager**: Operational\n`;
      response += `✅ **Active Framework**: ${state.activeFramework}\n`;
      response += `✅ **Available Frameworks**: ${frameworks.length} configured\n`;
      response += `${this.getHealthIcon(health.status)} **System Health**: ${
        health.status
      }\n\n`;

      // Check each framework
      frameworks.forEach((fw) => {
        const icon = fw.enabled ? "✅" : "⚠️";
        response += `${icon} **${fw.name}**: ${
          fw.enabled ? "Enabled" : "Disabled"
        }\n`;
      });
      response += "\n";
    } else {
      response += `❌ **Framework Manager**: Not initialized\n\n`;
    }

    // Performance Diagnostics
    response += "## 📊 Performance Diagnostics\n\n";
    response += `**Total Executions**: ${this.systemControl.systemAnalytics.totalExecutions}\n`;
    response += `**Success Rate**: ${this.getSuccessRate()}%\n`;
    response += `**Average Execution Time**: ${this.formatExecutionTime(
      this.systemControl.systemAnalytics.averageExecutionTime
    )}\n`;

    // Performance Assessment
    const successRate = this.getSuccessRate();
    if (successRate >= 95) {
      response += `✅ **Performance Assessment**: Excellent (${successRate}%)\n`;
    } else if (successRate >= 85) {
      response += `⚠️ **Performance Assessment**: Good (${successRate}%)\n`;
    } else {
      response += `❌ **Performance Assessment**: Needs attention (${successRate}%)\n`;
    }
    response += "\n";

    // System Resources
    response += "## 💾 System Resources\n\n";
    if (this.systemControl.systemAnalytics.memoryUsage) {
      const mem = this.systemControl.systemAnalytics.memoryUsage;
      const heapUsagePercent = Math.round((mem.heapUsed / mem.heapTotal) * 100);

      response += `**Memory Usage**: ${this.formatBytes(
        mem.heapUsed
      )}/${this.formatBytes(mem.heapTotal)} (${heapUsagePercent}%)\n`;

      if (heapUsagePercent < 70) {
        response += `✅ **Memory Status**: Healthy\n`;
      } else if (heapUsagePercent < 90) {
        response += `⚠️ **Memory Status**: Monitor usage\n`;
      } else {
        response += `❌ **Memory Status**: High usage - consider optimization\n`;
      }
    }

    response += `**System Uptime**: ${this.formatUptime(
      this.systemControl.systemAnalytics.uptime
    )}\n\n`;

    // Recommendations
    response += "## 💡 Diagnostic Recommendations\n\n";

    const recommendations: string[] = [];

    if (this.getSuccessRate() < 90) {
      recommendations.push(
        "Investigate execution failure patterns to improve success rate"
      );
    }

    if (this.systemControl.systemAnalytics.averageExecutionTime > 5000) {
      recommendations.push(
        "Consider optimizing execution performance - average time is high"
      );
    }

    if (
      this.systemControl.systemAnalytics.memoryUsage &&
      this.systemControl.systemAnalytics.memoryUsage.heapUsed /
        this.systemControl.systemAnalytics.memoryUsage.heapTotal >
        0.8
    ) {
      recommendations.push("Monitor memory usage - heap utilization is high");
    }

    if (recommendations.length > 0) {
      recommendations.forEach((rec, index) => {
        response += `${index + 1}. ${rec}\n`;
      });
    } else {
      response += "✅ No issues detected. System is operating optimally.\n";
    }

    response += `\n---\n*Diagnostics completed at: ${new Date().toISOString()}*`;

    return this.createMinimalSystemResponse(response, "diagnostics");
  }

  /**
   * Reset framework switching metrics
   */
  public async resetMetrics(args: {
    confirm?: boolean;
  }): Promise<ToolResponse> {
    if (!args.confirm) {
      return this.createMinimalSystemResponse(
        "❌ Metrics reset cancelled. Set 'confirm: true' to reset all switching performance metrics.",
        "reset_metrics"
      );
    }

    const beforeMetrics = { ...this.systemControl.systemAnalytics };

    this.resetAnalyticsData();

    if (this.systemControl.frameworkStateManager) {
      this.systemControl.frameworkStateManager.resetMetrics();
    }

    let response = `# 🔄 Metrics Reset Completed\n\n`;
    response += `**Reset Timestamp**: ${new Date().toISOString()}\n\n`;

    response += "## Metrics Before Reset\n\n";
    response += `**Total Executions**: ${beforeMetrics.totalExecutions}\n`;
    response += `**Successful**: ${beforeMetrics.successfulExecutions}\n`;
    response += `**Failed**: ${beforeMetrics.failedExecutions}\n`;
    response += `**Average Time**: ${this.formatExecutionTime(
      beforeMetrics.averageExecutionTime
    )}\n\n`;

    response += "## Metrics After Reset\n\n";
    response += `**Total Executions**: ${this.systemControl.systemAnalytics.totalExecutions}\n`;
    response += `**Successful**: ${this.systemControl.systemAnalytics.successfulExecutions}\n`;
    response += `**Failed**: ${this.systemControl.systemAnalytics.failedExecutions}\n`;
    response += `**Average Time**: ${this.formatExecutionTime(
      this.systemControl.systemAnalytics.averageExecutionTime
    )}\n\n`;

    response +=
      "✅ All switching performance metrics have been reset. Framework switching monitoring will start fresh.";

    return this.createMinimalSystemResponse(response, "reset_metrics");
  }

  /**
   * Get framework switch history
   */
  public async getSwitchHistory(args: {
    limit?: number;
  }): Promise<ToolResponse> {
    if (!this.systemControl.frameworkStateManager) {
      throw new Error("Framework state manager not initialized");
    }

    const { limit = 20 } = args;

    const history =
      this.systemControl.frameworkStateManager.getSwitchHistory(limit);
    const currentState =
      this.systemControl.frameworkStateManager.getCurrentState();

    let response = `# 📈 Framework Switch History\n\n`;
    response += `**Current Framework**: ${currentState.activeFramework}\n`;
    response += `**History Entries**: ${history.length}\n\n`;

    if (history.length === 0) {
      response += "No framework switches recorded yet.\n\n";
    } else {
      response += "## Recent Switches\n\n";

      history.forEach((entry, index) => {
        response += `### ${index + 1}. ${entry.from} → ${entry.to}\n\n`;
        response += `**Timestamp**: ${entry.timestamp.toISOString()}\n`;
        response += `**Reason**: ${entry.reason}\n\n`;
      });
    }

    response += "---\n\n";
    response +=
      "**Note**: This history helps track framework usage patterns and audit changes.";

    return this.createMinimalSystemResponse(response, "switch_history");
  }

  /**
   * Manage system configuration
   */
  public async manageConfig(args: {
    config?: {
      key: string;
      value?: string;
      operation: "get" | "set" | "list" | "validate";
    };
  }): Promise<ToolResponse> {
    const configRequest = args.config;

    // Check if ConfigManager is available
    if (!this.configManager) {
      return createStructuredResponse(
        "❌ **Configuration Manager Unavailable**\n\n" +
          "ConfigManager is not initialized. This indicates a system initialization issue.\n" +
          "Configuration management requires proper system startup.",
        { operation: "config", error: "config_manager_unavailable" },
        true
      );
    }

    try {
      // Handle different config operations
      if (!configRequest) {
        return await this.handleConfigList();
      }

      switch (configRequest.operation) {
        case "list":
          return await this.handleConfigList();
        case "get":
          return await this.handleConfigGet(configRequest.key);
        case "set":
          return await this.handleConfigSet(
            configRequest.key,
            configRequest.value || ""
          );
        case "validate":
          return await this.handleConfigValidate(
            configRequest.key,
            configRequest.value || ""
          );
        default:
          throw new Error(
            `Unknown config operation: ${configRequest.operation}`
          );
      }
    } catch (error) {
      return this.handleError(error, "config_management");
    }
  }

  /**
   * Handle config list operation
   */
  private async handleConfigList(): Promise<ToolResponse> {
    const config = this.configManager!.getConfig();

    let response = "# ⚙️ System Configuration Overview\n\n";

    // Server Configuration
    response += "## 🖥️ Server Configuration\n\n";
    response += `**Name**: ${config.server.name}\n`;
    response += `**Version**: ${config.server.version}\n`;
    response += `**Port**: ${config.server.port}\n\n`;

    // Transport Configuration
    response += "## 🚀 Transport Configuration\n\n";
    response += `**Default Transport**: ${config.transports.default}\n`;
    response += `**STDIO Enabled**: ${
      config.transports.stdio.enabled ? "✅" : "❌"
    }\n`;
    response += `**SSE Enabled**: ${
      config.transports.sse.enabled ? "✅" : "❌"
    }\n\n`;

    // Analysis Configuration
    if (config.analysis) {
      response += "## 🔍 Analysis Configuration\n\n";
      response += `**LLM Integration**: ${
        config.analysis.semanticAnalysis.llmIntegration.enabled ? "✅" : "❌"
      }\n`;
      if (config.analysis.semanticAnalysis.llmIntegration.enabled) {
        response += `**Model**: ${config.analysis.semanticAnalysis.llmIntegration.model}\n`;
        response += `**Max Tokens**: ${config.analysis.semanticAnalysis.llmIntegration.maxTokens}\n`;
        response += `**Temperature**: ${config.analysis.semanticAnalysis.llmIntegration.temperature}\n`;
      }
      response += "\n";
    }

    // Logging Configuration
    if (config.logging) {
      response += "## 📝 Logging Configuration\n\n";
      response += `**Directory**: ${config.logging.directory}\n`;
      response += `**Level**: ${config.logging.level}\n\n`;
    }

    // Runtime Status
    response += "## 📊 Runtime Status\n\n";
    response += `**Framework System**: ${
      this.systemControl.frameworkStateManager ? "✅ Enabled" : "❌ Disabled"
    }\n`;
    response += `**Analytics Collection**: ✅ Enabled\n`;
    response += `**Performance Monitoring**: ✅ Enabled\n`;
    response += `**System Uptime**: ${this.formatUptime(
      this.systemControl.systemAnalytics.uptime
    )}\n`;
    response += `**Start Time**: ${new Date(this.startTime).toISOString()}\n\n`;

    // Available Operations
    response += "## 🔧 Available Configuration Keys\n\n";
    response += "**Server Configuration:**\n";
    response += "- `server.name` (string) - Server display name\n";
    response += "- `server.version` (string) - Server version\n";
    response +=
      "- `server.port` (number) - HTTP server port ⚠️ *restart required*\n\n";
    response += "**Transport Configuration:**\n";
    response +=
      "- `transports.default` (string) - Default transport ⚠️ *restart required*\n";
    response +=
      "- `transports.stdio.enabled` (boolean) - STDIO transport ⚠️ *restart required*\n";
    response +=
      "- `transports.sse.enabled` (boolean) - SSE transport ⚠️ *restart required*\n\n";
    response += "**Logging Configuration:**\n";
    response +=
      "- `logging.level` (string) - Log level: debug, info, warn, error\n";
    response += "- `logging.directory` (string) - Log file directory\n\n";
    response += "**Usage Examples:**\n";
    response +=
      '- Get value: `{ "config": { "key": "server.port", "operation": "get" } }`\n';
    response +=
      '- Set value: `{ "config": { "key": "logging.level", "value": "debug", "operation": "set" } }`\n';
    response +=
      '- Validate: `{ "config": { "key": "server.port", "value": "3000", "operation": "validate" } }`';

    return this.createMinimalSystemResponse(response, "config");
  }

  /**
   * Handle config get operation
   */
  private async handleConfigGet(key: string): Promise<ToolResponse> {
    if (!key) {
      throw new Error("Configuration key is required for get operation");
    }

    const value = this.getConfigValue(key);
    if (value === undefined) {
      return createStructuredResponse(
        `❌ **Configuration Key Not Found**\n\n` +
          `The key \`${key}\` does not exist in the configuration.\n\n` +
          `Use the \`list\` operation to see available configuration keys.`,
        { operation: "config_get", key, error: "key_not_found" },
        true
      );
    }

    let response = `# 🔍 Configuration Value\n\n`;
    response += `**Key**: \`${key}\`\n`;
    response += `**Current Value**: \`${JSON.stringify(value)}\`\n`;
    response += `**Type**: ${typeof value}\n\n`;

    if (this.requiresRestart(key)) {
      response += `⚠️ **Restart Required**: Changes to this setting require a server restart to take effect.\n\n`;
    } else {
      response += `✅ **Runtime Changeable**: This setting can be changed without restart.\n\n`;
    }

    response += `**Usage**: To modify this value, use:\n`;
    response += `\`{ "config": { "key": "${key}", "value": "new_value", "operation": "set" } }\``;

    return this.createMinimalSystemResponse(response, "config");
  }

  /**
   * Handle config set operation
   */
  private async handleConfigSet(
    key: string,
    value: string
  ): Promise<ToolResponse> {
    if (!key || value === undefined) {
      throw new Error("Both key and value are required for set operation");
    }

    // Check if SafeConfigWriter is available
    if (!this.safeConfigWriter) {
      return createStructuredResponse(
        `⚠️ **Configuration Writing Unavailable**\n\n` +
          `Configuration writing is not available (SafeConfigWriter not initialized).\n` +
          `This may indicate a file system permission issue or invalid configuration path.\n\n` +
          `**Key**: \`${key}\`\n` +
          `**Value**: \`${value}\`\n\n` +
          `**Fallback**: Use the \`validate\` operation to check if your change would be valid.`,
        {
          operation: "config_set",
          key,
          value,
          error: "config_writer_unavailable",
        },
        true
      );
    }

    // First validate the new value
    const validation = this.validateConfigValue(key, value);
    if (!validation.valid) {
      return {
        content: [
          {
            type: "text",
            text:
              `❌ **Invalid Configuration Value**\n\n` +
              `**Key**: \`${key}\`\n` +
              `**Value**: \`${value}\`\n` +
              `**Error**: ${validation.error}\n\n` +
              `${
                validation.suggestion
                  ? `**Suggestion**: ${validation.suggestion}`
                  : ""
              }`,
          },
        ],
        isError: true,
      };
    }

    try {
      // Perform the actual configuration update
      const currentValue = this.getConfigValue(key);
      const writeResult = await this.safeConfigWriter.updateConfigValue(
        key,
        value
      );

      if (!writeResult.success) {
        return {
          content: [
            {
              type: "text",
              text:
                `❌ **Configuration Update Failed**\n\n` +
                `**Key**: \`${key}\`\n` +
                `**Value**: \`${value}\`\n` +
                `**Error**: ${writeResult.error || writeResult.message}\n\n` +
                `${
                  writeResult.backupPath
                    ? `**Backup**: ${writeResult.backupPath}\n`
                    : ""
                }` +
                `**Current Value**: \`${JSON.stringify(
                  currentValue
                )}\` (unchanged)\n\n` +
                `**Note**: Configuration file has been left unchanged. No restart required.`,
            },
          ],
          isError: true,
        };
      }

      // Success! Configuration has been updated
      let response = `✅ **Configuration Updated Successfully**\n\n`;
      response += `**Key**: \`${key}\`\n`;
      response += `**Previous Value**: \`${JSON.stringify(currentValue)}\`\n`;
      response += `**New Value**: \`${value}\`\n`;
      response += `**Backup Created**: \`${writeResult.backupPath}\`\n\n`;

      if (writeResult.restartRequired) {
        response += `⚠️ **Server Restart Required**\n\n`;
        response += `This configuration change requires a server restart to take effect.\n`;
        response += `Use the \`restart\` action with \`confirm: true\` to restart the server.\n\n`;
        response += `**Alternative**: The configuration file has been updated and will take effect on next startup.`;
      } else {
        response += `✅ **Change Applied Immediately**\n\n`;
        response += `This configuration change has been applied and is now active.\n`;
        response += `No server restart is required.`;
      }

      response += `\n\n**Recovery**: If needed, you can restore the previous configuration using:\n`;
      response += `\`{ "action": "config_restore", "backup_path": "${writeResult.backupPath}" }\``;

      return this.createMinimalSystemResponse(response, "config");
    } catch (error) {
      this.logger.error(
        `Unexpected error during config set for ${key}:`,
        error
      );
      return {
        content: [
          {
            type: "text",
            text:
              `❌ **Unexpected Configuration Error**\n\n` +
              `**Key**: \`${key}\`\n` +
              `**Value**: \`${value}\`\n` +
              `**Error**: ${String(error)}\n\n` +
              `**Status**: Configuration unchanged. System remains stable.\n` +
              `**Action**: Check system logs for detailed error information.`,
          },
        ],
        isError: true,
      };
    }
  }

  /**
   * Handle config validate operation
   */
  private async handleConfigValidate(
    key: string,
    value: string
  ): Promise<ToolResponse> {
    if (!key || value === undefined) {
      throw new Error("Both key and value are required for validate operation");
    }

    const validation = this.validateConfigValue(key, value);
    const currentValue = this.getConfigValue(key);

    let response = `# 🔍 Configuration Validation\n\n`;
    response += `**Key**: \`${key}\`\n`;
    response += `**Proposed Value**: \`${value}\`\n`;
    response += `**Current Value**: \`${JSON.stringify(currentValue)}\`\n`;
    response += `**Valid**: ${validation.valid ? "✅ Yes" : "❌ No"}\n\n`;

    if (!validation.valid) {
      response += `**Error**: ${validation.error}\n`;
      if (validation.suggestion) {
        response += `**Suggestion**: ${validation.suggestion}\n`;
      }
    } else {
      response += `**Type**: ${validation.type}\n`;
      response += `**Restart Required**: ${
        this.requiresRestart(key) ? "⚠️ Yes" : "✅ No"
      }\n`;
    }

    return this.createMinimalSystemResponse(response, "config");
  }

  /**
   * Get configuration value using dot notation
   */
  private getConfigValue(key: string): any {
    const config = this.configManager!.getConfig();
    const parts = key.split(".");
    let value: any = config;

    for (const part of parts) {
      if (value && typeof value === "object" && part in value) {
        value = value[part];
      } else {
        return undefined;
      }
    }

    return value;
  }

  /**
   * Validate configuration value
   */
  private validateConfigValue(
    key: string,
    value: string
  ): { valid: boolean; error?: string; suggestion?: string; type?: string } {
    // Basic key validation
    if (!this.isValidConfigKey(key)) {
      return {
        valid: false,
        error: `Unknown configuration key: ${key}`,
        suggestion: "Use the 'list' operation to see available keys",
      };
    }

    // Type-specific validation
    try {
      switch (key) {
        case "server.port":
          const port = parseInt(value, 10);
          if (isNaN(port) || port < 1024 || port > 65535) {
            return {
              valid: false,
              error: "Port must be a number between 1024-65535",
              suggestion: "Try a value like 3000 or 8080",
            };
          }
          return { valid: true, type: "number" };

        case "server.name":
        case "server.version":
          if (!value || value.trim().length === 0) {
            return {
              valid: false,
              error: "Value cannot be empty",
              suggestion: "Provide a non-empty string value",
            };
          }
          return { valid: true, type: "string" };

        case "transports.default":
          if (!["stdio", "sse"].includes(value)) {
            return {
              valid: false,
              error: "Transport must be 'stdio' or 'sse'",
              suggestion:
                "Use 'stdio' for desktop clients or 'sse' for web clients",
            };
          }
          return { valid: true, type: "string" };

        case "transports.stdio.enabled":
        case "transports.sse.enabled":
          if (!["true", "false"].includes(value.toLowerCase())) {
            return {
              valid: false,
              error: "Value must be 'true' or 'false'",
              suggestion: "Use boolean values: true or false",
            };
          }
          return { valid: true, type: "boolean" };

        case "logging.level":
          if (!["debug", "info", "warn", "error"].includes(value)) {
            return {
              valid: false,
              error: "Log level must be: debug, info, warn, or error",
              suggestion:
                "Use 'debug' for development or 'info' for production",
            };
          }
          return { valid: true, type: "string" };

        case "logging.directory":
          if (!value || value.trim().length === 0) {
            return {
              valid: false,
              error: "Directory path cannot be empty",
              suggestion: "Provide a valid directory path like './logs'",
            };
          }
          return { valid: true, type: "string" };

        default:
          return { valid: true, type: "unknown" };
      }
    } catch (error) {
      return {
        valid: false,
        error: `Validation error: ${error}`,
        suggestion: "Check the value format and try again",
      };
    }
  }

  /**
   * Check if config key is valid
   */
  private isValidConfigKey(key: string): boolean {
    const validKeys = [
      "server.name",
      "server.version",
      "server.port",
      "transports.default",
      "transports.stdio.enabled",
      "transports.sse.enabled",
      "logging.level",
      "logging.directory",
      "analysis.semanticAnalysis.llmIntegration.enabled",
      "analysis.semanticAnalysis.llmIntegration.model",
      "analysis.semanticAnalysis.llmIntegration.maxTokens",
      "analysis.semanticAnalysis.llmIntegration.temperature",
    ];
    return validKeys.includes(key);
  }

  /**
   * Check if config key requires restart
   */
  private requiresRestart(key: string): boolean {
    const restartRequired = [
      "server.port",
      "transports.default",
      "transports.stdio.enabled",
      "transports.sse.enabled",
      "analysis.semanticAnalysis.llmIntegration.enabled",
    ];
    return restartRequired.includes(key);
  }

  /**
   * Restore configuration from backup
   */
  public async restoreConfig(args: {
    backup_path?: string;
    confirm?: boolean;
  }): Promise<ToolResponse> {
    if (!args.backup_path) {
      return {
        content: [
          {
            type: "text",
            text:
              `❌ **Backup Path Required**\n\n` +
              `The \`backup_path\` parameter is required for config restore operations.\n\n` +
              `**Usage**: \`{ "action": "config_restore", "backup_path": "/path/to/backup", "confirm": true }\`\n\n` +
              `**Note**: Backup files are typically named like \`config.json.backup.1640995200000\``,
          },
        ],
        isError: true,
      };
    }

    if (!args.confirm) {
      return {
        content: [
          {
            type: "text",
            text:
              `⚠️ **Configuration Restore Confirmation Required**\n\n` +
              `**Backup Path**: \`${args.backup_path}\`\n` +
              `**Impact**: This will overwrite the current configuration file\n` +
              `**Data Loss Risk**: Current configuration will be lost unless backed up\n\n` +
              `**To proceed**: Set \`confirm: true\` to execute the restore.\n\n` +
              `**Alternative**: Use \`config\` operations to make individual changes instead of full restore.`,
          },
        ],
      };
    }

    // Check if SafeConfigWriter is available
    if (!this.safeConfigWriter) {
      return {
        content: [
          {
            type: "text",
            text:
              `❌ **Configuration Restore Unavailable**\n\n` +
              `Configuration restoration is not available (SafeConfigWriter not initialized).\n` +
              `This may indicate a file system permission issue or invalid configuration path.\n\n` +
              `**Backup Path**: \`${args.backup_path}\`\n\n` +
              `**Manual Restore**: You may need to manually copy the backup file to replace the current config.`,
          },
        ],
        isError: true,
      };
    }

    try {
      // Create a backup of the current config before restoring
      const fs = await import("fs");
      const currentConfigPath = this.safeConfigWriter.getConfigPath();
      const emergencyBackupPath = `${currentConfigPath}.emergency.backup.${Date.now()}`;

      if (fs.existsSync(currentConfigPath)) {
        await fs.promises.copyFile(currentConfigPath, emergencyBackupPath);
        this.logger.info(
          `Emergency backup created before restore: ${emergencyBackupPath}`
        );
      }

      // Perform the restoration
      const restoreResult = await this.safeConfigWriter.restoreFromBackup(
        args.backup_path
      );

      if (!restoreResult.success) {
        return {
          content: [
            {
              type: "text",
              text:
                `❌ **Configuration Restore Failed**\n\n` +
                `**Backup Path**: \`${args.backup_path}\`\n` +
                `**Error**: ${
                  restoreResult.error || restoreResult.message
                }\n\n` +
                `**Status**: Original configuration unchanged\n` +
                `${
                  fs.existsSync(emergencyBackupPath)
                    ? `**Emergency Backup**: ${emergencyBackupPath}\n`
                    : ""
                }` +
                `**Action**: Verify the backup file exists and is readable.`,
            },
          ],
          isError: true,
        };
      }

      // Success! Configuration has been restored
      let response = `✅ **Configuration Restored Successfully**\n\n`;
      response += `**Restored From**: \`${args.backup_path}\`\n`;
      response += `**Emergency Backup**: \`${emergencyBackupPath}\`\n`;
      response += `**Timestamp**: ${new Date().toISOString()}\n\n`;

      response += `⚠️ **Server Restart Recommended**\n\n`;
      response += `Configuration has been restored from backup. A server restart is recommended `;
      response += `to ensure all systems are using the restored configuration.\n\n`;

      response += `**To restart**: Use \`{ "action": "restart", "confirm": true }\`\n\n`;

      response += `**Recovery Options**:\n`;
      response += `- **Undo**: \`{ "action": "config_restore", "backup_path": "${emergencyBackupPath}", "confirm": true }\`\n`;
      response += `- **Check config**: \`{ "action": "config", "config": { "operation": "list" } }\``;

      return this.createMinimalSystemResponse(response, "config_restore");
    } catch (error) {
      this.logger.error(
        `Unexpected error during config restore from ${args.backup_path}:`,
        error
      );
      return {
        content: [
          {
            type: "text",
            text:
              `❌ **Unexpected Restore Error**\n\n` +
              `**Backup Path**: \`${args.backup_path}\`\n` +
              `**Error**: ${String(error)}\n\n` +
              `**Status**: Configuration unchanged. System remains stable.\n` +
              `**Action**: Check file permissions and backup file validity.`,
          },
        ],
        isError: true,
      };
    }
  }

  /**
   * Restart server with confirmation and reason
   */
  public async restartServer(args: {
    reason?: string;
    confirm?: boolean;
  }): Promise<ToolResponse> {
    const {
      reason = "Manual restart requested via system_control",
      confirm = false,
    } = args;

    if (!this.onRestart) {
      return {
        content: [
          {
            type: "text",
            text: "❌ **Restart Unavailable**: Server restart functionality not configured. This may indicate the server is running in a mode that doesn't support programmatic restart.",
          },
        ],
        isError: true,
      };
    }

    if (!confirm) {
      return {
        content: [
          {
            type: "text",
            text:
              `⚠️ **Server Restart Confirmation Required**\n\n` +
              `**Reason**: ${reason}\n` +
              `**Impact**: All active connections will be terminated\n` +
              `**Downtime**: Server will restart (typically 5-10 seconds)\n\n` +
              `**To proceed**: Set 'confirm: true' to execute the restart.\n\n` +
              `🔄 **Alternative**: Use hot-reload via prompt_manager 'reload' action for most changes.`,
          },
        ],
      };
    }

    let response = `🚨 **Server Restart Initiated**\n\n`;
    response += `**Reason**: ${reason}\n`;
    response += `**Timestamp**: ${new Date().toISOString()}\n\n`;
    response += `📊 **Pre-Restart System Status**:\n`;
    response += `- **Uptime**: ${this.formatUptime(
      this.systemControl.systemAnalytics.uptime
    )}\n`;
    response += `- **Total Executions**: ${this.systemControl.systemAnalytics.totalExecutions}\n`;
    response += `- **Success Rate**: ${this.getSuccessRate()}%\n`;

    if (this.systemControl.frameworkStateManager) {
      const currentState =
        this.systemControl.frameworkStateManager.getCurrentState();
      response += `- **Active Framework**: ${currentState.activeFramework}\n`;
    }

    response += `\n⚡ **Server will restart in 2 seconds**... Please wait for reconnection.\n\n`;
    response += `✅ All system state and configurations will be preserved.`;

    // Schedule restart after response is sent
    setTimeout(() => {
      this.logger.info(
        `System restart initiated via system_control. Reason: ${reason}`
      );
      this.onRestart!(reason);
    }, 2000);

    return this.createMinimalSystemResponse(response, "restart");
  }

  // Helper methods

  private resetAnalyticsData(): void {
    this.systemControl.systemAnalytics = {
      totalExecutions: 0,
      successfulExecutions: 0,
      failedExecutions: 0,
      averageExecutionTime: 0,
      gateValidationCount: 0,
      uptime: Date.now() - this.startTime,
      performanceTrends: [],
    };
  }

  /**
   * Enable framework system
   */
  public async enableFrameworkSystem(args: {
    reason?: string;
  }): Promise<ToolResponse> {
    try {
      if (!this.systemControl.frameworkStateManager) {
        return createStructuredResponse(
          "❌ Framework State Manager not available",
          {
            operation: "enable_framework",
            error: "framework_manager_unavailable",
          },
          true
        );
      }

      const reason = args.reason || "Manual enable via MCP tool";
      this.systemControl.frameworkStateManager.enableFrameworkSystem(reason);

      const status =
        this.systemControl.frameworkStateManager.isFrameworkSystemEnabled();

      let response = "✅ **Framework System Enabled**\n\n";
      response += `**Status**: ${status ? "Enabled" : "Disabled"}\n`;
      response += `**Reason**: ${reason}\n`;
      response += `**Active Framework**: ${
        this.systemControl.frameworkStateManager.getActiveFramework().name
      }\n`;
      response += `**Timestamp**: ${new Date().toISOString()}\n\n`;
      response +=
        "Framework injection will now be active for template and chain executions.\n\n";
      response +=
        "🔄 **Note**: Tool descriptions now reflect framework-enabled capabilities. Tool descriptions will show framework-enhanced functionality on next client connection/restart.";

      return this.createMinimalSystemResponse(response, "enable_framework");
    } catch (error) {
      return this.handleError(error, "enable_framework_system");
    }
  }

  /**
   * Disable framework system
   */
  public async disableFrameworkSystem(args: {
    reason?: string;
  }): Promise<ToolResponse> {
    try {
      if (!this.systemControl.frameworkStateManager) {
        return createStructuredResponse(
          "❌ Framework State Manager not available",
          {
            operation: "disable_framework",
            error: "framework_manager_unavailable",
          },
          true
        );
      }

      const reason = args.reason || "Manual disable via MCP tool";
      this.systemControl.frameworkStateManager.disableFrameworkSystem(reason);

      const status =
        this.systemControl.frameworkStateManager.isFrameworkSystemEnabled();

      let response = "🚫 **Framework System Disabled**\n\n";
      response += `**Status**: ${status ? "Enabled" : "Disabled"}\n`;
      response += `**Reason**: ${reason}\n`;
      response += `**Timestamp**: ${new Date().toISOString()}\n\n`;
      response +=
        "Framework injection is now bypassed. All executions will use standard prompts without methodology enhancements.\n\n";
      response +=
        "🔄 **Note**: Tool descriptions now reflect framework-disabled state. Tool descriptions will show basic functionality (no framework enhancement) on next client connection/restart.";

      return this.createMinimalSystemResponse(response, "disable_framework");
    } catch (error) {
      return this.handleError(error, "disable_framework_system");
    }
  }

  /**
   * Get framework system status
   */
  public async getFrameworkSystemStatus(args: any): Promise<ToolResponse> {
    try {
      if (!this.systemControl.frameworkStateManager) {
        return createStructuredResponse(
          "❌ Framework State Manager not available",
          {
            operation: "framework_status",
            error: "framework_manager_unavailable",
          },
          true
        );
      }

      const state = this.systemControl.frameworkStateManager.getCurrentState();
      const health = this.systemControl.frameworkStateManager.getSystemHealth();

      let response = "📊 **Framework System Status**\n\n";

      // Main status with enhanced clarity
      const isEnabled = state.frameworkSystemEnabled;
      const injectionStatus = isEnabled ? "✅ Active" : "🚫 Inactive";

      response += `**System Status**: ${
        state.frameworkSystemEnabled ? "✅ Enabled" : "🚫 Disabled"
      }\n`;
      response += `**Selected Framework**: ${state.activeFramework}\n`;
      response += `**Framework Injection**: ${injectionStatus}\n`;
      response += `**Health Status**: ${this.getHealthEmoji(
        health.status
      )} ${health.status.toUpperCase()}\n`;
      response += `**Last Updated**: ${state.switchedAt.toISOString()}\n`;
      response += `**Last Reason**: ${state.switchReason}\n\n`;

      // Available frameworks
      response += `**Available Frameworks**: ${health.availableFrameworks.join(
        ", "
      )}\n\n`;

      // Framework capabilities
      if (state.frameworkSystemEnabled) {
        response += "**Current Capabilities**:\n";
        response += "• Framework-aware prompt injection\n";
        response += "• Methodology-specific system prompts\n";
        response += "• Quality gate validation\n";
        response += "• Enhanced execution context\n\n";
      } else {
        response +=
          "**Current Mode**: Standard execution (no framework enhancements)\n\n";
      }

      // Switching metrics
      response += "**Switching Metrics**:\n";
      response += `• Total Operations: ${state.switchingMetrics.switchCount}\n`;
      response += `• Error Count: ${state.switchingMetrics.errorCount}\n`;
      response += `• Avg Response Time: ${state.switchingMetrics.averageResponseTime.toFixed(
        1
      )}ms\n`;

      // Health issues
      if (health.issues.length > 0) {
        response += "\n**Issues**:\n";
        health.issues.forEach((issue) => {
          response += `• ⚠️ ${issue}\n`;
        });
      }

      return this.createMinimalSystemResponse(response, "framework_status");
    } catch (error) {
      return this.handleError(error, "framework_system_status");
    }
  }

  /**
   * Get health status emoji
   */
  private getHealthEmoji(status: string): string {
    switch (status) {
      case "healthy":
        return "✅";
      case "degraded":
        return "⚠️";
      case "error":
        return "❌";
      default:
        return "❓";
    }
  }

  /**
   * Error handling helper
   */
  public handleError(error: unknown, context: string): ToolResponse {
    utilsHandleError(error, context, this.logger);

    return this.responseFormatter.formatErrorResponse(
      error instanceof Error ? error : String(error),
      {
        tool: "system_control",
        operation: context,
      },
      {
        includeStructuredData: true,
      }
    );
  }
}

/**
 * Create consolidated system control
 */
export function createConsolidatedSystemControl(
  logger: Logger,
  mcpServer: any,
  onRestart?: (reason: string) => Promise<void>
): ConsolidatedSystemControl {
  return new ConsolidatedSystemControl(logger, mcpServer, onRestart);
}

```
Page 12/12FirstPrevNextLast