snow-flow 3.4.35 → 3.4.39

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +412 -287
  2. package/dist/cli/deploy-artifact.js +2 -2
  3. package/dist/mcp/servicenow-deployment-mcp.js +1 -1
  4. package/dist/mcp/servicenow-mcp-server.js +2 -2
  5. package/dist/mcp/shared/mcp-logger.js +6 -12
  6. package/dist/queen/agent-factory.js +134 -52
  7. package/dist/queen/servicenow-queen.d.ts +127 -2
  8. package/dist/queen/servicenow-queen.js +978 -618
  9. package/dist/services/widget-deployment-service.d.ts +1 -1
  10. package/dist/services/widget-deployment-service.js +1 -1
  11. package/dist/templates/claude-md-template.d.ts +1 -1
  12. package/dist/templates/claude-md-template.js +2 -2
  13. package/dist/types/servicenow.types.d.ts +1 -1
  14. package/dist/utils/dependency-detector.d.ts +1 -1
  15. package/dist/utils/dependency-detector.js +1 -1
  16. package/dist/utils/servicenow-client.d.ts +1 -1
  17. package/dist/utils/servicenow-client.js +4 -8
  18. package/package.json +1 -1
  19. package/website/components/README.md +419 -0
  20. package/website/components/code-display/CodeDisplay.css +583 -0
  21. package/website/components/code-display/CodeDisplay.html +200 -0
  22. package/website/components/code-display/CodeDisplay.js +375 -0
  23. package/website/components/code-display/CodeDisplay.jsx +268 -0
  24. package/website/components/demo/ComponentLibraryDemo.html +845 -0
  25. package/website/components/feature-cards/FeatureCards.css +573 -0
  26. package/website/components/feature-cards/FeatureCards.html +247 -0
  27. package/website/components/feature-cards/FeatureCards.js +382 -0
  28. package/website/components/feature-cards/FeatureCards.jsx +235 -0
  29. package/website/components/hero/Hero.css +558 -0
  30. package/website/components/hero/Hero.html +98 -0
  31. package/website/components/hero/Hero.js +415 -0
  32. package/website/components/hero/Hero.jsx +214 -0
  33. package/website/components/interactive/InteractiveElements.css +776 -0
  34. package/website/components/interactive/InteractiveElements.html +283 -0
  35. package/website/components/interactive/InteractiveElements.js +489 -0
  36. package/website/components/interactive/InteractiveElements.jsx +444 -0
  37. package/website/components/layout/LayoutComponents.css +697 -0
  38. package/website/components/layout/LayoutComponents.html +374 -0
  39. package/website/components/layout/LayoutComponents.js +447 -0
  40. package/website/components/layout/LayoutComponents.jsx +379 -0
  41. package/website/components/navigation/Navigation.css +383 -0
  42. package/website/components/navigation/Navigation.html +89 -0
  43. package/website/components/navigation/Navigation.js +248 -0
  44. package/website/components/navigation/Navigation.jsx +124 -0
  45. package/website/css/animations.css +854 -0
  46. package/website/css/style.css +916 -948
  47. package/website/index.html +394 -424
  48. package/website/js/animations.js +707 -0
  49. package/website/js/main.js +310 -383
  50. package/website/mcp-servers.html +310 -0
@@ -3,6 +3,39 @@
3
3
  * ServiceNow Queen Agent
4
4
  * Central coordination point for the ServiceNow hive-mind
5
5
  */
6
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
7
+ if (k2 === undefined) k2 = k;
8
+ var desc = Object.getOwnPropertyDescriptor(m, k);
9
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
10
+ desc = { enumerable: true, get: function() { return m[k]; } };
11
+ }
12
+ Object.defineProperty(o, k2, desc);
13
+ }) : (function(o, m, k, k2) {
14
+ if (k2 === undefined) k2 = k;
15
+ o[k2] = m[k];
16
+ }));
17
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
18
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
19
+ }) : function(o, v) {
20
+ o["default"] = v;
21
+ });
22
+ var __importStar = (this && this.__importStar) || (function () {
23
+ var ownKeys = function(o) {
24
+ ownKeys = Object.getOwnPropertyNames || function (o) {
25
+ var ar = [];
26
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
27
+ return ar;
28
+ };
29
+ return ownKeys(o);
30
+ };
31
+ return function (mod) {
32
+ if (mod && mod.__esModule) return mod;
33
+ var result = {};
34
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
35
+ __setModuleDefault(result, mod);
36
+ return result;
37
+ };
38
+ })();
6
39
  Object.defineProperty(exports, "__esModule", { value: true });
7
40
  exports.ServiceNowQueen = void 0;
8
41
  const queen_memory_1 = require("./queen-memory");
@@ -13,6 +46,7 @@ const theme_manager_1 = require("../utils/theme-manager");
13
46
  const dependency_detector_1 = require("../utils/dependency-detector");
14
47
  // Gap Analysis Engine removed - using direct MCP approach
15
48
  const logger_1 = require("../utils/logger");
