#
tokens: 34820/50000 1/252 files (page 18/18)
lines: on (toggle) GitHub
raw markdown copy reset
This is page 18 of 18. Use http://codebase.md/minipuft/claude-prompts-mcp?lines=true&page={x} to view the full context.

# Directory Structure

```
├── .actrc
├── .gitattributes
├── .github
│   └── workflows
│       ├── ci.yml
│       ├── mcp-compliance.yml
│       └── pr-validation.yml
├── .gitignore
├── agent.md
├── assets
│   └── logo.png
├── CLAUDE.md
├── config
│   └── framework-state.json
├── docs
│   ├── architecture.md
│   ├── chain-modification-examples.md
│   ├── contributing.md
│   ├── enhanced-gate-system.md
│   ├── execution-architecture-guide.md
│   ├── installation-guide.md
│   ├── mcp-tool-usage-guide.md
│   ├── mcp-tools-reference.md
│   ├── prompt-format-guide.md
│   ├── prompt-management.md
│   ├── prompt-vs-template-guide.md
│   ├── README.md
│   ├── template-development-guide.md
│   ├── TODO.md
│   ├── troubleshooting.md
│   └── version-history.md
├── LICENSE
├── local-test.sh
├── plans
│   ├── nunjucks-dynamic-chain-orchestration.md
│   ├── outputschema-realtime-progress-and-validation.md
│   ├── parallel-conditional-execution-analysis.md
│   ├── sqlite-storage-migration.md
│   └── symbolic-command-language-implementation.md
├── README.md
├── scripts
│   ├── setup-windows-testing.sh
│   ├── test_server.js
│   ├── test-all-platforms.sh
│   └── windows-tests
│       ├── test-windows-paths.js
│       ├── test-windows-startup.sh
│       └── windows-env.sh
└── server
    ├── config
    │   ├── framework-state.json
    │   └── tool-descriptions.json
    ├── config.json
    ├── jest.config.cjs
    ├── LICENSE
    ├── package-lock.json
    ├── package.json
    ├── prompts
    │   ├── analysis
    │   │   ├── advanced_analysis_engine.md
    │   │   ├── content_analysis.md
    │   │   ├── deep_analysis.md
    │   │   ├── deep_research.md
    │   │   ├── markdown_notebook.md
    │   │   ├── note_integration.md
    │   │   ├── note_refinement.md
    │   │   ├── notes.md
    │   │   ├── progressive_research.md
    │   │   ├── prompts.json
    │   │   ├── query_refinement.md
    │   │   └── review.md
    │   ├── architecture
    │   │   ├── prompts.json
    │   │   └── strategic-system-alignment.md
    │   ├── content_processing
    │   │   ├── format_enhancement.md
    │   │   ├── noteIntegration.md
    │   │   ├── obsidian_metadata_optimizer.md
    │   │   ├── prompts.json
    │   │   ├── vault_related_notes_finder.md
    │   │   └── video_notes_enhanced.md
    │   ├── debugging
    │   │   ├── analyze_logs.md
    │   │   └── prompts.json
    │   ├── development
    │   │   ├── analyze_code_structure.md
    │   │   ├── analyze_file_structure.md
    │   │   ├── code_review_optimization_chain.md
    │   │   ├── component_flow_analysis.md
    │   │   ├── create_modularization_plan.md
    │   │   ├── detect_code_issues.md
    │   │   ├── detect_project_commands.md
    │   │   ├── expert_code_implementation.md
    │   │   ├── generate_comprehensive_claude_md.md
    │   │   ├── prompts.json
    │   │   ├── strategicImplement.md
    │   │   ├── suggest_code_improvements.md
    │   │   └── transform_code_to_modules.md
    │   ├── documentation
    │   │   ├── create_docs_chain.md
    │   │   ├── docs-content-creation.md
    │   │   ├── docs-content-planning.md
    │   │   ├── docs-final-assembly.md
    │   │   ├── docs-project-analysis.md
    │   │   ├── docs-review-refinement.md
    │   │   └── prompts.json
    │   ├── education
    │   │   ├── prompts.json
    │   │   └── vault_integrated_notes.md
    │   ├── general
    │   │   ├── diagnose.md
    │   │   └── prompts.json
    │   ├── promptsConfig.json
    │   └── testing
    │       ├── final_verification_test.md
    │       └── prompts.json
    ├── README.md
    ├── scripts
    │   └── validate-dependencies.js
    ├── src
    │   ├── api
    │   │   └── index.ts
    │   ├── chain-session
    │   │   └── manager.ts
    │   ├── config
    │   │   └── index.ts
    │   ├── Dockerfile
    │   ├── execution
    │   │   ├── context
    │   │   │   ├── context-resolver.ts
    │   │   │   ├── framework-injector.ts
    │   │   │   └── index.ts
    │   │   ├── index.ts
    │   │   ├── parsers
    │   │   │   ├── argument-parser.ts
    │   │   │   ├── index.ts
    │   │   │   └── unified-command-parser.ts
    │   │   └── types.ts
    │   ├── frameworks
    │   │   ├── framework-manager.ts
    │   │   ├── framework-state-manager.ts
    │   │   ├── index.ts
    │   │   ├── integration
    │   │   │   ├── framework-semantic-integration.ts
    │   │   │   └── index.ts
    │   │   ├── methodology
    │   │   │   ├── guides
    │   │   │   │   ├── 5w1h-guide.ts
    │   │   │   │   ├── cageerf-guide.ts
    │   │   │   │   ├── react-guide.ts
    │   │   │   │   └── scamper-guide.ts
    │   │   │   ├── index.ts
    │   │   │   ├── interfaces.ts
    │   │   │   └── registry.ts
    │   │   ├── prompt-guidance
    │   │   │   ├── index.ts
    │   │   │   ├── methodology-tracker.ts
    │   │   │   ├── service.ts
    │   │   │   ├── system-prompt-injector.ts
    │   │   │   └── template-enhancer.ts
    │   │   └── types
    │   │       ├── index.ts
    │   │       ├── integration-types.ts
    │   │       ├── methodology-types.ts
    │   │       └── prompt-guidance-types.ts
    │   ├── gates
    │   │   ├── constants.ts
    │   │   ├── core
    │   │   │   ├── gate-definitions.ts
    │   │   │   ├── gate-loader.ts
    │   │   │   ├── gate-validator.ts
    │   │   │   ├── index.ts
    │   │   │   └── temporary-gate-registry.ts
    │   │   ├── definitions
    │   │   │   ├── code-quality.json
    │   │   │   ├── content-structure.json
    │   │   │   ├── educational-clarity.json
    │   │   │   ├── framework-compliance.json
    │   │   │   ├── research-quality.json
    │   │   │   ├── security-awareness.json
    │   │   │   └── technical-accuracy.json
    │   │   ├── gate-state-manager.ts
    │   │   ├── guidance
    │   │   │   ├── FrameworkGuidanceFilter.ts
    │   │   │   └── GateGuidanceRenderer.ts
    │   │   ├── index.ts
    │   │   ├── intelligence
    │   │   │   ├── GatePerformanceAnalyzer.ts
    │   │   │   └── GateSelectionEngine.ts
    │   │   ├── templates
    │   │   │   ├── code_quality_validation.md
    │   │   │   ├── educational_clarity_validation.md
    │   │   │   ├── framework_compliance_validation.md
    │   │   │   ├── research_self_validation.md
    │   │   │   ├── security_validation.md
    │   │   │   ├── structure_validation.md
    │   │   │   └── technical_accuracy_validation.md
    │   │   └── types.ts
    │   ├── index.ts
    │   ├── logging
    │   │   └── index.ts
    │   ├── mcp-tools
    │   │   ├── config-utils.ts
    │   │   ├── constants.ts
    │   │   ├── index.ts
    │   │   ├── prompt-engine
    │   │   │   ├── core
    │   │   │   │   ├── engine.ts
    │   │   │   │   ├── executor.ts
    │   │   │   │   ├── index.ts
    │   │   │   │   └── types.ts
    │   │   │   ├── index.ts
    │   │   │   ├── processors
    │   │   │   │   ├── response-formatter.ts
    │   │   │   │   └── template-processor.ts
    │   │   │   └── utils
    │   │   │       ├── category-extractor.ts
    │   │   │       ├── classification.ts
    │   │   │       ├── context-builder.ts
    │   │   │       └── validation.ts
    │   │   ├── prompt-manager
    │   │   │   ├── analysis
    │   │   │   │   ├── comparison-engine.ts
    │   │   │   │   ├── gate-analyzer.ts
    │   │   │   │   └── prompt-analyzer.ts
    │   │   │   ├── core
    │   │   │   │   ├── index.ts
    │   │   │   │   ├── manager.ts
    │   │   │   │   └── types.ts
    │   │   │   ├── index.ts
    │   │   │   ├── operations
    │   │   │   │   └── file-operations.ts
    │   │   │   ├── search
    │   │   │   │   ├── filter-parser.ts
    │   │   │   │   └── prompt-matcher.ts
    │   │   │   └── utils
    │   │   │       ├── category-manager.ts
    │   │   │       └── validation.ts
    │   │   ├── shared
    │   │   │   └── structured-response-builder.ts
    │   │   ├── system-control.ts
    │   │   ├── tool-description-manager.ts
    │   │   └── types
    │   │       └── shared-types.ts
    │   ├── metrics
    │   │   ├── analytics-service.ts
    │   │   ├── index.ts
    │   │   └── types.ts
    │   ├── performance
    │   │   ├── index.ts
    │   │   └── monitor.ts
    │   ├── prompts
    │   │   ├── category-manager.ts
    │   │   ├── converter.ts
    │   │   ├── file-observer.ts
    │   │   ├── hot-reload-manager.ts
    │   │   ├── index.ts
    │   │   ├── loader.ts
    │   │   ├── promptUtils.ts
    │   │   ├── registry.ts
    │   │   └── types.ts
    │   ├── runtime
    │   │   ├── application.ts
    │   │   └── startup.ts
    │   ├── semantic
    │   │   ├── configurable-semantic-analyzer.ts
    │   │   └── integrations
    │   │       ├── index.ts
    │   │       └── llm-clients.ts
    │   ├── server
    │   │   ├── index.ts
    │   │   └── transport
    │   │       └── index.ts
    │   ├── smithery.yaml
    │   ├── text-references
    │   │   ├── conversation.ts
    │   │   └── index.ts
    │   ├── types
    │   │   └── index.ts
    │   ├── types.ts
    │   └── utils
    │       ├── chainUtils.ts
    │       ├── errorHandling.ts
    │       ├── global-resource-tracker.ts
    │       ├── index.ts
    │       └── jsonUtils.ts
    ├── tests
    │   ├── ci-startup-validation.js
    │   ├── enhanced-validation
    │   │   ├── contract-validation
    │   │   │   ├── contract-test-suite.js
    │   │   │   ├── interface-contracts.js
    │   │   │   └── interface-contracts.ts
    │   │   ├── environment-validation
    │   │   │   ├── environment-parity-checker.js
    │   │   │   └── environment-test-suite.js
    │   │   ├── lifecycle-validation
    │   │   │   ├── lifecycle-test-suite.js
    │   │   │   └── process-lifecycle-validator.js
    │   │   └── validation-orchestrator.js
    │   ├── helpers
    │   │   └── test-helpers.js
    │   ├── integration
    │   │   ├── mcp-tools.test.ts
    │   │   ├── server-startup.test.ts
    │   │   └── unified-parsing-integration.test.ts
    │   ├── performance
    │   │   ├── parsing-system-benchmark.test.ts
    │   │   └── server-performance.test.ts
    │   ├── scripts
    │   │   ├── consolidated-tools.js
    │   │   ├── establish-performance-baselines.js
    │   │   ├── functional-mcp-validation.js
    │   │   ├── integration-mcp-tools.js
    │   │   ├── integration-routing-system.js
    │   │   ├── integration-server-startup.js
    │   │   ├── integration-unified-parsing.js
    │   │   ├── methodology-guides.js
    │   │   ├── performance-memory.js
    │   │   ├── runtime-integration.js
    │   │   ├── unit-conversation-manager.js
    │   │   ├── unit-semantic-analyzer.js
    │   │   └── unit-unified-parsing.js
    │   ├── setup.ts
    │   ├── test-enhanced-parsing.js
    │   └── unit
    │       ├── conversation-manager.test.ts
    │       ├── semantic-analyzer-three-tier.test.ts
    │       └── unified-parsing-system.test.ts
    ├── tsconfig.json
    └── tsconfig.test.json
```

# Files

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

