snow-flow 2.0.2 → 2.0.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.
Files changed (173) hide show
  1. package/{.claude/mcp-config.json → .mcp.json} +13 -12
  2. package/.releaserc.json +47 -0
  3. package/README.md +48 -1
  4. package/package.json +1 -1
  5. package/.claude/claude-settings.json +0 -15
  6. package/.claude/commands/analysis/README.md +0 -9
  7. package/.claude/commands/automation/README.md +0 -9
  8. package/.claude/commands/github/README.md +0 -11
  9. package/.claude/commands/helpers/standard-checkpoint-hooks.sh +0 -179
  10. package/.claude/commands/hooks/README.md +0 -11
  11. package/.claude/commands/monitoring/README.md +0 -9
  12. package/.claude/commands/optimization/README.md +0 -9
  13. package/.claude/commands/training/README.md +0 -9
  14. package/.claude/commands/workflows/README.md +0 -9
  15. package/.claude/config.json +0 -36
  16. package/.claude/helpers/github-setup.sh +0 -28
  17. package/.claude/helpers/quick-start.sh +0 -19
  18. package/.claude/helpers/setup-mcp.sh +0 -18
  19. package/.claude/settings.json +0 -114
  20. package/.claude/settings.local.json +0 -33
  21. package/.claude-flow/metrics/agent-metrics.json +0 -1
  22. package/.claude-flow/metrics/performance.json +0 -9
  23. package/.claude-flow/metrics/system-metrics.json +0 -15986
  24. package/.claude-flow/metrics/task-metrics.json +0 -10
  25. package/.roo/README.md +0 -402
  26. package/.roo/mcp-list.txt +0 -257
  27. package/.roo/mcp.json +0 -32
  28. package/.roo/workflows/basic-tdd.json +0 -32
  29. package/.roomodes +0 -201
  30. package/CLAUDE.md +0 -393
  31. package/bin/snow-flow.js +0 -3
  32. package/dist/cli.js.bak +0 -2052
  33. package/dist/config/snow-flow-config.d.ts +0 -1492
  34. package/dist/config/snow-flow-config.js +0 -938
  35. package/scripts/create-env.js +0 -91
  36. package/scripts/postinstall.js +0 -30
  37. package/scripts/register-mcp-servers.js +0 -210
  38. package/scripts/reset-mcp-servers.js +0 -246
  39. package/scripts/setup-mcp.js +0 -106
  40. package/scripts/update-version.js +0 -31
  41. package/src/agents/README.md +0 -192
  42. package/src/agents/base-agent.ts +0 -251
  43. package/src/agents/coordinator.ts +0 -971
  44. package/src/agents/index.ts +0 -18
  45. package/src/agents/queen-403-handler.ts +0 -230
  46. package/src/agents/queen-agent.ts +0 -1399
  47. package/src/agents/script-writer-agent.ts +0 -769
  48. package/src/agents/security-agent.ts +0 -726
  49. package/src/agents/widget-creator-agent.ts +0 -568
  50. package/src/api/error-handling.ts +0 -1758
  51. package/src/api/natural-language-mapper.ts +0 -630
  52. package/src/api/performance-optimizer.ts +0 -891
  53. package/src/api/transaction-manager.ts +0 -754
  54. package/src/cli/deploy-artifact.ts +0 -304
  55. package/src/cli/snow-flow-cli-integration.ts +0 -434
  56. package/src/cli.ts +0 -4455
  57. package/src/cli.ts.bak +0 -5616
  58. package/src/compliance/advanced-compliance-system.ts +0 -1268
  59. package/src/compliance/index.ts +0 -19
  60. package/src/config/snow-flow-config.ts +0 -1019
  61. package/src/documentation/index.ts +0 -16
  62. package/src/documentation/self-documenting-system.ts +0 -1421
  63. package/src/dynamic-version.ts +0 -44
  64. package/src/healing/index.ts +0 -20
  65. package/src/healing/self-healing-system.ts +0 -1435
  66. package/src/health/README.md +0 -161
  67. package/src/health/system-health.ts +0 -995
  68. package/src/index.ts +0 -60
  69. package/src/intelligence/acl-analyzer.ts +0 -377
  70. package/src/intelligence/auto-resolution-engine.ts +0 -643
  71. package/src/intelligence/gap-analysis-engine.ts +0 -488
  72. package/src/intelligence/manual-instructions-generator.ts +0 -744
  73. package/src/intelligence/mcp-coverage-analyzer.ts +0 -708
  74. package/src/intelligence/multi-pass-requirements-analyzer.ts +0 -603
  75. package/src/intelligence/performance-recommendations-engine.ts +0 -1223
  76. package/src/intelligence/requirements-analyzer.ts +0 -1148
  77. package/src/intelligence/task-analyzer.ts +0 -628
  78. package/src/managers/scope-manager.ts +0 -555
  79. package/src/mcp/advanced/servicenow-advanced-features-mcp.ts +0 -16110
  80. package/src/mcp/base-mcp-server.ts +0 -660
  81. package/src/mcp/http-transport-wrapper.ts +0 -426
  82. package/src/mcp/service-discovery-client.ts +0 -312
  83. package/src/mcp/servicenow-automation-mcp-refactored.ts +0 -678
  84. package/src/mcp/servicenow-automation-mcp.ts +0 -838
  85. package/src/mcp/servicenow-deployment-mcp-refactored.ts +0 -1292
  86. package/src/mcp/servicenow-deployment-mcp.ts +0 -7244
  87. package/src/mcp/servicenow-graph-memory-mcp-refactored.ts +0 -721
  88. package/src/mcp/servicenow-graph-memory-mcp.ts +0 -832
  89. package/src/mcp/servicenow-integration-mcp-refactored.ts +0 -655
  90. package/src/mcp/servicenow-integration-mcp.ts +0 -819
  91. package/src/mcp/servicenow-intelligent-mcp-refactored.ts +0 -977
  92. package/src/mcp/servicenow-intelligent-mcp.ts +0 -4638
  93. package/src/mcp/servicenow-mcp-server.ts +0 -728
  94. package/src/mcp/servicenow-memory-mcp.ts +0 -474
  95. package/src/mcp/servicenow-operations-mcp-refactored.ts +0 -1995
  96. package/src/mcp/servicenow-operations-mcp.ts +0 -3384
  97. package/src/mcp/servicenow-platform-development-mcp-refactored.ts +0 -611
  98. package/src/mcp/servicenow-platform-development-mcp.ts +0 -970
  99. package/src/mcp/servicenow-progressive-indexer.ts +0 -370
  100. package/src/mcp/servicenow-reporting-analytics-mcp-refactored.ts +0 -695
  101. package/src/mcp/servicenow-reporting-analytics-mcp.ts +0 -1123
  102. package/src/mcp/servicenow-security-compliance-mcp-refactored.ts +0 -642
  103. package/src/mcp/servicenow-security-compliance-mcp.ts +0 -1157
  104. package/src/mcp/servicenow-update-set-mcp-refactored.ts +0 -751
  105. package/src/mcp/servicenow-update-set-mcp.ts +0 -811
  106. package/src/mcp/shared/agent-context-provider.ts +0 -365
  107. package/src/mcp/shared/base-mcp-server.ts +0 -2463
  108. package/src/mcp/shared/mcp-memory-manager.ts +0 -540
  109. package/src/mcp/shared/mcp-resource-manager.ts +0 -367
  110. package/src/mcp/snow-flow-mcp.ts +0 -911
  111. package/src/mcp/start-all-mcp-servers.ts +0 -102
  112. package/src/mcp/start-servicenow-mcp.ts +0 -67
  113. package/src/monitoring/enhanced-monitoring-system.ts +0 -1345
  114. package/src/monitoring/performance-tracker.ts +0 -777
  115. package/src/optimization/cost-optimization-engine.ts +0 -1125
  116. package/src/optimization/index.ts +0 -10
  117. package/src/queen/README.md +0 -403
  118. package/src/queen/agent-factory.ts +0 -574
  119. package/src/queen/index.ts +0 -94
  120. package/src/queen/mcp-execution-bridge.ts +0 -681
  121. package/src/queen/neural-learning.ts +0 -319
  122. package/src/queen/parallel-agent-engine.ts +0 -848
  123. package/src/queen/queen-memory-system.ts +0 -490
  124. package/src/queen/queen-memory.ts +0 -456
  125. package/src/queen/servicenow-queen.ts +0 -1029
  126. package/src/queen/types.ts +0 -87
  127. package/src/rollback/smart-rollback-system.ts +0 -866
  128. package/src/schemas/deployment.schema.json +0 -58
  129. package/src/schemas/flow.schema.json +0 -79
  130. package/src/schemas/widget.schema.json +0 -72
  131. package/src/snow-flow-system.ts +0 -541
  132. package/src/sparc/sparc-help.ts +0 -49
  133. package/src/sparc/team-sparc.ts +0 -88
  134. package/src/strategies/global-scope-strategy.ts +0 -736
  135. package/src/templates/base/application.template.json +0 -45
  136. package/src/templates/base/business_rule.template.json +0 -33
  137. package/src/templates/base/script_include.template.json +0 -18
  138. package/src/templates/base/table.template.json +0 -64
  139. package/src/templates/base/widget.template.json +0 -25
  140. package/src/templates/patterns/composite.incident-management.template.json +0 -140
  141. package/src/templates/patterns/widget.dashboard.template.json +0 -238
  142. package/src/templates/patterns/widget.datatable.template.json +0 -292
  143. package/src/testing/integration-test-suite.ts +0 -1276
  144. package/src/types/index.ts +0 -183
  145. package/src/types/neo4j-driver.d.ts +0 -23
  146. package/src/types/servicenow.types.ts +0 -307
  147. package/src/types/snow-flow.types.ts +0 -186
  148. package/src/types/todo.types.ts +0 -70
  149. package/src/utils/action-type-cache.ts +0 -286
  150. package/src/utils/agent-detector.ts +0 -573
  151. package/src/utils/artifact-tracker.ts +0 -379
  152. package/src/utils/dependency-detector.ts +0 -233
  153. package/src/utils/deployment-metadata-handler.ts +0 -518
  154. package/src/utils/error-recovery.ts +0 -680
  155. package/src/utils/logger.ts +0 -60
  156. package/src/utils/mcp-auth-middleware.ts +0 -262
  157. package/src/utils/mcp-config-manager.ts +0 -270
  158. package/src/utils/mcp-server-manager.ts +0 -446
  159. package/src/utils/mcp-tool-registry.ts +0 -298
  160. package/src/utils/migrate-snow-flow.ts +0 -98
  161. package/src/utils/oauth-html-templates.ts +0 -188
  162. package/src/utils/scope-utils.ts +0 -443
  163. package/src/utils/servicenow-client.ts +0 -3321
  164. package/src/utils/servicenow-id-generator.ts +0 -181
  165. package/src/utils/snow-memory-manager.ts +0 -605
  166. package/src/utils/snow-oauth.ts +0 -797
  167. package/src/utils/template-engine.ts +0 -463
  168. package/src/utils/theme-manager.ts +0 -295
  169. package/src/utils/unified-auth-store.ts +0 -222
  170. package/src/utils/update-set-importer.ts +0 -422
  171. package/src/utils/update-set-xml-packager.ts +0 -371
  172. package/src/utils/widget-template-generator.ts +0 -1744
  173. package/src/version.ts +0 -1950