49
+ const crypto = __importStar(require("crypto"));
16
50
  class ServiceNowQueen {
17
51
  constructor(config = {}) {
18
52
  this.config = {
@@ -38,12 +72,38 @@ class ServiceNowQueen {
38
72
  }
39
73
  }
40
74
  /**
41
- * Main entry point: Execute ServiceNow objective with MCP-FIRST workflow
75
+ * Main entry point: Execute ServiceNow objective with STRATEGIC ORCHESTRATION
76
+ *
77
+ * This is where the Queen Agent demonstrates true helicopter-view thinking:
78
+ * - Deep problem analysis beyond surface requirements
79
+ * - Strategic risk assessment and mitigation planning
80
+ * - Holistic solution architecture considering all stakeholders
81
+ * - Proactive bottleneck identification and resolution
82
+ * - Comprehensive orchestration of specialized agents
42
83
  */
43
84
  async executeObjective(objective) {
44
85
  const taskId = this.generateTaskId();
45
86
  const startTime = Date.now();
46
87
  try {
88
+ // 🧠 STRATEGIC PHASE 1: DEEP PROBLEM ANALYSIS
89
+ this.logger.info(`👑 QUEEN STRATEGIC ANALYSIS INITIATED`);
90
+ this.logger.info(`🎯 Objective: ${objective}`);
91
+ this.logger.info(`🧠 Analyzing: What is the REAL problem we're solving here?`);
92
+ // Analyze what the user ACTUALLY needs vs what they asked for
93
+ const problemAnalysis = await this.performDeepProblemAnalysis(objective);
94
+ this.logger.info(`📊 Problem Complexity: ${problemAnalysis.complexity} | Business Impact: ${problemAnalysis.businessImpact}`);
95
+ this.logger.info(`🎯 Core Problem: ${problemAnalysis.coreProblem}`);
96
+ this.logger.info(`👥 Stakeholders: ${problemAnalysis.stakeholders.join(', ')}`);
97
+ // 🧠 STRATEGIC PHASE 2: RISK & CONSTRAINT ASSESSMENT
98
+ this.logger.info(`🔍 STRATEGIC RISK ASSESSMENT`);
99
+ const riskAssessment = await this.performRiskAssessment(objective, problemAnalysis);
100
+ this.logger.info(`⚠️ Risk Level: ${riskAssessment.overallRisk} | Critical Risks: ${riskAssessment.criticalRisks.length}`);
101
+ if (riskAssessment.criticalRisks.length > 0) {
102
+ this.logger.info(`🚨 CRITICAL RISKS IDENTIFIED:`);
103
+ riskAssessment.criticalRisks.forEach(risk => {
104
+ this.logger.info(` • ${risk.description} (Impact: ${risk.impact}, Likelihood: ${risk.likelihood})`);
105
+ });
106
+ }
47
107
  if (this.config.debugMode) {
48
108
  this.logger.info(`🎯 Queen analyzing objective: ${objective}`);
49
109
  this.logger.info(`🚨 ENFORCING MCP-FIRST WORKFLOW`);
@@ -107,279 +167,215 @@ class ServiceNowQueen {
107
167
  status: 'analyzing'
108
168
  };
109
169
  this.activeTasks.set(taskId, task);
110
- // 🚨 PHASE 5: INTELLIGENT GAP ANALYSIS (Beyond MCP Tools)
111
- this.logger.info('🧠 Step 4: Running Intelligent Gap Analysis...');
112
- // Gap analysis now integrated into MCP workflow
113
- try {
114
- // Gap analysis handled by MCP tools directly
115
- autoPermissions: this.config.autoPermissions,
116
- environment;
117
- 'development',
118
- enableAutomation;
119
- true,
120
- includeManualGuides;
121
- true,
122
- riskTolerance;
123
- 'medium';
124
- }
125
- finally { }
126
- ;
127
- this.logger.info(`📊 Gap Analysis Complete:`);
128
- this.logger.info(` • Total Requirements: ${gapAnalysisResult.totalRequirements}`);
129
- this.logger.info(` • MCP Coverage: ${gapAnalysisResult.mcpCoverage.coveragePercentage}%`);
130
- this.logger.info(` • Automated: ${gapAnalysisResult.summary.successfulAutomation} configurations`);
131
- this.logger.info(` • Manual Work: ${gapAnalysisResult.summary.requiresManualWork} items`);
132
- // Display manual instructions if needed
133
- if (gapAnalysisResult.summary.requiresManualWork > 0) {
134
- this.logger.info('\n📋 Manual Configuration Required:');
135
- gapAnalysisResult.nextSteps.manual.forEach(step => this.logger.info(` • ${step}`));
136
- if (gapAnalysisResult.manualGuides) {
137
- this.logger.info('\n📚 Detailed manual guides available in gap _analysis result');
138
- }
170
+ // 🧠 PHASE 5: STRATEGIC SOLUTION ARCHITECTURE
171
+ this.logger.info(`🧠 Strategic Solution Architecture based on analysis...`);
172
+ this.logger.info(`🎯 Mitigation Strategies: ${riskAssessment.mitigationStrategies.join(', ')}`);
173
+ // Strategic solution design based on deep analysis
174
+ const solutionArchitecture = await this.designSolutionArchitecture(problemAnalysis, riskAssessment);
175
+ this.logger.info(`🏗️ Solution Architecture: ${solutionArchitecture.approach}`);
176
+ this.logger.info(`👥 Recommended Team: ${solutionArchitecture.recommendedAgents.join(', ')}`);
177
+ // Store strategic analysis in task
178
+ task.strategicAnalysis = {
179
+ problemAnalysis,
180
+ riskAssessment,
181
+ solutionArchitecture
182
+ };
183
+ // Phase 6: Spawn optimal agent swarm
184
+ const agents = this.spawnOptimalSwarm(task, _analysis);
185
+ // Phase 7: Execute coordinated deployment
186
+ task.status = 'executing';
187
+ const result = await this.coordinateExecution(task, agents, _analysis);
188
+ // Phase 8: Learn from execution
189
+ const duration = Date.now() - startTime;
190
+ this.learnFromExecution(task, agents, result, duration, null);
191
+ task.status = 'completed';
192
+ task.result = result;
193
+ if (this.config.debugMode) {
194
+ this.logger.info(`✅ Queen completed objective in ${duration}ms`);
139
195
  }
140
- // Display automation successes
141
- if (gapAnalysisResult.summary.successfulAutomation > 0) {
142
- this.logger.info('\n✅ Automated Configurations:');
143
- gapAnalysisResult.nextSteps.automated.forEach(step => this.logger.info(` • ${step}`));
196
+ return result;
197
+ }
198
+ catch (error) {
199
+ const duration = Date.now() - startTime;
200
+ await this.handleExecutionFailure(taskId, objective, error, duration);
201
+ throw error;
202
+ }
203
+ finally {
204
+ this.cleanupTask(taskId);
205
+ }
206
+ }
207
+ spawnOptimalSwarm(task, _analysis) {
208
+ if (this.config.debugMode) {
209
+ this.logger.info(`🐛 Spawning swarm for ${task.type} task (complexity: ${_analysis.estimatedComplexity})`);
210
+ }
211
+ // Use learned patterns or optimal sequence
212
+ const agentTypes = _analysis.suggestedPattern?.agentSequence ||
213
+ this.agentFactory.getOptimalAgentSequence(task.type, _analysis.estimatedComplexity);
214
+ // Spawn agent swarm
215
+ const agents = this.agentFactory.spawnAgentSwarm(agentTypes, task.id);
216
+ if (this.config.debugMode) {
217
+ this.logger.info(`👥 Spawned ${agents.length} agents: ${agents.map(a => a.type).join(', ')}`);
218
+ }
219
+ return agents;
220
+ }
221
+ async coordinateExecution(task, agents, _analysis) {
222
+ const results = [];
223
+ try {
224
+ // Execute agents in optimal sequence
225
+ if (this.shouldExecuteInParallel(agents)) {
226
+ results.push(...await this.executeAgentsInParallel(agents, task.objective));
144
227
  }
145
- // Display recommendations
146
- if (gapAnalysisResult.nextSteps.recommendations.length > 0) {
147
- this.logger.info('\n💡 Recommendations:');
148
- gapAnalysisResult.nextSteps.recommendations.forEach(rec => this.logger.info(` • ${rec}`));
228
+ else {
229
+ results.push(...await this.executeAgentsSequentially(agents, task.objective));
149
230
  }
150
- // Store gap _analysis result in task for later reference
151
- task.gapAnalysis = gapAnalysisResult;
152
- }
153
- catch (gapError) {
154
- console.warn(`⚠️ Gap Analysis failed: ${gapError instanceof Error ? gapError.message : 'Unknown error'}`);
155
- this.logger.info('🔄 Continuing with standard MCP workflow...');
156
- }
157
- // Phase 6: Spawn optimal agent swarm
158
- const agents = this.spawnOptimalSwarm(task, _analysis);
159
- // Phase 7: Execute coordinated deployment
160
- task.status = 'executing';
161
- const result = await this.coordinateExecution(task, agents, _analysis);
162
- // Phase 8: Learn from execution
163
- const duration = Date.now() - startTime;
164
- this.learnFromExecution(task, agents, result, duration, null);
165
- task.status = 'completed';
166
- task.result = result;
167
- if (this.config.debugMode) {
168
- this.logger.info(`✅ Queen completed objective in ${duration}ms`);
231
+ // Coordinate final deployment using MCP tools
232
+ const deploymentResult = await this.executeFinalDeployment(task, results, _analysis);
233
+ return {
234
+ taskId: task.id,
235
+ objective: task.objective,
236
+ agentResults: results,
237
+ deploymentResult,
238
+ artifacts: task.artifacts
239
+ };
240
+ }
241
+ catch (error) {
242
+ // Attempt recovery or fallback
243
+ return await this.attemptRecovery(task, agents, error);
169
244
  }
170
- return result;
171
245
  }
172
- catch(error) {
173
- const duration = Date.now() - startTime;
174
- await this.handleExecutionFailure(taskId, objective, error, duration);
175
- throw error;
246
+ shouldExecuteInParallel(agents) {
247
+ // Parallel execution for independent agents
248
+ const independentAgents = ['researcher', 'tester', 'script-writer'];
249
+ return agents.some(agent => independentAgents.includes(agent.type));
176
250
  }
177
- }
178
- exports.ServiceNowQueen = ServiceNowQueen;
179
- try { }
180
- finally {
181
- this.cleanupTask(taskId);
182
- }
183
- spawnOptimalSwarm(task, types_1.ServiceNowTask, _analysis, types_1.TaskAnalysis);
184
- types_1.Agent[];
185
- {
186
- if (this.config.debugMode) {
187
- this.logger.info(`🐛 Spawning swarm for ${task.type} task (complexity: ${_analysis.estimatedComplexity})`);
188
- }
189
- // Use learned patterns or optimal sequence
190
- const agentTypes = _analysis.suggestedPattern?.agentSequence ||
191
- this.agentFactory.getOptimalAgentSequence(task.type, _analysis.estimatedComplexity);
192
- // Spawn agent swarm
193
- const agents = this.agentFactory.spawnAgentSwarm(agentTypes, task.id);
194
- if (this.config.debugMode) {
195
- this.logger.info(`👥 Spawned ${agents.length} agents: ${agents.map(a => a.type).join(', ')}`);
196
- }
197
- return agents;
198
- }
199
- async;
200
- coordinateExecution(task, types_1.ServiceNowTask, agents, types_1.Agent[], _analysis, types_1.TaskAnalysis);
201
- Promise < any > {
202
- const: results, any, []: = [],
203
- try: {
204
- : .shouldExecuteInParallel(agents)
205
- }
206
- };
207
- {
208
- results.push(...await this.executeAgentsInParallel(agents, task.objective));
209
- }
210
- {
211
- results.push(...await this.executeAgentsSequentially(agents, task.objective));
212
- }
213
- // Coordinate final deployment using MCP tools
214
- const deploymentResult = await this.executeFinalDeployment(task, results, _analysis);
215
- return {
216
- taskId: task.id,
217
- objective: task.objective,
218
- agentResults: results,
219
- deploymentResult,
220
- artifacts: task.artifacts
221
- };
222
- try { }
223
- catch (error) {
224
- // Attempt recovery or fallback
225
- return await this.attemptRecovery(task, agents, error);
226
- }
227
- shouldExecuteInParallel(agents, types_1.Agent[]);
228
- boolean;
229
- {
230
- // Parallel execution for independent agents
231
- const independentAgents = ['researcher', 'tester', 'script-writer'];
232
- return agents.some(agent => independentAgents.includes(agent.type));
233
- }
234
- async;
235
- executeAgentsInParallel(agents, types_1.Agent[], objective, string);
236
- Promise < any[] > {
237
- : .config.debugMode
238
- };
239
- {
240
- this.logger.info('⚡ Executing agents in parallel');
241
- }
242
- const promises = agents.map(agent => this.agentFactory.executeAgentTask(agent.id, objective));
243
- return await Promise.all(promises);
244
- async;
245
- executeAgentsSequentially(agents, types_1.Agent[], objective, string);
246
- Promise < any[] > {
247
- : .config.debugMode
248
- };
249
- {
250
- this.logger.info('🔄 Executing agents sequentially');
251
- }
252
- const results = [];
253
- for (const agent of agents) {
254
- const result = await this.agentFactory.executeAgentTask(agent.id, objective);
255
- results.push(result);
256
- // Allow agents to coordinate between executions
257
- this.facilitateAgentCoordination(agent, results);
258
- }
259
- return results;
260
- facilitateAgentCoordination(currentAgent, types_1.Agent, previousResults, any[]);
261
- void {
262
- // Send relevant results to collaborative agents
263
- const: activeAgents = this.agentFactory.getActiveAgents(),
264
- for(, agent, of, activeAgents) {
265
- if (agent.id !== currentAgent.id) {
266
- this.agentFactory.sendAgentMessage(currentAgent.id, agent.id, 'result', {
267
- results: previousResults.slice(-1)[0], // Latest result
268
- fromAgent: currentAgent.type
269
- });
251
+ async executeAgentsInParallel(agents, objective) {
252
+ if (this.config.debugMode) {
253
+ this.logger.info('⚡ Executing agents in parallel');
270
254
  }
255
+ const promises = agents.map(agent => this.agentFactory.executeAgentTask(agent.id, objective));
256
+ return await Promise.all(promises);
271
257
  }
272
- };
273
- async;
274
- executeFinalDeployment(task, types_1.ServiceNowTask, agentResults, any[], _analysis, types_1.TaskAnalysis);
275
- Promise < any > {
276
- : .config.debugMode
277
- };
278
- {
279
- this.logger.info('🚀 Executing final deployment with MCP tools');
280
- }
281
- // The Queen coordinates the actual MCP tool calls based on agent recommendations
282
- const deploymentPlan = this.createDeploymentPlan(task, agentResults, _analysis);
283
- try {
284
- // Execute deployment using the unified deployment API
285
- const deploymentResult = await this.executeDeploymentPlan(deploymentPlan);
286
- // Track artifacts created
287
- if (deploymentResult.sys_id) {
288
- task.artifacts.push(deploymentResult.sys_id);
289
- // Store artifact in memory for future reference
290
- this.memory.storeArtifact({
291
- type: task.type,
292
- name: deploymentResult.name || task.objective,
293
- sys_id: deploymentResult.sys_id,
294
- config: deploymentResult.config || {},
295
- dependencies: _analysis.dependencies
296
- });
258
+ async executeAgentsSequentially(agents, objective) {
259
+ if (this.config.debugMode) {
260
+ this.logger.info('🔄 Executing agents sequentially');
261
+ }
262
+ const results = [];
263
+ for (const agent of agents) {
264
+ const result = await this.agentFactory.executeAgentTask(agent.id, objective);
265
+ results.push(result);
266
+ // Allow agents to coordinate between executions
267
+ this.facilitateAgentCoordination(agent, results);
268
+ }
269
+ return results;
297
270
  }
298
- return deploymentResult;
299
- }
300
- catch (error) {
301
- if (this.config.debugMode) {
302
- console.error('❌ Deployment failed:', error);
271
+ facilitateAgentCoordination(currentAgent, previousResults) {
272
+ // Send relevant results to collaborative agents
273
+ const activeAgents = this.agentFactory.getActiveAgents();
274
+ for (const agent of activeAgents) {
275
+ if (agent.id !== currentAgent.id) {
276
+ this.agentFactory.sendAgentMessage(currentAgent.id, agent.id, 'result', {
277
+ results: previousResults.slice(-1)[0], // Latest result
278
+ fromAgent: currentAgent.type
279
+ });
280
+ }
281
+ }
303
282
  }
304
- throw error;
305
- }
306
- createDeploymentPlan(task, types_1.ServiceNowTask, agentResults, any[], _analysis, types_1.TaskAnalysis);
307
- any;
308
- {
309
- // Extract deployment instructions from agent results
310
- const widgetCreator = agentResults.find(r => r.agentType === 'widget-creator');
311
- const flowBuilder = agentResults.find(r => r.agentType === 'flow-builder');
312
- const scriptWriter = agentResults.find(r => r.agentType === 'script-writer');
313
- const catalogManager = agentResults.find(r => r.agentType === 'catalog-manager');
314
- if (task.type === 'widget' && widgetCreator) {
283
+ async executeFinalDeployment(task, agentResults, _analysis) {
284
+ if (this.config.debugMode) {
285
+ this.logger.info('🚀 Executing final deployment with MCP tools');
286
+ }
287
+ // The Queen coordinates the actual MCP tool calls based on agent recommendations
288
+ const deploymentPlan = this.createDeploymentPlan(task, agentResults, _analysis);
289
+ try {
290
+ // Execute deployment using the unified deployment API
291
+ const deploymentResult = await this.executeDeploymentPlan(deploymentPlan);
292
+ // Track artifacts created
293
+ if (deploymentResult.sys_id) {
294
+ task.artifacts.push(deploymentResult.sys_id);
295
+ // Store artifact in memory for future reference
296
+ this.memory.storeArtifact({
297
+ type: task.type,
298
+ name: deploymentResult.name || task.objective,
299
+ sys_id: deploymentResult.sys_id,
300
+ config: deploymentResult.config || {},
301
+ dependencies: _analysis.dependencies
302
+ });
303
+ }
304
+ return deploymentResult;
305
+ }
306
+ catch (error) {
307
+ if (this.config.debugMode) {
308
+ console.error('❌ Deployment failed:', error);
309
+ }
310
+ throw error;
311
+ }
312
+ }
313
+ createDeploymentPlan(task, agentResults, _analysis) {
314
+ // Extract deployment instructions from agent results
315
+ const widgetCreator = agentResults.find(r => r.agentType === 'widget-creator');
316
+ const flowBuilder = agentResults.find(r => r.agentType === 'flow-builder');
317
+ const scriptWriter = agentResults.find(r => r.agentType === 'script-writer');
318
+ const catalogManager = agentResults.find(r => r.agentType === 'catalog-manager');
319
+ if (task.type === 'widget' && widgetCreator) {
320
+ return {
321
+ type: 'widget',
322
+ mcpTool: 'snow_deploy',
323
+ config: this.extractWidgetConfig(task.objective, agentResults),
324
+ autoPermissions: this.config.autoPermissions // Pass auto-permissions flag for dependency handling
325
+ };
326
+ }
327
+ // Flow creation is no longer supported - use ServiceNow Flow Designer directly
328
+ if (task.type === 'flow') {
329
+ throw new Error('Flow creation is no longer supported in Snow-Flow. Please use ServiceNow Flow Designer directly.');
330
+ }
331
+ if (task.type === 'script' && scriptWriter) {
332
+ return {
333
+ type: 'script',
334
+ mcpTool: 'snow_create_script_include',
335
+ config: this.extractScriptConfig(task.objective, agentResults)
336
+ };
337
+ }
338
+ // Default deployment plan
315
339
  return {
316
- type: 'widget',
340
+ type: task.type,
317
341
  mcpTool: 'snow_deploy',
318
- config: this.extractWidgetConfig(task.objective, agentResults),
319
- autoPermissions: this.config.autoPermissions // Pass auto-permissions flag for dependency handling
342
+ instruction: task.objective
320
343
  };
321
344
  }
322
- // Flow creation is no longer supported - use ServiceNow Flow Designer directly
323
- if (task.type === 'flow') {
324
- throw new Error('Flow creation is no longer supported in Snow-Flow. Please use ServiceNow Flow Designer directly.');
345
+ extractWidgetConfig(objective, agentResults) {
346
+ // Extract widget configuration from agent results
347
+ const widgetResult = agentResults.find(r => r.agentType === 'widget-creator');
348
+ return {
349
+ name: this.generateArtifactName(objective, 'widget'),
350
+ title: this.generateArtifactTitle(objective),
351
+ template: this.generateWidgetTemplate(objective),
352
+ css: this.generateWidgetCss(objective),
353
+ client_script: this.generateClientScript(objective),
354
+ script: this.generateServerScript(objective), // ServiceNow uses 'script' field, not 'server_script'
355
+ demo_data: this.generateDemoData(objective)
356
+ };
325
357
  }
326
- if (task.type === 'script' && scriptWriter) {
358
+ extractScriptConfig(objective, agentResults) {
327
359
  return {
328
- type: 'script',
329
- mcpTool: 'snow_create_script_include',
330
- config: this.extractScriptConfig(task.objective, agentResults)
360
+ name: this.generateArtifactName(objective, 'script'),
361
+ description: `Auto-generated script for: ${objective}`,
362
+ script: this.generateScriptCode(objective)
331
363
  };
332
364
  }
333
- // Default deployment plan
334
- return {
335
- type: task.type,
336
- mcpTool: 'snow_deploy',
337
- instruction: task.objective
338
- };
339
- }
340
- extractWidgetConfig(objective, string, agentResults, any[]);
341
- any;
342
- {
343
- // Extract widget configuration from agent results
344
- const widgetResult = agentResults.find(r => r.agentType === 'widget-creator');
345
- return {
346
- name: this.generateArtifactName(objective, 'widget'),
347
- title: this.generateArtifactTitle(objective),
348
- template: this.generateWidgetTemplate(objective),
349
- css: this.generateWidgetCss(objective),
350
- client_script: this.generateClientScript(objective),
351
- server_script: this.generateServerScript(objective),
352
- demo_data: this.generateDemoData(objective)
353
- };
354
- }
355
- extractScriptConfig(objective, string, agentResults, any[]);
356
- any;
357
- {
358
- return {
359
- name: this.generateArtifactName(objective, 'script'),
360
- description: `Auto-generated script for: ${objective}`,
361
- script: this.generateScriptCode(objective)
362
- };
363
- }
364
- generateArtifactName(objective, string, type, string);
365
- string;
366
- {
367
- const words = objective.toLowerCase().replace(/[^a-z\s]/g, '').split(/\s+/).filter(w => w.length > 2);
368
- const key_words = words.slice(0, 3).join('_');
369
- return `${key_words}_${type}`;
370
- }
371
- generateArtifactTitle(objective, string);
372
- string;
373
- {
374
- return objective.charAt(0).toUpperCase() + objective.slice(1);
375
- }
376
- generateWidgetTemplate(objective, string);
377
- string;
378
- {
379
- const isChart = objective.toLowerCase().includes('chart') || objective.toLowerCase().includes('graph');
380
- const isDashboard = objective.toLowerCase().includes('dashboard');
381
- if (isChart) {
382
- return `
365
+ // Simple artifact generation based on objective analysis
366
+ generateArtifactName(objective, type) {
367
+ const words = objective.toLowerCase().replace(/[^a-z\s]/g, '').split(/\s+/).filter(w => w.length > 2);
368
+ const key_words = words.slice(0, 3).join('_');
369
+ return `${key_words}_${type}`;
370
+ }
371
+ generateArtifactTitle(objective) {
372
+ return objective.charAt(0).toUpperCase() + objective.slice(1);
373
+ }
374
+ generateWidgetTemplate(objective) {
375
+ const isChart = objective.toLowerCase().includes('chart') || objective.toLowerCase().includes('graph');
376
+ const isDashboard = objective.toLowerCase().includes('dashboard');
377
+ if (isChart) {
378
+ return `
383
379
  <div class="panel panel-default">
384
380
  <div class="panel-heading">
385
381
  <h3 class="panel-title">{{data.title || '${this.generateArtifactTitle(objective)}'}}</h3>
@@ -388,9 +384,9 @@ string;
388
384
  <canvas id="chart-{{::data.widget_id}}" width="400" height="200"></canvas>
389
385
  </div>
390
386
  </div>`;
391
- }
392
- if (isDashboard) {
393
- return `
387
+ }
388
+ if (isDashboard) {
389
+ return `
394
390
  <div class="row">
395
391
  <div class="col-md-12">
396
392
  <div class="panel panel-default">
@@ -410,8 +406,8 @@ string;
410
406
  </div>
411
407
  </div>
412
408
  </div>`;
413
- }
414
- return `
409
+ }
410
+ return `
415
411
  <div class="panel panel-default">
416
412
  <div class="panel-heading">
417
413
  <h3 class="panel-title">{{data.title || '${this.generateArtifactTitle(objective)}'}}</h3>
@@ -430,11 +426,9 @@ string;
430
426
  </div>
431
427
  </div>
432
428
  </div>`;
433
- }
434
- generateWidgetCss(objective, string);
435
- string;
436
- {
437
- return `
429
+ }
430
+ generateWidgetCss(objective) {
431
+ return `
438
432
  .panel {
439
433
  margin-bottom: 20px;
440
434
  border-radius: 6px;
@@ -466,13 +460,11 @@ string;
466
460
  margin-bottom: 15px;
467
461
  }
468
462
  }`;
469
- }
470
- generateClientScript(objective, string);
471
- string;
472
- {
473
- const isChart = objective.toLowerCase().includes('chart') || objective.toLowerCase().includes('graph');
474
- if (isChart) {
475
- return `
463
+ }
464
+ generateClientScript(objective) {
465
+ const isChart = objective.toLowerCase().includes('chart') || objective.toLowerCase().includes('graph');
466
+ if (isChart) {
467
+ return `
476
468
  function($scope) {
477
469
  var c = this;
478
470
 
@@ -501,8 +493,8 @@ function($scope) {
501
493
  }
502
494
  };
503
495
  }`;
504
- }
505
- return `
496
+ }
497
+ return `
506
498
  function($scope) {
507
499
  var c = this;
508
500
 
@@ -522,13 +514,11 @@ function($scope) {
522
514
  c.server.refresh();
523
515
  };
524
516
  }`;
525
- }
526
- generateServerScript(objective, string);
527
- string;
528
- {
529
- const lowerObjective = objective.toLowerCase();
530
- if (lowerObjective.includes('incident')) {
531
- return `
517
+ }
518
+ generateServerScript(objective) {
519
+ const lowerObjective = objective.toLowerCase();
520
+ if (lowerObjective.includes('incident')) {
521
+ return `
532
522
  (function() {
533
523
  data.title = options.title || 'Incidents Dashboard';
534
524
  data.widget_id = gs.generateGUID();
@@ -569,8 +559,8 @@ string;
569
559
  data.chartType = 'doughnut';
570
560
  }
571
561
  })();`;
572
- }
573
- return `
562
+ }
563
+ return `
574
564
  (function() {
575
565
  data.title = options.title || '${this.generateArtifactTitle(objective)}';
576
566
  data.widget_id = gs.generateGUID();
@@ -591,24 +581,20 @@ string;
591
581
  }
592
582
  ];
593
583
  })();`;
594
- }
595
- generateDemoData(objective, string);
596
- any;
597
- {
598
- return {
599
- title: this.generateArtifactTitle(objective),
600
- items: [
601
- {
602
- title: 'Demo Item 1',
603
- description: 'Sample data for testing the widget'
604
- }
605
- ]
606
- };
607
- }
608
- generateScriptCode(objective, string);
609
- string;
610
- {
611
- return `
584
+ }
585
+ generateDemoData(objective) {
586
+ return {
587
+ title: this.generateArtifactTitle(objective),
588
+ items: [
589
+ {
590
+ title: 'Demo Item 1',
591
+ description: 'Sample data for testing the widget'
592
+ }
593
+ ]
594
+ };
595
+ }
596
+ generateScriptCode(objective) {
597
+ return `
612
598
  // Auto-generated script for: ${objective}
613
599
  // Generated by ServiceNow Queen Agent
614
600
 
@@ -621,331 +607,705 @@ string;
621
607
  message: 'Script executed successfully'
622
608
  };
623
609
  })();`;
624
- }
625
- async;
626
- executeDeploymentPlan(plan, any);
627
- Promise < any > {
628
- : .config.debugMode
629
- };
630
- {
631
- this.logger.info('🚀 Executing deployment plan with MCP Bridge');
632
- }
633
- // Create agent recommendation from plan
634
- const recommendation = {
635
- agentId: 'queen-agent',
636
- agentType: 'queen',
637
- action: `deploy-${plan.type}`,
638
- tool: plan.mcpTool,
639
- server: this.getServerForTool(plan.mcpTool),
640
- params: plan.config || {},
641
- reasoning: `Deploying ${plan.type} artifact as requested`,
642
- confidence: 0.95
643
- };
644
- // Execute through MCP bridge
645
- const result = await this.mcpBridge.executeAgentRecommendation({ id: 'queen-agent', type: 'queen' }, recommendation);
646
- if (result.success && result.toolResult) {
647
- const deploymentResult = {
648
- success: true,
649
- type: plan.type,
650
- name: plan.config?.name || result.toolResult.name,
651
- sys_id: result.toolResult.sys_id, // Real sys_id from ServiceNow!
652
- config: plan.config,
653
- mcpTool: plan.mcpTool,
654
- executionTime: result.executionTime
655
- };
656
- // Handle dependency injection for widgets
657
- if (plan.type === 'widget' && plan.config) {
658
- await this.handleWidgetDependencies(plan.config, plan.autoPermissions);
659
610
  }
660
- return deploymentResult;
661
- }
662
- else {
663
- throw new Error(`MCP execution failed: ${result.error || 'Unknown error'}`);
664
- }
665
- getServerForTool(tool, string);
666
- string;
667
- {
668
- // Map tools to their servers
669
- const toolServerMap = {
670
- 'snow_deploy': 'deployment',
671
- 'snow_deploy_widget': 'deployment',
672
- 'snow_deploy_flow': 'deployment',
673
- 'snow_find_artifact': 'intelligent',
674
- 'snow_update_set_create': 'update-set',
675
- 'snow_get_by_sysid': 'intelligent',
676
- 'snow_edit_by_sysid': 'intelligent'
677
- };
678
- return toolServerMap[tool] || 'deployment';
679
- }
680
- async;
681
- handleWidgetDependencies(widgetConfig, any, autoPermissions ? : boolean);
682
- Promise < void > {
683
- try: {
684
- // Detect dependencies in widget code
685
- const: dependencies = dependency_detector_1.DependencyDetector.analyzeWidget(widgetConfig),
686
- if(dependencies) { }, : .length === 0
687
- }
688
- };
689
- {
690
- return; // No dependencies needed
691
- }
692
- this.logger.info(`\n📦 Detected ${dependencies.length} external dependencies in widget:`);
693
- dependencies.forEach(dep => {
694
- this.logger.info(` • ${dep.name} - ${dep.description}`);
695
- });
696
- // Create MCP tools wrapper for theme manager
697
- const mcpTools = {
698
- snow_find_artifact: async (params) => {
611
+ async executeDeploymentPlan(plan) {
612
+ // Execute real MCP tools through the bridge
613
+ if (this.config.debugMode) {
614
+ this.logger.info('🚀 Executing deployment plan with MCP Bridge');
615
+ }
616
+ // Create agent recommendation from plan
699
617
  const recommendation = {
700
618
  agentId: 'queen-agent',
701
619
  agentType: 'queen',
702
- action: 'find-theme',
703
- tool: 'snow_find_artifact',
704
- server: 'intelligent',
705
- params,
706
- reasoning: 'Finding Service Portal theme for dependency injection',
620
+ action: `deploy-${plan.type}`,
621
+ tool: plan.mcpTool,
622
+ server: this.getServerForTool(plan.mcpTool),
623
+ params: plan.config || {},
624
+ reasoning: `Deploying ${plan.type} artifact as requested`,
707
625
  confidence: 0.95
708
626
  };
627
+ // Execute through MCP bridge
709
628
  const result = await this.mcpBridge.executeAgentRecommendation({ id: 'queen-agent', type: 'queen' }, recommendation);
710
- return result.toolResult;
711
- },
712
- snow_comprehensive_search: async (params) => {
713
- const recommendation = {
714
- agentId: 'queen-agent',
715
- agentType: 'queen',
716
- action: 'search-themes',
717
- tool: 'snow_comprehensive_search',
718
- server: 'intelligent',
719
- params,
720
- reasoning: 'Searching for Service Portal themes',
721
- confidence: 0.95
629
+ if (result.success && result.toolResult) {
630
+ const deploymentResult = {
631
+ success: true,
632
+ type: plan.type,
633
+ name: plan.config?.name || result.toolResult.name,
634
+ sys_id: result.toolResult.sys_id, // Real sys_id from ServiceNow!
635
+ config: plan.config,
636
+ mcpTool: plan.mcpTool,
637
+ executionTime: result.executionTime
638
+ };
639
+ // Handle dependency injection for widgets
640
+ if (plan.type === 'widget' && plan.config) {
641
+ await this.handleWidgetDependencies(plan.config, plan.autoPermissions);
642
+ }
643
+ return deploymentResult;
644
+ }
645
+ else {
646
+ throw new Error(`MCP execution failed: ${result.error || 'Unknown error'}`);
647
+ }
648
+ }
649
+ getServerForTool(tool) {
650
+ // Map tools to their servers
651
+ const toolServerMap = {
652
+ 'snow_deploy': 'deployment',
653
+ 'snow_deploy_widget': 'deployment',
654
+ 'snow_deploy_flow': 'deployment',
655
+ 'snow_find_artifact': 'intelligent',
656
+ 'snow_update_set_create': 'update-set',
657
+ 'snow_get_by_sysid': 'intelligent',
658
+ 'snow_edit_by_sysid': 'intelligent'
722
659
  };
723
- const result = await this.mcpBridge.executeAgentRecommendation({ id: 'queen-agent', type: 'queen' }, recommendation);
724
- return result.toolResult;
725
- },
726
- snow_get_by_sysid: async (params) => {
727
- const recommendation = {
728
- agentId: 'queen-agent',
729
- agentType: 'queen',
730
- action: 'get-theme',
731
- tool: 'snow_get_by_sysid',
732
- server: 'intelligent',
733
- params,
734
- reasoning: 'Getting Service Portal theme details',
735
- confidence: 0.95
660
+ return toolServerMap[tool] || 'deployment';
661
+ }
662
+ async handleWidgetDependencies(widgetConfig, autoPermissions) {
663
+ try {
664
+ // Detect dependencies in widget code
665
+ const dependencies = dependency_detector_1.DependencyDetector.analyzeWidget(widgetConfig);
666
+ if (dependencies.length === 0) {
667
+ return; // No dependencies needed
668
+ }
669
+ this.logger.info(`\n📦 Detected ${dependencies.length} external dependencies in widget:`);
670
+ dependencies.forEach(dep => {
671
+ this.logger.info(` • ${dep.name} - ${dep.description}`);
672
+ });
673
+ // Create MCP tools wrapper for theme manager
674
+ const mcpTools = {
675
+ snow_find_artifact: async (params) => {
676
+ const recommendation = {
677
+ agentId: 'queen-agent',
678
+ agentType: 'queen',
679
+ action: 'find-theme',
680
+ tool: 'snow_find_artifact',
681
+ server: 'intelligent',
682
+ params,
683
+ reasoning: 'Finding Service Portal theme for dependency injection',
684
+ confidence: 0.95
685
+ };
686
+ const result = await this.mcpBridge.executeAgentRecommendation({ id: 'queen-agent', type: 'queen' }, recommendation);
687
+ return result.toolResult;
688
+ },
689
+ snow_comprehensive_search: async (params) => {
690
+ const recommendation = {
691
+ agentId: 'queen-agent',
692
+ agentType: 'queen',
693
+ action: 'search-themes',
694
+ tool: 'snow_comprehensive_search',
695
+ server: 'intelligent',
696
+ params,
697
+ reasoning: 'Searching for Service Portal themes',
698
+ confidence: 0.95
699
+ };
700
+ const result = await this.mcpBridge.executeAgentRecommendation({ id: 'queen-agent', type: 'queen' }, recommendation);
701
+ return result.toolResult;
702
+ },
703
+ snow_get_by_sysid: async (params) => {
704
+ const recommendation = {
705
+ agentId: 'queen-agent',
706
+ agentType: 'queen',
707
+ action: 'get-theme',
708
+ tool: 'snow_get_by_sysid',
709
+ server: 'intelligent',
710
+ params,
711
+ reasoning: 'Getting Service Portal theme details',
712
+ confidence: 0.95
713
+ };
714
+ const result = await this.mcpBridge.executeAgentRecommendation({ id: 'queen-agent', type: 'queen' }, recommendation);
715
+ return result.toolResult;
716
+ },
717
+ snow_edit_by_sysid: async (params) => {
718
+ const recommendation = {
719
+ agentId: 'queen-agent',
720
+ agentType: 'queen',
721
+ action: 'update-theme',
722
+ tool: 'snow_edit_by_sysid',
723
+ server: 'intelligent',
724
+ params,
725
+ reasoning: 'Updating Service Portal theme with dependencies',
726
+ confidence: 0.95
727
+ };
728
+ const result = await this.mcpBridge.executeAgentRecommendation({ id: 'queen-agent', type: 'queen' }, recommendation);
729
+ return result.toolResult;
730
+ }
731
+ };
732
+ // Update theme with dependencies
733
+ const result = await theme_manager_1.ServicePortalThemeManager.updateThemeWithDependencies(dependencies, mcpTools, {
734
+ autoPermissions,
735
+ skipPrompt: autoPermissions, // Skip prompt if auto-permissions enabled
736
+ useMinified: true
737
+ });
738
+ if (result.success) {
739
+ this.logger.info(`✅ ${result.message}`);
740
+ }
741
+ else {
742
+ this.logger.warn(`⚠️ Dependencies not installed: ${result.message}`);
743
+ this.logger.info('💡 You may need to manually add these dependencies to your Service Portal theme');
744
+ }
745
+ }
746
+ catch (error) {
747
+ console.error('❌ Error handling widget dependencies:', error.message);
748
+ // Don't fail the deployment, just warn
749
+ this.logger.warn('⚠️ Widget deployed successfully but dependencies may need manual installation');
750
+ }
751
+ }
752
+ async attemptRecovery(task, agents, error) {
753
+ if (this.config.debugMode) {
754
+ this.logger.info(`🔄 Attempting recovery for task ${task.id}`);
755
+ }
756
+ // Try with reduced complexity or different agent sequence
757
+ const fallbackResult = {
758
+ taskId: task.id,
759
+ objective: task.objective,
760
+ status: 'recovered',
761
+ error: error.message,
762
+ fallbackApplied: true
736
763
  };
737
- const result = await this.mcpBridge.executeAgentRecommendation({ id: 'queen-agent', type: 'queen' }, recommendation);
738
- return result.toolResult;
739
- },
740
- snow_edit_by_sysid: async (params) => {
741
- const recommendation = {
742
- agentId: 'queen-agent',
743
- agentType: 'queen',
744
- action: 'update-theme',
745
- tool: 'snow_edit_by_sysid',
746
- server: 'intelligent',
747
- params,
748
- reasoning: 'Updating Service Portal theme with dependencies',
749
- confidence: 0.95
764
+ return fallbackResult;
765
+ }
766
+ learnFromExecution(task, agents, result, duration, error) {
767
+ const agentTypes = agents.map(a => a.type);
768
+ if (error) {
769
+ // Learn from failure
770
+ this.neuralLearning.learnFromFailure(task, error.message, agentTypes);
771
+ this.memory.recordTaskCompletion(task.id, task.objective, task.type, agentTypes, false, duration);
772
+ }
773
+ else {
774
+ // Learn from success
775
+ this.neuralLearning.learnFromSuccess(task, duration, agentTypes);
776
+ this.memory.recordTaskCompletion(task.id, task.objective, task.type, agentTypes, true, duration);
777
+ }
778
+ if (this.config.debugMode) {
779
+ this.logger.info(`📚 Queen learned from ${error ? 'failure' : 'success'}: ${task.objective}`);
780
+ }
781
+ }
782
+ async handleExecutionFailure(taskId, objective, error, duration) {
783
+ const task = this.activeTasks.get(taskId);
784
+ if (task) {
785
+ task.status = 'failed';
786
+ task.error = error.message;
787
+ // Learn from failure
788
+ this.memory.storeLearning(`failure_${task.type}`, `Failed: ${objective} - Error: ${error.message}`, 0.8);
789
+ }
790
+ if (this.config.debugMode) {
791
+ console.error(`❌ Task ${taskId} failed after ${duration}ms:`, error.message);
792
+ }
793
+ }
794
+ cleanupTask(taskId) {
795
+ this.activeTasks.delete(taskId);
796
+ this.agentFactory.cleanupCompletedAgents();
797
+ }
798
+ generateTaskId() {
799
+ return `task_${Date.now()}_${crypto.randomBytes(4).toString('hex')}`;
800
+ }
801
+ // Public API methods
802
+ getActiveTaskCount() {
803
+ return this.activeTasks.size;
804
+ }
805
+ getTaskStatus(taskId) {
806
+ return this.activeTasks.get(taskId) || null;
807
+ }
808
+ /**
809
+ * Get gap _analysis results for a task
810
+ */
811
+ getGapAnalysisResults(taskId) {
812
+ const task = this.activeTasks.get(taskId);
813
+ return task?.gapAnalysis || null;
814
+ }
815
+ /**
816
+ * Get all manual guides from gap _analysis for a task
817
+ */
818
+ getManualConfigurationGuides(taskId) {
819
+ // Get strategic analysis from task
820
+ const task = this.activeTasks.get(taskId);
821
+ const strategicAnalysis = task?.strategicAnalysis;
822
+ return strategicAnalysis?.problemAnalysis?.hiddenRequirements || null;
823
+ }
824
+ getHiveMindStatus() {
825
+ return {
826
+ activeTasks: this.activeTasks.size,
827
+ activeAgents: this.agentFactory.getActiveAgents().length,
828
+ memoryStats: {
829
+ patterns: this.memory['memory'].patterns.length,
830
+ artifacts: this.memory['memory'].artifacts.size,
831
+ learnings: this.memory['memory'].learnings.size
832
+ },
833
+ factoryStats: this.agentFactory.getStatistics(),
834
+ learningInsights: this.neuralLearning.getLearningInsights()
750
835
  };
751
- const result = await this.mcpBridge.executeAgentRecommendation({ id: 'queen-agent', type: 'queen' }, recommendation);
752
- return result.toolResult;
753
- }
754
- };
755
- // Update theme with dependencies
756
- const result = await theme_manager_1.ServicePortalThemeManager.updateThemeWithDependencies(dependencies, mcpTools, {
757
- autoPermissions,
758
- skipPrompt: autoPermissions, // Skip prompt if auto-permissions enabled
759
- useMinified: true
760
- });
761
- if (result.success) {
762
- this.logger.info(`✅ ${result.message}`);
763
- }
764
- else {
765
- this.logger.warn(`⚠️ Dependencies not installed: ${result.message}`);
766
- this.logger.info('💡 You may need to manually add these dependencies to your Service Portal theme');
767
- }
768
- try { }
769
- catch (error) {
770
- console.error('❌ Error handling widget dependencies:', error.message);
771
- // Don't fail the deployment, just warn
772
- this.logger.warn('⚠️ Widget deployed successfully but dependencies may need manual installation');
773
- }
774
- async;
775
- attemptRecovery(task, types_1.ServiceNowTask, agents, types_1.Agent[], error, Error);
776
- Promise < any > {
777
- : .config.debugMode
778
- };
779
- {
780
- this.logger.info(`🔄 Attempting recovery for task ${task.id}`);
781
- }
782
- // Try with reduced complexity or different agent sequence
783
- const fallbackResult = {
784
- taskId: task.id,
785
- objective: task.objective,
786
- status: 'recovered',
787
- error: error.message,
788
- fallbackApplied: true
789
- };
790
- return fallbackResult;
791
- learnFromExecution(task, types_1.ServiceNowTask, agents, types_1.Agent[], result, any, duration, number, error, Error | null);
792
- void {
793
- const: agentTypes = agents.map(a => a.type),
794
- if(error) {
795
- // Learn from failure
796
- this.neuralLearning.learnFromFailure(task, error.message, agentTypes);
797
- this.memory.recordTaskCompletion(task.id, task.objective, task.type, agentTypes, false, duration);
798
- }, else: {
799
- // Learn from success
800
- this: .neuralLearning.learnFromSuccess(task, duration, agentTypes),
801
- this: .memory.recordTaskCompletion(task.id, task.objective, task.type, agentTypes, true, duration)
802
- },
803
- : .config.debugMode
804
- };
805
- {
806
- this.logger.info(`📚 Queen learned from ${error ? 'failure' : 'success'}: ${task.objective}`);
807
- }
808
- async;
809
- handleExecutionFailure(taskId, string, objective, string, error, Error, duration, number);
810
- Promise < void > {
811
- const: task = this.activeTasks.get(taskId),
812
- if(task) {
813
- task.status = 'failed';
814
- task.error = error.message;
815
- // Learn from failure
816
- this.memory.storeLearning(`failure_${task.type}`, `Failed: ${objective} - Error: ${error.message}`, 0.8);
817
- },
818
- : .config.debugMode
819
- };
820
- {
821
- console.error(`❌ Task ${taskId} failed after ${duration}ms:`, error.message);
822
- }
823
- cleanupTask(taskId, string);
824
- void {
825
- this: .activeTasks.delete(taskId),
826
- this: .agentFactory.cleanupCompletedAgents()
827
- };
828
- generateTaskId();
829
- string;
830
- {
831
- return `task_${Date.now()}_${crypto.randomBytes(4).toString('hex')}`;
832
- }
833
- // Public API methods
834
- getActiveTaskCount();
835
- number;
836
- {
837
- return this.activeTasks.size;
838
- }
839
- getTaskStatus(taskId, string);
840
- types_1.ServiceNowTask | null;
841
- {
842
- return this.activeTasks.get(taskId) || null;
843
- }
844
- /**
845
- * Get gap _analysis results for a task
846
- */
847
- getGapAnalysisResults(taskId, string);
848
- any | null;
849
- {
850
- const task = this.activeTasks.get(taskId);
851
- return task?.gapAnalysis || null;
852
- }
853
- /**
854
- * Get all manual guides from gap _analysis for a task
855
- */
856
- getManualConfigurationGuides(taskId, string);
857
- any;
858
- {
859
- // Gap analysis integrated into MCP workflow
860
- return gapAnalysis?.manualGuides || null;
861
- }
862
- getHiveMindStatus();
863
- any;
864
- {
865
- return {
866
- activeTasks: this.activeTasks.size,
867
- activeAgents: this.agentFactory.getActiveAgents().length,
868
- memoryStats: {
869
- patterns: this.memory['memory'].patterns.length,
870
- artifacts: this.memory['memory'].artifacts.size,
871
- learnings: this.memory['memory'].learnings.size
872
- },
873
- factoryStats: this.agentFactory.getStatistics(),
874
- learningInsights: this.neuralLearning.getLearningInsights()
875
- };
876
- }
877
- exportMemory();
878
- string;
879
- {
880
- return this.memory.exportMemory();
881
- }
882
- importMemory(memoryData, string);
883
- void {
884
- this: .memory.importMemory(memoryData),
885
- : .config.debugMode
886
- };
887
- {
888
- this.logger.info('🧠 Queen hive-mind memory imported successfully');
889
- }
890
- clearMemory();
891
- void {
892
- this: .memory.clearMemory(),
893
- // Also reset neural learning weights
894
- this: .neuralLearning = new neural_learning_1.NeuralLearning(this.memory),
895
- : .config.debugMode
896
- };
897
- {
898
- this.logger.info('🧠 Queen hive-mind memory cleared - starting fresh');
899
- }
900
- getLearningInsights();
901
- any;
902
- {
903
- const neuralInsights = this.neuralLearning.getLearningInsights();
904
- return {
905
- successfulPatterns: this.memory['memory'].patterns.slice(0, 5).map(pattern => ({
906
- description: `${pattern.taskType} deployment using ${pattern.agentSequence.join(' → ')}`,
907
- successRate: Math.round(pattern.successRate * 100),
908
- avgDuration: pattern.avgDuration,
909
- useCount: this.memory.getSuccessRate(pattern.taskType)
910
- })),
911
- recommendations: [
912
- 'Use Queen Agent for complex multi-step ServiceNow tasks',
913
- 'Enable --debug mode for detailed hive-mind insights',
914
- 'Export memory regularly to preserve learning patterns',
915
- 'Let Queen analyze objectives for optimal agent coordination'
916
- ],
917
- commonTasks: Object.entries(neuralInsights.weights || {})
918
- .map(([type, count]) => ({
919
- type,
920
- count: typeof count === 'number' ? count : 0
921
- }))
922
- .sort((a, b) => b.count - a.count)
923
- .slice(0, 5),
924
- memoryStats: {
925
- totalPatterns: this.memory['memory'].patterns.length,
926
- totalArtifacts: this.memory['memory'].artifacts.size,
927
- totalLearnings: this.memory['memory'].learnings.size
928
- },
929
- neuralInsights
930
- };
931
- }
932
- async;
933
- shutdown();
934
- Promise < void > {
935
- : .config.debugMode
936
- };
937
- {
938
- this.logger.info('🛑 Shutting down ServiceNow Queen Agent');
939
- }
940
- // Clean up all agents
941
- const activeAgents = this.agentFactory.getActiveAgents();
942
- for (const agent of activeAgents) {
943
- this.agentFactory.terminateAgent(agent.id);
944
- }
945
- // Shutdown MCP Bridge
946
- if (this.mcpBridge) {
947
- await this.mcpBridge.shutdown();
836
+ }
837
+ exportMemory() {
838
+ return this.memory.exportMemory();
839
+ }
840
+ importMemory(memoryData) {
841
+ this.memory.importMemory(memoryData);
842
+ if (this.config.debugMode) {
843
+ this.logger.info('🧠 Queen hive-mind memory imported successfully');
844
+ }
845
+ }
846
+ clearMemory() {
847
+ this.memory.clearMemory();
848
+ // Also reset neural learning weights
849
+ this.neuralLearning = new neural_learning_1.NeuralLearning(this.memory);
850
+ if (this.config.debugMode) {
851
+ this.logger.info('🧠 Queen hive-mind memory cleared - starting fresh');
852
+ }
853
+ }
854
+ getLearningInsights() {
855
+ const neuralInsights = this.neuralLearning.getLearningInsights();
856
+ return {
857
+ successfulPatterns: this.memory['memory'].patterns.slice(0, 5).map(pattern => ({
858
+ description: `${pattern.taskType} deployment using ${pattern.agentSequence.join(' → ')}`,
859
+ successRate: Math.round(pattern.successRate * 100),
860
+ avgDuration: pattern.avgDuration,
861
+ useCount: this.memory.getSuccessRate(pattern.taskType)
862
+ })),
863
+ recommendations: [
864
+ 'Use Queen Agent for complex multi-step ServiceNow tasks',
865
+ 'Enable --debug mode for detailed hive-mind insights',
866
+ 'Export memory regularly to preserve learning patterns',
867
+ 'Let Queen analyze objectives for optimal agent coordination'
868
+ ],
869
+ commonTasks: Object.entries(neuralInsights.weights || {})
870
+ .map(([type, count]) => ({
871
+ type,
872
+ count: typeof count === 'number' ? count : 0
873
+ }))
874
+ .sort((a, b) => b.count - a.count)
875
+ .slice(0, 5),
876
+ memoryStats: {
877
+ totalPatterns: this.memory['memory'].patterns.length,
878
+ totalArtifacts: this.memory['memory'].artifacts.size,
879
+ totalLearnings: this.memory['memory'].learnings.size
880
+ },
881
+ neuralInsights
882
+ };
883
+ }
884
+ async shutdown() {
885
+ if (this.config.debugMode) {
886
+ this.logger.info('🛑 Shutting down ServiceNow Queen Agent');
887
+ }
888
+ // Clean up all agents
889
+ const activeAgents = this.agentFactory.getActiveAgents();
890
+ for (const agent of activeAgents) {
891
+ this.agentFactory.terminateAgent(agent.id);
892
+ }
893
+ // Shutdown MCP Bridge
894
+ if (this.mcpBridge) {
895
+ await this.mcpBridge.shutdown();
896
+ }
897
+ // Close memory system
898
+ this.memory.close();
899
+ }
900
+ /**
901
+ * STRATEGIC ORCHESTRATION METHODS
902
+ * These methods implement the Queen Agent's strategic thinking capabilities
903
+ */
904
+ /**
905
+ * Perform deep problem analysis to understand what user ACTUALLY needs
906
+ */
907
+ async performDeepProblemAnalysis(objective) {
908
+ this.logger.info('🧠 Deep Problem Analysis: Looking beyond surface requirements...');
909
+ // Analyze the objective for hidden complexity and real business needs
910
+ const analysis = {
911
+ coreProblem: this.extractCoreProblem(objective),
912
+ complexity: this.assessObjectiveComplexity(objective),
913
+ businessImpact: this.assessBusinessImpact(objective),
914
+ stakeholders: this.identifyStakeholders(objective),
915
+ hiddenRequirements: this.identifyHiddenRequirements(objective),
916
+ successCriteria: this.defineSuccessCriteria(objective)
917
+ };
918
+ this.logger.info(`🎯 Core Problem Identified: ${analysis.coreProblem}`);
919
+ this.logger.info(`📈 Success Criteria: ${analysis.successCriteria.join(', ')}`);
920
+ return analysis;
921
+ }
922
+ /**
923
+ * Perform comprehensive risk assessment
924
+ */
925
+ async performRiskAssessment(objective, problemAnalysis) {
926
+ this.logger.info('⚠️ Strategic Risk Assessment: Identifying all potential failure points...');
927
+ const risks = [
928
+ ...this.identifyTechnicalRisks(objective, problemAnalysis),
929
+ ...this.identifyBusinessRisks(objective, problemAnalysis),
930
+ ...this.identifyOperationalRisks(objective, problemAnalysis),
931
+ ...this.identifyComplianceRisks(objective, problemAnalysis)
932
+ ];
933
+ const criticalRisks = risks.filter(risk => risk.impact === 'high' && risk.likelihood === 'high');
934
+ const overallRisk = this.calculateOverallRisk(risks);
935
+ return {
936
+ risks,
937
+ criticalRisks,
938
+ overallRisk,
939
+ mitigationStrategies: this.developMitigationStrategies(criticalRisks)
940
+ };
941
+ }
942
+ /**
943
+ * Extract the core business problem from user request
944
+ */
945
+ extractCoreProblem(objective) {
946
+ const objective_lower = objective.toLowerCase();
947
+ // Analyze patterns to understand underlying need
948
+ if (objective_lower.includes('widget') || objective_lower.includes('dashboard')) {
949
+ return 'Users need better access to information or functionality through improved interface';
950
+ }
951
+ else if (objective_lower.includes('workflow') || objective_lower.includes('process')) {
952
+ return 'Business process efficiency and automation needs improvement';
953
+ }
954
+ else if (objective_lower.includes('integration') || objective_lower.includes('api')) {
955
+ return 'Systems need to communicate effectively to eliminate manual work';
956
+ }
957
+ else if (objective_lower.includes('report') || objective_lower.includes('analytics')) {
958
+ return 'Decision makers need better visibility into business performance';
959
+ }
960
+ else if (objective_lower.includes('notification') || objective_lower.includes('alert')) {
961
+ return 'Stakeholders need timely awareness of important events or status changes';
962
+ }
963
+ else {
964
+ return 'Business capability needs enhancement through ServiceNow platform optimization';
965
+ }
966
+ }
967
+ /**
968
+ * Assess objective complexity
969
+ */
970
+ assessObjectiveComplexity(objective) {
971
+ let complexity_score = 0;
972
+ const high_complexity_indicators = ['integration', 'multiple', 'complex', 'enterprise', 'automated', 'workflow'];
973
+ const medium_complexity_indicators = ['dashboard', 'report', 'widget', 'form', 'approval'];
974
+ high_complexity_indicators.forEach(indicator => {
975
+ if (objective.toLowerCase().includes(indicator))
976
+ complexity_score += 2;
977
+ });
978
+ medium_complexity_indicators.forEach(indicator => {
979
+ if (objective.toLowerCase().includes(indicator))
980
+ complexity_score += 1;
981
+ });
982
+ if (objective.length > 100)
983
+ complexity_score += 1;
984
+ if (objective.split(' ').length > 20)
985
+ complexity_score += 1;
986
+ if (complexity_score >= 4)
987
+ return 'high';
988
+ if (complexity_score >= 2)
989
+ return 'medium';
990
+ return 'low';
991
+ }
992
+ /**
993
+ * Assess business impact
994
+ */
995
+ assessBusinessImpact(objective) {
996
+ const high_impact_keywords = ['critical', 'urgent', 'production', 'enterprise', 'compliance', 'security'];
997
+ const medium_impact_keywords = ['efficiency', 'automation', 'improvement', 'optimization', 'user experience'];
998
+ const objective_lower = objective.toLowerCase();
999
+ if (high_impact_keywords.some(keyword => objective_lower.includes(keyword)))
1000
+ return 'high';
1001
+ if (medium_impact_keywords.some(keyword => objective_lower.includes(keyword)))
1002
+ return 'medium';
1003
+ return 'low';
1004
+ }
1005
+ /**
1006
+ * Identify stakeholders affected by the change
1007
+ */
1008
+ identifyStakeholders(objective) {
1009
+ const stakeholders = new Set();
1010
+ const objective_lower = objective.toLowerCase();
1011
+ // Default stakeholders for any ServiceNow change
1012
+ stakeholders.add('End Users');
1013
+ stakeholders.add('System Administrators');
1014
+ // Add specific stakeholders based on objective
1015
+ if (objective_lower.includes('approval'))
1016
+ stakeholders.add('Approvers');
1017
+ if (objective_lower.includes('manager'))
1018
+ stakeholders.add('Managers');
1019
+ if (objective_lower.includes('report') || objective_lower.includes('dashboard'))
1020
+ stakeholders.add('Business Analysts');
1021
+ if (objective_lower.includes('integration'))
1022
+ stakeholders.add('IT Operations');
1023
+ if (objective_lower.includes('security') || objective_lower.includes('compliance'))
1024
+ stakeholders.add('Security Team');
1025
+ if (objective_lower.includes('catalog') || objective_lower.includes('service'))
1026
+ stakeholders.add('Service Desk');
1027
+ return Array.from(stakeholders);
1028
+ }
1029
+ /**
1030
+ * Identify hidden requirements not explicitly stated
1031
+ */
1032
+ identifyHiddenRequirements(objective) {
1033
+ const hiddenReqs = [];
1034
+ const objective_lower = objective.toLowerCase();
1035
+ // Universal hidden requirements
1036
+ hiddenReqs.push('Solution must be maintainable by current team');
1037
+ hiddenReqs.push('Performance must not degrade existing system');
1038
+ hiddenReqs.push('Solution must be scalable for future growth');
1039
+ // Context-specific hidden requirements
1040
+ if (objective_lower.includes('widget') || objective_lower.includes('portal')) {
1041
+ hiddenReqs.push('Must work across all browsers and devices');
1042
+ hiddenReqs.push('Must meet accessibility standards');
1043
+ }
1044
+ if (objective_lower.includes('integration')) {
1045
+ hiddenReqs.push('Must handle integration failures gracefully');
1046
+ hiddenReqs.push('Must maintain data consistency');
1047
+ }
1048
+ if (objective_lower.includes('workflow') || objective_lower.includes('automation')) {
1049
+ hiddenReqs.push('Must handle exceptions and edge cases');
1050
+ hiddenReqs.push('Must provide clear audit trail');
1051
+ }
1052
+ return hiddenReqs;
1053
+ }
1054
+ /**
1055
+ * Define clear success criteria
1056
+ */
1057
+ defineSuccessCriteria(objective) {
1058
+ const criteria = [];
1059
+ const objective_lower = objective.toLowerCase();
1060
+ // Universal success criteria
1061
+ criteria.push('Solution deployed without system disruption');
1062
+ criteria.push('All stakeholders can use the solution effectively');
1063
+ criteria.push('Performance meets or exceeds baseline requirements');
1064
+ // Specific success criteria based on objective
1065
+ if (objective_lower.includes('widget') || objective_lower.includes('dashboard')) {
1066
+ criteria.push('Users can access information faster than before');
1067
+ criteria.push('User satisfaction with interface is positive');
1068
+ }
1069
+ if (objective_lower.includes('workflow') || objective_lower.includes('automation')) {
1070
+ criteria.push('Process time reduced compared to manual process');
1071
+ criteria.push('Error rate is lower than manual process');
1072
+ }
1073
+ if (objective_lower.includes('integration')) {
1074
+ criteria.push('Data flows correctly between systems');
1075
+ criteria.push('Integration performs within SLA requirements');
1076
+ }
1077
+ return criteria;
1078
+ }
1079
+ /**
1080
+ * Identify technical risks
1081
+ */
1082
+ identifyTechnicalRisks(objective, analysis) {
1083
+ const risks = [];
1084
+ const objective_lower = objective.toLowerCase();
1085
+ if (objective_lower.includes('integration')) {
1086
+ risks.push({
1087
+ type: 'technical',
1088
+ description: 'Integration points may fail or perform poorly',
1089
+ impact: 'high',
1090
+ likelihood: 'medium',
1091
+ mitigation: 'Implement robust error handling and monitoring'
1092
+ });
1093
+ }
1094
+ if (objective_lower.includes('widget') || objective_lower.includes('custom')) {
1095
+ risks.push({
1096
+ type: 'technical',
1097
+ description: 'Custom code may conflict with platform updates',
1098
+ impact: 'medium',
1099
+ likelihood: 'medium',
1100
+ mitigation: 'Follow platform best practices and test thoroughly'
1101
+ });
1102
+ }
1103
+ if (analysis.complexity === 'high') {
1104
+ risks.push({
1105
+ type: 'technical',
1106
+ description: 'High complexity increases chance of defects',
1107
+ impact: 'high',
1108
+ likelihood: 'high',
1109
+ mitigation: 'Break down into smaller phases with thorough testing'
1110
+ });
1111
+ }
1112
+ return risks;
1113
+ }
1114
+ /**
1115
+ * Identify business risks
1116
+ */
1117
+ identifyBusinessRisks(objective, analysis) {
1118
+ const risks = [];
1119
+ if (analysis.businessImpact === 'high') {
1120
+ risks.push({
1121
+ type: 'business',
1122
+ description: 'High business impact means high visibility and pressure',
1123
+ impact: 'high',
1124
+ likelihood: 'medium',
1125
+ mitigation: 'Ensure thorough testing and stakeholder communication'
1126
+ });
1127
+ }
1128
+ if (analysis.stakeholders.length > 5) {
1129
+ risks.push({
1130
+ type: 'business',
1131
+ description: 'Many stakeholders increase coordination complexity',
1132
+ impact: 'medium',
1133
+ likelihood: 'high',
1134
+ mitigation: 'Establish clear communication plan and change management'
1135
+ });
1136
+ }
1137
+ return risks;
1138
+ }
1139
+ /**
1140
+ * Identify operational risks
1141
+ */
1142
+ identifyOperationalRisks(objective, analysis) {
1143
+ const risks = [];
1144
+ const objective_lower = objective.toLowerCase();
1145
+ if (objective_lower.includes('automation') || objective_lower.includes('workflow')) {
1146
+ risks.push({
1147
+ type: 'operational',
1148
+ description: 'Automated processes may fail and require manual intervention',
1149
+ impact: 'medium',
1150
+ likelihood: 'medium',
1151
+ mitigation: 'Build in manual override capabilities and monitoring'
1152
+ });
1153
+ }
1154
+ return risks;
1155
+ }
1156
+ /**
1157
+ * Identify compliance risks
1158
+ */
1159
+ identifyComplianceRisks(objective, analysis) {
1160
+ const risks = [];
1161
+ const objective_lower = objective.toLowerCase();
1162
+ if (objective_lower.includes('data') || objective_lower.includes('integration')) {
1163
+ risks.push({
1164
+ type: 'compliance',
1165
+ description: 'Data handling may not meet privacy or security requirements',
1166
+ impact: 'high',
1167
+ likelihood: 'low',
1168
+ mitigation: 'Review with security and compliance teams'
1169
+ });
1170
+ }
1171
+ return risks;
1172
+ }
1173
+ /**
1174
+ * Calculate overall risk level
1175
+ */
1176
+ calculateOverallRisk(risks) {
1177
+ const high_risk_count = risks.filter(r => r.impact === 'high' && r.likelihood === 'high').length;
1178
+ const medium_risk_count = risks.filter(r => (r.impact === 'high' && r.likelihood === 'medium') ||
1179
+ (r.impact === 'medium' && r.likelihood === 'high')).length;
1180
+ if (high_risk_count > 0)
1181
+ return 'high';
1182
+ if (medium_risk_count > 1)
1183
+ return 'high';
1184
+ if (medium_risk_count > 0 || risks.length > 3)
1185
+ return 'medium';
1186
+ return 'low';
1187
+ }
1188
+ /**
1189
+ * Develop mitigation strategies for critical risks
1190
+ */
1191
+ developMitigationStrategies(criticalRisks) {
1192
+ const strategies = criticalRisks.map(risk => risk.mitigation);
1193
+ // Add general mitigation strategies
1194
+ strategies.push('Implement comprehensive testing at each phase');
1195
+ strategies.push('Establish rollback procedures before deployment');
1196
+ strategies.push('Monitor solution performance post-deployment');
1197
+ return [...new Set(strategies)]; // Remove duplicates
1198
+ }
1199
+ /**
1200
+ * Design solution architecture based on strategic analysis
1201
+ */
1202
+ async designSolutionArchitecture(problemAnalysis, riskAssessment) {
1203
+ this.logger.info('🏗️ Designing Strategic Solution Architecture...');
1204
+ // Determine optimal approach based on complexity and risks
1205
+ let approach = 'standard';
1206
+ let recommendedAgents = ['researcher', 'widget-creator', 'tester'];
1207
+ if (problemAnalysis.complexity === 'high' || riskAssessment.overallRisk === 'high') {
1208
+ approach = 'phased-implementation';
1209
+ recommendedAgents = ['researcher', 'app-architect', 'widget-creator', 'security-specialist', 'tester'];
1210
+ }
1211
+ if (riskAssessment.criticalRisks.length > 2) {
1212
+ approach = 'risk-first-architecture';
1213
+ recommendedAgents.unshift('security-specialist');
1214
+ }
1215
+ // Add specialized agents based on problem domain
1216
+ const objective_lower = problemAnalysis.coreProblem.toLowerCase();
1217
+ if (objective_lower.includes('integration')) {
1218
+ recommendedAgents.push('integration-specialist');
1219
+ }
1220
+ if (objective_lower.includes('workflow') || objective_lower.includes('process')) {
1221
+ recommendedAgents.push('flow-builder');
1222
+ }
1223
+ if (objective_lower.includes('performance')) {
1224
+ recommendedAgents.push('performance-specialist');
1225
+ }
1226
+ return {
1227
+ approach,
1228
+ recommendedAgents: [...new Set(recommendedAgents)], // Remove duplicates
1229
+ implementationSteps: this.generateImplementationSteps(approach, problemAnalysis),
1230
+ qualityGates: this.defineQualityGates(problemAnalysis, riskAssessment),
1231
+ monitoringStrategy: this.defineMonitoringStrategy(problemAnalysis)
1232
+ };
1233
+ }
1234
+ /**
1235
+ * Generate implementation steps based on approach
1236
+ */
1237
+ generateImplementationSteps(approach, problemAnalysis) {
1238
+ const baseSteps = [
1239
+ 'Validate requirements with stakeholders',
1240
+ 'Create proof of concept',
1241
+ 'Implement core functionality',
1242
+ 'Conduct security review',
1243
+ 'Perform comprehensive testing',
1244
+ 'Deploy with monitoring'
1245
+ ];
1246
+ if (approach === 'phased-implementation') {
1247
+ return [
1248
+ 'Phase 1: Research and architecture design',
1249
+ 'Phase 2: Build minimal viable solution',
1250
+ 'Phase 3: Add advanced features',
1251
+ 'Phase 4: Performance optimization',
1252
+ 'Phase 5: Full deployment and monitoring'
1253
+ ];
1254
+ }
1255
+ else if (approach === 'risk-first-architecture') {
1256
+ return [
1257
+ 'Risk mitigation planning',
1258
+ 'Security architecture review',
1259
+ ...baseSteps,
1260
+ 'Post-deployment risk validation'
1261
+ ];
1262
+ }
1263
+ return baseSteps;
1264
+ }
1265
+ /**
1266
+ * Define quality gates based on analysis
1267
+ */
1268
+ defineQualityGates(problemAnalysis, riskAssessment) {
1269
+ const gates = [
1270
+ 'Requirements validation complete',
1271
+ 'Architecture review passed',
1272
+ 'Code review completed',
1273
+ 'Security scan passed',
1274
+ 'Performance benchmarks met'
1275
+ ];
1276
+ if (riskAssessment.overallRisk === 'high') {
1277
+ gates.unshift('Risk mitigation plan approved');
1278
+ gates.push('Rollback procedures tested');
1279
+ }
1280
+ if (problemAnalysis.businessImpact === 'high') {
1281
+ gates.push('Stakeholder sign-off obtained');
1282
+ gates.push('Production readiness review passed');
1283
+ }
1284
+ return gates;
1285
+ }
1286
+ /**
1287
+ * Define monitoring strategy
1288
+ */
1289
+ defineMonitoringStrategy(problemAnalysis) {
1290
+ return {
1291
+ metrics: [
1292
+ 'System performance indicators',
1293
+ 'User experience metrics',
1294
+ 'Error rates and failure patterns',
1295
+ 'Business impact measurements'
1296
+ ],
1297
+ alerting: [
1298
+ 'Performance degradation alerts',
1299
+ 'Error threshold alerts',
1300
+ 'User satisfaction alerts'
1301
+ ],
1302
+ reporting: [
1303
+ 'Daily operational health reports',
1304
+ 'Weekly business impact reports',
1305
+ 'Monthly optimization recommendations'
1306
+ ]
1307
+ };
1308
+ }
948
1309
  }
949
- // Close memory system
950
- this.memory.close();
1310
+ exports.ServiceNowQueen = ServiceNowQueen;
951
1311
  //# sourceMappingURL=servicenow-queen.js.map