```typescript
   1 | /**
   2 |  * Consolidated System Control - Unified Framework & Analytics Management Tool
   3 |  *
   4 |  * Consolidates all system management functionality into a single intelligent tool:
   5 |  * - Framework switching and management (from system-status-tools.ts)
   6 |  * - System status and health monitoring
   7 |  * - Execution analytics and performance metrics
   8 |  * - Diagnostic reporting and maintenance
   9 |  * - Configuration management
  10 |  */
  11 | 
  12 | import { ConfigManager } from "../config/index.js";
  13 | import { FrameworkManager } from "../frameworks/framework-manager.js";
  14 | import {
  15 |   FrameworkStateManager,
  16 |   FrameworkSwitchRequest,
  17 | } from "../frameworks/framework-state-manager.js";
  18 | import { Logger } from "../logging/index.js";
  19 | import { ToolResponse } from "../types/index.js";
  20 | import { handleError as utilsHandleError } from "../utils/index.js";
  21 | import { SafeConfigWriter, createSafeConfigWriter } from "./config-utils.js";
  22 | import { createSystemResponse } from "./shared/structured-response-builder.js";
  23 | import { ToolDescriptionManager } from "./tool-description-manager.js";
  24 | // Phase 3: Prompt guidance system integration
  25 | import { PromptGuidanceService } from "../frameworks/prompt-guidance/index.js";
  26 | // Phase 4: Clean architecture gate performance analytics
  27 | import type { GatePerformanceAnalyzer } from "../gates/intelligence/GatePerformanceAnalyzer.js";
  28 | // Gates system management integration
  29 | import { GateSystemManager } from "../gates/gate-state-manager.js";
  30 | import type { GateGuidanceRenderer } from "../gates/guidance/GateGuidanceRenderer.js";
  31 | // Enhanced tool dependencies removed (Phase 1.3) - Core implementations
  32 | // Simple core response handling without enhanced complexity
  33 | interface SimpleResponseFormatter {
  34 |   formatResponse(content: any): any;
  35 |   formatSystemControlResponse(response: any, ...args: any[]): any; // Required
  36 |   formatErrorResponse(error: any, ...args: any[]): any; // Required
  37 |   setAnalyticsService(service: any): void; // Required
  38 | }
  39 | 
  40 | function createSimpleResponseFormatter(): SimpleResponseFormatter {
  41 |   return {
  42 |     formatResponse: (content: any) => content,
  43 |     formatSystemControlResponse: (response: any, ...args: any[]) => response, // Flexible args
  44 |     formatErrorResponse: (error: any, ...args: any[]) => ({
  45 |       content: [{ type: "text", text: String(error) }],
  46 |       isError: true,
  47 |       structuredContent: {
  48 |         executionMetadata: {
  49 |           executionId: `sc-error-${Date.now()}`,
  50 |           executionType: "prompt" as const,
  51 |           startTime: Date.now(),
  52 |           endTime: Date.now(),
  53 |           executionTime: 0,
  54 |           frameworkEnabled: false,
  55 |         },
  56 |       },
  57 |     }),
  58 |     setAnalyticsService: (service: any) => {}, // No-op for now
  59 |   };
  60 | }
  61 | 
  62 | // Simple output schema and response functions (minimal for Phase 1)
  63 | const systemControlOutputSchema = {
  64 |   content: { type: "array" },
  65 |   isError: { type: "boolean", optional: true },
  66 | };
  67 | 
  68 | function createStructuredResponse(
  69 |   content: any,
  70 |   isError: boolean | any = false,
  71 |   ...extraArgs: any[]
  72 | ): any {
  73 |   // Handle flexible parameters for Phase 1 compatibility
  74 |   const actualIsError = typeof isError === "boolean" ? isError : false;
  75 |   const metadata = extraArgs.length > 0 ? extraArgs[0] : {};
  76 | 
  77 |   // Use shared response builder for consistency
  78 |   if (actualIsError) {
  79 |     // For errors, we might want to use createErrorResponse, but for compatibility, use createSystemResponse
  80 |     return createSystemResponse(
  81 |       Array.isArray(content)
  82 |         ? content[0]?.text || String(content)
  83 |         : String(content),
  84 |       "error",
  85 |       {
  86 |         systemHealth: metadata.systemHealth,
  87 |         analytics: metadata.analytics,
  88 |         configChanges: metadata.configChanges,
  89 |       }
  90 |     );
  91 |   }
  92 | 
  93 |   return createSystemResponse(
  94 |     Array.isArray(content)
  95 |       ? content[0]?.text || String(content)
  96 |       : String(content),
  97 |     metadata.operation || "system_action",
  98 |     {
  99 |       frameworkState: metadata.frameworkState,
 100 |       systemHealth: metadata.systemHealth,
 101 |       analytics: metadata.analytics,
 102 |       configChanges: metadata.configChanges,
 103 |     }
 104 |   );
 105 | }
 106 | 
 107 | // Type aliases for compatibility
 108 | type ResponseFormatter = SimpleResponseFormatter;
 109 | const createResponseFormatter = createSimpleResponseFormatter;
 110 | // Analytics service
 111 | import { MetricsCollector } from "../metrics/index.js";
 112 | 
 113 | /**
 114 |  * System analytics interface - optimized for API performance and rich historical context
 115 |  */
 116 | interface SystemAnalytics {
 117 |   // High-frequency API fields (kept for O(1) performance)
 118 |   totalExecutions: number;
 119 |   successfulExecutions: number;
 120 |   failedExecutions: number;
 121 |   averageExecutionTime: number; // Critical for dashboard APIs
 122 |   gateValidationCount: number;
 123 |   uptime: number;
 124 |   memoryUsage?: NodeJS.MemoryUsage;
 125 | 
 126 |   // Rich historical data with execution context
 127 |   performanceTrends: Array<{
 128 |     timestamp: number;
 129 |     metric:
 130 |       | "executionTime"
 131 |       | "memoryDelta"
 132 |       | "successRate"
 133 |       | "gateValidationTime";
 134 |     value: number;
 135 |     executionMode?: string; // Replaces executionsByMode aggregation
 136 |     framework?: string;
 137 |     success?: boolean;
 138 |   }>;
 139 | }
 140 | 
 141 | /**
 142 |  * Consolidated System Control Tool
 143 |  */
 144 | export class ConsolidatedSystemControl {
 145 |   private logger: Logger;
 146 |   private mcpServer: any;
 147 |   private configManager?: ConfigManager;
 148 |   private safeConfigWriter?: SafeConfigWriter;
 149 |   public frameworkStateManager?: FrameworkStateManager;
 150 |   private frameworkManager?: FrameworkManager;
 151 |   public gateSystemManager?: GateSystemManager;
 152 |   private onRestart?: (reason: string) => Promise<void>;
 153 |   private toolDescriptionManager?: ToolDescriptionManager;
 154 |   private mcpToolsManager?: any; // Reference to MCPToolsManager for tool updates
 155 |   private analyticsService?: MetricsCollector;
 156 |   private responseFormatter: ResponseFormatter;
 157 |   // Phase 3: Prompt guidance service
 158 |   private promptGuidanceService?: PromptGuidanceService;
 159 |   // Phase 4: Clean architecture gate performance analytics
 160 |   public gatePerformanceAnalyzer?: GatePerformanceAnalyzer;
 161 |   private gateGuidanceRenderer?: GateGuidanceRenderer;
 162 |   public startTime: number = Date.now();
 163 | 
 164 |   // Analytics data
 165 |   public systemAnalytics: SystemAnalytics = {
 166 |     totalExecutions: 0,
 167 |     successfulExecutions: 0,
 168 |     failedExecutions: 0,
 169 |     averageExecutionTime: 0,
 170 |     gateValidationCount: 0,
 171 |     uptime: 0,
 172 |     performanceTrends: [],
 173 |   };
 174 | 
 175 |   constructor(
 176 |     logger: Logger,
 177 |     mcpServer: any,
 178 |     onRestart?: (reason: string) => Promise<void>
 179 |   ) {
 180 |     this.logger = logger;
 181 |     this.mcpServer = mcpServer;
 182 |     this.onRestart = onRestart;
 183 |     this.responseFormatter = createResponseFormatter();
 184 |   }
 185 | 
 186 |   /**
 187 |    * Set framework state manager
 188 |    */
 189 |   setFrameworkStateManager(frameworkStateManager: FrameworkStateManager): void {
 190 |     this.frameworkStateManager = frameworkStateManager;
 191 |   }
 192 | 
 193 |   /**
 194 |    * Set framework manager
 195 |    */
 196 |   setFrameworkManager(frameworkManager: FrameworkManager): void {
 197 |     this.frameworkManager = frameworkManager;
 198 |   }
 199 | 
 200 |   /**
 201 |    * Set tool description manager
 202 |    */
 203 |   setToolDescriptionManager(manager: ToolDescriptionManager): void {
 204 |     this.toolDescriptionManager = manager;
 205 |   }
 206 | 
 207 |   /**
 208 |    * Set analytics service
 209 |    */
 210 |   setAnalyticsService(analyticsService: MetricsCollector): void {
 211 |     this.analyticsService = analyticsService;
 212 |     this.responseFormatter.setAnalyticsService(analyticsService);
 213 |   }
 214 | 
 215 |   /**
 216 |    * Set config manager for configuration operations
 217 |    */
 218 |   setConfigManager(configManager: ConfigManager): void {
 219 |     this.configManager = configManager;
 220 | 
 221 |     // Initialize SafeConfigWriter with the config file path
 222 |     try {
 223 |       // Get the config file path from the ConfigManager using proper getter method
 224 |       const configPath = configManager.getConfigPath();
 225 |       this.safeConfigWriter = createSafeConfigWriter(
 226 |         this.logger,
 227 |         configManager,
 228 |         configPath
 229 |       );
 230 |       this.logger.debug(
 231 |         "ConfigManager and SafeConfigWriter configured for system control"
 232 |       );
 233 |     } catch (error) {
 234 |       this.logger.warn("Failed to initialize SafeConfigWriter:", error);
 235 |       this.logger.debug(
 236 |         "ConfigManager configured for system control (read-only mode)"
 237 |       );
 238 |     }
 239 |   }
 240 | 
 241 |   /**
 242 |    * Set restart callback (for system restart functionality)
 243 |    */
 244 |   setRestartCallback(onRestart: (reason: string) => Promise<void>): void {
 245 |     this.onRestart = onRestart;
 246 |     this.logger.debug("Restart callback configured for system control");
 247 |   }
 248 | 
 249 |   /**
 250 |    * Set MCPToolsManager reference (for dynamic tool updates)
 251 |    */
 252 |   setMCPToolsManager(mcpToolsManager: any): void {
 253 |     this.mcpToolsManager = mcpToolsManager;
 254 |     this.logger.debug(
 255 |       "MCPToolsManager reference configured for dynamic tool updates"
 256 |     );
 257 |   }
 258 | 
 259 |   /**
 260 |    * Set gate performance analyzer (Phase 4 - Clean Architecture)
 261 |    */
 262 |   setGatePerformanceAnalyzer(analyzer: GatePerformanceAnalyzer): void {
 263 |     this.gatePerformanceAnalyzer = analyzer;
 264 |     this.logger.debug("Gate performance analyzer configured for analytics");
 265 |   }
 266 | 
 267 |   /**
 268 |    * Set gate system manager for runtime gate management
 269 |    */
 270 |   setGateSystemManager(gateSystemManager: GateSystemManager): void {
 271 |     this.gateSystemManager = gateSystemManager;
 272 |     this.logger.debug(
 273 |       "Gate system manager configured for runtime gate control"
 274 |     );
 275 |   }
 276 | 
 277 |   /**
 278 |    * Set gate guidance renderer for discovery operations
 279 |    */
 280 |   setGateGuidanceRenderer(renderer: GateGuidanceRenderer): void {
 281 |     this.gateGuidanceRenderer = renderer;
 282 |     this.logger.debug(
 283 |       "Gate guidance renderer configured for gate discovery"
 284 |     );
 285 |   }
 286 | 
 287 |   /**
 288 |    * Helper function for minimal outputSchema compliance
 289 |    */
 290 |   private createMinimalSystemResponse(
 291 |     text: string,
 292 |     action: string
 293 |   ): ToolResponse {
 294 |     return createStructuredResponse(text, false, {
 295 |       action,
 296 |       executionMetadata: {
 297 |         executionId: `sc-${action}-${Date.now()}`,
 298 |         executionType: "prompt" as const,
 299 |         startTime: Date.now(),
 300 |         endTime: Date.now(),
 301 |         executionTime: 0,
 302 |         frameworkEnabled: true,
 303 |       },
 304 |       systemState: {
 305 |         frameworkEnabled: true,
 306 |         activeFramework: "CAGEERF",
 307 |         availableFrameworks: ["CAGEERF", "ReACT", "5W1H", "SCAMPER"],
 308 |         uptime: 0,
 309 |         memoryUsage: {
 310 |           rss: 0,
 311 |           heapTotal: 0,
 312 |           heapUsed: 0,
 313 |           external: 0,
 314 |         },
 315 |         serverHealth: "healthy" as const,
 316 |       },
 317 |     });
 318 |   }
 319 | 
 320 |   /**
 321 |    * Derived calculation: Get execution mode distribution from performance trends
 322 |    */
 323 |   getExecutionsByMode(): Record<string, number> {
 324 |     return this.systemAnalytics.performanceTrends.reduce((acc, trend) => {
 325 |       if (trend.executionMode) {
 326 |         acc[trend.executionMode] = (acc[trend.executionMode] || 0) + 1;
 327 |       }
 328 |       return acc;
 329 |     }, {} as Record<string, number>);
 330 |   }
 331 | 
 332 |   /**
 333 |    * Update system analytics with rich execution data
 334 |    */
 335 |   updateAnalytics(
 336 |     analytics: Partial<SystemAnalytics> & { currentExecution?: any }
 337 |   ): void {
 338 |     // Update aggregate fields
 339 |     Object.assign(this.systemAnalytics, analytics);
 340 |     this.systemAnalytics.uptime = Date.now() - this.startTime;
 341 | 
 342 |     // Update memory usage
 343 |     this.systemAnalytics.memoryUsage = process.memoryUsage();
 344 | 
 345 |     // Record execution time trend with rich context
 346 |     if (analytics.currentExecution) {
 347 |       const currentExecution = analytics.currentExecution;
 348 |       this.systemAnalytics.performanceTrends.push({
 349 |         timestamp: Date.now(),
 350 |         metric: "executionTime",
 351 |         value: currentExecution.executionTime,
 352 |         executionMode: currentExecution.executionMode,
 353 |         framework: currentExecution.framework,
 354 |         success: currentExecution.success,
 355 |       });
 356 |     }
 357 | 
 358 |     // Add memory delta trend if significant change
 359 |     if (this.systemAnalytics.memoryUsage) {
 360 |       const memoryDelta = this.calculateMemoryDelta();
 361 |       if (Math.abs(memoryDelta) > 1024 * 1024) {
 362 |         // Only track changes > 1MB
 363 |         this.systemAnalytics.performanceTrends.push({
 364 |           timestamp: Date.now(),
 365 |           metric: "memoryDelta",
 366 |           value: memoryDelta,
 367 |         });
 368 |       }
 369 |     }
 370 | 
 371 |     // Add success rate trend periodically (every 10 executions)
 372 |     if (analytics.totalExecutions && analytics.totalExecutions % 10 === 0) {
 373 |       const successRate =
 374 |         analytics.totalExecutions > 0
 375 |           ? ((analytics.successfulExecutions || 0) /
 376 |               analytics.totalExecutions) *
 377 |             100
 378 |           : 0;
 379 |       this.systemAnalytics.performanceTrends.push({
 380 |         timestamp: Date.now(),
 381 |         metric: "successRate",
 382 |         value: successRate,
 383 |       });
 384 |     }
 385 | 
 386 |     // Keep only last 100 trend points
 387 |     if (this.systemAnalytics.performanceTrends.length > 100) {
 388 |       this.systemAnalytics.performanceTrends.shift();
 389 |     }
 390 |   }
 391 | 
 392 |   /**
 393 |    * Calculate memory usage delta from previous execution
 394 |    */
 395 |   private lastMemoryUsage: number = 0;
 396 |   private calculateMemoryDelta(): number {
 397 |     if (!this.systemAnalytics.memoryUsage) return 0;
 398 | 
 399 |     const currentMemory = this.systemAnalytics.memoryUsage.heapUsed;
 400 |     const delta = currentMemory - this.lastMemoryUsage;
 401 |     this.lastMemoryUsage = currentMemory;
 402 | 
 403 |     return delta;
 404 |   }
 405 | 
 406 |   /**
 407 |    * Main action handler
 408 |    */
 409 |   public async handleAction(
 410 |     args: {
 411 |       action: string;
 412 |       [key: string]: any;
 413 |     },
 414 |     extra: any
 415 |   ): Promise<ToolResponse> {
 416 |     const { action } = args;
 417 |     this.logger.info(`⚙️ System Control: Executing action "${action}"`);
 418 | 
 419 |     const actionHandler = this.getActionHandler(action);
 420 |     return await actionHandler.execute(args);
 421 |   }
 422 | 
 423 |   /**
 424 |    * Get the appropriate action handler based on action type
 425 |    */
 426 |   private getActionHandler(action: string): ActionHandler {
 427 |     switch (action) {
 428 |       case "status":
 429 |         return new StatusActionHandler(this);
 430 |       case "framework":
 431 |         return new FrameworkActionHandler(this);
 432 |       case "gates":
 433 |         return new GateActionHandler(this);
 434 |       case "analytics":
 435 |         return new AnalyticsActionHandler(this);
 436 |       case "config":
 437 |         return new ConfigActionHandler(this);
 438 |       case "maintenance":
 439 |         return new MaintenanceActionHandler(this);
 440 |       default:
 441 |         throw new Error(
 442 |           `Unknown action: ${action}. Valid actions: status, framework, gates, analytics, config, maintenance`
 443 |         );
 444 |     }
 445 |   }
 446 | 
 447 |   /**
 448 |    * Get comprehensive system status
 449 |    */
 450 |   public async getSystemStatus(args: {
 451 |     include_history?: boolean;
 452 |     include_metrics?: boolean;
 453 |   }): Promise<ToolResponse> {
 454 |     const { include_history = false, include_metrics = true } = args;
 455 | 
 456 |     if (!this.frameworkStateManager) {
 457 |       throw new Error("Framework state manager not initialized");
 458 |     }
 459 | 
 460 |     const health = this.frameworkStateManager.getSystemHealth();
 461 |     const statusIcon = health.status === "healthy" ? "✅" : "⚠️";
 462 | 
 463 |     // Check if framework system is enabled for injection
 464 |     const isFrameworkEnabled = health.frameworkSystemEnabled;
 465 |     const frameworkStatusIcon = isFrameworkEnabled ? "✅" : "🚫";
 466 |     const frameworkStatusText = isFrameworkEnabled
 467 |       ? `${frameworkStatusIcon} Enabled (${health.activeFramework})`
 468 |       : `${frameworkStatusIcon} Disabled (${health.activeFramework} selected)`;
 469 | 
 470 |     let response = `${statusIcon} **System Status Overview**\n\n`;
 471 |     response += `**Framework System**: ${frameworkStatusText}\n`;
 472 |     response += `**Status**: ${health.status}\n`;
 473 |     response += `**Uptime**: ${Math.floor(
 474 |       (Date.now() - this.startTime) / 1000 / 60
 475 |     )} minutes\n\n`;
 476 | 
 477 |     // Add warning message when framework is selected but system disabled
 478 |     if (!isFrameworkEnabled && health.activeFramework) {
 479 |       response += `⚠️ **Notice**: ${health.activeFramework} is selected but framework injection is disabled.\n`;
 480 |       response += `Prompts will execute without methodology guidance.\n`;
 481 |       response += `Use \`system_control framework enable\` to activate framework injection.\n\n`;
 482 |     }
 483 | 
 484 |     if (include_metrics) {
 485 |       response += `📊 **Performance Metrics**:\n`;
 486 |       response += `- Total Executions: ${this.systemAnalytics.totalExecutions}\n`;
 487 |       response += `- Success Rate: ${
 488 |         this.systemAnalytics.totalExecutions > 0
 489 |           ? Math.round(
 490 |               (this.systemAnalytics.successfulExecutions /
 491 |                 this.systemAnalytics.totalExecutions) *
 492 |                 100
 493 |             )
 494 |           : 0
 495 |       }%\n`;
 496 |       response += `- Average Execution Time: ${this.systemAnalytics.averageExecutionTime}ms\n\n`;
 497 |     }
 498 | 
 499 |     return this.createMinimalSystemResponse(response, "status");
 500 |   }
 501 | 
 502 |   // Framework management methods
 503 |   public async switchFramework(args: {
 504 |     framework?: "CAGEERF" | "ReACT" | "5W1H" | "SCAMPER";
 505 |     reason?: string;
 506 |   }): Promise<ToolResponse> {
 507 |     if (!this.frameworkStateManager) {
 508 |       throw new Error("Framework state manager not initialized");
 509 |     }
 510 | 
 511 |     if (!args.framework) {
 512 |       throw new Error("Framework parameter is required for switch operation");
 513 |     }
 514 | 
 515 |     const { framework, reason = `User requested switch to ${args.framework}` } =
 516 |       args;
 517 | 
 518 |     const currentState = this.frameworkStateManager.getCurrentState();
 519 | 
 520 |     // Check if already active
 521 |     if (currentState.activeFramework === framework) {
 522 |       return this.createMinimalSystemResponse(
 523 |         `ℹ️ Framework '${framework}' is already active. No change needed.`,
 524 |         "switch_framework"
 525 |       );
 526 |     }
 527 | 
 528 |     const request: FrameworkSwitchRequest = {
 529 |       targetFramework: framework,
 530 |       reason: reason,
 531 |     };
 532 | 
 533 |     const success = await this.frameworkStateManager.switchFramework(request);
 534 | 
 535 |     if (success) {
 536 |       const newState = this.frameworkStateManager.getCurrentState();
 537 |       const activeFramework = this.frameworkStateManager.getActiveFramework();
 538 | 
 539 |       let response = `🔄 **Framework Switch Successful**\n\n`;
 540 |       response += `**Previous**: ${currentState.activeFramework}\n`;
 541 |       response += `**Current**: ${newState.activeFramework}\n`;
 542 |       response += `**Switched At**: ${newState.switchedAt.toISOString()}\n`;
 543 |       response += `**Reason**: ${reason}\n\n`;
 544 |       response += `**New Framework Details**:\n`;
 545 |       response += `- **Name**: ${activeFramework.name}\n`;
 546 |       response += `- **Description**: ${activeFramework.description}\n`;
 547 |       response += `- **Methodology**: ${activeFramework.methodology}\n\n`;
 548 |       response += `**Guidelines**: ${activeFramework.executionGuidelines.join(
 549 |         " • "
 550 |       )}\n\n`;
 551 |       response += `✅ All future prompt executions will now use the ${framework} methodology.`;
 552 | 
 553 |       return this.createMinimalSystemResponse(response, "switch_framework");
 554 |     } else {
 555 |       throw new Error(
 556 |         `Failed to switch to framework '${framework}'. Please check framework availability and try again.`
 557 |       );
 558 |     }
 559 |   }
 560 | 
 561 |   public async listFrameworks(args: {
 562 |     show_details?: boolean;
 563 |   }): Promise<ToolResponse> {
 564 |     if (!this.frameworkManager) {
 565 |       throw new Error("Framework manager not initialized");
 566 |     }
 567 | 
 568 |     const frameworks = this.frameworkManager.listFrameworks();
 569 |     const currentState = this.frameworkStateManager?.getCurrentState();
 570 |     const activeFramework = currentState?.activeFramework || "CAGEERF";
 571 | 
 572 |     let response = `📋 **Available Frameworks**\n\n`;
 573 | 
 574 |     frameworks.forEach((framework: any) => {
 575 |       // Handle case variations by comparing uppercase versions
 576 |       const isActive =
 577 |         framework.id.toUpperCase() === activeFramework.toUpperCase();
 578 |       const status = isActive ? "🟢 ACTIVE" : "⚪ Available";
 579 | 
 580 |       response += `**${framework.name}** ${status}\n`;
 581 | 
 582 |       if (args.show_details) {
 583 |         response += `   📝 ${framework.description}\n`;
 584 |         response += `   🎯 Methodology: ${framework.methodology}\n`;
 585 |         if (
 586 |           framework.executionGuidelines &&
 587 |           framework.executionGuidelines.length > 0
 588 |         ) {
 589 |           response += `   📋 Guidelines: ${framework.executionGuidelines
 590 |             .slice(0, 2)
 591 |             .join(" • ")}\n`;
 592 |         }
 593 |         response += `\n`;
 594 |       }
 595 |     });
 596 | 
 597 |     if (!args.show_details) {
 598 |       response += `\n💡 Use 'show_details: true' for more information about each framework.\n`;
 599 |     }
 600 | 
 601 |     response += `\n🔄 Switch frameworks using: action="framework", operation="switch", framework="<name>"`;
 602 | 
 603 |     return this.createMinimalSystemResponse(response, "list_frameworks");
 604 |   }
 605 | 
 606 |   public async enableFrameworkSystem(args: {
 607 |     reason?: string;
 608 |   }): Promise<ToolResponse> {
 609 |     if (!this.frameworkStateManager) {
 610 |       throw new Error("Framework state manager not initialized");
 611 |     }
 612 | 
 613 |     const currentState = this.frameworkStateManager.getCurrentState();
 614 |     if (currentState.frameworkSystemEnabled) {
 615 |       return this.createMinimalSystemResponse(
 616 |         `ℹ️ Framework system is already enabled.`,
 617 |         "enable_framework_system"
 618 |       );
 619 |     }
 620 | 
 621 |     // Enable framework system (for now, just return success message since the method may not exist)
 622 |     try {
 623 |       await (this.frameworkStateManager as any).enableFrameworkSystem?.(
 624 |         args.reason || "User requested to enable framework system"
 625 |       );
 626 |     } catch (error) {
 627 |       // Method may not exist, that's ok for now
 628 |     }
 629 | 
 630 |     const response =
 631 |       `✅ **Framework System Enabled**\n\n` +
 632 |       `**Reason**: ${
 633 |         args.reason || "User requested to enable framework system"
 634 |       }\n` +
 635 |       `**Status**: Framework system is now active\n` +
 636 |       `**Active Framework**: ${currentState.activeFramework}\n\n` +
 637 |       `🎯 All prompt executions will now use framework-guided processing.`;
 638 | 
 639 |     return this.createMinimalSystemResponse(
 640 |       response,
 641 |       "enable_framework_system"
 642 |     );
 643 |   }
 644 | 
 645 |   public async disableFrameworkSystem(args: {
 646 |     reason?: string;
 647 |   }): Promise<ToolResponse> {
 648 |     if (!this.frameworkStateManager) {
 649 |       throw new Error("Framework state manager not initialized");
 650 |     }
 651 | 
 652 |     const currentState = this.frameworkStateManager.getCurrentState();
 653 |     if (!currentState.frameworkSystemEnabled) {
 654 |       return this.createMinimalSystemResponse(
 655 |         `ℹ️ Framework system is already disabled.`,
 656 |         "disable_framework_system"
 657 |       );
 658 |     }
 659 | 
 660 |     // Disable framework system (for now, just return success message since the method may not exist)
 661 |     try {
 662 |       await (this.frameworkStateManager as any).disableFrameworkSystem?.(
 663 |         args.reason || "User requested to disable framework system"
 664 |       );
 665 |     } catch (error) {
 666 |       // Method may not exist, that's ok for now
 667 |     }
 668 | 
 669 |     const response =
 670 |       `⚠️ **Framework System Disabled**\n\n` +
 671 |       `**Reason**: ${
 672 |         args.reason || "User requested to disable framework system"
 673 |       }\n` +
 674 |       `**Status**: Framework system is now inactive\n` +
 675 |       `**Previous Framework**: ${currentState.activeFramework}\n\n` +
 676 |       `📝 Prompt executions will now use basic processing without framework guidance.`;
 677 | 
 678 |     return this.createMinimalSystemResponse(
 679 |       response,
 680 |       "disable_framework_system"
 681 |     );
 682 |   }
 683 | 
 684 |   /**
 685 |    * Enable gate system
 686 |    */
 687 |   public async enableGateSystem(args: {
 688 |     reason?: string;
 689 |   }): Promise<ToolResponse> {
 690 |     if (!this.gateSystemManager) {
 691 |       throw new Error("Gate system manager not initialized");
 692 |     }
 693 | 
 694 |     const currentState = this.gateSystemManager.getCurrentState();
 695 |     if (currentState.enabled) {
 696 |       return this.createMinimalSystemResponse(
 697 |         `ℹ️ Gate system is already enabled.`,
 698 |         "enable_gate_system"
 699 |       );
 700 |     }
 701 | 
 702 |     await this.gateSystemManager.enableGateSystem(
 703 |       args.reason || "User requested to enable gate system"
 704 |     );
 705 | 
 706 |     const response =
 707 |       `✅ **Gate System Enabled**\n\n` +
 708 |       `**Reason**: ${args.reason || "User requested to enable gate system"}\n` +
 709 |       `**Status**: Gate system is now active\n` +
 710 |       `**Validation**: Quality gates will now be applied to prompt executions\n\n` +
 711 |       `🔍 All template and chain executions will now include gate validation and guidance.`;
 712 | 
 713 |     return this.createMinimalSystemResponse(response, "enable_gate_system");
 714 |   }
 715 | 
 716 |   /**
 717 |    * Disable gate system
 718 |    */
 719 |   public async disableGateSystem(args: {
 720 |     reason?: string;
 721 |   }): Promise<ToolResponse> {
 722 |     if (!this.gateSystemManager) {
 723 |       throw new Error("Gate system manager not initialized");
 724 |     }
 725 | 
 726 |     const currentState = this.gateSystemManager.getCurrentState();
 727 |     if (!currentState.enabled) {
 728 |       return this.createMinimalSystemResponse(
 729 |         `ℹ️ Gate system is already disabled.`,
 730 |         "disable_gate_system"
 731 |       );
 732 |     }
 733 | 
 734 |     await this.gateSystemManager.disableGateSystem(
 735 |       args.reason || "User requested to disable gate system"
 736 |     );
 737 | 
 738 |     const response =
 739 |       `⚠️ **Gate System Disabled**\n\n` +
 740 |       `**Reason**: ${
 741 |         args.reason || "User requested to disable gate system"
 742 |       }\n` +
 743 |       `**Status**: Gate system is now inactive\n` +
 744 |       `**Impact**: Gate validation and guidance will be skipped\n\n` +
 745 |       `📝 Prompt executions will now skip quality gate validation.`;
 746 | 
 747 |     return this.createMinimalSystemResponse(response, "disable_gate_system");
 748 |   }
 749 | 
 750 |   /**
 751 |    * Get gate system status
 752 |    */
 753 |   public async getGateSystemStatus(): Promise<ToolResponse> {
 754 |     if (!this.gateSystemManager) {
 755 |       return this.createMinimalSystemResponse(
 756 |         `❌ Gate system manager not available.`,
 757 |         "gate_system_status"
 758 |       );
 759 |     }
 760 | 
 761 |     const currentState = this.gateSystemManager.getCurrentState();
 762 |     const health = this.gateSystemManager.getSystemHealth();
 763 | 
 764 |     let response = `🚪 **Gate System Status**\n\n`;
 765 |     response += `**System State**: ${
 766 |       currentState.enabled ? "Enabled" : "Disabled"
 767 |     }\n`;
 768 |     response += `**Health Status**: ${health.status}\n`;
 769 |     response += `**Total Validations**: ${health.totalValidations}\n`;
 770 |     response += `**Success Rate**: ${health.successRate}%\n`;
 771 |     response += `**Average Validation Time**: ${health.averageValidationTime}ms\n`;
 772 | 
 773 |     if (health.lastValidationTime) {
 774 |       response += `**Last Validation**: ${health.lastValidationTime.toISOString()}\n`;
 775 |     }
 776 | 
 777 |     if (health.issues.length > 0) {
 778 |       response += `\n⚠️ **Issues**:\n`;
 779 |       health.issues.forEach((issue) => {
 780 |         response += `- ${issue}\n`;
 781 |       });
 782 |     }
 783 | 
 784 |     response += `\n🔧 Control gates using: action="gates", operation="enable/disable"`;
 785 | 
 786 |     return this.createMinimalSystemResponse(response, "gate_system_status");
 787 |   }
 788 | 
 789 |   /**
 790 |    * Get gate system health details
 791 |    */
 792 |   public async getGateSystemHealth(): Promise<ToolResponse> {
 793 |     if (!this.gateSystemManager) {
 794 |       return this.createMinimalSystemResponse(
 795 |         `❌ Gate system manager not available.`,
 796 |         "gate_system_health"
 797 |       );
 798 |     }
 799 | 
 800 |     const health = this.gateSystemManager.getSystemHealth();
 801 | 
 802 |     let response = `🏥 **Gate System Health Report**\n\n`;
 803 | 
 804 |     // Health status indicator
 805 |     const statusIcon =
 806 |       health.status === "healthy"
 807 |         ? "✅"
 808 |         : health.status === "degraded"
 809 |         ? "⚠️"
 810 |         : "❌";
 811 |     response += `**Overall Status**: ${statusIcon} ${health.status.toUpperCase()}\n\n`;
 812 | 
 813 |     // Core metrics
 814 |     response += `**Performance Metrics**:\n`;
 815 |     response += `- Enabled: ${health.enabled ? "Yes" : "No"}\n`;
 816 |     response += `- Total Validations: ${health.totalValidations}\n`;
 817 |     response += `- Success Rate: ${health.successRate}%\n`;
 818 |     response += `- Average Validation Time: ${health.averageValidationTime}ms\n`;
 819 | 
 820 |     if (health.lastValidationTime) {
 821 |       response += `- Last Validation: ${health.lastValidationTime.toISOString()}\n`;
 822 |     }
 823 | 
 824 |     // Health analysis
 825 |     if (health.status === "healthy") {
 826 |       response += "\n✅ System is performing optimally. No action required.\n";
 827 |     } else if (health.status === "degraded") {
 828 |       response += "\n⚠️ System performance is degraded. Monitor closely.\n";
 829 |       if (health.issues.length > 0) {
 830 |         response += "\n**Issues Detected**:\n";
 831 |         health.issues.forEach((issue) => {
 832 |           response += `- ${issue}\n`;
 833 |         });
 834 |       }
 835 |     } else if (health.status === "disabled") {
 836 |       response += "\n🚫 Gate system is currently disabled.\n";
 837 |       response += "Enable using: `action='gates', operation='enable'`\n";
 838 |     }
 839 | 
 840 |     return this.createMinimalSystemResponse(response, "gate_system_health");
 841 |   }
 842 | 
 843 |   /**
 844 |    * List all available quality gates
 845 |    */
 846 |   async listAvailableGates(): Promise<ToolResponse> {
 847 |     const gates =
 848 |       (await this.gateGuidanceRenderer?.getAvailableGates()) || [];
 849 | 
 850 |     const gateList = gates.length
 851 |       ? gates.map((gate) => `• ${gate}`).join("\n")
 852 |       : "• No quality gates discovered. Ensure gate configuration is available.";
 853 | 
 854 |     const exampleGate = gates[0] || "gate-name";
 855 | 
 856 |     const response = [
 857 |       "📋 **Available Quality Gates**",
 858 |       "",
 859 |       "Discover gates using: `system_control({ action: \"gates\", operation: \"list\" })`",
 860 |       "",
 861 |       gateList,
 862 |       "",
 863 |       "**Usage**: Specify gate names in prompt_engine's `quality_gates` parameter",
 864 |       `**Example**: \`{ \\\"quality_gates\\\": [\"${exampleGate}\"], \\\"gate_mode\\\": \"enforce\" }\``,
 865 |     ].join("\n");
 866 | 
 867 |     return this.createMinimalSystemResponse(response, "gate_list");
 868 |   }
 869 | 
 870 |   public async resetMetrics(args: any): Promise<ToolResponse> {
 871 |     throw new Error("resetMetrics method not yet implemented");
 872 |   }
 873 | 
 874 |   public async getSwitchHistory(args: any): Promise<ToolResponse> {
 875 |     throw new Error("getSwitchHistory method not yet implemented");
 876 |   }
 877 | 
 878 |   public async getAnalytics(args: any): Promise<ToolResponse> {
 879 |     throw new Error("getAnalytics method not yet implemented");
 880 |   }
 881 | 
 882 |   public async restoreConfig(args: any): Promise<ToolResponse> {
 883 |     throw new Error("restoreConfig method not yet implemented");
 884 |   }
 885 | 
 886 |   public async manageConfig(args: any): Promise<ToolResponse> {
 887 |     throw new Error("manageConfig method not yet implemented");
 888 |   }
 889 | 
 890 |   public async restartServer(args: any): Promise<ToolResponse> {
 891 |     throw new Error("restartServer method not yet implemented");
 892 |   }
 893 | }
 894 | 
 895 | /**
 896 |  * Base class for action handlers using command pattern
 897 |  */
 898 | abstract class ActionHandler {
 899 |   constructor(protected systemControl: ConsolidatedSystemControl) {}
 900 |   abstract execute(args: any): Promise<ToolResponse>;
 901 | 
 902 |   // Convenience getters for accessing system control properties
 903 |   protected get responseFormatter() {
 904 |     return this.systemControl["responseFormatter"];
 905 |   }
 906 |   protected get logger() {
 907 |     return this.systemControl["logger"];
 908 |   }
 909 |   protected get startTime() {
 910 |     return this.systemControl.startTime;
 911 |   }
 912 |   protected get frameworkManager() {
 913 |     return this.systemControl["frameworkManager"];
 914 |   }
 915 |   protected get mcpToolsManager() {
 916 |     return this.systemControl["mcpToolsManager"];
 917 |   }
 918 |   protected get configManager() {
 919 |     return this.systemControl["configManager"];
 920 |   }
 921 |   protected get safeConfigWriter() {
 922 |     return this.systemControl["safeConfigWriter"];
 923 |   }
 924 |   protected get onRestart() {
 925 |     return this.systemControl["onRestart"];
 926 |   }
 927 | 
 928 |   // Helper methods for system status and formatting
 929 |   protected createMinimalSystemResponse(
 930 |     text: string,
 931 |     action: string
 932 |   ): ToolResponse {
 933 |     return createStructuredResponse(text, false, {
 934 |       action,
 935 |       systemState: {
 936 |         uptime: Date.now() - this.startTime,
 937 |         framework:
 938 |           this.systemControl.frameworkStateManager?.getCurrentState()
 939 |             .activeFramework,
 940 |       },
 941 |     });
 942 |   }
 943 | 
 944 |   protected getExecutionsByMode(): Record<string, number> {
 945 |     // Extract execution mode data from performance trends
 946 |     const modeData: Record<string, number> = {};
 947 |     this.systemControl.systemAnalytics.performanceTrends.forEach((trend) => {
 948 |       if (trend.executionMode) {
 949 |         modeData[trend.executionMode] =
 950 |           (modeData[trend.executionMode] || 0) + 1;
 951 |       }
 952 |     });
 953 |     return modeData;
 954 |   }
 955 | 
 956 |   protected formatUptime(uptime: number): string {
 957 |     const seconds = Math.floor(uptime / 1000);
 958 |     const minutes = Math.floor(seconds / 60);
 959 |     const hours = Math.floor(minutes / 60);
 960 |     const days = Math.floor(hours / 24);
 961 | 
 962 |     if (days > 0) return `${days}d ${hours % 24}h ${minutes % 60}m`;
 963 |     if (hours > 0) return `${hours}h ${minutes % 60}m`;
 964 |     if (minutes > 0) return `${minutes}m ${seconds % 60}s`;
 965 |     return `${seconds}s`;
 966 |   }
 967 | 
 968 |   protected formatExecutionTime(time: number): string {
 969 |     return `${Math.round(time)}ms`;
 970 |   }
 971 | 
 972 |   protected formatBytes(bytes: number): string {
 973 |     const units = ["B", "KB", "MB", "GB"];
 974 |     let value = bytes;
 975 |     let unitIndex = 0;
 976 |     while (value >= 1024 && unitIndex < units.length - 1) {
 977 |       value /= 1024;
 978 |       unitIndex++;
 979 |     }
 980 |     return `${Math.round(value * 100) / 100}${units[unitIndex]}`;
 981 |   }
 982 | 
 983 |   protected getHealthIcon(status: string): string {
 984 |     switch (status) {
 985 |       case "healthy":
 986 |         return "✅";
 987 |       case "warning":
 988 |         return "⚠️";
 989 |       case "error":
 990 |         return "❌";
 991 |       case "critical":
 992 |         return "🚨";
 993 |       default:
 994 |         return "❓";
 995 |     }
 996 |   }
 997 | 
 998 |   protected getSuccessRate(): number {
 999 |     const total = this.systemControl.systemAnalytics.totalExecutions;
1000 |     if (total === 0) return 100;
1001 |     return Math.round(
1002 |       (this.systemControl.systemAnalytics.successfulExecutions / total) * 100
1003 |     );
1004 |   }
1005 | 
1006 |   protected formatTrendContext(trend: any): string {
1007 |     let context = "";
1008 |     if (trend.framework) context += ` [${trend.framework}]`;
1009 |     if (trend.executionMode) context += ` (${trend.executionMode})`;
1010 |     if (trend.success !== undefined) context += trend.success ? " ✓" : " ✗";
1011 |     return context;
1012 |   }
1013 | 
1014 |   protected formatTrendValue(metric: string, value: number): string {
1015 |     switch (metric) {
1016 |       case "executionTime":
1017 |         return `${Math.round(value)}ms`;
1018 |       case "memoryDelta":
1019 |         return `${value > 0 ? "+" : ""}${this.formatBytes(value)}`;
1020 |       case "successRate":
1021 |         return `${Math.round(value * 100)}%`;
1022 |       case "gateValidationTime":
1023 |         return `${Math.round(value)}ms validation`;
1024 |       default:
1025 |         return String(value);
1026 |     }
1027 |   }
1028 | }
1029 | 
1030 | /**
1031 |  * Handler for status-related operations
1032 |  */
1033 | class StatusActionHandler extends ActionHandler {
1034 |   async execute(args: any): Promise<ToolResponse> {
1035 |     const operation = args.operation || "default";
1036 | 
1037 |     switch (operation) {
1038 |       case "health":
1039 |         return await this.getSystemHealthStatus();
1040 |       case "diagnostics":
1041 |         return await this.getSystemDiagnostics();
1042 |       case "framework_status":
1043 |         return await this.getFrameworkStatus();
1044 |       case "overview":
1045 |       case "default":
1046 |       default:
1047 |         return await this.systemControl.getSystemStatus({
1048 |           include_history: args.include_history,
1049 |           include_metrics: args.include_metrics,
1050 |         });
1051 |     }
1052 |   }
1053 | 
1054 |   private async getSystemHealthStatus(): Promise<ToolResponse> {
1055 |     if (!this.systemControl.frameworkStateManager) {
1056 |       throw new Error("Framework state manager not initialized");
1057 |     }
1058 | 
1059 |     const health = this.systemControl.frameworkStateManager.getSystemHealth();
1060 |     const statusIcon = health.status === "healthy" ? "✅" : "⚠️";
1061 | 
1062 |     let response = `${statusIcon} **System Health Status**: ${health.status}\n\n`;
1063 |     response += `📊 **Metrics**:\n`;
1064 | 
1065 |     // Improved framework status display
1066 |     const isFrameworkEnabled = health.frameworkSystemEnabled;
1067 |     const injectionStatus = isFrameworkEnabled ? "Working" : "Inactive";
1068 |     const frameworkStatusText = isFrameworkEnabled
1069 |       ? `✅ Enabled - ${health.activeFramework} methodology active`
1070 |       : `🚫 Disabled - ${health.activeFramework} selected but not injecting`;
1071 | 
1072 |     response += `- Framework System: ${frameworkStatusText}\n`;
1073 |     response += `- Framework Injection: ${injectionStatus}\n`;
1074 |     response += `- Available Frameworks: ${health.availableFrameworks.join(
1075 |       ", "
1076 |     )}\n`;
1077 |     response += `- Total Framework Switches: ${health.switchingMetrics.totalSwitches}\n`;
1078 | 
1079 |     return this.createMinimalSystemResponse(response, "health");
1080 |   }
1081 | 
1082 |   private async getSystemDiagnostics(): Promise<ToolResponse> {
1083 |     let response = `🔧 **System Diagnostics**\n\n`;
1084 | 
1085 |     try {
1086 |       if (this.systemControl.frameworkStateManager) {
1087 |         const health =
1088 |           this.systemControl.frameworkStateManager.getSystemHealth();
1089 |         response += `Framework State: ${health.status}\n`;
1090 |         response += `Active Framework: ${health.activeFramework}\n`;
1091 |       }
1092 | 
1093 |       response += `Server Uptime: ${
1094 |         Date.now() - this.systemControl.startTime
1095 |       }ms\n`;
1096 |     } catch (error) {
1097 |       response += `❌ Error during diagnostics: ${error}\n`;
1098 |     }
1099 | 
1100 |     return this.createMinimalSystemResponse(response, "diagnostics");
1101 |   }
1102 | 
1103 |   private async getFrameworkStatus(): Promise<ToolResponse> {
1104 |     if (!this.systemControl.frameworkStateManager) {
1105 |       throw new Error("Framework state manager not initialized");
1106 |     }
1107 | 
1108 |     const health = this.systemControl.frameworkStateManager.getSystemHealth();
1109 | 
1110 |     let response = `🎯 **Framework System Status**\n\n`;
1111 | 
1112 |     // Enhanced status display
1113 |     const isFrameworkEnabled = health.frameworkSystemEnabled;
1114 |     const injectionStatusIcon = isFrameworkEnabled ? "✅" : "🚫";
1115 |     const injectionStatusText = isFrameworkEnabled
1116 |       ? "Active - Framework guidance being applied"
1117 |       : "Inactive - Framework guidance disabled";
1118 | 
1119 |     response += `**Selected Framework**: ${health.activeFramework}\n`;
1120 |     response += `**Injection Status**: ${injectionStatusIcon} ${injectionStatusText}\n`;
1121 |     response += `**System State**: ${
1122 |       health.frameworkSystemEnabled ? "Enabled" : "Disabled"
1123 |     }\n`;
1124 |     response += `**Health Status**: ${health.status}\n`;
1125 |     response += `**Available Frameworks**: ${health.availableFrameworks.join(
1126 |       ", "
1127 |     )}\n`;
1128 | 
1129 |     // Add warning for confused state
1130 |     if (!isFrameworkEnabled && health.activeFramework) {
1131 |       response += `\n⚠️ **Warning**: Framework system is disabled while ${health.activeFramework} is selected.\n`;
1132 |       response += `This means prompts will NOT receive framework methodology guidance.\n`;
1133 |       response += `To enable framework injection, use: \`system_control framework enable\`\n`;
1134 |     }
1135 | 
1136 |     return this.createMinimalSystemResponse(response, "framework_status");
1137 |   }
1138 | }
1139 | 
1140 | /**
1141 |  * Handler for framework-related operations
1142 |  */
1143 | class FrameworkActionHandler extends ActionHandler {
1144 |   async execute(args: any): Promise<ToolResponse> {
1145 |     const operation = args.operation || "default";
1146 | 
1147 |     switch (operation) {
1148 |       case "switch":
1149 |         return await this.systemControl.switchFramework({
1150 |           framework: args.framework,
1151 |           reason: args.reason,
1152 |         });
1153 |       case "list":
1154 |         return await this.systemControl.listFrameworks({
1155 |           show_details: args.show_details,
1156 |         });
1157 |       case "enable":
1158 |         return await this.systemControl.enableFrameworkSystem({
1159 |           reason: args.reason,
1160 |         });
1161 |       case "disable":
1162 |         return await this.systemControl.disableFrameworkSystem({
1163 |           reason: args.reason,
1164 |         });
1165 |       default:
1166 |         throw new Error(
1167 |           `Unknown framework operation: ${operation}. Valid operations: switch, list, enable, disable`
1168 |         );
1169 |     }
1170 |   }
1171 | }
1172 | 
1173 | /**
1174 |  * Handler for gates-related operations
1175 |  */
1176 | class GateActionHandler extends ActionHandler {
1177 |   async execute(args: any): Promise<ToolResponse> {
1178 |     const operation = args.operation || "status";
1179 | 
1180 |     switch (operation) {
1181 |       case "enable":
1182 |         return await this.systemControl.enableGateSystem({
1183 |           reason: args.reason,
1184 |         });
1185 |       case "disable":
1186 |         return await this.systemControl.disableGateSystem({
1187 |           reason: args.reason,
1188 |         });
1189 |       case "status":
1190 |         return await this.systemControl.getGateSystemStatus();
1191 |       case "health":
1192 |         return await this.systemControl.getGateSystemHealth();
1193 |       case "list":
1194 |         return await this.systemControl.listAvailableGates();
1195 |       default:
1196 |         throw new Error(
1197 |           `Unknown gates operation: ${operation}. Valid operations: enable, disable, status, health, list`
1198 |         );
1199 |     }
1200 |   }
1201 | }
1202 | 
1203 | /**
1204 |  * Handler for analytics-related operations
1205 |  */
1206 | class AnalyticsActionHandler extends ActionHandler {
1207 |   async execute(args: any): Promise<ToolResponse> {
1208 |     const operation = args.operation || "default";
1209 | 
1210 |     switch (operation) {
1211 |       case "reset":
1212 |         return await this.systemControl.resetMetrics({
1213 |           confirm: args.confirm,
1214 |         });
1215 |       case "history":
1216 |         return await this.systemControl.getSwitchHistory({
1217 |           limit: args.limit,
1218 |         });
1219 |       case "view":
1220 |       case "default":
1221 |       default:
1222 |         return await this.systemControl.getAnalytics({
1223 |           include_history: args.include_history,
1224 |           reset_analytics: args.reset_analytics,
1225 |         });
1226 |     }
1227 |   }
1228 | }
1229 | 
1230 | /**
1231 |  * Handler for config-related operations
1232 |  */
1233 | class ConfigActionHandler extends ActionHandler {
1234 |   async execute(args: any): Promise<ToolResponse> {
1235 |     const operation = args.operation || "default";
1236 | 
1237 |     switch (operation) {
1238 |       case "restore":
1239 |         return await this.systemControl.restoreConfig({
1240 |           backup_path: args.backup_path,
1241 |           confirm: args.confirm,
1242 |         });
1243 |       case "get":
1244 |       case "set":
1245 |       case "list":
1246 |       case "validate":
1247 |       case "default":
1248 |       default:
1249 |         return await this.systemControl.manageConfig({
1250 |           config: args.config,
1251 |         });
1252 |     }
1253 |   }
1254 | }
1255 | 
1256 | /**
1257 |  * Handler for maintenance-related operations
1258 |  */
1259 | class MaintenanceActionHandler extends ActionHandler {
1260 |   async execute(args: any): Promise<ToolResponse> {
1261 |     const operation = args.operation || "default";
1262 | 
1263 |     switch (operation) {
1264 |       case "restart":
1265 |       case "default":
1266 |       default:
1267 |         return await this.systemControl.restartServer({
1268 |           reason: args.reason,
1269 |           confirm: args.confirm,
1270 |         });
1271 |     }
1272 |   }
1273 | 
1274 |   /**
1275 |    * Get comprehensive system status
1276 |    */
1277 |   public async getSystemStatus(args: {
1278 |     include_history?: boolean;
1279 |     include_metrics?: boolean;
1280 |   }): Promise<ToolResponse> {
1281 |     const { include_history = false, include_metrics = true } = args;
1282 | 
1283 |     if (!this.systemControl.frameworkStateManager) {
1284 |       throw new Error("Framework state manager not initialized");
1285 |     }
1286 | 
1287 |     const currentState =
1288 |       this.systemControl.frameworkStateManager.getCurrentState();
1289 |     const systemHealth =
1290 |       this.systemControl.frameworkStateManager.getSystemHealth();
1291 |     const activeFramework =
1292 |       this.systemControl.frameworkStateManager.getActiveFramework();
1293 | 
1294 |     let response = "# ⚙️ System Status Report\n\n";
1295 | 
1296 |     // Framework Status
1297 |     response += "## 📋 Framework Status\n\n";
1298 |     response += `**Active Framework**: ${activeFramework.name} (${activeFramework.id})\n`;
1299 |     response += `**Description**: ${activeFramework.description}\n`;
1300 |     response += `**System Health**: ${this.getHealthIcon(
1301 |       systemHealth.status
1302 |     )} ${systemHealth.status.toUpperCase()}\n`;
1303 |     response += `**Last Switch**: ${currentState.switchedAt.toISOString()}\n`;
1304 |     response += `**Switch Reason**: ${currentState.switchReason}\n\n`;
1305 | 
1306 |     // Gate System Status
1307 |     if (this.systemControl.gateSystemManager) {
1308 |       const gateHealth = this.systemControl.gateSystemManager.getSystemHealth();
1309 |       response += "## 🚪 Gate System Status\n\n";
1310 |       response += `**System State**: ${
1311 |         gateHealth.enabled ? "Enabled" : "Disabled"
1312 |       }\n`;
1313 |       response += `**Health Status**: ${this.getHealthIcon(
1314 |         gateHealth.status
1315 |       )} ${gateHealth.status.toUpperCase()}\n`;
1316 |       response += `**Total Validations**: ${gateHealth.totalValidations}\n`;
1317 |       response += `**Success Rate**: ${gateHealth.successRate}%\n`;
1318 |       if (gateHealth.lastValidationTime) {
1319 |         response += `**Last Validation**: ${gateHealth.lastValidationTime.toISOString()}\n`;
1320 |       }
1321 |       response += `\n`;
1322 |     } else {
1323 |       response += "## 🚪 Gate System Status\n\n";
1324 |       response += `**System State**: Not Available\n`;
1325 |       response += `**Note**: Gate system manager not initialized\n\n`;
1326 |     }
1327 | 
1328 |     // System Metrics
1329 |     response += "## 📊 System Metrics\n\n";
1330 |     response += `**Uptime**: ${this.formatUptime(
1331 |       this.systemControl.systemAnalytics.uptime
1332 |     )}\n`;
1333 |     response += `**Total Executions**: ${this.systemControl.systemAnalytics.totalExecutions}\n`;
1334 |     response += `**Success Rate**: ${this.getSuccessRate()}%\n`;
1335 |     response += `**Average Execution Time**: ${this.formatExecutionTime(
1336 |       this.systemControl.systemAnalytics.averageExecutionTime
1337 |     )}\n`;
1338 | 
1339 |     if (this.systemControl.systemAnalytics.memoryUsage) {
1340 |       const mem = this.systemControl.systemAnalytics.memoryUsage;
1341 |       response += `**Memory Usage**: ${this.formatBytes(
1342 |         mem.heapUsed
1343 |       )}/${this.formatBytes(mem.heapTotal)}\n`;
1344 |     }
1345 | 
1346 |     response += `\n`;
1347 | 
1348 |     // Available Frameworks
1349 |     const availableFrameworks =
1350 |       this.systemControl.frameworkStateManager.getAvailableFrameworks();
1351 |     response += "## 🔄 Available Frameworks\n\n";
1352 |     availableFrameworks.forEach((framework) => {
1353 |       const isActive = framework.id === currentState.activeFramework;
1354 |       const icon = isActive ? "🟢" : "⚪";
1355 |       response += `${icon} **${framework.name}** - ${framework.description}\n`;
1356 |     });
1357 |     response += "\n";
1358 | 
1359 |     // Performance Metrics
1360 |     if (include_metrics) {
1361 |       response += "## 🎯 Performance Breakdown\n\n";
1362 |       const switchingMetrics = systemHealth.switchingMetrics;
1363 |       response += `**Framework Switches**: ${switchingMetrics.totalSwitches}\n`;
1364 |       response += `**Framework Switch Success Rate**: ${
1365 |         switchingMetrics.totalSwitches > 0
1366 |           ? Math.round(
1367 |               (switchingMetrics.successfulSwitches /
1368 |                 switchingMetrics.totalSwitches) *
1369 |                 100
1370 |             )
1371 |           : 100
1372 |       }%\n`;
1373 |       response += `**Framework Switch Time**: ${Math.round(
1374 |         switchingMetrics.averageResponseTime
1375 |       )}ms\n`;
1376 | 
1377 |       response += `\n**Execution Modes**:\n`;
1378 |       const executionsByMode = this.getExecutionsByMode();
1379 |       Object.entries(executionsByMode).forEach(([mode, count]) => {
1380 |         response += `- ${
1381 |           mode.charAt(0).toUpperCase() + mode.slice(1)
1382 |         }: ${count} executions\n`;
1383 |       });
1384 |       response += `\n`;
1385 |     }
1386 | 
1387 |     // System Health Issues
1388 |     if (systemHealth.issues.length > 0) {
1389 |       response += "## ⚠️ System Issues\n\n";
1390 |       systemHealth.issues.forEach((issue) => {
1391 |         response += `- ⚠️ ${issue}\n`;
1392 |       });
1393 |       response += "\n";
1394 |     }
1395 | 
1396 |     // Recent Activity
1397 |     if (
1398 |       include_history &&
1399 |       this.systemControl.systemAnalytics.performanceTrends.length > 0
1400 |     ) {
1401 |       response += "## 📈 Recent Performance Trends\n\n";
1402 |       const recentTrends =
1403 |         this.systemControl.systemAnalytics.performanceTrends.slice(-10);
1404 |       recentTrends.forEach((trend, index) => {
1405 |         const timestamp = new Date(trend.timestamp)
1406 |           .toISOString()
1407 |           .split("T")[1]
1408 |           .split(".")[0];
1409 |         const contextInfo = this.formatTrendContext(trend);
1410 |         response += `${index + 1}. ${timestamp}: ${this.formatTrendValue(
1411 |           trend.metric,
1412 |           trend.value
1413 |         )}${contextInfo}\n`;
1414 |       });
1415 |       response += "\n";
1416 |     }
1417 | 
1418 |     // Control Commands
1419 |     response += "## 🎛️ Available Commands\n\n";
1420 |     response += "- `switch_framework` - Change active framework methodology\n";
1421 |     response +=
1422 |       "- `gates` - Control gate system (enable, disable, status, health)\n";
1423 |     response += "- `analytics` - View detailed execution analytics\n";
1424 |     response += "- `health` - Check system health status\n";
1425 |     response += "- `diagnostics` - Run comprehensive system diagnostics\n";
1426 |     response +=
1427 |       "- `config` - Manage system configuration (get, set, list, validate)\n";
1428 |     response += "- `config_restore` - Restore configuration from backup\n";
1429 |     response += "- `reset_metrics` - Reset framework switching counters\n";
1430 |     response += "- `switch_history` - View framework change history\n";
1431 |     response += "- `restart` - Full server restart (requires confirmation)\n";
1432 | 
1433 |     return this.responseFormatter.formatSystemControlResponse(
1434 |       response,
1435 |       "status",
1436 |       {
1437 |         frameworkEnabled: currentState.frameworkSystemEnabled,
1438 |         activeFramework: activeFramework.name,
1439 |         availableFrameworks:
1440 |           this.frameworkManager?.listFrameworks().map((f: any) => f.name) || [],
1441 |         uptime: (Date.now() - this.startTime) / 1000,
1442 |         memoryUsage: process.memoryUsage ? process.memoryUsage() : undefined,
1443 |         serverHealth: systemHealth.status as
1444 |           | "healthy"
1445 |           | "warning"
1446 |           | "error"
1447 |           | "critical",
1448 |         lastFrameworkSwitch: currentState.switchedAt.toISOString(),
1449 |       },
1450 |       undefined,
1451 |       {
1452 |         includeStructuredData: true,
1453 |       }
1454 |     );
1455 |   }
1456 | 
1457 |   /**
1458 |    * Switch framework
1459 |    */
1460 |   public async switchFramework(args: {
1461 |     framework?: "CAGEERF" | "ReACT" | "5W1H" | "SCAMPER";
1462 |     reason?: string;
1463 |   }): Promise<ToolResponse> {
1464 |     if (!this.systemControl.frameworkStateManager) {
1465 |       throw new Error("Framework state manager not initialized");
1466 |     }
1467 | 
1468 |     if (!args.framework) {
1469 |       throw new Error("Framework parameter is required for switch operation");
1470 |     }
1471 | 
1472 |     const { framework, reason = `User requested switch to ${args.framework}` } =
1473 |       args;
1474 | 
1475 |     const currentState =
1476 |       this.systemControl.frameworkStateManager.getCurrentState();
1477 | 
1478 |     // Check if already active
1479 |     if (currentState.activeFramework === framework) {
1480 |       return this.createMinimalSystemResponse(
1481 |         `ℹ️ Framework '${framework}' is already active. No change needed.`,
1482 |         "switch_framework"
1483 |       );
1484 |     }
1485 | 
1486 |     const request: FrameworkSwitchRequest = {
1487 |       targetFramework: framework,
1488 |       reason: reason,
1489 |     };
1490 | 
1491 |     const success =
1492 |       await this.systemControl.frameworkStateManager.switchFramework(request);
1493 | 
1494 |     if (success) {
1495 |       const newState =
1496 |         this.systemControl.frameworkStateManager.getCurrentState();
1497 |       const activeFramework =
1498 |         this.systemControl.frameworkStateManager.getActiveFramework();
1499 | 
1500 |       let response = `🔄 **Framework Switch Successful**\n\n`;
1501 |       response += `**Previous**: ${currentState.activeFramework}\n`;
1502 |       response += `**Current**: ${newState.activeFramework}\n`;
1503 |       response += `**Switched At**: ${newState.switchedAt.toISOString()}\n`;
1504 |       response += `**Reason**: ${reason}\n\n`;
1505 |       response += `**New Framework Details**:\n`;
1506 |       response += `- **Name**: ${activeFramework.name}\n`;
1507 |       response += `- **Description**: ${activeFramework.description}\n`;
1508 |       response += `- **Methodology**: ${activeFramework.methodology}\n\n`;
1509 |       response += `**Guidelines**: ${activeFramework.executionGuidelines.join(
1510 |         " • "
1511 |       )}\n\n`;
1512 |       response += `✅ All future prompt executions will now use the ${framework} methodology.`;
1513 | 
1514 |       // Trigger dynamic tool description updates
1515 |       if (this.mcpToolsManager?.reregisterToolsWithUpdatedDescriptions) {
1516 |         try {
1517 |           await this.mcpToolsManager.reregisterToolsWithUpdatedDescriptions();
1518 |           response += `\n\n🔄 **Tool descriptions updated** - MCP clients will receive updated tool descriptions with ${framework} methodology guidance.`;
1519 |         } catch (error) {
1520 |           this.logger.error(
1521 |             `Failed to update tool descriptions after framework switch: ${
1522 |               error instanceof Error ? error.message : String(error)
1523 |             }`
1524 |           );
1525 |           response += `\n\n⚠️ **Note**: Tool descriptions may need manual refresh for some clients.`;
1526 |         }
1527 |       }
1528 | 
1529 |       return this.createMinimalSystemResponse(response, "switch_framework");
1530 |     } else {
1531 |       return this.createMinimalSystemResponse(
1532 |         `❌ Failed to switch to framework '${framework}'. Check system logs for details.`,
1533 |         "switch_framework"
1534 |       );
1535 |     }
1536 |   }
1537 | 
1538 |   /**
1539 |    * List available frameworks
1540 |    */
1541 |   public async listFrameworks(args: {
1542 |     show_details?: boolean;
1543 |   }): Promise<ToolResponse> {
1544 |     if (!this.systemControl.frameworkStateManager) {
1545 |       throw new Error("Framework state manager not initialized");
1546 |     }
1547 | 
1548 |     const { show_details = true } = args;
1549 | 
1550 |     const currentState =
1551 |       this.systemControl.frameworkStateManager.getCurrentState();
1552 |     const availableFrameworks =
1553 |       this.systemControl.frameworkStateManager.getAvailableFrameworks();
1554 | 
1555 |     let response = "# 📋 Available Framework Methodologies\n\n";
1556 |     response += `**Currently Active**: ${currentState.activeFramework}\n\n`;
1557 | 
1558 |     availableFrameworks.forEach((framework) => {
1559 |       const isActive = framework.id === currentState.activeFramework;
1560 |       const icon = isActive ? "🟢" : "⚪";
1561 |       const status = isActive ? " (ACTIVE)" : "";
1562 | 
1563 |       response += `## ${icon} ${framework.name}${status}\n\n`;
1564 |       response += `**ID**: ${framework.id}\n`;
1565 |       response += `**Methodology**: ${framework.methodology}\n`;
1566 |       response += `**Description**: ${framework.description}\n`;
1567 |       response += `**Priority**: ${framework.priority}\n`;
1568 |       response += `**Enabled**: ${framework.enabled ? "✅ Yes" : "❌ No"}\n`;
1569 |       response += `**Applicable Types**: ${
1570 |         framework.applicableTypes.join(", ") || "All"
1571 |       }\n`;
1572 | 
1573 |       if (show_details && framework.executionGuidelines) {
1574 |         response += `\n**Execution Guidelines**:\n`;
1575 |         framework.executionGuidelines.forEach((guideline, index) => {
1576 |           response += `${index + 1}. ${guideline}\n`;
1577 |         });
1578 |       }
1579 | 
1580 |       response += "\n";
1581 |     });
1582 | 
1583 |     response += "---\n\n";
1584 |     response +=
1585 |       "**Usage**: Use `switch_framework` action to change the active framework methodology.\n";
1586 |     response +=
1587 |       "**Note**: The framework methodology determines how prompts are processed systematically.";
1588 | 
1589 |     return this.createMinimalSystemResponse(response, "list_frameworks");
1590 |   }
1591 | 
1592 |   /**
1593 |    * Get execution analytics
1594 |    */
1595 |   public async getAnalytics(args: {
1596 |     include_history?: boolean;
1597 |     reset_analytics?: boolean;
1598 |   }): Promise<ToolResponse> {
1599 |     const { include_history = false, reset_analytics = false } = args;
1600 | 
1601 |     if (reset_analytics) {
1602 |       this.resetAnalyticsData();
1603 |       return this.createMinimalSystemResponse(
1604 |         "📊 Analytics have been reset to zero.",
1605 |         "analytics"
1606 |       );
1607 |     }
1608 | 
1609 |     const successRate = this.getSuccessRate();
1610 |     const avgTime = this.formatExecutionTime(
1611 |       this.systemControl.systemAnalytics.averageExecutionTime
1612 |     );
1613 | 
1614 |     let response = "# 📊 System Analytics Report\n\n";
1615 | 
1616 |     // Overall Performance
1617 |     response += "## 📈 Overall Performance\n\n";
1618 |     response += `**Total Executions**: ${this.systemControl.systemAnalytics.totalExecutions}\n`;
1619 |     response += `**Success Rate**: ${successRate}%\n`;
1620 |     response += `**Failed Executions**: ${this.systemControl.systemAnalytics.failedExecutions}\n`;
1621 |     response += `**Average Execution Time**: ${avgTime}\n`;
1622 |     response += `**System Uptime**: ${this.formatUptime(
1623 |       this.systemControl.systemAnalytics.uptime
1624 |     )}\n\n`;
1625 | 
1626 |     // Execution Modes
1627 |     response += "## 🎯 Execution Mode Distribution\n\n";
1628 |     const executionsByMode = this.getExecutionsByMode();
1629 |     const totalModeExecutions = Object.values(executionsByMode).reduce(
1630 |       (a, b) => a + b,
1631 |       0
1632 |     );
1633 |     Object.entries(executionsByMode).forEach(([mode, count]) => {
1634 |       const percentage =
1635 |         totalModeExecutions > 0
1636 |           ? Math.round((count / totalModeExecutions) * 100)
1637 |           : 0;
1638 |       response += `- **${
1639 |         mode.charAt(0).toUpperCase() + mode.slice(1)
1640 |       } Mode**: ${count} executions (${percentage}%)\n`;
1641 |     });
1642 |     response += "\n";
1643 | 
1644 |     // Quality Gates (Phase 4: Enhanced with advanced analytics)
1645 |     response += "## 🛡️ Quality Gate Analytics\n\n";
1646 |     response += `**Gate Validations**: ${this.systemControl.systemAnalytics.gateValidationCount}\n`;
1647 |     response += `**Gate Adoption Rate**: ${
1648 |       this.systemControl.systemAnalytics.totalExecutions > 0
1649 |         ? Math.round(
1650 |             (this.systemControl.systemAnalytics.gateValidationCount /
1651 |               this.systemControl.systemAnalytics.totalExecutions) *
1652 |               100
1653 |           )
1654 |         : 0
1655 |     }%\n`;
1656 | 
1657 |     // Phase 4: Clean architecture gate performance analytics
1658 |     if (this.systemControl.gatePerformanceAnalyzer) {
1659 |       try {
1660 |         const gateAnalytics =
1661 |           this.systemControl.gatePerformanceAnalyzer.getPerformanceAnalytics();
1662 |         response += `**Advanced Gate System**: Enabled\n`;
1663 |         response += `**Total Gates Tracked**: ${gateAnalytics.totalGates}\n`;
1664 |         response += `**Average Gate Execution Time**: ${Math.round(
1665 |           gateAnalytics.avgExecutionTime
1666 |         )}ms\n`;
1667 |         response += `**Overall Gate Success Rate**: ${Math.round(
1668 |           gateAnalytics.overallSuccessRate * 100
1669 |         )}%\n`;
1670 | 
1671 |         if (gateAnalytics.topPerformingGates.length > 0) {
1672 |           response += `**Top Performing Gates**: ${gateAnalytics.topPerformingGates.join(
1673 |             ", "
1674 |           )}\n`;
1675 |         }
1676 | 
1677 |         if (gateAnalytics.underperformingGates.length > 0) {
1678 |           response += `**Needs Optimization**: ${gateAnalytics.underperformingGates.join(
1679 |             ", "
1680 |           )}\n`;
1681 |         }
1682 | 
1683 |         if (gateAnalytics.recommendations.length > 0) {
1684 |           response += `\n**Optimization Recommendations**:\n`;
1685 |           gateAnalytics.recommendations.forEach(
1686 |             (rec: string, index: number) => {
1687 |               response += `${index + 1}. ${rec}\n`;
1688 |             }
1689 |           );
1690 |         }
1691 |       } catch (error) {
1692 |         response += `**Advanced Gate System**: Error retrieving analytics\n`;
1693 |       }
1694 |     } else {
1695 |       response += `**Advanced Gate System**: Not available\n`;
1696 |     }
1697 | 
1698 |     response += "\n";
1699 | 
1700 |     // System Resources
1701 |     if (this.systemControl.systemAnalytics.memoryUsage) {
1702 |       response += "## 💾 System Resources\n\n";
1703 |       const mem = this.systemControl.systemAnalytics.memoryUsage;
1704 |       response += `**Heap Used**: ${this.formatBytes(mem.heapUsed)}\n`;
1705 |       response += `**Heap Total**: ${this.formatBytes(mem.heapTotal)}\n`;
1706 |       response += `**RSS**: ${this.formatBytes(mem.rss)}\n`;
1707 |       response += `**External**: ${this.formatBytes(mem.external)}\n\n`;
1708 |     }
1709 | 
1710 |     // Performance Trends
1711 |     if (
1712 |       include_history &&
1713 |       this.systemControl.systemAnalytics.performanceTrends.length > 0
1714 |     ) {
1715 |       response += "## 📈 Performance Trends\n\n";
1716 | 
1717 |       // Group trends by metric type for better organization
1718 |       const trendsByMetric =
1719 |         this.systemControl.systemAnalytics.performanceTrends.reduce(
1720 |           (acc, trend) => {
1721 |             if (!acc[trend.metric]) acc[trend.metric] = [];
1722 |             acc[trend.metric].push(trend);
1723 |             return acc;
1724 |           },
1725 |           {} as Record<string, any[]>
1726 |         );
1727 | 
1728 |       Object.entries(trendsByMetric).forEach(([metric, trends]) => {
1729 |         const recentTrends = trends.slice(-10);
1730 |         response += `### ${
1731 |           metric.charAt(0).toUpperCase() + metric.slice(1)
1732 |         } Trends\n`;
1733 |         recentTrends.forEach((trend, index) => {
1734 |           const time = new Date(trend.timestamp)
1735 |             .toISOString()
1736 |             .split("T")[1]
1737 |             .split(".")[0];
1738 |           const contextInfo = this.formatTrendContext(trend);
1739 |           response += `${index + 1}. ${time}: ${this.formatTrendValue(
1740 |             trend.metric,
1741 |             trend.value
1742 |           )}${contextInfo}\n`;
1743 |         });
1744 |         response += "\n";
1745 |       });
1746 |     }
1747 | 
1748 |     response += `\n---\n*Generated at: ${new Date().toISOString()}*`;
1749 | 
1750 |     return this.createMinimalSystemResponse(response, "analytics");
1751 |   }
1752 | 
1753 |   /**
1754 |    * Get system health
1755 |    */
1756 |   public async getSystemHealth(args: any): Promise<ToolResponse> {
1757 |     if (!this.systemControl.frameworkStateManager) {
1758 |       throw new Error("Framework state manager not initialized");
1759 |     }
1760 | 
1761 |     const health = this.systemControl.frameworkStateManager.getSystemHealth();
1762 |     const statusIcon = this.getHealthIcon(health.status);
1763 | 
1764 |     let response = `# 🏥 System Health Report\n\n`;
1765 |     response += `**Overall Status**: ${statusIcon} ${health.status.toUpperCase()}\n`;
1766 |     response += `**Active Framework**: ${health.activeFramework}\n`;
1767 |     response += `**Available Frameworks**: ${health.availableFrameworks.length}\n`;
1768 |     response += `**System Uptime**: ${this.formatUptime(
1769 |       this.systemControl.systemAnalytics.uptime
1770 |     )}\n\n`;
1771 | 
1772 |     // Performance Health
1773 |     response += "## 📊 Performance Health\n\n";
1774 |     response += `**Framework Switches**: ${health.switchingMetrics.totalSwitches}\n`;
1775 |     response += `**Framework Switch Success Rate**: ${
1776 |       health.switchingMetrics.totalSwitches > 0
1777 |         ? Math.round(
1778 |             (health.switchingMetrics.successfulSwitches /
1779 |               health.switchingMetrics.totalSwitches) *
1780 |               100
1781 |           )
1782 |         : 100
1783 |     }%\n`;
1784 |     response += `**Framework Switch Time**: ${Math.round(
1785 |       health.switchingMetrics.averageResponseTime
1786 |     )}ms\n`;
1787 |     response += `**Execution Success Rate**: ${this.getSuccessRate()}%\n\n`;
1788 | 
1789 |     // Issues
1790 |     if (health.issues.length > 0) {
1791 |       response += "## ⚠️ Detected Issues\n\n";
1792 |       health.issues.forEach((issue, index) => {
1793 |         response += `${index + 1}. ⚠️ ${issue}\n`;
1794 |       });
1795 |       response += "\n";
1796 |     } else {
1797 |       response +=
1798 |         "## ✅ System Status\n\nNo issues detected. System is operating normally.\n\n";
1799 |     }
1800 | 
1801 |     // Health Recommendations
1802 |     response += "## 💡 Health Recommendations\n\n";
1803 | 
1804 |     if (health.status === "healthy") {
1805 |       response += "✅ System is healthy. No action required.\n";
1806 |       response += "- Continue monitoring performance metrics\n";
1807 |       response += "- Regular analytics reviews recommended\n";
1808 |     } else if (health.status === "degraded") {
1809 |       response += "⚠️ System performance is degraded. Monitor closely.\n";
1810 |       response += "- Review recent framework switches for patterns\n";
1811 |       response += "- Consider resetting metrics if issues are resolved\n";
1812 |       response += "- Check execution failure rates\n";
1813 |     } else {
1814 |       response += "❌ System requires immediate attention.\n";
1815 |       response += "- Check framework configuration\n";
1816 |       response += "- Review system logs for error patterns\n";
1817 |       response += "- Consider system restart if issues persist\n";
1818 |     }
1819 | 
1820 |     return this.createMinimalSystemResponse(response, "health");
1821 |   }
1822 | 
1823 |   /**
1824 |    * Run comprehensive diagnostics
1825 |    */
1826 |   public async runDiagnostics(args: any): Promise<ToolResponse> {
1827 |     let response = "# 🔧 System Diagnostics Report\n\n";
1828 | 
1829 |     // Framework System Check
1830 |     response += "## 🔄 Framework System\n\n";
1831 |     if (this.systemControl.frameworkStateManager) {
1832 |       const state = this.systemControl.frameworkStateManager.getCurrentState();
1833 |       const health = this.systemControl.frameworkStateManager.getSystemHealth();
1834 |       const frameworks =
1835 |         this.systemControl.frameworkStateManager.getAvailableFrameworks();
1836 | 
1837 |       response += `✅ **Framework Manager**: Operational\n`;
1838 |       response += `✅ **Active Framework**: ${state.activeFramework}\n`;
1839 |       response += `✅ **Available Frameworks**: ${frameworks.length} configured\n`;
1840 |       response += `${this.getHealthIcon(health.status)} **System Health**: ${
1841 |         health.status
1842 |       }\n\n`;
1843 | 
1844 |       // Check each framework
1845 |       frameworks.forEach((fw) => {
1846 |         const icon = fw.enabled ? "✅" : "⚠️";
1847 |         response += `${icon} **${fw.name}**: ${
1848 |           fw.enabled ? "Enabled" : "Disabled"
1849 |         }\n`;
1850 |       });
1851 |       response += "\n";
1852 |     } else {
1853 |       response += `❌ **Framework Manager**: Not initialized\n\n`;
1854 |     }
1855 | 
1856 |     // Performance Diagnostics
1857 |     response += "## 📊 Performance Diagnostics\n\n";
1858 |     response += `**Total Executions**: ${this.systemControl.systemAnalytics.totalExecutions}\n`;
1859 |     response += `**Success Rate**: ${this.getSuccessRate()}%\n`;
1860 |     response += `**Average Execution Time**: ${this.formatExecutionTime(
1861 |       this.systemControl.systemAnalytics.averageExecutionTime
1862 |     )}\n`;
1863 | 
1864 |     // Performance Assessment
1865 |     const successRate = this.getSuccessRate();
1866 |     if (successRate >= 95) {
1867 |       response += `✅ **Performance Assessment**: Excellent (${successRate}%)\n`;
1868 |     } else if (successRate >= 85) {
1869 |       response += `⚠️ **Performance Assessment**: Good (${successRate}%)\n`;
1870 |     } else {
1871 |       response += `❌ **Performance Assessment**: Needs attention (${successRate}%)\n`;
1872 |     }
1873 |     response += "\n";
1874 | 
1875 |     // System Resources
1876 |     response += "## 💾 System Resources\n\n";
1877 |     if (this.systemControl.systemAnalytics.memoryUsage) {
1878 |       const mem = this.systemControl.systemAnalytics.memoryUsage;
1879 |       const heapUsagePercent = Math.round((mem.heapUsed / mem.heapTotal) * 100);
1880 | 
1881 |       response += `**Memory Usage**: ${this.formatBytes(
1882 |         mem.heapUsed
1883 |       )}/${this.formatBytes(mem.heapTotal)} (${heapUsagePercent}%)\n`;
1884 | 
1885 |       if (heapUsagePercent < 70) {
1886 |         response += `✅ **Memory Status**: Healthy\n`;
1887 |       } else if (heapUsagePercent < 90) {
1888 |         response += `⚠️ **Memory Status**: Monitor usage\n`;
1889 |       } else {
1890 |         response += `❌ **Memory Status**: High usage - consider optimization\n`;
1891 |       }
1892 |     }
1893 | 
1894 |     response += `**System Uptime**: ${this.formatUptime(
1895 |       this.systemControl.systemAnalytics.uptime
1896 |     )}\n\n`;
1897 | 
1898 |     // Recommendations
1899 |     response += "## 💡 Diagnostic Recommendations\n\n";
1900 | 
1901 |     const recommendations: string[] = [];
1902 | 
1903 |     if (this.getSuccessRate() < 90) {
1904 |       recommendations.push(
1905 |         "Investigate execution failure patterns to improve success rate"
1906 |       );
1907 |     }
1908 | 
1909 |     if (this.systemControl.systemAnalytics.averageExecutionTime > 5000) {
1910 |       recommendations.push(
1911 |         "Consider optimizing execution performance - average time is high"
1912 |       );
1913 |     }
1914 | 
1915 |     if (
1916 |       this.systemControl.systemAnalytics.memoryUsage &&
1917 |       this.systemControl.systemAnalytics.memoryUsage.heapUsed /
1918 |         this.systemControl.systemAnalytics.memoryUsage.heapTotal >
1919 |         0.8
1920 |     ) {
1921 |       recommendations.push("Monitor memory usage - heap utilization is high");
1922 |     }
1923 | 
1924 |     if (recommendations.length > 0) {
1925 |       recommendations.forEach((rec, index) => {
1926 |         response += `${index + 1}. ${rec}\n`;
1927 |       });
1928 |     } else {
1929 |       response += "✅ No issues detected. System is operating optimally.\n";
1930 |     }
1931 | 
1932 |     response += `\n---\n*Diagnostics completed at: ${new Date().toISOString()}*`;
1933 | 
1934 |     return this.createMinimalSystemResponse(response, "diagnostics");
1935 |   }
1936 | 
1937 |   /**
1938 |    * Reset framework switching metrics
1939 |    */
1940 |   public async resetMetrics(args: {
1941 |     confirm?: boolean;
1942 |   }): Promise<ToolResponse> {
1943 |     if (!args.confirm) {
1944 |       return this.createMinimalSystemResponse(
1945 |         "❌ Metrics reset cancelled. Set 'confirm: true' to reset all switching performance metrics.",
1946 |         "reset_metrics"
1947 |       );
1948 |     }
1949 | 
1950 |     const beforeMetrics = { ...this.systemControl.systemAnalytics };
1951 | 
1952 |     this.resetAnalyticsData();
1953 | 
1954 |     if (this.systemControl.frameworkStateManager) {
1955 |       this.systemControl.frameworkStateManager.resetMetrics();
1956 |     }
1957 | 
1958 |     let response = `# 🔄 Metrics Reset Completed\n\n`;
1959 |     response += `**Reset Timestamp**: ${new Date().toISOString()}\n\n`;
1960 | 
1961 |     response += "## Metrics Before Reset\n\n";
1962 |     response += `**Total Executions**: ${beforeMetrics.totalExecutions}\n`;
1963 |     response += `**Successful**: ${beforeMetrics.successfulExecutions}\n`;
1964 |     response += `**Failed**: ${beforeMetrics.failedExecutions}\n`;
1965 |     response += `**Average Time**: ${this.formatExecutionTime(
1966 |       beforeMetrics.averageExecutionTime
1967 |     )}\n\n`;
1968 | 
1969 |     response += "## Metrics After Reset\n\n";
1970 |     response += `**Total Executions**: ${this.systemControl.systemAnalytics.totalExecutions}\n`;
1971 |     response += `**Successful**: ${this.systemControl.systemAnalytics.successfulExecutions}\n`;
1972 |     response += `**Failed**: ${this.systemControl.systemAnalytics.failedExecutions}\n`;
1973 |     response += `**Average Time**: ${this.formatExecutionTime(
1974 |       this.systemControl.systemAnalytics.averageExecutionTime
1975 |     )}\n\n`;
1976 | 
1977 |     response +=
1978 |       "✅ All switching performance metrics have been reset. Framework switching monitoring will start fresh.";
1979 | 
1980 |     return this.createMinimalSystemResponse(response, "reset_metrics");
1981 |   }
1982 | 
1983 |   /**
1984 |    * Get framework switch history
1985 |    */
1986 |   public async getSwitchHistory(args: {
1987 |     limit?: number;
1988 |   }): Promise<ToolResponse> {
1989 |     if (!this.systemControl.frameworkStateManager) {
1990 |       throw new Error("Framework state manager not initialized");
1991 |     }
1992 | 
1993 |     const { limit = 20 } = args;
1994 | 
1995 |     const history =
1996 |       this.systemControl.frameworkStateManager.getSwitchHistory(limit);
1997 |     const currentState =
1998 |       this.systemControl.frameworkStateManager.getCurrentState();
1999 | 
2000 |     let response = `# 📈 Framework Switch History\n\n`;
2001 |     response += `**Current Framework**: ${currentState.activeFramework}\n`;
2002 |     response += `**History Entries**: ${history.length}\n\n`;
2003 | 
2004 |     if (history.length === 0) {
2005 |       response += "No framework switches recorded yet.\n\n";
2006 |     } else {
2007 |       response += "## Recent Switches\n\n";
2008 | 
2009 |       history.forEach((entry, index) => {
2010 |         response += `### ${index + 1}. ${entry.from} → ${entry.to}\n\n`;
2011 |         response += `**Timestamp**: ${entry.timestamp.toISOString()}\n`;
2012 |         response += `**Reason**: ${entry.reason}\n\n`;
2013 |       });
2014 |     }
2015 | 
2016 |     response += "---\n\n";
2017 |     response +=
2018 |       "**Note**: This history helps track framework usage patterns and audit changes.";
2019 | 
2020 |     return this.createMinimalSystemResponse(response, "switch_history");
2021 |   }
2022 | 
2023 |   /**
2024 |    * Manage system configuration
2025 |    */
2026 |   public async manageConfig(args: {
2027 |     config?: {
2028 |       key: string;
2029 |       value?: string;
2030 |       operation: "get" | "set" | "list" | "validate";
2031 |     };
2032 |   }): Promise<ToolResponse> {
2033 |     const configRequest = args.config;
2034 | 
2035 |     // Check if ConfigManager is available
2036 |     if (!this.configManager) {
2037 |       return createStructuredResponse(
2038 |         "❌ **Configuration Manager Unavailable**\n\n" +
2039 |           "ConfigManager is not initialized. This indicates a system initialization issue.\n" +
2040 |           "Configuration management requires proper system startup.",
2041 |         { operation: "config", error: "config_manager_unavailable" },
2042 |         true
2043 |       );
2044 |     }
2045 | 
2046 |     try {
2047 |       // Handle different config operations
2048 |       if (!configRequest) {
2049 |         return await this.handleConfigList();
2050 |       }
2051 | 
2052 |       switch (configRequest.operation) {
2053 |         case "list":
2054 |           return await this.handleConfigList();
2055 |         case "get":
2056 |           return await this.handleConfigGet(configRequest.key);
2057 |         case "set":
2058 |           return await this.handleConfigSet(
2059 |             configRequest.key,
2060 |             configRequest.value || ""
2061 |           );
2062 |         case "validate":
2063 |           return await this.handleConfigValidate(
2064 |             configRequest.key,
2065 |             configRequest.value || ""
2066 |           );
2067 |         default:
2068 |           throw new Error(
2069 |             `Unknown config operation: ${configRequest.operation}`
2070 |           );
2071 |       }
2072 |     } catch (error) {
2073 |       return this.handleError(error, "config_management");
2074 |     }
2075 |   }
2076 | 
2077 |   /**
2078 |    * Handle config list operation
2079 |    */
2080 |   private async handleConfigList(): Promise<ToolResponse> {
2081 |     const config = this.configManager!.getConfig();
2082 | 
2083 |     let response = "# ⚙️ System Configuration Overview\n\n";
2084 | 
2085 |     // Server Configuration
2086 |     response += "## 🖥️ Server Configuration\n\n";
2087 |     response += `**Name**: ${config.server.name}\n`;
2088 |     response += `**Version**: ${config.server.version}\n`;
2089 |     response += `**Port**: ${config.server.port}\n\n`;
2090 | 
2091 |     // Transport Configuration
2092 |     response += "## 🚀 Transport Configuration\n\n";
2093 |     response += `**Default Transport**: ${config.transports.default}\n`;
2094 |     response += `**STDIO Enabled**: ${
2095 |       config.transports.stdio.enabled ? "✅" : "❌"
2096 |     }\n`;
2097 |     response += `**SSE Enabled**: ${
2098 |       config.transports.sse.enabled ? "✅" : "❌"
2099 |     }\n\n`;
2100 | 
2101 |     // Analysis Configuration
2102 |     if (config.analysis) {
2103 |       response += "## 🔍 Analysis Configuration\n\n";
2104 |       response += `**LLM Integration**: ${
2105 |         config.analysis.semanticAnalysis.llmIntegration.enabled ? "✅" : "❌"
2106 |       }\n`;
2107 |       if (config.analysis.semanticAnalysis.llmIntegration.enabled) {
2108 |         response += `**Model**: ${config.analysis.semanticAnalysis.llmIntegration.model}\n`;
2109 |         response += `**Max Tokens**: ${config.analysis.semanticAnalysis.llmIntegration.maxTokens}\n`;
2110 |         response += `**Temperature**: ${config.analysis.semanticAnalysis.llmIntegration.temperature}\n`;
2111 |       }
2112 |       response += "\n";
2113 |     }
2114 | 
2115 |     // Logging Configuration
2116 |     if (config.logging) {
2117 |       response += "## 📝 Logging Configuration\n\n";
2118 |       response += `**Directory**: ${config.logging.directory}\n`;
2119 |       response += `**Level**: ${config.logging.level}\n\n`;
2120 |     }
2121 | 
2122 |     // Runtime Status
2123 |     response += "## 📊 Runtime Status\n\n";
2124 |     response += `**Framework System**: ${
2125 |       this.systemControl.frameworkStateManager ? "✅ Enabled" : "❌ Disabled"
2126 |     }\n`;
2127 |     response += `**Analytics Collection**: ✅ Enabled\n`;
2128 |     response += `**Performance Monitoring**: ✅ Enabled\n`;
2129 |     response += `**System Uptime**: ${this.formatUptime(
2130 |       this.systemControl.systemAnalytics.uptime
2131 |     )}\n`;
2132 |     response += `**Start Time**: ${new Date(this.startTime).toISOString()}\n\n`;
2133 | 
2134 |     // Available Operations
2135 |     response += "## 🔧 Available Configuration Keys\n\n";
2136 |     response += "**Server Configuration:**\n";
2137 |     response += "- `server.name` (string) - Server display name\n";
2138 |     response += "- `server.version` (string) - Server version\n";
2139 |     response +=
2140 |       "- `server.port` (number) - HTTP server port ⚠️ *restart required*\n\n";
2141 |     response += "**Transport Configuration:**\n";
2142 |     response +=
2143 |       "- `transports.default` (string) - Default transport ⚠️ *restart required*\n";
2144 |     response +=
2145 |       "- `transports.stdio.enabled` (boolean) - STDIO transport ⚠️ *restart required*\n";
2146 |     response +=
2147 |       "- `transports.sse.enabled` (boolean) - SSE transport ⚠️ *restart required*\n\n";
2148 |     response += "**Logging Configuration:**\n";
2149 |     response +=
2150 |       "- `logging.level` (string) - Log level: debug, info, warn, error\n";
2151 |     response += "- `logging.directory` (string) - Log file directory\n\n";
2152 |     response += "**Usage Examples:**\n";
2153 |     response +=
2154 |       '- Get value: `{ "config": { "key": "server.port", "operation": "get" } }`\n';
2155 |     response +=
2156 |       '- Set value: `{ "config": { "key": "logging.level", "value": "debug", "operation": "set" } }`\n';
2157 |     response +=
2158 |       '- Validate: `{ "config": { "key": "server.port", "value": "3000", "operation": "validate" } }`';
2159 | 
2160 |     return this.createMinimalSystemResponse(response, "config");
2161 |   }
2162 | 
2163 |   /**
2164 |    * Handle config get operation
2165 |    */
2166 |   private async handleConfigGet(key: string): Promise<ToolResponse> {
2167 |     if (!key) {
2168 |       throw new Error("Configuration key is required for get operation");
2169 |     }
2170 | 
2171 |     const value = this.getConfigValue(key);
2172 |     if (value === undefined) {
2173 |       return createStructuredResponse(
2174 |         `❌ **Configuration Key Not Found**\n\n` +
2175 |           `The key \`${key}\` does not exist in the configuration.\n\n` +
2176 |           `Use the \`list\` operation to see available configuration keys.`,
2177 |         { operation: "config_get", key, error: "key_not_found" },
2178 |         true
2179 |       );
2180 |     }
2181 | 
2182 |     let response = `# 🔍 Configuration Value\n\n`;
2183 |     response += `**Key**: \`${key}\`\n`;
2184 |     response += `**Current Value**: \`${JSON.stringify(value)}\`\n`;
2185 |     response += `**Type**: ${typeof value}\n\n`;
2186 | 
2187 |     if (this.requiresRestart(key)) {
2188 |       response += `⚠️ **Restart Required**: Changes to this setting require a server restart to take effect.\n\n`;
2189 |     } else {
2190 |       response += `✅ **Runtime Changeable**: This setting can be changed without restart.\n\n`;
2191 |     }
2192 | 
2193 |     response += `**Usage**: To modify this value, use:\n`;
2194 |     response += `\`{ "config": { "key": "${key}", "value": "new_value", "operation": "set" } }\``;
2195 | 
2196 |     return this.createMinimalSystemResponse(response, "config");
2197 |   }
2198 | 
2199 |   /**
2200 |    * Handle config set operation
2201 |    */
2202 |   private async handleConfigSet(
2203 |     key: string,
2204 |     value: string
2205 |   ): Promise<ToolResponse> {
2206 |     if (!key || value === undefined) {
2207 |       throw new Error("Both key and value are required for set operation");
2208 |     }
2209 | 
2210 |     // Check if SafeConfigWriter is available
2211 |     if (!this.safeConfigWriter) {
2212 |       return createStructuredResponse(
2213 |         `⚠️ **Configuration Writing Unavailable**\n\n` +
2214 |           `Configuration writing is not available (SafeConfigWriter not initialized).\n` +
2215 |           `This may indicate a file system permission issue or invalid configuration path.\n\n` +
2216 |           `**Key**: \`${key}\`\n` +
2217 |           `**Value**: \`${value}\`\n\n` +
2218 |           `**Fallback**: Use the \`validate\` operation to check if your change would be valid.`,
2219 |         {
2220 |           operation: "config_set",
2221 |           key,
2222 |           value,
2223 |           error: "config_writer_unavailable",
2224 |         },
2225 |         true
2226 |       );
2227 |     }
2228 | 
2229 |     // First validate the new value
2230 |     const validation = this.validateConfigValue(key, value);
2231 |     if (!validation.valid) {
2232 |       return {
2233 |         content: [
2234 |           {
2235 |             type: "text",
2236 |             text:
2237 |               `❌ **Invalid Configuration Value**\n\n` +
2238 |               `**Key**: \`${key}\`\n` +
2239 |               `**Value**: \`${value}\`\n` +
2240 |               `**Error**: ${validation.error}\n\n` +
2241 |               `${
2242 |                 validation.suggestion
2243 |                   ? `**Suggestion**: ${validation.suggestion}`
2244 |                   : ""
2245 |               }`,
2246 |           },
2247 |         ],
2248 |         isError: true,
2249 |       };
2250 |     }
2251 | 
2252 |     try {
2253 |       // Perform the actual configuration update
2254 |       const currentValue = this.getConfigValue(key);
2255 |       const writeResult = await this.safeConfigWriter.updateConfigValue(
2256 |         key,
2257 |         value
2258 |       );
2259 | 
2260 |       if (!writeResult.success) {
2261 |         return {
2262 |           content: [
2263 |             {
2264 |               type: "text",
2265 |               text:
2266 |                 `❌ **Configuration Update Failed**\n\n` +
2267 |                 `**Key**: \`${key}\`\n` +
2268 |                 `**Value**: \`${value}\`\n` +
2269 |                 `**Error**: ${writeResult.error || writeResult.message}\n\n` +
2270 |                 `${
2271 |                   writeResult.backupPath
2272 |                     ? `**Backup**: ${writeResult.backupPath}\n`
2273 |                     : ""
2274 |                 }` +
2275 |                 `**Current Value**: \`${JSON.stringify(
2276 |                   currentValue
2277 |                 )}\` (unchanged)\n\n` +
2278 |                 `**Note**: Configuration file has been left unchanged. No restart required.`,
2279 |             },
2280 |           ],
2281 |           isError: true,
2282 |         };
2283 |       }
2284 | 
2285 |       // Success! Configuration has been updated
2286 |       let response = `✅ **Configuration Updated Successfully**\n\n`;
2287 |       response += `**Key**: \`${key}\`\n`;
2288 |       response += `**Previous Value**: \`${JSON.stringify(currentValue)}\`\n`;
2289 |       response += `**New Value**: \`${value}\`\n`;
2290 |       response += `**Backup Created**: \`${writeResult.backupPath}\`\n\n`;
2291 | 
2292 |       if (writeResult.restartRequired) {
2293 |         response += `⚠️ **Server Restart Required**\n\n`;
2294 |         response += `This configuration change requires a server restart to take effect.\n`;
2295 |         response += `Use the \`restart\` action with \`confirm: true\` to restart the server.\n\n`;
2296 |         response += `**Alternative**: The configuration file has been updated and will take effect on next startup.`;
2297 |       } else {
2298 |         response += `✅ **Change Applied Immediately**\n\n`;
2299 |         response += `This configuration change has been applied and is now active.\n`;
2300 |         response += `No server restart is required.`;
2301 |       }
2302 | 
2303 |       response += `\n\n**Recovery**: If needed, you can restore the previous configuration using:\n`;
2304 |       response += `\`{ "action": "config_restore", "backup_path": "${writeResult.backupPath}" }\``;
2305 | 
2306 |       return this.createMinimalSystemResponse(response, "config");
2307 |     } catch (error) {
2308 |       this.logger.error(
2309 |         `Unexpected error during config set for ${key}:`,
2310 |         error
2311 |       );
2312 |       return {
2313 |         content: [
2314 |           {
2315 |             type: "text",
2316 |             text:
2317 |               `❌ **Unexpected Configuration Error**\n\n` +
2318 |               `**Key**: \`${key}\`\n` +
2319 |               `**Value**: \`${value}\`\n` +
2320 |               `**Error**: ${String(error)}\n\n` +
2321 |               `**Status**: Configuration unchanged. System remains stable.\n` +
2322 |               `**Action**: Check system logs for detailed error information.`,
2323 |           },
2324 |         ],
2325 |         isError: true,
2326 |       };
2327 |     }
2328 |   }
2329 | 
2330 |   /**
2331 |    * Handle config validate operation
2332 |    */
2333 |   private async handleConfigValidate(
2334 |     key: string,
2335 |     value: string
2336 |   ): Promise<ToolResponse> {
2337 |     if (!key || value === undefined) {
2338 |       throw new Error("Both key and value are required for validate operation");
2339 |     }
2340 | 
2341 |     const validation = this.validateConfigValue(key, value);
2342 |     const currentValue = this.getConfigValue(key);
2343 | 
2344 |     let response = `# 🔍 Configuration Validation\n\n`;
2345 |     response += `**Key**: \`${key}\`\n`;
2346 |     response += `**Proposed Value**: \`${value}\`\n`;
2347 |     response += `**Current Value**: \`${JSON.stringify(currentValue)}\`\n`;
2348 |     response += `**Valid**: ${validation.valid ? "✅ Yes" : "❌ No"}\n\n`;
2349 | 
2350 |     if (!validation.valid) {
2351 |       response += `**Error**: ${validation.error}\n`;
2352 |       if (validation.suggestion) {
2353 |         response += `**Suggestion**: ${validation.suggestion}\n`;
2354 |       }
2355 |     } else {
2356 |       response += `**Type**: ${validation.type}\n`;
2357 |       response += `**Restart Required**: ${
2358 |         this.requiresRestart(key) ? "⚠️ Yes" : "✅ No"
2359 |       }\n`;
2360 |     }
2361 | 
2362 |     return this.createMinimalSystemResponse(response, "config");
2363 |   }
2364 | 
2365 |   /**
2366 |    * Get configuration value using dot notation
2367 |    */
2368 |   private getConfigValue(key: string): any {
2369 |     const config = this.configManager!.getConfig();
2370 |     const parts = key.split(".");
2371 |     let value: any = config;
2372 | 
2373 |     for (const part of parts) {
2374 |       if (value && typeof value === "object" && part in value) {
2375 |         value = value[part];
2376 |       } else {
2377 |         return undefined;
2378 |       }
2379 |     }
2380 | 
2381 |     return value;
2382 |   }
2383 | 
2384 |   /**
2385 |    * Validate configuration value
2386 |    */
2387 |   private validateConfigValue(
2388 |     key: string,
2389 |     value: string
2390 |   ): { valid: boolean; error?: string; suggestion?: string; type?: string } {
2391 |     // Basic key validation
2392 |     if (!this.isValidConfigKey(key)) {
2393 |       return {
2394 |         valid: false,
2395 |         error: `Unknown configuration key: ${key}`,
2396 |         suggestion: "Use the 'list' operation to see available keys",
2397 |       };
2398 |     }
2399 | 
2400 |     // Type-specific validation
2401 |     try {
2402 |       switch (key) {
2403 |         case "server.port":
2404 |           const port = parseInt(value, 10);
2405 |           if (isNaN(port) || port < 1024 || port > 65535) {
2406 |             return {
2407 |               valid: false,
2408 |               error: "Port must be a number between 1024-65535",
2409 |               suggestion: "Try a value like 3000 or 8080",
2410 |             };
2411 |           }
2412 |           return { valid: true, type: "number" };
2413 | 
2414 |         case "server.name":
2415 |         case "server.version":
2416 |           if (!value || value.trim().length === 0) {
2417 |             return {
2418 |               valid: false,
2419 |               error: "Value cannot be empty",
2420 |               suggestion: "Provide a non-empty string value",
2421 |             };
2422 |           }
2423 |           return { valid: true, type: "string" };
2424 | 
2425 |         case "transports.default":
2426 |           if (!["stdio", "sse"].includes(value)) {
2427 |             return {
2428 |               valid: false,
2429 |               error: "Transport must be 'stdio' or 'sse'",
2430 |               suggestion:
2431 |                 "Use 'stdio' for desktop clients or 'sse' for web clients",
2432 |             };
2433 |           }
2434 |           return { valid: true, type: "string" };
2435 | 
2436 |         case "transports.stdio.enabled":
2437 |         case "transports.sse.enabled":
2438 |           if (!["true", "false"].includes(value.toLowerCase())) {
2439 |             return {
2440 |               valid: false,
2441 |               error: "Value must be 'true' or 'false'",
2442 |               suggestion: "Use boolean values: true or false",
2443 |             };
2444 |           }
2445 |           return { valid: true, type: "boolean" };
2446 | 
2447 |         case "logging.level":
2448 |           if (!["debug", "info", "warn", "error"].includes(value)) {
2449 |             return {
2450 |               valid: false,
2451 |               error: "Log level must be: debug, info, warn, or error",
2452 |               suggestion:
2453 |                 "Use 'debug' for development or 'info' for production",
2454 |             };
2455 |           }
2456 |           return { valid: true, type: "string" };
2457 | 
2458 |         case "logging.directory":
2459 |           if (!value || value.trim().length === 0) {
2460 |             return {
2461 |               valid: false,
2462 |               error: "Directory path cannot be empty",
2463 |               suggestion: "Provide a valid directory path like './logs'",
2464 |             };
2465 |           }
2466 |           return { valid: true, type: "string" };
2467 | 
2468 |         default:
2469 |           return { valid: true, type: "unknown" };
2470 |       }
2471 |     } catch (error) {
2472 |       return {
2473 |         valid: false,
2474 |         error: `Validation error: ${error}`,
2475 |         suggestion: "Check the value format and try again",
2476 |       };
2477 |     }
2478 |   }
2479 | 
2480 |   /**
2481 |    * Check if config key is valid
2482 |    */
2483 |   private isValidConfigKey(key: string): boolean {
2484 |     const validKeys = [
2485 |       "server.name",
2486 |       "server.version",
2487 |       "server.port",
2488 |       "transports.default",
2489 |       "transports.stdio.enabled",
2490 |       "transports.sse.enabled",
2491 |       "logging.level",
2492 |       "logging.directory",
2493 |       "analysis.semanticAnalysis.llmIntegration.enabled",
2494 |       "analysis.semanticAnalysis.llmIntegration.model",
2495 |       "analysis.semanticAnalysis.llmIntegration.maxTokens",
2496 |       "analysis.semanticAnalysis.llmIntegration.temperature",
2497 |     ];
2498 |     return validKeys.includes(key);
2499 |   }
2500 | 
2501 |   /**
2502 |    * Check if config key requires restart
2503 |    */
2504 |   private requiresRestart(key: string): boolean {
2505 |     const restartRequired = [
2506 |       "server.port",
2507 |       "transports.default",
2508 |       "transports.stdio.enabled",
2509 |       "transports.sse.enabled",
2510 |       "analysis.semanticAnalysis.llmIntegration.enabled",
2511 |     ];
2512 |     return restartRequired.includes(key);
2513 |   }
2514 | 
2515 |   /**
2516 |    * Restore configuration from backup
2517 |    */
2518 |   public async restoreConfig(args: {
2519 |     backup_path?: string;
2520 |     confirm?: boolean;
2521 |   }): Promise<ToolResponse> {
2522 |     if (!args.backup_path) {
2523 |       return {
2524 |         content: [
2525 |           {
2526 |             type: "text",
2527 |             text:
2528 |               `❌ **Backup Path Required**\n\n` +
2529 |               `The \`backup_path\` parameter is required for config restore operations.\n\n` +
2530 |               `**Usage**: \`{ "action": "config_restore", "backup_path": "/path/to/backup", "confirm": true }\`\n\n` +
2531 |               `**Note**: Backup files are typically named like \`config.json.backup.1640995200000\``,
2532 |           },
2533 |         ],
2534 |         isError: true,
2535 |       };
2536 |     }
2537 | 
2538 |     if (!args.confirm) {
2539 |       return {
2540 |         content: [
2541 |           {
2542 |             type: "text",
2543 |             text:
2544 |               `⚠️ **Configuration Restore Confirmation Required**\n\n` +
2545 |               `**Backup Path**: \`${args.backup_path}\`\n` +
2546 |               `**Impact**: This will overwrite the current configuration file\n` +
2547 |               `**Data Loss Risk**: Current configuration will be lost unless backed up\n\n` +
2548 |               `**To proceed**: Set \`confirm: true\` to execute the restore.\n\n` +
2549 |               `**Alternative**: Use \`config\` operations to make individual changes instead of full restore.`,
2550 |           },
2551 |         ],
2552 |       };
2553 |     }
2554 | 
2555 |     // Check if SafeConfigWriter is available
2556 |     if (!this.safeConfigWriter) {
2557 |       return {
2558 |         content: [
2559 |           {
2560 |             type: "text",
2561 |             text:
2562 |               `❌ **Configuration Restore Unavailable**\n\n` +
2563 |               `Configuration restoration is not available (SafeConfigWriter not initialized).\n` +
2564 |               `This may indicate a file system permission issue or invalid configuration path.\n\n` +
2565 |               `**Backup Path**: \`${args.backup_path}\`\n\n` +
2566 |               `**Manual Restore**: You may need to manually copy the backup file to replace the current config.`,
2567 |           },
2568 |         ],
2569 |         isError: true,
2570 |       };
2571 |     }
2572 | 
2573 |     try {
2574 |       // Create a backup of the current config before restoring
2575 |       const fs = await import("fs");
2576 |       const currentConfigPath = this.safeConfigWriter.getConfigPath();
2577 |       const emergencyBackupPath = `${currentConfigPath}.emergency.backup.${Date.now()}`;
2578 | 
2579 |       if (fs.existsSync(currentConfigPath)) {
2580 |         await fs.promises.copyFile(currentConfigPath, emergencyBackupPath);
2581 |         this.logger.info(
2582 |           `Emergency backup created before restore: ${emergencyBackupPath}`
2583 |         );
2584 |       }
2585 | 
2586 |       // Perform the restoration
2587 |       const restoreResult = await this.safeConfigWriter.restoreFromBackup(
2588 |         args.backup_path
2589 |       );
2590 | 
2591 |       if (!restoreResult.success) {
2592 |         return {
2593 |           content: [
2594 |             {
2595 |               type: "text",
2596 |               text:
2597 |                 `❌ **Configuration Restore Failed**\n\n` +
2598 |                 `**Backup Path**: \`${args.backup_path}\`\n` +
2599 |                 `**Error**: ${
2600 |                   restoreResult.error || restoreResult.message
2601 |                 }\n\n` +
2602 |                 `**Status**: Original configuration unchanged\n` +
2603 |                 `${
2604 |                   fs.existsSync(emergencyBackupPath)
2605 |                     ? `**Emergency Backup**: ${emergencyBackupPath}\n`
2606 |                     : ""
2607 |                 }` +
2608 |                 `**Action**: Verify the backup file exists and is readable.`,
2609 |             },
2610 |           ],
2611 |           isError: true,
2612 |         };
2613 |       }
2614 | 
2615 |       // Success! Configuration has been restored
2616 |       let response = `✅ **Configuration Restored Successfully**\n\n`;
2617 |       response += `**Restored From**: \`${args.backup_path}\`\n`;
2618 |       response += `**Emergency Backup**: \`${emergencyBackupPath}\`\n`;
2619 |       response += `**Timestamp**: ${new Date().toISOString()}\n\n`;
2620 | 
2621 |       response += `⚠️ **Server Restart Recommended**\n\n`;
2622 |       response += `Configuration has been restored from backup. A server restart is recommended `;
2623 |       response += `to ensure all systems are using the restored configuration.\n\n`;
2624 | 
2625 |       response += `**To restart**: Use \`{ "action": "restart", "confirm": true }\`\n\n`;
2626 | 
2627 |       response += `**Recovery Options**:\n`;
2628 |       response += `- **Undo**: \`{ "action": "config_restore", "backup_path": "${emergencyBackupPath}", "confirm": true }\`\n`;
2629 |       response += `- **Check config**: \`{ "action": "config", "config": { "operation": "list" } }\``;
2630 | 
2631 |       return this.createMinimalSystemResponse(response, "config_restore");
2632 |     } catch (error) {
2633 |       this.logger.error(
2634 |         `Unexpected error during config restore from ${args.backup_path}:`,
2635 |         error
2636 |       );
2637 |       return {
2638 |         content: [
2639 |           {
2640 |             type: "text",
2641 |             text:
2642 |               `❌ **Unexpected Restore Error**\n\n` +
2643 |               `**Backup Path**: \`${args.backup_path}\`\n` +
2644 |               `**Error**: ${String(error)}\n\n` +
2645 |               `**Status**: Configuration unchanged. System remains stable.\n` +
2646 |               `**Action**: Check file permissions and backup file validity.`,
2647 |           },
2648 |         ],
2649 |         isError: true,
2650 |       };
2651 |     }
2652 |   }
2653 | 
2654 |   /**
2655 |    * Restart server with confirmation and reason
2656 |    */
2657 |   public async restartServer(args: {
2658 |     reason?: string;
2659 |     confirm?: boolean;
2660 |   }): Promise<ToolResponse> {
2661 |     const {
2662 |       reason = "Manual restart requested via system_control",
2663 |       confirm = false,
2664 |     } = args;
2665 | 
2666 |     if (!this.onRestart) {
2667 |       return {
2668 |         content: [
2669 |           {
2670 |             type: "text",
2671 |             text: "❌ **Restart Unavailable**: Server restart functionality not configured. This may indicate the server is running in a mode that doesn't support programmatic restart.",
2672 |           },
2673 |         ],
2674 |         isError: true,
2675 |       };
2676 |     }
2677 | 
2678 |     if (!confirm) {
2679 |       return {
2680 |         content: [
2681 |           {
2682 |             type: "text",
2683 |             text:
2684 |               `⚠️ **Server Restart Confirmation Required**\n\n` +
2685 |               `**Reason**: ${reason}\n` +
2686 |               `**Impact**: All active connections will be terminated\n` +
2687 |               `**Downtime**: Server will restart (typically 5-10 seconds)\n\n` +
2688 |               `**To proceed**: Set 'confirm: true' to execute the restart.\n\n` +
2689 |               `🔄 **Alternative**: Use hot-reload via prompt_manager 'reload' action for most changes.`,
2690 |           },
2691 |         ],
2692 |       };
2693 |     }
2694 | 
2695 |     let response = `🚨 **Server Restart Initiated**\n\n`;
2696 |     response += `**Reason**: ${reason}\n`;
2697 |     response += `**Timestamp**: ${new Date().toISOString()}\n\n`;
2698 |     response += `📊 **Pre-Restart System Status**:\n`;
2699 |     response += `- **Uptime**: ${this.formatUptime(
2700 |       this.systemControl.systemAnalytics.uptime
2701 |     )}\n`;
2702 |     response += `- **Total Executions**: ${this.systemControl.systemAnalytics.totalExecutions}\n`;
2703 |     response += `- **Success Rate**: ${this.getSuccessRate()}%\n`;
2704 | 
2705 |     if (this.systemControl.frameworkStateManager) {
2706 |       const currentState =
2707 |         this.systemControl.frameworkStateManager.getCurrentState();
2708 |       response += `- **Active Framework**: ${currentState.activeFramework}\n`;
2709 |     }
2710 | 
2711 |     response += `\n⚡ **Server will restart in 2 seconds**... Please wait for reconnection.\n\n`;
2712 |     response += `✅ All system state and configurations will be preserved.`;
2713 | 
2714 |     // Schedule restart after response is sent
2715 |     setTimeout(() => {
2716 |       this.logger.info(
2717 |         `System restart initiated via system_control. Reason: ${reason}`
2718 |       );
2719 |       this.onRestart!(reason);
2720 |     }, 2000);
2721 | 
2722 |     return this.createMinimalSystemResponse(response, "restart");
2723 |   }
2724 | 
2725 |   // Helper methods
2726 | 
2727 |   private resetAnalyticsData(): void {
2728 |     this.systemControl.systemAnalytics = {
2729 |       totalExecutions: 0,
2730 |       successfulExecutions: 0,
2731 |       failedExecutions: 0,
2732 |       averageExecutionTime: 0,
2733 |       gateValidationCount: 0,
2734 |       uptime: Date.now() - this.startTime,
2735 |       performanceTrends: [],
2736 |     };
2737 |   }
2738 | 
2739 |   /**
2740 |    * Enable framework system
2741 |    */
2742 |   public async enableFrameworkSystem(args: {
2743 |     reason?: string;
2744 |   }): Promise<ToolResponse> {
2745 |     try {
2746 |       if (!this.systemControl.frameworkStateManager) {
2747 |         return createStructuredResponse(
2748 |           "❌ Framework State Manager not available",
2749 |           {
2750 |             operation: "enable_framework",
2751 |             error: "framework_manager_unavailable",
2752 |           },
2753 |           true
2754 |         );
2755 |       }
2756 | 
2757 |       const reason = args.reason || "Manual enable via MCP tool";
2758 |       this.systemControl.frameworkStateManager.enableFrameworkSystem(reason);
2759 | 
2760 |       const status =
2761 |         this.systemControl.frameworkStateManager.isFrameworkSystemEnabled();
2762 | 
2763 |       let response = "✅ **Framework System Enabled**\n\n";
2764 |       response += `**Status**: ${status ? "Enabled" : "Disabled"}\n`;
2765 |       response += `**Reason**: ${reason}\n`;
2766 |       response += `**Active Framework**: ${
2767 |         this.systemControl.frameworkStateManager.getActiveFramework().name
2768 |       }\n`;
2769 |       response += `**Timestamp**: ${new Date().toISOString()}\n\n`;
2770 |       response +=
2771 |         "Framework injection will now be active for template and chain executions.\n\n";
2772 |       response +=
2773 |         "🔄 **Note**: Tool descriptions now reflect framework-enabled capabilities. Tool descriptions will show framework-enhanced functionality on next client connection/restart.";
2774 | 
2775 |       return this.createMinimalSystemResponse(response, "enable_framework");
2776 |     } catch (error) {
2777 |       return this.handleError(error, "enable_framework_system");
2778 |     }
2779 |   }
2780 | 
2781 |   /**
2782 |    * Disable framework system
2783 |    */
2784 |   public async disableFrameworkSystem(args: {
2785 |     reason?: string;
2786 |   }): Promise<ToolResponse> {
2787 |     try {
2788 |       if (!this.systemControl.frameworkStateManager) {
2789 |         return createStructuredResponse(
2790 |           "❌ Framework State Manager not available",
2791 |           {
2792 |             operation: "disable_framework",
2793 |             error: "framework_manager_unavailable",
2794 |           },
2795 |           true
2796 |         );
2797 |       }
2798 | 
2799 |       const reason = args.reason || "Manual disable via MCP tool";
2800 |       this.systemControl.frameworkStateManager.disableFrameworkSystem(reason);
2801 | 
2802 |       const status =
2803 |         this.systemControl.frameworkStateManager.isFrameworkSystemEnabled();
2804 | 
2805 |       let response = "🚫 **Framework System Disabled**\n\n";
2806 |       response += `**Status**: ${status ? "Enabled" : "Disabled"}\n`;
2807 |       response += `**Reason**: ${reason}\n`;
2808 |       response += `**Timestamp**: ${new Date().toISOString()}\n\n`;
2809 |       response +=
2810 |         "Framework injection is now bypassed. All executions will use standard prompts without methodology enhancements.\n\n";
2811 |       response +=
2812 |         "🔄 **Note**: Tool descriptions now reflect framework-disabled state. Tool descriptions will show basic functionality (no framework enhancement) on next client connection/restart.";
2813 | 
2814 |       return this.createMinimalSystemResponse(response, "disable_framework");
2815 |     } catch (error) {
2816 |       return this.handleError(error, "disable_framework_system");
2817 |     }
2818 |   }
2819 | 
2820 |   /**
2821 |    * Get framework system status
2822 |    */
2823 |   public async getFrameworkSystemStatus(args: any): Promise<ToolResponse> {
2824 |     try {
2825 |       if (!this.systemControl.frameworkStateManager) {
2826 |         return createStructuredResponse(
2827 |           "❌ Framework State Manager not available",
2828 |           {
2829 |             operation: "framework_status",
2830 |             error: "framework_manager_unavailable",
2831 |           },
2832 |           true
2833 |         );
2834 |       }
2835 | 
2836 |       const state = this.systemControl.frameworkStateManager.getCurrentState();
2837 |       const health = this.systemControl.frameworkStateManager.getSystemHealth();
2838 | 
2839 |       let response = "📊 **Framework System Status**\n\n";
2840 | 
2841 |       // Main status with enhanced clarity
2842 |       const isEnabled = state.frameworkSystemEnabled;
2843 |       const injectionStatus = isEnabled ? "✅ Active" : "🚫 Inactive";
2844 | 
2845 |       response += `**System Status**: ${
2846 |         state.frameworkSystemEnabled ? "✅ Enabled" : "🚫 Disabled"
2847 |       }\n`;
2848 |       response += `**Selected Framework**: ${state.activeFramework}\n`;
2849 |       response += `**Framework Injection**: ${injectionStatus}\n`;
2850 |       response += `**Health Status**: ${this.getHealthEmoji(
2851 |         health.status
2852 |       )} ${health.status.toUpperCase()}\n`;
2853 |       response += `**Last Updated**: ${state.switchedAt.toISOString()}\n`;
2854 |       response += `**Last Reason**: ${state.switchReason}\n\n`;
2855 | 
2856 |       // Available frameworks
2857 |       response += `**Available Frameworks**: ${health.availableFrameworks.join(
2858 |         ", "
2859 |       )}\n\n`;
2860 | 
2861 |       // Framework capabilities
2862 |       if (state.frameworkSystemEnabled) {
2863 |         response += "**Current Capabilities**:\n";
2864 |         response += "• Framework-aware prompt injection\n";
2865 |         response += "• Methodology-specific system prompts\n";
2866 |         response += "• Quality gate validation\n";
2867 |         response += "• Enhanced execution context\n\n";
2868 |       } else {
2869 |         response +=
2870 |           "**Current Mode**: Standard execution (no framework enhancements)\n\n";
2871 |       }
2872 | 
2873 |       // Switching metrics
2874 |       response += "**Switching Metrics**:\n";
2875 |       response += `• Total Operations: ${state.switchingMetrics.switchCount}\n`;
2876 |       response += `• Error Count: ${state.switchingMetrics.errorCount}\n`;
2877 |       response += `• Avg Response Time: ${state.switchingMetrics.averageResponseTime.toFixed(
2878 |         1
2879 |       )}ms\n`;
2880 | 
2881 |       // Health issues
2882 |       if (health.issues.length > 0) {
2883 |         response += "\n**Issues**:\n";
2884 |         health.issues.forEach((issue) => {
2885 |           response += `• ⚠️ ${issue}\n`;
2886 |         });
2887 |       }
2888 | 
2889 |       return this.createMinimalSystemResponse(response, "framework_status");
2890 |     } catch (error) {
2891 |       return this.handleError(error, "framework_system_status");
2892 |     }
2893 |   }
2894 | 
2895 |   /**
2896 |    * Get health status emoji
2897 |    */
2898 |   private getHealthEmoji(status: string): string {
2899 |     switch (status) {
2900 |       case "healthy":
2901 |         return "✅";
2902 |       case "degraded":
2903 |         return "⚠️";
2904 |       case "error":
2905 |         return "❌";
2906 |       default:
2907 |         return "❓";
2908 |     }
2909 |   }
2910 | 
2911 |   /**
2912 |    * Error handling helper
2913 |    */
2914 |   public handleError(error: unknown, context: string): ToolResponse {
2915 |     utilsHandleError(error, context, this.logger);
2916 | 
2917 |     return this.responseFormatter.formatErrorResponse(
2918 |       error instanceof Error ? error : String(error),
2919 |       {
2920 |         tool: "system_control",
2921 |         operation: context,
2922 |       },
2923 |       {
2924 |         includeStructuredData: true,
2925 |       }
2926 |     );
2927 |   }
2928 | }
2929 | 
2930 | /**
2931 |  * Create consolidated system control
2932 |  */
2933 | export function createConsolidatedSystemControl(
2934 |   logger: Logger,
2935 |   mcpServer: any,
2936 |   onRestart?: (reason: string) => Promise<void>
2937 | ): ConsolidatedSystemControl {
2938 |   return new ConsolidatedSystemControl(logger, mcpServer, onRestart);
2939 | }
2940 | 
```
Page 18/18FirstPrevNextLast