This is page 17 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/prompt-engine/core/engine.ts:
--------------------------------------------------------------------------------
```typescript
1 | /**
2 | * Consolidated Prompt Engine - Unified Execution Tool
3 | *
4 | * Consolidates all prompt execution functionality into a single systematic tool:
5 | * - execute_prompt (from index.ts)
6 | * - Chain execution with progress tracking
7 | * - Structural execution mode detection
8 | * - Gate validation and retry logic
9 | */
10 |
11 | import path from "path";
12 | import { z } from "zod";
13 | import { ConfigManager } from "../../../config/index.js";
14 | import { Logger } from "../../../logging/index.js";
15 | import { PromptManager } from "../../../prompts/index.js";
16 | import {
17 | ChainExecutionProgress,
18 | ConvertedPrompt,
19 | ExecutionState,
20 | GateDefinition,
21 | PromptData,
22 | ToolResponse,
23 | } from "../../../types/index.js";
24 | // Import enhanced gate configuration from execution types
25 | import {
26 | type EnhancedGateConfiguration,
27 | } from "../../../execution/types.js";
28 | // REMOVED: ModularChainDefinition from deleted chain-scaffolding.ts
29 | import {
30 | PromptError,
31 | ValidationError,
32 | getAvailableTools,
33 | isChainPrompt,
34 | handleError as utilsHandleError,
35 | } from "../../../utils/index.js";
36 | import { processTemplate } from "../../../utils/jsonUtils.js";
37 | // Gate evaluation removed - now using Framework methodology validation
38 | import { FrameworkManager } from "../../../frameworks/framework-manager.js";
39 | import { FrameworkExecutionContext } from "../../../frameworks/types/index.js";
40 | import { FrameworkStateManager } from "../../../frameworks/framework-state-manager.js";
41 | import { ContentAnalyzer } from "../../../semantic/configurable-semantic-analyzer.js";
42 | import { ConversationManager } from "../../../text-references/conversation.js";
43 | import { TextReferenceManager } from "../../../text-references/index.js";
44 | import { ChainSessionManager, createChainSessionManager } from "../../../chain-session/manager.js";
45 | import { createExecutionResponse } from "../../shared/structured-response-builder.js";
46 | // Legacy gate system removed - using lightweight gates only
47 | // NEW: Lightweight gate system
48 | import {
49 | LightweightGateSystem,
50 | createLightweightGateSystem,
51 | type TemporaryGateRegistryDefinition as TemporaryGateDefinition,
52 | } from "../../../gates/core/index.js";
53 | // NEW: Role-based gate components (Phase 3)
54 | import {
55 | GateGuidanceRenderer,
56 | createGateGuidanceRenderer,
57 | } from "../../../gates/guidance/GateGuidanceRenderer.js";
58 | // Gate validation integration
59 | import {
60 | EngineValidator,
61 | GateValidationResult,
62 | } from "../utils/validation.js";
63 | // Phase 4: Clean architecture gate intelligence (replaced advanced orchestrator)
64 | import {
65 | GateSelectionEngine,
66 | createGateSelectionEngine,
67 | ExtendedGateSelectionCriteria,
68 | } from "../../../gates/intelligence/GateSelectionEngine.js";
69 | import {
70 | GateSelectionResult,
71 | } from "../../../gates/core/gate-definitions.js";
72 | // Phase 1: Intelligent category detection
73 | import {
74 | CategoryExtractor,
75 | extractPromptCategory,
76 | CategoryExtractionResult
77 | } from "../utils/category-extractor.js";
78 | // Phase 3: Prompt guidance system integration
79 | import {
80 | PromptGuidanceService,
81 | createPromptGuidanceService,
82 | type ServicePromptGuidanceResult
83 | } from "../../../frameworks/prompt-guidance/index.js";
84 | // REMOVED: ChainOrchestrator and detectChainType/isModularChain - modular chain system completely removed
85 | // REMOVED: Chain URI addressing system - deprecated with markdown-embedded chains
86 | // New unified parsing system
87 | import {
88 | createParsingSystem,
89 | type ExecutionContext,
90 | type ParsingSystem,
91 | } from "../../../execution/parsers/index.js";
92 | // REMOVED: Dynamic template discovery - scaffolding system deprecated
93 | // Tool description manager
94 | import { ToolDescriptionManager } from "../../tool-description-manager.js";
95 | // Chain execution separation
96 | import { ChainExecutor } from "./executor.js";
97 | import { ChainExecutionContext, ChainExecutionOptions } from "./types.js";
98 | // Enhanced tool dependencies removed (Phase 1.3) - Core implementations
99 | // Simple core response handling without enhanced complexity
100 | interface SimpleResponseFormatter {
101 | formatResponse(content: any): any;
102 | formatPromptEngineResponse(response: any, ...args: any[]): any; // Required
103 | formatErrorResponse(error: any, ...args: any[]): any; // Required
104 | setAnalyticsService(service: any): void; // Required
105 | }
106 |
107 | function createSimpleResponseFormatter(): SimpleResponseFormatter {
108 | return {
109 | formatResponse: (content: any) => content,
110 | formatPromptEngineResponse: (response: any, ...args: any[]) => {
111 | // Create proper ToolResponse with structuredContent using shared builder
112 | const executionContext = args[0] || {};
113 | const options = args[1] || {};
114 |
115 | // For template/prompt execution, return simple text so Claude Code can see instructions
116 | // For chain execution, keep structured content for state tracking
117 | const executionType = executionContext.executionType || "prompt";
118 | const includeStructuredContent = executionType === "chain";
119 |
120 | return createExecutionResponse(
121 | String(response),
122 | "execute",
123 | {
124 | executionType,
125 | executionTime: executionContext.executionTime,
126 | frameworkUsed: executionContext.frameworkUsed,
127 | stepsExecuted: executionContext.stepsExecuted,
128 | sessionId: executionContext.sessionId,
129 | gateResults: executionContext.gateResults
130 | },
131 | includeStructuredContent
132 | );
133 | },
134 | formatErrorResponse: (error: any, ...args: any[]) => {
135 | return createExecutionResponse(
136 | String(error),
137 | "error",
138 | {
139 | executionType: "prompt",
140 | executionTime: 0,
141 | frameworkUsed: undefined,
142 | stepsExecuted: 0,
143 | sessionId: undefined
144 | }
145 | );
146 | },
147 | setAnalyticsService: (service: any) => {}, // No-op for now
148 | };
149 | }
150 |
151 | // Simple output schema (minimal for Phase 1)
152 | const promptEngineOutputSchema = {
153 | content: { type: "array" },
154 | isError: { type: "boolean", optional: true },
155 | };
156 |
157 | // Type aliases for compatibility
158 | type ResponseFormatter = SimpleResponseFormatter;
159 | const createResponseFormatter = createSimpleResponseFormatter;
160 | type FormatterExecutionContext = {
161 | [key: string]: any; // Completely flexible for Phase 1
162 | };
163 | // Analytics service
164 | import { ExecutionData, MetricsCollector } from "../../../metrics/index.js";
165 |
166 | /**
167 | * Prompt classification interface for execution strategy
168 | */
169 | export interface PromptClassification {
170 | executionType: "prompt" | "template" | "chain";
171 | requiresExecution: boolean;
172 | confidence: number;
173 | reasoning: string[];
174 | suggestedGates: string[];
175 | framework?: string;
176 | }
177 |
178 | /**
179 | * Tool routing detection result interface
180 | */
181 | interface ToolRoutingResult {
182 | requiresRouting: boolean;
183 | targetTool?: string;
184 | translatedParams?: Record<string, any>;
185 | originalCommand?: string;
186 | }
187 |
188 | /**
189 | * Consolidated Prompt Engine Tool
190 | */
191 | export class ConsolidatedPromptEngine {
192 | private logger: Logger;
193 | private mcpServer: any;
194 | private promptManager: PromptManager;
195 | private configManager: ConfigManager;
196 | private readonly serverRoot: string;
197 | private semanticAnalyzer: ContentAnalyzer;
198 | private conversationManager: ConversationManager;
199 | private textReferenceManager: TextReferenceManager;
200 | private chainSessionManager: ChainSessionManager;
201 | private frameworkStateManager?: FrameworkStateManager;
202 | private frameworkManager?: FrameworkManager;
203 | // Legacy gate system removed - using only lightweightGateSystem
204 | // NEW: Lightweight gate system (Phase 2 integration)
205 | private lightweightGateSystem: LightweightGateSystem;
206 | // NEW: Temporary gate registry access (Phase 3 enhancement)
207 | private get temporaryGateRegistry() {
208 | return this.lightweightGateSystem.getTemporaryGateRegistry?.();
209 | }
210 | // NEW: Role-based gate guidance renderer (Phase 3)
211 | private gateGuidanceRenderer: GateGuidanceRenderer;
212 | // Gate validation engine
213 | private engineValidator?: EngineValidator;
214 | // Phase 4: Clean architecture gate intelligence
215 | private gateSelectionEngine?: GateSelectionEngine;
216 | // Chain execution delegation
217 | private chainExecutor?: ChainExecutor;
218 | // REMOVED: chainOrchestrator - modular chain system removed
219 | // Chain URI addressing system
220 | // REMOVED: chainAddressingSystem - deprecated with markdown-embedded chains
221 |
222 | // MCP Tools Manager reference for analytics flow
223 | private mcpToolsManager?: any;
224 |
225 | // Analytics service for event-driven analytics collection
226 | private analyticsService?: MetricsCollector;
227 |
228 | // Response formatter for structured output
229 | private responseFormatter: ResponseFormatter;
230 |
231 | // New unified parsing system
232 | private parsingSystem: ParsingSystem;
233 |
234 | // Dynamic template discovery system
235 | // REMOVED: dynamicTemplateDiscovery - scaffolding system deprecated
236 |
237 | // Tool description manager
238 | private toolDescriptionManager?: ToolDescriptionManager;
239 |
240 | // Phase 3: Prompt guidance service
241 | private promptGuidanceService?: PromptGuidanceService;
242 |
243 | private activeGateRequest?: {
244 | gateIds: string[];
245 | gateMode: 'enforce' | 'advise' | 'report';
246 | qualityGates: string[];
247 | customChecks: Array<{ name: string; description: string }>;
248 | executionScopeId?: string;
249 | };
250 |
251 | // Data references
252 | private promptsData: PromptData[] = [];
253 | private convertedPrompts: ConvertedPrompt[] = [];
254 |
255 | // Execution state tracking
256 | private currentExecutionState: ExecutionState | null = null;
257 | private executionHistory: ExecutionState[] = [];
258 | private chainProgressState: ChainExecutionProgress | null = null;
259 |
260 | constructor(
261 | logger: Logger,
262 | mcpServer: any,
263 | promptManager: PromptManager,
264 | configManager: ConfigManager,
265 | semanticAnalyzer: ContentAnalyzer,
266 | conversationManager: ConversationManager,
267 | textReferenceManager: TextReferenceManager,
268 | // Legacy gateEvaluationService parameter removed - using lightweight system only
269 | mcpToolsManager?: any
270 | // Phase 3: Removed executionCoordinator parameter - no longer needed
271 | ) {
272 | this.logger = logger;
273 | this.mcpServer = mcpServer;
274 | this.promptManager = promptManager;
275 | this.configManager = configManager;
276 | this.semanticAnalyzer = semanticAnalyzer;
277 | this.conversationManager = conversationManager;
278 | this.textReferenceManager = textReferenceManager;
279 |
280 | // Initialize chain session manager with both conversation and text reference managers
281 | this.chainSessionManager = createChainSessionManager(logger, conversationManager, textReferenceManager);
282 |
283 | // Legacy gate evaluation service assignment removed
284 | this.mcpToolsManager = mcpToolsManager;
285 | // Phase 3: Removed executionCoordinator assignment - using LLM-driven chain model
286 |
287 | // Initialize lightweight gate system with temporary gates (Phase 3 enhancement)
288 | const config = configManager.getConfig();
289 | const gatesConfig = config.gates;
290 | const configRoot =
291 | typeof this.configManager.getServerRoot === 'function'
292 | ? this.configManager.getServerRoot()
293 | : path.dirname(this.configManager.getConfigPath?.() ?? path.join(process.cwd(), 'config.json'));
294 | this.serverRoot = configRoot;
295 |
296 | const gatesDirectory = gatesConfig?.definitionsDirectory
297 | ? path.isAbsolute(gatesConfig.definitionsDirectory)
298 | ? gatesConfig.definitionsDirectory
299 | : path.resolve(configRoot, gatesConfig.definitionsDirectory)
300 | : path.resolve(configRoot, 'src/gates/definitions');
301 |
302 | // Get LLM config for gate validator
303 | const llmConfig = config.analysis?.semanticAnalysis?.llmIntegration;
304 |
305 | this.lightweightGateSystem = createLightweightGateSystem(
306 | logger,
307 | gatesDirectory,
308 | undefined, // gateSystemManager - will be set later if needed
309 | {
310 | enableTemporaryGates: true,
311 | maxMemoryGates: 100, // Allow up to 100 temporary gates in memory
312 | defaultExpirationMs: 30 * 60 * 1000, // 30 minutes default expiration
313 | llmConfig // Pass LLM config to gate validator
314 | }
315 | );
316 |
317 | // NEW: Initialize role-based gate guidance renderer (Phase 3)
318 | // Phase 3 Enhancement: Pass temporary gate registry to renderer for temp gate support
319 | const temporaryGateRegistry = this.lightweightGateSystem.getTemporaryGateRegistry();
320 | this.gateGuidanceRenderer = createGateGuidanceRenderer(
321 | logger,
322 | gatesDirectory,
323 | temporaryGateRegistry
324 | );
325 |
326 | // Initialize EngineValidator with gate system (Phase 1.1 fix)
327 | this.engineValidator = new EngineValidator(this.lightweightGateSystem);
328 |
329 | // Phase 4: Initialize clean architecture gate intelligence
330 | this.gateSelectionEngine = createGateSelectionEngine(logger);
331 |
332 | // Note: Performance analytics now handled separately through system control
333 | // No need to connect gate selection engine to other components
334 |
335 | // Initialize new parsing system
336 | this.parsingSystem = createParsingSystem(logger);
337 |
338 | // Initialize dynamic template discovery
339 | // REMOVED: Dynamic template discovery initialization - scaffolding system deprecated
340 |
341 | // Initialize response formatter
342 | this.responseFormatter = createResponseFormatter();
343 |
344 | this.logger.info(
345 | "ConsolidatedPromptEngine initialized with new unified parsing system, dynamic template discovery, and response formatter"
346 | );
347 | }
348 |
349 | /**
350 | * Update data references
351 | */
352 | updateData(
353 | promptsData: PromptData[],
354 | convertedPrompts: ConvertedPrompt[]
355 | ): void {
356 | this.promptsData = promptsData;
357 | this.convertedPrompts = convertedPrompts;
358 | }
359 |
360 | /**
361 | * Set framework state manager (called after initialization)
362 | */
363 | setFrameworkStateManager(frameworkStateManager: FrameworkStateManager): void {
364 | this.frameworkStateManager = frameworkStateManager;
365 | this.initializeChainExecutor();
366 | }
367 |
368 | /**
369 | * Set framework manager (called after initialization)
370 | */
371 | setFrameworkManager(frameworkManager: FrameworkManager): void {
372 | this.frameworkManager = frameworkManager;
373 | this.initializeChainExecutor();
374 | this.initializePromptGuidanceService();
375 | }
376 |
377 | /**
378 | * Initialize ChainExecutor once dependencies are available
379 | */
380 | private initializeChainExecutor(): void {
381 | if (this.frameworkManager && this.frameworkStateManager) {
382 | this.chainExecutor = new ChainExecutor(
383 | this.conversationManager,
384 | this.lightweightGateSystem,
385 | this.frameworkManager,
386 | this.frameworkStateManager,
387 | this.responseFormatter,
388 | this.chainSessionManager
389 | );
390 | this.logger.debug("ChainExecutor initialized successfully");
391 | }
392 | }
393 |
394 | /**
395 | * Initialize PromptGuidanceService once framework manager is available
396 | */
397 | private async initializePromptGuidanceService(): Promise<void> {
398 | if (this.frameworkManager && !this.promptGuidanceService) {
399 | try {
400 | const methodologyStatePath = path.join(
401 | this.serverRoot,
402 | 'runtime-state',
403 | 'framework-state.json'
404 | );
405 |
406 | this.promptGuidanceService = await createPromptGuidanceService(
407 | this.logger,
408 | {
409 | systemPromptInjection: {
410 | enabled: true,
411 | injectionMethod: 'smart',
412 | enableTemplateVariables: true,
413 | enableContextualEnhancement: true
414 | },
415 | templateEnhancement: {
416 | enabled: true,
417 | enhancementLevel: 'moderate',
418 | enableArgumentSuggestions: true,
419 | enableStructureOptimization: true
420 | },
421 | methodologyTracking: {
422 | enabled: true,
423 | persistStateToDisk: true,
424 | enableHealthMonitoring: true,
425 | stateFilePath: methodologyStatePath
426 | }
427 | },
428 | this.frameworkManager
429 | );
430 | this.logger.debug("PromptGuidanceService initialized successfully");
431 | } catch (error) {
432 | this.logger.warn("Failed to initialize PromptGuidanceService:", error);
433 | // Continue without guidance service - it's optional
434 | }
435 | }
436 | }
437 |
438 | /**
439 | * Set analytics service (called after initialization)
440 | */
441 | setAnalyticsService(analyticsService: MetricsCollector): void {
442 | this.analyticsService = analyticsService;
443 | this.responseFormatter.setAnalyticsService(analyticsService);
444 | }
445 |
446 | /**
447 | * Set tool description manager (called after initialization)
448 | */
449 | setToolDescriptionManager(manager: ToolDescriptionManager): void {
450 | this.toolDescriptionManager = manager;
451 | }
452 |
453 | /**
454 | * Get the prompts base path using ConfigManager for cross-platform compatibility
455 | */
456 | private getPromptsBasePath(): string {
457 | // Use environment variable override if available
458 | if (process.env.MCP_PROMPTS_PATH) {
459 | return process.env.MCP_PROMPTS_PATH;
460 | }
461 |
462 | // Use ConfigManager to get proper path resolution
463 | const promptsFilePath = this.configManager.getPromptsFilePath();
464 | // Get the directory containing the prompts config file
465 | return path.dirname(promptsFilePath);
466 | }
467 |
468 | // REMOVED: setChainOrchestrator method - modular chain system removed
469 |
470 | /**
471 | * Get lightweight gate system for external access
472 | */
473 | getLightweightGateSystem(): LightweightGateSystem {
474 | return this.lightweightGateSystem;
475 | }
476 |
477 | /**
478 | * Expose gate guidance renderer for discovery operations
479 | */
480 | getGateGuidanceRenderer(): GateGuidanceRenderer {
481 | return this.gateGuidanceRenderer;
482 | }
483 |
484 | /**
485 | * Set gate system manager for runtime gate management
486 | */
487 | setGateSystemManager(gateSystemManager: any): void {
488 | this.lightweightGateSystem.setGateSystemManager(gateSystemManager);
489 | this.logger.debug("Gate system manager configured for prompt engine");
490 | }
491 |
492 | /**
493 | * Get framework-enhanced system prompt injection
494 | */
495 | private async getFrameworkExecutionContext(
496 | prompt: ConvertedPrompt
497 | ): Promise<FrameworkExecutionContext | null> {
498 | this.logger.debug(`[ENGINE DEBUG] getFrameworkExecutionContext called for prompt: ${prompt.id}`);
499 |
500 | if (!this.frameworkManager || !this.frameworkStateManager) {
501 | this.logger.debug(`[ENGINE DEBUG] Missing dependencies - frameworkManager: ${!!this.frameworkManager}, frameworkStateManager: ${!!this.frameworkStateManager}`);
502 | return null;
503 | }
504 |
505 | // NEW: Check if framework system is enabled before generating context
506 | const isEnabled = this.frameworkStateManager.isFrameworkSystemEnabled();
507 | this.logger.debug(`[ENGINE DEBUG] Framework system enabled: ${isEnabled}`);
508 | if (!isEnabled) {
509 | return null;
510 | }
511 |
512 | try {
513 | // Get current active framework from state manager
514 | const activeFramework = this.frameworkStateManager.getActiveFramework();
515 | this.logger.debug(`[ENGINE DEBUG] Active framework:`, {
516 | methodology: activeFramework.methodology,
517 | name: activeFramework.name
518 | });
519 |
520 | // Generate execution context using the framework manager
521 | const context = this.frameworkManager.generateExecutionContext(prompt, {
522 | userPreference: activeFramework.methodology as any,
523 | });
524 |
525 | this.logger.debug(`[ENGINE DEBUG] Generated execution context:`, {
526 | hasContext: !!context,
527 | contextType: context ? typeof context : 'null',
528 | hasSystemPrompt: context?.systemPrompt ? true : false,
529 | systemPromptLength: context?.systemPrompt?.length || 0
530 | });
531 |
532 | return context;
533 | } catch (error) {
534 | this.logger.warn(
535 | "Failed to generate framework execution context:",
536 | error
537 | );
538 | return null;
539 | }
540 | }
541 |
542 |
543 | /**
544 | * Main prompt execution handler
545 | */
546 | public async executePromptCommand(
547 | args: {
548 | command: string;
549 | execution_mode?: "auto" | "prompt" | "template" | "chain";
550 | gate_validation?: boolean;
551 | step_confirmation?: boolean;
552 | llm_driven_execution?: boolean;
553 | force_restart?: boolean;
554 | session_id?: string;
555 | chain_uri?: string;
556 | timeout?: number;
557 | options?: Record<string, any>;
558 | temporary_gates?: TemporaryGateDefinition[];
559 | gate_scope?: 'execution' | 'session' | 'chain' | 'step';
560 | inherit_chain_gates?: boolean;
561 | quality_gates?: string[];
562 | custom_checks?: Array<{ name: string; description: string }>;
563 | gate_mode?: 'enforce' | 'advise' | 'report';
564 | },
565 | extra: any
566 | ): Promise<ToolResponse> {
567 | const {
568 | command,
569 | execution_mode = "auto",
570 | gate_validation,
571 | step_confirmation,
572 | llm_driven_execution,
573 | force_restart,
574 | session_id,
575 | chain_uri,
576 | timeout,
577 | options = {},
578 | temporary_gates,
579 | gate_scope = 'execution',
580 | inherit_chain_gates = true,
581 | quality_gates,
582 | custom_checks,
583 | gate_mode,
584 | } = args;
585 |
586 | const hasSimplifiedGates =
587 | (quality_gates?.length ?? 0) > 0 || (custom_checks?.length ?? 0) > 0;
588 | const resolvedGateMode: 'enforce' | 'advise' | 'report' =
589 | gate_mode ?? (hasSimplifiedGates ? 'enforce' : 'advise');
590 |
591 | const normalizedArgs = {
592 | ...args,
593 | gate_mode: resolvedGateMode,
594 | quality_gates,
595 | custom_checks,
596 | };
597 |
598 | this.logger.info(
599 | `🚀 [ENTRY] Prompt Engine: Executing "${command}" (mode: ${execution_mode})`
600 | );
601 |
602 | // Phase 1: Check if command should be routed to a different tool
603 | const routingResult = await this.detectToolRoutingCommand(command);
604 | this.logger.info(`🔍 [ROUTING DEBUG] Tool routing check:`, {
605 | command,
606 | requiresRouting: routingResult.requiresRouting,
607 | targetTool: routingResult.targetTool
608 | });
609 |
610 | if (routingResult.requiresRouting) {
611 | this.logger.info(`🔀 [ROUTING DEBUG] Command being routed to different tool: ${routingResult.targetTool}`);
612 | const routedResult = await this.routeToTool(
613 | routingResult.targetTool!,
614 | routingResult.translatedParams!,
615 | routingResult.originalCommand!
616 | );
617 | return routedResult;
618 | }
619 |
620 | // Parse command and extract execution context
621 | const executionContext = await this.parseAndPrepareExecution(command);
622 |
623 | // Handle chain management commands
624 | if (executionContext.isChainManagement && this.chainExecutor) {
625 | return await this.chainExecutor.executeChainManagement(
626 | executionContext.chainAction!,
627 | executionContext.chainParameters || {},
628 | options
629 | );
630 | }
631 |
632 | // Determine execution strategy
633 | const strategy = await this.determineExecutionStrategy(
634 | executionContext.convertedPrompt,
635 | execution_mode,
636 | {
637 | gate_validation,
638 | quality_gates,
639 | custom_checks,
640 | }
641 | );
642 |
643 | // Initialize execution state with session tracking
644 | this.initializeExecutionState(
645 | executionContext.convertedPrompt,
646 | strategy,
647 | session_id
648 | );
649 |
650 | // Execute using determined strategy
651 | return await this.executeWithStrategy(strategy, executionContext, {
652 | ...normalizedArgs,
653 | gate_validation,
654 | step_confirmation,
655 | llm_driven_execution,
656 | force_restart,
657 | session_id,
658 | chain_uri,
659 | timeout,
660 | options,
661 | });
662 | }
663 |
664 | /**
665 | * Parse command and prepare execution context
666 | */
667 | private async parseAndPrepareExecution(command: string) {
668 | const {
669 | promptId,
670 | arguments: promptArgs,
671 | convertedPrompt,
672 | isChainManagement,
673 | chainAction,
674 | chainParameters,
675 | } = await this.parseCommandUnified(command);
676 |
677 | // Apply prompt guidance if available and not a chain management command
678 | let enhancedPrompt = convertedPrompt;
679 | let guidanceResult: ServicePromptGuidanceResult | undefined;
680 |
681 | // FIXED: Re-enable PromptGuidanceService with system prompt injection only
682 | // This provides framework methodology reminder at the START of responses
683 | // Gate guidance (framework-compliance) provides quality criteria at the END
684 | if (!isChainManagement && this.promptGuidanceService && convertedPrompt) {
685 | try {
686 | this.logger.info(`🔧 [FRAMEWORK DEBUG] Calling PromptGuidanceService for ${convertedPrompt.id}`, {
687 | hasPromptGuidanceService: !!this.promptGuidanceService,
688 | isInitialized: this.promptGuidanceService.isInitialized(),
689 | originalSystemMessage: convertedPrompt.systemMessage?.substring(0, 100)
690 | });
691 |
692 | guidanceResult = await this.promptGuidanceService.applyGuidance(convertedPrompt, {
693 | includeSystemPromptInjection: true, // ENABLED: Framework reminder at beginning
694 | includeTemplateEnhancement: false // DISABLED: Prevent template duplication
695 | });
696 |
697 | this.logger.info(`🔧 [FRAMEWORK DEBUG] PromptGuidanceService result:`, {
698 | guidanceApplied: guidanceResult.guidanceApplied,
699 | hasEnhancedPrompt: !!guidanceResult.enhancedPrompt,
700 | enhancementsApplied: guidanceResult.metadata.enhancementsApplied,
701 | enhancedSystemMessage: guidanceResult.enhancedPrompt?.systemMessage?.substring(0, 200)
702 | });
703 |
704 | if (guidanceResult.guidanceApplied && guidanceResult.enhancedPrompt) {
705 | enhancedPrompt = guidanceResult.enhancedPrompt;
706 | this.logger.info(`✅ [FRAMEWORK DEBUG] Prompt guidance applied: ${guidanceResult.metadata.enhancementsApplied.join(', ')}`);
707 | } else {
708 | this.logger.warn(`⚠️ [FRAMEWORK DEBUG] Guidance not applied - guidanceApplied=${guidanceResult.guidanceApplied}, hasEnhancedPrompt=${!!guidanceResult.enhancedPrompt}`);
709 | }
710 | } catch (error) {
711 | this.logger.error("❌ [FRAMEWORK DEBUG] Prompt guidance failed:", error);
712 | }
713 | } else {
714 | this.logger.warn(`⚠️ [FRAMEWORK DEBUG] Skipping PromptGuidanceService:`, {
715 | isChainManagement,
716 | hasService: !!this.promptGuidanceService,
717 | hasPrompt: !!convertedPrompt
718 | });
719 | }
720 |
721 | return {
722 | promptId,
723 | promptArgs,
724 | convertedPrompt: enhancedPrompt,
725 | originalPrompt: convertedPrompt,
726 | guidanceResult,
727 | isChainManagement,
728 | chainAction,
729 | chainParameters,
730 | };
731 | }
732 |
733 | /**
734 | * Determine the execution strategy based on mode and prompt type
735 | */
736 | private async determineExecutionStrategy(
737 | convertedPrompt: any,
738 | execution_mode: string,
739 | overrides?: {
740 | gate_validation?: boolean;
741 | quality_gates?: string[];
742 | custom_checks?: Array<{ name: string; description: string }>;
743 | }
744 | ): Promise<{
745 | mode: "prompt" | "template" | "chain";
746 | gateValidation: boolean;
747 | }> {
748 | let effectiveExecutionMode: "prompt" | "template" | "chain";
749 |
750 | if (!execution_mode || execution_mode === "auto") {
751 | const detectedMode = await this.detectExecutionMode(convertedPrompt);
752 | effectiveExecutionMode = detectedMode as "prompt" | "template" | "chain";
753 | } else {
754 | effectiveExecutionMode = execution_mode as
755 | | "prompt"
756 | | "template"
757 | | "chain";
758 | }
759 |
760 | const hasSimplifiedGates =
761 | (overrides?.quality_gates?.length ?? 0) > 0 ||
762 | (overrides?.custom_checks?.length ?? 0) > 0;
763 |
764 | const effectiveGateValidation =
765 | overrides?.gate_validation ??
766 | (hasSimplifiedGates ? true : effectiveExecutionMode === "chain");
767 |
768 | this.logger.info(
769 | `🔍 EXECUTION MODE DEBUG: Effective settings: mode=${effectiveExecutionMode}, gates=${effectiveGateValidation}, prompt=${convertedPrompt.id}, simplifiedGates=${hasSimplifiedGates}`
770 | );
771 |
772 | return {
773 | mode: effectiveExecutionMode,
774 | gateValidation: effectiveGateValidation,
775 | };
776 | }
777 |
778 | /**
779 | * Initialize execution state tracking with session support
780 | */
781 | private initializeExecutionState(
782 | convertedPrompt: any,
783 | strategy: { mode: string; gateValidation: boolean },
784 | sessionId?: string
785 | ) {
786 | this.currentExecutionState = {
787 | type: isChainPrompt(convertedPrompt) ? "chain" : "single",
788 | promptId: convertedPrompt.id,
789 | status: "pending",
790 | gates: [],
791 | results: {},
792 | metadata: {
793 | startTime: Date.now(),
794 | executionMode: strategy.mode as "prompt" | "template" | "chain",
795 | gateValidation: strategy.gateValidation,
796 | sessionId, // Store session ID for step result capture
797 | },
798 | };
799 | }
800 |
801 | /**
802 | * Execute using the determined strategy
803 | */
804 | private async executeWithStrategy(
805 | strategy: {
806 | mode: "prompt" | "template" | "chain";
807 | gateValidation: boolean;
808 | },
809 | context: any,
810 | args: any
811 | ): Promise<ToolResponse> {
812 | const { convertedPrompt, promptArgs } = context;
813 |
814 | // Phase 3: Create execution scope for temporary gates
815 | const executionScopeId = this.createExecutionScope(convertedPrompt, strategy, args);
816 |
817 | try {
818 |
819 | switch (strategy.mode) {
820 | case "prompt":
821 | this.logger.info(
822 | `📍 EXECUTION PATH: Taking PROMPT path for ${convertedPrompt.id}`
823 | );
824 | const promptResult = await this.executePrompt(
825 | convertedPrompt,
826 | promptArgs,
827 | this.getExecutionContext(executionScopeId, 'execution')
828 | );
829 | return promptResult;
830 |
831 | case "template":
832 | this.logger.info(
833 | `📍 EXECUTION PATH: Taking TEMPLATE path for ${convertedPrompt.id}`
834 | );
835 | const templateResult = await this.executeTemplateWithFramework(
836 | convertedPrompt,
837 | promptArgs,
838 | strategy.gateValidation,
839 | this.getExecutionContext(executionScopeId, 'execution')
840 | );
841 | return templateResult;
842 |
843 | case "chain":
844 | this.logger.info(
845 | `📍 EXECUTION PATH: Taking CHAIN path for ${convertedPrompt.id}`
846 | );
847 | if (!this.chainExecutor) {
848 | return this.responseFormatter.formatErrorResponse(
849 | 'ChainExecutor not initialized - framework managers required',
850 | 'ConsolidatedPromptEngine',
851 | 'executePromptCommand'
852 | );
853 | }
854 |
855 | // Ensure chain session exists
856 | const chainSessionId = await this.ensureChainSession(
857 | convertedPrompt,
858 | args.session_id,
859 | args.force_restart,
860 | promptArgs
861 | );
862 |
863 | return await this.chainExecutor.executeChainWithDualSupport(
864 | convertedPrompt,
865 | promptArgs,
866 | strategy.gateValidation,
867 | {
868 | enableGates: strategy.gateValidation,
869 | force_restart: args.force_restart,
870 | session_id: chainSessionId,
871 | step_confirmation: args.step_confirmation,
872 | llm_driven_execution: args.llm_driven_execution,
873 | chain_uri: args.chain_uri,
874 | timeout: args.timeout,
875 | temporary_gates: args.temporary_gates,
876 | gate_scope: args.gate_scope,
877 | inherit_chain_gates: args.inherit_chain_gates,
878 | ...args.options,
879 | }
880 | );
881 |
882 | default:
883 | throw new ValidationError(`Unknown execution mode: ${strategy.mode}`);
884 | }
885 |
886 | } finally {
887 | // Phase 3: Cleanup execution scope and temporary gates
888 | this.cleanupExecutionScope(executionScopeId);
889 | }
890 | }
891 |
892 | /**
893 | * Phase 3: Create execution scope for temporary gate lifecycle management
894 | * Phase 4: Enhanced with execution-time temporary gate support
895 | */
896 | private createExecutionScope(
897 | convertedPrompt: any,
898 | strategy: { mode: string; gateValidation: boolean },
899 | args: any
900 | ): string {
901 | const scopeId = `exec_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
902 |
903 | this.logger.info(`🔧 [EXECUTION SCOPE] Created execution scope:`, {
904 | scopeId,
905 | promptId: convertedPrompt?.id,
906 | mode: strategy.mode,
907 | gateValidation: strategy.gateValidation,
908 | sessionId: args.session_id,
909 | hasExecutionTimeGates: !!args.temporary_gates,
910 | executionTimeGateCount: args.temporary_gates?.length || 0
911 | });
912 |
913 | // Create execution-time temporary gates if provided
914 | if (args.temporary_gates && args.temporary_gates.length > 0 && this.temporaryGateRegistry) {
915 | const gateScope = args.gate_scope || 'execution';
916 | this.logger.info(`🚀 [EXECUTION-TIME GATES] Creating ${args.temporary_gates.length} execution-time temporary gates`, {
917 | scope: gateScope,
918 | scopeId
919 | });
920 |
921 | for (const tempGate of args.temporary_gates) {
922 | try {
923 | const gateId = this.temporaryGateRegistry.createTemporaryGate(
924 | {
925 | name: tempGate.name,
926 | type: tempGate.type,
927 | scope: gateScope,
928 | description: tempGate.description,
929 | guidance: tempGate.guidance,
930 | pass_criteria: tempGate.pass_criteria,
931 | source: 'manual',
932 | context: { executionTimeGate: true, promptId: convertedPrompt?.id }
933 | },
934 | scopeId
935 | );
936 |
937 | this.logger.debug(`✅ [EXECUTION-TIME GATES] Created temporary gate: ${gateId} (${tempGate.name})`);
938 | } catch (error) {
939 | this.logger.error(`❌ [EXECUTION-TIME GATES] Failed to create temporary gate:`, {
940 | error: error instanceof Error ? error.message : String(error),
941 | gateName: tempGate.name
942 | });
943 | }
944 | }
945 | }
946 |
947 | const simplifiedGateIds = this.convertSimplifiedGates(
948 | args.quality_gates,
949 | args.custom_checks,
950 | scopeId
951 | );
952 |
953 | const hasSimplifiedGates =
954 | (args.quality_gates?.length ?? 0) > 0 ||
955 | (args.custom_checks?.length ?? 0) > 0;
956 |
957 | if (hasSimplifiedGates || args.gate_mode) {
958 | const gateMode = (args.gate_mode as 'enforce' | 'advise' | 'report') || 'advise';
959 | this.activeGateRequest = {
960 | gateIds: simplifiedGateIds,
961 | gateMode,
962 | qualityGates: args.quality_gates || [],
963 | customChecks: args.custom_checks || [],
964 | executionScopeId: scopeId,
965 | };
966 | } else {
967 | this.activeGateRequest = undefined;
968 | }
969 |
970 | return scopeId;
971 | }
972 |
973 | /**
974 | * Phase 3: Cleanup execution scope and associated temporary gates
975 | */
976 | private cleanupExecutionScope(scopeId: string): void {
977 | if (this.temporaryGateRegistry) {
978 | this.temporaryGateRegistry.cleanupScope(scopeId);
979 | this.logger.info(`🧹 [EXECUTION SCOPE] Cleaned up execution scope: ${scopeId}`);
980 | } else {
981 | this.logger.debug(`🧹 [EXECUTION SCOPE] No temporary gate registry available for cleanup: ${scopeId}`);
982 | }
983 |
984 | if (this.activeGateRequest?.executionScopeId === scopeId) {
985 | this.activeGateRequest = undefined;
986 | }
987 | }
988 |
989 | private convertSimplifiedGates(
990 | qualityGates?: string[],
991 | customChecks?: Array<{ name: string; description: string }>,
992 | executionScopeId?: string
993 | ): string[] {
994 | const gateIds: string[] = [];
995 |
996 | if (qualityGates && qualityGates.length > 0) {
997 | gateIds.push(...qualityGates);
998 | }
999 |
1000 | if (customChecks && customChecks.length > 0) {
1001 | if (!this.temporaryGateRegistry) {
1002 | this.logger.warn(
1003 | "Temporary gate registry unavailable; custom checks cannot be registered"
1004 | );
1005 | } else {
1006 | for (const check of customChecks) {
1007 | try {
1008 | const gateId = this.temporaryGateRegistry.createTemporaryGate(
1009 | {
1010 | name: check.name,
1011 | type: 'validation',
1012 | scope: 'execution',
1013 | description: check.description,
1014 | guidance: `Ensure: ${check.description}`,
1015 | pass_criteria: [],
1016 | source: 'manual',
1017 | },
1018 | executionScopeId
1019 | );
1020 |
1021 | gateIds.push(gateId);
1022 | } catch (error) {
1023 | this.logger.error(
1024 | `Failed to create temporary gate for custom check ${check.name}:`,
1025 | error
1026 | );
1027 | }
1028 | }
1029 | }
1030 | }
1031 |
1032 | return gateIds;
1033 | }
1034 |
1035 | private mergeRequestedGates(gates: string[]): string[] {
1036 | const requested = this.activeGateRequest?.gateIds || [];
1037 | if (!requested.length) {
1038 | return gates;
1039 | }
1040 |
1041 | const combined = [...requested, ...gates];
1042 | return [...new Set(combined)];
1043 | }
1044 |
1045 | private formatGateStatus(validation: GateValidationResult | null): string {
1046 | if (!validation) {
1047 | if (this.activeGateRequest?.gateMode === 'report') {
1048 | return `\n\n---\nℹ️ **Quality Gates**: Validation not executed\n`;
1049 | }
1050 | return '';
1051 | }
1052 |
1053 | const total = validation.results?.length ?? 0;
1054 |
1055 | if (validation.passed) {
1056 | return `\n\n---\n✅ **Quality Gates**: All checks passed (${total} gates)\n`;
1057 | }
1058 |
1059 | const failed = (validation.results || []).filter((result) => !result.passed);
1060 | let message = `\n\n---\n⚠️ **Quality Gates**: ${failed.length} of ${total} failed\n\n`;
1061 |
1062 | for (const result of failed) {
1063 | message += `❌ **${result.gate}**: ${result.message}\n`;
1064 | }
1065 |
1066 | return message;
1067 | }
1068 |
1069 | /**
1070 | * Phase 3: Get execution context for temporary gates
1071 | */
1072 | private getExecutionContext(scopeId: string, scope: 'execution' | 'session' | 'chain' | 'step' = 'execution') {
1073 | return {
1074 | scopeId,
1075 | scope
1076 | };
1077 | }
1078 |
1079 | /**
1080 | * Phase 3: Extract temporary gates from prompt configuration
1081 | */
1082 | private getTemporaryGatesFromPrompt(prompt: ConvertedPrompt): Array<Omit<TemporaryGateDefinition, 'id' | 'created_at'>> | undefined {
1083 | // Phase 3 Fix: Check enhancedGateConfiguration first, then fall back to gateConfiguration
1084 | const gateConfig = (prompt.enhancedGateConfiguration || prompt.gateConfiguration) as EnhancedGateConfiguration | undefined;
1085 | if (!gateConfig?.temporary_gates) {
1086 | return undefined;
1087 | }
1088 |
1089 | return gateConfig.temporary_gates.map((tempGate: any) => ({
1090 | name: tempGate.name,
1091 | type: tempGate.type,
1092 | scope: tempGate.scope,
1093 | description: tempGate.description,
1094 | guidance: tempGate.guidance,
1095 | pass_criteria: tempGate.pass_criteria,
1096 | expires_at: tempGate.expires_at,
1097 | source: tempGate.source || 'manual',
1098 | context: tempGate.context
1099 | }));
1100 | }
1101 |
1102 | /**
1103 | * Phase 1: Chain Management Command Detection
1104 | */
1105 |
1106 | // REMOVED: detectChainManagementCommand - migrated to ChainExecutor
1107 |
1108 | // REMOVED: parseKeyValueParams - migrated to ChainExecutor
1109 |
1110 | // REMOVED: handleChainManagementCommand - migrated to ChainExecutor
1111 |
1112 | /**
1113 | * Detect if command should be routed to a different tool
1114 | */
1115 | private async detectToolRoutingCommand(command: string): Promise<ToolRoutingResult> {
1116 | const trimmedCommand = command.trim();
1117 |
1118 | // Built-in commands that route to prompt_manager
1119 | if (/^(>>|\/)?listprompts?(\s.*)?$/i.test(trimmedCommand)) {
1120 | const args = trimmedCommand.replace(/^(>>|\/)?listprompts?\s*/i, '').trim();
1121 | return {
1122 | requiresRouting: true,
1123 | targetTool: 'prompt_manager',
1124 | translatedParams: {
1125 | action: 'list',
1126 | ...(args && { search_query: args })
1127 | },
1128 | originalCommand: command
1129 | };
1130 | }
1131 |
1132 | // Help and status commands that route to system_control
1133 | if (/^(>>|\/)?help$/i.test(trimmedCommand)) {
1134 | return {
1135 | requiresRouting: true,
1136 | targetTool: 'system_control',
1137 | translatedParams: {
1138 | action: 'status',
1139 | show_details: true
1140 | },
1141 | originalCommand: command
1142 | };
1143 | }
1144 |
1145 | if (/^(>>|\/)?status$/i.test(trimmedCommand)) {
1146 | return {
1147 | requiresRouting: true,
1148 | targetTool: 'system_control',
1149 | translatedParams: {
1150 | action: 'status'
1151 | },
1152 | originalCommand: command
1153 | };
1154 | }
1155 |
1156 | // Framework switch commands
1157 | const frameworkMatch = trimmedCommand.match(/^(>>|\/)?framework\s+(switch|change)\s+(.+)$/i);
1158 | if (frameworkMatch) {
1159 | return {
1160 | requiresRouting: true,
1161 | targetTool: 'system_control',
1162 | translatedParams: {
1163 | action: 'framework',
1164 | operation: 'switch',
1165 | framework: frameworkMatch[3].trim()
1166 | },
1167 | originalCommand: command
1168 | };
1169 | }
1170 |
1171 | // Analytics/metrics commands
1172 | if (/^(>>|\/)?analytics?$/i.test(trimmedCommand)) {
1173 | return {
1174 | requiresRouting: true,
1175 | targetTool: 'system_control',
1176 | translatedParams: {
1177 | action: 'analytics'
1178 | },
1179 | originalCommand: command
1180 | };
1181 | }
1182 |
1183 | // No routing needed - let existing parser handle it
1184 | return {
1185 | requiresRouting: false
1186 | };
1187 | }
1188 |
1189 | /**
1190 | * Route command to appropriate tool with safe error handling
1191 | */
1192 | private async routeToTool(targetTool: string, params: Record<string, any>, originalCommand: string): Promise<ToolResponse> {
1193 | this.logger.info(`🔀 Routing command "${originalCommand}" to ${targetTool}`);
1194 |
1195 | try {
1196 | switch (targetTool) {
1197 | case 'prompt_manager':
1198 | if (this.mcpToolsManager?.promptManagerTool) {
1199 | this.logger.debug(`Calling prompt_manager with params:`, params);
1200 | return await this.mcpToolsManager.promptManagerTool.handleAction(params, {});
1201 | } else {
1202 | throw new Error('Prompt manager tool not available');
1203 | }
1204 |
1205 | case 'system_control':
1206 | if (this.mcpToolsManager?.systemControl) {
1207 | this.logger.debug(`Calling system_control with params:`, params);
1208 | return await this.mcpToolsManager.systemControl.handleAction(params, {});
1209 | } else {
1210 | throw new Error('System control tool not available');
1211 | }
1212 |
1213 | default:
1214 | throw new Error(`Unknown target tool: ${targetTool}`);
1215 | }
1216 | } catch (error) {
1217 | this.logger.error(`Tool routing failed for ${targetTool}:`, error);
1218 |
1219 | // Return formatted error response
1220 | return this.responseFormatter.formatErrorResponse(
1221 | error instanceof Error
1222 | ? `Tool routing failed: ${error.message}`
1223 | : `Tool routing failed: ${String(error)}`,
1224 | {
1225 | tool: 'prompt_engine',
1226 | operation: 'routeToTool',
1227 | targetTool,
1228 | originalCommand
1229 | },
1230 | {
1231 | includeStructuredData: true
1232 | }
1233 | );
1234 | }
1235 | }
1236 |
1237 | /**
1238 | * Parse command string using unified parsing system with chain management detection
1239 | */
1240 | private async parseCommandUnified(command: string): Promise<{
1241 | promptId: string;
1242 | arguments: Record<string, any>;
1243 | convertedPrompt: ConvertedPrompt;
1244 | isChainManagement?: boolean;
1245 | chainAction?: string;
1246 | chainParameters?: Record<string, any>;
1247 | }> {
1248 | // Phase 1: Smart chain management command detection
1249 | if (this.chainExecutor) {
1250 | const chainCommand = this.chainExecutor.detectChainManagementCommand(command);
1251 | if (chainCommand.isChainManagement) {
1252 | // Mark this as a chain management operation
1253 | return {
1254 | promptId: '',
1255 | arguments: {},
1256 | convertedPrompt: {} as ConvertedPrompt,
1257 | isChainManagement: true,
1258 | chainAction: chainCommand.action!,
1259 | chainParameters: chainCommand.parameters!
1260 | };
1261 | }
1262 | }
1263 | // Use new unified command parser
1264 | const parseResult = await this.parsingSystem.commandParser.parseCommand(
1265 | command,
1266 | this.promptsData
1267 | );
1268 |
1269 | // Find the matching prompt data and converted prompt (case-insensitive lookup)
1270 | const promptData = this.promptsData.find(
1271 | (p) => p.id.toLowerCase() === parseResult.promptId.toLowerCase() ||
1272 | (p.name && p.name.toLowerCase() === parseResult.promptId.toLowerCase())
1273 | );
1274 | if (!promptData) {
1275 | throw new PromptError(
1276 | `Unknown prompt: ${parseResult.promptId}. Use >>listprompts to see available prompts.`
1277 | );
1278 | }
1279 |
1280 | const convertedPrompt = this.convertedPrompts.find(
1281 | (p) => p.id === promptData.id
1282 | );
1283 | if (!convertedPrompt) {
1284 | throw new PromptError(
1285 | `Converted prompt data not found for: ${parseResult.promptId}`
1286 | );
1287 | }
1288 |
1289 | // Process arguments using new argument processor
1290 | const context: ExecutionContext = {
1291 | conversationHistory: [], // Would be injected from conversation manager
1292 | environmentVars: process.env as Record<string, string>,
1293 | promptDefaults: {},
1294 | systemContext: {},
1295 | };
1296 |
1297 | const argResult = await this.parsingSystem.argumentParser.parseArguments(
1298 | parseResult.rawArgs,
1299 | promptData,
1300 | context
1301 | );
1302 |
1303 | // Log parsing details for monitoring
1304 | this.logger.debug(`Command parsed successfully:`, {
1305 | strategy: parseResult.metadata.parseStrategy,
1306 | confidence: parseResult.confidence,
1307 | argumentsProcessed: Object.keys(argResult.processedArgs).length,
1308 | appliedDefaults: argResult.metadata.appliedDefaults.length,
1309 | warnings: [
1310 | ...parseResult.metadata.warnings,
1311 | ...argResult.metadata.warnings,
1312 | ],
1313 | });
1314 |
1315 | return {
1316 | promptId: promptData.id,
1317 | arguments: argResult.processedArgs, // Pass typed arguments directly
1318 | convertedPrompt,
1319 | };
1320 | }
1321 |
1322 | /**
1323 | * Detect execution mode using semantic analysis - THREE-TIER MODEL
1324 | * Returns appropriate execution strategy based on prompt characteristics
1325 | */
1326 | private async detectExecutionMode(
1327 | convertedPrompt: ConvertedPrompt
1328 | ): Promise<"prompt" | "template" | "chain"> {
1329 | if (convertedPrompt.executionMode) {
1330 | return convertedPrompt.executionMode;
1331 | }
1332 |
1333 | const classification = await this.analyzePrompt(convertedPrompt);
1334 | this.autoAssignQualityGates(convertedPrompt, classification);
1335 |
1336 | this.logger.debug(
1337 | `Semantic analysis: ${classification.executionType} (${Math.round(
1338 | classification.confidence * 100
1339 | )}%)`
1340 | );
1341 |
1342 | // Return the semantic analysis result directly - it now handles the three-tier distinction
1343 | return classification.executionType;
1344 | }
1345 |
1346 | /**
1347 | * Create fallback analysis when semantic analysis is disabled
1348 | */
1349 | private createDisabledAnalysisFallback(
1350 | prompt: ConvertedPrompt
1351 | ): PromptClassification {
1352 | const hasChainSteps = Boolean(prompt.chainSteps?.length);
1353 | const argCount = prompt.arguments?.length || 0;
1354 | const hasTemplateVars = /\{\{.*?\}\}/g.test(
1355 | prompt.userMessageTemplate || ""
1356 | );
1357 |
1358 | // Reliable structural detection: only use verifiable indicators
1359 | const hasComplexTemplateLogic =
1360 | /\{\{.*?\|.*?\}\}|\{%-.*?-%\}|\{%.*?if.*?%\}|\{%.*?for.*?%\}/g.test(
1361 | prompt.userMessageTemplate || ""
1362 | );
1363 | const hasMultipleArgs = argCount > 1; // More than one argument suggests complexity
1364 |
1365 | // Three-tier detection based on structural indicators only
1366 | let executionType: "prompt" | "template" | "chain" = "prompt";
1367 |
1368 | if (hasChainSteps) {
1369 | executionType = "chain";
1370 | } else if (hasComplexTemplateLogic) {
1371 | // Complex Nunjucks logic always needs template mode
1372 | executionType = "template";
1373 | } else if (hasTemplateVars && hasMultipleArgs) {
1374 | // Template variables with multiple args suggests framework benefit
1375 | executionType = "template";
1376 | }
1377 | // Default to 'prompt' for simple cases (no vars, single arg, or static content)
1378 |
1379 | return {
1380 | executionType,
1381 | requiresExecution: true,
1382 | confidence: 0.9, // High confidence in structural detection
1383 | reasoning: [
1384 | "Structural auto detection (semantic analysis disabled)",
1385 | `Args: ${argCount}, Template vars: ${hasTemplateVars}, Complex logic: ${hasComplexTemplateLogic}`,
1386 | `Selected ${executionType} mode based on verifiable structural indicators`,
1387 | ],
1388 | suggestedGates: ["basic_validation"],
1389 | framework: "disabled",
1390 | };
1391 | }
1392 |
1393 | /**
1394 | * Detect analysis intent using LLM semantic understanding (FUTURE IMPLEMENTATION)
1395 | *
1396 | * This method will be implemented when the LLM semantic layer is completed.
1397 | * It will provide intelligent analysis intent detection by examining:
1398 | * - Template content and complexity
1399 | * - Argument semantics and naming patterns
1400 | * - Task complexity indicators
1401 | * - Context and domain-specific signals
1402 | *
1403 | * @param prompt - The prompt to analyze for analysis intent
1404 | * @returns Promise<boolean> - True if prompt requires analytical framework processing
1405 | *
1406 | * @todo Implement when ContentAnalyzer LLM integration is enabled
1407 | * @todo Design proper interface for semantic intent classification
1408 | * @todo Add confidence scoring and reasoning for intent decisions
1409 | */
1410 | private async detectAnalysisIntentLLM(
1411 | prompt: ConvertedPrompt
1412 | ): Promise<boolean> {
1413 | // STUB: Always return false until LLM semantic analysis is implemented
1414 | // When implemented, this will use the LLM to intelligently detect:
1415 | // - Analysis vs formatting tasks
1416 | // - Complex reasoning requirements
1417 | // - Domain-specific analytical patterns
1418 | // - Context-dependent intent signals
1419 |
1420 | this.logger.debug(
1421 | `LLM analysis intent detection not yet implemented for ${prompt.id}`
1422 | );
1423 | return false;
1424 | }
1425 |
1426 | /**
1427 | * Analyze prompt for execution strategy (configuration-aware)
1428 | */
1429 | private async analyzePrompt(
1430 | prompt: ConvertedPrompt
1431 | ): Promise<PromptClassification> {
1432 | // Check if semantic analysis is enabled via the analyzer
1433 | if (!this.semanticAnalyzer.isLLMEnabled()) {
1434 | this.logger.debug(
1435 | `Semantic analysis disabled for ${prompt.id} - using structural fallback`
1436 | );
1437 | return this.createDisabledAnalysisFallback(prompt);
1438 | }
1439 |
1440 | try {
1441 | const analysis = await this.semanticAnalyzer.analyzePrompt(prompt);
1442 | return {
1443 | executionType: analysis.executionType,
1444 | requiresExecution: analysis.requiresExecution,
1445 | confidence: analysis.confidence,
1446 | reasoning: analysis.reasoning,
1447 | suggestedGates: analysis.suggestedGates,
1448 | framework: "semantic",
1449 | };
1450 | } catch (error) {
1451 | this.logger.error(`Semantic analysis failed for ${prompt.id}:`, error);
1452 | return {
1453 | executionType: isChainPrompt(prompt) ? "chain" : "template",
1454 | requiresExecution: true,
1455 | confidence: 0.5,
1456 | reasoning: [`Fallback analysis: ${error}`],
1457 | suggestedGates: ["execution_validation"],
1458 | framework: "fallback",
1459 | };
1460 | }
1461 | }
1462 |
1463 | /**
1464 | * Auto-assign quality gates based on classification
1465 | */
1466 | private autoAssignQualityGates(
1467 | prompt: ConvertedPrompt,
1468 | classification: PromptClassification
1469 | ): void {
1470 | const autoGates: GateDefinition[] = [];
1471 |
1472 | if (classification.requiresExecution && classification.confidence > 0.5) {
1473 | autoGates.push({
1474 | id: "content_length_validation",
1475 | name: "Content Length Validation",
1476 | type: "validation",
1477 | requirements: [
1478 | {
1479 | type: "content_length",
1480 | criteria: { min: 50 },
1481 | required: true,
1482 | },
1483 | ],
1484 | failureAction: "retry",
1485 | });
1486 | }
1487 |
1488 | if (autoGates.length > 0) {
1489 | (prompt as any).autoAssignedGates = autoGates;
1490 | this.logger.debug(
1491 | `Auto-assigned ${autoGates.length} gates for ${prompt.id}`
1492 | );
1493 | }
1494 | }
1495 |
1496 | /**
1497 | * NEW: Execute basic prompt with simple variable substitution (fastest)
1498 | * No framework processing, minimal overhead
1499 | */
1500 | private async executePrompt(
1501 | prompt: ConvertedPrompt,
1502 | args: Record<string, string>,
1503 | executionContext?: {
1504 | scopeId?: string;
1505 | scope?: 'execution' | 'session' | 'chain' | 'step';
1506 | }
1507 | ): Promise<ToolResponse> {
1508 | if (!this.currentExecutionState) {
1509 | throw new PromptError("No execution state available");
1510 | }
1511 |
1512 | this.currentExecutionState.status = "running";
1513 |
1514 | // Simple template processing without framework enhancement
1515 | let content = prompt.userMessageTemplate;
1516 | if (prompt.systemMessage) {
1517 | content = `[System: ${prompt.systemMessage}]\n\n${content}`;
1518 | }
1519 |
1520 | // Phase 4: Enhanced args without gate injection (gates now appended at end)
1521 | const enhancedArgs = args;
1522 |
1523 | // Phase 3: Inject session context for step result interpolation
1524 | const sessionEnhancedArgs = await this.injectSessionContext(enhancedArgs);
1525 |
1526 | // Fast variable substitution using modern template processor
1527 | content = processTemplate(content, sessionEnhancedArgs, {});
1528 |
1529 | // Phase 4: Enhanced gate validation for basic prompts (only when framework system is enabled)
1530 | let gateResults: GateValidationResult | null = null;
1531 | const frameworkEnabled = this.frameworkStateManager?.isFrameworkSystemEnabled();
1532 | const hasRequestedGates = (this.activeGateRequest?.gateIds?.length || 0) > 0;
1533 | const shouldValidate = frameworkEnabled || hasRequestedGates;
1534 | this.logger.info(
1535 | `🔍 [DEBUG] Framework system enabled: ${frameworkEnabled}, requestedGates=${hasRequestedGates}`
1536 | );
1537 |
1538 | if (shouldValidate) {
1539 | const gateValidation = await this.validateContentWithGates(prompt, content, sessionEnhancedArgs, 'prompt');
1540 | gateResults = gateValidation.validation;
1541 | this.logger.info(`🔍 [DEBUG] Gate validation result:`, {
1542 | hasGateResults: !!gateResults,
1543 | gateResultsType: typeof gateResults,
1544 | gateResultsValue: gateResults
1545 | });
1546 |
1547 | if (gateResults && !gateResults.passed) {
1548 | this.logger.debug(`Basic prompt gate validation failed for ${prompt.id}:`, gateResults.results);
1549 | // For basic prompts, we just log and continue
1550 | } else if (gateResults && gateResults.passed) {
1551 | this.logger.debug(`Basic prompt gate validation passed for ${prompt.id}`);
1552 | }
1553 | }
1554 |
1555 | // Update state and analytics
1556 | this.currentExecutionState.status = "completed";
1557 | this.currentExecutionState.metadata.endTime = Date.now();
1558 | // Store gate results in execution state for analytics
1559 | if (gateResults) {
1560 | (this.currentExecutionState.metadata as any).gateResults = gateResults;
1561 | }
1562 |
1563 | // Capture step result if this is part of a chain session
1564 | await this.captureStepResult(content, prompt);
1565 |
1566 | this.recordExecutionAnalytics();
1567 |
1568 | // Create execution context for response formatter
1569 | const executionId = `exec_${Date.now()}_${Math.random()
1570 | .toString(36)
1571 | .substr(2, 9)}`;
1572 | const activeFramework =
1573 | this.frameworkStateManager?.getActiveFramework()?.name;
1574 | const frameworkEnabledForContext =
1575 | this.frameworkStateManager?.isFrameworkSystemEnabled() || false;
1576 |
1577 | const formatterContext: FormatterExecutionContext = {
1578 | executionId,
1579 | executionType: "prompt",
1580 | startTime: this.currentExecutionState.metadata.startTime,
1581 | endTime: this.currentExecutionState.metadata.endTime || Date.now(),
1582 | frameworkUsed: activeFramework,
1583 | frameworkEnabled: frameworkEnabledForContext,
1584 | success: true,
1585 | };
1586 |
1587 | // FIXED: Add supplemental gate guidance for prompt mode (same as template mode)
1588 | let enhancedContent = content;
1589 | this.logger.info(`🔍 [DEBUG] Gate conditional logic:`, {
1590 | hasGateResults: !!gateResults,
1591 | gateResultsValue: gateResults,
1592 | willExecuteIfBranch: !!gateResults,
1593 | willExecuteElseBranch: !gateResults
1594 | });
1595 |
1596 | if (gateResults) {
1597 | this.logger.info(`🔀 [DEBUG] Taking IF branch (gateResults exists)`);
1598 |
1599 | // Get selected gates from validation - basic prompts use 'prompt' mode gates
1600 | const selectedGates = await this.getAdvancedGateSelection(prompt, 'prompt');
1601 | const frameworkContext = await this.getFrameworkExecutionContext(prompt);
1602 |
1603 | if (selectedGates.length > 0) {
1604 | const temporaryGates = this.getTemporaryGatesFromPrompt(prompt);
1605 | const supplementalGuidance = await this.getSupplementalGateGuidance(
1606 | selectedGates,
1607 | frameworkContext,
1608 | prompt,
1609 | temporaryGates,
1610 | executionContext
1611 | );
1612 | if (supplementalGuidance) {
1613 | enhancedContent = content + supplementalGuidance;
1614 | }
1615 | }
1616 | } else {
1617 | this.logger.info(`🔀 [DEBUG] Taking ELSE branch (no gateResults) - this should call our gate guidance renderer`);
1618 | // TEMP TEST: Force gate guidance even without validation results
1619 | const testGates = ['framework-compliance', 'educational-clarity'];
1620 | const frameworkContext = await this.getFrameworkExecutionContext(prompt);
1621 | const temporaryGates = this.getTemporaryGatesFromPrompt(prompt);
1622 |
1623 | const supplementalGuidance = await this.getSupplementalGateGuidance(
1624 | testGates,
1625 | frameworkContext,
1626 | prompt,
1627 | temporaryGates,
1628 | executionContext
1629 | );
1630 | if (supplementalGuidance) {
1631 | enhancedContent = content + supplementalGuidance;
1632 | } else {
1633 | enhancedContent = content + "(Gate manager returned empty guidance)";
1634 | }
1635 | }
1636 |
1637 | if (this.activeGateRequest) {
1638 | enhancedContent += this.formatGateStatus(gateResults);
1639 | }
1640 |
1641 | // Format response with structured data
1642 | const executionWarning = `⚠️ EXECUTION REQUIRED: The following content contains instructions that YOU must interpret and execute:\n\n`;
1643 |
1644 | return this.responseFormatter.formatPromptEngineResponse(
1645 | executionWarning + enhancedContent,
1646 | formatterContext,
1647 | {
1648 | includeAnalytics: true,
1649 | includeMetadata: true,
1650 | },
1651 | gateResults // Include gate validation results for basic prompts too
1652 | );
1653 | }
1654 |
1655 | /**
1656 | * Inject session context variables for template interpolation
1657 | */
1658 | private async injectSessionContext(args: Record<string, any>): Promise<Record<string, any>> {
1659 | const sessionId = (this.currentExecutionState?.metadata as any)?.sessionId;
1660 |
1661 | if (!sessionId) {
1662 | // No session context available
1663 | return args;
1664 | }
1665 |
1666 | try {
1667 | // Get session context from chain session manager
1668 | const sessionContext = this.chainSessionManager.getChainContext(sessionId);
1669 |
1670 | // Merge session context with existing args
1671 | // Session context takes precedence for step result variables
1672 | return {
1673 | ...args,
1674 | ...sessionContext
1675 | };
1676 | } catch (error) {
1677 | this.logger.warn(`Failed to inject session context for session ${sessionId}:`, error);
1678 | return args;
1679 | }
1680 | }
1681 |
1682 | /**
1683 | * Ensure chain session exists for chain execution
1684 | */
1685 | private async ensureChainSession(
1686 | convertedPrompt: ConvertedPrompt,
1687 | providedSessionId?: string,
1688 | forceRestart?: boolean,
1689 | originalArgs?: Record<string, any>
1690 | ): Promise<string> {
1691 | // Generate session ID if not provided
1692 | const sessionId = providedSessionId || `chain_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
1693 |
1694 | // Check if session exists and force restart is requested
1695 | if (forceRestart && this.chainSessionManager.hasActiveSession(sessionId)) {
1696 | this.chainSessionManager.clearSession(sessionId);
1697 | this.logger.debug(`Force restart: cleared existing session ${sessionId}`);
1698 | }
1699 |
1700 | // Create session if it doesn't exist
1701 | if (!this.chainSessionManager.hasActiveSession(sessionId)) {
1702 | // Get step count from chain definition
1703 | const stepCount = this.getChainStepCount(convertedPrompt);
1704 |
1705 | // Create new session
1706 | this.chainSessionManager.createSession(
1707 | sessionId,
1708 | convertedPrompt.id,
1709 | stepCount,
1710 | originalArgs || {}
1711 | );
1712 |
1713 | this.logger.info(
1714 | `Created new chain session ${sessionId} for chain ${convertedPrompt.id} with ${stepCount} steps`
1715 | );
1716 | }
1717 |
1718 | return sessionId;
1719 | }
1720 |
1721 | /**
1722 | * Get the number of steps in a chain
1723 | */
1724 | private getChainStepCount(convertedPrompt: ConvertedPrompt): number {
1725 | // For markdown-embedded chains, try to extract step count from chain definition
1726 | if (convertedPrompt.chainSteps) {
1727 | return convertedPrompt.chainSteps.length;
1728 | }
1729 |
1730 | // Fallback: try to parse from userMessageTemplate
1731 | if (convertedPrompt.userMessageTemplate) {
1732 | const stepMatches = convertedPrompt.userMessageTemplate.match(/## Step \d+|### Step \d+/g);
1733 | if (stepMatches) {
1734 | return stepMatches.length;
1735 | }
1736 | }
1737 |
1738 | // Default to 1 if we can't determine step count
1739 | this.logger.warn(`Could not determine step count for chain ${convertedPrompt.id}, defaulting to 1`);
1740 | return 1;
1741 | }
1742 |
1743 | /**
1744 | * Capture step result for chain session management
1745 | */
1746 | private async captureStepResult(content: string, prompt: ConvertedPrompt): Promise<void> {
1747 | const sessionId = (this.currentExecutionState?.metadata as any)?.sessionId;
1748 |
1749 | if (!sessionId) {
1750 | // No session ID, this is not part of a chain execution
1751 | return;
1752 | }
1753 |
1754 | // Check if this session exists and should capture results
1755 | if (!this.chainSessionManager.hasActiveSession(sessionId)) {
1756 | this.logger.debug(`Session ${sessionId} not found or inactive, skipping result capture`);
1757 | return;
1758 | }
1759 |
1760 | try {
1761 | // Get current session state to determine step number
1762 | const session = this.chainSessionManager.getSession(sessionId);
1763 | if (!session) {
1764 | this.logger.warn(`Session ${sessionId} not found during result capture`);
1765 | return;
1766 | }
1767 |
1768 | // For LLM-driven chains, we need to determine the step number
1769 | // This implementation assumes the step number is derived from current state
1770 | const currentStepNumber = session.state.currentStep;
1771 |
1772 | // Store the step result
1773 | const stepMetadata = {
1774 | promptId: prompt.id,
1775 | executionTime: Date.now() - (this.currentExecutionState?.metadata?.startTime || Date.now()),
1776 | contentLength: content.length,
1777 | timestamp: Date.now()
1778 | };
1779 |
1780 | this.chainSessionManager.updateSessionState(
1781 | sessionId,
1782 | currentStepNumber,
1783 | content,
1784 | stepMetadata
1785 | );
1786 |
1787 | this.logger.debug(
1788 | `Captured step ${currentStepNumber} result for session ${sessionId} (${content.length} chars)`
1789 | );
1790 | } catch (error) {
1791 | this.logger.error(`Failed to capture step result for session ${sessionId}:`, error);
1792 | }
1793 | }
1794 |
1795 | /**
1796 | * Execute template with full framework processing and gates
1797 | */
1798 | private async executeTemplateWithFramework(
1799 | prompt: ConvertedPrompt,
1800 | args: Record<string, string>,
1801 | enableGates: boolean,
1802 | executionContext?: {
1803 | scopeId?: string;
1804 | scope?: 'execution' | 'session' | 'chain' | 'step';
1805 | }
1806 | ): Promise<ToolResponse> {
1807 | if (!this.currentExecutionState) {
1808 | throw new PromptError("No execution state available");
1809 | }
1810 |
1811 | this.currentExecutionState.status = "running";
1812 |
1813 | // Process template with framework-enhanced system prompt injection
1814 | let content = prompt.userMessageTemplate;
1815 |
1816 | // FIXED: Get framework execution context for enhanced system prompt
1817 | const frameworkContext = await this.getFrameworkExecutionContext(prompt);
1818 | this.logger.debug(`[ENGINE DEBUG] Framework context result:`, {
1819 | hasFrameworkContext: !!frameworkContext,
1820 | frameworkContextType: frameworkContext ? typeof frameworkContext : 'null',
1821 | hasSystemPrompt: frameworkContext?.systemPrompt ? true : false,
1822 | systemPromptLength: frameworkContext?.systemPrompt?.length || 0
1823 | });
1824 |
1825 | if (prompt.systemMessage || frameworkContext) {
1826 | let systemPrompt = prompt.systemMessage || "";
1827 |
1828 | // FIXED: Enhance with framework-specific system prompt if available
1829 | if (frameworkContext) {
1830 | const frameworkSystemPrompt = frameworkContext.systemPrompt;
1831 | this.logger.debug(`[ENGINE DEBUG] Framework system prompt:`, {
1832 | hasFrameworkSystemPrompt: !!frameworkSystemPrompt,
1833 | frameworkSystemPromptLength: frameworkSystemPrompt?.length || 0,
1834 | frameworkSystemPromptPreview: frameworkSystemPrompt?.substring(0, 100) + '...'
1835 | });
1836 | if (frameworkSystemPrompt) {
1837 | systemPrompt = systemPrompt
1838 | ? `${frameworkSystemPrompt}\n\n${systemPrompt}`
1839 | : frameworkSystemPrompt;
1840 | }
1841 | }
1842 |
1843 | if (systemPrompt) {
1844 | content = `[System: ${systemPrompt}]\n\n${content}`;
1845 | }
1846 | }
1847 |
1848 | // Phase 4: Enhanced args without gate injection (gates now appended at end)
1849 | const enhancedArgs = args;
1850 |
1851 | // Template processing with special context and optional tools
1852 | const specialContext: Record<string, string> = {
1853 | previous_message: "{{previous_message}}",
1854 | };
1855 | if (prompt.tools) {
1856 | specialContext["tools_available"] = getAvailableTools();
1857 | }
1858 |
1859 | // Inject session context for step result interpolation
1860 | const sessionEnhancedArgs = await this.injectSessionContext(enhancedArgs);
1861 |
1862 | content = processTemplate(content, sessionEnhancedArgs, specialContext);
1863 |
1864 | // Phase 1.2: Post-execution gate validation with retry logic (only for template mode when gates are enabled)
1865 | let gateResults: GateValidationResult | null = null;
1866 | let selectedGates: string[] = [];
1867 | let retryAttempt = 0;
1868 | const gateModeForExecution = this.activeGateRequest?.gateMode || (enableGates ? 'enforce' : 'advise');
1869 | const maxRetries = gateModeForExecution === 'enforce' ? 2 : 0;
1870 |
1871 | if (enableGates) {
1872 | do {
1873 | const gateValidation = await this.validateContentWithGates(prompt, content, sessionEnhancedArgs, 'template');
1874 | gateResults = gateValidation.validation;
1875 | selectedGates = gateValidation.selectedGates;
1876 |
1877 | if (gateResults && !gateResults.passed && retryAttempt < maxRetries) {
1878 | retryAttempt++;
1879 | this.logger.warn(`Gate validation failed for ${prompt.id} (attempt ${retryAttempt}):`, gateResults.results);
1880 |
1881 | // Get retry hints from failed gates
1882 | const retryHints = this.getRetryHintsFromValidation(gateResults);
1883 | if (retryHints.length > 0) {
1884 | this.logger.debug(`Applying retry hints: ${retryHints.join(', ')}`);
1885 |
1886 | // Enhance args with retry hints for content regeneration
1887 | const retryEnhancedArgs = {
1888 | ...sessionEnhancedArgs,
1889 | retry_hints: retryHints.join('\n'),
1890 | previous_attempt: content.substring(0, 200) + '...',
1891 | improvement_focus: this.getImprovementFocus(gateResults)
1892 | };
1893 |
1894 | // Regenerate content with improvement hints
1895 | content = processTemplate(prompt.userMessageTemplate, retryEnhancedArgs, specialContext);
1896 | this.logger.debug(`Content regenerated for retry attempt ${retryAttempt}`);
1897 | } else {
1898 | // No actionable hints available, break retry loop
1899 | this.logger.debug(`No actionable retry hints available, accepting current result`);
1900 | break;
1901 | }
1902 | } else if (gateResults && gateResults.passed) {
1903 | this.logger.debug(`Gate validation passed for ${prompt.id}` + (retryAttempt > 0 ? ` after ${retryAttempt} retries` : ''));
1904 | break;
1905 | } else {
1906 | // Max retries reached
1907 | if (retryAttempt >= maxRetries) {
1908 | this.logger.warn(`Max retries (${maxRetries}) reached for ${prompt.id}, proceeding with current content`);
1909 | }
1910 | break;
1911 | }
1912 | } while (retryAttempt <= maxRetries);
1913 | }
1914 |
1915 | // Update state and analytics
1916 | this.currentExecutionState.status = "completed";
1917 | this.currentExecutionState.metadata.endTime = Date.now();
1918 | // Store gate results in execution state for analytics
1919 | if (gateResults) {
1920 | (this.currentExecutionState.metadata as any).gateResults = gateResults;
1921 | }
1922 | this.recordExecutionAnalytics();
1923 |
1924 | // Create execution context for response formatter
1925 | const executionId = `exec_${Date.now()}_${Math.random()
1926 | .toString(36)
1927 | .substr(2, 9)}`;
1928 | const activeFramework =
1929 | this.frameworkStateManager?.getActiveFramework()?.name;
1930 | const frameworkEnabledForContext =
1931 | this.frameworkStateManager?.isFrameworkSystemEnabled() || false;
1932 |
1933 | const formatterContext: FormatterExecutionContext = {
1934 | executionId,
1935 | executionType: "template",
1936 | startTime: this.currentExecutionState.metadata.startTime,
1937 | endTime: this.currentExecutionState.metadata.endTime || Date.now(),
1938 | frameworkUsed: activeFramework,
1939 | frameworkEnabled: frameworkEnabledForContext,
1940 | success: true,
1941 | };
1942 |
1943 | // Phase 4: Append supplemental gate guidance to content
1944 | let enhancedContent = content;
1945 |
1946 | if (gateResults && selectedGates.length > 0) {
1947 | const temporaryGates = this.getTemporaryGatesFromPrompt(prompt);
1948 | const supplementalGuidance = await this.getSupplementalGateGuidance(
1949 | selectedGates,
1950 | frameworkContext,
1951 | prompt,
1952 | temporaryGates,
1953 | executionContext
1954 | );
1955 | if (supplementalGuidance) {
1956 | enhancedContent = content + supplementalGuidance;
1957 | }
1958 | } else {
1959 | // TEMP TEST: Force gate guidance even without validation results (same as executePrompt)
1960 | const testGates = ['framework-compliance', 'educational-clarity'];
1961 | const temporaryGates = this.getTemporaryGatesFromPrompt(prompt);
1962 | const supplementalGuidance = await this.getSupplementalGateGuidance(
1963 | testGates,
1964 | frameworkContext,
1965 | prompt,
1966 | temporaryGates,
1967 | executionContext
1968 | );
1969 | if (supplementalGuidance) {
1970 | enhancedContent = enhancedContent + supplementalGuidance;
1971 | } else {
1972 | enhancedContent = enhancedContent + `\n--- GATE MANAGER RETURNED EMPTY ---\n`;
1973 | }
1974 | }
1975 |
1976 | if (this.activeGateRequest) {
1977 | enhancedContent += this.formatGateStatus(gateResults);
1978 | }
1979 |
1980 | // Format response with structured data
1981 | const executionWarning = `⚠️ EXECUTION REQUIRED: The following content contains instructions that YOU must interpret and execute:\n\n`;
1982 |
1983 | return this.responseFormatter.formatPromptEngineResponse(
1984 | executionWarning + enhancedContent,
1985 | formatterContext,
1986 | {
1987 | includeAnalytics: true,
1988 | includeMetadata: true,
1989 | },
1990 | gateResults // Include gate validation results
1991 | );
1992 | }
1993 |
1994 | // REMOVED: getGateInfo - migrated to ChainExecutor
1995 |
1996 | // REMOVED: generateMetadataSection - migrated to ChainExecutor
1997 |
1998 | /**
1999 | * Get supplemental gate guidance to append to responses (Phase 1 - Enhanced with intelligent category detection)
2000 | */
2001 | private async getSupplementalGateGuidance(
2002 | selectedGates: string[],
2003 | frameworkContext?: any,
2004 | prompt?: any,
2005 | temporaryGates?: Array<Omit<TemporaryGateDefinition, 'id' | 'created_at'>>,
2006 | executionContext?: {
2007 | scopeId?: string;
2008 | scope?: 'execution' | 'session' | 'chain' | 'step';
2009 | }
2010 | ): Promise<string> {
2011 | // Phase 1: Enhanced category detection
2012 | let categoryExtractionResult: CategoryExtractionResult;
2013 | if (prompt) {
2014 | categoryExtractionResult = extractPromptCategory(prompt, this.logger);
2015 | this.logger.info(`🏷️ [CATEGORY EXTRACTOR] Category detected:`, {
2016 | category: categoryExtractionResult.category,
2017 | source: categoryExtractionResult.source,
2018 | confidence: categoryExtractionResult.confidence,
2019 | promptId: prompt.id
2020 | });
2021 | } else {
2022 | // Fallback when prompt not available
2023 | categoryExtractionResult = {
2024 | category: 'general',
2025 | source: 'fallback',
2026 | confidence: 20,
2027 | sourceData: {}
2028 | };
2029 | this.logger.warn(`🏷️ [CATEGORY EXTRACTOR] No prompt provided, using fallback category`);
2030 | }
2031 |
2032 | console.log(`🎯 [CONSOLE DEBUG] getSupplementalGateGuidance called:`, {
2033 | selectedGatesCount: selectedGates.length,
2034 | selectedGates,
2035 | hasFrameworkContext: !!frameworkContext,
2036 | frameworkMethodology: frameworkContext?.selectedFramework?.methodology,
2037 | detectedCategory: categoryExtractionResult.category,
2038 | categorySource: categoryExtractionResult.source,
2039 | categoryConfidence: categoryExtractionResult.confidence
2040 | });
2041 | this.logger.info(`🎯 [GATE MANAGER] getSupplementalGateGuidance called:`, {
2042 | selectedGatesCount: selectedGates.length,
2043 | selectedGates,
2044 | hasFrameworkContext: !!frameworkContext,
2045 | frameworkMethodology: frameworkContext?.selectedFramework?.methodology,
2046 | detectedCategory: categoryExtractionResult.category,
2047 | categorySource: categoryExtractionResult.source
2048 | });
2049 |
2050 | // Phase 3: Enhanced gate selection with 5-level precedence and temporary gates
2051 | let finalSelectedGates = selectedGates;
2052 | let temporaryGateIds: string[] = [];
2053 |
2054 | // Step 1: Create temporary gates if provided
2055 | if (temporaryGates && temporaryGates.length > 0 && this.temporaryGateRegistry && executionContext) {
2056 | for (const tempGate of temporaryGates) {
2057 | try {
2058 | const gateId = this.temporaryGateRegistry.createTemporaryGate(
2059 | tempGate,
2060 | executionContext.scopeId
2061 | );
2062 | temporaryGateIds.push(gateId);
2063 | this.logger.info(`🚀 [TEMPORARY GATE] Created temporary gate:`, {
2064 | gateId,
2065 | name: tempGate.name,
2066 | scope: tempGate.scope,
2067 | scopeId: executionContext.scopeId
2068 | });
2069 | } catch (error) {
2070 | this.logger.error(`❌ [TEMPORARY GATE] Failed to create temporary gate:`, {
2071 | error: error instanceof Error ? error.message : String(error),
2072 | gateName: tempGate.name
2073 | });
2074 | }
2075 | }
2076 | }
2077 |
2078 | // Step 2: Apply 5-level precedence selection
2079 | if (prompt) {
2080 | const extractor = new CategoryExtractor(this.logger);
2081 | const frameworkGates = this.getFrameworkGates(frameworkContext);
2082 |
2083 | // Use enhanced precedence system with temporary gates
2084 | const intelligentSelection = extractor.selectGatesWithEnhancedPrecedence(
2085 | categoryExtractionResult,
2086 | frameworkGates,
2087 | selectedGates.length > 0 ? selectedGates : ['content-structure'], // fallback
2088 | temporaryGateIds, // temporary gates have highest precedence
2089 | categoryExtractionResult.gateConfiguration
2090 | );
2091 |
2092 | finalSelectedGates = intelligentSelection.selectedGates;
2093 |
2094 | this.logger.info(`🎯 [5-LEVEL PRECEDENCE] Applied enhanced gate selection:`, {
2095 | originalGates: selectedGates,
2096 | temporaryGates: temporaryGateIds,
2097 | finalGates: finalSelectedGates,
2098 | precedenceUsed: intelligentSelection.precedenceUsed,
2099 | reasoning: intelligentSelection.reasoning,
2100 | temporaryGatesApplied: intelligentSelection.temporaryGatesApplied
2101 | });
2102 | } else if (temporaryGateIds.length > 0) {
2103 | // No prompt context but we have temporary gates - include them
2104 | finalSelectedGates = [...selectedGates, ...temporaryGateIds];
2105 | this.logger.info(`🎯 [TEMPORARY GATES ONLY] Applied temporary gates without prompt context:`, {
2106 | originalGates: selectedGates,
2107 | temporaryGates: temporaryGateIds,
2108 | finalGates: finalSelectedGates
2109 | });
2110 | }
2111 |
2112 | if (finalSelectedGates.length === 0) {
2113 | this.logger.debug(`[GATE MANAGER] No gates selected after intelligent selection, returning empty guidance`);
2114 | return '';
2115 | }
2116 |
2117 | try {
2118 |
2119 | // NEW: Use role-based gate guidance renderer with intelligent category detection and gate selection (Phase 1 & 2)
2120 | const supplementalGuidance = await this.gateGuidanceRenderer.renderGuidance(
2121 | finalSelectedGates, // Use intelligently selected gates
2122 | {
2123 | framework: frameworkContext?.selectedFramework?.methodology || 'CAGEERF',
2124 | category: categoryExtractionResult.category, // Dynamic category based on intelligent detection
2125 | promptId: frameworkContext?.promptId
2126 | }
2127 | );
2128 |
2129 | this.logger.debug(`[GATE GUIDANCE RENDERER] Gate guidance renderer returned guidance:`, {
2130 | guidanceLength: supplementalGuidance.length,
2131 | hasContent: supplementalGuidance.length > 0
2132 | });
2133 |
2134 | return supplementalGuidance;
2135 | } catch (error) {
2136 | this.logger.error("Failed to get supplemental gate guidance:", error);
2137 | return '';
2138 | }
2139 | }
2140 |
2141 | /**
2142 | * Get framework-specific gates for intelligent selection
2143 | *
2144 | * Returns the universal framework-compliance gate for all frameworks.
2145 | * Future: Can add framework-specific quality gates alongside framework-compliance.
2146 | */
2147 | private getFrameworkGates(frameworkContext?: any): string[] {
2148 | if (!frameworkContext?.selectedFramework?.methodology) {
2149 | return [];
2150 | }
2151 |
2152 | const methodology = frameworkContext.selectedFramework.methodology;
2153 |
2154 | // All frameworks get universal framework-compliance gate
2155 | // Framework-specific gates can be added in future iterations
2156 | switch (methodology) {
2157 | case 'CAGEERF':
2158 | return ['framework-compliance'];
2159 | case 'ReACT':
2160 | return ['framework-compliance'];
2161 | case '5W1H':
2162 | return ['framework-compliance'];
2163 | case 'SCAMPER':
2164 | return ['framework-compliance'];
2165 | default:
2166 | return ['framework-compliance'];
2167 | }
2168 | }
2169 |
2170 | /**
2171 | * Extract gate title from guidance text
2172 | */
2173 | private extractGateTitle(guidanceText: string): string {
2174 | const lines = guidanceText.split('\n');
2175 | const titleLine = lines.find(line => line.includes('Guidelines') || line.includes(':'));
2176 | if (titleLine) {
2177 | return titleLine.replace(/\*\*/g, '').replace(/:/g, '').trim();
2178 | }
2179 | return 'Quality Guidelines';
2180 | }
2181 |
2182 | /**
2183 | * Simple prompt categorization for gate activation
2184 | */
2185 | private categorizePrompt(promptId: string): string {
2186 | // Basic categorization based on prompt ID patterns
2187 | if (promptId.includes("research") || promptId.includes("analysis")) {
2188 | return "research";
2189 | } else if (promptId.includes("code") || promptId.includes("development")) {
2190 | return "code";
2191 | } else if (
2192 | promptId.includes("content") ||
2193 | promptId.includes("documentation")
2194 | ) {
2195 | return "content_processing";
2196 | }
2197 | return "general";
2198 | }
2199 |
2200 | /**
2201 | * Get framework-specific gates for validation (Phase 4: Enhanced with advanced orchestration)
2202 | */
2203 | private async getAdvancedGateSelection(
2204 | prompt: ConvertedPrompt,
2205 | executionMode: 'prompt' | 'template' | 'chain',
2206 | semanticAnalysis?: any
2207 | ): Promise<string[]> {
2208 | this.logger.debug(`[GATE DEBUG] getAdvancedGateSelection called:`, {
2209 | promptId: prompt.id,
2210 | executionMode,
2211 | hasGateSelectionEngine: !!this.gateSelectionEngine,
2212 | hasSemanticAnalysis: !!semanticAnalysis
2213 | });
2214 |
2215 | if (!this.gateSelectionEngine) {
2216 | this.logger.debug(`[GATE DEBUG] No gate selection engine, using fallback gates`);
2217 | return this.mergeRequestedGates(this.getFallbackGates(prompt));
2218 | }
2219 |
2220 | try {
2221 | // Build gate selection criteria
2222 | const criteria: ExtendedGateSelectionCriteria = {
2223 | framework: this.frameworkStateManager?.getActiveFramework()?.methodology,
2224 | category: prompt.category || 'general',
2225 | promptId: prompt.id,
2226 | executionMode,
2227 | complexityLevel: this.assessPromptComplexity(prompt),
2228 | semanticAnalysis,
2229 | frameworkContext: this.frameworkStateManager?.isFrameworkSystemEnabled()
2230 | ? this.frameworkStateManager.getActiveFramework()
2231 | : undefined,
2232 | userPreferences: {
2233 | qualityFocus: 'balanced',
2234 | performanceMode: false,
2235 | strictValidation: true
2236 | }
2237 | };
2238 |
2239 | this.logger.debug(`[GATE DEBUG] Gate selection criteria:`, {
2240 | hasFrameworkContext: !!criteria.frameworkContext,
2241 | frameworkMethodology: criteria.frameworkContext?.methodology,
2242 | executionMode: criteria.executionMode,
2243 | complexityLevel: criteria.complexityLevel
2244 | });
2245 |
2246 | // Use gate selection engine for intelligent gate selection
2247 | const selection = await this.gateSelectionEngine.selectGates(criteria);
2248 |
2249 | this.logger.debug(`[GATE DEBUG] Advanced gate selection result:`, {
2250 | promptId: prompt.id,
2251 | selectedGates: selection.selectedGates,
2252 | gateCount: selection.selectedGates.length,
2253 | confidence: selection.confidence,
2254 | reasoning: selection.reasoning,
2255 | estimatedTime: selection.estimatedExecutionTime
2256 | });
2257 |
2258 | return this.mergeRequestedGates(selection.selectedGates);
2259 |
2260 | } catch (error) {
2261 | this.logger.error("Advanced gate selection failed, using fallback:", error);
2262 | const fallbackGates = this.getFallbackGates(prompt);
2263 | this.logger.debug(`[GATE DEBUG] Using fallback gates:`, { fallbackGates });
2264 | return this.mergeRequestedGates(fallbackGates);
2265 | }
2266 | }
2267 |
2268 | /**
2269 | * Fallback gate selection for when advanced orchestration is unavailable
2270 | */
2271 | private getFallbackGates(prompt: ConvertedPrompt): string[] {
2272 | // TEMP DEBUG: Add comprehensive logging
2273 | const isEnabled = this.frameworkStateManager?.isFrameworkSystemEnabled();
2274 | this.logger.debug(`[FALLBACK GATES DEBUG] Framework system enabled: ${isEnabled}`);
2275 |
2276 | if (!isEnabled) {
2277 | this.logger.debug(`[FALLBACK GATES DEBUG] Framework disabled, returning content-structure`);
2278 | return ['content-structure'];
2279 | }
2280 |
2281 | const activeFramework = this.frameworkStateManager?.getActiveFramework();
2282 | this.logger.debug(`[FALLBACK GATES DEBUG] Active framework:`, {
2283 | hasFramework: !!activeFramework,
2284 | methodology: activeFramework?.methodology,
2285 | frameworkObj: activeFramework
2286 | });
2287 |
2288 | if (!activeFramework) {
2289 | this.logger.debug(`[FALLBACK GATES DEBUG] No active framework, returning content-structure`);
2290 | return ['content-structure'];
2291 | }
2292 |
2293 | const gates: string[] = [];
2294 |
2295 | // Framework-specific gates based on methodology
2296 | switch (activeFramework.methodology) {
2297 | case 'CAGEERF':
2298 | gates.push('framework-compliance', 'technical-accuracy', 'content-structure');
2299 | break;
2300 | case 'ReACT':
2301 | gates.push('framework-compliance', 'educational-clarity');
2302 | break;
2303 | case '5W1H':
2304 | gates.push('framework-compliance', 'research-quality');
2305 | break;
2306 | case 'SCAMPER':
2307 | gates.push('framework-compliance', 'content-structure');
2308 | break;
2309 | }
2310 |
2311 | // Add category-specific gates
2312 | const category = this.categorizePrompt(prompt.id);
2313 | switch (category) {
2314 | case 'code':
2315 | gates.push('code-quality', 'security-awareness');
2316 | break;
2317 | case 'research':
2318 | gates.push('research-quality', 'technical-accuracy');
2319 | break;
2320 | case 'content_processing':
2321 | gates.push('content-structure', 'educational-clarity');
2322 | break;
2323 | }
2324 |
2325 | // Remove duplicates and return
2326 | const finalGates = [...new Set(gates)];
2327 | this.logger.debug(`[FALLBACK GATES DEBUG] Final gates returned:`, {
2328 | gatesArray: finalGates,
2329 | gateCount: finalGates.length
2330 | });
2331 | return finalGates;
2332 | }
2333 |
2334 | /**
2335 | * Assess prompt complexity for gate selection
2336 | */
2337 | private assessPromptComplexity(prompt: ConvertedPrompt): 'low' | 'medium' | 'high' {
2338 | const argCount = prompt.arguments?.length || 0;
2339 | const contentLength = prompt.userMessageTemplate?.length || 0;
2340 | const hasSystemMessage = Boolean(prompt.systemMessage);
2341 |
2342 | if (argCount >= 5 || contentLength > 1000 || hasSystemMessage) return 'high';
2343 | if (argCount >= 3 || contentLength > 500) return 'medium';
2344 | return 'low';
2345 | }
2346 |
2347 | /**
2348 | * Validate content with framework-specific gates (Phase 4: Enhanced with advanced orchestration)
2349 | */
2350 | private async validateContentWithGates(
2351 | prompt: ConvertedPrompt,
2352 | content: string,
2353 | promptArgs: Record<string, any>,
2354 | executionMode: 'prompt' | 'template' | 'chain' = 'template',
2355 | semanticAnalysis?: any
2356 | ): Promise<{ validation: GateValidationResult | null; selectedGates: string[] }> {
2357 | if (!this.engineValidator) {
2358 | this.logger.debug("EngineValidator not available for gate validation");
2359 | return { validation: null, selectedGates: [] };
2360 | }
2361 |
2362 | // Get advanced gate selection (Phase 4)
2363 | const suggestedGates = await this.getAdvancedGateSelection(prompt, executionMode, semanticAnalysis);
2364 |
2365 | if (suggestedGates.length === 0) {
2366 | this.logger.debug("No gates suggested for validation");
2367 | return { validation: { passed: true, results: [] }, selectedGates: [] };
2368 | }
2369 |
2370 | try {
2371 | const startTime = performance.now();
2372 | this.logger.debug(`Validating content with advanced gate selection: ${suggestedGates.join(', ')}`);
2373 |
2374 | const validationResult = await this.engineValidator.validateWithGates(
2375 | prompt,
2376 | promptArgs,
2377 | suggestedGates,
2378 | content // FIXED: Pass processed content for validation
2379 | );
2380 |
2381 | const executionTime = performance.now() - startTime;
2382 |
2383 | // Performance metrics now handled separately by GatePerformanceAnalyzer in system control
2384 |
2385 | return { validation: validationResult, selectedGates: suggestedGates };
2386 | } catch (error) {
2387 | this.logger.error("Gate validation failed:", error);
2388 |
2389 | // Performance metrics for failed validation now handled by GatePerformanceAnalyzer
2390 |
2391 | return { validation: { passed: false, results: [{ gate: 'system', passed: false, message: `Validation error: ${error}` }] }, selectedGates: suggestedGates };
2392 | }
2393 | }
2394 |
2395 | /**
2396 | * Extract retry hints from gate validation results (Phase 3 implementation)
2397 | */
2398 | private getRetryHintsFromValidation(gateResults: GateValidationResult): string[] {
2399 | const hints: string[] = [];
2400 |
2401 | for (const result of gateResults.results) {
2402 | if (!result.passed && result.message) {
2403 | // Convert gate failure messages to actionable hints
2404 | const hint = this.convertGateMessageToHint(result.gate, result.message);
2405 | if (hint) {
2406 | hints.push(hint);
2407 | }
2408 | }
2409 | }
2410 |
2411 | return hints;
2412 | }
2413 |
2414 | /**
2415 | * Convert gate failure message to actionable retry hint
2416 | */
2417 | private convertGateMessageToHint(gateId: string, message: string): string | null {
2418 | // Convert specific gate failures to actionable improvement hints
2419 | switch (gateId) {
2420 | case 'technical-accuracy':
2421 | return 'Include specific version numbers, official documentation references, and technical specifications';
2422 | case 'content-structure':
2423 | return 'Organize content with clear headers, logical flow, and structured sections';
2424 | case 'framework-compliance':
2425 | return 'Follow the active methodology framework structure and include all required sections';
2426 | case 'research-quality':
2427 | return 'Include credible sources, evidence-based statements, and factual accuracy';
2428 | case 'educational-clarity':
2429 | return 'Use clear explanations, provide examples, and ensure concepts are well-explained';
2430 | case 'code-quality':
2431 | return 'Include proper syntax, error handling, and follow coding best practices';
2432 | case 'security-awareness':
2433 | return 'Address security considerations, validate inputs, and follow security best practices';
2434 | default:
2435 | // Generic hint based on message content
2436 | if (message.toLowerCase().includes('length')) {
2437 | return 'Provide more detailed and comprehensive content';
2438 | } else if (message.toLowerCase().includes('structure')) {
2439 | return 'Improve content organization and structure';
2440 | } else if (message.toLowerCase().includes('quality')) {
2441 | return 'Enhance content quality and accuracy';
2442 | }
2443 | return `Address validation concern: ${message}`;
2444 | }
2445 | }
2446 |
2447 | /**
2448 | * Get improvement focus based on failed gates
2449 | */
2450 | private getImprovementFocus(gateResults: GateValidationResult): string {
2451 | const failedGates = gateResults.results.filter(r => !r.passed).map(r => r.gate);
2452 |
2453 | if (failedGates.includes('technical-accuracy')) {
2454 | return 'Technical accuracy and precision';
2455 | } else if (failedGates.includes('framework-compliance')) {
2456 | return 'Methodology framework compliance';
2457 | } else if (failedGates.includes('content-structure')) {
2458 | return 'Content organization and structure';
2459 | } else if (failedGates.length > 1) {
2460 | return 'Multiple quality aspects';
2461 | } else {
2462 | return 'Content quality improvement';
2463 | }
2464 | }
2465 |
2466 | /**
2467 | * Record execution analytics using event-driven architecture
2468 | */
2469 | private recordExecutionAnalytics(): void {
2470 | if (!this.currentExecutionState) {
2471 | this.logger.debug(
2472 | "RecordExecutionAnalytics called but currentExecutionState is null"
2473 | );
2474 | return;
2475 | }
2476 |
2477 | if (!this.analyticsService) {
2478 | this.logger.debug(
2479 | "Analytics service not available - skipping analytics recording"
2480 | );
2481 | return;
2482 | }
2483 |
2484 | const duration =
2485 | (this.currentExecutionState.metadata.endTime || Date.now()) -
2486 | this.currentExecutionState.metadata.startTime;
2487 |
2488 | const executionData: ExecutionData = {
2489 | executionId: `exec_${Date.now()}_${Math.random()
2490 | .toString(36)
2491 | .substr(2, 9)}`,
2492 | executionType: this.currentExecutionState.metadata.executionMode as
2493 | | "prompt"
2494 | | "template"
2495 | | "chain",
2496 | startTime: this.currentExecutionState.metadata.startTime,
2497 | endTime: this.currentExecutionState.metadata.endTime || Date.now(),
2498 | executionTime: duration,
2499 | success: this.currentExecutionState.status === "completed",
2500 | frameworkUsed: this.getActiveFrameworkId(),
2501 | frameworkEnabled:
2502 | this.frameworkStateManager?.isFrameworkSystemEnabled() || false,
2503 | stepsExecuted: (this.currentExecutionState.metadata as any).stepsExecuted,
2504 | sessionId: (this.currentExecutionState.metadata as any).sessionId,
2505 | toolName: "prompt_engine",
2506 | error:
2507 | this.currentExecutionState.status === "failed"
2508 | ? (this.currentExecutionState as any).error
2509 | : undefined,
2510 | memoryUsage: {
2511 | heapUsed: process.memoryUsage().heapUsed,
2512 | heapTotal: process.memoryUsage().heapTotal,
2513 | external: process.memoryUsage().external,
2514 | },
2515 | };
2516 |
2517 | // Record execution analytics via event
2518 | this.analyticsService.recordExecution(executionData);
2519 |
2520 | // Store in history for local access (keep limited history)
2521 | this.executionHistory.push({ ...this.currentExecutionState });
2522 | if (this.executionHistory.length > 100) {
2523 | this.executionHistory.shift();
2524 | }
2525 |
2526 | this.logger.debug(
2527 | `Analytics recorded: ${executionData.executionType} execution (${duration}ms, success: ${executionData.success})`
2528 | );
2529 | }
2530 |
2531 | /**
2532 | * Get active framework ID
2533 | */
2534 | private getActiveFrameworkId(): string | undefined {
2535 | if (!this.frameworkStateManager?.isFrameworkSystemEnabled()) {
2536 | return undefined;
2537 | }
2538 | return this.frameworkStateManager?.getCurrentState().activeFramework;
2539 | }
2540 |
2541 | /**
2542 | * Get execution analytics from analytics service
2543 | */
2544 | getAnalytics() {
2545 | if (this.analyticsService) {
2546 | return this.analyticsService.getExecutionStats();
2547 | }
2548 |
2549 | // Fallback for backward compatibility
2550 | return {
2551 | totalExecutions: 0,
2552 | successfulExecutions: 0,
2553 | failedExecutions: 0,
2554 | averageExecutionTime: 0,
2555 | executionsByMode: {
2556 | prompt: 0,
2557 | template: 0,
2558 | chain: 0,
2559 | },
2560 | executionsByTool: {
2561 | prompt_engine: 0,
2562 | prompt_manager: 0,
2563 | system_control: 0,
2564 | },
2565 | lastUpdated: Date.now(),
2566 | };
2567 | }
2568 |
2569 | /**
2570 | * Get parsing system statistics for monitoring
2571 | */
2572 | getParsingStats() {
2573 | return {
2574 | commandParser: this.parsingSystem.commandParser.getStats(),
2575 | argumentParser: this.parsingSystem.argumentParser.getStats(),
2576 | contextResolver: this.parsingSystem.contextResolver.getStats(),
2577 | };
2578 | }
2579 |
2580 | /**
2581 | * Reset parsing statistics
2582 | */
2583 | resetParsingStats(): void {
2584 | this.parsingSystem.commandParser.resetStats();
2585 | this.parsingSystem.argumentParser.resetStats();
2586 | this.parsingSystem.contextResolver.resetStats();
2587 | this.logger.debug("Parsing system statistics reset");
2588 | }
2589 |
2590 | /**
2591 | * Error handling helper
2592 | */
2593 | private handleError(error: unknown, context: string): ToolResponse {
2594 | utilsHandleError(error, context, this.logger);
2595 |
2596 | return this.responseFormatter.formatErrorResponse(
2597 | error instanceof Error ? error : String(error),
2598 | {
2599 | tool: "prompt_engine",
2600 | operation: context,
2601 | },
2602 | {
2603 | includeStructuredData: true,
2604 | }
2605 | );
2606 | }
2607 |
2608 | // REMOVED: executeChainWithDualSupport - migrated to ChainExecutor
2609 |
2610 | /**
2611 | * MIGRATION: Chain management commands - deprecated scaffolding removed
2612 | */
2613 | // REMOVED: executeChainManagement - migrated to ChainExecutor
2614 | // REMOVED: handleScaffoldCommand (~56 lines) - deprecated scaffolding functionality
2615 |
2616 | // REMOVED: handleConvertCommand (~42 lines) - deprecated chain conversion functionality
2617 |
2618 | /**
2619 | * Handle validate command for markdown-embedded chains
2620 | */
2621 | // REMOVED: handleValidateCommand - migrated to ChainExecutor
2622 |
2623 | /**
2624 | * Handle list chains command
2625 | */
2626 | // REMOVED: handleListChainsCommand - migrated to ChainExecutor
2627 |
2628 | // REMOVED: handleListTemplatesCommand (~55 lines) - scaffolding system deprecated
2629 | // Migration: Use `prompt_manager action=list filter=category:analysis` for organized prompt discovery
2630 |
2631 | // REMOVED: handleDiscoverWorkflowsCommand (~50 lines) - scaffolding system deprecated
2632 | // Migration: Use `prompt_manager action=list filter="intent:debugging category:development"` for intelligent discovery
2633 |
2634 | // REMOVED: handleScaffoldUsingCommand (~135 lines) - deprecated workflow scaffolding functionality
2635 | // REMOVED: createChainDefinitionFromTemplate (~40 lines) - deprecated template creation functionality
2636 |
2637 | // REMOVED: handleChainEditCommand (~25 lines) - deprecated chain editing functionality
2638 | // Migration: Chain editing is no longer needed with markdown-embedded chains
2639 | }
2640 |
2641 | /**
2642 | * Create consolidated prompt engine with enhanced parsing system
2643 | */
2644 | export function createConsolidatedPromptEngine(
2645 | logger: Logger,
2646 | mcpServer: any,
2647 | promptManager: PromptManager,
2648 | configManager: ConfigManager,
2649 | semanticAnalyzer: ContentAnalyzer,
2650 | conversationManager: ConversationManager,
2651 | textReferenceManager: TextReferenceManager,
2652 | mcpToolsManager?: any
2653 | // Phase 3: Removed executionCoordinator parameter - using LLM-driven chain model
2654 | ): ConsolidatedPromptEngine {
2655 | const engine = new ConsolidatedPromptEngine(
2656 | logger,
2657 | mcpServer,
2658 | promptManager,
2659 | configManager,
2660 | semanticAnalyzer,
2661 | conversationManager,
2662 | textReferenceManager,
2663 | // Phase 3: Legacy gateEvaluationService removed - using lightweight system only
2664 | mcpToolsManager
2665 | // Phase 3: Removed executionCoordinator parameter
2666 | );
2667 |
2668 | logger.info("ConsolidatedPromptEngine created with enhanced features:");
2669 | logger.info("- Unified multi-strategy command parsing");
2670 | logger.info("- Advanced argument processing pipeline");
2671 | logger.info(
2672 | "- Optional gate evaluation service for template-driven verification"
2673 | );
2674 | logger.info("- Intelligent context resolution system");
2675 | logger.info("- Backward compatibility with legacy parsing");
2676 |
2677 | return engine;
2678 | }
2679 |
```