snow-flow 3.3.2 → 3.3.4

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.
@@ -3,39 +3,6 @@
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
- })();
39
6
  Object.defineProperty(exports, "__esModule", { value: true });
40
7
  exports.ServiceNowQueen = void 0;
41
8
  const queen_memory_1 = require("./queen-memory");
@@ -44,9 +11,8 @@ const agent_factory_1 = require("./agent-factory");
44
11
  const mcp_execution_bridge_1 = require("./mcp-execution-bridge");
45
12
  const theme_manager_1 = require("../utils/theme-manager");
46
13
  const dependency_detector_1 = require("../utils/dependency-detector");
47
- const gap_analysis_engine_1 = require("../intelligence/gap-analysis-engine");
14
+ // Gap Analysis Engine removed - using direct MCP approach
48
15
  const logger_1 = require("../utils/logger");
49
- const crypto = __importStar(require("crypto"));
50
16
  class ServiceNowQueen {
51
17
  constructor(config = {}) {
52
18
  this.config = {
@@ -63,12 +29,12 @@ class ServiceNowQueen {
63
29
  this.neuralLearning = new neural_learning_1.NeuralLearning(this.memory);
64
30
  this.agentFactory = new agent_factory_1.AgentFactory(this.memory);
65
31
  this.mcpBridge = new mcp_execution_bridge_1.MCPExecutionBridge(this.memory);
66
- this.gapAnalysisEngine = new gap_analysis_engine_1.GapAnalysisEngine(this.mcpBridge, this.logger, this.config.autoPermissions);
32
+ // Gap analysis integrated directly into MCP workflow
67
33
  this.activeTasks = new Map();
68
34
  if (this.config.debugMode) {
69
35
  this.logger.info('šŸ ServiceNow Queen Agent initialized with hive-mind intelligence');
70
36
  this.logger.info('šŸ”Œ MCP Execution Bridge connected for real ServiceNow operations');
71
- this.logger.info('🧠 Intelligent Gap Analysis Engine ready for beyond-MCP configurations');
37
+ this.logger.info('🧠 ServiceNow integration engine ready for MCP operations');
72
38
  }
73
39
  }
74
40
  /**
@@ -143,241 +109,277 @@ class ServiceNowQueen {
143
109
  this.activeTasks.set(taskId, task);
144
110
  // 🚨 PHASE 5: INTELLIGENT GAP ANALYSIS (Beyond MCP Tools)
145
111
  this.logger.info('🧠 Step 4: Running Intelligent Gap Analysis...');
146
- let gapAnalysisResult = null;
112
+ // Gap analysis now integrated into MCP workflow
147
113
  try {
148
- gapAnalysisResult = await this.gapAnalysisEngine.analyzeAndResolve(objective, {
149
- autoPermissions: this.config.autoPermissions,
150
- environment: 'development',
151
- enableAutomation: true,
152
- includeManualGuides: true,
153
- riskTolerance: 'medium'
154
- });
155
- this.logger.info(`šŸ“Š Gap Analysis Complete:`);
156
- this.logger.info(` • Total Requirements: ${gapAnalysisResult.totalRequirements}`);
157
- this.logger.info(` • MCP Coverage: ${gapAnalysisResult.mcpCoverage.coveragePercentage}%`);
158
- this.logger.info(` • Automated: ${gapAnalysisResult.summary.successfulAutomation} configurations`);
159
- this.logger.info(` • Manual Work: ${gapAnalysisResult.summary.requiresManualWork} items`);
160
- // Display manual instructions if needed
161
- if (gapAnalysisResult.summary.requiresManualWork > 0) {
162
- this.logger.info('\nšŸ“‹ Manual Configuration Required:');
163
- gapAnalysisResult.nextSteps.manual.forEach(step => this.logger.info(` • ${step}`));
164
- if (gapAnalysisResult.manualGuides) {
165
- this.logger.info('\nšŸ“š Detailed manual guides available in gap _analysis result');
166
- }
167
- }
168
- // Display automation successes
169
- if (gapAnalysisResult.summary.successfulAutomation > 0) {
170
- this.logger.info('\nāœ… Automated Configurations:');
171
- gapAnalysisResult.nextSteps.automated.forEach(step => this.logger.info(` • ${step}`));
172
- }
173
- // Display recommendations
174
- if (gapAnalysisResult.nextSteps.recommendations.length > 0) {
175
- this.logger.info('\nšŸ’” Recommendations:');
176
- gapAnalysisResult.nextSteps.recommendations.forEach(rec => this.logger.info(` • ${rec}`));
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');
177
138
  }
178
- // Store gap _analysis result in task for later reference
179
- task.gapAnalysis = gapAnalysisResult;
180
139
  }
181
- catch (gapError) {
182
- console.warn(`āš ļø Gap Analysis failed: ${gapError instanceof Error ? gapError.message : 'Unknown error'}`);
183
- this.logger.info('šŸ”„ Continuing with standard MCP workflow...');
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}`));
184
144
  }
185
- // Phase 6: Spawn optimal agent swarm
186
- const agents = this.spawnOptimalSwarm(task, _analysis);
187
- // Phase 7: Execute coordinated deployment
188
- task.status = 'executing';
189
- const result = await this.coordinateExecution(task, agents, _analysis);
190
- // Phase 8: Learn from execution
191
- const duration = Date.now() - startTime;
192
- this.learnFromExecution(task, agents, result, duration, null);
193
- task.status = 'completed';
194
- task.result = result;
195
- if (this.config.debugMode) {
196
- this.logger.info(`āœ… Queen completed objective in ${duration}ms`);
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}`));
197
149
  }
198
- return result;
199
- }
200
- catch (error) {
201
- const duration = Date.now() - startTime;
202
- await this.handleExecutionFailure(taskId, objective, error, duration);
203
- throw error;
204
- }
205
- finally {
206
- this.cleanupTask(taskId);
207
- }
208
- }
209
- spawnOptimalSwarm(task, _analysis) {
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;
210
167
  if (this.config.debugMode) {
211
- this.logger.info(`šŸ› Spawning swarm for ${task.type} task (complexity: ${_analysis.estimatedComplexity})`);
212
- }
213
- // Use learned patterns or optimal sequence
214
- const agentTypes = _analysis.suggestedPattern?.agentSequence ||
215
- this.agentFactory.getOptimalAgentSequence(task.type, _analysis.estimatedComplexity);
216
- // Spawn agent swarm
217
- const agents = this.agentFactory.spawnAgentSwarm(agentTypes, task.id);
218
- if (this.config.debugMode) {
219
- this.logger.info(`šŸ‘„ Spawned ${agents.length} agents: ${agents.map(a => a.type).join(', ')}`);
220
- }
221
- return agents;
222
- }
223
- async coordinateExecution(task, agents, _analysis) {
224
- const results = [];
225
- try {
226
- // Execute agents in optimal sequence
227
- if (this.shouldExecuteInParallel(agents)) {
228
- results.push(...await this.executeAgentsInParallel(agents, task.objective));
229
- }
230
- else {
231
- results.push(...await this.executeAgentsSequentially(agents, task.objective));
232
- }
233
- // Coordinate final deployment using MCP tools
234
- const deploymentResult = await this.executeFinalDeployment(task, results, _analysis);
235
- return {
236
- taskId: task.id,
237
- objective: task.objective,
238
- agentResults: results,
239
- deploymentResult,
240
- artifacts: task.artifacts
241
- };
242
- }
243
- catch (error) {
244
- // Attempt recovery or fallback
245
- return await this.attemptRecovery(task, agents, error);
168
+ this.logger.info(`āœ… Queen completed objective in ${duration}ms`);
246
169
  }
170
+ return result;
247
171
  }
248
- shouldExecuteInParallel(agents) {
249
- // Parallel execution for independent agents
250
- const independentAgents = ['researcher', 'tester', 'script-writer'];
251
- return agents.some(agent => independentAgents.includes(agent.type));
172
+ catch(error) {
173
+ const duration = Date.now() - startTime;
174
+ await this.handleExecutionFailure(taskId, objective, error, duration);
175
+ throw error;
252
176
  }
253
- async executeAgentsInParallel(agents, objective) {
254
- if (this.config.debugMode) {
255
- this.logger.info('⚔ Executing agents in parallel');
256
- }
257
- const promises = agents.map(agent => this.agentFactory.executeAgentTask(agent.id, objective));
258
- return await Promise.all(promises);
259
- }
260
- async executeAgentsSequentially(agents, objective) {
261
- if (this.config.debugMode) {
262
- this.logger.info('šŸ”„ Executing agents sequentially');
263
- }
264
- const results = [];
265
- for (const agent of agents) {
266
- const result = await this.agentFactory.executeAgentTask(agent.id, objective);
267
- results.push(result);
268
- // Allow agents to coordinate between executions
269
- this.facilitateAgentCoordination(agent, results);
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
+ });
270
270
  }
271
- return results;
272
271
  }
273
- facilitateAgentCoordination(currentAgent, previousResults) {
274
- // Send relevant results to collaborative agents
275
- const activeAgents = this.agentFactory.getActiveAgents();
276
- for (const agent of activeAgents) {
277
- if (agent.id !== currentAgent.id) {
278
- this.agentFactory.sendAgentMessage(currentAgent.id, agent.id, 'result', {
279
- results: previousResults.slice(-1)[0], // Latest result
280
- fromAgent: currentAgent.type
281
- });
282
- }
283
- }
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
+ });
284
297
  }
285
- async executeFinalDeployment(task, agentResults, _analysis) {
286
- if (this.config.debugMode) {
287
- this.logger.info('šŸš€ Executing final deployment with MCP tools');
288
- }
289
- // The Queen coordinates the actual MCP tool calls based on agent recommendations
290
- const deploymentPlan = this.createDeploymentPlan(task, agentResults, _analysis);
291
- try {
292
- // Execute deployment using the unified deployment API
293
- const deploymentResult = await this.executeDeploymentPlan(deploymentPlan);
294
- // Track artifacts created
295
- if (deploymentResult.sys_id) {
296
- task.artifacts.push(deploymentResult.sys_id);
297
- // Store artifact in memory for future reference
298
- this.memory.storeArtifact({
299
- type: task.type,
300
- name: deploymentResult.name || task.objective,
301
- sys_id: deploymentResult.sys_id,
302
- config: deploymentResult.config || {},
303
- dependencies: _analysis.dependencies
304
- });
305
- }
306
- return deploymentResult;
307
- }
308
- catch (error) {
309
- if (this.config.debugMode) {
310
- console.error('āŒ Deployment failed:', error);
311
- }
312
- throw error;
313
- }
298
+ return deploymentResult;
299
+ }
300
+ catch (error) {
301
+ if (this.config.debugMode) {
302
+ console.error('āŒ Deployment failed:', error);
314
303
  }
315
- createDeploymentPlan(task, agentResults, _analysis) {
316
- // Extract deployment instructions from agent results
317
- const widgetCreator = agentResults.find(r => r.agentType === 'widget-creator');
318
- const flowBuilder = agentResults.find(r => r.agentType === 'flow-builder');
319
- const scriptWriter = agentResults.find(r => r.agentType === 'script-writer');
320
- const catalogManager = agentResults.find(r => r.agentType === 'catalog-manager');
321
- if (task.type === 'widget' && widgetCreator) {
322
- return {
323
- type: 'widget',
324
- mcpTool: 'snow_deploy',
325
- config: this.extractWidgetConfig(task.objective, agentResults),
326
- autoPermissions: this.config.autoPermissions // Pass auto-permissions flag for dependency handling
327
- };
328
- }
329
- // Flow creation is no longer supported - use ServiceNow Flow Designer directly
330
- if (task.type === 'flow') {
331
- throw new Error('Flow creation is no longer supported in Snow-Flow. Please use ServiceNow Flow Designer directly.');
332
- }
333
- if (task.type === 'script' && scriptWriter) {
334
- return {
335
- type: 'script',
336
- mcpTool: 'snow_create_script_include',
337
- config: this.extractScriptConfig(task.objective, agentResults)
338
- };
339
- }
340
- // Default deployment plan
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) {
341
315
  return {
342
- type: task.type,
316
+ type: 'widget',
343
317
  mcpTool: 'snow_deploy',
344
- instruction: task.objective
318
+ config: this.extractWidgetConfig(task.objective, agentResults),
319
+ autoPermissions: this.config.autoPermissions // Pass auto-permissions flag for dependency handling
345
320
  };
346
321
  }
347
- extractWidgetConfig(objective, agentResults) {
348
- // Extract widget configuration from agent results
349
- const widgetResult = agentResults.find(r => r.agentType === 'widget-creator');
350
- return {
351
- name: this.generateArtifactName(objective, 'widget'),
352
- title: this.generateArtifactTitle(objective),
353
- template: this.generateWidgetTemplate(objective),
354
- css: this.generateWidgetCss(objective),
355
- client_script: this.generateClientScript(objective),
356
- server_script: this.generateServerScript(objective),
357
- demo_data: this.generateDemoData(objective)
358
- };
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.');
359
325
  }
360
- extractScriptConfig(objective, agentResults) {
326
+ if (task.type === 'script' && scriptWriter) {
361
327
  return {
362
- name: this.generateArtifactName(objective, 'script'),
363
- description: `Auto-generated script for: ${objective}`,
364
- script: this.generateScriptCode(objective)
328
+ type: 'script',
329
+ mcpTool: 'snow_create_script_include',
330
+ config: this.extractScriptConfig(task.objective, agentResults)
365
331
  };
366
332
  }
367
- // Simple artifact generation based on objective analysis
368
- generateArtifactName(objective, type) {
369
- const words = objective.toLowerCase().replace(/[^a-z\s]/g, '').split(/\s+/).filter(w => w.length > 2);
370
- const key_words = words.slice(0, 3).join('_');
371
- return `${key_words}_${type}`;
372
- }
373
- generateArtifactTitle(objective) {
374
- return objective.charAt(0).toUpperCase() + objective.slice(1);
375
- }
376
- generateWidgetTemplate(objective) {
377
- const isChart = objective.toLowerCase().includes('chart') || objective.toLowerCase().includes('graph');
378
- const isDashboard = objective.toLowerCase().includes('dashboard');
379
- if (isChart) {
380
- return `
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 `
381
383
  <div class="panel panel-default">
382
384
  <div class="panel-heading">
383
385
  <h3 class="panel-title">{{data.title || '${this.generateArtifactTitle(objective)}'}}</h3>
@@ -386,9 +388,9 @@ class ServiceNowQueen {
386
388
  <canvas id="chart-{{::data.widget_id}}" width="400" height="200"></canvas>
387
389
  </div>
388
390
  </div>`;
389
- }
390
- if (isDashboard) {
391
- return `
391
+ }
392
+ if (isDashboard) {
393
+ return `
392
394
  <div class="row">
393
395
  <div class="col-md-12">
394
396
  <div class="panel panel-default">
@@ -408,8 +410,8 @@ class ServiceNowQueen {
408
410
  </div>
409
411
  </div>
410
412
  </div>`;
411
- }
412
- return `
413
+ }
414
+ return `
413
415
  <div class="panel panel-default">
414
416
  <div class="panel-heading">
415
417
  <h3 class="panel-title">{{data.title || '${this.generateArtifactTitle(objective)}'}}</h3>
@@ -428,9 +430,11 @@ class ServiceNowQueen {
428
430
  </div>
429
431
  </div>
430
432
  </div>`;
431
- }
432
- generateWidgetCss(objective) {
433
- return `
433
+ }
434
+ generateWidgetCss(objective, string);
435
+ string;
436
+ {
437
+ return `
434
438
  .panel {
435
439
  margin-bottom: 20px;
436
440
  border-radius: 6px;
@@ -462,11 +466,13 @@ class ServiceNowQueen {
462
466
  margin-bottom: 15px;
463
467
  }
464
468
  }`;
465
- }
466
- generateClientScript(objective) {
467
- const isChart = objective.toLowerCase().includes('chart') || objective.toLowerCase().includes('graph');
468
- if (isChart) {
469
- return `
469
+ }
470
+ generateClientScript(objective, string);
471
+ string;
472
+ {
473
+ const isChart = objective.toLowerCase().includes('chart') || objective.toLowerCase().includes('graph');
474
+ if (isChart) {
475
+ return `
470
476
  function($scope) {
471
477
  var c = this;
472
478
 
@@ -495,8 +501,8 @@ function($scope) {
495
501
  }
496
502
  };
497
503
  }`;
498
- }
499
- return `
504
+ }
505
+ return `
500
506
  function($scope) {
501
507
  var c = this;
502
508
 
@@ -516,11 +522,13 @@ function($scope) {
516
522
  c.server.refresh();
517
523
  };
518
524
  }`;
519
- }
520
- generateServerScript(objective) {
521
- const lowerObjective = objective.toLowerCase();
522
- if (lowerObjective.includes('incident')) {
523
- return `
525
+ }
526
+ generateServerScript(objective, string);
527
+ string;
528
+ {
529
+ const lowerObjective = objective.toLowerCase();
530
+ if (lowerObjective.includes('incident')) {
531
+ return `
524
532
  (function() {
525
533
  data.title = options.title || 'Incidents Dashboard';
526
534
  data.widget_id = gs.generateGUID();
@@ -561,8 +569,8 @@ function($scope) {
561
569
  data.chartType = 'doughnut';
562
570
  }
563
571
  })();`;
564
- }
565
- return `
572
+ }
573
+ return `
566
574
  (function() {
567
575
  data.title = options.title || '${this.generateArtifactTitle(objective)}';
568
576
  data.widget_id = gs.generateGUID();
@@ -583,20 +591,24 @@ function($scope) {
583
591
  }
584
592
  ];
585
593
  })();`;
586
- }
587
- generateDemoData(objective) {
588
- return {
589
- title: this.generateArtifactTitle(objective),
590
- items: [
591
- {
592
- title: 'Demo Item 1',
593
- description: 'Sample data for testing the widget'
594
- }
595
- ]
596
- };
597
- }
598
- generateScriptCode(objective) {
599
- return `
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 `
600
612
  // Auto-generated script for: ${objective}
601
613
  // Generated by ServiceNow Queen Agent
602
614
 
@@ -609,294 +621,331 @@ function($scope) {
609
621
  message: 'Script executed successfully'
610
622
  };
611
623
  })();`;
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);
612
659
  }
613
- async executeDeploymentPlan(plan) {
614
- // Execute real MCP tools through the bridge
615
- if (this.config.debugMode) {
616
- this.logger.info('šŸš€ Executing deployment plan with MCP Bridge');
617
- }
618
- // Create agent recommendation from plan
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) => {
619
699
  const recommendation = {
620
700
  agentId: 'queen-agent',
621
701
  agentType: 'queen',
622
- action: `deploy-${plan.type}`,
623
- tool: plan.mcpTool,
624
- server: this.getServerForTool(plan.mcpTool),
625
- params: plan.config || {},
626
- reasoning: `Deploying ${plan.type} artifact as requested`,
702
+ action: 'find-theme',
703
+ tool: 'snow_find_artifact',
704
+ server: 'intelligent',
705
+ params,
706
+ reasoning: 'Finding Service Portal theme for dependency injection',
627
707
  confidence: 0.95
628
708
  };
629
- // Execute through MCP bridge
630
709
  const result = await this.mcpBridge.executeAgentRecommendation({ id: 'queen-agent', type: 'queen' }, recommendation);
631
- if (result.success && result.toolResult) {
632
- const deploymentResult = {
633
- success: true,
634
- type: plan.type,
635
- name: plan.config?.name || result.toolResult.name,
636
- sys_id: result.toolResult.sys_id, // Real sys_id from ServiceNow!
637
- config: plan.config,
638
- mcpTool: plan.mcpTool,
639
- executionTime: result.executionTime
640
- };
641
- // Handle dependency injection for widgets
642
- if (plan.type === 'widget' && plan.config) {
643
- await this.handleWidgetDependencies(plan.config, plan.autoPermissions);
644
- }
645
- return deploymentResult;
646
- }
647
- else {
648
- throw new Error(`MCP execution failed: ${result.error || 'Unknown error'}`);
649
- }
650
- }
651
- getServerForTool(tool) {
652
- // Map tools to their servers
653
- const toolServerMap = {
654
- 'snow_deploy': 'deployment',
655
- 'snow_deploy_widget': 'deployment',
656
- 'snow_deploy_flow': 'deployment',
657
- 'snow_find_artifact': 'intelligent',
658
- 'snow_update_set_create': 'update-set',
659
- 'snow_get_by_sysid': 'intelligent',
660
- 'snow_edit_by_sysid': 'intelligent'
661
- };
662
- return toolServerMap[tool] || 'deployment';
663
- }
664
- async handleWidgetDependencies(widgetConfig, autoPermissions) {
665
- try {
666
- // Detect dependencies in widget code
667
- const dependencies = dependency_detector_1.DependencyDetector.analyzeWidget(widgetConfig);
668
- if (dependencies.length === 0) {
669
- return; // No dependencies needed
670
- }
671
- this.logger.info(`\nšŸ“¦ Detected ${dependencies.length} external dependencies in widget:`);
672
- dependencies.forEach(dep => {
673
- this.logger.info(` • ${dep.name} - ${dep.description}`);
674
- });
675
- // Create MCP tools wrapper for theme manager
676
- const mcpTools = {
677
- snow_find_artifact: async (params) => {
678
- const recommendation = {
679
- agentId: 'queen-agent',
680
- agentType: 'queen',
681
- action: 'find-theme',
682
- tool: 'snow_find_artifact',
683
- server: 'intelligent',
684
- params,
685
- reasoning: 'Finding Service Portal theme for dependency injection',
686
- confidence: 0.95
687
- };
688
- const result = await this.mcpBridge.executeAgentRecommendation({ id: 'queen-agent', type: 'queen' }, recommendation);
689
- return result.toolResult;
690
- },
691
- snow_comprehensive_search: async (params) => {
692
- const recommendation = {
693
- agentId: 'queen-agent',
694
- agentType: 'queen',
695
- action: 'search-themes',
696
- tool: 'snow_comprehensive_search',
697
- server: 'intelligent',
698
- params,
699
- reasoning: 'Searching for Service Portal themes',
700
- confidence: 0.95
701
- };
702
- const result = await this.mcpBridge.executeAgentRecommendation({ id: 'queen-agent', type: 'queen' }, recommendation);
703
- return result.toolResult;
704
- },
705
- snow_get_by_sysid: async (params) => {
706
- const recommendation = {
707
- agentId: 'queen-agent',
708
- agentType: 'queen',
709
- action: 'get-theme',
710
- tool: 'snow_get_by_sysid',
711
- server: 'intelligent',
712
- params,
713
- reasoning: 'Getting Service Portal theme details',
714
- confidence: 0.95
715
- };
716
- const result = await this.mcpBridge.executeAgentRecommendation({ id: 'queen-agent', type: 'queen' }, recommendation);
717
- return result.toolResult;
718
- },
719
- snow_edit_by_sysid: async (params) => {
720
- const recommendation = {
721
- agentId: 'queen-agent',
722
- agentType: 'queen',
723
- action: 'update-theme',
724
- tool: 'snow_edit_by_sysid',
725
- server: 'intelligent',
726
- params,
727
- reasoning: 'Updating Service Portal theme with dependencies',
728
- confidence: 0.95
729
- };
730
- const result = await this.mcpBridge.executeAgentRecommendation({ id: 'queen-agent', type: 'queen' }, recommendation);
731
- return result.toolResult;
732
- }
733
- };
734
- // Update theme with dependencies
735
- const result = await theme_manager_1.ServicePortalThemeManager.updateThemeWithDependencies(dependencies, mcpTools, {
736
- autoPermissions,
737
- skipPrompt: autoPermissions, // Skip prompt if auto-permissions enabled
738
- useMinified: true
739
- });
740
- if (result.success) {
741
- this.logger.info(`āœ… ${result.message}`);
742
- }
743
- else {
744
- this.logger.warn(`āš ļø Dependencies not installed: ${result.message}`);
745
- this.logger.info('šŸ’” You may need to manually add these dependencies to your Service Portal theme');
746
- }
747
- }
748
- catch (error) {
749
- console.error('āŒ Error handling widget dependencies:', error.message);
750
- // Don't fail the deployment, just warn
751
- this.logger.warn('āš ļø Widget deployed successfully but dependencies may need manual installation');
752
- }
753
- }
754
- async attemptRecovery(task, agents, error) {
755
- if (this.config.debugMode) {
756
- this.logger.info(`šŸ”„ Attempting recovery for task ${task.id}`);
757
- }
758
- // Try with reduced complexity or different agent sequence
759
- const fallbackResult = {
760
- taskId: task.id,
761
- objective: task.objective,
762
- status: 'recovered',
763
- error: error.message,
764
- fallbackApplied: true
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
765
722
  };
766
- return fallbackResult;
767
- }
768
- learnFromExecution(task, agents, result, duration, error) {
769
- const agentTypes = agents.map(a => a.type);
770
- if (error) {
771
- // Learn from failure
772
- this.neuralLearning.learnFromFailure(task, error.message, agentTypes);
773
- this.memory.recordTaskCompletion(task.id, task.objective, task.type, agentTypes, false, duration);
774
- }
775
- else {
776
- // Learn from success
777
- this.neuralLearning.learnFromSuccess(task, duration, agentTypes);
778
- this.memory.recordTaskCompletion(task.id, task.objective, task.type, agentTypes, true, duration);
779
- }
780
- if (this.config.debugMode) {
781
- this.logger.info(`šŸ“š Queen learned from ${error ? 'failure' : 'success'}: ${task.objective}`);
782
- }
783
- }
784
- async handleExecutionFailure(taskId, objective, error, duration) {
785
- const task = this.activeTasks.get(taskId);
786
- if (task) {
787
- task.status = 'failed';
788
- task.error = error.message;
789
- // Learn from failure
790
- this.memory.storeLearning(`failure_${task.type}`, `Failed: ${objective} - Error: ${error.message}`, 0.8);
791
- }
792
- if (this.config.debugMode) {
793
- console.error(`āŒ Task ${taskId} failed after ${duration}ms:`, error.message);
794
- }
795
- }
796
- cleanupTask(taskId) {
797
- this.activeTasks.delete(taskId);
798
- this.agentFactory.cleanupCompletedAgents();
799
- }
800
- generateTaskId() {
801
- return `task_${Date.now()}_${crypto.randomBytes(4).toString('hex')}`;
802
- }
803
- // Public API methods
804
- getActiveTaskCount() {
805
- return this.activeTasks.size;
806
- }
807
- getTaskStatus(taskId) {
808
- return this.activeTasks.get(taskId) || null;
809
- }
810
- /**
811
- * Get gap _analysis results for a task
812
- */
813
- getGapAnalysisResults(taskId) {
814
- const task = this.activeTasks.get(taskId);
815
- return task?.gapAnalysis || null;
816
- }
817
- /**
818
- * Get all manual guides from gap _analysis for a task
819
- */
820
- getManualConfigurationGuides(taskId) {
821
- const gapAnalysis = this.getGapAnalysisResults(taskId);
822
- return gapAnalysis?.manualGuides || 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()
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
835
736
  };
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
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
882
750
  };
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
- }
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}`);
900
763
  }
901
- exports.ServiceNowQueen = ServiceNowQueen;
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();
948
+ }
949
+ // Close memory system
950
+ this.memory.close();
902
951
  //# sourceMappingURL=servicenow-queen.js.map