@@ -1,1029 +0,0 @@
1
- /**
2
- * ServiceNow Queen Agent
3
- * Central coordination point for the ServiceNow hive-mind
4
- */
5
-
6
- import { ServiceNowTask, TaskAnalysis, Agent, AgentType } from './types';
7
- import { QueenMemorySystem } from './queen-memory';
8
- import { NeuralLearning } from './neural-learning';
9
- import { AgentFactory } from './agent-factory';
10
- import { MCPExecutionBridge, AgentRecommendation } from './mcp-execution-bridge';
11
- import { ServicePortalThemeManager } from '../utils/theme-manager';
12
- import { DependencyDetector } from '../utils/dependency-detector';
13
- import { GapAnalysisEngine, GapAnalysisResult } from '../intelligence/gap-analysis-engine';
14
- import { Logger } from '../utils/logger';
15
- import * as crypto from 'crypto';
16
-
17
- export interface QueenConfig {
18
- memoryPath?: string;
19
- maxConcurrentAgents?: number;
20
- learningRate?: number;
21
- debugMode?: boolean;
22
- autoPermissions?: boolean;
23
- }
24
-
25
- export class ServiceNowQueen {
26
- private memory: QueenMemorySystem;
27
- private neuralLearning: NeuralLearning;
28
- private agentFactory: AgentFactory;
29
- private mcpBridge: MCPExecutionBridge;
30
- private gapAnalysisEngine: GapAnalysisEngine;
31
- private activeTasks: Map<string, ServiceNowTask>;
32
- private config: Required<QueenConfig>;
33
- private logger: Logger;
34
-
35
- constructor(config: QueenConfig = {}) {
36
- this.config = {
37
- memoryPath: config.memoryPath,
38
- maxConcurrentAgents: config.maxConcurrentAgents || 5,
39
- learningRate: config.learningRate || 0.1,
40
- debugMode: config.debugMode || false,
41
- autoPermissions: config.autoPermissions || false
42
- };
43
-
44
- // Initialize logger
45
- this.logger = new Logger('ServiceNowQueen');
46
-
47
- // Initialize hive-mind components
48
- this.memory = new QueenMemorySystem(this.config.memoryPath);
49
- this.neuralLearning = new NeuralLearning(this.memory);
50
- this.agentFactory = new AgentFactory(this.memory);
51
- this.mcpBridge = new MCPExecutionBridge(this.memory);
52
- this.gapAnalysisEngine = new GapAnalysisEngine(this.mcpBridge, this.logger, this.config.autoPermissions);
53
- this.activeTasks = new Map();
54
-
55
- if (this.config.debugMode) {
56
- this.logger.info('🐝 ServiceNow Queen Agent initialized with hive-mind intelligence');
57
- this.logger.info('🔌 MCP Execution Bridge connected for real ServiceNow operations');
58
- this.logger.info('🧠 Intelligent Gap Analysis Engine ready for beyond-MCP configurations');
59
- }
60
- }
61
-
62
- /**
63
- * Main entry point: Execute ServiceNow objective with MCP-FIRST workflow
64
- */
65
- async executeObjective(objective: string): Promise<any> {
66
- const taskId = this.generateTaskId();
67
- const startTime = Date.now();
68
-
69
- try {
70
- if (this.config.debugMode) {
71
- this.logger.info(`🎯 Queen analyzing objective: ${objective}`);
72
- this.logger.info(`🚨 ENFORCING MCP-FIRST WORKFLOW`);
73
- }
74
-
75
- // 🚨 PHASE 1: MANDATORY MCP PRE-FLIGHT AUTHENTICATION CHECK
76
- this.logger.info('🔐 Step 1: Validating ServiceNow connection...');
77
- const authCheck = await this.mcpBridge.executeAgentRecommendation(
78
- { id: 'queen-agent', type: 'queen' },
79
- {
80
- agentId: 'queen-agent',
81
- agentType: 'queen',
82
- action: 'validate-connection',
83
- tool: 'snow_validate_live_connection',
84
- server: 'operations',
85
- params: { test_level: 'permissions' },
86
- reasoning: 'MANDATORY: Pre-flight authentication check before any ServiceNow operations',
87
- confidence: 0.95
88
- }
89
- );
90
-
91
- if (!authCheck.success) {
92
- const authError = `
93
- 🚨 ServiceNow Authentication Failed: ${authCheck.error}
94
-
95
- 🔧 Fix this now:
96
- 1. Run: snow-flow auth login
97
- 2. Check .env: SNOW_INSTANCE, SNOW_CLIENT_ID, SNOW_CLIENT_SECRET
98
- 3. Test: snow_auth_diagnostics()
99
-
100
- ❌ Cannot proceed with Queen Agent operations until authentication works!
101
- `;
102
- this.logger.error('Authentication failed:', authError);
103
- throw new Error(authError);
104
- }
105
-
106
- this.logger.info('✅ ServiceNow authentication validated');
107
-
108
- // 🚨 PHASE 2: MANDATORY SMART DISCOVERY (Prevent Duplication)
109
- this.logger.info('🔍 Step 2: Discovering existing artifacts...');
110
- const discovery = await this.mcpBridge.executeAgentRecommendation(
111
- { id: 'queen-agent', type: 'queen' },
112
- {
113
- agentId: 'queen-agent',
114
- agentType: 'queen',
115
- action: 'discover-artifacts',
116
- tool: 'snow_comprehensive_search',
117
- server: 'intelligent',
118
- params: {
119
- query: objective,
120
- include_inactive: false
121
- },
122
- reasoning: 'MANDATORY: Check for existing artifacts before creating new ones',
123
- confidence: 0.90
124
- }
125
- );
126
-
127
- if (discovery.success && discovery.toolResult?.found?.length > 0) {
128
- this.logger.info(`🔍 Found ${discovery.toolResult.found.length} existing artifacts that might be relevant:`);
129
- discovery.toolResult.found.forEach((artifact: any) => {
130
- this.logger.info(`💡 Consider reusing: ${artifact.name} (${artifact.sys_id})`);
131
- });
132
- }
133
-
134
- // Phase 3: Initial Neural Analysis (informed by MCP discovery)
135
- const _analysis = this.neuralLearning.analyzeTask(objective);
136
-
137
- // Phase 4: Create and register task
138
- const task: ServiceNowTask = {
139
- id: taskId,
140
- objective,
141
- type: _analysis.type,
142
- artifacts: [],
143
- status: 'analyzing'
144
- };
145
- this.activeTasks.set(taskId, task);
146
-
147
- // 🚨 PHASE 5: INTELLIGENT GAP ANALYSIS (Beyond MCP Tools)
148
- this.logger.info('🧠 Step 4: Running Intelligent Gap Analysis...');
149
- let gapAnalysisResult: GapAnalysisResult | null = null;
150
-
151
- try {
152
- gapAnalysisResult = await this.gapAnalysisEngine.analyzeAndResolve(objective, {
153
- autoPermissions: this.config.autoPermissions,
154
- environment: 'development',
155
- enableAutomation: true,
156
- includeManualGuides: true,
157
- riskTolerance: 'medium'
158
- });
159
-
160
- this.logger.info(`📊 Gap Analysis Complete:`);
161
- this.logger.info(` • Total Requirements: ${gapAnalysisResult.totalRequirements}`);
162
- this.logger.info(` • MCP Coverage: ${gapAnalysisResult.mcpCoverage.coveragePercentage}%`);
163
- this.logger.info(` • Automated: ${gapAnalysisResult.summary.successfulAutomation} configurations`);
164
- this.logger.info(` • Manual Work: ${gapAnalysisResult.summary.requiresManualWork} items`);
165
-
166
- // Display manual instructions if needed
167
- if (gapAnalysisResult.summary.requiresManualWork > 0) {
168
- this.logger.info('\n📋 Manual Configuration Required:');
169
- gapAnalysisResult.nextSteps.manual.forEach(step => this.logger.info(` • ${step}`));
170
-
171
- if (gapAnalysisResult.manualGuides) {
172
- this.logger.info('\n📚 Detailed manual guides available in gap _analysis result');
173
- }
174
- }
175
-
176
- // Display automation successes
177
- if (gapAnalysisResult.summary.successfulAutomation > 0) {
178
- this.logger.info('\n✅ Automated Configurations:');
179
- gapAnalysisResult.nextSteps.automated.forEach(step => this.logger.info(` • ${step}`));
180
- }
181
-
182
- // Display recommendations
183
- if (gapAnalysisResult.nextSteps.recommendations.length > 0) {
184
- this.logger.info('\n💡 Recommendations:');
185
- gapAnalysisResult.nextSteps.recommendations.forEach(rec => this.logger.info(` • ${rec}`));
186
- }
187
-
188
- // Store gap _analysis result in task for later reference
189
- (task as any).gapAnalysis = gapAnalysisResult;
190
-
191
- } catch (gapError) {
192
- console.warn(`⚠️ Gap Analysis failed: ${gapError instanceof Error ? gapError.message : 'Unknown error'}`);
193
- this.logger.info('🔄 Continuing with standard MCP workflow...');
194
- }
195
-
196
- // Phase 6: Spawn optimal agent swarm
197
- const agents = this.spawnOptimalSwarm(task, _analysis);
198
-
199
- // Phase 7: Execute coordinated deployment
200
- task.status = 'executing';
201
- const result = await this.coordinateExecution(task, agents, _analysis);
202
-
203
- // Phase 8: Learn from execution
204
- const duration = Date.now() - startTime;
205
- this.learnFromExecution(task, agents, result, duration, null);
206
-
207
- task.status = 'completed';
208
- task.result = result;
209
-
210
- if (this.config.debugMode) {
211
- this.logger.info(`✅ Queen completed objective in ${duration}ms`);
212
- }
213
-
214
- return result;
215
-
216
- } catch (error) {
217
- const duration = Date.now() - startTime;
218
- await this.handleExecutionFailure(taskId, objective, error as Error, duration);
219
- throw error;
220
- } finally {
221
- this.cleanupTask(taskId);
222
- }
223
- }
224
-
225
- private spawnOptimalSwarm(task: ServiceNowTask, _analysis: TaskAnalysis): Agent[] {
226
- if (this.config.debugMode) {
227
- this.logger.info(`🐛 Spawning swarm for ${task.type} task (complexity: ${_analysis.estimatedComplexity})`);
228
- }
229
-
230
- // Use learned patterns or optimal sequence
231
- const agentTypes = _analysis.suggestedPattern?.agentSequence ||
232
- this.agentFactory.getOptimalAgentSequence(task.type, _analysis.estimatedComplexity);
233
-
234
- // Spawn agent swarm
235
- const agents = this.agentFactory.spawnAgentSwarm(agentTypes, task.id);
236
-
237
- if (this.config.debugMode) {
238
- this.logger.info(`👥 Spawned ${agents.length} agents: ${agents.map(a => a.type).join(', ')}`);
239
- }
240
-
241
- return agents;
242
- }
243
-
244
- private async coordinateExecution(task: ServiceNowTask, agents: Agent[], _analysis: TaskAnalysis): Promise<any> {
245
- const results: any[] = [];
246
-
247
- try {
248
- // Execute agents in optimal sequence
249
- if (this.shouldExecuteInParallel(agents)) {
250
- results.push(...await this.executeAgentsInParallel(agents, task.objective));
251
- } else {
252
- results.push(...await this.executeAgentsSequentially(agents, task.objective));
253
- }
254
-
255
- // Coordinate final deployment using MCP tools
256
- const deploymentResult = await this.executeFinalDeployment(task, results, _analysis);
257
-
258
- return {
259
- taskId: task.id,
260
- objective: task.objective,
261
- agentResults: results,
262
- deploymentResult,
263
- artifacts: task.artifacts
264
- };
265
-
266
- } catch (error) {
267
- // Attempt recovery or fallback
268
- return await this.attemptRecovery(task, agents, error as Error);
269
- }
270
- }
271
-
272
- private shouldExecuteInParallel(agents: Agent[]): boolean {
273
- // Parallel execution for independent agents
274
- const independentAgents = ['researcher', 'tester', 'script-writer'];
275
- return agents.some(agent => independentAgents.includes(agent.type));
276
- }
277
-
278
- private async executeAgentsInParallel(agents: Agent[], objective: string): Promise<any[]> {
279
- if (this.config.debugMode) {
280
- this.logger.info('⚡ Executing agents in parallel');
281
- }
282
-
283
- const promises = agents.map(agent =>
284
- this.agentFactory.executeAgentTask(agent.id, objective)
285
- );
286
-
287
- return await Promise.all(promises);
288
- }
289
-
290
- private async executeAgentsSequentially(agents: Agent[], objective: string): Promise<any[]> {
291
- if (this.config.debugMode) {
292
- this.logger.info('🔄 Executing agents sequentially');
293
- }
294
-
295
- const results: any[] = [];
296
-
297
- for (const agent of agents) {
298
- const result = await this.agentFactory.executeAgentTask(agent.id, objective);
299
- results.push(result);
300
-
301
- // Allow agents to coordinate between executions
302
- this.facilitateAgentCoordination(agent, results);
303
- }
304
-
305
- return results;
306
- }
307
-
308
- private facilitateAgentCoordination(currentAgent: Agent, previousResults: any[]): void {
309
- // Send relevant results to collaborative agents
310
- const activeAgents = this.agentFactory.getActiveAgents();
311
-
312
- for (const agent of activeAgents) {
313
- if (agent.id !== currentAgent.id) {
314
- this.agentFactory.sendAgentMessage(
315
- currentAgent.id,
316
- agent.id,
317
- 'result',
318
- {
319
- results: previousResults.slice(-1)[0], // Latest result
320
- fromAgent: currentAgent.type
321
- }
322
- );
323
- }
324
- }
325
- }
326
-
327
- private async executeFinalDeployment(task: ServiceNowTask, agentResults: any[], _analysis: TaskAnalysis): Promise<any> {
328
- if (this.config.debugMode) {
329
- this.logger.info('🚀 Executing final deployment with MCP tools');
330
- }
331
-
332
- // The Queen coordinates the actual MCP tool calls based on agent recommendations
333
- const deploymentPlan = this.createDeploymentPlan(task, agentResults, _analysis);
334
-
335
- try {
336
- // Execute deployment using the unified deployment API
337
- const deploymentResult = await this.executeDeploymentPlan(deploymentPlan);
338
-
339
- // Track artifacts created
340
- if (deploymentResult.sys_id) {
341
- task.artifacts.push(deploymentResult.sys_id);
342
-
343
- // Store artifact in memory for future reference
344
- this.memory.storeArtifact({
345
- type: task.type as any,
346
- name: deploymentResult.name || task.objective,
347
- sys_id: deploymentResult.sys_id,
348
- config: deploymentResult.config || {},
349
- dependencies: _analysis.dependencies
350
- });
351
- }
352
-
353
- return deploymentResult;
354
-
355
- } catch (error) {
356
- if (this.config.debugMode) {
357
- console.error('❌ Deployment failed:', error);
358
- }
359
- throw error;
360
- }
361
- }
362
-
363
- private createDeploymentPlan(task: ServiceNowTask, agentResults: any[], _analysis: TaskAnalysis): any {
364
- // Extract deployment instructions from agent results
365
- const widgetCreator = agentResults.find(r => r.agentType === 'widget-creator');
366
- const flowBuilder = agentResults.find(r => r.agentType === 'flow-builder');
367
- const scriptWriter = agentResults.find(r => r.agentType === 'script-writer');
368
- const catalogManager = agentResults.find(r => r.agentType === 'catalog-manager');
369
-
370
- if (task.type === 'widget' && widgetCreator) {
371
- return {
372
- type: 'widget',
373
- mcpTool: 'snow_deploy',
374
- config: this.extractWidgetConfig(task.objective, agentResults),
375
- autoPermissions: this.config.autoPermissions // Pass auto-permissions flag for dependency handling
376
- };
377
- }
378
-
379
- // Flow creation is no longer supported - use ServiceNow Flow Designer directly
380
- if (task.type === 'flow') {
381
- throw new Error('Flow creation is no longer supported in Snow-Flow. Please use ServiceNow Flow Designer directly.');
382
- }
383
-
384
- if (task.type === 'script' && scriptWriter) {
385
- return {
386
- type: 'script',
387
- mcpTool: 'snow_create_script_include',
388
- config: this.extractScriptConfig(task.objective, agentResults)
389
- };
390
- }
391
-
392
- // Default deployment plan
393
- return {
394
- type: task.type,
395
- mcpTool: 'snow_deploy',
396
- instruction: task.objective
397
- };
398
- }
399
-
400
- private extractWidgetConfig(objective: string, agentResults: any[]): any {
401
- // Extract widget configuration from agent results
402
- const widgetResult = agentResults.find(r => r.agentType === 'widget-creator');
403
-
404
- return {
405
- name: this.generateArtifactName(objective, 'widget'),
406
- title: this.generateArtifactTitle(objective),
407
- template: this.generateWidgetTemplate(objective),
408
- css: this.generateWidgetCss(objective),
409
- client_script: this.generateClientScript(objective),
410
- server_script: this.generateServerScript(objective),
411
- demo_data: this.generateDemoData(objective)
412
- };
413
- }
414
-
415
- private extractScriptConfig(objective: string, agentResults: any[]): any {
416
- return {
417
- name: this.generateArtifactName(objective, 'script'),
418
- description: `Auto-generated script for: ${objective}`,
419
- script: this.generateScriptCode(objective)
420
- };
421
- }
422
-
423
- // Simple artifact generation based on objective analysis
424
- private generateArtifactName(objective: string, type: string): string {
425
- const words = objective.toLowerCase().replace(/[^a-z\s]/g, '').split(/\s+/).filter(w => w.length > 2);
426
- const key_words = words.slice(0, 3).join('_');
427
- return `${key_words}_${type}`;
428
- }
429
-
430
- private generateArtifactTitle(objective: string): string {
431
- return objective.charAt(0).toUpperCase() + objective.slice(1);
432
- }
433
-
434
- private generateWidgetTemplate(objective: string): string {
435
- const isChart = objective.toLowerCase().includes('chart') || objective.toLowerCase().includes('graph');
436
- const isDashboard = objective.toLowerCase().includes('dashboard');
437
-
438
- if (isChart) {
439
- return `
440
- <div class="panel panel-default">
441
- <div class="panel-heading">
442
- <h3 class="panel-title">{{data.title || '${this.generateArtifactTitle(objective)}'}}</h3>
443
- </div>
444
- <div class="panel-body">
445
- <canvas id="chart-{{::data.widget_id}}" width="400" height="200"></canvas>
446
- </div>
447
- </div>`;
448
- }
449
-
450
- if (isDashboard) {
451
- return `
452
- <div class="row">
453
- <div class="col-md-12">
454
- <div class="panel panel-default">
455
- <div class="panel-heading">
456
- <h3 class="panel-title">{{data.title || '${this.generateArtifactTitle(objective)}'}}</h3>
457
- </div>
458
- <div class="panel-body">
459
- <div class="row">
460
- <div class="col-md-4" ng-repeat="item in data.items">
461
- <div class="well text-center">
462
- <h4>{{item.label}}</h4>
463
- <h2 class="text-primary">{{item.value}}</h2>
464
- </div>
465
- </div>
466
- </div>
467
- </div>
468
- </div>
469
- </div>
470
- </div>`;
471
- }
472
-
473
- return `
474
- <div class="panel panel-default">
475
- <div class="panel-heading">
476
- <h3 class="panel-title">{{data.title || '${this.generateArtifactTitle(objective)}'}}</h3>
477
- </div>
478
- <div class="panel-body">
479
- <div ng-if="data.items.length > 0">
480
- <div class="list-group">
481
- <div class="list-group-item" ng-repeat="item in data.items">
482
- <h4 class="list-group-item-heading">{{item.title}}</h4>
483
- <p class="list-group-item-text">{{item.description}}</p>
484
- </div>
485
- </div>
486
- </div>
487
- <div ng-if="data.items.length === 0" class="text-center">
488
- <p>No items to display</p>
489
- </div>
490
- </div>
491
- </div>`;
492
- }
493
-
494
- private generateWidgetCss(objective: string): string {
495
- return `
496
- .panel {
497
- margin-bottom: 20px;
498
- border-radius: 6px;
499
- }
500
-
501
- .panel-heading {
502
- background-color: #f5f5f5;
503
- border-bottom: 1px solid #ddd;
504
- }
505
-
506
- .panel-body {
507
- padding: 15px;
508
- }
509
-
510
- .well {
511
- background-color: #f9f9f9;
512
- border: 1px solid #e3e3e3;
513
- border-radius: 4px;
514
- padding: 19px;
515
- margin-bottom: 20px;
516
- }
517
-
518
- .text-primary {
519
- color: #337ab7;
520
- }
521
-
522
- @media (max-width: 768px) {
523
- .col-md-4 {
524
- margin-bottom: 15px;
525
- }
526
- }`;
527
- }
528
-
529
- private generateClientScript(objective: string): string {
530
- const isChart = objective.toLowerCase().includes('chart') || objective.toLowerCase().includes('graph');
531
-
532
- if (isChart) {
533
- return `
534
- function($scope) {
535
- var c = this;
536
-
537
- c.$onInit = function() {
538
- if (c.data.chartData) {
539
- c.renderChart();
540
- }
541
- };
542
-
543
- c.renderChart = function() {
544
- var ctx = document.getElementById('chart-' + c.data.widget_id);
545
- if (ctx && c.data.chartData) {
546
- new Chart(ctx, {
547
- type: c.data.chartType || 'bar',
548
- data: c.data.chartData,
549
- options: {
550
- responsive: true,
551
- plugins: {
552
- title: {
553
- display: true,
554
- text: c.data.title || 'Chart'
555
- }
556
- }
557
- }
558
- });
559
- }
560
- };
561
- }`;
562
- }
563
-
564
- return `
565
- function($scope) {
566
- var c = this;
567
-
568
- c.$onInit = function() {
569
- // Initialize widget
570
- if (c.data.items) {
571
- c.processItems();
572
- }
573
- };
574
-
575
- c.processItems = function() {
576
- // Process and format items for display
577
- c.data.items = c.data.items || [];
578
- };
579
-
580
- c.refreshData = function() {
581
- c.server.refresh();
582
- };
583
- }`;
584
- }
585
-
586
- private generateServerScript(objective: string): string {
587
- const lowerObjective = objective.toLowerCase();
588
-
589
- if (lowerObjective.includes('incident')) {
590
- return `
591
- (function() {
592
- data.title = options.title || 'Incidents Dashboard';
593
- data.widget_id = gs.generateGUID();
594
-
595
- // Query incidents
596
- var gr = new GlideRecord('incident');
597
- gr.addActiveQuery();
598
- gr.orderByDesc('sys_created_on');
599
- gr.setLimit(10);
600
- gr.query();
601
-
602
- data.items = [];
603
- while (gr.next()) {
604
- data.items.push({
605
- title: gr.getValue('short_description'),
606
- description: 'Priority: ' + gr.getDisplayValue('priority') + ' | State: ' + gr.getDisplayValue('state'),
607
- sys_id: gr.getValue('sys_id'),
608
- priority: gr.getValue('priority'),
609
- state: gr.getValue('state')
610
- });
611
- }
612
-
613
- // Chart data for incidents by priority
614
- if (data.items.length > 0) {
615
- var priorityCounts = {};
616
- data.items.forEach(function(item) {
617
- priorityCounts[item.priority] = (priorityCounts[item.priority] || 0) + 1;
618
- });
619
-
620
- data.chartData = {
621
- labels: Object.keys(priorityCounts),
622
- datasets: [{
623
- label: 'Incidents by Priority',
624
- data: Object.values(priorityCounts),
625
- backgroundColor: ['#ff6384', '#ff9f40', '#ffcd56', '#4bc0c0']
626
- }]
627
- };
628
- data.chartType = 'doughnut';
629
- }
630
- })();`;
631
- }
632
-
633
- return `
634
- (function() {
635
- data.title = options.title || '${this.generateArtifactTitle(objective)}';
636
- data.widget_id = gs.generateGUID();
637
- data.items = [];
638
-
639
- // Add your data processing logic here
640
- // Example: Query relevant records and populate data.items
641
-
642
- // Default demo data
643
- data.items = [
644
- {
645
- title: 'Sample Item 1',
646
- description: 'This is a sample item for demonstration'
647
- },
648
- {
649
- title: 'Sample Item 2',
650
- description: 'This is another sample item'
651
- }
652
- ];
653
- })();`;
654
- }
655
-
656
- private generateDemoData(objective: string): any {
657
- return {
658
- title: this.generateArtifactTitle(objective),
659
- items: [
660
- {
661
- title: 'Demo Item 1',
662
- description: 'Sample data for testing the widget'
663
- }
664
- ]
665
- };
666
- }
667
-
668
- private generateScriptCode(objective: string): string {
669
- return `
670
- // Auto-generated script for: ${objective}
671
- // Generated by ServiceNow Queen Agent
672
-
673
- (function() {
674
- // Add your script logic here
675
- gs.info('${objective} script executed');
676
-
677
- return {
678
- success: true,
679
- message: 'Script executed successfully'
680
- };
681
- })();`;
682
- }
683
-
684
- private async executeDeploymentPlan(plan: any): Promise<any> {
685
- // Execute real MCP tools through the bridge
686
- if (this.config.debugMode) {
687
- this.logger.info('🚀 Executing deployment plan with MCP Bridge');
688
- }
689
-
690
- // Create agent recommendation from plan
691
- const recommendation: AgentRecommendation = {
692
- agentId: 'queen-agent',
693
- agentType: 'queen',
694
- action: `deploy-${plan.type}`,
695
- tool: plan.mcpTool,
696
- server: this.getServerForTool(plan.mcpTool),
697
- params: plan.config || {},
698
- reasoning: `Deploying ${plan.type} artifact as requested`,
699
- confidence: 0.95
700
- };
701
-
702
- // Execute through MCP bridge
703
- const result = await this.mcpBridge.executeAgentRecommendation(
704
- { id: 'queen-agent', type: 'queen' },
705
- recommendation
706
- );
707
-
708
- if (result.success && result.toolResult) {
709
- const deploymentResult = {
710
- success: true,
711
- type: plan.type,
712
- name: plan.config?.name || result.toolResult.name,
713
- sys_id: result.toolResult.sys_id, // Real sys_id from ServiceNow!
714
- config: plan.config,
715
- mcpTool: plan.mcpTool,
716
- executionTime: result.executionTime
717
- };
718
-
719
- // Handle dependency injection for widgets
720
- if (plan.type === 'widget' && plan.config) {
721
- await this.handleWidgetDependencies(plan.config, plan.autoPermissions);
722
- }
723
-
724
- return deploymentResult;
725
- } else {
726
- throw new Error(`MCP execution failed: ${result.error || 'Unknown error'}`);
727
- }
728
- }
729
-
730
- private getServerForTool(tool: string): string {
731
- // Map tools to their servers
732
- const toolServerMap: Record<string, string> = {
733
- 'snow_deploy': 'deployment',
734
- 'snow_deploy_widget': 'deployment',
735
- 'snow_deploy_flow': 'deployment',
736
- 'snow_find_artifact': 'intelligent',
737
- 'snow_update_set_create': 'update-set',
738
- 'snow_get_by_sysid': 'intelligent',
739
- 'snow_edit_by_sysid': 'intelligent'
740
- };
741
- return toolServerMap[tool] || 'deployment';
742
- }
743
-
744
- private async handleWidgetDependencies(widgetConfig: any, autoPermissions?: boolean): Promise<void> {
745
- try {
746
- // Detect dependencies in widget code
747
- const dependencies = DependencyDetector.analyzeWidget(widgetConfig);
748
-
749
- if (dependencies.length === 0) {
750
- return; // No dependencies needed
751
- }
752
-
753
- this.logger.info(`\n📦 Detected ${dependencies.length} external dependencies in widget:`);
754
- dependencies.forEach(dep => {
755
- this.logger.info(` • ${dep.name} - ${dep.description}`);
756
- });
757
-
758
- // Create MCP tools wrapper for theme manager
759
- const mcpTools = {
760
- snow_find_artifact: async (params: any) => {
761
- const recommendation: AgentRecommendation = {
762
- agentId: 'queen-agent',
763
- agentType: 'queen',
764
- action: 'find-theme',
765
- tool: 'snow_find_artifact',
766
- server: 'intelligent',
767
- params,
768
- reasoning: 'Finding Service Portal theme for dependency injection',
769
- confidence: 0.95
770
- };
771
- const result = await this.mcpBridge.executeAgentRecommendation(
772
- { id: 'queen-agent', type: 'queen' },
773
- recommendation
774
- );
775
- return result.toolResult;
776
- },
777
- snow_comprehensive_search: async (params: any) => {
778
- const recommendation: AgentRecommendation = {
779
- agentId: 'queen-agent',
780
- agentType: 'queen',
781
- action: 'search-themes',
782
- tool: 'snow_comprehensive_search',
783
- server: 'intelligent',
784
- params,
785
- reasoning: 'Searching for Service Portal themes',
786
- confidence: 0.95
787
- };
788
- const result = await this.mcpBridge.executeAgentRecommendation(
789
- { id: 'queen-agent', type: 'queen' },
790
- recommendation
791
- );
792
- return result.toolResult;
793
- },
794
- snow_get_by_sysid: async (params: any) => {
795
- const recommendation: AgentRecommendation = {
796
- agentId: 'queen-agent',
797
- agentType: 'queen',
798
- action: 'get-theme',
799
- tool: 'snow_get_by_sysid',
800
- server: 'intelligent',
801
- params,
802
- reasoning: 'Getting Service Portal theme details',
803
- confidence: 0.95
804
- };
805
- const result = await this.mcpBridge.executeAgentRecommendation(
806
- { id: 'queen-agent', type: 'queen' },
807
- recommendation
808
- );
809
- return result.toolResult;
810
- },
811
- snow_edit_by_sysid: async (params: any) => {
812
- const recommendation: AgentRecommendation = {
813
- agentId: 'queen-agent',
814
- agentType: 'queen',
815
- action: 'update-theme',
816
- tool: 'snow_edit_by_sysid',
817
- server: 'intelligent',
818
- params,
819
- reasoning: 'Updating Service Portal theme with dependencies',
820
- confidence: 0.95
821
- };
822
- const result = await this.mcpBridge.executeAgentRecommendation(
823
- { id: 'queen-agent', type: 'queen' },
824
- recommendation
825
- );
826
- return result.toolResult;
827
- }
828
- };
829
-
830
- // Update theme with dependencies
831
- const result = await ServicePortalThemeManager.updateThemeWithDependencies(
832
- dependencies,
833
- mcpTools,
834
- {
835
- autoPermissions,
836
- skipPrompt: autoPermissions, // Skip prompt if auto-permissions enabled
837
- useMinified: true
838
- }
839
- );
840
-
841
- if (result.success) {
842
- this.logger.info(`✅ ${result.message}`);
843
- } else {
844
- this.logger.warn(`⚠️ Dependencies not installed: ${result.message}`);
845
- this.logger.info('💡 You may need to manually add these dependencies to your Service Portal theme');
846
- }
847
-
848
- } catch (error: any) {
849
- console.error('❌ Error handling widget dependencies:', error.message);
850
- // Don't fail the deployment, just warn
851
- this.logger.warn('⚠️ Widget deployed successfully but dependencies may need manual installation');
852
- }
853
- }
854
-
855
- private async attemptRecovery(task: ServiceNowTask, agents: Agent[], error: Error): Promise<any> {
856
- if (this.config.debugMode) {
857
- this.logger.info(`🔄 Attempting recovery for task ${task.id}`);
858
- }
859
-
860
- // Try with reduced complexity or different agent sequence
861
- const fallbackResult = {
862
- taskId: task.id,
863
- objective: task.objective,
864
- status: 'recovered',
865
- error: error.message,
866
- fallbackApplied: true
867
- };
868
-
869
- return fallbackResult;
870
- }
871
-
872
- private learnFromExecution(task: ServiceNowTask, agents: Agent[], result: any, duration: number, error: Error | null): void {
873
- const agentTypes = agents.map(a => a.type);
874
-
875
- if (error) {
876
- // Learn from failure
877
- this.neuralLearning.learnFromFailure(task, error.message, agentTypes);
878
- this.memory.recordTaskCompletion(task.id, task.objective, task.type, agentTypes, false, duration);
879
- } else {
880
- // Learn from success
881
- this.neuralLearning.learnFromSuccess(task, duration, agentTypes);
882
- this.memory.recordTaskCompletion(task.id, task.objective, task.type, agentTypes, true, duration);
883
- }
884
-
885
- if (this.config.debugMode) {
886
- this.logger.info(`📚 Queen learned from ${error ? 'failure' : 'success'}: ${task.objective}`);
887
- }
888
- }
889
-
890
- private async handleExecutionFailure(taskId: string, objective: string, error: Error, duration: number): Promise<void> {
891
- const task = this.activeTasks.get(taskId);
892
- if (task) {
893
- task.status = 'failed';
894
- task.error = error.message;
895
-
896
- // Learn from failure
897
- this.memory.storeLearning(
898
- `failure_${task.type}`,
899
- `Failed: ${objective} - Error: ${error.message}`,
900
- 0.8
901
- );
902
- }
903
-
904
- if (this.config.debugMode) {
905
- console.error(`❌ Task ${taskId} failed after ${duration}ms:`, error.message);
906
- }
907
- }
908
-
909
- private cleanupTask(taskId: string): void {
910
- this.activeTasks.delete(taskId);
911
- this.agentFactory.cleanupCompletedAgents();
912
- }
913
-
914
- private generateTaskId(): string {
915
- return `task_${Date.now()}_${crypto.randomBytes(4).toString('hex')}`;
916
- }
917
-
918
- // Public API methods
919
-
920
- getActiveTaskCount(): number {
921
- return this.activeTasks.size;
922
- }
923
-
924
- getTaskStatus(taskId: string): ServiceNowTask | null {
925
- return this.activeTasks.get(taskId) || null;
926
- }
927
-
928
- /**
929
- * Get gap _analysis results for a task
930
- */
931
- getGapAnalysisResults(taskId: string): GapAnalysisResult | null {
932
- const task = this.activeTasks.get(taskId);
933
- return (task as any)?.gapAnalysis || null;
934
- }
935
-
936
- /**
937
- * Get all manual guides from gap _analysis for a task
938
- */
939
- getManualConfigurationGuides(taskId: string): any {
940
- const gapAnalysis = this.getGapAnalysisResults(taskId);
941
- return gapAnalysis?.manualGuides || null;
942
- }
943
-
944
- getHiveMindStatus(): any {
945
- return {
946
- activeTasks: this.activeTasks.size,
947
- activeAgents: this.agentFactory.getActiveAgents().length,
948
- memoryStats: {
949
- patterns: this.memory['memory'].patterns.length,
950
- artifacts: this.memory['memory'].artifacts.size,
951
- learnings: this.memory['memory'].learnings.size
952
- },
953
- factoryStats: this.agentFactory.getStatistics(),
954
- learningInsights: this.neuralLearning.getLearningInsights()
955
- };
956
- }
957
-
958
- exportMemory(): string {
959
- return this.memory.exportMemory();
960
- }
961
-
962
- importMemory(memoryData: string): void {
963
- this.memory.importMemory(memoryData);
964
- if (this.config.debugMode) {
965
- this.logger.info('🧠 Queen hive-mind memory imported successfully');
966
- }
967
- }
968
-
969
- clearMemory(): void {
970
- this.memory.clearMemory();
971
- // Also reset neural learning weights
972
- this.neuralLearning = new NeuralLearning(this.memory);
973
- if (this.config.debugMode) {
974
- this.logger.info('🧠 Queen hive-mind memory cleared - starting fresh');
975
- }
976
- }
977
-
978
- getLearningInsights(): any {
979
- const neuralInsights = this.neuralLearning.getLearningInsights();
980
-
981
- return {
982
- successfulPatterns: this.memory['memory'].patterns.slice(0, 5).map(pattern => ({
983
- description: `${pattern.taskType} deployment using ${pattern.agentSequence.join(' → ')}`,
984
- successRate: Math.round(pattern.successRate * 100),
985
- avgDuration: pattern.avgDuration,
986
- useCount: this.memory.getSuccessRate(pattern.taskType)
987
- })),
988
- recommendations: [
989
- 'Use Queen Agent for complex multi-step ServiceNow tasks',
990
- 'Enable --debug mode for detailed hive-mind insights',
991
- 'Export memory regularly to preserve learning patterns',
992
- 'Let Queen analyze objectives for optimal agent coordination'
993
- ],
994
- commonTasks: Object.entries(neuralInsights.weights || {})
995
- .map(([type, count]) => ({
996
- type,
997
- count: typeof count === 'number' ? count : 0
998
- }))
999
- .sort((a, b) => b.count - a.count)
1000
- .slice(0, 5),
1001
- memoryStats: {
1002
- totalPatterns: this.memory['memory'].patterns.length,
1003
- totalArtifacts: this.memory['memory'].artifacts.size,
1004
- totalLearnings: this.memory['memory'].learnings.size
1005
- },
1006
- neuralInsights
1007
- };
1008
- }
1009
-
1010
- async shutdown(): Promise<void> {
1011
- if (this.config.debugMode) {
1012
- this.logger.info('🛑 Shutting down ServiceNow Queen Agent');
1013
- }
1014
-
1015
- // Clean up all agents
1016
- const activeAgents = this.agentFactory.getActiveAgents();
1017
- for (const agent of activeAgents) {
1018
- this.agentFactory.terminateAgent(agent.id);
1019
- }
1020
-
1021
- // Shutdown MCP Bridge
1022
- if (this.mcpBridge) {
1023
- await this.mcpBridge.shutdown();
1024
- }
1025
-
1026
- // Close memory system
1027
- this.memory.close();
1028
- }
1029
- }